Go MCP server for surgical file edits: insert, replace, move, copy, dry-run, verified replaceall.
io.github.kehsiaocuba-ux/fedit MCP Server
Go-based MCP server for surgical file editing. It provides operations for anchored insert, delete, replace, and move/copy, supporting programmatic modifications to text files through an MCP interface.
๐ ๏ธ Key Features
Anchored insert
Delete
Replace
Move
Copy
๐ Use Cases
Apply precise text edits in code or documentation
Perform repeatable file transformations in developer workflows
โก Developer Benefits
Built with Go (golang)
Designed for developer tooling and LLM-driven file editing workflows
Exposes file-editor functionality via MCP
โ ๏ธ Limitations
No tool count, installation steps, or command details are provided in the available data
A zero-dependency CLI tool for surgical file edits from the command line.
No interactive editors. No sed/awk gymnastics. Just simple, predictable operations
with built-in verification.
Built for sysadmins, DevOps engineers, and anyone who scripts config changes.
fedit demo
code
go install github.com/amalexico/fedit@latest
Why fedit?
One binary, zero dependencies โ pure Go, runs everywhere
21 language mappers โ see the structure of any file before editing
-v flag โ verify every mutation before moving on
Line-aware โ no regex surprises, no "which match did it hit?"
Stream engine โ process multi-GB files line-by-line with atomic integrity
Field extraction โ pull CSV/TSV column N without awk
Many files at once โ a comma list or glob in -file, plus cross-file copy, move and replace with -dest (since v1.9.0)
Safe โ no in-place unless you say so, never touches files you did not name
Install
Go install (recommended):
bash
go install github.com/amalexico/fedit@latest
Or download the binary from GitHub Releases and put it in your PATH.
Verify:
bash
fedit -file /etc/hostname -op show
Quick Start
bash
# See what is in a file
fedit -file config.yaml -op show
# See just lines 10-25
fedit -file config.yaml -op show -line 10 -end 25
# Find every line containing "timeout"
fedit -file config.yaml -op find -match "timeout"# See the structure of a Go file
fedit -file main.go -op map -lang go
# Replace line 42 with new content
fedit -file config.yaml -op replace -line 42 -end 42 -text "timeout: 60s" -v
# Insert a line after every occurrence of "server {"
fedit -file nginx.conf -op insertafter -match "server {" -text " include security.conf;" -v
# Move a function block before another (content-matched, atomic)
fedit -file main.go -op move -match "func OldHelper(" -end 45 -beforematch "func NewHelper(" -v
# Copy a config block and paste it 3 times at a new location
fedit -file values.yaml -op copy -line 50 -end 65 -after 200 -times 3 -v
# Extract column 2 from a TSV file (v1.4+)
fedit -file data.tsv -op fields -col 2
# Write content with literal backslashes โ no \n escape expansion (v1.6.0)
fedit -file config.txt -op writeraw -text "path=C:\\Users\\admin"# Hex-encode tricky text to sidestep shell quoting (v1.6.0)# fwencode produces the hex; fedit decodes it before writing
fedit -file config.txt -op write -texthex 706174683d2f746d70
# Overwrite a file cleanly then insert new content (v1.6.0)
fedit -file config.txt -op insert -line 0 -cleanfirst -text "# regenerated"# Get bare line numbers for scripting (v1.6.0)
fedit -file main.go -op find -match "TODO" -x 2>$null# Regex replace on a multi-GB log without loading it into memory (v1.4+)
fedit -file huge.log -op replaceall -match 'ERROR' -text 'WARN' -stream
All Operations
show โ Display file contents
bash
# Entire file
fedit -file app.conf -op show
# Lines 50-75 only
fedit -file app.conf -op show -line 50 -end 75
# Last 10 lines
fedit -file app.conf -op show -line -10:
# Lines 50 to 5th from end
fedit -file app.conf -op show -line 50 -end -5
# Lines 100-103 (relative range)
fedit -file app.conf -op show -line 100:+3
# Show from one anchor to another (no line numbers needed)
fedit -file config.go -op show -match "func Start" -endmatch "func End"
find โ Search for lines matching a substring
bash
# Find all lines containing "ERROR"
fedit -file /var/log/app.log -op find -match "ERROR"# Output includes context lines and occurrence numbers# Use -nth to target a specific match in other operations
Pro tip: Run find first to get line numbers, then use replace or delete with exact lines.
insert โ Insert content after a line number
bash
# Insert a comment after line 1
fedit -file script.sh -op insert -line 1 -text "# Added by deploy script" -v
# Insert multiple lines from a file
fedit -file config.yaml -op insert -line 10 -textfile extra-config.yaml -v
insertafter โ Insert after a matching line (RECOMMENDED)
insertbefore โ Insert before a matching line (RECOMMENDED)
bash
# Add a header before the first route definition
fedit -file routes.rb -op insertbefore -match "get '/'" -text " # === Public Routes ===" -v
# Insert a dependency before the closing bracket
fedit -file package.json -op insertbefore -match "}" -nth -1 -textfile new-deps.txt -v
replace โ Replace a line range with new content
bash
# Replace a single line
fedit -file config.ini -op replace -line 15 -end 15 -text "max_connections = 200" -v
# Replace the one line that contains a text (no end bound needed; after v1.12.0)
fedit -file config.ini -op replace -match "max_connections" -text "max_connections = 200" -v
# Replace from a matched line through line 35 (-match with -end; after v1.12.0)
fedit -file server.conf -op replace -match "[cache]" -end 35 -textfile patched-block.txt -v
# Replace lines 30-35 with content from a patch file
fedit -file server.conf -op replace -line 30 -end 35 -textfile patched-block.txt -v
# Replace a section by content anchors (no line numbers needed)
fedit -file CHANGELOG.md -op replace -match "## v1.6" -endmatch "## v1.5" -textfile new-section.txt -v
replaceall โ Global find-and-replace
bash
# Change all occurrences of old domain to new
fedit -file nginx.conf -op replaceall -match "old.example.com" -text "new.example.com" -v
# Update a version string everywhere
fedit -file Makefile -op replaceall -match "1.1.0" -text "1.2.0" -v
Every replaceall is verified by default: after the write, fedit re-reads the file from disk and prints VERIFY: PASS or VERIFY: FAIL followed by the changed lines. This covers a single file, -match-regex, -stream, -files and a file list in -file, and fedit_replaceall over MCP. -v adds a context window for every match (not printed with -stream).
Exit codes for replaceall: 0 ok, 1 the edit did not happen, 3 the file was written but verification failed or could not be done. With several files, one FAIL file makes the exit code 3 even when the others succeeded, and the MCP result is an error.
-files GLOB prints the same per-file report as a file list in -file: one OK, SKIP or FAIL line per file, then multi -file replaceall: N/M file(s) succeeded. An OK line reads OK PATH replaced on N line(s); VERIFY: PASS, a file without the text is a SKIP (No lines contain: TEXT) and is never modified. Exit code 0 if at least one file succeeded and none failed (SKIP files do not change that), 1 if none succeeded, 3 if any file is FAIL.
fields -- Extract a column from delimited files (v1.4.0)
bash
# Extract column 2 from a tab-separated file (default delimiter: tab)
fedit -file data.tsv -op fields -col 2
# Extract the third field from a CSV
fedit -file report.csv -op fields -col 3 -delim ","# Extract usernames from /etc/passwd (colon-delimited)
fedit -file /etc/passwd -op fields -col 1 -delim ":"
Output goes to stdout for piping. Lines shorter than -col are skipped silently.
Always streaming -- no memory limit regardless of file size.
-stream -- Large-file streaming mode (v1.4.0)
Add -stream to replaceall or find to process files line-by-line without
loading them into memory. 10 MB per-line buffer handles JSON blobs and minified files.
Atomic integrity: writes to a temp file then renames -- original is untouched on interruption.
bash
# Replace a pattern in a multi-GB log file
fedit -file server.log -op replaceall -match "10.0.0.1" -text "10.0.0.2" -stream
# Regex replace in a huge file with capture groups
fedit -file big.csv -op replaceall -match-regex 'id_(\d+)' -text 'ID_$1' -stream
# Streaming find -- grep-style output to stdout
fedit -file huge.log -op find -match "FATAL" -stream
Supported with -stream: replaceall (literal and regex), find.
Not supported: move, copy, map (these require full file structure in memory).
writeraw โ Write without escape expansion
bash
# Write a Windows path without double-escaping backslashes
fedit -file config.ini -op writeraw -text "basedir=C:\\Program Files\\App"# Write content from a file as-is
fedit -file output.txt -op writeraw -textfile template.txt
Unlike write, writeraw treats \n as two characters (backslash + n), not a newline.
writelines โ Write lines interactively from stdin
bash
fedit -file notes.txt -op writelines
# Type lines at the > prompt, Ctrl+Z (Windows) or Ctrl+D (Unix) to finish
-texthex โ Hex-encoded input (v1.6.0)
Encode text to hex first (e.g. with fwencode), then pass the hex string as -text.
Eliminates all shell-quoting issues with special characters.
bash
# Decode hex string and write โ no quoting gymnastics needed
fedit -file deploy.sh -op write -texthex 23212f62696e2f62617368
Same idea as -texthex, but for the search anchors. PowerShell mangles a double quote
inside -match before fedit sees it, so case "replace": silently becomes case replace:
and matches nothing. Pass the anchor as hex instead; fedit decodes it into -match
(or -endmatch) once, so every op that takes an anchor works unchanged.
bash
# Find a line containing double quotes (hex of: case "replace":)
fedit -file main.go -op find -matchhex 6361736520227265706c616365223a
Multiple files -- comma list or glob (show/find/map since v1.8.1, mutation and MCP since v1.9.0, -sourcefile and -sourceblock with a list since v1.11.0)
-file accepts a comma-separated list, a glob, or both. A real file with that exact name wins over glob expansion.
Read-only ops (show, find, map) print a ==> path <== header per file:
bash
# Find TODO in every Go file in the current folder
fedit -file '*.go' -op find -match 'TODO'# Map two files at once
fedit -file main.go,mcp.go -op map -lang go
find skips files with no hits (grep-style) and exits 1 only if nothing matched in any file.
map skips unrecognized extensions with a SKIP line.
A summary line reports how many files had results.
Mutating ops (replaceall, insertafter, insertbefore, delete, replace, write) run on each file on its own:
bash
# Replace in every matching file
fedit -file '*.conf' -op replaceall -match 'old.example.com' -text 'new.example.com'# Insert after the first match in each file
fedit -file a.yaml,b.yaml -op insertafter -match 'servers:' -text ' - new'# Delete from a start line through an end line in each file (-endmatch is inclusive)
fedit -file '*.md' -op delete -match '<!-- start -->' -endmatch '<!-- end -->'
A problem in one file (no match, unreadable, read-only, write failed) is reported as SKIP and never stops the batch. A skipped file is never modified.
The report lists OK, SKIP or FAIL per file, then N/M file(s) succeeded. A FAIL is a replaceall file that was written but did not pass the on-disk verification. Exit code 0 if at least one file succeeded and none failed, 1 if none succeeded, 3 if any file is FAIL (FAIL wins).
Only -match (plus -endmatch for delete and replace), -nth and -text/-textfile/-texthex are accepted, plus -sourcefile/-sourceblock/-lang on insertafter and insertbefore (since v1.11.0). -match-regex works with replaceall, and write needs no -match and writes the same content to every file. -block, -line, -end, -cleanfirst, -stream and -files are rejected (use -endmatch for a range), and so are move and copy, all before any file is read.
MCP: fedit_replaceall, fedit_insertafter, fedit_insertbefore, fedit_delete and fedit_replace take a comma list or glob in file, with the same rules and a per-file report; block, line, end, stream and files are rejected. fedit_write always treats file as one path. fedit_show, fedit_find and fedit_map also take a list.
Cross-file copy, move and replace -- -dest (v1.9.0, MCP since v1.10.0)
-dest copies or moves a block from -file into one or more other files. It takes a comma-separated list of existing files (no globs). The source is chosen the usual way: -line/-end, -match/-endmatch, or -block with -lang. The destination anchor is resolved separately inside each destination file, using one of -after, -before, -aftermatch, -beforematch, -afterblock or -beforeblock (the block anchors need -lang).
bash
# Copy a function into two other files, right after a named block in each
fedit -file a.go -op copy -block Helper -lang go -dest b.go,c.go -afterblock Init
# Move a config section into two files, before a marker line in each
fedit -file base.conf -op move -match '[cache]' -endmatch '[/cache]' -dest x.conf,y.conf -beforematch '[logging]'# Paste 2 copies in each destination
fedit -file src.txt -op copy -line 5:+3 -dest a.txt,b.txt -aftermatch ANCHOR -times 2
Each destination is handled on its own. A problem in one (missing file, anchor not found, read-only, write failed) is reported as SKIP and that file is never modified. The batch never aborts.
move writes all the destinations first. The source text is removed only if at least one destination write succeeded. If every destination fails, the source is left intact, so text is never lost.
The report lists OK or SKIP per destination, then N/M file(s) succeeded. Exit code 0 if at least one destination succeeded, 1 if none did.
A destination that is the source file itself is a SKIP, and a file listed twice is used once.
copy and move take -dest with an anchor flag, and replace takes -dest with -destblock (below). It is rejected with any other op, and with -match-regex, -cleanfirst, -stream or -files, before any file is read. It does not combine with a multi -file list: -file must be the single source file.
Cross-file transfer moves text, not dependencies. A Go function that calls fmt.Println lands textually perfect in a file with no fmt import, and that file will not compile until you add the import. Since v1.11.0, copy, move and replace with -dest add an advisory note when a Go destination lacks a standard library import that the transferred lines use (advisory only: results and exit codes are unchanged).
MCP: fedit_copy, fedit_move and fedit_replace take a dest parameter (a comma list of files) with the same anchors, and destblock for replace; same rules and a per-destination report; file must be a single path. fedit_insertafter and fedit_insertbefore take sourcefile and sourceblock (with lang); there file may also be a comma list or glob.
Replace a block in other files -- replace -dest with -destblock
replace -dest overwrites a named block in each destination with the source block or range from -file. -destblock names the block to overwrite and is required. The source is chosen as for copy and move, and -lang lets block names resolve.
bash
# Overwrite Helper in two files with the Helper from a.go
fedit -file a.go -op replace -block Helper -lang go -dest b.go,c.go -destblock Helper -v
A destination that does not have that block is a SKIP, never an insert. Each destination is handled on its own, like copy and move.
-destblock is only accepted with replace -dest.
Insert a block from another file -- -sourcefile and -sourceblock
insertafter and insertbefore can take their content from a named block in another file. -file stays the file being edited and the anchor is chosen as usual.
bash
# Insert Helper from a.go into b.go, after the line matching '// helpers'
fedit -file b.go -op insertafter -match '// helpers' -sourcefile a.go -sourceblock Helper -lang go -v
-sourcefile and -sourceblock must be used together and need -lang. They cannot be combined with -text, -textfile or -texthex.
-file may be a comma list or glob (since v1.11.0). The block is read once from -sourcefile and inserted into every file at that file's own -match, with a per-file report. A file without the match is a SKIP and is never modified. This is not a -dest fan-out: each target is edited at its own -match.
Since v1.11.0, when the source and the destination are both Go files and the inserted block uses a standard library package the destination does not import, a hint is printed (stderr on the CLI, the OK message on MCP; advisory only: the insert is still done and the exit code is unchanged). With a file list the hint is added to that file's report line.
The MCP tools take sourcefile and sourceblock as parameters on fedit_insertafter and fedit_insertbefore (with lang).
guided -- Natural-order entry point (CLI, since v1.11.0)
fedit guided takes the source, the verb and the destination in plain order and turns them into the explicit -op command, which it prints to stderr before running it. It is a CLI shortcut only, with no MCP tool, by design: it exists to guide a person typing at a terminal (it can ask which block you mean when a name is ambiguous), and an MCP client already passes the same information as explicit parameters. The engine and the explicit flags are unchanged.
The source is a named block (the language comes from the file extension) or "line N-M".
Several destinations: quote them as one comma list ("b.go,c.go"), because PowerShell would otherwise split them.
Each destination is handled on its own. A missing file is created, and a missing anchor (or no position at all) appends at the end, with a note. A move runs its copies first and the move last, so the source is erased only after a write succeeded.
Block names are matched by substring, as everywhere else. If a name matches several blocks, a single exact match wins (a note says so); otherwise you get a numbered choice in a terminal, or the list of candidates and exit code 2 when there is no terminal. The chosen block is then addressed by line numbers.
replace overwrites TARGET (default: the same name as the source) in each destination and skips a destination that does not have it.
silent runs the plan with -quiet: no echo, no notes, and no engine report when every file succeeded (skips and errors still print).
report-only runs the plan without the verify output and without the echo line, but keeps the notes and the engine's own summary. Both modifiers go last and work with every verb.
dry goes last, after silent or report-only when you use one. It adds -dry to every step, so each step prints its diff and writes nothing, and the parent log record carries dry=true. A destination file that does not exist is not created: the plan says guided: dry-run: would create FILE and put the block into it instead (for a move it adds that the block would then be removed from the source), and no diff is shown for that file. The bare prompt accepts dry, silent dry and report-only dry. A target block literally named dry cannot be the last word.
Bare fedit guided (no other arguments) asks the questions one at a time: the operation, the source file and block, the destination, the position, then the modifier. Operation and position can be answered by name or by number, and a wrong choice is asked again (three tries). The prompts go to stderr and the answers are read from stdin, one per line, so piped input works. If the input ends before the last answer, nothing is changed.
-dry -- Preview a change without writing it (since v1.12.0)
-dry turns an operation that changes files into a preview. Nothing is written, truncated or created. fedit prints a unified diff (three lines of context, and /dev/null for a file that does not exist yet) to stdout, and the report on stderr ends with dry-run: applied=false (no file was changed). Exit codes are the same as for a real run, so a script can try a change before it makes it.
bash
# Preview, then apply
fedit -file app.conf -op replaceall -match old.example.com -text new.example.com -dry
fedit -file app.conf -op replaceall -match old.example.com -text new.example.com
# Preview a multi-file run: one diff per file, and the total reads would succeed
fedit -file "*.conf" -op replaceall -match old.example.com -text new.example.com -dry
# Preview a cross-file copy
fedit -file a.go -op copy -block Helper -lang go -dest b.go,c.go -afterblock Init -dry
The verify step is skipped, because nothing was written: replaceall and -v print VERIFY: SKIP (dry-run) and the exit code is 0. There is no VERIFY window and no STATS block; move and copy keep their own STATS block, which is computed from the plan.
Multi-file and -dest runs print one diff per file. The batch total reads N/M file(s) would succeed, each file line is worded as a preview (would replace on 1 line(s), would insert 1 line(s) at match on line 3, block "X" would be replaced with N line(s)) and a replaceall line ends with VERIFY: SKIP (dry-run), and a -dest move reports move: would remove lines N-M from SRC instead of removing them.
-stream with -dry reads the file, runs the replacement and prints counts only: no diff, no temporary file, nothing written.
On the command line the summary line of a single-file run is worded as a preview too, with the wording the MCP tools use: Would insert 1 line(s) after line 1 (4 total after), Would delete lines 2-2 (2 total after), Would write 1 line(s) to FILE, Would regex-replace on 1 line(s) (3 total).
-cleanfirst with -dry truncates nothing; the diff shows the old content removed and the new content added.
A run that would fail still fails: no match or a missing block gives the usual error and exit code, with no diff.
-dry works with -outputresult. It cannot be combined with fedit -config or fedit -log merge (usage error, exit 1), and -dry=false is refused too.
A dry run is logged like any run: its end record carries dry=true (see "Audit log" below). In fedit guided add the word dry at the end; over MCP pass dry_run (see "MCP Server Mode" below).
Limits: a guided dry run shows no diff for a destination file that does not exist yet, and a guided target block literally named dry cannot be the last word.
-cleanfirst โ Truncate before writing (v1.6.0)
bash
# Clear the file then insert fresh content at line 0
fedit -file output.txt -op insert -line 0 -cleanfirst -text "# regenerated"
-x โ Machine-readable output (v1.6.0)
bash
# Get bare line numbers from find (stdout only, no context noise)
fedit -file main.go -op find -match "TODO" -x 2>$null# Extract CSV column with no stats footer
fedit -file data.csv -op fields -col 2 -delim "," -x
v1.5.0: HCL/Terraform block mapper (-lang hcl)
Move, copy, and refactor Terraform blocks by name โ no line numbers needed.
Accepts -lang hcl, -lang tf, or -lang terraform (all equivalent).
Nested blocks (e.g. ingress {} inside a resource) are correctly ignored โ
only top-level blocks are matched.
v1.5.0: Nix block mapper (-lang nix)
Move and copy top-level attribute bindings in Nix expression files.
Handles attribute sets (name = { }), lists (name = [ ]), and
dotted attributes (programs.git = { }).
bash
# Reorder home-manager program configs
fedit -file home.nix -op move -block "programs.git" \
-beforeblock "programs.ssh" -lang nix -v
# Copy a service config as a scaffold
fedit -file configuration.nix -op copy -block "services.nginx" \
-after 50 -lang nix -v
move โ Move a line range to a new position
bash
# Move lines 100-120 to after line 200 (explicit range)
fedit -file server.go -op move -line 100 -end 120 -after 200 -v
# Move a function block to before another function (content-matched)
fedit -file routes.go -op move -match "func OldHelper(" -end 45 -beforematch "func NewHelper(" -v
# Swap two nginx server blocks
fedit -file nginx.conf -op move -match "server {" -endmatch "# end server 1" -aftermatch "# end server 2" -v
# Cut once, scaffold 3 copies at destination
fedit -file main.go -op move -line 5 -end 12 -after 100 -times 3 -v
Rules:
Destination may not overlap the source range โ fedit reports a precise error with line numbers.
-times N: cut once, paste N times. Net delta = blockSize ร (Nโ1). Default times=1 = zero delta.
To move the block into other files instead, use -dest (see Cross-file copy, move and replace above).
copy โ Copy a line range to a new position
bash
# Copy a config block to after a section header
fedit -file values.yaml -op copy -line 50 -end 65 -aftermatch "# staging" -v
# Duplicate a test fixture 10 times for parameterised tests
fedit -file fixtures_test.go -op copy -match "func TestCase(" -end 30 -after 200 -times 10 -v
# Reorder Python classes (copy source before target; overlap is allowed)
fedit -file processor.py -op copy -match "class ModuleProcessor_15" -endmatch "class ModuleProcessor_16" -beforematch "class ModuleProcessor_13" -v
Rules:
Snapshot semantics: source range is read once before any writes. All N copies are identical clones of the original, even when destination overlaps source.
To copy the block into other files instead, use -dest (see Cross-file copy, move and replace above).
Net delta = blockSize ร times.
delete โ Remove lines
bash
# Delete a single line
fedit -file hosts -op delete -line 12 -end 12 -v
# Delete the one line that contains a text (no end bound needed; after v1.12.0)
fedit -file hosts -op delete -match "127.0.0.1 old-host" -v
# Delete from a matched line through line 55 (-match with -end; after v1.12.0)
fedit -file config.yaml -op delete -match "legacy:" -end 55 -v
# Delete a block (lines 40-55)
fedit -file config.yaml -op delete -line 40 -end 55 -v
write โ Create or overwrite a file
bash
# Create a new file
fedit -file /tmp/note.txt -op write -text "Deployment started" -v
# Write multi-line content from another file
fedit -file /etc/motd -op write -textfile new-motd.txt -v
map โ Structural overview of a file
bash
# Map a Go file โ see all functions, types, imports
fedit -file main.go -op map -lang go
# Map a Dockerfile โ see stages and instructions
fedit -file Dockerfile -op map -lang dockerfile
# Map a Makefile โ see variables, targets, duplicates
fedit -file Makefile -op map -lang makefile
Supported Map Languages (21)
Language
Key Structures Detected
go
package, imports, types, interfaces, functions
python
imports, classes, functions, decorators
javascript
imports, exports, classes, functions, arrows
typescript
(same as javascript)
css
imports, custom properties, selectors, @media, @keyframes; duplicate selectors are counted per container block, so the same selector in different @media or @keyframes blocks is not a duplicate (since v1.11.0)
headings (fenced code is skipped, so shell comments are not listed as headings), code blocks, links; duplicate headings (same text, level and parent, case-insensitive) are flagged (since v1.11.0)
FROM stages, all instructions; duplicate stage names (case-insensitive) and CMD, ENTRYPOINT or HEALTHCHECK repeated in one stage are flagged (since v1.11.0)
makefile
includes, variables, .PHONY, targets
json
root type, top-level keys, nesting depth, duplicate keys within one object, malformed-file error
top-level blocks by kind (terraform, provider, variable, locals, data, resource, module, output, moved, import, check), duplicate blocks; terraform and tf are aliases (since v1.11.0)
nix
top-level attribute blocks and simple attributes, duplicate attribute paths; unindented lines only (since v1.11.0)
Most mappers detect duplicates (functions, tables, keys, header columns, blocks, attributes, selectors, headings, Dockerfile stages) and flag them with warnings.
Flags Reference
Flag
Description
-file PATH
Target file (required); comma list or glob for show/find/map and replaceall/insertafter/insertbefore/delete/replace/write
-dest PATH,PATH
Cross-file copy, move and replace: comma list of destination files, each needs one anchor flag (-after, -before, -aftermatch, -beforematch, -afterblock, -beforeblock), or -destblock for replace (v1.9.0, MCP since v1.10.0)
-op OP
Operation to perform (required)
-line N
Starting line number (1-based); N:+M=range, -N=from end, -N:=last N lines, :=EOF
-end N
Ending line (for ranges); -N counts from end of file
-text "s"
Inline text content
-textfile F
Read content from a file
-match "s"
Substring to search for
-nth N
Which occurrence (default 1, -1 = last)
-lang LANG
Language for map and for -block operations
-v
Verify: show affected lines after edit (replaceall always verifies the written file; -v adds a window for every hit)
-endmatch "s"
Content-anchor end of range, plain text like -match and not a regex (show/replace/delete/move/copy). With replace and delete the end bound is optional: -match alone acts on the single matched line and -match with -end N runs through line N (after v1.12.0); show, move and copy still need -end or -endmatch
-quiet
Suppress output on success, including the per-file report of multi-file and -dest runs (skips and errors still print); exit code signals result (since v1.11.0)
-outputresult FILE
Write the operation report to FILE (UTF-8, no BOM) and print one summary line on the terminal. FILE may not be any file being edited (-file, -files, -dest) and its directory must exist. On a non-zero exit nothing is written to FILE: the whole report goes to stderr with the same exit code
-outappend
With -outputresult: append to FILE instead of overwriting it
-dry
Dry run: print a unified diff of what the operation would change and write nothing; the report ends with applied=false (since v1.12.0); see "-dry" above
Hex-encoded -match and -endmatch anchors, for anchors that contain double quotes (v1.8.1)
-match-regex P
replaceall: regex with capture groups ($1 $2)
-files GLOB
replaceall across every file matching a glob (other ops take a comma list or glob in -file); the report is the per-file list described under replaceall
-stream
Large-file mode for replaceall and find (v1.4.0)
-cleanfirst
Truncate the file before insert or write (v1.6.0)
-raw
show: bare content, no line numbers or footer, for piping to fwencode (v1.7.0)
-x
find: bare line numbers; fields: no stats footer (v1.6.0)
-col N, -delim CHAR
fields: column number (1-based) and field delimiter (default tab) (v1.4.0)
-extract SPEC, -get REGEX, -wdelim CHAR
find: sub-line extraction (word and character slices), regex pre-filter and word delimiter (v1.7.0; over MCP an invalid get regex is an error, since v1.11.0)
-block NAME
Target a named function, class or resource instead of line numbers (needs -lang); block ends skip strings, multi-line strings and comments, see "How block ends are found" below (since v1.11.0)
-after N, -before N
move/copy destination: after or before line N (0 = beginning of file)
-aftermatch TEXT, -beforematch TEXT
move/copy destination: after or before the first line that contains TEXT
-afterblock NAME, -beforeblock NAME
move/copy destination: after or before a named block (needs -lang); with insertafter and insertbefore they are rejected with an error that points to -block (since v1.11.0)
-times N
move/copy: paste N times (move cuts once)
-destblock NAME
replace -dest only: the block to overwrite in each destination (required); a destination without it is skipped (v1.9.0, MCP since v1.10.0)
-sourcefile F, -sourceblock NAME
insertafter/insertbefore: take the content from a named block of another file (needs -lang; not with -text, -textfile or -texthex). -file may be a list, and a Go import hint can appear (both since v1.11.0); the flags themselves date from v1.9.0, MCP since v1.10.0
How block ends are found (since v1.11.0)
With -block NAME (and -sourceblock, -destblock, -beforeblock, -afterblock) the range of a block comes from a scanner for the language. Python and Ruby blocks do not use brace counting and are not affected. Go, JS and TS, Rust, Java, C#, PHP, HCL and Nix count braces (and brackets in Nix), and the count ignores:
Strings, including multi-line ones: backtick strings (Go raw strings, JS template literals), C# verbatim (@"...") and raw (""") strings, Java text blocks, Rust raw strings (r"...", r#"..."#), HCL heredocs (<<EOT, <<-EOT), PHP heredocs and nowdocs (<<<EOT, <<<'EOT', with an indented closing marker allowed) and Nix indented strings (two single quotes). In a Java text block a backslash escapes the next character, so an escaped \""" does not end the block.
Rust char literals, lifetimes and loop labels.
Comments: // and /* */ (nested in Rust), and # in PHP, HCL and Nix (in PHP, #[ starts an attribute and is not a comment). Nix has no // comment, because // is its update operator.
JS and TS regular expression literals are recognised by a heuristic (after v1.12.0), so a regex literal that contains /* or braces no longer opens a comment or counts braces. A slash after ), ], an identifier or a number is taken as division, so a regex directly after ) (if (x) /re/.test(y)) is not recognised, and a regex must close on the same line. Other languages are not affected.
Known gaps: the regex limits above, and a block comment that opens outside any block. For a block like that, check the range with show first and fall back to -line.
Exit codes
Code
Meaning
0
ok
1
nothing done, refused or usage error
2
guided plan error or panic
3
verification failed (or the -outputresult file could not be written)
4
strict logging refused the run
5
strict end record failed
Since v1.12.0 a script that treats every non-zero exit alike may see 3, 4 or 5. The sections for multi-file runs, -dest, replaceall, -dry and the audit log give the details for each feature.
Audit log (since v1.12.0, off by default)
fedit can write one record per operation to an audit log: who ran what, on which files, with what result. It is off unless you turn it on, and while it is off nothing in a run changes. It covers command-line runs, guided runs and the MCP server.
Modes (-log-mode or FEDIT_LOG_MODE):
off (default): nothing is written.
permissive: the operation always runs. If the log cannot be written, the records are saved in a spool folder under the fedit user folder, The action was not logged is printed to stderr (over MCP it is also returned in the tool result as an extra text item), and the next logged run (or fedit -log merge) appends them to the log with late=true.
strict: if the begin record cannot be written, the run is refused before anything changes (exit 4). If the operation succeeded but the end record cannot be written, the exit code is 5. A run that already failed keeps its own exit code.
Settings are read in this order: flag, then environment variable, then the settings file (see "Settings file" below), then default. An invalid value is an error (exit 1, nothing edited) even when logging is off.
Flag
Environment
Meaning
-log-mode M
FEDIT_LOG_MODE
off (default), permissive or strict
-log-file FILE
FEDIT_LOG_FILE
Log file; %VAR% and ~ are expanded. Default %LOCALAPPDATA%\fedit\fedit.log (the user config folder when that variable is not set)
-log-max-mb N
FEDIT_LOG_MAX_MB
Rotate the log at N MB (default 10, 0 = never). A rotated file is named <log>.<UTC timestamp>
-log-content on|off
FEDIT_LOG_CONTENT
on: log -text values verbatim. off (default): length and SHA-256 only
-log-level L
FEDIT_LOG_LEVEL
all (default), warning or error: which severities are written. Strict always writes all
-log-scope S
FEDIT_LOG_SCOPE
all (default: every operation, reads included) or writes (only operations that can change a file)
Every record is one line with a UTC timestamp, a level ([INFO] for exit 0, [WARNING] for 1, [ERROR] otherwise) and key=value pairs. The begin and end records of a run share the same id.
Begin record: op, source (cli, guided or mcp), user (with the domain on Windows), host, pid, cwd, then, when given, file, files and dest as absolute paths (a glob keeps its pattern), text_len and text_sha256 (or text with -log-content on; -texthex is hashed after decoding) and textfile (the path), then textfile_len and textfile_sha256 of that file when it can be read (the content itself is never logged, not even with -log-content on; since v1.12.0). Over MCP a call that uses output_file also logs it (an absolute path, plus output_append=true when it is set; since v1.12.0), and every call carries client and client_version. In permissive mode a not logged notice (the audit log could not be written, so the record went to the spool) is also returned in the MCP tool result as an extra text item after the result, besides the server stderr (since v1.12.0).
End record: phase=end, exit and ms, plus the result when the operation reports one: lines_changed for every plain write operation on a single file (lines inserted, deleted, replaced or written; for move and copy the block size times the number of copies; none for a dry run or a failed call) and for replaceall, which also gets replacements (occurrences; lines_changed counts lines, and both are noted the same way over MCP) and verify (PASS or FAIL), and for multi-file runs files_total, files_ok, files_skip, files_fail and a per-file results list. A write on a single file also gets sha256_before and sha256_after.
Dry run: a run with -dry (also guided dry and MCP dry_run) is logged like any other run, and its end record carries dry=true. For an existing file sha256_after is the same as sha256_before, a dry multi-file run logs verify=none, and a dry run notes no replacements and no lines_changed.
A usage error (no -op, unknown -op) is not an operation and is not logged. -outputresult never receives log records.
fedit -log merge appends the spooled records to the main log now, in any mode, using the FEDIT_LOG_* environment and the settings file. It prints Merged N spooled record(s) into FILE or No spooled records to merge on stderr, and exits 1 on a usage error, an invalid setting or a merge that stops. It is not logged itself.
guided: a plain one-step command is logged as one run with source=guided. A run with several steps or a file to create has a parent record (op=guided, steps, create) and one child run per step, each with parent=<id of the parent>. Strict refuses before the parent creates any file.
MCP: every tool call is one logged run with source=mcp. The settings come from the FEDIT_LOG_* environment of the server process and from the settings file (there are no flags), so set the environment variables in the env block of your MCP client config; FEDIT_CONFIG there points the server at another settings file. An error result is logged as exit 1 and a failed verification as exit 3. In strict mode a call whose begin record cannot be written returns an error result and changes nothing; a call that succeeded but whose end record cannot be written returns an error result that says the operation completed.
Limits: multi-file runs have per-file results but no per-file hashes; a guided parent exits 1 when any step fails.
Settings file (since v1.12.0)
The logging settings can also be kept in a settings file, so you do not need environment variables on every machine or in every MCP client config. The file is optional: without it nothing changes.
Location: fedit\fedit.ini in the user config folder (on Windows %APPDATA%\fedit\fedit.ini, on Linux ~/.config/fedit/fedit.ini). FEDIT_CONFIG names another file; ~ and %VAR% are expanded and a relative path is made absolute.
Format: one key = value per line. Blank lines and lines that start with # or ; are ignored. Keys are not case-sensitive, there are no sections, and a UTF-8 byte order mark (Notepad adds one) is ignored. If a key appears twice, the last one wins.
Keys: log_mode, log_file, log_max_mb, log_content, log_level and log_scope, with the same values as the matching flags in the table above.
Order: flag, then environment variable, then settings file, then default.
Errors: a missing file is not an error. A file that cannot be read, a line that is not key = value and an invalid value are errors that name the file and the line (exit 1, before anything is edited), even when logging is off. An unknown key is a warning on stderr and is ignored.
-noconfig (command line only) ignores the file for that run. guided runs and the MCP server always read it. fedit -log merge -noconfig skips it for that merge; without -noconfig a broken file stops fedit -log merge, and the message names -noconfig (since v1.12.0).
fedit -config reads and changes the file without opening it by hand: path prints its location, show lists every key with its effective value and where it comes from (environment, ini or default), get KEY prints one effective value (exit 1 for an unknown key), and set KEY VALUE and unset KEY check the key and the value, then write the file atomically (the folder is created when needed; comments, blank lines and line endings are kept). set and unset are logged like any write operation, with config_key and config_value in the begin record, and are not available over MCP. A broken settings file stops show, get, set and unset (exit 1, naming the line); path still works.
# Set an alias
$f = "C:\tools\fedit.exe"
# Find all TODO comments in Go code
& $f -file main.go -op find -match "TODO"
# Replace a config value
& $f -file config.toml -op replaceall -match 'debug = true' -text 'debug = false' -v
# Map a file to understand its structure
& $f -file main.go -op map -lang go
Tips
Always use -v on mutations โ it costs nothing and saves you from blind edits
Use find before replace โ get the exact line numbers first
Prefer insertafter/insertbefore over insert โ matching is more resilient than hardcoded line numbers
Use -nth -1 to target the last occurrence of a match
Use -textfile for multi-line inserts โ avoids shell quoting headaches
map before editing unfamiliar files โ see the structure first
LLM Benchmark
How well do current LLMs use fedit vs. rewriting whole files?
We tested Claude (Sonnet 4.6), ChatGPT (GPT-4o), and Gemini (2.5 Pro) on
7 realistic editing tasks across files of 565-1206 lines. Each model was tested
twice per task: once asked to output the whole file ("raw"), once asked to
output fedit commands only ("fedit").
1. ChatGPT cannot output large files reliably.
6 of 7 raw tests truncated. The most striking failure was T6, where it inserted
the literal placeholder line [... TRUNCATED FOR BREVITY ...] into otherwise
valid HTML โ a uniquely dangerous failure mode where output looks structurally
complete but contains placeholder strings. T7 truncated 1206 lines down to 166.
2. LLMs hallucinate line numbers โ and it gets worse with chain length.
Gemini's line-number errors grew across the suite: off by 36-56 lines on T2
(single replace), 45 lines on T3, then 73 lines on T5 (3-step chain).
ChatGPT showed similar drift on T5. Claude was the only model that produced
runnable line-numbered commands consistently.
3. Content-matching ops are immune to the hallucination class.
Gemini failed every fedit test that required line numbers (T1, T2, T3, T5, T6,
T7), but PASSED T4 โ which used replaceall with a content match. Same model,
same task complexity, dramatically different reliability. The bottleneck is
counting, not understanding.
4. insertafter on a function declaration matches the OPENING line.
Models repeatedly tried insertafter -match "func MyFunc()" to insert content
AFTER the function ended. This is correct fedit behavior (it inserts after the
matched line) but inserts the new code INSIDE the function body. Workaround:
insertbefore the NEXT structural element. Confirmed in T1 and T7.
5. Even Claude flubs line-number direction.
T6: Claude used insert -line 30 to add a banner before the 3rd button at line
30. But insert -line N adds content AFTER line N. The correct command was
insertbefore -match "View Details" -nth 3. Even the strongest model gets
direction wrong about 1 in 6 single-step ops when reaching for line numbers.
6. -match is single-line only โ and that's a feature.
ChatGPT (T3 fedit) tried to pass a multi-line CSS block as -match with literal
\n escapes. fedit doesn't interpret escapes in -match and matches only
single lines. This kept the operation safe (zero matches โ no edit) rather than
allowing a fragile multi-line pattern that could easily mismatch.
7. Markdown rendering is a hidden adversary.
ChatGPT and Gemini outputs lost __name__ โ name, __init__ โ **init**,
and stripped CSS/Python indentation when rendered in chat UIs. The underlying
files (when downloaded directly) were correct. This affects copy-paste workflows
but not API integrations. For best results, use the model's "copy code"
button or download links โ never select-and-copy from rendered output.
8. Three different models converged on the same one-liner for T4.
Claude, ChatGPT, and Gemini all independently produced
fedit -op replaceall -match "FetchUser" -text "GetAccount".
When the right tool is obvious, models reach for it. fedit's design surface
makes the right tool obvious for content-driven edits.
Recommendations for LLM-driven workflows
Based on these results, prefer content-matching operations over line-number
operations when generating fedit commands from an LLM:
Use insertbefore -match "next anchor" instead of insert -line N
Use replaceall -match "old" -text "new" instead of replace -line N -end M
Use find -match and show to confirm line numbers before any line-numbered op
Reserve line-numbered ops for cases where an MCP-connected LLM has just run
fedit_find or fedit_show and has verified the line in context
Use -block / -lang to target named functions and structs without any line numbers
For best results, give the LLM an MCP connection to fedit (see
MCP Server Mode) so it can fedit_find and fedit_show
before mutating. This eliminates the line-number hallucination class entirely
and was the path Claude consistently took when it had recon available.
Methodology
Each test run in a fresh chat with the original file uploaded
Prompts identical across models; only "raw" vs "fedit" framing differed
Output saved verbatim, then diffed against ground truth via Compare-Object
Ground truth verified by running fedit commands locally and re-reading output
All 7 raw outputs that PASSED Compare-Object empty (byte-identical to ground
truth): Claude T2, T3, T4, T5, T6, T7 + Gemini T5, T6, T7
PASS* indicates byte-difference from indentation-stripping in chat UI render,
with content structurally correct (verified by re-running fedit ops on the
saved file)
Test corpus
7 synthetic files (565-1206 lines) covering Go, YAML, CSS, Python, and HTML.
Full results, ground truth files, test prompts and the 7-file corpus:
amalexhandler.com/fedit#benchmark.
MCP Server Mode
fedit includes a built-in Model Context Protocol (MCP) server, so AI coding assistants can use fedit as a tool for precise file edits.
bash
fedit mcp
This starts a JSON-RPC 2.0 server on stdin/stdout. The server exposes all 14 editing operations as MCP tools:
Tool
Description
fedit_show
Display file contents (full or line range); comma list or glob in file
fedit_insert
Insert content after a line number
fedit_delete
Delete one or more lines; comma list or glob in file with match
fedit_replace
Replace a line range or named block; comma list or glob in file with match; dest + destblock overwrite a named block in other files
fedit_replaceall
Global find-and-replace; match_regex for regex and textfile for replacement text (both since v1.11.0); comma list or glob in file; the written file is re-read and verified, and a VERIFY: FAIL comes back as an error result
fedit_write
Create or overwrite a file
fedit_writeraw
Create or overwrite a file with no escape expansion (backslashes literal)
fedit_map
Structural overview (21 languages; lang is detected from the extension when omitted); comma list or glob in file
fedit_find
Find lines matching a substring; comma list or glob in file
fedit_insertafter
Insert after a matching line or named block; sourcefile + sourceblock + lang insert a block from another file (Go import hint since v1.11.0); comma list or glob in file
fedit_insertbefore
Insert before a matching line or named block; sourcefile + sourceblock + lang insert a block from another file (Go import hint since v1.11.0); comma list or glob in file
fedit_move
Move a line range to a new position; destination-overlap rejected; dest moves the block into other files
fedit_copy
Copy a line range; snapshot semantics, overlap allowed, -times N; dest copies it into other files
fedit_fields
Extract column N from CSV/TSV/delimited file (-col N -delim CHAR); always streaming
The ten tools that change files (fedit_insert, fedit_delete, fedit_replace, fedit_write, fedit_writeraw, fedit_replaceall, fedit_insertafter, fedit_insertbefore, fedit_move and fedit_copy) also take an optional boolean dry_run (since v1.12.0). With dry_run true nothing is written, truncated or created. The result text starts with dry-run: applied=false (no file was changed), followed by a unified diff of each file that would change and then the summary of the tool, worded as a preview (Would insert ..., Would replace ..., Would write ...) because nothing was done; a real call keeps its past tense. A multi-file total reads N/M file(s) would succeed. A call that would fail is still an error, and the read-only tools have no dry_run parameter. A dry call is logged like any call, with dry=true on its end record.
All 14 tools also take two optional parameters, output_file (string) and output_append (boolean) (since v1.12.0), for results that should not enter the conversation, such as a large fedit_show, fedit_find or fedit_map result. With output_file the full result text is written to that file (UTF-8, no BOM; overwritten, or appended when output_append is true) and the tool returns only one line, result written to FILE (N lines) or result appended to FILE (N lines). The operation itself runs as usual, so a changing tool still changes its files; with dry_run the dry-run text (the applied=false line and the diff) is what is written. Some calls are refused before the tool runs and write nothing: output_append without output_file, a result file that is also an edited file (file, dest or a glob match) and a result file whose folder does not exist. A call that fails returns its error in full and leaves the result file untouched. If the result file cannot be written after the operation succeeded, the error says so and carries the text. A relative path resolves against the working directory of the server, like every other path. This is the MCP counterpart of -outputresult and -outappend on the command line.
Without fedit, LLMs rewrite entire files โ burning tokens and introducing drift. With fedit as an MCP tool, the model calls fedit_map to see structure, fedit_find to locate targets, and fedit_replace or fedit_insertafter to make surgical edits. Every mutation returns stats (line delta, elapsed time) so the model can verify its work.
FAQ
Do I need fedit if my team has a solid PR review process?
Probably not for human-driven edits where you review every diff. fedit shines in two specific cases:
Whole-file rewrites in long configs. When an LLM regenerates a 600-line values.yaml to change one key, the diff is technically reviewable but practically nobody scrolls to line 412 to confirm nothing else moved. fedit makes the diff exactly N lines for an N-line change.
Agent loops without a human in the middle. If you run agents semi-autonomously (issue โ branch โ PR opened, you review at the end), giving the agent surgical tools (fedit_replace, fedit_insertafter) instead of "rewrite the whole file" measurably reduces review surface area.
If your workflow already catches these, the CLI is overkill. The MCP server may still be useful as an agent primitive.
Does fedit support streaming for all operations?
Currently replaceall and find support -stream mode. move and copy require the full file in memory because they need to read both source and destination ranges. map requires structure analysis. fields is always streaming.
What is the maximum file size fedit can handle?
In default (in-memory) mode: limited by available RAM, typically fine up to a few hundred MB. With -stream: unlimited -- fedit processes one line at a time with a 10 MB per-line buffer.
Does fedit support Terraform / HCL?
Yes, as of v1.5.0. Use -lang hcl (or -lang tf/terraform) with -block, -beforeblock, -afterblock to move and copy Terraform blocks by name. All 11 top-level block types are supported. The map op supports HCL/Terraform and Nix since v1.11.0: fedit -op map on a .tf, .hcl or .nix file (or with -lang hcl, terraform, tf or nix) lists the top-level blocks (HCL) or attributes (Nix) and flags duplicates, and fedit_map does the same over MCP.
Does fedit preserve comments and formatting?
Yes, by design. fedit does not parse-and-reformat โ it operates on raw text bytes at line granularity.
If you replace -line 47 -end 49, lines 1โ46 and 50โEOF are untouched byte-for-byte: comments, trailing whitespace, mixed indentation, BOM markers, all preserved exactly. This is the main reason fedit is line-addressable instead of AST-based: AST round-trips lose too much (trailing commas, comment positioning, key ordering, blank-line spacing).
This matters most for nginx configs (inline comments documenting why a directive exists), Ansible playbooks (YAML anchors and merge keys), and any file where a human formatting choice carries semantic weight.
Is the MCP server Claude-specific or Cursor-specific?
Neither โ it targets the open MCP spec. Plain JSON-RPC 2.0 over stdin/stdout against the public Model Context Protocol schema. No vendor-specific bits.
Tested with Claude Desktop; should work with any compliant MCP client (Cursor, Continue, Cline, custom integrations). Tool definitions and JSON Schema live in mcp.go if you want to inspect the surface area before wiring it up.
What if the target string appears multiple times in the file?
No. Each fedit invocation reads the file fresh, so line numbers always reflect the current state on disk. You can chain operations safely with ; (PowerShell) or && (bash):
The tradeoff is one disk read per operation, which is negligible for editing workflows.
If you want drift-immunity by design, prefer content-based targeting (insertafter / insertbefore / replaceall with -match) over line numbers โ those resolve the target on each invocation regardless of what previous ops did.