GitHub Copilot Slash Commands

Slash commands are shortcuts you type in Copilot Chat to trigger specific actions instantly. Instead of writing a long description of what you want, you type a short command like /fix or /test and Copilot performs the action on the selected code immediately. This topic covers every available slash command and when to use each one.

How Slash Commands Work

Type a forward slash followed by the command name in the Copilot Chat input box. Most commands work on whatever code you have highlighted in your editor. If nothing is highlighted, the command applies to the current file or the last topic discussed in the chat.

USAGE PATTERN:
1. Highlight the code you want to work with (optional but recommended)
2. Open Copilot Chat (Ctrl+Shift+I)
3. Type /commandname in the input box
4. Press Enter
→ Copilot executes the action on your selection

The Full List of Slash Commands

┌──────────────┬──────────────────────────────────────────────────┐
│  COMMAND     │  WHAT IT DOES                                    │
├──────────────┼──────────────────────────────────────────────────┤
│  /explain    │  Explains selected code in plain English         │
│  /fix        │  Detects and fixes bugs in selected code         │
│  /tests      │  Generates unit tests for selected code          │
│  /doc        │  Writes documentation/comments for code          │
│  /simplify   │  Rewrites complex code to be simpler             │
│  /optimize   │  Improves performance of selected code           │
│  /new        │  Creates a new file, project, or component       │
│  /terminal   │  Suggests shell commands for the terminal        │
│  /clear      │  Clears the current chat conversation            │
│  /help       │  Shows a list of available commands              │
└──────────────┴──────────────────────────────────────────────────┘

/explain — Understand Code Instantly

Select any block of code, type /explain, and Copilot gives you a plain-language breakdown of what it does. This is especially useful when reading someone else's code or revisiting code you wrote months ago.

SELECTED CODE:
const debounced = useCallback(
    debounce((query) => {
        dispatch(searchProducts(query));
    }, 400),
    [dispatch]
);

IN CHAT: /explain

COPILOT RESPONSE:
This creates a debounced search function that waits 400
milliseconds after you stop typing before dispatching a
search request. This prevents the app from making an API
call for every single keystroke.

useCallback ensures the debounced function is only recreated
if the dispatch function changes. Without it, a new debounced
function would be created on every render, which would reset
the 400ms timer each time.

/fix — Repair Broken Code

Select code with a bug, type /fix, and Copilot analyzes the problem and suggests a corrected version. For best results, include the error message in the chat before or after the command.

SELECTED CODE:
function connectDB() {
    mongoose.connect(process.env.DB_URL)
    console.log('Connected to database');
}

IN CHAT: /fix — it logs "Connected" before connection is ready

COPILOT RESPONSE:
The problem is that mongoose.connect() returns a Promise, but
the function doesn't await it. The console.log runs before
the connection is established.

Fixed version:
async function connectDB() {
    await mongoose.connect(process.env.DB_URL);
    console.log('Connected to database');
}

/tests — Generate Test Cases

Select a function and type /tests to generate a complete test file for it. Copilot detects your testing framework from the project context and writes tests in the same style.

SELECTED FUNCTION:
function formatCurrency(amount, currency = 'USD') {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency
    }).format(amount);
}

IN CHAT: /tests

COPILOT GENERATES:
describe('formatCurrency', () => {
    test('formats USD by default', () => {
        expect(formatCurrency(1234.5)).toBe('$1,234.50');
    });

    test('formats EUR when specified', () => {
        expect(formatCurrency(1234.5, 'EUR')).toBe('€1,234.50');
    });

    test('handles zero correctly', () => {
        expect(formatCurrency(0)).toBe('$0.00');
    });

    test('handles negative amounts', () => {
        expect(formatCurrency(-50)).toBe('-$50.00');
    });
});

/doc — Write Documentation

Select a function and type /doc to generate a documentation comment above it. Copilot automatically uses the correct format — JSDoc for JavaScript, docstrings for Python, XML comments for C#.

SELECTED FUNCTION:
function retry(fn, times, delay) {
    return new Promise((resolve, reject) => {
        const attempt = (n) => {
            fn().then(resolve).catch(err => {
                if (n === 0) return reject(err);
                setTimeout(() => attempt(n - 1), delay);
            });
        };
        attempt(times);
    });
}

IN CHAT: /doc

COPILOT GENERATES:
/**
 * Retries an async function a specified number of times with a delay.
 *
 * @param {Function} fn - Async function to retry. Must return a Promise.
 * @param {number} times - Maximum number of retry attempts.
 * @param {number} delay - Milliseconds to wait between retries.
 * @returns {Promise} Resolves with the function's result on success.
 * @throws {Error} Rejects with the last error after all retries are exhausted.
 *
 * @example
 * await retry(() => fetchData(), 3, 1000);
 * // Tries up to 3 times with 1-second delays between attempts
 */

/simplify — Remove Unnecessary Complexity

Select overly complex code and type /simplify to get a cleaner version that does the same thing.

COMPLEX ORIGINAL:
function isEven(n) {
    if (n % 2 === 0) {
        return true;
    } else {
        return false;
    }
}

IN CHAT: /simplify

COPILOT RESPONSE:
const isEven = (n) => n % 2 === 0;
ANOTHER EXAMPLE — Nested conditions:
function getGrade(score) {
    if (score >= 90) {
        if (score >= 95) { return 'A+'; }
        else { return 'A'; }
    } else {
        if (score >= 80) { return 'B'; }
        else { return 'C'; }
    }
}

IN CHAT: /simplify

COPILOT RESPONSE:
function getGrade(score) {
    if (score >= 95) return 'A+';
    if (score >= 90) return 'A';
    if (score >= 80) return 'B';
    return 'C';
}

/optimize — Improve Performance

Select slow or inefficient code and type /optimize. Copilot rewrites it for better performance and explains what it changed and why.

SLOW ORIGINAL:
function findDuplicates(arr) {
    const duplicates = [];
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] === arr[j] && !duplicates.includes(arr[i])) {
                duplicates.push(arr[i]);
            }
        }
    }
    return duplicates;
}
// O(n³) — very slow for large arrays

IN CHAT: /optimize

COPILOT RESPONSE:
function findDuplicates(arr) {
    const seen = new Set();
    const duplicates = new Set();
    for (const item of arr) {
        if (seen.has(item)) duplicates.add(item);
        else seen.add(item);
    }
    return [...duplicates];
}
// O(n) — dramatically faster for large arrays

Explanation: The original used nested loops (O(n²)) plus
includes() (O(n)), making it O(n³). This version uses a Set
for O(1) lookups, reducing the overall complexity to O(n).

/new — Create New Files and Projects

The /new command helps you scaffold new files, components, or even entire project structures.

IN CHAT:
/new Create a React component for a user avatar
     that shows initials if no image is provided

→ Copilot creates a new file with the full component:
  UserAvatar.jsx with props: src, name, size
  Falls back to colored initials circle when src is missing

/terminal — Shell Command Suggestions

Use /terminal in the Chat panel (or switch to terminal chat) to get help with command-line tasks.

IN CHAT: /terminal Find all TypeScript files modified in the last 24 hours

COPILOT SUGGESTS:
find . -name "*.ts" -mtime -1 -not -path "*/node_modules/*"

IN CHAT: /terminal Install all packages and run tests in one command

COPILOT SUGGESTS:
npm install && npm test

Combining Slash Commands in a Workflow

Slash commands work best as a sequence. Use them one after the other to build, document, and test a function in a single workflow.

WORKFLOW EXAMPLE:
1. Write a rough version of a function
2. /simplify     → clean up the implementation
3. /optimize     → improve performance
4. /doc          → add documentation
5. /tests        → generate test cases
6. /fix          → fix any issues the tests reveal

Result: A production-ready function with documentation
        and tests — completed in under 10 minutes.

Slash commands remove the need to describe common tasks in long sentences. Once you memorize the handful of commands you use most, your interaction with Copilot becomes faster and more consistent.

Leave a Comment

Your email address will not be published. Required fields are marked *