# Macro Tips and Techniques

## Getting Input for a Macro

The dialog-based macro discussed in reflects a conventional approach to obtaining input in a Java program. Nevertheless, it can be too lengthy or tedious for someone trying to write a macro quickly. Not every macro needs a user interface specified in such detail; some macros require only a single keystroke or no input at all. In this section we outline some other techniques for obtaining input that will help you write macros quickly.

### Getting a Single Line of Text

As mentioned earlier in , the method `Macros.input()` offers a convenient way to obtain a single line of text input. Here is an example that inserts a pair of HTML markup tags specified by the user.

    // Insert_Tag.bsh

    void insertTag()
    {
        caret = textArea.getCaretPosition();
        tag = Macros.input(view, Enter name of tag:);
        if( tag == null || tag.length() == 0) return;
        text = textArea.getSelectedText();
        if(text == null) text = ;
        sb = new StringBuffer();
        sb.append(<).append(tag).append(>);
        sb.append(text);
        sb.append(</).append(tag).append(>);
        textArea.setSelectedText(sb.toString());
        if(text.length() == 0)
            textArea.setCaretPosition(caret + tag.length() + 2);
    }

    insertTag();

    // end Insert_Tag.bsh

Here the call to `Macros.input()` seeks the name of the markup tag. This method sets the message box title to a fixed string, Macro input, but the specific message Enter name of tag provides all the information necessary. The return value `tag` must be tested to see if it is null. This would occur if the user presses the Cancel button or closes the dialog window displayed by `Macros.input()`.

### Getting Multiple Data Items

If more than one item of input is needed, a succession of calls to `Macros.input()` is a possible, but awkward approach, because it would not be possible to correct early input after the corresponding message box is dismissed. Where more is required, but a full dialog layout is either unnecessary or too much work, the Java method `JOptionPane.showConfirmDialog()` is available. The version to use has the following prototype:

-                                 public static int
                                  showConfirmDialog

                                  Component
                                  parentComponent

                                  Object
                                  message

                                  String
                                  title

                                  int
                                  optionType

                                  int
                                  messageType

The usefulness of this method arises from the fact that the `message` parameter can be an object of any Java class (since all classes are derived from `Object`), or any array of objects. The following example shows how this feature can be used.

    // excerpt from Write_File_Header.bsh

    title = Write file header;

    currentName = buffer.getName();

    nameField = new JTextField(currentName);
    authorField = new JTextField(Your name here);
    descField = new JTextField(, 25);

    namePanel = new JPanel(new GridLayout(1, 2));
    nameLabel = new JLabel(Name of file:, SwingConstants.LEFT);
    saveField = new JCheckBox(Save file when done,
        !buffer.isNewFile());
    namePanel.add(nameLabel);
    namePanel.add(saveField);

    message = new Object[9];
    message[0] = namePanel;
    message[1] = nameField;
    message[2] = Box.createVerticalStrut(10);
    message[3] = Author's name:;
    message[4] = authorField;
    message[5] = Box.createVerticalStrut(10);
    message[6] = Enter description:;
    message[7] = descField;
    message[8] = Box.createVerticalStrut(5);

    if( JOptionPane.OK_OPTION !=
        JOptionPane.showConfirmDialog(view, message, title,
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE))
        return null;

    // *****remainder of macro script omitted*****

    // end excerpt from Write_File_Header.bsh

This macro takes several items of user input and produces a formatted file header at the beginning of the buffer. The full macro is included in the set of macros installed by jEdit. There are a number of input features of this excerpt worth noting.

- The macro uses a total of seven visible components. Two of them are created behind the scenes by `showConfirmDialog()`, the rest are made by the macro. To arrange them, the script creates an array of `Object` objects and assigns components to each location in the array. This translates to a fixed, top-to-bottom arrangement in the message box created by `showConfirmDialog()`.

- The macro uses `JTextField` objects to obtain most of the input data. The fields `nameField` and `authorField` are created with constructors that take the initial, default text to be displayed in the field as a parameter. When the message box is displayed, the default text will appear and can be altered or deleted by the user.

- The text field `descField` uses an empty string for its initial value. The second parameter in its constructor sets the width of the text field component, expressed as the number of characters of average width. When `showConfirmDialog()` prepares the layout of the message box, it sets the width wide enough to accommodate the designated with of `descField`. This technique produces a message box and input text fields that are wide enough for your data with one line of code.

- The displayed message box includes a `JCheckBox` component that determines whether the buffer will be saved to disk immediately after the file header is written. To conserve space in the message box, we want to display the check box to the right of the label Name of file:. To do that, we create a `JPanel` object and populate it with the label and the checkbox in a left-to-right `GridLayout`. The `JPanel` containing the two components is then added to the beginning of `message` array.

- The two visible components created by `showConfirmDialog()` appear at positions 3 and 6 of the `message` array. Only the text is required; they are rendered as text labels.

- There are three invisible components created by `showConfirmDialog()`. Each of them involves a call to `Box.createVerticalStrut()`. The `Box` class is a sophisticated layout class that gives the user great flexibility in sizing and positioning components. Here we use a `static` method of the `Box` class that produces a vertical strut. This is a transparent component whose width expands to fill its parent component (in this case, the message box). The single parameter indicates the height of the strut in pixels. The last call to `createVerticalStrut()` separates the description text field from the OK and Cancel buttons that are automatically added by `showConfirmDialog()`.

- Finally, the call to `showConfirmDialog()` uses defined constants for the option type and the message type. The constants are the same as those used with the `Macros.confirm()` method; see . The option type signifies the use of OK and Cancel buttons. The `QUERY_MESSAGE` message type causes the message box to display a question mark icon.

  The return value of the method is tested against the value `OK_OPTION`. If the return value is something else (because the Cancel button was pressed or because the message box window was closed without a button press), a `null` value is returned to a calling function, signaling that the user canceled macro execution. If the return value is `OK_OPTION`, each of the input components can yield their contents for further processing by calls to `JTextField.getText()` (or, in the case of the check box, `JCheckBox.isSelected()`).

### Selecting Input From a List

Another useful way to get user input for a macro is to use a combo box containing a number of pre-set options. If this is the only input required, one of the versions of `showInputDialog()` in the `JOptionPane` class provides a shortcut. Here is its prototype:

-                                 public static Object
                                  showInputDialog

                                  Component
                                  parentComponent

                                  Object
                                  message

                                  String
                                  title

                                  int
                                  messageType

                                  Icon icon

                                  Object[]
                                  selectionValues

                                  Object
                                  initialSelectionValue

This method creates a message box containing a drop-down list of the options specified in the method's parameters, along with OK and Cancel buttons. Compared to `showConfirmDialog()`, this method lacks an `optionType` parameter and has three additional parameters: an `icon` to display in the dialog (which can be set to `null`), an array of `selectionValues` objects, and a reference to one of the options as the `initialSelectionValue` to be displayed. In addition, instead of returning an `int` representing the user's action, `showInputDialog()` returns the `Object` corresponding to the user's selection, or `null` if the selection is canceled.

The following macro fragment illustrates the use of this method.

    // fragment illustrating use of showInputDialog()
    options = new Object[5];
    options[0] = "JLabel";
    options[1] = "JTextField";
    options[2] = "JCheckBox";
    options[3] = "HistoryTextField";
    options[4} = "-- other --";

    result = JOptionPane.showInputDialog(view,
        "Choose component class",
        "Select class for input component",
        JOptionPane.QUESTION_MESSAGE,
        null, options, options[0]);

The return value `result` will contain either the `String` object representing the selected text item or `null` representing no selection. Any further use of this fragment would have to test the value of `result` and likely exit from the macro if the value equaled `null`.

A set of options can be similarly placed in a `JComboBox` component created as part of a larger dialog or `showMessageDialog()` layout. Here are some code fragments showing this approach:

    // fragments from Display_Abbreviations.bsh
    // import statements and other code omitted

    // from main routine, this method call returns an array
    // of Strings representing the names of abbreviation sets

    abbrevSets = getActiveSets();

    ...

    // from showAbbrevs() method

    combo = new JComboBox(abbrevSets);
    // set width to uniform size regardless of combobox contents
    Dimension dim = combo.getPreferredSize();
    dim.width = Math.max(dim.width, 120);
    combo.setPreferredSize(dim);
    combo.setSelectedItem(STARTING_SET); // defined as "global"

    // end fragments

### Using a Single Keypress as Input

Some macros may choose to emulate the style of character-based text editors such as emacs or vi. They will require only a single keypress as input that would be handled by the macro but not displayed on the screen. If the keypress corresponds to a character value, jEdit can pass that value as a parameter to a BeanShell script.

The jEdit class InputHandler is an abstract class that that manages associations between keyboard input and editing actions, along with the recording of macros. Keyboard input in jEdit is normally managed by the derived class DefaultInputHandler. One of the methods in the InputHandler class handles input from a single keypress:

-                                 public void
                                  readNextChar

                                  String
                                  prompt

                                  String
                                  code

When this method is called, the contents of the `prompt` parameter is shown in the view's status bar. The method then waits for a key press, after which the contents of the `code` parameter will be run as a BeanShell script, with one important modification. Each time the string `__char__` appears in the parameter script, it will be substituted by the character pressed. The key press is consumed by `readNextChar()`. It will not be displayed on the screen or otherwise processed by jEdit.

Using `readNextChar()` requires a macro within the macro, formatted as a single, potentially lengthy string literal. The following macro illustrates this technique. It selects a line of text from the current caret position to the first occurrence of the character next typed by the user. If the character does not appear on the line, no new selection occurs and the display remains unchanged.

    // Next_Char.bsh

    script = new StringBuffer(512);
    script.append( "start = textArea.getCaretPosition();"         );
    script.append( "line = textArea.getCaretLine();"              );
    script.append( "end = textArea.getLineEndOffset(line) + 1;"   );
    script.append( "text = buffer.getText(start, end - start);"   );
    script.append( "match = text.indexOf(__char__, 1);"           );
    script.append( "if(match != -1) {"                            );
    script.append(   "if(__char__ != '\\n') ++match;"             );
    script.append(   "textArea.select(start, start + match - 1);" );
    script.append( "}"                                            );

    view.getInputHandler().readNextChar("Enter a character",
        script.toString());

    // end Next_Char.bsh

Once again, here are a few comments on the macro's design.

- A `StringBuffer` object is used for efficiency; it obviates multiple creation of fixed-length `String` objects. The parameter to the constructor of `script` specifies the initial size of the buffer that will receive the contents of the child script.

- Besides the quoting of the script code, the formatting of the macro is entirely optional but (hopefully) makes it easier to read.

- It is important that the child script be self-contained. It does not run in the same namespace as the parent macro `Next_Char.bsh` and therefore does not share variables, methods, or scripted objects defined in the parent macro.

- Finally, access to the InputHandler object used by jEdit is available by calling `getInputHandler()` on the current view.

## Startup Scripts

On startup, jEdit runs any BeanShell scripts located in the `startup` subdirectory of the jEdit installation and user settings directories (see ). As with macros, the scripts must have a `.bsh` file name extension. Startup scripts are run near the end of the startup sequence, after plugins, properties and such have been initialized, but before the first view is opened.

Startup scripts can perform initialization tasks that cannot be handled by command line options or ordinary configuration options, such as customizing jEdit's user interface by changing entries in the Java platform's `UIManager` class.

Startup scripts have an additional feature lacking in ordinary macros that can help you further customize jEdit. Variables and methods defined in a startup script are available in all instances of the BeanShell interpreter created in jEdit. This allows you to create a personal library of methods and objects that can be accessed at any time during the editing session in another macro, the BeanShell shell of the Console plugin, or menu items such as Utilities>BeanShell>Evaluate BeanShell Expression.

The startup script routine will run script files in the installation directory first, followed by scripts in the user settings directory. In each case, scripts will be executed in alphabetical order, applied without regard to whether the file name contains upper or lower case characters.

If a startup script throws an exception (because, for example, it attempts to call a method on a `null` object). jEdit will show an error dialog box and move on to the next startup script. If script bugs are causing jEdit to crash or hang on startup, you can use the `-nostartupscripts` command line option to disable them for that editing session.

Another important difference between startup scripts and ordinary macros is that startup scripts cannot use the pre-defined variables `view`, `textArea`, `editPane` and `buffer`. This is because they are executed before the initial view is created.

If you are writing a method in a startup script and wish to use one of the above variables, pass parameters of the appropriate type to the method, so that a macro calling them after startup can supply the appropriate values. For example, a startup script could include a method

    void doSomethingWithView(View v, String s)  {
        ...
    }

so that during the editing session another macro can call the method using

    doSomethingWithView(view, "something");

### Reloading startup scripts without restarting

It is actually possible to reload startup scripts or load other scripts without restarting jEdit, using a BeanShell statement like the following:

    BeanShell.runScript(view,path,null,false);

For path, you can substitute any string, or a method call such as `buffer.getPath()`.

## Running Scripts from the Command Line

The `-run` command line switch specifies a BeanShell script to run on startup:

    $ jedit -run=test.bsh

Note that just like with startup scripts, the `view`, `textArea`, `editPane` and `buffer` variables are not defined.

If another instance is already running, the script will be run in that instance, and you will be able to use the `jEdit.getLastView()` method to obtain a view. However, if a new instance of jEdit is being started, the script will be run at the same time as all other startup scripts; that is, before the first view is opened.

If your script needs a view instance to operate on, you can use the following code pattern to obtain one, no matter how or when the script is being run:

    void doSomethingUseful()
    {
        void run()
        {
            view = jEdit.getLastView();

            // put actual script body here
        }

        if(jEdit.getLastView() == null)
            VFSManager.runInAWTThread(this);
        else
            run();
    }

    doSomethingUseful();

If the script is being run in a loaded instance, it can be invoked to perform its work immediately. However, if the script is running at startup, before an initial view exists, its operation must be delayed to allow the view object first to be created and displayed. In order to queue the macro's operation, the scripted closure named `doSomethingUseful()` implements the `Runnable` interface of the Java platform. That interface contains only a single `run()` method that takes no parameters and has no return value. The macro's implementation of the `run()` method contains the working portion of the macro. Then the scripted object, represented by a reference to `this`, is passed to the `runInAWTThread()` method. This schedules the macro's operations for execution after the startup routine is complete.

As this example illustrates, the `runInAWTThread()` method can be used to ensure that a macro will perform operations after other operations have completed. If it is invoked during startup, it schedules the specified `Runnable` object to run after startup is complete. If invoked when jEdit is fully loaded, the `Runnable` object will execute after all pending input/output is complete, or immediately if there are no pending I/O operations. This will delay operations on a new buffer, for example, until after the buffer is loaded and displayed.

## Advanced BeanShell Techniques

BeanShell has a few advanced features that we haven't mentioned yet. They will be discussed in this section.

### BeanShell's Convenience Syntax

We noted earlier that BeanShell syntax does not require that variables be declared or defined with their type, and that variables that are not typed when first used can have values of differing types assigned to them. In addition to this loose syntax, BeanShell allows a convenience syntax for dealing with the properties of JavaBeans. They may be accessed or set as if they were data members. They may also be accessed using the name of the property enclosed in quotation marks and curly brackets. For example, the following statement are all equivalent, assuming `btn` is a `JButton` instance:

    b.setText("Choose");
    b.text = "Choose";
    b{"text"} = "Choose";

The last form can also be used to access a key-value pair of a `Hashtable` object.

### Special BeanShell Keywords

BeanShell uses special keywords to refer to variables or methods defined in the current or an enclosing block's scope:

- The keyword `this` refers to the current scope.

- The keyword `super` refers to the immediately enclosing scope.

- The keyword `global` refers to the top-level scope of the macro script.

The following script illustrates the use of these keywords:

    a = "top\n";
    foo() {
        a = "middle\n";
        bar() {
            a = "bottom\n";
            textArea.setSelectedText(global.a);
            textArea.setSelectedText(super.a);
            // equivalent to textArea.setSelectedText(this.a):
            textArea.setSelectedText(a);
        }

        bar();
    }
    foo();

When the script is run, the following text is inserted in the current buffer:

    top
    middle
    bottom

### Implementing Classes and Interfaces

As discussed in the macro example in , scripted objects can implicitly implement Java interfaces such as `ActionListener`. For example:

    myRunnable() {
        run() {
            System.out.println("Hello world!");
        }

        return this;
    }

    Runnable r = myRunnable();
    new Thread(r).start();

Frequently it will not be necessary to implement all of the methods of a particular interface in order to specify the behavior of a scripted object. To prevent BeanShell from throwing exceptions for missing interface methods, implement the `invoke()` method, which is called when an undefined method is invoked on a scripted object. Typically, the implementation of this method will do nothing, as in the following example:

    invoke(method, args) {}

In addition to the implicit interface definitions described above, BeanShell permits full-blown classes to be defined. Indeed, almost any Java class definition should work in BeanShell:

    class Cons {
        // Long-live LISP!
        Object car;
        Object cdr;

        rplaca(Object car) {
            this.car = car;
        }

        rplacd(Object cdr) {
            this.cdr = cdr;
        }
    }

## Debugging Macros

Here are a few techniques that can prove helpful in debugging macros.

### Identifying Exceptions

An exception is a condition reflecting an error or other unusual result of program execution that requires interruption of normal program flow and some kind of special handling. Java has a rich (and extensible) collection of exception classes which represent such conditions.

jEdit catches exceptions thrown by BeanShell scripts and displays them in a dialog box. In addition, the full traceback is written to the activity log (see for more information about the activity log).

There are two broad categories of errors that will result in exceptions:

- Interpreter errors, which may arise from typing mistakes like mismatched brackets or missing semicolons, or from BeanShell's failure to find a class corresponding to a particular variable.

  Interpreter errors are usually accompanied by the line number in the script, along with the cause of the error.

- Execution errors, which result from runtime exceptions thrown by the Java platform when macro code is executed.

  Some exceptions thrown by the Java platform can often seem cryptic. Nevertheless, examining the contents of the activity log may reveals clues as to the cause of the error.

### Using the Activity Log as a Tracing Tool

Sometimes exception tracebacks will say what kind of error occurred but not where it arose in the script. In those cases, you can insert calls that log messages to the activity log in your macro. If the logged messages appear when the macro is run, it means that up to that point the macro is fine; but if an exception is logged first, it means the logging call is located after the cause of the error.

To write a message to the activity log, use the following method of the Log class:

-                                 public static void
                                  log

                                  int
                                  urgency

                                  Object
                                  source

                                  Object
                                  message

See the documentation for the Log class for information about the method's parameters.

The following code sends a typical debugging message to the activity log:

    Log.log(Log.DEBUG, BeanShell.class, "counter = " + counter);

The corresponding activity log entry might read as follows:

    [debug] BeanShell: counter = 15

#### Using message dialog boxes as a tracing tool

If you would prefer not having to deal with the activity log, you can use the `Macros.message()` method as a tracing tool. Just insert calls like the following in the macro code:

    Macros.message(view,"tracing");

Execution of the macro is halted until the message dialog box is closed. When you have finished debugging the macro, you should delete or comment out the debugging calls to `Macros.message()` in your final source code.