Как сохранить файл в vs code
Перейти к содержимому

Как сохранить файл в vs code

  • автор:

Visual Studio Code – редактор кода для Linux, OS X и Windows

За свою долгую историю существования Microsoft выпустил немало инструментов разработки. Но так уж сложилось что на слуху у всех только лишь Visual Studio – большая и мощная IDE «комбайн» предназначенная для всего и вся. Развивается этот продукт уже более двух десятков лет и вобрал в себя самые разные функции. Многим этот инструментарий нравится и иногда даже задавали вопрос – будет ли перенесен Visual Studio на другие платформы. На что чаще всего получали ответ нет. Наверное, понятно почему, в целом такое портирование будет дорогим и неоправданно сложным, уж очень много всего в этой IDE завязано на Windows.

И вот, этой весной для многих неожиданностью было то что Microsoft представил новый продукт под названием Visual Studio Code, да еще и работающий сразу на трех платформах, Linux, OS X и Windows. Не замахиваясь на все функции полноценной IDE, внутри Microsoft решили переосмыслить подход, по которому строится основной инструментарий программиста и начали с самого главного – редактора кода. Visual Studio Code это именно редактор, но при этом обладающий функциями IDE, полагающийся на расширения.

Уже сейчас вы можете использовать Visual Studio Code для создания веб-проектов ASP.NET 5 или Node.js (в чем-то даже удобнее чем в «взрослой» Visual Studio), использовать различные языки, такие как JavaScript, TypeScript, C#, работать с пакетными менеджерами npm, скаффолдингом yeoman и даже осуществлять отладку. Плюсом ко всему будет отличный «интеллисенс», поддержка сниппетов кода, рефакторинг, навигация, многооконность, поддержка git и многое другое.

Установка Visual Studio Code
Mac OS X
Linux

Совет: если вы хотите чтобы Visual Studio Code стартовал из терминала добавьте на него ссылку

Windows
Дополнительные инструменты

Без инструментария Visual Studio Code годится разве что для простого редактирования файлов, для полноценной работы понадобится сопутствующий инструментарий, который зависит от ваших целей и задач:

    — гибкий фреймворк создания современных веб-приложений – платформа для создания масштабируемых сетевых приложений – система контроля версий – инструмент «скаффолдинга» примерно тоже самое что и File | New Project в VS — yeoman генератор для ASP.NET 5 приложений, выполните npm install -g generator-aspnet для установки — yeoman генератор для быстрого создания AngularJS приложений, выполните npm install -g generator-hottowel для установки – фреймворк для Node приложений, использует «движок» шаблонов Jade – инструментарий создания «тасков» для выполнения сопутствующих сборке проекта задач – фреймворк создания модульных тестов на JavaScript/Node – клиентский пакетный менеджер – язык TypeScript, добавляет модульность, классы и прочие приятные вещи в ваш JavaScript код – определения TypeScript для популярных JavaScript библиотек, включают поддержку IntelliSense вVS Code
Начало работы

Чтобы попробовать в деле VS Code, проще всего создать веб-проект Node. Для этого установите Node на свой компьютер (ссылка выше) и выполните следующие команды:

В текущем каталоге будет создан проект, который можно будет открыть в Visual Studio Code. Для того чтобы проверить, что все работает как надо, выполните команду npm start и запустите браузер по адресу http://localhost:3000.
После всех этих действий просто запустите VS Code в папке с проектом

Если вы хотите попробовать возможности VS Code на примере ASP.NET 5 то можете воспользоваться инструкцией по адресу https://code.visualstudio.com/Docs/ASPnet5.

Базовые возможности Visual Studio Code

Как и многие редакторы кода, VS Code использует распространенную схему расположения основных элементов – слева обозреватель файлов, справа редактор кода. В дополнение к этому есть специфичные элементы, обеспечивающие навигацию и выполнение специальных команд.

Файлы, папки, и проекты

VS Code работает с файлами и папками в которых находятся проекты. В простейшем случае вы можете открыть файл на редактирование просто выполнив команду ./code index.html. Более интересным случаем является открытие папки. VS Code сам определяет тип проекта в зависимости от содержимого папки. Например, если в папке находятся файлы package.json, project.json, tsconfig.json или файлы .sln и .proj для Visual Studio ASP.NET 5.0 то VS Code включает много новых функций которые обеспечивают IntelliSence, подсказки, навигацию по коду, выполнение команд и многое другое.

Расположение основных элементов

VS Code обладает интуитивно понятной и простой схемой расположения основных элементов. Интерфейс разделен на четыре основных блока, это:

  1. Редактор, основной блок в котором осуществляется изменение содержимого открытого файла
  2. Сайдбар, с помощью которого можно увидеть различные представления файлов проекта
  3. Статусбар, показывающий текущий статус различных операций
  4. Вьюбар, позволяющий переключаться между режимами сайдбара и индицирующий с помощью иконок различную информацию, например количество исходящих git изменений

Редактор VS Code может открыть для редактирования на экране до трех файлов одновременно, располагая их друг за другом справа. Открыть дополнительные редакторы можно различными способами:
Ctrl (Mac: Cmd) и кликнуть на файле в обозревателе
Ctrl+\ для того чтобы разделить активный текущий редактор на два
Open to the Side в контекстном меню файла в обозревателе

Палитра команд

Самым главным инструментом взаимодействия с редактором в VS Code является палитра команд. Вызвать ее можно через клавиатуру, нажав на комбинацию Ctrl+Shift+P. Множество команд перечисленных в палитре тоже привязаны к клавишам.

Введите в строку команды знак вопроса? и тогда вы получите перечень команд которые работают в текущем контексте:

Некоторые часто используемые команды:

  • Ctrl+P навигация к файлу или символу по набранной строке
  • Ctrl+Tab циклично открывает последние отредактированные файлы
  • Ctrl+Shift+P выводит список команд редактора
  • Ctrl+Shift+O навигация к некоторому символу в файле
  • Ctrl+G навигация к строке в файле
  • Ctrl+Tab выводит список всех файлов которые были открыты от момента запуска VS Code, удерживайте Ctrl и нажимайте Tab до тех пор пока не выберите нужный файл
  • Alt+Left и Alt+Right навигация по ранее редактированным файлам и строкам назад и вперед
Обозреватель

Обозреватель предназначен для открытия и управления файлами находящимися в папке вашего проекта. Вы можете осуществлять множество привычных операций по созданию, изменению имени, удалению файлов и папок, и их перемещению.

Файлы, которые вы редактировали или открывали двойным щелчком в обозревателе, помещаются в верхнюю часть обозревателя и получают статус Working files:

Автосохранение

По умолчанию, VS Code работает в режиме явного сохранения, которое вы можете выполнить, нажав на комбинацию Ctrl+S. Этот режим совместим с большинством инструментов следящих за статусом файлов (например bower). Можно включить и режим автоматического сохранения (Auto Save), нажав Ctrl+Shift+P и набрать auto.

Поиск

Нажимите Ctrl+Shift+F и введите интересующую вас фразу. Результаты поиска будут сгруппированы, в дополнение вы можете развернуть узел группы чтобы посмотреть множественные вхождения. В строке поиска поддерживаются регулярные выражения.

Более детальный поиск может быть осуществлен с помощью команды Ctrl+Shift+J. Введите в дополнительные поля критерии поиска.

Возможности редактора
Подсказки IntelliSence

Где бы вы не находились в вашем коде, нажав на Ctrl+Space будет выведено окно подсказки IntelliSence. При наборе кода редактор будет показывать его автоматически.

Подсказки параметров

Для перегруженных функций вы можете листать варианты реализации используя клавиши Up и Down.

Сниппеты кода

VS Code поддерживает аббревиатуры Emmet. Вы можете использовать их при редактировании файлов HTML, Razor, CSS, Less, Sass, XML или Jade. Основной перечень аббревиатур можно посмотреть по адресу http://docs.emmet.io/cheat-sheet/.

Переход к определению символа

Нажав на F12 вы перейдете к определению символа. Если нажать Ctrl и провести курсором по символу вы увидите определение в дополнительном окне.

Переход к методу или переменной

Нажав на Ctrl+Shift+O вы откроете перечень методов в файле, в дополнение вы можете нажать двоеточие: и методы будут сгруппированы по типу. Нажав на Up и Down выберите нужный метод и курсор в редакторе перейдет на строку где находится выбранный метод.

Для языков C# и TypeScript вы можете использовать комбинацию Ctrl+T и набрать нужный метод или переменную, при этом будет осуществлен поиск по всем файлам в проекте.

Просмотр определения символа

Если вам необходимо быстро посмотреть на определение символа или на референсы, для того чтобы вспомнить детали реализации или использования, можно использовать поиск или переход к определению символов, что не всегда удобно так как переключает контекст.
В этом случае можно воспользоваться командами Reference Search (Shift+F12) или Peek Definition (Alt+F12) и результаты поиска будут отображаться в инлайн окошке:

Переименование методов и переменных

Нажав F2 вы можете изменить имя метода или переменной. Стандартная операция рефакторинга, но пока она поддерживается только для языков C# и TypeScript.

Отладка

В VS Code входит отладчик. Его возможности пока ограничены, и работают не на всех платформах. Тем не менее, вы можете использовать отладчик для языков JavaScript и TypeScript на всех платформах, а для C# и F# на платформах OS X и Linux.

Для того чтобы запустить отладку проекта Node, достаточно нажать на иконку бага в Activity Bar. После генерации файла launch.json запустится отладчик. Для проектов Node VS Code автоматически определяет каталог ./bin/www.

Сохраните конфигурационный файл и выберите пункт Launch в меню, установите точку останова и нажмите F5 для старта отладки.

Отладчик позволяет просматривать значения текущих переменных:

Более подробно о возможностях отладчика можно почитать по адресу https://code.visualstudio.com/Docs/debugging в том числе о том как сконфигурировать Mono для отладки C# и F# кода на платформах OS X и Linux.

Контроль версий

VS Code интегрирован с системой контроля версий git, и поддерживает большинство команд. В версии 0.5 был зафиксирован ряд ошибок связанных с интеграцией. Поддерживаются локальные и удаленные репозитарии.

Конфликты

VS Code позволяет осуществлять слияния и разрешение конфликтов при работе с системой контроля версий:

How can we save all files in (VSCode) like we do in Visual Studio

How can we save all the files in Visual Studio Code like we do in Visual Studio by pressing Ctrl + Shift + S ?

rashfmnb's user avatar

16 Answers 16

It doesn’t look like VS Code has a built-in single-press keyboard shortcut to save all open files on Windows.

The simplest way would be to use the menu accelerators: ALT + F , followed by ALT + L .

Alternatively, you can change the key binding by editing the keyboard preferences:

VS Code with File menu open, Preferences, Keyboard Shortcuts highlighted

Add the binding to the right half of the screen, then restart VS Code:

enter image description here

jessehouwing's user avatar

Ctrl + K S // Windows

Ctrl + Alt + S // Linux

RBT's user avatar

TL;DR: You can press Ctrl + K , S to save all open files with a little caveat associated with it.

Detailed Explanation: Be careful about keyboard shortcut combination shown in any menu description. There is a little caveat to it. The combination Ctrl + K S shown as menu description text (Refer screenshot below) gives an impression that we have to press Ctrl key, keep the Ctrl key pressed and then press the keys K and S one by one in succession. This is not the case.

enter image description here

After having pressed Ctrl + K combination, you need to release both Ctrl and K keys and then press S key separately.

For cases where Ctrl key has to be kept pressed continuously, you’ll notice that modifier keys will appear twice in the menu description text. For example, to open a new folder, the menu item’s text shows Ctrl + K Ctrl + O . In this case Ctrl modifier key is present twice (refer screenshot below).

Как сохранить файл в vs code

enter image description here

enter image description here

enter image description here

  1. нажмите клавишу Ctrl + K.
  2. отпустите клавиши Ctrl и K.
  3. нажмите клавишу S.

Как мы можем сохранить все файлы в (VSCode), как в Visual Studio

введите описание изображения здесь

введите описание изображения здесь

введите описание изображения здесь

  1. Нажмите Ctrl + K.
  2. Отпустите обе клавиши Ctrl и K.
  3. Нажмите клавишу S.

Сообщение о нижнем статусе VSCode после нажатия <kbd> Ctrl </kbd> + <kbd> k </kbd>.

Basic Editing

Visual Studio Code is an editor first and foremost, and includes the features you need for highly productive source code editing. This topic takes you through the basics of the editor and helps you get moving with your code.

Keyboard shortcuts

Being able to keep your hands on the keyboard when writing code is crucial for high productivity. VS Code has a rich set of default keyboard shortcuts as well as allowing you to customize them.

    — Learn the most commonly used and popular keyboard shortcuts by downloading the reference sheet. — Use the keyboard shortcuts of your old editor (such as Sublime Text, Atom, and Vim) in VS Code by installing a Keymap extension. — Change the default keyboard shortcuts to fit your style.

Multiple selections (multi-cursor)

VS Code supports multiple cursors for fast simultaneous edits. You can add secondary cursors (rendered thinner) with Alt+Click . Each cursor operates independently based on the context it sits in. A common way to add more cursors is with ⌥⌘↓ (Windows Ctrl+Alt+Down , Linux Shift+Alt+Down ) or ⌥⌘↑ (Windows Ctrl+Alt+Up , Linux Shift+Alt+Up ) that insert cursors below or above.

Note: Your graphics card driver (for example NVIDIA) might overwrite these default shortcuts.

⌘D (Windows, Linux Ctrl+D ) selects the word at the cursor, or the next occurrence of the current selection.

Tip: You can also add more cursors with ⇧⌘L (Windows, Linux Ctrl+Shift+L ) , which will add a selection at each occurrence of the current selected text.

Multi-cursor modifier

If you’d like to change the modifier key for applying multiple cursors to Cmd+Click on macOS and Ctrl+Click on Windows and Linux, you can do so with the editor.multiCursorModifier setting. This lets users coming from other editors such as Sublime Text or Atom continue to use the keyboard modifier they are familiar with.

The setting can be set to:

  • ctrlCmd — Maps to Ctrl on Windows and Cmd on macOS.
  • alt — The existing default Alt .

There’s also a menu item Use Ctrl+Click for Multi-Cursor in the Selection menu to quickly toggle this setting.

The Go to Definition and Open Link gestures will also respect this setting and adapt such that they do not conflict. For example, when the setting is ctrlCmd , multiple cursors can be added with Ctrl/Cmd+Click , and opening links or going to definition can be invoked with Alt+Click .

Shrink/expand selection

Quickly shrink or expand the current selection. Trigger it with ⌃⇧⌘← (Windows, Linux Shift+Alt+Left ) and ⌃⇧⌘→ (Windows, Linux Shift+Alt+Right ) .

Here’s an example of expanding the selection with ⌃⇧⌘→ (Windows, Linux Shift+Alt+Right ) :

Column (box) selection

Place the cursor in one corner and then hold Shift+Alt while dragging to the opposite corner:

Note: This changes to Shift+Ctrl/Cmd when using Ctrl/Cmd as multi-cursor modifier.

There are also default key bindings for column selection on macOS and Windows, but not on Linux.

Key Command Command ID
⇧↓ (Windows Ctrl+Shift+Alt+Down , Linux ) Column Select Down cursorColumnSelectDown
⇧↑ (Windows Ctrl+Shift+Alt+Up , Linux ) Column Select Up cursorColumnSelectUp
⇧← (Windows Ctrl+Shift+Alt+Left , Linux ) Column Select Left cursorColumnSelectLeft
⇧→ (Windows Ctrl+Shift+Alt+Right , Linux ) Column Select Right cursorColumnSelectRight
⇧PageDown (Windows Ctrl+Shift+Alt+PageDown , Linux ) Column Select Page Down cursorColumnSelectPageDown
⇧PageUp (Windows Ctrl+Shift+Alt+PageUp , Linux ) Column Select Page Up cursorColumnSelectPageUp

You can edit your keybindings.json to bind them to something more familiar if you want.

Column Selection mode

The user setting Editor: Column Selection controls this feature. Once this mode is entered, as indicated in the Status bar, the mouse gestures and the arrow keys will create a column selection by default. This global toggle is also accessible via the Selection > Column Selection Mode menu item. In addition, one can also disable Column Selection mode from the Status bar.

Save / Auto Save

By default, VS Code requires an explicit action to save your changes to disk, ⌘S (Windows, Linux Ctrl+S ) .

However, it’s easy to turn on Auto Save , which will save your changes after a configured delay or when focus leaves the editor. With this option turned on, there is no need to explicitly save the file. The easiest way to turn on Auto Save is with the File > Auto Save toggle that turns on and off save after a delay.

For more control over Auto Save , open User or Workspace settings and find the associated settings:

  • files.autoSave : Can have the values:
    • off — to disable auto save.
    • afterDelay — to save files after a configured delay (default 1000 ms).
    • onFocusChange — to save files when focus moves out of the editor of the dirty file.
    • onWindowChange — to save files when the focus moves out of the VS Code window.

    Hot Exit

    VS Code will remember unsaved changes to files when you exit by default. Hot exit is triggered when the application is closed via File > Exit (Code > Quit on macOS) or when the last window is closed.

    You can configure hot exit by setting files.hotExit to the following values:

    • «off» : Disable hot exit.
    • «onExit» : Hot exit will be triggered when the application is closed, that is when the last window is closed on Windows/Linux or when the workbench.action.quit command is triggered (from the Command Palette, keyboard shortcut or menu). All windows without folders opened will be restored upon next launch.
    • «onExitAndWindowClose» : Hot exit will be triggered when the application is closed, that is when the last window is closed on Windows/Linux or when the workbench.action.quit command is triggered (from the Command Palette, keyboard shortcut or menu), and also for any window with a folder opened regardless of whether it is the last window. All windows without folders opened will be restored upon next launch. To restore folder windows as they were before shutdown, set window.restoreWindows to all .

    If something happens to go wrong with hot exit, all backups are stored in the following folders for standard install locations:

    • Windows %APPDATA%\Code\Backups
    • macOS $HOME/Library/Application Support/Code/Backups
    • Linux $HOME/.config/Code/Backups

    Find and Replace

    VS Code allows you to quickly find text and replace in the currently opened file. Press ⌘F (Windows, Linux Ctrl+F ) to open the Find Widget in the editor, search results will be highlighted in the editor, overview ruler and minimap.

    If there are more than one matched result in the current opened file, you can press Enter and ⇧Enter (Windows, Linux Shift+Enter ) to navigate to next or previous result when the find input box is focused.

    Seed Search String From Selection

    When the Find Widget is opened, it will automatically populate the selected text in the editor into the find input box. If the selection is empty, the word under the cursor will be inserted into the input box instead.

    This feature can be turned off by setting editor.find.seedSearchStringFromSelection to false .

    Find In Selection

    By default, the find operations are run on the entire file in the editor. It can also be run on selected text. You can turn this feature on by clicking the hamburger icon on the Find Widget.

    If you want it to be the default behavior of the Find Widget, you can set editor.find.autoFindInSelection to always , or to multiline , if you want it to be run on selected text only when multiple lines of content are selected.

    Advanced find and replace options

    In addition to find and replace with plain text, the Find Widget also has three advanced search options:

    • Match Case
    • Match Whole Word
    • Regular Expression

    The replace input box support case preserving, you can turn it on by clicking the Preserve Case (AB) button.

    Multiline support and Find Widget resizing

    You can search multiple line text by pasting the text into the Find input box and Replace input box. Pressing Ctrl+Enter inserts a new line in the input box.

    While searching long text, the default size of Find Widget might be too small. You can drag the left sash to enlarge the Find Widget or double click the left sash to maximize it or shrink it to its default size.

    Search across files

    VS Code allows you to quickly search over all files in the currently opened folder. Press ⇧⌘F (Windows, Linux Ctrl+Shift+F ) and enter your search term. Search results are grouped into files containing the search term, with an indication of the hits in each file and its location. Expand a file to see a preview of all of the hits within that file. Then single-click on one of the hits to view it in the editor.

    A simple text search across files

    Tip: We support regular expression searching in the search box, too.

    You can configure advanced search options by clicking the ellipsis (Toggle Search Details) below the search box on the right (or press ⇧⌘J (Windows, Linux Ctrl+Shift+J ) ). This will show additional fields to configure the search.

    Advanced search options

    Advanced search options

    In the two input boxes below the search box, you can enter patterns to include or exclude from the search. If you enter example , that will match every folder and file named example in the workspace. If you enter ./example , that will match the folder example/ at the top level of your workspace. Use , to separate multiple patterns. Paths must use forward slashes. You can also use glob syntax:

    • * to match zero or more characters in a path segment
    • ? to match on one character in a path segment
    • ** to match any number of path segments, including none
    • to group conditions (for example matches all HTML and text files)
    • [] to declare a range of characters to match ( example.[0-9] to match on example.0 , example.1 , …)
    • [. ] to negate a range of characters to match ( example.[!0-9] to match on example.a , example.b , but not example.0 )

    VS Code excludes some folders by default to reduce the number of search results that you are not interested in (for example: node_modules ). Open settings to change these rules under the files.exclude and search.exclude section.

    Note that glob patterns in the search view work differently than in settings such as files.exclude and search.exclude . In the settings, you must use **/example to match a folder named example in subfolder folder1/example in your workspace. In the search view, the ** prefix is assumed. The glob patterns in these settings are always evaluated relative to the path of the workspace folder.

    Also note the Use Exclude Settings and Ignore Files toggle button in the files to exclude box. The toggle determines whether to exclude files that are ignored by your .gitignore files and/or matched by your files.exclude and search.exclude settings.

    Tip: From the Explorer, you can right-click on a folder and select Find in Folder to search inside a folder only.

    Search and replace

    You can also Search and Replace across files. Expand the Search widget to display the Replace text box.

    search and replace

    When you type text into the Replace text box, you will see a diff display of the pending changes. You can replace across all files from the Replace text box, replace all in one file or replace a single change.

    search and replace diff view

    Tip: You can quickly reuse a previous search term by using ↓ (Windows, Linux Down ) and ↑ (Windows, Linux Up ) to navigate through your search term history.

    Case changing in regex replace

    VS Code supports changing the case of regex matching groups while doing Search and Replace in the editor or globally. This is done with the modifiers \u\U\l\L , where \u and \l will upper/lowercase a single character, and \U and \L will upper/lowercase the rest of the matching group.

    The modifiers can also be stacked — for example, \u\u\u$1 will uppercase the first three characters of the group, or \l\U$1 will lowercase the first character, and uppercase the rest. The capture group is referenced by $n in the replacement string, where n is the order of the capture group.

    Search Editor

    Search Editors let you view workspace search results in a full-sized editor, complete with syntax highlighting and optional lines of surrounding context.

    Below is a search for the word ‘SearchEditor’ with two lines of text before and after the match for context:

    Search Editor overview

    The Open Search Editor command opens an existing Search Editor if one exists, or to otherwise create a new one. The New Search Editor command will always create a new Search Editor.

    In the Search Editor, results can be navigated to using Go to Definition actions, such as F12 to open the source location in the current editor group, or ⌘K F12 (Windows, Linux Ctrl+K F12 ) to open the location in an editor to the side. Additionally, double-clicking can optionally open the source location, configurable with the search.searchEditor.doubleClickBehaviour setting.

    You can also use the Open New Search Editor button at the top of the Search view, and can copy your existing results from a Search view over to a Search Editor with the Open in editor link at the top of the results tree, or the Search Editor: Open Results in Editor command.

    The Search Editor above was opened by selecting the Open New Search Editor button (third button) on the top of the Search view.

    Search Editor commands and arguments
    • search.action.openNewEditor — Opens the Search Editor in a new tab.
    • search.action.openInEditor — Copy the current Search results into a new Search Editor.
    • search.action.openNewEditorToSide — Opens the Search Editor in a new window next to the window you currently have opened.

    There are two arguments that you can pass to the Search Editor commands ( search.action.openNewEditor , search.action.openNewEditorToSide ) to allow keybindings to configure how a new Search Editor should behave:

    • triggerSearch — Whether a search be automatically run when a Search Editor is opened. Default is true.
    • focusResults — Whether to put focus in the results of a search or the query input. Default is true.

    For example, the following keybinding runs the search when the Search Editor is opened but leaves the focus in the search query control.

    Search Editor context default

    The search.searchEditor.defaultNumberOfContextLines setting has a default value of 1, meaning one context line will be shown before and after each result line in the Search Editor.

    Reuse last Search Editor configuration

    The search.searchEditor.reusePriorSearchConfiguration setting (default is false ) lets you reuse the last active Search Editor’s configuration when creating a new Search Editor.

    IntelliSense

    We’ll always offer word completion, but for the rich languages, such as JavaScript, JSON, HTML, CSS, SCSS, Less, C# and TypeScript, we offer a true IntelliSense experience. If a language service knows possible completions, the IntelliSense suggestions will pop up as you type. You can always manually trigger it with ⌃Space (Windows, Linux Ctrl+Space ) . By default, Tab or Enter are the accept keyboard triggers but you can also customize these key bindings.

    Tip: The suggestions filtering supports CamelCase so you can type the letters which are upper cased in a method name to limit the suggestions. For example, «cra» will quickly bring up «createApplication».

    Tip: IntelliSense suggestions can be configured via the editor.quickSuggestions and editor.suggestOnTriggerCharacters settings.

    JavaScript and TypeScript developers can take advantage of the npmjs type declaration (typings) file repository to get IntelliSense for common JavaScript libraries (Node.js, React, Angular). You can find a good explanation on using type declaration files in the JavaScript language topic and the Node.js tutorial.

    Formatting

    VS Code has great support for source code formatting. The editor has two explicit format actions:

    • Format Document ( ⇧⌥F (Windows Shift+Alt+F , Linux Ctrl+Shift+I ) ) — Format the entire active file.
    • Format Selection ( ⌘K ⌘F (Windows, Linux Ctrl+K Ctrl+F ) ) — Format the selected text.

    You can invoke these from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or the editor context menu.

    VS Code has default formatters for JavaScript, TypeScript, JSON, and HTML. Each language has specific formatting options (for example, html.format.indentInnerHtml ) which you can tune to your preference in your user or workspace settings. You can also disable the default language formatter if you have another extension installed that provides formatting for the same language.

    Along with manually invoking code formatting, you can also trigger formatting based on user gestures such as typing, saving or pasting. These are off by default but you can enable these behaviors through the following settings:

    • editor.formatOnType — Format the line after typing.
    • editor.formatOnSave — Format a file on save.
    • editor.formatOnPaste — Format the pasted content.

    Note: Not all formatters support format on paste as to do so they must support formatting a selection or range of text.

    In addition to the default formatters, you can find extensions on the Marketplace to support other languages or formatting tools. There is a Formatters category so you can easily search and find formatting extensions. In the Extensions view search box, type ‘formatters’ or ‘category:formatters’ to see a filtered list of extensions within VS Code.

    Folding

    You can fold regions of source code using the folding icons on the gutter between line numbers and line start. Move the mouse over the gutter and click to fold and unfold regions. Use Shift + Click on the folding icon to fold or unfold the region and all regions inside.

    Folding

    You can also use the following actions:

    • Fold ( ⌥⌘[ (Windows, Linux Ctrl+Shift+[ ) ) folds the innermost uncollapsed region at the cursor.
    • Unfold ( ⌥⌘] (Windows, Linux Ctrl+Shift+] ) ) unfolds the collapsed region at the cursor.
    • Toggle Fold ( ⌘K ⌘L (Windows, Linux Ctrl+K Ctrl+L ) ) folds or unfolds the region at the cursor.
    • Fold Recursively ( ⌘K ⌘[ (Windows, Linux Ctrl+K Ctrl+[ ) ) folds the innermost uncollapsed region at the cursor and all regions inside that region.
    • Unfold Recursively ( ⌘K ⌘] (Windows, Linux Ctrl+K Ctrl+] ) ) unfolds the region at the cursor and all regions inside that region.
    • Fold All ( ⌘K ⌘0 (Windows, Linux Ctrl+K Ctrl+0 ) ) folds all regions in the editor.
    • Unfold All ( ⌘K ⌘J (Windows, Linux Ctrl+K Ctrl+J ) ) unfolds all regions in the editor.
    • Fold Level X ( ⌘K ⌘2 (Windows, Linux Ctrl+K Ctrl+2 ) for level 2) folds all regions of level X, except the region at the current cursor position.
    • Fold All Block Comments ( ⌘K ⌘/ (Windows, Linux Ctrl+K Ctrl+/ ) ) folds all regions that start with a block comment token.

    Folding regions are by default evaluated based on the indentation of lines. A folding region starts when a line has a smaller indent than one or more following lines, and ends when there is a line with the same or smaller indent.

    Since the 1.22 release, folding regions can also be computed based on syntax tokens of the editor’s configured language. The following languages already provide syntax aware folding: Markdown, HTML, CSS, LESS, SCSS, and JSON.

    If you prefer to switch back to indentation-based folding for one (or all) of the languages above, use:

    Regions can also be defined by markers defined by each language. The following languages currently have markers defined:

    Language Start region End region
    Bat ::#region or REM #region ::#endregion or REM #endregion
    C# #region #endregion
    C/C++ #pragma region #pragma endregion
    CSS/Less/SCSS /*#region*/ /*#endregion*/
    Coffeescript #region #endregion
    F# //#region or (#_region) //#endregion or (#_endregion)
    Java //#region or //<editor-fold> // #endregion or //</editor-fold>
    Markdown <!— #region —> <!— #endregion —>
    Perl5 #region or =pod #endregion or =cut
    PHP #region #endregion
    PowerShell #region #endregion
    Python #region or # region #endregion or # endregion
    TypeScript/JavaScript //#region //#endregion
    Visual Basic #Region #End Region

    To fold and unfold only the regions defined by markers use:

    • Fold Marker Regions ( ⌘K ⌘8 (Windows, Linux Ctrl+K Ctrl+8 ) ) folds all marker regions.
    • Unfold Marker Regions ( ⌘K ⌘9 (Windows, Linux Ctrl+K Ctrl+9 ) ) unfolds all marker regions.

    Indentation

    VS Code lets you control text indentation and whether you’d like to use spaces or tab stops. By default, VS Code inserts spaces and uses 4 spaces per Tab key. If you’d like to use another default, you can modify the editor.insertSpaces and editor.tabSize settings.

    Auto-detection

    VS Code analyzes your open file and determines the indentation used in the document. The auto-detected indentation overrides your default indentation settings. The detected setting is displayed on the right side of the Status Bar:

    auto detect indentation

    You can click on the Status Bar indentation display to bring up a dropdown with indentation commands allowing you to change the default settings for the open file or convert between tab stops and spaces.

    indentation commands

    Note: VS Code auto-detection checks for indentations of 2, 4, 6 or 8 spaces. If your file uses a different number of spaces, the indentation may not be correctly detected. For example, if your convention is to indent with 3 spaces, you may want to turn off editor.detectIndentation and explicitly set the tab size to 3.

    File encoding support

    Set the file encoding globally or per workspace by using the files.encoding setting in User Settings or Workspace Settings.

    files.encoding setting

    You can view the file encoding in the status bar.

    Encoding in status bar

    Click on the encoding button in the status bar to reopen or save the active file with a different encoding.

    Reopen or save with a different encoding

    Then choose an encoding.

    Select an encoding

    Next steps

    You’ve covered the basic user interface — there is a lot more to VS Code. Read on to find out about:

      — Watch a tutorial on the basics of VS Code. — Learn how to configure VS Code to your preferences through user and workspace settings. — Peek and Goto Definition, and more. — Learn about the integrated terminal for quickly performing command-line tasks from within VS Code. — VS Code brings smart code completions. — This is where VS Code really shines.

    Common questions

    Is it possible to globally search and replace?

    Yes, expand the Search view text box to include a replace text field. You can search and replace across all the files in your workspace. Note that if you did not open VS Code on a folder, the search will only run on the currently open files.

    global search and replace

    How do I turn on word wrap?

    You can control word wrap through the editor.wordWrap setting. By default, editor.wordWrap is off but if you set to it to on , text will wrap on the editor’s viewport width.

    You can toggle word wrap for the VS Code session with ⌥Z (Windows, Linux Alt+Z ) .

    Как мы можем сохранить все файлы в (VSCode), как в Visual Studio

    Как мы можем сохранить все файлы в Visual Studio Code, как мы это делаем в Visual Studio, нажав Ctrl + Shift + S ?

    7 ответов

    Не похоже, что к нему привязан ярлык.

    Самый простой способ — использовать ускорители меню: ALT + f , за которым следует ALT + l .

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

    enter image description here

    Добавьте привязку к правой половине экрана и перезапустите Code:

    enter image description here

    Поддерживается в последних версиях Моя версия: 1.39.1

    Этот keybindings.json переключает сочетания клавиш Save All и Save так, чтобы Cmd + S был привязан к Save All :

    Для пользователей Windows сочетание клавиш отображается как 11-й параметр в меню «Файл» как:

    Отображаемое сочетание клавиш соответствует следующему:

    Нажмите Ctrl + k

    Отпустите клавиши Ctrl и k .

    Обратите внимание, что в нижней части окна отобразится сообщение с запросом на второй ключ, например:

    VSCode bottom status message after pressing <kbd>Ctrl</kbd> + <kbd>k</kbd>.

    1. Нажмите s .

    Это применимо к другой команде «Закрыть рабочее пространство», которую можно найти в меню «Файл» (вместо нажатия s вы нажимаете f ).

    Для пользователя Windows — код Visual Studio имеет Ctrl + K, S

    1. Нажмите Ctrl + K.
    2. Отпустите обе клавиши Ctrl и K.
    3. Нажмите кнопку S.

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

    В коде Visual Studio с сегодняшнего дня вы можете нажать Ctrl + K + S , чтобы сохранить все несохраненные файлы, открытые в данный момент в вашем редакторе.

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

    Здесь следует отметить трюк: комбинация клавиш Ctrl + K S , отображаемая вместе с текстом пункта меню, создает впечатление, что вы должны нажать Ctrl , удерживайте нажатой клавишу Ctrl и затем быстро последовательно нажимайте клавиши K и S . Это не случай.

    enter image description here

    После нажатия комбинации Ctrl + K отпустите обе клавиши Ctrl и K , а затем нажмите S ключ отдельно. В случаях, когда клавишу Ctrl необходимо удерживать нажатой постоянно, она будет отображаться, например, как [ Ctrl + K Ctrl + O ] (для открытия новой папки) в тексте пункта меню.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *