Wednesday, September 24, 2008

UltraEdit macro: act on selected text or whole document

Updates
15/06/2009 12:28:28 PM. Fixed up the example macro, which was broken (bad c&p plus forgot "GotoLine 1 1"). Added some additional explanation.

I often want my UltraEdit macros to act on the text I have selected or the whole document if I have no text selected. Here is a small macro I use often that demonstrates how to do this.

InsertMode
ColumnModeOff
HexOff
UnixReOff
IfSel
Find SelectText "<"
Replace All "&lt;"
Find SelectText ">"
Replace All "&gt;"
Find SelectText """
Replace All "&quot;"
Find SelectText "^t"
Replace All "  "
Else
GotoLine 1 1
Find "<"
Replace All "&lt;"
Find ">"
Replace All "&gt;"
Find """
Replace All "&quot;"
Find "^t"
Replace All "  "
EndIf

The red text is the guts of macro, i.e. what it does. It replaces:

  • the less than symbol "<" with "&lt;";
  • the greater than symbol ">" with "&gt;";
  • the double quote symbol """ with "&quot;"; and
  • tab characters with two spaces " ".

The blue text is the control logic. If you have text selected (IfSel), the actions will be performed only upon that selected text. Otherwise (Else), the logic will be applied accross the entire document (GotoLine 1 1 ... Find ... Replace All).

UltraEdit macros are purely procedural, so there isn't any way around repeating the slightly modified code in the IF and ELSE.

I think UltraEdit is very cool because it supports many ways to automate various things: look up tags, templates, macros and (JavaScript) scripts.