Search code examples
syntax-highlightingnotepad++

Notepad++ : Custom Syntax Highlighting for .txt files


I keep code samples that I find useful as text files on my computer. I store them as txt files as opposed to the language in which they are written, so that they will open in Notepad++ instead of the editor (i.e. I don't want my c++ examples to open in an IDE, just Notepad).

Is there a way I can have Notepad++ apply appropriate syntax highlighting to the text file by reading a special code in the text file itself?

For example if I had some sql, the first line of the text file could read like this:

##Language=SQL 

... my sql code properly highlighted as sql ...

Thanks in advance. I realize I could just choose the language after opening the file (i.e. Language > SQL), but it would be much more convenient if it could do it automatically.


Solution

  • I ended up writing it myself:

    1. You need the Python plugin

    2. Add the code below to your startup.py file

    3. Switch your Python Initialization setting from "LAZY" to "ATSTARTUP"

    #if found determine the menu command and switch language in NPP
    def switch_language_view(args):
        notepad.activateBufferID(args["bufferID"])
        lineone = editor.getLine(0)
        if '##' in lineone:
            lineone = lineone[lineone.rfind('##'):].replace('##', '')
            lineone = "MENUCOMMAND." + lineone.upper()
            try:
                notepad.menuCommand( eval(lineone) )
            except:
                pass
    
    #command to link notification
    notepad.callback(switch_language_view, [NOTIFICATION.FILEOPENED])