簡體   English   中英

使用eclipse插件中的行號突出顯示jdt java文本編輯器中的文本

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

我正在嘗試編寫一個 eclipse 插件,它在用戶保存文本(ResourceChangeListener)后在 java 編輯器中突出顯示一些文本。 我正在實施ILightweightLabelDecorator並擴展BaseLabelProvider ,該方法

public void decorate(Object arg0, IDecoration arg1)

被調用,但我得到類型為 org.eclipse.jdt.internal.core.* 的對象,例如 org.eclipse.jdt.internal.core.PackageDeclaration。 我需要來自該對象的行號,以便我可以突出顯示該文本。 ASTNode 對象有一個屬性來獲取位置(行號),但我沒有得到那個。 如何從 org.eclipse.jdt.internal.core.* 對象獲取 ASTNode?

提前致謝。

PackageDeclaration是 JDT Java 模型的一部分,它是許多 Java 代碼使用的 AST 的輕量級版本。 因此,它與ASTNode

許多 Java 模型對象(包括PackageDeclaration )都實現了ISourceReference ,它告訴您有關源代碼的信息。 這包括getSourcegetSourceRange方法。

我們可以使用以下方法來訪問行號,

    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; 
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM