Incremental Markdown Fenced Code Block Parser
Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Live chat and code-editor UIs often receive Markdown responses incrementally over a network stream, where arbitrary packet splits can cut right across fence markers, language tags, or line breaks. To syntax-highlight fenced code blocks as tokens arrive, the client needs a stateful parser that identifies block boundaries on the fly and streams confirmed characters without waiting for the entire document.
Implement StreamingCodeFenceParser with the following interface:
class StreamingCodeFenceParser:
def __init__(self) -> None: ...
def feed(self, chunk: str) -> List[Dict[str, str]]: ...
def flush(self) -> List[Dict[str, str]]: ...
Fenced Code Block Rules
- Opening fence line:
- Begins at position
0of the stream or right after a newline (\n). - May start with
0to3space characters (' '), which are discarded;4or more leading spaces or any tab ('\t') disqualifies the line as a fence. - Continues with an unbroken run of at least
3backticks (`) or at least3tildes (~). Mixing`and~within the delimiter run is not valid. - Everything after that delimiter run up to
\n(or end of stream duringflush()), trimmed of leading and trailing whitespace, forms the block'slanguageinfo string (""if blank). - If the opening run uses backticks (
`), no backtick may appear anywhere in the info string on that line. Tilde (~) fences have no such restriction.
- Begins at position
- Code block body:
- Consists of all characters following the opening fence line's
\nup to the start of a valid closing fence line (or end of stream).
- Consists of all characters following the opening fence line's
- Closing fence line:
- Begins right after
\nwith0to3leading' 'spaces (tabs are not allowed). - Uses the exact same delimiter character (
`or~) that opened the active block, with a contiguous run length greater than or equal to the opening fence's run length. - May be followed only by optional
' 'spaces before\nor end of stream; any non-space character (including tabs or info text) makes the line ordinary code content instead.
- Begins right after
- Outside prose:
- Every character outside fenced code blocks is plain text.
Emitted Events & Streaming Conventions
feed(chunk) and flush() return a list of event dictionaries:
{"type": "text", "content": str}— plain text outside code blocks, emitted as soon as the characters are guaranteed not to form an opening fence.{"type": "code_start", "language": str}— emitted when an opening fence line finishes (languageis""when omitted).{"type": "code_chunk", "content": str}— code content inside an active block, emitted as soon as a line prefix is guaranteed not to form a closing fence.{"type": "code_end"}— emitted when a closing fence completes or when an unclosed block is terminated byflush().
Additional boundary rules:
- The \n terminating an opening or closing fence line is consumed by the fence itself and excluded from content, whereas \n at the end of a normal text or code line stays in content.
- Within a single feed() or flush() call, adjacent text slices are merged into one text event, adjacent code_chunk slices are merged into one code_chunk event, and events with empty "" content are never emitted.
- Calling flush() resolves any buffered partial line at end of stream without adding a trailing \n (so a valid opening or closing fence line lacking \n still takes effect, while any non-fence buffered prefix flushes as text or code_chunk), emits {"type": "code_end"} if a block is still open, and resets the parser so the same instance can process a new stream.
Examples
Example 1
parser = StreamingCodeFenceParser()
parser.feed("Run query:\n```sq")
# -> [{"type": "text", "content": "Run query:\n"}]
parser.feed("l\nSELECT 42;\n```\nOK")
# -> [
# {"type": "code_start", "language": "sql"},
# {"type": "code_chunk", "content": "SELECT 42;\n"},
# {"type": "code_end"},
# {"type": "text", "content": "OK"},
# ]
parser.flush()
# -> []
Walk-through: "Run query:\n" begins with 'R', immediately ruling out an opening fence so it streams right out, while "```sq" waits for its line break. In the second chunk, "l\n" finishes the "sql" opening fence, "SELECT 42;\n" streams as code_chunk, "```\n" closes the 3-backtick block, and "OK" emits immediately as plain text.
Example 2
parser = StreamingCodeFenceParser()
parser.feed("~~")
# -> []
parser.feed("~\nlet x = 7;\n~~~~ ")
# -> [
# {"type": "code_start", "language": ""},
# {"type": "code_chunk", "content": "let x = 7;\n"},
# ]
parser.flush()
# -> [{"type": "code_end"}]
Walk-through: "~~" at the start of a line could still grow into ~~~, so feed("~~") holds it and returns []. Adding "~\n" confirms an untagged 3-tilde block, "let x = 7;\n" streams as code, and trailing "~~~~ " (4 >= 3 tildes plus a space) stays buffered until flush() confirms end of stream with no disqualifying trailing text.
Constraints
0 <= len(chunk)— chunks may be empty strings, single characters, or multi-kilobyte slices cut at arbitrary byte/character boundaries.- A block opened with
`can never be closed by~(and vice versa), nor by a shorter delimiter run than the one that opened it. - Non-fence lines must stream eagerly once disqualified rather than waiting for
\n, achievingO(N)total processing time acrossNstreamed characters.
Step-by-step walkthrough
Understand the streaming requirement and edge rules
When a live interface streams Markdown responses incrementally, packet splits can land at any character offset — right inside
```or mid-way throughsql. Our parser accepts arbitrary string slices viafeed(chunk)and must emit structured events (text,code_start,code_chunk,code_end) as soon as safe, resolving any remaining state whenflush()marks end of stream.Let's pin down the exact CommonMark-style rules and edge conventions up front:
- Opening fence line: Starts at the beginning of the stream or right after
\n, with0to3leading' 'spaces (a\ttab or a 4th space disqualifies it), followed by a contiguous delimiter run of3or more`characters or3or more~characters (never mixed). Everything after the run on that line, trimmed of leading and trailing whitespace, becomeslanguage(the info string). For`fences, the info string cannot contain`(because```foo`is inline code, not a fence);~fences have no such restriction. - Closing fence line: Starts on a new line with
0to3leading' 'spaces, uses the same delimiter character that opened the block, has at least as many consecutive delimiters as the opening fence, and is followed only by optional' 'spaces up to\nor end of stream (no info string allowed). - Newline ownership and merging: The
\nending an opening or closing fence line is consumed by the fence itself, whereas the\nat the end of a normal code line belongs tocode_chunk(so"SELECT 42;\n```\n"emitscode_chunk"SELECT 42;\n"). Adjacenttextpieces (orcode_chunkpieces) produced within onefeed/flushcall are merged into a single event, and empty-content events are never emitted. - End of stream (
flush): Resolves any held line without adding a trailing\n(so a trailing"~~~~ "closes a 3-tilde block, and"```rust"opens a block), emitscode_endif a block is still open so the UI never gets stuck inside code mode, and resets the parser for reuse.
- Opening fence line: Starts at the beginning of the stream or right after
Why both "emit immediately" and "wait for every newline" fail
Before designing our parser, look at why the two most tempting shortcuts break:
- Emitting every character immediately fails correctness. Suppose
feed("~~")arrives first. If we emit"~~"astext, and the very next chunk is"~\n", the line was actually an opening fence"~~~\n"— and we cannot "un-emit" an event the UI has already rendered. - Buffering every line until
\nfails real-time streaming. If a prose paragraph has a 300-character line with no newline yet, holding the whole line freezes the screen until the paragraph finishes, violating eager streaming.
The sweet spot comes from noticing that fences can only start at the beginning of a line, and almost every normal line disqualifies itself within 1 to 4 characters. As soon as a line starts with
"R"(or 4 spaces, or"\t", or"``x"), it can never become a fence — so we immediately flush those held characters and stream the rest of that line with zero buffering until the next\n!- Emitting every character immediately fails correctness. Suppose
Model the parser as a four-state machine
A finite state machine (FSM) is a design where the program sits in one named mode ("state") at a time, and each incoming input updates variables and switches modes according to explicit rules.
At any point in the stream, two independent questions describe where we are:
- Are we currently outside or inside a fenced code block?
- Are we at the start of a line that might still be a fence (pending), or in the middle of a line already proven not to be a fence?
Multiplying
2 × 2gives four states:State Meaning On disqualifying char On '\n' ------------------- -------------------------------------- ------------------------ -------------------------------------- PENDING_OPEN_FENCE Start of line outside code; might open Emit held chars as text If run_len >= 3: emit code_start -> OUTSIDE_CODE -> PENDING_CLOSE_FENCE Else: emit line + '\n' as text (stay) OUTSIDE_CODE Mid-line outside code; cannot be fence Emit slice as text (stay) Emit through '\n' -> PENDING_OPEN_FENCE PENDING_CLOSE_FENCE Start of line inside code; might close Emit held chars as code If run_len >= fence_len: emit code_end -> INSIDE_CODE -> PENDING_OPEN_FENCE Else: emit line + '\n' as code (stay) INSIDE_CODE Mid-line inside code; cannot be fence Emit slice as code (stay) Emit through '\n' -> PENDING_CLOSE_FENCEWhile in either
PENDING_*state, each non-newline character passes through three sequential phases:Phase in line PENDING_OPEN_FENCE PENDING_CLOSE_FENCE (opened by fence_char * fence_len) ---------------------- --------------------------------------- ------------------------------------------------------ 1. Before run starts ' ' up to 3 times; '`' or '~' starts ' ' up to 3 times; only fence_char starts run; run; anything else -> ruled out anything else -> ruled out 2. Inside delimiter run ch == run_char -> run_len += 1 ch == run_char -> run_len += 1 3. After run ends Need run_len >= 3, and if run_char=='`' Need run_len >= fence_len AND ch == ' '; (run_over = True) forbid '`'; else append to info anything else -> ruled outCode parser state and O(1)-amortized event merging
Let's start with state setup and event-building helpers (amortized O(1) means each character costs constant work on average across the whole stream, even if one occasional step joins buffered pieces at the end of a call):
- The stream begins at column 0 of the very first line outside any block, so
_reset()starts inPENDING_OPEN_FENCE. - Inside
_add_content, notice how we storeevent["content"]temporarily as a Pythonlistof string slices (["l", "et x = 7;\n"]) and call"".join(...)once at the end of the call in_take_events(). Repeatedly doings = s + chin Python copies the entire growing string on every step (O(N^2)time on single-character streams), whereas appending to a list and joining once runs in linearO(N)time.
from typing import Any, Dict, List OUTSIDE_CODE = "OUTSIDE_CODE" # normal text, middle of a line already ruled out as a fence PENDING_OPEN_FENCE = "PENDING_OPEN_FENCE" # start of a text line that could still become an opening fence INSIDE_CODE = "INSIDE_CODE" # code content, middle of a line already ruled out as a fence PENDING_CLOSE_FENCE = "PENDING_CLOSE_FENCE" # start of a code line that could still become a closing fence class StreamingCodeFenceParser: def __init__(self) -> None: self._reset() def _reset(self) -> None: # Stream begins at column 0 of line 1 outside any code block. self.state = PENDING_OPEN_FENCE # fence_char / fence_len: opening delimiter (e.g. "`", 3) of the active code block. self.fence_char = "" self.fence_len = 0 # events: list of event dicts accumulated during the current feed() or flush() call. # While building, text/code_chunk "content" holds List[str] slices joined once in _take_events. self.events: List[Dict[str, Any]] = [] self._start_line() def _start_line(self) -> None: """Reset per-line candidate-fence state when starting a new line or giving up on one.""" self.line: List[str] = [] # raw chars held since the start of this line, e.g. [" ", "`", "`"] self.indent = 0 # count of leading ' ' spaces before the delimiter run (0..3 valid) self.run_char = "" # "`" or "~" once the delimiter run begins self.run_len = 0 # number of contiguous run_char characters at the start of the run self.run_over = False # True once any character after the delimiter run has appeared self.info: List[str] = [] # chars after an opening delimiter run, e.g. ["p", "y"] def _add_content(self, kind: str, content: str) -> None: if content == "": return # Merge adjacent pieces of the same event type within one call using a list of slices # so repeated appends stay O(total length) instead of O(length^2) string concatenation. if self.events and self.events[-1]["type"] == kind: self.events[-1]["content"].append(content) else: self.events.append({"type": kind, "content": [content]}) def _take_events(self) -> List[Dict[str, str]]: events = self.events self.events = [] for event in events: if "content" in event: event["content"] = "".join(event["content"]) return events- The stream begins at column 0 of the very first line outside any block, so
Code the character-by-character fence prefix scanner
In a pending state,
_scan_char(ch)checks for"\n"first; otherwise it appendschtoself.lineand asks_still_possible(ch)whether the line can still be a valid fence.Look carefully at
self.run_overin Phase 2 and Phase 3 of_still_possible: once any character after the opening delimiter run appears (say the space in~~~ a ~),self.run_overflips toTrue. Without that boolean, the later~inside the info stringa ~would matchch == self.run_charand falsely bumpself.run_lenfrom3to4! Similarly, on a closing line like``` `,self.run_overensures the backtick after the spaces is treated as a post-run character (ch == " "isFalse), immediately disqualifying the line.def _scan_char(self, ch: str) -> None: """Process one character while buffering a potential opening or closing fence line.""" if ch == "\n": self._finish_line("\n") return self.line.append(ch) if not self._still_possible(ch): self._give_up_line() def _still_possible(self, ch: str) -> bool: """Update candidate-fence counters for `ch`; return False as soon as a fence is impossible.""" closing = self.state == PENDING_CLOSE_FENCE # Phase 1: Before the delimiter run begins (0 to 3 leading spaces allowed, no tabs). if self.run_len == 0: if ch == " ": self.indent += 1 return self.indent <= 3 if ch != "`" and ch != "~": return False # A closing fence must use the exact same delimiter character that opened the block. if closing and ch != self.fence_char: return False self.run_char = ch self.run_len = 1 return True # Phase 2: Still inside the contiguous run of backticks or tildes. if ch == self.run_char and not self.run_over: self.run_len += 1 return True # Phase 3: First or later character after the delimiter run has ended. self.run_over = True if closing: # Closing fences require run_len >= opening fence_len and allow only trailing spaces. return self.run_len >= self.fence_len and ch == " " # Opening fences require at least 3 delimiters; backtick fences forbid '`' in info strings. if self.run_len < 3: return False if self.run_char == "`" and ch == "`": return False self.info.append(ch) return TrueCode line resolution and fast mid-line slicing
Now let's handle the three ways a line moves forward:
_give_up_line(): Called the instant_still_possiblereturnsFalse. Emits everything held inself.lineas"text"or"code_chunk", switches toOUTSIDE_CODEorINSIDE_CODE, and clearsself.line._finish_line(newline): Called when"\n"arrives (withnewline="\n") or at end-of-streamflush()(withnewline=""). Because_still_possiblealready rejected every illegal character mid-line, we only need to check whetherself.run_lenreached the required minimum (>= 3to open,>= self.fence_lento close)! Ifself.run_lenfell short (for example, an empty line""or just"``"before"\n"), we emit the held characters plusnewlineas normal content and stay in the same pending state for the next line._copy_rest_of_line(chunk, start): Once inOUTSIDE_CODEorINSIDE_CODE, we use C-speedchunk.find("\n", start)to grab the entire remainder of the line in a single slice rather than stepping one character at a time in Python.
def _give_up_line(self) -> None: """Flush buffered prefix immediately once the current line is proven not to be a fence.""" if self.state == PENDING_OPEN_FENCE: self._add_content("text", "".join(self.line)) self.state = OUTSIDE_CODE else: self._add_content("code_chunk", "".join(self.line)) self.state = INSIDE_CODE self._start_line() def _finish_line(self, newline: str) -> None: """Resolve a buffered candidate line on '\\n' (or '' at EOF during flush).""" if self.state == PENDING_OPEN_FENCE: if self.run_len >= 3: language = "".join(self.info).strip() self.events.append({"type": "code_start", "language": language}) self.fence_char = self.run_char self.fence_len = self.run_len # Next line starts inside the newly opened code block, watching for a closing fence. self.state = PENDING_CLOSE_FENCE else: # Fewer than 3 delimiters (e.g. "" or "``") before '\n' is ordinary text. self._add_content("text", "".join(self.line) + newline) else: # _still_possible already guaranteed matching fence_char and only spaces after the run. if self.run_len >= self.fence_len: self.events.append({"type": "code_end"}) self.state = PENDING_OPEN_FENCE else: self._add_content("code_chunk", "".join(self.line) + newline) self._start_line() def _copy_rest_of_line(self, chunk: str, start: int) -> int: """Emit chunk[start:] up to and including the next '\\n' once a line is known non-fence.""" kind = "text" if self.state == OUTSIDE_CODE else "code_chunk" newline_pos = chunk.find("\n", start) if newline_pos == -1: self._add_content(kind, chunk[start:]) return len(chunk) # Include the '\n' in the current content, then switch to pending for the next line start. self._add_content(kind, chunk[start:newline_pos + 1]) if self.state == OUTSIDE_CODE: self.state = PENDING_OPEN_FENCE else: self.state = PENDING_CLOSE_FENCE return newline_pos + 1Code `feed`, `flush`, and trace a split-delimiter stream
Look closely at the two sequential
ifblocks insideflush():- First, if we are in
PENDING_OPEN_FENCEorPENDING_CLOSE_FENCE,self._finish_line("")resolves the held line.- If the stream ended on
"```"inside a 3-backtick block,_finish_line("")emitscode_endand movesself.statetoPENDING_OPEN_FENCE. - If the stream ended on
"``"inside a 3-backtick block,_finish_line("")emits"``"ascode_chunkand leavesself.stateinPENDING_CLOSE_FENCE. - If the stream ended on
"```rust"(an opening fence with no newline),_finish_line("")emitscode_start("rust")and movesself.statetoPENDING_CLOSE_FENCE.
- If the stream ended on
- Second,
if self.state == INSIDE_CODE or self.state == PENDING_CLOSE_FENCE:checks whether the block is still open after Step 1 — if so, it appends{"type": "code_end"}! That handles unclosed blocks and newline-less"```rust"at EOF without ever emitting a duplicatecode_end.
def feed(self, chunk: str) -> List[Dict[str, str]]: """Process an incoming chunk of text and return zero or more events.""" i = 0 while i < len(chunk): # Fast path: once a line cannot be a fence, slice straight up to the next newline. if self.state == OUTSIDE_CODE or self.state == INSIDE_CODE: i = self._copy_rest_of_line(chunk, i) else: # Slow path at line start: inspect one character to see if a fence is still possible. self._scan_char(chunk[i]) i += 1 return self._take_events() def flush(self) -> List[Dict[str, str]]: """Signal the end of the stream and return the final events. The parser can then be reused.""" # Step 1: Resolve any buffered candidate line at EOF without adding a trailing newline. # Note: if this was a valid opening fence (e.g. "```rust"), _finish_line transitions # self.state to PENDING_CLOSE_FENCE so Step 2 below immediately closes the empty block. if self.state == PENDING_OPEN_FENCE or self.state == PENDING_CLOSE_FENCE: self._finish_line("") # Step 2: If a code block is still open at EOF, emit code_end so the UI never hangs in code mode. if self.state == INSIDE_CODE or self.state == PENDING_CLOSE_FENCE: self.events.append({"type": "code_end"}) events = self._take_events() self._reset() return eventsLet's trace Example 2 (
feed("~~"),feed("~\nlet x = 7;\n~~~~ "),flush()):Call Piece State before Action Returned events ------------------------- ------------ ------------------- --------------------------------------- ---------------------------- feed("~~") "~" PENDING_OPEN_FENCE run_char='~', run_len=1 (hold) "~" PENDING_OPEN_FENCE run_len=2 (hold) [] feed("~\nlet x = 7;\n~~~~ ") "~" PENDING_OPEN_FENCE run_len=3 (hold) "\n" PENDING_OPEN_FENCE run_len 3 >= 3 -> emit code_start("") fence=('~', 3), -> PENDING_CLOSE_FENCE "l" PENDING_CLOSE_FENCE 'l' != '~' -> _give_up_line() adds "l" -> INSIDE_CODE "et x = 7;\n" INSIDE_CODE slice up to '\n', merge -> "let x = 7;\n" -> PENDING_CLOSE_FENCE "~~~~ " PENDING_CLOSE_FENCE run_len=4 >= 3, trailing ' ' (hold!) [code_start(""), code_chunk("let x = 7;\n")] flush() EOF PENDING_CLOSE_FENCE _finish_line(""): run_len 4 >= 3 -> emit code_end, -> PENDING_OPEN_FENCE [code_end]- First, if we are in
Complete solution
from typing import Any, Dict, List OUTSIDE_CODE = "OUTSIDE_CODE" # normal text, middle of a line already ruled out as a fence PENDING_OPEN_FENCE = "PENDING_OPEN_FENCE" # start of a text line that could still become an opening fence INSIDE_CODE = "INSIDE_CODE" # code content, middle of a line already ruled out as a fence PENDING_CLOSE_FENCE = "PENDING_CLOSE_FENCE" # start of a code line that could still become a closing fence class StreamingCodeFenceParser: """Turns a stream of Markdown chunks into text / code_start / code_chunk / code_end events. Choices for points the rules leave open: - adjacent text or code_chunk pieces produced by one call are merged into one event; - language is the whole info string with surrounding whitespace removed; - indentation and the spaces after a closing fence must be spaces (a tab means "not a fence"); - at flush, an opening fence line with no newline still opens a block, and a block that is still open is closed with code_end, so a renderer never stays inside a code block. """ def __init__(self) -> None: self._reset() def feed(self, chunk: str) -> List[Dict[str, str]]: """Process an incoming chunk of text and return zero or more events.""" i = 0 while i < len(chunk): # Fast path: once a line cannot be a fence, slice straight up to the next newline. if self.state == OUTSIDE_CODE or self.state == INSIDE_CODE: i = self._copy_rest_of_line(chunk, i) else: # Slow path at line start: inspect one character to see if a fence is still possible. self._scan_char(chunk[i]) i += 1 return self._take_events() def flush(self) -> List[Dict[str, str]]: """Signal the end of the stream and return the final events. The parser can then be reused.""" # Step 1: Resolve any buffered candidate line at EOF without adding a trailing newline. # Note: if this was a valid opening fence (e.g. "```rust"), _finish_line transitions # self.state to PENDING_CLOSE_FENCE so Step 2 below immediately closes the empty block. if self.state == PENDING_OPEN_FENCE or self.state == PENDING_CLOSE_FENCE: self._finish_line("") # Step 2: If a code block is still open at EOF, emit code_end so the UI never hangs in code mode. if self.state == INSIDE_CODE or self.state == PENDING_CLOSE_FENCE: self.events.append({"type": "code_end"}) events = self._take_events() self._reset() return events def _reset(self) -> None: # Stream begins at column 0 of line 1 outside any code block. self.state = PENDING_OPEN_FENCE # fence_char / fence_len: opening delimiter (e.g. "`", 3) of the active code block. self.fence_char = "" self.fence_len = 0 # events: list of event dicts accumulated during the current feed() or flush() call. # While building, text/code_chunk "content" holds List[str] slices joined once in _take_events. self.events: List[Dict[str, Any]] = [] self._start_line() def _start_line(self) -> None: """Reset per-line candidate-fence state when starting a new line or giving up on one.""" self.line: List[str] = [] # raw chars held since the start of this line, e.g. [" ", "`", "`"] self.indent = 0 # count of leading ' ' spaces before the delimiter run (0..3 valid) self.run_char = "" # "`" or "~" once the delimiter run begins self.run_len = 0 # number of contiguous run_char characters at the start of the run self.run_over = False # True once any character after the delimiter run has appeared self.info: List[str] = [] # chars after an opening delimiter run, e.g. ["p", "y"] def _add_content(self, kind: str, content: str) -> None: if content == "": return # Merge adjacent pieces of the same event type within one call using a list of slices # so repeated appends stay O(total length) instead of O(length^2) string concatenation. if self.events and self.events[-1]["type"] == kind: self.events[-1]["content"].append(content) else: self.events.append({"type": kind, "content": [content]}) def _take_events(self) -> List[Dict[str, str]]: events = self.events self.events = [] for event in events: if "content" in event: event["content"] = "".join(event["content"]) return events def _copy_rest_of_line(self, chunk: str, start: int) -> int: """Emit chunk[start:] up to and including the next '\\n' once a line is known non-fence.""" kind = "text" if self.state == OUTSIDE_CODE else "code_chunk" newline_pos = chunk.find("\n", start) if newline_pos == -1: self._add_content(kind, chunk[start:]) return len(chunk) # Include the '\n' in the current content, then switch to pending for the next line start. self._add_content(kind, chunk[start:newline_pos + 1]) if self.state == OUTSIDE_CODE: self.state = PENDING_OPEN_FENCE else: self.state = PENDING_CLOSE_FENCE return newline_pos + 1 def _scan_char(self, ch: str) -> None: """Process one character while buffering a potential opening or closing fence line.""" if ch == "\n": self._finish_line("\n") return self.line.append(ch) if not self._still_possible(ch): self._give_up_line() def _still_possible(self, ch: str) -> bool: """Update candidate-fence counters for `ch`; return False as soon as a fence is impossible.""" closing = self.state == PENDING_CLOSE_FENCE # Phase 1: Before the delimiter run begins (0 to 3 leading spaces allowed, no tabs). if self.run_len == 0: if ch == " ": self.indent += 1 return self.indent <= 3 if ch != "`" and ch != "~": return False # A closing fence must use the exact same delimiter character that opened the block. if closing and ch != self.fence_char: return False self.run_char = ch self.run_len = 1 return True # Phase 2: Still inside the contiguous run of backticks or tildes. if ch == self.run_char and not self.run_over: self.run_len += 1 return True # Phase 3: First or later character after the delimiter run has ended. self.run_over = True if closing: # Closing fences require run_len >= opening fence_len and allow only trailing spaces. return self.run_len >= self.fence_len and ch == " " # Opening fences require at least 3 delimiters; backtick fences forbid '`' in info strings. if self.run_len < 3: return False if self.run_char == "`" and ch == "`": return False self.info.append(ch) return True def _give_up_line(self) -> None: """Flush buffered prefix immediately once the current line is proven not to be a fence.""" if self.state == PENDING_OPEN_FENCE: self._add_content("text", "".join(self.line)) self.state = OUTSIDE_CODE else: self._add_content("code_chunk", "".join(self.line)) self.state = INSIDE_CODE self._start_line() def _finish_line(self, newline: str) -> None: """Resolve a buffered candidate line on '\\n' (or '' at EOF during flush).""" if self.state == PENDING_OPEN_FENCE: if self.run_len >= 3: language = "".join(self.info).strip() self.events.append({"type": "code_start", "language": language}) self.fence_char = self.run_char self.fence_len = self.run_len # Next line starts inside the newly opened code block, watching for a closing fence. self.state = PENDING_CLOSE_FENCE else: # Fewer than 3 delimiters (e.g. "" or "``") before '\n' is ordinary text. self._add_content("text", "".join(self.line) + newline) else: # _still_possible already guaranteed matching fence_char and only spaces after the run. if self.run_len >= self.fence_len: self.events.append({"type": "code_end"}) self.state = PENDING_OPEN_FENCE else: self._add_content("code_chunk", "".join(self.line) + newline) self._start_line()✅ Submit now — all tests should pass.
Intuition & how it works
Think of the parser as a checkpoint inspector standing at the very start of each new line of incoming text: if the first character is a letter like "R", the line can never be a code fence, so the inspector immediately waves "R" and the entire rest of that line straight through to the screen until the next \n. Only when a line begins with 0–3 spaces followed by ` or ~ does the inspector hold those characters on a short side track until either a disqualifying character proves the line is ordinary content or a \n confirms the fence.
Two naive shortcuts fail in opposite ways. Emitting every character immediately fails when "~~" arrives in chunk 1 and "~\n" arrives in chunk 2, because you already emitted "~~" as plain text and cannot retract rendered UI events. Waiting for \n on every single line fixes correctness, but freezes long prose paragraphs until their newline arrives instead of streaming eagerly.
We track two facts with a finite state machine, or FSM (a small set of named modes with explicit rules for how each input switches modes): whether we are outside or inside a block, and whether the current line is still a fence candidate (PENDING_OPEN_FENCE, OUTSIDE_CODE, PENDING_CLOSE_FENCE, INSIDE_CODE). Let's trace Example 1 and an EOF close:
feed("Run query:\n```sq"):"R"immediately rules out an opening fence, so"Run query:\n"streams right out astext. After\n,"```sq"stays buffered inPENDING_OPEN_FENCE(run_len = 3,info = ['s', 'q']), returning[{"type": "text", "content": "Run query:\n"}].feed("l\nSELECT 42;\n```"):"l"extends the info string (the language metadata after an opening delimiter run, i.e., the contiguous sequence of fence characters), and\nemitscode_start("sql"). On the next line"S"is not`, so"SELECT 42;\n"streams immediately ascode_chunk, while trailing"```"is held inPENDING_CLOSE_FENCEin case a later chunk adds" x"(which would turn it into code rather than a closing fence).flush(): end-of-stream resolves the held"```"(run_len = 3 >= 3), emitting[{"type": "code_end"}].
Complexity
- Time: O(N) across the whole stream of N characters (amortized O(1) per character, meaning constant average work per character even when chunks split awkwardly). At line starts (
PENDING_*), each character updates integer/boolean counters in O(1) time without rescanningself.line; once a line is ruled out (OUTSIDE_CODE/INSIDE_CODE),str.find("\n", start)jumps across the rest of the line in one C-level scan, and accumulating slices in a list before a single"".join(...)copies each character only a constant number of times. - Space: O(L + M), where
Lis the length of the currently buffered candidate fence line andMis the size of the events returned by the currentfeed()call. Normal lines are flushed after 1–4 characters, soLis only non-trivial while reading an opening fence's info string or trailing spaces on a closing fence.
Edge cases
- Arbitrary chunk splits: Whether a fence arrives one byte per
feed()call ("","","","p","y","\n"`) or all in one document chunk, persistent FSM fields produce identical merged events. - Disqualified opening prefixes:
4leading spaces (" ```"), a leading tab ("\t```"), mixed delimiters ("~"), fewer than 3 delimiters ("``x"), or any`inside a backtick fence's info string ("```ab") are emitted astextas soon as the disqualifying character arrives. Under **CommonMark** (the standard Markdown specification),~fences *are* allowed to contain ``` and~in their info string ("~~~ ab ~"opens with language"ab ~"`). - Strict closing fence rules: Inside a block opened by
(`fence_len = 4`), `"```\n"` (too short), `"~~~~\n"` (wrong delimiter), `"\n"(4 spaces),"```` x\n"(trailing text), and"`\n"` (backtick after spaces) all stay `code_chunk`; `"\n"(3spaces,5 >= 4` backticks, trailing spaces) closes the block. - Empty blocks and blank lines:
"```\n```\n"emitscode_start("")followed directly bycode_endwith no emptycode_chunk, while blank lines inside a block emit"\n"ascode_chunk. - End-of-stream (
flush) combinations: Held"``"outside code flushes astext; held"``"inside a 3-backtick block flushes ascode_chunkfollowed bycode_end; held"```rust"without a newline emitscode_start("rust")followed immediately bycode_end; callingflush()resets internal state so the parser instance can be reused.
Common mistakes
- Flushing candidate prefixes at chunk boundaries. Emitting
"``"or"```py"just becausefeed()reached the end ofchunkbreaks streaming whenever a token split lands inside a fence line. - Buffering every line until
\n. Easy to code, but introduces visible UI lag on long prose lines that start with ordinary text. - Allowing
run_lento grow after spaces. Withoutself.run_over, a line like``` `or~~~ a ~mistakenly counts the later delimiter as part of the opening or closing run. - Attaching fence newlines to content (or eating code newlines). The
\nending an opening or closing fence line belongs to the fence, whereas the\nending the last line of code before a closing fence belongs tocode_chunk. - Repeated string concatenation (
buf += ch). Building held lines or merged event strings with+=in a loop can degrade toO(N^2)work on long inputs; append to alistand call"".join(...)once.
Follow-up questions
- How does the parser support fenced Markdown examples that embed 3-backtick snippets inside an outer 4-backtick block, and how could you highlight inner blocks too? Our parser already supports CommonMark fence nesting automatically because
self.fence_lenrecords the exact opening run length (4) and_still_possible/_finish_lineclose the block only when a matching delimiter line satisfiesself.run_len >= self.fence_len. Inside a 4-backtick block, inner```sqland```lines haverun_len == 3 < 4, so they stream verbatim insidecode_chunkwithout prematurely closing the outer block. If the client UI also wants recursive syntax highlighting for embedded snippets inside amarkdownblock, instantiate a secondaryStreamingCodeFenceParserwhenevercode_startreportslanguage in ("md", "markdown")and pipe the outer block'scode_chunkpayloads through that child parser.
text
Input: ````md\nsql\nSELECT 42;\n\n````\n
Events: code_start("md") -> code_chunk("sql\nSELECT 42;\n\n") -> code_end
-
When a network stream drops mid-generation inside an open fence, how should termination work so the client UI recovers cleanly? Wrap the stream-reading loop in a
try/finallyblock that unconditionally invokesparser.flush()on normal completion, cancellation, or socket error. Insideflush(), any incomplete buffered candidate line inside the block is emitted first as acode_chunk, followed automatically by{"type": "code_end"}, andself._reset()restores the state machine toPENDING_OPEN_FENCEso the renderer exits code-block mode and subsequent messages start fresh. If the UI wants to display an "incomplete snippet" indicator on aborted streams, attach a boolean field such as{"type": "code_end", "truncated": True}whenevercode_endis synthesized by Step 2 offlush()rather than a genuine closing fence. -
Which changes reduce heap allocations and copying overhead when incoming chunks span hundreds of kilobytes? Our implementation already avoids per-character Python loops on ordinary lines by jumping across newlines with C-speed
chunk.find("\n", start)and joining slice lists once perfeed()call. To cut memory traffic further on multi-hundred-kilobyte buffers, emit zero-copy(start_offset, end_offset)index spans intochunkwhenever adjacent pieces already lie contiguously in the input buffer, and scan line-start prefixes with a precompiledre.Patternin C rather than stepping through_scan_char. Finally, if untrusted streams might send a multi-megabyte line starting with```and no\n(causingself.infoto buffer unboundedly while checking for a disqualifying`), enforce a fixed info-string ceiling (such as1 KB) past which the parser abandons the fence candidate and flushes the prefix as plain text.
Alternative approaches
- Pure prefix-classifier function (
classify_line(buf)). Bufferself.lineas a string and re-run a stateless regex/helper on each new chunk to returnDEFINITE_FENCE,MAYBE_FENCE, orNOT_FENCE. This separates state transitions cleanly for unit testing, though re-scanningself.lineon single-character chunks costsO(L^2)on long candidate lines unless paired with incremental counters. - Line-buffered batch parser with a 1-line lookahead. Split strictly on
\nand hold only the incomplete tail after the last\n. Very compact (~30 lines of code) and fine when chunks arrive line by line, but violates early-emission requirements whenever long prose lines stream token by token.
Follow-up questions
- How does the parser support fenced Markdown examples that embed 3-backtick snippets inside an outer 4-backtick block, and how could you highlight inner blocks too?
- When a network stream drops mid-generation inside an open fence, how should termination work so the client UI recovers cleanly?
- Which changes reduce heap allocations and copying overhead when incoming chunks span hundreds of kilobytes?
Similar questions
- Directory Snapshot Merkle Tree with Path Hashing and Subtree Diffing
- Repository Merkle Hashing and Incremental Tree Diff
- Subtree-Pruned Workspace Diffing with Merkle Trees
- Binary Merkle Tree Construction and Inclusion Proofs
- Incremental Merkle Hashing for Virtual Directories
- Linking Career Turning Points to an Architectural Deep Dive
More Cursor interview questions
- Directory Snapshot Merkle Tree with Path Hashing and Subtree Diffing Medium
- Directory-Hierarchy Merkle Tree for Repository Diffing Hard
- Linking Career Turning Points to an Architectural Deep Dive Medium Pro
- Design a Hierarchical Sliding-Window Notification Rate Limiter Medium Pro
- Distributed Multi-Scope IDE Configuration Sync Medium Pro
- Fault-Tolerant Recurring Job Scheduler Medium Pro
- Repository Merkle Hashing and Incremental Tree Diff Medium Pro
- Incremental Merkle Hashing for Virtual Directories Medium Pro
- Subtree-Pruned Workspace Diffing with Merkle Trees Medium Pro
- Binary Merkle Tree Construction and Inclusion Proofs Medium Pro