Code Generation Intermediate
Cursor offers three levels of AI code generation: Tab for inline completions, Cmd-K for targeted edits, and Chat/Composer for larger generation tasks. This lesson covers techniques for getting the best results from each approach.
Tab Completion
Tab completion is Cursor's real-time autocomplete. It predicts what you are about to type and offers multi-line suggestions as you code:
| Action | Key | Description |
|---|---|---|
| Accept suggestion | Tab | Accept the full suggested completion |
| Accept word | Ctrl + Right Arrow | Accept one word at a time from the suggestion |
| Dismiss | Esc | Dismiss the current suggestion |
| Trigger manually | Ctrl + Space | Force a suggestion when one is not showing |
Cmd-K Inline Editing
Cmd-K (Ctrl+K on Windows/Linux) is Cursor's inline editing command. Select code, press Cmd-K, and describe what to change:
Common Cmd-K Operations
| Operation | Prompt Example |
|---|---|
| Add error handling | "Add try-catch with proper error messages" |
| Add types | "Add TypeScript types to all parameters and return values" |
| Optimize | "Optimize this function for performance" |
| Convert | "Convert this class component to a functional component with hooks" |
| Add logging | "Add debug logging for each step" |
| Write tests | "Write jest tests for this function" |
Generating Entire Files
For generating entire new files, use either Chat or Composer:
# Generate a complete React component
Create a UserProfile component in React with TypeScript that:
- Displays user avatar, name, email, and bio
- Has an edit mode toggle
- Uses the existing @types/User.ts type
- Follows the styling patterns in @components/Card.tsx
- Includes loading and error states
Generating Tests
Cursor excels at test generation because it can read the implementation:
# Generate comprehensive tests
Write unit tests for @src/utils/validation.ts using Jest.
Cover:
- All exported functions
- Edge cases (empty strings, null, undefined)
- Error cases
- At least 3 test cases per function
Follow the existing test patterns in @tests/helpers.test.ts
Generating Documentation
# Select a function, press Cmd-K, then type:
Add JSDoc documentation with @param, @returns, @throws, and @example tags
Tips for Better Generation
- Be specific — "Add input validation" is vague; "Validate that email matches RFC 5322 format" is precise
- Reference existing code — Use @-mentions to show the AI your conventions and patterns
- Generate incrementally — Generate one function at a time rather than an entire file
- Review carefully — AI-generated code can have subtle bugs; always review the diff
- Iterate — If the first result is not right, refine your prompt rather than starting over
Try It Yourself
Practice all three generation methods: write a comment and let Tab complete the function, select code and use Cmd-K to add error handling, and use Chat to generate a complete test file.
Next: Multi-File Editing →
Lilly Tech Systems