如何在 Visual Studio 代码中增加多行选择的数量

Web*_*per 7 visual-studio-code

我想在 Visual Studio 代码中为多选插入符添加更多数量。现在,当我打字时写出相同的单词。

在此输入图像描述

但我想通过一些快捷键添加增加的数字,这样我就不需要手动更新每个数字。理想的结果应该是这样的。

在此输入图像描述

我想知道这在 VS Code 中是否可行。

谢谢

Mar*_*ark 8

您不需要为您的用例进行扩展,尽管这可能会让事情变得更容易。以下是如何在不使用扩展的情况下完成此操作。

  1. 查找:(?<=index:\s*)\d+ :仅选择 后面的数字index:
  2. Alt+Enter将选择所有这些数字。

现在,您可以运行一个简单的代码片段,将这些数字替换为从 0 或从 1 开始的递增数字。进行此键绑定以插入片段(在您的 中keybindings.json):

{
  "key": "alt+m",        // whatever keybinding you want
  "command": "editor.action.insertSnippet",
  "args": {
    "snippet": "$CURSOR_NUMBER"  // this will increment and is 1-based
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 触发上述键绑定。演示:

使用片段递增数字的演示


这是一种扩展方法,使用我编写的扩展Find and Transform,这使得这变得很容易。进行此键绑定:

{
  "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
  }
}
Run Code Online (Sandbox Code Playgroud)

这将查找和替换合并为一步。

使用查找和转换扩展增加数字


这是另一种方法,因此您不需要对起点进行硬编码。

{
  "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"
  }
}
Run Code Online (Sandbox Code Playgroud)

将光标放在您想要作为起点的数字旁边或选择该数字。该数字实际上可以位于文档中的任何位置。

选择演示的序列