logo

GitHub Copilot Cheat Sheet


title: GitHub Copilot date: 2024-12-01 10:00:00 background: bg-[#000000] tags: - AI - GitHub - Coding - Autocomplete categories: - AI intro: GitHub Copilot cheat sheet with shortcuts, usage tips, Chat features and best practices plugins: - copyCode

Overview

What is GitHub Copilot

  • AI coding assistant by GitHub and OpenAI
  • Trained on public code repositories
  • Supports multiple IDEs and languages
  • Provides code completion, generation, explanation

Supported IDEs

IDESupport Level
VS CodeFull support
Visual StudioFull support
JetBrains IDEsFull support
NeovimPlugin support
Azure Data StudioSupported

Supported Languages

  • JavaScript/TypeScript
  • Python
  • Java
  • C/C++/C#
  • Go
  • Ruby
  • PHP
  • And many more...

VS Code Shortcuts

Code Completion {.row-span-2}

ShortcutAction
TabAccept suggestion
EscDismiss suggestion
Alt + ]Next suggestion
Alt + [Previous suggestion
Alt + \Trigger suggestion
Ctrl + EnterView all suggestions

Copilot Chat

ShortcutAction
Ctrl + IInline Chat
Ctrl + Shift + IOpen Chat panel
Ctrl + LClear Chat

Code Actions

ShortcutAction
Ctrl + Shift + Alt + EExplain code
Ctrl + Shift + Alt + FFix code
Ctrl + Shift + Alt + TGenerate tests
Ctrl + Shift + Alt + DGenerate docs

JetBrains Shortcuts

Code Completion

ShortcutAction
TabAccept suggestion
EscDismiss suggestion
Alt + ]Next suggestion
Alt + [Previous suggestion
Alt + \Manual trigger

Chat

ShortcutAction
Ctrl + Shift + COpen Copilot Chat

Completion Techniques

Comment-Driven Development {.cols-2}

Function Description

# Calculate the factorial of a number recursively
# Handle edge cases for negative numbers
def factorial(n):
    # Copilot completes the implementation

Detailed Specification

// Send POST request to specified URL
// Parameters: url - request URL, data - request body
// Returns: Promise<Response>
// Throws: NetworkError if request fails
async function postData(url, data) {

Algorithm Description

# Implement binary search on sorted array
# Return index if found, -1 otherwise
# Time complexity: O(log n)
def binary_search(arr, target):

Data Transformation

// Convert array of objects to lookup map
// Input: [{id: 1, name: 'a'}, {id: 2, name: 'b'}]
// Output: {1: {id: 1, name: 'a'}, 2: {id: 2, name: 'b'}}
function arrayToMap(arr, key) {

Function Signature Guidance

Clear Naming

function calculateTotalPriceWithTax(
    items: CartItem[],
    taxRate: number
): number {

Type Annotations

def send_email(
    to: str,
    subject: str,
    body: str,
    attachments: list[str] | None = None
) -> bool:

Descriptive Parameters

function filterUsersByAge(
    users,          // Array of user objects
    minAge,         // Minimum age (inclusive)
    maxAge          // Maximum age (inclusive)
) {

Context Hints

Related Imports

import { useState, useEffect } from 'react';
import axios from 'axios';

// Copilot understands you're writing React + API
function UserList() {

Adjacent Code

users = fetch_users()
emails = [u.email for u in users]

# Copilot uses context for better completion
active_users = users.filter(

Existing Patterns

// Following existing code pattern
const getUser = (id: string) => api.get(`/users/${id}`);
const getPosts = (id: string) => api.get(`/posts/${id}`);

// Copilot follows the pattern
const getComments =

Copilot Chat

Opening Chat

VS Code:

Ctrl + Shift + I  or
Click Copilot icon in sidebar

Slash Commands {.row-span-2}

Explain Code

/explain
Select code and use this command

Fix Issues

/fix
Automatically identify and fix problems

Generate Tests

/tests
Generate tests for selected code

Generate Docs

/doc
Generate documentation comments

Optimize

@workspace /optimize
Optimize selected code

Simplify

/simplify
Simplify complex code

New File

/new
Create a new file with specified content

@ Context References

Workspace

@workspace explain the project structure

Terminal

@terminal the last command failed, how do I fix it?

VS Code

@vscode how do I configure auto-format on save?

File

@file:src/index.ts explain this file

Inline Chat

  1. Select code
  2. Press Ctrl + I
  3. Type instruction
  4. Review and accept changes

Common Instructions:

add error handling
convert to async/await
add type annotations
make this more readable

Code Generation

From Comments {.cols-2}

JavaScript Function

// Validate email format
// Return true if valid, false otherwise
function validateEmail(email) {
	// Copilot generates regex validation
}

Python Class

# User class with the following properties:
# - id: user ID (int)
# - name: username (str)
# - email: email address (str)
# - created_at: creation timestamp
# Methods: to_dict(), from_dict()
class User:

React Component

// UserCard component
// Props: user object with name, avatar, bio
// Display user info in a card layout
// Include edit button if isEditable is true
function UserCard({ user, isEditable }) {

API Endpoint

# FastAPI endpoint for user registration
# Accept: email, password, name
# Validate: email format, password strength
# Return: user object with JWT token
@app.post("/register")
async def register(

From Function Names

function sortByDateDescending(items: Item[]): Item[] {

function filterActiveSubscribers(users: User[]): User[] {

function calculateMonthlyRevenue(orders: Order[]): number {

function groupByCategory<T>(items: T[], key: keyof T): Record<string, T[]> {

Test Generation

Jest Tests

// test for validateEmail function
describe('validateEmail', () => {
	// Copilot generates test cases:
	// - valid email
	// - invalid format
	// - empty string
	// - edge cases
});

Pytest

# pytest tests for User class
class TestUser:
    # Copilot generates test methods:
    # - test_create_user
    # - test_to_dict
    # - test_from_dict
    # - test_invalid_email

Documentation

JSDoc

/**
 * [Cursor here, Copilot completes]
 */
function processOrder(order, options) {

Python Docstring

def calculate_discount(price, percentage, max_discount=None):
    """
    [Copilot completes docstring with:
    - Description
    - Args
    - Returns
    - Raises
    - Examples]
    """

TypeScript Interface

/**
 * [Copilot generates interface documentation]
 */
interface PaymentRequest {
	amount: number;
	currency: string;
	customerId: string;
}

Prompt Examples

Code Review

/explain
Review this code for:
- Potential bugs
- Performance issues
- Security vulnerabilities
- Best practice violations

Refactoring

Select code → Ctrl + I → Type:
"refactor to use async/await instead of promises"
"extract repeated logic into a helper function"
"convert to functional programming style"

Learning New APIs

/explain
How does this library's authentication work?
Show me usage examples.

Error Fixing

@terminal
I got this error:
ModuleNotFoundError: No module named 'requests'

How do I fix it?

Performance Optimization

/optimize
This function is slow with large datasets.
How can I improve its performance?

Security Review

@workspace
Review this authentication code for security issues.
Focus on:
- SQL injection
- XSS vulnerabilities
- Secure password handling

Configuration

VS Code Settings

Enable/Disable

{
	"github.copilot.enable": {
		"*": true,
		"markdown": false,
		"plaintext": false
	}
}

Inline Suggestions

{
	"github.copilot.inlineSuggest.enable": true
}

Project Instructions

Create .github/copilot-instructions.md:

# Copilot Instructions

## Code Style

-   Use TypeScript for all files
-   Follow ESLint rules
-   Use functional programming style
-   Prefer immutable data structures

## Naming Conventions

-   Variables: camelCase
-   Constants: UPPER_SNAKE_CASE
-   Classes: PascalCase
-   Files: kebab-case

## Testing Requirements

-   Use Jest framework
-   Cover edge cases
-   Include error handling tests
-   Aim for 80% coverage

## Documentation

-   JSDoc for public functions
-   Inline comments for complex logic
-   README for each module

Best Practices

Improving Suggestions

  1. Write clear comments

    • Describe function purpose
    • Specify parameters and returns
    • Provide usage examples
  2. Use meaningful names

    • Functions describe behavior
    • Variables express meaning
    • Complete type annotations
  3. Maintain relevant context

    • Import related libraries
    • Define related types
    • Provide example data

Code Review Prompts

Select code → Ctrl + I →
"review for potential issues and suggest improvements"

Learning New Codebase

@workspace
I'm new here. Explain:
- Project structure
- Key patterns used
- How to add a new feature

CLI Tool

Installation

gh extension install github/gh-copilot

Common Commands

Explain Command

gh copilot explain "git rebase -i HEAD~3"

Suggest Command

gh copilot suggest "find files larger than 100MB"

Aliases

# Add to .bashrc or .zshrc
alias '??'='gh copilot suggest -t shell'
alias 'git?'='gh copilot suggest -t git'
alias 'gh?'='gh copilot suggest -t gh'

Example Usage

# Get shell command suggestions
?? "compress all images in current directory"

# Get git command help
git? "undo last commit but keep changes"

# Get GitHub CLI help
gh? "list my open pull requests"

Troubleshooting

Inaccurate Suggestions

  • Add more context
  • Write detailed comments
  • Use Alt + ] to cycle suggestions
  • Try rephrasing your comment

Slow Suggestions

  • Check network connection
  • Reduce number of open files
  • Restart IDE

No Suggestions

  • Confirm Copilot is enabled
  • Check file type is supported
  • Check status bar Copilot icon

Privacy Considerations

  • Disable Copilot for sensitive code
  • Check organization policies
  • Use .gitignore to exclude sensitive files
🤖 AI 工具

GitHub Copilot

GitHub Copilot Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · AI 工具🧭 Markdown 速查🏷️ 3 个标签
#ai#coding#github
向下滚动查看内容
返回全部 Cheat Sheets

Overview

What is GitHub Copilot
  • AI coding assistant by GitHub and OpenAI
  • Trained on public code repositories
  • Supports multiple IDEs and languages
  • Provides code completion, generation, explanation
Supported IDEs
IDESupport Level
VS CodeFull support
Visual StudioFull support
JetBrains IDEsFull support
NeovimPlugin support
Azure Data StudioSupported
Supported Languages
  • JavaScript/TypeScript
  • Python
  • Java
  • C/C++/C#
  • Go
  • Ruby
  • PHP
  • And many more...

VS Code Shortcuts

Code Completion
ShortcutAction
TabAccept suggestion
EscDismiss suggestion
Alt + ]Next suggestion
Alt + [Previous suggestion
Alt + \Trigger suggestion
Ctrl + EnterView all suggestions
Copilot Chat
ShortcutAction
Ctrl + IInline Chat
Ctrl + Shift + IOpen Chat panel
Ctrl + LClear Chat
Code Actions
ShortcutAction
Ctrl + Shift + Alt + EExplain code
Ctrl + Shift + Alt + FFix code
Ctrl + Shift + Alt + TGenerate tests
Ctrl + Shift + Alt + DGenerate docs

JetBrains Shortcuts

Code Completion
ShortcutAction
TabAccept suggestion
EscDismiss suggestion
Alt + ]Next suggestion
Alt + [Previous suggestion
Alt + \Manual trigger
Chat
ShortcutAction
Ctrl + Shift + COpen Copilot Chat

Completion Techniques

Comment-Driven Development

Function Description

PYTHON
滚动查看更多
# Calculate the factorial of a number recursively
# Handle edge cases for negative numbers
def factorial(n):
    # Copilot completes the implementation

Detailed Specification

JAVASCRIPT
滚动查看更多
// Send POST request to specified URL
// Parameters: url - request URL, data - request body
// Returns: Promise<Response>
// Throws: NetworkError if request fails
async function postData(url, data) {

Algorithm Description

PYTHON
滚动查看更多
# Implement binary search on sorted array
# Return index if found, -1 otherwise
# Time complexity: O(log n)
def binary_search(arr, target):

Data Transformation

JAVASCRIPT
滚动查看更多
// Convert array of objects to lookup map
// Input: [{id: 1, name: 'a'}, {id: 2, name: 'b'}]
// Output: {1: {id: 1, name: 'a'}, 2: {id: 2, name: 'b'}}
function arrayToMap(arr, key) {
Function Signature Guidance

Clear Naming

TYPESCRIPT
滚动查看更多
function calculateTotalPriceWithTax(
    items: CartItem[],
    taxRate: number
): number {

Type Annotations

PYTHON
滚动查看更多
def send_email(
    to: str,
    subject: str,
    body: str,
    attachments: list[str] | None = None
) -> bool:

Descriptive Parameters

JAVASCRIPT
滚动查看更多
function filterUsersByAge(
    users,          // Array of user objects
    minAge,         // Minimum age (inclusive)
    maxAge          // Maximum age (inclusive)
) {
Context Hints

Related Imports

JAVASCRIPT
滚动查看更多
import { useState, useEffect } from 'react';
import axios from 'axios';

// Copilot understands you're writing React + API
function UserList() {

Adjacent Code

PYTHON
滚动查看更多
users = fetch_users()
emails = [u.email for u in users]

# Copilot uses context for better completion
active_users = users.filter(

Existing Patterns

TYPESCRIPT
滚动查看更多
// Following existing code pattern
const getUser = (id: string) => api.get(`/users/${id}`);
const getPosts = (id: string) => api.get(`/posts/${id}`);

// Copilot follows the pattern
const getComments =

Copilot Chat

Opening Chat

VS Code:

CODE
滚动查看更多
Ctrl + Shift + I  or
Click Copilot icon in sidebar
Slash Commands

Explain Code

CODE
滚动查看更多
/explain
Select code and use this command

Fix Issues

CODE
滚动查看更多
/fix
Automatically identify and fix problems

Generate Tests

CODE
滚动查看更多
/tests
Generate tests for selected code

Generate Docs

CODE
滚动查看更多
/doc
Generate documentation comments

Optimize

CODE
滚动查看更多
@workspace /optimize
Optimize selected code

Simplify

CODE
滚动查看更多
/simplify
Simplify complex code

New File

CODE
滚动查看更多
/new
Create a new file with specified content
@ Context References

Workspace

CODE
滚动查看更多
@workspace explain the project structure

Terminal

CODE
滚动查看更多
@terminal the last command failed, how do I fix it?

VS Code

CODE
滚动查看更多
@vscode how do I configure auto-format on save?

File

CODE
滚动查看更多
@file:src/index.ts explain this file
Inline Chat
  1. Select code
  2. Press Ctrl + I
  3. Type instruction
  4. Review and accept changes

Common Instructions:

CODE
滚动查看更多
add error handling
CODE
滚动查看更多
convert to async/await
CODE
滚动查看更多
add type annotations
CODE
滚动查看更多
make this more readable

Code Generation

From Comments

JavaScript Function

JAVASCRIPT
滚动查看更多
// Validate email format
// Return true if valid, false otherwise
function validateEmail(email) {
	// Copilot generates regex validation
}

Python Class

PYTHON
滚动查看更多
# User class with the following properties:
# - id: user ID (int)
# - name: username (str)
# - email: email address (str)
# - created_at: creation timestamp
# Methods: to_dict(), from_dict()
class User:

React Component

JSX
滚动查看更多
// UserCard component
// Props: user object with name, avatar, bio
// Display user info in a card layout
// Include edit button if isEditable is true
function UserCard({ user, isEditable }) {

API Endpoint

PYTHON
滚动查看更多
# FastAPI endpoint for user registration
# Accept: email, password, name
# Validate: email format, password strength
# Return: user object with JWT token
@app.post("/register")
async def register(
From Function Names
TYPESCRIPT
滚动查看更多
function sortByDateDescending(items: Item[]): Item[] {

function filterActiveSubscribers(users: User[]): User[] {

function calculateMonthlyRevenue(orders: Order[]): number {

function groupByCategory<T>(items: T[], key: keyof T): Record<string, T[]> {
Test Generation

Jest Tests

JAVASCRIPT
滚动查看更多
// test for validateEmail function
describe('validateEmail', () => {
	// Copilot generates test cases:
	// - valid email
	// - invalid format
	// - empty string
	// - edge cases
});

Pytest

PYTHON
滚动查看更多
# pytest tests for User class
class TestUser:
    # Copilot generates test methods:
    # - test_create_user
    # - test_to_dict
    # - test_from_dict
    # - test_invalid_email
Documentation

JSDoc

JAVASCRIPT
滚动查看更多
/**
 * [Cursor here, Copilot completes]
 */
function processOrder(order, options) {

Python Docstring

PYTHON
滚动查看更多
def calculate_discount(price, percentage, max_discount=None):
    """
    [Copilot completes docstring with:
    - Description
    - Args
    - Returns
    - Raises
    - Examples]
    """

TypeScript Interface

TYPESCRIPT
滚动查看更多
/**
 * [Copilot generates interface documentation]
 */
interface PaymentRequest {
	amount: number;
	currency: string;
	customerId: string;
}

Prompt Examples

Code Review
CODE
滚动查看更多
/explain
Review this code for:
- Potential bugs
- Performance issues
- Security vulnerabilities
- Best practice violations
Refactoring
CODE
滚动查看更多
Select code → Ctrl + I → Type:
"refactor to use async/await instead of promises"
CODE
滚动查看更多
"extract repeated logic into a helper function"
CODE
滚动查看更多
"convert to functional programming style"
Learning New APIs
CODE
滚动查看更多
/explain
How does this library's authentication work?
Show me usage examples.
Error Fixing
CODE
滚动查看更多
@terminal
I got this error:
ModuleNotFoundError: No module named 'requests'

How do I fix it?
Performance Optimization
CODE
滚动查看更多
/optimize
This function is slow with large datasets.
How can I improve its performance?
Security Review
CODE
滚动查看更多
@workspace
Review this authentication code for security issues.
Focus on:
- SQL injection
- XSS vulnerabilities
- Secure password handling

Configuration

VS Code Settings

Enable/Disable

JSON
滚动查看更多
{
	"github.copilot.enable": {
		"*": true,
		"markdown": false,
		"plaintext": false
	}
}

Inline Suggestions

JSON
滚动查看更多
{
	"github.copilot.inlineSuggest.enable": true
}
Project Instructions

Create .github/copilot-instructions.md:

MARKDOWN
滚动查看更多
# Copilot Instructions

Code Style

  • Use TypeScript for all files
  • Follow ESLint rules
  • Use functional programming style
  • Prefer immutable data structures

Naming Conventions

  • Variables: camelCase
  • Constants: UPPER_SNAKE_CASE
  • Classes: PascalCase
  • Files: kebab-case

Testing Requirements

  • Use Jest framework
  • Cover edge cases
  • Include error handling tests
  • Aim for 80% coverage

Documentation

  • JSDoc for public functions
  • Inline comments for complex logic
  • README for each module
CODE
滚动查看更多

Best Practices

Improving Suggestions
  1. Write clear comments

    • Describe function purpose
    • Specify parameters and returns
    • Provide usage examples
  2. Use meaningful names

    • Functions describe behavior
    • Variables express meaning
    • Complete type annotations
  3. Maintain relevant context

    • Import related libraries
    • Define related types
    • Provide example data
Code Review Prompts
CODE
滚动查看更多
Select code → Ctrl + I →
"review for potential issues and suggest improvements"
Learning New Codebase
CODE
滚动查看更多
@workspace
I'm new here. Explain:
- Project structure
- Key patterns used
- How to add a new feature

CLI Tool

Installation
BASH
滚动查看更多
gh extension install github/gh-copilot
Common Commands

Explain Command

BASH
滚动查看更多
gh copilot explain "git rebase -i HEAD~3"

Suggest Command

BASH
滚动查看更多
gh copilot suggest "find files larger than 100MB"
Aliases
BASH
滚动查看更多
# Add to .bashrc or .zshrc
alias '??'='gh copilot suggest -t shell'
alias 'git?'='gh copilot suggest -t git'
alias 'gh?'='gh copilot suggest -t gh'
Example Usage
BASH
滚动查看更多
# Get shell command suggestions
?? "compress all images in current directory"

# Get git command help
git? "undo last commit but keep changes"

# Get GitHub CLI help
gh? "list my open pull requests"

Troubleshooting

Inaccurate Suggestions
  • Add more context
  • Write detailed comments
  • Use Alt + ] to cycle suggestions
  • Try rephrasing your comment
Slow Suggestions
  • Check network connection
  • Reduce number of open files
  • Restart IDE
No Suggestions
  • Confirm Copilot is enabled
  • Check file type is supported
  • Check status bar Copilot icon
Privacy Considerations
  • Disable Copilot for sensitive code
  • Check organization policies
  • Use .gitignore to exclude sensitive files

相关 Cheat Sheets