Monday, March 31, 2008

Better line editing for Rhino shell

Thanks to a patch from Matthieu Riou, we now have line editing in the Rhino shell. The heavy lifting comes from JLine, a nice Java library for handling console input. We get command history (using the up and down arrow keys to bring up previous command lines) for free. And with some additional code in Rhino we have limited support for completion.

We don't ship with JLine by default (perhaps we should?), so you'll have to download it yourself. Rhino automatically detects whether JLine is on the classpath and uses it if so and otherwise maintains the previous simple behavior. So to run your shell with JLine your command will look like

java -cp js.jar:lib/jline-0.9.93.jar org.mozilla.javascript.tools.shell.Main


Completion works by looking at the global scope and attempting to complete variables defined there. For example,

js> var obj = {prop1:{prop2:3}};
js> ob

After typing ob and pressing tab, Rhino will autocomplete to obj. It's also smart enough if it sees a dotted property list it will walk it to find names to autocomplete:

js> obj.prop1.pr

Pressing tab after obj.prop1.pr will autocomplete to obj.prop1.prop2.

Some limitations: it's not possible as far as I know to enumerate all the classes or packages in the Java runtime, so autocompletion works somewhat disappointingly for Java classes. I've also found that JLine doesn't work in the Eclipse console, so I just leave the JLine jar off when I'm running in Eclipse.

For more details, see bug 418034.