Eclipse RCP: programmatically associate file type with Editor?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 10:04:52

问题


How programmatically associate file type with Editor?

That is what Eclipse-RCP Java code can do what is archived with the following UI interaction:

Window -> Preferences
General -> Editors -> File Associations
Add... > File type: *.json
Select *.json file type 
Add... (Associated editors) > JavaScript Editor
Make it default

Ralated to Q
https://stackoverflow.com/questions/12429221/eclipse-file-associations-determine-which-editor-in-list-of-associated-editors
Eclipse: associate an editor with a content type
Get associated file extensions for an Eclipse editor
Opening a default editor, on a treeviewer selection eclipse rcp(eg: as eclipse knows that j.java files must be opened in text editor)

eclipse rcp change icon for xml configuration file


回答1:


I know your questions says "programmatically" but I'll give a complete run down of the methods.

If you are writing the plugin that provides the editor, then you should simply declare the extension in your plugin.xml.

   <extension
         point="org.eclipse.ui.editors">
      <editor
            ...
            extensions="json"
            ...

If you are distributing a complete RPC application, you can edit the plugin.xml for the plugin that provides the editor or add a plugin that just refers to that editor.

But, if you have to do it programmatically, you are manipulating the internals of an RPC instance. Eclipse does not provide a public API for that but this code will do it:

            // error handling is omitted for brevity
    String extension = "json";
    String editorId = "theplugin.editors.TheEditor";

    EditorRegistry editorReg = (EditorRegistry)PlatformUI.getWorkbench().getEditorRegistry();
    EditorDescriptor editor = (EditorDescriptor) editorReg.findEditor(editorId);
    FileEditorMapping mapping = new FileEditorMapping(extension);
    mapping.addEditor(editor);
    mapping.setDefaultEditor(editor);

    IFileEditorMapping[] mappings = editorReg.getFileEditorMappings();
    FileEditorMapping[] newMappings = new FileEditorMapping[mappings.length+1];
    for (int i = 0; i < mappings.length; i++) {
        newMappings[i] = (FileEditorMapping) mappings[i];
    }
    newMappings[mappings.length] = mapping;
    editorReg.setFileEditorMappings(newMappings);



回答2:


Associating file type means associating content of ur editor with a predefined one. This can be easily achieved via plugin.xml.. Just follow the following link:-

Eclipse help Documentation

http://help.eclipse.org/indigo/index.jsp

and search for org.eclipse.core.contenttype.contentTypes.



来源:https://stackoverflow.com/questions/15877123/eclipse-rcp-programmatically-associate-file-type-with-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!