Let's talk about how to add and use multiple cursors in VSCode
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!
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.
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
:
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
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
⌘ 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.
case provided in the search box to ignore ,
matches Whole word ,
regular function to find complex text, and then use
⌘ ⇧ L to select all.
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.
cursor right,
cursor end:
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
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:
- 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
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
The shortcut key to move the cursor plus theOn Mac⌫ key is leftThe shortcut key to delete the cursor moving area, add Up fn ⌫ is right shortcut key to delete the cursor movement area
⌘ → 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
letterCase as an example, the conversion results are:
- Transform to Uppercase:
- LETTERCASE
- lettercase
- LetterCase
- letter_case
transform to to find all text conversion commands
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:
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:
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('pluralize'); 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); } }); }
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
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
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> ); }
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', }
实现 LetterMapper 类型
在我 TypeScript 类型体操实例解析 这篇文章中有实现过一个将字符串字面量类型中所有字符转换成大写的类型:
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;
这个 LetterMapper
类型手敲会觉得很浪费光阴,让我们用多光标编辑酷炫的实现它:
多光标编辑之外的选择
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to define header files using Visual Studio Code? Create a header file and declare symbols in the header file using the .h or .hpp suffix name (such as classes, functions, variables) Compile the program using the #include directive to include the header file in the source file. The header file will be included and the declared symbols are available.

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

How to solve the problem that Chinese comments in Visual Studio Code become question marks: Check the file encoding and make sure it is "UTF-8 without BOM". Change the font to a font that supports Chinese characters, such as "Song Style" or "Microsoft Yahei". Reinstall the font. Enable Unicode support. Upgrade VSCode, restart the computer, and recreate the source file.

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Common commands for VS Code terminals include: Clear the terminal screen (clear), list the current directory file (ls), change the current working directory (cd), print the current working directory path (pwd), create a new directory (mkdir), delete empty directory (rmdir), create a new file (touch) delete a file or directory (rm), copy a file or directory (cp), move or rename a file or directory (mv) display file content (cat) view file content and scroll (less) view file content only scroll down (more) display the first few lines of the file (head)

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

Causes and solutions for the VS Code terminal commands not available: The necessary tools are not installed (Windows: WSL; macOS: Xcode command line tools) Path configuration is wrong (add executable files to PATH environment variables) Permission issues (run VS Code as administrator) Firewall or proxy restrictions (check settings, unrestrictions) Terminal settings are incorrect (enable use of external terminals) VS Code installation is corrupt (reinstall or update) Terminal configuration is incompatible (try different terminal types or commands) Specific environment variables are missing (set necessary environment variables)
