org.eclipse.jface.text.Region Java Examples

The following examples show how to use org.eclipse.jface.text.Region. 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: OpenDeclarationHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	XtextEditor xtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (xtextEditor != null) {
		ITextSelection selection = (ITextSelection) xtextEditor.getSelectionProvider().getSelection();

		IRegion region = new Region(selection.getOffset(), selection.getLength());

		ISourceViewer internalSourceViewer = xtextEditor.getInternalSourceViewer();

		IHyperlink[] hyperlinks = getDetector().detectHyperlinks(internalSourceViewer, region, false);
		if (hyperlinks != null && hyperlinks.length > 0) {
			IHyperlink hyperlink = hyperlinks[0];
			hyperlink.open();
		}
	}		
	return null;
}
 
Example #2
Source File: SexpCharacterPairMatcher.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
protected synchronized IRegion performMatch(IDocument doc, int caretOffset) throws BadLocationException {
	int charOffset = caretOffset - 1;
	boolean forward = fPairs.isStartCharacter(doc.getChar(charOffset));
	// simple documents (e.g. .txt) don't have type categories
	if (EmacsPlusUtils.getTypeCategory(doc) != null) {
		exPositions = EmacsPlusUtils.getExclusions(doc, EmacsPlusUtils.ALL_POS);
		// remember category position if first character is in a comment or string
		exPosition = EmacsPlusUtils.inPosition(doc, exPositions, charOffset);
	}
	IRegion reg = super.performMatch(doc, caretOffset);
	// if we started in a category position, make sure we end in the same one
	if (reg == null || 
		(exPosition != null && !exPosition.includes(forward ? reg.getOffset() + reg.getLength() : reg.getOffset()))) {
		return new Region(charOffset, 1);	
	}
	return reg;
}
 
Example #3
Source File: TexlipseAnnotationUpdater.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates and returns a background job which searches and highlights all \label and \*ref. 
 * @param document
 * @param model
 * @param refName   The name of the reference
 * @return The job
 */
private Job createMatchReferenceJob(final IDocument document, final IAnnotationModel model, final String refName) {
    return
        new Job("Update Annotations") {
            public IStatus run(IProgressMonitor monitor) {
                String text = document.get();
                String refNameRegExp = refName.replaceAll("\\*", "\\\\*");
                final String simpleRefRegExp = "\\\\([a-zA-Z]*ref|label)\\s*\\{" + refNameRegExp + "\\}";
                Matcher m = (Pattern.compile(simpleRefRegExp)).matcher(text);
                while (m.find()) {
                    if (monitor.isCanceled()) return Status.CANCEL_STATUS;
                    IRegion match = LatexParserUtils.getCommand(text, m.start());
                    //Test if it is a real LaTeX command
                    if (match != null) {
                        IRegion fi = new Region(m.start(), m.end()-m.start());
                        createNewAnnotation(fi, "References", model);
                    }
                }
                return Status.OK_STATUS;
            }
    };
}
 
Example #4
Source File: SolidityHyperlinkHelper.java    From solidity-ide with Eclipse Public License 1.0 6 votes vote down vote up
protected void createImportedNamespacesHyperlinksByOffset(XtextResource resource, int offset,
		IHyperlinkAcceptor acceptor) {
	INode node = NodeModelUtils.findLeafNodeAtOffset(resource.getParseResult().getRootNode(), offset);
	if (node != null) {			
		List<INode> importNodes = NodeModelUtils.findNodesForFeature(node.getSemanticElement(), SolidityPackage.Literals.IMPORT_DIRECTIVE__IMPORTED_NAMESPACE);
		if (importNodes != null && !importNodes.isEmpty()) {
			for (INode importNode : importNodes) {
				ImportDirective importElement = (ImportDirective) importNode.getSemanticElement();
				URI targetURI = getFileURIOfImport(importElement);
				XtextHyperlink result = getHyperlinkProvider().get();
				result.setURI(targetURI);
				Region region = new Region(importNode.getOffset(), importNode.getLength());
				result.setHyperlinkRegion(region);
				result.setHyperlinkText(targetURI.toString());
				acceptor.accept(result);
			}
		}
	}
}
 
Example #5
Source File: TLAEditor.java    From tlaplus with MIT License 6 votes vote down vote up
public void selectAndReveal(final pcal.Region aRegion) throws BadLocationException {
	final IDocument document = getDocumentProvider().getDocument(
			getEditorInput());

	// Translate pcal.Region coordinates into Java IDocument coordinates
	final PCalLocation begin = aRegion.getBegin();
	final int startLineOffset = document.getLineOffset(begin.getLine());
	final int startOffset = startLineOffset + begin.getColumn();
	
	final PCalLocation end = aRegion.getEnd();
	final int endLineOffset = document.getLineOffset(end.getLine());
	final int endOffset = endLineOffset + end.getColumn();

	final int length = endOffset - startOffset;
	
	selectAndReveal(startOffset, length);
}
 
Example #6
Source File: QuickTypeHierarchyHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void openPresentation(final XtextEditor editor, final IJavaElement javaElement,
		final EObject selectedElement) {
	final ISourceViewer sourceViewer = editor.getInternalSourceViewer();
	ITextRegion significantTextRegion = locationInFileProvider.getSignificantTextRegion(selectedElement);
	InformationPresenter presenter = new HierarchyInformationPresenter(sourceViewer, javaElement, new Region(significantTextRegion.getOffset(),significantTextRegion.getLength()));
	presenter.setDocumentPartitioning(IDocumentExtension3.DEFAULT_PARTITIONING);
	presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
	IInformationProvider provider = new JavaElementProvider(editor, false);
	presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
	presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
	presenter.setSizeConstraints(50, 20, true, false);
	presenter.install(sourceViewer);
	presenter.showInformation();
}
 
Example #7
Source File: PartitionDoubleClickSelector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) {
	IRegion match= super.findExtendedDoubleClickSelection(document, offset);
	if (match != null)
		return match;

	try {
		ITypedRegion region= TextUtilities.getPartition(document, fPartitioning, offset, true);
		if (offset == region.getOffset() + fHitDelta || offset == region.getOffset() + region.getLength() - fHitDelta) {
			if (fLeftBorder == 0 && fRightBorder == 0)
				return region;
			if (fRightBorder == -1) {
				String delimiter= document.getLineDelimiter(document.getLineOfOffset(region.getOffset() + region.getLength() - 1));
				if (delimiter == null)
					fRightBorder= 0;
				else
					fRightBorder= delimiter.length();
			}
			return new Region(region.getOffset() + fLeftBorder, region.getLength() - fLeftBorder - fRightBorder);
		}
	} catch (BadLocationException e) {
		return null;
	}
	return null;
}
 
Example #8
Source File: LatexParserUtils.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
private static IRegion findEnvironment(String input, String envName, String command, int fromIndex) {
    int pos = input.indexOf("{" + envName + "}", fromIndex + command.length());
    while (pos != -1) {
        int end = pos + envName.length() + 2;
        // Search for the command
        int beginStart = findLastCommand(input, command, pos);
        if (beginStart != -1 && beginStart >= fromIndex) {
            // Check for whitespaces between \begin and {...}
                while (pos != beginStart + command.length() && Character.isWhitespace(input.charAt(--pos)))
                    ;
            if (pos == beginStart + command.length()) {
                return new Region(beginStart, end - beginStart);
            }
        }
        pos = input.indexOf("{" + envName + "}", pos + envName.length() + 2);
    }
    return null;
}
 
Example #9
Source File: AbstractCompositeHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test public void testEmptyHoverList () {
	AbstractCompositeHover hover = new AbstractCompositeHover() {

		@Override
		protected List<ITextHover> createHovers() {
			List<ITextHover> hovers = Lists.newArrayList();
			return hovers;
		}
	};

	assertEquals (0, hover.getHovers().size());
	assertNull (hover.getHoverRegion(editor.getInternalSourceViewer(), 0));
	assertNull (hover.getHoverControlCreator());
	assertNull (hover.getHoverInfo(editor.getInternalSourceViewer(), new Region(0,0)));
	assertNull (hover.getHoverInfo2(editor.getInternalSourceViewer(), new Region(0,0)));
}
 
Example #10
Source File: ScopeSelectionAction.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
public void perform(IDocument doc, ICoreTextSelection selection, BaseEditor editor) {
    FastStack<IRegion> cache = getCache(editor);
    Region initialRegion = new Region(selection.getOffset(), selection.getLength());
    if (cache.size() > 0) {
        IRegion peek = cache.peek();
        if (!peek.equals(initialRegion)) {
            cache.clear();
        }
    }
    if (cache.size() == 0) {
        cache.push(initialRegion);
    }
    ICoreTextSelection newSelection = getNewSelection(doc, selection, editor);
    if (initialRegion.equals(new Region(newSelection.getOffset(), newSelection.getLength()))) {
        return;
    }

    editor.setSelection(newSelection.getOffset(), newSelection.getLength());
    cache.push(new Region(newSelection.getOffset(), newSelection.getLength()));
}
 
Example #11
Source File: XmlUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets a region for the attribute's value (without the quotes).
 */
public static IRegion getAttributeValueRegion(IDOMAttr attribute) {
  String attrValue = attribute.getValueRegionText();
  if (attrValue == null) {
    return null;
  }
  
  int offset = attribute.getValueRegionStartOffset();
  int length = attrValue.length();

  // Strip off the quotes
  if (isXmlQuote(attrValue.charAt(0))) {
    offset++;
    length--;
  }
  if (isXmlQuote(attrValue.charAt(attrValue.length() - 1))) {
    length--;
  }

  return new Region(offset, length);
}
 
Example #12
Source File: NLSStringHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
	if (!(getEditor() instanceof JavaEditor))
		return null;

	ITypeRoot je= getEditorInputJavaElement();
	if (je == null)
		return null;

	// Never wait for an AST in UI thread.
	CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, offset, 1);
	if (node instanceof StringLiteral) {
		StringLiteral stringLiteral= (StringLiteral)node;
		return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
	} else if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName)node;
		return new Region(simpleName.getStartPosition(), simpleName.getLength());
	}

	return null;
}
 
Example #13
Source File: OpenDeclarationAction.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Open the declaration if possible.
 */
@Override
public void run()
{
	ITextEditor textEditor = getTextEditor();

	if (textEditor instanceof JSSourceEditor)
	{
		ITextSelection selection = (ITextSelection) textEditor.getSelectionProvider().getSelection();
		IRegion region = new Region(selection.getOffset(), 1);
		JSHyperlinkDetector detector = new JSHyperlinkDetector();
		IHyperlink[] hyperlinks = detector.detectHyperlinks((AbstractThemeableEditor) textEditor, region, true);

		if (!ArrayUtil.isEmpty(hyperlinks))
		{
			// give first link highest precedence
			hyperlinks[0].open();
		}
	}
}
 
Example #14
Source File: ExcludeRegionList.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public IRegion[] selectValidRanges(int start, int end)
{
	final List<Region> result = new ArrayList<Region>();
	for (final IRegion region : excludes)
	{
		final int regionEnd = region.getOffset() + region.getLength();
		if (start <= regionEnd && region.getOffset() <= end)
		{
			if (start < region.getOffset())
			{
				int validEnd = Math.min(end, region.getOffset());
				result.add(new Region(start, validEnd - start));
			}
			start = regionEnd;
			if (start > end)
			{
				break;
			}
		}
	}
	if (start < end)
	{
		result.add(new Region(start, end - start));
	}
	return result.toArray(new IRegion[result.size()]);
}
 
Example #15
Source File: CSSTextHover.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
private RegionInfo getColorRegionInfo(CSSNode cssNode)
{
	if (cssNode == null)
	{
		return null;
	}

	String text = cssNode.getText();
	if (StringUtil.isEmpty(text))
	{
		return null;
	}

	IRegion region = new Region(cssNode.getStartingOffset(), cssNode.getLength());
	if (text.charAt(0) == '#')
	{
		return new RegionInfo(region, CSSColorsUI.hexToRGB(text));
	}
	else if (CSSColors.namedColorExists(text))
	{
		return new RegionInfo(region, CSSColorsUI.namedColorToRGB(text));
	}
	return new RegionInfo(region, text);
}
 
Example #16
Source File: Regions.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
private static IRegion intersection(IRegion o1, IRegion o2) {
	int offset1 = o1.getOffset();
	int offset2 = o2.getOffset();
	int offset = Math.max(offset1, offset2);
	int length = Math.min(offset1 + o1.getLength(), offset2 + o2.getLength()) - offset;
	if (length <= 0) {
		return null;
	}
	if (offset == offset1 && length == o1.getLength()) {
		return o1;
	}
	if (offset == offset2 && length == o2.getLength()) {
		return o2;
	}
	return new Region(offset, length);
}
 
Example #17
Source File: DocumentUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * searches backwards for the given string within the same partition type
 * @return the region of the match or <code>null</code> if no match were found
 * @since 2.4
 */
public IRegion searchBackwardsInSamePartition(String toFind, String documentText, IDocument document, int endOffset) throws BadLocationException {
	if (endOffset < 0) {
		return null;
	}
	int length = toFind.length();
	String text = preProcessSearchString(documentText);
	ITypedRegion partition = document.getPartition(endOffset);
	int indexOf = text.lastIndexOf(toFind, endOffset - length);
	while (indexOf >= 0) {
		ITypedRegion partition2 = document.getPartition(indexOf);
		if (partition2.getType().equals(partition.getType())) {
			return new Region(indexOf, length);
		}
		indexOf = text.lastIndexOf(toFind, partition2.getOffset() - length);
	}
	String trimmed = toFind.trim();
	if (trimmed.length() > 0 && trimmed.length() != length) {
		return searchBackwardsInSamePartition(trimmed, documentText, document, endOffset);
	}
	return null;
}
 
Example #18
Source File: JavaElementProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IRegion getSubject(ITextViewer textViewer, int offset) {
	if (textViewer != null && fEditor != null) {
		IRegion region= JavaWordFinder.findWord(textViewer.getDocument(), offset);
		if (region != null)
			return region;
		else
			return new Region(offset, 0);
	}
	return null;
}
 
Example #19
Source File: DocumentHelper.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * At a given position in text retrieves the region marking the word, starting before and ending on current position 
 * @param document document
 * @param documentOffset offset (position of the cursor)
 * @param detector for identification of words 
 * @return a region expanded backwards
 */
public static IRegion getRegionExpandedBackwards(IDocument document, int documentOffset, IWordDetector detector)
{

    // Use string buffer to collect characters
    int charCounter = 0;
    while (true)
    {
        try
        {

            // Read character backwards
            char c = document.getChar(--documentOffset);

            // This was the start of a word
            if (!detector.isWordPart(c))
                break;

            // Count character
            charCounter++;

        } catch (BadLocationException e)
        {

            // Document start reached, no word
            break;
        }
    }
    return new Region(documentOffset + 1, charCounter);
}
 
Example #20
Source File: HoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void hover_over_function_call() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("module arithmetics");
  _builder.newLine();
  _builder.newLine();
  _builder.append("/*");
  _builder.newLine();
  _builder.append(" ");
  _builder.append("* A mathematical constant.");
  _builder.newLine();
  _builder.append(" ");
  _builder.append("* It is approximately equal to 3.14.");
  _builder.newLine();
  _builder.append(" ");
  _builder.append("*/");
  _builder.newLine();
  _builder.append("def pi: 3.14");
  _builder.newLine();
  _builder.newLine();
  _builder.append("pi * 4;");
  _builder.newLine();
  final String text = _builder.toString();
  final String hoverText = "pi";
  int _lastIndexOf = text.lastIndexOf(hoverText);
  int _length = hoverText.length();
  final Region hoverRegion = new Region(_lastIndexOf, _length);
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("A mathematical constant.");
  _builder_1.newLine();
  _builder_1.append("It is approximately equal to 3.14.");
  this.hasHoverOver(text, hoverRegion, _builder_1.toString());
}
 
Example #21
Source File: GamlEditor.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public void applyTemplate(final Template t) {
	// TODO Create a specific context type (with GAML specific variables ??)
	final XtextTemplateContextType ct = new XtextTemplateContextType();
	final IDocument doc = getDocument();
	final ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
	final int offset = selection.getOffset();
	final int length = selection.getLength();
	final Position pos = new Position(offset, length);
	final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
	final IRegion r = new Region(offset, length);
	final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
	tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
}
 
Example #22
Source File: RenameAnalyzeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(SimpleName node) {
	VariableDeclaration decl= getVariableDeclaration(node);
	if (decl == null) {
		return super.visit(node);
	}

	IVariableBinding binding= decl.resolveBinding();
	if (binding == null) {
		return super.visit(node);
	}

	boolean keysEqual= fKey.equals(binding.getKey());
	boolean rangeInSet= fRanges.contains(new Region(node.getStartPosition(), node.getLength()));

	if (keysEqual && !rangeInSet) {
		fProblemNodes.add(node);
	}

	if (!keysEqual && rangeInSet) {
		fProblemNodes.add(node);
	}

	/*
	 * if (!keyEquals && !rangeInSet)
	 * 		ok, different local variable.
	 *
	 * if (keyEquals && rangeInSet)
	 * 		ok, renamed local variable & has been renamed.
	 */

	return super.visit(node);
}
 
Example #23
Source File: PresentationDamager.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IRegion doComputeIntersection(ITypedRegion partition, DocumentEvent e, IDocument document) {
	Iterable<ILexerTokenRegion> tokensInPartition = Iterables.filter(tokenSourceAccess.getTokens(document, false), Regions.overlaps(partition.getOffset(), partition.getLength()));
	Iterator<ILexerTokenRegion> tokens = Iterables.filter(tokensInPartition, Regions.overlaps(e.getOffset(), e.getLength())).iterator();
	if (tokens.hasNext()) {
		ILexerTokenRegion first = tokens.next();
		ILexerTokenRegion last = first;
		while(tokens.hasNext())
			last = tokens.next();
		return new Region(first.getOffset(), last.getOffset()+last.getLength() -first.getOffset());
	}
	// this shouldn't happen, but just in case return the whole partition
	return partition;
}
 
Example #24
Source File: JavaSourceViewer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Performance optimization: since we know at this place
 * that none of the clients expects the given range to be
 * untouched we reuse the given range as return value.
 * </p>
 */
@Override
protected StyleRange modelStyleRange2WidgetStyleRange(StyleRange range) {
	IRegion region= modelRange2WidgetRange(new Region(range.start, range.length));
	if (region != null) {
		// don't clone the style range, but simply reuse it.
		range.start= region.getOffset();
		range.length= region.getLength();
		return range;
	}
	return null;
}
 
Example #25
Source File: TexPairMatcher.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Matches smallest region between a pair. If there is another pair (of same type)
 * inside the region, it is taken into consideration. Example (numbers indicate
 * matching parens):
 * <pre>
 * (there is a region (inside) another region)
 * 1                   2      2               1    
 * </pre>
 * 
 * @param document
 * @param offset 
 * @return region (the pair included) between the matching pair, or <code>null</code>
 *   if there is no counterpair for the character at the offset (either it is
 *   not a matching pair character or it's pair does not exist)
 *  
 * @see org.eclipse.jface.text.source.ICharacterPairMatcher#match(org.eclipse.jface.text.IDocument, int)
 */
public IRegion match(IDocument document, int offset) {
    offset--; // we want to match pairs after we have entered the pair
                // character
    if (offset < 0)
        return null;
    try {
        int index = pairs.indexOf(document.getChar(offset));
        if (index == -1) {
            return null;
        }
        // Check for a backslash then it is no brace but a command
        if (offset > 0 && document.getChar(offset - 1) == '\\')
            return null;
        
        String docString = document.get();
        int peerIndex;
        if ((index % 2) == 1) {
            fAnchor = LatexParserUtils.RIGHT;
            peerIndex = LatexParserUtils.findPeerChar(docString, offset, fAnchor, pairs.charAt(index), 
                    pairs.charAt(index - 1));
            if (peerIndex != -1)
                return new Region(peerIndex, offset - peerIndex + 1);
        } else {
            fAnchor = LatexParserUtils.LEFT;
            peerIndex = LatexParserUtils.findPeerChar(docString, offset, fAnchor, pairs.charAt(index), 
                    pairs.charAt(index + 1));
            if (peerIndex != -1)
                return new Region(offset, peerIndex - offset + 1);
        }

    } catch (BadLocationException ble) {
        TexlipsePlugin.log("Bad location in TexPairMatcher.match()", ble);
    }
    return null;
}
 
Example #26
Source File: AbstractEObjectHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Call this method only from within an IUnitOfWork
 */
protected Pair<EObject, IRegion> getXtextElementAt(XtextResource resource, final int offset) {
	// check for cross reference
	EObject crossLinkedEObject = eObjectAtOffsetHelper.resolveCrossReferencedElementAt(resource, offset);
	if (crossLinkedEObject != null) {
		if (!crossLinkedEObject.eIsProxy()) {
			IParseResult parseResult = resource.getParseResult();
			if (parseResult != null) {
				ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
				if(leafNode != null && leafNode.isHidden() && leafNode.getOffset() == offset) {
					leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
				}
				if (leafNode != null) {
					ITextRegion leafRegion = leafNode.getTextRegion();
					return Tuples.create(crossLinkedEObject, (IRegion) new Region(leafRegion.getOffset(), leafRegion.getLength()));
				}
			}
		}
	} else {
		EObject o = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
		if (o != null) {
			ITextRegion region = locationInFileProvider.getSignificantTextRegion(o);
			final IRegion region2 = new Region(region.getOffset(), region.getLength());
			if (TextUtilities.overlaps(region2, new Region(offset, 0)))
				return Tuples.create(o, region2);
		}
	}
	return null;
}
 
Example #27
Source File: TmxFileFindReplaceImpl.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param vu
 *            The VTDNav token must at TU's SEG node;
 * @param findStr
 *            target to find in TU;
 * @param offset
 *            the start offset of TU content to begin find
 * @return The {@link FindReasult}
 * @throws VTDException
 *             ;
 */
private FindReasult forwardReadContent4Match(String subFile, VTDUtils vu, String findStr, int offset)
		throws VTDException {
	TmxInnerTagParser parser = TmxInnerTagParser.getInstance();
	String text = vu.getElementContent();
	StringBuilder b = new StringBuilder(text);
	parser.parseInnerTag(b);
	text = TextUtil.resetSpecialString(b.toString());
	if (text == null || text.length() < findStr.length()) {
		return null;
	}
	Region r = matchString(offset, text, findStr);
	if (r != null) {
		vu.getVTDNav().push();
		vu.getVTDNav().toElement(VTDNav.PARENT);
		vu.getVTDNav().toElement(VTDNav.PARENT);
		String hsid = vu.getCurrentElementAttribut("hsid", null);
		vu.getVTDNav().pop();
		if (hsid != null && hsid.length() != 0) {
			String tuIdentifier = subFile + TeCoreConstant.ID_MARK + hsid;
			if (tmxDataAccess.getDisplayTuIdentifiers().contains(tuIdentifier)) {
				return new FindReasult(r, subFile + TeCoreConstant.ID_MARK + hsid);
			}
		}
	}
	return null;
}
 
Example #28
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 #29
Source File: PyDefaultDamagerRepairer.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * This implementation damages entire lines unless clipped by the given partition.
 * </p>
 *
 * @return the full lines containing the document changes described by the document event,
 *         clipped by the given partition. If there was a partitioning change then the whole
 *         partition is returned.
 */
@Override
public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e, boolean documentPartitioningChanged) {

    if (!documentPartitioningChanged) {
        try {

            IRegion info = fDocument.getLineInformationOfOffset(e.getOffset());
            int start = Math.max(partition.getOffset(), info.getOffset());

            int end = e.getOffset() + (e.getText() == null ? e.getLength() : e.getText().length());

            if (info.getOffset() <= end && end <= info.getOffset() + info.getLength()) {
                // optimize the case of the same line
                end = info.getOffset() + info.getLength();
            } else {
                end = endOfLineOf(end);
            }

            end = Math.min(partition.getOffset() + partition.getLength(), end);
            return new Region(start, end - start);

        } catch (BadLocationException x) {
        }
    }

    return partition;
}
 
Example #30
Source File: FixedCharCountPartitionDoubleClickSelector.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IRegion getSelectedRegion(IDocument document, ITypedRegion completePartition) throws BadLocationException {
	if (fLeftBorder == 0 && fRightBorder == 0)
		return completePartition;
	if (fRightBorder == -1) {
		String delimiter = document.getLineDelimiter(document.getLineOfOffset(completePartition.getOffset()
				+ completePartition.getLength() - 1));
		if (delimiter == null)
			fRightBorder = 0;
		else
			fRightBorder = delimiter.length();
	}
	return new Region(completePartition.getOffset() + fLeftBorder, completePartition.getLength() - fLeftBorder
			- fRightBorder);
}