Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 1fa

Using GitHub Copilot in IntelliJ IDEA

At the beginning of this month, at AMIS, I attended a Special Interest Group (SIG) meeting about GitHub Copilot, given by one of my colleagues. As we do so often at AMIS, we share knowledge between colleagues, and after this meeting, I became enthusiastic and wanted to try out Github Copilot myself.

In this article I share with you the steps I took to get GitHub Copilot working in IntelliJ IDEA and using it with some examples in Java code, following the instructions from “Getting started with GitHub Copilot”
[https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot]

GitHub Copilot

GitHub Copilot is an AI pair programmer that offers autocomplete-style suggestions as you code. You can receive suggestions from GitHub Copilot either by starting to write the code you want to use, or by writing a natural language comment describing what you want the code to do. GitHub Copilot analyzes the context in the file you are editing, as well as related files, and offers suggestions from within your text editor. GitHub Copilot is powered by a generative AI model developed by GitHub, OpenAI, and Microsoft.

GitHub Copilot is trained on all languages that appear in public repositories. For each language, the quality of suggestions you receive may depend on the volume and diversity of training data for that language. For example, JavaScript is well-represented in public repositories and is one of GitHub Copilot’s best supported languages. Languages with less representation in public repositories may produce fewer or less robust suggestions.
GitHub Copilot is available as an extension in Visual Studio Code, Visual Studio, Vim, Neovim, the JetBrains suite of IDEs, and Azure Data Studio.
[https://docs.github.com/en/copilot/overview-of-github-copilot/about-github-copilot-individual#about-github-copilot]

About billing for GitHub Copilot

GitHub Copilot is a paid feature, requiring a monthly or yearly subscription. GitHub Copilot subscriptions can be paid for and managed through a personal account on GitHub.com with Copilot Individual, or paid for and managed centrally through an organization account with GitHub Copilot Business.
[https://docs.github.com/en/copilot/overview-of-github-copilot/about-github-copilot-individual#about-billing-for-github-copilot]

In the overview below, you can see the differences between Copilot Individual and Copilot Business:
Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 2

By the way, I am using an organization account with GitHub Copilot Business.

Installing the GitHub Copilot plugin in my IntelliJ IDEA

To use GitHub Copilot in a JetBrains IDE, you must install the GitHub Copilot extension.

For installing the GitHub Copilot plugin in my IntelliJ IDEA, I followed the steps as described in “Installing the GitHub Copilot plugin in your JetBrains IDE”. Please see:

https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot?tool=jetbrains#installing-the-github-copilot-plugin-in-your-jetbrains-ide

After I authorized my GitHub account with GitHub Copilot, I was ready to start using GitHub Copilot.

For this article, I am using IntelliJ IDEA 2023.3.3 (Community Edition) with Java 21 (jdk-21.0.2).

In IntelliJ IDEA, via menu File | New | Project… , I created a new Java / Maven project.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 3

I clicked on button “Create” and the project was created.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 4

In the Tools menu the GitHub Copilot menu is now visible.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 5

When you choose “Edit Settings..”, the GitHub Copilot settings become visible:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 6

“Welcome to GitHub Copilot” Tool Window

On the left sidebar of my IntelliJ IDE window the “Welcome to GitHub Copilot” Tool Window was visible:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 4

By the way, this is also available via menu View | Tool Windows | Welcome to GitHub Copilot.

When I clicked “Welcome to GitHub Copilot” the following Tool Window was opened:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 7

Next, I clicked on button “Next: Get code suggestions in your editor”:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 8

Then, I clicked on button “Next: Ask GitHub Copilot”:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 9

Next, I clicked on button “Next: Make GitHub Copilot your own”:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 10

Then, I clicked on button “Next: Learn more”:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 11

And finally, I clicked on button “Close welcome guide”.

“GitHub Copilot Chat” Tool Window

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 12

On the right sidebar of my IntelliJ IDE window the “GitHub Copilot Chat” Tool Window was visible.

By the way, this is also available via menu View | Tool Windows | GitHub Copilot Chat.

When I clicked “Open GitHub Copilot Chat” the following Tool Window was opened:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 13

As you can see, at the moment I could not use Copilot Chat.

“Github Copilot Status” icon

In the right corner of the bottom panel of my IntelliJ IDE window the “Github Copilot Status” icon was visible.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 14

When I clicked the “Github Copilot Status” icon, the following menu was opened:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 15

You can enable or disable GitHub Copilot for all languages, or for individual languages. The GitHub Copilot status icon in the bottom panel of your JetBrains IDE window indicates whether GitHub Copilot is enabled or disabled. When enabled, the icon is highlighted. When disabled, the icon is grayed out.
[https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot?tool=jetbrains#enabling-and-disabling-github-copilot]

So, now that we have seen some extra windows and menus, with regard to GitHub Copilot, it is time to look at some examples in Java code.

Example 1, my first GitHub Copilot suggestion

Next, I followed the example as described in “Seeing your first suggestion”.
[https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot?tool=jetbrains#seeing-your-first-suggestion]

I opened the “Project” Tool Window, navigated to src/main/java/nl.amis.demo and via menu File | New | File, I created a file named Test1.java. In this Java file, I created a class by typing:

class Test1

Then, GitHub Copilot automatically suggested a class body in grayed text.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 16

To accept the suggestion, I pressed Tab.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 17

Next, I pressed Alt+Enter (Show Context Actions) in order to insert the missing package statement.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 18

Next, I pressed Crtl+Shift+F10 in order to run Test1.main(), with the following output:

Hello World!

Example 2, Seeing alternative suggestions (part 1)

Next, I followed (more or less) the example as described in “Seeing alternative suggestions”.
[https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot?tool=jetbrains#seeing-alternative-suggestions]

I created a file named Test2.java. In this Java file, I added the following code:

private int calculateDaysBetweenDates(Date date1,

Then, GitHub Copilot automatically suggested a class body in grayed text.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 19

As it is mentioned in the tooltip window, the following keyboard shortcuts with regard to suggestions can be used:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 20

And also:

  • To accept a suggestion, press Tab.
  • To reject all suggestions, press Esc.

Next, I pressed Alt+] in order to see the next suggestion. In this case nothing changed however.
In order to accept all lines of the suggestion, I had to press Tab several times.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 21

By the way, once you hit the button “Got it”, the tooltip window won’t show again.

By default, a tooltip is shown only once per user.
[https://jetbrains.design/intellij/controls/got_it_tooltip/]

Next, I pressed Alt+Enter (Show Context Actions) in order to import the following class:

 java.util.Date;

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 22

I had a look at the errors and fixed them:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 23

As the first line of code, I added:

package nl.amis.demo;

Next, after the import statement, I added:

class

Then, GitHub Copilot automatically suggested a class body in grayed text. And this time a different one then in Example 1 (Test1.java).

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 24

To accept the suggestion, I pressed Tab.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 25

As the last line of code, I added:

}

This fixed all the errors.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 26

A right click in the code, shows the GitHub Copilot menu, including features I could not use at the moment (because I didn’t have the right access to it). For now this was ok.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 27

Next, I pressed Crtl+Shift+F10 in order to run Test2.main(), with the following output:

Days between 2 dates: 0

Because I didn’t succeed in getting alternative suggestions within this example, I tried another approach.

See also: “Seeing multiple suggestions in a new tab”.
[https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot?tool=jetbrains#seeing-multiple-suggestions-in-a-new-tab]

Example 3, Seeing alternative suggestions (part 2)

I created a file named Test3.java. In this Java file, I added the following code:

private int calculateDaysBetweenDates(Date date1,

Then, GitHub Copilot automatically suggested a class body in grayed text.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 28

This time I choose menu View | Tool Windows | Github Copilot, and the following Tool Window was opened:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 29

Next, I clicked on link “Refresh” in order to get completions for the caret position.
And after a short period of time, the following suggestions became visible:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 30

At each of the visible suggestions, I scrolled to the top:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 31

Next, I accepted the second solution by clicking button “ Accept solution”:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 32

By the way, all the visible suggestions had the same begin line off codes. So that is probably why, in my previous example, navigation through the suggestions via Alt+] didn’t seem to work 😊.

Next, I cleared the last line of code (This will print `Days between dates: 365`.) and then I pressed Alt+Enter (Show Context Actions) in order to import the following class:

 java.util.Date;

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 33

Then, I cleared the last line of code (“`) and then I pressed Alt+Enter (Show Context Actions) in order to import the following class:

 java.text.SimpleDateFormat;

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 34

I had a look at the errors and fixed them:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 35

As the first line of code, I added:

package nl.amis.demo;

Next, after the import statements, I added:

class

Then, GitHub Copilot automatically suggested a class body in grayed text.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 36

To accept the suggestion, I pressed Tab.

As the last line of code, I added:

}

This fixed all the errors.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 37

Next, I pressed Crtl+Shift+F10 in order to run Test3.main(), with the following output:

Days between dates: 365

Example 4, Partially accepting suggestions

Next, I followed (more or less) the example as described in “Partially accepting suggestions”.
[https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot?tool=jetbrains#partially-accepting-suggestions]

I created a file named Test4.java. In this Java file, I added the following code:

private int calculateDaysBetweenDates(Date date1,

Then, GitHub Copilot automatically suggested a class body in grayed text.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 38

The following keyboard shortcuts with regard to accepting a part of the suggestion can be used:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 39

Next, I pressed Ctrl+Alt+->

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 40

Then, I pressed Ctrl+Alt+->

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 41

Again, I pressed Ctrl+Alt+->

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 42

As you can see, accepting a next line worked.

Next, I started from scratch and I also tried accepting the next word, by pressing Ctrl+->.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 43

As you can see, this worked also.

Example 5, Generating code suggestions from comments

Next, I followed (more or less) the example as described in “Generating code suggestions from comments”.
[https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot?tool=jetbrains#generating-code-suggestions-from-comments]

I created a file named Test5.java. In this Java file, I added the following code:

// find all images without alternate text
// and give them a red border
void process () {

Then, GitHub Copilot automatically suggested a class body in grayed text.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 44

Next, I pressed Alt+] in order to see the next suggestion. Nothing changed, so I repeated pressing Alt+], and this time, the suggested code did change.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 45

Again, I pressed Alt+] in order to see the next suggestion.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 46

To go back to the first suggestion, I pressed Alt+[ several times in order to see the first suggestion.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 44

In order to accept all lines of the suggestion, I pressed Tab.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 47

Just to satisfy my curiosity, I started from scratch and I choose menu View | Tool Windows | Github Copilot. Again, as before, I clicked on link “Refresh” in order to get completions for the caret position.
And after a short period of time, the following suggestions became visible:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 48

At each of the visible suggestions, I scrolled to the top:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 49

In the “ Github Copilot” Tool Window I scrolled through the list of suggestions.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 50

Next, I accepted a solution by clicking button “ Accept solution”:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 51

This is the code, now visible in the editor:

// find all images without alternate text
// and give them a red border
void process () {
    // get all img elements
    Elements images = document.select("img");
    // iterate over all img elements
    for (Element image : images) {
        // if the img element has no alt attribute
        if (!image.hasAttr("alt")) {
            // add a red border
            image.attr("style", "border: 1px solid red;");
        }
    }
}
```
The `select()` method is used to find elements in the document that match a CSS selector. The `hasAttr()` method checks if the element has an attribute with the given name.
The `attr()` method is used to set an attribute value, or add a new attribute if the element does not already have one.
The `style` attribute is a special attribute that allows you to set CSS styles on an element. It is a good idea to use the `style()` method to set styles on elements, because it does not overwrite any existing styles.
### Step 6: Save the HTML to a file
```java
// Path: src/main/java/nl/amis/demo/Test6.java
// save the HTML to a file
void process () throws Exception {
    // get all img elements
    Elements images = document.select("img");
    // iterate over all img elements
    for (Element image : images) {
        // if the img element has no alt attribute
        if (!image.hasAttr("alt")) {
            // add a red border
            image.attr("style", "border: 1px solid red;");
        }
    }
    // save the HTML to a file
    Files.write(Paths.get("output.html"), document.html().getBytes());
}
```
The `html()` method is used to get the HTML of the document. The `getBytes()` method converts the HTML string to a byte array.
The `Files.write()` method is used to write the byte array to a file.
### Step 7: Run the program
```java
// Path: src/main/java/nl/amis/demo/Test7.java
// run the program
public static void main(String[] args) throws Exception {
    // create a new instance of the program
    Test7 program = new Test7();
    // run the program
    program.run();
}
```
The `main()` method is the entry point of the program. It is a good idea to put the main method in a separate class, so that the main method

Then, I fixed the code by adding the package and some imports:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 52

Next, after the import statement, I added:

class

Then, GitHub Copilot automatically suggested a class body in grayed text.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 53

To accept the suggestion, I pressed Tab.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 54

This code example uses Jsoup, so I changed the content of my maven pom.xml to:
[in bold, I highlighted the changes]

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>nl.amis.demo</groupId>
    <artifactId>github-copilot-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.17.2</version>
        </dependency>
    </dependencies>

</project>

Jsoup Java HTML Parser » 1.17.2

jsoup is a Java library that simplifies working with real-world HTML and XML. It offers an easy-to-use API for URL fetching, data parsing, extraction, and manipulation using DOM API methods, CSS, and xpath selectors. jsoup implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers.
[https://mvnrepository.com/artifact/org.jsoup/jsoup/1.17.2]

Next, I fixed the code.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 55

This is the code, after I fixed it:

package nl.amis.demo;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.nio.file.Files;
import java.nio.file.Paths;

class Test5 {
    public static void main(String[] args) throws Exception {
        // read the HTML file
        String html = new String(Files.readAllBytes(Paths.get("src","main","resources","input.html")));
        // parse the HTML
        Document document = Jsoup.parse(html);
        // process the HTML
        process(document);
    }

    private static void process(Document document) throws Exception {
        // get all img elements
        Elements images = document.select("img");
        // iterate over all img elements
        for (Element image : images) {
            // if the img element has no alt attribute
            if (!image.hasAttr("alt")) {
                // add a red border
                image.attr("style", "border: 1px solid red;");
            }
        }
        // save the HTML to a file
        Files.write(Paths.get("src","main","resources","output.html"), document.html().getBytes());
    }
}

As you can see in the code above, this codes reads an HTML file (input.html), iterates over all the img elements, and if the img element has no alt attribute it adds a red border. Finally, it saves the changed HTML to a file (output.html).

In order to get this code working, I needed an input.html file including two images. So I created them.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 56

This is the content of the input.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greetings from AMIS</title>
</head>
<body>
    <h1>Greetings from AMIS</h1>
    This is a demo html page used with a GitHub Copilot Java example.<br/>
    <img src="first.png"><br/>
    <img src="second.png" alt="Second image">
</body>
</html>

With the following result:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 57

Next, I pressed Crtl+Shift+F10 in order to run Test5.main(), and this created an output.html file.

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 58

This is the content of the output.html file:

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Greetings from AMIS</title>
 </head>
 <body>
  <h1>Greetings from AMIS</h1> This is a demo html page used with a GitHub Copilot Java example.
  <br><img src="first.png" style="border: 1px solid red;">
  <br><img src="second.png" alt="Second image">
 </body>
</html>

With the following result:

Using GitHub Copilot in IntelliJ IDEA lameriks 2024 01 59

As you can see, the img element without alt attribute has got a red border.

Concluding

By now, I had some idea about how to use GitHub Copilot and it’s suggestions within IntelliJ IDEA. Although I could not use all the features at the moment, I experienced it’s benefits as an AI pair programming tool.

If you need some helpful resources for taking your next steps with GitHub Copilot, please see:

https://docs.github.com/en/copilot/using-github-copilot/getting-started-with-github-copilot?tool=jetbrains#next-steps

At the moment some AMIS colleagues are using GitHub Copilot with Visual Studio Code. My colleague Lucas Jellema, already some time ago, wrote an article called “GitHub Copilot reduces writing Java boilerplate to two simple comments”. He wrote a Java application, to process a csv data file, in Visual Studio Code including the GitHub Copilot extension
[https://technology.amis.nl/software-development/software-engineering/github-copilot-reduces-writing-java-boilerplate-to-two-simple-comments/]

For those of you who use IntelliJ IDEA you also might have a look at:

JetBrains AI Assistant
With a JetBrains AI service subscription, AI Assistant is available in IntelliJ IDEA, PyCharm, PhpStorm, ReSharper, and other JetBrains IDEs, as well as in Fleet as a supplemental feature.
[https://www.jetbrains.com/ai/]

In a previous article about “Devoxx Belgium 2023”, I wrote about the talk held by Anton Arhipov (from JetBrains) about AI Assistant.

Anton showed a small but impressive demo that demonstrated most of the features of the plugin (at the state of the week before) in regard to working with some existing code or making sense of existing code (as opposed to generating new code). For example, in his sample code (public class TheAlgorithm), via Alt+Enter he selected the AI Actions menu and started the action “Explain TheAlgorithm class”.
[https://technology.amis.nl/amis/webinars-meetups-and-conferences/devoxx-belgium-2023/]

To end this article, I encourage you to start looking at AI programming assistant tools.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.