2

Sublime provides ability to:

  • select/edit all occurrences of a variable (Quick Find All; alt+F3 on Windows)
  • select each occurrence one-by-one and then edit the summed total (Quick Add Next; ctrl+d on Windows)

What I want:

  • select/edit all occurrences within a function's scope

note: I've read this related link (Sublime Text: Select all instances of a variable and edit variable name) and didn't see an answer to how editing might be restricted to function scope.

Zach Valenta
  • 1,783
  • 1
  • 20
  • 35

1 Answers1

1

You can create a fairly simple plugin to do this, making use of Quick Find All, and then just removing any selections that are not inside the current function.

  • From the Tools menu -> Developer -> New Plugin...
  • Replace the contents of the new tab with the following:
import sublime
import sublime_plugin


class SelectWordInFunctionCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        prev_sel = [sel for sel in view.sel()]
        function_region = next((region for region in view.find_by_selector('meta.function') if region.contains(view.sel()[0])), None)
        if function_region:
            #word = view.expand_by_class(view.sel()[0].begin(), sublime.CLASS_WORD_START + sublime.CLASS_WORD_END)
            view.window().run_command('find_all_under')
            sel = [sel for sel in view.sel() if function_region.contains(sel)]
            view.sel().clear()
            view.sel().add_all(sel if any(sel) else prev_sel)
        else:
            view.window().status_message('Not inside a function')
  • instead of using the find_all_under command, use select_word_in_function - you can create a keybinding to do this only when inside a function definition:
{ "keys": ["alt+f3"], "command": "select_word_in_function", "context":
    [
        { "key": "selector", "operator": "equal", "operand": "meta.function", "match_all": true },
    ]
},

Disclaimer: this definitely works with PHP in ST build 3142 and other syntaxes that scope the whole function, but a different approach to detect where the function starts and ends may need to be used for other syntaxes that can't/don't behave this way.

Keith Hall
  • 15,362
  • 3
  • 53
  • 71