This content originally appeared on DEV Community and was authored by Sreenath
Complete step-by-step guide to AI-powered code generation directly in vim
If you're a vim user who's tired of constantly switching to ChatGPT, Claude, or other AI tools just to generate a quick function or command, this tutorial is for you.
By the end of this guide, you'll be generating code directly in your vim buffer without ever leaving your editor.
What We're Building
Instead of this workflow:
- Get stuck on a function
- Alt-tab to ChatGPT
- Ask for help
- Copy the response
- Alt-tab back to vim
- Paste and fix formatting
You'll do this:
- Type
:r !llmswap generate "what you need"
- Code appears at your cursor
- Keep coding
Prerequisites
- Vim installed (obviously!)
- Python 3.7+
- An API key for any LLM provider (OpenAI, Anthropic, Google, etc.)
Step 1: Install llmswap
pip install llmswap
That's it. No config files, no complex setup.
Step 2: Set Your API Key
Choose your preferred AI provider and set the environment variable:
For OpenAI (GPT-4):
export OPENAI_API_KEY="sk-your-key-here"
For Anthropic (Claude):
export ANTHROPIC_API_KEY="sk-ant-your-key-here"
For Google (Gemini):
export GEMINI_API_KEY="your-gemini-key"
For local/free option (Ollama):
# No API key needed, just install Ollama
export OLLAMA_MODEL="llama2"
Add this to your .bashrc
or .zshrc
to make it permanent.
Step 3: Test in Terminal First
Before using in vim, test in your terminal:
llmswap generate "Python function to read CSV file with error handling"
You should see a complete function appear. If not, check your API key setup.
Step 4: The Magic Vim Command
In vim, the :r !
command runs a shell command and inserts its output at your cursor position.
Basic syntax:
:r !llmswap generate "what you want to generate"
Step 5: Your First Code Generation
Open vim and try this:
- Open a Python file:
vim test.py
- Position your cursor where you want the function
- Type:
:r !llmswap generate "function to validate email address"
- Press Enter
- Watch the code appear!
Real Examples You Can Try Right Now
Python Examples
Generate a class:
:r !llmswap generate "Python class for database connection with connection pooling"
Generate error handling:
:r !llmswap generate "try-catch block for file operations in Python"
Generate API call:
:r !llmswap generate "Python function to make HTTP POST request with retry logic"
JavaScript Examples
Generate React component:
:r !llmswap generate "React functional component with useState and useEffect"
Generate Express middleware:
:r !llmswap generate "Express middleware for request logging and authentication"
Generate async function:
:r !llmswap generate "JavaScript async function to fetch data from API with error handling"
Configuration Files
Generate Docker config:
:r !llmswap generate "Dockerfile for Node.js application with multi-stage build"
Generate nginx config:
:r !llmswap generate "nginx configuration for reverse proxy with SSL"
Generate systemd service:
:r !llmswap generate "systemd service file for Python web application"
Step 6: Advanced Vim Integration
Create Vim Mappings
Add these to your .vimrc
for quick access:
" Generate code with <leader>g
nnoremap <leader>g :r !llmswap generate "
" Generate and explain with <leader>e
nnoremap <leader>e :r !llmswap generate "
Now you can just press <leader>g
and start typing what you need.
Language-Specific Generation
Force specific language output:
:r !llmswap generate "database connection" --language python
:r !llmswap generate "API endpoint" --language javascript
:r !llmswap generate "struct definition" --language rust
Save Generated Code to File
:!llmswap generate "complete web scraper" --save scraper.py
This generates code and saves it directly to a file.
Step 7: Pro Tips and Tricks
1. Be Specific in Your Requests
Instead of:
:r !llmswap generate "function"
Try:
:r !llmswap generate "Python function to parse JSON with nested error handling and logging"
2. Generate Test Code
:r !llmswap generate "pytest unit tests for user authentication function"
3. Generate Documentation
:r !llmswap generate "docstring for this function" --context "def calculate_metrics(data, threshold):"
4. Generate Command Line Scripts
:r !llmswap generate "bash script to backup PostgreSQL database with compression"
5. Generate Regular Expressions
:r !llmswap generate "regex to extract email addresses from text"
Common Use Cases
Database Operations
MongoDB queries:
:r !llmswap generate "MongoDB aggregation pipeline to group users by signup date"
SQL operations:
:r !llmswap generate "PostgreSQL query to find duplicate records in users table"
DevOps and System Administration
Docker commands:
:r !llmswap generate "docker-compose file for Python app with Redis and PostgreSQL"
Kubernetes configs:
:r !llmswap generate "Kubernetes deployment YAML for Node.js application"
Log analysis:
:r !llmswap generate "awk command to extract error patterns from nginx logs"
Web Development
API endpoints:
:r !llmswap generate "FastAPI endpoint with request validation and error handling"
Frontend components:
:r !llmswap generate "Vue.js component with props, computed properties, and methods"
Troubleshooting
Code Doesn't Appear
- Check your API key is set correctly
- Test
llmswap generate "hello world"
in terminal first - Make sure you're using
:r !
(not just:!
)
Wrong Language Generated
- Add
--language python
(or your language) to the command - Be more specific about what you want
Formatting Issues
- The generated code appears at cursor position
- Use vim's formatting commands (
=
key) to fix indentation - Position cursor at the right indentation level before generating
API Errors
- Check your API key hasn't expired
- Make sure you have credits/quota remaining
- Try switching providers:
export ANTHROPIC_API_KEY=...
Why This Changes Everything
Once you get used to this workflow, you'll realize:
- No more context switching - Stay in the zone
- Faster development - Generate boilerplate instantly
- Learn as you go - See different approaches to problems
- Multi-language support - Works with any programming language
- Provider flexibility - Use OpenAI, Claude, Gemini, or local models
Taking It Further
Multiple Providers
# Use different providers for different tasks
export OPENAI_API_KEY="..." # For general coding
export ANTHROPIC_API_KEY="..." # For complex logic
export GEMINI_API_KEY="..." # For fast responses
llmswap automatically uses the first available key it finds.
Local Development with Ollama
For completely offline development:
# Install Ollama
curl -fsSL https://ollama.com/install.sh | sh
# Pull a model
ollama pull llama2
# Use with llmswap
export OLLAMA_MODEL="llama2"
# Now llmswap generate works offline!
Conclusion
You now have AI-powered code generation built directly into vim. No more browser tabs, no more copy-paste, no more breaking your flow.
The key command to remember:
:r !llmswap generate "exactly what you need"
Start with simple examples and gradually incorporate it into your workflow. Within a week, you'll wonder how you ever coded without it.
Quick Reference
" Basic generation
:r !llmswap generate "Python function to read CSV"
" With language specification
:r !llmswap generate "API endpoint" --language javascript
" Save to file
:!llmswap generate "complete script" --save script.py
" Get explanation
:!llmswap generate "explain this regex: '^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$'"
Resources
- GitHub: https://github.com/sreenathmmenon/llmswap
- PyPI: https://pypi.org/project/llmswap/
- Documentation: Full provider setup guides in the repo
Try it now: Install llmswap and generate your first function in vim. You'll never go back to the old way.
Did this tutorial help you? Give the project a ⭐ on GitHub - every star helps with continued development!
This content originally appeared on DEV Community and was authored by Sreenath

Sreenath | Sciencx (2025-09-10T17:54:01+00:00) How to Generate Code in Vim Without Leaving Your Editor (llmswap Tutorial). Retrieved from https://www.scien.cx/2025/09/10/how-to-generate-code-in-vim-without-leaving-your-editor-llmswap-tutorial/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.