Предоставление общего доступа к серверу или терминалу в Visual Studio Code
Предоставление общего доступа к серверу или терминалу в качестве узла сеанса совместной работы в Visual Studio Code.
Общий доступ к серверу
Время от времени организатору совместного сеанса нужно предоставлять гостям доступ к веб-приложениям либо другим локальным серверам или службам. Это могут быть другие конечные точки REST или базы данных и другие серверы. Visual Studio Live Share позволяет указать номер локального порта, при необходимости присвоить ему имя и предоставить общий доступ к нему всем гостям.
Гости в этом случае смогут подключаться к указанному порту сервера, предоставленному в общий доступ, через аналогичные порты на своих локальных компьютерах. Например, если вы предоставили общий доступ к веб-серверу, работающему на порту 3000, гости будут обращаться к тому же веб-серверу на своих компьютерах через порт http://localhost:3000.
Это подключение устанавливается с использованием защищенного туннеля SSH или туннеля SSL между организатором и гостями, а проверка подлинности осуществляется через службу. Этот механизм подключения позволяет убедиться, что доступ имеют только пользователи в рамках сеанса совместной работы.
В качестве узла будьте выборочными в отношении портов, которыми вы предоставляете общий доступ к гостям. Лучше использовать порты приложений, а не предоставлять общий доступ к системному порту. Для гостей предоставленные в общий доступ порты используются так же, как если бы этот сервер или служба были запущены прямо на их компьютере. Это удобно, но совместное использование неправильного порта может быть рискованным.
В целях безопасности другим гостям предоставляются только серверы, работающие на указанных портах. Организатору совместного сеанса легко добавить новый порт. Вот как это сделать.
- На вкладке Live Share или на вкладке Live Share Explorer выберите элемент сервера общего доступа или кнопку:
- Введите номер порта, на котором работает сервер. При желании также укажите имя.

Вот и все! Теперь сервер, работающий на указанном порту, будет сопоставлен с аналогичным портом, связанным с localhost каждого гостя (если этот порт не был занят).
Если нужный порт на компьютере гостя уже занят, вместо него автоматически выбирается другой. Гость может просмотреть список общих портов (по имени, если они указаны) на вкладке Обозреватель Live Share или вкладке VS Live Share. Список см. в разделе Общие серверы. Если выбрать порт, этот сервер откроется в браузере. Можно также щелкнуть сервер правой кнопкой мыши и выбрать действие копирования ссылки на сервер в буфер обмена.

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

Общий доступ к терминалу
Современные разработчики часто используют разнообразные средства командной строки. Live Share позволяет организаторам совместно использовать терминал с гостями. Общий терминал может быть доступен только для чтения или для всех операций совместной работы, чтобы и вы, и гости могли выполнять команды и просматривать результаты. Вы можете сделать вывод терминала видимым для гостей. Вы также можете разрешить гостям выполнять тесты или создавать сборки, и даже изучать связанные со средой проблемы, которые возникают только на вашем компьютере.
По умолчанию терминалы не используются совместно, так как при этом гостям предоставляется как минимум доступ для чтения выходных данных всех запускаемых команд (или даже возможность самостоятельно выполнять любые команды). Такая конфигурация по умолчанию позволяет выполнять команды в локальных терминалах с меньшим риском и предоставлять общий доступ только при необходимости. И только организаторы могут запускать общие терминалы. За счет этого ограничения гости не смогут запустить общий терминал и сделать что-то неожиданное.
В качестве узла можно предоставить общий доступ к терминалу на вкладке Live Share или Live Share Explorer . Выберите элемент терминала или кнопку»:

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

Когда вы выберете нужный тип общего терминала, этот терминал появится на вкладке Терминал в Visual Studio Code.

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

Чтобы завершить сеанс терминала, введите выход, закройте окно терминала или нажмите кнопку «Отменить общий доступ» на вкладке Live Share Explorer или на вкладке Live Share. Все будут отключены.
Следующие шаги
Дополнительные сведения см. в следующих статьях:
- Краткое руководство. Предоставление общего доступа к первому проекту
- Краткое руководство. Присоединение к первому сеансу
- Установка и вход в Live Share в Visual Studio
- Требования к подключению для Live Share
- Функции системы безопасности Live Share
- Сведения об установке Linux
Возникли проблемы? Ознакомьтесь с разделом по устранению неполадок или отправьте отзыв.
Как сделать несколько различных терминалов в Visual Studio Code и сохранить их для следующих запусков редактора?
В Visual Studio Code есть возможность запускать консоли.
Сейчас VSC запускает мне стандартную консоль, cmd.exe. А я хочу добавить в список гитбаш и использовать сразу две. В правой части, в панели Terminal есть выпадающий список с консолями, где сейчас только cmd.exe и кнопка «новый терминал», при нажатии на которую создаются ещё cmd.exe.
Зайдя в files-preferences-settings-terminal и найдя файл config.json можно заменить путь с cmd.exe до нужной консоли гит-баш, которая добавится при нажатии на кнопку «новый терминал», теперь в выпадающем списке будут две консоли, cmd и git-bush, как мне и нужно. Но при выходе из редактора список сбрасывается и в выпадающем меню остается последняя указанная консоль. Как сделать что бы при выходе хотя бы выпадающий список с консолями сохранялся, а еще лучше что бы весь блок терминал остался как при выходе (размеры окон терминалов и их расположение)
Отслеживать
Sergey Harchenko
задан 25 апр 2019 в 9:42
Sergey Harchenko Sergey Harchenko
96 1 1 серебряный знак 11 11 бронзовых знаков
возможно подойдет расширение
25 апр 2019 в 10:03
3 ответа 3
Сортировка: Сброс на вариант по умолчанию
Нашел решение, которое упрощает запуск двух консолей, в моём случае консолей cmd.exe и git-bash. Данный способ не идеальный, но позволяет запустить две консоли в 3 клика и сохранить список консолей для текущего проекта при перезапуске.
Пожалуйста, если вы найдете как улучшить мой вариант, оставьте комментарий или напишите лично мне.
РЕШЕНИЕ
(Способ работает по такой схеме, в которой стандартной консолью у вас задан git-bash, иначе как дополнительная консоль git-bash почему то открывается вне редактора.)
Как подсказали в комментарии, подойдёт расширение «Terminals Manager», автора «Fabio Spampinato».
1) Запускаем VSC. Убедимся, что мы находимся в папке своего проекта, именно для него мы создаем список консолей. Как сделать это глобально я не знаю.
2) Устанавливаем расширение
3) Открываем консоль VSC ctrl+shift+p
4) Вводим: «Terminals: Edit Configuration», откроется файл terminal.json
5) впишем простейшие настройки для второго терминала. В моём случае cmd.exe.
< "autorun": true, "terminals": [ < "name": "cmd", "shellPath": "C://Windows//System32//cmd.exe" >] >
6) Перезапускаем редактор
7) В панели терминалов (ctrl+ё) справа видим выпадающее меню, в котором и будут две наши консоли.
PS
В папке проекта появится папка .vscode, в которой хранятся конфиги наших настроек.
После запуска VSC в выпадающем меню не сразу отображаются оба терминала, у меня задержка около 1-2 секунд, пока редактор прогружается.
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:

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.

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).

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:

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:

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.

- 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 .

- Folder links: Links to folders are similar to file links but will open a new VS Code window at the folder.

- 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.

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

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.

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 ) .

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.

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.
Как запустить код в терминале в VS Code

Терминал VS Code (Visual Studio Code) поддерживает текстовые команды. Результаты и вывод можно просмотреть в редакторе, который поддерживает такие оболочки, как bash, командную строку и PowerShell. Запуск кода в терминале позволяет пользователям разделить терминал на разные панели, перемещаться по истории команд, настраивать среду оболочки и настраивать свои параметры для улучшения рабочего процесса.
В этой статье более подробно рассматривается, как запускать код в терминале VS Code.
Запуск кода в терминале
Терминал VS Code — это командная строка, интегрированная непосредственно в платформу. С его помощью вы можете запускать сценарии, выполнять команды и взаимодействовать с операционной системой вашего ПК или любыми другими инструментами разработки, не выходя из среды кода. Выполните следующие действия, чтобы запустить код в терминале VS Code:
- В VS Code откройте файл, над которым хотите работать. Чтобы это работало, вам необходимо иметь правильное языковое расширение, соответствующее вашему языку программирования. Их можно найти на вкладке «Расширения».

- Нажмите клавишу (`) на клавиатура. Откроется встроенный терминал. Альтернативой здесь является выбор “Терминала” в разделе “Просмотр” строка меню. Находясь здесь, выберите «Новый терминал».

- Перейдите в каталог, содержащий файл кода, через “cd” команда. Если файл находится внутри “Document” например, используемая здесь команда должна быть «cd Documents». Это позволит вам перейти к папке.

- Когда нужный каталог будет найден, вам следует запустите файл кода. Для этого введите команду, соответствующую конкретному используемому языку программирования.
- JavaScript: node filename.js
- Python: python filename.py
- C++: g++ filename.cpp -o output && ./output
- Java: javac filename.java && java filename
- Ruby: Ruby filename.rb
- Имя файла должно быть заменено реальным именем файла кода.

- Выполните команду, нажав кнопку Enter. Это должно отобразить код в терминале.

Интегрированный терминал в VS Code
Терминал Visual Studio Code полностью интегрирован и запускается прямо из корня рабочей области. Он предлагает интеграцию редактора с такими функциями, как обнаружение ошибок и ссылки. Вы можете запускать различные команды так же, как на автономных терминалах.
Вот как открыть интегрированный терминал:
- Перейдите в меню на верхней панели инструментов и выберите «Просмотр».

- Выберите &ldquo ;Терминал” из раскрывающегося меню. Альтернативно используйте “Ctrl+`” (обратная галочка), чтобы запустить терминал.
- Терминал откроется в окне VS Code. Здесь отображается командная строка.
- Отрегулируйте размер панели терминала путем перетаскивания. Кнопку максимизации в правом верхнем углу можно использовать для перехода в полноэкранный режим.

- Нажмите стрелку раскрывающегося списка в правом верхнем углу и выберите нужную оболочку. Таким образом можно переключаться между оболочками.

- Откройте команду “Command Палитра» нажав “Ctrl+Shift+P».
- Используйте «Вид: Переключить терминал»;

- Открыть во встроенном терминале” Команды меню можно использовать в Проводнике.
- Панель терминала можно переключать с помощью “Ctrl+`” ярлык на клавиатуре.
- Команда “Ctrl+Shift+`” сочетание клавиш помогает создать новый терминал.
Терминал в VS Code имеет некоторые дополнительные функции, называемые интеграцией оболочки. Он отслеживает, где выполняются команды. Ярлык Ctrl+shift+C позволяет открыть VS Code во внешнем терминале.
Терминальные оболочки
В различных оболочках можно использовать интегрированный терминал. Они часто устанавливаются на компьютер, а значения по умолчанию извлекаются из системных настроек по умолчанию. При обнаружении оболочек они отображаются в раскрывающемся списке профилей терминала.
Управление терминалами
В правой части окна терминала находится пользовательский интерфейс вкладок терминала. Каждый терминал имеет имя, цвет, значок и оформление группы данных, если таковое существует.
Чтобы добавить экземпляры терминала:
- Выберите “+ ” на панели «Терминал» (вверху справа).

- Перейдите к терминалу раскрывающийся список и выберите профиль.
- Альтернативно нажмите команду Ctrl+Shift+`. С помощью этого действия вы создадите новую запись в верхнем списке, связанную с конкретным терминалом.
Чтобы удалить экземпляры:
- Наведите указатель мыши на вкладку и выберите “Корзину” вариант,

- Выберите элемент вкладки и нажмите “Удалить”
- Альтернативно щелкните правой кнопкой мыши и используйте команду “Терминал: убить активные экземпляры терминала” вариант команды из контекстного меню.
Можно перемещаться между различными группами терминалов с помощью фокуса следующего сочетания клавиш Ctr+PageDown и фокуса предыдущего сочетания клавиш Ctrl+PageUp. . При изменении статуса терминала в правой части терминала могут появиться значки. Вы можете навести курсор на значок, чтобы просмотреть информацию о статусе, которая может содержать действия.
Разделить панели (группы)
Вы можете располагать разные терминалы рядом. Он позволяет разделить панели, а затем создать группу панелей для работы.
- Найдите запись в списке терминалов справа и наведите на нее курсор.
- Выберите встроенную разделенную кнопку.

- Перейдите в контекстное меню, щелкните его правой кнопкой мыши, затем выберите «Разделить». меню.

- Нажмите “Alt” а затем нажмите кнопку “+” или одну вкладку на панели терминала.

- Активируйте “Ctrl+Shift+5” команда.

Чтобы перемещаться между терминалами внутри группы, вам нужно перейти на предыдущую панель, нажав “Alt+Left” или следующую панель, нажав «Alt+Right». Когда вы перетаскиваете вкладки в списке, вы, по сути, меняете их порядок. Однако когда вкладка перетаскивается в основную область терминала, вы успешно перемещаете терминал из одной группы в другую.
С помощью команды “Терминал: Unsplit” перемещает терминал внутри своей группы. Это достигается щелчком правой кнопкой мыши по контекстному меню или с помощью палитры команд.
Терминалы в области редактора
Терминалы в редакторе можно открывается с помощью команд “Терминал: Создать новый терминал в области редактора” или «Терминал: создать новый в области редактора сбоку». Этого также можно добиться, просто перетащив терминал из представления в область редактора. Обычно редакторы терминала представлены так же, как обычные вкладки редактора.
Редакторы терминалов могут располагаться с обеих сторон или могут располагаться во многих измерениях с помощью системы компоновки групп редакторов. Параметр “terminal.integrated.defaultLocation” изменяет “редактор” по умолчанию; или “просмотр” местоположение терминала области.
Навигация по содержимому
Буфер относится к содержимому терминала, и это тот раздел, который находится над кнопкой «прокрутки назад». или вид снизу. Кнопка “terminal.integrated.scrollback” Настройка определяет объем сохраняемой обратной прокрутки. По умолчанию — 1000 строк.
Перемещение по буферу можно осуществлять с помощью различных команд, в том числе:
- Ctrl+Alt+PageUp: прокрутить строку вверх
- Ctrl+Alt+PageDown: прокрутить вниз
- Shift+PageUp: прокрутить страницу вверх
- Shift+PageDown: прокрутить страницу вниз
- Ctrl+ Главная страница: прокрутить вверх
- Ctrl+End: прокрутить вниз
Для навигации по командам:
- Ctrl+Up: Прокрутите до предыдущей команды
- Ctrl+Вниз: переход к следующей команде.
Обычно прокрутка происходит одновременно. Однако вы можете настроить его с помощью “terminal. интегрированная плавная прокрутка” возможность анимации в течение короткого времени.
Часто задаваемые вопросы
Что делать, если у меня возникли проблемы с запуском терминал VS?
Если у вас возникли проблемы с запуском терминала, перейдите к руководству по устранению неполадок, где вы можете получить дополнительные инструкции.
Можно ли создать терминал администратора?
Обычно интегрированная оболочка запускается с разрешениями VS Code. Если целью является запуск оболочки с правами администратора или любым другим разрешением, используйте “runas.exe” и другие утилиты в терминале.
Упростите рабочий процесс с помощью терминала VS Code
Выполнение кода в терминале VS Code является эффективным и удобным, поскольку вам не нужно покидать редактор. Он упрощает все задачи разработки, и вы можете переключаться между выполнением кода и самим кодированием. В конечном итоге вы повысите производительность и сможете сосредоточиться на выполнении и отладке кода.
Вы пробовали запускать код в терминале VS Code? Каков был ваш опыт? Дайте нам знать в разделе комментариев ниже.
