3

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

Community
  • 1
  • 1
Paul Verest
  • 60,022
  • 51
  • 208
  • 332

2 Answers2

4

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);
Tom Blodget
  • 20,260
  • 3
  • 39
  • 72
1

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.

Richa
  • 94
  • 10
  • ContentType may be too complicated option http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fruntime_content_contributing.htm&cp=2_0_3_4_1 – Paul Verest Dec 26 '13 at 10:32