codemap_replace_text

Find and replace text in a file. Supports symbol targeting (relativePath$symbolName) to scope changes to a specific function or class, exact mode (recommended for template literals), line ranges (relativePath:10-20), and fuzzy matching.

iowritereplaceeditrefactorsymbol-targeting

Parameters

NameTypeRequiredDescription
targetstring✅ RequiredRelative path to the file, symbol reference (relativePath$symbolName) to scope replacement, or line range (relativePath:10-20)
oldStringstring❌ OptionalText to find and replace. Must be unique within the target scope. Omit when using line range mode.
newStringstring✅ RequiredReplacement text
exactboolean❌ OptionalUse exact string matching (no fuzzy logic). Recommended for template literals and code with escape sequences. Default: false (default: false)
skipValidationboolean❌ OptionalSkip syntax validation after replacement. Default: false (default: false)

Usage Examples

MCP Usage (for AI Agents like Claude)

json
{
  "name": "codemap_replace_text",
  "arguments": {
    "target": "src/config.ts",
    "oldString": "const API_URL = 'http://localhost:3000'",
    "newString": "const API_URL = 'https://api.production.com'"
  }
}

Example Output

JSON Response

json
{
  "success": true,
  "data": {
    "updated": "/home/user/project/src/config.ts",
    "replacements": 1,
    "oldLength": 44,
    "newLength": 47,
    "fuzzyMatch": true,
    "confidence": 0.92,
    "location": "lines 15-18",
    "warnings": [
      "Fuzzy match (92.0%). Minor differences detected."
    ]
  }
}
ℹ️When to Use This Tool
    Use codemap_replace_text when you need to:
  • Update configuration values (API URLs, database hosts, version numbers)
  • Refactor function or variable names across single files
  • Fix typos or update documentation strings
  • Modify import paths after reorganizing code structure
  • Update hardcoded strings or constants in specific locations
💡Common Patterns
Configuration Update Pattern
1. Read file to verify content exists
2. Replace old value with new value
3. Verify replacement count > 0
4. Optional: read file again to confirm change


Safest pattern for critical configuration changes.

Refactoring Pattern
1. Search for all files containing target string
2. For each file: replace text
3. Track successes and failures
4. Reindex to update code graph
5. Run tests to verify changes


Use for renaming functions, classes, or constants.

Exact Match for Special Characters
1. Identify content with special characters (backticks, quotes, regex chars)
2. Set exact: true to disable fuzzy matching
3. Perform replacement
4. Validate result


Critical for template literals, regex patterns, and escaped strings.
💡Pro Tips
  • Use exact: true for template literals: Backticks, dollar signs, and braces in template literals can confuse fuzzy matching. Always use exact: true when replacing code with template literals.
  • Verify before replacing: Read the file first to confirm the old string exists. This prevents silent failures where you think a replacement happened but nothing changed.
  • Use line ranges for targeted edits: When you know the line number, use file.ts:10-20 to limit replacements to that range. This prevents unintended changes elsewhere in the file.
  • Check replacement count: The response includes replacements count. If it's 0 and you expected changes, investigate - maybe the string doesn't exist or has changed.
  • Handle multiple occurrences carefully: By default, replace-text replaces all matches. If you only want to change one, use line ranges to narrow the scope.
Best Practices
  • Always set exact: true when working with code containing special characters (template literals, regex, JSON)
  • Read file before replacing to verify the old string exists - prevents blind replacements
  • After refactoring replacements, run codemap_reindex() to update symbols and references
  • Use search to find all affected files before doing batch replacements across the codebase
  • For critical changes, implement verification steps - read file after replacement to confirm
  • Track replacement counts in batch operations to detect files where replacement failed
⚠️Common Mistakes
Mistake: Not using exact: true for template literals, causing fuzzy match failures
Instead: Always set exact: true when replacing strings with backticks, ${}, or special characters

Mistake: Assuming replacement succeeded without checking the response
Instead: Check result.replacements count. Zero replacements means nothing changed - investigate why.

Mistake: Replacing globally without considering that some matches shouldn't change
Instead: Use line ranges (file.ts:10-20) to limit scope when you know the target location

Mistake: Forgetting to reindex after refactoring changes, leaving code graph stale
Instead: Call codemap_reindex() after any replacement that affects function/class names or structure

Mistake: Using fuzzy matching for JSON or structured data, causing malformed results
Instead: Set exact: true for JSON, YAML, or any structured format where whitespace matters

Mistake: Not handling "no matches found" errors in batch operations, causing script failures
Instead: Wrap replace calls in try/catch and continue processing when matches aren't found

Changelog

1 release
    • 🐛FixedLine-range targets (file.ts:10-20) now resolve correctly. A stray double-escape (\\d instead of \d) in the TargetResolver line-range regex caused ranges to fail silently before this fix.
    • 🐛FixedSymbol-scoped replaces (file.ts$symbolName) now work on multi-line files of any size. A newline-handling bug in TargetResolver.extractSymbolContent caused symbol content lookups to return undefined from the first symbol onward on any multi-line file.

Related Tools