Lý thuyết
25 phút
Bài 3/12

Copilot Autocomplete - Ghost Text Magic

Master Ghost Text suggestions và các kỹ thuật để Copilot suggest code chính xác hơn

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

Text
1┌─────────────────────────────────────────┐
2│ def calculate_average(numbers): │ ← Code bạn viết
3│ return sum(numbers) / len(numbers) │ ← Ghost Text (màu xám)
4└─────────────────────────────────────────┘

Keyboard shortcuts cho Ghost Text

ActionWindows/LinuxmacOS
Accept allTabTab
Accept wordCtrl+→Cmd+→
Accept lineEndCmd+→
DismissEscEsc
Next suggestionAlt+]Option+]
Previous suggestionAlt+[Option+[

2. Triggers để Copilot suggest

2.1 Function signature

Chỉ cần viết tên function, Copilot sẽ suggest body:

Python
1def validate_email(email):
2 # Copilot suggests regex validation!

2.2 Comments trước code

Comments là "prompt" mạnh nhất:

Python
1# Check if a number is prime
2def is_prime(n):
3 # Copilot đã hiểu context từ comment

2.3 Docstrings

Copilot rất giỏi với docstrings:

Python
1def binary_search(arr, target):
2 """
3 Perform binary search on a sorted array.
4
5 Args:
6 arr: Sorted list of elements
7 target: Element to find
8
9 Returns:
10 Index of target if found, -1 otherwise
11 """
12 # Copilot generates perfect implementation!

2.4 Tiếp nối pattern

Copilot học từ patterns trong file:

Python
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:

Python
1def f(x, y):
2 pass
3
4def proc(d):
5 pass

Good:

Python
1def calculate_distance(point1, point2):
2 # Copilot hiểu cần calculate distance
3
4def process_user_data(user_dict):
5 # Copilot hiểu đang xử lý user data

3.2 Cung cấp context qua imports

Python
1import pandas as pd
2import matplotlib.pyplot as plt
3
4# Copilot biết bạn đang làm data analysis
5df = pd.read_csv('data.csv')
6# Suggestions sẽ liên quan đến pandas/matplotlib

3.3 Viết example trong comments

Python
1# Convert temperature from Celsius to Fahrenheit
2# Example: celsius_to_fahrenheit(0) -> 32
3# Example: celsius_to_fahrenheit(100) -> 212
4def celsius_to_fahrenheit(celsius):
5 # Copilot có examples để verify logic

3.4 Break down complex tasks

Thay vì:

Python
1# Build a complete REST API with authentication

Hãy:

Python
1# Step 1: Create Flask app
2# Step 2: Add user model
3# Step 3: Implement register endpoint
4# Step 4: Implement login endpoint
5# Step 5: Add JWT authentication

4. Multiple Suggestions

Copilot thường có nhiều suggestions cho cùng một context.

Xem tất cả suggestions

  1. Khi có Ghost Text, nhấn Ctrl+Enter
  2. Panel hiện ra với 10+ suggestions
  3. 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

Python
1# Sort a list of dictionaries by 'name' key
2users = [{"name": "Bob"}, {"name": "Alice"}, {"name": "Charlie"}]
3
4# Suggestion 1:
5sorted_users = sorted(users, key=lambda x: x['name'])
6
7# Suggestion 2:
8from operator import itemgetter
9sorted_users = sorted(users, key=itemgetter('name'))
10
11# 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

  1. Select code block
  2. Nhấn Ctrl+I
  3. Gõ instruction
  4. Review và Accept/Reject

Use cases

Python
1# Original code
2def greet(name):
3 return "Hello " + name
4
5# Select code → Ctrl+I → "Add type hints and docstring"
6
7# Result
8def greet(name: str) -> str:
9 """
10 Return a greeting message for the given name.
11
12 Args:
13 name: The name to greet
14
15 Returns:
16 A greeting string
17 """
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 ✅

  1. Viết comments trước code - Đây là prompt tốt nhất
  2. Đặt tên biến/function descriptive - Copilot hiểu context
  3. Provide examples - Giúp Copilot hiểu expected behavior
  4. Review suggestions carefully - Copilot không phải lúc nào cũng đúng
  5. Use Tab wisely - Chỉ accept khi chắc chắn

DON'T ❌

  1. Blind accept - Luôn review code
  2. Vague naming - x, data, temp không helpful
  3. Skip context - Copilot cần context để suggest tốt
  4. 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:

Python
1"""
2Data Processor Module
3
4This module provides utilities for processing CSV data:
5- Load CSV file into list of dictionaries
6- Filter data by column value
7- Calculate statistics (mean, median, mode)
8- Export processed data to JSON
9"""
10
11import csv
12import json
13from statistics import mean, median, mode
14
15# TODO: Let Copilot implement these functions
16
17# Load CSV file and return list of dictionaries
18def load_csv(filepath):
19 pass
20
21# Filter data where column equals value
22def filter_by_column(data, column, value):
23 pass
24
25# Calculate statistics for a numeric column
26def calculate_stats(data, column):
27 pass
28
29# Export data to JSON file
30def export_to_json(data, filepath):
31 pass
32
33# Main function to demonstrate usage
34def main():
35 pass
36
37if __name__ == "__main__":
38 main()

Hints

  1. Đặt cursor sau mỗi pass
  2. Delete pass và đợi Copilot suggest
  3. 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!