Code Editing with Gemini CLI

Use Gemini CLI's AI-powered capabilities to edit, refactor, and improve your code with intelligent suggestions.

Gemini CLI transforms how you interact with code by letting you describe edits in plain English and receive complete, context-aware implementations. Rather than searching Stack Overflow for the right pattern or manually updating dozens of function signatures, you can express what you want — "add error handling", "convert to TypeScript", "extract a reusable utility" — and get a working implementation back in seconds. This guide covers single-file editing, multi-file editing workflows, refactoring operations, and the best practices that separate clean AI-assisted edits from noisy, hard-to-review diffs.

Single-File Editing

Single-file editing is the simplest and fastest use case. Pipe the file into Gemini CLI with a precise instruction and redirect the output to a new file or back to the original after review.

Basic edit commands

# Add error handling to a function

gemini "Add try/catch error handling to every async function. Use descriptive error messages." < api.js > api.new.js

# Optimize for performance

gemini "Optimize this code for performance. Explain each change in a comment above it." < heavy.js > heavy.optimized.js

# Convert JavaScript to TypeScript

gemini "Convert this JavaScript file to TypeScript. Add type annotations for all parameters, return values, and variables." < utils.js > utils.ts

Redirecting to a new filename (> file.new.js) is safer than overwriting the original directly. Review the output with diff original.js original.new.js before replacing.

Safe apply workflow

Follow this three-step workflow to apply edits without risking data loss.

# Step 1 — generate the edited version

gemini "Add JSDoc comments to all exported functions" < src/helpers.js > src/helpers.new.js

# Step 2 — review the diff

diff src/helpers.js src/helpers.new.js

# Step 3 — apply if satisfied

mv src/helpers.new.js src/helpers.js

# Or revert to original easily with git

git checkout -- src/helpers.js

Code explanation

Use Gemini CLI to understand unfamiliar code before editing it. This is especially valuable when working on legacy codebases or third-party code.

gemini "Explain what this code does, step by step. Note any non-obvious logic." < complex-algorithm.js

gemini "Add inline comments explaining this algorithm at each key step." < sort.py > sort-commented.py

gemini "Identify any code smells or potential bugs in this file." < legacy.js

Multi-File Editing

Gemini CLI processes one file at a time, but combining it with shell loops and find commands lets you apply consistent transformations across an entire codebase. The key is keeping your prompts idempotent — safe to run multiple times without producing duplicate changes.

Apply the same edit to all files in a directory

#!/bin/bash

# Add error handling to all JS files in src/

for file in src/*.js; do

echo "Processing: $file"

gemini "Add error handling to all async functions. Do not change function signatures." \

< "$file" > "${file%.js}.edited.js"

sleep 1

done

# Review all diffs before applying

for f in src/*.edited.js; do diff "${f%.edited.js}.js" "$f"; done

The sleep 1 between calls prevents hitting the API rate limit when processing many files. For large projects, increase the delay or process files in batches.

Recursive edit with find

#!/bin/bash

# Convert all .js files in the project tree to TypeScript

find . -name "*.js" -not -path "*/node_modules/*" | while read -r file; do

ts_file="${file%.js}.ts"

if [[ -f "$ts_file" ]]; then

echo "Skipping $file — .ts version already exists"

continue

fi

gemini "Convert this JavaScript to TypeScript. Add strict types. Preserve all logic." < "$file" > "$ts_file"

sleep 1

done

Important cautions for multi-file edits

  • Always commit or stash your current work before running a multi-file edit script.
  • Write outputs to new files, never overwrite originals in the loop — review first.
  • Test the script on a single file before applying it to the entire codebase.
  • Run your test suite after applying edits to catch any regressions.
  • Gemini CLI does not maintain state between files — each call is independent.

Refactoring Operations

Refactoring is where Gemini CLI's AI capabilities shine most. Use it to modernize legacy patterns, extract reusable code, clean up duplication, and restructure complex logic — all while keeping the existing behaviour intact.

Modernize legacy JavaScript

gemini "Refactor this file to modern ES2022 JavaScript: use const/let, arrow functions, async/await, optional chaining, and nullish coalescing. Do not change the public API." < legacy.js > modern.js

Be explicit about the target standard (ES2020, ES2022, etc.) and any constraints such as "do not change function signatures" or "must work in Node.js 16".

Extract reusable utilities

gemini "Identify all repeated code patterns in this file and extract them into named helper functions. List each extracted function at the top of the output." < monolith.js

# Extract a specific pattern

gemini "Extract all database query logic into a separate module called db.js. Show both the updated original file and the new db.js content." < service.js

Bug fixing

gemini "Find and fix all bugs in this code. For each fix, add a comment starting with // FIX: explaining what was wrong." < buggy-script.js > fixed.js

# Diagnose before fixing

gemini "This code should return X but returns Y. Identify the root cause of the bug and explain it without fixing it yet." < broken.py

Asking Gemini CLI to explain the bug before fixing it gives you confidence that the model has understood the problem correctly — especially useful for subtle logic errors.

Code splitting and modularisation

gemini "This file has 3 responsibilities: auth, user management, and email sending. Split it into 3 separate modules. Output each module as a clearly labelled code block." < user-service.js

Review the proposed module boundaries before creating the separate files. Gemini CLI may suggest slightly different names or structures — adapt as needed for your project conventions.

Best Practices for AI-Assisted Code Editing

  • 1.Be specific in your prompts. "Add error handling" is vague. "Add try/catch to all async functions, log errors with console.error, and re-throw after logging" produces consistent, predictable output.
  • 2.Include constraints explicitly. State what should NOT change: "do not change the function signature", "do not remove existing comments", "preserve all existing tests".
  • 3.Review AI suggestions before applying. Gemini CLI produces high-quality output but is not infallible. Read the diff before overwriting your original files.
  • 4.Test code changes thoroughly. Run your test suite immediately after applying edits. If tests fail, compare the diff and identify which change caused the regression.
  • 5.Use version control to track changes. Commit before running edit scripts so you always have a clean state to compare against and revert to.
  • 6.Iterate in small steps. Apply one type of edit at a time — first add types, then add error handling, then add docs. Smaller edits are easier to review and revert.

Frequently Asked Questions

Can Gemini CLI edit multiple files at once?

Gemini CLI processes one file at a time via stdin. To edit multiple files, use a shell loop that iterates over the files and calls Gemini CLI for each one. The examples in the Multi-File Editing section above show exactly how to do this, including how to handle rate limits between calls.

How do I prevent Gemini CLI from changing parts of my code I want to keep?

Include explicit preservation instructions in your prompt: "Do not change function signatures, do not remove existing comments, and do not modify the import statements at the top of the file." The more specific you are about what should stay the same, the more predictable the output will be. For very sensitive sections, consider adding a comment like // DO NOT MODIFY and mention it in your prompt.

What file types does Gemini CLI work best with for code editing?

Gemini CLI works well with any text-based programming language. It has particularly strong performance with JavaScript, TypeScript, Python, Go, Rust, Java, and C/C++ due to the volume of these languages in its training data. It also handles HTML, CSS, SQL, YAML, and configuration files effectively. For best results with less common languages, provide extra context in your prompt about the language's conventions.

Learn More

Explore advanced code editing techniques: