Menu

Scripting Notepad++ with javascript

2008-07-13
2012-11-13
  • Daniel Wachsstock

    I don't know if this will help others, but it made my life much easier.
    I was frustrated with the limitations of the macro system, but didn't want to program my own plugins for simple things, but I realized that the Run menu will run anything that you can use in Shell.Run (http://msdn.microsoft.com/en-us/library/d5fk67ky(VS.85).aspx), including script files for Windows Script Host, and that script can use SendKeys (http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx) to communicate back to Notepad++.

    So, for example, a simple script to wrap text in a <span> tag would be:

    var s = WScript.Arguments(0);
    WScript.CreateObject("WScript.Shell").SendKeys('<span>' + s + '</span>');

    Save it as a .js file (say, "span.js") and enter the following in the Run... dialog:

    "path/to/span.js" "$(CURRENT_WORD)"

    and save it, and voila! instant javascript macro.

    Obviously, this is more useful with more sophisticated scripts, and you have to read the SendKeys documentation for the special characters and escape codes. You probably want to include a line like

    s = s.replace(/([[+^%{}\]])/g, '{$1}').replace('\n', '{ENTER}').replace('\t', '{TAB}');

    to avoid problems.

    You can use any language that WSH understands, like VBScript or even Perl (http://www.xav.com/perl/Components/Windows/PerlScript.html)

     
    • Nobody/Anonymous

      interest.
      but when i follow your instruction nothing happen to the selected word. i dont know why.

       
    • Nobody/Anonymous

      OMG, this is amazing, this should go right to the Notepad++ features/documentation, along with some useful scripts.

       
    • Daniel Wachsstock

      Playing with this I notice that $(CURRENT_WORD) uses \r\n for the line separator, which gets turned into two separate line endings. Also, the 'replace's should be global.

      So the string should be
      s = s.replace(/([[+^%{}\]])/g, '{$1}').replace(/\r/g,'').replace(/\n/g, '{ENTER}').replace(/\t/g, '{TAB}');

       
    • Daniel Wachsstock

      And another gotcha: $(CURRENT_WORD) strips double quotes out. Not a deal-killer, but annoying.
      One could use a copy/paste hack to get around this (like http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1215.mspx\) but I don't like it and don't want to mess with the clipboard.