Commands

User-invokable commands can be added to the menus and command palette, optionally with keyboard key-equivalents. These commands invoke a callback registered in the JavaScript execution environment of the extension.

Defining a Command

The extension’s extension.json can include a commands object defining which commands are exposed by the extension.

The commands object can contain several “sections” that commands may be defined:

Example:

{
    "identifier": "com.panic.HTML",
    "name": "HTML",
    "vendor": "Panic Inc.",
    
    "main": "main.js",
    
    "commands": {
        "editor": [
            {
                "title": "Wrap Selection In Tag",
                "command": "wrapSelectionInTag",
                "shortcut": "cmd-<",
                "when": "editorHasFocus",
                "filters": {
                    "syntaxes": ["html"]
                }
            }
        ]
        
    }
}

This defines a command, “Wrap Selection In Tag”, that when invoked by the user will invoke the wrapSelectionInTag command handler registered in the extension’s JavaScript environment. Registration of the command handler is done like so:

// Wraps the current editor selection in a new tag, with placeholders
nova.commands.register("wrapSelectionInTag", (editor) => {
    var selectedRanges = editor.selectedRanges.reverse();
    editor.edit(function(e) {
        for (var range of selectedRanges) {
            var text = editor.getTextInRange(range);
            var newText = "<$[tag]>" + text + "</$[tag]>";
            e.replace(range, newText);
        }
    });
});

Each command can be configured using a number of options:

When Clauses

The when clause of extension commands is an expression that defines under what circumstances a command should be enabled. The expression format follows a strict subset of standard JavaScript conditional syntax. The variables available within these expressions is dependent on the context in which the extension is available.

Examples:

Variables in When Clauses

The set of available variables for various contexts in when expressions are:

Editor Context
documentHasPath The document has a path, representing a file on disk (as opposed to an untitled file)
editorHasFocus The editor is the focused pane and is first responder
editorHasSelection The editor has at least one non-zero-length selected range
editorHasMultipleSelections The editor has at least two or more selections (including multiple cursors)
editorSyntax Evaluates the editor syntax name against a string (editorSyntax == 'javascript')
ViewItem Context
viewItem The contextValue for the item(s) that are currently selected