Select all search results

2011-05-07
2015-04-10
  • This script selects all the occurrences in the current document of the given regex.  I'm posting it here as it's coming up a few times and so people might find it useful, if even they don't use Python Script normally.

    It operates on either the current selection if something is selected, or over the whole document if there's no current selection.

    first = True
    def found(line, m):
        global first
        pos = editor.positionFromLine(line)
        if first:
            editor.setSelection(pos + m.end(), pos + m.start())
            first = False
        else:
            editor.addSelection(pos + m.end(), pos + m.start())
    
    regex = notepad.prompt('Search for:', 'Select all results')
    if regex:
        editor.setMultipleSelection(True)
        lines = editor.getUserLineSelection()
        editor.pysearch(regex, found, 0, lines[0], lines[1])
    
     
  • ChildeAgrestis
    ChildeAgrestis
    2014-10-30

    How do I do this with the new research method, where the matchFunction only seems to receive the match object as a parameter, not the line number?

    Sorry if this is a dumb question, I am new to PythonScript and Python.

     
  • Sasumner
    Sasumner
    2015-04-10

    This seems to be a valid porting from the old pysearch() to the new research():

    matches = []
    
    def refound(m):
        global matches
        # append the match (start, end) positions to the matches array
        matches.append(m.span(0))
    
    regex = notepad.prompt('Search for:', 'Select all results')
    if regex:
        editor.setMultipleSelection(True)
        lines = editor.getUserLineSelection()
        editor.research(regex, refound, 0, editor.positionFromLine(lines[0]), editor.positionFromLine(lines[1]))
        first = True
        for (match_start_pos, match_end_pos) in matches:
            if first:
                first = False
                editor.setSelection(match_start_pos, match_end_pos)
            else:
                editor.addSelection(match_start_pos, match_end_pos)