Search code examples
visual-studio-codekeyboard-shortcuts

VSCode select next occurrence of variable


In VSCode on Mac, I can use the keyboard shortcut Cmd + D to select the next occurrence of my currently highlighted text.

For example, if I highlight the variable order on line 1 in the below code, hitting Cmd + D causes order_form on line 2 to be partially highlighted, and hitting Cmd + D again causes order to be highlighted on line 3.

1. order = "Some string"
2. order_form = create_form()
3. return "Here is your order: " + order

However, I just want to select the actual variable order on lines 1 and 3 (i.e. excluding the text that is part of the variable order_form)

What keyboard shortcut can I use to just highlight the actual variables named order on lines 1 and 3?


Solution

  • The Ctrl+D functionality uses the current Find widget settings "behind the scenes" - whether that Find widget is visible or not.

    So you would get the behaviour you want if the Whole Word option was enabled in that Find widget first before you began Ctrl+D'ing.

    Alternatively, as the demo below shows when you place your cursor on the word you want order you can then hit Alt+W which will toggle the Whole Word option on and off. Note the little box that opens in the top right of the editor that shows only the Find options.

    Then all your find next occurrences with Ctrl+D will find only what you want with that Whole Word option still enabled.

    If you want to skip any of those occurrences, you can use the command

    Add Selection To Previous Find Match
    editor.action.addSelectionToPreviousFindMatch
    

    (which you would have to make your own keybinding for). Just trigger that command to skip the next possible match - so follow this order:

    1. Ctrl+D on the first order
    2. Alt+W to enable whole word matching
    3. trigger the command Add Selection To Previous Find Match
    4. Ctrl+D to select the next order

    It sounds like a bit of a hassle but they are common commands to know - to skip the next match and to toggle Whole Word matching.

    [That little box that opens with the Find options is a little glitchey in that it seems to sometimes also enable the case sensitivity option as well - which isn't a problem in your example.]

    toggle whole word find next match demo