# Implementing a Simple Plugin

There are many applications for the leading operating systems that provide a scratch-pad or sticky note facility for the desktop display. A similar type of facility operating within the jEdit display would be a convenience. The use of dockable windows would allow the notepad to be displayed or hidden with a single mouse click or keypress (if a keyboard shortcut were defined). The contents of the notepad could be saved at program exit (or, if earlier, deactivation of the plugin) and retrieved at program startup or plugin activation.

We will keep the capabilities of this plugin modest, but a few other features would be worthwhile. The user should be able to write the contents of the notepad to storage on demand. It should also be possible to choose the name and location of the file that will be used to hold the notepad text. This would allow the user to load other files into the notepad display. The path of the notepad file should be displayed in the plugin window, but will give the user the option to hide the file name. Finally, there should be an action by which a single click or keypress would cause the contents of the notepad to be written to the new text buffer for further processing.

The full source code for QuickNotepad is contained in jEdit's source code distribution. We will provide excerpts in this discussion where it is helpful to illustrate specific points. You are invited to obtain the source code for further study or to use as a starting point for your own plugin.

## How Plugins are Loaded

Plugin API loading at startup

We will discuss the implementation of the QuickNotepad plugin, along with the jEdit APIs it makes use of. But first, we describe how plugins are loaded.

As part of its startup routine, jEdit's `main` method calls various methods to load and initialize plugins.

Additionally, plugins using the jEdit 4.2 plugin API can be loaded and unloaded at any time. This is a great help when developing your own plugins -- there is no need to restart the editor after making changes (see ).

Plugins are loaded from files with the `.jar` filename extension located in the `jars` subdirectories of the jEdit installation and user settings directories (see ).

For each JAR archive file it finds, jEdit scans its entries and performs the following tasks:

- Adds to a collection maintained by jEdit a new object of type PluginJAR. This is a data structure holding the name of the JAR archive file, a reference to the JARClassLoader, and a collection of plugins found in the archive file.

- Loads any properties defined in files ending with the extension `.props` that are contained in the archive. See .

- Reads action definitions from any file named `actions.xml` in the archive (the file need not be at the top level). See .

- Parses and loads the contents of any file named `dockables.xml` in the archive (the file need not be at the top level). This file contains BeanShell code for creating docking or floating windows that will contain the visible components of the plugin. Not all plugins define dockable windows, but those that do need a `dockables.xml` file. See .

- Checks for a class name with a name ending with `Plugin.class`.

  Such a class is known as a plugin core class and must extend jEdit's abstract EditPlugin class.

  The initialization routine checks the plugin's properties to see if it is subject to any dependencies. For example, a plugin may require that the version of the Java runtime environment or of jEdit itself be equal to or above some threshold version. A plugin can also require the presence of another plugin.

  If any dependency is not satisfied, the loader marks the plugin as broken and logs an error message.

After scanning the plugin JAR file and loading any resources, a new instance of the plugin core class is created and added to the collection maintained by the appropriate PluginJAR. jEdit then calls the `start()` method of the plugin core class. The `start()` method can perform initialization of the object's data members. Because this method is defined as an empty no-op in the EditPlugin abstract class, a plugin need not provide an implementation if no unique initialization is required.

Updating 4.1 plugins

Note that while jEdit 4.1 plugins were only loaded on startup, jEdit 4.2 plugins can be loaded at any time. As a result, the `start()` method needs to cope with being called at any time, and `stop()` needs to fully clean up after the plugin.

## The QuickNotepadPlugin Class

The major issues encountered when writing a plugin core class arise from the developer's decisions on what features the plugin will make available. These issues have implications for other plugin elements as well.

- Will the plugin provide for actions that the user can trigger using jEdit's menu items, toolbar buttons and keyboard shortcuts?

- Will the plugin have its own visible interface?

- Will the plugin have settings that the user can configure?

- Will the plugin respond to any messages reflecting changes in the host application's state?

- Should the plugin do something special when it gets focus?

Recall that the plugin core class must extend EditPlugin. In QuickNotepad's plugin core class, there are no special initialization or shutdown chores to perform, so we will not need a `start()` or `stop()` method.

The resulting plugin core class is lightweight and straightforward to implement:

-     public class QuickNotepadPlugin extends EditPlugin {
      	public static final String NAME = "quicknotepad";
      	public static final String OPTION_PREFIX = "options.quicknotepad.";
      }

  The class has been simplified since 4.1, and all we defined here were a couple of String data members to enforce consistent syntax for the name of properties we will use throughout the plugin.

- These names are used in `actions.xml` for each of the menu choices. This file is discussed in more detail in . Each action is a beanshell script.

      <!DOCTYPE ACTIONS SYSTEM "actions.dtd">
      <ACTIONS>
      	<ACTION NAME="quicknotepad.choose-file">
      		<CODE>
      			wm.addDockableWindow(QuickNotepadPlugin.NAME);
      			wm.getDockableWindow(QuickNotepadPlugin.NAME).chooseFile();
      		</CODE>
      	</ACTION>

      	<ACTION NAME="quicknotepad.save-file">
      		<CODE>
      			wm.addDockableWindow(QuickNotepadPlugin.NAME);
      			wm.getDockableWindow(QuickNotepadPlugin.NAME).saveFile();
      		</CODE>
      	</ACTION>

      	<ACTION NAME="quicknotepad.copy-to-buffer">
      		<CODE>
      			wm.addDockableWindow(QuickNotepadPlugin.NAME);
      			wm.getDockableWindow(QuickNotepadPlugin.NAME).copyToBuffer();
      		</CODE>
      	</ACTION>
      </ACTIONS>

- The names also come up in the properties file, `QuickNotePad.props` file. The properties define option panes and strings used by the plugin. It is explained in more detail in and the EditPlugin API docs.

      # jEdit only needs to load the plugin the first time the user accesses it
      # the presence of this property also tells jEdit the plugin is using the new API
      plugin.QuickNotepadPlugin.activate=defer

      # These two properties are required for all plugins
      plugin.QuickNotepadPlugin.name=QuickNotepad
      plugin.QuickNotepadPlugin.author=John Gellene

      # version number == jEdit version number
      plugin.QuickNotepadPlugin.version=4.3

      # online help
      plugin.QuickNotepadPlugin.docs=index.html

      # we only have one dependency, jEdit 4.2final, since we use the new plugin API
      plugin.QuickNotepadPlugin.depend.0=jedit 04.02.99.00

      # plugin menu
      plugin.QuickNotepadPlugin.menu=quicknotepad \
      	- \
      	quicknotepad.choose-file \
      	quicknotepad.save-file \
      	quicknotepad.copy-to-buffer

      # action labels for actions supplied by dockables.xml
      quicknotepad.label=QuickNotepad

      # action labels for actions supplied by actions.xml
      quicknotepad.choose-file.label=Choose notepad file
      quicknotepad.save-file.label=Save notepad file
      quicknotepad.copy-to-buffer.label=Copy notepad to buffer

      # plugin option pane
      plugin.QuickNotepadPlugin.option-pane=quicknotepad

      # Option pane activation BeanShell snippet
      options.quicknotepad.code=new QuickNotepadOptionPane();

      # Option pane labels
      options.quicknotepad.label=QuickNotepad
      options.quicknotepad.file=File:
      options.quicknotepad.choose-file=Choose
      options.quicknotepad.choose-file.title=Choose a notepad file
      options.quicknotepad.choose-font=Font:
      options.quicknotepad.show-filepath.title=Display notepad file path

      # window title
      quicknotepad.title=QuickNotepad

      # window toolbar buttons
      quicknotepad.choose-file.icon=Open.png
      quicknotepad.save-file.icon=Save.png
      quicknotepad.copy-to-buffer.icon=CopyToBuffer.png

      # default settings
      options.quicknotepad.show-filepath=true
      options.quicknotepad.font=Monospaced
      options.quicknotepad.fontstyle=0
      options.quicknotepad.fontsize=14

      # Setting not defined but supplied for completeness
      options.quicknotepad.filepath=

## The Property File

jEdit maintains a list of properties, which are name/value pairs used to store human-readable strings, user settings, and various other forms of meta-data. During startup, jEdit loads the default set of properties, followed by plugin properties stored in plugin JAR files, finally followed by user properties.

Some properties are used by the plugin API itself. Others are accessed by the plugin using methods in the jEdit class. Others are accessed by the scripts used by plugin packagers

See the Macros/Properties/Create Plugin Announcement macro for an example.

.

Property files contained in plugin JARs must end with the filename extension `.props`, and have a very simple syntax, which the following example illustrates:

    # Lines starting with '#' are ignored.
    name=value
    another.name=another value
    long.property=Long property value, split over \
        several lines
    escape.property=Newlines and tabs can be inserted \
        using the \t and \n escapes
    backslash.property=A backslash can be inserted by writing \\.

Now we look at a fragment from the `QuickNotepad.props` file

Examine the actual file for a more complete example

which contains properties for the QuickNotepad plugin. The first type of property data is information about the plugin itself; these are the only properties that must be specified in order for the plugin to load:

    # general plugin information
    plugin.QuickNotepadPlugin.activate=defer
    plugin.QuickNotepadPlugin.name=QuickNotepad
    plugin.QuickNotepadPlugin.author=John Gellene
    plugin.QuickNotepadPlugin.version=4.03
    plugin.QuickNotepadPlugin.docs=QuickNotepad.html
    # depends on jedit 4.2final
    plugin.QuickNotepadPlugin.depend.0=jedit 04.02.99.00
    plugin.QuickNotepadPlugin.description=A demo jEdit plugin that provides a notepad dockable.
    plugin.QuickNotepadPlugin.longdescription=description.html

These properties are each described in detail in the documentation for the EditPlugin class and do not require further discussion here.

Next in the file comes a property that sets the title of the plugin's dockable window. Dockable windows are discussed in detail in .

    # dockable window name
    quicknotepad.title=QuickNotepad

Next, we see menu item labels for the plugin's actions. All of these but the first are defined in `actions.xml` file, and that is because the dockable itself has its own actions. Actions are discussed further in .

    # action labels
    # Dockable label
    quicknotepad.label=QuickNotepad
    # Additional strings extracted from the plugin java source
    quicknotepad.choose-file.label=Choose notepad file
    quicknotepad.save-file.label=Save notepad file
    quicknotepad.copy-to-buffer.label=Copy notepad to buffer

Next, the plugin's menu is defined. See .

    # application menu items
    quicknotepad.menu.label=QuickNotepad
    quicknotepad.menu=quicknotepad - quicknotepad.choose-file \
      quicknotepad.save-file quicknotepad.copy-to-buffer

We have created a small toolbar as a component of QuickNotepad, so file names for the button icons follow:

    # plugin toolbar buttons
    quicknotepad.choose-file.icon=Open.png
    quicknotepad.save-file.icon=Save.png
    quicknotepad.copy-to-buffer.icon=Edit.png

The menu item labels corresponding to these icons will also serve as tooltip text.

Finally, the properties file set forth the labels and settings used by the option pane:

    # Option pane labels
    options.quicknotepad.label=QuickNotepad
    options.quicknotepad.file=File:
    options.quicknotepad.choose-file=Choose
    options.quicknotepad.choose-file.title=Choose a notepad file
    options.quicknotepad.choose-font=Font:
    options.quicknotepad.show-filepath.title=Display notepad file path

    # Initial default font settings
    options.quicknotepad.show-filepath=true
    options.quicknotepad.font=Monospaced
    options.quicknotepad.fontstyle=0
    options.quicknotepad.fontsize=14

    # Setting not defined but supplied for completeness
    options.quicknotepad.filepath=

PropertySideKick

There is a SideKick for Property files, provided in the JavaSideKick plugin. This gives you a compact and sorted tree view of property files.

Updating 4.1 plugins

jEdit 4.2 plugins are distinguished from jEdit 4.1 plugins by the presence of the `plugin.name.activate` property. If this property is set, the plugin is treated like a jEdit 4.2 plugin. Usually, this property should be set to `defer`. See the API documentation for the EditPlugin class for details. jEdit 4.1 plugins which have not been updated to use the 4.2 API will not be supported in jEdit 4.3.

## The EditBus

jEdit (and some plugins) generate several kinds of messages to alert plugins and other components of jedit-specific events. The message classes, all derived from EBMessage cover the opening and closing of the application, changes in the status of buffers and views, changes in user settings, as well as changes in the state of other program features. A full list of messages can be found in the org.gjt.sp.jedit.msg package.

For example, the ViewUpdate messages are all related to the jEdit View, or the top-level window. If the user creates multiple Views, a plugin may need to know when they are created or destroyed, so it would monitor ViewUpdate messages.

BufferUpdate messages are all related to jEdit buffers. They let plugins know when a buffer has become dirty, when it is about to be closed, after it is closed, created, loaded, or saved. Each of these messages are described in further detail in the API docs.

As another example, The Navigator plugin monitors a newly added (to jEdit 4.3) EBMessage of the kind BufferChanging. The BufferChanging event provides Navigator enough advance notice to save the TextArea's caret just before the current EditPane changes its active Buffer. The `BufferChanged` event, another `EditPaneUpdate` message, is thrown shortly afterward. This is not used by Navigator, but it is used by SideKick to determine when it is time to reparse the buffer.

Plugins register `EBComponent` instances with the EditBus to receive messages reflecting changes in jEdit's state.

`EBComponent`s are added and removed with the `EditBus.addToBus()` and `EditBus.removeFromBus()` methods.

Typically, the `EBComponent.handleMessage()` method is implemented with one or more `if` blocks that test whether the message is an instance of a derived message class in which the component has an interest.

    if(msg instanceof BufferUpdate) {
        // a buffer's state has changed!
    }
    else if(msg instanceof ViewUpdate) {
        // a view's state has changed!
    }
    // ... and so on

If a plugin core class will respond to EditBus messages, it can be derived from EBPlugin, in which case no explicit `addToBus()` call is necessary. Otherwise, EditPlugin will suffice as a plugin base class. Note that QuickNotepad uses the latter.

Using the Activity Log to see the EditBus

To determine precisely which EditBus messages are being sent by jEdit or the plugins, start up jEdit with an additional argument, `-log=5`. You can set an even lower log level to see further details (the default is 7). With a log level of 5 or lower, the Activity Log will include [notice]s, which will show us exactly which EditBus message is sent and when. See for more details.

## The Actions Catalog

Actions define procedures that can be bound to a menu item, a toolbar button or a keyboard shortcut. Most plugin Actions

Some plugins, such as Sidekick, Console, and ProjectViewer, create pure Java EditAction-derived Actions, based which services are available, or which files are found in a certain path. However, this is an advanced topic you can explore further in the source and API docs of those plugins.

are short scripts written in BeanShell, jEdit's macro scripting language. These scripts either direct the action themselves, delegate to a method in one of the plugin's classes that encapsulates the action, or do a little of both. The scripts are usually short; elaborate action protocols are usually contained in compiled code, rather than an interpreted macro script, to speed execution.

Actions are defined by creating an XML file entitled `actions.xml` and placing it in the plugin JAR file.

The `actions.xml` file from the QuickNotepad plugin looks as follows:

    <ACTIONS>
    	<ACTION NAME="quicknotepad.choose-file">
    		<CODE>
    			wm.addDockableWindow(QuickNotepadPlugin.NAME);
    			wm.getDockableWindow(QuickNotepadPlugin.NAME).chooseFile();
    		</CODE>
    	</ACTION>

    	<ACTION NAME="quicknotepad.save-file">
    		<CODE>
    			wm.addDockableWindow(QuickNotepadPlugin.NAME);
    			wm.getDockableWindow(QuickNotepadPlugin.NAME).saveFile();
    		</CODE>
    	</ACTION>

    	<ACTION NAME="quicknotepad.copy-to-buffer">
    		<CODE>
    			wm.addDockableWindow(QuickNotepadPlugin.NAME);
    			wm.getDockableWindow(QuickNotepadPlugin.NAME).copyToBuffer();
    		</CODE>
    	</ACTION>
    </ACTIONS>

This file defines three actions. They each use a built-in variable `wm`, which refers to the current view's DockableWindowManager. Whenever you need to obtain a reference to the current dockable, or create a new one, this is the class to use. We use the method `addDockable() followed by getDockable()` to create if necessary, and then bring up the QuickNotepad plugin dockable. This will be docked or floating, depending on how it was last used.

When an action is invoked, the BeanShell scripts address the plugin through static methods, or if instance data is needed, the current View, its DockableWindowManager, and the plugin object return by the `getDockable()` method.

If you are unfamiliar with BeanShell code, you may nevertheless notice that the code statements bear a strong resemblance to Java code, with one exception: the variable `view` is never assigned any value.

For complete answers to this and other BeanShell mysteries, see ; two observations will suffice here. First, the variable `view` is predefined by jEdit's implementation of BeanShell to refer to the current View object. Second, the BeanShell scripting language is based upon Java syntax, but allows variables to be typed at run time, so explicit types for variables need not be declared.

A formal description of each element of the `actions.xml` file can be found in the documentation of the ActionSet class.

## The dockables.xml Window Catalog

A Dockable is a window that can float like a dialog, or dock into jEdit's docking area. Each dockable needs a label (for display in menus, and on small buttons) and a title (for display in the floating window's title bar).

The jEdit plugin API uses BeanShell to create the top-level visible container of a plugin's interface. The BeanShell code is contained in a file named `dockables.xml`. It usually is quite short, providing only a single BeanShell expression used to create a visible plugin window.

The following example from the QuickNotepad plugin illustrates the requirements of the data file:

    <?xml version="1.0"?>

    <!DOCTYPE DOCKABLES SYSTEM "dockables.dtd">

    <DOCKABLES>
    	<DOCKABLE NAME="quicknotepad">
    		new QuickNotepad(view, position);
    	</DOCKABLE>
    </DOCKABLES>

In this example, the <DOCKABLE> element has a single attribute, the dockable window's identifier. This attribute is used to key a property where the window title is stored; see .

For each dockable, jedit defines an action with the same name. This means you do not need to define an explicit action to create your dockable - in fact, jEdit defines three actions: "toggle", "get" and "new floating instance" for each.

The contents of the <DOCKABLE> element itself is a BeanShell expression that constructs a new QuickNotepad object. The `view` and `position` are predefined by the plugin API as the view in which the plugin window will reside, and the docking position of the plugin. You can use `position` to customize the layout of your plugin depending on whether it appears on the sides, or the top/bottom, or as a floating dockable.

A formal description of each element of the `dockables.xml` file can be found in the documentation of the DockableWindowManager class. This class also contains the public interface you should use for getting, showing, hiding, and other interactions with the plugin's top-level windows.

## The services.xml file

A "service" is a mechanism by which one plugin can work with other plugins and avoid a bidirectional build-dependency. For example, the XML plugin "depends" on Sidekick, but in fact, it is SideKick which creates and operates on an object (a `SideKickParser`, in fact) defined in the XML plugin. In a way, the dependency is bidirectional.

Similarly, the AntFarm plugin defines but does not instantiate a `Shell` object. It is the Console plugin which creates a specific shell for each available service. SideKick and Console use the ServiceManager to search for services offered by other plugins.

Here is an example of a service from the XML plugin, which extends Sidekick:

    <!DOCTYPE SERVICES SYSTEM "services.dtd">

    <SERVICES>
            <SERVICE CLASS="sidekick.SideKickParser" NAME="xml">
                    new xml.parser.SAXParserImpl();
            </SERVICE>
    </SERVICES>

The object it returns tells Sidekick how it can parse files of a specific type. The API docs for SideKickParser indicate exactly which methods must be implemented in a plugin which offers this service. It should be enough information to let Sidekick, which has its own dockable, display the tree information in its own view.

For more information about services, refer to the ServiceManager class API documentation. There, you can find out what the tags and attributes mean, as well as how to register and use services.

## The QuickNotepad Class

Here is where most of the features of the plugin will be implemented. To work with the dockable window API, the top level window will be a JPanel. The visible components reflect a simple layout. Inside the top-level panel we will place a scroll pane with a text area. Above the scroll pane we will place a panel containing a small tool bar and a label displaying the path of the current notepad file.

We have identified three user actions that need implementation here: `chooseFile()`, `saveFile()`, and `copyToBuffer()`. As noted earlier, we also want the text area to change its appearance in immediate response to a change in user options settings. In order to do that, the window class must respond to a PropertiesChanged message from the EditBus.

Unlike the EBPlugin class, the EBComponent interface does not deal with the component's actual subscribing and unsubscribing to the EditBus. To accomplish this, we use a pair of methods inherited from the Java platform's JComponent class that are called when the window is made visible, and when it is hidden. These two methods, `addNotify()` and `removeNotify()`, are overridden to add and remove the visible window from the list of EditBus subscribers.

We will provide for two minor features when the notepad is displayed in the floating window. First, when a floating plugin window is created, we will give the notepad text area input focus. Second, when the notepad if floating and has input focus, we will have the Escape key dismiss the notepad window. An AncestorListener and a KeyListener will implement these details.

Here is the listing for the data members, the constructor, and the implementation of the EBComponent interface:

    public class QuickNotepad extends JPanel
        implements EBComponent
    {
        private String filename;
        private String defaultFilename;
        private View view;
        private boolean floating;

        private QuickNotepadTextArea textArea;
        private QuickNotepadToolPanel toolPanel;

        //
        // Constructor
        //

        public QuickNotepad(View view, String position)
        {
            super(new BorderLayout());

            this.view = view;
            this.floating = position.equals(
                DockableWindowManager.FLOATING);

            this.filename = jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX
                + "filepath");
            if(this.filename == null || this.filename.length() == 0)
            {
                this.filename = new String(jEdit.getSettingsDirectory()
                    + File.separator + "qn.txt");
                jEdit.setProperty(QuickNotepadPlugin.OPTION_PREFIX
                    + "filepath",this.filename);
            }
            this.defaultFilename = new String(this.filename);

            this.toolPanel = new QuickNotepadToolPanel(this);
            add(BorderLayout.NORTH, this.toolPanel);

            if(floating)
                this.setPreferredSize(new Dimension(500, 250));

            textArea = new QuickNotepadTextArea();
            textArea.setFont(QuickNotepadOptionPane.makeFont());
            textArea.addKeyListener(new KeyHandler());
            textArea.addAncestorListener(new AncestorHandler());
            JScrollPane pane = new JScrollPane(textArea);
            add(BorderLayout.CENTER, pane);

            readFile();
        }

        //
        // Attribute methods
        //

        // for toolBar display
        public String getFilename()
        {
            return filename;
        }

        //
        // EBComponent implementation
        //

        public void handleMessage(EBMessage message)
        {
            if (message instanceof PropertiesChanged)
            {
                propertiesChanged();
            }
        }

        private void propertiesChanged()
        {
            String propertyFilename = jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX + "filepath");
            if(!defaultFilename.equals(propertyFilename))
            {
                saveFile();
                toolPanel.propertiesChanged();
                defaultFilename = propertyFilename.clone();
                filename = defaultFilename.clone();
                readFile();
            }
            Font newFont = QuickNotepadOptionPane.makeFont();
            if(!newFont.equals(textArea.getFont()))
            {
                textArea.setFont(newFont);
                textArea.invalidate();
            }
        }

        // These JComponent methods provide the appropriate points
        // to subscribe and unsubscribe this object to the EditBus

        public void addNotify()
        {
            super.addNotify();
            EditBus.addToBus(this);
        }

        public void removeNotify()
        {
            saveFile();
            super.removeNotify();
            EditBus.removeFromBus(this);
        }

        ...

    }

This listing refers to a QuickNotebookTextArea object. It is currently implemented as a JTextArea with word wrap and tab sizes hard-coded. Placing the object in a separate class will simply future modifications.

## The QuickNotepadToolBar Class

There is nothing remarkable about the toolbar panel that is placed inside the QuickNotepad object. The constructor shows the continued use of items from the plugin's properties file.

    public class QuickNotepadToolPanel extends JPanel
    {
        private QuickNotepad pad;
        private JLabel label;

        public QuickNotepadToolPanel(QuickNotepad qnpad)
        {
            pad = qnpad;
            JToolBar toolBar = new JToolBar();
            toolBar.setFloatable(false);

            toolBar.add(makeCustomButton("quicknotepad.choose-file",
                new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        QuickNotepadToolPanel.this.pad.chooseFile();
                    }
                }));
            toolBar.add(makeCustomButton("quicknotepad.save-file",
                new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        QuickNotepadToolPanel.this.pad.saveFile();
                    }
                }));
            toolBar.add(makeCustomButton("quicknotepad.copy-to-buffer",
                new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        QuickNotepadToolPanel.this.pad.copyToBuffer();
                    }
                }));
            label = new JLabel(pad.getFilename(),
                SwingConstants.RIGHT);
            label.setForeground(Color.black);
            label.setVisible(jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX
                + "show-filepath").equals("true"));
            this.setLayout(new BorderLayout(10, 0));
            this.add(BorderLayout.WEST, toolBar);
            this.add(BorderLayout.CENTER, label);
            this.setBorder(BorderFactory.createEmptyBorder(0, 0, 3, 10));
        }

        ...

    }

The method makeCustomButton() provides uniform attributes for the three toolbar buttons corresponding to three of the plugin's use actions. The menu titles for the user actions serve double duty as tooltip text for the buttons. There is also a `propertiesChanged()` method for the toolbar that sets the text and visibility of the label containing the notepad file path.

## The QuickNotepadOptionPane Class

Using the default implementation provided by AbstractOptionPane reduces the preparation of an option pane to two principal tasks: writing a `_init()` method to layout and initialize the pane, and writing a `_save()` method to commit any settings changed by user input. If a button on the option pane should trigger another dialog, such as a JFileChooser or jEdit's own enhanced VFSFileChooserDialog, the option pane will also have to implement the ActionListener interface to display additional components.

The QuickNotepad plugin has only three options to set: the path name of the file that will store the notepad text, the visibility of the path name on the tool bar, and the notepad's display font. Using the shortcut methods of the plugin API, the implementation of `_init()` looks like this:

    public class QuickNotepadOptionPane extends AbstractOptionPane
          implements ActionListener
    {
        private JTextField pathName;
        private JButton pickPath;
        private FontSelector font;

        ...

        public void _init()
        {
            showPath = new JCheckBox(jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX
                + "show-filepath.title"),
            jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX +  "show-filepath")
                .equals("true"));
            addComponent(showPath);

            pathName = new JTextField(jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX
                + "filepath"));
            JButton pickPath = new JButton(jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX
                + "choose-file"));
            pickPath.addActionListener(this);

            JPanel pathPanel = new JPanel(new BorderLayout(0, 0));
            pathPanel.add(pathName, BorderLayout.CENTER);
            pathPanel.add(pickPath, BorderLayout.EAST);

            addComponent(jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX + "file"),
                pathPanel);

            font = new FontSelector(makeFont());
            addComponent(jEdit.getProperty(
                QuickNotepadPlugin.OPTION_PREFIX + "choose-font"),
                font);
        }

        ...

    }

Here we adopt the vertical arrangement offered by use of the `addComponent()` method with one embellishment. We want the first row of the option pane to contain a text field with the current notepad file path and a button that will trigger a file chooser dialog when pressed. To place both of them on the same line (along with an identifying label for the file option), we create a JPanel to contain both components and pass the configured panel to `addComponent()`.

The `_init()` method uses properties from the plugin's property file to provide the names of label for the components placed in the option pane. It also uses a property whose name begins with `PROPERTY_PREFIX` as a persistent data item - the path of the current notepad file. The elements of the notepad's font are also extracted from properties using a static method of the option pane class.

The `_save()` method extracts data from the user input components and assigns them to the plugin's properties. The implementation is straightforward:

    public void _save()
    {
        jEdit.setProperty(QuickNotepadPlugin.OPTION_PREFIX
            + "filepath", pathName.getText());
        Font _font = font.getFont();

        jEdit.setProperty(QuickNotepadPlugin.OPTION_PREFIX
            + "font", _font.getFamily());
        jEdit.setProperty(QuickNotepadPlugin.OPTION_PREFIX
            + "fontsize", String.valueOf(_font.getSize()));
        jEdit.setProperty(QuickNotepadPlugin.OPTION_PREFIX
            + "fontstyle", String.valueOf(_font.getStyle()));
        jEdit.setProperty(QuickNotepadPlugin.OPTION_PREFIX
            + "show-filepath", String.valueOf(showPath.isSelected()));
    }

The class has only two other methods, one to display a file chooser dialog in response to user action, and the other to construct a Font object from the plugin's font properties. They do not require discussion here.

## Plugin Documentation

While not required by the plugin API, a help file is an essential element of any plugin written for public release. A single web page is often all that is required. There are no specific requirements on layout, but because of the design of jEdit's help viewer, the use of frames should be avoided. Topics that would be useful include the following:

- a description of the purpose of the plugin;

- an explanation of the type of input the user can supply through its visible interface (such as mouse action or text entry in controls);

- a listing of available user actions that can be taken when the plugin does not have input focus;

- a summary of configuration options;

- information on development of the plugin (such as a change log, a list of to do items, and contact information for the plugin's author); and

- licensing information, including acknowledgments for any library software used by the plugin.

The location of the plugin's help file is stored in the `plugin.QuickNotepad.docs` property; see .

## The build.xml Ant build file

We have already outlined the contents of the user action catalog, the properties file and the documentation file in our earlier discussion. The final step is to compile the source file and build the archive file that will hold the class files and the plugin's other resources.

Publicly released plugins include with their source a makefile in XML format for the Ant utility. The format for this file requires few changes from plugin to plugin. Here is a version of `build.xml` that could be used by QuickNotepad:

    <project name="QuickNotepad"
             default="build">
        <description>
            This is an ant build.xml file for building the QuickNotepad plugin for jEdit.
        </description>
        <property name="user-doc.xml"
              value="users-guide.xml" />
        <property file="build.properties" />
        <property file="../build.properties" />
    	<property name="build.support"
    			  value="../../../build-support" />
        <import file="${build.support}/plugin-build.xml" />
    </project>

This build file imports another modular build file, `plugin-build.xml` from the `build-support` project. It is available as a package you can check out from subversion, or found online in the jEdit's SVN repository. It contains the common build steps used to build the core jEdit plugins, and some example `build.properties.sample` files which you can adapt for use with your development environment.

Customizing this build file for a different plugin will likely only require three changes to build.xml file:

- the name of the project

- the dependencies of the plugin

- The extra files that need to be copied into the jar.

Because this build file and the one of most plugins import a `build.properties` file from the current and the parent directories, it is possible to build most of jEdit's plugins in a uniform way by setting the common properties in a single `build.properties` file, placed in the plugin source's parent directory.

For a full discussion of the `Ant` file format and command syntax, you should consult the Ant documentation, also available through jEdit's help system if you installed the Ant Plugin. When editing Ant build files, the XML plugin gives you completion tips for both elements and attributes. The Console plugin provides you with an ANT button which you can bind to keyboard actions. In addition, there are the AntFarm and Antelope plugins which also proivde you with alternate means to execute Ant targets through the Console.

## Reloading the Plugin

Once you have compiled your plugin, you will need to test its behavior when it is reloaded. Follow these steps to reload your plugin without restarting jEdit:

- From the Plugins menu open the Plugin Manager.

- On the Manage tab uncheck Hide libraries. This will allow you to see plugins that are not loaded.

- Find the plugin on the Manage tab and uncheck it. This will unload the plugin. You will get a warning if this plugin does not support dynamic reloading. If you get that warning you will need to restart jEdit to reload the plugin until the plugin is converted over to the 4.2 API.

- Recheck the plugin to reload it.

The Activator plugin provides a very convenient (dockable) way to test the activating and reloading behavior of your plugin. Be sure to test your plugin's reloading behavior with both the Activator and the Reloader tabs.

If you have reached this point in the text, you are probably serious about writing a plugin for jEdit. Good luck with your efforts, and thank you for contributing to the jEdit project.

## Tips for debugging plugins

#### BeanShell

jEdit includes a Beanshell interface into its currently running JVM at all times. You can access it a variety of ways, but one way is from `Plugins - Console - Shells - BeanShell`. From here, you can interactively inspect the values of any object in memory, call any of its member functions, or create new instances of any class that is currently loaded by jEdit or any of its plugins. All this, without setting any breakpoints!

If you're too lazy to type each Beanshell statement interactively, you can also create debugging code snippets as macros and invoke them from `utilities - beanshell - evaluate selection`, or `Macros - Misc - Evaluate Buffer in Beanshell`, or place the file in your own macros directory and bind it to its own keyboard shortcut.

#### Other useful tips

This section is new but will be expanded shortly. Please post suggestions to the `jedit-devel` mailing list.