- Visual Studio Code (Русский)
- Contents
- Установка
- Использование
- Конфигурация
- Встроенный терминал
- Внешний терминал
- Решение проблем
- Глобальное меню не работает в KDE Plasma
- Невозможно переместить объект в корзину
- Невозможно отладить C#
- Невозможно открыть .csproj с сервером OmniSharp, ошибка расположения Microsoft.Common.props
- OmniSharp не может обнаружить MSBuild
- «Повторить попытку в режиме Sudo» не работает
- remote-containers.openFolder не найдена
- VS Live Share missing API
- Установка Visual Studio Code в Linux
- Устанавливаем Visual Studio Code в Linux
- Способ 1: Использование репозиториев через консоль
- Способ 2: Скачивание официального DEB-пакета
- Visual Studio Code
- Contents
- Installation
- Usage
- Configuration
- Integrated Terminal
- External terminal
- Running natively under Wayland
- Troubleshooting
- Global menu not working in KDE/Plasma
- Unable to move items to trash
- Unable to debug C#
- Unable to open .csproj with OmniSharp server, invalid Microsoft.Common.props location
- Error from OmniSharp that MSBuild cannot be located
- Saving with «Retry as Sudo» does not work
- Keyboard variants or keymappings do not map
- Command «. » not found
- VS Live Share missing API
- Command ‘remote-containers.openFolder’ not found
- Command ‘GitHub Pull Requests: Configure Remotes. ‘ resulted in an error (command ‘pr.configureRemotes’ not found)
- Git: ssh_askpass: exec(/usr/lib/ssh/ssh-askpass): No such file or directory
- No extensions found
- Cutoff characters in integrated Terminal
- Blurry text under Wayland
- No such interface“org.freedesktop.Secret.Collection”
- Authentification with Github failed while using VSCodium
Visual Studio Code (Русский)
Перевод этой статьи или раздела не отражает оригинальное содержание.
Visual Studio Code — кроссплатформенный, бесплатный и свободный (используется лицензия MIT) текстовый редактор, разрабатываемый Microsoft. Он использует фреймворк Electron и поддерживает расширения, список которых можно найти на странице магазина расширений или в самом редакторе. Несмотря на то, что проект является открытым, Microsoft также распространяет проприетарные сборки с пользовательским соглашением (EULA), см. объяснение в репозитории GitHub.
Contents
Установка
Редактор VSCode доступен для установки с помощью следующих пакетов:
- code — свободная сборка
- visual-studio-code-binAUR — проприетарная сборка Microsoft
- visual-studio-code-insiders-binAUR — проприетарная сборка Microsoft с ежедневными обновлениями
- code-gitAUR — свободная сборка (нестабильная версия для разработчиков)
- vscodium-binAUR — свободная сборка со стандартной конфигурацией, поддерживаемой сообществом
Утилита ptvsd (Python Tools for Visual Studio Debug) предоставляется пакетом python-ptvsd AUR .
Использование
Запустите командой code ( code-git для пакета code-git AUR ).
Если требуется запустить несколько экземпляров приложения, добавьте ключ -n без параметров.
Конфигурация
Пакет code хранит конфигурацию в файле
Пакет visual-studio-code-bin AUR хранит конфигурацию в файле
Встроенный терминал
Меню Вид > Терминал или Ctrl + ` открывает встроенный терминал. По умолчанию используется Bash без каких-либо параметров, но настройки, указанные далее позволяют изменить данное взаимодействие.
- terminal.integrated.shell.linux устанавливает терминал по умолчанию
- terminal.integrated.shellArgs.linux устанавливает передаваемые в терминал аргументы
Например, установить по умолчанию fish с параметрами.
Вы можете столкнуться со странными запросами при установке встроенного терминала, удалением некоторых строк, поэтому рекомендуется либо не использовать аргументы, либо использовать внешний терминал.
Внешний терминал
Если вы используете Terminator как терминал по умолчанию, у вас могут возникнуть проблемы в VS Code с ошибками вида: Unable to launch debugger worker process (vsdbg) through the terminal. spawn truecolor ENOENT , поэтому следует сменить терминал на другой, например, gnome-terminal .
Строка настроек «terminal.external.linuxExec»: «имя терминала» установит терминал на требуемый. Пример установки gnome-terminal :
Решение проблем
Глобальное меню не работает в KDE Plasma
Visual Studio Code использует D-Bus для меню, поэтому для него следует установить пакет libdbusmenu-glib .
Невозможно переместить объект в корзину
По умолчанию все приложения, использующие Electron, используют gio (из пакета glib2 ) для удаления. Конфигурирование утилиты происходит через установку переменной окружения ELECTRON_TRASH .
Однако, в новых версиях Electron поддерживает и kioclient5 , и kioclient , и trash-cli , и gio (по умолчанию), и gvfs-trash (отмечен устаревшим). Смотрите также страницу environment-variables в GitHub репозитории Electron.
Невозможно отладить C#
Для отладки приложений на C# (платформа .NET) испольуется расширение OmniSharp, которое требует проприетарный компонент .NET Core Debugger (смотри пакеты в разделе установка). Смотри также объяснение в репозитории GitHub.
Если вы используете свободный пакет, отладка упадёт почти незаметно, лишь оставив в консоли сообщение:
Для отладки в свободном пакете можно использовать пакет netcoredbg AUR . Чтобы использовать его для отладки проектов, требуется в настройке проекта указать соответствующую конфигурацию, например:
Невозможно открыть .csproj с сервером OmniSharp, ошибка расположения Microsoft.Common.props
Требуется сменить путь к SDK. Вот, как выглядит файл до изменений.
Вот, как выглядит файл после изменения.
OmniSharp не может обнаружить MSBuild
На странице OmniSharp introduction в GitHub написано, что пользователям Arch Linux требуется установить mono-msbuild . Ошибка, которая появляется при отсутствии пакета:
Возможно, потребуется собрать пакет самостоятельно.
«Повторить попытку в режиме Sudo» не работает
К сожалению, пакет code не поддерживает эту функцию в полной мере, так как официально Microsoft не поддерживает пакет для Arch Linux. Смотри также FS#61516 или тикет на GitHub.
remote-containers.openFolder не найдена
Для решения проблемы требуется открыть VS Code со включённым API remote-containers (см. баг FS#63374)
VS Live Share missing API
Пакет code не имеет некоторых API, которые нужны для работы расширения Live Share. Вот ошибка, которая появляется при такой проблеме:
Следуя инструкции на Microsoft Docs, есть разные решения:
Источник
Установка Visual Studio Code в Linux
Каждому программисту нужно иметь удобное приложение, в котором он будет набирать и редактировать исходный код. Visual Studio Code — одно из лучших решений, распространяемое как на Windows, так и на операционные системы на ядре Linux. Инсталляция упомянутого редактора может производиться разными методами, каждый из которых будет наиболее оптимальным для определенного класса пользователей. Давайте сегодня остановимся на этой процедуре и разберемся со всеми действиями максимально подробно.
К сожалению, интегрированная среда разработки под названием Visual Studio доступна только для ПК под управлением ОС Windows. Следует сразу обратить внимание, что в этой статье мы показываем, как загрузить редактор исходного кода Visual Studio Code — одно из решений в линейке VS.
Устанавливаем Visual Studio Code в Linux
Конечно, дистрибутивов, написанных на ядре Linux, достаточно много. Однако сейчас особой популярностью пользуются ОС, за основу которых взят Debian либо Ubuntu. Именно на такие платформы мы и хотим обратить внимание, взяв для наглядности Ubuntu 18.04. Обладателям других дистрибутивов мы тоже подскажем, каким образом лучше всего будет произвести установку, однако давайте начнем по порядку.
Способ 1: Использование репозиториев через консоль
Компания Microsoft активно следит за своими официальными хранилищами. Последние версии программ туда оперативно выкладываются и пользователи сразу же могут скачать их и без каких-либо проблем инсталлировать на свой компьютер. Что же касается Visual Studio Code, здесь следует рассмотреть варианты с использованием двух разных репозиториев. Взаимодействие с первым выглядит следующим образом:
- Запустите «Терминал» через Ctrl + Alt + T или воспользуйтесь соответствующей иконкой в меню.
Пропишите команду sudo snap install —classic vscode для загрузки и установки VS из официального хранилища.
Подтвердите подлинность учетной записи, введя свой пароль для рут-доступа.
По завершении установки вы получите уведомление и можно будет сразу же запустить программу, введя vscode .
Теперь вам доступно взаимодействие с графическим интерфейсом интересующего редактора. В меню был создан значок, через который также запускается VS.
Однако не каждому пользователю подходит метод инсталляции через представленный репозиторий, поэтому советуем ознакомиться с альтернативным вариантом, который не сложнее рассмотренного.
- Откройте «Терминал» и в первую очередь обновите системные библиотеки путем ввода sudo apt update .
Далее следует установить зависимости, используя sudo apt install software-properties-common apt-transport-https wget .
Подтвердите добавление новых файлов, выбрав правильный вариант.
Инсталлируйте ключ Microsoft GPG, который играет роль шифрования электронных подписей через wget -q https://packages.microsoft.com/keys/microsoft.asc -O- | sudo apt-key add — .
Затем завершите добавление, вставив строку sudo add-apt-repository «deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main» .
Осталось только установить саму программу, написав sudo apt install code .
Запуск Visual Studio Code, добавленной в систему таким образом, выполняется через команду code .
Способ 2: Скачивание официального DEB-пакета
Не всем юзерам порой удобно работать через консоль или могут возникнуть какие-то трудности с командами. К тому же иногда на компьютере отсутствует подключение к интернету. В этих случаях на помощь приходит официальный DEB-пакет, который вы можете предварительно загрузить на носитель и уже на своем ПК установить VS Code.
- Перейдите по указанной выше ссылке и скачайте DEB-пакет необходимой вам программы.
Откройте папку, куда была произведена загрузка, и запустите ее.
Начните установку через «Менеджер приложений».
Подтвердите свою учетную запись вводом пароля.
По окончании инсталляции найти значок запуска программы можно через меню, воспользовавшись поиском.
Если же появилась надобность в добавлении обновлений к рассматриваемому софту, откройте консоль и поочередно вводите следующие команды:
sudo apt-get install apt-transport-https
sudo apt-get update
sudo apt-get install code
Что касается пользователей, использующих дистрибутивы, разработанные на основе RHEL, Fedora или CentOS, вам следует использовать указанные ниже строки, чтобы провести инсталляцию программы.
sudo rpm —import https://packages.microsoft.com/keys/microsoft.asc
sudo sh -c ‘echo -e «[code]\nname=Visual Studio Code\nbaseurl=https://packages.microsoft.com/yumrepos/vscode\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc» > /etc/yum.repos.d/vscode.repo’
Обновление пакетов осуществляется путем указания dnf check-update , а затем sudo dnf install code .
Существуют обладатели и ОС на openSUSE and SLE. Здесь код немного меняется:
sudo rpm —import https://packages.microsoft.com/keys/microsoft.asc
sudo sh -c ‘echo -e «[code]\nname=Visual Studio Code\nbaseurl=https://packages.microsoft.com/yumrepos/vscode\nenabled=1\ntype=rpm-md\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc» > /etc/zypp/repos.d/vscode.repo’
Обновление же производится через последовательную активацию sudo zypper refresh и sudo zypper install code
Теперь вы ознакомлены с методами установки Visual Studio Code на разные дистрибутивы ядра Linux. Если же вы столкнулись с какими-либо проблемами или неполадками, обязательно сначала ознакомьтесь с текстом ошибки, изучите официальную документацию операционной системы, а также оставляйте вопросы в комментариях.
Помимо этой статьи, на сайте еще 12315 инструкций.
Добавьте сайт Lumpics.ru в закладки (CTRL+D) и мы точно еще пригодимся вам.
Отблагодарите автора, поделитесь статьей в социальных сетях.
Источник
Visual Studio Code
Visual Studio Code is a cross-platform proprietary text editor (licensed under an End-User License Agreement) developed by Microsoft, built on top of a free and open-source project named Codium (licensed under the MIT License), written in JavaScript and TypeScript – the relationship between Codium and Visual Studio Code is more or less the same as the one between Chromium and Google Chrome; for an explanation of the mixed licensing, see this GitHub comment. Visual Studio Code is built on the Electron framework and is extensible using extensions, which can be browsed on the web or from within the text editor itself.
Contents
Installation
The following packages provide VSCode:
- code (open-source release)
- code-gitAUR (in-development open-source version)
- visual-studio-code-binAUR (Microsoft-branded release)
- visual-studio-code-insiders-binAUR (Microsoft-branded release, updated daily)
- vscodium-binAUR (community-driven fully open-source version of VSCode, with all Microsoft telemetry stripped out — latest release, binary package)
- vscodiumAUR (community-driven fully open-source version of VSCode, with all Microsoft telemetry stripped out — latest release, git build)
- vscodium-gitAUR (community-driven fully open-source version of VSCode, with all Microsoft telemetry stripped out — latest commit on branch master, git build)
The Microsoft ptvsd (Python Tools for Visual Studio Debug) server/module is available at python-ptvsd AUR .
Usage
Run code to start the application (or if you are using other releases, run code-git for code-git AUR or codium for vscodium-bin AUR / vscodium AUR / vscodium-git AUR ).
If for any reason you wish to launch multiple instances of Visual Studio Code, the -n flag can be used.
Configuration
code stores settings in
vscodium AUR and related packages store their settings in
When migrating from Code to Codium (or vice versa), the settings directory can be copied or moved, since they share most of their codebase, the settings are compatible.
Integrated Terminal
View > Integrated Terminal or Ctrl + ` opens up an integrated terminal. By default, Bash is used with no additional arguments, although this can be changed. terminal.integrated.shell.linux sets the default shell to be used and terminal.integrated.shellArgs.linux sets the arguments to be passed to the shell.
You might face weird prompts after setting the integrated shell arguments with external terminal, remove the line to solve the problem or use an external terminal.
External terminal
If you are using Terminator as default terminal for Arch and you have an error on Visual Studio Code: Unable to launch debugger worker process (vsdbg) through the terminal. spawn truecolor ENOENT , you can change the terminal that will be used by Visual Studio to another terminal (e.g. gnome-terminal ).
«terminal.external.linuxExec»: «Your alternative terminal» sets the default terminal to be used for exec debug.
Running natively under Wayland
If you are using a Wayland-based WM or DE, you can force Visual Studio Code to run natively under Wayland (instead of under XWayland) by adding command-line options —enable-features=UseOzonePlatform —ozone-platform=wayland . For example, you can try launching VSCode using
These options can be automatically applied every time Visual Studio Code is launched by adding them to the file $
Troubleshooting
Global menu not working in KDE/Plasma
Visual Studio Code uses DBus to pass the menu to Plasma, try installing libdbusmenu-glib .
Unable to move items to trash
By default, Electron apps use gio to delete files. kioclient5 is automatically selected instead if Plasma is detected. Different trash implementations can be used by setting the ELECTRON_TRASH environment variable.
For example, for deleting files using trash-cli :
At the time of writing, Electron supports kioclient5 , kioclient , trash-cli , gio (default) and gvfs-trash (deprecated). More info is available at this documentation page.
Unable to debug C#
If you want to debug C#.NET (using the OmniSharp extension) then you need to install the Microsoft branded release (from the AUR). This is apparently because the .NET Core debugger is only licensed to be used with official Microsoft products — see this github discussion.
When using the open-source package, debugging fails fairly quietly. The debug console will just show the initial message:
For debugging with the open-source package netcoredbg AUR can be used. To run it in VS Code, add this configuration to .NET Core launch configuration of the project:
Unable to open .csproj with OmniSharp server, invalid Microsoft.Common.props location
You have to switch from mono to proper SDK version props.
Modify import to look like this:
Error from OmniSharp that MSBuild cannot be located
It is noted in the OmniSharp introduction that Arch Linux users should install the mono-msbuild package. Without it, you might get an error like:
You might be able to build anyway (possibly depending whether you have mono installed too).
Omnisharp ships with its own mono version, so, if it is unable to locate the installed one, if you want to tell omnisharp to look for a «global» mono installed in your machine, put this in your settings.json:
Saving with «Retry as Sudo» does not work
This feature does not work in the code package, because Microsoft does not support the way the Arch package is packaged (native instead of bundled Electron). See FS#61516 and the upstream bug report for more information.
The binary release visual-studio-code-bin AUR does not have this issue, and the feature works there.
Keyboard variants or keymappings do not map
Switching keyboard layouts under some Linux window managers does not result in a change in the low level X window APIs VS Code uses to read the current keyboard layout. This means that VS Code ends up sometimes reading one of the other configured keyboard layouts and not the current active one. PR welcome.
Per the wiki, there are two possible solutions:
- make sure setxkbmap -query returns as the first keyboard layout the one you want to work with in VS Code.
- use «keyboard.dispatch»: «keyCode» in your settings and restart VS Code. This will prevent VS Code from trying to determine your keyboard layout whatsoever.
Command «. » not found
In the official build of VS Code, a product.json file lists the extensions that are allowed to use certain proposed APIs accessed by extensions. However, the product.json is absent in the OSS build code . [1]
In the related issues below, some flags may be required to enable certain APIs. [2] You may either run code with these flags, or you can add the relevant entries to the extensionAllowedProposedApi section in the product.json file ( code installs this to /usr/lib/code/product.json ).
This can also be resolved by installing the code-features AUR package, which installs a pacman hook that patches the file on every package update. Alternatively, you may also consider installing the Microsoft branded packages: visual-studio-code-bin AUR , visual-studio-code-insiders-bin AUR .
VS Live Share missing API
Use either the solution above by editing the product.json , or open VS Code with:
Command ‘remote-containers.openFolder’ not found
Open VS Code enabling remote-containers API as commented in FS#63374:
Command ‘GitHub Pull Requests: Configure Remotes. ‘ resulted in an error (command ‘pr.configureRemotes’ not found)
Open VS Code with:
Git: ssh_askpass: exec(/usr/lib/ssh/ssh-askpass): No such file or directory
This error is a result of an encrypted ssh-key, and can be solved by installing a dialogue provider like SSH keys#x11-ssh-askpass or the alternatives listed there like ksshaskpass for KDE.
One thing to note is that for e.g. ksshaskpass you would need to link it from /usr/lib/ssh/ssh-askpass to get VSCode to find it:
No extensions found
There exist several differences between «vscode» (open-source) and «Visual Studio Code» (Microsoft product based on vscode), see: Differences between the repository and Visual Studio Code. The usage of Microsoft marketplace for extensions is restricted to products of the Visual Studio Code’s family. Consequently, it cannot be used by vscode (see FS#67780). The code and vscodium-bin AUR / vscodium AUR / vscodium-git AUR packages are configured to use the Open VSX registry instead of the Microsoft one. This explains why some extensions are missing from the vscode explorer while they appear to be listed online.
The workaround is to either install the visual-studio-code-bin AUR package instead, manually download and install the .vsix file from the web marketplace page, or ask the maintainer to upload its extension to OpenVSX.
Technically, one could also edit the product.json as shown in this Github comment, but that would not comply with the Microsoft Marketplace Terms of Use. Additionally, the changes would be overwritten during package update. This can be overcome by installing code-marketplace AUR / vscodium-bin-marketplace AUR / vscodium-marketplace AUR package, which installs a pacman hook that patches the file on every package update.
Cutoff characters in integrated Terminal
Characters that are too wide can end up clipping. For example the italic bold text of Deno stack-traces.
This can be avoided by setting «terminal.integrated.rendererType» to «experimentalWebgl».
Blurry text under Wayland
Visual Studio Code defaults to run under XWayland, which may cause blurry text if you are using HiDPI screens. To fix this issue, try forcing Electron to run under Wayland—see #Running natively under Wayland.
No such interface“org.freedesktop.Secret.Collection”
Authentification with Github failed while using VSCodium
When connecting a Github account, change «vscodium» to «vscode» in the URL as seen in this comment. Then copy the identification token into VSCodium. Should it still fail, install a keyring like gnome-keyring or create a new keyring as mentioned here in the Visual Studio Code docs and here on Github.
Источник