DEV Community

Sreenath
Sreenath

Posted on

How to Generate Code in Vim Without Leaving Your Editor (llmswap Tutorial)

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:

  1. Get stuck on a function
  2. Alt-tab to ChatGPT
  3. Ask for help
  4. Copy the response
  5. Alt-tab back to vim
  6. Paste and fix formatting

You'll do this:

  1. Type :r !llmswap generate "what you need"
  2. Code appears at your cursor
  3. 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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

For Anthropic (Claude):

export ANTHROPIC_API_KEY="sk-ant-your-key-here"
Enter fullscreen mode Exit fullscreen mode

For Google (Gemini):

export GEMINI_API_KEY="your-gemini-key"
Enter fullscreen mode Exit fullscreen mode

For local/free option (Ollama):

# No API key needed, just install Ollama
export OLLAMA_MODEL="llama2"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Step 5: Your First Code Generation

Open vim and try this:

  1. Open a Python file: vim test.py
  2. Position your cursor where you want the function
  3. Type: :r !llmswap generate "function to validate email address"
  4. Press Enter
  5. 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"
Enter fullscreen mode Exit fullscreen mode

Generate error handling:

:r !llmswap generate "try-catch block for file operations in Python"
Enter fullscreen mode Exit fullscreen mode

Generate API call:

:r !llmswap generate "Python function to make HTTP POST request with retry logic"
Enter fullscreen mode Exit fullscreen mode

JavaScript Examples

Generate React component:

:r !llmswap generate "React functional component with useState and useEffect"
Enter fullscreen mode Exit fullscreen mode

Generate Express middleware:

:r !llmswap generate "Express middleware for request logging and authentication"
Enter fullscreen mode Exit fullscreen mode

Generate async function:

:r !llmswap generate "JavaScript async function to fetch data from API with error handling"
Enter fullscreen mode Exit fullscreen mode

Configuration Files

Generate Docker config:

:r !llmswap generate "Dockerfile for Node.js application with multi-stage build"
Enter fullscreen mode Exit fullscreen mode

Generate nginx config:

:r !llmswap generate "nginx configuration for reverse proxy with SSL"
Enter fullscreen mode Exit fullscreen mode

Generate systemd service:

:r !llmswap generate "systemd service file for Python web application"
Enter fullscreen mode Exit fullscreen mode

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 "
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Save Generated Code to File

:!llmswap generate "complete web scraper" --save scraper.py
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Try:

:r !llmswap generate "Python function to parse JSON with nested error handling and logging"
Enter fullscreen mode Exit fullscreen mode

2. Generate Test Code

:r !llmswap generate "pytest unit tests for user authentication function"
Enter fullscreen mode Exit fullscreen mode

3. Generate Documentation

:r !llmswap generate "docstring for this function" --context "def calculate_metrics(data, threshold):"
Enter fullscreen mode Exit fullscreen mode

4. Generate Command Line Scripts

:r !llmswap generate "bash script to backup PostgreSQL database with compression"
Enter fullscreen mode Exit fullscreen mode

5. Generate Regular Expressions

:r !llmswap generate "regex to extract email addresses from text"
Enter fullscreen mode Exit fullscreen mode

Common Use Cases

Database Operations

MongoDB queries:

:r !llmswap generate "MongoDB aggregation pipeline to group users by signup date"
Enter fullscreen mode Exit fullscreen mode

SQL operations:

:r !llmswap generate "PostgreSQL query to find duplicate records in users table"
Enter fullscreen mode Exit fullscreen mode

DevOps and System Administration

Docker commands:

:r !llmswap generate "docker-compose file for Python app with Redis and PostgreSQL"
Enter fullscreen mode Exit fullscreen mode

Kubernetes configs:

:r !llmswap generate "Kubernetes deployment YAML for Node.js application"
Enter fullscreen mode Exit fullscreen mode

Log analysis:

:r !llmswap generate "awk command to extract error patterns from nginx logs"
Enter fullscreen mode Exit fullscreen mode

Web Development

API endpoints:

:r !llmswap generate "FastAPI endpoint with request validation and error handling"
Enter fullscreen mode Exit fullscreen mode

Frontend components:

:r !llmswap generate "Vue.js component with props, computed properties, and methods"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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.-]+$'"
Enter fullscreen mode Exit fullscreen mode

Resources

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!

Top comments (0)