Перейти к содержимому

Как открыть терминал в вс код

  • автор:

Интегрированный терминал в Visual Studio для Mac

Visual Studio для Mac планируется выйти на пенсию 31 августа 2024 года в соответствии с современной политикой жизненного цикла Майкрософт. Хотя вы можете продолжать работать с Visual Studio для Mac, есть несколько других вариантов для разработчиков на Mac, таких как предварительная версия нового расширения комплекта разработки C# для VS Code.

Вы можете открыть окно встроенного терминала в Visual Studio для Mac из корня вашего решения. Этот терминал может использоваться в различных ситуациях, в том числе для выполнения задач интерфейсной части (например, npm, ng или vue), управления контейнерами, запуска расширенных команд git, выполнения команд Entity Framework, просмотра выходных данных интерфейса командной строки dotnet, добавления пакетов NuGet и т. д.

Открыть терминал можно следующими способами:

  • Используйте сочетание клавиш CTRL + `, чтобы отобразить или скрыть окно терминала.
  • Используйте команду меню Вид>Терминал.
  • Используйте команду терминал из панели поиска.

Screenshot showing the Visual Studio for Mac integrated terminal immediately after being launched.

По умолчанию при запуске терминала происходит следующее:

  • В качестве рабочего каталога устанавливается путь к текущему решению.
  • Загружается установленная по умолчанию системная оболочка.

Search

Чтобы выполнить поиск содержимого в окне терминала, воспользуйтесь командой меню Поиск > Найти….

Search experience in the Visual Studio for Mac Integrated Terminal

Сочетания клавиш для терминала

Команды Сочетания клавиш
Отображение или скрытие окна терминала CTRL + `
Создание нового экземпляра терминала CTRL+’
Прокрутка страницы вверх PageUp
Прокрутка страницы вниз PageDown
Циклический перебор ранее выполненных команд ^, ^ ,
Увеличение размера шрифта ⌘+
Уменьшение размера шрифта ⌘-

Несколько экземпляров

Множество экземпляров терминала могут в любое время работать одновременно. Чтобы создать новый экземпляр, воспользуйтесь сочетанием клавиш CTRL + ‘. Для переключения между экземплярами можно выбрать нужную вкладку или нажать клавиши CTRL + TAB и воспользоваться средством выбора окон.

Multiple terminal instances in Visual Studio for Mac

Настройка окна терминала

Настройка шрифта терминала

Вы можете изменять Семейство, Гарнитуру и Размер шрифта, используемого для содержимого окна терминала, в разделе Параметры…>Среда>Шрифты. По умолчанию будет использоваться тот же шрифт, что и для содержимого окна вывода, то есть Menlo (обычный) с размером 11. При желании вы можете установить любой шрифт независимо от используемого в Текстовом редакторе.

Screenshot showing customizing the font settings for the integrated terminal.

Использование настроек системного терминала

Для встроенного терминала используются те же параметры по умолчанию и конфигурации, что и для системного терминала macOS. Это значит, что во встроенном терминале также можно использовать соответствующие настройки вашего терминала (zsh, oh-my-zsh и т. д.).

Как открыть терминал в вс код

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

$ code --version 1.71.2 74b1f979648cc44d385a2286793c226e611f59e7 x64 $ code --list-extensions espressif.esp-idf-extension ms-vscode.cpptools 

Если вы хотите запустить командную строку из среды разработки VS Code, см. описание возможностей встроенного терминала [2].

Для получения обзорной подсказки по командной строке VS Code откройте терминал или командную строку, и введите команду code —help . В ответ вы увидите версию, пример применения и список опций командной строки.

$ code --help Visual Studio Code 1.71.2 
Usage: code [options][paths. ] 
Для чтения из stdin добавьте '-' (например 'ps aux | grep code | code -') 
Опции: -d --diff < file> < file>Сравнение двух файлов друг с другом. -m --merge < path1> < path2 > < base> < result>Выполнение слияния по принципу дерева, с предоставлением путей для двух модифицированных версий файла, общего оригинала обоих модифицированных версий, и выходного файла для сохранения результатов слияния. -a --add < folder>Добавление папки (папок) к последнему активному окну. -g --goto < file:line[:character]>Открыть файл по указанному пути, на указанной строе и позиции символа. -n --new-window Принудительно открыть новое окно. -r --reuse-window Принудительно открыть файл или папку в уже открытое окно. -w --wait Ожидание закрытия файлов перед возвратом. --locale < locale>Установить используемую локаль (например en-US или zh-TW). --user-data-dir < dir>Указывает директорию, которая хранит данные пользователя. Может использоваться для открытия нескольких отдельных экземпляров Code. --profile < settingsProfileName>Откроет предоставленную папку или workspace с указанным профилем и свяжет профиль с workspace. Если профиль не существует, то будет создан новый. Чтобы опция дала эффект, должна быть предоставлена папка или workspace. -h --help Печать подсказки по использованию. 
Управление расширениями --extensions-dir < dir>Установит путь корня для расширений. --list-extensions Выведет список установленных расширений. --show-versions Покажет версии установленных расширений, когда используется --list-extensions. --category < category>Фильтрует установленные расширения по предоставленной категории, когда используется --list-extensions. --install-extension < ext-id | path>Установит или обновит расширение. В аргументе указывается либо идентификатор (id) расширения, либо путь до VSIX. Идентификатор расширения представлен в виде '$.$'. Используйте аргумент '--force', чтобы обновить до последней версии. Для установки определенной версии предоставьте '@$'. Пример: 'vscode.csharp@1.2.3'. --pre-release Установит версию предварительного релиза расширения, когда используется --install-extension. --uninstall-extension < ext-id>Деинсталлирует расширение. --enable-proposed-api < ext-id>Разрешает предлагаемые функции API для расширений. Может принимать один или большее количество идентификаторов ID для индивидуального управления расширениями. 
Решение проблем -v --version Печать версии. --verbose Печать подробного вывода (подразумевает --wait). --log < level>Используемый уровень лога. По умолчанию установлен уровень 'info'. Допустимы значения 'critical', 'error', 'warn', 'info', 'debug', 'trace', 'off'. -s --status Печать использования процессов и диагностической информации. --prof-startup Запуск профайлера CPU при старте (startup). --disable-extensions Запрет всех установленных расширений. --disable-extension < ext-id>Запрет расширения. --sync < on | off>Включение или выключение синхронизации. --inspect-extensions < port>Позволяет выполнять отладку и профайлинг расширений. Проверьте инструментарий разработчика для URI соединения. --inspect-brk-extensions < port>Позволяет выполнять отладку и профайлинг расширений с хостом расширений, приостановленном после старта. Проверьте инструментарий разработчика для URI соединения. --disable-gpu Запрет аппаратного ускорения GPU. --max-memory < memory>Максимальный объём памяти для окна (в мегабайтах). --telemetry Покажет все события телеметрии, которые собирает VS code. 

Запуск из командной строки. Вы можете запустить VS Code из командной строки для быстрого открытия файла, папки, или проекта. Обычно VS Code открывают в контексте папки (например, корневой папки проекта). Чтобы сделать это, запустите терминал или приглашение командной строки, командами cd перейдите в каталог проекта, и введите команду code . :

VSCode run from CLI

Пользователи macOS должны сначала запустить команду (Shell Command: Install ‘code’ command in PATH) для добавления исполняемого кода среды VS Code в переменную окружения PATH. Для помощи см. руководство по установке VS Code на macOS [3].

Инсталляции Windows и Linux должны добавить место нахождения бинарников VS Code в системные пути поиска. Если это не тот случай, то вы можете добавить вручную путь в переменную окружения Path (%PATH% на Windows и $PATH на Linux). Например, на Windows среда VS Code может быть установлена в папку AppData\Local\Programs\Microsoft VS Code\bin. Чтобы получить инструкции по установке, специфичные для платформы, см. [4].

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

$ code index.html style.css documentation\readme.md 

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

Если вы указали в командной строке больше одного файла, запустится только один экземпляр VS Code. Если в командной строке вы создадите больше одной папки, то VS Code создаст Multi-root Workspace [5], включающее каждую папку.

Аргумент Описание
file Имя файла, который должен быть открыт. Если этот файл не существует, то он будет создан и помечен как редактируемый. Можно указать в командной строке несколько параметров file (файл1, файл2, . и т. д.), которые отделяются друг от друга пробелом.
file:line[:character] Используется с аргументом -g. Имя файла file для открытия на указанной строке и опционально на указанной позиции символа в строке.
folder Имя папки для открытия. Можно указать несколько папок, и будет создано Multi-root Workspace [5].

[Ссылки]

1. Visual Studio Code Code Command Line Interface site:code.visualstudio.com.
2. Visual Studio Code Terminal Basics site:code.visualstudio.com.
3. Visual Studio Code on macOS site:code.visualstudio.com.
4. Setting up Visual Studio Code site:code.visualstudio.com.
5. Multi-root Workspaces site:code.visualstudio.com.

Visual Studio Code #

Visual Studio Code — это текстовый редактор, вроде блокнота в Windows, но созданный специально для программистов: он поставляется вместе с подсветкой синтаксиса, автодополнением, встроенным терминалом, системой контроля версий и ещё огромным количеством инструментов, упрощающих написание кода. Однако VS Code это не IDE, т.е. он изначально не содержит в себе инструментов для компиляции и запуска написанного кода, что означает, что для комфортной разработки, его необходимо настроить соответствующим образом. Именно этому и посвящена данная статья.

Где скачать #

Загрузить VS Code можно здесь . Сайт сам поймёт, какую операционную систему ты используешь, и предложит соответствующую версию. При установке рекомендуем поставить все галочки и не менять язык на русский, так как вся статья написана для англоязычной версии.

Настройка для работы с C++ #

Windows #

  1. Установить компилятор g++ отсюда, выбрав последнюю доступную версию нужной разрядности. После установки необходимо перезапустить компьютер;
  2. Открываем командную строку, для этого нажимаем комбинацию клавиш Win + R , вводим cmd и нажимаем Enter, в открывшемся окне прописываем g++ —version и снова нажимаем Enter. Если ты увидишь сообщение, содержащее версию, значит компилятор установлен и можно переходить к следующему шагу. Если же появится ошибка, значит система не понимает, где установлен компилятор, и ей необходимо указать, где он находится. Для этого необходимо добавить g++ в PATH : Параметры > Система > О системе > Сведения о системе > Дополнительные параметры системы > Переменные среды > Системные переменные > Path, тут необходимо нажать кнопку Добавить и вставить следующий путь: c:\mingw\libexec\gcc\x86_64-w64-mingw32 ;
  3. Теперь ты можешь компилировать С++ код, прописывая в консоли g++ FILE_NAME.cpp , и запускать скомпилированный файл a.exe . Однако можно автоматизировать этот процесс внутри VS Code. Для этого нужно зайти в раздел с расширениями с помощью комбинации клавиш Ctrl + Shift + X или можно нажать на иконку с кубиками в боковой панели, а затем найти и установить расширение Code Runner ;
  4. Теперь, чтобы скомпилировать .cpp файл, можно просто использовать комбинацию клавиш Ctrl + Alt + N или соответствующую кнопку в правом верхнем углу. При желании, её можно изменить в настройках;
  5. Далее необходимо открыть настройки, пользуясь сочетанием клавиш Ctrl + , или нажав на шестерёнку в левом нижнем углу. В строке поиска ввести @ext:formulahendry.code-runner terminal и поставить галочку в Code-runner: Run In Terminal . Теперь код будет запускаться во встроенном терминале, и у тебя появится возможность вводить входные данные с клавиатуры.

Linux #

  1. Установить компилятор g++ используя пакетный менеджер, например, если ты используешь Ubuntu, тебе нужно открыть терминал и написать sudo apt install gcc ;
  2. Чтобы убедиться, что компилятор установился правильно, введи в терминале g++ —version . Если всё в порядке, ты увидишь сообщение, содержащее версию g++ ;
  3. Далее, уже в самом VS Code, заходим в раздел с расширениями с помощью Ctrl + Shift + X или можно просто нажать на иконку с кубиками в боковой панели, а затем найти и установить расширение Code Runner ;
  4. Теперь, чтобы скомпилировать .cpp файл, ты можешь просто использовать комбинацию клавиш Ctrl + Alt + N . При желании, её можно изменить в настройках;
  5. Далее необходимо открыть настройки, пользуясь сочетанием клавиш Ctrl + , или нажав на шестерёнку в левом нижнем углу. В строке поиска ввести @ext:formulahendry.code-runner terminal и поставить галочку в Code-runner: Run In Terminal . Теперь код будет запускаться во встроенном терминале, и у тебя появится возможность вводить входные данные с клавиатуры.

Mac #

  1. На Mac установить компилятор g++ легче всего, используя пакетный менеджер Homebrew, который не установлен по умолчанию. Чтобы его установить, тебе нужно открыть терминал и вставить туда следующую команду:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 

Несколько советов для удобства #

  1. Если ты раньше пользовался Visual Studio, и, открывая свой старый код, у тебя возникают проблемы с отображением кириллицы, тебе следует изменить кодировку файла. Для этого во встроенной командной строке найди Change File Encoding > Reopen with Encoding и выбери самое первое с подписью Guessed from content.
  2. Для того, чтобы программа корректно компилировалась, каждый раз после её изменения нужно сначала её сохранить с помощью Ctrl + S . Чтобы этого не делать, можно включить автосохранение: для этого нужно найти параметр Files: Auto Save в настройках и выбрать значение afterDelay .
  3. Чтобы изменить или добавить сочетания клавиш, открой командную строку ( Ctrl + Shift + P на Windows и Linux или Cmd + Shift + P на Mac) и в поиске найди Preferences: Open Keyboard Shortcuts . Например, одной из полезных горячих клавиш будет увеличение/уменьшение размера шрифта, для этого в меню горячих клавиш введи Editor Font Zoom и поставь горячие клавиши на . In и . Out , мы предпочитаем использовать Ctrl + = для увеличения и Ctrl + — для уменьшения шрифта.
  4. При компиляции .cpp файла в папке с ним появляется .out файл. Чтобы .out файлы не мешались во встроенном проводнике, можно скрыть их в настройках. Для этого в настройках введи Files: Exclude , и добавь туда значение *.exe (аналогично для любого другого расширения).

Работа с Git #

Visual Studio Code даёт всё необходимое для удобной работы с системой контроля версий. Здесь ты можешь спокойно пуллить, коммитить, пушить, мерджить и т.д. Самый простой, на мой взгляд, способ это делать — использовать командную строку Ctrl + Shift + P . Здесь ты можешь найти любое действие в системе контроля версий. Все они начинаются с Git: , а дальше идёт название действия, например, Git: Pull или Git: View File History .

Другим способом работы с Git является вкладка View: Show Source Control , где можно делать всё то же, но используя графический интерфейс.

VS Code в браузере #

GitHub очень тесно интегрируется с VS Code — ты можешь открыть любой репозиторий и нажать на клавиатуре на точку или поменять github.com на guthub.dev в адресной строке, чтобы открыть web-версию VS Code. Тут ты сможешь посмотреть и изменить файлы, не клонируя репозиторий на свой компьютер. Однако, это неполноценная версия VS Code: здесь у тебя не получится воспользоваться терминалом или скомпилировать .cpp файл.

Кастомизация #

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

Например, я предпочитаю минималистичный вид, поэтому мой VS Code на данный момент выглядит вот так:

My VS Code screenshot

Темы #

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

  1. Открыть панель расширений c помощью Ctrl + Shift + X на Windows и Linux или Cmd + Shift + X на Mac;
  2. Найти понравившуюся тему ( @category:»themes» чтобы видеть только темы);
  3. Нажать на кнопку Install;
  4. Если тема не применилась автоматически, или ты хочешь выбрать другую среди установленных, достаточно открыть командную строку ( Ctrl + Shift + P на Windows и Linux или Cmd + Shift + P на Mac), после чего найти параметр Preferences: Color Theme и выбрать желаемую тему.

Иконки файлов #

Точно так же, как и темы, ты можешь изменить иконки во встроенном проводнике — боковой панели, которая отображает все файлы рабочей директории. Для этого достаточно просто написать icons в поиске расширений и установить расширение с понравившимися иконками. Если иконки не применились автоматически, или ты хочешь выбрать другую среди установленных, достаточно открыть командную строку и в параметре Preferences: File Icon Theme выбрать желаемую тему иконок.

Шрифт #

В VS Code ты можешь поменять шрифт кода с помощью параметра Editor: Font Family в настройках, где перечисляются шрифты по приоритету. Например, у меня это ‘Fira code’, Menlo, Monaco, ‘Courier New’, monospace , что означает, что будет использоваться шрифт Fira Code, но если он не найдётся среди установленных, будет использоваться Menlo и так далее. Чтобы использовать свой шрифт, просто добавь его первым в эту строку.

Оба этих шрифта поддерживают лигатуры. Что это? Лигатура — это знак, объединяющий два или более символа. В коде они применяются для отображения операторов и помогают уменьшить шум путем слияния символов и удаления лишних деталей и в определённых случаях уравновесить пространство между символами. Вот несколько примеров:

Ligatures example

Скрытие панелей #

Ещё одним способом кастомизации VS Code является изменение поведения панелей и других элементов интерфейса, что помогает освободить огромное количество места на экране. У меня обычно скрыты все элементы интерфейса, кроме самого пространства редактора, а когда у меня появляется необходимость воспользоваться, скажем, строкой состояния, я использую соответствующую комбинацию клавиш. Все сочетания клавиш настраиваются в Preferences: Open Keyboard Shortcuts .

Настройки #

На самом деле, в VS Code есть ещё огромное количество настроек, которые ты можешь найти… в настройках. Поэтому, если тебе что-то не нравится, ты всегда можешь поискать этот параметр в настройках приложения или в интернете — скорее всего ты не первый, кто захотел изменить это, и сможешь найти готовое решение.

И ешё, все свои настройки ты можешь синхронизировать через свой аккаунт GitHub, чтобы иметь единые настройки на компьютере дома и в университете. Статья об этом .

Terminal Basics

Visual Studio Code includes a full featured integrated terminal that starts at the root of your workspace. It provides integration with the editor to support features like links and error detection. The integrated terminal can run commands such as mkdir and git just like a standalone terminal.

You can open a terminal as follows:

  • From the menu, use the Terminal >New Terminal or View >Terminal menu commands.
  • From the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), use the View: Toggle Terminal command.
  • In the Explorer, you can use the Open in Integrated Terminal context menu command to open a new terminal from a folder.
  • To toggle the terminal panel, use the ⌃` (Windows, Linux Ctrl+` ) keyboard shortcut.
  • To create a new terminal, use the ⌃⇧` (Windows, Linux Ctrl+Shift+` ) keyboard shortcut.

VS Code’s terminal has additional functionality called shell integration that tracks where commands are run with decorations on the left of a command and in the scrollbar:

The integrated terminal can run commands such as mkdir and git just like a standalone terminal. VS Code

Note: If you prefer to work outside VS Code, open an external terminal with the ⇧⌘C (Windows, Linux Ctrl+Shift+C ) keyboard shortcut

Terminal shells

The integrated terminal can use various shells installed on your machine, with the default being pulled from your system defaults. Shells are detected and presented in the terminal profiles dropdown.

A detected profile can be chosen in the dropdown next to the new terminal button. Some examples on Windows include PowerShell, Command Prompt, Git Bash and WSL

You can learn more about configuring terminal shells in the terminal profiles article.

Managing terminals

The terminal tabs UI is on the right side of the terminal view. Each terminal has an entry with its name, icon, color, and group decoration (if any).

Activating the Launch Profile button will show all detected and manually configured profiles

Add terminal instances by selecting the + icon on the top-right of the TERMINAL panel, selecting a profile from the terminal dropdown, or by triggering the ⌃⇧` (Windows, Linux Ctrl+Shift+` ) command. This action creates another entry in the tab list associated with that terminal.

Remove terminal instances by hovering a tab and selecting the Trash Can button, selecting a tab item and pressing Delete , using Terminal: Kill the Active Terminal Instance command, or via the right-click context menu.

Navigate between terminal groups using focus next ⇧⌘] (Windows, Linux Ctrl+PageDown ) and focus previous ⇧⌘[ (Windows, Linux Ctrl+PageUp ) .

Icons may appear to the right of the terminal title on the tab label when a terminal’s status changes. Some examples are a bell (macOS) and for tasks, displaying a check mark when there are no errors and an X otherwise. Hover the icon to read status information, which may contain actions.

Groups (split panes)

Place multiple terminals side-by-side and create a group by splitting a terminal:

  • Hover over a entry in the list of terminals on the right and select the inline split button.
  • Right-click the context menu and selecting the Split menu option.
  • Alt and click on a tab, the + button, or the single tab on the terminal panel.
  • Trigger the ⌘\ (Windows, Linux Ctrl+Shift+5 ) command.

Tip: The working directory for the new terminal depends on the terminal.integrated.splitCwd setting.

Navigate between terminals in a group by focusing the previous pane, ⌥⌘← (Windows, Linux Alt+Left ) , or the next pane, ⌥⌘→ (Windows, Linux Alt+Right ) .

Dragging and dropping tabs in the list rearranges them. Dragging a tab into the main terminal area allows moving a terminal from one group to another.

Moving a terminal into its own group can be done with the Terminal: Unsplit Terminal command through the Command Palette or in the right-click context menu.

Terminals in editor area

You can open terminals in the editor area (terminal editors) with the Terminal: Create New Terminal in Editor Area command, the Terminal: Create New Terminal in Editor Area to the Side command, or by dragging a terminal from the terminal view into the editor area. Terminal editors are presented like regular editor tabs:

Terminal editors are presented like regular text file tabs

You can have terminal editors on either side or arranged in multiple dimensions using the editor group layout system, e.g. PowerShell and WSL terminals stacked to the right of file editors:

Terminal editors are can be laid out using the editor group layout system, for example 2 terminals could sit to the right of a text editor

The terminal.integrated.defaultLocation setting can change the default view or editor area terminal location.

Navigating the buffer

The content in the terminal is called the buffer, with the section right above the bottom viewport being called «scrollback». The amount of scrollback kept is determined by the terminal.integrated.scrollback setting and defaults to 1000 lines.

There are various commands available to navigate around the terminal buffer:

  • Scroll up a line — ⌥⌘PageUp (Windows Ctrl+Alt+PageUp , Linux Ctrl+Shift+Up )
  • Scroll down a line — ⌥⌘PageDown (Windows Ctrl+Alt+PageDown , Linux Ctrl+Shift+Down )
  • Scroll up a page — PageUp (Windows, Linux Shift+PageUp )
  • Scroll down a page — PageDown (Windows, Linux Shift+PageDown )
  • Scroll to the top — ⌘Home (Windows Ctrl+Home , Linux Shift+Home )
  • Scroll to the bottom — ⌘End (Windows Ctrl+End , Linux Shift+End )

Command navigation is also available (see shell integration):

  • Scroll to the previous command — ⌘↑ (Windows, Linux Ctrl+Up )
  • Scroll to the next command — ⌘↓ (Windows, Linux Ctrl+Down )

Scrolling will happen instantaneously, but can be configured to animate over a short duration with the terminal.integrated.smoothScrolling setting.

Links

The terminal features sophisticated link detection with editor integration and even extension contributed link handlers. Hover over a link to display an underline, then hold the Ctrl / Cmd key and click.

These built-in link handlers are used in the following priority order:

  • URIs/URLs: Links that look like URIs, such as https://code.visualstudio.com , vscode://path/to/file or file://path/to/file will open using the standard handler for the protocol. For example, https links will open the browser. Opening a URI link will open it in the system browser
  • File links: Links to files that have been verified to exist on the system. These will open the file in a new editor tab and support many common line/column formats such as file:1:2 , file:line 1, column 2 . Activating a file link will open it in an editor
  • Folder links: Links to folders are similar to file links but will open a new VS Code window at the folder. Activating a folder link will open it in a new window
  • Word links: Fallback link type that uses the terminal.integrated.wordSeparators setting. The setting defines word boundaries and make nearly all text into words. Activating a word link searches the workspace for the word. If there is a single result it will open, otherwise it will present the search results. Word links are considered «low confidence» and will not show an underline or tooltip unless you hold the Ctrl / Cmd key. They also have limited support for line and column suffixes. Activating a word link

The Open Detected Link command ( ⇧⌘O (Windows, Linux Ctrl+Shift+O ) ) can be used to access links via the keyboard:

Open Detected Link opens a quick pick with all links in the viewport, split into categories

Tip: If link verification causes performance issues, like in high latency remote environments, disable it via the terminal.integrated.enableFileLinks setting.

Extensions handling links

Extensions can contribute link providers which allow the extension to define what happens when clicked. An example of this is the GitLens extension detecting Git branch links.

When GitLens is installed, hovering a branch name will provide custom behavior to open the branch in the UI

Keyboard accessibility

Links are keyboard accessible through several commands that open links based on the type of link.

  • Terminal: Open Last Local File Link — Opens the most recent local file link. No default keybinding.
  • Terminal: Open Last URL link — Opens the most recent URI/URL link. No default keybinding.
  • Terminal: Open Detected Link. — Opens a searchable Quick Pick with all detected links, including word links. The default keybinding is Ctrl/Cmd+Shift+O , which is the same as the Go to Symbol in Editor keyboard shortcut.

Copy & paste

The keybindings for copy and paste follow platform standards:

  • Linux: Ctrl+Shift+C and Ctrl+Shift+V ; selection paste is available with Shift+Insert
  • macOS: Cmd+C and Cmd+V
  • Windows: Ctrl+C and Ctrl+V

Copying is done automatically on selection when terminal.integrated.copyOnSelection is enabled.

By default, there is a warning when pasting multiple lines, which can be disabled with the terminal.integrated.enableMultiLinePasteWarning setting. This is only done when the shell does not support «bracketed paste mode». When that mode is enabled, the shell is indicating that it can handle multiple line pasting.

Using the mouse

Right-click behavior

The right-click behavior differs based on the platform:

  • Linux: Show the context menu.
  • macOS: Select the word under the cursor and show the context menu.
  • Windows: Copy and drop selection if there is a selection, otherwise paste.

This can be configured using the terminal.integrated.rightClickBehavior setting. The options are:

  • default — Show the context menu.
  • copyPaste — Copy when there is a selection, otherwise paste.
  • paste — Paste on right-click.
  • selectWord — Select the word under the cursor and show the context menu.
  • nothing — Do nothing and pass event to terminal.

Reposition the cursor with Alt

Alt and left-click will reposition the cursor to underneath the mouse. This works by simulating arrow keystrokes, which may not work reliably for some shells or programs. This feature can be disabled with the terminal.integrated.altClickMovesCursor setting.

Mouse events mode

When applications running in the terminal turn on mouse events mode, such as Vim mouse mode, mouse interaction is sent to the application instead of the terminal. This means that clicking and dragging will no longer create a selection. Terminal selection can be forced by holding the Alt key on Windows and Linux, this can also be done with the Option key on macOS but requires enabling the terminal.integrated.macOptionClickForcesSelection setting first.

Find

The integrated terminal has find functionality that can be triggered with ⌘F (Windows, Linux Ctrl+F ) .

Find in the terminal will highlight all text matching the query

Tip: Ctrl+F can be sent to the shell by removing the workbench.action.terminal.focusFind command from commands to skip shell.

Run selected text

To use the runSelectedText command, select text in an editor and run the command Terminal: Run Selected Text in Active Terminal via the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), the terminal will attempt to run the selected text. If no text is selected in the active editor, the entire line that the cursor is on will run in the terminal.

Tip: Also run the active file using the command workbench.action.terminal.runActiveFile .

Maximizing the terminal

The terminal view can be maximized by clicking the maximize panel size button with the upwards chevron icon. This will temporarily hide the editors and maximize the panel. This is useful to temporarily focus on a large amount of output. Some developers use VS Code as a standalone terminal by opening a new window, maximizing the panel, and hiding the side bar.

Note that the panel can only be maximized if its alignment option is set to Center.

Select all

There is a Terminal: Select All command, which is bound to Cmd+A on macOS, but does not have a default keybinding on Windows and Linux as it may conflict with shell hotkeys. To use Ctrl+A to select all, add this custom keybinding:

 "key": "ctrl+a", "command": "workbench.action.terminal.selectAll", "when": "terminalFocus && !isMac" >, 

Drag and drop file paths

Dragging a file into the terminal will input the path into the terminal, with escaping to match the active shell.

Automating terminals with tasks

The Tasks feature can be used to automate the launching of terminals, for example, the following .vscode/tasks.json file will launch a Command Prompt and PowerShell terminal in a single terminal group when the window starts:

 "version": "2.0.0", "presentation":  "echo": false, "reveal": "always", "focus": false, "panel": "dedicated", "showReuseMessage": true  >, "tasks": [   "label": "Create terminals", "dependsOn": [ "First", "Second"  ], // Mark as the default build task so cmd/ctrl+shift+b will create them "group":  "kind": "build", "isDefault": true  >, // Try start the task on folder open "runOptions":  "runOn": "folderOpen"  >  >,   // The name that shows up in terminal tab "label": "First", // The task will launch a shell "type": "shell", "command": "", // Set the shell type "options":  "shell":  "executable": "cmd.exe", "args": []  >  >, // Mark as a background task to avoid the spinner animation on the terminal tab "isBackground": true, "problemMatcher": [], // Create the tasks in a terminal group "presentation":  "group": "my-group"  >  >,   "label": "Second", "type": "shell", "command": "", "options":  "shell":  "executable": "pwsh.exe", "args": []  >  >, "isBackground": true, "problemMatcher": [], "presentation":  "group": "my-group"  >  >  ] > 

This file could be committed to the repository to share with other developers or created as a user task via the workbench.action.tasks.openUserTasks command.

Working directory

By default, the terminal will open at the folder that is opened in the Explorer. The terminal.integrated.cwd setting allows specifying a custom path to open instead:

 "terminal.integrated.cwd": "/home/user" > 

Split terminals on Windows will start in the directory that the parent terminal started with. On macOS and Linux, split terminals will inherit the current working directory of the parent terminal. This behavior can be changed using the terminal.integrated.splitCwd setting:

 "terminal.integrated.splitCwd": "workspaceRoot" > 

There are also extensions available that give more options such as Terminal Here.

Fixed dimension terminals

The Terminal: Set Fixed Dimensions command allows changing the number of columns and rows that the terminal and it’s backing pseudoterminal uses. This will add scroll bars when necessary, which may lead to an unpleasant UX and is generally not recommended, but it is a common ask on Windows in particular for reading logs or long lines when paging tools aren’t available.

You can also right-click on a terminal tab and select Toggle Size to Content Width ( ⌥Z (Windows, Linux Alt+Z ) ) to resize the number of terminal columns to the largest wrapped line in the terminal.

Next steps

The basics of the terminal have been covered in this document. Read on to find out more about:

  • Tasks — Tasks let you integrate with external tools and leverage the terminal heavily.
  • Mastering VS Code’s Terminal — An external blog with plenty of power user tips for the terminal.
  • Explore terminal commands by browsing the keyboard shortcuts within VS Code (Preferences: Open Keyboard Shortcuts then search on ‘terminal’).

Common questions

I’m having problems launching the terminal

There’s a dedicated troubleshooting guide for these sorts of problems.

How do I create an Admin terminal?

The integrated terminal shell is running with the permissions of VS Code. If you need to run a shell command with elevated (administrator) or different permissions, use platform utilities such as runas.exe within a terminal.

You can learn more about customizing terminals via terminal profiles in Configuring Profiles.

Can I add a keyboard shortcut for the Explorer’s Open in Integrated Terminal command?

You can open new terminals for specific folders from the Explorer via the Open in Integrated Terminal context menu command.

A folder selected in the Explorer displaying the context menu with the Open in Integrated Terminal command

By default, there is no keyboard shortcut associated with Open in Integrated Terminal but you can add your own via the Keyboard Shortcuts editor ( ⌘K ⌘S (Windows, Linux Ctrl+K Ctrl+S ) ) to add a keybinding to your keybindings.json .

The keybindings.json example below adds the keyboard shortcut Ctrl+T for openInTerminal .

 "key": "ctrl+t", "command": "openInTerminal", "when": "filesExplorerFocus" > 

Why is nvm complaining about a prefix option when the integrated terminal is launched?

nvm (Node Version Manager) users often see this error for the first time inside VS Code’s integrated terminal:

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local" Run `npm config delete prefix` or `nvm use --delete-prefix v8.9.1 --silent` to unset it 

This is mostly a macOS problem and does not happen in external terminals. The typical reasons for this are the following:

  • npm was globally installed using another instance of node that is somewhere in your path (such as /usr/local/bin/npm ).
  • To get the development tools on the $PATH , VS Code will launch a bash login shell on startup. This means that your ~/.bash_profile has already run and when an integrated terminal launches, it will run another login shell, reordering the $PATH potentially in unexpected ways.

To resolve this issue, you need to track down where the old npm is installed and remove both it and its out-of-date node_modules. Find the nvm initialization script and run which npm before it runs, which should print the path when you launch a new terminal.

Once you have the path to npm, find the old node_modules by resolving the symlink by running a command something like this:

ls -la /usr/local/bin | grep "np[mx]" 

This will give you the resolved path at the end:

. npm -> ../lib/node_modules/npm/bin/npm-cli.js . npx -> ../lib/node_modules/npm/bin/npx-cli.js 

From there, removing the files and relaunching VS Code should fix the issue:

rm /usr/local/bin/npm /usr/local/lib/node_modules/npm/bin/npm-cli.js rm /usr/local/bin/npx /usr/local/lib/node_modules/npm/bin/npx-cli.js 

Why does macOS make a ding sound when I resize terminal split panes?

The keybindings ⌃⌘← and ⌃⌘→ are the defaults for resizing individual split panes in the terminal. While they work, they also cause a system «invalid key» sound to play due to an issue in Chromium. The recommended workaround is to tell macOS to no-op for these keybindings by running this in your terminal:

mkdir -p ~/Library/KeyBindings cat > ~/Library/KeyBindings/DefaultKeyBinding.dict EOF   "^@\UF701" = "noop";  "^@\UF702" = "noop";  "^@\UF703" = "noop"; > EOF 

I’m having problems with the terminal rendering. What can I do?

By default, the integrated terminal will render using GPU acceleration on most machines. Typically when there are rendering problems it’s an issue of something in your hardware/OS/drivers not playing nicely with the GPU renderer. The first thing to try is to disable GPU acceleration, trading off rendering speed for DOM-based rendering, which is more reliable:

 "terminal.integrated.gpuAcceleration": "off" > 

See the GPU acceleration section for more information.

I see 1~ or [201~ when I paste something

This normally means that the program/shell running inside the terminal requested to turn on «bracketed paste mode» but something doesn’t support it properly. To work around this, you could run printf «\e[?2004l» to disable it for that session or add the following to your ~/.inputrc file:

set enable-bracketed-paste off 

Alternatively, bracketed paste mode can be forced to ignore the shell’s request by turning it off with this setting:

 "terminal.integrated.ignoreBracketedPasteMode": true > 

Ctrl+A, Ctrl+R output ^A, ^R on zsh

This can happen if zsh is in Vim mode instead of Emacs mode, due to setting $EDITOR or $VISUAL to vi / vim in your init scripts.

To work around this, you have two options:

  • Ensure that you don’t set $EDITOR to vi(m) . However, this isn’t an option if you want your Git editor to work.
  • Add bindkey -e to your init script to set Emacs explicitly.

How can I configure Cmd+. to map to Ctrl+C like macOS’ built-in terminal?

The macOS default terminal uses Cmd+. to perform the same as Ctrl+C . To get this behavior in VS Code, add this custom keybinding:

 "key": "cmd+.", "command": "workbench.action.terminal.sendSequence", "when": "terminalFocus", "args":  "text": "\u0003" > > 

Why are the colors in the terminal not correct?

One of our accessibility features we enable by default is to ensure a minimum contrast ratio of at least 4.5 is met for the foreground text. This feature ensures that text is readable regardless of the shell and theme used which is not possible otherwise. To disable this feature, you can set:

"terminal.integrated.minimumContrastRatio": 1 

See the minimum contrast ratio section for more information.

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

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