Visual studio code on windows

Editor

Source Code Folding

The editor now contains a first implementation of code folding. You can turn the feature on and off with the configuration setting (File > Preferences > Settings). Once enabled, you can collapse and expand code regions using the folding icons next to the line numbers. Regions that can be folded are shown with a icon, regions that are already folded with the icon. The icon only shows when the mouse is over the gutter.

Additionally you can use the following commands from the commands menu (F1) or with keyboard shortcuts:

  • Fold (⌥⌘[ (Windows, Linux Ctrl+Shift+[)) folds the innermost uncollapsed region at the cursor
  • Unfold (⌥⌘] (Windows, Linux Ctrl+Shift+])) unfolds the collapsed region at the cursor
  • Fold All (⌘K ⌘0 (Windows, Linux Ctrl+K Ctrl+0)) folds all region in the editor
  • Unfold All (⌘K ⌘J (Windows, Linux Ctrl+K Ctrl+J)) unfolds all regions in the editor

The folding regions are evaluated solely based on the indentation of each line. This first version does not yet support language agnostic folding regions, or folding markers. This is in discussion for an upcoming release (see issue #3422).

IntelliSense Performance

The IntelliSense widget underwent a full rewrite to address some performance problems. It now handles lists of 20,000 extensions in milliseconds, compared to the previous ~10 seconds of lag.

Indentation

Initiated by user request #1228, we have added indentation status in the editor to help with ‘tabs to spaces’ conversion and vice versa. The Status Bar shows whether the Tab key will insert spaces or tabs and the current indentation size in characters.

You can adjust the indentation size and toggle between tabs and spaces with three new actions:

Ruler Settings

There is a new setting available. For example, setting it to will display two vertical rulers in the editor, one after the 80th character and one after the 120th character.

Default End of Line Sequence

A new setting controls the default new line character when creating new files. It defaults to on Windows and to on Linux and OS X.

Word navigation and word separators

Word navigation and word deletion commands updated and now honor a new setting, , when deciding what is a word, regardless of the current language of the file.

Improved usage of web workers

With the adoption of the Salsa JavaScript language service as the default, we could streamline our usage of web workers and now have a dedicated web worker that is language agnostic, which we use for diff computation, link detection or simple textual completions. This reduces the latency of these computations and is memory friendly, as it automatically shuts down when not needed.

Performance

Performance is key to an editor and during November we fixed almost 50 performance-related issues. We spent significant time in the profiler and revisited the initialization phase of VS Code. Improving performance is not just about optimizing algorithms but also about improving perceived performance for the user. We began thinking about the startup life-cycle phases (#38080) to better order the creation of our components for faster perceived startup (for instance, always try to show a blinking cursor in the editor). To learn more about our performance work, you can review our issues labeled with perf-startup, perf-bloat (source code reduction), or perf.

Finally here are some noteworthy optimizations we’d like to mention:

  • Improve startup and overall performance with an improved configuration-model #37426, #37539.
  • Improve startup by caching extension information from files #28331.
  • Improve startup by delaying the creation of helper processes, like file watcher #38230, search app #38235, and extensions process #38323.
  • Improve file loading for better startup performance #37541.
  • Use the faster list widget instead of the tree when possible #38638. Rework the BREAKPOINTS view and the OPEN EDITORS Explorer section.
  • Optimize the handling of touch events for improved performance #37917.
  • Improve the overall workbench performance by skipping unnecessary layouts and computations , #39185, #38966, #38963, #38962, #38960.
  • Improve startup by removing unused code #38414.

And we are not done. Performance is a constant theme of the whole development team. Track our work with the perf-labels and don’t be shy in filing performance related issues.

Настраиваем расширения

Ниже приведен список расширений, которые нам понадобятся для правильной настройки VS Code. Откройте VS Code и перейдите на панель расширений (Ctrl + Shift + X), которая находится на левой панели инструментов, и начните загружать друг за другом следующие расширения:

C / C++ от Microsoft —  Для корректной работы этого расширения нам понадобится установленный и добавленный в PATH компилятор MinGW. Если у вас его нет, следуйте этому руководству.

C++ Intellisense от austin.

Python от Microsoft — вам нужно будет настроить Python для работы этого расширения

Загрузите и установите последнюю версию отсюда.

Java Extension Pack от Microsoft —  Перед установкой убедитесь, что в вашей системе настроены Java 8 JDK и JRE и указаны все необходимые переменные среды для Java. Если нет, посмотрите это видео о том, как настроить Java на вашем компьютере.

Code Runner от Jun Han — мы будем использовать это расширение для запуска всех наших программ. Для этого необходимо выполнить некоторые шаги по настройке. Мы увидим эти шаги в следующих разделах.

Расширения, перечисленные ниже, необязательны для дальнейшей настройки, но я рекомендую вам обратить на них внимание, посмотреть, заинтересуют ли они вас, и если нет, то перейти к следующему разделу. (Необязательно)Material Theme от Mattia Astronio — это расширение содержит множество приятных глазу тем

Вы можете выбрать любую, какая понравится. Лично я предпочитаю Monokai, которая доступна в VS Code по умолчанию, без каких-либо расширений

(Необязательно)Material Theme от Mattia Astronio — это расширение содержит множество приятных глазу тем. Вы можете выбрать любую, какая понравится. Лично я предпочитаю Monokai, которая доступна в VS Code по умолчанию, без каких-либо расширений.

Чтобы выбрать тему, нажмите Ctrl + Shift + P. Откроется палитра команд. Осуществите поиск по слову “theme” и выберите опцию Color Theme. Чтобы настроить иконки, можете выбрать опцию File Icon Theme.

Расширения для тех, кто интересуется FrontEnd-фреймворками для веб-разработки, такими как Angular и React:

  • (Необязательно) Angular Language Service от Angular.
  • (Необязательно) Angular Snippets от John Papa.
  • (Необязательно) ES7 React / Redux / GraphQL / React-Native snippets от dsznajder.
  • (Необязательно) React Native Tools от Microsoft.
  • (Необязательно) Live Server от Ritwick Dey.

Integrated Terminal

Fallback DOM renderer

Back in the 1.17 release, the Integrated Terminal changed to rendering using canvas in order to boost performance. While this was great for the majority of users, some environments had issues with this at either the hardware and OS levels and rendering ended up taking longer. VS Code now measures the average time it takes to render a frame and if it takes too long, you will get a notification to switch to the new fallback DOM renderer:

This new renderer uses the DOM like the original terminal, so if your environment has issues rendering with canvas, this should provide a more stable experience. You can also turn on the DOM renderer manually with this setting:

The terminal now supports the italicized xterm character attribute:

Better CLI support in WSL

Running the command line inside the Windows Subsystem for Linux (WSL) will now suppress output and return to the prompt.

Navigation to split terminals using the Quick Open menu

JSX Support

To improve the JavaScript and JSX support, the plan is to adopt Salsa. There is good progress on the Salsa project, but until VS Code has switched over to Salsa, we can only offer a workaround for using VS Code with JSX.

Install the vscode-eslint extension and configure JSX support. This will provide you with validation in JSX files.

If you are using React constructs inside .js files then you can install the js-is-jsx extension which changes the file mapping so that .js files are treated as .jsx files. Be aware that if you install this extension, you lose the existing language support for .js files.

The grammars used to colorize JS and JSX are now aligned.

Параметры заменыReplacement parameters

Возможно, вам нужно предоставить пользователю возможность заменять части фрагмента кода.You may want parts of a code snippet to be replaced by the user. Например, может потребоваться, чтобы пользователь заменил имя переменной на используемое в текущем проекте.For example, you might want the user to replace a variable name with one in their current project. Возможны два типа замен: литералы и объекты.You can provide two types of replacements: literals and objects. используется для определения замещающего элемента для отрывка кода, который полностью заключен во фрагмент, но, скорее всего, будет изменен после вставки в код (например, строка или числовое значение).Use the to identify a replacement for a piece of code that is entirely contained within the snippet but will likely be customized after it’s inserted into the code (for example, a string or numeric value). используется для определения элемента, который необходим во фрагменте кода, но, скорее всего, будет определен вне самого фрагмента (например, экземпляр объекта или элемент управления).Use the to identify an item that’s required by the code snippet but is likely to be defined outside of the snippet itself (for example, an object instance or a control).

Чтобы пользователь мог легко заменить число, квадратный корень которого требуется вычислить, измените элемент Snippet в файле SquareRoot.snippet следующим образом:To enable the user to easily replace the number to calculate the square root of, modify the Snippet element of the SquareRoot.snippet file as follows:

Обратите внимание, что замещающему литералу назначен идентификатор ().Notice that the literal replacement is given an ID (). На этот идентификатор указывает ссылка в фрагменте кода путем заключения его в символы :That ID is referenced from within the code snippet by surrounding it with characters:

Сохраните файл фрагмента.Save the snippet file.

Откройте проект и вставьте фрагмент.Open a project and insert the snippet.
После вставки фрагмента кода редактируемый литерал выделяется для замены.The code snippet is inserted and the editable literal is highlighted for replacement

Наведите указатель мыши на замещающий параметр, чтобы увидеть подсказку для значения.Hover over the replacement parameter to see the tooltip for the value.

Совет
Если в фрагменте имеется несколько заменяемых параметров, можно нажать клавишу TAB, чтобы переходить от одного к другому для изменения значений.If there’s more than one replacable parameter in a snippet, you can press Tab to navigate from one to the other to change the values.

Preview: Multi Root Workspaces

We continued working on support for opening multiple folders in a single VS Code window (instance) (issue #396). There was a preview of this feature in our last releases (see , and ).

During this milestone, we focused on making the transition into a workspace work without a window reload and introduced more APIs for extensions to better support multi-root workspaces.

Enter a workspace without window reload

Previously we required a full window reload when creating or saving workspaces or when adding folders to a workspace. We no longer require this window reload making the multi-root experience a lot smoother.

Extension recommendations

We extended the support of extension recommendations to multi-root workspaces. Extension recommendations from all root folders are consolidated and shown. You can also configure recommendations for the multi-root workspace itself using the command Extensions: Configure Recommended Extensions (Workspace). This will open the workspace configuration file and you can enter the recommendations under a section.

New API: Workspace Folder Picker

With the advent of multi-root support in VS Code, we noticed that often an extension wants to ask the user for a specific . The new proposed API method opens a picker and returns the result.

New API: RelativePattern

To make it easier to filter file paths to a specific , we added a new type and support it in the following places:

The type is a class as follows:

You can create a relative pattern via the following call:

When a is used, file paths will be matched relative to the base path of the pattern. For example, given a base path of and a file path of , the pattern within will match on .

Smarter workspace file format saving

When saving the workspace file back to disk upon changes, we will now prefer to use forward slashes for paths on Windows in case the file is already using slashes. This should make it easier to share workspace files between Windows and other platforms.

In addition, we now preserve any comments within the workspace file. Even though JSON does not allow for comments inside the file, we now use the same JSON parser that we use for VS Code settings which allows for comments and is also more error tolerant. For example, trailing commas will not render the workspace file as invalid anymore.

Workspace folder name

You can now assign a property to each of the folders within the configuration file. The name will be picked up in the Explorer and can be used to distinguish multiple workspace folders that have the same basename.

Запуск системы Visual Studio 2013

При запуске на экране появится заставка Microsoft Visual Studio 2013. Как и большинство заставок, она содержит информацию о версии продукта и обладателе лицензии.

При первом запуске системы Visual Studio 2013 заставка будет отображаться в течение нескольких секунд, а затем будет открыто с окно с предложением войти в систему, используя учетную запись Microsoft:

После этого вы получите приглашение выбрать установки среды по умолчанию. На первый взгляд, довольно странно спрашивать людей, которые еще не использовали продукт, как они собираются с ним работать. Тем не менее, поскольку компания Microsoft объединила большое количество языков и технологий в единой среде разработке, эта среда должна учитывать незначительные (а иногда и заметные) различия между разработчиками.

Если вы остановите свое внимание на разных опциях, перечисленных в этом списке, то увидите, что параметры среды, которые можно изменить, включают в себя положение и внешний вид разных окон, меню, панелей инструментов и даже «горячие» клавиши. Например, если в качестве установки по умолчанию вы выберете опцию General, то на экране будут описаны изменения, которые произойдут в этом случае

Позже мы покажем процедуру изменения установок среды, принятых по умолчанию, на более поздних этапах работы.

Если вы ранее разрабатывали программы на языке Visual Basic .NET и теперь переходите на новую версию системы Visual Studio, то не используйте опцию Visual Basic. Эта опция предназначена для разработчиков, использующих среду VB6, и просто приведет в ярость разработчиков, использующих язык Visual Basic .NET, поскольку они будут использовать разные «горячие» клавиши. Мы рекомендуем использовать общие настройки (General), так как они будут влиять на стандартные раскладки клавиатур без связи с другими языками программирования.

Вы также можете выбрать на этом экране цветовую тему для Visual Studio.

Как пользоваться Visual Studio Code?

Программа Visual Studio Code — полезная находка для программистов прикладных и веб-приложений, встраиваемых в различное ПО сценариев, исполнимых скриптов для веб-сайтов и т.д. Приложение предназначено для решения нескольких основных задач:

  • Подсветка синтаксиса. При помещении исходного кода программ/сценариев/скриптов и т.д. Visual Studio Code автоматически распознает его принадлежность к тому или иному языку программирования/кодинга, затем подсвечивает команды, переменные, блоки кода и другие его элементы в разные цвета. Также, к примеру, при установке курсора перед открывающей скобкой, редактор автоматически находит закрывающую скобку, выделяя ее. Все это обеспечивает простоту визуального восприятия кода.
  • Автодополнение. Очень удобная функция, значительно сокращающая время написания кода путем подстановки остаточной части команды после нескольких введенных пользователем символов. Если вариантов несколько, все они выводятся в выпадающем меню под вводимыми символами. Автодополнение работает не со всеми языками программирования.
  • Рефакторинг. Данная функция служит для упрощения исходного кода путем замены команд и их блоков более простыми конструкциями. При этом не затрагивается внешняя функциональность и поведение программы, исходный код которой подвергается рефакторингу.
  • Отладка. Эта функция предназначена для поиска ошибок в исходных кодах программ. Редактор Visual Studio Code способен находить не только синтаксические (к примеру, не там поставленная скобка), но и логические ошибки (например, когда переменной присваивается нетипичное для нее значение). Редактор подсвечивает найденные ошибки и даже предлагает варианты ее устранения. Отладка может выполняться как по всему коду, так и в определенной ее части, для чего достаточно выставить точки останова в требуемых местах.

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

Preview features

Preview features are not ready for release but are functional enough to use. We welcome your early feedback while they are under development.

Settings Sync

We have been working the last couple of months to support synchronizing VS Code preferences across machines and this feature is available for preview on the Insiders release.

You can now disable sync on other machine using Turn off Preferences Sync context menu action on the machine entry in Synced Machines view.

We’ve also improved progress information when turning on sync.

TypeScript 4.0 support

This iteration, we’ve continued improving our support for TypeScript 4.0. Some highlights include:

  • Highlight calls to deprecated symbols in the editor with strikethrough

  • Explain reasons why a given refactoring cannot be applied

  • Improved auto imports — Read more in the .

You can try out these features today by installing the TypeScript nightly extension.

Partial IntelliSense support while large JavaScript or TypeScript projects are loading

The TypeScript 4.0 beta also brings a new feature that should help reduce the time you spend waiting while a large JavaScript or TypeScript project is being loading. To explain how this works, we first need to cover a little background on how current versions of TypeScript work.

When you open a JavaScript or TypeScript file in VS Code, the TypeScript language service determines which project that file belongs to and then loads the associated project for it. Sometimes this project can be quite large, such as with the core VS Code codebase, which consists of many thousands of TypeScript files. While a project is being loaded, VS Code able to handle basic syntax operations, such as getting the document outline and enabling code folding, but it cannot currently provide IntelliSense or other more advanced language features because they depend on understanding the entire project. In order to provide auto imports, for example, the TypeScript language service needs to know all exported symbols in a project.

The changes in TypeScript 4.0 make it possible for VS Code provide IntelliSense and other more advanced language features while a large project is still loading. The caveat is that the IntelliSense we can provide is limited to consulting the current file instead of the entire project. This means that features such as suggestions and Go to Definition will work, but we will only show suggestions from the current file and you can only run Go to Definition to jump to another symbol in the current file.

If you work with large JavaScript and TypeScript projects, we are interested in hearing your feedback on this new feature. You can try it today using the TypeScript nightly extension. Our hope is that it allows you to start work with your code almost instantly until the more complete, project-wide IntelliSense becomes available.

Undo/Redo for Code Action

We are working on being able to undo and redo Code Actions and refactorings. A prominent example is the Java class rename refactoring, which makes a textual change as well as renaming the file on disk. This can now be undone but it still requires triggering undo two times. Stay tuned as we further improve this and please provide early feedback.

Accessibility

This milestone we received great feedback from our community, which helped us identify and tackle many accessibility issues.

  • Diff view is now more accessible. Use F7 and ⇧F7 (Windows, Linux Shift+F7) to navigate through changes and use the Stage / Unstage / Revert Selected Ranges commands to stage, unstage, or revert the current change.
  • Better roles used across our widgets. The role is used for the Suggest widget and Quick Pick, for static lists, and for read-only content such as the Welcome view and Markdown preview.
  • Tuned the behavior of our Quick Pick widget.
  • The current line CodeLens can now be shown in the Quick Pick with the Show CodeLens Commands For Current Line command.

Поля Description и ярлыковDescription and shortcut fields

  1. Поля Description предоставляют дополнительные сведения о вашем фрагменте кода при просмотре в диспетчере фрагментов кода.Description fields give more information about your code snippet when viewed in the Code Snippets Manager. Ярлык — это тег, который пользователи могут вводить для вставки фрагмента.The shortcut is a tag that users can type in order to insert your snippet. Измените добавленный фрагмент, открыв файл %USERPROFILE%\Documents\Visual Studio 2017\Code Snippets\\My Code Snippet\SquareRoot.snippet.Edit the snippet you have added by opening the file %USERPROFILE%\Documents\Visual Studio 2017\Code Snippets\\My Code Snippet\SquareRoot.snippet.
  1. Поля Description предоставляют дополнительные сведения о вашем фрагменте кода при просмотре в диспетчере фрагментов кода.Description fields give more information about your code snippet when viewed in the Code Snippets Manager. Ярлык — это тег, который пользователи могут вводить для вставки фрагмента.The shortcut is a tag that users can type in order to insert your snippet. Измените добавленный фрагмент, открыв файл %USERPROFILE%\Documents\Visual Studio 2019\Code Snippets\\My Code Snippet\SquareRoot.snippet.Edit the snippet you have added by opening the file %USERPROFILE%\Documents\Visual Studio 2019\Code Snippets\\My Code Snippet\SquareRoot.snippet.

Совет

Так как вы изменяете файл в том каталоге, куда его поместила система Visual Studio, вам не нужно заново импортировать его в Visual Studio.Since you’re editing the file in the directory where Visual Studio placed it, you don’t need to reimport it to Visual Studio.

Добавьте элементы Author и Description в элемент Header и заполните их.Add Author and Description elements to the Header element, and fill them in.

Элемент Header должен выглядеть примерно так:The Header element should look something like this:

Откройте диспетчер фрагментов кода и выберите фрагмент кода.Open the Code Snippets Manager and select your code snippet

В правой области обратите внимание на то, что поля Description и Author теперь заполнены.In the right pane, notice that the Description and Author fields are now populated.

Чтобы добавить ярлык, добавьте элемент Shortcut внутрь элемента Header:To add a shortcut, add a Shortcut element within the Header element:

Сохраните файл фрагмента еще раз.Save the snippet file again.

Чтобы протестировать ярлык, откройте использованный ранее проект, введите sqrt в редакторе и нажмите клавишу TAB (один раз для Visual Basic или два раза для C#).To test the shortcut, open the project you used previously, type sqrt in the editor and press Tab (once for Visual Basic, twice for C#).
Код фрагмента должен быть вставлен.The snippet code is inserted.

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

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

Adblock
detector