Java Code Examples for org.eclipse.jface.text.source.ISourceViewer#setSelectedRange()

The following examples show how to use org.eclipse.jface.text.source.ISourceViewer#setSelectedRange() . 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: XtextQuickAssistProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.3
 */
protected void selectAndRevealQuickfix(IQuickAssistInvocationContext invocationContext, Set<Annotation> applicableAnnotations, List<ICompletionProposal> completionProposals) {
       if (completionProposals.isEmpty()) {
       	return;
       }
	if (!(invocationContext instanceof QuickAssistInvocationContext && ((QuickAssistInvocationContext) invocationContext).isSuppressSelection())) {
		ISourceViewer sourceViewer = invocationContext.getSourceViewer();
		IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
		Iterator<Annotation> iterator = applicableAnnotations.iterator();
		while (iterator.hasNext()) {
			Position pos = annotationModel.getPosition(iterator.next());
			if (pos != null) {
				sourceViewer.setSelectedRange(pos.getOffset(), pos.getLength());
				sourceViewer.revealRange(pos.getOffset(), pos.getLength());
				break;
			}
		}
	}
}
 
Example 2
Source File: OutlineNodeElementOpener.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public void open(IOutlineNode node, ISourceViewer textViewer) {
	if (node != null) {
		ITextRegion textRegion = node.getSignificantTextRegion();
		if (textRegion != null && textRegion != ITextRegion.EMPTY_REGION) {
			int offset = textRegion.getOffset();
			int length = textRegion.getLength();
			textViewer.setRangeIndication(offset, length, true);
			textViewer.revealRange(offset, length);
			textViewer.setSelectedRange(offset, length);
		} else {
			node.tryReadOnly(new IUnitOfWork.Void<EObject>() {
				@Override
				public void process(EObject state) throws Exception {
					openEObject(state);
				}
			});
		}
		
	}
}
 
Example 3
Source File: RenameLinkedMode.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public boolean start(IRenameElementContext renameElementContext, Provider<LinkedPositionGroup> provider, IProgressMonitor monitor) {
	if (renameElementContext == null)
		throw new IllegalArgumentException("RenameElementContext is null");
	this.linkedPositionGroup = provider.get();
	if (linkedPositionGroup == null || linkedPositionGroup.isEmpty())
		return false;
	this.editor = (XtextEditor) renameElementContext.getTriggeringEditor();
	this.focusEditingSupport = new FocusEditingSupport();
	ISourceViewer viewer = editor.getInternalSourceViewer();
	IDocument document = viewer.getDocument();
	originalSelection = viewer.getSelectedRange();
	currentPosition = linkedPositionGroup.getPositions()[0];
	originalName = getCurrentName();
	try {
		linkedModeModel = new LinkedModeModel();
		linkedModeModel.addGroup(linkedPositionGroup);
		linkedModeModel.forceInstall();
		linkedModeModel.addLinkingListener(new EditorSynchronizer());
		LinkedModeUI ui = new EditorLinkedModeUI(linkedModeModel, viewer);
		ui.setExitPolicy(new ExitPolicy(document));
		if (currentPosition.includes(originalSelection.x))
			ui.setExitPosition(viewer, originalSelection.x, 0, Integer.MAX_VALUE);
		ui.enter();
		if (currentPosition.includes(originalSelection.x)
				&& currentPosition.includes(originalSelection.x + originalSelection.y))
			viewer.setSelectedRange(originalSelection.x, originalSelection.y);
		if (viewer instanceof IEditingSupportRegistry) {
			IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer;
			registry.register(focusEditingSupport);
		}
		openPopup();
		return true;
	} catch (BadLocationException e) {
		throw new WrappedException(e);
	}
}
 
Example 4
Source File: AbstractEditorDoubleClickTextSelectionTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected XtextEditor doubleClick(XtextEditor xtextEditor, int cursorPosition) {
	ISourceViewer viewer = xtextEditor.getInternalSourceViewer();

	// Set the cursor position
	viewer.setSelectedRange(cursorPosition, 0);

	// Fire a mouse down event with the left mouse button
	Event event = new Event();
	event.button = 1;
	viewer.getTextWidget().notifyListeners(SWT.MouseDown, event);

	return xtextEditor;
}
 
Example 5
Source File: PasteJavaCodeHandler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
void doFormat(ISourceViewer sourceViewer, final String xtendCode, Point selection) {
	int offset = selection.x;
	int length = xtendCode.length();
	if (offset - 1 >= 0) {
		offset--;
		length++;
	}
	sourceViewer.setSelectedRange(offset, length);
	sourceViewer.getTextOperationTarget().doOperation(ISourceViewer.FORMAT);
	int restoreCaretAtOffset = sourceViewer.getSelectedRange().x + sourceViewer.getSelectedRange().y;
	sourceViewer.setSelectedRange(restoreCaretAtOffset, 0);
}
 
Example 6
Source File: IndentAction.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Selects the given range on the editor.
 * 
 * @param newOffset
 *            the selection offset
 * @param newLength
 *            the selection range
 */
private void selectAndReveal(int newOffset, int newLength) {
	Assert.isTrue(newOffset >= 0);
	Assert.isTrue(newLength >= 0);
	ITextEditor editor = getTextEditor();
	if (editor instanceof TypeScriptEditor) {
		ISourceViewer viewer = ((TypeScriptEditor) editor).getViewer();
		if (viewer != null)
			viewer.setSelectedRange(newOffset, newLength);
	} else
		// this is too intrusive, but will never get called anyway
		getTextEditor().selectAndReveal(newOffset, newLength);

}
 
Example 7
Source File: SearchMinibuffer.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
protected void leave(int offset, int len, boolean isWidget) {
	addToHistory();
	ISourceViewer viewer = getViewer();
	if (viewer != null) {
		int off = (isWidget ? MarkUtils.widget2ModelOffset(getViewer(), offset) : offset);
		viewer.setSelectedRange(off, len);
		viewer.revealRange(off,0);
	}
	super.leave(true);
}
 
Example 8
Source File: IndentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Selects the given range on the editor.
 *
 * @param newOffset the selection offset
 * @param newLength the selection range
 */
private void selectAndReveal(int newOffset, int newLength) {
	Assert.isTrue(newOffset >= 0);
	Assert.isTrue(newLength >= 0);
	ITextEditor editor= getTextEditor();
	if (editor instanceof JavaEditor) {
		ISourceViewer viewer= ((JavaEditor)editor).getViewer();
		if (viewer != null)
			viewer.setSelectedRange(newOffset, newLength);
	} else
		// this is too intrusive, but will never get called anyway
		getTextEditor().selectAndReveal(newOffset, newLength);

}
 
Example 9
Source File: SelectAllOccurrencesHandler.java    From eclipse-multicursor with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Mostly based on code from {@link org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedNamesAssistProposal}
 */
private void startEditing(ISourceViewer viewer) throws ExecutionException {
	Point selOffsetAndLen = viewer.getSelectedRange();
	int selStart = CoordinatesUtil.fromOffsetAndLengthToStartAndEnd(selOffsetAndLen).x;

	IDocument document = viewer.getDocument();
	try {
		String selectedText;
		if (selOffsetAndLen.y == 0) { // no characters selected
			String documentText = document.get();
			Point wordOffsetAndLen = TextUtil.findWordSurrounding(documentText, selStart);
			if (wordOffsetAndLen != null) {
				selectedText = document.get(wordOffsetAndLen.x, wordOffsetAndLen.y);
			} else {
				IRegion selectedLine = document.getLineInformationOfOffset(selStart);
				selectedText = document.get(selectedLine.getOffset(), selectedLine.getLength());
			}
		} else {
			selectedText = document.get(selOffsetAndLen.x, selOffsetAndLen.y);
		}

		LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup();

		FindReplaceDocumentAdapter findReplaceAdaptor = new FindReplaceDocumentAdapter(document);
		IRegion matchingRegion = findReplaceAdaptor.find(0, selectedText, true, true, false, false);
		while (matchingRegion != null) {
			linkedPositionGroup.addPosition(new LinkedPosition(document, matchingRegion.getOffset(), matchingRegion
					.getLength()));

			matchingRegion = findReplaceAdaptor.find(matchingRegion.getOffset() + matchingRegion.getLength(),
					selectedText, true, true, false, false);
		}

		LinkedModeModel model = new LinkedModeModel();
		model.addGroup(linkedPositionGroup);
		model.forceInstall();

		LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
		ui.setExitPolicy(new DeleteBlockingExitPolicy(document));
		ui.enter();

		// by default the text being edited is selected so restore original selection
		viewer.setSelectedRange(selOffsetAndLen.x, selOffsetAndLen.y);
	} catch (BadLocationException e) {
		throw new ExecutionException("Editing failed", e);
	}
}
 
Example 10
Source File: BaseEditor.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * implementation copied from org.eclipse.ui.externaltools.internal.ant.editor.PlantyEditor#setSelection
 */
public void setSelection(int offset, int length) {
    ISourceViewer sourceViewer = getSourceViewer();
    sourceViewer.setSelectedRange(offset, length);
    sourceViewer.revealRange(offset, length);
}
 
Example 11
Source File: SearchReplaceMinibuffer.java    From e4macs with Eclipse Public License 1.0 4 votes vote down vote up
private void setSelection(int off) {
	ISourceViewer viewer = getViewer();
	viewer.setSelectedRange(MarkUtils.widget2ModelOffset(viewer, off), 0);
}
 
Example 12
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Jumps to the matching bracket.
 */
public void gotoMatchingBracket() {

	ISourceViewer sourceViewer= getSourceViewer();
	IDocument document= sourceViewer.getDocument();
	if (document == null)
		return;

	IRegion selection= getSignedSelection(sourceViewer);
	if (fPreviousSelections == null)
		initializePreviousSelectionList();

	IRegion region= fBracketMatcher.match(document, selection.getOffset(), selection.getLength());
	if (region == null) {
		region= fBracketMatcher.findEnclosingPeerCharacters(document, selection.getOffset(), selection.getLength());
		initializePreviousSelectionList();
		fPreviousSelections.add(selection);
	} else {
		if (fPreviousSelections.size() == 2) {
			if (!selection.equals(fPreviousSelections.get(1))) {
				initializePreviousSelectionList();
			}
		} else if (fPreviousSelections.size() == 3) {
			if (selection.equals(fPreviousSelections.get(2)) && !selection.equals(fPreviousSelections.get(0))) {
				IRegion originalSelection= fPreviousSelections.get(0);
				sourceViewer.setSelectedRange(originalSelection.getOffset(), originalSelection.getLength());
				sourceViewer.revealRange(originalSelection.getOffset(), originalSelection.getLength());
				initializePreviousSelectionList();
				return;
			}
			initializePreviousSelectionList();
		}
	}

	if (region == null) {
		setStatusLineErrorMessage(JavaEditorMessages.GotoMatchingBracket_error_noMatchingBracket);
		sourceViewer.getTextWidget().getDisplay().beep();
		return;
	}

	int offset= region.getOffset();
	int length= region.getLength();

	if (length < 1)
		return;

	int anchor= fBracketMatcher.getAnchor();
	// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
	int targetOffset= (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1 : offset + length - 1;

	boolean visible= false;
	if (sourceViewer instanceof ITextViewerExtension5) {
		ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
		visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
	} else {
		IRegion visibleRegion= sourceViewer.getVisibleRegion();
		// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
		visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
	}

	if (!visible) {
		setStatusLineErrorMessage(JavaEditorMessages.GotoMatchingBracket_error_bracketOutsideSelectedElement);
		sourceViewer.getTextWidget().getDisplay().beep();
		return;
	}

	int adjustment= getOffsetAdjustment(document, selection.getOffset() + selection.getLength(), selection.getLength());
	targetOffset+= adjustment;
	int direction= (selection.getLength() == 0) ? 0 : ((selection.getLength() > 0) ? 1 : -1);
	if (fPreviousSelections.size() == 1 && direction < 0) {
		targetOffset++;
	}

	if (fPreviousSelections.size() > 0) {
		fPreviousSelections.add(new Region(targetOffset, direction));
	}
	sourceViewer.setSelectedRange(targetOffset, direction);
	sourceViewer.revealRange(targetOffset, direction);
}
 
Example 13
Source File: RenameLinkedMode.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void start() {
		if (getActiveLinkedMode() != null) {
			// for safety; should already be handled in RenameJavaElementAction
			fgActiveLinkedMode.startFullDialog();
			return;
		}

		ISourceViewer viewer= fEditor.getViewer();
		IDocument document= viewer.getDocument();
		fOriginalSelection= viewer.getSelectedRange();
		int offset= fOriginalSelection.x;

		try {
			CompilationUnit root= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

			fLinkedPositionGroup= new LinkedPositionGroup();
			ASTNode selectedNode= NodeFinder.perform(root, fOriginalSelection.x, fOriginalSelection.y);
			if (! (selectedNode instanceof SimpleName)) {
				return; // TODO: show dialog
			}
			SimpleName nameNode= (SimpleName) selectedNode;

			if (viewer instanceof ITextViewerExtension6) {
				IUndoManager undoManager= ((ITextViewerExtension6)viewer).getUndoManager();
				if (undoManager instanceof IUndoManagerExtension) {
					IUndoManagerExtension undoManagerExtension= (IUndoManagerExtension)undoManager;
					IUndoContext undoContext= undoManagerExtension.getUndoContext();
					IOperationHistory operationHistory= OperationHistoryFactory.getOperationHistory();
					fStartingUndoOperation= operationHistory.getUndoOperation(undoContext);
				}
			}
			
			fOriginalName= nameNode.getIdentifier();
			final int pos= nameNode.getStartPosition();
			ASTNode[] sameNodes= LinkedNodeFinder.findByNode(root, nameNode);

			//TODO: copied from LinkedNamesAssistProposal#apply(..):
			// sort for iteration order, starting with the node @ offset
			Arrays.sort(sameNodes, new Comparator<ASTNode>() {
				public int compare(ASTNode o1, ASTNode o2) {
					return rank(o1) - rank(o2);
				}
				/**
				 * Returns the absolute rank of an <code>ASTNode</code>. Nodes
				 * preceding <code>pos</code> are ranked last.
				 *
				 * @param node the node to compute the rank for
				 * @return the rank of the node with respect to the invocation offset
				 */
				private int rank(ASTNode node) {
					int relativeRank= node.getStartPosition() + node.getLength() - pos;
					if (relativeRank < 0)
						return Integer.MAX_VALUE + relativeRank;
					else
						return relativeRank;
				}
			});
			for (int i= 0; i < sameNodes.length; i++) {
				ASTNode elem= sameNodes[i];
				LinkedPosition linkedPosition= new LinkedPosition(document, elem.getStartPosition(), elem.getLength(), i);
				if (i == 0)
					fNamePosition= linkedPosition;
				fLinkedPositionGroup.addPosition(linkedPosition);
			}

			fLinkedModeModel= new LinkedModeModel();
			fLinkedModeModel.addGroup(fLinkedPositionGroup);
			fLinkedModeModel.forceInstall();
			fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor));
			fLinkedModeModel.addLinkingListener(new EditorSynchronizer());

			LinkedModeUI ui= new EditorLinkedModeUI(fLinkedModeModel, viewer);
			ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE);
			ui.setExitPolicy(new ExitPolicy(document));
			ui.enter();

			viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection

			if (viewer instanceof IEditingSupportRegistry) {
				IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
				registry.register(fFocusEditingSupport);
			}

			openSecondaryPopup();
//			startAnimation();
			fgActiveLinkedMode= this;

		} catch (BadLocationException e) {
			JavaPlugin.log(e);
		}
	}
 
Example 14
Source File: RenameLinkedMode.java    From typescript.java with MIT License 4 votes vote down vote up
public void start() {
	if (getActiveLinkedMode() != null) {
		// for safety; should already be handled in RenameJavaElementAction
		fgActiveLinkedMode.startFullDialog();
		return;
	}

	ISourceViewer viewer = fEditor.getViewer();
	IDocument document = viewer.getDocument();

	ITypeScriptFile tsFile = fEditor.getTypeScriptFile();
	tsFile.setDisableChanged(true);
	fOriginalSelection = viewer.getSelectedRange();
	int offset = fOriginalSelection.x;

	try {
		fLinkedPositionGroup = new LinkedPositionGroup();
		if (viewer instanceof ITextViewerExtension6) {
			IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager();
			if (undoManager instanceof IUndoManagerExtension) {
				IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager;
				IUndoContext undoContext = undoManagerExtension.getUndoContext();
				IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory();
				fStartingUndoOperation = operationHistory.getUndoOperation(undoContext);
			}
		}

		// Find occurrences
		List<OccurrencesResponseItem> occurrences = tsFile.occurrences(offset).get(1000, TimeUnit.MILLISECONDS);

		// Create Eclipse linked position from the occurrences list.
		int start, length;
		for (int i = 0; i < occurrences.size(); i++) {
			OccurrencesResponseItem item = occurrences.get(i);
			start = tsFile.getPosition(item.getStart());
			length = tsFile.getPosition(item.getEnd()) - start;
			LinkedPosition linkedPosition = new LinkedPosition(document, start, length, i);
			if (i == 0) {
				fOriginalName = document.get(start, length);
				fNamePosition = linkedPosition;
			}
			fLinkedPositionGroup.addPosition(linkedPosition);
		}

		fLinkedModeModel = new LinkedModeModel();
		fLinkedModeModel.addGroup(fLinkedPositionGroup);
		fLinkedModeModel.forceInstall();
		fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor));
		fLinkedModeModel.addLinkingListener(new EditorSynchronizer());

		LinkedModeUI ui = new EditorLinkedModeUI(fLinkedModeModel, viewer);
		ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE);
		ui.setExitPolicy(new ExitPolicy(document));
		ui.enter();

		viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); // by
																				// default,
																				// full
																				// word
																				// is
																				// selected;
																				// restore
																				// original
																				// selection

		if (viewer instanceof IEditingSupportRegistry) {
			IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer;
			registry.register(fFocusEditingSupport);
		}

		openSecondaryPopup();
		// startAnimation();
		fgActiveLinkedMode = this;

	} catch (Exception e) {
		JSDTTypeScriptUIPlugin.log(e);
	}
}
 
Example 15
Source File: JavaScriptLightWeightEditor.java    From typescript.java with MIT License 4 votes vote down vote up
/**
 * Jumps to the matching bracket.
 */
public void gotoMatchingBracket() {

	ISourceViewer sourceViewer = getSourceViewer();
	IDocument document = sourceViewer.getDocument();
	if (document == null)
		return;

	IRegion selection = getSignedSelection(sourceViewer);

	int selectionLength = Math.abs(selection.getLength());
	if (selectionLength > 1) {
		setStatusLineErrorMessage(JSDTTypeScriptUIMessages.GotoMatchingBracket_error_invalidSelection);
		sourceViewer.getTextWidget().getDisplay().beep();
		return;
	}

	// #26314
	int sourceCaretOffset = selection.getOffset() + selection.getLength();
	if (isSurroundedByBrackets(document, sourceCaretOffset))
		sourceCaretOffset -= selection.getLength();

	IRegion region = fBracketMatcher.match(document, sourceCaretOffset);
	if (region == null) {
		setStatusLineErrorMessage(JSDTTypeScriptUIMessages.GotoMatchingBracket_error_noMatchingBracket);
		sourceViewer.getTextWidget().getDisplay().beep();
		return;
	}

	int offset = region.getOffset();
	int length = region.getLength();

	if (length < 1)
		return;

	int anchor = fBracketMatcher.getAnchor();
	// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
	int targetOffset = (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1 : offset + length;

	boolean visible = false;
	if (sourceViewer instanceof ITextViewerExtension5) {
		ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
		visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
	} else {
		IRegion visibleRegion = sourceViewer.getVisibleRegion();
		// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
		visible = (targetOffset >= visibleRegion.getOffset()
				&& targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
	}

	if (!visible) {
		setStatusLineErrorMessage(JSDTTypeScriptUIMessages.GotoMatchingBracket_error_bracketOutsideSelectedElement);
		sourceViewer.getTextWidget().getDisplay().beep();
		return;
	}

	if (selection.getLength() < 0)
		targetOffset -= selection.getLength();

	sourceViewer.setSelectedRange(targetOffset, selection.getLength());
	sourceViewer.revealRange(targetOffset, selection.getLength());
}
 
Example 16
Source File: TypeScriptEditor.java    From typescript.java with MIT License 4 votes vote down vote up
/**
 * Highlights and moves to a corresponding element in editor
 * 
 * @param reference
 *            corresponding entity in editor
 * @param moveCursor
 *            if true, moves cursor to the reference
 */
private void setSelection(NavigationBarItem reference, boolean moveCursor) {
	if (reference == null) {
		return;
	}

	if (moveCursor) {
		markInNavigationHistory();
	}

	ISourceViewer sourceViewer = getSourceViewer();
	if (sourceViewer == null) {
		return;
	}
	StyledText textWidget = sourceViewer.getTextWidget();
	if (textWidget == null) {
		return;
	}
	try {
		Location start = reference.getSpans().get(0).getStart();
		Location end = reference.getSpans().get(0).getEnd();

		if (start == null || end == null)
			return;

		ITypeScriptFile tsFile = getTypeScriptFile();

		int offset = tsFile.getPosition(start);
		int length = tsFile.getPosition(end) - offset;

		if (offset < 0 || length < 0 || length > sourceViewer.getDocument().getLength()) {
			return;
		}
		textWidget.setRedraw(false);

		// Uncomment that if we wish to select only variable and not the
		// whole block.
		// but there is a bug with this code with
		// private a: string. it's the first 'a' (of private) which is
		// selected and not the second.
		// String documentPart = sourceViewer.getDocument().get(offset,
		// length);
		//
		// // Try to find name because position returns for whole block
		// String name = reference.getText();
		// if (name != null) {
		// int nameoffset = documentPart.indexOf(name);
		// if (nameoffset != -1) {
		// offset += nameoffset;
		// length = name.length();
		// }
		// }
		if (length > 0) {
			setHighlightRange(offset, length, moveCursor);
		}

		if (!moveCursor) {
			return;
		}

		if (offset > -1 && length > 0) {
			sourceViewer.revealRange(offset, length);
			// Selected region begins one index after offset
			sourceViewer.setSelectedRange(offset, length);
			markInNavigationHistory();
		}
	} catch (Exception e) {

	} finally {
		textWidget.setRedraw(true);
	}
}
 
Example 17
Source File: GoToMatchingBracketAction.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
public void run(IAction action) {
    if (targetEditor == null) return;
    ISourceViewer sourceViewer= targetEditor.getViewer();
    IDocument document= sourceViewer.getDocument();
    if (document == null)
        return;
    ITextSelection selection = (ITextSelection) targetEditor.getSelectionProvider().getSelection();
    SubStatusLineManager slm = 
        (SubStatusLineManager) targetEditor.getEditorSite().getActionBars().getStatusLineManager();
    
    int selectionLength= Math.abs(selection.getLength());
    if (selectionLength > 1) {
        slm.setErrorMessage(TexlipsePlugin.getResourceString("gotoMatchingBracketNotSelected"));
        slm.setVisible(true);
        sourceViewer.getTextWidget().getDisplay().beep();
        return;
    }
    
    int sourceCaretOffset= selection.getOffset() + selection.getLength();

    TexPairMatcher fBracketMatcher = new TexPairMatcher("{}[]()");
    
    IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
    if (region == null) {
        slm.setErrorMessage(TexlipsePlugin.getResourceString("gotoMatchingBracketNotFound"));
        slm.setVisible(true);            
        sourceViewer.getTextWidget().getDisplay().beep();
        return;
    }

    int offset= region.getOffset();
    int length= region.getLength();

    if (length < 1) return;

    int anchor = fBracketMatcher.getAnchor();
    int targetOffset= (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;

    if (selection.getLength() < 0)
        targetOffset -= selection.getLength();

    sourceViewer.setSelectedRange(targetOffset, selection.getLength());
    sourceViewer.revealRange(targetOffset, selection.getLength());
}