org.eclipse.jface.text.ITextSelection Java Examples

The following examples show how to use org.eclipse.jface.text.ITextSelection. 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: TypeScriptEditor.java    From typescript.java with 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 #2
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 #3
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 #4
Source File: InferTypeArgumentsAction.java    From Eclipse-Postfix-Code-Completion with 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 #5
Source File: SearchExecuteMinibuffer.java    From e4macs with 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 #6
Source File: AddBlockCommentAction.java    From Eclipse-Postfix-Code-Completion with 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 #7
Source File: AppendCommentHandler.java    From e4macs with 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 #8
Source File: MoveAction.java    From Eclipse-Postfix-Code-Completion with 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 #9
Source File: TagsSearchHandler.java    From e4macs with 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 #10
Source File: BlockHandler.java    From e4macs with 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 #11
Source File: ToggleCommentAction.java    From goclipse with 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 #12
Source File: XtendRenameContextFactory.java    From xtext-xtend with 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 #13
Source File: KbdMacroLoadHandler.java    From e4macs with 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 #14
Source File: TextViewerMoveLinesAction.java    From xtext-eclipse with 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 #15
Source File: InlineMethodAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(ITextSelection selection) {
	ITypeRoot typeRoot= SelectionConverter.getInput(fEditor);
	if (typeRoot == null)
		return;
	if (! JavaElementUtil.isSourceAvailable(typeRoot))
		return;
	run(selection.getOffset(), selection.getLength(), typeRoot);
}
 
Example #16
Source File: TLAProofFoldingStructureProvider.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * Runs the fold operation represented by commandId. This
 * should be an id from {@link IProofFoldCommandIds}.
 * 
 * Does nothing if currently computing the folds
 * from a parse result.
 * 
 * @param commandId
 * @param the current selection in the editor
 */
public void runFoldOperation(String commandId, ITextSelection selection)
{
    if (canPerformFoldingCommands)
    {
        /*
         * Allow commands to run even if a range of text
         * is selected (highlighted). We treat end of the selection
         * (indexed by offset+length) as the location of the caret
         * for the command. This means that for commands that act
         * on specific steps, the step on which the command acts is determined
         * by the position of selection.getOffset()+selection.getLength().
         */
        if (selection != null)
        {
            int caretOffset = selection.getOffset() + selection.getLength();
            if (commandId.equals(IProofFoldCommandIds.FOCUS_ON_STEP))
            {
                foldEverythingUnusable(caretOffset);
            } else if (commandId.equals(IProofFoldCommandIds.FOLD_ALL_PROOFS))
            {
                foldAllProofs();
            } else if (commandId.equals(IProofFoldCommandIds.EXPAND_ALL_PROOFS))
            {
                expandAllProofs();
            } else if (commandId.equals(IProofFoldCommandIds.EXPAND_SUBTREE))
            {
                expandCurrentSubtree(caretOffset);
            } else if (commandId.equals(IProofFoldCommandIds.COLLAPSE_SUBTREE))
            {
                hideCurrentSubtree(caretOffset);
            } else if (commandId.equals(IProofFoldCommandIds.SHOW_IMMEDIATE))
            {
                showImmediateDescendants(caretOffset);
            }
        }
    }
}
 
Example #17
Source File: NewLineIndentHandler.java    From e4macs with 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 {
	int result = NO_OFFSET; 
	Control c = MarkUtils.getTextWidget(editor);
	if (c instanceof StyledText) {
		StyledText st = (StyledText)c;
		String ld = st.getLineDelimiter();
		int insertionOffset = getCursorOffset(editor,currentSelection);
		int widgetInsertionOffset = st.getCaretOffset();
		
		// the offset position will be updated by the internals on insertion/indent
		Position caret= new Position(insertionOffset, 0);
		document.addPosition(caret);
		
		st.setSelectionRange(widgetInsertionOffset, 0);
		// operate directly on the widget
		st.replaceTextRange(widgetInsertionOffset, 0, ld);
		document.removePosition(caret);
		
		if (st.getSelection().x == widgetInsertionOffset) {
			// move cursor by the amount detected
			result = getCursorOffset(editor) + caret.offset - insertionOffset;
		} 
	}
	return result;
}
 
Example #18
Source File: HTMLEditor.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void selectionChanged()
{
	super.selectionChanged();

	ISelection selection = getSelectionProvider().getSelection();
	if (selection.isEmpty())
	{
		return;
	}
	ITextSelection textSelection = (ITextSelection) selection;
	int offset = textSelection.getOffset();
	highlightTagPair(offset);
}
 
Example #19
Source File: IRenameContextFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected IRenameElementContext createLocalRenameElementContext(EObject targetElement, XtextEditor editor,
		ITextSelection selection, XtextResource resource) {
	final URI targetElementURI = EcoreUtil2.getPlatformResourceOrNormalizedURI(targetElement);
	IRenameElementContext.Impl renameElementContext = new IRenameElementContext.Impl(targetElementURI,
			targetElement.eClass(), editor, selection, resource.getURI());
	return renameElementContext;
}
 
Example #20
Source File: ExtractClassAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(ITextSelection selection) {
	try {
		if (!ActionUtil.isEditable(fEditor))
			return;
		IType type= RefactoringActions.getEnclosingOrPrimaryType(fEditor);
		if (RefactoringAvailabilityTester.isExtractClassAvailable(type)) {
			RefactoringExecutionStarter.startExtractClassRefactoring(type, getShell());
		}
	} catch (CoreException e) {
		ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
	}
}
 
Example #21
Source File: MoveAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean tryMoveInstanceMethod(ITextSelection selection) throws JavaModelException {
	IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
	if (element == null || !(element instanceof IMethod))
		return false;

	IMethod method= (IMethod) element;
	if (!RefactoringAvailabilityTester.isMoveMethodAvailable(method))
		return false;
	fMoveInstanceMethodAction.run(selection);
	return true;
}
 
Example #22
Source File: TextViewerDeleteLineAction.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void run() {

	if (fTarget == null)
		return;

	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;

	try {
		fTarget.deleteLine(document, selection, fType, fCopyToClipboard);
	} catch (BadLocationException e) {
		// should not happen
	}
}
 
Example #23
Source File: ShowChildrenOnlyHandler.java    From tlaplus with 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.SHOW_IMMEDIATE,
                    (ITextSelection) editor.getSelectionProvider().getSelection()));
        }
    }
}
 
Example #24
Source File: BrowseKillRingHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Insert text from kill ring entry into the most recently activated text editor
 * 
 * @param text - the text from the kill ring entry
 */
//	@SuppressWarnings("restriction")	// for cast to internal org.eclipse.ui.internal.WorkbenchWindow
private void insertFromBrowseRing(String text) {
	// insert into most recently active editor
	IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	RecentEditor recent = getRecentEditor();
	// use widget to avoid unpleasant scrolling side effects of IRewriteTarget		
	Control widget = MarkUtils.getTextWidget(recent.editor);
	if (recent.editor != null) {
		try {
			// cache for ancillary computations
			setThisEditor(recent.editor);
			// reduce the amount of unnecessary work
			if (window instanceof WorkbenchWindow) {
				((WorkbenchWindow) window).largeUpdateStart();
			}
			widget.setRedraw(false);
			recent.page.activate(recent.epart);
			insertText(recent.editor.getDocumentProvider().getDocument(recent.editor.getEditorInput()),
					(ITextSelection)recent.editor.getSelectionProvider().getSelection(), text);
		} catch (Exception e) {
		} finally {
			widget.setRedraw(true);
			setThisEditor(null);
			if (window instanceof WorkbenchWindow) {
				((WorkbenchWindow) window).largeUpdateEnd();
			}
		}
	} else {
		beep();
	}
}
 
Example #25
Source File: SourceActionDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getElementAfterCursorPosition(CompilationUnitEditor editor, IJavaElement[] members) throws JavaModelException {
	if (editor == null) {
		return -1;
	}
	int offset= ((ITextSelection) editor.getSelectionProvider().getSelection()).getOffset();

	for (int i= 0; i < members.length; i++) {
		IMember curr= (IMember) members[i];
		ISourceRange range= curr.getSourceRange();
		if (offset < range.getOffset()) {
			return i;
		}
	}
	return members.length;
}
 
Example #26
Source File: XMLEditor.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void selectionChanged()
{
	super.selectionChanged();

	ISelection selection = getSelectionProvider().getSelection();
	if (selection.isEmpty())
	{
		return;
	}
	ITextSelection textSelection = (ITextSelection) selection;
	int offset = textSelection.getOffset();
	highlightTagPair(offset);
}
 
Example #27
Source File: OccurrenceMarker.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IStatus run(IProgressMonitor monitor) {
	final XtextEditor editor = initialEditor;
	final boolean isMarkOccurrences = initialIsMarkOccurrences;
	final ITextSelection selection = initialSelection;
	final SubMonitor progress = SubMonitor.convert(monitor, 2);
	if (!progress.isCanceled()) {
		final Map<Annotation, Position> annotations = (isMarkOccurrences) ? occurrenceComputer.createAnnotationMap(editor, selection,
				progress.newChild(1)) : Collections.<Annotation, Position>emptyMap();
		if (!progress.isCanceled()) {
			Display.getDefault().asyncExec(new Runnable() {
				@Override
				public void run() {
					if (!progress.isCanceled()) {
						final IAnnotationModel annotationModel = getAnnotationModel(editor);
						if (annotationModel instanceof IAnnotationModelExtension)
							((IAnnotationModelExtension) annotationModel).replaceAnnotations(
									getExistingOccurrenceAnnotations(annotationModel), annotations);
						else if(annotationModel != null)
							throw new IllegalStateException(
									"AnnotationModel does not implement IAnnotationModelExtension");  //$NON-NLS-1$
					}
				}
			});
			return Status.OK_STATUS;
		}
	}
	return Status.CANCEL_STATUS;
}
 
Example #28
Source File: OccurrenceMarker.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void doMarkOccurrences(final ISelection selection) {
	if (selection instanceof ITextSelection) {
		XtextEditor editor = this.editor;
		if (editor != null) {
			markOccurrenceJob.cancel();
			markOccurrenceJob.initialize(editor, (ITextSelection) selection, isMarkOccurrences);
			if (!markOccurrenceJob.isSystem())
				markOccurrenceJob.setSystem(true);
			markOccurrenceJob.setPriority(Job.DECORATE);
			markOccurrenceJob.schedule();
		}
	}
}
 
Example #29
Source File: EditorAPITextPositionTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCalculateOffsetsEmptySelection() {
  int startLine = 7;
  int endLine = 7;
  TextSelection textSelection = selection(startLine, 5, endLine, 5);

  ITextEditor editor = new ITextEditorBuilder().withLineOffsetLookupAnswer(startLine, 23).build();

  ITextSelection expectedOffsets = offsets(28, 28);

  ITextSelection calculatedOffsets = EditorAPI.calculateOffsets(editor, textSelection);

  assertEquals(expectedOffsets, calculatedOffsets);
}
 
Example #30
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void updateStatusLine() {
	ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
	Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
	String message= null;
	if (annotation != null) {
		updateMarkerViews(annotation);
		if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem() || isProblemMarkerAnnotation(annotation))
			message= annotation.getText();
	}
	setStatusLineErrorMessage(null);
	setStatusLineMessage(message);
}