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

Bài 3: Inline Suggestions & Next Edit Suggestions — Gợi ý code thông minh

Ghost text completions, tab to accept, cycle suggestions, multi-line completions. Next Edit Suggestions (NES) — dự đoán edit tiếp theo. Navigating suggestions, partial accept, keyboard shortcuts. Tips tối ưu chất lượng gợi ý.

💻 Lập trình — Bài 3 Bài 3: Inline Suggestions & Next Edit Suggestions — Gợi ý code thông minh

Vibe Coding với GitHub Copilot: Từ Cơ bản đến Nâng cao

Phần 1: Nền tảng Vibe Coding & GitHub Copilot

xdev.asia

1. Inline Suggestions là gì?

Inline Suggestions (Ghost Text) là tính năng cốt lõi của GitHub Copilot — khi bạn gõ code, Copilot tự động gợi ý phần code tiếp theo dưới dạng text mờ (ghost text) hiển thị ngay trong editor.

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

Copilot phân tích context xung quanh để đưa ra gợi ý phù hợp:

  • Tên file, ngôn ngữ lập trình
  • Comments phía trên dòng hiện tại
  • Code đã viết trong file
  • Các file khác đang mở trong editor
  • Import statements, function signatures

2. Thao tác với Inline Suggestions

2.1. Accept & Reject

Thao tác Shortcut macOS Shortcut Win/Linux
Accept toàn bộ suggestion Tab Tab
Reject suggestion Esc Esc
Accept từng word Cmd+→ Ctrl+→
Accept từng line Cmd+Shift+→ Ctrl+Shift+→

2.2. Cycle qua nhiều Suggestions

Copilot thường có nhiều gợi ý khác nhau. Hover vào ghost text để thấy navigation controls:

Thao tác Shortcut macOS Shortcut Win/Linux
Suggestion tiếp theo Option+] Alt+]
Suggestion trước Option+[ Alt+[

2.3. Partial Accept — Kỹ thuật quan trọng

Partial accept cho phép bạn chỉ lấy một phần suggestion, rồi tiếp tục gõ để Copilot gợi ý lại theo hướng bạn muốn:

// 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

Đây là kỹ thuật steering — dẫn dắt AI theo ý bạn thay vì chấp nhận mù quáng.

3. Next Edit Suggestions (NES)

NES là tính năng nâng cao hơn — Copilot dự đoán chỗ tiếp theo bạn cần edit dựa trên thay đổi bạn vừa làm.

Ví dụ: Rename variable

// 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

Ví dụ: Thêm parameter

# 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

Bật NES

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

4. Multi-line Completions

Copilot có thể suggest entire functions, classes, hoặc blocks of code:

// 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);
}

Tips cho multi-line suggestions tốt hơn:

  • Viết comment mô tả rõ ràng trước khi nhấn Enter
  • Đặt tên function/variable có ý nghĩa — Copilot đọc tên để hiểu ý định
  • Mở file liên quan — Copilot dùng context từ các tab đang mở
  • Viết test trước — Copilot đọc test để hiểu expected behavior

5. Comment-Driven Development

Một pattern hiệu quả cho Vibe Coding với Inline Suggestions:

# 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. Tối ưu context để suggestions tốt hơn

6.1. File đang mở ảnh hưởng suggestions

Copilot xem context từ các tab đang mở. Mở những file liên quan để Copilot hiểu codebase:

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. Import statements là context tốt

# 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. Type annotations cho suggestions chính xác hơn

// 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. Khi nào Inline Suggestions không hiệu quả?

  • Logic phức tạp, domain-specific — dùng Chat/Agent thay thế
  • Không có context — file mới trống, không có imports/comments
  • Code đã viết sai pattern — Copilot sẽ tiếp tục pattern sai
  • Cross-file dependencies — Copilot có giới hạn context window

Rule of thumb: Inline Suggestions phù hợp cho single-file, incremental edits. Cho multi-file features, dùng Agent Mode (Bài 5).

8. Bài tập thực hành

Tạo file practice.ts và thực hành:

  1. Viết comment mô tả function → nhấn Enter → accept suggestion
  2. Gõ function signature → để Copilot suggest body
  3. Thử partial accept (Cmd+→) để steer suggestion
  4. Cycle qua multiple suggestions (Option+]/[)
  5. Rename một variable → quan sát NES suggest edits ở nơi khác
// 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. Tổng kết

Feature Mô tả Khi nào dùng
Inline Suggestions Ghost text tự động khi gõ Code hàng ngày, boilerplate
Partial Accept Accept từng word/line Steer suggestion theo ý muốn
NES Predict next edit location Rename, add params, refactor
Multi-line Suggest entire functions Khi có comment/signature rõ ràng
Comment-driven Write comment → get code Complex logic description

Bài tiếp theo sẽ cover Inline Chat & Smart Actions — công cụ mạnh mẽ cho targeted edits và refactoring ngay trong editor.