Service Portal: Syntax Editor Macros

April 27, 2019 10:12 pm

Published by

Syntax Editor Macros… One of those things that you don’t realize you miss until they’re gone. And unfortunately in the Service Portal Widget Editor there is currently no support for them, so I created a small script to enable Syntax Editor Macros in the Service Portal Widget Editor.


//object to store macros in

var macrosObj={


//add keyup event listener

jQuery(window).on('keyup', function(e) {

var keyCode = e.keyCode || e.which;

//check if key pressed is TAB

if (keyCode == 9) {

//get DOM element for active pane

var cmEl = jQuery(document.activeElement).parents('.CodeMirror')[0];

//get CodeMirror object for active pane. CodeMirror is the Syntax Editor library used in the Widget Editor

var cmObj = cmEl.CodeMirror;

//get position of cursor and end of line

var tmpCursor=cmObj.getCursor();

var eol=cmObj.getLine(tmpCursor.line).length;

//do nothing if cursor is not at end of line

//this allows users to continue using TAB key for formatting/indentation

if(tmpCursor.ch < eol){

return true;


//do nothing if any text is selected


return true;


//find the start and end position of the word preceeding the cursor

var wordObj = cmObj.findWordAt({

line: tmpCursor.line,

ch: tmpCursor.ch-2


//get the actual word preceeding the cursor

var word = cmObj.getRange(wordObj.anchor, wordObj.head);

//do nothing if a corresponding Syntax Editor Macro does not exist

if(typeof macrosObj[word]==='undefined')

return true;

//select the word preceeding the cursor

var sel = cmObj.setSelection(wordObj.anchor,wordObj.head);

//replace selection with the text of the Syntax Editor Macro

cmObj.replaceSelection( macrosObj[word].text );



//populate macrosObj with records from the Syntax Editor Macro table

var requestBody = "";

var client=new XMLHttpRequest();





client.onreadystatechange = function() {

if(this.readyState == this.DONE) {

var rspObj=JSON.parse(this.response).result;

for(var macro in rspObj){



var currentMacro=rspObj[macro];







Create Widget Dependency

  1. Service Portal > Widgets
  2. Open: Widget Edit Panel
  3. Dependencies (related list) > New
    • Name: widgetMacros
  4. Save
  5. JS Includes (related list) > New
    • Display name: widgetMacros
    • Source: UI Script
    • UI Script: [UI Script created above]
  6. Submit

That’s it!

Service Portal Widget Editor now has full support for the Syntax Editor Macros used throughout the rest of the platform. This functionality is introduced in the ServiceNow Service Portal Advanced class – I’ll be teaching this class at Knowledge 19 this year!

Tags: ,