eclipse cdt插件:如何编程可应用c代码格式化程序

时间:2015-12-09 09:49:03

标签: eclipse-plugin format eclipse-cdt preferences

我正在为Windows 8.1上的eclipse(Kepler)CDT编写一个插件。 我的插件扩展了eclipse,使用户能够创建具有特定配置的项目。 我希望我的所有插件项目都采用相同的c代码格式。所以在我的插件代码中,在创建项目文件和配置时,我添加了以下代码以添加所需的格式:

ProjectScope scope = new ProjectScope(project);
IEclipsePreferences ref = scope.getNode("org.eclipse.cdt.core");
ref.put("org.eclipse.cdt.core.formatter.lineSplit", "100");
ref.put("org.eclipse.cdt.core.formatter.alignment_for_parameters_in_method_declaration", "18");
ref.put("org.eclipse.cdt.core.formatter.brace_position_for_block", "next_line");
ref.put("org.eclipse.cdt.core.formatter.brace_position_for_method_declaration", "next_line");
ref.put("org.eclipse.cdt.core.formatter.tabulation.char", "space");
ref.put("org.eclipse.cdt.core.formatter.alignment_for_arguments_in_method_invocation", "18");
ref.put("org.eclipse.cdt.core.formatter.alignment_for_constructor_initializer_list", "16");
ref.flush();

此代码确实可以正常工作并根据需要配置格式,但生成的格式仅存在于项目属性中,尚未应用。如果我想应用格式并导致文件以此格式显示,我必须单击 apply 按钮,或按 CTRL + SHIFT + ˚F

您是否知道应用格式可编程性的任何方法,尽管每个项目都将使用已格式化的自动生成文件生成?

2 个答案:

答案 0 :(得分:1)

您应该能够使用Eclipse菜单间谍(Alt-Shift-F2)或通过在密钥首选项中查找格式化程序的键绑定或通过将cdt.ui插件作为源插件导入来查找命令ID进入你的工作台。

当您拥有命令ID时,您可以使用命令服务execute it programmatically

答案 1 :(得分:1)

我找到了解决问题的方法。感谢@Bananewizen的帮助! 我发现ctrl + shift + f后面的命令id是:ICEditorActionDefinitionIds.FORMAT 我成功运行命令可编程性,但我必须处理文件加载以格式化其代码。所以我实现了IPartListener,在partOpened函数中,我写道:

@Override
public void partOpened(IWorkbenchPart part) {
    try {
        IFile file = (IFile) part.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
            final String cmdName = ICEditorActionDefinitionIds.FORMAT;
            IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
            try {
                handlerService.executeCommand(cmdName, null);
            } catch (Exception e) {}
    } catch (Exception e) {}
}

现在找到手柄并且效果很好!

相关问题