Notepad++ Editing Techniques

navigation tips

  • Bookmark point and jump
    1. click the line number to create a bookmark
    2. Press F2 to jump to each bookmark
  • Function list and search
    • (View menu) > Function List
  • Full screen (F11, F12)

replace tips

  • replace “a pattern” (like “<td id='row15'>” )
    Replace dialog search mode: regular expression
    search: <td id='row..'>
    replace:
    note: . : means representing a unknown char
  • replace “a blank line”
    Replace dialog search mode: extended
    search : \r\n\r\n
    replace: \r\n
    note: \r\n\r\n means double new lines
  • get rid of tabs and spaces in blank lines
    Replace dialog search mode: regular expression
    find: ^\s*$
    replace: 
    note: start and any mount space or tab and a end

Notepad++ customization

  • add plugins (Plugins > Plugin Manager) or manually put in plugin folder
  • add macros (no need if you use notepad++ PythonScript plugin)
  • customize context menu (right click menu):
  • default tab size
    • Settings → Preferences → Language Menu/Tab Settings tab → The tab options at bottom right.
  • split view
  • add Flash actionscript syntax highlight fix
    • Win+R, type “%appdata%\notepad++\” and go to that folder, open langs.xml config file
    • search for “haskell”, and take “as” string away from
      < Language name="haskell" ext="hs lhs as las" commentLine="--" >
  • add Flash jsfl script syntax highlighted
    • add jsfl to ActionScript section in langs.xml
  • Add jsx as javascript for Photoshop scripting
    • search: name=“javascript”
    • add jsx behind js after a space.

Notepad++ Plugin list

  • Note: to enable notepad++ to put installed plugin in App root directory instead of user data directory, create a empty file in App root directory called “allowAppDataPlugins.xml”
Plugin name
Hex Editor Hex code file editing
TextFX automate common text typing operation
Compare compare difference and similarity between 2 files in split view
Plugin Manager a plugin online browser and install helper
Python Script add Python consolve integration and python automation for notepad++
  • Important Note if your script not working
    • if in your Npp python console or your script does nothing, maybe try add this line at beginning or at start
      from Npp import *
      # test
      editor.addText('test')

notepad cmds

  • file operation
    # Create a new document
    notepad.new()
     
    # open file
    notepad.open("\web\index.htm")
     
    # Save the file
    newFilename = notepad.getCurrentFilename() + ".changed"
    notepad.saveAs(newFilename);
  • setting operation
    notepad.getFormatType()
    notepad.setFormatType(formatType, bufferID) # Npp.FORMATTYPE.WIN
     
    # set syntax color language
    notepad.getLangType(bufferID) 
    notepad.setLangType(langType, bufferID) # Npp.LANGTYPE.PYTHON; Npp.LANGTYPE.TXT; Npp.LANGTYPE.PHP
  • user input
    # dialog 
    # "1" for type 2 button set; return pressed button id
    notepad.messageBox("hello world","My Title",1)
    # prompt 
    notepad.prompt("Enter your name:", "Simple Interact UI", "Tom")

editor cmds

Most useful scintilla edit cmd

editor.addText(text) Add text to the document at current position.
editor.clearAll() Delete all text in the document.
editor.selectAll() Select all the text in the document.
editor.gotoLine(line) Set caret to start of a line and ensure it is visible.
editor.getCurLine() = str Retrieve the text of the line containing the caret. Returns the index of the caret on the line.
editor.setTabWidth(tabWidth) Change the visible size of a tab to be a multiple of the width of a space character.
editor.getTabWidth() = int Retrieve the visible size of a tab.
editor.getSelText() = str Retrieve the selected text. Return the length of the text.
editor.lineDelete() Delete current line
editor.lineDown() navi - move cursor to next line
  • text operation
    # Simple search / replace
    editor.replace("old", "new")
    editor.replaceLine(3, "New contents")
     
    # Python regular expressions search and replace
    editor.pyreplace(r"^([A-Z]{3,5})--\1", r"CODE: \1")
     
    # Call a Scintilla function
    editor.appendText("Changed codes\r\n");
     
    # Set clipboard
    editor.copyText("MyTextReadyToPaste") 
     
    # insert character at beginning of line
    editor.rereplace("^","|")
    editor.rereplace("^(.)",r"before_\1")
     
    #insert after
    editor.rereplace("(.)$",r"\1_after")
     
    # replace
    # editor.rereplace(regex, replace) - general
    editor.rereplace("find","replace")
     
    # replace pattern tag with variable elements
    editor.rereplace("<td[^>]*>", "|")
     
    # replace with new line
    editor.rereplace("</tr>", "|\r\n")
     
    # remove pattern
    editor.rereplace("</*tbody>", "")
     
    # replace all tags
    editor.rereplace("<[^>]*>", "")
     
    # delete all blank line
    editor.replace("\r\n\r\n","\r\n")
     
    # delete either ??
    editor.rereplace("__(item|link)__","")
     
    # swap front text and back text
    # ref: http://manual.macromates.com/en/regular_expressions
    ''' example
    <li><a href='https://addons.mozilla.org/en-US/firefox/addon/copy-urls-expert/'>Copy Urls Expert</a></li>
    <li><a href='https://addons.mozilla.org/en-US/firefox/addon/awesome-screenshot-capture-/'>Awesome Screenshot Plus</a></li>
    <li><a href='https://adblockplus.org/en/'>Add-on Search: AdBlock Plus</a></li>
    <li><a href='https://adblockplus.org/en/elemhidehelper'>Add-on Search: Element Hiding Helper for ABP</a></li>
    <li><a href='https://addons.mozilla.org/en-US/firefox/addon/image-block/'>Image block toggle</a></li>
    <li><a href='https://addons.mozilla.org/en-US/firefox/addon/js-switch/'>JS switch</a><li>
    <li><a href='https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/'>SQLite Manager (sql datebase editor)</a><li>
    '''
    editor.rereplace("<li.+'(.+)'>(.+)<\/a.+li>","\2, \1")
    ''' result
    Copy Urls Expert, https://addons.mozilla.org/en-US/firefox/addon/copy-urls-expert/
    Awesome Screenshot Plus, https://addons.mozilla.org/en-US/firefox/addon/awesome-screenshot-capture-/
    Add-on Search: AdBlock Plus, https://adblockplus.org/en/
    Add-on Search: Element Hiding Helper for ABP, https://adblockplus.org/en/elemhidehelper
    Image block toggle, https://addons.mozilla.org/en-US/firefox/addon/image-block/
    JS switch, https://addons.mozilla.org/en-US/firefox/addon/js-switch/
    SQLite Manager (sql datebase editor), https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
    '''

python console cmds

  • open console: Plugin menu > Python Script > Show Console
  • the console included with NPP-python script plugin is a true python console, so everything in python console works here
  • python console
    # Write to the console window
    console.write("Saved as %s\n" % newFilename)
     
    # Run a command on the file, and output results to the new file
    console.run('compiler.exe "%s"' % newFilename, editor)
  • common python cmds operation
    # change working directory in console
    import os
    os.listdir('./')
     
    # list wildchar files
    import glob
    glob.glob('*.py')
     
    # list file
    for filename in os.listdir("C:\\temp"):
        print filename
     
    # show files
    print [d for d in os.listdir('./') if d.endswith(".py")]
    [s in os.listdir('./') if s.endswith('.f') or s.endswith('.c') or s.endswith('.z')]
    [s in os.listdir('./') if s.rpartition('.')[2] in ('f','c','z')]

Integrate Your Python Script with Notepad++

  • the default loading directory for NppPythonScript plugin, any script will be automatically add to path for import
    npp\plugins\PythonScript\lib
    npp\plugins\PythonScript\scripts 
    npp\plugins\Config\PythonScript\lib
    npp\plugins\Config\PythonScript\scripts
  • the default script for loading/running automatically should be named “startup.py” and placed in any of above location
  • example of a startup.py to enable error feedback in python console (as the default python console doesn't tell you any error)
    startup.py
    # ref: https://github.com/bruderstein/PythonScript/blob/master/scripts/startup.py
    # The lines up to and including sys.stderr should always come first
    # Then any errors that occur later get reported to the console
    # If you'd prefer to report errors to a file, you can do that instead here.
    import sys
    from Npp import *
     
    # Set the stderr to the normal console as early as possible, in case of early errors
    sys.stderr = console
     
    # Define a class for writing to the console in red
    class ConsoleError:
    	def __init__(self):
    		global console
    		self._console = console;
     
    	def write(self, text):
    		self._console.writeError(text);
     
    # Set the stderr to write errors in red
    sys.stderr = ConsoleError()
     
    # This imports the "normal" functions, including "help"
    import site
     
    # This sets the stdout to be the currently active document, so print "hello world", 
    # will insert "hello world" at the current cursor position of the current document
    sys.stdout = editor

Show your scripts in Plugin menu > Python Script > Scripts

  • if you put your scripts above default loading directories, it will automatically show in the above menu place.
  • if you want to put your scripts in a custom location like “D:\Lib\npp_script”, then you need to modify this config file to register these script item
    npp\plugins\Config\PythonScriptStartup.cnf
    • example config code
      ITEM/D:\Lib\npp_script\date.py
      ITEM/D:\Lib\npp_script\my_script1.py
    • then it will show up in Python script > configuration panel, which further enable use in Context Menu
  • Note:
    • if you put script for importing in other location as well, make sure add that lib/module path with sys.path.append in startup.py (its auto loading script), which sits in any of these default PythonScript plugin default loading directories
    • or if you prefer lazy loading module from your running script, you can add code at beginning like
      import os,sys
      cur_path = os.path.dirname(__file__)
      cur_path in sys.path or sys.path.append(cur_path)

add your script to context menu

  1. add your script in default location to menu from Python Script > Configuration panel, or use PythonScriptStartup.cnf mentioned above to register script item in custom directory
  2. then add this to contextMenu.xml (Settings > Edit pop up context menu)
    <Item PluginEntryName="Python Script" PluginCommandItemName="my_script1" />
  3. or put in a sub menu called script with FolderName
    <Item FolderName="Script" PluginEntryName="Python Script" PluginCommandItemName="date" />

add your script to tool bar with icon

  1. add your script in default location to toolbar from Python Script > Configuration panel, or use PythonScriptStartup.cnf mentioned above to add script item in custom directory
  2. set the icon using 16×16 BMP normal image format file
  • note
    • all the setting is stored in npp\plugins\Config\PythonScriptStartup.cnf, sample code like
      ITEM/D:\Lib\npp_script\date.py
      ITEM/D:\Lib\npp_script\my_script1.py
      TOOLBAR/D:\Lib\npp_script\date.py/D:\_icon\date.bmp
      TOOLBAR/D:\Lib\npp_script\my_script1.py/D:\_icon\one.bmp
      SETTING/STARTUP/LAZY

My Npp Python Script

  • add date yyyy.mm.dd
    date.py
    import time
    import Npp
    # import sys
    timeStr = time.strftime( '%Y.%m.%d' )
    # sys.stdout.write(timeStr)
    Npp.editor.addText( timeStr )
  • add level mark
    from Npp import *
    selected = editor.getSelText()
    editor.replaceSel('---- {0} ----'.format(selected))
  • run PyQt4 or other Qt inside notepad++
    import sys
    my_path = r'/your_path_to_standard_site_package/'
    my_path in sys.path or sys.path.append(my_path)
     
    from Npp import *
    from PyQt4 import QtGui
    from functools import partial
    a = QtGui.QApplication([])
    w = QtGui.QWidget()
    main_layout = QtGui.QHBoxLayout()
    w.setLayout(main_layout)
    my_label = QtGui.QLabel('Hello')
    my_btn = QtGui.QPushButton('Text')
    main_layout.addWidget(my_label)
    main_layout.addWidget(my_btn)
    my_btn.clicked.connect(partial(editor.addText,'cool'))
    w.show()
    a.exec_()