© Alessandro Del Sole 2019
Alessandro Del SoleVisual Studio Code Distilledhttps://doi.org/10.1007/978-1-4842-4224-7_3

3. Language Support and Code Editing Features

Alessandro Del Sole1 
(1)
Cremona, Italy
 

Visual Studio Code is not just another evolved text editor with syntax colorization and automatic indentation. Instead, it is a very powerful code-focused development environment expressly designed to make it easier to write web, mobile, and cloud applications using languages that are available to different development platforms.

With the ambition to provide a powerful, rich development environment, Visual Studio Code integrates a number of editing features that are focused on improving the productivity and quality of your code. This chapter discusses what languages are supported in Visual Studio Code and all the available code editing features, starting from the most basic that are available to all the supported languages to the most advanced productivity tools that are available to specific languages such as C# and TypeScript.

Note

Keyboard shortcuts used in this chapter are based on the default settings in Visual Studio Code.

Language Support

Out of the box, Visual Studio Code has built-in support for many languages. Table 3-1 groups supported languages by editing features.
Table 3-1

Language Support by Feature

Languages

Editing Features

Batch, C, C#, C++, Clojure, CoffeeScript, Diff, Dockerfile, F#, Go, HLSL, Jade, Java, HandleBars, Ini, Lua, Makefile, Objective-C, Objective-C++, Perl, PowerShell, Properties, Pug, Python, R, Razor, Ruby, Rust, SCSS, ShaderLab, Shell Script, SQL, Visual Basic, XML

Common features (syntax coloring, bracket matching, basic word completion)

Groovy, Markdown, PHP, Swift

Common features and code snippets

CSS, HTML, JSON, JSON with Comments, Less, Sass

Common features, code snippets, IntelliSense, Outline

TypeScript, TypeScript React, JavaScript, JavaScript React

Common features, code snippets, IntelliSense, Outline, parameter hints, refactoring, Find All References, Go To Definition, Peek Definition

Visual Studio Code can be extended with additional languages produced by the developer community and that can be downloaded from the Visual Studio Marketplace. This is discussed in more detail in Chapter 6, “Installing and Managing Extensions,” but, in the meantime, you can have a look at the available languages.

Working with C# and C++

The C# programming language deserves a more detailed version, because of its popularity and because it is now a cross-platform language that you can use not only on Windows but also on macOS and Linux. As you can see from Table 3-1, the editing experience that Visual Studio Code offers out of the box for C# is limited to common features.

However, full and rich support for the coding experience with C# is offered via the Microsoft C# free extension ( https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp ). This provides an optimized experience for .NET Core development and includes all the support and tools you need to build apps with C#, including the necessary support for the .NET Core debugger. With this extension, you will basically get the same experience available to TypeScript, including advanced editing capabilities based on the .NET Compiler Platform (also known as Roslyn) that makes it easier to fix code issues as you type. If you plan to work with C#, I definitely recommend you to install this extension, especially because this chapter discusses some editing features that are available only through the extension. Extensibility is explained in more detail in Chapter 6, "Installing and Managing Extensions," so the easiest way to get the extension installed without further information is opening any C# code file (.cs) and following the instructions shown by Visual Studio Code when it detects that a proper extension is available for that file type.

Similarly, you might want to install the Microsoft C/C++ extension that adds enhanced editing features to the C and C++ languages, plus debugging support for Windows (PDB, MinGW, Cygwin), macOS, and Linux. The extension is available at https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools , and you can follow the same steps described before about the C# extension for easy installation, of course opening a .c, .h, or .cpp file.

Basic Code 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 2017, 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 the editing features, giving you an option to edit code faster. For this reason, the keyboard shortcut is also mentioned for many of the described features.

Note

Features described in this section apply to all the supported languages described in Table 3-1, except where expressly specified.

Working with Text

As you would expect, the code editor in VS Code offers commands for text manipulation and text selection. The Edit menu provides the Undo, Redo, Copy, Cut, Paste, Find, Replace, Find in Files, and Replace in Files commands. These commands are available in every text editor and do not require any further explanation, except for the find and replace tools that were described in the previous chapter.

The Edit menu also includes the Toggle Line Comment and Toggle Block Comment commands, which add a single line comment or a block comment, respectively, depending on the language. For instance, in C# the first command would comment a line like this:
// int a = 0;
Instead, the block comment tool would add a multiline comment as follows:
/* */ int a = 0;

The Edit menu also provides two commands to work with code snippets, Emmet: Expand Abbreviation and Emmet…. The first command is the menu representation of keyboard shortcuts offered by code editor to add a code snippet, whereas the second command opens the Command Palette and shows the list of code snippets that you can add. Code snippets are discussed in more detail in the “Reusable Code Snippets” section in this chapter.

The Selection menu not only provides commands for text selection but also commands that make it easier to move or duplicate lines of code above and below the current line. The Add Cursor Above, Add Cursor Below, and Add Cursors To Line Ends commands allow working with multicursors, described in the “Multicursors” section in this chapter.

If you click an identifier, reserved word, or type name in the editor, you can use the Add Next Occurrence, Add Previous Occurrence, and Select All Occurrences commands that allow to quickly select occurrences of the selected word, and occurrences will be highlighted in a different color, which differs depending on the current theme.

Syntax Colorization

For all the languages summarized in Table 3-1, the code editor in Visual Studio Code provides the proper syntax colorization. Figure 3-1 shows an example based on a TypeScript code file.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig1_HTML.jpg
Figure 3-1

Syntax colorization

Syntax colorization is available for other languages via extensibility. If you need to work with a language that is not included out of the box, you can check the Visual Studio Marketplace and see if an extension is available to support such a language. See Chapter 6, "Installing and Managing Extensions," for information about extensibility. As a side note, syntax colorization is the minimum that an extension must provide to add support for a new language.

Delimiter Matching and Text Selection

The code editor can highlight matching delimiters such as brackets and parentheses (both square and round). This feature is extremely useful to delimit code blocks and is triggered once the cursor gets near one of the delimiters. Figure 3-2 shows an example based on bracket matching in a constructor definition.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig2_HTML.jpg
Figure 3-2

Delimiter matching

This feature is also very useful when you need to visually delimit nested blocks and with complex and long expressions. It is worth mentioning that you can press Ctrl+D to fast select a word or identifier at the right of the cursor and that you can also easily expand (Shift+Alt+Right) and shrink (Shift+Alt+Left) text selection within enclosing delimiters of a code block.

Code Block Folding

The code editor allows folding delimited code blocks. Just hover line numbers and the - symbol will appear near the start of a code block. Simply click to fold, and you will see the + symbol at this point, which you click to unfold the code block. Figure 3-3 provides an example.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig3_HTML.jpg
Figure 3-3

Code block folding

Multicursors

The code editor supports multicursors . Each cursor operates independently, and you can add secondary cursors by pressing Alt-Click at the desired position. You will see that secondary cursors will be rendered thinner. The most typical situation in which you want to use multicursors is when you want to add (or replace) the same text in different positions of a code file.

Reusable 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. See the “Language Support” section to discover what languages support code snippets natively. For instance, in a Swift file, you can easily add a do..catch block definition by using the do code snippet, as shown in Figure 3-4.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig4_HTML.jpg
Figure 3-4

Adding code snippets

Code snippets are available as you type within the code editor, and you can recognize them by the icon representing a small, white sheet. Notice how a tooltip shows a preview of the code snippet. Pressing Tab over the previous snippet produces the result shown in Figure 3-5.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig5_HTML.jpg
Figure 3-5

A newly added code snippet with a variable name highlighted

Notice that if the code snippet contains variable names or identifiers, these might be highlighted suggesting that you should give them a different name (like for the error identifier in Figure 3-5). When you rename a highlighted identifier, all occurrences will be also renamed.

Visual Studio Code is not limited to built-in code snippets. You can download code snippets produced by other developers for many languages from the Visual Studio Marketplace. Actually, most of the extensions that introduce or extend support for programming languages also include a number of code snippets .

Word Completion

Out of the box, the code editor in Visual Studio Code implements basic word completion for all the supported languages. This feature helps you complete words and statements as you type. For example, if you look at Figure 3-6, you can see how the code editor suggests terminating a statement with the Class keyword in a Visual Basic file, based on what the developer is typing.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig6_HTML.jpg
Figure 3-6

Completing a statement with word completion

Simply press Enter or Tab to insert the suggested word. The word completion engine learns as you code and can provide suggestions based on variables and member names you declare. For example, Figure 3-7 demonstrates how the editor suggests adding the name of a variable called Test, declared previously in the code.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig7_HTML.jpg
Figure 3-7

The code editor can suggest identifiers declared in the code

Minimap Mode

Sometimes it is difficult to have an idea of the position of the cursor inside a source code file, especially with very long files. Visual Studio Code provides the Minimap , a small preview of the source code file on the code editor’s scrollbar. Figure 3-8 provides an example.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig8_HTML.jpg
Figure 3-8

The Minimap allows for previewing source code on the scrollbar

If you click the Minimap, the portion of source code that is visible in the code editor is highlighted in the scrollbar, so that you can have a better perception of the current position of the cursors. The Minimap can be disabled and enabled using the ViewToggle Minimap command.

Whitespace Rendering and Breadcrumbs

A very common feature with text editors is the possibility of showing light dots instead of white spaces. In Visual Studio Code, this is possible for white spaces within indentations. To accomplish this, you select View Toggle Render Whitespace . Figure 3-9 shows an example of how white spaces for indentations are replaced with dots.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig9_HTML.jpg
Figure 3-9

Rendering indentation spaces with dots

Simply use again the same command to return to white spaces. Another very useful command is Toggle Breadcrumbs , available in the View menu. With supported languages, such as JavaScript, TypeScript, and C# with the extension installed, it shows an icon at the upper left corner of the code editor, which you can expand to see the definition of types and members, as shown in Figure 3-10.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig10_HTML.jpg
Figure 3-10

Navigating between types and members with breadcrumbs

By clicking a type or member name, the cursor will be moved to its definition, making code navigation much easier.

Markdown Preview

Visual Studio Code supports the Markdown syntax for producing documents in the very popular .md file format. Other than syntax colorization, for this particular language Visual Studio Code also provides a preview of how the document will look like. Simply press Ctrl+Shift+V (Cmd+Shift+V on macOS) in the code editor, and the preview will appear in a separate window, as demonstrated in Figure 3-11.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig11_HTML.jpg
Figure 3-11

Integrated Markdown preview

This feature is very useful because it allows to preview your documents without the need of an external program such as a web browser.

Evolved Code Editing

Visual Studio Code is an extremely powerful code editing tool and brings to a cross-platform and multilanguage environment many features that have been available in Microsoft Visual Studio since many years, providing what is called evolved code editing. This section explains all the advanced code editing features that are available, out of the box, to languages such as TypeScript and JavaScript and to languages like C#, C++, and Python with the appropriate extensions installed.

Working with IntelliSense

IntelliSense provides rich, advanced word completion via a convenient popup that appears as you type. In the developer tools from Microsoft, such as Visual Studio, IntelliSense has always been one of the most popular features, and the reason is that 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-12 shows IntelliSense in action with a C# code file.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig12_HTML.jpg
Figure 3-12

IntelliSense showing suggestions as you type and advanced word completion

As you can see in Figure 3-12, IntelliSense shows the list of available members as you write, for the given type (in this case Console). When you select a word from the completion list, Visual Studio Code shows the member documentation.

Note

The documentation for a type or member will only be available if it has been supplied by the developers. For example, in C# the documentation for types and members must be provided with XML comments. This will enable IntelliSense to display it in a tooltip, like in Figure 3-12.

Press either Tab or Enter to complete the word insertion. Not limited to this, IntelliSense in Visual Studio code 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 3-13.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig13_HTML.jpg
Figure 3-13

Suggestion filtering in IntelliSense

IntelliSense also provides the foundation for other advanced features in the code editor that depend on it, described in the next subsections.

Parameter Hints

When you write a function invocation, IntelliSense also shows a tooltip that describes each parameter. This feature is called parameter hints and is available only if the documentation for function parameters has been implemented. An example is visible in Figure 3-14.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig14_HTML.jpg
Figure 3-14

IntelliSense shows parameter hints

For languages such as C# and TypeScript or, more generally, with languages that allow for function overloads, parameter hints show the description for the parameters of each overload. You can also scroll the list of overloads with the up and down arrow keys to select a different overload .

Inline Documentation with Tooltips

If you hover types, variables, and type members, Visual Studio Code will show a tooltip that contains the documentation for the selected object. Figure 3-15 provides an example.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig15_HTML.jpg
Figure 3-15

Tooltips provide quick, inline documentation

Like parameter hints, this feature is available only if the documentation has been implemented. If you instead hover a variable name, the tooltip will only show the type for the variable.

Go To Definition

Visual Studio Code provides another interesting feature called Go To Definition . You can hover over a symbol with the mouse and, if you press Ctrl (or ⌘ on macOS), the symbol will appear as a hyperlink; also, a tooltip will show the code that declares that symbol. You click the type name while pressing Ctrl, and you will be redirected to the code that defines that type. Figure 3-16 shows how the code editor appears when you press Ctrl and hover over a type name.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig16_HTML.jpg
Figure 3-16

Ctrl + hovering over a type enables Go To Definition

The same tool is available if you select a type name and press F12 or if you right-click a type name and then select Go To Definition from the context menu. This is an extremely useful feature that lets you quickly browse between type definitions that are in different code files.

Note

For C#, Go To Definition can also open the definition of a type exposed by the .NET Core libraries, not just your code.

Find All References

Find All References is a very useful feature that makes it easy to see how many times and where a type or member has been used across the code. For each type or member, the code editor shows how many times a member has been referenced and in which files. Figure 3-17 shows an example based on finding all references of a type called Startup.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig17_HTML.jpg
Figure 3-17

Finding all references of types and members

If you click an occurrence in the list on the right, the code editor brings up a popup containing the code where that occurrence has been found. It is very important noting that this popup is interactive, which means that you can edit the code directly, without the need of opening the containing code file separately. This allows keeping your focus on the code, saving time. Also, notice that the interactive popup shows, at the top, the file name that contains the selected reference .

Peek Definition

Suppose you have dozens of code files and that you want to see or edit the definition of a type you are currently using. With other editors, you should search among the code files, which not only can be annoying but that 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 right-click a type name and then select Peek Definition (the keyboard shortcut is Alt+F12); an interactive popup window appears, showing the code that defines the type, giving you not only an option to look at the code but also of direct editing. Figure 3-18 shows the peek window in action.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig18_HTML.jpg
Figure 3-18

Working on a type defined in another file with Peek Definition

As you can see, the peek window is very similar to the Find All References feature, and it still shows the file name that defines the type at its top. Simply click the file name to open the code file in a separate editor.

Renaming Symbols and Identifiers

It is very frequent to rename a symbol, 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 Symbol command, a small interactive popup appears. Figure 3-19 shows an example based on a symbol called app. There you can write the new name without any dialogs, keeping your focus on the code.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig19_HTML.jpg
Figure 3-19

Renaming symbols

All references of that symbol will be renamed accordingly. Additionally, you can rename all the occurrences of an identifier. You simply right-click the identifier, then select Change All Occurrences (or press Ctrl+F2 on Windows/Linux and ⌘+F2 on macOS); all the occurrences will be highlighted and updated with the new name as you type.

Live Code Analysis

With C#, TypeScript, and with languages whose support can be enhanced via extensions like Python, Visual Studio Code can detect code issues as you type, suggesting fixes and offering code refactorings. This is one of the most powerful features in this tool, which is something that you will not find in most other code editors. The next examples are based on the C# programming language, since (together with TypeScript) this supports the richest experience possible in Visual Studio Code, and therefore it is a good choice to discuss the powerful coding features available. Of course, everything discussed here applies to all other languages that support the same enhanced features.

According to the severity level of a code issue, Visual Studio Code underlines with squiggles the pieces of code that need your attention. 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 3-20 shows two code issues, one with green squiggles (an unused local variable) and one with red squiggles (a symbol that does not exist), plus the tooltip for the code issue with the higher severity level.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig20_HTML.jpg
Figure 3-20

Code issue detection as you type

Code issues are detected as you type and they are also listed in the Problems panel. If you look at Figure 3-20, you can also see an icon with the shape of a light bulb. This icon is a shortcut for a tool called Light Bulb. When you click the Light Bulb, Visual Studio Code shows possible code fixes for the current context. For example, if you look at Figure 3-21, you can see the suggestions that the Light Bulb provides to fix the missing symbol underlined with red squiggles.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig21_HTML.jpg
Figure 3-21

Potential fixes suggested by the Light Bulb

In this particular case, the editor suggests four options, such as creating a field, a read-only field, a property, or a local variable. In this particular case, a field would be created as follows:
private static bool welcomeMessage;
Instead, a property would be generated like this:
public static bool welcomeMessage { get; private set; }
Probably bool is not the type you would expect here, but Visual Studio Code has not enough information to infer a different type. However, when the code contains some information that Visual Studio Code could use to understand the proper type, properties, fields, and local variables would be generated of the expected type. With the Light Bulb, it is also easier to generate types on the fly. Figure 3-22 shows an example based on an object called person, for which a type has not been defined yet. As you can see, for this context the code editor shows a larger list of possible fixes, including generating a new class, either in the current file or in a separate file.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig22_HTML.jpg
Figure 3-22

Generating types on the fly

Not limited to this, the Light Bulb can help you refactor your code and keep it cleaner. For example, you can click any of the using directives (or equivalent in other languages) and, when the Light Bulb appears, you can see how it offers to remove unused code, as shown in Figure 3-23.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig23_HTML.jpg
Figure 3-23

Code refactoring made easy

Actually, there is even more power. Suppose you want to create a class that implements the IDisposable interface . As you can see in Figure 3-24, the code editor cannot find the definition of such interface and shows a red squiggle, but the Light Bulb provides shortcuts for quickly fixing this issue. For example, it suggests adding a using System; directive, which is what the code needs.
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig24_HTML.jpg
Figure 3-24

Adding missing directives

At this point, IDisposable will be still underlined with a red squiggle because the code is not implementing the interface yet. If you still enable the Light Bulb, you will see how the code editor suggests potential fixes based on the current context, such as implementing the interface in different ways (see Figure 3-25).
../images/474995_1_En_3_Chapter/474995_1_En_3_Fig25_HTML.jpg
Figure 3-25

The Light Bulb provides suggestions based on the current context

Just to give you an idea of the power of this tool, following is the code that is generated if you choose to implement the interface with Dispose pattern:
using System;
public class Person: IDisposable
{
    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls
    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects).
            }
            // TODO: free unmanaged resources (unmanaged objects)
            // TODO: set large fields to null.
            disposedValue = true;
        }
    }
    // TODO: override a finalizer only if Dispose(bool disposing) above
    // has code to free unmanaged resources.
    // ~Person() {
    //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    //   Dispose(false);
    // }
    // This code added to correctly implement the disposable pattern.
    public void Dispose()
    {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }
    #endregion
}

You would get a similar result, but with different implementation, if the choice was one of the other possible code fixes. 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.

Summary

Visual Studio Code is a code-centric tool that supports out of the box a wide variety of languages, offering coding features such as syntax colorization, delimiter matching, code block folding, multicursors, code snippets, and code completion that are common to all the supported languages.

In addition, languages such as TypeScript and C# provide the so-called evolved code editing experience via integrated tools such as IntelliSense, Go To Definition and Peek Definition, Find All References, and the extremely powerful Light Bulb that detects code issues as you type and that suggests potential fixes based on the context. Now that you have knowledge of the powerful coding features that Visual Studio Code offers, it is time to see how to use them with individual source code files and structured folders.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.64.128