Quick Start

This section is showing how to add a simple command to launch an external program and replace the selection with the output of this program.

1. Creating a New Script File

  1. Open the Option window (menu View > Options).
  2. Right-click on the window, select New Script File....
  3. Enter the name 'my-commands. It is just the name of the file on disk. Press return, a new empty file should be opened.

2. Adding the Function

Insert the following code into the newly created file:

function myFirstCommand (frame, application)
	var win = frame activeWindow
	var p = Process run ("cmd /c date /t", "", false)
	win replaceSelection (win file newBlockFromString (p stdout), false)
end

If you're using a Unix system, replace "cmd /c date /t" with "date".

3. Adding the Command

Add the following intialization function:

function initialize (settings)
	settings addCommand ("example-command", "My First Command", "F9", ref myFirstCommand, "")
end

The initialize function is invoked each time settings are reloaded. It just declare a new command with the following arguments:

4. Running the Command

Save the file and press F9 or use the command My First Command from the Tools menu, it should insert the current date at the cursor location.

Here are more comments about the script:

	var win = frame activeWindow

Defines a win variable and initializes it to the active window: frame is the first parameter representing the top level window. activeWindow is a 'message' sent to frame to retrieve its active window.

	var p = Process run ("cmd /c date /t", "", false)

Executes cmd /c date /t without specifying a working directory ("") and without showing the cmd window (false). The result of the operations is stored in the local variable p. Process is a class, but classes are also objects, so it is possible to send a message to a class. Here, the message run with its arguments is sent to the Process class.

	win replaceSelection (win file newBlockFromString (p stdout), false)

Inserts the output of the command in the active window: p is an object containing the exit code and the standard output of the previously executed command.

The stdout is a string, it must be first converted to a TextBlock object. That is exactly what win file newBlockFromString (p stdout) does.

replaceSelection is the last operation: it replaces the selection with the given block. false argument prevents to select the replaced text, the cursor is just moved after the inserted text.

5. More Information

For more information, have a look at the Language Reference and the Class Reference. You can also have a look at the various example scripts in the file examples/scripts.cbs or look at scripts in config-optional/.