Navigate between words in two ways using different separators

Viewed 127

Thanks to Visual Studio Code—Customizing word separators I was able to set underscore as separator. So now whenever I press Ctrl+Left Arrow, VS code recognizes that the word starts right after the underscore. However sometimes I want go at the very beginning of the variable/function/class name and, using underscore as separator, I have to press Ctrl+Left Arrow several times to get there. Is there any way to get a behavior like:

  • Ctrl+Left Arrow it considers underscore as separator
  • Ctrl+Alt+Left Arrow it doesn't consider underscore as separator
3 Answers

As rioV8 said, you can use the Select By plugin.

Follow these steps to get pretty much what you want:

  1. Install the plugin from your Visual Studio Code Extensions tab (Ctrl+Shift+X)
  2. Click on the bottom left gear and click on "Keyboard Shortcuts" as in this picture
  3. At the top right corner of the "Keyboard Shortcuts" tab, you'll find three icons, click on the one at the left, as in this picture (or Ctrl+k Ctrl+s)
  4. In the json file that has appeared on your screen, paste this:
  {
    "key": "ctrl+alt+right",  // or any other key combo
    "when": "editorTextFocus",
    "command": "moveby.regex",
    "args": [
      "moveAvoidUnderscore",
      "moveby",
      "next",
      "end"
    ]
  }

Or at least insert this shortcut at the end of the file, following a ','. You should have something like this.

  1. In File > Preferences > Settings (Ctrl+,), search for selectby

  2. Click Edit in settings.json

  3. Replace anything you have with that:

{
    "selectby.regexes": {
        "moveAvoidUnderscore": {
            "moveby": " "
        }
    }
}
  1. To setup left: replace "key": "ctrl+alt+left" and "args": [ ..., "prev", "start" ]

If I didn't miss anything, you should be good to go :)

You can do this quite easily with the macro extension multi-command. Make this keybinding in your keybindings.json:

{
  "key": "ctrl+alt+left",
  "command": "extension.multiCommand.execute",
  "args": {
    "sequence": [
      "editor.action.smartSelect.grow",
      "editor.action.smartSelect.grow",
      "cursorLeft"    // just gets rid of the selection
    ]
  },
}

move to start of while word

Another possible way for achieving the desired behaviour is through the following steps:

  1. Exclude _ from the word separators in case you still have it included.

  2. Add the two following keybindings to your keybindings.json :

     {      
        "key": "ctrl+shift+left",    
         "command": "cursorWordLeft",
         "when": "textInputFocus"
     },
    
     {
         "key": "ctrl+left",
         "command": "cursorWordPartLeft",
         "when": "textInputFocus"
     }
    

The first keybinding allows you to move to the left of a word by pressing Ctrl + Shift + Left Arrow.

The second keybinding allows you to move to the left of a word by pressing Ctrl + Left Arrow but considering _ this time.

Related