org.eclipse.jface.text.ITextSelection#getOffset ( )源码实例Demo

下面列出了org.eclipse.jface.text.ITextSelection#getOffset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Pydev   文件: ScopeSelectionAction.java
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;
        }
    }
}
 
源代码2 项目: e4macs   文件: RegionWidenHandler.java
/**
 * @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();
}
 
源代码3 项目: e4macs   文件: YankPopHandler.java
/**
 * 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();
}
 
@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();
	}
}
 
源代码5 项目: e4macs   文件: TransposeSexpHandler.java
/**
 * 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);
}
 
源代码6 项目: e4macs   文件: SearchMinibuffer.java
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);
	}
}
 
源代码7 项目: corrosion   文件: SnippetContentAssistProcessor.java
/**
 * 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();
	}
}
 
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);
}
 
源代码9 项目: e4macs   文件: SexpHandler.java
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;
}
 
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());
	}
}
 
源代码11 项目: gama   文件: GamlEditor.java
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);
}
 
/**
 * 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;
}
 
源代码13 项目: xds-ide   文件: SelectionUtils.java
/**
 * 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;
}
 
源代码14 项目: e4macs   文件: RegisterNumberHandler.java
/**
 * @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;
}
 
@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();

}
 
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;
	}
}
 
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;
}
 
源代码18 项目: Pydev   文件: PySelectionFromEditor.java
public static PySelection createPySelectionFromEditor(ISourceViewer viewer, ITextSelection textSelection) {
    return new PySelection(viewer.getDocument(), new CoreTextSelection(
            viewer.getDocument(), textSelection.getOffset(), textSelection.getLength()));
}
 
源代码19 项目: Pydev   文件: PyEdit.java
@Override
public ICoreTextSelection getTextSelection() {
    ITextSelection selection = (ITextSelection) this.getSelectionProvider().getSelection();
    return new CoreTextSelection(getDocument(), selection.getOffset(), selection.getLength());
}
 
源代码20 项目: xtext-eclipse   文件: ExpressionUtil.java
protected boolean contains(ITextRegion textRegion, ITextSelection selection) {
	return textRegion.getOffset() <= selection.getOffset()
			&& textRegion.getOffset() + textRegion.getLength() >= selection.getOffset() + selection.getLength();
}