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

The following examples show how to use org.eclipse.jface.text.ITextSelection#getLength() . 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: RegionNarrowHandler.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 {

	if (editor != null) {
		// if nothing is selected, beep()
		if (currentSelection.getLength() == 0) {
			beep();
		} else {
			// narrow to selection
			editor.resetHighlightRange();
			editor.showHighlightRangeOnly(true);
			editor.setHighlightRange(currentSelection.getOffset(), currentSelection.getLength(), true);
			// Remember region to support narrow/widen in the face of Eclipse's bad behavior on activation:
			// org.eclipse.jdt.internal.ui.javaeditor.BasicJavaEditorActionContributor.setActiveEditor
			BufferLocal.getInstance().set(editor, BufferLocal.NARROW_REGION, editor.getHighlightRange());
			MarkUtils.setSelection(editor, getCursorOffset(editor), 0);
		}
	}
	return super.transform(editor, document, currentSelection, event);
}
 
Example 2
Source File: ToggleCommentAction.java    From tlaplus with MIT License 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
 */
private 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
        // TODO
    }

    return null;
}
 
Example 3
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 4
Source File: RefactorActionGroup.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void refactorMenuShown(IMenuManager refactorSubmenu) {
	// we know that we have an MenuManager since we created it in
	// addRefactorSubmenu.
	Menu menu= ((MenuManager)refactorSubmenu).getMenu();
	menu.addMenuListener(new MenuAdapter() {
		@Override
		public void menuHidden(MenuEvent e) {
			refactorMenuHidden();
		}
	});
	ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection();
	JavaTextSelection javaSelection= new JavaTextSelection(getEditorInput(), getDocument(), textSelection.getOffset(), textSelection.getLength());

	for (Iterator<SelectionDispatchAction> iter= fActions.iterator(); iter.hasNext(); ) {
		SelectionDispatchAction action= iter.next();
		action.update(javaSelection);
	}
	refactorSubmenu.removeAll();
	if (fillRefactorMenu(refactorSubmenu) == 0)
		refactorSubmenu.add(fNoActionAvailable);
}
 
Example 5
Source File: JsniParser.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public static ITypedRegion getEnclosingJsniRegion(ITextSelection selection,
    IDocument document) {
  try {
    ITypedRegion region = TextUtilities.getPartition(document,
        GWTPartitions.GWT_PARTITIONING, selection.getOffset(), false);

    if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
      int regionEnd = region.getOffset() + region.getLength();
      int selectionEnd = selection.getOffset() + selection.getLength();

      // JSNI region should entirely contain the selection
      if (region.getOffset() <= selection.getOffset()
          && regionEnd >= selectionEnd) {
        return region;
      }
    }
  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
  }

  return null;
}
 
Example 6
Source File: IndentAction.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Returns if the current selection is valid, i.e. whether it is empty and
 * the caret in the whitespace at the start of a line, or covers multiple
 * lines.
 * 
 * @return <code>true</code> if the selection is valid for an indent
 *         operation
 */
private boolean isValidSelection() {
	ITextSelection selection = getSelection();
	if (selection.isEmpty())
		return false;

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

	IDocument document = getDocument();
	if (document == null)
		return false;

	try {
		IRegion firstLine = document.getLineInformationOfOffset(offset);
		int lineOffset = firstLine.getOffset();

		// either the selection has to be empty and the caret in the WS at
		// the line start
		// or the selection has to extend over multiple lines
		if (length == 0)
			return document.get(lineOffset, offset - lineOffset).trim().length() == 0;
		else
			// return lineOffset + firstLine.getLength() < offset + length;
			return false; // only enable for empty selections for now

	} catch (BadLocationException e) {
	}

	return false;
}
 
Example 7
Source File: OccurrencesSearchResultPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void preformEditorSelectionChanged(ITextSelection selection, CompilationUnit astRoot) {
	if (!isLinkingEnabled()) {
		return;
	}
	IOccurrencesFinder finder;

	AbstractTextSearchResult input= getInput();
	if (input == null) {
		finder= new OccurrencesFinder();
	} else {
		String id= ((OccurrencesSearchQuery) input.getQuery()).getFinderId();
		if (id == OccurrencesFinder.ID) {
			finder= new OccurrencesFinder();
		} else if (id == ExceptionOccurrencesFinder.ID) {
			finder= new ExceptionOccurrencesFinder();
		} else {
			finder= new ImplementOccurrencesFinder();
		}
	}

	int offset= selection.getOffset();
	int length= selection.getLength();
	if (finder.initialize(astRoot, offset, length) == null) {
		final OccurrencesSearchQuery query= new OccurrencesSearchQuery(finder, astRoot.getTypeRoot());
		query.run(null);
		OccurrencesSearchResult result= (OccurrencesSearchResult) query.getSearchResult();
		final JavaElementLine line= getMatchingLine(result, offset, length);

		getSite().getShell().getDisplay().asyncExec(new Runnable() {
			public void run() {
				setInput(query.getSearchResult(), line == null ? null : new StructuredSelection(line));
			}
		});
	}
}
 
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: SexpHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
protected int noSelectTransform(ITextEditor editor, int offset, ITextSelection selection, boolean moveit) {
	// move the cursor if moveit == true	
	int newOffset = selection.getOffset();
	newOffset = (moveit ? newOffset + selection.getLength() : newOffset);
	selectAndReveal(editor, newOffset, newOffset);
	
	return NO_OFFSET;
}
 
Example 10
Source File: ToggleSLCommentAction.java    From xtext-eclipse with Eclipse Public License 2.0 5 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
 * @since 2.1
 */
protected 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
		log.error(x.getMessage(), x);
	}

	return null;
}
 
Example 11
Source File: CorrectIndentationHandler.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	final XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (activeXtextEditor == null) {
		return null;
	}
	final IXtextDocument doc = activeXtextEditor.getDocument();
	final ITextSelection selection = (ITextSelection) activeXtextEditor.getSelectionProvider().getSelection();
	final IRegion region = new Region(selection.getOffset(), selection.getLength());
	this.formatterProvider.get().format(doc, region);
	return null;
}
 
Example 12
Source File: EmacsPlusCmdHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * If no text is selected, see if the handler wants to get one
 * 
 * @param editor
 * @param selection
 * @return new selection, if handler modified it, else selection
 * @throws ExecutionException 
 */
protected ITextSelection getCmdSelection(ITextEditor editor,ITextSelection selection) throws ExecutionException {
	ITextSelection 	newSelection = selection;
	if (selection.getLength() <= 0) {
		newSelection = getNewSelection(getThisDocument(), selection);
		if (newSelection != null && newSelection != selection) {
			selection = newSelection;
			setSelection(editor,newSelection);
		} else {
			newSelection = selection;
		}
	}
	return newSelection;
}
 
Example 13
Source File: HandleBackspaceAction.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void execute(IDocument doc, ITextSelection selection, int commandLineOffset) {

    PyBackspace pyBackspace = new PyBackspace();
    pyBackspace.setDontEraseMoreThan(commandLineOffset);
    pyBackspace.setIndentPrefs(DefaultIndentPrefs.get(null));
    PySelection ps = new PySelection(doc, new CoreTextSelection(doc, selection.getOffset(), selection.getLength()));

    pyBackspace.perform(ps);
}
 
Example 14
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 15
Source File: ConvertLocalToFieldAction.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 (!ActionUtil.isEditable(fEditor))
		return;
	ICompilationUnit cunit= SelectionConverter.getInputAsCompilationUnit(fEditor);
	PromoteTempToFieldRefactoring refactoring= new PromoteTempToFieldRefactoring(cunit, selection.getOffset(), selection.getLength());
	new RefactoringStarter().activate(new PromoteTempWizard(refactoring), getShell(), RefactoringMessages.ConvertLocalToField_title, RefactoringSaveHelper.SAVE_NOTHING);
}
 
Example 16
Source File: TLAEditor.java    From tlaplus with MIT License 5 votes vote down vote up
public Object execute(ExecutionEvent event) throws ExecutionException
{
    final IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
    final TLAEditor tlaEditor = activeEditor.getAdapter(TLAEditor.class);

    final ITextSelection selection = (ITextSelection) tlaEditor.getSelectionProvider().getSelection();
    final IRegion region = new Region(selection.getOffset(), selection.getLength());

    // get the detectors
    final ISourceViewer internalSourceViewer = tlaEditor.getSourceViewer();
    final IHyperlinkDetector[] hyperlinkDetectors = tlaEditor.getSourceViewerConfiguration()
            .getHyperlinkDetectors(internalSourceViewer);
    if (hyperlinkDetectors != null)
    {
        for (int i = 0; i < hyperlinkDetectors.length; i++)
        {
            // detect
            final IHyperlink[] hyperlinks = hyperlinkDetectors[i].detectHyperlinks(internalSourceViewer, region,
                    false);
            if (hyperlinks != null && hyperlinks.length > 0)
            {
                // open
                final IHyperlink hyperlink = hyperlinks[0];
                hyperlink.open();
                break;
            }
        }
    }
    return null;
}
 
Example 17
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
private IRegion getBlockComment(IDocument document, ITextSelection selection, CommentSupport commentSupport)
		throws BadLocationException {
	if (selection.getText() == null) {
		return null;
	}
	String text = document.get();
	String open = commentSupport.getBlockComment().getKey();
	String close = commentSupport.getBlockComment().getValue();
	int selectionStart = selection.getOffset();
	int selectionEnd = selectionStart + selection.getLength();
	int openOffset = TextUtils.startIndexOfOffsetTouchingString(text, selectionStart, open);
	if (openOffset == -1) {
		openOffset = text.lastIndexOf(open, selectionStart);
		if (openOffset == -1 || openOffset < document.getLineOffset(selection.getStartLine())) {
			return null;
		}
	}

	int closeOffset = TextUtils.startIndexOfOffsetTouchingString(text, selectionEnd, close);
	if (closeOffset == -1 || closeOffset < openOffset + open.length()) {
		closeOffset = text.indexOf(close, selectionEnd);
		IRegion endLineRegion = document.getLineInformation(document.getLineOfOffset(selectionEnd));
		if (openOffset == -1 || closeOffset < openOffset + open.length()
				|| closeOffset > endLineRegion.getOffset() + endLineRegion.getLength()) {
			return null;
		}
	}

	// Make sure there isn't a different block closer before the one we found
	int othercloseOffset = text.indexOf(close, openOffset + open.length());
	while (othercloseOffset != -1 && othercloseOffset < closeOffset) {
		int startOfLineOffset = document.getLineOffset(document.getLineOfOffset(othercloseOffset));
		if (commentSupport.getLineComment() != null && text.substring(startOfLineOffset, othercloseOffset)
				.indexOf(commentSupport.getLineComment()) != -1) {
			return null;
		}
		othercloseOffset = text.indexOf(close, othercloseOffset + close.length());
	}
	return new Region(openOffset, closeOffset - openOffset);
}
 
Example 18
Source File: DerivedSourceView.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
private TextRegion mapTextRegion(IWorkbenchPartSelection workbenchPartSelection) {
	ITextSelection textSelection = (ITextSelection) workbenchPartSelection.getSelection();
	TextRegion localRegion = new TextRegion(textSelection.getOffset(), textSelection.getLength());
	return localRegion;
}
 
Example 19
Source File: ParagraphMarkHandler.java    From e4macs with Eclipse Public License 1.0 4 votes vote down vote up
private void reverseSelection(ITextEditor editor, IDocument document, ITextSelection selection) {
	// invert selection so cursor appears at correct end
	int end = selection.getOffset() + selection.getLength();
	setSelection(editor,new TextSelection(document,end,-selection.getLength()));
}
 
Example 20
Source File: RectangleSupport.java    From e4macs with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Convert the selection information to a RectangleInfo object with information about the 
 * offsets, lengths and columns involved
 * 
 * @param editor
 * @param document
 * @param selection
 * @return the RectangleInfo object
 */
public RectangleInfo getRectangleInfo(ITextEditor editor, IDocument document,ITextSelection selection) {
	RectangleInfo result = null;
	try {
		if (selection != null) {
			result = new RectangleInfo(); 
			// get begin and end offsets
			int beginOff = selection.getOffset();
			int endOff = beginOff + selection.getLength();
			// get begin and end line information
			IRegion bl = document.getLineInformationOfOffset(beginOff);
			IRegion el = document.getLineInformationOfOffset(endOff);
			int blOff = bl.getOffset();
			int elOff = el.getOffset();
			// determine the start and end columns
			int startCol = getColumn(document, blOff, beginOff - blOff,Integer.MAX_VALUE).getLength();
			int endCol = getColumn(document, elOff, endOff - elOff,Integer.MAX_VALUE).getLength();
			if (endCol < startCol) {
				int tmp = endCol;
				endCol = startCol;
				startCol = tmp;
			}
			result.setStartColumn(startCol);
			result.setEndColumn(endCol);
			// for each line in the rectangle, determine the offset and length
			int bline = document.getLineOfOffset(blOff);
			int eline = document.getLineOfOffset(elOff);
			LineInfo[] lines = new LineInfo[eline+1-bline];
			for (int i = 0; i < lines.length; i ++) {
				IRegion line = document.getLineInformation(bline + i);
				IRegion start = getColumn(document,line.getOffset(),line.getLength(),startCol);
				IRegion end = getColumn(document,line.getOffset(),line.getLength(),endCol);
				lines[i] = new LineInfo(start.getOffset(),(end.getOffset()-start.getOffset()),end.getLength());
			}
			result.setLines(lines);
		}
	} catch (BadLocationException e) {
		result = null;
	}
	return result;
}