Как выбрать терминал vs code
Как изменить терминал в visual studio code
VSCode Изменить терминал по умолчанию
Я использую Visual Studio Code на своем ПК с Windows 10. Я хочу изменить свой терминал по умолчанию с Windows PowerShell на Bash в Ubuntu (в Windows).
Как я могу это сделать?
Я просто набираю следующие ключевые слова в открытом терминале;
Смотрите подробности на изображении ниже. (VSCode версии 1.19.1 — ОС Windows 10)
Он также работает на VS Code Mac. Я пробовал это с VSCode (версия 1.20.1)
В окне настроек JSON добавьте это (в фигурных скобках <> ):
(Здесь вы также можете указать любые другие пользовательские настройки, которые захотите)
Проверьте этот путь, чтобы убедиться, что ваш файл bash.exe находится там, иначе узнайте, где он находится, и вместо этого укажите этот путь.
Теперь, если вы откроете новое окно терминала в VS Code, оно должно открыться с помощью bash вместо PowerShell.
VSCode Изменить терминал по умолчанию
Я использую код Visual Studio на своем ПК с Windows 10. Я хочу изменить свой терминал по умолчанию из Windows PowerShell на Bash на Ubuntu (в Windows).
Как я могу это сделать?
Вы также можете выбрать свой терминал по умолчанию, нажав F1 в коде VS и набрав/выбрав терминал: выберите «Стандартная оболочка».
Я просто набираю следующие ключевые слова в открытом терминале;
Подробнее см. Ниже. (Версия VSCode 1.19.1 — ОС Windows 10)
Он также работает на VS Code Mac. Я попробовал это с VSCode (версия 1.20.1)
Добавьте это в окне настроек JSON (в фигурных скобках <> ):
(Здесь вы можете также установить любые другие пользовательские настройки)
Извлеките этот путь, чтобы убедиться, что ваш файл bash.exe находится там, в противном случае выясните, где он находится, и укажите вместо него этот путь.
Теперь, если вы откроете новое окно терминала в VS Code, оно должно открываться с помощью bash вместо PowerShell.
VSCode Изменить терминал по умолчанию
Я использую код Visual Studio на моем компьютере с Windows 10. Я хочу изменить свой терминал по умолчанию с Windows PowerShell на Bash в Ubuntu (в Windows).
Как я могу это сделать?
4 ответа
Если вы хотите выбрать тип консоли, вы можете написать это в файле «keybinding.json» (этот файл можно найти по следующему пути «Файл-> Настройки-> Сочетания клавиш») `
Я просто набираю следующие ключевые слова в открытом терминале;
Подробности смотрите на картинке ниже. (VSCode версия 1.19.1 — ОС Windows 10)
Работает и на VS Code Mac. Я попробовал это с VSCode (Версия 1.20.1)
В окне настроек JSON добавьте это (в фигурных скобках <> ):
(Здесь вы также можете разместить любые другие пользовательские настройки, которые вы хотите)
Извлеките этот путь, чтобы убедиться, что ваш файл bash.exe находится там, в противном случае выясните, где он находится, и укажите вместо этого путь.
Теперь, если вы откроете новое окно терминала в VS Code, оно должно открываться с помощью bash вместо PowerShell.
Integrated Terminal
Visual Studio Code includes a fully-featured integrated terminal that conveniently starts at the root of your workspace. It provides integration with the editor to support features like links and error detection.
To open the terminal:
Note: Open an external terminal with the ⇧⌘C (Windows, Linux Ctrl+Shift+C ) keyboard shortcut if you prefer to work outside VS Code.
Terminal shells
The integrated terminal can use various shells installed on your machine, with the defaults being:
You can select other available shells to use in terminal instances or as the default such as Command Prompt on Windows, and zsh on macOS and Linux.
You can learn more about configuring terminal shells in the terminal profiles section below.
Note: If you’re having trouble launching your preferred shell in the integrated terminal, it may be due to your shell’s configuration or a VS Code terminal setting. There’s a dedicated troubleshooting guide to help you with these sorts of problems.
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).
Tip: Change the tabs location using the terminal.integrated.tabs.location setting.
Terminal instances can be added 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.
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.
Grouping
Split the terminal by:
Tabs support drag and drop to allow rearranging. Dragging an entry in a terminal group into the empty will remove it from the group (for example, unsplit). Dragging a tab into the main terminal area allows joining a group.
Unsplit a split terminal by triggering the Terminal: Unsplit Terminal command.
Customizing Tabs
Change the terminal’s name, icon, and tab color via the right-click context menu or by triggering the following commands:
Command | Command ID |
---|---|
Terminal: Rename | workbench.action.terminal.rename |
Terminal: Change Icon | workbench.action.terminal.changeIcon |
Terminal: Change Color | workbench.action.terminal.changeColor |
Tip: Go back to the old version by setting terminal.integrated.tabs.enabled:false
Terminal profiles
Terminal profiles are platform-specific shell configurations comprised of an executable path, arguments, and other customizations.
You can use variables in terminal profiles as shown in the example above with the APPDATA environment variable. You can find a list of available variables in the Variables Reference topic.
Configure your default integrated terminal by running the Terminal: Select Default Profile command, which is also accessible via the terminal dropdown.
Configuring profiles
To create a new profile, run the Terminal: Select Default Profile command and activate the configure button on the right side of the shell to base it on. This will add a new entry to your settings that can be tweaked manually in your settings.json file.
Other arguments supported in profiles include:
The default profile can be defined manually with the terminal.integrated.defaultProfile.* settings. This should be set to the name of an existing profile:
Tip: 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.
Removing built-in profiles
Configuring the task/debug profile
By default, the task/debug features will use the default profile. To override that, use the terminal.integrated.automationShell.
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:
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:
There are also extensions available that give more options such as Terminal Here.
Terminal process reconnection
Local and remote terminal processes are restored on window reload, such as when an extension install requires a reload. The terminal will be reconnected and the UI state of the terminals will be restored, including the active tab and split terminal relative dimensions.
Links
The terminal features link detection, showing an underline when files or URLs are hovered with the mouse that will go to the target when Ctrl / Cmd is held. If a file or URL cannot be detected, they are still surfaced as «low confidence» links, which only show an underline when hovered. These low confidence links will search the workspace for the term, opening the match if one is found.
Clicking a file link will either open that document in an editor or produce a Quick Pick with all matches.
Extensions make use of links in the terminal, such as GitLens, to identify branches.
Local echo
On some remote connections, there’s a delay between typing and seeing the characters on the terminal as a result of the round trip the data has to make from VS code to the process. Local echo attempts to predict modifications and cursor movements made locally in the terminal to decrease this lag.
Terminal appearance
Customize the terminal’s appearance using the following settings:
Copy & Paste
The keybindings for copy and paste follow platform standards:
Using the mouse
Right-click behavior
The right-click behavior differs based on the platform:
This can be configured using the terminal.integrated.rightClickBehavior setting.
Alt click
Alt left click will reposition the cursor to underneath the mouse. This works by simulating arrow keystrokes, which may fail for some shells or programs. This feature can be disabled.
Keybindings and the shell
Look at the setting details to see the complete list of default commands.
Chord keybindings in the terminal
By default, when a chord keybinding is the highest priority keybinding, it will always skip the terminal shell (bypassing terminal.integrated.commandsToSkipShell ) and be evaluated by VS Code instead of the terminal. This is typically the desired behavior unless you’re on Windows/Linux and want your shell to use ctrl+k (for bash, this cuts the line after the cursor). This can be disabled with the following setting:
Send text via a keybinding
The workbench.action.terminal.sendSequence command can be used to send a specific sequence of text to the terminal, including escape sequences. This enables things like sending arrow keys, enter, cursor moves, etc. For example, the below sequence jumps over the word to the left of the cursor ( Ctrl+Left ) and presses backspace:
Note that the command only works with the \u0000 format for using characters via their character code (not \x00 ). Read more about these hex codes and the sequences terminals work with on the following resources:
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 line that the cursor is on is run in the terminal.
Automating launching of terminals
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.
Next steps
The basics of the terminal have been covered in this document. Read on to find out more about:
Common questions
I’m having problems launching the terminal
There’s a dedicated troubleshooting guide for these sorts of problems.
Can I use the integrated terminal with the Windows Subsystem for Linux?
Why is VS Code shortcut X not working when the terminal has focus?
Currently, the terminal consumes many key bindings, preventing Visual Studio Code from reacting to them. An example of this is Ctrl+B to open the Side Bar on Linux and Windows. This is necessary as various terminal programs and/or shells may respond to these key bindings themselves. Use the terminal.integrated.commandsToSkipShell setting to prevent specific key bindings from being handled by the terminal.
Can I use Cmder’s shell with the terminal on Windows?
Yes, to use the Cmder shell in VS Code, you need to add the following settings to your settings.json file:
You may refer to Cmder’s wiki for more information.
Why is Cmd+k/Ctrl+k not clearing the terminal?
Normally Cmd+k / Ctrl+k clears the terminal on macOS/Windows, but this can stop working when chord keybindings are added either by the user or extensions. The Cmd+k / Ctrl+k keybindings rely on the VS Code keybinding priority system that defines which keybinding is active at any given time (user > extension > default). To fix this, you need to redefine your user keybinding that will have priority, preferably at the bottom of your user keybindings.json file:
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:
This is mostly a macOS problem and does not happen in external terminals. The typical reasons for this are the following:
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:
This will give you the resolved path at the end:
From there, removing the files and relaunching VS Code should fix the issue:
Can I use Powerline fonts in the integrated terminal?
Yes. Specify Powerline fonts with the terminal.integrated.fontFamily setting.
Note that you want to specify the font family, not an individual font like Meslo LG M DZ Regular for Powerline where Regular is the specific font name.
How do I configure zsh on macOS to jump words with Ctrl+Left/Right arrow?
By default, Ctrl+Left/Right arrow will jump words in bash. Configure the same for zsh by adding these keybindings:
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:
Why is my terminal showing a multi-colored triangle or a completely black rectangle?
This can happen on macOS because of how the terminal launches using VS Code’s environment. When VS Code launches for the first time, to source your «development environment,» it launches your configured shell as a login shell, which runs your
/.zprofile scripts. Now when the terminal launches, it also runs as a login shell, which will put the standard paths to the front (for example, /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ) and reinitialize your shell environment.
To get a better understanding, you can simulate what is happening by launching an inner login shell within your operating system’s built-in terminal:
Unfortunately, unlike in Linux, standalone macOS terminals all run as login shells by default, since macOS does not run a login shell when the user logs into the system. This encourages «bad behavior,» like initializing aliases in your profile script when they should live in your rc script as that runs on non-login shells.
/.zshrc file since aliases only apply to the shell they’re set in.
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. It does this using multiple elements, which are better tuned than the DOM for rendering interactive text that changes often. The terminal features 3 renderers that fallback if they are detected to perform poorly in this order:
Как изменить интегрированный терминал в коде visual studio или VSCode
Я хочу изменить интегрированный терминал CMDER Я использую Vscode в windows 8.1 я проверил doc, а также файл предпочтений, но я запутался Итак, из следующих строк, какая строка изменит его
// Внешний Терминал
// Интегрированная Терминал
5 ответов
чтобы изменить встроенный терминал в Windows, вам просто нужно изменить terminal.integrated.shell.windows строку:
Вы можете тогда доступ к нему с помощью ключей Ctrl + backtick по умолчанию.
можно получить эту работу в VS-коде и интегрировать терминал Cmder (не всплывать).
«terminal.integrated.shellArgs.windows»: [«/k», «%CMDER_ROOT%\vendor\init.bat»]
Я знаю, что поздно, но вы можете быстро выполнить это, просто набрав Ctrl + Shift + p, а затем введите default, он покажет опцию, которая говорит
Terminal: Выберите Оболочку По Умолчанию
, Он будет отображать все терминалы, доступные для вас.
правильная настройка вашей оболочки в Windows-это вопрос поиска правильный исполняемый файл и обновление параметров. Ниже приведен список общие исполняемые файлы оболочки и их расположения по умолчанию.
существует также команда удобства Выберите Оболочку По Умолчанию что может быть доступ через палитру команд, которая может обнаружить и установить это для вы.
так что вы можете открыть палитра команд с помощью ctrl+shift+p используйте команду Выберите Оболочку По Умолчанию, то он отображает все доступные интерфейсы командной строки, выберите все, что вы хотите, VS код устанавливает, что по умолчанию интегрированный терминал для вас автоматически.
если вы хотите установить его вручную, найдите местоположение исполняемого файла вашего cli и откройте пользовательские настройки vscode ( ctrl+, ) затем установить
пример для gitbash на windows7:
официальный способ описан в документах VS Code, что похоже на ответ khernands.
если вы не хотите устанавливать CMDER_ROOT в качестве глобальной переменной среды вы можете сделать это в этом пакетном файле. Кроме того, cd в текущий рабочий dir в конце решил проблему пути для меня.
в этом случае, просто установите shell для конкретной задачи:
Если вы пишете код в Windows, вы заслуживаете лучшего терминала
Я хочу сделать признание. Когда дело доходит до моего компьютера, я оставляю все в значительной степени сыром виде. Конечно, у меня есть любимые маленькие инструменты. Я использую плагины Chrome, такие как Wappalyzer, и множество расширений VS Code, таких как Chrome Debugger и Live Server. Но я сознательно не использую темы, шрифты, средства форматирования и другие приятные для глаз настройки. В далеком прошлом, когда я только начинал программировать, я тратил слишком много времени на перестройку своей индивидуальной настройки на разных компьютерах и на новом оборудовании. Постоянные настройки устарели, поэтому я решил по возможности сократить до стокового.
Это мое оправдание, почему я провел много месяцев, по большей части игнорируя продукт Microsoft Windows Terminal. В конце концов, время, которое я провожу в командной строке, ограничено и ничем не примечательно. Я настраиваю свое приложение, устанавливаю пакеты npm или Nuget и двигаюсь дальше. Проводить время в окне терминала означает заходить в темный угол операционной системы и делать то, что нужно.
Но теперь я вынужден признать, что был неправ. Или, по крайней мере, есть еще один инструмент, для которого мне нужно освободить место. Поскольку Windows Terminal не просто заменяет скрипучую часть программного обеспечения ОС с кодовой базой 30-летней давности, он также добавляет некоторые действительно практичные функции.
Терминал открыт
Прежде чем продолжить, стоит сделать краткий обзор того, что такое терминал на самом деле. Это потому, что мы, разработчики, работающие в Windows, привыкли объединять терминалы и программы оболочки в одну расплывчатую идею. Например, вы можете подумать, что когда Windows перешла со старой командной строки на объектно-ориентированную оболочку PowerShell, она заменила программу терминала. Но на самом деле это неправда.
Вы думаете, что запускаете PowerShell, но на самом деле вы запускаете интерфейс ConHost, который взаимодействует с PowerShell.
Вместо этого Microsoft начала создавать новый терминал под названием Windows Terminal. Он существует уже почти год, но еще не дошел до включения в ОС Windows. Это означает, что если вам нужен Терминал Windows, вы должны установить его из Windows Store. (Или вы можете загрузить его с GitHub и собрать самостоятельно, потому что новый терминал, естественно, имеет открытый исходный код.)
Почему терминал Windows?
Из-за того, как работают терминалы, в них не так много очевидного волшебства. Фактически, «выполнение работы» выполняется любой программой оболочки, которую вы используете. Но оказывается, что новый терминал Windows содержит множество практических удобств, которые могут сделать вас более продуктивным (или, по крайней мере, менее раздражающим) при выполнении повседневной работы. Вот несколько причин полюбить Windows Terminal:
Несколько вкладок. Помните, когда в веб-браузерах была только одна вкладка? Как мы это ненавидели! Но мы терпели это в ConHost уже целое поколение. К счастью, Windows Terminal позволяет открывать столько вкладок, сколько нужно в одном окне.
Одновременное использование нескольких оболочек. Терминал Windows поддерживает любую стандартную программу оболочки. Вы можете использовать старую добрую PowerShell, почти устаревшую командную строку, Azure Cloud Shell (для управления онлайн-ресурсами Azure) и даже bash, если вы включили Windows Linux Subsystem. И вы можете запускать их все рядом, на разных вкладках или панелях одного и того же окна Терминала Windows.
Оболочки сошли с ума
Современный курсор. Что это за блочная штука в ConHost? Он показывает вашу текущую позицию, а не точку вставки, поэтому легко забыть, вставляет ли нажатие клавиши до или после текущего символа.
Изобилие настроек. Все они управляются через немного непонятный файл настроек JSON. Освойте его, чтобы управлять внешним видом окна терминала (размером, цветами, настройкой «всегда поверх») и добавьте свои собственные сочетания клавиш.
Пользователи Linux скажут вам, что многие из этих функций у них были в течение многих лет. Опытные разработчики Windows скажут вам то же самое, потому что они уже используют какую-то альтернативу терминалу с открытым исходным кодом. В основном они правы, но теперь вам не нужно игнорировать их в тихом смущении.
Терминал Windows также имеет графическое оформление, которое мне кажется изящным и почти бесполезным. Мне было интересно поиграть с этими функциями около 90 секунд, а потом забыть на всю оставшуюся жизнь:
Настраиваемая прозрачность с размытием фона. Вы даже можете настроить его на лету, удерживая Ctrl + Shift и вращая кнопку мыши. Но зачем?
Цветовые схемы и пользовательские фоновые изображения.
Анимированные фоны в формате GIF. (Привет, Windows Plus примерно из 1998 года.)
Конечно, если вы решите использовать эти функции, я не буду судить.
Краткое примечание о терминале VS Code
Если вы используете Visual Studio Code, вы, вероятно, знакомы с его интегрированным терминалом. Вы можете выбрать, какую оболочку использовать (например, PowerShell или bash), но вы всегда используете терминал VS Code, а не ConHost.
Тем не менее, терминал VS Code довольно прост. Терминал Windows не может заменить встроенный терминал. Однако вы можете настроить Windows Terminal так, чтобы он работал как внешний терминал для VS Code. Таким образом, когда вы запускаете терминал из VS Code, вы откроете отдельное окно Windows Terminal, что даст вам больше места для передышки и современные функции, которые вам действительно нужны.
Последнее слово
Терминал Windows неуклонно продвигается к версии 2.0, которая ожидается этой весной, и в конечном итоге включение в Windows. Планируется длинный список новых функций, включая возможность отрывать вкладки и перемещать их из одного окна терминала к другому, бесконечная прокрутка и приятный пользовательский интерфейс для управления настройками. Будет ли он вызывать безумную любовь, как VS Code или язык C #? Нет. Но иногда достаточно сделать жизнь менее болезненной.