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

The following examples show how to use org.eclipse.jface.text.IRegion#getOffset() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GoToMatchingBracketAction.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void run() {
	IXtextDocument document = editor.getDocument();
	ISelection selection = editor.getSelectionProvider().getSelection();
	if (selection instanceof ITextSelection) {
		ITextSelection textSelection = (ITextSelection) selection;
		if (textSelection.getLength()==0) {
			IRegion region = matcher.match(document, textSelection.getOffset());
			if (region != null) {
				if (region.getOffset()+1==textSelection.getOffset()) {
					editor.selectAndReveal(region.getOffset()+region.getLength(),0);
				} else {
					editor.selectAndReveal(region.getOffset()+1,0);
				}
			}
		}
	}
}
 
Example 2
Source File: SexpBaseBackwardHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * When moving backward, and we're consuming _'s, see if we're currently positioned by an _
 * 
 * @param doc
 * @param iter
 * @param pos current word position
 * @return new offset if word moves past any _'s, else pos   
 */
int checkUnder(IDocument doc, BreakIterator iter, int pos) {
	int result = pos;
	try {
		if (!isUnder()) {
			char c = doc.getChar(result);
			IRegion lineInfo = doc.getLineInformationOfOffset(pos);
			if (c == '_') {
				// we've backed over an _
				Matcher matcher = getUnderMatcher();
				// get text including the trailing _
				matcher.reset(doc.get(lineInfo.getOffset(), pos+1 - lineInfo.getOffset()));
				if (matcher.find()) {
					result = lineInfo.getOffset() + matcher.start(1);
				}
			} else if (result > lineInfo.getOffset()){
				// check preceding character
				c = doc.getChar(result-1);
				if (c == '_' || (!isDot() && c == '.')) {
					// we've been stopped by a preceding _ or . 
					result = checkUnder(doc,iter,iter.previous());
				}
			}
		}
	} catch (BadLocationException e) {
	}
	return result;
}
 
Example 3
Source File: DocumentUtils.java    From http4e with Apache License 2.0 5 votes vote down vote up
public static IRegion getDelimRegion( IDocument doc, int offset) throws BadLocationException{
   IRegion regLine = doc.getLineInformationOfOffset(offset);
   FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(doc);
   int lineOff = regLine.getOffset();
   IRegion regDelim = null;
   try {
      regDelim = finder.find(lineOff, AssistConstants.S_EQUAL, true, true, false, false);
  } catch (Exception ignore) {}

   return regDelim;
}
 
Example 4
Source File: AddImportOnSelectionAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IEditingSupport createViewerHelper(final ITextSelection selection, final SelectTypeQuery query) {
	return new IEditingSupport() {

		public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) {
			return subjectRegion.getOffset() <= selection.getOffset() + selection.getLength() &&  selection.getOffset() <= subjectRegion.getOffset() + subjectRegion.getLength();
		}

		public boolean ownsFocusShell() {
			return query.isShowing();
		}

	};
}
 
Example 5
Source File: TypeScriptIndenter.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Peeks the next char in the document that comes after <code>offset</code>
 * on the same line as <code>offset</code>.
 *
 * @param offset
 *            the offset into document
 * @return the token symbol of the next element, or TokenEOF if there is
 *         none
 */
private int peekChar(int offset) {
	if (offset < fDocument.getLength()) {
		try {
			IRegion line = fDocument.getLineInformationOfOffset(offset);
			int lineOffset = line.getOffset();
			int next = fScanner.nextToken(offset, lineOffset + line.getLength());
			return next;
		} catch (BadLocationException e) {
		}
	}
	return Symbols.TokenEOF;
}
 
Example 6
Source File: TeXSpellingReconcileStrategy.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param p
 * @return true, if the Position is inside a region which was checked by
 * the spell checker
 */
private boolean wasChecked (Position p) {
    for (IRegion r : regions) {
        if (p.getOffset() >= r.getOffset() &&
                p.getOffset() <= r.getOffset() + r.getLength()) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: PyMoveLineAction.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes the region of the skipped line given the text block to be moved. If
 * <code>fUpwards</code> is <code>true</code>, the line above <code>selection</code>
 * is selected, otherwise the line below.
 *
 * @param document the document <code>selection</code> refers to
 * @param selection the selection on <code>document</code> that will be moved.
 * @return the region comprising the line that <code>selection</code> will be moved over, without its terminating delimiter.
 */
private ICoreTextSelection getSkippedLine(IDocument document, ICoreTextSelection selection) {
    int skippedLineN = (getMoveUp() ? selection.getStartLine() - 1 : selection.getEndLine() + 1);
    if (skippedLineN > document.getNumberOfLines()
            || ((skippedLineN < 0 || skippedLineN == document.getNumberOfLines()))) {
        return null;
    }
    try {
        IRegion line = document.getLineInformation(skippedLineN);
        return new CoreTextSelection(document, line.getOffset(), line.getLength());
    } catch (BadLocationException e) {
        // only happens on concurrent modifications
        return null;
    }
}
 
Example 8
Source File: IndentGuidesPainter.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Convert a widget offset to the corresponding document offset.
 * 
 * @param widgetOffset
 *            the widget offset
 * @return document offset
 */
private int getDocumentOffset(int widgetOffset) {
	if (fTextViewer instanceof ITextViewerExtension5) {
		ITextViewerExtension5 extension = (ITextViewerExtension5) fTextViewer;
		return extension.widgetOffset2ModelOffset(widgetOffset);
	}
	IRegion visible = fTextViewer.getVisibleRegion();
	if (widgetOffset > visible.getLength()) {
		return -1;
	}
	return widgetOffset + visible.getOffset();
}
 
Example 9
Source File: ErrorDescription.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
public int getBeginColumn(IDocument doc) {
    try {
        IRegion lineInformationOfOffset = doc.getLineInformationOfOffset(errorStart);
        return errorStart - lineInformationOfOffset.getOffset();
    } catch (BadLocationException e) {
    }
    return 0;
}
 
Example 10
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Returns <code>true</code> if the comment being inserted at
 * <code>command.offset</code> is the first comment (the first javadoc
 * comment if <code>ignoreJavadoc</code> is <code>true</code>) of the given
 * member.
 * <p>
 * see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=55325 (don't add
 * parameters if the member already has a comment)
 * </p>
 */
private boolean isFirstComment(IDocument document, DocumentCommand command, IMember member,
		boolean ignoreNonJavadoc) throws BadLocationException, JavaScriptModelException {
	IRegion partition = TextUtilities.getPartition(document, fPartitioning, command.offset, false);
	ISourceRange sourceRange = member.getSourceRange();
	if (sourceRange == null || sourceRange.getOffset() != partition.getOffset())
		return false;
	int srcOffset = sourceRange.getOffset();
	int srcLength = sourceRange.getLength();
	int nameRelativeOffset = member.getNameRange().getOffset() - srcOffset;
	int partitionRelativeOffset = partition.getOffset() - srcOffset;
	String token = ignoreNonJavadoc ? "/**" : "/*"; //$NON-NLS-1$ //$NON-NLS-2$
	return document.get(srcOffset, srcLength).lastIndexOf(token, nameRelativeOffset) == partitionRelativeOffset;
}
 
Example 11
Source File: UiBinderXmlParser.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private void setFieldReferenceFirstFragmentUndefinedError(
    IRegion attrValueRegion, IRegion exprContentRegion, String exprContents) {
  String firstFragment = UiBinderUtilities.getFirstFragment(exprContents);
  int start = attrValueRegion.getOffset() + exprContentRegion.getOffset();
  problemMarkerManager.setFirstFragmentUndefinedError(new Region(start,
      firstFragment.length()), firstFragment);
}
 
Example 12
Source File: SpellCheckIterator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new spell check iterator.
 *
 * @param document the document containing the specified partition
 * @param region the region to spell check
 * @param locale the locale to use for spell checking
 * @param breakIterator the break-iterator
 */
public SpellCheckIterator(IDocument document, IRegion region, Locale locale, BreakIterator breakIterator) {
	fOffset= region.getOffset();
	fWordIterator= breakIterator;
	fDelimiter= TextUtilities.getDefaultLineDelimiter(document);

	String content;
	try {

		content= document.get(region.getOffset(), region.getLength());
		if (content.startsWith(NLSElement.TAG_PREFIX))
			content= ""; //$NON-NLS-1$

	} catch (Exception exception) {
		content= ""; //$NON-NLS-1$
	}
	fContent= content;

	fWordIterator.setText(content);
	fPredecessor= fWordIterator.first();
	fSuccessor= fWordIterator.next();

	final BreakIterator iterator= BreakIterator.getSentenceInstance(locale);
	iterator.setText(content);

	int offset= iterator.current();
	while (offset != BreakIterator.DONE) {

		fSentenceBreaks.add(new Integer(offset));
		offset= iterator.next();
	}
}
 
Example 13
Source File: JavaIndenter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the indentation of the line at <code>offset</code> as a
 * <code>StringBuffer</code>. If the offset is not valid, the empty string
 * is returned.
 *
 * @param offset the offset in the document
 * @return the indentation (leading whitespace) of the line in which
 * 		   <code>offset</code> is located
 */
private StringBuffer getLeadingWhitespace(int offset) {
	StringBuffer indent= new StringBuffer();
	try {
		IRegion line= fDocument.getLineInformationOfOffset(offset);
		int lineOffset= line.getOffset();
		int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + line.getLength());
		indent.append(fDocument.get(lineOffset, nonWS - lineOffset));
		return indent;
	} catch (BadLocationException e) {
		return indent;
	}
}
 
Example 14
Source File: PyCompletionPresentationUpdater.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private StyleRange createStyleRange(ITextViewer viewer, int initialOffset, int len) {
    StyledText text = viewer.getTextWidget();
    if (text == null || text.isDisposed()) {
        return null;
    }

    int widgetCaret = text.getCaretOffset();

    int modelCaret = 0;
    if (viewer instanceof ITextViewerExtension5) {
        ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
        modelCaret = extension.widgetOffset2ModelOffset(widgetCaret);
    } else {
        IRegion visibleRegion = viewer.getVisibleRegion();
        modelCaret = widgetCaret + visibleRegion.getOffset();
    }

    if (modelCaret >= initialOffset + len) {
        return null;
    }

    int length = initialOffset + len - modelCaret;

    Color foreground = getForegroundColor();
    Color background = getBackgroundColor();

    return new StyleRange(modelCaret, length, foreground, background);
}
 
Example 15
Source File: IndentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 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 16
Source File: JavaDoubleClickSelector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) {
	IRegion match= fPairMatcher.match(document, offset);
	if (match != null && match.getLength() >= 2)
		return new Region(match.getOffset() + 1, match.getLength() - 2);
	return findWord(document, offset);
}
 
Example 17
Source File: IndentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Computes and returns the indentation for a javadoc line. The line
 * must be inside a javadoc comment.
 *
 * @param document the document
 * @param line the line in document
 * @param scanner the scanner
 * @param partition the javadoc partition
 * @return the indent, or <code>null</code> if not computable
 * @throws BadLocationException
 * @since 3.1
 */
private static String computeJavadocIndent(IDocument document, int line, JavaHeuristicScanner scanner, ITypedRegion partition) throws BadLocationException {
	if (line == 0) // impossible - the first line is never inside a javadoc comment
		return null;

	// don't make any assumptions if the line does not start with \s*\* - it might be
	// commented out code, for which we don't want to change the indent
	final IRegion lineInfo= document.getLineInformation(line);
	final int lineStart= lineInfo.getOffset();
	final int lineLength= lineInfo.getLength();
	final int lineEnd= lineStart + lineLength;
	int nonWS= scanner.findNonWhitespaceForwardInAnyPartition(lineStart, lineEnd);
	if (nonWS == JavaHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
		if (nonWS == JavaHeuristicScanner.NOT_FOUND)
			return document.get(lineStart, lineLength);
		return document.get(lineStart, nonWS - lineStart);
	}

	// take the indent from the previous line and reuse
	IRegion previousLine= document.getLineInformation(line - 1);
	int previousLineStart= previousLine.getOffset();
	int previousLineLength= previousLine.getLength();
	int previousLineEnd= previousLineStart + previousLineLength;

	StringBuffer buf= new StringBuffer();
	int previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
	if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND || document.getChar(previousLineNonWS) != '*') {
		// align with the comment start if the previous line is not an asterisked line
		previousLine= document.getLineInformationOfOffset(partition.getOffset());
		previousLineStart= previousLine.getOffset();
		previousLineLength= previousLine.getLength();
		previousLineEnd= previousLineStart + previousLineLength;
		previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
		if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND)
			previousLineNonWS= previousLineEnd;

		// add the initial space
		// TODO this may be controlled by a formatter preference in the future
		buf.append(' ');
	}

	String indentation= document.get(previousLineStart, previousLineNonWS - previousLineStart);
	buf.insert(0, indentation);
	return buf.toString();
}
 
Example 18
Source File: RubyRegexpAutoIndentStrategy.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private void autoDedent(IDocument d, DocumentCommand c)
{
	if (c.offset <= 0 || d.getLength() == 0 || c.text.length() > 1)
	{
		return;
	}

	try
	{
		// Get the line and run a regexp check against it
		IRegion curLineRegion = d.getLineInformationOfOffset(c.offset);
		// Only de-dent when at end of line!
		int endOffset = curLineRegion.getOffset() + curLineRegion.getLength();
		if (c.offset != endOffset)
			return;

		String scope = getScopeAtOffset(d, c.offset);
		RubyRegexp decreaseIndentRegexp = getDecreaseIndentRegexp(scope);
		// what line will be after new char is inserted....
		String lineContent = d.get(curLineRegion.getOffset(), c.offset - curLineRegion.getOffset());
		if (matchesRegexp(decreaseIndentRegexp, lineContent + c.text))
		{
			int lineNumber = d.getLineOfOffset(c.offset);
			if (lineNumber == 0) // first line, should be no indent yet...
			{
				return;
			}
			int endIndex = findEndOfWhiteSpace(d, curLineRegion.getOffset(), curLineRegion.getOffset()
					+ curLineRegion.getLength());
			String currentLineIndent = d.get(curLineRegion.getOffset(), endIndex - curLineRegion.getOffset());
			if (currentLineIndent.length() == 0)
			{
				return;
			}
			// Textmate just assumes we subtract one indent level, unless the matching level it should be at is >=
			// what we're at now!
			String decreasedIndent = ""; //$NON-NLS-1$

			// if we subtract one indent level and it is shorter than matching indent, then don't subtract!
			String matchingIndent = findCorrectIndentString(d, lineNumber, currentLineIndent);

			String indentString = getIndentString();
			if (currentLineIndent.length() > indentString.length())
			{
				decreasedIndent = currentLineIndent
						.substring(0, currentLineIndent.length() - indentString.length());
			}
			// if indent level hasn't changed, or shouldn't be moved back, return early!
			if (decreasedIndent.equals(currentLineIndent) || decreasedIndent.length() < matchingIndent.length())
			{
				return;
			}
			// Shift the current line...
			int i = 0;
			while (i < lineContent.length() && Character.isWhitespace(lineContent.charAt(i)))
			{
				i++;
			}
			// Just shift the content beforehand
			String newContent = decreasedIndent + lineContent.substring(i);
			d.replace(curLineRegion.getOffset(), lineContent.length(), newContent);
			c.doit = true;
			int diff = currentLineIndent.length() - decreasedIndent.length();
			c.offset -= diff;
			return;
		}
	}
	catch (BadLocationException e)
	{
		IdeLog.logError(CommonEditorPlugin.getDefault(), e);
	}

	return;
}
 
Example 19
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns the range of the Javadoc prefix on the given line in
 * <code>document</code>. The prefix greedily matches the following regex
 * pattern: <code>\w*\*\w*</code>, that is, any number of whitespace
 * characters, followed by an asterisk ('*'), followed by any number of
 * whitespace characters.
 *
 * @param document the document to which <code>line</code> refers
 * @param line the line from which to extract the prefix range
 * @return an <code>IRegion</code> describing the range of the prefix on the given line
 * @throws BadLocationException if accessing the document fails
 */
private IRegion findPrefixRange(IDocument document, IRegion line) throws BadLocationException {
	int lineOffset= line.getOffset();
	int lineEnd= lineOffset + line.getLength();
	int indentEnd= findEndOfWhiteSpace(document, lineOffset, lineEnd);
	if (indentEnd < lineEnd && document.getChar(indentEnd) == '*') {
		indentEnd++;
		while (indentEnd < lineEnd && document.getChar(indentEnd) == ' ')
			indentEnd++;
	}
	return new Region(lineOffset, indentEnd - lineOffset);
}
 
Example 20
Source File: DefaultJavaFoldingStructureProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a folding position that remembers its member from an
 * {@link #alignRegion(IRegion, DefaultJavaFoldingStructureProvider.FoldingStructureComputationContext) aligned}
 * region.
 *
 * @param aligned an aligned region
 * @param member the member to remember
 * @return a folding position corresponding to <code>aligned</code>
 */
protected final Position createMemberPosition(IRegion aligned, IMember member) {
	return new JavaElementPosition(aligned.getOffset(), aligned.getLength(), member);
}