If there are any features VSCode can use to improve coding efficiency, multi-cursor editing is definitely one of them. Multi-cursor editing allows us to avoid repeating the same text operations, and the text processing commands built into VSCode and provided by third-party extensions greatly increase the flexibility of multi-cursor editing. It is hoped that this article will teach readers how to flexibly use multi-cursor editing in daily editing.

Content Outline:

  • How do I add multiple cursors
  • Move the cursor
  • Select the text
  • Delete the text
  • Text processing command
  • Multi-cursor field example
  • Better option for multi-cursor editing

How do I add multiple cursors

General method

Hold down the ⌥ key and move the cursor to wherever you want to add a cursor. Click to add a cursor.

Add cursor shortcut keys

The ⌥ key is included in VSCode and cursor related shortcuts

⌘+K, ⌘+S to open VSCode shortcut list, search cursor will list all cursor related shortcuts, search add cursor to view and add cursor related shortcuts:

Add cursor to same column:

  • ++left: Adds the cursor to the same column in the next row
  • ++write: Adds the cursor to the same column as the previous row

Add district

Multiple cursors and selections can exist simultaneously in the VSCode editor. In most selection commands in VSCode, the selection is accompanied by a cursor. So we can use the add selection shortcut to add multiple cursors.

Commonly used are:

  • +D: Adds a selection to the next match found, or if there are multiple matches, one more is added with each trigger
  • ++L: adds a selection to all matches found

The above two shortcuts, while referring to a match found, do not actually expand the search box when used.

The commands offered by VSCode are symmetric most of the time. For example, ⌘+D is to add a selection to the next lookup match, and there is a probability that there will be a command to add a selection to the previous lookup match.

To allow more complex text to be searched, ⌘+⇧+L can be used to initiate a search, use the search box to omit case, match entire words, and invoke the re function to find complex text.

When registering a select, use the ⌥+⇧+I shortcut to add a cursor to the end of all rows of the select. If you want to move the cursor to the top of the line, type the Home button.

Here is an example of selecting multiple lines, adding the cursor to the end of all lines, and changing the TypeScript interface to use commas to separate properties:

The cursor

Multi-cursor editing is obviously impossible with mouse positioning, which requires us to use buttons to move. The basic four arrows, up, down, left, and right, Home and End keys don’t need to be said. In addition, it is common to move one word, or part of a word, at a time.

Cursor right, cursor End, etc., to view cursor shortcuts:

Word level movement is very common:

  • +-: Move the cursor right to the end of the next word
  • ^++-: Move the cursor right to the next part of the word, where the hump, beginning, and end are stops

Previously, we talked about the symmetrical design of VSCode commands. ⌥+→ moves to the right to the next suffix, so ⌥+ ← moves to the left to the previous prefix.

It also verifies that the cursor related shortcut keys are ⌥. Therefore, when we customize the shortcut key, the cursor related shortcut key should also include ⌥. For example, we can define ⌥+J to move to the previous git change, and symmetric design ⌥+K to move to the next git change. Easy to remember, easy to search.

Some Mac users may find the cursor moving too slowly. This can be adjusted in Settings -> Keyboard to make the cursor move more silky:

  • Drag to moveDelay before repetitionThe slider sets the wait time before the character starts repeating.
  • Drag to moveThe key repeatSlider to set the rate at which characters are repeated.

It is recommended to speed up the key repetition so that the cursor moves faster and more silky.

Select the text

In multi-cursor editing, the most common operations are move, select, delete, insert, etc.

Registering the move cursor shortcut plus ⇧ will select the move area shortcut

Here are a few examples to prove the rule:

  • -Is to move one character to the right,+-You can select the next character right
  • writeI’m going to move up one row,+writeI’m just going to pick one row up
  • +-Is moving right to the end of the word,++-Select the current position of the cursor to the next word
  • ^++-Is to move right to the next part of the word,+^++-That’s part of the word to the right

One selection command that needs to be covered separately is Smart Select. We know that the CMD + D shortcut can select a word, but it can not select a string, so we can use smart selection to do this.

  • ^++-: Expands the selection range
  • ^++please: Reduces the selection range

Antfu recently wrote an extension to intelligently select text by double-clicking on it. Although it has nothing to do with multi-cursor editing, readers who are interested can check it out: vscode-smart-clicks.

Delete the text

The shortcut key for moving the cursor plus ⌫ is the shortcut key for deleting the cursor movement area to the left, and the shortcut key for deleting the cursor movement area to the right is fn + ⌫

⌘+→ to the End key, ⌘+← to the Home key, and fn + ⌫ to the Delete key should be common to all applications.

  • +: Delete left to the beginning of the word
  • +: Deletes part of the word to the left

Because Backspace is inherently directional, there is no need for arrow keys in the shortcut keys.

Text processing command

For multi-cursor editing, we can use commands that come with VSCode or third-party extensions to quickly insert specific text or convert selected text to specific text.

VSCode has the following built-in conversion results to letterCase:

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

Search transform to to find all text conversion commands

To give a practical example, let’s say we want to change a bunch of small hump constants to all caps:

In addition to VSCode’s built-in Text processing commands, you can also use third-party plug-ins, which are recommended here: Text Power Tools. Recommended reasons: Active maintenance and rich functions.

There are so many features that readers can check out the extended home page. I don’t think you’d be able to see this article if you didn’t have the spirit of exploration and the ability to toss around. I’ll just show you how to insert numbers:

Competent readers can also write their own VSCode extensions for more text processing commands like insert, transform, and even delete. It is important to note that the implementation handles all checks, such as the author’s VSCode extension VSCode FE Helper, which pluralizes selected words. The code is simple. Note that all selections are traversed, so this command handles all selections when called in multi-cursor editing:

import { TextEditor } from 'vscode';

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

Multi-cursor field example

I’m going to show you a few examples of how I use multiple cursors. For friends who are not familiar with multi-cursor editing may look a little complicated, but their own practice should be no problem. I often use multi-cursor editing in my development, but it’s not as slick as this one, and it’s probably not minimal, but it’s still much more efficient than repeated editing. I’m gonna make a lot of mistakes, but it doesn’t matter.

Replace the var

As you all know, when you learn CTRL + C, CTRL + V, you are already a beginner programmer. When you can not only copy code but also change other people’s code, you are a mature programmer. Learned multi – cursor editing, we can greatly improve the efficiency of code modification.

When we copy JS code from StackOverflow, which may contain many var’s, we can use multi-cursor editing to replace all var’s with lets.

Steps:

  1. Place the cursor on var
  2. ++LTo select all var’s
  3. Input the let

Install multiple Node packages

Sometimes WHEN I start a new project, I need to install a lot of ESLint plugins. At first, I copied the package names one by one from the package.json of the previous project, which was too troublesome. Why not just copy the package name and the version number into the package.json of the new project, because the package version of the previous project is not necessarily the latest, and the new project needs the latest version installed.

Steps:

  1. Open package.json and place the cursor on the first package name
  2. +Alt+leftAdd multiple cursors to multiple package names
  3. ^++-, the use ofsmart selectSelect the package name and+Ccopy
  4. +N, create a temporary file,+VPaste in the past
  5. Set the cursor to the beginning of the second line,+Alt+leftAdd multiple cursors to the same column below
  6. First,“, one more space to copy the entire text to Terminal

Reconstruct the React Router path to an enumeration

The 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>
  );
}
Copy the code

Refactor a route from a string to 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 = '/settings',
  Collection = '/collection',
  NotFound = '/notFound',}Copy the code

This example is selected mainly because the operation process uses text processing command to deal with the case problem, because there are too many steps, you can directly watch the GIF demo:

Implement the LetterMapper type

In my TypeScript type exercise instance parsing article, I implemented a type that converts all characters in a string literal type to uppercase:

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

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

This LetterMapper type will feel like a waste of time, let’s implement it with a cool multi-cursor edit:

An alternative to multi-cursor editing

VSCode is the new king of the editor world, with many features besides multi-cursor editing to improve coding and refactoring efficiency. Such as:

  • F2 Rename symbols, batch replace variable names and do not use multiple cursors if possible
  • Snippets, I’ve seen someone on Twitter post about writing a React component all afternoon, and then a snippet is done
  • Code Actions On Save, automatically add missing imports, formatting, Auto fix for Lint, etc when saving files
  • Auto fix and Fix All, you can’t use Code Actions On Save if you use Auto Save, but you can manually call Auto fix and fix all
  • Formatting extensions, such as formatting code styles using prettier, JS/TS Import/Export Sorter formatting imports

And so on. As a veteran VSCode player, I feel that VSCode still has a lot of features that I haven’t explored yet. As we all know, fiddling with the editor, the shell, and the system is the programmer’s three main pleasures. It’s the unknown that’s interesting, that keeps us excited, that makes us lament our ignorance every time we discover a new continent.

conclusion

Multi-cursor editing is a very useful feature of VSCode. Mastering cursor movement, select, delete, and some common text processing commands will make it easier to use multi-cursor editing. VSCode’s shortcut design has its own design philosophy, and understanding it not only helps us remember shortcuts, but also makes it easy to search in the shortcut table. This philosophy should also be used when customizing shortcuts or writing extensions that provide default shortcuts. When you’re not satisfied with the efficiency of pre-coding refactoring, play around with the editor and you may be pleasantly surprised.

In this paper, to the end.

First in my blog warehouse, nuggets and zhihu, welcome to blog warehouse to raise an issue or in the comments section to ask questions and discuss, without my permission, prohibit reprint.