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
| IDE | Support Level |
|---|---|
| VS Code | Full support |
| Visual Studio | Full support |
| JetBrains IDEs | Full support |
| Neovim | Plugin support |
| Azure Data Studio | Supported |
Supported Languages
- JavaScript/TypeScript
- Python
- Java
- C/C++/C#
- Go
- Ruby
- PHP
- And many more...
VS Code Shortcuts
Code Completion {.row-span-2}
| Shortcut | Action |
|---|---|
Tab | Accept suggestion |
Esc | Dismiss suggestion |
Alt + ] | Next suggestion |
Alt + [ | Previous suggestion |
Alt + \ | Trigger suggestion |
Ctrl + Enter | View all suggestions |
Copilot Chat
| Shortcut | Action |
|---|---|
Ctrl + I | Inline Chat |
Ctrl + Shift + I | Open Chat panel |
Ctrl + L | Clear Chat |
Code Actions
| 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 |
JetBrains Shortcuts
Code Completion
| Shortcut | Action |
|---|---|
Tab | Accept suggestion |
Esc | Dismiss suggestion |
Alt + ] | Next suggestion |
Alt + [ | Previous suggestion |
Alt + \ | Manual trigger |
Chat
| Shortcut | Action |
|---|---|
Ctrl + Shift + C | Open 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
- Select code
- Press
Ctrl + I - Type instruction
- 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
-
Write clear comments
- Describe function purpose
- Specify parameters and returns
- Provide usage examples
-
Use meaningful names
- Functions describe behavior
- Variables express meaning
- Complete type annotations
-
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
.gitignoreto exclude sensitive files