Fix Markdown Code Fence Closings
Scan and repair malformed closing fences in markdown files. Closing fences must never contain language identifiers.
Triggers
| Trigger Phrase |
Operation |
fix markdown fences |
Scan and repair malformed fence closings |
repair code block closings |
Fix closing fences with language identifiers |
markdown rendering broken |
Diagnose and fix fence issues |
code blocks bleeding into content |
Fix unclosed or malformed fences |
validate markdown code blocks |
Check all fences for correctness |
Quick Reference
| Symptom |
Cause |
Fix |
| Code block bleeds into text |
Closing fence has language identifier |
Insert a bare closing fence above it; the line then opens the next block |
| Nested blocks render wrong |
Missing closing fence before new opening |
Insert closing fence |
| Content cut off at end of file |
Unclosed code block |
Append closing fence |
When to Use
Use this skill when:
- Markdown code blocks render incorrectly or bleed into surrounding content
- Closing fences have language identifiers (e.g.,
```python instead of ```)
- Validating markdown documentation before committing
Use manual editing instead when:
- The issue is indentation or content inside the code block (not the fences)
- You need to change the language identifier on opening fences
Process
Do not walk the file by hand. Fence tracking is a state machine, and
fix_fences.py runs it.
- Report. Run the script over the target path. It prints defects as
FILE:LINE: KIND: TEXT, up to 200 lines, then says how many it left out (rerun
with --max-lines 0 for all, or narrow the path). It exits 1 when it finds any.
python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" FILE_OR_DIR
Read the report. Two kinds appear:
malformed_closing: a closing fence carries a language identifier, so
the block bleeds into the following prose.
unclosed_block: the file ends with a block still open.
Decide, then write. Repair is best-effort on an ambiguous file. When a
defect cluster sits inside documentation that shows fenced markdown, the
author usually wanted a wider container fence (four backticks around a
three-backtick example), not the closing fence the repair inserts. Widen
the container by hand in that case. Otherwise:
python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" FILE_OR_DIR --write
- Confirm. Re-run step 1. A clean tree exits 0. Then read
git diff and
confirm only fence lines moved.
Scripts
fix_fences.py
Detects and repairs malformed fence closings. Reporting is the default;
--write is required to modify a file.
python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" PATH [PATH ...]
python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" PATH --write
python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" PATH --json
Options: --write repairs in place, --json emits machine-readable output,
--pattern sets the glob for directory scans (default *.md), --max-lines
bounds the text listing (default 200, 0 lists all; --json is never cut). Paths default
to the current directory. .git, node_modules, .venv, venv, and __pycache__
are skipped.
Fence matching follows CommonMark, which is what keeps the tool from damaging
documentation:
- A fence is three or more backticks or three or more tildes.
- A closing fence uses the same character and is at least as long as the
opener, so a three-backtick example nested inside a four-backtick container
stays literal text.
- A backtick opening fence whose info string contains a backtick is not a
fence.
- A marker more than three spaces past its containing block is an indented
code block, not a fence. That is what stops a repair from appending a fence
to a document that shows a bare fence inside an indented block. The three
spaces are counted from the innermost open list item, not from column zero,
so a fence indented four spaces inside a list item is still a fence.
- A list item's content column is not always the marker plus its padding. Five
or more spaces after the marker means the content column is the marker plus
one; an item with no content on its line is the same. A marker that is itself
indented code opens no item, a thematic break is never an item even though
* * * matches the bullet grammar, and a list may interrupt a paragraph only
when the item is non-empty and, if ordered, starts at 1 (leading zeros do not
change that start). That last veto is scoped to the item the paragraph lives
in: a marker indented below the content column closes the item, the paragraph
closes with it, and the marker is then judged at the outer level where no
paragraph is open. A link reference definition ([foo]: /url) is its own
block and leaves no paragraph open, so a list may start after one; but a
definition cannot interrupt a paragraph that is already open, its
destination and title must be complete ([foo]: <broken is prose), its
destination balances parentheses at any depth and may escape either
angle delimiter while a title may escape its own and may run across
lines until that delimiter arrives, a continuation belongs to the same
leaf block and so keeps its meaning at any indent, and
either the destination or a bare title may sit on the following line, and
a blank line, a fenced block, a list marker or an indented code block
cancels a definition still waiting for one, while a line that does
continue one is a lazy continuation and does not close the item holding
it. A label of only whitespace is not a definition at all. A blank line
directly after an empty marker closes the item, and a paragraph
continuation line may dedent without closing it.
Getting any of these wrong moves the content column, which moves what counts
as a fence.
- A marker line's remainder is re-parsed inside the item it opens, so a fence
marker after a bullet opens a block whose indent is the item's content
column, and
- - a opens two items. A block also ends when the item holding
it ends, with no closing marker, so a line that dedents below it closes it.
Without either rule the tool kept a block open past its real end, and
--write appended a closing fence to documents already well formed.
- Known gaps, each measured and none counted. Where
markdown-it-py is
installed, --write refuses a file whose repair comes out unclosed (see
"Write guard"), which stops the shapes below whose input was balanced and
whose repair leaves a fence open. It does not stop a repair that the
reference parser still reads as balanced. Where it is not installed those
shapes are written as described. A raw HTML block swallows a following
fence, so a fence inside one is read as a fence here and as HTML by
CommonMark. --write refuses that file with no extra package (see "Write
guard"): measured across all seven CommonMark HTML block types, opener
terminated and unterminated, 20 of 20 shapes are refused. The check reads
HTML blocks at column zero to three. A block inside a list item or a
blockquote is not seen, so a fence inside one is still written to. It also
refuses a file where a start condition 7 tag such as <span> follows
paragraph text, which CommonMark does not read as a block. A refused write
costs a manual edit. A blockquote prefix is never stripped,
and that costs two different things. A fence inside > is invisible, which is a miss: six
shapes diverge and --write changes none. A blockquote INTERRUPTING a
paragraph is worse: CommonMark ends the paragraph and lazily continues the
quote, so a following 2. opens a list, while we keep the paragraph open
and the repair function appends a closer to a balanced document. Five of
twelve measured shapes do that. Where markdown-it-py is installed,
--write refuses all five and writes none (see "Write guard"); without it
the five are written. A backslash in a link destination escapes whatever
follows it, where CommonMark escapes only ASCII punctuation, so an escaped
space and an escaped tab are read wrongly: 62 of 64 shapes agree. The spec
rule was measured before being believed and is worse, 34 of 64 with 30
--write corruptions, so the permissive rule stays. The escaped-TAB half is
destructive on its own account, because tabs are expanded to four-column
stops before the grammar sees them, so what the permissive rule eats depends
on the label's length: nine of eleven single-line label lengths turn a
balanced document into an unclosed one, and the two that do not are the two
that land on a tab stop. Escaped space and the next-line destination path
corrupt none of eleven. Where markdown-it-py is installed, --write
refuses all nine and writes none (see "Write guard"); without it the nine
are written. And a setext ===
underline directly under a list item, followed by a lazy continuation and
then an indented fence, leaves that fence unseen. The repair function is
DESTRUCTIVE here, and it was recorded as a miss on a measurement that did not
hold: over nine shapes, seven are rewritten and six go in balanced and come
out unclosed. The smallest is five lines, - item / === / lazy /
two-space fence / out, where the list item ending closes the fence for
CommonMark and the repair appends a second one at top level. Where
markdown-it-py is installed, --write refuses all six of those files and
writes none (see "Write guard"); the seventh rewritten shape is a genuinely
unclosed file and is repaired correctly. Without the package the six are
written. --- under
the same item already agrees. The scanners' agreement with a CommonMark
reference is measured by the fuzz baselines in the repository's test suite.
Files are read and written as bytes, so CRLF and CR endings survive, a UTF-8
BOM survives, and every separator str.splitlines would swallow (U+000B,
U+000C, U+001C, U+001D, U+001E, U+0085, U+2028, U+2029) stays put. Each line keeps its own terminator, so
a mixed-ending file is not normalized. Repair is idempotent.
Exit codes (ADR-035):
0 no defects found, or --write repaired every defect it found
1 report mode found at least one defect; nothing was written. With
--write, at least one file was refused (see "Write guard"); nothing was
written for it
2 a requested path does not exist, or a file could not be read or written
Write guard
--write runs two checks before it replaces a file. Either one refuses it: the
file is not written, it is listed on a Refused line with the reason, the
refused key under --json names it and refusal_reasons says why, and the
run exits 1. Other files in the same run are still repaired. When a file is
refused, read the report and fix the fences by hand.
A fence inside a raw HTML block. CommonMark reads the fence as HTML, so the
document is complete, while the scanner reads a fence and would append a
closer. The edit lands on a well-formed file. The scanner does not model HTML
blocks, so a file with a fence-looking line inside one is refused. This check
needs no extra package. Fences inside a fenced block are skipped, so HTML shown
as an example does not count, and an HTML block that a blank line or its own end
marker closes before the fence does not count either. A block inside a list item
or a blockquote is not seen.
A repair that leaves a fence open. A repair must never turn a balanced file
into an unclosed one. The worst case is a mistaken closer next to a raw HTML
block: the repair inserts a closing fence above the info-string fence, then
appends another at the end of the file, and the appended one is a fresh opener
that nothing closes. A tracked file did exactly that. So --write checks the
repaired text against markdown-it-py. A file that was balanced and would come
out unclosed is refused. A file that was already unclosed is never refused,
since repair cannot make it worse by that measure.
markdown-it-py is optional because this skill is vendored into trees that
carry no third-party packages. Without it this second check is skipped, stderr
says so, and the HTML check still runs. Report mode never needs either.
Reference: the algorithm
Kept so a reader can audit the script, not so the agent can run it by hand.
Track fence state while scanning line by line:
- Track list containers: outside a block, close any list item the line
has dedented out of, and close any paragraph those items held, then open one
if the line starts an item. The stack of open content columns is what the
indent test below measures against. Closing the paragraph with its item is
what lets a marker that cannot interrupt a paragraph still open a list after
a dedent.
- Detect opening fence: outside a block, a line of three or more
backticks or tildes, indented no more than three columns past the innermost
open list item, opens one. Record the character, the length, and the indent.
- Detect the end of the containing item: inside a block that opened
inside a list item, a line indented below that item's content column ends
the block, with no closing marker and nothing inserted.
- Detect malformed closing fence: inside a block, a line using the same
character at the same length or longer, carrying a non-empty info string.
Insert a bare closing fence before it.
- Detect valid closing fence: the same character at the same length or
longer with an empty info string. Exit the block.
- At end of file: a still-open block gets a bare closing fence appended.
Verification
python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" PATH
echo "exit=$?" # 0 = clean, 1 = defects found, 2 = bad input
Anti-Patterns
| Avoid |
Why |
Instead |
| Manually searching for bad fences |
Error-prone in large files, and the agent cannot track fence length by eye |
Run fix_fences.py |
| Simulating the state machine in-context |
The script already does it, exactly and for free |
Read the script's report |
Running --write across a whole repo unreviewed |
A repair inside nested documentation is often the wrong fix |
Report first, review, then write per path |
| Copying opening fence line to close a block |
Creates the exact bug this skill fixes |
Close with the opener's character, no info string, at least the opener's length |
| Fixing fences without tracking block state |
Misidentifies nested vs sequential blocks |
Run fix_fences.py, which tracks it |
Prevention
When generating markdown with code blocks:
- Close with the opener's fence character and no info string, at a length
at least the opener's. A four-backtick container needs four to close it,
which is what lets it hold a three-backtick example.
- Never copy the opening fence line to close
- Track block state when programmatically generating markdown
The shipped script does this for you; fix_fences.py is the
implementation, and the Reference section above is the algorithm it runs. An
earlier revision of this file inlined a copy of that parser here under
"Implementation: Python (Recommended)". It was the pre-CommonMark version,
which had no fence-length rule and so corrupted any document showing a
three-backtick example inside a four-backtick container. It is gone rather
than fixed: a second copy of a parser drifts from the one that ships.
# Find files with potential issues
# Single quotes throughout: a backtick inside DOUBLE quotes opens command
# substitution, and this line used to fail `bash -n` for that reason.
grep -rEn --include="*.md" -- '```\w+' . | grep -vE '^[^:]*:[0-9]*:[[:space:]]*```\w+[[:space:]]*$'
An earlier revision also inlined a PowerShell rewriter here. It is gone for
the same reason, and measurement is why rather than symmetry: run on a CRLF
file it rewrote every ending to LF, which the Edge Cases list below
explicitly promises it does not do, and a ~~~python block left unclosed
was invisible to it because it matched backticks only. The shipped script
closes that tilde block and preserves the CRLF. A copy that drifts this far
while sitting under the same heading is worse than no example.
- Nested indentation: Preserves indent level from opening fence
- Multiple consecutive blocks: Each block tracked independently
- File ending inside block: Closes an unclosed block with a fence of the same character and length
- Mixed line endings:
\n, \r\n and \r are preserved per line, as is a UTF-8 BOM and the presence or absence of a trailing newline
1---2name: fix-markdown-fences-33description: >-4 Repair malformed markdown code fence closings. Use when you say "fix markdown5 fences", "repair code block closings", "markdown rendering broken", "code6 blocks bleeding into content", or "validate markdown code blocks" on any .md7 file. Do NOT use for documentation accuracy checks or verifying code examples8 (use doc-accuracy).9metadata:10 source: https://skillmd.com/skills/rjmurillo/fix-markdown-fences-311---1213# Fix Markdown Code Fence Closings1415Scan and repair malformed closing fences in markdown files. Closing fences must never contain language identifiers.1617## Triggers1819| Trigger Phrase | Operation |20|----------------|-----------|21| `fix markdown fences` | Scan and repair malformed fence closings |22| `repair code block closings` | Fix closing fences with language identifiers |23| `markdown rendering broken` | Diagnose and fix fence issues |24| `code blocks bleeding into content` | Fix unclosed or malformed fences |25| `validate markdown code blocks` | Check all fences for correctness |2627## Quick Reference2829| Symptom | Cause | Fix |30|---------|-------|-----|31| Code block bleeds into text | Closing fence has language identifier | Insert a bare closing fence above it; the line then opens the next block |32| Nested blocks render wrong | Missing closing fence before new opening | Insert closing fence |33| Content cut off at end of file | Unclosed code block | Append closing fence |3435## When to Use3637**Use this skill when:**3839- Markdown code blocks render incorrectly or bleed into surrounding content40- Closing fences have language identifiers (e.g., ` ```python ` instead of ` ``` `)41- Validating markdown documentation before committing4243**Use manual editing instead when:**4445- The issue is indentation or content inside the code block (not the fences)46- You need to change the language identifier on opening fences4748## Process4950Do not walk the file by hand. Fence tracking is a state machine, and51`fix_fences.py` runs it.52531. **Report.** Run the script over the target path. It prints defects as54 `FILE:LINE: KIND: TEXT`, up to 200 lines, then says how many it left out (rerun55 with `--max-lines 0` for all, or narrow the path). It exits 1 when it finds any.5657```bash58python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" FILE_OR_DIR59```60612. **Read the report.** Two kinds appear:62 - `malformed_closing`: a closing fence carries a language identifier, so63 the block bleeds into the following prose.64 - `unclosed_block`: the file ends with a block still open.65663. **Decide, then write.** Repair is best-effort on an ambiguous file. When a67 defect cluster sits inside documentation that shows fenced markdown, the68 author usually wanted a wider container fence (four backticks around a69 three-backtick example), not the closing fence the repair inserts. Widen70 the container by hand in that case. Otherwise:7172```bash73python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" FILE_OR_DIR --write74```75764. **Confirm.** Re-run step 1. A clean tree exits 0. Then read `git diff` and77 confirm only fence lines moved.7879## Scripts8081### fix_fences.py8283Detects and repairs malformed fence closings. Reporting is the default;84`--write` is required to modify a file.8586```bash87python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" PATH [PATH ...]88python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" PATH --write89python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" PATH --json90```9192Options: `--write` repairs in place, `--json` emits machine-readable output,93`--pattern` sets the glob for directory scans (default `*.md`), `--max-lines`94bounds the text listing (default 200, `0` lists all; `--json` is never cut). Paths default95to the current directory. `.git`, `node_modules`, `.venv`, `venv`, and `__pycache__`96are skipped.9798Fence matching follows CommonMark, which is what keeps the tool from damaging99documentation:100101- A fence is three or more backticks or three or more tildes.102- A closing fence uses the same character and is at least as long as the103 opener, so a three-backtick example nested inside a four-backtick container104 stays literal text.105- A backtick opening fence whose info string contains a backtick is not a106 fence.107- A marker more than three spaces past its containing block is an indented108 code block, not a fence. That is what stops a repair from appending a fence109 to a document that shows a bare fence inside an indented block. The three110 spaces are counted from the innermost open list item, not from column zero,111 so a fence indented four spaces inside a list item is still a fence.112- A list item's content column is not always the marker plus its padding. Five113 or more spaces after the marker means the content column is the marker plus114 one; an item with no content on its line is the same. A marker that is itself115 indented code opens no item, a thematic break is never an item even though116 `* * *` matches the bullet grammar, and a list may interrupt a paragraph only117 when the item is non-empty and, if ordered, starts at 1 (leading zeros do not118 change that start). That last veto is scoped to the item the paragraph lives119 in: a marker indented below the content column closes the item, the paragraph120 closes with it, and the marker is then judged at the outer level where no121 paragraph is open. A link reference definition (`[foo]: /url`) is its own122 block and leaves no paragraph open, so a list may start after one; but a123 definition cannot interrupt a paragraph that is already open, its124 destination and title must be complete (`[foo]: <broken` is prose), its125 destination balances parentheses at any depth and may escape either126 angle delimiter while a title may escape its own and may run across127 lines until that delimiter arrives, a continuation belongs to the same128 leaf block and so keeps its meaning at any indent, and129 either the destination or a bare title may sit on the following line, and130 a blank line, a fenced block, a list marker or an indented code block131 cancels a definition still waiting for one, while a line that does132 continue one is a lazy continuation and does not close the item holding133 it. A label of only whitespace is not a definition at all. A blank line134 directly after an empty marker closes the item, and a paragraph135 continuation line may dedent without closing it.136 Getting any of these wrong moves the content column, which moves what counts137 as a fence.138- A marker line's remainder is re-parsed inside the item it opens, so a fence139 marker after a bullet opens a block whose indent is the item's content140 column, and `- - a` opens two items. A block also ends when the item holding141 it ends, with no closing marker, so a line that dedents below it closes it.142 Without either rule the tool kept a block open past its real end, and143 `--write` appended a closing fence to documents already well formed.144- Known gaps, each measured and none counted. Where `markdown-it-py` is145 installed, `--write` refuses a file whose repair comes out unclosed (see146 "Write guard"), which stops the shapes below whose input was balanced and147 whose repair leaves a fence open. It does not stop a repair that the148 reference parser still reads as balanced. Where it is not installed those149 shapes are written as described. A raw HTML block swallows a following150 fence, so a fence inside one is read as a fence here and as HTML by151 CommonMark. `--write` refuses that file with no extra package (see "Write152 guard"): measured across all seven CommonMark HTML block types, opener153 terminated and unterminated, 20 of 20 shapes are refused. The check reads154 HTML blocks at column zero to three. A block inside a list item or a155 blockquote is not seen, so a fence inside one is still written to. It also156 refuses a file where a start condition 7 tag such as `<span>` follows157 paragraph text, which CommonMark does not read as a block. A refused write158 costs a manual edit. A blockquote prefix is never stripped,159 and that costs two different things. A fence inside `>` is invisible, which is a miss: six160 shapes diverge and `--write` changes none. A blockquote INTERRUPTING a161 paragraph is worse: CommonMark ends the paragraph and lazily continues the162 quote, so a following `2.` opens a list, while we keep the paragraph open163 and the repair function appends a closer to a balanced document. Five of164 twelve measured shapes do that. Where `markdown-it-py` is installed,165 `--write` refuses all five and writes none (see "Write guard"); without it166 the five are written. A backslash in a link destination escapes whatever167 follows it, where CommonMark escapes only ASCII punctuation, so an escaped168 space and an escaped tab are read wrongly: 62 of 64 shapes agree. The spec169 rule was measured before being believed and is worse, 34 of 64 with 30170 `--write` corruptions, so the permissive rule stays. The escaped-TAB half is171 destructive on its own account, because tabs are expanded to four-column172 stops before the grammar sees them, so what the permissive rule eats depends173 on the label's length: nine of eleven single-line label lengths turn a174 balanced document into an unclosed one, and the two that do not are the two175 that land on a tab stop. Escaped space and the next-line destination path176 corrupt none of eleven. Where `markdown-it-py` is installed, `--write`177 refuses all nine and writes none (see "Write guard"); without it the nine178 are written. And a setext `===`179 underline directly under a list item, followed by a lazy continuation and180 then an indented fence, leaves that fence unseen. The repair function is181 DESTRUCTIVE here, and it was recorded as a miss on a measurement that did not182 hold: over nine shapes, seven are rewritten and six go in balanced and come183 out unclosed. The smallest is five lines, `- item` / `===` / `lazy` /184 two-space fence / `out`, where the list item ending closes the fence for185 CommonMark and the repair appends a second one at top level. Where186 `markdown-it-py` is installed, `--write` refuses all six of those files and187 writes none (see "Write guard"); the seventh rewritten shape is a genuinely188 unclosed file and is repaired correctly. Without the package the six are189 written. `---` under190 the same item already agrees. The scanners' agreement with a CommonMark191 reference is measured by the fuzz baselines in the repository's test suite.192193Files are read and written as bytes, so CRLF and CR endings survive, a UTF-8194BOM survives, and every separator `str.splitlines` would swallow (U+000B,195U+000C, U+001C, U+001D, U+001E, U+0085, U+2028, U+2029) stays put. Each line keeps its own terminator, so196a mixed-ending file is not normalized. Repair is idempotent.197198Exit codes (ADR-035):199200- `0` no defects found, or `--write` repaired every defect it found201- `1` report mode found at least one defect; nothing was written. With202 `--write`, at least one file was refused (see "Write guard"); nothing was203 written for it204- `2` a requested path does not exist, or a file could not be read or written205206### Write guard207208`--write` runs two checks before it replaces a file. Either one refuses it: the209file is not written, it is listed on a `Refused` line with the reason, the210`refused` key under `--json` names it and `refusal_reasons` says why, and the211run exits 1. Other files in the same run are still repaired. When a file is212refused, read the report and fix the fences by hand.213214**A fence inside a raw HTML block.** CommonMark reads the fence as HTML, so the215document is complete, while the scanner reads a fence and would append a216closer. The edit lands on a well-formed file. The scanner does not model HTML217blocks, so a file with a fence-looking line inside one is refused. This check218needs no extra package. Fences inside a fenced block are skipped, so HTML shown219as an example does not count, and an HTML block that a blank line or its own end220marker closes before the fence does not count either. A block inside a list item221or a blockquote is not seen.222223**A repair that leaves a fence open.** A repair must never turn a balanced file224into an unclosed one. The worst case is a mistaken closer next to a raw HTML225block: the repair inserts a closing fence above the info-string fence, then226appends another at the end of the file, and the appended one is a fresh opener227that nothing closes. A tracked file did exactly that. So `--write` checks the228repaired text against `markdown-it-py`. A file that was balanced and would come229out unclosed is refused. A file that was already unclosed is never refused,230since repair cannot make it worse by that measure.231232`markdown-it-py` is optional because this skill is vendored into trees that233carry no third-party packages. Without it this second check is skipped, stderr234says so, and the HTML check still runs. Report mode never needs either.235236## Reference: the algorithm237238Kept so a reader can audit the script, not so the agent can run it by hand.239240Track fence state while scanning line by line:2412421. **Track list containers**: outside a block, close any list item the line243 has dedented out of, and close any paragraph those items held, then open one244 if the line starts an item. The stack of open content columns is what the245 indent test below measures against. Closing the paragraph with its item is246 what lets a marker that cannot interrupt a paragraph still open a list after247 a dedent.2482. **Detect opening fence**: outside a block, a line of three or more249 backticks or tildes, indented no more than three columns past the innermost250 open list item, opens one. Record the character, the length, and the indent.2513. **Detect the end of the containing item**: inside a block that opened252 inside a list item, a line indented below that item's content column ends253 the block, with no closing marker and nothing inserted.2544. **Detect malformed closing fence**: inside a block, a line using the same255 character at the same length or longer, carrying a non-empty info string.256 Insert a bare closing fence before it.2575. **Detect valid closing fence**: the same character at the same length or258 longer with an empty info string. Exit the block.2596. **At end of file**: a still-open block gets a bare closing fence appended.260261## Verification262263```bash264python3 "${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/fix-markdown-fences/scripts/fix_fences.py" PATH265echo "exit=$?" # 0 = clean, 1 = defects found, 2 = bad input266```267268- [ ] The script exits 0 on the repaired path.269- [ ] `git diff` shows only fence lines added, no content modifications.270- [ ] Defects that belong inside a wider container fence were widened by271 hand rather than closed by `--write`.272273## Anti-Patterns274275| Avoid | Why | Instead |276|-------|-----|---------|277| Manually searching for bad fences | Error-prone in large files, and the agent cannot track fence length by eye | Run `fix_fences.py` |278| Simulating the state machine in-context | The script already does it, exactly and for free | Read the script's report |279| Running `--write` across a whole repo unreviewed | A repair inside nested documentation is often the wrong fix | Report first, review, then write per path |280| Copying opening fence line to close a block | Creates the exact bug this skill fixes | Close with the opener's character, no info string, at least the opener's length |281| Fixing fences without tracking block state | Misidentifies nested vs sequential blocks | Run `fix_fences.py`, which tracks it |282283## Prevention284285When generating markdown with code blocks:2862871. Close with the opener's fence character and no info string, at a length288 at least the opener's. A four-backtick container needs four to close it,289 which is what lets it hold a three-backtick example.2902. Never copy the opening fence line to close2913. Track block state when programmatically generating markdown292293The shipped script does this for you; `fix_fences.py` is the294implementation, and the Reference section above is the algorithm it runs. An295earlier revision of this file inlined a copy of that parser here under296"Implementation: Python (Recommended)". It was the pre-CommonMark version,297which had no fence-length rule and so corrupted any document showing a298three-backtick example inside a four-backtick container. It is gone rather299than fixed: a second copy of a parser drifts from the one that ships.300301<details>302<summary><strong>Implementation: Bash (Quick Check)</strong></summary>303304```bash305# Find files with potential issues306# Single quotes throughout: a backtick inside DOUBLE quotes opens command307# substitution, and this line used to fail `bash -n` for that reason.308grep -rEn --include="*.md" -- '```\w+' . | grep -vE '^[^:]*:[0-9]*:[[:space:]]*```\w+[[:space:]]*$'309```310311</details>312313An earlier revision also inlined a PowerShell rewriter here. It is gone for314the same reason, and measurement is why rather than symmetry: run on a CRLF315file it rewrote every ending to LF, which the Edge Cases list below316explicitly promises it does not do, and a `~~~python` block left unclosed317was invisible to it because it matched backticks only. The shipped script318closes that tilde block and preserves the CRLF. A copy that drifts this far319while sitting under the same heading is worse than no example.320321<details>322<summary><strong>Edge Cases Handled</strong></summary>3233241. **Nested indentation**: Preserves indent level from opening fence3252. **Multiple consecutive blocks**: Each block tracked independently3263. **File ending inside block**: Closes an unclosed block with a fence of the same character and length3274. **Mixed line endings**: `\n`, `\r\n` and `\r` are preserved per line, as is a UTF-8 BOM and the presence or absence of a trailing newline328329</details>