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

The following examples show how to use org.eclipse.jface.text.ITextSelection#getOffset() . 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: SearchMinibuffer.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
public void selectionChanged(SelectionChangedEvent event) {
	boolean ignore= false;
	ISelection selection= event.getSelection();
	ITextSelection textSelection = ((selection instanceof ITextSelection) ? (ITextSelection)selection : null);
	if (textSelection != null) {
		Point range= getSelection();
		ignore= textSelection.getOffset() + textSelection.getLength() == range.x + range.y;
	} else if (selection instanceof MarkSelection) {
		// ignore mark selections as this is a side-effect of leaving the search
		ignore = true;
	}
	if (!isSearching() && !ignore) {
		// leave with affecting the selection position
		super.leave(false);
	}
}
 
Example 2
Source File: ScopeSelectionAction.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
public void deselect(BaseEditor editor) {
    FastStack<IRegion> stack = ScopeSelectionAction.getCache(editor);

    ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
    Region region = new Region(selection.getOffset(), selection.getLength());
    Iterator<IRegion> it = stack.topDownIterator();
    while (it.hasNext()) {
        IRegion iRegion = it.next();
        stack.pop(); //After getting the latest, pop it.

        if (iRegion.equals(region)) {
            if (stack.size() > 0) {
                IRegion peek = stack.peek();
                editor.setSelection(peek.getOffset(), peek.getLength());
            }
            break;
        }
    }
}
 
Example 3
Source File: TransposeSexpHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get the previous and following sexps around point
 * @param editor
 * @param document
 * @param selection
 * @param wordp
 * @return A Sexps structure containing the two sexps as ITextSelections
 * 
 * @throws BadLocationException
 */
private Sexps getSexpsAtPoint(ITextEditor editor, IDocument document, ITextSelection selection, boolean wordp) throws BadLocationException {
	ITextSelection forward =foresexp.getTransSexp(document, selection.getOffset(), wordp);
	ITextSelection backward = null;
	if (forward != null) {
		// check if cursor was inside sexp1
		if (forward.getOffset() < selection.getOffset()) {
			backward = foresexp.getTransSexp(document, forward.getOffset() + forward.getLength(), wordp);
			ITextSelection tmp = forward;
			forward = backward;
			backward = tmp;
		} else {
			backward = backsexp.getTransSexp(document, forward.getOffset(), wordp);
		}
	}
	return new Sexps(forward,backward);
}
 
Example 4
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void setSelection(ISelection selection) {
	if (selection instanceof ITextSelection) {
		if (fInvalidSelection != null) {
			fInvalidSelection= null;

			ITextSelection newSelection= (ITextSelection) selection;
			ITextSelection oldSelection= (ITextSelection) getSelection();

			if (newSelection.getOffset() == oldSelection.getOffset() && newSelection.getLength() == oldSelection.getLength()) {
				markValid();
			} else {
				super.setSelection(selection);
			}
		} else {
			super.setSelection(selection);
		}
	} else if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).getFirstElement() instanceof EditorBreadcrumb) {
		markInvalid();
	}
}
 
Example 5
Source File: YankPopHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Replace the yanked text with the previous yank and return the new offset 
 * 
 * @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 {
	
	if (KillRing.getInstance().isYanked()) {
		return (currentSelection.getOffset() + yankIt(document,currentSelection));
	} else if (autoBrowse) { 
		// Browse kill ring if true
		try {
			EmacsPlusUtils.executeCommand(IEmacsPlusCommandDefinitionIds.BROWSE_KILL_RING,null,editor);
		} catch (Exception e) {
			EmacsPlusUtils.showMessage(editor, EmacsPlusActivator.getString(YP_DISABLED),false);
		}
	} else {
		EmacsPlusUtils.showMessage(editor, EmacsPlusActivator.getString(YP_DISABLED),false);
	}
	return currentSelection.getOffset();
}
 
Example 6
Source File: RegionWidenHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusNoEditHandler#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 {

	// because of issues with preferences -> java -> editor [] only show the selected Java element
	// always set the highlight range to false
	if (editor != null) {
		IRegion remembered= editor.getHighlightRange();
		editor.resetHighlightRange();
		editor.showHighlightRangeOnly(false);
		if (remembered != null) {
			editor.setHighlightRange(remembered.getOffset(), remembered.getLength(), false);
		}
		// remove buffer local value
		BufferLocal.getInstance().kill(editor, BufferLocal.NARROW_REGION);
	} else {
		beep();
	}
	return currentSelection.getOffset();
}
 
Example 7
Source File: JavaMoveLinesAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ILineRange getLineRange(IDocument document, ITextSelection selection) throws BadLocationException {
	final int offset= selection.getOffset();
	int startLine= document.getLineOfOffset(offset);
	int endOffset= offset + selection.getLength();
	int endLine= document.getLineOfOffset(endOffset);
	final int nLines= endLine - startLine + 1;
	return new LineRange(startLine, nLines);
}
 
Example 8
Source File: DefaultRenameElementHandler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isRefactoringEnabled(IRenameElementContext renameElementContext, XtextResource resource) {
	ResourceSet resourceSet = resource.getResourceSet();
	if (renameElementContext != null && resourceSet != null) {
		EObject targetElement = resourceSet.getEObject(renameElementContext.getTargetElementURI(), true);
		if (targetElement != null && !targetElement.eIsProxy()) {
			if(targetElement.eResource() == resource && renameElementContext.getTriggeringEditorSelection() instanceof ITextSelection) {
				ITextSelection textSelection = (ITextSelection) renameElementContext.getTriggeringEditorSelection();
				ITextRegion selectedRegion = new TextRegion(textSelection.getOffset(), textSelection.getLength());
				INode crossReferenceNode = eObjectAtOffsetHelper.getCrossReferenceNode(resource, selectedRegion);
				if(crossReferenceNode == null) {
					// selection is on the declaration. make sure it's the name
					ITextRegion significantRegion = locationInFileProvider.getSignificantTextRegion(targetElement);
					if(!significantRegion.contains(selectedRegion)) 
						return false;
				}
			}
			IRenameStrategy.Provider renameStrategyProvider = globalServiceProvider.findService(targetElement,
					IRenameStrategy.Provider.class);
			try {
				if (renameStrategyProvider.get(targetElement, renameElementContext) != null) {
					return true;
				} else {
					IRenameStrategy2 strategy2 = globalServiceProvider.findService(targetElement, IRenameStrategy2.class); 
					ISimpleNameProvider simpleNameProvider = globalServiceProvider.findService(targetElement, ISimpleNameProvider.class); 
					return strategy2 != null && simpleNameProvider.canRename(targetElement);
				}
					
			} catch (NoSuchStrategyException e) {
				MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Cannot rename element",
						e.getMessage());
			}
		}
	}
	return false;
}
 
Example 9
Source File: SelectionConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IJavaElement resolveEnclosingElement(IJavaElement input, ITextSelection selection) throws JavaModelException {
	IJavaElement atOffset= null;
	if (input instanceof ICompilationUnit) {
		ICompilationUnit cunit= (ICompilationUnit)input;
		JavaModelUtil.reconcile(cunit);
		atOffset= cunit.getElementAt(selection.getOffset());
	} else if (input instanceof IClassFile) {
		IClassFile cfile= (IClassFile)input;
		atOffset= cfile.getElementAt(selection.getOffset());
	} else {
		return null;
	}
	if (atOffset == null) {
		return input;
	} else {
		int selectionEnd= selection.getOffset() + selection.getLength();
		IJavaElement result= atOffset;
		if (atOffset instanceof ISourceReference) {
			ISourceRange range= ((ISourceReference)atOffset).getSourceRange();
			while (range.getOffset() + range.getLength() < selectionEnd) {
				result= result.getParent();
				if (! (result instanceof ISourceReference)) {
					result= input;
					break;
				}
				range= ((ISourceReference)result).getSourceRange();
			}
		}
		return result;
	}
}
 
Example 10
Source File: OpenAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(ITextSelection selection) {

	if (!checkEnabled(selection))
		return;

	IRegion region= new Region(selection.getOffset(), selection.getLength());
	PropertyKeyHyperlinkDetector detector= new PropertyKeyHyperlinkDetector();
	detector.setContext(fEditor);
	IHyperlink[]hyperlinks= detector.detectHyperlinks(fEditor.internalGetSourceViewer(), region, false);

	if (hyperlinks != null && hyperlinks.length == 1)
		hyperlinks[0].open();

}
 
Example 11
Source File: RegisterNumberHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.minibuffer.IMinibufferExecutable#executeResult(org.eclipse.ui.texteditor.ITextEditor, java.lang.Object)
 */
public boolean doExecuteResult(ITextEditor editor, Object minibufferResult) {
	
	if (minibufferResult != null && ((String)minibufferResult).length() > 0) {
		String key = (String)minibufferResult;
		int number = 0; 
		if (getCallCount() > 1) {
			number = getCallCount();
		} else {
			ITextSelection sel = getCurrentSelection(editor);
			// if some text is selected, use it
			if (sel.getLength() == 0) {
				// else get the next token in the buffer and try that
				sel = getNextSelection(getThisDocument(editor), sel);
			}
			String text = null;
			if (sel != null && (text = sel.getText()) != null && text.length() > 0) {
				try {
					number = Integer.parseInt(text);
					int offend = sel.getOffset()+sel.getLength();
					selectAndReveal(editor, offend, offend);
				} catch (NumberFormatException e) {
				}
			} 
		}
		TecoRegister.getInstance().put(key,number);				
		showResultMessage(editor, String.format(REGISTER_NUMBER, key,number), false);
	} else {
		showResultMessage(editor, NO_REGISTER, true);
	}
	return true;
}
 
Example 12
Source File: SelectionUtils.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Special for keyword "@ARG" in debug script language
 */
public static WordAndRegion getWordUnderCursor(IDocument document, boolean isPrevious, ITextSelection selection, boolean withSobaka) 
{
    try {
        boolean isPunctUnderCursor = document.get(selection.getOffset(), 1).matches(tokenExpression);
        int right = selection.getOffset();
        if (!isPunctUnderCursor) {
            for (int i = right + 1; i < document.getLength(); i++) {
                if (document.get(i, 1).matches(tokenExpression)) break;
                right = i;
            }
        }
        else {
            right--;
        }
        int left = selection.getOffset();
        for (int i = left - 1; i > -1; i--) {
            if (document.get(i, 1).matches(tokenExpression)) break;
            left = i;
        }
        String word = document.get(left, right - left + 1);
        if (word.length() == 0                     // empty word OR ... 
                || word.matches(tokenExpression+"+")) { // ... only punctuation/spaces //$NON-NLS-1$
            return null;
        }
        if (withSobaka && left>0) {
            if ("@".equals(document.get(left-1, 1))) {
                --left;
                word = "@" + word;
            }
        }
        return new WordAndRegion(word, left, right - left + 1, selection.getOffset());
    } catch (BadLocationException e) {
    }
    return null;
}
 
Example 13
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 14
Source File: GamlEditor.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public void applyTemplate(final Template t) {
	// TODO Create a specific context type (with GAML specific variables ??)
	final XtextTemplateContextType ct = new XtextTemplateContextType();
	final IDocument doc = getDocument();
	final ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
	final int offset = selection.getOffset();
	final int length = selection.getLength();
	final Position pos = new Position(offset, length);
	final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
	final IRegion r = new Region(offset, length);
	final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
	tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
}
 
Example 15
Source File: OccurrencesSearchMenuAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ISelection getEditorSelection(JavaEditor editor) {
	ITypeRoot element= SelectionConverter.getInput(editor);
	if (element == null)
		return null;

	if (editor.isBreadcrumbActive())
		return editor.getBreadcrumb().getSelectionProvider().getSelection();
	else {
		ITextSelection textSelection= (ITextSelection) editor.getSelectionProvider().getSelection();
		IDocument document= JavaUI.getDocumentProvider().getDocument(editor.getEditorInput());
		return new JavaTextSelection(element, document, textSelection.getOffset(), textSelection.getLength());
	}
}
 
Example 16
Source File: SexpHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
protected int noSelectTransform(TextConsoleViewer viewer, int offset, ITextSelection selection, boolean moveit) {
	// move the cursor if moveit == true	
	int newOffset = selection.getOffset();
	newOffset = (moveit ? newOffset + selection.getLength() : newOffset);
	viewer.setSelectedRange(newOffset, 0);
	
	return NO_OFFSET;
}
 
Example 17
Source File: SnippetContentAssistProcessor.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get the current selection from the given {@code viewer}. If there is a (non
 * empty) selection returns a {@code Range} computed from the selection and
 * returns this wrapped in an optional, otherwise returns an empty optional.
 *
 * @param document currently active document
 * @param viewer   the text viewer for the completion
 * @return either an optional containing the text selection, or an empty
 *         optional, if there is no (non-empty) selection.
 */
private static Optional<Range> getRangeFromSelection(IDocument document, ITextViewer viewer) {
	if (!(viewer instanceof ITextViewerExtension9)) {
		return Optional.empty();
	}
	ITextViewerExtension9 textViewer = (ITextViewerExtension9) viewer;

	ITextSelection textSelection = textViewer.getLastKnownSelection();
	if (textSelection == null) {
		return Optional.empty();
	}
	int selectionLength = textSelection.getLength();
	if (selectionLength <= 0) {
		return Optional.empty();
	}

	try {
		int startOffset = textSelection.getOffset();
		Position startPosition = LSPEclipseUtils.toPosition(startOffset, document);
		int endOffset = startOffset + selectionLength;
		Position endPosition = LSPEclipseUtils.toPosition(endOffset, document);

		return Optional.of(new Range(startPosition, endPosition));
	} catch (BadLocationException e) {
		return Optional.empty();
	}
}
 
Example 18
Source File: PySelectionFromEditor.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
public static PySelection createPySelectionFromEditor(ISourceViewer viewer, ITextSelection textSelection) {
    return new PySelection(viewer.getDocument(), new CoreTextSelection(
            viewer.getDocument(), textSelection.getOffset(), textSelection.getLength()));
}
 
Example 19
Source File: PyEdit.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public ICoreTextSelection getTextSelection() {
    ITextSelection selection = (ITextSelection) this.getSelectionProvider().getSelection();
    return new CoreTextSelection(getDocument(), selection.getOffset(), selection.getLength());
}
 
Example 20
Source File: ExpressionUtil.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected boolean contains(ITextRegion textRegion, ITextSelection selection) {
	return textRegion.getOffset() <= selection.getOffset()
			&& textRegion.getOffset() + textRegion.getLength() >= selection.getOffset() + selection.getLength();
}