Copilot Autocomplete - Ghost Text Magic
1. Hiểu về Ghost Text
Ghost Text là inline suggestions màu xám mờ mà Copilot hiển thị khi bạn đang gõ. Đây là tính năng core của Copilot.
Cách hoạt động
1┌─────────────────────────────────────────┐2│ def calculate_average(numbers): │ ← Code bạn viết3│ return sum(numbers) / len(numbers) │ ← Ghost Text (màu xám)4└─────────────────────────────────────────┘Keyboard shortcuts cho Ghost Text
| Action | Windows/Linux | macOS |
|---|---|---|
| Accept all | Tab | Tab |
| Accept word | Ctrl+→ | Cmd+→ |
| Accept line | End | Cmd+→ |
| Dismiss | Esc | Esc |
| Next suggestion | Alt+] | Option+] |
| Previous suggestion | Alt+[ | Option+[ |
2. Triggers để Copilot suggest
2.1 Function signature
Chỉ cần viết tên function, Copilot sẽ suggest body:
1def validate_email(email):2 # Copilot suggests regex validation!2.2 Comments trước code
Comments là "prompt" mạnh nhất:
1# Check if a number is prime2def is_prime(n):3 # Copilot đã hiểu context từ comment2.3 Docstrings
Copilot rất giỏi với docstrings:
1def binary_search(arr, target):2 """3 Perform binary search on a sorted array.4 5 Args:6 arr: Sorted list of elements7 target: Element to find8 9 Returns:10 Index of target if found, -1 otherwise11 """12 # Copilot generates perfect implementation!2.4 Tiếp nối pattern
Copilot học từ patterns trong file:
1users = [2 {"name": "Alice", "age": 30},3 {"name": "Bob", "age": 25},4 # Copilot sẽ suggest thêm users theo pattern!3. Kỹ thuật viết code để Copilot hiểu tốt hơn
3.1 Đặt tên biến/function rõ ràng
❌ Bad:
1def f(x, y):2 pass34def proc(d):5 pass✅ Good:
1def calculate_distance(point1, point2):2 # Copilot hiểu cần calculate distance3 4def process_user_data(user_dict):5 # Copilot hiểu đang xử lý user data3.2 Cung cấp context qua imports
1import pandas as pd2import matplotlib.pyplot as plt34# Copilot biết bạn đang làm data analysis5df = pd.read_csv('data.csv')6# Suggestions sẽ liên quan đến pandas/matplotlib3.3 Viết example trong comments
1# Convert temperature from Celsius to Fahrenheit2# Example: celsius_to_fahrenheit(0) -> 323# Example: celsius_to_fahrenheit(100) -> 2124def celsius_to_fahrenheit(celsius):5 # Copilot có examples để verify logic3.4 Break down complex tasks
Thay vì:
1# Build a complete REST API with authenticationHãy:
1# Step 1: Create Flask app2# Step 2: Add user model3# Step 3: Implement register endpoint4# Step 4: Implement login endpoint5# Step 5: Add JWT authentication4. Multiple Suggestions
Copilot thường có nhiều suggestions cho cùng một context.
Xem tất cả suggestions
- Khi có Ghost Text, nhấn
Ctrl+Enter - Panel hiện ra với 10+ suggestions
- Click để chọn hoặc
Escđể close
Khi nào dùng multiple suggestions?
- Code có nhiều cách implement
- Muốn so sánh approaches
- Suggestion đầu không đúng ý
Example
1# Sort a list of dictionaries by 'name' key2users = [{"name": "Bob"}, {"name": "Alice"}, {"name": "Charlie"}]34# Suggestion 1:5sorted_users = sorted(users, key=lambda x: x['name'])67# Suggestion 2:8from operator import itemgetter9sorted_users = sorted(users, key=itemgetter('name'))1011# Suggestion 3:12users.sort(key=lambda x: x['name'])5. Inline Chat (Ctrl+I)
Ngoài Ghost Text, bạn có thể dùng Inline Chat để yêu cầu specific changes.
Cách sử dụng
- Select code block
- Nhấn
Ctrl+I - Gõ instruction
- Review và Accept/Reject
Use cases
1# Original code2def greet(name):3 return "Hello " + name45# Select code → Ctrl+I → "Add type hints and docstring"67# Result8def greet(name: str) -> str:9 """10 Return a greeting message for the given name.11 12 Args:13 name: The name to greet14 15 Returns:16 A greeting string17 """18 return f"Hello {name}"6. Copilot Labs Features (Preview)
6.1 Explain Code
Select code → Right click → Copilot: Explain This
6.2 Fix Bug
Khi có error, Copilot có thể suggest fix.
6.3 Generate Docs
Tự động generate docstrings cho functions.
6.4 Generate Tests
Select function → Generate unit tests tự động!
7. Best Practices Summary
DO ✅
- Viết comments trước code - Đây là prompt tốt nhất
- Đặt tên biến/function descriptive - Copilot hiểu context
- Provide examples - Giúp Copilot hiểu expected behavior
- Review suggestions carefully - Copilot không phải lúc nào cũng đúng
- Use Tab wisely - Chỉ accept khi chắc chắn
DON'T ❌
- Blind accept - Luôn review code
- Vague naming -
x,data,tempkhông helpful - Skip context - Copilot cần context để suggest tốt
- Ignore errors - Copilot-generated code vẫn có thể có bugs
8. Hands-on Exercise
Challenge: Data Processing với Copilot
Tạo file data_processor.py và để Copilot help bạn implement:
1"""2Data Processor Module34This module provides utilities for processing CSV data:5- Load CSV file into list of dictionaries6- Filter data by column value7- Calculate statistics (mean, median, mode)8- Export processed data to JSON9"""1011import csv12import json13from statistics import mean, median, mode1415# TODO: Let Copilot implement these functions1617# Load CSV file and return list of dictionaries18def load_csv(filepath):19 pass2021# Filter data where column equals value22def filter_by_column(data, column, value):23 pass2425# Calculate statistics for a numeric column26def calculate_stats(data, column):27 pass2829# Export data to JSON file30def export_to_json(data, filepath):31 pass3233# Main function to demonstrate usage34def main():35 pass3637if __name__ == "__main__":38 main()Hints
- Đặt cursor sau mỗi
pass - Delete
passvà đợi Copilot suggest - Nếu suggestion không đúng, thêm comment mô tả chi tiết hơn
Tiếp theo
Bài tiếp theo chúng ta sẽ học Prompt Engineering for Code - nghệ thuật viết prompts để Copilot sinh ra exactly code bạn muốn!
