Java Code Examples for org.eclipse.jface.text.ITextSelection

The following examples show how to use org.eclipse.jface.text.ITextSelection. These examples are extracted from open source projects. 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 Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: MoveAction.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run(ITextSelection selection) {
	try {
		if (!ActionUtil.isEditable(fEditor))
			return;
		if (fMoveStaticMembersAction.isEnabled() && tryMoveStaticMembers(selection))
			return;

		if (fMoveInstanceMethodAction.isEnabled() && tryMoveInstanceMethod(selection))
			return;

		if (tryReorgMove())
			return;

		MessageDialog.openInformation(getShell(), RefactoringMessages.MoveAction_Move, RefactoringMessages.MoveAction_select);
	} catch (JavaModelException e) {
		ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
	}
}
 
Example #2
Source Project: goclipse   Author: GoClipse   File: ToggleCommentAction.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a region describing the text block (something that starts at
 * the beginning of a line) completely containing the current selection.
 *
 * @param selection The selection to use
 * @param document The document
 * @return the region describing the text block comprising the given selection
 */
protected static IRegion getTextBlockFromSelection(ITextSelection selection, IDocument document) {

	try {
		IRegion line= document.getLineInformationOfOffset(selection.getOffset());
		int length= selection.getLength() == 0 ? 
				line.getLength() : 
				selection.getLength() + (selection.getOffset() - line.getOffset());
		return new Region(line.getOffset(), length);

	} catch (BadLocationException x) {
		// should not happen
		LangCore.logError("Unexpected error.", x);
	}

	return null;
}
 
Example #3
Source Project: e4macs   Author: MulgaSoft   File: BlockHandler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
		ExecutionEvent event) throws BadLocationException {

	Control text = getTextWidget(editor);
	String cmd = ((getDirection() == FORWARD) ? IEmacsPlusCommandDefinitionIds.NEXT_LINE : IEmacsPlusCommandDefinitionIds.PREVIOUS_LINE);
	try {
		// use widget to avoid unpleasant scrolling side effects of IRewriteTarget			
		text.setRedraw(false);		
		for (int i=0; i < blockMovementSize; i++) {
			try {
				EmacsPlusUtils.executeCommand(cmd, null, editor);
			} catch (Exception e)  {}
		}
	} finally {
		text.setRedraw(true);
	}
	return NO_OFFSET;
}
 
Example #4
Source Project: e4macs   Author: MulgaSoft   File: TagsSearchHandler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The initial search string will be the closest full word forward, if it is on the same line
 * 
 * @param document
 * @param selection
 * @return the initial search string
 * 
 * @throws BadLocationException
 */
protected ITextSelection initText(ITextEditor editor, IDocument document, ITextSelection selection) throws BadLocationException {
	ITextSelection result = null;

	if (selection != null) {
		if (selection.getLength() == 0) {
			int line = document.getLineOfOffset(selection.getOffset());
			// get the proximate word
			try {
				ITextSelection tmp = new SexpForwardHandler().getTransSexp(document, selection.getOffset(), true);
				// make sure we're still on the same line
				if (tmp != null && line == document.getLineOfOffset(tmp.getOffset())) {
					selection = tmp;
				}
				// ignore 
			} catch (BadLocationException e) {}
		}
		if (selection != null && selection.getLength() > 0 && selection.getText() != null) {
			result = selection;
		}
	}
	return result;
}
 
Example #5
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: AddBlockCommentAction.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadLocationException, BadPartitioningException {
	int selectionOffset= selection.getOffset();
	int selectionEndOffset= selectionOffset + selection.getLength();
	List<Edit> edits= new LinkedList<Edit>();
	ITypedRegion partition= docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, selectionOffset, false);

	handleFirstPartition(partition, edits, factory, selectionOffset);

	while (partition.getOffset() + partition.getLength() < selectionEndOffset) {
		partition= handleInteriorPartition(partition, edits, factory, docExtension);
	}

	handleLastPartition(partition, edits, factory, selectionEndOffset);

	executeEdits(edits);
}
 
Example #6
Source Project: tm4e   Author: eclipse   File: ToggleLineCommentHandler.java    License: 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 #7
Source Project: tm4e   Author: eclipse   File: ToggleLineCommentHandler.java    License: 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 #8
Source Project: typescript.java   Author: angelozerr   File: TypeScriptEditor.java    License: MIT License 6 votes vote down vote up
protected void doSelectionChanged(SelectionChangedEvent event) {
	ISelection selection = event.getSelection();
	NavigationBarItem item = null;
	Iterator iter = ((IStructuredSelection) selection).iterator();
	while (iter.hasNext()) {
		Object o = iter.next();
		if (o instanceof NavigationBarItem) {
			item = (NavigationBarItem) o;
			break;
		}
	}

	setSelection(item, !isActivePart());

	ISelectionProvider selectionProvider = getSelectionProvider();
	if (selectionProvider == null)
		return;

	ISelection textSelection = selectionProvider.getSelection();
	if (!(textSelection instanceof ITextSelection))
		return;

	fForcedMarkOccurrencesSelection = textSelection;
	updateOccurrenceAnnotations((ITextSelection) textSelection);

}
 
Example #9
Source Project: xtext-eclipse   Author: eclipse   File: TextViewerMoveLinesAction.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Given a selection on a document, computes the lines fully or partially covered by
 * <code>selection</code>. A line in the document is considered covered if
 * <code>selection</code> comprises any characters on it, including the terminating delimiter.
 * <p>Note that the last line in a selection is not considered covered if the selection only
 * comprises the line delimiter at its beginning (that is considered part of the second last
 * line).
 * As a special case, if the selection is empty, a line is considered covered if the caret is
 * at any position in the line, including between the delimiter and the start of the line. The
 * line containing the delimiter is not considered covered in that case.
 * </p>
 *
 * @param document the document <code>selection</code> refers to
 * @param selection a selection on <code>document</code>
 * @param viewer the <code>ISourceViewer</code> displaying <code>document</code>
 * @return a selection describing the range of lines (partially) covered by
 * <code>selection</code>, without any terminating line delimiters
 * @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
 */
private ITextSelection getMovingSelection(IDocument document, ITextSelection selection, ITextViewer viewer) throws BadLocationException {
	int low= document.getLineOffset(selection.getStartLine());
	int endLine= selection.getEndLine();
	int high= document.getLineOffset(endLine) + document.getLineLength(endLine);

	// get everything up to last line without its delimiter
	String delim= document.getLineDelimiter(endLine);
	if (delim != null)
		high -= delim.length();

	// the new selection will cover the entire lines being moved, except for the last line's
	// delimiter. The exception to this rule is an empty last line, which will stay covered
	// including its delimiter
	if (delim != null && document.getLineLength(endLine) == delim.length())
		fAddDelimiter= true;
	else
		fAddDelimiter= false;

	return new TextSelection(document, low, high - low);
}
 
Example #10
Source Project: xtext-xtend   Author: eclipse   File: XtendRenameContextFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public IRenameElementContext createLocalRenameElementContext(EObject targetElement, XtextEditor editor,
		ITextSelection selection, XtextResource resource) {
	EObject declarationTarget = getDeclarationTarget(targetElement);
	if (declarationTarget instanceof XtendFunction && ((XtendFunction) declarationTarget).isDispatch()) {
		IProject project = projectUtil.getProject(declarationTarget.eResource().getURI());
		ResourceSet resourceSet = resourceSetProvider.get(project);
		XtendFunction relaodedDispatchFunction = (XtendFunction) resourceSet.getEObject(
				EcoreUtil2.getPlatformResourceOrNormalizedURI(declarationTarget), true);
		Iterable<JvmOperation> allDispatchOperations = dispatchRenameSupport
				.getAllDispatchOperations(relaodedDispatchFunction);
		Map<URI, IJavaElement> jvm2javaElement = newLinkedHashMap();
		for (JvmOperation jvmOperation : allDispatchOperations) {
			IJavaElement javaElement = getJavaElementFinder().findExactElementFor(jvmOperation);
			if (javaElement != null) {
				URI jvmOperationURI = EcoreUtil.getURI(jvmOperation);
				jvm2javaElement.put(jvmOperationURI, javaElement);
			}
		}
		if (!jvm2javaElement.isEmpty()) {
			return new DispatchMethodRenameContext(relaodedDispatchFunction, jvm2javaElement, editor, selection,
					resource);
		}
	}
	return super.createLocalRenameElementContext(targetElement, editor, selection, resource);
}
 
Example #11
Source Project: e4macs   Author: MulgaSoft   File: AppendCommentHandler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
		throws BadLocationException {
	IRegion reg = document.getLineInformationOfOffset(currentSelection.getOffset());
	String lineTxt = document.get(reg.getOffset(),reg.getLength());
	// Check if the line already contains a eol comment
	int pos = lineTxt.lastIndexOf(COMMENT_MARKER);
	if (pos < 0) {
		pos = reg.getOffset() + reg.getLength();
		document.replace(pos, 0, LINE_COMMENT);
		return pos + LINE_COMMENT.length();
	} else {
		// If it already exists, position cursor at the comment
		return pos
				+ COMMENT_MARKER.length()
				+ reg.getOffset()
				+ (lineTxt.substring(pos).matches(COMMENT_REGEX) ? 1 : 0);
	}
}
 
Example #12
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: InferTypeArgumentsAction.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run(ITextSelection selection) {
	if (!ActionUtil.isEditable(fEditor))
		return;
	IJavaElement element= SelectionConverter.getInput(fEditor);
	IJavaElement[] array= new IJavaElement[] {element};
	try {
		if (element != null && RefactoringAvailabilityTester.isInferTypeArgumentsAvailable(array)){
			RefactoringExecutionStarter.startInferTypeArgumentsRefactoring(array, getShell());
		} else {
			MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.InferTypeArgumentsAction_unavailable);
		}
	} catch (JavaModelException e) {
		ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
	}
}
 
Example #13
Source Project: e4macs   Author: MulgaSoft   File: SearchExecuteMinibuffer.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Prime the minibuffer with the supplied text (which must be guaranteed to be present and selected in the buffer)
 *  
 * @param selection
 */
public void initMinibufferSelection(ITextSelection selection){
	if (selection != null && selection.getLength() > 0) {
		String text = selection.getText();
		saveState();
		try {
			// temporarily disable selection changed
			setSearching(true);				
			MarkUtils.setSelection(getEditor(),selection);
		} finally {
			setSearching(false);
		}
		initMinibuffer(text);
		checkCasePos(text);
		addToHistory();
		// force start (for history searches) to beginning of text rather than cursor
		setStartOffset(getTextWidget().getSelectionRange().x);
		setFound(true);
	}
}
 
Example #14
Source Project: e4macs   Author: MulgaSoft   File: KbdMacroLoadHandler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
		ExecutionEvent event) throws BadLocationException {
	
	fileCompletions = null;
	if (!KbdMacroSupport.getInstance().isDefining() && !KbdMacroSupport.getInstance().isExecuting()) {
		String macroName = event.getParameter(NAME_ARG);
		boolean forceIt = (event.getParameter(FORCE_ARG) != null ? Boolean.valueOf(event.getParameter(FORCE_ARG)) : false);
		if (macroName != null && macroName.length() > 0) {
			File file = macroFile(macroName);
			if (file.exists()) {
				loadMacro(editor,macroName,file,forceIt);
			} else {
				asyncShowMessage(editor, String.format(MACRO_MISSING, macroName), true);					
			}
		} else {
			mbState = this.nameState();
			return mbState.run(editor);
		}
	} else {
		asyncShowMessage(editor, BAD_MACRO_STATE, true);
	}
	return NO_OFFSET;
}
 
Example #15
Source Project: e4macs   Author: MulgaSoft   File: RectangleOpenHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.IDocument, org.eclipse.jface.text.ITextSelection, org.eclipse.core.commands.ExecutionEvent)
 */
@Override
protected int doTransform(ITextEditor editor, IDocument document,
		ITextSelection currentSelection)
		throws BadLocationException {
	int result = NO_OFFSET;
	result = updateRectangle(editor, document, getImpliedSelection(editor,currentSelection), null, false);		
	return result;
}
 
Example #16
Source Project: e4macs   Author: MulgaSoft   File: KbdMacroEndCallHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.IDocument, org.eclipse.jface.text.ITextSelection, org.eclipse.core.commands.ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document,
		ITextSelection currentSelection, ExecutionEvent event)
		throws BadLocationException {
	return NO_OFFSET;
}
 
Example #17
Source Project: xds-ide   Author: excelsior-oss   File: ModulaOutlinePage.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Synchronizes outline view selection with editor selection, using the given editor selection
 */
private void synchronizeOutlineWithEditor(ISelection selection) {
	if (selection.isEmpty()) {
		return;
	}
	if (selection instanceof ITextSelection) {
		ITextSelection textSelection = (ITextSelection) selection;
		selectInTheOutlineTree(textSelection.getOffset());
		editor.setFocus();
	}
}
 
Example #18
Source Project: e4macs   Author: MulgaSoft   File: DownListHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.SexpBaseForwardHandler#consoleDispatch(TextConsoleViewer, IConsoleView, ExecutionEvent)
 */
public Object consoleDispatch(final TextConsoleViewer viewer, final IConsoleView activePart, ExecutionEvent event) {

	IDocument doc = viewer.getDocument();
	ITextSelection currentSelection = (ITextSelection) viewer.getSelectionProvider().getSelection();
	ITextSelection selection = downList(doc, currentSelection);
	if (selection == null) {
		unbalanced(activePart,false);
	} else {
		endTransform(viewer,selection.getOffset() + selection.getLength(), currentSelection, selection);
	}
	return null;
}
 
Example #19
Source Project: Pydev   Author: fabioz   File: FirstCharAction.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Run to the first char (other than whitespaces) or to the real first char. 
 */
@Override
public void run(IAction action) {

    try {
        ITextEditor textEditor = getTextEditor();
        IDocument doc = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
        ITextSelection selection = (ITextSelection) textEditor.getSelectionProvider().getSelection();

        perform(doc, selection);
    } catch (Exception e) {
        beep(e);
    }
}
 
Example #20
Source Project: e4macs   Author: MulgaSoft   File: KbdMacroBindHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument, ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
		ExecutionEvent event) throws BadLocationException {
	boolean named = isUniversalPresent();
	if (KbdMacroSupport.getInstance().hasKbdMacro(named) && !KbdMacroSupport.getInstance().isBusy()) {
		mbState = (named ? nameState() : bindState(null));
		return mbState.run(editor);
	} else {
		asyncShowMessage(editor, NO_MACRO_ERROR, true);
	}
	return NO_OFFSET;
}
 
Example #21
Source Project: birt   Author: eclipse   File: ScriptLineBreakpointAdapter.java    License: 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 #22
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: InlineTempAction.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(ITextSelection selection) {
	ICompilationUnit input= SelectionConverter.getInputAsCompilationUnit(fEditor);
	if (!ActionUtil.isEditable(fEditor))
		return;
	RefactoringExecutionStarter.startInlineTempRefactoring(input, null, selection, getShell());
}
 
Example #23
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: CopyToClipboardAction.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void copyToClipboard(ITextSelection selection, int repeatCount) {
	try{
		fClipboard.setContents(new String[] { selection.getText() }, new Transfer[] { TextTransfer.getInstance() });
	} catch (SWTError e) {
		if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD || repeatCount >= MAX_REPEAT_COUNT)
			throw e;

		if (MessageDialog.openQuestion(getShell(), InfoViewMessages.CopyToClipboard_error_title, InfoViewMessages.CopyToClipboard_error_message))
			copyToClipboard(selection, repeatCount + 1);
	}
}
 
Example #24
Source Project: tlaplus   Author: tlaplus   File: FocusOnStepHandler.java    License: MIT License 5 votes vote down vote up
/**
 * This method is used to update the enablement state. This has the
 * effect of graying out any menu items for the
 * command if the handler is disabled. Through experimentation, this method seems to be
 * called just before such menu items are rendered in the UI and
 * just before the handler is executed.
 */
public void setEnabled(Object context)
{
    TLAEditor editor = EditorUtil.getTLAEditorWithFocus();

    if (editor != null)
    {
        if (editor.getProofStructureProvider() != null)
        {
            setBaseEnabled(editor.getProofStructureProvider().canRunFoldOperation(
                    IProofFoldCommandIds.FOCUS_ON_STEP,
                    (ITextSelection) editor.getSelectionProvider().getSelection()));
        }
    }
}
 
Example #25
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: JavaMoveLinesAction.java    License: 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 #26
Source Project: xtext-eclipse   Author: eclipse   File: RailroadSelectionLinker.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void textSelectionChanged(SelectionChangedEvent event) {
	ISelection selection = event.getSelection();
	if (selection instanceof ITextSelection && !selection.isEmpty()) {
		ITextSelection textSelection = (ITextSelection) selection;
		int offset = textSelection.getOffset();
		IFigure figureToBeSelected = findFigureForTextOffset(view.getContents(), offset, null);
		if (figureToBeSelected != null) {
			selectFigure(figureToBeSelected);
			view.reveal(figureToBeSelected);
		}
	}
}
 
Example #27
Source Project: xds-ide   Author: excelsior-oss   File: WorkbenchUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Fetches the text selection from the active text editor.
 * 
 * @return the text selection or <code>null</code>, when there is no active
 *         editor or it is not a text editor
 */
public static ITextSelection getActiveTextSelection() {
    IEditorPart editor = getActiveEditor(true);
    if (editor instanceof ITextEditor) {
        ISelection selection = ((ITextEditor) editor)
                .getSelectionProvider().getSelection();
        if (selection instanceof ITextSelection) {
            return (ITextSelection) selection;
        }
    }
    return null;
}
 
Example #28
Source Project: xtext-eclipse   Author: eclipse   File: AbstractSourceView.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isValidSelection(IWorkbenchPartSelection workbenchPartSelection) {
	return !this.equals(workbenchPartSelection.getWorkbenchPart())
			&& workbenchPartSelection.getWorkbenchPart() instanceof XtextEditor
			&& workbenchPartSelection.getSelection() instanceof ITextSelection
			&& ((XtextEditor) workbenchPartSelection.getWorkbenchPart()).getLanguageName().equalsIgnoreCase(
					languageName);
}
 
Example #29
Source Project: e4macs   Author: MulgaSoft   File: MarkUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param editor
 * @param start
 *            - in model coords
 * @param length
 *            - in model coords
 */
public static ITextSelection setSelection(ITextEditor editor, int start, int length) {

	TextViewer tv = findTextViewer(editor);
	ITextSelection selection = new TextSelection(null, start, length);
	if (tv != null) {
		tv.setSelection(selection, false);
	} else {
		setSelection(editor, selection);
	}
	return selection;
}
 
Example #30
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: BlockCommentAction.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the editor's selection, or <code>null</code> if no selection can be obtained or the
 * editor is <code>null</code>.
 *
 * @return the selection of the action's editor, or <code>null</code>
 */
protected ITextSelection getCurrentSelection() {
	ITextEditor editor= getTextEditor();
	if (editor != null) {
		ISelectionProvider provider= editor.getSelectionProvider();
		if (provider != null) {
			ISelection selection= provider.getSelection();
			if (selection instanceof ITextSelection)
				return (ITextSelection) selection;
		}
	}
	return null;
}