Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 653
Nomura Nori Avatar asked Feb 07 '26 07:02

Nomura Nori


2 Answers

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

like image 77
Mark Avatar answered Feb 08 '26 21:02

Mark


You can do it with Increment Selection or Text Pastry

like image 25
Hoàng Huy Khánh Avatar answered Feb 08 '26 22:02

Hoàng Huy Khánh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!