Vs code windows hotkeys

Visual Studio Code lets you perform most tasks directly from the keyboard. This article explains how you can modify the default keyboard shorts that come with VS Code.

Note

If you visit this page on a Mac, you will see the keyboard shortcuts for the Mac. If you visit using Windows or Linux, you will see the keys for that platform. If you need the keyboard shortcuts for another platform, hover your mouse over the key you are interested in.

Keyboard Shortcuts editor

VS Code provides a rich keyboard shortcut editing experience with the Keyboard Shortcuts editor. The editor lists all available commands with and without keyboard shortcuts, and enables you to change, remove, or reset their keyboard shortcuts using the available actions. To find commands or keyboard shortcuts, use the search box and enter a command or shortcut to filter the list.

To open the Keyboard Shortcuts editor, select the File > Preferences > Keyboard Shortcuts menu, or use the Preferences: Open Keyboard Shortcuts command (⌘K ⌘S (Windows, Linux Ctrl+K Ctrl+S)) in the Command Palette.

Keyboard Shortcuts

Note

The keyboard shortcuts match your current keyboard layout. For example, keyboard shortcut Cmd+\ in US keyboard layout will be shown as Ctrl+Shift+Alt+Cmd+7 when the layout is changed to German. The dialog to change a keyboard shortcut assigns the correct and desired keyboard shortcut according to your keyboard layout.

Customize shortcuts for UI actions

To customize a keyboard shortcut for a UI action, right-click on any action item in your workbench, and select Configure Keybinding. This opens the Keyboard Shortcuts editor, filtered to the corresponding command. If the action has a when clause, it’s automatically included, making it easier to set up your keyboard shortcuts just the way you need them.

Keymap extensions

Keymap extensions modify the VS Code shortcuts to match those of other editors, so you don’t need to learn new keyboard shortcuts.

Select the File > Preferences > Migrate Keyboard Shortcuts from… menu to get a list of popular keymap extensions. There is also a Keymaps category of extensions in the Marketplace.

Keyboard Shortcuts reference

We have a printable version of the default keyboard shortcuts. Select Help > Keyboard Shortcut Reference to display a condensed PDF version suitable for printing as an easy reference.

The following links provide access to the three platform-specific versions (US English keyboard):

  • Windows
  • macOS
  • Linux

Detecting keyboard shortcut conflicts

If you have many extensions installed or you have modified your keyboard shortcuts, there might be keyboard shortcut conflicts, where the same keyboard shortcut is mapped to multiple commands. This can result in confusing behavior, especially if different keyboard shortcuts are going in and out of scope as you move around the editor.

Right-click on an item in the list of keyboard shortcuts, and select Show Same Keybindings to view all entries with the same keyboard shortcut.

show keyboard shortcut conflicts menu

Troubleshooting keyboard shortcuts

To troubleshoot keyboard shortcut problems, you can execute the command Developer: Toggle Keyboard Shortcuts Troubleshooting. This activates logging of dispatched keyboard shortcuts and opens the Output panel with the corresponding log file.

You can then press your desired keyboard shortcut and check what keyboard shortcut VS Code detects and what command is invoked.

For example, when pressing cmd+/ in a code editor on macOS, the logging output would be:

[KeybindingService]: / Received  keydown event - modifiers: [meta], code: MetaLeft, keyCode: 91, key: Meta
[KeybindingService]: | Converted keydown event - modifiers: [meta], code: MetaLeft, keyCode: 57 ('Meta')
[KeybindingService]: \ Keyboard event cannot be dispatched.
[KeybindingService]: / Received  keydown event - modifiers: [meta], code: Slash, keyCode: 191, key: /
[KeybindingService]: | Converted keydown event - modifiers: [meta], code: Slash, keyCode: 85 ('/')
[KeybindingService]: | Resolving meta+[Slash]
[KeybindingService]: \ From 2 keybinding entries, matched editor.action.commentLine, when: editorTextFocus && !editorReadonly, source: built-in.

In the example log, the first keydown event is for the MetaLeft key (cmd) and cannot be dispatched. The second keydown event is for the Slash key (/) and is dispatched as meta+[Slash]. There were two keyboard shortcut entries mapped from meta+[Slash] and the one that matched was for the command editor.action.commentLine, which has the when condition editorTextFocus && !editorReadonly and is a built-in keyboard shortcut entry.

Viewing modified keyboard shortcuts

To filter the list to only show the shortcuts you have modified, select the Show User Keybindings command in the More Actions () menu. This applies the @source:user filter to the Keyboard Shortcuts editor (Source is ‘User’).

Default Keyboard Shortcuts

Advanced customization

VS Code keeps track of the keyboard shortcuts you have customized in the keybindings.json file. For advanced customization, you can also directly modify the keybindings.json file.

To open the keybindings.json file:

  • Open Keyboard Shortcuts editor, and then select the Open Keyboard Shortcuts (JSON) button on the right of the editor title bar.

    Open Keyboard Shortcuts JSON button

  • Alternatively, use the Open Default Keyboard Shortcuts (JSON) command in the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

Keyboard rules

A keyboard shortcut configuration in VS Code is also known as a keyboard rule. Each rule consists of the following attributes:

  • key: describes the pressed key(s), for example ⌘F (Windows, Linux Ctrl+F).
  • command: the identifier of the VS Code command to execute, for example workbench.view.explorer to open the Explorer view.
  • when: (optional) clause containing a boolean expression that is evaluated depending on the current context.

Chords (two separate keypress actions) are described by separating the two keypresses with a space. For example, Ctrl+K Ctrl+C.

When a key is pressed, the following evaluation rules are applied:

  • Rules are evaluated from bottom to top.
  • The first rule that matches both the key and when clause, is accepted.
  • If a rule is found, no more rules are processed.
  • If a rule is found and has a command set, the command is executed.

The additional keybindings.json rules are appended at runtime to the bottom of the default rules, thus allowing them to overwrite the default rules. The keybindings.json file is watched by VS Code, so editing it while VS Code is running will update the rules at run-time.

The keyboard shortcuts dispatching is done by analyzing a list of rules that are expressed in JSON. Here are some examples:

// Keyboard shortcuts that are active when the focus is in the editor
{ "key": "home",            "command": "cursorHome",                  "when": "editorTextFocus" },
{ "key": "shift+home",      "command": "cursorHomeSelect",            "when": "editorTextFocus" },

// Keyboard shortcuts that are complementary
{ "key": "f5",              "command": "workbench.action.debug.continue", "when": "inDebugMode" },
{ "key": "f5",              "command": "workbench.action.debug.start",    "when": "!inDebugMode" },

// Global keyboard shortcuts
{ "key": "ctrl+f",          "command": "actions.find" },
{ "key": "alt+left",        "command": "workbench.action.navigateBack" },
{ "key": "alt+right",       "command": "workbench.action.navigateForward" },

// Global keyboard shortcuts using chords (two separate keypress actions)
{ "key": "ctrl+k enter",    "command": "workbench.action.keepEditor" },
{ "key": "ctrl+k ctrl+w",   "command": "workbench.action.closeAllEditors" },

Accepted keys

The key is made up of modifiers and the key itself.

The following modifiers are accepted:

Platform Modifiers
macOS Ctrl+, Shift+, Alt+, Cmd+
Windows Ctrl+, Shift+, Alt+, Win+
Linux Ctrl+, Shift+, Alt+, Meta+

The following keys are accepted:

  • f1-f19, a-z, 0-9
  • `, , =, [, ], \, ;, , ,, ., /
  • left, up, right, down, pageup, pagedown, end, home
  • tab, enter, escape, space, backspace, delete
  • pausebreak, capslock, insert
  • numpad0-numpad9, numpad_multiply, numpad_add, numpad_separator
  • numpad_subtract, numpad_decimal, numpad_divide

Command arguments

You can invoke a command with arguments. This is useful if you often perform the same operation on a specific file or folder. You can add a custom keyboard shortcut to do exactly what you want.

The following is an example overriding the Enter key to print some text:

{
  "key": "enter",
  "command": "type",
  "args": { "text": "Hello World" },
  "when": "editorTextFocus"
}

The type command will receive {"text": "Hello World"} as its first argument, and add «Hello World» to the file instead of producing the default command.

For more information on commands that take arguments, refer to Built-in Commands.

Running multiple commands

A keyboard shortcut can be configured to run multiple commands sequentially by using the command runCommands.

  • Run several commands without arguments:

    The following example copies the current line down, marks the current line as a comment, and moves the cursor to the copied line.

    {
      "key": "ctrl+alt+c",
      "command": "runCommands",
      "args": {
        "commands": [
          "editor.action.copyLinesDownAction",
          "cursorUp",
          "editor.action.addCommentLine",
          "cursorDown"
        ]
      }
    },
    
  • To pass arguments to commands:

    This example creates a new untitled TypeScript file and inserts a custom snippet.

    {
      "key": "ctrl+n",
      "command": "runCommands",
      "args": {
        "commands": [
          {
            "command": "workbench.action.files.newUntitledFile",
            "args": {
              "languageId": "typescript"
            }
          },
          {
            "command": "editor.action.insertSnippet",
            "args": {
              "langId": "typescript",
              "snippet": "class ${1:ClassName} {\n\tconstructor() {\n\t\t$0\n\t}\n}"
            }
          }
        ]
      }
    },
    

Note that commands run by runCommands receive the value of "args" as the first argument. In the previous example, workbench.action.files.newUntitledFile receives {"languageId": "typescript" } as its first and only argument.

To pass several arguments, you need to have "args" as an array:

{
  "key": "ctrl+shift+e",
  "command": "runCommands",
  "args": {
    "commands": [
      {
        // command invoked with 2 arguments: vscode.executeCommand("myCommand", "arg1", "arg2")
        "command": "myCommand",
        "args": ["arg1", "arg2"]
      }
    ]
  }
}

To pass an array as the first argument, wrap the array in another array: "args": [ [1, 2, 3] ].

Removing a keyboard shortcut

To remove a keyboard shortcut, right-click on the entry in the Keyboard Shortcuts editor, and select Remove Keybinding.

To remove a keyboard shortcut by using the keybindings.json file, add a - to the command and the rule will be a removal rule.

Here is an example:

// In Default Keyboard Shortcuts
...
{ "key": "tab", "command": "tab", "when": ... },
{ "key": "tab", "command": "jumpToNextSnippetPlaceholder", "when": ... },
{ "key": "tab", "command": "acceptSelectedSuggestion", "when": ... },
...

// To remove the second rule, for example, add in keybindings.json:
{ "key": "tab", "command": "-jumpToNextSnippetPlaceholder" }

To override a specific keyboard shortcut rule with an empty action, you can specify an empty command:

// To override and disable any `tab` keyboard shortcut, for example, add in keybindings.json:
{ "key": "tab", "command": "" }

Keyboard layouts

Note

This section relates only to keyboard shortcuts, not to typing in the editor.

Keys are string representations for virtual keys and do not necessarily relate to the produced character when they are pressed. More precisely:

  • Reference: Virtual-Key Codes (Windows)
  • tab for VK_TAB (0x09)
  • ; for VK_OEM_1 (0xBA)
  • = for VK_OEM_PLUS (0xBB)
  • , for VK_OEM_COMMA (0xBC)
  • for VK_OEM_MINUS (0xBD)
  • . for VK_OEM_PERIOD (0xBE)
  • / for VK_OEM_2 (0xBF)
  • ` for VK_OEM_3 (0xC0)
  • [ for VK_OEM_4 (0xDB)
  • \ for VK_OEM_5 (0xDC)
  • ] for VK_OEM_6 (0xDD)
  • for VK_OEM_7 (0xDE)
  • etc.

Different keyboard layouts usually reposition these virtual keys or change the characters produced when they are pressed. When using a different keyboard layout than the standard US, Visual Studio Code does the following:

All the keyboard shortcuts are rendered in the UI using the current system’s keyboard layout. For example, Split Editor when using a French (France) keyboard layout is now rendered as Ctrl+*:

render keyboard shortcut

When editing keybindings.json, VS Code highlights misleading keyboard shortcuts, those that are represented in the file with the character produced under the standard US keyboard layout, but that need pressing keys with different labels under the current system’s keyboard layout. For example, here is how the default keyboard shortcut rules look like when using a French (France) keyboard layout:

keybindings.json guidance

There is also a UI control that helps input the keyboard shortcut rule when editing keybindings.json. To launch the Define Keybinding control, press ⌘K ⌘K (Windows, Linux Ctrl+K Ctrl+K). The control listens for key presses and renders the serialized JSON representation in the text box and below it, the keys that VS Code has detected under your current keyboard layout. Once you’ve typed the key combination you want, you can press Enter and a rule snippet is inserted.

keyboard shortcut widget

Note

On Linux, VS Code detects your current keyboard layout on startup, and then caches this information. We recommend that you restart VS Code when you change your keyboard layout.

Keyboard layout-independent bindings

Using scan codes, it is possible to define keyboard shortcuts that do not change with the change of the keyboard layout. For example:

{ "key": "cmd+[Slash]", "command": "editor.action.commentLine", "when": "editorTextFocus" }

Accepted scan codes:

  • [F1]-[F19], [KeyA]-[KeyZ], [Digit0]-[Digit9]
  • [Backquote], [Minus], [Equal], [BracketLeft], [BracketRight], [Backslash], [Semicolon], [Quote], [Comma], [Period], [Slash]
  • [ArrowLeft], [ArrowUp], [ArrowRight], [ArrowDown], [PageUp], [PageDown], [End], [Home]
  • [Tab], [Enter], [Escape], [Space], [Backspace], [Delete]
  • [Pause], [CapsLock], [Insert]
  • [Numpad0]-[Numpad9], [NumpadMultiply], [NumpadAdd], [NumpadComma]
  • [NumpadSubtract], [NumpadDecimal], [NumpadDivide]

when clause contexts

VS Code gives you precise control over when your keyboard shortcuts are enabled through the optional when clause. If your keyboard shortcut doesn’t have a when clause, the keyboard shortcut is globally available at all times. A when clause evaluates to either true or false for enabling keyboard shortcuts.

VS Code sets various context keys and specific values depending on what elements are visible and active in the VS Code UI. For example, the built-in Start Debugging command has the keyboard shortcut F5, which is only enabled when there is an appropriate debugger available (context debuggersAvailable is true) and the editor isn’t in debug mode (context inDebugMode is false):

Start Debugging when clause in the Keyboard Shorts editor

You can also view a keyboard shortcut’s when clause directly in the default keybinding.json (Preferences: Open Default Keyboard Shortcuts (JSON)):

{ "key": "f5",  "command": "workbench.action.debug.start",
                   "when": "debuggersAvailable && !inDebugMode" },

Conditional operators

For when clause conditional expressions, the following conditional operators are useful for keyboard shortcuts:

Operator Symbol Example
Equality == "editorLangId == typescript"
Inequality != "resourceExtname != .js"
Or || "isLinux||isWindows"
And && "textInputFocus && !editorReadonly"
Matches =~ "resourceScheme =~ /^untitled$|^file$/"

You can find the full list of when clause conditional operators in the when clause contexts reference.

Available contexts

You can find some of the available when clause contexts in the when clause context reference.

The list there isn’t exhaustive and you can find other when clause contexts by searching and filtering in the Keyboard Shortcuts editor (Preferences: Open Keyboard Shortcuts ) or reviewing the default keybindings.json file (Preferences: Open Default Keyboard Shortcuts (JSON)).

Custom keyboard shortcuts for refactorings

The editor.action.codeAction command lets you configure keyboard shortcuts for specific Refactorings (Code Actions). For example, the keyboard shortcut below triggers the Extract function refactoring Code Action:

{
  "key": "ctrl+shift+r ctrl+e",
  "command": "editor.action.codeAction",
  "args": {
    "kind": "refactor.extract.function"
  }
}

This is covered in depth in the Refactoring article, where you can learn about different kinds of Code Actions and how to prioritize them in the case of multiple possible refactorings.

  • VS Code default keyboard shortcuts reference

Common questions

How can I find out what command is bound to a specific key?

In the Keyboard Shortcuts editor, you can filter on specific keystrokes to see which commands are bound to which keys. In the following screenshot, you can see that Ctrl+Shift+P is bound to Show All Commands to bring up the Command Palette.

Keyboard shortcuts quick outline

How to add a keyboard shortcut to an action, for example, add Ctrl+D to Delete Lines

Find a rule that triggers the action in the Default Keyboard Shortcuts and write a modified version of it in your keybindings.json file:

// Original, in Default Keyboard Shortcuts
{ "key": "ctrl+shift+k",          "command": "editor.action.deleteLines",
                                     "when": "editorTextFocus" },
// Modified, in User/keybindings.json, Ctrl+D now will also trigger this action
{ "key": "ctrl+d",                "command": "editor.action.deleteLines",
                                     "when": "editorTextFocus" },

How can I add a keyboard shortcut for only certain file types?

Use the editorLangId context key in your when clause:

{ "key": "shift+alt+a",           "command": "editor.action.blockComment",
                                     "when": "editorTextFocus && editorLangId == csharp" },

I have modified my keyboard shortcuts in keybindings.json; why don’t they work?

The most common problem is a syntax error in the file. Otherwise, try removing the when clause or picking a different key. Unfortunately, at this point, it is a trial and error process.

04/03/2025

#База знаний


  • 0

Становимся многорукими волшебниками: ускоряемся с помощью хоткеев и парочки других приёмов.

 vlada_maestro / shutterstock

В IT пришёл из наружной рекламы, где проработал с десяток лет. В Skillbox изучает веб-вёрстку. Увлекается археологией, диджеингом и плёночной фотографией.

Здорово экономят время разработчика горячие клавиши. Есть такие и в Visual Studio Code. Здесь даже можно создавать свои сочетания, но большинству пользователей хватает исходных комбинаций (особенно новичкам, у кого и так глаза разбегаются от уймы настроек).

Пройдёмся по самым полезным для начинающего верстальщика. Читайте и сразу же пробуйте.

Типичная задача

Найти все элементы с классом link и стилизовать некоторые, присвоив им дополнительный класс.

Что делать

Нажмите Ctrl + F (Windows) или ⌘Cmd + F (macOS). Введите искомое — высветятся все найденные места. Остаётся перемещаться по ним (стрелочками в форме поиска).

Ситуация

Вы хотите создать комментарий или временно отключить участок кода (например, чтобы проверить работу оставшейся части).

Что делать

Выделите нужный участок и нажмите Ctrl + / (Windows) или ⌘Cmd + / (macOS). Если выделения нет, то закомментируется строка, в которой стоит курсор (раскомментировать её можно так же).

Типичные ситуации

  • При проверке вёрстки понадобилось найти и изменить определённое свойство: инспектор кода в браузере показывает путь к нужному файлу (чаще всего со стилями) и номер строки в нём.
  • В редакторе кода появляется сообщение об ошибке в определённой строке.

Что делать

Нажмите Ctrl + G (Windows) или ⌃Ctrl + G (macOS), введите номер строки — и вам не придётся листать вручную.

Типичная ситуация

Нужно изменить вложенность элемента, дать ему правильную обёртку. Вообще, перемещать элементы на уровень выше или ниже приходится часто, особенно на первых этапах вёрстки.

Что делать

Поставьте курсор на нужную строку и нажмите Alt + ↑ / ↓ (Windows) или
⌥Option + ↑ / ↓ (macOS).

Следите за сохранением структуры документа — не забывайте переносить и закрывающие теги.

Ситуация

В разметку надо быстро добавить одинаковые элементы. То есть вставить дубликат строки выше или ниже этой же строки.

Что делать

Поставьте курсор на нужную строку и нажмите Shift+Alt + ↓ / ↑ (Windows) или ⇧Shift + ⌥Option + / (macOS).

Типичная потребность

Быстро выровнять код, чтобы он стал более читаемым, понятным, красивым и соответствовал вашему код-стайлу (например, о джавишном читайте здесь).

Что делать

Жмите Shift + Alt + F (Windows) или ⇧Shift + ⌥Option + F (macOS).

Чтобы форматирование работало:

  • Установите плагин форматирования кода.
  • Настройте редактор в соответствии с вашим код-стайлом. И не забудьте выставить верное число отступов (общеприняты 2 или 4).

Мультикурсорность зрелищна сама по себе и здорово ускоряет работу верстальщика.

Ситуация

Вам понадобилось написать одно и то же сразу в нескольких местах.

Чтобы размножить курсор:

  • Зажмите Alt (в Windows) или ⌥Option (в macOS) и кликайте левой кнопкой мышки там, куда нужно добавить курсор.
  • Выделите несколько строк, зажав среднюю кнопку мыши. В каждой из выделенных строк появится по курсору.
  • Если лень кликать мышкой, то дублировать курсор можно так: Ctrl + Alt + ↑ / ↓ (Windows) или ⌥Option + ⌘Cmd + ↑ / ↓ (macOS).

Ситуация

Нужно изменить одинаковый код сразу в нескольких местах.

Что делать

Выделите мышью символы и нажмите Ctrl + D (Windows) или ⌘Cmd + D (macOS). Если нажать больше одного раза, то к выделению добавится ещё одно вхождение того же куска далее по тексту. Затем можно редактировать все выделенные области сразу (подсвечиваются синим).

Как это работает

Вы набираете один-два символа, а автоподстановка предлагает название тега (в паре с закрывающим) для HTML или название свойства для CSS. Дождитесь, пока редактор подсветит предлагаемый вариант (когда их несколько — выберите нужный), и нажмите Tab или Enter.

Все доступные сокращения здесь. По мере запоминания ваши навыки и скорость будут расти, и, поверьте, это немалое удовольствие.

Зачем нужно 

Чтобы быстрее создавать структуры из вложенных друг в друга тегов.

Например: нужно создать ненумерованный список, вложить в него четыре элемента, внутри каждого из которых будет по ссылке класса link. И всё это быстро-быстро.

Что делать

Достаточно набрать ul>li*4>a.link, дождаться подсветки этого варианта (он в выпадашке один) и нажать Tab или Enter, а редактор сам вставит развёрнутую конструкцию. Это очень ускоряет работу, хотя поначалу и похоже на волшебство.

Сложно представить реальную работу в VS Code без терминала.

Ситуация

Нужно вызвать терминал, с которым легче искать ошибки в коде (оповещения будут во вкладке Problems), а также работать с Git (распределённая система управления версиями).

Что делать

Нажать Ctrl + ` для Windows или ⌃Ctrl + ` для macOS.

Запоминать горячие клавиши вовсе не сложно, главное — начать их применять. Полные списки сочетаний тут и тут, а сокращений — здесь.

Желаем вам быстрой и приятной работы в VS Code!

Профессия Веб-разработчик

Освойте востребованную профессию с нуля и добавьте более 60 проектов в портфолио. Учитесь онлайн, в удобном вам темпе.

Узнать больше →

Курс с трудоустройством: «Веб-разработчик»
Узнать о курсе

Любую команду в Visual Studio Code можно выполнить через командную строку (Ctrl + Shift + P), но сочетания клавиш помогают сильно экономить время. Достаточно только привыкнуть их использовать.

Для вашего удобства в конце статьи есть шпаргалка со всеми хоткеями.

Прим. пер. Во всех сочетаниях используется английская раскладка.

Открыть настройки пользователя: Ctrl + ,

Время от времени заходить в настройки всё же приходится. Этот хоткей ускоряет процесс.

Показать список горячих клавиш: Ctrl + K   Ctrl + S

Переключиться между средами разработки: Ctrl + R

Этот хоткей открывает список ваших недавних рабочих пространств. Это быстрый способ переключаться между папками и проектами. Обратите внимание, что при переходе сессия терминала закроется (если она была активна).

Глобальный перенос по словам: Alt + Z

Простой и удобный способ сразу увидеть все длинные строки без горизонтальной прокрутки.

Перейти на строку: Ctrl + G

Иногда нужно быстро и часто перескакивать на разные строки в объёмных файлах, а скроллить весь документ неудобно. Этот хоткей как раз для таких целей.

Перейти к файлу: Ctrl + P

Самый быстрый способ переключения между файлами (особенно если они ещё не открыты).

Перейти к следующей ошибке или предупреждению: F8

Отладка одной клавишей во плоти. Ещё можно переходить на предыдущую ошибку или предупреждение, используя Shift + F8.

Переключиться между вкладками: Ctrl + Tab

Быстрый способ переключения между уже открытыми файлами.

Поместить курсор в конец каждой выделенной строки: Shift + Alt + I

Эта возможность удобна для тех случаев, когда нужно выполнить идентичные операции в последовательных строках.

Выделить текущую строку: Ctrl + L

Хоткей используется для быстрого выделения всей строки, на которой установлен курсор.

Выделить все вхождения текущего выделения: Ctrl + Shift + L

Хоткей сэкономит время, потому что теперь не нужно использовать Ctrl + D во всём файле.

Выделить все вхождения текущего слова: Ctrl + F2

Теперь вам не нужно даже выделять конкретное слово — просто поместите на него курсор, нажмите хоткей и одновременно правьте все его вхождения.

Подсказки по параметрам: Ctrl + Shift + Space

Если вы вдруг забыли порядок параметров, а прерываться на документацию нет желания.

Форматировать документ: Shift + Alt + F

Специально для тех, кому лень постоянно придерживаться правил форматирования.

Форматировать выделенную область: Ctrl + K   Ctrl + F

Такой же, как и предыдущий хоткей, но форматируется не весь документ, а только выделенная область.

Перейти к определению: F12

Быстрый способ перейти к определению функции или переменной.

Показать определение: Alt + F12

Сочетание клавиш похоже на прошлое, но в этом случае курсор никуда не перемещается.

Переименовать переменную: F2

Незаменимый хоткей для рефакторинга кода.

Обрезать пробелы в конце: Ctrl + K   Ctrl + X

Чтобы вручную не удалять лишние пробелы в конце строки. Работает при выделении нескольких строк.

Отобразить открытый файл в проводнике: Ctrl + K   R

Если вам нужно что-либо сделать с открытым файлом, поиск которого может занять много времени.

Замена в файлах: Ctrl + Shift + H

Если одного файла вам не достаточно.

Превью Markdown-файла: Ctrl + K   V

Открыть предпросмотр Markdown-файла.

Включить Zen Mode: Ctrl + K   Z

Не позволяйте навязчивым интерфейсам отвлекать вас от программирования. Хоткей поможет сконцентрироваться на коде.

Шпаргалка

Хоткеи для VS Code: гифки с демонстрацией и шпаргалка 23

107К открытий115К показов

Уровень сложностиПростой

Время на прочтение3 мин

Количество просмотров221K

«Поговорим не про Vim», олдам, сеньорам и тру-си-разработчикам на проверку: пользуетесь ли вы такими сочетаниями VS Code? Если же вы только начинаете программировать, влетаете в айти на реактивном самолете курсов по Питону, или просто не знаете ничего про хоткеи VS Code, возможно вам точно пригодится парочка сочетаний :)

Все сочетания описаны для VS Code на Windows
↓ / ↑ / ← / → — стрелки вниз, вниз и т.д.
ЛКМ / ПКМ / СКМ — левая, правая, средняя кнопки мышки соответственно.

  1. Shift + Tab — сместить табуляцию на один шаг влево. Если вы пишете на Python, то табуляция или четыре пробела — ваш неизменный спутник. Но мало кто знает, что достаточно поставить курсор в любое место строки, нажать Shift + Tab и вуаля, вся строка смещается влево на «один таб».

    Shift + Tab

    Shift + Tab
  2. Ctrl + / — закомментировать или раскомментировать строку. VS Code сам разберется, какой язык программирования вы используете, и в начале строки установит или удалит необходимый символ для комментария. Место, где находится курсор на строке неважно.

    Ctrl + /
  3. Shift + Del — удалить строку целиком. Теперь не нужно выделять мышкой всю строку и потом нажимать Backspace. Не нужно выделять всю строку. Правда!

    Shift + Del

    Shift + Del
  4. Alt + ↑ / ↓ — перемещение строки с курсором вверх или вниз. Просто попробуйте и ощутите, насколько это удобно. Знаете шутку «стоит всего один раз зимой надеть подштанники, и ты уже не можешь остановиться»? Так вот стоит только один раз переместить так строку, и вы уже не сможете по-другому!

    Alt + ↑ / ↓

    Alt + ↑ / ↓
  5. Shift + Alt + ↓ / ↑ — дублирование строки с курсором вниз. В зависимости от ↓ или ↑ курсор останется на текущей или новой строке. Теперь можно обойтись без Ctrl + C, хотя нет, нельзя =)

    Alt + ↑ / ↓

    Alt + ↑ / ↓
  6. F2 — переименовать переменную. Прошу заметить, что переименовываются все переменные с таким названием только внутри блока, не внутри всего открытого файла. Часто нужно переименовать переменную, которая уже используется в нескольких местах функции, и тут либо вручную расставлять курсор в нужное место, либо поставить курсор на переменную и нажать F2.

    F2
  7. F12 или Alt + ЛКМ на переменной — перейти к переменной или родительскому классу. Часто рассказывают про PyCharm, будто только он умеет проваливаться в родительские классы, чтобы посмотреть, какие его атрибуты мы можем переопределять, наследуясь от него; но так умеет и VS Code.

    F12 или Alt + ЛКМ
  8. Ctrl + D — выделяет слово, на котором находится курсор. Следующее нажатие на D (удерживая Ctrl) выделить следующее по порядку вниз идентичное значение. Вот пишете вы функцию, и вам нужно выделить ближайшие значения ‘name’. Легко! Выделить все вхождения слова можно вот так — Ctrl + F2. Радует то, что курсор оказывается в конце каждого выделенного значения и сразу можно редактировать!

    Ctrl + D

    Ctrl + D
  9. Ctrl + L — выделяет всю строку. Целиком. Теперь копипастить еще проще, не правда ли? =)

    Ctrl + L

    Ctrl + L
  10. Ctrl + Alt + → — разделить рабочую область и переместить актуальную вкладку вправо. Ctrl + Alt + ← возвращает вкладку назад. Вы не поверите, насколько удобно видеть, например, models.py и views.py рядом.

    Ctrl + Alt + →

    Ctrl + Alt + →

А теперь неочевидные, но потрясающие возможности. Меню → Файл → Настройки → Сочетания клавиш (Ctrl + K + Ctrl + S), в строке поиска вводим необходимый параметр и кликаем по результату мышкой, после нажимаем нужные клавиши для установки пользовательской настройки и наслаждаемся. Команды, которые точно стоит попробовать:

editor.action.jumpToBracket — переход к парной скобке, у меня установлено на Ctrl + Q. Сначала переход к ближайшей скобке, а следующее нажатие перемещает вас к парной скобке и так далее. Часто нам нужно оказаться либо в начале скобок, либо в конце. А кликать мышкой или стрелками не всегда удобно. Теперь достаточно одного нажатия и вы у нужной скобки.

Ctrl + Alt + →

Ctrl + Alt + →

editor.action.selectToBracket — выделить все внутри ближайших скобок и сами скобки, у меня это Ctrl + Shift + Q. Сколько кликов мышкой, сколько ошибок, выделяя внутри скобок мышкой или Shift + стрелки. А теперь можно просто одним нажатием выделить все точно и быстро.

editor.action.selectToBracket

editor.action.selectToBracket

Буду благодарен за любые интересные и полезные хоткеи, пишите в комментариях, что понравилось из моих, и что вы используете сами?

P. S. В комментариях рассказали про логичную, но неочевидную возможность IDE-шек и иже с ними: чтобы вырезать или скопировать строку, необязательно выделять ее целиком, можно просто переместить курсор на неё. ❤️

Cover image for Visual Studio Code Keyboard Shortcuts for Windows

Visual Studio Code is the most popular code editor or IDE (Integrated Development Environment) currently. VS Code is Free, built on open source, easy to use code editor.

Visual Studio Code keyboard shortcuts helps developers in writing code more efficiently and for boosting their working performance.

Shortcut keys are categorized in following categories :-

  • General Shortcuts
  • Basic Editing Shortcuts
  • Navigation Shortcuts
  • Search and replace Shortcuts
  • Multi-cursor and selection Shortcuts
  • Rich languages editing Shortcuts
  • Editor management Shortcuts
  • File management Shortcuts
  • Debug Shortcuts
  • Integrated terminal Shortcuts

Shortcut Key — Description

General Shortcuts

Ctrl+Shift+P, F1Show Command Palette
Ctrl+PQuick Open, Go to File
Ctrl+Shift+NNew window
Ctrl+Shift+WClose window
Ctrl+,User Settings
Ctrl+K Ctrl+SKeyboard Shortcuts

Basic Editing

Ctrl+XCut line
Ctrl+CCopy line
Alt+ ↑ / ↓Move line up/down
Shift+Alt + ↓ / ↑Copy line up/down
Ctrl+Shift+KDelete line
Ctrl+EnterInsert line below
Ctrl+Shift+EnterInsert line above
Ctrl+Shift+\Jump to matching bracket
Ctrl+] / [Indent/outdent line
Home / EndGo to beginning/end of line
Ctrl+HomeGo to beginning of file
Ctrl+EndGo to end of file
Ctrl+↑ / ↓Scroll line up/down
Alt+PgUp / PgDnScroll page up/down
Ctrl+Shift+[Fold (collapse) region
Ctrl+Shift+]Unfold (uncollapse) region
Ctrl+K Ctrl+[Fold (collapse) all subregions
Ctrl+K Ctrl+]Unfold (uncollapse) all subregions
Ctrl+K Ctrl+0Fold (collapse) all regions
Ctrl+K Ctrl+JUnfold (uncollapse) all regions
Ctrl+K Ctrl+CAdd line comment
Ctrl+K Ctrl+URemove line comment
Ctrl+/Toggle line comment
Shift+Alt+AToggle block comment
Alt+ZToggle word wrap

Navigation Shortcuts

Ctrl+TShow all Symbols
Ctrl+GGo to Line
Ctrl+PGo to File
Ctrl+Shift+OGo to Symbol
Ctrl+Shift+MShow Problems panel
F8Go to the next error
Shift+F8Go to previous error
Ctrl+Shift+TabNavigate editor group history
Alt+ ← / →Go back / forward
Ctrl+MToggle Tab moves the focus

Search and replace

Ctrl+FFind
Ctrl+HReplace
F3 / Shift+F3Find next/previous
Alt+EnterSelect all occurences of Find match
Ctrl+DAdd selection to next Find match
Ctrl+K Ctrl+DMove last selection to next Find match
Alt+C / R / WToggle case-sensitive / regex / whole word

Multi-cursor and selection Shortcuts

Alt+ClickInsert cursor
Ctrl+Alt+ ↑ / ↓Insert cursor above / below
Ctrl+UUndo last cursor operation
Shift+Alt+IInsert cursor at end of each line selected
Ctrl+LSelect current line
Ctrl+Shift+LSelect all occurrences of current selection
Ctrl+F2Select all occurrences of current word
Shift+Alt+→Expand selection
Shift+Alt+←Shrink selection
Shift+Alt + (drag mouse)Column (box) selection
Ctrl+Shift+Alt + (arrow key)Column (box) selection
Ctrl+Shift+Alt + PgUp/PgDnColumn (box) selection page up/down

Rich languages editing

Ctrl+SpaceTrigger suggestion
Ctrl+Shift+SpaceTrigger parameter hints
Shift+Alt+FFormat document
Ctrl+K Ctrl+FFormat selection
F12Go to Definition
Alt+F12Peek Definition
Ctrl+K F12Open Definition to the side
Ctrl+.Quick Fix
Shift+F12Show References
F2Rename Symbol
Ctrl+K Ctrl+XTrim trailing whitespace
Ctrl+K MChange file language

Editor management

Ctrl+F4, Ctrl+WClose editor
Ctrl+K FClose folder
Ctrl+\Split editor
Ctrl+ 1 / 2 / 3Focus into 1st, 2nd or 3rd editor group
Ctrl+K Ctrl+ ←/→Focus into previous/next editor group
Ctrl+Shift+PgUp / PgDnMove editor left/right
Ctrl+K ← / →Move active editor group

File management

Ctrl+NNew File
Ctrl+OOpen File…
Ctrl+SSave
Ctrl+Shift+SSave As…
Ctrl+K SSave All
Ctrl+F4Close
Ctrl+K Ctrl+WClose All
Ctrl+Shift+TReopen closed editor
Ctrl+KEnter Keep preview mode editor open
Ctrl+TabOpen next
Ctrl+Shift+TabOpen previous
Ctrl+K PCopy path of active file
Ctrl+K RReveal active file in Explorer
Ctrl+K OShow active file in new window/instance

Debug

F9Toggle breakpoint
F5Start/Continue
Shift+F5Stop
F11 / Shift+F11Step into/out
F10Step over
Ctrl+K Ctrl+IShow hover

Integrated terminal

Ctrl+CCopy selection
Ctrl+VPaste into active terminal
Ctrl+↑ / ↓Scroll up/down
Shift+PgUp / PgDnScroll page up/down
Ctrl+Home / EndScroll to top/bottom

Other operating systems’ keyboard shortcuts and additional
unassigned shortcuts available at Click here

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows server в россии
  • Code 5 отказано в доступе windows 10
  • Kmsauto активатор windows 7 профессиональная
  • Отмена изменений windows 10 при восстановлении системы
  • Активация windows через корпоративный сервер