Professional Documents
Culture Documents
Visual Studio Code 2016 Succinctly
Visual Studio Code 2016 Succinctly
Visual Studio Code 2016 Succinctly
Table of Contents
The Story behind the Succinctly Series of Books ................................................................................... 5
About the Author ......................................................................................................................................... 7
Introduction ................................................................................................................................................. 8
Chapter 1 Code Editing Evolved for Windows, Linux, and OS X ........................................................... 9
Why Visual Studio Code .......................................................................................................................... 9
Language Support ................................................................................................................................. 10
Editing Features ..................................................................................................................................... 12
Working With Files and Folders ............................................................................................................. 38
Chapter Summary .................................................................................................................................. 50
Chapter 2 The Workspace and the User Interface ................................................................................. 51
The Code Editor ..................................................................................................................................... 51
The Status Bar ....................................................................................................................................... 53
The View Bar ......................................................................................................................................... 53
The Side Bar .......................................................................................................................................... 55
Quick File Navigation ............................................................................................................................. 60
The Command Palette ........................................................................................................................... 60
Chapter Summary .................................................................................................................................. 62
Chapter 3 Git Version Control and Task Automation ............................................................................ 63
Version Control with Git ......................................................................................................................... 63
Automating Tasks .................................................................................................................................. 74
Chapter Summary .................................................................................................................................. 84
Chapter 4 Creating and Debugging Applications .................................................................................. 85
Chapter Prerequisites ............................................................................................................................ 85
Creating an ASP.NET Core Web Application ........................................................................................ 86
Debugging in Visual Studio Code .......................................................................................................... 93
Chapter Summary ................................................................................................................................ 101
Chapter 5 Customizing and Extending Visual Studio Code ............................................................... 102
Introducing the Visual Studio Code Marketplace ................................................................................. 102
Understanding Customizations and Extensions .................................................................................. 103
Customizing Visual Studio Code ......................................................................................................... 104
Create Your First Extension: Language With Grammar, Colorization, and Snippets .......................... 113
Chapter Summary ................................................................................................................................ 128
As many of you may know, Syncfusion is a provider of software components for the
Microsoft platform. This puts us in the exciting but challenging position of always
being on the cutting edge.
Whenever platforms or tools are shipping out of Microsoft, which seems to be about
every other week these days, we have to educate ourselves, quickly.
Free forever
Syncfusion will be working to produce books on several topics. The books will always be free.
Any updates we publish will also be free.
Introduction
Visual Studio Code is the first cross-platform, multi-language development tool in the Microsoft
Visual Studio family that runs on Windows, Linux, and Mac OS X. It is free and open source. It
is definitely a code-centric tool, which makes it easier to edit code files and folder-based project
systems as well as write cross-platform web and mobile applications for the most popular
platforms, such as Node.js and the new ASP.NET Core. It has integrated support for a large
number of languages and rich editing features such as IntelliSense, finding symbol references,
quickly reaching a type definition, and much more. This is an important investment from
Microsoft, which represents another great step in the new open way of thinking in Redmond.
Visual Studio Code combines the simplicity of a powerful code editor with the tools a developer
needs to support the application life-cycle development, including debuggers and Git version
control integration. It is therefore a complete development tool, rather than being a simple code
editor. For more advanced coding and development, you should certainly consider Visual Studio
2015remember that the Community edition ships for freebut Visual Studio Code can be
really helpful in many situations.
Before you continue reading, make sure you have installed the proper version of Visual Studio
Code. Installers are available for Mac OS X, Linux, and Windows. You can follow the official
documentation in case you have trouble installing the software. Microsoft is releasing new
versions of Visual Studio Code very frequently, typically once a month. The environment
periodically checks for new updates and, when available, it prompts you to install the new
release, and then asks to be restarted when finished. This book has been written using version
0.10.11. For this reason, some features might have changed at the time of your reading, others
might have been improved, and others might be totally new. This is a necessary clarification that
you should keep in mind while reading, and this is also the reason why I often provide links to
the official documentation. It is interesting to mention that there is also a Visual Studio Code
Insiders build that works side-by-side with the regular release and automatically installs updates
on your behalf. In case you are interested, remember that this is a separate installation, which
implies installing extensions and configuring settings separately.
In this book you will learn how to use and how to get the most out of Visual Studio Code, seeing
how you can use it both as a powerful code editor and as a complete environment for end-toend development. Figures are based on the Microsoft Windows 10 operating system, but there
is essentially no difference on Linux or Mac OS X. Also, Visual Studio Code includes a number
of color themes that style its layout. Im using the so-called Light Theme, so you might see
different colors than I, but, again, colors you use certainly do not affect what I explain here. I will
also explain how to change the color theme, but if you are impatient or if you just want to be
consistent with the books figures, simply select File > Preferences > Color Theme. The
companion source code is available on GitHub at:
https://github.com/AlessandroDelSole/VSCodeSuccinctly.
Now sit down, open Visual Studio Code, and enjoy this amazing tool. Im sure youll love it.
Built-in support for coding with many languages, including those you typically use in
cross-platform development scenarios, with advanced editing features and support for
additional languages via extensibility.
Built-in debugger for Node.js, with support for additional debuggers (such as Mono) via
extensibility.
Version control based on the popular Git engine, which provides an integrated
experience for collaboration that supports code commits and branches, and is the proper
choice for a tool intended to work with possibly any language.
In order to properly combine all these features into one tool, Visual Studio Code provides a
coding environment that is different from other developer tools, such as Microsoft Visual Studio.
In fact, Visual Studio Code is a folder-based environment that makes it easy to work with code
files that are not organized within projects, and offers a unified way to work with different
languages. Starting from this assumption, Code offers an advanced editing experience with
features that are common to any supported languages, plus some features that are available to
specific languages. As you will learn throughout the book, Code also makes it easy to extend its
built-in features by supplying custom languages, syntax coloring, editing tools, debuggers, and
much more via a number of extensibility points. Now that you have a clearer idea of Codes
goals, you are ready to learn the amazing editing features that put it on top of any other code
editor.
Visual Studio Code does not invoke compilers, so it does not produce binaries such as
.exe or .dll files. You can certainly implement task automation, which will be discussed in
Chapter 3, but this is different than having the compilation process integrated.
Visual Studio Code has no designers, so creating an applications user interface can
only be done by writing all of the related code manually. As you can imagine, this is fine
with some languages and scenarios but it can be very complicated with certain
applications and development platforms, especially if you are used to working with the
powerful graphical tools available in Microsoft Visual Studio.
The built-in debugger is specific to web, cross-platform languages and it currently targets
only Node.js. Plus, it is not as advanced as the Visual Studio debugger.
Visual Studio Code is a general purpose tool and is not the proper choice for specific
development scenarios such as building Windows desktop applications.
If your requirements are different, consider instead Microsoft Visual Studio 2015, which is the
premier development environment for building, testing, deploying, and maintaining any kind of
application. The Visual Studio 2015 Community edition is free and provides a full development
environment for any development platform.
Language support
Visual Studio Code has built-in support for many languages out of the box. Table 1 groups
supported languages by editing features.
Table 1: Language Support
10
JavaScript
TypeScript, C#
Starting from version 0.10.10, C# is no longer available out of the box; instead it is available as
an extension. The reason why I included C# in Table 1 is for consistency with previous versions
and because many of you might already have experienced C# editing features in the past. In
order to have C# installed, follow these steps:
1. Open a C# code file (.cs) in Visual Studio Code.
2. When asked, accept the option to install the C# extension.
3. Restart Visual Studio Code when the installation is complete.
Visual Studio Code can be extended for additional languages with tools produced by the
developer community. These extensions can be downloaded from the Visual Studio Code
Marketplace. This is discussed in more detail in Chapter 5, "Customizing and Extending Visual
Studio Code." In the meantime, you can have a look at the available languages.
Note: This book describes all the available features in Visual Studio Code based on
common development and coding scenarios. However, Visual Studio Code also has
support for very specific scenarios with C#, JSON, HTML, Markdown, TypeScript, and
DockerFile, so do not miss the Languages page in the documentation.
11
Editing features
Visual Studio Code provides many of the features you would expect from a powerful code
editor. This section describes what editing features make your coding experience amazing with
this new tool. If you are familiar with Microsoft Visual Studio 2013 and higher, you will also see
how some features have been inherited from this IDE. It is worth mentioning that Visual Studio
Code provides keyboard shortcuts for almost all of the editing features, enabling you to edit
code faster. For this reason, I will also mention the keyboard shortcuts for every feature I
describe. With regard to this, remember that the counterpart for the Windows Ctrl key in Mac is
Cmd.
Syntax coloring
Visual Studio Code provides the proper syntax coloring for the language your code files are
written with. Figure 1 shows an example based on a C# code file.
Syntax coloring is arguably the most important feature when editing a code file, and this is
available to all supported languages. You can also define your own highlighting rules when
adding custom languages (see Chapter 5).
Bracket matching
The code editor can highlight matching brackets, as shown in Figure 2.
12
This feature is extremely useful for identifying the beginning and end of long code blocks and is
triggered once the cursor is near one of the brackets.
IntelliSense
IntelliSense is a feature that offers rich, advanced word completion via a convenient pop-up that
appears as you type. In developer tools from Microsoft such as Visual Studio, IntelliSense has
always been one of the most popular features because it is not simply word completion. In fact,
IntelliSense provides suggestions as you type, showing the documentation about a member if
available, and displaying an icon near each suggestion that describes what kind of syntax
element a word represents. Figure 3 shows IntelliSense in action.
13
Figure 3: IntelliSense shows suggestions as you type and provides rich word completion.
As you can see in Figure 3, IntelliSense shows a list of available members for the given type--in
this case Console--as you write. When you select a word from the completion list, Code shows
the summary for the member documentation. Also, if you click the i symbol (which stands for
Information), you can see the full member documentation (see Figure 4).
14
To quickly complete the word insertion, use either Tab or Enter. Not limited to this, IntelliSense
in Visual Studio Code also supports suggestion filtering: Based on the CamelCase convention,
you can type the uppercase letters of a member name to filter the suggestion list. For instance,
if you are working against the System.Console type and you write cv, the suggestion list will
show the CursorVisible property, as demonstrated in Figure 5.
15
Out of the box, IntelliSense is available to the following languages: CSS, HTML, JavaScript,
JSON, Less, Sass, TypeScript, and C#.
Parameter hints
When you code a function invocation, IntelliSense also shows a tooltip that describes each
parameter if the documentation has been supplied (such as XML comments in C#). This feature
is called parameter hints and you can see it in action in Figure 6.
16
Go To Definition
With supported languages, Visual Studio Code provides an interesting feature called Goto
Definition. You can hover over a symbol with the pointer and the symbol will appear as a
hyperlink. Also, a tooltip will show the code that declares that symbol (see Figure 7).
17
Also, you can hold Ctrl and click on the symbol and Code will open the definition directly in the
file that contains the related code.
Tip: Alternatively, you can press F12 or right-click and select Go To Definition.
Tooltips
You can hover over types, variables, and type members, and Visual Studio Code will show a
tooltip that contains the documentation for the selected object. This feature is available only if
the documentation has been provided, such as XML comments for C#. Figure 8 shows an
example where you can see a descriptive tooltip of a type called Document.
18
If you instead hover over a variable name, the tooltip will show the type for the variable.
19
Figure 9: See where and how many times members have been used with Find All References
Just click on each occurrence in the list to see the code that has a reference to it. It is very
important to note that this pop-up is interactive, which means that you can edit the code directly
without having to open the containing code file separately. This allows you to keep your focus
on the code, saving time. Also notice that the interactive pop-up shows the file name that
contains the selected reference at the top.
Tip: You can also enable Find All References by pressing Shift+F12 or by rightclicking and then selecting Find All References.
Rename Symbol
Renaming a symbol is a common editing task, so Visual Studio Code offers a convenient way to
accomplish this. If you press F2 over the symbol you wish to rename, or right-click and then
select the Rename command, a small interactive pop-up appears (see Figure 10). There you
can write the new name without any dialogs, keeping your focus on the code.
20
Additionally, you can rename all the occurrences of an identifier. Just right-click the identifier
and then select Change All Occurrences (or press Ctrl+F2); all the occurrences will be
highlighted and updated with the new name as you type (see Figure 11).
21
Peek Definition
Suppose you have dozens of code files and you want to see or edit the definition of a type you
are currently using. With other editors, you would search among the code files, which not only
can be annoying but would also move your focus away from the original code. Visual Studio
Code brilliantly solves this problem with a feature called Peek Definition. You can simply rightclick a type name and then select Peek Definition (the keyboard shortcut is Alt+F12). An
interactive pop-up window appears showing the code that defines the type, giving you not only
an option to look at the code, but also the option to directly edit it. Figure 12 shows the peek
window in action.
22
As you can see, the peek window is very similar to the Find All Reference feature and it still
shows the file name that defines the type at its top. Double-click the file name to open the code
file in a separate editor.
Fast Selection
You can press Ctrl+D to select a word or identifier at the right of the cursor.
23
Multi-Cursors
Visual Studio Codes editor supports multi-cursors. Each cursor operates independently and you
can add secondary cursors by holding Alt and clicking at the desired position. You will see that
secondary cursors are rendered thinner. The most typical situation in which you want to use
multi-cursors is when you want to add (or replace) the same text in different positions of a code
file. Figure 13 shows an example.
Figure 13: Multi-cursors can be used to add the same text in multiple positions.
The Change All Occurrences feature you saw before automatically uses multi-cursors too.
Goto Symbol
Another interesting and powerful feature is Goto Symbol. By pressing Ctrl+Shift+O, you will be
able to browse symbols in the current code file. Also, if you type : in the search box, symbols
will be grouped by category. Figure 14 shows how to browse symbols grouped by category.
24
Use the up and down arrow keys to highlight the corresponding symbol definition in the code
file. In addition, the symbol list is automatically filtered based on what you type in the search
box.
If you click the name of a symbol that is defined inside a different code file, this will be opened
inside a new editor window.
25
Note: This feature is fully available to C# and TypeScript however there is some basic
support for JavaScript and CSS. This section describes the full functionality based on
some C# code.
According to the severity of a code issue, Visual Studio Code underlines the pieces of code that
need your attention with squiggles. Green squiggles mean a warning; red squiggles mean an
error that must be fixed. If you hover over the line or symbol with squiggles, you will get a tooltip
that describes the issue. Figure 16 shows two code issues, one with green squiggles for an
unnecessary using directive, and one with red squiggles for a symbol that does not exist. The
figure also shows the tooltip for the code issue with the higher severity level.
Of course, Visual Studio Code also provides an integrated, easy way to fix code issues via the
so-called Light Bulb shown in Figure 17 under the unnecessary using directive.
26
Figure 17: The Light Bulb provides a shortcut for resolving code issues.
When you click the Light Bulb, Visual Studio Code shows possible code fixes for the current
context. In this case, it allows you to remove unnecessary directives and to sort directives, as
shown in Figure 18.
Just click the desired fix and it will be applied to the code issue. Actually, this tool is much more
powerful. Consider the symbol called logContent that does not exist in the code file and is
underlined as a code issue as expected (see Figure 16). If you click this symbol and then open
the Light Bulb, the code editor will show a list of possible proper fixes for the current context,
such as creating a field, creating a property, creating a local variable, and more, as shown in
Figure 19.
27
Figure 19: The Light Bulb provides proper code fixes based on the context.
For instance, if you select the Create property option, Visual Studio Code generates a property
stub for you, as shown in Figure 20.
28
Theres much more power than this. Consider Figure 21, where you see a class that needs to
implement the IDisposable interface. As you can see, there is a code issue because the code
editor cannot find the definition for this interface, so it provides possible fixes.
We know this interface is from the System namespace, so the proper fix here is the using
System; option. When selected, Visual Studio Code adds a using System; directive to the
code file. However, this is not enough to solve the code issue because the class actually lacks
the interface implementation. If you click the Light Bulb again, you will see how the code editor
offers to implement the interface for you based on four different choices, as demonstrated in
Figure 22.
29
If you select the Implement interface with Dispose pattern, you will see how Visual Studio
Code supplies all the plumbing code for a correct interface implementation, as shown in Figure
23.
30
Figure 23: Visual Studio Code applies the code fix, adding all the plumbing code.
If you chose one of the other code fixes, you would get a similar result but with different
implementation. Though it is not possible to show examples for all the code fixes that Code can
apply, what you have to keep in mind is that suggestions and code fixes are based on the
context for the code issue, which is a very powerful feature that makes Visual Studio Code a
unique editor. Once you know how to work with the Light Bulb, you will see on your own
possible fixes depending on the code issues you encounter. Visual Studio Code also provides
an alternative way to see all the code issues it finds. Select View > Errors and Warnings
(Ctrl+Shift+M) or click the Errors and Warnings symbols at the lower left corner. This opens a
list of code issues (see Figure 24) that you can also filter by typing into the search box. Then
you can simply click a code issue and move to it immediately.
31
Note: Behind the scenes, this feature is based on the .NET Compiler Platform, also
known as Roslyn. Roslyn provides open source C# and Visual Basic compilers with rich
code analysis APIs. Visual Studio Code does not work with compilers like Visual Studio
does, but it calls a special language service that performs code analysis as you type.
Visual Studio 2015 heavily uses the Roslyn APIs to empower the code editor with even
more advanced features, such as live preview. If you want to discover more about Roslyn
with .NET, consider reading Roslyn Succinctly.
32
If you press Ctrl+Shift+V, Visual Studio Code shows a live preview of how the document will be
rendered, as shown in Figure 26.
33
This is a very useful feature that gives you an immediate view of what the document will look
like.
Code snippets
Visual Studio Code ships with a number of built-in code snippets that you can easily add by
using the Emmet abbreviation syntax and pressing Tab. Table 1 lists what languages support
code snippets natively. For instance, in C# you can easily add a property definition by using the
prop code snippet, as shown in Figure 27.
34
Code snippets are available in the IntelliSense pop-up as you type. They're recognizable by the
small white sheet icon. Pressing Tab over the snippet in the previous figure produces the result
shown in Figure 28.
35
As another example, with JavaScript code files you can use the define snippet (see Figure 29)
to add a module definition. This code snippet produces the result shown in Figure 30.
36
37
Visual Studio Code is not limited to built-in code snippets. You can download code snippets
produced by the developer community for many languages, and you can even create and share
your own snippets. This is discussed in Chapter 5, "Customizing and Extending Visual Studio
Code".
package.json
project.json
tsconfig.json
.sln or .xproj Visual Studio solution and project files for ASP.NET Core
38
If Code finds one of these files, it is able to organize the file structure into a convenient editing
experience and offer additional rich editing features such as IntelliSense and code refactoring. If
a folder only contains source code files without any of the aforementioned .json or .sln files, it
still opens and shows all the source code files in that folder, providing a convenient way to
switch between all of them. The sections that follow describe how to work with single files and
folders in Visual Studio Code, plus how Code manages projects.
39
Tip: Visual Studio Code also features the Explorer, which provides a structured,
organized view of currently opened files. This is discussed in Chapter 2, "The Workspace
and the User Interface."
An editor can be closed by using the Close button at the upper right corner, or by using the
Close All Files command in the File menu.
When you select a new language, the Select Language Mode pop-up is updated with the
selected language and the editor enables the proper features it, as shown in Figure 33 where
the syntax colorization and IntelliSense is based on selecting JavaScript.
40
Figure 33: Changing the language for a code file enables the proper features.
Of course, you can change the current language for any existing files, not just new files.
41
Similarly, you can change the line terminator by clicking the Select End of Line Sequence
item, represented in previous figures by CLRF in the lower right corner of the editor. Visual
Studio Code supports CRLF (carriage return and line feed) and LF (line feed); the default
selection is CRLF. You can also move instantly to a line of code by clicking the Go to Line item,
represented by the line and column number in the status bar. This will open a search box where
you can type the line number you want to go to and the line of code will be immediately
highlighted as you type. You can also navigate to a line by pressing Ctrl+G (see Figure 35).
42
43
project.json files. If found, Code treats the folder as a DNX project written in C#. DNX
stands for .NET Execution Environment and is a runtime with an SDK built on top of
.NET Core for building portable, cross-platform ASP.NET Core solutions.
MSBuild solution files (.sln). If found, Visual Studio Code knows this is a solution built
for Microsoft Visual Studio, so it scans the referenced projects (*.csproj and *.vbproj
files) and organizes files and subfolders in the proper way.
tsconfig.json files. If found, Visual Studio Code knows this represents the root of a
TypeScript project, so it scans for the referenced files and provides the proper file and
folder representation.
jsconfig.json files. If found, Visual Studio Code knows this represents the root of a
JavaScript project. So, similarly to TypeScript, it scans for the referenced files and
provides the proper file and folder representation.
package.json files. These are typically included with JavaScript projects and DNX
projects, so Visual Studio Code automatically resolves the project type based on the
folders content.
Tip: Opening a .sln or .json file directly will result in editing the content of the
individual file. For this reason, you should open a folder, not a solution or project file.
If none of the supported projects are found, Visual Studio Code loads all the code files in the
folder as a loose assortment, organizing them into a virtual folder for easy navigation. Now lets
discover how Visual Studio Code allows you to work with folders and supported projects.
Opening a folder
Generally speaking, you open a folder with Code via File > Open Folder. On Windows, if you
selected the option during installation, you can right-click a folder name in File Explorer and then
select Open with Code. Whatever folder you open, Code organizes files and subfolders into a
structured view represented in the Explorer side bar. Figure 36 shows an example.
44
45
The root container is the folder name. Files and subfolders are nested in it, and you can expand
each subfolder to browse every file it contains. Just click a file to open an editor window of it.
The Explorer tool is much more than just file browsing, but lets save this for Chapter 2, where I
will discuss Codes user interface deeply. For now, focus on the visual representation it provides
for any folders.
Notice how the root level in Explorer is the project name. You can browse folders, code files,
and edit anything that Visual Studio Code can properly recognize. You can also take a look at
the project.json file, which contains project information, the list of dependencies, scripts, and
other information. Figure 38 shows an excerpt.
46
Note: With DNX projects, you will be required to restore NuGet packages using the
dnu restore command from the Command Palette. This is described in more detail in
Chapter 4, "In Practice."
47
TypeScript projects behavior in Visual Studio Code is the same as for JavaScript.
48
It is worth noting that features such as Find all References and code issue detection are
enabled if Visual Studio Code detects NuGet packages inside the solution.
Tip: In Chapter 3, "Git Version Control and Task Automation," you will also learn how
to launch the MSBuild engine from VS Code and compile a DNX project written with C#.
49
Chapter summary
Visual Studio Code is an open source, cross-platform, multi-language development environment
that puts writing code at its center. Code supports a variety of languages and offers an
enhanced editing experience with common features such as syntax colorization, and more
advanced capabilities such as IntelliSense, code issue detection, and code browsing. In order to
support different project systems, Visual Studio Code is file and folder based, which means that
it supports working with loose code files and with organized, structured folders containing
project and code files. After this long overview of the available editing features, the next logical
step is discussing the workspace and the user interface.
50
51
Figure 42: The code editor allows opening up to three code files.
Right-click a file name in the Explorer bar and then select Open to Side.
Hold Ctrl and click on a file name in Explorer.
Press Ctrl+\ to split the editor in two.
Notice that if you already have three files open and you want to open another file, the editor that
is active will display that file. You can quickly switch between editors by pressing Ctrl+1, Ctrl+2,
and Ctrl+3.
52
Zooming editors
You can easily zoom in and out of the active editor by pressing Ctrl+Plus Sign and
Ctrl+Hyphen respectively. Alternatively, you can select View > Zoom in and View > Zoom out.
Notice that this is an accessibility feature, so when you zoom the code editor, the view bar and
side bar will also be zoomed.
Git version control information and options, such as the current branch and the
Synchronize Changes button.
Errors and warnings. You already saw this in the Code Issues and Refactoring section in
Chapter 1.
Indentation. This is the Spaces: 4 item in Figure 43. You can click this to change the
indentation size and to convert indentation to tabs or spaces.
The cursor's position expressed in line and column numbers.
The current file encoding.
The current line terminator.
The language for the open file.
The project name if you open a folder that contains a supported project system. It is
worth noting that, in case the folder contains multiple project files, clicking this item will
allow switching between projects.
The feedback button, which allows sharing your feedback about Visual Studio Code on
Twitter.
The status bar is blue if you open a folder or violet if you open a single file.
53
The view bar can be thought of as a collapsed container for the side bar, and it provides
shortcuts to the following tools: Explorer, Search, Git, and Debug, which are described in the
next sections.
54
55
56
The subview that shows a folder structure provides four buttons from left to right: New File, New
Folder, Refresh, and Collapse. The function of each is self-explanatory. The Working Files
subview has two buttons: Save All and Close All Files. Right-clicking a folder or file name in
Explorer provides a context menu that offers common commands, such as the Open to the Side
option mentioned at the beginning of this chapter. A very interesting command is Reveal to
Explorer (or Reveal to Finder on Mac and Open Containing Folder on Linux), which opens the
containing folder for the selected item. Notice that the Explorer icon in the view bar reports the
number of modified files.
57
Search results are offered in a hierarchical view that groups all the files that contain the
specified search key, and shows an excerpt of the line of code that contains it. Occurrences are
highlighted in both the list of files and in the code editor. When you are done, you can clean up
search results by clicking the Clear Search Results button.
58
59
When you release the Tab key, the selected file is opened for editing. The second way is to
press Alt+Left Arrow Key or Alt+Right Arrow Key to switch between active files.
60
The Command Palette is basically an easy way to access all of Visual Studio Codes
functionalities via the keyboard. This is not just related to menu commands or user interface
instrumentation, but also other actions that are not accessible elsewhere. For instance, the
Command Palette allows installing extensions as well as restoring NuGet packages over the
current project or folder. You can move up and down the list to see all the available commands,
and you can type characters to filter the list. You will notice many commands map actions
available within menus. Other commands, such as extension, debug, and Git commands, will be
discussed in the next chapters so it is important that you get started with the Command Palette
at this point.
61
Chapter summary
The user interface in Visual Studio Code is optimized to maximize the available space for
editing. The workspace is divided into four areas. The code editor is where you write code and
where you can open up to three files concurrently. The status bar reports summary information
about the file or folder. The view bar is a collapsed container for the side bar that offers four
important tools: Explorer, Search, Git, and Debug. Explorer provides an organized view of files
and folders, while Search allows searching across files with advanced options. Git and Debug
will be discussed in the next chapters. Visual Studio Code offers another important tool, the
Command Palette, where you can browse the list of available commands, including those you
execute against projects, folders, and files directly.
62
63
64
Click Initialize git repository. Visual Studio Code will initialize the local repository and show the
list of files that the version control is tracking but has not yet committed (see Figure 53).
65
66
Notice how the Git icon shows the number of pending changes. This is an important indicator
that you will always see any time you have pending, uncommitted changes. Write a commit
description and then press Ctrl+Enter. At this point, files are committed to the local repository
and the list of pending changes will be cleaned. Now there is a problem: You need a remote
repository but the official documentation does not describe how to associate one to Code. Lets
look at how to accomplish this.
67
Once the repository is created, GitHub provides fundamental information you need to associate
the remote repository with the local one. Figure 55 shows the remote address for the Git version
control engine and the commands you have to type to perform the association.
Figure 55: Getting the Necessary Information to Associate the Remote Repository to the Local One
The next step is to open the command prompt and navigate to the folder that contains your
Cordova project. Next, write the following two lines:
> git remote add origin https://github.com/YourAccount/YourRepository.git
> git push -u origin master
Where YourAccount and YourRepository represent your GitHub user name and the
repository name respectively. The first line tells Git that the remote origin for the current folder
(which contains the local repository) is the specified URL. The second line pushes the content of
the local repository into the branch called master. Depending on your Internet connection, it will
take up to a couple minutes to complete the upload operation. Now you really have everything
you need and you can start discovering the Git integration that Visual Studio Code offers.
68
By clicking a file in the list, you can see the differences between the new and the old file
versions, as shown in Figure 57. This tool is called Diff.
69
Figure 57: The Diff tool allows you to compare changes between versions.
On the left side you have the old version, while the new one is on the right. This is a very
important tool when working with any version control engine. You can also promote files for
staging, which means marking them as ready for the next commit. This is actually not
mandatory, as you can commit directly, but it is useful to have a visual representation of your
changes. You can stage a file by clicking the + symbol near its name. Visual Studio Code
organizes staged files into a logical container, as you can see in Figure 58. Similarly, you can
unstage files by clicking the symbol.
70
Managing commits
When you are ready, you can click the button and access additional actions, such as
Commit, Sync, Pull, and Pull (Rebase). Figure 59 shows how you can commit all files, and also
shows how files marked for deletion are represented with a red icon.
71
When ready, click Commit All. Remember that this action commits files to the local repository.
You then have to Sync in order to synchronize changes with the remote repository. You also
have an option to undo the last commit and revert to the previous version with the Undo Last
Commit command. Pull and Pull (Rebase) allow you to merge a branch into another branch.
Pull actually is non-destructive and merges the history of the two branches, while Pull (Rebase)
rewrites the project history by creating new commits for each commit in the original branch.
Git commands
The Command Palette has support for specific Git commands which you can type as if you were
in a command shell. Figure 60 shows the list of available Git commands.
72
For instance, you can use Git Sync to synchronize the local and remote repository, or you can
use Git Push to send pending changes to the remote repository. A common scenario in which
you use Git commands is with branches.
73
Figure 61: The New Branch and the Publish Branch Button
With this tool, you do not need to create and manage a branch in your Git repository provider.
Automating tasks
I have mentioned several times that Visual Studio Code is more than just a code editor; it is an
end-to-end development environment. After reading the book this far, I expect you have a better
understanding of what I mean. But there is more. Any respectable development environment
needs to run external tasks, such as programs, compilers, or general purpose tools. Of course,
this is the case with Code too. Visual Studio Code allows running external programs Tasks.
When you run a Task, Visual Studio Code will display the Output window where the output of
external programs is redirected to. This window will be covered shortly.
Note: What you will see in this section is a practical implementation of tasks. Of
course, Visual Studio Code supports many, many types of tasks and more complex
operations. That said, be sure to check out the official documentation about specific and
complex task configurations.
74
Code Listing 1
The preconfigured default task starts the TypeScript compiler against a file called HelloWorld.ts.
Im going to show you how to implement your custom tasks shortly, but before that you need to
understand what a task is made of. In its most basic form, a task is made of the following JSON
elements:
75
version. This represents the VS Code minimum version and should be left unchanged.
command. This is the external program you want to run. Remember that you will need to
include the full path for the program if an environment PATH variable has not been
configured for it.
isShellCommand. This represents whether a command is a shell script or not (you will
leave this true in most cases).
showOutput. This specifies when the Output window must show the output captured
from the external program. Supported values are always, never, and silent. They will
show the output window always, never, or only when unrecognized errors are detected.
args: One or more arguments to be passed to the command. Typical arguments are file
names and command-line switches.
Optionally, you can specify a problem matcher, which is a way to make Visual Studio Code
understand and process styles of errors and warnings produced by external programs. For
instance, the $tsc problem matcher (TypeScript) assumes that file names in the output are
relative to the opened folder; the $mscompile (C# and Visual Basic) and the $lessCompile
(Less) problem matcher assumes that file names are represented as an absolute path. Code
supports many problem matchers out of the box, but you can define your own matchers for
programs that are not supported directly. Also, you can configure multiple tasks and you will see
an example based on Batch files later in this chapter. Discovering custom problem matchers is
left to you as an exercise (look at the Visual Studio Code docs). Here, you will learn how to
configure practical tasks such as running a Python program, executing a Batch file, and
compiling a Visual Studio solution with MSBuild.
Tip: Tasks you define will not be executed until you save task.json, so do not forget
this. Also, remember to close the task.json editor if your task runs against a different,
active code file (or at least switch the view to the code file).
Using variables is very common when you run a task that works at the project or folder level or
against file names that you either cannot predict or that you do not want to hardcode. You will
see a couple examples in the next sections.
76
Press Ctrl+Shift+P or the F1 key to open the Command Palette. Next, type Configure Task
Runner or select the auto-fill suggestion item that appears while typing, as shown in Figure 63.
At this point Visual Studio Code generates a new task.json file for the current folder. Either clear
the content of the file or comment the pre-configured TypeScript task and write the new task
shown in Code Listing 2.
77
Code Listing 2
78
Figure 64: The Output window shows results from the external program.
As you can see, this is a very useful and powerful feature because it runs an external program
and brings its output directly into the development environment.
Tip: The Output window is not interactive. For instance, if your program expects user
input, the Output window is not able to capture it. Keep this in mind when you configure
your tasks.
@ECHO OFF
SET FOLDERNAME=C:\TEMP\TESTFOLDER
SET FILENAME=%FOLDERNAME%\TEXTFILE.TXT
MKDIR %FOLDERNAME%
ECHO %FOLDERNAME%
CREATED
{
"version": "0.1.0",
"command": "${workspaceRoot}/CreateDir.bat",
"isShellCommand": true,
"showOutput": "always",
"args": [ ]
}
79
In this case, your command is the Batch file whose execution is handled by the operating
system that will treat it like an executable program. There are no arguments here because the
Batch file does not expect any. Notice how the ${workspaceRoot} variable is specified to tell
Code that the file is in the root folder. If you save tasks.json and press Ctrl+Shift+B, Visual
Studio Code will launch the Batch file and show the result in the Output window, as shown in
Figure 65.
Figure 65: The Output window shows the result of executing a Batch file.
80
Code Listing 5
81
Figure 66: The Output window shows the result of compiling an MSBuild solution.
If you want to use the powerful editing features of Visual Studio Code and you want to be able
to compile your solutions, this option is definitely a nice addition.
82
Code Listing 6
{
"version": "0.1.0",
"command": "msbuild",
"isShellCommand": true,
"showOutput": "always",
"args": ["WPCDemo.sln"],
"tasks": [
{
"taskName": "build",
"isBuildCommand": true,
"showOutput": "always"
},
{
"taskName": "test",
"showOutput": "never"
}
]
}
The following is a list of key points about configuring multiple tasks:
Code Listing 6 defines two tasks for the build and test tasks supported by Visual Studio Code.
The build task is available by pressing Ctrl+Shift+B, and the test task is available by pressing
Ctrl+Shift+T. Both are also available through the Command Palette, as you can see in Figure
67.
Figure 67: Invoking the build and test tasks from the Command Palette.
Not limited to this, you can also specify additional tasks with custom names. Code Listing 7
shows how to define a new task called onError, which is displayed in the Output window only
when compile errors are detected. Finally, Figure 68 shows how you can invoke the custom task
from the Command Palette.
83
Code Listing 7
{
"version": "0.1.0",
"command": "msbuild",
"isShellCommand": true,
"showOutput": "always",
"args": ["WPCDemo.sln"],
"tasks": [
{
"taskName": "build",
"isBuildCommand": true,
"showOutput": "always"
},
{
"taskName": "test",
"showOutput": "never"
},
{
"taskName": "onError",
"showOutput": "silent"
},
]
}
By defining multiple tasks, you can run external programs over your project and folders targeting
different configurations.
Chapter Summary
Visual Studio Code provides integrated support for source code version control based on the Git
engine, offering tools that make it easy to commit and manage your changes, including
branches. Code also allows you to define build, test, and custom tasks, enabling you to run
external programs such as compilers over your projects and folders. These are key features that
make Visual Studio Code different from a simple source code notepad. Now you have in your
hands all the powerful features you need to start writing great applications with Code, which is
the topic of the next chapter.
84
Chapter prerequisites
Before you start writing web applications with Visual Studio Code, you need to make sure you
have installed the following prerequisites:
Node.js, a JavaScript runtime that includes, among the others, the npm (Node Package
Manager) command-line tool.
DNX, the.NET Execution Environment required to build cross-platform web applications
with ASP.NET Core 1.0 (formerly ASP.NET 5), the new development platform from
Microsoft for the next generation of cross-platform web apps.
DNX integrates well with Node.js and provides additional command-line tools that you will use
very often. The next step is installing Yeoman, a very popular command-line tool that helps you
with scaffolding a variety of modern web projects. Installing Yeoman is very easy: Open a
command prompt and type the following line, assuming you have already installed Node.js:
> npm install -g yo generator-aspnet gulp bower
This line will install the ASP.NET Core generator from Yeoman (also referred to as yo), plus
Gulp and Bower.
Note: If you are new to cross-platform web development, you might wonder what
Gulp and Bower are. In a few words, Gulp is a tool that simplifies the automation of
repetitive tasks whereas Bower is a library and package manager for web apps. Click
their links in the previous paragraph to get more information.
If you are wondering why you need these additional tools, the answer is very simple: They allow
creating and managing applications in a way that is completely platform and environment
independent. For instance, Yeoman generates ASP.NET Core applications based on
project.json files, which is suitable for Visual Studio Code and many other development tools on
different operating systems and platforms. This is different from creating ASP.NET Core apps
with Microsoft Visual Studio, which generates proprietary solution files. Though the result is the
same, and though Visual Studio is much more powerful, of course, you need Windows and
Visual Studio itself. Another prerequisite is installing the Express application framework that you
use to scaffold a Node.js application. The command you type in the command line is the
following:
85
86
Notice how you can create a variety of projects, including the popular Web API. Select the Web
Application template and press Enter. You will be prompted to enter a name for the
application. For consistency, type CodeSuccinctlyWeb and press Enter. Yeoman generates a
subfolder called C:\MyWebApps\CodeSuccinctlyWeb and all the necessary files for scaffolding
the application in this folder. You can see the generation progress in the Console window and,
at completion, Yeoman suggests a sequence of commands to run (see Figure 70).
For now, you can skip running the suggested commands, as you will do this from within Visual
Studio Code shortly.
Tip: dnu stands for .NET Utilities and allows executing specific actions against
projects. Type dnu help for further information
Now open Visual Studio Code, select File > Open Folder, and select the CodeSuccinctlyWeb
folder. Visual Studio Code will find a project.json file and organize the files in a proper view.
Note: Explaining how an ASP.NET Core project is structured is beyond the scope of
this book. Here we focus on how to work with ASP.NET Core projects in VS Code. For
further details, refer to the official ASP.NET Core documentation.
87
You can manually request to restore NuGet packages in the Command Palette by first typing
dnx restore packages, and then selecting the dnu restore command. If you have multiple
projects in your folder, you will have an option to target a specified project. Once you restore all
the NuGet packages, the red squiggles will go away.
88
89
Tip: You can change the default port (5000) in the file called Dockerfile.
Alternatives for publishing your ASP.NET 5 applications to different production server types are
explained in the documentation. Microsoft has also produced a great tutorial that explains how
to publish your ASP.NET 5 application to Microsoft Azure in a few steps.
90
The new controller is added to the Controllers folder and the Output window shows information
about the code generation. If you look at the error list, you will see an error stating An
anonymous type cannot have multiple properties with the same name. This is a known
issue and you can fix it by navigating to the code where the error is and remove the duplicate
properties. Web API controllers accept requests through the common HTTP verbs, such as
GET, POST, PUT, and DELETE. For this reason, the new controller has auto-generated
methods matching some of the most common HTTP verbs. Imagine you want to return a filtered
list of customers. To do this, rewrite the Get method as shown in Code Listing 8.
Code Listing 8
91
<connectionStrings>
<add name="NorthwindContext"
connectionString="Data Source=.\SqlExpress;Initial
Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
In real-world scenarios, you might want to supply the connection string in your C# code instead
of placing it in the configuration file, but it is not necessary in this case. Now run the application
again with commands you learned previously and open a web browser to the
http://localhost:5000 web address. By following the routing conventions of Web API, you can get
the list of customers by typing the following address: http://localhost:5000/api/Customers. The
result you get is shown in Figure 74.
With a few steps, you have been able to implement data access in your ASP.NET Core
application using Entity Framework. Additional steps might involve adding code migrations,
CRUD operations, and proper views to present information with a user interface.
92
Testing the application is very easy, as you simply need to type npm start. By default, this will
start the server listening to port 3000, so in your web browser you can reach the application at
http://localhost:3000. Figure 76 shows the sample application running.
93
Behind the scenes, the project contains a package.json file which defines a script called start
that runs node ./bin/www. This provides the startup mechanism.
94
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}\\bin\\www",
"stopOnEntry": false,
"args": [],
"cwd": "${workspaceRoot}",
"preLaunchTask": null,
"runtimeExecutable": null,
"runtimeArgs": [
"--nolazy"
],
"env": {
"NODE_ENV": "development"
},
"externalConsole": false,
"sourceMaps": false,
"outDir": null
},
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 5858,
"address": "localhost",
"restart": false,
"sourceMaps": false,
"outDir": null,
"localRoot": "${workspaceRoot}",
"remoteRoot": null
}
95
]
}
In most cases you will leave the default values unchanged, but you might need to tweak values
for the attach configuration. The properties are self-explanatory and easy to understand, but you
can always have a look at the official documentation for further details. Make sure you have
saved launch.json before going on.
Managing breakpoints
Before starting the application in debugging mode, it is useful to place one or more breakpoints
to discover the full debugging capabilities in VS Code. In order to place breakpoints, you click
the white space near the line number. For instance, place a breakpoint on the welcomeText
variable declaration you wrote previously, as shown in Figure 77.
You can remove a breakpoint by simply clicking it again, or you can manage breakpoints in the
Breakpoints area of the Debug view (see Figure 78).
96
Figure 79: The debugger encounters a breakpoint and shows all the instrumentation.
Notice how the status bar turns orange while debugging and how the Output window shows
information about the debugging process. On the left side, the Debug view shows a number of
tools:
Variables, which shows the list of variables that are currently under the debugger's
control and that you can investigate by expanding each variable.
Watch, where you can evaluate expressions.
Call Stack, where you can see the stack of method calls. If you click a method call, the
code editor will bring you to the code that is making that call.
Breakpoints, where you can manage breakpoints.
At the top of the IDE, also notice the debugging toolbar (see Figure 80) called Debug actions
pane, which holds the following commands from left to right:
97
Continue (F5), which allows continuing the application execution after breaking on a
breakpoint or an exception.
Step Over (F10), which executes one statement at a time except for method calls, which
are invoked without stepping into them.
Step Into (F11), which executes one statement at a time, including statements within
method bodies.
Step Out (F12), which executes the remaining lines of a function starting from the
current breakpoint.
Restart (Ctrl+Shift+F5), which restarts the application execution.
Stop (Shift+F5), which stops debugging.
If you hover over a variable name in the code editor, a convenient pop-up makes it easy to
investigate values and property values depending on the type of the variable. Figure 81 shows a
pop-up showing information about the app variable. You can expand properties and see their
values, and you can also investigate properties in the Variable area of the Debug side bar.
98
As another example, simply hover the welcomeText variable declared manually to see how a
tooltip shows its current value (see Figure 82). In this case the value has been hardcoded, but if
it was supplied programmatically, then this feature would make it really easy to understand if the
actual value was the expected one.
The debugger also offers the Call Stack feature, which allows stepping through the method
calls stack. When you click a method call in the stack, the code editor will open the file
containing the call, highlighting it as shown in Figure 83.
99
Finally, you have an option to use the Watch tool to evaluate expressions. While debugging,
right-click an object and then select Debug: Add to Watch (see Figure 84).
Another useful tool is the Debug console. You can open this by clicking the Open Debug
console button to the right of the gear icon in the Debug view. When you open this tool, you
can write expressions to be evaluated immediately. For instance, Figure 85 shows how to
evaluate the welcomeText variable by typing its name. Code will show the variable's current
value.
100
It is worth mentioning that the Debug console also allows sending commands to the debugger,
which is done by attaching the debugger to an already running application.
Chapter summary
The power of Visual Studio Code as a development environment is apparent when it comes to
writing real applications. With the help of specific generators, you can easily write ASP.NET 5
web applications using C# and the .NET Execution Environment (DNX). This chapter also
described how easy it is to implement Entity Framework data access with a few commands. If
you develop Node.js applications instead, you can also leverage a powerful, built-in debugger
that offers all the necessary tools you need to write great apps, such as breakpoints, variable
investigation, call stack, and expression evaluators. By completing this chapter, you have
experienced the most important and powerful features you need to write great cross-platform
applications. Now it is time to discuss how to customize Visual Studio Code.
101
102
Feature
103
Description
Type
Color themes
Customization
Customization
Key bindings
Customization
Customization
Code snippets
Customization
Debuggers
Extension
Language servers
Extension
Activation
Extension
Feature
Description
Type
Editor
Extension
Workspace
Extension
Eventing
Extension
Evolved editing
Extension
Except for color themes, key bindings, and user settings that you can customize via VS Codes
specific options, customizations and extensions share the way they can be created. In fact, you
typically create both (or at least you get started creating them) with Yeoman, the command-line
generator you already met in Chapter 4. For this reason, after showing you how to install
existing extensions, in this chapter I will describe how to create custom basic language support
plus code snippets using Yeoman. I will also put you in the right direction to get started with
extensions, but I will not cover the process of producing other types of extensions, which is
something more complex and out of the scope of a book in the Succinctly series. What you
really need to do before reading this chapter is install the Yeoman generator for VS Code, which
can be done by typing the following in the command prompt:
> npm install g yo code
Choosing a theme
Visual Studio Code ships with a number of color themes you can pick to give the environment a
different look and feel. You select a color theme by clicking File > Preferences > Color Theme.
The list of available color themes will be shown in the Command Palette, as you can see in
Figure 86.
104
Once you select a different color theme, it will be applied immediately. Also, you can get a
preview of the theme as you scroll through the list with the keyboard. For instance, Figure 87
shows the Dark (Visual Studio) theme, which is a very popular choice that is similar to the Dark
+ default theme.
105
106
If supplied by the theme producer, you can get information about a theme via the Readme and
License files. Finally, click the Install Extension button, the last on the right, to install the
selected theme. Notice that a VS Code restart will be required, and then you will be able to
apply the new theme. You can also create custom themes using the Yeoman command-line tool
that I will describe shortly.
107
Default settings relate to the code editor, file management, HTTP proxies, Git engine, linters,
Markdown preview, and installed extensions behavior (if any). The default settings view
provides detailed comments for each available setting expressed with JSON format so that you
can easily understand what setting a particular line applies to. For more details about available
settings, visit the official documentation. You can easily provide custom settings by overriding
one or more default settings, writing inside settings.json. Figure 89 shows an example where
you can see how to change the default editor font, how to remove line numbers, and how to
disable file auto-save. Also, you can see how IntelliSense will help you choose among available
settings. It is worth mentioning that using IntelliSense to pick a setting will also add a default
value that you will want to replace with a custom one.
IntelliSense also shows hints about settings with a convenient tooltip under the selected setting.
You can also expand the tooltip by clicking the information icon. When done, do not forget to
save settings.json otherwise your changes will be lost.
108
109
Simply press the keys you want to bind to a new shortcut, and then press Enter. At this point,
Visual Studio Code generates the proper JSON markup (see Figure 91), leaving you to specify
the target command and optionally a when element to specify the action context.
110
When you are done with your custom key bindings, do not forget to save keybindings.json.
111
When you select an item, VS Code starts to install it. When finished, you will be prompted to
restart the application. At this point, you will be able to use the new language and snippets as
shown in Figure 93, which shows an example based on Delphi and the newly installed
OmniPascal extension.
Figure 93: Writing Delphi Code with Syntax Colorization, Snippets, and IntelliSense Support
112
There is already rich support for important languages in the Extension Gallery, such as Python,
Cobol, Fortran, and even PowerShell scripts. Among the others, you might want to check out
the Cordova Tools for Visual Studio Code, which introduces a new debugger, commands, and
IntelliSense for Cordova projects; the Python extension, which extends Python language
support with IntelliSense, code snippets, a debugger, and enables features such as Go to
Definition, Find all References, and Go to Symbol; and Visual Studio Team Services, which
provides integration between VS Code and Visual Studio Team Services, introducing support
for team projects, work items, and code management. These are really great examples of VS
Code extensibility.
113
As you can see, with this tool you can create extensions, color themes, new languages, and
code snippets. Select New Language Support and press Enter. Next the tool will ask for
several pieces of information in sequence. So, provide the following information (see Figure 95
for reference):
1. Enter the URL or path for the .tmLanguage syntax file, in this case
https://raw.githubusercontent.com/mulander/ada.tmbundle/master/Syntaxes/Ada.tmLang
uage.
2. Enter ADA as the name of the extension.
3. Accept the ada automatic suggestion as the extension identifier.
4. Provide an extension description. In this case Im entering ADA language and code
snippets.
5. Enter your publisher name. If you plan to publish extensions to the online Visual Studio
Marketplace, keep note of the publisher name you are entering as you will need to
register online (this will be described shortly).
6. Accept ada as the languageId option. Notice that this must always be lowercase.
7. Accept Ada as the detected name, which is what you will see when you select a
language in the code editors selector.
8. Accept the proposed file extensions that VS Code will associate to the current
language.adb and .ads in this case. Of course you can add or edit file extensions.
Your new language will be created in a few seconds. Figure 95 shows the full steps and the
summary at the end of the operation.
114
The new language will be created in a subfolder of the folder where you invoked the command
prompt, which in my example is C:\Temp\Ada. Now, open the newly-created Ada folder with
Visual Studio Code. As you can see in Figure 96, the Explorer shows the list of files that the
new extension is made of. Among them, a README.md file is available and you should edit this
file into a more personalized document. Figure 96 shows an example.
115
Tip: When you use a .tmLanguage syntax file produced by other developers, though
the license agreement typically allows using it with no restrictions, it is a good idea to
give credit to the original work, as Im doing in Figure 96.
Now open the package.json file, whose content is shown in Code Listing 10. Generally
speaking, extensions and customizations have a manifest file called package.json that contains
all the necessary information for Visual Studio Code to install and run the extension properly. As
you can see, properties are self-explanatory and are the JSON counterpart of the information
you entered when using Yeoman. It is worth mentioning the importance of categories, which
are used to categorize an extension in the Visual Studio Marketplace. You can combine multiple
categories, as you will see with snippets shortly. The contributes field stores the list of
features the extension brings into Visual Studio Code--in this case, the language and its
grammar. This is also the place to provide additional contributes, as you will do with code
snippets in a moment.
Code Listing 10
{
"name": "ada",
"displayName": "ADA",
"description": "ADA language and code snippets",
"version": "0.0.1",
"publisher": "AlessandroDelSole",
"engines": {
"vscode": "^0.10.10"
116
},
"categories": [
"Languages"
],
"contributes": {
"languages": [{
"id": "ada",
"aliases": ["Ada", "ada"],
"extensions": [".adb",".ads"],
"configuration": "./ada.configuration.json"
}],
"grammars": [{
"language": "ada",
"scopeName": "source.ada",
"path": "./syntaxes/ada.tmLanguage"
}]
}
}
117
Also notice that VS Code will suggest the proper file extension when you first save a new file.
Now you have a new language, but it would be a good idea to bundle some code snippets and
make some customizations to the extension manifest.
118
TextMate and Sublime Text snippets are XML files. Basically you must enclose the code inside
the CDATA section of the content node. Notice how you can use placeholders between brackets
to define default values for a field. In this case the {1:i} placeholder means that the code
editor will highlight the i variable so that the user understands it can be replaced with a different
identifier. The number 1 will match any occurrence of the specified variable, but you could use
2, 3, and so on to suggest other default value replacements. You should also provide a
keyboard shortcut that allows activating the code snippet in VS Code by pressing Tab, which is
accomplished by providing the shortcut in the tabTrigger node. Lets leave off the scope node,
which is not necessary at this point. Save the file as AdaForLoop. Now consider the following
Ada code, which performs a simple loop..end loop loop:
loop
a := a + 1;
exit when a = 10;
end loop;
Figure 99 shows this snippet in Sublime Text.
119
Save the snippet as AdaLoopEndLoop. Now open a command prompt in the directory where
you saved the code snippet files and type yo code. When the Yeoman tool starts, select New
Code Snippets as the extension generation option. By using Figure 100 as a reference, provide
in sequence:
1. The folder that contains TextMate or Sublime snippets. You can type . if you already
opened a command prompt in the folder that contains the desired snippets.
2. The name of the extension, e.g., Ada Code Snippets.
3. The extension identifier. You can accept the auto-generated identifier.
4. An extension description.
5. Your publisher name, as you did with the language support generation.
6. The language id that your snippets are for. In this case, the language id is ada. In the
case that you are packaging code snippets for other languages, you will need to supply
the id for those languages (e.g., Markdown, Python).
120
As for a new language, Yeoman generates a new folder containing the extension manifest
(package.json), a README.md file that you are encouraged to edit before you distribute your
extension, and a subfolder called snippets, which contains a file called snippets.json. This one
contains all the code snippets you provided, converted to JSON format. You can certainly open
the new folder with Visual Studio Code and investigate the extension structure, not just edit the
README.md file. As it is, the code snippet extension is ready for distribution, so it is really easy
to package and distribute code snippets for existing languages. However, the goal now is to
distribute both the Ada language support and the JSON code snippets. First, copy the snippets
subfolder into the folder that contains the Ada language extension (see the steps listed just
before creating code snippets). Just to make sure you copy this folder into the proper place, it is
at the same level of the syntaxes and .vscode folders. Second, you need to make an edit to
the package.json file that was created for the Ada language support. More specifically,
because you can combine multiple contributes in one extension, you will add a snippets
property as shown in Code Listing 11. This snippets property can be simply copied and pasted
from the package.json that was created for the code snippet extension.
121
Code Listing 11
{
"name": "ada",
"displayName": "ADA",
"description": "ADA language and code snippets",
"version": "0.0.1",
"publisher": "AlessandroDelSole",
"engines": {
"vscode": "^0.10.10"
},
"categories": [
"Languages", "Snippets"
],
"contributes": {
"languages": [{
"id": "ada",
"aliases": ["Ada", "ada"],
"extensions": [".adb",".ads"],
"configuration": "./ada.configuration.json"
}],
"grammars": [{
"language": "ada",
"scopeName": "source.ada",
"path": "./syntaxes/ada.tmLanguage"
}],
"snippets": [{
"language": "ada",
"path": "./snippets/snippets.json"
}]
}
}
Notice how the categories property has been extended to included snippets as well. This will
make the extension discoverable when users search for both languages and snippets. Save
your edits, and run Visual Studio Code again. You already saw how the language support
works, so now type the snippet shortcuts flp and then press Tab, or llp and then press Tab.
Figure 101 shows how the loop..end loop code snippet has been inserted, highlighting
placeholders for replacements.
122
So with relatively little effort you have been able to plug a new language with code snippets into
Visual Studio Code. At this point, you are ready to share the result of your work with the rest of
the world.
123
Note: Because the personal access token will not be stored anywhere, it is essential
that you follow the portals suggestion of saving it in a secure place, as you will need it
to publish extensions online.
124
{
"name": "ada",
"displayName": "ADA",
"description": "ADA language and code snippets",
"version": "0.0.1",
"publisher": "AlessandroDelSole",
"icon": "images/MyIcon.jpg",
"license": "SEE LICENSE IN LICENSE.md",
"homepage":
"https://github.com/AlessandroDelSole/VSCodeSuccinctly/blob/AdaLanguage/REA
DME.md",
"bugs": {
"url": "https://github.com/AlessandroDelSole/VSCodeSuccinctly/issues",
"email": "alessandro.delsole@visual-basic.it"
},
"engines": {
"vscode": "^0.10.10"
},
"categories": [
"Languages"
],
"contributes": {
"languages": [
{
"id": "ada",
"aliases": [ "Ada", "ada" ],
"extensions": [ ".adb", ".ads" ],
"configuration": "./ada.configuration.json"
}
],
"grammars": [
{
"language": "ada",
"scopeName": "source.ada",
"path": "./syntaxes/ada.tmLanguage"
125
}
],
"snippets": [
{
"language": "ada",
"path": "./snippets/snippets.json"
}
]
}
}
A couple of notes about the extension manifest:
To provide an icon, create a subfolder inside the extensions folder and place a 128
128 image there.
The license property value must always be SEE LICENSE IN LICENSE.md, so you
need to add a LICENSE.md file in the root folder of your extension.
Do not forget to check out additional possibilities in the official documentation. Now you really
have all you need to publish your work online.
126
Figure 104 shows instead how the extension appears in the Command Palette, where you can
see how users can look at the license agreement and open the Readme file.
127
There is so much more in the Visual Studio Code extensibility, but in this chapter you have seen
a number of steps, information, and resources that are common to any customization and
extension you want to build.
Chapter Summary
Visual Studio Code can be customized and extended in many ways. You can customize VS
Codes settings, such as the color theme, user and workspace settings, and key bindings. You
can also download and install extensions from the Visual Studio Code Marketplace, and
manage installed extensions, using the Command Palette. Not limited to this, you can write your
own customizations and extensions using the Yeoman generator for Visual Studio Code, which
enables you to get started with extensibility quickly, such as generating new language support,
code snippets, color themes, and other kinds of extensions. Advanced extensibility has not been
discussed in this chapter, but you can definitely have a look at the documentation.
128