Java Code Examples for org.eclipse.jface.text.ITextSelection#getStartLine()

The following examples show how to use org.eclipse.jface.text.ITextSelection#getStartLine() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
private void addLineComments(IDocument document, ITextSelection selection, String comment, ITextEditor editor)
		throws BadLocationException {
	int lineNumber = selection.getStartLine();
	int endLineNumber = selection.getEndLine();
	int insertedChars = 0;

	while (lineNumber <= endLineNumber) {
		document.replace(document.getLineOffset(lineNumber), 0, comment);
		if (lineNumber != endLineNumber) {
			insertedChars += comment.length();
		}
		lineNumber++;
	}
	ITextSelection newSelection = new TextSelection(selection.getOffset() + comment.length(),
			selection.getLength() + insertedChars);
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
Example 2
Source File: ToggleCommentHandler.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
protected boolean isSelectionCommented(IDocument document, ITextSelection selection, String commentPrefix) 
{
    try {
        for (int lineNum = selection.getStartLine(); lineNum <= selection.getEndLine(); ++lineNum) {
            IRegion r  = document.getLineInformation(lineNum);
            String str = document.get(r.getOffset(), r.getLength()).trim();
            if (!str.startsWith(commentPrefix)) {
                return false;
            }
        }
        return true;
    } catch (Exception x) {
    }

    return false;
}
 
Example 3
Source File: PAppendCommentHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
		throws BadLocationException {
	int currentLine = currentSelection.getStartLine();
	currentLine = currentLine -1;
	if (currentLine < 0){
		throw new BadLocationException();
	}
	IRegion reg = document.getLineInformation(currentLine);
	ITextSelection newSelection = new TextSelection(document,reg.getOffset(), 0);
	return super.transform(editor,document, newSelection, event);
}
 
Example 4
Source File: PyMethodNavigation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This method will search for the next/previous function (depending on the abstract methods)
 * and will go to the position in the document that corresponds to the name of the class/function definition.
 */
@Override
public void run(IAction action) {
    PyEdit pyEdit = getPyEdit();
    IDocument doc = pyEdit.getDocument();
    ITextSelection selection = (ITextSelection) pyEdit.getSelectionProvider().getSelection();

    boolean searchForward = getSearchForward();

    int startLine = selection.getStartLine();

    //we want to start searching in the line before/after the line we're in.
    if (searchForward) {
        startLine += 1;
    } else {
        startLine -= 1;
    }
    stmtType goHere = FastParser.firstClassOrFunction(doc, startLine, searchForward, pyEdit.isCythonFile());

    NameTok node = getNameNode(goHere);
    if (node != null) {
        //ok, somewhere to go
        pyEdit.revealModelNode(node);

    } else {
        //no place specified until now... let's try to see if we should go to the start or end of the file
        if (searchForward) {
            pyEdit.selectAndReveal(doc.getLength(), 0);

        } else {
            pyEdit.selectAndReveal(0, 0);
        }
    }
}
 
Example 5
Source File: ScriptLineBreakpointAdapter.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public boolean canToggleLineBreakpoints( IWorkbenchPart part,
		ISelection selection )
{
	DecoratedScriptEditor textEditor = getEditor( part );

	if ( textEditor != null )
	{
		String script = textEditor.getScript( );

		if ( script == null || script.trim( ).length( ) == 0 )
		{
			return false;
		}

		ITextSelection textSelection = (ITextSelection) selection;
		IReportScriptLocation location = (IReportScriptLocation) textEditor.getAdapter( IReportScriptLocation.class );

		if ( location != null )
		{
			int lineNumber = textSelection.getStartLine( );

			if ( location.getLineNumber( ) > 0 )
			{
				lineNumber = location.getLineNumber( );
			}

			return JsUtil.checkBreakable( script, lineNumber );
		}
	}

	return false;
}
 
Example 6
Source File: CompilationUnitEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isMultilineSelection() {
	ISelection selection= getSelectionProvider().getSelection();
	if (selection instanceof ITextSelection) {
		ITextSelection ts= (ITextSelection) selection;
		return  ts.getStartLine() != ts.getEndLine();
	}
	return false;
}
 
Example 7
Source File: JavaMoveLinesAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes the region of the skipped line given the text block to be moved. If
 * <code>fUpwards</code> is <code>true</code>, the line above <code>selection</code>
 * is selected, otherwise the line below.
 *
 * @param document the document <code>selection</code> refers to
 * @param selection the selection on <code>document</code> that will be moved.
 * @return the region comprising the line that <code>selection</code> will be moved over, without its terminating delimiter.
 */
private ITextSelection getSkippedLine(IDocument document, ITextSelection selection) {
	int skippedLineN= (fUpwards ? selection.getStartLine() - 1 : selection.getEndLine() + 1);
	if (skippedLineN > document.getNumberOfLines() || (!fCopy && (skippedLineN < 0 ||  skippedLineN == document.getNumberOfLines())))
		return null;
	try {
		if (fCopy && skippedLineN == -1)
			skippedLineN= 0;
		IRegion line= document.getLineInformation(skippedLineN);
		return new TextSelection(document, line.getOffset(), line.getLength());
	} catch (BadLocationException e) {
		// only happens on concurrent modifications
		return null;
	}
}
 
Example 8
Source File: JavaMoveLinesAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if <code>selection</code> is contained by the visible region of <code>viewer</code>.
 * As a special case, a selection is considered contained even if it extends over the visible
 * region, but the extension stays on a partially contained line and contains only white space.
 *
 * @param selection the selection to be checked
 * @param viewer the viewer displaying a visible region of <code>selection</code>'s document.
 * @return <code>true</code>, if <code>selection</code> is contained, <code>false</code> otherwise.
 */
private boolean containedByVisibleRegion(ITextSelection selection, ISourceViewer viewer) {
	int min= selection.getOffset();
	int max= min + selection.getLength();
	IDocument document= viewer.getDocument();

	IRegion visible;
	if (viewer instanceof ITextViewerExtension5)
		visible= ((ITextViewerExtension5) viewer).getModelCoverage();
	else
		visible= viewer.getVisibleRegion();

	int visOffset= visible.getOffset();
	try {
		if (visOffset > min) {
			if (document.getLineOfOffset(visOffset) != selection.getStartLine())
				return false;
			if (!isWhitespace(document.get(min, visOffset - min))) {
				showStatus();
				return false;
			}
		}
		int visEnd= visOffset + visible.getLength();
		if (visEnd < max) {
			if (document.getLineOfOffset(visEnd) != selection.getEndLine())
				return false;
			if (!isWhitespace(document.get(visEnd, max - visEnd))) {
				showStatus();
				return false;
			}
		}
		return true;
	} catch (BadLocationException e) {
	}
	return false;
}
 
Example 9
Source File: DefineFoldingRegionAction.java    From tlaplus with MIT License 5 votes vote down vote up
public void run()
{
    ITextEditor editor = getTextEditor();
    ISelection selection = editor.getSelectionProvider().getSelection();
    if (selection instanceof ITextSelection)
    {
        ITextSelection textSelection = (ITextSelection) selection;
        if (textSelection.getLength() != 0)
        {
            IAnnotationModel model = getAnnotationModel(editor);
            if (model != null)
            {

                int start = textSelection.getStartLine();
                int end = textSelection.getEndLine();

                try
                {
                    IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
                    int offset = document.getLineOffset(start);
                    int endOffset = document.getLineOffset(end + 1);
                    Position position = new Position(offset, endOffset - offset);
                    model.addAnnotation(new ProjectionAnnotation(), position);
                } catch (BadLocationException x)
                {
                    // ignore
                }
            }
        }
    }
}
 
Example 10
Source File: MarkerUtil.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Tries to retrieve right bug marker for given selection. If there are many
 * markers for given editor, and text selection doesn't match any of them,
 * return null. If there is only one marker for given editor, returns this
 * marker in any case.
 *
 * @param selection
 * @param editor
 * @return may return null
 */
public static IMarker getMarkerFromEditor(ITextSelection selection, IEditorPart editor) {
    IResource resource = (IResource) editor.getEditorInput().getAdapter(IFile.class);
    IMarker[] allMarkers;
    if (resource != null) {
        allMarkers = getMarkers(resource, IResource.DEPTH_ZERO);
    } else {
        IClassFile classFile = (IClassFile) editor.getEditorInput().getAdapter(IClassFile.class);
        if (classFile == null) {
            return null;
        }
        Set<IMarker> markers = getMarkers(classFile.getType());
        allMarkers = markers.toArray(new IMarker[markers.size()]);
    }
    // if editor contains only one FB marker, do some cheating and always
    // return it.
    if (allMarkers.length == 1) {
        return allMarkers[0];
    }
    // +1 because it counts real lines, but editor shows lines + 1
    int startLine = selection.getStartLine() + 1;
    for (IMarker marker : allMarkers) {
        int line = getEditorLine(marker);
        if (startLine == line) {
            return marker;
        }
    }
    return null;
}
 
Example 11
Source File: TextViewerJoinLinesAction.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void run() {

	ITextViewer viewer= getTextViewer();
	if (viewer == null)
		return;

	if (!canModifyViewer())
		return;

	IDocument document= viewer.getDocument();
	if (document == null)
		return;

	ITextSelection selection= getSelection(viewer);
	if (selection == null)
		return;

	int startLine= selection.getStartLine();
	int endLine= selection.getEndLine();
	try {
		int caretOffset= joinLines(document, startLine, endLine);
		if (caretOffset > -1) {
			StyledText widget= viewer.getTextWidget();
			widget.setRedraw(false);
			adjustHighlightRange(viewer, caretOffset, 0);
			viewer.revealRange(caretOffset, 0);

			viewer.setSelectedRange(caretOffset, 0);
			widget.setRedraw(true);
		}
	} catch (BadLocationException e) {
		// should not happen
	}

}
 
Example 12
Source File: TextViewerMoveLinesAction.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Computes the region of the skipped line given the text block to be moved. If
 * <code>fUpwards</code> is <code>true</code>, the line above <code>selection</code>
 * is selected, otherwise the line below.
 *
 * @param document the document <code>selection</code> refers to
 * @param selection the selection on <code>document</code> that will be moved.
 * @return the region comprising the line that <code>selection</code> will be moved over, without its terminating delimiter.
 */
private ITextSelection getSkippedLine(IDocument document, ITextSelection selection) {
	int skippedLineN= (fUpwards ? selection.getStartLine() - 1 : selection.getEndLine() + 1);
	if (skippedLineN > document.getNumberOfLines() || (!fCopy && (skippedLineN < 0 ||  skippedLineN == document.getNumberOfLines())))
		return null;
	try {
		if (fCopy && skippedLineN == -1)
			skippedLineN= 0;
		IRegion line= document.getLineInformation(skippedLineN);
		return new TextSelection(document, line.getOffset(), line.getLength());
	} catch (BadLocationException e) {
		// only happens on concurrent modifications
		return null;
	}
}
 
Example 13
Source File: TextViewerMoveLinesAction.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks if <code>selection</code> is contained by the visible region of <code>viewer</code>.
 * As a special case, a selection is considered contained even if it extends over the visible
 * region, but the extension stays on a partially contained line and contains only white space.
 *
 * @param selection the selection to be checked
 * @param viewer the viewer displaying a visible region of <code>selection</code>'s document.
 * @return <code>true</code>, if <code>selection</code> is contained, <code>false</code> otherwise.
 */
private boolean containedByVisibleRegion(ITextSelection selection, ITextViewer viewer) {
	int min= selection.getOffset();
	int max= min + selection.getLength();
	IDocument document= viewer.getDocument();

	IRegion visible;
	if (viewer instanceof ITextViewerExtension5)
		visible= ((ITextViewerExtension5) viewer).getModelCoverage();
	else
		visible= viewer.getVisibleRegion();

	int visOffset= visible.getOffset();
	try {
		if (visOffset > min) {
			if (document.getLineOfOffset(visOffset) != selection.getStartLine())
				return false;
			if (!isWhitespace(document.get(min, visOffset - min))) {
				return false;
			}
		}
		int visEnd= visOffset + visible.getLength();
		if (visEnd < max) {
			if (document.getLineOfOffset(visEnd) != selection.getEndLine())
				return false;
			if (!isWhitespace(document.get(visEnd, max - visEnd))) {
				return false;
			}
		}
		return true;
	} catch (BadLocationException e) {
	}
	return false;
}
 
Example 14
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
private boolean areLinesCommented(IDocument document, ITextSelection selection, String comment)
		throws BadLocationException {
	int lineNumber = selection.getStartLine();
	while (lineNumber <= selection.getEndLine()) {
		IRegion lineRegion = document.getLineInformation(lineNumber);
		if (!document.get(lineRegion.getOffset(), lineRegion.getLength()).trim().startsWith(comment)) {
			return false;
		}
		lineNumber++;
	}
	return true;
}
 
Example 15
Source File: GotoMatchingParenHandler.java    From tlaplus with MIT License 4 votes vote down vote up
/**
 * The method called when the user executes the Goto Matching Paren command.
 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
 */
public Object execute(ExecutionEvent event) throws ExecutionException {
    TLAEditor tlaEditor = EditorUtil.getTLAEditorWithFocus();
    document = tlaEditor.publicGetSourceViewer().getDocument();
    
    try {
        ITextSelection selection = (ITextSelection) tlaEditor
                .getSelectionProvider().getSelection();
        Region selectedRegion = new Region(selection.getOffset(),
                selection.getLength());
        
        int selectedParenIdx = getSelectedParen(selectedRegion);
        
        int lineNumber = selection.getStartLine();
          // Note: if the selection covers multiple lines, then 
          // selectParenIdx should have thrown an exception.
        if (lineNumber < 0) {
            throw new ParenErrorException("Toolbox bug: bad selected line computed", null, null);
        }
        
        setLineRegions(lineNumber);
        setRegionInfo();
        
        if (selectedParenIdx < PCOUNT) {
            findMatchingRightParen(selectedParenIdx);
        } 
        else {
            findMatchingLeftParen(selectedParenIdx);
        }
        tlaEditor.selectAndReveal(currLoc, 0);            
    } catch (ParenErrorException e) {
        /*
         * Report the error.
         */
        IResource resource = ResourceHelper
                .getResourceByModuleName(tlaEditor.getModuleName());
        ErrorMessageEraser listener = new ErrorMessageEraser(tlaEditor,
                resource);
        tlaEditor.getViewer().getTextWidget().addCaretListener(listener);
        tlaEditor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage(e.message);
        
        Region[] regions = e.regions;
        if (regions[0] != null) {
            try {
                // The following code was largely copied from the The
                // ShowUsesHandler class.
                Spec spec = ToolboxHandle.getCurrentSpec();
                spec.setMarkersToShow(null);
                IMarker[] markersToShow = new IMarker[2];
                for (int i = 0; i < 2; i++) {
                    IMarker marker = resource
                            .createMarker(PAREN_ERROR_MARKER_TYPE);
                    Map<String, Integer> markerAttributes = new HashMap<String, Integer>(
                            2);
                    markerAttributes.put(IMarker.CHAR_START, new Integer(
                            regions[i].getOffset()));
                    markerAttributes.put(
                            IMarker.CHAR_END,
                            new Integer(regions[i].getOffset()
                                    + regions[i].getLength()));
                    marker.setAttributes(markerAttributes);

                    markersToShow[i] = marker;
                }
                spec.setMarkersToShow(markersToShow);
            } catch (CoreException exc) {
                System.out
                        .println("GotoMatchingParenHandler.execute threw CoreException");
            }
        }
    }
    return null;
}
 
Example 16
Source File: RegionConverter.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
private static IRegion convertRegion(int offset, int length, String text,
    String originalDelimiter) {
  try {
    Document document = new Document(text);
    String delimiter = document.getLineDelimiter(0);

    // If the document's line delimiter is the same as that used to originally
    // calculate this offset/length, then just return the original region.
    if (delimiter == null || delimiter.equals(originalDelimiter)) {
      return new Region(offset, length);
    }

    // If we're running a platform other than the one this offset/length was
    // calculated on, we'll need to adjust the values. We start by creating
    // a text selection containing the original region and the text with the
    // original line endings.
    String originalText = text.replaceAll(delimiter, originalDelimiter);
    ITextSelection originalSelection = new TextSelection(new Document(
        originalText), offset, length);

    int delimiterLengthCorrection = originalDelimiter.length()
        - delimiter.length();

    // Adjust the offset by the delimiter length difference for each line
    // that came before it.
    int newOffset = originalSelection.getOffset()
        - (delimiterLengthCorrection * originalSelection.getStartLine());

    // Adjust the length by the delimiter length difference for each line
    // between the start and the end of the original region

    // TODO: account for case where the selection ends with a line break;
    // currently this will not update the length since the selection starts
    // and ends on the same line.
    int regionLineBreaks = originalSelection.getEndLine()
        - originalSelection.getStartLine();
    int newLength = originalSelection.getLength()
        - (delimiterLengthCorrection * regionLineBreaks);

    return new Region(newOffset, newLength);
  } catch (BadLocationException e) {
    return null;
  }
}
 
Example 17
Source File: ToggleCommentHandler.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private void getTypeContent(StringBuilder buf,
		ITextSelection iTextSelection, String type)
		throws BadLocationException {
	int offset = 0;
	if (iTextSelection.getOffset() == iDocument.getLength()) {
		offset = iDocument.getLength() - 1;
	} else {
		offset = iTextSelection.getOffset();
	}
	ITypedRegion typeRegion = iDocument.getPartition(offset);
	String text = iTextSelection.getText();
	ITypedRegion typeRegion_new = null;
	if (offset > 0) {
		typeRegion_new = iDocument.getPartition(offset - 1);
	}
	String TYPE_COMMENT = TYPE_HTML_COMMENT;
	String TYPE_COMMENT_BEGIN = TYPE_HTML_COMMENT_BEGIN;
	String TYPE_COMMENT_END = TYPE_HTML_COMMENT_END;
	if (TYPE_CSS.equals(type)) {
		TYPE_COMMENT = TYPE_CSS_M_COMMENT;
		TYPE_COMMENT_BEGIN = TYPE_CSS_M_COMMENT_BEGIN;
		TYPE_COMMENT_END = TYPE_CSS_M_COMMENT_END;
	}

	if (iTextSelection.getLength() == 0) {
		if (typeRegion != null && typeRegion.getType().equals(TYPE_COMMENT)) {
			setTypeContent(buf, typeRegion, TYPE_COMMENT_BEGIN,
					TYPE_COMMENT_END);
			return;
		} else if (typeRegion_new != null
				&& typeRegion_new.getType().equals(TYPE_COMMENT)) {
			setTypeContent(buf, typeRegion, TYPE_COMMENT_BEGIN,
					TYPE_COMMENT_END);
			return;
		}

		int lineNum = iTextSelection.getStartLine();
		IRegion lineInfo = iDocument.getLineInformation(lineNum);
		text = iDocument.get(lineInfo.getOffset(), lineInfo.getLength());
		String content = text.trim();
		if (content == null || content.length() == 0) {
			if (TYPE_HTML.equals(type)) {
				buf.append("<!---->");
			} else {
				buf.append("/**/");
			}

			subLength = 0;
			selecedRangeOffset = (iTextSelection.getOffset() + TYPE_COMMENT_BEGIN
					.length());
			return;
		}
		if (text != null && content.endsWith(TYPE_COMMENT_END)) {
			int index = text.indexOf(TYPE_COMMENT_END);
			typeRegion = iDocument.getPartition(iTextSelection.getOffset()
					- (text.length() - index));
			if ((typeRegion != null)
					&& (typeRegion.getType().equals(TYPE_COMMENT))) {

				setTypeContent(buf, typeRegion, TYPE_COMMENT_BEGIN,
						TYPE_COMMENT_END);
				selecedRangeOffset = (lineInfo.getOffset()
						+ lineInfo.getLength() + buf.toString().length() - text
						.length());
				return;
			}
		}

		String replaceText = TYPE_COMMENT_BEGIN + content
				+ TYPE_COMMENT_END;
		text = text.replace(content, replaceText);
		buf.append(text);
		subLength = lineInfo.getLength();
		lineStartOffset = lineInfo.getOffset();
	} else {
		if ((typeRegion != null)
				&& (typeRegion.getType().equals(TYPE_COMMENT))) {
			setTypeContent(buf, typeRegion, TYPE_COMMENT_BEGIN,
					TYPE_COMMENT_END);
		} else {
			buf.append(TYPE_COMMENT_BEGIN);
			buf.append(text);
			buf.append(TYPE_COMMENT_END);
			subLength = iTextSelection.getLength();
			lineStartOffset = iTextSelection.getOffset();
		}
	}
}
 
Example 18
Source File: AddBlockCommentHandler.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        ITextSelection selection = WorkbenchUtils.getActiveTextSelection();
        IDocument      doc       = WorkbenchUtils.getActiveDocument();
        IEditorInput   input     = WorkbenchUtils.getActiveInput();
        IEditorPart    editor    = WorkbenchUtils.getActiveEditor(false);

        boolean isTextOperationAllowed = (selection != null) && (doc != null) 
                                      && (input != null)     && (editor != null) 
                                      && (editor instanceof ModulaEditor);

        if (isTextOperationAllowed) {
            ITextEditor iTextEditor = (ITextEditor)editor;
            final ITextOperationTarget operationTarget = (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
            String commentPrefix = ((SourceCodeTextEditor)editor).getEOLCommentPrefix();
            isTextOperationAllowed = (operationTarget != null)
                                  && (operationTarget instanceof TextViewer)
                                  && (validateEditorInputState(iTextEditor))
                                  && (commentPrefix != null);
            
            if ((isTextOperationAllowed)) {
                int startLine = selection.getStartLine();
                int endLine = selection.getEndLine(); 
                int selOffset = selection.getOffset();
                int selLen = selection.getLength();
                int realEndLine = doc.getLineOfOffset(selOffset + selLen); // for selection end at pos=0 (endLine is line before here) 
                
                // Are cursor and anchor at 0 positions?
                boolean is0pos = false;
                if (doc.getLineOffset(startLine) == selOffset) {
                    if ((doc.getLineOffset(endLine) + doc.getLineLength(endLine) == selOffset + selLen)) {
                        is0pos = true;
                    }
                }
                
                
                ArrayList<ReplaceEdit> edits = null;
                int offsAfter[] = {0};
                if (is0pos || selLen == 0) {
                    edits = commentWholeLines(startLine, (selLen == 0) ? startLine : endLine, realEndLine, doc, offsAfter);
                } else {
                    edits = commentRange(selOffset, selLen, "(*", "*)", offsAfter); //$NON-NLS-1$ //$NON-NLS-2$
                }
                
                if (edits != null && !edits.isEmpty()) {
                    DocumentRewriteSession drws = null;
                    try {
                        if (doc instanceof IDocumentExtension4) {
                            drws = ((IDocumentExtension4)doc).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
                        }
                        MultiTextEdit edit= new MultiTextEdit(0, doc.getLength());
                        edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()]));
                        edit.apply(doc, TextEdit.CREATE_UNDO);
                        iTextEditor.getSelectionProvider().setSelection(new TextSelection(offsAfter[0], 0));
                    }
                    finally {
                        if (doc instanceof IDocumentExtension4 && drws != null) {
                            ((IDocumentExtension4)doc).stopRewriteSession(drws);
                        }
                    }
                    
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 19
Source File: ScriptLineBreakpointAdapter.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void toggleLineBreakpoints( IWorkbenchPart part, ISelection selection )
		throws CoreException
{
	DecoratedScriptEditor textEditor = getEditor( part );
	if ( textEditor != null )
	{
		ITextSelection textSelection = (ITextSelection) selection;
		IReportScriptLocation location = (IReportScriptLocation) textEditor.getAdapter( IReportScriptLocation.class );
		if ( location == null )
		{
			return;
		}

		int lineNumber = textSelection.getStartLine( );
		if ( location.getLineNumber( ) > 0 )
		{
			lineNumber = location.getLineNumber( );
		}

		IResource resource = (IResource) textEditor.getEditorInput( )
				.getAdapter( IResource.class );
		if ( resource == null )
		{
			resource = ScriptDebugUtil.getDefaultResource( );
		}

		IBreakpoint[] breakpoints = DebugPlugin.getDefault( )
				.getBreakpointManager( )
				.getBreakpoints( IScriptConstants.SCRIPT_DEBUG_MODEL );
		for ( int i = 0; i < breakpoints.length; i++ )
		{
			IBreakpoint breakpoint = breakpoints[i];
			if ( resource.equals( breakpoint.getMarker( ).getResource( ) ) )
			{
				if ( ( (ScriptLineBreakpoint) breakpoint ).getLineNumber( ) == ( lineNumber + 1 )
						&& ( (ScriptLineBreakpoint) breakpoint ).getFileName( )
								.equals( location.getReportFileName( ) )
						&& ( (ScriptLineBreakpoint) breakpoint ).getSubName( )
								.equals( location.getID( ) ) )
				{
					breakpoint.delete( );
					return;
				}
			}
		}
		// create line breakpoint (doc line numbers start at 0)
		ScriptLineBreakpoint lineBreakpoint = new ScriptLineBreakpoint( resource,
				location.getReportFileName( ),
				location.getID( ),
				lineNumber + 1 , location.getDisplayName( ));
		//lineBreakpoint.setDisplayName( location.getDisplayName( ) );
		DebugPlugin.getDefault( )
				.getBreakpointManager( )
				.addBreakpoint( lineBreakpoint );
	}

}
 
Example 20
Source File: ScriptRunToLineAdapter.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void runToLine( IWorkbenchPart part, ISelection selection,
		ISuspendResume target ) throws CoreException
{
	ITextEditor textEditor = getTextEditor( part );

	if ( textEditor == null )
	{
		return;
	}
	else
	{
		IEditorInput input = textEditor.getEditorInput( );

		if ( input == null || !( input instanceof DebugJsInput ) )
		{
			return;
		}

		DebugJsInput scriptInput = (DebugJsInput) input;
		IResource resource = (IResource) input.getAdapter( IResource.class );
		if ( resource == null )
		{
			resource = ScriptDebugUtil.getDefaultResource( );
		}

		final IDocument document = textEditor.getDocumentProvider( )
				.getDocument( input );
		if ( document == null )
		{
			return;
		}
		else
		{
			final int[] validLine = new int[1];
			// final String[] typeName = new String[1];
			final int[] lineNumber = new int[1];
			final ITextSelection textSelection = (ITextSelection) selection;
			Runnable r = new Runnable( ) {

				public void run( )
				{
					lineNumber[0] = textSelection.getStartLine( ) + 1;
				}
			};
			BusyIndicator.showWhile( DebugUI.getStandardDisplay( ), r );
			// TODO add the validLine to adjust if the line is validLine
			validLine[0] = lineNumber[0];
			if ( validLine[0] == lineNumber[0] )
			{
				ScriptLineBreakpoint point = new RunToLinebreakPoint( resource,
						scriptInput.getFile( ).getAbsolutePath( ),
						scriptInput.getId( ),
						lineNumber[0] );
				point.setType( ScriptLineBreakpoint.RUNTOLINE );
				if ( target instanceof IAdaptable )
				{
					ScriptDebugTarget debugTarget = (ScriptDebugTarget) ( (IAdaptable) target ).getAdapter( IDebugTarget.class );
					if ( debugTarget != null )
					{
						debugTarget.breakpointAdded( point );
						debugTarget.resume( );
					}
				}
			}
			else
			{
				// invalid line
				return;
			}
		}

	}
}