Write inserts for Eclipse ----- Simple Editor

xiaoxiao2021-03-06  67

Writing a plugin for Eclipse is a wonderful thing, just like a two creation in a great artistic work, this feeling is really good. Through this article I hope to help some people interested in Eclipse, especially beginners to experience this feeling, so I decided to write these things. In the area of ​​Coding, I have such an idea: The Simpler IS, The More Useful it is. Especially in the area you are not familiar, this law is especially suitable, so I decided to show Eclipse in a simple way. The wonderful place, of course, on the other hand, it is not enough excuse for his own level :)

Then let me start from Editor, such a many applications, especially text-related programs, which is also a basic part of many plugins. Let's learn how to build your own editor in Eclipse. Our Editor is aimed at the Namespace2Package.mappings file, you may feel unfamiliar, it is a file in the development of grid, don't worry, it is just a file of Name = Value, just like Property in Java. File is the same. Probably this look:

OK, this file is dead, and it consumes it in the future. What kind of effect I hope? I want to give it a grammar color, so it is easy to distinguish Name and Value, just like this:

I will call this editor for mappingeditor, I only take a name.

In the book of David Gallardo, he gives a complete example of writing a log4j plugin, including a part of an Editor, and an example of an XML Editor's complete part of the plug-in-in-IN in Eclipse. Routine. The former project is too large, including a lot of writing plugins, but in key parts, he did not give a complete and clear concept and context, when you see it, it will feel very halo. The latter has a clear concentrate, the code is clear, but unfortunately there is not enough annotation to help you understand the concept, so you have to check the API help, then update your concept again, then get the right Conclusion. Of course, learning to write Editor is the help of Eclipse comes with the help, HelpàPlatform Plug-in Developer GuideàProgrammer's Guidepen, which introduces enough concept, some of which make people feel very unfamiliar, and have no Run's code, so you are sure I feel not addiction. So here I want to give a compromise, I explain some important core concepts, try to use a simple method, then give Run's code, which is quite a framework, let you modify it on it. Meet the kind of psychology we have ever had :) But don't expect me to be responsible for me, I just say that I understand their understanding, everyone may have his own understanding, so if you think I am wrong , Very welcome to discuss with me.

Although MappingediTor is simple, it covers almost all concepts and main steps written by Editor, I will try out which is what you have to pay attention to, and what is Eclipse to lay the foundation for you, I will tell you what to write? Part is to build your own editor, Well, I will try my best.

Before you begin, you have to prepare, write plugins, not as simple as you think, you may have seen some articles about Eclipse, mostly depicted a beautiful scene, but in fact, when you do it, you are not so. Wonderful, this is a universal reason. You only have to look at how many basic classes in EDITOR Eclipse can be understood. Abstract interfaces and some interfaces are achieved, there must be nearly 100, and if there is no help, it is really difficult to get some shortprints. But don't be too scared, the editor plug-in has existed an Frameworks, Eclipse has made these, as long as you understand this frameworks, then what you have to complete is just a small part, of course, this is relative to Eclipse Those who are. Understanding a Frameworks is the understanding of its design concept, here I also want to emphasize and highlight the interpretation of the concept, I hope I can do it.

I am really coming now.

In Eclipse, an editor is a complex embodying the MVC mode, which includes a visual partial (VIEW), a data to be processed, an editor input (Model), also has a control section, you can It is believed that the control part is Editor itself, but it is actually a few assistant class. Since the content we handle is fundamentally text, another framework in Eclipse is also used, which is Text Frameworks, Eclipse has always been used with this framework to process text content. Remembering them is enough to handle text. From our point of view, it is just some practical classes, so there is no need to know too profound, because I know it is not deep :)

Let us look at Editor's structure from overall

This is what we can easily understand in reality, can not be simple, MVC, drawing the above picture is simply a waste of time. Now map it into Eclipse and see what it is. Each name in the picture box corresponds to a class in Eclipse, and they are the classes we have to inherit.

The overall structure is the case, the green part is the part we need to extend.

A editor has many features, the most basic, copy, paste, these basic functions, Eclipse, of course, will not bear to let you go to God, they have been implemented by TextEditor, so the focus is not here. I want to achieve syntax coloring, it is the content related to display, so you can think of it, you should be related to the SourceViewerConfiguration class above. In the future, I may join the contents of Content Assist, buried a film :)

The following begins to explain:

TextEditor is a core class, which looks like a class hierarchy, which will find it has a lot of Fields, a FileDocumNetProvider, a sourceview, a sourceViewerConfiguration, which is through setting these fields, our Editor is different from other Editor, thus Realize your own unique features. From a new point of view, this way is similar to IOC, control reversal; another model of the model is Templete mode. We inherit the TextEditor to implement MappingEditor, which complete our settings.

Note: In order to reduce the space, only the core code is given, I omitted the package, IMPORT part, the complete code and the Eclipse project file can be downloaded out in the end of the text. Mappingeditor.java

Public class mappingeditor extends textEditor {

Private ColorManager ColorManager;

Public mappingeditor () {

Super ();

ColorManager = new colorManager ();

SetSourceViewerConfiguration

NEW MAPPINGCONFIGURATION (ColorManager);

SetDocumentProvider (New MappingDocumentProvider ());

}

Public void dispose () {

ColorManager.dispose ();

Super.dispose ();

}

}

ColorManager is a class that we implemented to manage color resources, because these system resources in SWT are colors such as heavyweight resources, and unified management is a better solution. The code is very simple, entry is clear.

ColorManager.java

Public class colorManager {

Protected map fcolortable = new hashmap (10);

Public void dispose () {

Iterator E = fcolortable.values ​​(). Iterator ();

While (E.hasNext ())

(Color) E.NEXT ()). Dispose ();

}

Public Color GetColor (RGB RGB) {

Color Color = (color) fcolortable.get (RGB);

IF (color == NULL) {

Color = New color (), RGB);

FCOLORTABLE.PUT (RGB, Color);

}

Return Color;

}

}

Also use several constants about colors, put them in the IColorConstans interface

Public interface icilconstants {

RGB Name = New RGB (0x33, 0x33, 0xFF);

RGB Value = New RGB (0xFF, 0x33, 0x33);

}

MappingDocumentProvider Inherits from FileDocumNetProvider, used to transform the file type to the unified format Document capable of handling it, and we need to implement this conversion.

MappingDocumentProvider.java

Public class mappingDocumentProvider Extends FileDocumentProvider {

Protected IDocument CreateDocument (Object Element) throws coreException {

Idocument Document = Super.Createdocument (Element);

IF (Document! = null) {

IDocumentPartitioner Partitioner =

New defaultPartitioner

New mappingPartitionscanner (),

NEW STRING [] {] {

MappingPartitionscanner.xml_tag,

MappingPartitionscanner.xml_Comment}; Partitioner.Connect (Document);

Document.SetDocumentPartitioner (Partitioner);

}

Return Document;

}

}

MappingPartitionscanner class inherits from RulebasedPartitionscanner

There is another conceptual partitions, a partition is part of the document, so that we can handle the different parts of the document, you can predict that this should be related to the color of the grammar. Remember that these parts do not overlap each other, not that part belongs to two partitions. The partition division should be implemented when completing the file to Document, where there must be a tool to divide the IDocument (i representation interface) into different partitions, which is IDocumentPartitioner. We need to achieve such an IDocumentPartitioner, which is MappingPartitionscanner.

Then the next question is what we are divided into principles? Eclipse provides a way similar to natural language, through rules, a rule is an Irule, we tell Partitioner we want to use, which will install rules to divide documents into different parts. Standing on a high angle to see these problems, everything is so simple and reasonable. There is no framework for Irule, which is available. Eclipse provides several simple but common rules, but this is far less than our complex demand, we need to write your own rule, whether it is inherited Existing Rule is still a defined IRULE interface, and this requires some techniques and wisdom. Here, mappingeditor divides the document into two parts, one part represents the content of Value, named mapping_value, does not need to divide the Name content into a part, because in addition to value, the remaining default part is Name, use Idocument.default_content_type is represented behind.

Let's take a look at the implementation of the MappingPartitionscanner class:

Public class mappingPartitionscanner extends rulebasedpartitionscanner {

Public final static string mapping_value = "__mapping_value";

Public mappingPartitionscanner () {

IToken tag = new token (mapping_value);

Ipredicaterule [] rules = new ipredicaterule [1];

Rules [0] = New SingleLineRule ("=", NULL, TAG, (CHAR) 0, TRUE

SetPredicaterules (Rules);

}

}

It can be seen that we use an Eclispe to provide a simple Rule-SingLeLineRule (), which is a part of the code in each line of the text.

Now we have divided the document into a different part, this is not the foundation for the realization of grammar color?

Eclispe provides another powerful framework to handle text, which is Text Frameworks. Text Frameworks uses a mode called the destroyer (Repaire), the regulator (Reconciling) to implement syntax color, when we modify some of the document, what parties need to be calculated to be redisplayed, this is damage. Destruction will return a zone to repair to provide the correct display. The regulator runs through both, and the regulator monitors the change of the document, and then notifies the destroyer, the destroyer calculates the changed portion, and then tells the fixer to it. The settings of the destroyer, the repairman, and regulators are set in SourceViewerConfiguration, as previously described, which are used to control the display portion.

MappingConfiguration.java

Public class mappingconfiguration extends SourceViewERCONFIGURATION {

Private ColorManager ColorManager;

Private rulebasedscanner namecanner;

Private rulebasedscanner valuescanner;

Public MappingConfiguration (ColorManager ColorManager) {

This.colorManager = ColorManager;

}

Public String [] getConfiguredContentTypes (isourceViewer SourceViewer) {

Return new string [] {

Idocument.default_content_type,

MappingPartitionscanner.mapping_value};

}

protected rulebasedscanner getnamescanner () {

IF (Namescanner == NULL) {

Namescanner = new rulebasedscanner ();

Namescanner.SetDefaultreturntoken

NEW token

New TextAttribute (

ColorManager.getColor (iColorConstants.name)))))))))

}

Return Namescanner;

}

protected rulebasedscanner getValuescanner () {

IF (VALUESCANNER == NULL) {

VALUESCANNER = New rulebasedscanner ();

VALUESCANNNER.SETDEFAULTRETURNTOKEN

NEW token

New TextAttribute (

ColorManager.getColor (iColorConstants.Value))))))))))

}

Return Valuescanner;

}

Public IpresentationReconciler getPresentationReconciler (isourceViewer SourceViewer) {

PresentationReconcilr reconciler = new presentationReconciler ();

DefaultDamagerRepairer DR =

New DefaultDamagerRepaire (getValuescanner ());

Reconciler.SetDamager (DR, mappingPartitionscanner.mapping_value);

Reconciler.SetRepairer (DR, mappingPartitionscanner.mapping_value); Dr = New DefaultDamagerRepaire (getnamescanner ());

Reconciler.SetDamager (DR, Idocument.default_Content_Type);

Reconciler.SetRepairer (DR, IDocument.default_content_type);

Return Reconciler;

}

}

The getConfigureDContentTypes () method tells the Editor document which part of the part.

GetPresentationReconciler () Method Sets the contents of the mappingeditor, which contains the following main contents.

We are not prepared to achieve too complicated Damager and Repairer, so we use the Eclispe default class, in this method, we set different Damager and Repairer for different partitions. When you create Damager and Repairer, you need to pass an ITOKENSCANNER. A ITOKENSCANNER is used to look for token in a partition, where we use a specific implementation rulebasedscanner, which looks for token according to rules, and RuleBaseDPartitionscanner is the same. Because Name in Mappingeditor is Name, Value is Value, which will not further divide in the Name or Value's partition, so we don't have to set any rules, and make the entire partition as a token, so we just tell tokenscanner The Token returned by default, it is set by SetDefaultReturNToken (Itoken token). If you want to achieve a keyword, you must implement a specific RuleBascanner yourself. One of the remaining problems is there, the implementation of the Token class is very simple, just a class containing Object, we will join a TextAttribute property that sets token colors to TOKEN. So when Editor wants to display this token, the Damager / Repairer mechanism will show us to us according to this property, everything is like this.

Introduction to some concepts, I will write every step in implementing the plugin in detail, just hope that beginners don't miss anything, for high-level comrades, you can ignore these, but focus on the concept, you are likely to put forward the concept Your better view, then please contact me, let's explore and improve :)

Eclipse's version update is somewhat too fast, of course, to a large extent, there is no impact on our plug-in, of course, there are places to pay attention to. I recommend using the "Super Stable" version, here I use M7.

Let's begin.

Newly built a plug-in engineering (PLUG_IN Project), entering the project's name org.tsinghua.plugins.mappingeditor, no special meaning, click Next, enter the plug-in project structure page, no need to modify anything, click Next, enter Plug-in content, I fill in your own ID in the provider name, and other use default options are enough. Click Finish, a plugin engineering framework is built, and it is added to the inside. Let's take a look at this plug-in engineering, there is the following directory structure in the Eclipse's package cost, mappingeditorPlugin.java is the main class of the plugin. As the core of the plugin, it is generally saved some global things. Due to the plugin we have to write. It's too simple, so there is no need to modify it at all.

The next step is to be able to run for our plug-in, you need to introduce some packages:

Right-click the project, select the Libraries page àadd external jars on the right side of PropertiesàJava Build Pathà, and then add the following packages below the project:

Org.eclipse.ui.editors_3.0.0 / Editors.jar

Org.eclipse.jface.text_3.0.0 / jfacetext.jar

Org.eclipse.text_3.0.0 / text.jar

Org.eclipse.ui.Workbench.texteditor_3.0.0 / Texteditor.jar

How do you know which packs I want to use, this is a problem with experience and knowledge, there is not a simple way, you need to learn slowly during the process of writing code.

Next we have to introduce other plugins for our Editor plug-in project. If you understand the eclipse plugin architecture, we will understand that our plugin cannot work separately, it needs to work with other plugins, especially as EDitor is like an Eclipse extension, just like starting me, if we don't have a great artwork, we will not do anything.

Open the plug-in.xml plugin description file, select Dependencies, fill it

Org.eclipse.jface.text

Org.eclipse.ui.EDITORS

Org.eclipse.ui.Workbench.texteditor

Three plugins

OK, so far, some preparation work is done, and now you can focus on the code. Create a new Org.tsinghua.plugins.mappingeditor.editors package, add the class code mentioned before.

After the code is written, you have to enter the last job, we want to extend the Eclipse's Editor extension, register our Editor When we try to open a namespace2package.mappings file, the Eclipse platform calls our Editor, so we have to tell Eclipse Some of our information is the concept of Eclipse extension.

Go to Plugin.xml, click on the extensions page below, click the Add button,

Select Generic Wizards à Schema-based Extension, as shown above:

Select the org.eclipse.ui.editors extension point, do not modify other, then press Finish to end, then the result is this:

Then we fill a Editor:

The rest is to modify the properties of this extension point, tell Eclipse what we did.

The class attribute is our Editor class:

Org.tsinghua.plugins.mappingeditor.editors.mappingeditor

Default: True

Indicates this Editor as the default editor that opens our specified file.

Filenames:

That is to specify the file type to be processed by Mappingeditor, here is a full name Namespace2Package.MAppings, we can specify files with a feature extension by setting an Extensions property.

Icon: Specify an icon for mappingeditor

Run the plugin, menu run-run .., configure a plug-in running environment as shown below:

Double-click on the left MappingEditor running the configuration file or select Run - Run AS - 5 Run-Time Workbench running plugins, open the namespace2Package.mappings file in Workbench.

Let's take a look at the final effect.

Author: oosky @ smth

Mail: wzt@mails.tsinghua.edu.cn

转载请注明原文地址:https://www.9cbs.com/read-119544.html

New Post(0)