Macros in Kate editor v 3.8.4 (KDE 4.8.4)

After a recent Debian upgrade, I needed to revisit the Kate macros I developed for Kate version 2.

The location of the scripts has changed; on Debian wheezy they are in /usr/share/kde4/apps/katepart/script/. Also, now it is possible to include multiple scripts in the same file, and you need a header section in your file as explained here (please also see below for an example). Basically, the header needs to signal that the file contains Kate scripts, and list all the function names that should be available as commands on the command line.

Some of the internal function calls have changed as well, but I was pleased to find that one could define helper functions and call them from the commands. As I use my commands as shortcuts for snippets I insert often while programming or debugging, I defined two helper functions: one two simply insert some string at the position of the cursor, and another that ensures that the line is indented before inserting the string.

I also found that I needed to nudge the cursor to make word completion work properly.

Please see a sample header and two command functions and the two helper functions below:

/* kate-script
 * author: NAME
 * revision: 1
 * kate-version: 3.4
 * type: commands
 * functions: hello, ihello
 */

function insert_at_cursor(text){
Cur = view.cursorPosition();
document.insertText(Cur,text);
Cur = view.cursorPosition(); /* to make word completion appear */
Cur.column--;
view.setCursorPosition(Cur);
Cur.column++;
view.setCursorPosition(Cur);
}

function tab_insert(text){
Cur = view.cursorPosition();
if(Cur.column==0){ text = "\t" + text; }
document.insertText(Cur,text);
Cur = view.cursorPosition(); /* to make word completion appear */
Cur.column--;
view.setCursorPosition(Cur);
Cur.column++;
view.setCursorPosition(Cur);
}

function hello(){ insert_at_cursor('Hello world!'); }
function ihello(){ tab_insert('Hello world!'); }

Put this in a .js file in /usr/share/kde4/apps/katepart/script/, and the commands 'hello' and 'ihello' should be available after reloading the scripts in Kate or restarting it. Press F7 to get to the command line, type one of the commands, and press ENTER. I usually use one, two, or three-character-long command names, and they speed things up a lot (and they can also help with RSI, especially if the inserted string contains many characters that need Shift to type).

For macros in Kate 2.5.5, please see this previous post.

Popular Posts