Community
    • Login

    How can I pass a search term to Notepad++ via command?

    Scheduled Pinned Locked Moved Help wanted · · · – – – · · ·
    6 Posts 4 Posters 49 Views
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • N
      Native2904
      last edited by

      Hello,
      I wanted to ask if it’s possible to pass a value to Notepad++ that is then immediately searched for and highlighted in the file being opened.

      Something like this:

      notepad++.exe "%1" -(search) "term"
      

      Is there a command, parameter, or plugin that allows this to be automated?

      Thank you in advance for your help!

      PeterJonesP 1 Reply Last reply Reply Quote 0
      • PeterJonesP
        PeterJones @Native2904
        last edited by

        @Native2904 ,

        Notepad++ doesn’t natively have a command-line-based search syntax. Sorry.

        It has come up a few times before, like “How to start a search automatically” and “Find in Files from command line” (warning: toward the end of both of those, the discussion devolves because of a new direction someone took the conversation; focus on the earlier portions of those discussions).

        Using a script in the PythonScript plugin to process the -pluginMessage could be used for such a thing. But I don’t know that anyone’s implemented it. It never made it to a full script in those previous discussions, because @alankilborn offered, but the OP actually made a VB.net script for it in this post, so @alankilborn never published a PythonScript solution. Unfortunately, he’s not around as much anymore, but if he didn’t already write it, he’s not likely to.

        I don’t know of any plugins that have implemented a start-search-from--pluginMessage: it might make sense for the custom-search gurus – I was about to suggest @coises’s Columns++ … but as I was typing this reply, he posted about a new Search++, which is probably a better place for it: he might be willing to add -pluginMessage processing to trigger a search from the command-line.

        (If @Coises doesn’t seem interested, I might be willing to try to convert the VB.net script into a PythonScript solution… But some users have found it hard to get PythonScript solutions working, despite our FAQ which is supposed to help.)

        CoisesC PeterJonesP Alan KilbornA 3 Replies Last reply Reply Quote 0
        • CoisesC
          Coises @PeterJones
          last edited by

          @PeterJones said in How can I pass a search term to Notepad++ via command?:

          I don’t know of any plugins that have implemented a start-search-from–pluginMessage: it might make sense for the custom-search gurus – I was about to suggest @coises’s Columns++ … but as I was typing this reply, he posted about a new Search++, which is probably a better place for it: he might be willing to add -pluginMessage processing to trigger a search from the command-line.

          (If @Coises doesn’t seem interested, I might be willing to try to convert the VB.net script into a PythonScript solution… But some users have found it hard to get PythonScript solutions working, despite our FAQ which is supposed to help.)

          Offhand, it seems like it would make sense. However, my new plugin still has a lot of work to be done to refine its basic features and add major missing ones. This is a good idea; I’m just not likely to get to it anytime soon.

          1 Reply Last reply Reply Quote 2
          • PeterJonesP
            PeterJones @PeterJones
            last edited by PeterJones

            @PeterJones said in How can I pass a search term to Notepad++ via command?:

            I might be willing to try to convert the VB.net script into a PythonScript solution

            Here’s my first stab.

            Instructions:

            {these assume a normal installation of Notepad++, using %AppData%\Notepad++ for user configuration}

            See PythonScript FAQ

            • Create %AppData%\Notepad++\plugins\PythonScript\scripts\commandlineSearch27482.py, from the contents below
            • Check for menu entry Plugins > Python Script > Scripts > startup (User)
              • if it is listed, Ctrl+click on it to edit, and add the following to the end:
                import commandlineSearch27482
                
              • if it isn’t listed, create %AppData%\Notepad++\plugins\PythonScript\scripts\user.py from the contents below
              • set Plugins > Python Script > Configuration… to Initialisation: ATSTARTUP
              • exit and restart Notepad++

            After doing that, the script should look for
            notepad++ -pluginMessage="PythonScriptCommandlineSearch=term", and run a search for term

            For example,

            notepad++ -pluginMessage="PythonScriptCommandlineSearch=BM_CLICK"
            

            was able to find BM_CLICK instance when commandlineSearch27482.py is in the editor, so I think it works, (it worked whether N++ was already running, or whether this call was the first launch)

            Caveat: For now, it won’t work with semicolon ; or double-quote " in the search term; if that is needed, I would need to add an escape sequence processing, which would make it more complicated. But as it is, it should handle >90% of desired standard searches…

            commandlineSearch27482.py:

            # encoding=utf-8
            """in response to https://community.notepad-plus-plus.org/topic/27472/ 
            (fixed URL)
            
            process -pluginMessage="PythonScriptCommandlineSearch=term"
            
            `term` must be a normal search term, not a regular expression; it currently cannot include semicolons `;` or double-quotes `"`
            """
            #####   -------
            #####   Instructions:
            #####
            #####   {these assume a normal installation of Notepad++, using %AppData%\Notepad++ for user configuration}
            #####
            #####   See [PythonScript FAQ](https://community.notepad-plus-plus.org/topic/23039/faq-how-to-install-and-run-a-script-in-pythonscript)
            #####
            #####   - Create `%AppData%\Notepad++\plugins\PythonScript\scripts\commandlineSearch27482.py`, from the contents below
            #####   - Check for menu entry **Plugins > Python Script > Scripts > startup (User)**
            #####       - if it is listed, `Ctrl+click` on it to edit, and add the following to the end:
            #####       - if it isn't listed, create `%AppData%\Notepad++\plugins\PythonScript\scripts\user.py` from the contents below
            #####       - set **Plugins > Python Script > Configuration...** to **Initialisation: `ATSTARTUP`**
            #####       - exit and restart Notepad++
            #####
            #####   After doing that, the script should look for
            #####   `notepad++ -pluginMessage="PythonScriptCommandlineSearch=term"`, and run a search for `term`
            #####
            #####   For now, it won't work with semicolon `;` or double-quote `"` in the search term;
            #####       if that is needed, I would need to add an escape sequence processing, which would make it more complicated.
            #####   -------
            
            
            from Npp import notepad, console, NOTIFICATION, MENUCOMMAND
            import ctypes
            import sys
            import re
            
            import ctypes
            from ctypes.wintypes import HWND, UINT, WPARAM, LPARAM, HMODULE, LPCWSTR, LPCSTR, LPVOID
            
            def usePluginMessageString27482(s):
                m = re.search(r'PythonScriptCommandlineSearch=([^;"]+)', s)
                t = m.group(1)
            
                # Define the functions and constants needed
                FindWindow = ctypes.windll.user32.FindWindowW
                FindWindow.argtypes = [LPCWSTR, LPCWSTR]
                FindWindow.restype  = HWND
            
                FindWindowEx = ctypes.windll.user32.FindWindowExW
                FindWindowEx.argtypes = [HWND, HWND, LPCWSTR, LPCWSTR]
                FindWindowEx.restype  = HWND
            
                SendMessage = ctypes.windll.user32.SendMessageW
                SendMessage.argtypes = [HWND, UINT, WPARAM, LPARAM]
                SendMessage.restype  = LPARAM
            
                SendMessageStr = ctypes.windll.user32.SendMessageW
                SendMessageStr.argtypes = [HWND, UINT, WPARAM, LPCWSTR]
                SendMessageStr.restype  = LPARAM
            
                SendDlgItemMessage = ctypes.windll.user32.SendDlgItemMessageW
                SendDlgItemMessage.argtypes = [HWND, UINT, UINT, WPARAM, LPARAM]
                SendDlgItemMessage.restype = LPARAM
            
                WM_SETTEXT = 0x000C
                BM_CLICK = 0x00F5
            
                # see https://community.notepad-plus-plus.org/post/59785 for VB.net inspiration
                notepad.menuCommand(MENUCOMMAND.SEARCH_FIND)
                hFindWnd = FindWindow("#32770", "Find")
                hComboBx = FindWindowEx(hFindWnd, 0, "ComboBox", None) if hFindWnd else 0
                hFindStr = FindWindowEx(hComboBx, 0, "Edit", None) if hComboBx else 0
                SendMessageStr(hFindStr, WM_SETTEXT, 0, t)
            
                # set search mode:
                hNormBtn = FindWindowEx(hFindWnd, 0, "Button", "&Normal")
                if hNormBtn:
                    SendMessageStr(hNormBtn, BM_CLICK, 0, None)
            
                # start search
                hFindBtn = FindWindowEx(hFindWnd, 0, "Button", "Find Next")
                #console.write(f"FindWindows: FIND={hFindWnd:08X} ComboBox={hComboBx:08X} FindNext:{hFindBtn:08X}\n")
                if hFindBtn:
                    SendMessageStr(hFindBtn, BM_CLICK, 0, None)
            
                # TODO: I'd like to try SendDlgItemMessageW(hFindWnd, ctrlID, BM_CLICK, 0, 0), to avoid having to search for the "Find Next" button
                #   but using the 1625 from search macros, I couldn't get it to change Search Mode, so just manually click the buttons for now
            
            def getStringFromNotification27482(args):
                code = args['code'] if 'code' in args else None
                idFrom = args['idFrom'] if 'idFrom' in args else None
                hwndFrom = args['hwndFrom'] if 'hwndFrom' in args else None
                #console.write(f"notification(code:{code}, idFrom:{idFrom}, hwndFrom:{hwndFrom}) received\n")
                if idFrom is None: return
                s = ctypes.wstring_at(idFrom)
                #console.write(f"\tAdditional Info: str=\"{s}\"\n")
                usePluginMessageString27482(s)
            
            def getStringFromCommandLine27482():
                for token in sys.argv:
                    if len(token)>15 and token[0:15]=="-pluginMessage=":
                        s = token[15:]
                        #console.write(f"TODO: process {token} => \"{s}\"\n")
                        usePluginMessageString27482(s)
            
            notepad.callback(getStringFromNotification27482, [NOTIFICATION.CMDLINEPLUGINMSG])
            console.write("Registered getStringFromNotification27482 callback for CMDLINEPLUGINMSG\n")
            getStringFromCommandLine27482()
            

            startup.py: if you need to create it, use the following

            from Npp import *
            import sys
            
            console.write("Start of user startup.py\n")
            
            # add scripts folder to the path
            #d = notepad.getPluginConfigDir() + r'\PythonScript\Scripts\nppCommunity'
            #if not d in sys.path:
            #    sys.path.append(d)
            # updated to https://community.notepad-plus-plus.org/topic/22299/convenience-technique-when-organizing-pythonscripts-into-folders
            import os
            for (root, dirs, files) in os.walk(notepad.getPluginConfigDir() + r'\PythonScript\scripts', topdown=False):
                if root not in sys.path:
                    sys.path.append(root)
            
            import commandlineSearch27482
            
            PeterJonesP 1 Reply Last reply Reply Quote 0
            • Alan KilbornA
              Alan Kilborn @PeterJones
              last edited by

              @PeterJones said:

              …so @alankilborn never published a PythonScript solution. Unfortunately, he’s not around as much anymore

              I’m definitely “around”, but more of a lurker these days. :-)

              1 Reply Last reply Reply Quote 0
              • PeterJonesP
                PeterJones @PeterJones
                last edited by

                @PeterJones said in How can I pass a search term to Notepad++ via command?:

                commandlineSearch27482

                just noticed that this is actually topic/27472, not 27482… but I’m not going to change all my comments and variable names at this point. Well, maybe the comment with the URL.

                1 Reply Last reply Reply Quote 0
                • First post
                  Last post
                The Community of users of the Notepad++ text editor.
                Powered by NodeBB | Contributors