Community
    • Login

    Notepad++ Restart Shortcut Key

    Scheduled Pinned Locked Moved General Discussion
    17 Posts 7 Posters 5.8k 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.
    • Alan KilbornA
      Alan Kilborn @Lycan Thrope
      last edited by

      @lycan-thrope

      Hmm, not sure how I could have made it simpler, but I will try:

      Click on the Run menu to drop it down:

      76a5bc13-9882-4abd-b4bc-4a23eeefa055-image.png

      Pick Run… from the menu that has dropped:

      dbbba74e-d784-473a-a85e-554f7f07c0b3-image.png

      A box appears:

      8cf95034-14ef-4d16-87db-f47fa9873f2a-image.png

      Paste in the text I supplied earlier:

      d380d95a-7b5e-4ee8-8886-a96aca247c66-image.png

      The full text won’t show because the box on the screen is too narrow, but it is all there.

      Press Save… to see:

      286d118f-c37f-443b-b545-4e3f117c5fe4-image.png

      Give it a name, example:

      c3769a6a-1e72-4926-ae44-a6113ee959a3-image.png

      Press OK, box closes.

      Click Run menu again (reference first screenshot) to get dropdown with some new content:

      5db5c514-7817-41bd-8261-26e45e60c9ee-image.png

      So you’d select this when you want to restart Notepad++.

      Hopefully that clarifies.

      Lycan ThropeL 1 Reply Last reply Reply Quote 2
      • artie-finkelsteinA
        artie-finkelstein @David-Maisonave 0
        last edited by

        @david-maisonave-0 said in Notepad++ Restart Shortcut Key:

        I thought this trick would make a nice addition to my “npp_config.bat” file for editing editor and plugin configuration files, however there appear to be ‘caveats’ related to it’s use. All testing so far has been performed by manually using the Run menu selection. My usage environment (with the plugins data removed):

        Notepad++ v8.1.9   (32-bit)
        Build time : Oct 21 2021 - 23:32:04
        Path : C:\Programs\Notepad++\notepad++.exe
        Command Line : 
        Admin mode : ON
        Local Conf mode : ON
        Cloud Config : OFF
        OS Name : Windows 7 Professional (64-bit) 
        OS Build : 7601.0
        Current ANSI codepage : 1252
        

        && TIMEOUT /T 1 &&

        It appears the timeout command is required to get the Npp restart to trigger properly, i.e., no timeout, no relaunch (even after the obligatory manual restart of Notepad++ to (re-)read the ‘shortcuts.xml’ file).

        As expected, Notepad does not object to being ‘non-forcefully’ shutdown with open files if Settings > Preferences > Backup > Enable session snapshot and periodic backup is checked. If the option is not checked, Notepad++ raises it’s ‘Save file…’ dialog to allow saving, but then the restart does not happen, regardless of saving or not saving any modified files, however, ‘cancel’ does cancel the inherent close command from “taskkill” and the following restart from the ‘user defined command’. I have not tried delay times other than 1 second.

        As @alan-kilborn, I also use a pinned tab on the task bar for fast getaways and restarts. I’m of very mixed feelings about fully automating the restart. I’d rather blame my fingers instead of my code when I screw up an important file save, but that won’t stop a few test runs tomorrow.

        dinkumoilD 1 Reply Last reply Reply Quote 0
        • dinkumoilD
          dinkumoil @artie-finkelstein
          last edited by dinkumoil

          @artie-finkelstein said in Notepad++ Restart Shortcut Key:

          It appears the timeout command is required to get the Npp restart to trigger properly, i.e., no timeout, no relaunch

          As expected, Notepad does not object to being ‘non-forcefully’ shutdown with open files if Settings > Preferences > Backup > Enable session snapshot and periodic backup is checked. If the option is not checked, Notepad++ raises it’s ‘Save file…’ dialog to allow saving, but then the restart does not happen, regardless of saving or not saving any modified files

          The reason for both of these observations is that you are likely running Notepad++ in “Single Instance” mode and the timeout period of 1 second is too short to completely shut down the process of the already running Notepad++ instance. Thus, the new Notepad++ instance (started by the start command) notices that there is already another Notepad++ process running in the system and terminates itself. If you increase the timeout period to, for example, 5 seconds or even more, the restart should work.

          The above is the reason why I use a more sophisticated solution to automatically restart Notepad++ - a VBScript using WMI classes and events, see the code below. This solution also only works if Notepad++ is set up to work in “Single Instance” mode, but it works nearly reliable (see below) and only restarts that instance of Notepad++ from which the script has been launched. Thus, it is possible to run at the same time another (maybe portable) version of Notepad++ from another directory set up to “Multiple Instances” mode - these instances will not be terminated by the script.

          Why did I say “nearly reliable”? If Notepad++ is set up to not using sessions+backups and you click your menu entry to restart Notepad++, the confirmation dialog appears. If you click “Cancel”, Notepad++ keeps running. But in the background my script keeps running as well because it waits for the Notepad++ process to terminate. If you later on terminate Notepad++ manually (because you’ve finished your work), unexpectedly a new instance of Notepad++ starts up - the script running in background has satisfied its wait condition (a Notepad++ process has been terminated) and launches a new Notepad++ instance. To overcome this problem maybe a timeout could be introduced to break the waiting loop after a certain amount of time, but then the snake bites in its tail - this timeout would be sometimes too short and sometimes too long, the same situation like where you are now.

          Here is the code of my script (I stored it as RestartNpp.vbs in a subdirectory of the Notepad++ installation directory called exttools):

          Option Explicit
          
          
          '-------------------------------------------------------------------------------
          'Variables declaration
          '-------------------------------------------------------------------------------
          Dim objFSO, objWshShell, objWMIService
          Dim colProcesses, objProcess, strInstanceQuery
          Dim colEvents, objEvent, strEventQuery, intInterval
          Dim strNppDirPath, strNppExeName, strNppExePath
          
          
          '-------------------------------------------------------------------------------
          'Variables initialization
          '-------------------------------------------------------------------------------
          Set objFSO        = CreateObject("Scripting.FileSystemObject")
          Set objWshShell   = CreateObject("WScript.Shell")
          Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2" )
          
          strNppExeName     = "notepad++.exe"
          intInterval       = 1
          
          
          '-------------------------------------------------------------------------------
          ' Request termination of running Npp, wait for its termination and restart it
          '-------------------------------------------------------------------------------
          If WScript.Arguments.Count > 0 Then
            strNppDirPath   = WScript.Arguments(0)
            strNppExePath   = objFSO.BuildPath(strNppDirPath, strNppExeName)
          
            If objFSO.FileExists(strNppExePath) Then
              strInstanceQuery = "SELECT * FROM Win32_Process" & _
                                 " WHERE ExecutablePath = '" & EscapeForWMI(strNppExePath) & "'"
          
              strEventQuery    = "SELECT * FROM __InstanceOperationEvent" & _
                                 " WITHIN " & intInterval & _
                                 " WHERE TargetInstance ISA 'Win32_Process'" & _
                                 " AND TargetInstance.ExecutablePath = '" & EscapeForWMI(strNppExePath) & "'"
          
              Set colProcesses = objWMIService.ExecQuery(strInstanceQuery)
          
              For Each objProcess In colProcesses
                objWshShell.Run "taskkill /im " & Quote(strNppExeName), 0, False
          
                Set colEvents = objWMIService.ExecNotificationQuery(strEventQuery)
          
                Do
                  Set objEvent = colEvents.NextEvent()
          
                  Select Case objEvent.Path_.Class
                    Case "__InstanceDeletionEvent" Exit Do
                  End Select
                Loop
          
                objWshShell.CurrentDirectory = objFSO.GetParentFolderName(strNppExePath)
                objWshShell.Run Quote(strNppExePath), 1, False
          
                Exit For
              Next
            End If
          End If
          
          
          
          '===============================================================================
          ' Surround a string with double quotes
          '===============================================================================
          
          Function Quote(ByRef strString)
            Quote = """" & strString & """"
          End Function
          
          
          '===============================================================================
          ' Escape special chars of string for use with WMI
          '===============================================================================
          
          Function EscapeForWMI(ByRef strAString)
            EscapeForWMI = Replace(strAString, "\", "\\")
          End Function
          

          This is the required entry in shortcuts.xml(if you chose another name for the script or another storage location, you have to adapt the path of the script to your needs):

          <Command name="Restart Notepad++" Ctrl="no" Alt="no" Shift="no" Key="0">wscript /nologo &quot;$(NPP_DIRECTORY)\exttools\RestartNpp.vbs&quot; &quot;$(NPP_DIRECTORY)&quot;</Command>
          
          1 Reply Last reply Reply Quote 4
          • andrecool-68A
            andrecool-68
            last edited by andrecool-68

            My example of restarting Notepad++ and resetting to defaults

            In the catalog with NOTEPAD ++. EXE Create a VBS directory with all the necessary files.

              Restart.vbs
              Reset_Restart.vbs
              config.xml
              contextMenu.xml
              session.xml
              shortcuts.xml
              stylers.model.xml
            

            file shortcuts.xml

                <UserDefinedCommands>
                    <Command name="Restart Notepad++" Ctrl="yes" Alt="no" Shift="no" Key="116">&quot;$(NPP_DIRECTORY)\VBS\Restart.vbs&quot;</Command>
                    <Command name="Reset default settings Restart Notepad++" Ctrl="yes" Alt="no" Shift="yes" Key="116">&quot;$(NPP_DIRECTORY)\VBS\Reset_Restart.vbs&quot;</Command>
            

            Restart Notepad++

            file Restart.vbs

            Q = "winmgmts:\\.\root\cimv2:win32_process.Handle="
            With CreateObject("WScript.Shell")
              .CurrentDirectory = Left(WSH.ScriptFullName, InStrRev(WSH.ScriptFullName, "\"))
              With GetObject(Q & .Exec("rundll32 kernel32,Sleep").ProcessId)
                PID = GetObject(Q & .ParentProcessId).ParentProcessId: .Terminate
              End With
                .Run "taskkill /PID " & PID, 0, 1: WSH.Sleep 200: .Run "..\notepad++.exe"
            End With
            

            Reset default settings Restart Notepad++

            file Reset_Restart.vbs

            Set oWSH = CreateObject("WScript.Shell")
            oWSH.CurrentDirectory = Left(WSH.ScriptFullName, InStrRev(WSH.ScriptFullName, "\"))
            Q = "winmgmts:\\.\root\cimv2:win32_process.Handle="
            With GetObject(Q & oWSH.Exec("rundll32 kernel32,Sleep").ProcessId)
               GetObject(Q & GetObject(Q & .ParentProcessId).ParentProcessId).Terminate: .Terminate
            End With
            CreateObject("Scripting.FileSystemObject").CopyFile "*.xml", "..", 1
            oWSH.Run "..\notepad++.exe": Set oWSH = Nothing
            
            dinkumoilD 1 Reply Last reply Reply Quote 1
            • dinkumoilD
              dinkumoil @andrecool-68
              last edited by

              @andrecool-68

              Nice way to get Npp’s PID, though it is very cryptic code. I prefer readable and understandable code over short code.

              andrecool-68A 1 Reply Last reply Reply Quote 1
              • andrecool-68A
                andrecool-68 @dinkumoil
                last edited by

                @dinkumoil The author of the code is here https://www.cyberforum.ru/vbscript-wsh/thread2616849.html

                1 Reply Last reply Reply Quote 0
                • Lycan ThropeL
                  Lycan Thrope @Alan Kilborn
                  last edited by

                  @alan-kilborn apologies, this forum takes a little getting used to. :(

                  Pasted here to keep on topic.
                  Wow, thanks for those picture explanations, Alan, and clueing me into some of Notepa++ functionality I haven’t known about. To be honest, I’m just going beyond using it as a sytax-highlighting general purpose file editor and trying to use it to add a UDL/FunctionList for an old language that hasn’t been done before. That’s why it took so long to respond…I’ve been beating my head trying to learn regex, use the tools this forum recommended, and try and make heads or tails out of the FunctionList structure by looking over the C++ FunctionList…and not getting very far yet. :(

                  However it was a pleasure to see it laid out simply with pics. I do that a lot myself when trying to explain things to folks so it’s “a thousand words clear” what you are saying. I have never touched the “Run” menu option, so that should give you a hint about how new I am to NPP’s large functional footprint. Thanks again…and if anyone can do the same for the FunctionList explanation of a mixed parser and what needs to go where, it would be greatly appreciated. :)

                  Lee

                  1 Reply Last reply Reply Quote 2
                  • Alan KilbornA
                    Alan Kilborn
                    last edited by

                    I often use a second Notepad++ instance for testing out scripts that I’m considering sharing/posting. Many times these scripts have bugs while developing (of course!) and I need to restart my testbed instance of N++ to clear things out for a fresh test run.

                    Well, the base technique above doesn’t work if I’m running my main N++ instance as well, because it just looks for a task named “notepad++” and kills what it finds – this can be my main instance and not my death-intended testbed instance.

                    What really should be done, to stop the current instance of N++, is to look for it’s process-id or “pid” when doing a taskkill.

                    I wrote a script to exit and restart the testbed N++ instance, by using the pid, and thought I’d share it here. I call it ExitAndRestartNpp.py:

                    # -*- coding: utf-8 -*-
                    from __future__ import print_function
                    
                    from Npp import *
                    import os
                    import subprocess
                    from ctypes import (WinDLL)
                    
                    #-------------------------------------------------------------------------------
                    
                    class EARN(object):
                    
                        def __init__(self):
                            self.debug = True if 0 else False
                            kernel32 = WinDLL('kernel32')
                            our_pid = kernel32.GetCurrentProcessId()
                            npp_exe_path = notepad.getNppDir() + os.sep + 'notepad++.exe'
                            si = subprocess.STARTUPINFO()
                            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                            #si.wShowWindow = subprocess.SW_HIDE  # default, don't really need to set it
                            timeout_in_secs = 3
                            command = 'cmd /c taskkill /PID {pid} && TIMEOUT /T {to} && start "" "{exe}" -multiInst'.format(
                                pid=our_pid, exe=npp_exe_path, to=timeout_in_secs)
                            if self.debug:
                                print(command)
                            else:
                                notepad.saveAllFiles()
                                subprocess.call(command, startupinfo=si)
                    
                    #-------------------------------------------------------------------------------
                    
                    if __name__ == '__main__': EARN()
                    
                    1 Reply Last reply Reply Quote 4
                    • Alan KilbornA
                      Alan Kilborn
                      last edited by

                      Of course, for my use case just described, this .bat file also works, and is less complicated than the script:

                      @echo off
                      :loop
                      C:\npp.misc\Releases\npp.8.3.2\npp.8.3.2.portable.x64\notepad++.exe -multiInst
                      choice /m "Run Notepad++ again? "
                      if %ERRORLEVEL% equ 2 goto :end
                      if %ERRORLEVEL% equ 1 goto :loop
                      :end
                      

                      :-)

                      1 Reply Last reply Reply Quote 3
                      • PeterJonesP
                        PeterJones @Alan Kilborn
                        last edited by PeterJones

                        For anyone who has a taskkill-based solution – either the Run command or a fancier PythonScript – you might want to add /F to make it a “stronger” kill. I have run across some circumstances (for example, for here where a normal kill wasn’t sufficient).

                        Edit: one downfall of the /F is that it will cause an “emergency exit”, so Notepad++ is not given a chance to save any settings (including recently-closed files). So only use the /F if you really need the extra power

                        1 Reply Last reply Reply Quote 1
                        • PeterJonesP PeterJones referenced this topic on
                        • First post
                          Last post
                        The Community of users of the Notepad++ text editor.
                        Powered by NodeBB | Contributors