• Login
Community
  • Login

Is there a way/plugin that makes notepad++ run code on a file when we open it?

Scheduled Pinned Locked Moved Help wanted · · · – – – · · ·
44 Posts 3 Posters 35.3k 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.
  • A
    Alguem Meugla
    last edited by Jul 15, 2017, 10:47 PM

    Is there a way/plugin that makes notepad++ run code on a file when we open it?
    For example: I could put some code for np++, telling it to collapse all start blocks, inside a comment so it wouldn’t affect my code?
    I do code in a few files with a lot of code, including functions, etc. and everytime I open those files I must collapse all those unneeded parts. Automatically saving this data about what blocks are collapsed in the file isn’t a good idea, but a plugin that helps me adding that info inside a comment, which notepad++ could still read and know what blocks should be collapsed would help a lot.
    Thanks.

    C 1 Reply Last reply Jul 16, 2017, 3:00 PM Reply Quote 0
    • C
      Claudia Frank @Alguem Meugla
      last edited by Jul 16, 2017, 3:00 PM

      @Alguem-Meugla

      plugins which functionality I’m aware of are python script, lua script and nppexec.
      I don’t understand you request fully so I’m not 100% certain that nppexec
      can solve it but I assume python and lua script should be usable in this case.

      Cheers
      Claudia

      1 Reply Last reply Reply Quote 0
      • A
        Alguem Meugla
        last edited by Jul 16, 2017, 5:37 PM

        I want to make it so when I open the files, they will have some code that will tell notepad++ to collapse all biggest blocks (ie: it will collapse functions, but not any ifs or whiles inside it), so I don’t need to close all them manually. My code is in javascript.

        C 1 Reply Last reply Jul 16, 2017, 6:57 PM Reply Quote 0
        • C
          Claudia Frank @Alguem Meugla
          last edited by Jul 16, 2017, 6:57 PM

          @Alguem-Meugla

          do you mean the same as pressing ALT+0 ?

          Cheers
          Claudia

          1 Reply Last reply Reply Quote 0
          • A
            Alguem Meugla
            last edited by Jul 16, 2017, 8:59 PM

            Something similar, but it would collapse only the biggest things, ie: see this gif . It shouldn’t collapse more things inside those which are being collapsed.
            It would also make it possible to choose which things should be collapsed at start. For example, on an html file I would only want it to close the head and some scripts while keeping others opened.

            C 1 Reply Last reply Jul 16, 2017, 10:21 PM Reply Quote 0
            • C
              Claudia Frank @Alguem Meugla
              last edited by Jul 16, 2017, 10:21 PM

              @Alguem-Meugla

              Something similar, but it would collapse only the biggest things, ie: see this gif. It shouldn’t collapse more things inside those which are being collapsed.

              A python script like this would do this

              _number_of_lines = editor.getLineCount()
              i = 0
              while True:
                  if i < _number_of_lines:
                      if editor.getFoldLevel(i) & FOLDLEVEL.HEADERFLAG:
                          editor.foldLine(i,0)
                          i = editor.getLastChild(i,-1)
                      else:
                          i += 1
                  else:
                      break
              

              It would also make it possible to choose which things should be collapsed at start. For example, on an html file I would only want it to close the head and some scripts while keeping others opened.

              How should this work? A fold flag doesn’t know if it is set for the header tag or something else.
              Of course you could anaylze the code for the head tag but how should teh script know
              which scripts you want to have collapsed and which expanded?

              Cheers
              Claudia

              A 1 Reply Last reply Jul 17, 2017, 6:18 PM Reply Quote 0
              • A
                Alguem Meugla @Claudia Frank
                last edited by Jul 17, 2017, 6:18 PM

                @Claudia-Frank said:

                How should this work? A fold flag doesn’t know if it is set for the header tag or something else.
                Of course you could anaylze the code for the head tag but how should teh script know
                which scripts you want to have collapsed and which expanded?

                Cheers
                Claudia

                It would “click” the + that is on a specified line or the line were the flag is.

                C 1 Reply Last reply Jul 17, 2017, 7:11 PM Reply Quote 0
                • C
                  Claudia Frank @Alguem Meugla
                  last edited by Jul 17, 2017, 7:11 PM

                  @Alguem-Meugla

                  No, this is not what I meant.
                  Let’s assume we have the following code

                  <!DOCTYPE html>
                  <html>
                      <head>
                          <script>
                              function func_h1() {
                                  document.getElementById("h1").innerHTML = "Should I be collapsed?";
                              }
                          </script>
                      </head>
                      <body>
                  
                          <h2>JavaScript Example</h2>
                  
                          <p id="h1">Head1</p>
                          <p id="b1">Body1</p>
                  
                          <button type="button" onclick="func_h1()">Head1</button>
                          <button type="button" onclick="func_b1()">Body1</button>
                  
                  
                          <script>
                              function func_b1() {
                                  document.getElementById("b1").innerHTML = "Or Should I be collpased?";
                              }
                          </script>
                      </body>
                  </html> 
                  

                  How should a script decide which of the script tag needs to be collapsed?
                  There must be some logic provided by you to collapse the correct tag.

                  Cheers
                  Claudia

                  A 1 Reply Last reply Jul 17, 2017, 7:38 PM Reply Quote 1
                  • A
                    Alguem Meugla @Claudia Frank
                    last edited by Alguem Meugla Jul 17, 2017, 7:40 PM Jul 17, 2017, 7:38 PM

                    .

                    <!DOCTYPE html>
                    <html>
                    <head>       <!-- NPP_PLZ_COLLAPSE_THIS_LINE -->
                        <script>
                            function func_h1() {
                                document.getElementById("h1").innerHTML = "Should I be collapsed?";
                            }
                        </script>
                    </head>
                    <body>
                    
                        <h2>JavaScript Example</h2>
                    
                        <p id="h1">Head1</p>
                        <p id="b1">Body1</p>
                    
                        <button type="button" onclick="func_h1()">Head1</button>
                        <button type="button" onclick="func_b1()">Body1</button>
                    
                    
                        <script>       // NPP_PLZ_COLLAPSE_THIS_LINE
                            function func_b1() {
                                document.getElementById("b1").innerHTML = "Or Should I be collpased?";
                            }
                        </script>
                        <script>
                            function func_b1() {
                                document.getElementById("b1").innerHTML = "Or Should I be collpased?";
                            }
                        </script>
                    </body>
                    </html> 
                    

                    It would then “click” on the - that is on the right of the number of the lines that contains “NPP_PLZ_COLLAPSE_THIS_LINE” (btw when I said “+” above in a post I meant “-”).

                    OR

                    1.<!DOCTYPE html>
                    2.<html>
                    3.<head>       <!-- NPP_PLZ_COLLAPSE_THE_LINES(3,21) -->
                    4.    <script>
                    5.        function func_h1() {
                    6.            document.getElementById("h1").innerHTML = "Should I be collapsed?";
                    7.        }
                    8.    </script>
                    9.</head>
                    10.<body>
                    11.
                    12.    <h2>JavaScript Example</h2>
                    13. 
                    14.    <p id="h1">Head1</p>
                    15.    <p id="b1">Body1</p>
                    16.
                    17.    <button type="button" onclick="func_h1()">Head1</button>
                    18.    <button type="button" onclick="func_b1()">Body1</button>
                    19.
                    20.
                    21.    <script>
                    22.        function func_b1() {
                    23.            document.getElementById("b1").innerHTML = "Or Should I be collpased?";
                    24.        }
                    25.    </script>
                    26.    <script>
                    27.        function func_b1() {
                    28.            document.getElementById("b1").innerHTML = "Or Should I be collpased?";
                    29.        }
                    30.    </script>
                    31.</body>
                    32.</html> 
                    

                    It would collapse the lines 3 and 21 because of “NPP_PLZ_COLLAPSE_THE_LINES(3,21)”.

                    C 1 Reply Last reply Jul 17, 2017, 7:58 PM Reply Quote 0
                    • C
                      Claudia Frank @Alguem Meugla
                      last edited by Claudia Frank Jul 17, 2017, 8:00 PM Jul 17, 2017, 7:58 PM

                      @Alguem-Meugla

                      ok, let’s finalize it.
                      The folding logic is the following

                      Searching through the document to find either the identifier to collapse
                      the fold header in this line or the identifier to collapse every root fold header starting
                      from A to (including) Z.

                      In the case of folding A to Z the identifier is immediately followed by the start and end line separated by a comma and encased by round parenthesis.

                      In any case only this level will be folded so if clicking onto the plus sign
                      the whole structure gets expanded again.

                      Program logic is,
                      whenever a file gets activated first it gets scanned about the identifiers and
                      the parts get collapsed. If a file gets closed and reopened the logic will be applied again.
                      If only the buffer is switch, meaning you switch from one tab to another one
                      nothing happens.

                      Do you agree?

                      Cheers
                      Claudia

                      A 1 Reply Last reply Jul 17, 2017, 8:35 PM Reply Quote 0
                      • A
                        Alguem Meugla @Claudia Frank
                        last edited by Jul 17, 2017, 8:35 PM

                        @Claudia-Frank said:

                        Program logic is,
                        whenever a file gets activated first it gets scanned about the identifiers and
                        the parts get collapsed. If a file gets closed and reopened the logic will be applied again.
                        If only the buffer is switch, meaning you switch from one tab to another one
                        nothing happens.

                        Do you agree?

                        That’s it!

                        C 2 Replies Last reply Jul 17, 2017, 9:06 PM Reply Quote 0
                        • C
                          Claudia Frank @Alguem Meugla
                          last edited by Jul 17, 2017, 9:06 PM

                          @Alguem-Meugla

                          ok - I don’t find the time today but I will provide a possible solution tomorrow.

                          Cheers
                          Claudia

                          1 Reply Last reply Reply Quote 1
                          • S
                            savage roar
                            last edited by Jul 17, 2017, 11:11 PM

                            I have a similar problem.
                            I wrote a script that solves it, but I can’t make it work properly in FILEOPENED callback.
                            This works just fine.

                            from Npp import *
                            
                            # Collapses all blocks annotated with "//!"
                            def auto_collapse():
                            	to_collapse = [];
                            	for i in range(0, editor.getLineCount()-1):
                            		line = editor.getLine(i).strip()
                            		if line[:3] == "//!":
                            			to_collapse.append(i+1)
                            	for num in to_collapse:
                            		editor.foldLine(num, 0)
                            
                            auto_collapse()
                            

                            But this script behaves buggy as hell (no errors, just incorrect folding). Why? Maybe there is another “FILEREADY” callback to hook on?

                            from Npp import *
                            
                            def auto_collapse(args):
                            	notepad.activateBufferID(args["bufferID"])
                            	to_collapse = [];
                            	for i in range(0, editor.getLineCount()-1):
                            		line = editor.getLine(i).strip()
                            		if line[:3] == "//!":
                            			to_collapse.append(i+1)
                            	for num in to_collapse:
                            		editor.foldLine(num, 0)
                            		
                            notepad.callback(auto_collapse, [NOTIFICATION.FILEOPENED])
                            
                            1 Reply Last reply Reply Quote 0
                            • S
                              savage roar
                              last edited by Jul 18, 2017, 8:17 AM

                              Okay, now THIS works for me. It seems like that dirty hack with “new/close” forces N++ to repaint the folded document. Now I’m searching for the best way to launch this on N++ startup.

                              from Npp import *
                              
                              def auto_collapse(args):
                              	notepad.activateBufferID(args["bufferID"])
                              	for i in range(0, editor.getLineCount()-1):
                              		line = editor.getLine(i).strip()
                              		if line[:3] == "//!":
                              			editor.foldLine(i+1, 0)
                              	notepad.new()
                              	notepad.close()
                              
                              notepad.callback(auto_collapse, [NOTIFICATION.FILEOPENED])
                              
                              C 1 Reply Last reply Jul 18, 2017, 2:58 PM Reply Quote 0
                              • C
                                Claudia Frank @Alguem Meugla
                                last edited by Jul 18, 2017, 2:57 PM

                                @Alguem-Meugla

                                Ok, this wasn’t as straightforward as I thought it is, basically because
                                the folding flags get set after buffer has been activated, therefore
                                I’m using now UPDATEUI callback, with some logic to prevent multiple scans, to do the folding

                                Within the configuration area you can define which file extensions
                                should be handled. COLLPASE_LINE_IDENTIFIER and COLLPASE_FROM_TO_IDENTIFIER
                                can be changed as long as the changes do not break regex searches.
                                In addition for COLLPASE_FROM_TO_IDENTIFIER matches need to be in form any_numberCOMMAany_number (like 3,4 or 14,25).

                                In order to make this work automatically, meaning that the script gets called when npp starts,
                                create a new script and name it startup.py (if you not already have a user startup.py - not to be confused with the standard startup.py python script automatically created)
                                and copy the content into it. Restart npp and test it.

                                If you do it like that then the logic is the following:
                                When starting npp, the script gets executed and registers two callbacks.
                                The BUFFERACTIVED callback gets called whenever you switch to another tab,
                                then the function checks if this file should be folded and if so if it has been already done.
                                If it hasn’t be done it set a global flag that it needs to be done.
                                The second callback UPDATEUI is called whenever something changes within the current document,
                                if the flag has been set that the document should be scanned, it will do so, collapses
                                the found lines and set the global flag to false in order to prevent subsequent scans.

                                import os
                                
                                # ---------------------------- configuration area -----------------------------
                                
                                FILE_EXTENSION_LIST = ['.html','.js']
                                COLLPASE_LINE_IDENTIFIER = 'NPP_COLLAPSE_IT'
                                COLLPASE_FROM_TO_IDENTIFIER = 'NPP_COLLAPSE\((\d+,\d+)\)'
                                
                                # -----------------------------------------------------------------------------
                                
                                
                                def scan(number_of_lines):
                                    
                                    def find_line_identifiers(): # NPP_COLLAPSE_IT
                                        matches = []
                                        editor.research('\\b{0}\\b'.format(COLLPASE_LINE_IDENTIFIER), lambda m: matches.append(m.span()), 0)   
                                        return matches
                                    
                                    def find_from_to_line_identifiers(): # NPP_COLLAPSE(19,41)
                                        matches = []
                                        editor.research('{0}'.format(COLLPASE_FROM_TO_IDENTIFIER), lambda m: matches.append(m.span(1)), 0)   
                                        return matches
                                            
                                    for match in find_line_identifiers():
                                        _line = editor.lineFromPosition(match[0])
                                        if editor.getFoldLevel(_line) & FOLDLEVEL.HEADERFLAG:
                                            editor.foldLine(_line,0)
                                    
                                    for match in find_from_to_line_identifiers():
                                        start_line, end_line = list(map(lambda x: int(x)-1, editor.getTextRange(*match).split(',')))
                                        while True:
                                            if start_line <= end_line:
                                                if editor.getFoldLevel(start_line) & FOLDLEVEL.HEADERFLAG:
                                                    editor.foldLine(start_line,0)
                                                    start_line = editor.getLastChild(start_line,-1) + 1
                                                else:
                                                    start_line += 1
                                            else:
                                                break 
                                
                                should_be_folded = False
                                def callback_FOLD_BUFFERACTIVATED(args):
                                    global should_be_folded
                                    _state = editor.getProperty('AUTO_FOLDED')
                                    if _state == '':
                                        filename, extension = os.path.splitext(notepad.getBufferFilename(args['bufferID']))
                                        if extension in FILE_EXTENSION_LIST:
                                            editor.setProperty('AUTO_FOLDED', '1')
                                            should_be_folded = True
                                        else:
                                            editor.setProperty('AUTO_FOLDED', '-1')
                                            should_be_folded = False
                                    elif _state == '-1':
                                        should_be_folded = False
                                
                                def callback_FOLD_UPDATEUI(args):
                                    global should_be_folded
                                    if should_be_folded:
                                        scan(editor.getLineCount())
                                        should_be_folded = False
                                
                                notepad.callback(callback_FOLD_BUFFERACTIVATED, [NOTIFICATION.BUFFERACTIVATED])
                                editor.callback(callback_FOLD_UPDATEUI, [SCINTILLANOTIFICATION.UPDATEUI])
                                

                                Did only some basic tests, but hope this is useful for you.

                                Cheers
                                Claudia

                                A 1 Reply Last reply Jul 18, 2017, 5:55 PM Reply Quote 0
                                • C
                                  Claudia Frank @savage roar
                                  last edited by Jul 18, 2017, 2:58 PM

                                  @savage-roar

                                  call the script from user startup.py or put your code into user startup.py .

                                  Cheers
                                  Claudia

                                  1 Reply Last reply Reply Quote 0
                                  • C
                                    Claudia Frank
                                    last edited by Jul 18, 2017, 5:06 PM

                                    Minor code cleanup

                                    import os
                                    
                                    # ---------------------------- configuration area -----------------------------
                                    
                                    FILE_EXTENSION_LIST = ['.html','.js']
                                    COLLPASE_LINE_IDENTIFIER = 'NPP_COLLAPSE_IT'
                                    COLLPASE_FROM_TO_IDENTIFIER = 'NPP_COLLAPSE\((\d+,\d+)\)'
                                    
                                    # -----------------------------------------------------------------------------
                                    
                                    
                                    def scan(number_of_lines):
                                        
                                        def find_line_identifiers(): # NPP_COLLAPSE_IT
                                            matches = []
                                            editor.research('\\b{0}\\b'.format(COLLPASE_LINE_IDENTIFIER), lambda m: matches.append(m.span()), 0)   
                                            return matches
                                        
                                        def find_from_to_line_identifiers(): # NPP_COLLAPSE(19,41)
                                            matches = []
                                            editor.research(COLLPASE_FROM_TO_IDENTIFIER, lambda m: matches.append(m.span(1)), 0)   
                                            return matches
                                                
                                        for match in find_line_identifiers():
                                            _line = editor.lineFromPosition(match[0])
                                            if editor.getFoldLevel(_line) & FOLDLEVEL.HEADERFLAG:
                                                editor.foldLine(_line,0)
                                        
                                        for match in find_from_to_line_identifiers():
                                            start_line, end_line = map(lambda x: int(x)-1, editor.getTextRange(*match).split(','))
                                            while True:
                                                if start_line <= end_line:
                                                    if editor.getFoldLevel(start_line) & FOLDLEVEL.HEADERFLAG:
                                                        editor.foldLine(start_line,0)
                                                        start_line = editor.getLastChild(start_line,-1) + 1
                                                    else:
                                                        start_line += 1
                                                else:
                                                    break 
                                    
                                    should_be_folded = False
                                    def callback_FOLD_BUFFERACTIVATED(args):
                                        global should_be_folded
                                        _state = editor.getProperty('AUTO_FOLDED')
                                        if _state == '':
                                            filename, extension = os.path.splitext(notepad.getBufferFilename(args['bufferID']))
                                            if extension in FILE_EXTENSION_LIST:
                                                editor.setProperty('AUTO_FOLDED', '1')
                                                should_be_folded = True
                                            else:
                                                editor.setProperty('AUTO_FOLDED', '-1')
                                                should_be_folded = False
                                        else:
                                            should_be_folded = False
                                    
                                    def callback_FOLD_UPDATEUI(args):
                                        global should_be_folded
                                        if should_be_folded:
                                            scan(editor.getLineCount())
                                            should_be_folded = False
                                    
                                    notepad.callback(callback_FOLD_BUFFERACTIVATED, [NOTIFICATION.BUFFERACTIVATED])
                                    editor.callback(callback_FOLD_UPDATEUI, [SCINTILLANOTIFICATION.UPDATEUI])
                                    

                                    Cheers
                                    Claudia

                                    1 Reply Last reply Reply Quote 0
                                    • A
                                      Alguem Meugla @Claudia Frank
                                      last edited by Jul 18, 2017, 5:55 PM

                                      @Claudia-Frank said:

                                      create a new script and name it startup.py (if you not already have a user startup.py - not to be confused with the standard startup.py python script automatically created)

                                      Where do I find/put that?

                                      C 2 Replies Last reply Jul 18, 2017, 7:16 PM Reply Quote 1
                                      • C
                                        Claudia Frank @Alguem Meugla
                                        last edited by Claudia Frank Jul 18, 2017, 7:16 PM Jul 18, 2017, 7:16 PM

                                        @Alguem-Meugla

                                        either install python script plugin via plugin manager or by using the msi package .
                                        I would suggest to use the msi package as it has been reported that installation via plugin manager
                                        fails from time to time.

                                        Once installed, goto Plugins->Python Script->New Script and name it startup.py .
                                        and press Save button.
                                        Copy the posted script into the newly created document, save it and restart npp.

                                        Cheers
                                        Claudia

                                        1 Reply Last reply Reply Quote 1
                                        • C
                                          Claudia Frank @Alguem Meugla
                                          last edited by Jul 18, 2017, 7:27 PM

                                          @Alguem-Meugla

                                          sorry - I forgot one step.

                                          before you restart npp, goto
                                          Plugins->Python Script->Configuration
                                          and instead of Initialisation: LAZY choose ATSTARTUP.

                                          Cheers
                                          Claudia

                                          A 1 Reply Last reply Jul 18, 2017, 8:01 PM Reply Quote 1
                                          8 out of 44
                                          • First post
                                            8/44
                                            Last post
                                          The Community of users of the Notepad++ text editor.
                                          Powered by NodeBB | Contributors