Table of Contents (Hide)

VS Code - How To Get Started

Introduction

VS Code (i.e., Visual Studio Code), released in 2015, is a source-code editor (or light-weight IDE) made by Microsoft for Windows, Linux and macOS. It supports syntax highlighting, intelligent code completion, snippets, code refactoring, debugging, and embedded Git. Users can change the theme, shortcuts, preferences, and install extensions. It supports many languages, including C/C++, C#, Java, Python, JavaScript, and etc.

VS Code was ranked the most popular developer environment in the Stack Overflow Developer Survey since 2018. The popularity of VS Code comes from its fast launch speed, its limited use of resources, and its better user experience.

The features include:

  • IntelliSense: supports syntax highlighting, auto code completion, bracket matching, code folding, and configurable snippets, refactoring, etc.
  • Debugging: with break points, call stacks and an interactive console.
  • Built-in Git (Source Version Control) support.
  • Extensible (via extensions) and customizable. There are many extensions in the extension market place.
  • With Microsoft Azure (cloud), you can deploy and host your React, Angular, Vue, Node, Python sites.

Install VS Code and Get Started

Goto the VS Code mother site (@ https://code.visualstudio.com/). Download the installer for your OS. I recommend ZIP version, which you can simply unzip into any directory, and remove the whole directory when it is no longer needed.

To Get Started, read or watch the video under "Docs".

(Windows) The global settings are kept in "%APP_DATA%\Code\User\Settings.json".

VS Code for Java

Read "Getting Started with Java in VS Code" @ https://code.visualstudio.com/docs/java/java-tutorial.

For your information, the 15 best Java IDEs in 2022 selected by guru99 are: Eclipse, Tabnine, IntelliJ IDEA, BlueJ, MyEclipse, Xcode, Apache NetBeans, jGRASP, Codata, Codenvy, Slickedit, JBoss Forge, JDeveloper, JEdit.

Installation

You also need to install:

  1. JDK: See "JDK - How To"; and setup environment variable JAVA_HOME.
  2. VS Code.
  3. VS Code extension "Extension Pack for Java" (an extension pack is a suit of extensions), that provides Java IntelliSense, debugging, unit testing, Maven/Gradle support, project management, integrating with frameworks such as Tomcat, Jetty and Spring Boot (with more extensions), and more. To install, select the "Extensions", and search for "Extension Pack for Java".

Open the Command Palette (Ctrl+P), enter "Java: Overview" to read a quick Java get started guide.

Getting Started

To Get Started in Java Programming (I assume that you have some basic knowledge of programming and Java):

  1. Setup and Open Workspace Folder: Create a folder, say "VSCodeJavaTest". VS Code works directly with folder that contains source codes. To set up the workspace, simply open a folder via "File" menu ⇒ "Open Folder..."
  2. Create a new Class: Point your mouse over the project name ⇒ Click on the icon "New File" ⇒ Enter "Hello.java" ⇒ A new file appears on the editor pane.
  3. Write a hello-word: In the editor pane, enter a hello-world Java program as follow.
    Try out the code snippets (you might need to wait until the "Java: Activating" turns into "Java: Ready" in the status bar):
    1. Enter "class" ⇒ select the item with a open-bottom-box icon, indicating a code snippet. VS Code will expand to the class definition.
    2. Enter "main" ⇒ select the code snippet (with open-bottom-box icon). VS Code will expand to the main() method.
    3. Enter "sysout" ⇒ select the code snippet. VS Code will expand to System.out.println(). Enter some codes.
      /**
       * Say hello
       */
      public class Hello {
          public static void main(String[] args) {
            int number = 8899;
            String msgHeader = "hello, ";
            System.out.println("hello, world");
            System.out.println("hello, again");
            System.out.println(msgHeader + number);
         }
      }
  4. Run the program:
    1. There is no need to compile your Java program. VS Code performs incremental compilation, i.e., it compile the line as soon as you enter the line and show you the compilation error immediately, if any.
    2. To run the program, push the "Run" above the main() method. You can check the output on the "TERMINAL" pane at the bottom.
      (Advanced)
      If you look at the command issued in CMD terminal to run the Java program:
      C:\path\to\workDir> c: && cd c:\path\to\workDir && cmd /C 
         ""C:\Program Files\Java\jdk-21\bin\java.exe"
             --enable-preview 
             -XX:+ShowCodeDetailsInExceptionMessages
             -cp C:\path\to\vsCode\bin
          YourJavaProgramName "
      It consists of 3 commands joined together with && (run the second command if the first command succeeds and so on):
      1. Set drive (c:)
      2. Change directory (cd \path\to\workDir)
      3. Run your Java program by invoking JRE via cmd /C "java -cp \path\to\vscode\bin YourJavaProgramName"
    3. Alternatively, you can also run your program by entering your own commands in the "TERMINAL".
      (In windows, TERMINAL is a Power Shell (PS) by default - but you can switch to the familiar Command Prompt (CMD) via the plus-down button ⇒ Select default profile ⇒ Command Prompt.)
      C:\path\to\workDir> javac Hello.java    // Compile Java program (compiled class in the same work directory)
      C:\path\to\workDir> java Hello          // Run the compiled class file
      ......
      C:\path\to\workDir> java Hello.java     // Compile and run Java source file in one step
      ......
  5. Debug the program: To debug the program, first set a breakpoint by clicking on the left-margin of a chosen statement (line), e.g., at the main() method. A solid red dot appears at the line margin. Push the "Debug" button above the main() method. A pop-up tool bar appears where you can:
    • Continue (F5): run to the next breakpoint or end of program.
    • Step Over (F10): step over the method, i.e., run the method in one step without inspecting the method.
    • Step Into (F11): step into method to inspect the method.
    • Step Out (Shift+F11): step out from the method and return to caller.
    • Restart (Ctrl+Shift+F5):
    • Stop (Shift+F5): terminal the program.
    You can check the output at the "TERMINAL" pane; and inspect or watch variables in the "Run and Debug" (right-triangle with a bug) pane on the left.
    Read "Running and debugging Java" @ https://code.visualstudio.com/docs/java/java-debugging.
Creating a Java Project

If you are writing big Java programs, you should create a Java project by bring up the command palette (Ctrl-Shift-P) ⇒ "Java: Create Java Project" ⇒ Select the Project Type (e.g., No Built Tool) ⇒ Select the "project location" ⇒ Input a "Project name". A sub-directory "Project Name" will be created under the "Project Location" with sub-sub-directories src, bin, lib.

Take note that using Java Folder (in above section), the classes are kept in a VS Code temporary directory, which is not meant for production.

Creating Java Packages

Not as straightforward as expected?! You can do one of the followings:

  1. EXPLORER ⇒ JAVA PROJECTS ⇒ Click "+" (New) besides the ProjectName ⇒ package.
  2. EXPLORER ⇒ ProjectName ⇒ src ⇒ New Folders (besides the ProjectName) ⇒ Create the directory structure corresponding to package name, where . is mapped to a sub-directory, e.g., package com.example.test is mapped to com\example\test.
  3. EXPLORER ⇒ ProjectName ⇒ right-click "src" ⇒ New Java File ⇒ Enter fully qualified class name including package name, e.g., com.example.Hello.

Unit Testing via JUnit or TestNG

Read "Testing Java with VS Code" @ https://code.visualstudio.com/docs/java/java-testing.

You need to install VS Code extension "Test Runner for Java", which support JUnit 4, JUnit 5 and TestNG.

[TODO]

Java Build Tools: Maven and Gradle

[TODO]

Working with Java Frameworks: Spring Boot, Tomcat and Jetty

Tomcat

Install extension "Community Server Connectors". A SERVERS pane appears under EXPLORER.

To configure the server: EXPLORER ⇒ SERVERS ⇒ Create New Server ⇒ Download Server (yes or no depends on whether you have the server installed) ⇒ No, use server on disk ⇒ browse to select TOMCAT_HOME directory.

You can start/stop the Tomcat server by right-click and select the option.

Tips and Tricks for Java Programming

Navigating Symbol and Search for Symbol

Right-click on a symbol, you can select:

  • Go To Definition (F12), Go To Type Definition
  • Go To Implementations, Go to References
  • Go To Super Implementation
  • Peek ⇒ Peek Definition (Alt+F12): To take a quick look at a symbol definition, without opening the target file.
  • Peek ⇒ Peek Call Hierarchy: Show method call hierarchy

Search for Symbols

  • To search for a symbol in the workspace, press Ctrl+T, and enter the name after the # prompt. You can also use Ctrl+P (Quick Open) and enter # followed by the symbol name.
  • To search for a symbol in the current file, press Ctrl+P (Quick Open), and enter @ followed by the symbol name.
Smart Semantic Selection

Place the cursor anywhere within the intended range. Use Shift+Alt+Right to expand, and Shift+Alt+Left to shrink.

Refactoring

Read "Getting Started with Java in VS Code" ⇒ "Refactoring".

Formatter

You can use "Format Document" to format your Java codes.

To edit formatter settings: choose command "Java: Open Java Formatter Settings with Preview".

Change Indentation (Tab/Spaces)

Goto "Preferences" ⇒ "Settings" ⇒ Select "User" or "Workspace" ⇒ Set the "Editor: Tab Size" and "Editor: Insert Spaces" properties.

For "Language" specific settings: Go to command palette, enter "Preferences: Configure Language Specific Settings" ⇒ Choose your language (e.g., @lang:html) ⇒ Set the "Editor: Tab Size" and "Editor: Insert Spaces" properties.

SonarLint

The "SonarLint" extension lets you detect bugs and vulnerabilities as you write code. The extension runs in the background and highlights source code that poses a quality or security concern.

Checkstyle

The "Checkstyle for Java" extension, allow you to check style using either Google's or Sun's Check or customized files.

It supports "live linting" and "batch check".

Parameter Names and Labels (x:, a:)

In the later VS Code, you see x: in front of the string inside the println(), which is not part of the executable code, but the parameter name of the println(String x) method.

To disable the labels, add this option in your settings.json file:

"editor.inlayHints.enabled": false

The location of the settings.json is:

  1. Windows: %APPDATA%\Code\User\settings.json. (On "cmd", enter "echo %APPDATA%" to find its directory.)
  2. macOS: $HOME/Library/Application/Support/Code/User/settings.json
  3. Linux: $HOME/.config/Code/User/settings.json

After Note: This is actually a good feature that should be kept! For example, in constructor Rectangle(double length, double width), the labels show the order of the parameters.

VS Code for Python

Read:

  • "Getting Started with Python in VS Code" @ https://code.visualstudio.com/docs/python/python-tutorial.
  • "Python in Visual Studio Code" @ https://code.visualstudio.com/docs/languages/python.
Installation

You need to install:

  1. Python
  2. VS Code extension "Python extension for Visual Studio Code " (an extension pack is a suit of extensions), that provides Java IntelliSense, debugging, unit testing, Maven/Gradle support, project management, integrating with frameworks such as Tomcat, Jetty and Spring Boot (with more extensions), and more.
Getting Started

To Get Started in Python Programming:

  1. Setup Workspace Folder: Create a folder, say "VSCodePythonTest". VS Code goes by folders (and sub-folders and files), instead of project or workspace.
    Launch VS Code ⇒ Select "File" menu ⇒ "Open Folder..." ⇒ Select the above folder (as your project workspace).
  2. Write a Python Script: Point your mouse over the project name ⇒ Click on the icon "New File" ⇒ Enter "Hello.py" ⇒ A new file appears on the editor pane.
    [TODO]
  3. Run: To Run the script, choose "Run Python File" from the "Run" menu (right-pointing triangle).
  4. Debug: To debug the script, set a breakpoint by clicking on the left-margin of a selected statement. Choose "Debug Python File" from the "Run" menu. The "debug task bar" appears. Click the Run (Continue) button. You can then step through the codes via the "Step Over", "Step In" and "Step Out" buttons.

[TODO]

VS Code for HTML/CSS/JavaScript/Node.js

JavaScript runs in two modes: (a) client-side JavaScript together with HTML/CSS run inside the browser; and (b) server-side (or standalone) JavaScript run under the Node.js engine.

HTML/CSS/Client-Side-JavaScript run inside Web Browser

Installation

You need to install:

  • Extensions "HTML CSS Support", "HTML Snippets", ...
  • Extension "Live Server": Launch a development local Server with live reload feature for static and dynamic pages. To launch, click "Go Live" in the status bar. Click again to close the server.
  • For HTML Live Preview, install VS Code extension "Live Preview". You can right-click an HTML file and select “Open with Live Server”.
Getting Started

To get started with HTML/CSS/Client-Side-JavaScript:

  1. Setup Workspace: Create a folder, say "VSCodeJSTest". VS Code goes by folder (and sub-folders and files), instead of project or workspace.
    Launch VS Code ⇒ File ⇒ Open Folder... ⇒ Select the above project folder.
  2. Create a new Script: Point your mouse over the project name ⇒ Click on the icon "New File" ⇒ Enter "Hello.html" ⇒ A new file appears on the editor pane.
  3. Write a hello-world: Enter the following code, which include HTML, CSS, and JavaScript. Try out the IntelliSense and Snippets, e.g., enter h1 and select snippet (with a box icon) to expand to <h1></h1>,
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8" />
      <title>HTML Testing</title>
      <style>
        h1 { color: blue }
      </style>
      <script>
        alert("hello, world");
      </script>
    </head>
    <body>
      <h1>hello, world</h1>
      <p>hello world again and again and again.</p>
    </body>
    </html>
  4. Run the Script:
    1. Click "Go Live" in the status bar to show it on the browser (via the Live Server extension). Any changes to the file will be reloaded live. Click again to disconnect.
    2. Alternatively, You can use a web browser to open the .html file. However, you need to refresh (F5) the page to get the changes.
  5. Debug the program: Use the F12 Debugger of the browser.

Standalone (or Server-Side) JavaScript run in Node.js

Installation

You need to install:

  1. Node.js, which provide a JavaScript engine for running standalone JavaScript program.
Getting Started

To get started with standalone JavaScript programs:

  1. Setup Workspace: Create a folder, say "VSCodeJSTest". VS Code goes by folder (and sub-folders and files), instead of project or workspace.
    Launch VS Code ⇒ File ⇒ Open Folder... ⇒ Select the above project folder.
  2. Create a new Script: Point your mouse over the project name ⇒ Click on the icon "New File" ⇒ Enter "app.js" ⇒ A new file appears on the editor pane.
  3. Write a hello-world: Enter the following JavaScript program. Try out the IntelliSense and snippets, e.g., you could type "log" and choose the snippet (with box icon) to expand to console.log().
    var i = 5566;
    var msg = "hello";
    console.log("hello, world");
    console.log("hello, again");
    console.log("hello, again and again");
    console.log(msg, i);
  4. Run the program:
    1. Select "Run" menu ⇒ "Run Without Debugging" (or Ctrl+F5) ⇒ Choose environment "Node.js" (if prompted). You can find the output under the "Debug Console" pane.
    2. You can also run your program by issuing your own commands in the "Terminal": Goto the "Terminal", enter "node app.js".
  5. Debug the program: To debug the program, first set a breakpoint by clicking on the left-margin of the chosen statement (a solid red dot appears). Select "Run" menu ⇒ "Start Debugging" (or F5) ⇒ Choose environment "Node.js" (if prompted). You can then "Step Over" (or "Continue" or "Stop" or "Step Into" or "Step Out') the codes via the buttons in the pop-up toolbar. You can check the output at the "Debug Console" pane; and inspect or watch variables in the "Run and Debug" pane on the left.

An Express App

Reference: https://code.visualstudio.com/docs/nodejs/nodejs-tutorial

Express is a very popular Node.js application framework. You can create a new Express app using the "Express Generator Tool". You can install via npm (Node Package Manager) as follows:

npm install -g express-generator
   // -g for global (all users)

To generate an Express app scaffold:

cd /path/to/project-folder
   // change directory to your project directory
express myExpressApp --view pug
   // Generate a new Express app
   // --view pug: to use pug template engine (pug is an HTML template preprocessor)
cd myExpressApp
npm install
   // install the dependencies
SET DEBUG=myexpressapp:* & npm start
   // run the app

You can access the server by issuing URL http://localhost:3000 from a web browser.

Stop the server by pressing Ctrl+C.

VS Code for C/C++

Read "VS Code C++" @ https://code.visualstudio.com/docs/cpp/introvideos-cpp.

For your information, the 15 best Free C++ IDE/Source-Code-Editor in 2022 selected by guru99 are: C++ Builder, Tabnine, Visual Studio Code, Eclipse, Codelite, Atom, CLion, Emacs, NotePad++, NetBeans, Codeblocks, Cevelop, Kdevelop, SlickEdit, Graviton.

Installation

You need to install:

  1. VS code extension "C/C++ Extension Pack" (an extension pack is a suit of extensions).
  2. GCC compiler: To check if you have a C/C++ compiler, issue these commands:
    gcc --version    // C compiler
    ......
    g++ --version    // C++ compiler
    ......
    gdb --version    // C/C++ debugger
    For macOS and Linux, C/C++ GCC Compiler are pre-installed.
    For Windows, you could install either Cygwin64 or MinGW-w64 C/C++ Compiler (or MSVC - Microsoft Visual C/C++ Compiler).

Getting Started

  1. Setup Workspace: Create a folder, say "VSCodeCTest". VS Code goes by folder (and sub-folders and files), instead of project or workspace. Launch VS Code ⇒ "File" ⇒ "Open Folder..." ⇒ Select the project folder.
  2. Create a new Program: Point your mouse over the project name ⇒ Click on the icon "New File" ⇒ Enter "Hello.c" or "Hello.cpp" ⇒ A new file appears on the editor pane.
  3. Write a Hello-world Program: Enter the following codes. You can type "main" and choose the snippet (with box icon) to expand to main() function.
    // Hello.c
    #include <stdio.h>
    
    int main()
    {
        printf("hello world from C\n");
        printf("hello world again\n");
        return 0;
    }
    // Hello.cpp
    #include <iostream>
    using namespace std;
    int main() {
       cout << "hello world from C++" << endl;
       cout << "hello world again" << endl;
       return 0;
    }
  4. Build (Compile & Link) and Run via Terminal: Goto "Terminal" and issue these commands:
    gcc -o Hello.exe Hello.c   // Compile and Link the C source code
    .\Hello.exe                // Run
    
    g++ -o Hello.exe Hello.cpp   // Compile and Link the C++ source code
    .\Hello.exe                  // Run
  5. Build, Run and Debug the program via "C/C++ Runner Extension"
    It is very difficult to configure the Ctrl+F5 and F5 to run and debug your C/C++ program. Instead, I install the "C/C++ Runner Extension", which provides its menu on the status bar (at the bottom of the screen).
    • First, select the project folder.
    • Build: Click the "Build" button to build the program.
    • Run: Click the "Run" button to run the program (without debugging).
    • Debug: Set a breakpoint in your program and click the "Debug" button. You can then use the pop-up toolbar to "Step Over" (or "Continue" or "Stop" or "Step Into" or "Step Out') the codes.
    [TO CHECK] Not sure if you need to create a new folder per C/C++ app (main()). Also check how the C/C++ Runner does the configurations; and set up Ctrl+F5 and F5.

Tips and Tricks

Error: #include errors detected, please update your includePath.

This error message is put up by the IntelliSense for syntax assist. You could still compile and run your program via the Terminal.

To fix this error: Select "Edit IncludePath setting" ⇒ Under IntelliSense Configurations ⇒ Include path ⇒ Add the following include paths below "${workspaceFolder}/**" (for Windows' Cygwin64):

%CYGWIN64_HOME%\lib\gcc\x86_64-pc-cygwin\11\include
%CYGWIN64_HOME%\lib\gcc\x86_64-pc-cygwin\11\include\c++
%CYGWIN64_HOME%\lib\gcc\x86_64-pc-cygwin\11\include\c++\x86_64-pc-cygwin

Check the "c_cpp_properties.json" under ".vscode" folder.

Debugging

Setting up a debugger for you programming environment and able to debug programs is the MOST important skills for a programmer.

Debug Configuration (launching)

[TODO]

Debugging Panes

The following panes appears in debug mode:

  • Variables:
  • Watches:
  • Call Stack:
  • Loaded Scripts:
  • Breakpoints:
  • Debug Console:
Debugging Toolbar's Actions
  • Continue: Continue until the next breakpoint or end of program.
  • Step-Over: Step over a function call, i.e., the function runs in one step.
  • Step-In/Step-Out: Step into or out (return) of a function call.
  • Restart: Restart program.
  • Stop: terminate the program.
  • Hot Code Replace: apply code changes without restarting the running program.

Source Version Control via Git

VS code has an embedded Git for Source Version Control. Git records all your changes to a file over time; and allow you to revert back to a specific version of your file if you wish.

Initialize Git Repository
git config --global init.defaultBranch main

Choose "View" menu ⇒ "Source Control". Push "Initialize Repository".

.ignore: [TODO]

Creating a branch

[TODO]

Tips and Tricks

Spell Checker: Install VS Code extension "Code spell checker". Positioning the cursor in the mis-spelt word, click the lightbulb or Ctrl-dot for suggestions. To edit the dictionary, goto settings ⇒ search "c spell: word" for this workspace or all users.

IntelliSense: This is the most important editing feature, which can improve your productivity many folds. It includes auto-code-complete, documentation, templates, syntax highlighting, and many more. You need to try it out.

Command Palette: Command Palette is one of the most strange/innovative feature in VS Code. You can enter any commands instead of using the menu or tool bar. Goto "View" menu ⇒ "Command Palette".

Zoom In/Out (Ctrl++ and Ctrl+-)

Autosave: You can autosave your edited files by enabling "autosave", via selecting "File" menu ⇒ "Auto Save". I see no reason why you should not enable autosave.

Source Formatting: Right-click on a file ⇒ Format Document (Shift+Alt+F).
You should also turn on these editor preference settings: "editor: format on type" (editor automatically format the line after typing), "editor: format on paste" (editor automatically format the paste content).
To do this, goto "File" menu ⇒ "Preferences" ⇒ "Settings" ⇒ Enter "format on type" ⇒ check "Editor: Format on Type".

Column (Block) Select: Hold Shift-Alt (Windows) or Shift-Option (macOS) while dragging your mouse with the left-mouse-button.

Rename (Refactor) Variables: Select the variable ⇒ right-click ⇒ Rename Symbol (F2) ⇒ type the new name. All the occurrences of this variable will be renamed.

Indentation (Space/Tab): For my Java programs, I prefer indentation of 3 spaces (with spaces instead of tab). Click on the "spaces: 4" on the status bar, select command "Indent using spaces" and "3". You can then reformat the source code via F2.

Quick Open (Ctrl+P): For you to quickly open one or more files.

Multiple Cursors (Alt+Click): You can add additional cursor via Alt+click. You can also add additional cursors of all the current selection via Shift+Ctrl+L. For example, do a "Find (Ctrl+F)" on a certain word, remove the Find menu, and Shift+Ctrl+L.

Customized Keyboard Shortcut: [TODO]

REFERENCES & RESOURCES