Chuyển đến nội dung chính

第 3 課:內聯建議與下一個編輯建議 - 智慧代碼建議

幽靈文字完成、選項卡接受、循環建議、多行完成。下一個編輯建議 (NES) — 預測下一個編輯。導航建議、部分接受、鍵盤快速鍵。優化建議品質的提示。

💻 程式設計 — 第 3 課 第 3 課:內聯建議與下一次編輯 建議——智慧程式碼建議

使用 GitHub Copilot 進行 Vibe 編碼:從基礎知識到高級

第 1 部分:Vibe 編碼平台和 GitHub Copilot

亞洲開發網

1. 什麼是內嵌建議?

內嵌建議(幽靈文字)是 GitHub Copilot 的核心功能 - 當您鍵入程式碼時,Copilot 會自動以以下形式建議下一段程式碼: 幽靈文字 顯示在編輯器中。

Bạn gõ:    function calculateTax(income) {
Ghost text: ░░ const taxRate = income > 50000 ? 0.3 : 0.2;
            ░░ return income * taxRate;
            ░░}

副駕駛分析 情境 周圍提出合適的建議:

  • 檔案名稱、程式語言
  • 目前行上方的註釋
  • 程式碼寫入文件
  • 其他文件在編輯器中打開
  • 導入語句、函式簽名

2. 使用內聯建議

2.1.接受與拒絕

操作 捷徑 macOS Windows/Linux 快捷方式
接受所有建議 選項卡 選項卡
拒絕建議 ESC ESC
接受每一個字 Cmd+→ Ctrl+→
接受每一行 Cmd+Shift+→ Ctrl+Shift+→

2.2.循環瀏覽許多建議

副駕駛經常有很多不同的建議。將滑鼠懸停在幽靈文字上即可查看導航控制項:

操作 捷徑 macOS Windows/Linux 快捷方式
下一個建議 選項+] Alt+]
建議優先 選項+[ Alt+[

2.3.部分接受-重要技術

部分接受 允許您僅接受部分建議,然後繼續輸入以使 Copilot 按您想要的方向重新建議:

// Ghost text suggest: const result = data.filter(item => item.active).map(item => item.name);
// Bạn accept "const result = data.filter(" bằng Cmd+→ vài lần
// Rồi gõ tiếp: item => item.price > 100
// Copilot sẽ suggest phần còn lại phù hợp với logic mới

這是技術性的 轉向。轉向 ——引導AI按照你的喜好,而不是盲目接受。

3. 下一個編輯建議 (NES)

NES 更先進-Copilot 預測下一步需要編輯的位置 基於您剛剛所做的更改。

例如:重新命名變數

// Bạn vừa đổi tên biến ở dòng 5: userName → displayName
// NES tự động highlight và suggest đổi tên ở dòng 12, 18, 25

// Dòng 5: const displayName = user.name; ← bạn vừa edit // Dòng 12: console.log(displayName); ← NES suggest edit này // ^^^^^^^^^^^ // Nhấn Tab để accept, Copilot tự nhảy đến dòng tiếp theo cần edit

範例:新增參數

# Bạn vừa thêm parameter 'currency' vào function definition
def format_price(amount, currency):   # ← vừa thêm currency
    # NES suggest cập nhật body function để sử dụng currency
    return f"{currency} {amount:,.2f}"

NES cũng suggest cập nhật tất cả function calls

format_price(100, "USD") # ← NES suggest thêm argument

打開紅白機

{
  "editor.inlineSuggest.edits.enabled": true
}

4. 多行補全

Copilot 可以建議整個函數、類別或程式碼區塊:

// Bạn gõ comment mô tả:
// Function to validate email address using regex

// Copilot suggest toàn bộ function:
function validateEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

更好的多行建議的提示:

  • 寫出清晰的描述性評論 按 Enter 鍵之前
  • 有意義地命名函數/變數 — 副駕駛讀名字以了解意圖
  • 開啟相關文件 — Copilot 使用開啟標籤中的上下文
  • 先寫測試 — 副駕駛閱讀測驗以了解預期行為

5. 評論驅動開發

帶有內聯建議的 Vibe 編碼的有效模式:

# 1. Viết comment mô tả intent
# Read CSV file, group by category, calculate average price per category,
# sort by average price descending, and return top 5

# 2. Nhấn Enter → Copilot sinh toàn bộ implementation
import pandas as pd

def get_top_categories(csv_path: str, top_n: int = 5) -> pd.DataFrame:
    df = pd.read_csv(csv_path)
    result = (df.groupby('category')['price']
              .mean()
              .sort_values(ascending=False)
              .head(top_n)
              .reset_index()
              .rename(columns={'price': 'avg_price'}))
    return result

6.優化上下文以獲得更好的建議

6.1.開啟的文件受到建議的影響

副駕駛查看單字上下文 打開選項卡。開啟相關文件,以便 Copilot 了解程式碼庫:

Tab 1: models/User.ts          ← Copilot biết User schema
Tab 2: services/UserService.ts ← Đang viết, suggest dựa trên User model
Tab 3: tests/user.test.ts      ← Copilot hiểu expected behavior

6.2.導入語句是很好的上下文

# Viết imports trước → Copilot biết bạn dùng thư viện nào
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
from pydantic import BaseModel

Bây giờ Copilot sẽ suggest code theo FastAPI patterns

6.3.類型註釋提供更精確的建議

// Với type → suggestion chính xác
interface Product {
  id: string;
  name: string;
  price: number;
  category: string;
}

function filterProducts(products: Product[], minPrice: number): Product[] { // Copilot biết chính xác structure và suggest phù hợp }

7. 內嵌建議什麼時候不起作用?

  • 複雜的、特定領域的邏輯 — 使用聊天/代理代替
  • 沒有上下文 — 新檔案為空,沒有匯入/註釋
  • 程式碼以錯誤的模式編寫 — 副駕駛將繼續錯誤的模式
  • 跨文件依賴 — 副駕駛的上下文視窗有限

經驗法則: 內嵌建議適用於 單檔增量編輯。對於多檔案功能,請使用 代理模式 (第 5 課)。

8.練習練習

建立文件 練習.ts 並練習:

  1. 寫一則描述該功能的評論 → 按 Enter → 接受建議
  2. 輸入函數簽名 → 讓 Copilot 建議正文
  3. 嘗試部分接受 (Cmd+→) 引導建議
  4. 循環顯示多個建議 (Option+]/[)
  5. 重新命名變數 → 觀察 NES 在其他地方建議的編輯
// Bài tập 1: Viết comment, nhấn Enter
// Function to convert temperature from Celsius to Fahrenheit

// Bài tập 2: Viết signature, để Copilot suggest body
function sortByDate(items: Array<{date: string, title: string}>)

// Bài tập 3: Viết test function, để Copilot suggest test cases
describe('sortByDate', () => {
  it('should

9. 總結

特點 描述 何時使用
內嵌建議 打字時自動生成幻影文本 每日代碼、樣板
部分接受 接受每個單字/行 根據需要引導建議
紅白機 預測下一個編輯位置 重新命名、新增參數、重構
多線 建議整個功能 當有明確的評論/簽名時
評論驅動 寫評論→取得程式碼 複雜邏輯描述

下一首歌曲將是翻唱歌曲 內嵌聊天和智慧操作 — 在編輯器中進行有針對性的編輯和重構的強大工具。