Java Code Examples for org.eclipse.ui.texteditor.ITextEditor#selectAndReveal()

The following examples show how to use org.eclipse.ui.texteditor.ITextEditor#selectAndReveal() . 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: EditorUtil.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Selects and reveals the given line in given editor.
 * <p>
 * Must be executed from UI thread.
 *
 * @param editorPart
 * @param lineNumber
 */
public static void goToLine(IEditorPart editorPart, int lineNumber) {
    if (!(editorPart instanceof ITextEditor) || lineNumber < DEFAULT_LINE_IN_EDITOR) {
        return;
    }
    ITextEditor editor = (ITextEditor) editorPart;
    IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
    if (document != null) {
        IRegion lineInfo = null;
        try {
            // line count internaly starts with 0, and not with 1 like in
            // GUI
            lineInfo = document.getLineInformation(lineNumber - 1);
        } catch (BadLocationException e) {
            // ignored because line number may not really exist in document,
            // we guess this...
        }
        if (lineInfo != null) {
            editor.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
        }
    }
}
 
Example 2
Source File: EditorOpener.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
public IEditorPart openAndSelect(IWorkbenchPage wbPage, IFile file, int offset, int length, boolean activate)
        throws PartInitException {
    String editorId = null;
    IEditorDescriptor desc = IDE.getEditorDescriptor(file);
    if (desc == null || !desc.isInternal()) {
        editorId = "org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$
    } else {
        editorId = desc.getId();
    }

    IEditorPart editor;
    if (NewSearchUI.reuseEditor()) {
        editor = showWithReuse(file, wbPage, editorId, activate);
    } else {
        editor = showWithoutReuse(file, wbPage, editorId, activate);
    }

    if (editor instanceof ITextEditor) {
        ITextEditor textEditor = (ITextEditor) editor;
        textEditor.selectAndReveal(offset, length);
    } else if (editor != null) {
        showWithMarker(editor, file, offset, length);
    }
    return editor;
}
 
Example 3
Source File: EditorUtils.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Select the line given by lineNumber. Takes no effect if lineNumber <= 0 || lineNumber > number of lines in document
 * @param textEdit Text editor to select line in
 * @param lineNumber Line number to select. (First line in the editor is line 1)
 */
public static void showInEditor(ITextEditor textEdit, int lineNumber) {
    // Setting line number programatically courtesy of
    // http://stackoverflow.com/questions/2873879/eclipe-pde-jump-to-line-x-and-highlight-it
    if (lineNumber > 0) {
        IDocument document = textEdit.getDocumentProvider().getDocument(
                textEdit.getEditorInput());
        if (document != null) {
            IRegion lineInfo = null;
            try {
                // line count internally starts with 0
                lineInfo = document.getLineInformation(lineNumber - 1);
            } catch (BadLocationException e) {
                // ignored because line number may not really exist in document,
            }
            if (lineInfo != null) {
                textEdit.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
            }
        }
    }
}
 
Example 4
Source File: JavaSearchResultPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void showMatch(Match match, int offset, int length, boolean activate) throws PartInitException {
	IEditorPart editor= fEditorOpener.openMatch(match);

	if (editor != null && activate)
		editor.getEditorSite().getPage().activate(editor);
	Object element= match.getElement();
	if (editor instanceof ITextEditor) {
		ITextEditor textEditor= (ITextEditor) editor;
		textEditor.selectAndReveal(offset, length);
	} else if (editor != null) {
		if (element instanceof IFile) {
			IFile file= (IFile) element;
			showWithMarker(editor, file, offset, length);
		}
	} else if (getInput() instanceof JavaSearchResult) {
		JavaSearchResult result= (JavaSearchResult) getInput();
		IMatchPresentation participant= result.getSearchParticpant(element);
		if (participant != null)
			participant.showMatch(match, offset, length, activate);
	}
}
 
Example 5
Source File: TextDocumentMarkerResolution.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
public void run(IMarker marker) {
    try {
        IResource resource = marker.getResource();
        if (resource.getType() != IResource.FILE) {
            throw new CoreException(createStatus(null, "The editor is not a File: " + resource.getName()));
        }
        IFile file = (IFile) resource;
        ITextEditor editor = openTextEditor(file);
        IDocument document = editor.getDocumentProvider().getDocument(new FileEditorInput(file));
        if (document == null) {
            throw new CoreException(createStatus(null, "The document is null"));
        }
        IRegion region = processFix(document, marker);
        if (region != null) {
            editor.selectAndReveal(region.getOffset(), region.getLength());
        }
    } catch (CoreException e) {
        Activator.getDefault().getLog().log(e.getStatus());
    }
}
 
Example 6
Source File: PyConvertTabToSpace.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Grabs the selection information and performs the action.
 */
@Override
public void run(IAction action) {
    try {
        if (!canModifyEditor()) {
            return;
        }

        // Select from text editor
        ITextEditor textEditor = getTextEditor();
        ps = PySelectionFromEditor.createPySelectionFromEditor(textEditor);
        ps.selectAll(false);
        // Perform the action
        perform(textEditor);

        // Put cursor at the first area of the selection
        textEditor.selectAndReveal(ps.getLineOffset(), 0);
    } catch (Exception e) {
        beep(e);
    }
}
 
Example 7
Source File: PyConvertSpaceToTab.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Grabs the selection information and performs the action.
 */
@Override
public void run(IAction action) {
    try {
        if (!canModifyEditor()) {
            return;
        }

        // Select from text editor
        ITextEditor textEditor = getTextEditor();
        ps = PySelectionFromEditor.createPySelectionFromEditor(textEditor);
        ps.selectAll(false);
        // Perform the action
        perform(ps, textEditor);

        // Put cursor at the first area of the selection
        textEditor.selectAndReveal(ps.getLineOffset(), 0);
    } catch (Exception e) {
        beep(e);
    }
}
 
Example 8
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
private void removeBlockComment(IDocument document, ITextSelection selection, IRegion existingBlock,
		CharacterPair blockComment, ITextEditor editor) throws BadLocationException {
	int openOffset = existingBlock.getOffset();
	int openLength = blockComment.getKey().length();
	int closeOffset = existingBlock.getOffset() + existingBlock.getLength();
	int closeLength = blockComment.getValue().length();
	document.replace(openOffset, openLength, "");
	document.replace(closeOffset - openLength, closeLength, "");

	int offsetFix = openLength;
	int lengthFix = 0;
	if (selection.getOffset() < openOffset + openLength) {
		offsetFix = selection.getOffset() - openOffset;
		lengthFix = openLength - offsetFix;
	}
	if (selection.getOffset() + selection.getLength() > closeOffset) {
		lengthFix += selection.getOffset() + selection.getLength() - closeOffset;
	}
	ITextSelection newSelection = new TextSelection(selection.getOffset() - offsetFix,
			selection.getLength() - lengthFix);
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
Example 9
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 10
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
private void removeLineComments(IDocument document, ITextSelection selection, String comment, ITextEditor editor)
		throws BadLocationException {
	int lineNumber = selection.getStartLine();
	int endLineNumber = selection.getEndLine();
	String oldText = document.get();
	int deletedChars = 0;
	Boolean isStartBeforeComment = false;

	while (lineNumber <= endLineNumber) {
		int commentOffset = oldText.indexOf(comment, document.getLineOffset(lineNumber) + deletedChars);
		document.replace(commentOffset - deletedChars, comment.length(), "");
		if (deletedChars == 0) {
			isStartBeforeComment = commentOffset > selection.getOffset();
		}
		if (lineNumber != endLineNumber) {
			deletedChars += comment.length();
		}
		lineNumber++;
	}
	ITextSelection newSelection = new TextSelection(
			selection.getOffset() - (isStartBeforeComment ? 0 : comment.length()),
			selection.getLength() - deletedChars);
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
Example 11
Source File: ErrorLineMatcher.java    From corrosion with Eclipse Public License 2.0 6 votes vote down vote up
private static void jumpToPosition(IEditorPart editorPart, int lineNumber, int lineOffset) {
	if (editorPart instanceof ITextEditor) {
		ITextEditor textEditor = (ITextEditor) editorPart;
		IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());

		if (document != null) {
			IRegion region = null;
			try {
				region = document.getLineInformation(lineNumber - 1);
			} catch (BadLocationException exception) {
				// ignore
			}

			if (region != null)
				textEditor.selectAndReveal(region.getOffset() + lineOffset - 1, 0);
		}
	}
}
 
Example 12
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
private void addBlockComment(IDocument document, ITextSelection selection, CharacterPair blockComment,
		ITextEditor editor) throws BadLocationException {
	document.replace(selection.getOffset(), 0, blockComment.getKey());
	document.replace(selection.getOffset() + selection.getLength() + blockComment.getKey().length(), 0,
			blockComment.getValue());
	ITextSelection newSelection = new TextSelection(selection.getOffset() + blockComment.getKey().length(),
			selection.getLength());
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
Example 13
Source File: StorageBasedTextEditorOpener.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void open(IWorkbenchPage page) {
	try {
		IEditorInput input = EditorUtils.createEditorInput(storage);
		IEditorDescriptor editorDescriptor = IDE.getEditorDescriptor(storage.getName());
		IEditorPart opened = IDE.openEditor(page, input, editorDescriptor.getId());
		if (region != null && opened instanceof ITextEditor) {
			ITextEditor openedTextEditor = (ITextEditor) opened;
			openedTextEditor.selectAndReveal(region.getOffset(), region.getLength());
		}
	} catch (PartInitException e) {
		LOG.error(e.getMessage(), e);
	}
}
 
Example 14
Source File: EndStatementCodeMining.java    From jdt-codemining with Eclipse Public License 1.0 5 votes vote down vote up
public EndStatementCodeMining(Statement node, ITextEditor textEditor, ITextViewer viewer, int minLineNumber,
		ICodeMiningProvider provider) {
	super(new Position(node.getStartPosition() + node.getLength(), 1), provider, e -> {
		textEditor.selectAndReveal(node.getStartPosition(), 0);
	});
	String label = getLabel(node, viewer.getDocument(), minLineNumber);
	super.setLabel(label);
}
 
Example 15
Source File: TLCUIHelper.java    From tlaplus with MIT License 5 votes vote down vote up
public static boolean jumpToSavedLocation(Location location, Model model,
Set<Class<? extends ITextEditor>> blacklist)
 {
     IEditorPart editor = model.getAdapter(ModelEditor.class);
     if (editor instanceof ModelEditor)
     {
         ModelEditor modelEditor = (ModelEditor) editor;

         ITextEditor moduleEditor = modelEditor.getSavedModuleEditor(location.source());

         if (moduleEditor != null && !blacklist.contains(moduleEditor.getClass()))
         {
             try
             {
                 IRegion jumpToRegion = AdapterFactory.locationToRegion(moduleEditor.getDocumentProvider()
                         .getDocument(moduleEditor.getEditorInput()), location);
                 // bring the model editor into focus
                 UIHelper.getActivePage().activate(modelEditor);
                 // set the nested module editor as the active page in the model editor
                 modelEditor.setActiveEditor(moduleEditor);
                 // highlight the appropriate text
                 moduleEditor.selectAndReveal(jumpToRegion.getOffset(), jumpToRegion.getLength());
                 return true;
             } catch (BadLocationException e)
             {
                 TLCUIActivator.getDefault().logError("Error converting location to region in saved module. The location is "
                         + location, e);
             }
         }
     }
     return false;
 }
 
Example 16
Source File: NLSSearchResultPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void showMatch(Match match, int currentOffset, int currentLength, boolean activate) throws PartInitException {
	IEditorPart editor= fEditorOpener.openMatch(match);
	if (editor != null && activate)
		editor.getEditorSite().getPage().activate(editor);
	if (editor instanceof ITextEditor) {
		ITextEditor textEditor= (ITextEditor) editor;
		textEditor.selectAndReveal(currentOffset, currentLength);
	}
}
 
Example 17
Source File: TestResultHyperlink.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void revealLocationInFile(IEditorPart editorPart)
		throws CoreException {
	if (editorPart instanceof ITextEditor && locationText.line > 0) {
		ITextEditor textEditor = (ITextEditor) editorPart;
		IDocumentProvider provider = textEditor.getDocumentProvider();
		IEditorInput editorInput = editorPart.getEditorInput();
		provider.connect(editorInput);
		IDocument document = provider.getDocument(editorInput);
		try {
			IRegion regionOfLine = document.getLineInformation(locationText.line - 1);
			// only used to reveal the location
			textEditor.selectAndReveal(regionOfLine.getOffset(), regionOfLine.getLength());
			int startOffset = regionOfLine.getOffset() + locationText.column - 1;
			int length = regionOfLine.getLength() - locationText.column;
			if (startOffset >= document.getLength()) {
				startOffset = document.getLength() - 1;
			}
			if (length + startOffset >= document.getLength()) {
				length = document.getLength() - startOffset - 1;
			}
			textEditor.setHighlightRange(startOffset, length, true);
		} catch (BadLocationException e) {
			MessageDialog.openInformation(N4JSGracefulActivator.getActiveWorkbenchShell(),
					ConsoleMessages.msgInvalidLineNumberTitle(),
					ConsoleMessages.msgInvalidLineNumberIn(
							(locationText.line) + "",
							locationText.fileName));
		}
		provider.disconnect(editorInput);
	}
}
 
Example 18
Source File: N4JSStackTraceHyperlink.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void revealLocationInFile(String typeName, int line, int column, IEditorPart editorPart)
		throws CoreException {
	if (editorPart instanceof ITextEditor && line >= 0) {
		ITextEditor textEditor = (ITextEditor) editorPart;
		IDocumentProvider provider = textEditor.getDocumentProvider();
		IEditorInput editorInput = editorPart.getEditorInput();
		provider.connect(editorInput);
		IDocument document = provider.getDocument(editorInput);
		try {
			IRegion regionOfLine = document.getLineInformation(line);
			// only used to reveal the location
			textEditor.selectAndReveal(regionOfLine.getOffset(), regionOfLine.getLength());
			int startOffset = regionOfLine.getOffset() + column;
			int length = regionOfLine.getLength() - column;
			if (startOffset >= document.getLength()) {
				startOffset = document.getLength() - 1;
			}
			if (length + startOffset >= document.getLength()) {
				length = document.getLength() - startOffset - 1;
			}
			textEditor.setHighlightRange(startOffset, length, true);
		} catch (BadLocationException e) {
			MessageDialog.openInformation(N4JSGracefulActivator.getActiveWorkbenchShell(),
					ConsoleMessages.msgInvalidLineNumberTitle(),
					ConsoleMessages.msgInvalidLineNumberIn(
							(line + 1) + "",
							typeName));
		}
		provider.disconnect(editorInput);
	}
}
 
Example 19
Source File: CallHierarchyUI.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Opens the element in the editor or shows an error dialog if that fails.
 *
 * @param element the element to open
 * @param shell parent shell for error dialog
 * @param activateOnOpen <code>true</code> if the editor should be activated
 * @return <code>true</code> iff no error occurred while trying to open the editor,
 *         <code>false</code> iff an error dialog was raised.
 */
public static boolean openInEditor(Object element, Shell shell, boolean activateOnOpen) {
       CallLocation callLocation= CallHierarchy.getCallLocation(element);

       try {
        IMember enclosingMember;
        int selectionStart;
		int selectionLength;

        if (callLocation != null) {
			enclosingMember= callLocation.getMember();
			selectionStart= callLocation.getStart();
			selectionLength= callLocation.getEnd() - selectionStart;
        } else if (element instanceof MethodWrapper) {
        	enclosingMember= ((MethodWrapper) element).getMember();
        	ISourceRange selectionRange= enclosingMember.getNameRange();
        	if (selectionRange == null)
        		selectionRange= enclosingMember.getSourceRange();
        	if (selectionRange == null)
        		return true;
        	selectionStart= selectionRange.getOffset();
        	selectionLength= selectionRange.getLength();
        } else {
            return true;
        }

		IEditorPart methodEditor = JavaUI.openInEditor(enclosingMember, activateOnOpen, false);
           if (methodEditor instanceof ITextEditor) {
               ITextEditor editor = (ITextEditor) methodEditor;
			editor.selectAndReveal(selectionStart, selectionLength);
           }
           return true;
       } catch (JavaModelException e) {
           JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),
                   IJavaStatusConstants.INTERNAL_ERROR,
                   CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_message, e));

           ErrorDialog.openError(shell, CallHierarchyMessages.OpenLocationAction_error_title,
               CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_message,
               e.getStatus());
           return false;
       } catch (PartInitException x) {
           String name;
       	if (callLocation != null)
       		name= callLocation.getCalledMember().getElementName();
       	else if (element instanceof MethodWrapper)
       		name= ((MethodWrapper) element).getName();
       	else
       		name= "";  //$NON-NLS-1$
           MessageDialog.openError(shell, CallHierarchyMessages.OpenLocationAction_error_title,
               Messages.format(
                   CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_messageArgs,
                   new String[] { name, x.getMessage() }));
           return false;
       }
   }
 
Example 20
Source File: AbstractLangStructureEditor.java    From goclipse with Eclipse Public License 1.0 4 votes vote down vote up
public static void setElementSelection(ITextEditor editor, StructureElement element) {
	SourceRange nameSR = element.getNameSourceRange2();
	if(nameSR != null) {
		editor.selectAndReveal(nameSR.getOffset(), nameSR.getLength());
	}
}