Home  >  Article  >  Development Tools  >  Let's talk about how to add and use multiple cursors in VSCode

Let's talk about how to add and use multiple cursors in VSCode

青灯夜游
青灯夜游forward
2022-03-28 20:35:124885browse

This article will talk about VSCode cool and practical multi-cursor editing. I will introduce the method of adding and using multi-cursors. I hope it will be helpful to everyone!

Let's talk about how to add and use multiple cursors in VSCode

If you want to say which feature of VSCode has greatly improved coding efficiency, multi-cursor editing is definitely one of them. Multi-cursor editing allows us to avoid repeating the same text operations. The text processing commands built in VSCode and provided by third-party extensions can greatly enhance the flexibility of multi-cursor editing. I hope that by reading this article, I can teach readers how to flexibly use multi-cursor editing in daily editing. [Recommended learning: "vscode introductory tutorial"]

Content outline:

  • How to add multiple cursors
  • Move the cursor
  • Select text
  • Delete text
  • Text processing command
  • Multi-cursor practical example
  • A better choice besides multi-cursor editing

How to add multiple cursors

General method

Hold down the key, then move the cursor to wherever you want to add the cursor and click directly A cursor will be added.

Lets talk about how to add and use multiple cursors in VSCode

Add cursor shortcut keys

The shortcut keys related to the cursor in VSCode all have the ⌥ key

We can open the VSCode shortcut key table through K, S shortcut key combination and search for cursor All shortcut keys related to the cursor will be listed. Search for add cursor to view the shortcut keys related to add cursor:

Lets talk about how to add and use multiple cursors in VSCode

Add the cursor to the same column:

  • : Add the cursor to the next row and the same column
  • : Add the cursor in the same column of the previous row

Lets talk about how to add and use multiple cursors in VSCode

Add selection

There can be multiple cursors and multiple selections in the VSCode editor at the same time. Most commands for adding a selection in VSCode will also add a cursor when adding a selection. Therefore, we can use the shortcut keys for adding a selection to add multiple cursors.

Commonly used ones are:

  • ##⌘ D: Add the selection to the next found match. If there are multiple matches, each Trigger once and add one more
  • L: Add a selection to all found matches

Lets talk about how to add and use multiple cursors in VSCode

Although the above two shortcut keys refer to the found matches, they actually do not expand the search box when used.

The commands provided by VSCode often meet symmetry. For example,

D is to add a selection to the next match found, so there is a high probability that there will be a command Used to add a selection to the previously found match.

Lets talk about how to add and use multiple cursors in VSCode

If the text to be found is more complex, we can directly open the search first and use the

case provided in the search box to ignore , matches Whole word , regular function to find complex text, and then use L to select all.

Lets talk about how to add and use multiple cursors in VSCode

If there is already a selection , we can use the shortcut key I To add the cursor at the end of all lines in the selection. If you want to move the cursor to the beginning of the line at this time, just enter the Home key.

The following example is to select multiple lines first, then add the cursor to the end of all lines, and change the TypeScript interface to use commas to separate attributes:

Lets talk about how to add and use multiple cursors in VSCode

Cursor movement

Obviously you cannot use the mouse to position when editing multiple cursors, which requires us to use keys to move. The most basic four arrows are the up, down, left and right arrows, and the Home and End keys are needless to say. In addition, it is commonly used to move one word or part of a word at a time.

You can view the shortcut keys related to moving the cursor by searching for

cursor right, cursor end:

Lets talk about how to add and use multiple cursors in VSCode

Word-level movement is very commonly used:

  • : Move the cursor right to the end of the next word
  • ^ : Move the cursor right to the next part of the word, the hump, the beginning and the end of the word are all stop points

Lets talk about how to add and use multiple cursors in VSCode

As mentioned before, the symmetrical design of VSCode commands, is to move to the right to the end of the next word, then is to move the beginning of the previous word to the left.

And this also verifies what we said before, the shortcut keys related to the cursor all have . Therefore, when we customize shortcut keys, it is best to add to the shortcut keys related to the cursor. For example, you can define J to move to the previous git change, and then symmetrically design K to move to the next git change. . Easy to remember and search.

Some Mac users may feel that the cursor moves too slowly. This can be adjusted in Settings -> Keyboard to make the cursor move smoother:

Lets talk about how to add and use multiple cursors in VSCode

  • Drag the Delay before repeating slider to set how long a character waits before it starts repeating.
  • Drag the Key Repeat slider to set the rate at which characters repeat.

It is recommended to increase the key repeat speedfaster, so that the cursor movement will be faster and smoother.

Selected text

When editing with multiple cursors, the most common operations are moving, selecting, deleting, inserting, etc.

The shortcut key for moving the cursor plus is the shortcut key for selecting the move area

Let’s list a few examples Verify this rule:

  • moves one character to the right, can select the next character ## to the right
  • #↑ is to move up one line, is to select one line up
  • is to move right to the end of the word, is to select the current position of the cursor to the next end of the word
  • ^ is to move right to the next part of the word, ^ is to select part of the word to the right

1Lets talk about how to add and use multiple cursors in VSCode

There is a selection command that needs to be introduced separately is

smart select. We know that the shortcut key cmd D can select a word, but if you want to select a string, it will not work. At this time, you can use smart selection to achieve it.

  • ^ : Expand the selection range
  • ^ : Reduce the selection range

1Lets talk about how to add and use multiple cursors in VSCode

Recently antfu has written an extension that uses double-click to intelligently select text, although it is similar to Multi-cursor editing does not matter, but interested readers can experience it:

vscode-smart-clicks.

Delete text

The shortcut key to move the cursor plus the

key is leftThe shortcut key to delete the cursor moving area, add Up fn is right shortcut key to delete the cursor movement area

On Mac

Represents the End key, represents the Home key, fn represents Delete This rule should be common to all applications.

  • : Delete left to the beginning
  • ^ : Delete part of the word to the left
Because backspace itself is directional, there is no need to match the direction keys with the shortcut keys.

Text processing commands

In multi-cursor editing, we can use the commands provided by VSCode or third-party extensions to quickly insert specific text or convert selected text into specific text.

VSCode has the following built-in features. Taking the word

letterCase as an example, the conversion results are:

    Transform to Uppercase:
  • LETTERCASE
  • Transform to Lowercase:
  • lettercase
  • Transform to Title Case:
  • LetterCase
  • Transform to Snake Case:
  • letter_case
Search

transform to to find all text conversion commands

1Lets talk about how to add and use multiple cursors in VSCode

To give a practical example, for example, we need to change a bunch of constants that were originally in small camel case to all uppercase:

1Lets talk about how to add and use multiple cursors in VSCode

In addition to VSCode's built-in text processing commands, you can also use third-party plug-ins. Here are the recommendations: Text Power Tools. Reasons for recommendation: Active maintenance and rich functions.

There are many functions. Readers can check the extension homepage to learn more about it. I think if you don’t have the spirit of exploration and the ability to toss, you probably won’t be able to read this article. I will only demonstrate the function of inserting numbers here:

1Lets talk about how to add and use multiple cursors in VSCode

Capable readers can also write their own VSCode extensions to implement more text processing commands such as insertion, conversion, and even deletion. . It should be noted that all selections must be processed during implementation. For example, the author's VSCode extension VSCode FE Helper implements an extension that converts selected words into plurals as follows. The code is very simple. You can notice that all selections are traversed, so when calling this command during multi-cursor editing, all selections can be processed:

import { TextEditor } from 'vscode';

export default async function plur(editor: TextEditor): Promise<void> {
  const { default: pluralize } = await import(&#39;pluralize&#39;);
  editor.edit((editorBuilder) => {
    const { document, selections } = editor;
    for (const selection of selections) {
      const word = document.getText(selection);
      const pluralizedWord = pluralize(word);
      editorBuilder.replace(selection, pluralizedWord);
    }
  });
}

1Lets talk about how to add and use multiple cursors in VSCode

Multi-cursor practical example

Next I will demonstrate a few examples of how I usually use multiple cursors. For those who are not familiar with multi-cursor editing, it may seem a bit complicated, but if you practice it yourself and practice it, you should be fine. I often use multi-cursor editing when developing, but it is not as smooth as demonstrated in the article, and the steps may not be the minimum, but it is still much more efficient than repeated editing. I often make mistakes when typing, but it doesn’t matter because I can withdraw it anyway.

Replace var

As we all know, when you learn ctrl c, ctrl v, you are already a junior programmer. When you can not only copy code but also modify other people's code, then you are already a mature programmer. Learning multi-cursor editing can greatly improve the efficiency of modifying code.

When we copy a piece of JS code from stackoverflow, there may be many vars in it. We can use multi-cursor editing to replace all vars with let.

Steps:

  • Place the cursor on var

  • L, to select all var

  • Enter let

1Lets talk about how to add and use multiple cursors in VSCode

install Multiple node packages

Sometimes when I open a new project, I need to install many eslint plug-ins. My initial approach was to copy the package names one by one from the package.json of the previous project, which was too troublesome. Some people say, why don't you just copy the package name and version number to the package.json of the new project? The main reason for not doing that is that the package version number of the previous project is not necessarily the latest, and the new project needs to install the latest version.

Steps:

  • Open package.json and set the cursor to the first package name

  • Alt Add multiple cursors to multiple package names

  • ##^ , use smart select to select the package name and Ccopy

  • N, create a new temporary file, Vpaste it

  • Set the cursor Go to the beginning of the second line,

    Alt Add multiple cursors to the same column below

  • First

    , then type a space to copy the entire text to the terminal

1Lets talk about how to add and use multiple cursors in VSCode

Reconstruct the react router path to an enumeration

Original code:

function App() {
  return (
    <HashRouter>
      <Routes>
        <Route index element={<Home />} />
        <Route path="/settings" element={<Settings />} />
        <Route path="/collection" element={<Collection />} />
        <Route path="/notFound" element={<NotFound />} />
      </Routes>
    </HashRouter>
  );
}

Reconstruct the original string route into an enumeration type:

export function App() {
  return (
    <HashRouter>
      <Routes>
        <Route index element={<Home />} />
        <Route path={RoutePath.Settings} element={<Settings />} />
        <Route path={RoutePath.Collection} element={<Collection />} />
        <Route path={RoutePath.NotFound} element={<NotFound />} />
      </Routes>
    </HashRouter>
  );
}

enum RoutePath {
  Settings = &#39;/settings&#39;,
  Collection = &#39;/collection&#39;,
  NotFound = &#39;/notFound&#39;,
}

This example was chosen mainly because text processing commands were used during the operation. To deal with the case problem, since there are too many steps, let’s just watch the animation demonstration:

1Lets talk about how to add and use multiple cursors in VSCode

实现 LetterMapper 类型

在我 TypeScript 类型体操实例解析 这篇文章中有实现过一个将字符串字面量类型中所有字符转换成大写的类型:

type LetterMapper = {
  a: &#39;A&#39;;
  b: &#39;B&#39;;
  c: &#39;C&#39;;
  d: &#39;D&#39;;
  e: &#39;E&#39;;
  f: &#39;F&#39;;
  g: &#39;G&#39;;
  h: &#39;H&#39;;
  i: &#39;I&#39;;
  j: &#39;J&#39;;
  k: &#39;K&#39;;
  l: &#39;L&#39;;
  m: &#39;M&#39;;
  n: &#39;N&#39;;
  o: &#39;O&#39;;
  p: &#39;P&#39;;
  q: &#39;Q&#39;;
  r: &#39;R&#39;;
  s: &#39;S&#39;;
  t: &#39;T&#39;;
  u: &#39;U&#39;;
  v: &#39;V&#39;;
  w: &#39;W&#39;;
  x: &#39;X&#39;;
  y: &#39;Y&#39;;
  z: &#39;Z&#39;;
};

type CapitalFirstLetter<S extends string> = S extends `${infer First}${infer Rest}`
  ? First extends keyof LetterMapper
    ? `${LetterMapper[First]}${Rest}`
    : S
  : S;

这个 LetterMapper 类型手敲会觉得很浪费光阴,让我们用多光标编辑酷炫的实现它:

Lets talk about how to add and use multiple cursors in VSCode

多光标编辑之外的选择

VSCode 作为编辑器界的新生代王者,集百家之众长,除了多光标编辑还有很多可以提高编码和重构效率的特性。例如:

  • F2 重命名符号,批量替换变量名可以的话就不要用多光标编辑
  • Snippets,曾经在 twitter 看到有人发帖说写了一下午的 react 组件,结果人家一个 snippet 就整完了
  • Code Actions On Save,在保存文件的时候自动添加缺失的 imports,格式化, lint 的 auto fix 等
  • Auto fix 和 fix all,如果你用了自动保存就不能用 Code Actions On Save 了,不过你可以手动调用自动修复和修复所有
  • 各种格式化扩展,例如使用 prettier 格式化代码风格,JS/TS Import/Export Sorter 格式化 imports

等等。作为一个 VSCode 老玩家,我都觉得 VSCode 还有很多使用的功能特性地方我没探索到。众所周知,折腾编辑器,折腾 shell,折腾系统,是程序员的三大乐趣。充满未知才会有趣,才能让我们热此不疲,让我们每一次发现新大陆的时候感叹自己以前的无知。

总结

多光标编辑是 VSCode 一个非常实用的特性,熟练掌握光标的移动,选中,删除和一些常用的文本处理命令可以让我们使用多光标编辑时更加得心应手。VSCode 的快捷键设计有它的一套自己的设计哲学,理解它不但有助于我们记忆快捷键,也便于在快捷键表中搜索。在我们自定义快捷键或者编写扩展的提供默认快捷键的时候也应该要参考这套哲学。当你觉得对下前编码重构的效率不满意时,不妨折腾下编辑器,也许能够带给你意外的惊喜。

本文完。

更多关于VSCode的相关知识,请访问:vscode教程!!

The above is the detailed content of Let's talk about how to add and use multiple cursors in VSCode. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete