Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform pre-defined Find-Replace-All in VSCode using a keybinding

I can't seem to find a good list of documented commands that can be run from VSCode keybindings.

On the online VSCode documentation, the Commands Guide lists two ways to discover commands:

The commands found for keyboard shortcuts are usually "simple" commands that do not take arguments. The "advanced commands api" seems to be missing some very basic, fundamental commands.

For example, on the VSCode Keybindings page there is a section called "Command Arguments" that has the following example entry:

{ "key": "enter", "command": "type",
  "args": { "text": "Hello World" },
  "when": "editorTextFocus" }

But I don't see anywhere that the type command is documented. So I assume there are probably several other basic commands like this that exist but I don't know where to find documentation for them.

Anyway, what I am really looking for at the moment is a command that I can run to do a pre-defined search and replace in the current editor, specifying the find text, replacement text, and options... something like below:

{ "key": "ctrl+shift+8", 
  "command": "findReplaceAll",
  "args": { 
    "findText": "Company(\\w+)", 
    "replaceText": "User$1"
    "options": { "ignoreCase": false, "wholeWord": true, "regex": true }
  },
  "when": "editorTextFocus" }

But I haven't been able to find any such findReplaceAll command or anything similar in the documentation, but certainly something like this must exist, right?

Thanks!

like image 714
drwatsoncode Avatar asked Aug 18 '19 02:08

drwatsoncode


People also ask

How do I replace all occurrences in Visual Studio?

You can find and replace text in the Visual Studio editor by using Find and Replace (Ctrl+F or Ctrl+H) or Find/Replace in Files (Ctrl+Shift+F or Ctrl+Shift+H). You can also find and replace only some instances of a pattern by using multi-caret selection.


Video Answer


1 Answers

Install the extension Replace Rules.

Construct a search-replace in your settings.json (Workspace or User). Read the page about the possibilities.

  "replacerules.rules": {
    "Replace User": {
      "find": "User(\d+)",
      "replace": "Player$1"
    }
  }

In keybindings.json define the following keybinding:

  {
  "key": "ctrl+shift+alt+u",
  "command": "replacerules.runRule",
  "when": "editorTextFocus",
  "args": { "ruleName": "Replace User"}
  }

If you select some text the search-replace will only be performed within the selection.

like image 139
rioV8 Avatar answered Oct 11 '22 20:10

rioV8