# Code Completion **Status**: ✅ Complete **Phase**: Phase 3 - MVP Features **Last Updated**: December 4, 2025 --- ## Overview Code Completion provides intelligent code suggestions as you type. The completion engine analyzes your code context and suggests relevant completions ranked by relevance, frequency, and recency. It supports multiple languages through a pluggable provider system and includes ghost text (inline suggestions) for quick acceptance. ## Key Features - **Context-Aware Suggestions**: Analyzes code context to suggest only relevant completions - **Multi-Language Support**: Built-in support for Rust, TypeScript, and Python with generic fallback - **Ghost Text**: Inline suggestions shown in lighter color for quick preview - **Intelligent Ranking**: Completions ranked by relevance, frequency, and recency - **Language-Specific Providers**: Pluggable providers for language-specific behavior - **Configuration-Driven**: Language-specific behavior defined in configuration files, not hardcoded ## How to Use ### Basic Usage 1. **Start Typing**: Begin typing code in your editor 2. **View Suggestions**: Completion suggestions appear automatically 3. **Select Suggestion**: Use arrow keys to navigate, Enter to select 4. **Accept Ghost Text**: Press Tab to accept the inline suggestion ### Keyboard Shortcuts | Shortcut | Action | |----------|--------| | **Tab** | Accept ghost text suggestion | | **Escape** | Dismiss suggestions | | **Enter** | Select highlighted suggestion | | **Arrow Up/Down** | Navigate suggestions | | **Ctrl+Space** | Trigger completion manually | ### Ghost Text Ghost text shows the top suggestion in a lighter color. You can: - **Accept**: Press Tab to insert the suggestion - **Dismiss**: Press Escape to hide the suggestion - **Ignore**: Continue typing to update the suggestion - **Partial Accept**: Press Ctrl+Right to accept word-by-word ## External LSP Integration ### Overview Code completion now integrates with external LSP servers for production-quality semantic completions. When an external LSP server is configured for a language, ricecoder forwards completion requests to the external server and merges the results with internal completions. ### How It Works 1. **Request Forwarding**: When you trigger completion, ricecoder forwards the request to the configured external LSP server 2. **Response Merging**: External completions are merged with internal completions, with external results prioritized 3. **Graceful Degradation**: If the external LSP is unavailable, ricecoder falls back to internal completions 4. **Deduplication**: Duplicate completions are automatically removed ### Supported External LSP Servers - **Rust**: rust-analyzer (recommended) - **TypeScript/JavaScript**: typescript-language-server - **Python**: pylsp - **Go**: gopls - **And many more**: See [External LSP Integration](./External-LSP-Integration.md) for complete list ### Configuration External LSP servers are configured in `~/.ricecoder/lsp-servers.yaml`. See [External LSP Configuration Guide](./External-LSP-Configuration.md) for detailed configuration options. ### Performance - **External LSP**: 100-500ms (depends on project size) - **Internal Fallback**: 50-100ms - **Merged Results**: Displayed within 500ms ### Fallback Behavior If external LSP is unavailable, ricecoder automatically falls back to internal completions: - **Completions**: Internal keyword and pattern-based completions - **Diagnostics**: Internal syntax checking - **Hover**: Internal symbol lookup This ensures ricecoder remains usable even if external LSP servers are not installed or fail. ## Configuration ### Language Configuration Completion behavior is configured through language configuration files. Each language can define: - **Keywords**: Language-specific keywords to suggest - **Snippets**: Code templates for common patterns - **Ranking Weights**: How to weight relevance, frequency, and recency - **Provider**: Reference to language-specific provider ### Configuration Format Configuration files use YAML format: ```yaml language: rust keywords: - fn - let - mut - struct - impl - trait snippets: - label: "fn main" template: "fn main() {\n ${1}\n}" description: "Main function" - label: "println!" template: "println!(\"${1}\");" description: "Print macro" ranking_weights: relevance: 0.5 frequency: 0.3 recency: 0.2 provider: "rust" ``` ### Configuration Hierarchy Configurations are loaded in this order (later overrides earlier): 1. **Built-in Defaults**: Default configuration for each language 2. **User Configuration**: `~/.ricecoder/completion.yaml` 3. **Project Configuration**: `.ricecoder/completion.yaml` 4. **Runtime Overrides**: CLI flags or API calls ## Supported Languages ### Rust Full support with Rust-specific completions: - Keywords: `fn`, `let`, `mut`, `struct`, `impl`, `trait`, `match`, `if`, `for`, `while` - Types: `String`, `Vec`, `Option`, `Result`, `HashMap` - Macros: `println!`, `vec!`, `format!`, `panic!` - Snippets: Function templates, loop templates, match patterns ### TypeScript/JavaScript Full support with TypeScript-specific completions: - Keywords: `const`, `let`, `var`, `function`, `class`, `interface`, `async`, `await` - Types: `Array`, `Object`, `Promise`, `Map`, `Set` - Methods: Common array and object methods - Snippets: Function templates, arrow functions, async patterns ### Python Full support with Python-specific completions: - Keywords: `def`, `class`, `if`, `for`, `while`, `with`, `async`, `await` - Types: `list`, `dict`, `str`, `int`, `float`, `bool` - Methods: Common list and dict methods - Snippets: Function templates, class templates, context managers ### Generic Fallback For unconfigured languages, the engine provides generic text-based completions: - Prefix matching - Fuzzy matching - Frequency-based ranking - No language-specific knowledge ## Examples ### Rust Example ```rust fn main() { let x = // Suggestions: String, Vec, Option, Result, ... let numbers = vec![1, 2, 3]; for n in numbers.iter() { // Suggestions: println!, format!, panic!, ... } } ``` ### TypeScript Example ```typescript const data = // Suggestions: Array, Object, Promise, Map, ... async function fetchData() { const response = await fetch(url); // Suggestions: json(), text(), blob(), ... } ``` ### Python Example ```python def process_data(items): result = // Suggestions: list, dict, str, ... for item in items: # Suggestions: append, extend, insert, ... ``` ## Troubleshooting ### No Suggestions Appearing **Problem**: Completion suggestions don't appear when typing. **Solutions**: 1. Check that completion is enabled: `ricecoder config completion.enabled true` 2. Verify language is supported: Check `ricecoder completion list-languages` 3. Check for errors: Look in logs for completion errors 4. Try manual trigger: Press Ctrl+Space to manually trigger completion ### Suggestions Are Irrelevant **Problem**: Completion suggestions don't match the context. **Solutions**: 1. Check language configuration: Verify language is correctly detected 2. Update ranking weights: Adjust `ranking_weights` in configuration 3. Check context analysis: Verify scope and symbol detection is working 4. Report issue: File a bug with code example ### Ghost Text Not Showing **Problem**: Ghost text (inline suggestions) doesn't appear. **Solutions**: 1. Check ghost text is enabled: `ricecoder config completion.ghost_text.enabled true` 2. Check theme supports ghost text: Verify theme has ghost text styling 3. Check terminal supports styling: Some terminals don't support lighter colors 4. Try different theme: Switch to a theme with better ghost text support ### Performance Issues **Problem**: Completion is slow or causes lag. **Solutions**: 1. Reduce suggestion count: `ricecoder config completion.max_suggestions 10` 2. Increase timeout: `ricecoder config completion.timeout_ms 200` 3. Disable frequency tracking: `ricecoder config completion.track_frequency false` 4. Check system resources: Monitor CPU and memory usage ## Performance Completion performance targets: - **Completion Generation**: < 100ms - **Ghost Text Update**: < 50ms - **Prefix Filtering**: < 50ms - **Ranking**: < 50ms Performance is optimized through: - Efficient prefix matching and fuzzy matching - Caching of parsed code and symbols - Lazy loading of language-specific providers - Configurable suggestion limits ## Limitations - **Incomplete Code**: Completion works best with syntactically valid code - **Large Files**: Performance may degrade with very large files (>100KB) - **Complex Types**: Type inference is limited for complex generic types - **External Dependencies**: Completion doesn't analyze external dependencies ## See Also - [External LSP Integration](./External-LSP-Integration.md) - External LSP server integration - [External LSP Configuration](./External-LSP-Configuration.md) - Configuration reference - [Configuration Guide](./Configuration.md) - Configuration options - [LSP Integration](./LSP-Integration.md) - Language Server Protocol integration - [Architecture Overview](./Architecture-Overview.md) - System architecture - [Troubleshooting](./Troubleshooting.md) - General troubleshooting guide --- *Last updated: December 5, 2025*