Virtual studio для linux

Visual Studio Code on Linux

Installation

See the Download Visual Studio Code page for a complete list of available installation options.

By downloading and using Visual Studio Code, you agree to the license terms and privacy statement.

Debian and Ubuntu based distributions

The easiest way to install Visual Studio Code for Debian/Ubuntu based distributions is to download and install the .deb package (64-bit), either through the graphical software center if it’s available, or through the command line with:

Note that other binaries are also available on the VS Code download page.

Installing the .deb package will automatically install the apt repository and signing key to enable auto-updating using the system’s package manager. Alternatively, the repository and key can also be installed manually with the following script:

Then update the package cache and install the package using:

RHEL, Fedora, and CentOS based distributions

We currently ship the stable 64-bit VS Code in a yum repository, the following script will install the key and repository:

Then update the package cache and install the package using dnf (Fedora 22 and above):

Or on older versions using yum :

Due to the manual signing process and the system we use to publish, the yum repo may lag behind and not get the latest version of VS Code immediately.

Visual Studio Code is officially distributed as a Snap package in the Snap Store:

You can install it by running:

Once installed, the Snap daemon will take care of automatically updating VS Code in the background. You will get an in-product update notification whenever a new update is available.

Note: If snap isn’t available in your Linux distribution, please check the following Installing snapd guide, which can help you get that set up.

Learn more about snaps from the official Snap Documentation.

openSUSE and SLE-based distributions

The yum repository above also works for openSUSE and SLE-based systems, the following script will install the key and repository:

Then update the package cache and install the package using:

AUR package for Arch Linux

To get more information about the installation from the AUR, please consult the following wiki entry: Install AUR Packages.

Nix package for NixOS (or any Linux distribution using Nix package manager)

There is a community maintained VS Code Nix package in the nixpkgs repository. In order to install it using Nix, set allowUnfree option to true in your config.nix and execute:

Installing .rpm package manually

The VS Code .rpm package (64-bit) can also be manually downloaded and installed, however, auto-updating won’t work unless the repository above is installed. Once downloaded it can be installed using your package manager, for example with dnf :

Note that other binaries are also available on the VS Code download page.

Updates

VS Code ships monthly and you can see when a new release is available by checking the release notes. If the VS Code repository was installed correctly, then your system package manager should handle auto-updating in the same way as other packages on the system.

Note: Updates are automatic and run in the background for the Snap package.

Node.js

Node.js is a popular platform and runtime for easily building and running JavaScript applications. It also includes npm, a Package Manager for Node.js modules. You’ll see Node.js and npm mentioned frequently in our documentation and some optional VS Code tooling requires Node.js (for example, the VS Code extension generator).

If you’d like to install Node.js on Linux, see Installing Node.js via package manager to find the Node.js package and installation instructions tailored to your Linux distribution. You can also install and support multiple versions of Node.js by using the Node Version Manager.

To learn more about JavaScript and Node.js, see our Node.js tutorial, where you’ll learn about running and debugging Node.js applications with VS Code.

Setting VS Code as the default text editor

xdg-open

You can set the default text editor for text files ( text/plain ) that is used by xdg-open with the following command:

Debian alternatives system

Debian-based distributions allow setting a default editor using the Debian alternatives system, without concern for the MIME type. You can set this by running the following and selecting code:

Читайте также:  Setting domain in linux

If Visual Studio Code doesn’t show up as an alternative to editor , you need to register it:

Windows as a Linux developer machine

Another option for Linux development with VS Code is to use a Windows machine with the Windows Subsystem for Linux (WSL).

Windows Subsystem for Linux

With WSL, you can install and run Linux distributions on Windows. This enables you to develop and test your source code on Linux while still working locally on a Windows machine. WSL supports Linux distributions such as Ubuntu, Debian, SUSE, and Alpine available from the Microsoft Store.

When coupled with the Remote — WSL extension, you get full VS Code editing and debugging support while running in the context of a Linux distro on WSL.

See the Developing in WSL documentation to learn more or try the Working in WSL introductory tutorial.

Next steps

Once you have installed VS Code, these topics will help you learn more about it:

  • Additional Components — Learn how to install Git, Node.js, TypeScript, and tools like Yeoman.
  • User Interface — A quick orientation to VS Code.
  • User/Workspace Settings — Learn how to configure VS Code to your preferences through settings.

Common questions

Azure VM Issues

I’m getting a «Running without the SUID sandbox» error?

You can safely ignore this error.

Debian and moving files to trash

If you see an error when deleting files from the VS Code Explorer on the Debian operating system, it might be because the trash implementation that VS Code is using is not there.

Run these commands to solve this issue:

Conflicts with VS Code packages from other repositories

Some distributions, for example Pop!_OS provide their own code package. To ensure the official VS Code repository is used, create a file named /etc/apt/preferences.d/code with the following content:

«Visual Studio Code is unable to watch for file changes in this large workspace» (error ENOSPC)

When you see this notification, it indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. Before adjusting platform limits, make sure that potentially large folders, such as Python .venv , are added to the files.watcherExclude setting (more details below). The current limit can be viewed by running:

The limit can be increased to its maximum by editing /etc/sysctl.conf (except on Arch Linux, read below) and adding this line to the end of the file:

The new value can then be loaded in by running sudo sysctl -p .

While 524,288 is the maximum number of files that can be watched, if you’re in an environment that is particularly memory constrained, you may want to lower the number. Each file watch takes up 1080 bytes, so assuming that all 524,288 watches are consumed, that results in an upper bound of around 540 MiB.

Arch-based distros (including Manjaro) require you to change a different file; follow these steps instead.

Another option is to exclude specific workspace directories from the VS Code file watcher with the files.watcherExclude setting. The default for files.watcherExclude excludes node_modules and some folders under .git , but you can add other directories that you don’t want VS Code to track.

I can’t see Chinese characters in Ubuntu

We’re working on a fix. In the meantime, open the application menu, then choose File > Preferences > Settings. In the Text Editor > Font section, set «Font Family» to Droid Sans Mono, Droid Sans Fallback . If you’d rather edit the settings.json file directly, set editor.fontFamily as shown:

Package git is not installed

This error can appear during installation and is typically caused by the package manager’s lists being out of date. Try updating them and installing again:

The code bin command does not bring the window to the foreground on Ubuntu

Running code . on Ubuntu when VS Code is already open in the current directory will not bring VS Code into the foreground. This is a feature of the OS which can be disabled using ccsm .

Under General > General Options > Focus & Raise Behaviour, set «Focus Prevention Level» to «Off». Remember this is an OS-level setting that will apply to all applications, not just VS Code.

Cannot install .deb package due to «/etc/apt/sources.list.d/vscode.list: No such file or directory»

This can happen when sources.list.d doesn’t exist or you don’t have access to create the file. To fix this, try manually creating the folder and an empty vscode.list file:

Cannot move or resize the window while X forwarding a remote window

If you are using X forwarding to use VS Code remotely, you will need to use the native title bar to ensure you can properly manipulate the window. You can switch to using it by setting window.titleBarStyle to native .

Using the custom title bar

The custom title bar and menus were enabled by default on Linux for several months. The custom title bar has been a success on Windows, but the customer response on Linux suggests otherwise. Based on feedback, we have decided to make this setting opt-in on Linux and leave the native title bar as the default.

The custom title bar provides many benefits including great theming support and better accessibility through keyboard navigation and screen readers. Unfortunately, these benefits do not translate as well to the Linux platform. Linux has a variety of desktop environments and window managers that can make the VS Code theming look foreign to users. For users needing the accessibility improvements, we recommend enabling the custom title bar when running in accessibility mode using a screen reader. You can still manually set the title bar with the Window: Title Bar Style ( window.titleBarStyle ) setting.

Читайте также:  Chemdraw для windows 10

Broken cursor in editor with display scaling enabled

Due to an upstream issue #14787 with Electron, the mouse cursor may render incorrectly with scaling enabled. If you notice that the usual text cursor is not being rendered inside the editor as you would expect, try falling back to the native menu bar by configuring the setting window.titleBarStyle to native .

Repository changed its origin value

If you receive an error similar to the following:

Use apt instead of apt-get and you will be prompted to accept the origin change:

Источник

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

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

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

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

Установка Visual Studio Code

Mac OS X

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

Linux

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

Windows

Совет: если вы хотите чтобы Visual Studio Code стартовал из терминала сделайте logon/logoff, соответствующие пути к файлу прописываются в переменной PATH самим установщиком

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

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

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

Начало работы

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

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

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

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

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

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

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

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

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

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

Каждый раз когда вы запускаете VS Code будет загружено последнее состояние основных элементов.

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

Совет: Вы можете переместить сайдбар слева на право с помощью меню View, Move Sidebar а так же включить его видимость с помощью клавиатуры (Ctrl+B).

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

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

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

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

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

Обозреватель

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

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

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

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

Поиск

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

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

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

Подсказки IntelliSence

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Отладка

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

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

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

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

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

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

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

Совет: установите credential helper для того чтобы не получать постоянные запросы на ввод данных учетной записи https://help.github.com/articles/caching-your-github-password-in-git/

Конфликты

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

Источник

Оцените статью