Unleashing the Power of GitHub Copilot in Visual Studio Code

by John Miller | November 11, 2024

In recent years, AI has been revolutionizing the way we code. One of the most exciting developments in this field is GitHub Copilot, an AI-powered code assistant developed by GitHub in collaboration with OpenAI. It leverages machine learning models trained on billions of lines of public code, allowing it to understand context and provide relevant suggestions. Whether you're writing a new function or fixing a bug, Copilot is there to help streamline your coding process. Let's dive into the basics of using GitHub Copilot in Visual Studio Code (VS Code) to supercharge your development workflow.

Getting Started

1. Installation

To start using GitHub Copilot in VS Code, you'll need to install the GitHub Copilot extension. Here's how:

  • Open Visual Studio Code.
  • Go to the Extensions view by clicking the Extensions icon in the Activity Bar on the side of the window or by pressing Ctrl+Shift+X.
  • Search for “GitHub Copilot” and click Install.

GitHub Copilot is a paid service with a 30-day free trial. Refer to the GitHub documentation to select a plan and signup for an account. See Subscription plans for GitHub Copilot - GitHub Docs for more information on signing up for Copilot.

2. Authentication

After installing the extension, you'll need to authenticate with your GitHub account:

  • Open any file or create a new one.
  • Start typing, and Copilot will prompt you to sign in to GitHub.
  • Follow the on-screen instructions to complete the sign-in process.

Basic Concepts

1. Autocomplete Suggestions

As you type, GitHub Copilot provides real-time code suggestions. You can accept these suggestions by pressing Tab. If you see multiple suggestions, you can navigate through them using the Up and Down arrow keys.

Copilot Auto-complete example

Here with little prompting of Copilot, other than the name of code file (circle.cs), Copilot generates suggested implementations of the class. The acceptance toolbar shows three suggestions and you can rotate through them with the arrows. From the toolbar you can also open the Completions Panel and see all suggestions. In this case, there are 10 suggestions. You can tab to accept the displayed suggestion or in the Completion Panel accept a specific suggestion.

Autocomplete makes a good attempt at suggesting code; when it's context aware it becomes very powerful.

2. Context-Aware Code

Copilot understands the context of your code. For example, if you're writing a function, it can suggest complete function implementations based on the function name and its parameters. It can even provide comments and documentation snippets. The context-aware capabilities of GitHub Copilot allow it to understand the structure and purpose of your code.

Given this definition of the Circle class:

public class Circle : Shape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    public override double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

Copilot infers several things:

  • Class inheritance: The Circle class inherits from a Shape class, suggesting that Circle is a specific type of shape.
  • Properties and methods: The class has a Radius property and an Area method, indicating that it deals with geometric calculations.
  • Constructor: The constructor initializes the Radius property, which is essential for any calculations involving the circle.

Given this context, when you ask Copilot to add a new method, it suggests relevant methods that are typical for a circle, such as calculating the circumference. It can also provide appropriate comments and documentation based on common practices:

    /// <summary>
    /// Calculates the circumference of the circle.
    /// </summary>
    /// <returns>The circumference of the circle.</returns>
    public double Circumference()
    {
        return 2 * Math.PI * Radius;
    }

For example, when adding the Circumference method, Copilot understands that:

  • The method should be related to the geometric properties of a circle.
  • It should use the Radius property.
  • It should follow the same style and conventions as the existing Area method.
  • This context awareness helps Copilot provide accurate and relevant code suggestions that fit seamlessly into your existing codebase.

Context awareness learns how you write code and tries to emulate your style. For example, if you start and end most methods with a log entry, Copilot will recognize the pattern and offer to insert a log entry consistent with the pattern and tailored to the current context.

3. Multiline Completions

For more complex tasks, Copilot can suggest multi-line completions. These are especially useful for boilerplate code, loops, or error handling. You can accept these suggestions in the same way as single-line completions. The autocomplete suggestions for the circle class example is a good example of multiline insertions.

4. Example-Based Learning

You can teach Copilot by providing examples. If you write a few lines of code or a comment describing what you want, Copilot can suggest the next lines of code. This can be incredibly powerful for repetitive tasks or following specific coding patterns.

For example, if we add the comment to the circle.cs:

// Oval is a shape class that inherits from Circle and overrides the Area method

And we start the definition of a class on the next line. Copilot will suggest a class that implements the comment.

Copilot Oval class suggestion

This works for other code comments. The comment, “Loop through all of the accounts and apply a discounts of 10% to the accounts with a lifetime value greater than 100000” would generate a suggestion that contained a request for the accounts, a loop through the accounts, a condition to select an account, and that application of the discount. If Copilot is aware how data is requested in other parts of the app, how lifetime value is derived, and how discounts are applied.

Copilot Workspaces

The @workspace command in GitHub Copilot is a powerful feature that allows you to ask questions about your entire codebase. When you use @workspace, Copilot intelligently retrieves relevant files and symbols from your workspace to provide context-aware answers. Here are some ways you can use @workspace:

  • Finding Existing Code: You can ask questions like, “Where is the database connection string configured?” or “How can I validate a date?” Copilot will find and reference the relevant code in your workspace1.
  • Planning Code Edits: You can ask for plans on how to implement specific features, such as, “How can I add a rich tool-tip to a button?” or “Add date validation to #selection”. Copilot will provide a plan based on your existing code.
  • Explaining Concepts: You can ask higher-level questions like, “How is authentication implemented?” or “Which API routes depend on this service?” Copilot will give an overview and reference relevant parts of your code.
  • Workspace Context: @workspace uses the same sources a developer would when navigating a codebase in VS Code, such as all files in the workspace (except those ignored by .gitignore), directory structure, symbols, and definitions.

By using @workspace, you can make Copilot an expert in your workspace, helping you navigate and understand your codebase more effectively.

Copilot Functions

GitHub Copilot provides several core capabilities that can be accessed in several ways. These capabilities are doc, explain, fix, generate, optimize, and tests.

doc

The /doc command is used to provide documentation or explanations for a given code. It can generate comments, summaries, or detailed descriptions to help understand the functionality and purpose of the code.

explain

The /explain command is used to provide an explanation or description of a given code snippet, helping to understand its functionality and how it works. This particularly useful when dealing with code you didn't write or code that is generated.

fix

The /fix command is used to identify and correct issues in a given code snippet, such as syntax errors, logical errors, or other problems that may be present.

generate

The /generate command is used to generate new code snippets or suggestions based on the provided context or instructions. It helps in creating boilerplate code, completing code, or generating new functionality based on the given input.

optimize

The /optimize command is used to improve the performance or efficiency of a given code snippet. It analyzes the code and suggests or applies optimizations to enhance its execution speed, memory usage, or overall efficiency.

test

The /test command is used to generate unit tests for a given code snippet. It helps in creating automated tests to verify the functionality and correctness of the code.

Copilot Integration With VS Code

Copilot integrates with many IDEs. In this post, I'm describing the integration with VS Code. The integration with other IDEs should be similar but may be different.

The Copilot Chat

Copilot chat

Copilot Chat commands are special commands you can use within the chat interface to quickly perform common tasks or get specific information. Here are some of the key commands:

Common GitHub Copilot Chat Commands

Command Description Example
/doc Adds documentation comments for the specified or selected code. /doc AddBasketAsync method in BasketService.cs
/explain Provides explanations for the selected code. /explain the AddItemToBasket method in BasketService.cs
/fix Proposes a fix for problems in the selected code. /fix the SetQuantities method in BasketService.cs
/generate Generates code to answer your question. /generate a function to sum all numbers in a list
/help Gets help with Copilot Chat. /help
/optimize Analyzes and suggests improvements for the running time of the selected code. /optimize the fetchData function
/tests Creates unit tests for the selected code. /tests for the calculate_circle_area function

Using Chat Variables

You can also use chat variables to provide more context to Copilot:

  • #selection: Refers to the selected text in your code.
  • #file: Refers to the current file.
  • #editor: Refers to the current editor.
  • #codebase: Refers to the entire codebase.
  • #git: Refers to the Git repository.

Example Usage

Let's say you want to add documentation to a method:

function fetchData(url) {
    // Fetch data from the URL
    return fetch(url)
        .then(response => response.json())
        .then(data => {
            console.log(data);
            return data;
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

You can use the /doc command to add comments:

/doc fetchData method in DataService.js

Copilot will then add appropriate documentation comments to the fetchData method.

These commands can help you quickly perform tasks and get information without leaving your IDE, making your coding process more efficient.

Chat Window, Chat With Extension Feature

The Chat with Extension feature allows you to target your prompt to an GitHub Copilot Extension.

Copilot chat with extension

If you are interested in the current workspace, the @workspace command will return the current workspace contents. Selecting the “@” sign inserts the @ sign into the chat which brings up a list of extensions and their commands. Any characters after the @ filters the list. Below I've added a w and the list is filtered to workspace commands.

GitHub Copilot with the @w entered, which filters the responses to the commands that begin with w.

There are quite a few extensions from third-party vendors. Be sure to checkout the GitHub Copilot Marketplace.

Chat Window Attach Context Feature

This feature adds content to the workspace.

Copilot chat attach context

Selecting to attach content brings up a list of content types.

GitHub Copilot with a list of attachment types

Chat Window Voice Chat and Pick Model Features

These actions are self explanatory and do what you would expect.

GitHub Copilot voice chat. Click to speak into GitHub Copilot and it will translate your voice to text.

In GitHub Copilot list where you can pick the model you want to use.

Chat Window Send Menu

The send button submits a prompt and the drop-down exposes a menu of send options.

Copilot chat send menu

Send vs. Send and Dispatch

“Send” will send your message as it is, while “Send and Dispatch” will send your message and also execute the relevant GitHub Copilot Chat Assistant functions to provide a more interactive and dynamic response.

Send to @workspace

“Send to @workspace” allows you to send the current code snippet or message to your workspace, which can be a shared environment or project space where team members can collaborate and view shared content.

Send to Copilot Edits

“Send to Copilot Edits” sends the selected code snippet to GitHub Copilot for suggestions and improvements, allowing you to receive inline code edits or enhancements directly within your development environment.

Send to New Chat

“Send to New Chat” allows you to send the current message or code snippet to a new chat session, creating a separate conversation thread for that specific content.

The Copilot Shortcut Menu

Copilot shortcut menu

In VS Code you can right-click in the code editor and then select the Copilot menu option to bring up the Copilot shortcut menu.

Editor Inline Chat

The GitHub Copilot Editor, which appears inline, where you can interact with Copilot.

The “Editor Inline Chat” menu option in GitHub Copilot allows you to start an inline chat session directly within your code editor. This feature enables you to interact with GitHub Copilot in a conversational manner, asking questions and receiving context-aware responses and code suggestions right next to your code. It helps you get real-time assistance and explanations without leaving your coding environment.

Explain, Fix, Generate Docs, and Generate Tests

These are the same options as in the main chat window, but they are scoped to the inline context.

Review and Comment

The “Review and Comment” menu option in GitHub Copilot allows you to review the selected code and provide comments or feedback. This feature helps you to analyze the code, suggest improvements, and document your thoughts directly within the code editor. It facilitates collaboration and code review processes by enabling you to leave detailed comments and suggestions for yourself or your team members.

Running the Review and Comment menu option in GitHub Copilot

Running Review and Comment on the circle class generates suggestion for adding XML comments to the code and allows you accept or discards the suggestions.

Add File to Chat

The “Add File to Chat” menu option in GitHub Copilot allows you to include an entire file in your chat session. This feature enables you to discuss, review, or get assistance on the entire content of a file, rather than just a selected snippet. It helps in providing context-aware suggestions, explanations, or improvements for the whole file.

Copilot Extensions

GitHub Copilot Extensions are additional tools and features that enhance the functionality of GitHub Copilot within your development environment. These extensions can provide various capabilities such as:

  • Language Support: Extensions for different programming languages to provide context-aware code completions, suggestions, and documentation.
  • Framework Integration: Extensions that integrate with specific frameworks or libraries to offer tailored code suggestions and best practices.
  • Testing and Debugging: Tools to help generate unit tests, debug code, and ensure code quality.
  • Documentation: Features to automatically generate documentation comments and summaries for your code.
  • Code Optimization: Extensions that suggest performance improvements and optimizations for your code.

These extensions aim to improve your coding experience by providing more relevant and powerful assistance based on the specific context of your project and the technologies you are using. See the GitHub Copilot Marketplace to find and install extensions.

Tips for Effective Use

Write Descriptive Comments

To make example-based learning suggestions more effective, use clear, descriptive comments to help Copilot understand your intent. This will improve the relevance and accuracy of the suggestions.

Review and Edit

Always review the suggestions provided by Copilot. While it is a powerful tool, it may not always produce perfect code. Treat GitHub Copilot's suggestions as a starting point rather than the final solution.

Experiment With Different Prompts

If Copilot's suggestions aren't quite what you're looking for, try rephrasing your comments or writing a different code snippet to see if it provides more relevant suggestions.

Conclusion

GitHub Copilot is a game-changing tool for developers. It can significantly speed up your coding process, reduce the mental load of writing boilerplate code, and even inspire new approaches to problem-solving. By integrating Copilot into your VS Code workflow, you can focus more on the creative aspects of development while letting AI handle the mundane tasks.


Prompts:

  • Can you write a blog post on the basics concepts when using GitHub Copilot in Visual Studio Code?
  • Can you convert this to markdown?
  • Can you explain the Copilot @workspace command?
  • /explain the GitHub Copilot Chat commands
  • Can you provide an example of “Copilot understands the context of your code.”
  • Can you explain how this is context aware?
  • @github what is the difference between “Send” and “Send and Dispatch” in the Copilot Chat?
  • @github What does Send to @workspace do?
  • @github What does Send to Copilot Edits do?
  • @github what does Send to New Chat do?
  • @github what does the /doc command do?
  • @github what does the /explain command do?
  • @github what does the /fix command do?
  • @github what does the /generate command do?
  • @github what does the /optimize command do?
  • @github what does the /test command do?
  • @github please explain the “Editor Inline Chat” menu option
  • @github explain the Review and Comment menu option
  • @github explain the “Add File to Chat” menu option
  • @github explain Copilot Extensions