Functional Chops and the Best Text Editor in the World

Call me fickle but PSPad is the best thing since sliced bread. Crimson? Notepad++? Who?

PSPad's killer feature is that you can script it with any language supported by the Windows Scripting Host. For me that means JavaScript but, with the right trickery installed it could mean something really cool like Python, Ruby or even Haskell.

By way of a Hello, world example, I wrote a little script to convert a block of CSV in the editor window to an HTML table. It took me little over an hour.

  1. function CSVToTable()  
  2. {  
  3.     var editor = newEditor();  
  4.     editor.assignActiveEditor();  
  5.       
  6.     var CSVRegex = /,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/;  
  7.     var replacementText = "";  
  8.     var lines = editor.selText().split("\n");  
  9.   
  10.     if (lines.length >  0)  
  11.     {  
  12.         replacementText += "<table>\n";  
  13.         map(lines, function (line) {  
  14.             if (line.length > 0)  
  15.             {  
  16.                 replacementText += "<tr>";  
  17.                 var tokens = line.replace(/\r/,"").split(CSVRegex);  
  18.                 map(tokens, function (token) {  
  19.                     replacementText += "<td>" + token + "</td>";  
  20.                     });  
  21.                 replacementText += "</tr>\n";  
  22.             }  
  23.             });  
  24.   
  25.         replacementText += "</table>\n";  
  26.         editor.selText(replacementText);  
  27.     }  
  28. }  


It could be a little more robust - I hung the editor by using column mode to select a stupid block - but that, to all intents and purposes, is it.

Notice the calls to the map function. Closures and anonymous functions are a revelation and lead to beautifully concise code.

  1. function map(a, fn)  
  2. {  
  3.     var i;  
  4.     for ( i = 0; i < a.length; i++)  
  5.     {  
  6.         fn(a[i]);  
  7.     }  
  8. }  


User scripts install neatly into PSPad's menus with accelerator key support so I can now highlight any block of CSV, hit Alt-C-S-C and it will be replaced with an HTML table.

  1. <!-- 1,2,"3,4",5,6 -->
  2. <!-- 1,2,"3,4",5,6 -->
  3. <!-- 1,2,"3,4",5,6 -->
  4. <table>
  5. <tr><td>1</td><td>2</td><td>"3,4"</td><td>5</td><td>6</td></tr>
  6. <tr><td>1</td><td>2</td><td>"3,4"</td><td>5</td><td>6</td></tr>
  7. <tr><td>1</td><td>2</td><td>"3,4"</td><td>5</td><td>6</td></tr>
  8. </table>

Comments

Popular Posts