在 CDT 的 eclipse 插件中使用自己的 CodeFormatter

Use own CodeFormatter in eclipse plugin with CDT

我正在尝试使用扩展点 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] Unexpected token type, expecting:91, actual:Token type=1006 image =@ offset=0 at org.eclipse.cdt.internal.formatter.Scribe.printNextToken(Scribe.java:1653)

会检查 NamespaceDefinition 是否确实对应于代码中的标记 "namespace",但实际上并不对应。我只想使用我自己的 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;
        }
    }
}

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

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

(上面的selection会影响整个工作区。你也可以在per-project的基础上选择一个格式化程序在项目属性->C/C++常规->格式化程序。 )

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


更新:为了回答您的评论,是的,我相信可以通过 CDT 的 public [=35= 以编程方式更改当前格式化程序].我希望像下面这样的东西能起作用:

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