Gummill - 2015-11-15

In Sublime text multiple occurrences of a word can be selected by simply pressing Ctrl+D. This feature is called Quick Add Next: https://www.sublimetext.com/docs/2/multiple_selection_with_the_keyboard.html

The following script implements the same basic functionality in PythonScript:

def ensureNormalSelection():
    """
    Make sure that currentPosition is at the end of the selection.
    If the cursor is at the left end of a selection, then that specific
    selection will be the first result of the findText command. We avoid that
    by explicitly moving the cursor to the end of the selection.
    """
    anchor = editor.getSelectionStart()
    end = editor.getSelectionEnd()
    editor.setSelectionEnd(end)
    editor.setSelectionStart(anchor)

currentlySelectedText = editor.getSelText()
if not currentlySelectedText:
    pass
else:
    # Find the string to search for. We can't use getSelText since we may have
    # several instances of the string selected, resulting in textToSearchFor
    # being, e.g., 'abcabcabc' rather than simply 'abc'.
    mainSelNumber = editor.getMainSelection()
    selStart = editor.getSelectionNAnchor(mainSelNumber)
    selEnd = editor.getSelectionNCaret(mainSelNumber)
    textToSearchFor = editor.getTextRange(selStart, selEnd)
    # Do the search.
    ensureNormalSelection()
    currentPosition = editor.getCurrentPos()
    fileLength = editor.getLength()
    try:
        (startPos, endPos) = editor.findText(0, currentPosition, fileLength,
                                             textToSearchFor)
    except:
        (startPos, endPos) = editor.findText(0, 0, currentPosition,
                                             textToSearchFor)
    editor.addSelection(startPos, endPos)

Minimal working example:
In a text file

abc abc

select the first 'abc' and run the script. This should cause the second 'abc' to also be selected.

To remove the latest added selection, run

editor.dropSelectionN(editor.getMainSelection())
 

Last edit: Gummill 2015-11-15