nilesh virkar
nilesh virkar

Reputation: 459

Highlight text from jdt java text editor using line numbers in eclipse plugin

I am trying to write an eclipse plugin which highlights some text in java editor after user save the text (ResourceChangeListener). I am implementing ILightweightLabelDecorator and extending BaseLabelProvider, The method

public void decorate(Object arg0, IDecoration arg1)

getting called but I am getting Objects of type org.eclipse.jdt.internal.core.* e.g org.eclipse.jdt.internal.core.PackageDeclaration. I need line numbers from that object so I can highlight that text. ASTNode object has a property to get the position (line numbers) but I am not getting that one. How can I get ASTNode from org.eclipse.jdt.internal.core.* objects?

Thanks in advance.

Upvotes: 1

Views: 104

Answers (2)

nilesh virkar
nilesh virkar

Reputation: 459

We can use the following method for accessing line number,

    private int getLineNumberInSource(SourceRefElement member) throws 
JavaModelException { 
    if (member == null || !member.exists()) { 
        return -1; 
    } 
    ICompilationUnit compilationUnit = member.getCompilationUnit(); 
    if (compilationUnit == null) { 
        return -1; 
    } 
    String fullSource = compilationUnit.getBuffer().getContents(); 
    if (fullSource == null) { 
        return -1; 
    } 
    ISourceRange nameRange = member.getNameRange(); 
    if (nameRange == null) { 
        return -1; 
    } 
    String string2 = fullSource.substring(0, nameRange.getOffset()); 
    return 
            string2.split(compilationUnit.findRecommendedLineSeparator()).length; 
} 

Upvotes: 0

greg-449
greg-449

Reputation: 111142

PackageDeclaration is part of the JDT Java Model which is a lighter weight version of the AST used by a lot of the Java code. As such it isn't related to ASTNode.

Many Java Model objects (including PackageDeclaration) implement ISourceReference which tells you about the source code. This includes getSource and getSourceRange methods.

Upvotes: 1

Related Questions