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

  1. Opening fence line:
    • Begins at position 0 of the stream or right after a newline (\n).
    • May start with 0 to 3 space characters (' '), which are discarded; 4 or more leading spaces or any tab ('\t') disqualifies the line as a fence.
    • Continues with an unbroken run of at least 3 backticks (`) or at least 3 tildes (~). Mixing ` and ~ within the delimiter run is not valid.
    • Everything after that delimiter run up to \n (or end of stream during flush()), trimmed of leading and trailing whitespace, forms the block's language info 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.
  2. Code block body:
    • Consists of all characters following the opening fence line's \n up to the start of a valid closing fence line (or end of stream).
  3. Closing fence line:
    • Begins right after \n with 0 to 3 leading ' ' 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 \n or end of stream; any non-space character (including tabs or info text) makes the line ordinary code content instead.
  4. 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 (language is "" 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 by flush().

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, achieving O(N) total processing time across N streamed characters.

Step-by-step walkthrough

  1. 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 through sql. Our parser accepts arbitrary string slices via feed(chunk) and must emit structured events (text, code_start, code_chunk, code_end) as soon as safe, resolving any remaining state when flush() 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, with 0 to 3 leading ' ' spaces (a \t tab or a 4th space disqualifies it), followed by a contiguous delimiter run of 3 or more ` characters or 3 or more ~ characters (never mixed). Everything after the run on that line, trimmed of leading and trailing whitespace, becomes language (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 0 to 3 leading ' ' 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 \n or end of stream (no info string allowed).
    • Newline ownership and merging: The \n ending an opening or closing fence line is consumed by the fence itself, whereas the \n at the end of a normal code line belongs to code_chunk (so "SELECT 42;\n```\n" emits code_chunk "SELECT 42;\n"). Adjacent text pieces (or code_chunk pieces) produced within one feed/flush call 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), emits code_end if a block is still open so the UI never gets stuck inside code mode, and resets the parser for reuse.
  2. Why both "emit immediately" and "wait for every newline" fail

    Before designing our parser, look at why the two most tempting shortcuts break:

    1. Emitting every character immediately fails correctness. Suppose feed("~~") arrives first. If we emit "~~" as text, 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.
    2. Buffering every line until \n fails 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!

  3. 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:

    1. Are we currently outside or inside a fenced code block?
    2. 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 × 2 gives 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_FENCE
    

    While 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 out
    
  4. Code 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 in PENDING_OPEN_FENCE.
    • Inside _add_content, notice how we store event["content"] temporarily as a Python list of string slices (["l", "et x = 7;\n"]) and call "".join(...) once at the end of the call in _take_events(). Repeatedly doing s = s + ch in 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 linear O(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
    
  5. Code the character-by-character fence prefix scanner

    In a pending state, _scan_char(ch) checks for "\n" first; otherwise it appends ch to self.line and asks _still_possible(ch) whether the line can still be a valid fence.

    Look carefully at self.run_over in Phase 2 and Phase 3 of _still_possible: once any character after the opening delimiter run appears (say the space in ~~~ a ~), self.run_over flips to True. Without that boolean, the later ~ inside the info string a ~ would match ch == self.run_char and falsely bump self.run_len from 3 to 4! Similarly, on a closing line like ``` `, self.run_over ensures the backtick after the spaces is treated as a post-run character (ch == " " is False), 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 True
    
  6. Code line resolution and fast mid-line slicing

    Now let's handle the three ways a line moves forward:

    1. _give_up_line(): Called the instant _still_possible returns False. Emits everything held in self.line as "text" or "code_chunk", switches to OUTSIDE_CODE or INSIDE_CODE, and clears self.line.
    2. _finish_line(newline): Called when "\n" arrives (with newline="\n") or at end-of-stream flush() (with newline=""). Because _still_possible already rejected every illegal character mid-line, we only need to check whether self.run_len reached the required minimum (>= 3 to open, >= self.fence_len to close)! If self.run_len fell short (for example, an empty line "" or just "``" before "\n"), we emit the held characters plus newline as normal content and stay in the same pending state for the next line.
    3. _copy_rest_of_line(chunk, start): Once in OUTSIDE_CODE or INSIDE_CODE, we use C-speed chunk.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 + 1
    
  7. Code `feed`, `flush`, and trace a split-delimiter stream

    Look closely at the two sequential if blocks inside flush():

    1. First, if we are in PENDING_OPEN_FENCE or PENDING_CLOSE_FENCE, self._finish_line("") resolves the held line.
      • If the stream ended on "```" inside a 3-backtick block, _finish_line("") emits code_end and moves self.state to PENDING_OPEN_FENCE.
      • If the stream ended on "``" inside a 3-backtick block, _finish_line("") emits "``" as code_chunk and leaves self.state in PENDING_CLOSE_FENCE.
      • If the stream ended on "```rust" (an opening fence with no newline), _finish_line("") emits code_start("rust") and moves self.state to PENDING_CLOSE_FENCE.
    2. 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 duplicate code_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 events
    

    Let'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]
    
  8. 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:

  1. feed("Run query:\n```sq"): "R" immediately rules out an opening fence, so "Run query:\n" streams right out as text. After \n, "```sq" stays buffered in PENDING_OPEN_FENCE (run_len = 3, info = ['s', 'q']), returning [{"type": "text", "content": "Run query:\n"}].
  2. 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 \n emits code_start("sql"). On the next line "S" is not `, so "SELECT 42;\n" streams immediately as code_chunk, while trailing "```" is held in PENDING_CLOSE_FENCE in case a later chunk adds " x" (which would turn it into code rather than a closing fence).
  3. 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 rescanning self.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 L is the length of the currently buffered candidate fence line and M is the size of the events returned by the current feed() call. Normal lines are flushed after 1–4 characters, so L is 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: 4 leading 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" emits code_start("") followed directly by code_end with no empty code_chunk, while blank lines inside a block emit "\n" as code_chunk.
  • End-of-stream (flush) combinations: Held "``" outside code flushes as text; held "``" inside a 3-backtick block flushes as code_chunk followed by code_end; held "```rust" without a newline emits code_start("rust") followed immediately by code_end; calling flush() resets internal state so the parser instance can be reused.

Common mistakes

  • Flushing candidate prefixes at chunk boundaries. Emitting "``" or "```py" just because feed() reached the end of chunk breaks 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_len to grow after spaces. Without self.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 \n ending an opening or closing fence line belongs to the fence, whereas the \n ending the last line of code before a closing fence belongs to code_chunk.
  • Repeated string concatenation (buf += ch). Building held lines or merged event strings with += in a loop can degrade to O(N^2) work on long inputs; append to a list and 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_len records the exact opening run length (4) and _still_possible / _finish_line close the block only when a matching delimiter line satisfies self.run_len >= self.fence_len. Inside a 4-backtick block, inner ```sql and ``` lines have run_len == 3 < 4, so they stream verbatim inside code_chunk without prematurely closing the outer block. If the client UI also wants recursive syntax highlighting for embedded snippets inside a markdown block, instantiate a secondary StreamingCodeFenceParser whenever code_start reports language in ("md", "markdown") and pipe the outer block's code_chunk payloads 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 / finally block that unconditionally invokes parser.flush() on normal completion, cancellation, or socket error. Inside flush(), any incomplete buffered candidate line inside the block is emitted first as a code_chunk, followed automatically by {"type": "code_end"}, and self._reset() restores the state machine to PENDING_OPEN_FENCE so 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} whenever code_end is synthesized by Step 2 of flush() 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 per feed() call. To cut memory traffic further on multi-hundred-kilobyte buffers, emit zero-copy (start_offset, end_offset) index spans into chunk whenever adjacent pieces already lie contiguously in the input buffer, and scan line-start prefixes with a precompiled re.Pattern in C rather than stepping through _scan_char. Finally, if untrusted streams might send a multi-megabyte line starting with ``` and no \n (causing self.info to buffer unboundedly while checking for a disqualifying `), enforce a fixed info-string ceiling (such as 1 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)). Buffer self.line as a string and re-run a stateless regex/helper on each new chunk to return DEFINITE_FENCE, MAYBE_FENCE, or NOT_FENCE. This separates state transitions cleanly for unit testing, though re-scanning self.line on single-character chunks costs O(L^2) on long candidate lines unless paired with incremental counters.
  • Line-buffered batch parser with a 1-line lookahead. Split strictly on \n and 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

Similar questions

More Cursor interview questions

All 11 Cursor questions →