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

The following examples show how to use org.eclipse.jface.text.Position#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: AnnotationWithQuickFixesHover.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected Object getHoverInfoInternal(ITextViewer textViewer, final int lineNumber, final int offset) {
	AnnotationInfo result = recentAnnotationInfo;
	if (result != null)
		return result;
	List<Annotation> annotations = getAnnotations(lineNumber, offset);
	for (Annotation annotation : sortBySeverity(annotations)) {
		Position position = getAnnotationModel().getPosition(annotation);
		if (annotation.getText() != null && position != null) {
			final QuickAssistInvocationContext invocationContext = new QuickAssistInvocationContext(sourceViewer, position.getOffset(), position.getLength(), true);
			CompletionProposalRunnable runnable = new CompletionProposalRunnable(invocationContext);
			// Note: the resolutions have to be retrieved from the UI thread, otherwise
			// workbench.getActiveWorkbenchWindow() will return null in LanguageSpecificURIEditorOpener and
			// cause an exception
			Display.getDefault().syncExec(runnable);
			if (invocationContext.isMarkedCancelled()) {
				return null;
			}
			result = new AnnotationInfo(annotation, position, sourceViewer, runnable.proposals);
			recentAnnotationInfo = result;
			return result;
		}
	}
	return null;
}
 
Example 2
Source File: AnnotationExpandHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the distance to the ruler line.
 *
 * @param position the position
 * @param document the document
 * @param line the line number
 * @return the distance to the ruler line
 */
protected int compareRulerLine(Position position, IDocument document, int line) {

	if (position.getOffset() > -1 && position.getLength() > -1) {
		try {
			int firstLine= document.getLineOfOffset(position.getOffset());
			if (line == firstLine)
				return 1;
			if (firstLine <= line && line <= document.getLineOfOffset(position.getOffset() + position.getLength()))
				return 2;
		} catch (BadLocationException x) {
		}
	}

	return 0;
}
 
Example 3
Source File: SexpHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Check if we're in a String (assuming the editor supports string categories)
 *  
 * @param document
 * @param dir
 * @param cpos
 * @param stringChar
 * @return the offset at the correct end of the string, or the current pos if not in string
 */
private int inString(IDocument document, int dir, int cpos, char stringChar) {
	int result = cpos;
	List<Position> positions = EmacsPlusUtils.getExclusions(document, EmacsPlusUtils.STRING_POS);
	if (positions.size() > 0) {
		Position pos;
		if ((pos = EmacsPlusUtils.inPosition(document, positions, cpos)) != null) {
			try {
				// check if we're looking at the same string syntax and get the end of the string
				if (document.get(pos.getOffset(),1).charAt(0) == stringChar) {
					result = ((dir == FORWARD) ? pos.getOffset() + pos.getLength() : pos.getOffset());
				}
			} catch (BadLocationException e) {}
		}
	}
	return result;
}
 
Example 4
Source File: JsonDocument.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
public IRegion getRegion(JsonPointer pointer) {
    Model model = getModel();
    if (model == null) {
        return null;
    }

    AbstractNode node = model.find(pointer);
    if (node == null) {
        return new Region(0, 0);
    }

    Position position = node.getPosition(this);

    return new Region(position.getOffset(), position.getLength());
}
 
Example 5
Source File: DocumentPartitioner.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the index of the first position which ends after the given offset.
 * 
 * @param positions
 *            the positions in linear order
 * @param offset
 *            the offset
 * @return the index of the first position which ends after the offset
 */
private int getFirstIndexEndingAfterOffset(Position[] positions, int offset) {
	int i = -1, j = positions.length;
	while (j - i > 1) {
		int k = (i + j) >> 1;
		Position p = positions[k];
		if (p.getOffset() + p.getLength() > offset)
			j = k;
		else
			i = k;
	}
	return j;
}
 
Example 6
Source File: DocumentPartitioner.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the index of the first position which starts at or after the given offset.
 * 
 * @param positions
 *            the positions in linear order
 * @param offset
 *            the offset
 * @return the index of the first position which starts after the offset
 */
private int getFirstIndexStartingAfterOffset(Position[] positions, int offset) {
	int i = -1, j = positions.length;
	while (j - i > 1) {
		int k = (i + j) >> 1;
		Position p = positions[k];
		if (p.getOffset() >= offset)
			j = k;
		else
			i = k;
	}
	return j;
}
 
Example 7
Source File: AnnotationWithQuickFixesHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Region getHoverRegionInternal(final int lineNumber, final int offset) {
	recentAnnotationInfo = null;
	List<Annotation> annotations = getAnnotations(lineNumber, offset);
	for (Annotation annotation : sortBySeverity(annotations)) {
		Position position = sourceViewer.getAnnotationModel().getPosition(annotation);
		if (position != null) {
			final int start = position.getOffset();
			return new Region(start, position.getLength());	
		}
	}
	return null;
}
 
Example 8
Source File: ProblemAnnotationHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Region getHoverRegionInternal(final int lineNumber, final int offset) {
	List<Annotation> annotations = getAnnotations(lineNumber, offset);
	for (Annotation annotation : sortBySeverity(annotations)) {
		Position position = sourceViewer.getAnnotationModel().getPosition(annotation);
		if (position != null) {
			final int start = position.getOffset();
			return new Region(start, position.getLength());	
		}
	}
	return null;
}
 
Example 9
Source File: AbstractProblemHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Find annotations that include the given offset. Only annotations for which {@link #isHandled(Annotation)}
 * returns {@code true} and {@link #isLineDiffInfo(Annotation)} returns {@code false} are included.
 * 
 * <p>If there are multiple annotations, those that start on the given line number are put first in the list,
 * then those that start one line before, etc.</p>
 * 
 * <p>The offset can be negative. In that case only annotations that start on the given line number
 * are returned.</p>
 */
public List<Annotation> getAnnotations(final int lineNumber, final int offset) {
	if (getAnnotationModel() == null) {
		return Collections.emptyList();
	}
	final Iterator<?> iterator = getAnnotationModel().getAnnotationIterator();
	List<Annotation> result = Lists.newArrayList();
	List<Integer> lineDiffs = Lists.newArrayList();
	while (iterator.hasNext()) {
		final Annotation annotation = (Annotation) iterator.next();
		if (isHandled(annotation) && !isLineDiffInfo(annotation)) {
			Position position = getAnnotationModel().getPosition(annotation);
			if (position != null) {
				final int start = position.getOffset();
				final int end = start + position.getLength();

				if (offset < 0 || start <= offset && offset <= end) {
					try {
						int lineDiff = Math.abs(lineNumber - getDocument().getLineOfOffset(start));
						if (lineDiff == 0 || offset >= 0) {
							// Insert the annotation according to its line number difference
							int index = lineDiffs.size();
							while (index > 0 && lineDiffs.get(index - 1) > lineDiff) {
								index--;
							}
							result.add(index, annotation);
							lineDiffs.add(index, lineDiff);
						}
					} catch (Exception x) {
						// Skip this annotation
					}
				}
			}
		}
	}
	return result;
}
 
Example 10
Source File: LineBackgroundPainter.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private boolean overlaps(Position currentLine, int modelCaret)
{
	if (currentLine.overlapsWith(modelCaret, 0))
		return true;
	if (modelCaret == (currentLine.getOffset() + currentLine.getLength()))
	{
		return true;
	}
	return false;
}
 
Example 11
Source File: CppStyleMessageConsole.java    From CppStyle with MIT License 5 votes vote down vote up
/**
 * Binary search for the position at a given offset.
 *
 * @param offset
 *            the offset whose position should be found
 * @return the position containing the offset, or <code>null</code>
 */
private Position findPosition(int offset, Position[] positions) {

	if (positions.length == 0) {
		return null;
	}

	int left = 0;
	int right = positions.length - 1;
	int mid = 0;
	Position position = null;

	while (left < right) {

		mid = (left + right) / 2;

		position = positions[mid];
		if (offset < position.getOffset()) {
			if (left == mid) {
				right = left;
			} else {
				right = mid - 1;
			}
		} else if (offset > (position.getOffset() + position.getLength() - 1)) {
			if (right == mid) {
				left = right;
			} else {
				left = mid + 1;
			}
		} else {
			left = right = mid;
		}
	}

	position = positions[left];
	if (offset >= position.getOffset() && (offset < (position.getOffset() + position.getLength()))) {
		return position;
	}
	return null;
}
 
Example 12
Source File: SemanticHighlightingPresenter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the index of the first position with an offset greater than the given offset.
 *
 * @param positions the positions, must be ordered by offset and must not overlap
 * @param offset the offset
 * @return the index of the last position with an offset greater than the given offset
 */
private int computeIndexAfterOffset(List<Position> positions, int offset) {
	int i= -1;
	int j= positions.size();
	while (j - i > 1) {
		int k= (i + j) >> 1;
		Position position= positions.get(k);
		if (position.getOffset() > offset)
			j= k;
		else
			i= k;
	}
	return j;
}
 
Example 13
Source File: DeleteWhitespaceHandler.java    From e4macs with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Determine the correct set of lines and delete the whitespace at the end of each of them.
 * 
 * @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;
	int lastLine = 0;
	int firstLine = 0;
	int maxOffset = Integer.MAX_VALUE;		
	if (editor.showsHighlightRangeOnly()) {
		// if the buffer is narrowed, then operate on precise region
		IRegion narrow = editor.getHighlightRange();
		int lastOffset = narrow.getOffset() + narrow.getLength();
		firstLine = document.getLineOfOffset(narrow.getOffset()); 
		lastLine = document.getLineOfOffset(lastOffset);
		IRegion endInfo = document.getLineInformationOfOffset(lastOffset);
		if (endInfo.getOffset() != lastOffset) {
			// point maxOffset at the last character in the narrowed region
			maxOffset = lastOffset -1;
		} else {
			// back up if we're at the first offset of the last line
			lastLine--;
		}
	} else {
		lastLine = document.getNumberOfLines() -1;
	}
	if (firstLine <= lastLine) {
		Position coff = new Position(getCursorOffset(editor,currentSelection),0);
		try {
			// record the position so we can restore it after any whitespace deletions
			document.addPosition(coff);
			deleteWhitepace(lastLine,firstLine,maxOffset,document);
		} catch (BadLocationException e) {
			// shouldn't happen, but alert user if it does
			asyncShowMessage(editor,BAD_LOCATION_ERROR,true);
		} finally {
			result = coff.getOffset();
			document.removePosition(coff);
		}
	}
	return result;
}
 
Example 14
Source File: DefaultCellSearchStrategy.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
/** burke 修改find/replace界面修改  不需要fuzzySearch*/
//private boolean fuzzySearch;

public IRegion executeSearch(String findValue, String dataValue) {
	// 如果查找的字符和单元格中的数据长度为 0,,则直接返回没有找到。
	if (findValue == null || findValue.length() == 0 || dataValue == null || dataValue.length() == 0) {
		return null;
	}
	Document doc = new Document(dataValue);
	FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(doc);
	IRegion region;
	try {
		if (startOffset == -1) {
			if (searchForward) {
				startOffset = 0;
			} else {
				startOffset = adapter.length() - 1;
			}
		}
		region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch);
		while (region != null) {
			boolean inTag = false;
			for (int i = region.getOffset(); i < region.getOffset() + region.getLength(); i++) {
				Position tagRange = InnerTagUtil.getStyledTagRange(dataValue, i);
				if (tagRange != null) {
					if (searchForward) {
						if (tagRange.getOffset() + tagRange.getLength() == dataValue.length()) {
							return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。
						}
						startOffset = tagRange.getOffset() + tagRange.getLength();
					} else {
						if (tagRange.offset == 0) {
							return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。
						}
						startOffset = tagRange.getOffset() - 1;
					}
					inTag = true;
					break;
				}
			}
			if (inTag) {
				region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch);
			} else {
				break;
			}
		}
		return region;
	} catch (BadLocationException e) {
		return null;
	}
}
 
Example 15
Source File: DefaultJavaFoldingStructureProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Finds a match for <code>tuple</code> in a collection of
 * annotations. The positions for the
 * <code>JavaProjectionAnnotation</code> instances in
 * <code>annotations</code> can be found in the passed
 * <code>positionMap</code> or <code>fCachedModel</code> if
 * <code>positionMap</code> is <code>null</code>.
 * <p>
 * A tuple is said to match another if their annotations have the
 * same comment flag and their position offsets are equal.
 * </p>
 * <p>
 * If a match is found, the annotation gets removed from
 * <code>annotations</code>.
 * </p>
 *
 * @param tuple the tuple for which we want to find a match
 * @param annotations collection of
 *        <code>JavaProjectionAnnotation</code>
 * @param positionMap a <code>Map&lt;Annotation, Position&gt;</code>
 *        or <code>null</code>
 * @param ctx the context
 * @return a matching tuple or <code>null</code> for no match
 */
private Tuple findMatch(Tuple tuple, Collection<JavaProjectionAnnotation> annotations, Map<JavaProjectionAnnotation, Position> positionMap, FoldingStructureComputationContext ctx) {
	Iterator<JavaProjectionAnnotation> it= annotations.iterator();
	while (it.hasNext()) {
		JavaProjectionAnnotation annotation= it.next();
		if (tuple.annotation.isComment() == annotation.isComment()) {
			Position position= positionMap == null ? ctx.getModel().getPosition(annotation) : positionMap.get(annotation);
			if (position == null)
				continue;

			if (tuple.position.getOffset() == position.getOffset()) {
				it.remove();
				return new Tuple(annotation, position);
			}
		}
	}

	return null;
}
 
Example 16
Source File: CopiedOverviewRuler.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the position of the first annotation found in the given line range.
 *
 * @param lineNumbers the line range
 * @return the position of the first found annotation
 */
protected Position getAnnotationPosition(int[] lineNumbers) {
    if (lineNumbers[0] == -1) {
        return null;
    }

    Position found = null;

    try {
        IDocument d = fTextViewer.getDocument();
        IRegion line = d.getLineInformation(lineNumbers[0]);

        int start = line.getOffset();

        line = d.getLineInformation(lineNumbers[lineNumbers.length - 1]);
        int end = line.getOffset() + line.getLength();

        for (int i = fAnnotationsSortedByLayer.size() - 1; i >= 0; i--) {

            Object annotationType = fAnnotationsSortedByLayer.get(i);

            Iterator e = new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY);
            while (e.hasNext() && found == null) {
                Annotation a = (Annotation) e.next();
                if (a.isMarkedDeleted()) {
                    continue;
                }

                if (skip(a.getType())) {
                    continue;
                }

                Position p = fModel.getPosition(a);
                if (p == null) {
                    continue;
                }

                int posOffset = p.getOffset();
                int posEnd = posOffset + p.getLength();
                IRegion region = d.getLineInformationOfOffset(posEnd);
                // trailing empty lines don't count
                if (posEnd > posOffset && region.getOffset() == posEnd) {
                    posEnd--;
                    region = d.getLineInformationOfOffset(posEnd);
                }

                if (posOffset <= end && posEnd >= start) {
                    found = p;
                }
            }
        }
    } catch (BadLocationException x) {
    }

    return found;
}
 
Example 17
Source File: DefaultCellSearchStrategy.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
/** burke 修改find/replace界面修改  不需要fuzzySearch*/
//private boolean fuzzySearch;

public IRegion executeSearch(String findValue, String dataValue) {
	// 如果查找的字符和单元格中的数据长度为 0,,则直接返回没有找到。
	if (findValue == null || findValue.length() == 0 || dataValue == null || dataValue.length() == 0) {
		return null;
	}
	Document doc = new Document(dataValue);
	FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(doc);
	IRegion region;
	try {
		if (startOffset == -1) {
			if (searchForward) {
				startOffset = 0;
			} else {
				startOffset = adapter.length() - 1;
			}
		}
		region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch);
		while (region != null) {
			boolean inTag = false;
			for (int i = region.getOffset(); i < region.getOffset() + region.getLength(); i++) {
				Position tagRange = InnerTagUtil.getStyledTagRange(dataValue, i);
				if (tagRange != null) {
					if (searchForward) {
						if (tagRange.getOffset() + tagRange.getLength() == dataValue.length()) {
							return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。
						}
						startOffset = tagRange.getOffset() + tagRange.getLength();
					} else {
						if (tagRange.offset == 0) {
							return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。
						}
						startOffset = tagRange.getOffset() - 1;
					}
					inTag = true;
					break;
				}
			}
			if (inTag) {
				region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch);
			} else {
				break;
			}
		}
		return region;
	} catch (BadLocationException e) {
		return null;
	}
}
 
Example 18
Source File: TLAFastPartitioner.java    From tlaplus with MIT License 2 votes vote down vote up
/**
 * Pretty print a <code>Position</code>.
 *
 * @param position the position to format
 * @return a formatted string
 */
private String toString(Position position) {
    return "P[" + position.getOffset() + "+" + position.getLength() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
 
Example 19
Source File: DocumentPartitioner.java    From xtext-eclipse with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Pretty print a <code>Position</code>.
 * 
 * @param position
 *            the position to format
 * @return a formatted string
 */
private String toString(Position position) {
	return "P[" + position.getOffset() + "+" + position.getLength() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
 
Example 20
Source File: DocumentPartitioner.java    From xtext-eclipse with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Returns <code>true</code> if the given ranges overlap with or touch each other.
 * 
 * @param gap
 *            the first range
 * @param offset
 *            the offset of the second range
 * @param length
 *            the length of the second range
 * @return <code>true</code> if the given ranges overlap with or touch each other
 */
private boolean overlapsOrTouches(Position gap, int offset, int length) {
	return gap.getOffset() <= offset + length && offset <= gap.getOffset() + gap.getLength();
}