Running Scripts from the Command Line
Prev | Chapter 15. Macro Tips and Techniques | Next

## 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.

Prev | Up | Next
Startup Scripts | Home | Advanced BeanShell Techniques