Nomura Nori
Nomura Nori

Reputation: 5167

how to put increased number for multiline selection in visual studio code

I want to add increased number for multi selected caret in visual studio code. now, When I type it write same words.

enter image description here

But I would like to add increased number by some shortkey so that I don't need to update each one manually. Preferred result should be like this.

enter image description here

I want to know if this is possible in vs code.

Thanks

Upvotes: 11

Views: 11496

Answers (2)

Mark
Mark

Reputation: 180631

You do not need an extension for your use case, although that may make it easier. Here is how to do it without an extension.

  1. Find: (?<=index:\s*)\d+ : this selects only the digits following index: .
  2. Alt+Enter will select all those digits.

Now you can run a simple snippet to replace those digits with an increasing number that could be 0-based or 1-based. Make this keybinding to insert the snippet (in your keybindings.json):

{
  "key": "alt+m",        // whatever keybinding you want
  "command": "editor.action.insertSnippet",
  "args": {
    "snippet": "$CURSOR_NUMBER"  // this will increment and is 1-based
  }
}
  1. Trigger the above keybinding. Demo:

demo of incrementing a digit with a snippet


Here is an extension approach, using an extension I wrote, Find and Transform, that makes this easy. Make this keybinding:

{
  "key": "alt+m",        // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    "find": "(?<=index:\\s*)\\d+",   // same find regex
    "replace": "${matchNumber}",     // this variable will increase, 1-based
    "isRegex": true
  }
}

That combines the find and replace in one step.

increment digit with Find and Transform extension


Here is another method so you do not need to hardcode the starting point.

{
  "key": "alt+m",                  // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    "preCommands": [
      "editor.action.addSelectionToNextFindMatch", 
      "editor.action.clipboardCopyAction"
    ],
    "find": "(?<=index:\\s*)\\d+",
    "replace": [
      "$${",
        // whatever math you want to do here
        "return Number(${CLIPBOARD}) + ${matchIndex};",
      "}$$",
    ],
    "isRegex": true,
    "postCommands": "cancelSelection"
  }
}

Put the cursor next to or select the number you want as the starting point. The number could be anywhere in the document actually.

sequence from selection demo

Upvotes: 13

You can do it with Increment Selection or Text Pastry

Upvotes: 5

Related Questions