10 горячих клавиш VS Code, которые ускорят вашу работу
Горячие клавиши — добро, польза и экономия времени. Давайте разберёмся, как с их помощью упростить себе жизнь в Visual Studio Code.
Создать структуру документа
Это сочетание клавиш за секунду создаёт базовую структуру кода или вложенные теги.
Быстро добавить комментарий
Чтобы добавить комментарий, нужно перейти в начало строки и дописать туда два слеша. Это медленно. Быстрее нажать в любом месте строки Ctrl + / , и строка закомментируется, если она ещё не. А если уже да, то комментарий исчезнет.
Перейти к строке под номером
Windows — Ctrl + G
macOS — Control + G
Иногда отладчики внезапно сообщают, что на строке 953 случилась непоправимая инфернальная ошибка вселенной. Чтобы не выискивать вручную, не листать и не тратить на это время, нажмите Ctrl + G , введите номер строки и спокойно спасайте вселенную.
Поменять строку местами с соседними
Случается такое, что ваш алгоритм — не алгоритм. Всё пошло не так, а вместо числа 42 вывелось сообщение «Данные удалены». Кому-то для этого нужно переписать весь код, но иногда бывает достаточно поменять строки местами и всё заработает.
Alt и стрелки меняют текущую строку местами с соседними.
Дублировать строку
Windows Shift + Alt + ↓ / ↑
macOS Shift + Option + ↓ / ↑
Это для тех, кто не хочет копировать и вставлять несколько раз одно и то же.
Перейти к парной скобке
Windows Ctrl + Shift + \
macOS Shift + Command + \
Когда кода становится много, очень просто запутаться в закрывающих и открывающих скобках, непонятно, где какой блок, и вообще, что происходит. На помощь приходит Ctrl + Shift + \ — это хорошее дополнение к стандартной подсветке парных скобок в VS Code.
Переименовать переменную
Писали, писали, а старший разработчик пришёл и сказал, что ваши переменные a , b и c — дурной тон. Чтобы не выискивать их по всему документу и не менять руками, есть F2 .
Отформатировать документ
Windows — Shift + Alt + F
macOS Shift + Option + F
VS Code предложит установить расширение или выбрать из существующих, а потом красиво отформатирует документ — расставит по местам блоки и скобки, сделает строки кода читаемыми.
Перейти к переменной
Иногда вообще непонятно, откуда взялась переменная, какая у неё область видимости и где она объявлена. F12 перенесёт вас к объявлению выделенной переменной, функции или метода. Если объявление в другом файле — всё равно перенесёт.
Включить или выключить перенос слов
Windows — Alt + Z
macOS Option + Z
Если строки кода или текст не вмещаются в редактор по ширине, включите перенос.
Включить дзен-режим
Windows — Ctrl + KZ
macOS — Command + KZ
Лучшее решение для тех, кто входит в состояние потока, когда пишет код. Дзен-режим скрывает все панели, разворачивает редактор на весь экран, и вы можете плыть в волнах кода и думать только о нём. Чтобы вернуться в реальный мир, нажмите Escape .
How to Comment in VS Code — The VSCode Comment Shortcut
This quick guide will teach you the VSCode comment shortcut and everything else you need to know about commenting in VS Code, including multi-line comments.
I don’t know of a programming language that does not support comments.
Code-comments are incredibly useful. When building out complex functionality, sometimes I’ll even write out the whole function in pseudo-code comments before writing any code.
Comments make code more readable and understandable. This is especially useful if you work on a large team with lots of people. Every comment you write could save you and your colleagues some back and forth on slack.
The other great use-case of comments is quickly disabling one or multiple lines of code. This comes in handy when debugging your program.
Comments serve two main use-cases:
- Add information that gives context to your code
- Quickly disable code while debugging
Here’s how to do both in VS Code:
Create a Comment in VSCode, the easy way.
You’ll use this mainly to add information to the flow of your program that will help your future-self and your colleagues understand what’s going on.
First, place your cursor where you’d like to add the comment. Then, use the VS Code comment shortcut that corresponds to your platform below.
- On Windows, the shortcut is: CTRL + /
- On Mac, the shortcut is: Command + /
The VSCode comment shortcut Mac is very similar to the Windows version.
Comment-out code in VSCode
This is the other main usage of comments. Commenting-out code while debugging. This is probably the most useful shortcut in here. Here’s how to do it:
- Select the text or code that you want to comment out
- Execute the shortcut that corresponds to your platform. (editor.action.commentLine)
- Windows: Ctrl + /
- Mac: Command + /
You can also uncomment using the same command. Select the code that is currently commented-out and execute the shortcut. It should become un-commented again.
Once you do it a few times it will become muscle memory and boost your productivity. I use this command constantly and can’t imagine not having it.
Toggling block comments in VSCode
Some programming languages support block comments. These are comments which span multiple lines of code (a block). If you want to comment out multiple lines of code within the same comment, this is what you’re looking for.
To toggle a VSCode comment block, you can use editor.action.blockComment:
- Windows: Shift + Alt + A
- Mac: Shift + Option + A
There’s one other way to comment and un-comment, but it’s not as handy.
Comment out code (editor.action.addCommentLine):
- Windows: Ctrl + K + C
- Mac: Command + K + C
Un-comment code (editor.action.removeCommentLine):
- Windows: Ctrl + K + U
- Mac: Command + K + U
The main difference with these commands is that they each only have a single purpose. They do not toggle code like the slash shortcut. So, if you keep executing (CTRL + K + C), the comments will keep piling up, as shown in the screenshot below.
The same is true for un-commenting.
Like I said, I think these commands are a lot less handy, and I don’t think there’s ever a good reason to them over the slash one. unless of course you rebound the slash shortcut to do something else.
Changing the comment key binds in VS Code
If for some reason you want to change the default key binds for commenting and uncommenting in VS Code, you can follow these steps:
How to comment multiple lines in Visual Studio Code?
I cannot find a way to comment and uncomment multiple lines of code in Visual Studio Code.
Is it possible to comment and uncomment multiple lines in Visual Studio Code using some shortcut? If yes, how to do it?
41 Answers 41
Windows: Shift + Alt + A
Linux: Shift + Ctrl + A
Here you can find all the keyboard shortcuts:
PS: I prefer Ctrl + Shift + / for toggling block comments because Ctrl + / is shortcut for toggling line comments so it’s naturally easier to remember. To do so, just click on the settings icon in the bottom left of the screen and click ‘Keyboard Shortcuts’ and find "toggle block. ". Then click and enter your desired combination.
First, select the lines you want to comment/uncomment ( CTRL + L is convenient to select a few lines)
To toggle line comments, execute editor.action.commentLine ( CTRL + / on Windows)
or
To add line comments, execute editor.action.addCommentLine ( CTRL + K CTRL + C )
To remove line comments, execute editor.action.removeCommentLine ( CTRL + K CTRL + U )
or
To toggle a block comment, execute editor.action.blockComment ( SHIFT — ALT — A )
How to comment out multiline / single line in VS Code:
MacOS:
Shift + Option + A :
Windows:
How to remap / change these shortcuts?
Windows: File > Preferences > Keyboard Shortcuts.
MacOS: Code > Preferences > Keyboard Shortcuts.
You can search through the list both by keybindings (key names) and command names.
The keyboard shortcut to comment multiple in Windows is shift + alt + A .
In my case, Ubuntu, the shortcut is ctrl + shift + A .
You can see all available keybindings on the official documentation.
Here’s the relevant bit for osx:
You will need to select the lines you want to comment first, then execute above shortcut, i.e. ⌘/ on osx Ctrl/ on Windows.
In MacOS comment out multi-lines in Visual Studio Code by keyboard shortcut:
Option + Shift + A
Select all lines and then press CTRL + /
Try option 1 first. If it doesn’t work for you then try option 2 which is the actual shortcut for VS Code:
Option 1. Alt / Option + Shift + A
Option 2. While the text is selected hit Ctrl / Cmd + K and then Ctrl / Cmd + C .
As of now (version 1.16.3), you can check all available keyboard shortcuts by going into File > Preferences > Keyboard shortcuts. Here you can search for shortcuts related to code comments.
For users who are coming from Sublime Text or likes to have Ctrl + Shift + / , you can make the change from the above mentioned settings panel or simply install the Sublime Text Keymap extension by Microsoft.
Update: As VS Code has become pretty much standard editor for almost everything these days, I would say picking option 1 is always helpful.
VS Code: Making Comments in React and JSX
This article shows you a couple of different ways to comment out (and uncomment) a single line or a block of code in React and JSX.
Using Keyboard Shortcuts
If you are using VS Code (Visual Studio Code) to develop your React app then you can easily and quickly make comments by using keyboard shortcuts.
All you need to do is select that code block with your mouse, then press the following key combination:
- Ctrl + K, then press Ctrl + C if you’re using Windows
- Command + K, then press Command + C if you’re on a Mac
To uncomment a block of code, use your mouse to select it and then use the key combination:
- Ctrl + K then Ctrl + U if you’re on Windows
- Command + K, then Command + U if you’re on a Mac
You can also use:
- Ctrl + / (the slash key) to comment and uncomment lines of code on Windows.
- Command + / to comment and uncomment lines of code on Mac.
Demo:
Manually Comment
For JSX code, you can use* …*/> syntax to make comments:
For non-JSX code (the code outside return or render), you can use // (double-slashes) or /*…*/ syntax to comment out lines of code, like this:
Conclusion
We’ve run through a couple of techniques for making comments in React and JSX. If you’d like to explore more about modern React and frontend development, take a look at the following articles:
You can also check our React category page and React Native category page for the latest tutorials and examples.