Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>Khemia Macros - Simple VSCode ProgrammabilityNew to Visual Studio Code? Get it now.
Khemia Macros - Simple VSCode Programmability

Khemia Macros - Simple VSCode Programmability

Preview

Tony Patterson

|
263 installs
| (1) | Free
A macro writing system for Visual Studio Code
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Khemia Macros - Simple VSCode Programmability

Features

Khemia is a simple macro language to help automate repetitive typing jobs in Visual Studio Code. It is simple to pick up and powerful when needed.

Getting Started

A Khemia program is normally saved as a text file with the extension .khemia.

When you the command Run Khemia Program from the Visual Studio Code command palette, you will be asked to select a Khemia script file. The file will then be loaded and run against the active document.

To run the last Khemia program again, use the Run Last Khemia Program Again command. This is useful when you want to run the last program several times - you can bind this command to a key to do that, whatever the last program was.

Another useful command is Run Inline Khemia Program, which accepts Khemia programs directly as an argument, allowing key bindings to be easily used with short scripts.

The use of keyboard shortcuts is discussed later on.

A program in Khemia is made up of a series of commands separated by semi-colons or new-lines. Comments are introduced by # and continue to the end of the line. Program flow commands use { and } to group sub-ordinate commands together.

Basic Commands

The simplest Khemia programs use the following five commands:

  • L or Left
  • R or Right
  • U or Up
  • D or Down
  • Type

These move the cursor or type text in to the document.

At its simplest, the Type command is given a string and this supplied string is added to the document as if it were being typed.

Type 'Hello'

You can use both double and single quotes, as long as they match, to supply the string. Normally, statements are separated by a ; or a new line, but these can both be used within a string:

Type "This string contains a new line
and a semi-colon;";

These characters are entered verbatim in to the document.

A \ character can be used as an escape to enter special characters to be added. In this way you can add quotes in to a string even when they are the same type as the quote delimiters:

Type "Use double-quotes \" and single quotes \'."

The back-slash can also be used to enter tabs \t, new-lines \n and carriage returns \r. Any other character will lead to an error.

The cursor movement characters can optionally be followed by a number to move the cursor multiple times. To move the cursor four characters to the right, use:

R 4;

Adding the Select keyword will cause the selection to be extended as the cursor is moved. To extend the selection down three lines, use:

D 3 Select;

Finding Text in a Document

The Find command is used to search for text in a document. Khemia allows three types of search to be done, but by default a straightforward text search which ignores character case is used. To find the text word, you would use:

Find 'Word';

This woul match Word as well as WORD, WoRd and any other case alteration of word.

When the text is found, it is also selected (by default). This means you can immediately use Type to replace the found text with something else.

By default, the search starts from the current cursor location and proceeds to the end of the document and stops.

If the search fails to find anything, it will cause the Khemia program to stop.

A simple search and replace can therefore be built like this:

Find 'Word';
Type 'Mot';

Running this macro will replace the first instance of Word with Mot. If Word is not found, then nothing happens.

Modifying the way that Find works

There are three ways in which you can change the way that Find behaves.

The search Mode determines how Khemia matches text in its results:

  • Fold is the default behaviour and matches text exactly, regardless of case.
  • MatchCase requires an exact text match including exact case matching.
  • RegEx matches the text according to the supplied regular expression.

The search Direction can be one of the following:

  • Forward searches from the cursor position, forward until the end of the file.
  • Backward searches from the cursor position, backward until the start of the file.
  • FromStart searches from the start of the file, forward until the end.
  • FromEnd searches from the end of the file, backward until the start.

The search Behaviour can be one of the following:

  • Before places the cursor at the beginning of the found text.
  • After places the cursor at the end of the found text.
  • Select selects the found text.
  • Remove seletes the found text and then places the cursor where the text was.

To set the way that find works, you can add any item from each of the three groups to your Find command:

Find 'hello' MatchCase Forward;
Find 'Interval' FromStart Remove;
Find '@.*@' RegEx Select;

Deleting Text

The selected text can be deleted with the Delete command.

Using Variables

Khemia allows simple expressions to be evaluated in programs. For example:

Set $name = "John Smith";

The Set keyword is optional.

Variables are indicated by a name starting with $ for a string variable, or a name starting with % for an integer variable.

The following pseudo-variables are defined:

Variable Purpose
%%column The 1-based character offset in the current line
%%line The 1-based number of the current line
$$file The name of the current file
$$folder The folder where the current file is saved
$$lf The line-feed character
$$path The full path of the current file
$$selection The currently-selected text
$$workspace The default workspace's folder path

The following operators are defined:

Operator Purpose
+ Concatenate strings or integer add
- Integer subtract or negation
* Integer/string multiply
/ Integer divide
(...) Override operator precedence
[...] String splicing operator
.Length Returns the length of a string

We can therefore write commands like these:

$name = "John Smith" + $$lf;
$address = $name + $$lf + %number + " Chalk Lane" + $$lf + "Ipswich"

And use the variables in Type like this:

Type "The address is:" + $$lf + $address

The string slicing operators work like those in Python and allow the string to be sliced according to three parameters passed within the brackets, as follows:

string[start:end:step]

The string is split to create a new string using characters from the range starting at index start and ending before index end. All parameters are optional and use sensible defaults when not supplied. If supplied, the step parameter takes every nth character from the range.

It is possible to use -ve numbers to specify the indices as an offset from the end of the string. A -ve step may be provided to return ranges from the input string in reverse order.

Some examples are shown below, but the Python documentation is a useful reference.

Expression Result
'Hello World'[:2] 'He'
'Hello World'[-3] 'rld'
'Hello World'[2:-3] 'llo Wo'
'Hello World'[2: -1:2] 'loWr'
'Hello World'[-3:2:-2] 'rWo'

Control Statements

The command Repeat can be used to repeat a set of commands. The simplest way of using Repeat is to indicate how many times you want the commands to be run:

Repeat 4 {
    Type "Hello" + $$lf
}

This types the word Hello, followed by a line-feed, 4 times.

You can use the With keyword to introduce a variable that contains the iteration count:

Repeat 4 with %myCounter {
    Type "Hello " + %myCounter + $$lf
}

This produces:

Hello 1
Hello 2
Hello 3
Hello 4

The counter starts with the value 1 and is incremented at the end of each loop. You can set the counter to something different at any point, but it will always have the iteration number at the start of each loop.

Find in Repeat Statement

As noted before, Find causes the program to terminate if the required text cannot be found. In a Repeat statement this behaviour is modified slightly in that the current loop iteration stops and program execution continues at the statement after the repeat.

A simple search and replace can therefore be defined like this:

Repeat {
    Find 'Hello';
    Type 'Bonjour';
}

In this case, the loop count is left out, because we want to repeat until the Find cannot continue. If a repeat count is specified, the program will stop either after the specified number of iterations or when Find can no longer find any relevant text:

Repeat 4 With %i {
    Find 'Hello' FromStart;
    Type 'Bonjour ' + %i;
}

This program will replace up to 4 instances of the word Hello, starting at the beginning of the document and replacing them with the word Bonjour and the instance number. If fewer than 4 instances of the word Hello exist, they will all be replaced.

To reduce the possibility of creating a program which never ends, repeat will not allow more than 1000 iterations when no numeric limit is given. You can override this behaviour by simply specifying a very high limit.

Running Visual Studio Code Commands

The Command statement allows you to run commands in Visual Studio Code. In this way you can access other macros and perform actions which Khemia does not natively support. For example:

Command 'editor.action.commentLine'

This will toggle the the current line to and from a comment. Commands which take arguments are supported with the With keyword. You need to specify the arguments as JSON:

Command 'cursorMove' With '{"to": "viewPortTop", "select": true}'

Activating a Macro with a Keypress

To set up key-bindings for Khemia macros, you need to edit Visual Studio Code's key bindings file, using Preferences: Open Keyboard Shortcuts (JSON) in the command palette. You can then enter a command such as:

{
  "key": "ctrl+shift+q",
  "command": "khemia.runMacro",
  "args": "./list_to_qualified_sql_select.khemia"
}

Choose a keyboard combination and program to suit. The argument can be a full file path to a macro or can use the following pseudo-root folders:

Root Usage
#/ The home path as configured in the Khemia settings
./ The currently loaded working folder
~/ The user's home folder (works on Windows too)

For example:

#/insert_header.khemia

This will run the insert_header macro in the folder that has been saved in the Khemia preferences.

For small macros, you can pass the macro as an argument to the inline macro runner.

{
  "key": "ctrl+8",
  "command": "khemia.runInlineMacro",
  "args": "Find '##' Before; R 1; Type ' Name:  '; L 1 "
}

You can bind a key to re-run the last macro run:

{
  "key": "ctrl+0",
  "command": "khemia.runMacroAgain"
}

This will run the last successful macro again. It runs the compiled copy of the macro, so if it does not matter whether it was from a file or was inline it will run the macro exactly as before. This happens even if the source file has been changed. Because it uses the compiled copy of the macro, it may be a little faster than compiling and then running a macro.

Khemia registers the following keys by default:

Key Action
Ctrl+Shift+K, Ctrl+Shift+R Run a macro from a file
Ctrl+Shift+K, Ctrl+Shift+A Run the last macro again
Ctrl+Shift+Q Run the macro ~/Scratch.khemia
Ctrl+Shift+K, Ctrl+Shift+S Load the scratch macro in to the editor

Use Cmd instead of Ctrl on Mac.

To use the Scratch macro you will need to configure the folder in the Khemia settings and make a suitable file.

And Finally…

Output can be logged to the output window using the Log command. This can be passed an expression and can be helpful in diagnosing behaviour when a program doesn't work the way you want it to. Output is shown in the Khemia channel of the Output window.

If there us an error in the macro file Khemia will show a pop-up error in the Visual Studio Code window at the bottom right. This will include the precise location where the error was found.

The extension provides basic Intellisense suggesstions and program validation for files with the Khemia extension.

Khemia always runs scripts in their saved form, that is, if the script is open in Code and modified, running it will run the version on disc, not the version in the editor.

Requirements

If you have any requirements or dependencies, add a section describing those and how to install and configure them.

Extension Settings

This extension contributes the following settings:

  • khemia.homeFolder : Set the default folder in which to look for macro files.

Known Issues

  • Expression evaluation doesn't allow some (albeit not very useful) combinations of operators, such as: 'abc'[1:2][:1]
  • Name completion of pseudo-variables adds extra '$' or '%'
  • Numeric pseudo-variables don't provide Intellisense

Future Features

  • If statement
  • Break statement
  • Snippets
  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2025 Microsoft