appwiki:notepadplusplus

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)

find non ascii

  • find in regex
    [^\x00-\x7F]+

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')
  • 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")

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/
    '''
  • 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')]
  • 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 (default startup.py is here)
    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
  • To get Qt (PySide or PyQt4) to work with PythonScript, (depends on your pythonscript's python version)
    • if you use Plugins > PythonScript > Show Console, it will show the python 2.7.18 in 64bit (my case) as the python version
    • download the same or similar version of Python from python offical website,
    • download “Windows x86-64 MSI installer”, you can install to a special path if you want to make it not affect your system.
      • in install step, you can choose where to install, and where add python.exe to path, by default it won't, as if you already have multiple python versions installed, choose not add to path will not affect your current setup, choose add to path, if you want it to be your default python as well. (my case, I just want it to be a py2.7 package download, so I don't check add python.exe to path during install)
    • once ok, you can use your own python to install package, and add the site-packages path to PythonScript python's sys.path
    • start your standalone python, and run (PySide,PyQt4,PySide2,PyQt5 depends on your PythonScript plugin's python version)
      import subprocess
      import sys
      def install(package):
          subprocess.check_call([sys.executable, "-m", "pip", "install", package])
      # py2 case: 2.7 = PySide
      install("PySide")
       
      # py3 case: 3.x = PySide2
      install("PySide2")
  • add that standalone package path to PythonScript config startup.py file
    # notepad path\plugins\Config\PythonScript\scripts\startup.py

    and code

    # optional clear multiple python registered system path issue
    old_path = sys.path
    old_path = [x for x in old_path if not x.startswith('D:\\my_other_system_env_registered_python_path\\Python27') ]
    sys.path = old_path
     
    # register lib path
    import os
    my_path_list =[
        r'D:\my_path_match_version_local_python_path\Python27\Lib\site-packages',
        r'D:\my_path_to_other_mpp_app_i_write\NppCoder',
        r'D:\my_path_to_other_npp_script\npp_script'
        ]
    for x in my_path_list:
        if os.path.isdir(x):
            sys.path.append(x)
  • 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_()
  • appwiki/notepadplusplus.txt
  • Last modified: 2023/02/06 06:40
  • by ying