Step 4: Generating Multi-Line Code Blocks

GitHub Copilot can generate substantial code blocks, like functions or classes, based on context or explicit instructions.

Method 1: Inline Generation from Context / Comments

Copilot automatically suggests multi-line blocks when it detects context like a function signature, class definition, or a descriptive comment.

  1. Start writing code that implies a larger structure (e.g., class User: or function calculateTotal(items) {).
  2. Alternatively, write a comment describing what the next block should do (e.g., // function to fetch user data from API).
  3. Wait a moment for Copilot to provide a multi-line greyed-out suggestion.
  4. Press Tab to accept the entire block.

Example (Comment Trigger):

# User types:
# Function to calculate the factorial of n using recursion
def factorial(n):

# Copilot Suggests (ghost text):
def factorial(n):
    """Calculates the factorial of n recursively."""
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

Method 2: Chat Generation (Ctrl+Alt+I or Chat View)

Use Copilot Chat for more explicit control over generation, especially for complex blocks or when you want to refine the request.

  1. Open Copilot Chat (either inline with Ctrl+I in VS Code, or the full Chat view via Ctrl+Alt+I or View menu).
  2. Type a clear prompt describing the code block you need.
  3. Use context variables like #selection or #file, or @workspace / @project participants to provide context if needed.
  4. Use slash commands like /new or /newNotebook for generating new files/notebooks.
  5. Review the generated code block in the chat.
  6. Use the provided buttons to Copy, Insert at Cursor, Insert into New File, or Preview the code.

Example Prompt (Chat):

/new Create a simple Python Flask route for /hello that returns "Hello, World!"

Copilot Chat will generate the necessary Flask code block, potentially in a new file context.

Tips for Effective Generation

Be Specific & Provide Context

Clearly define the language, purpose, inputs, outputs, and any libraries/frameworks to use. Use Chat context variables (#file, #selection) or provide examples in your prompt.

Break Down Complex Tasks

Instead of asking for an entire application, prompt for smaller components (e.g., "Generate the User model class", then "Generate the API endpoint to get users").

Iterate and Refine

Use follow-up prompts in Chat to modify the generated code (e.g., "Add error handling to the previous code", "Refactor this using list comprehensions"). Review and test all generated code.