GitHub Copilot Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。
| IDE | Support Level |
|---|---|
| VS Code | Full support |
| Visual Studio | Full support |
| JetBrains IDEs | Full support |
| Neovim | Plugin support |
| Azure Data Studio | Supported |
| Shortcut | Action |
|---|---|
Tab | Accept suggestion |
Esc | Dismiss suggestion |
Alt + ] | Next suggestion |
Alt + [ | Previous suggestion |
Alt + \ | Trigger suggestion |
Ctrl + Enter | View all suggestions |
| Shortcut | Action |
|---|---|
Ctrl + I | Inline Chat |
Ctrl + Shift + I | Open Chat panel |
Ctrl + L | Clear Chat |
| Shortcut | Action |
|---|---|
Ctrl + Shift + Alt + E | Explain code |
Ctrl + Shift + Alt + F | Fix code |
Ctrl + Shift + Alt + T | Generate tests |
Ctrl + Shift + Alt + D | Generate docs |
| Shortcut | Action |
|---|---|
Tab | Accept suggestion |
Esc | Dismiss suggestion |
Alt + ] | Next suggestion |
Alt + [ | Previous suggestion |
Alt + \ | Manual trigger |
| Shortcut | Action |
|---|---|
Ctrl + Shift + C | Open Copilot Chat |
# Calculate the factorial of a number recursively
# Handle edge cases for negative numbers
def factorial(n):
# Copilot completes the implementation
// 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) {
# Implement binary search on sorted array
# Return index if found, -1 otherwise
# Time complexity: O(log n)
def binary_search(arr, target):
// 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) {
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)
) {
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 =
VS Code:
Ctrl + Shift + I or
Click Copilot icon in sidebar
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
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
Ctrl + ICommon Instructions:
add error handling
convert to async/await
add type annotations
make this more readable
// Validate email format
// Return true if valid, false otherwise
function validateEmail(email) {
// Copilot generates regex validation
}
# 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:
// 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 }) {
# 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(
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[]> {
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
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;
}
/explain
Review this code for:
- Potential bugs
- Performance issues
- Security vulnerabilities
- Best practice violations
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"
/explain
How does this library's authentication work?
Show me usage examples.
@terminal
I got this error:
ModuleNotFoundError: No module named 'requests'
How do I fix it?
/optimize
This function is slow with large datasets.
How can I improve its performance?
@workspace
Review this authentication code for security issues.
Focus on:
- SQL injection
- XSS vulnerabilities
- Secure password handling
Enable/Disable
{
"github.copilot.enable": {
"*": true,
"markdown": false,
"plaintext": false
}
}
Inline Suggestions
{
"github.copilot.inlineSuggest.enable": true
}
Create .github/copilot-instructions.md:
# Copilot Instructions
Write clear comments
Use meaningful names
Maintain relevant context
Select code → Ctrl + I →
"review for potential issues and suggest improvements"
@workspace
I'm new here. Explain:
- Project structure
- Key patterns used
- How to add a new feature
gh extension install github/gh-copilot
Explain Command
gh copilot explain "git rebase -i HEAD~3"
Suggest Command
gh copilot suggest "find files larger than 100MB"
# 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'
# 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"
Alt + ] to cycle suggestions.gitignore to exclude sensitive files