appwiki:notepadplusplus

Differences

This shows you the differences between two versions of the page.


Previous revision
appwiki:notepadplusplus [2023/02/06 06:40] (current) – [Plugin - PythonScript] ying
Line 1: Line 1:
 +====== Notepad++ Editing Techniques ======
  
 +**navigation tips**
 +
 +  * Bookmark point and jump
 +    - click the line number to create a bookmark
 +    - 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 <code>[^\x00-\x7F]+</code>
 +**replace tips**
 +
 +  * replace "a pattern" (like "<td id='row15'>" ) <code>
 +Replace dialog search mode: regular expression
 +search: <td id='row..'>
 +replace:
 +note: . : means representing a unknown char
 +</code>
 +  * replace "a blank line" <code>
 +Replace dialog search mode: extended
 +search : \r\n\r\n
 +replace: \r\n
 +note: \r\n\r\n means double new lines
 +</code>
 +  * get rid of tabs and spaces in blank lines <code>
 +Replace dialog search mode: regular expression
 +find: ^\s*$
 +replace: 
 +note: start and any mount space or tab and a end
 +</code>
 +
 +====== 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):
 +    * ref: http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Context_Menu
 +    * file location <code>npp_root\contextMenu.xml</code>
 +  * default tab size
 +    * Settings -> Preferences -> Language Menu/Tab Settings tab -> The tab options at bottom right.
 +  * split view \\ {{:appwiki:npp_split_view.png?400|}}
 +
 +===== syntax highlight =====
 +
 +  * mel syntax highlight: 
 +    * download from http://www.creativecrash.com/downloads/applications/syntax-scripting/c/mel-language-definition-for-notepad-
 +    * put mel.api into ./plugin/api folder
 +    * put userDefineLang.xml and insertExt.ini into root folder or under user npp root folder
 +      * userDefineLang.xml to %userprofile%\AppData\Roaming\Notepad++\
 +
 +  * 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 <code xml>< Language name="haskell" ext="hs lhs as las" commentLine="--" ></code>
 +
 +  * 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.
 +
 +===== make Npp portable =====
 +
 +  * method 1: install and copy the notepad++ folder out
 +  * method 2: download Npp portable from http://portableapps.com/apps/development/notepadpp_portable
 +
 +====== 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 ^
 +| [[http://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/|Hex Editor]] | Hex code file editing |
 +| TextFX | automate common text typing operation |
 +| [[http://sourceforge.net/projects/npp-compare/|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++ |
 +
 +  * coding snipple tool
 +    - [[https://www.youtube.com/watch?v=OfoU_7YVqEI|Zen Coding - syntax codegen]] (it has [[http://code.google.com/p/zen-coding/|js version]], and [[http://sourceforge.net/projects/npppythonscript/files/ZenCoding-Python/|new python version]])
 +      * example syntax for create 15x12 table with row id and col class (press ctrl_alt_enter)<code>
 +table>tr#row-$*15>td.col-$*12
 +</code>
 +    - [[https://www.youtube.com/watch?v=AUdlHORCHy8|QuickText - snippet gen]]
 +    - [[https://www.youtube.com/watch?v=7xNeUbsScUc|Code Express -snippet gen and expression]]
 +
 +===== Plugin - PythonScript =====
 +
 +  * install:
 +    * install/get latest notepad++
 +    * from plugin manager, search python script, check and install (default is v2, w python 2.7.18, you can use same method to manually use alpha py3.10.9 version with same method)
 +    * for tkinter lib, go lastest release version: https://github.com/bruderstein/PythonScript/releases/
 +      * unzip PythonScript_TclTk_xxx.xxx.zip, and copy lib into npp/plugins/PythonScripts lib folder.
 +      * (optional) unzip  PythonScript_ExtraLibs_xxxx.zip if you need lib2to3, distutils,bsddb
 +    * (outdate) <del>or download manually and put in plugin folder from http://npppythonscript.sourceforge.net/
 +</del>
 +  * Python for Npp document
 +    * http://npppythonscript.sourceforge.net/docs/latest/
 +    * Npp.editor cmd: http://npppythonscript.sourceforge.net/docs/latest/scintilla.html#scintilla-methods
 +    * Npp app object cmd: http://npppythonscript.sourceforge.net/docs/latest/notepad.html
 +
 +  * **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 <code python>
 +from Npp import *
 +# test
 +editor.addText('test')
 +</code>
 +
 +==== notepad cmds ====
 +  * file operation<code python>
 +# Create a new document
 +notepad.new()
 +
 +# open file
 +notepad.open("\web\index.htm")
 +
 +# Save the file
 +newFilename = notepad.getCurrentFilename() + ".changed"
 +notepad.saveAs(newFilename);
 +</code>
 +  * setting operation <code python>
 +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
 +</code>
 +  * user input <code python>
 +# 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")
 +</code>
 +
 +
 +==== 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 <code python>
 +# 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/
 +'''
 +</code>
 +
 +==== 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 <code python>
 +# 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)
 +</code>
 +  * common python cmds operation <code python>
 +# 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')]
 +</code>
 +
 +==== Integrate Your Python Script with Notepad++ ====
 +
 +  * the default loading directory for NppPythonScript plugin, any script will be automatically add to path for import <code>
 +npp\plugins\PythonScript\lib
 +npp\plugins\PythonScript\scripts (default startup.py is here)
 +npp\plugins\Config\PythonScript\lib
 +npp\plugins\Config\PythonScript\scripts
 +</code>
 +  * 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) <code python 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
 +</code>
 +
 +**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 <code>npp\plugins\Config\PythonScriptStartup.cnf</code>
 +    * example config code <code>
 +ITEM/D:\Lib\npp_script\date.py
 +ITEM/D:\Lib\npp_script\my_script1.py
 +</code>
 +    * 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 <code python>
 +import os,sys
 +cur_path = os.path.dirname(__file__)
 +cur_path in sys.path or sys.path.append(cur_path)
 +</code>
 +
 +**add your script to context menu**
 +
 +  - 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
 +  - then add this to contextMenu.xml (Settings > Edit pop up context menu) <code xml><Item PluginEntryName="Python Script" PluginCommandItemName="my_script1" /></code>
 +  - or put in a sub menu called script with FolderName <code xml><Item FolderName="Script" PluginEntryName="Python Script" PluginCommandItemName="date" /></code>
 +
 +**add your script to tool bar with icon**
 +
 +  - 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
 +  - set the icon using 16x16 BMP normal image format file
 +
 +  * **note**
 +    * all the setting is stored in npp\plugins\Config\PythonScriptStartup.cnf, sample code like <code>
 +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
 +</code>
 +
 +
 +==== 3rd party addon using notepad++ and pythonscript ====
 +
 +  * pythonscript git: https://github.com/bruderstein/PythonScript
 +  * use notepad as interactive python runner: https://github.com/bitagoras/PyPadPlusPlus
 +
 +==== Qt GUI and PythonScript ====
 +
 +  * 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, 
 +      * search version number in https://www.python.org/downloads/
 +      * (my case) https://www.python.org/downloads/release/python-2718/
 +    * 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) <code python>
 +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")
 +</code>
 +  * add that standalone package path to PythonScript config startup.py file <code>
 +# notepad path\plugins\Config\PythonScript\scripts\startup.py
 +</code> and code <code python>
 +# 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)
 +
 +</code>
 +==== My Npp Python Script ====
 +
 +  * add date yyyy.mm.dd <code python date.py>import time
 +import Npp
 +# import sys
 +timeStr = time.strftime( '%Y.%m.%d' )
 +# sys.stdout.write(timeStr)
 +Npp.editor.addText( timeStr )
 +</code>
 +  * add level mark <code python>
 +from Npp import *
 +selected = editor.getSelText()
 +editor.replaceSel('---- {0} ----'.format(selected))
 +</code>
 +
 +  * run PyQt4 or other Qt inside notepad++ <code python>
 +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_()
 +</code>