【问题标题】:Use own CodeFormatter in eclipse plugin with CDT在带有 CDT 的 eclipse 插件中使用自己的 CodeFormatter
【发布时间】:2019-11-17 17:43:30
【问题描述】:

我正在尝试使用扩展点org.eclipse.cdt.core.CodeFormatter,但它似乎没有效果。不幸的是,我找不到任何例子。 The extension point description 不是很全面。

我的 plugin.xml 看起来像这样:

<extension
     point="org.eclipse.cdt.core.CodeFormatter">
  <codeFormatter
        class="de.verified.rtt.ide.editors.rts.RTTLCodeFormatter"
        id="de.verified.rtt.ide.editors.rts.codeformatter"
        name="RTTL Code Formatter">
  </codeFormatter>

此扩展程序位于顶层。也许它必须在语言、文件关联、视角或其他东西中?

详细问题描述:

在我的插件中,我使用了一种通过一些关键字和概念扩展 C++ 的语言。为了解析这个文件,我正在编写我自己的扩展 GNUCPPParser 的源解析器。目前,我的解析器为 CDT 未知的令牌创建标准 IASTDeclarations。例如,对于“@rttConcept{...}”,我的解析器使用“ICPPASTNamespaceDefinition”,因为@rttConcept 在某种程度上类似于命名空间定义。现在使用“@rttConcept”不再在编辑器中创建语法错误突出显示。当尝试使用 CodeFormatter 格式化此代码时,会引发异常

org.eclipse.cdt.internal.formatter.AbortFormatting:[1/1] 意外令牌类型,预期:91,实际:令牌类型=1006 图像 =@ 偏移量=0 在 org.eclipse.cdt.internal.formatter.Scribe.printNextToken(Scribe.java:1653)

检查 NamespaceDefinition 是否真的对应于代码中的令牌“命名空间”,但它不对应。我只想用自己的 CodeFormatter 来捕捉 AbortFormatting 异常:

@SuppressWarnings("restriction")
public class MyCodeFormatter extends CCodeFormatter {

    public static final String ID = "de.blub.rtt.ide.editors.rts.codeformatter";

    @Override
    public TextEdit[] format(int kind, String source, IRegion[] regions, String lineSeparator) {
        try {
            return super.format(kind, source, regions, lineSeparator);            
        } catch(AbortFormatting ex) {
            return null;
        }
    }
}

【问题讨论】:

  • 你需要更多,如果格式化程序抛出异常,以下代码“有问题的令牌”将无法正确格式化。
  • 目前我并没有真正捕捉到异常。但即使......我还需要什么“更多”?
  • 你需要创建一个真正的格式化程序,格式化你需要的新令牌,为每个节点创建方法。看看 cdt 核心代码中的代码格式化程序访问者。尝试/捕获是不够的。

标签: java eclipse eclipse-plugin eclipse-cdt


【解决方案1】:

plugin.xml 中声明您的格式化程序只是使其可用作a 格式化程序。

如果你想将它用作当前的格式化程序,你必须在首选项UI中选择它(Preferences -> C/C++ -> Code Style -> Formatter,应该有一个drop -down 将您的格式化程序的名称作为选项之一)。

(以上选择会影响整个工作区。您也可以在项目属性 -> C/C++ 常规 -> 格式化程序中为每个项目选择格式化程序。)

也就是说,请注意 greywolf82 评论中的警告。


更新:要回答您的评论,是的,我相信可以通过 CDT 的公共 API 以编程方式更改当前的格式化程序。我希望类似以下的工作:

HashMap<String, String> options = CCorePlugin.getOptions();
options.put(CCorePreferenceConstants.CODE_FORMATTER,
            "de.verified.rtt.ide.editors.rts.codeformatter");
CCorePlugin.setOptions(options);

【讨论】:

  • 谢谢。有没有办法动态选择当前的格式化程序?这样用户就不需要这样做了。
猜你喜欢
  • 2015-12-02
  • 2019-04-23
  • 2011-08-20
  • 2012-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 2011-10-31
相关资源
最近更新 更多