Something went wrong. Try again.
My version of https://github.com/vercel-labs/fx
Something went wrong. Try again.
Zig
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422const std = @import("std");const Allocator = std.mem.Allocator;
const display_width = @import("../shared/display_width.zig");const ansi = @import("presentation/ansi.zig");const tu = @import("presentation/text_util.zig");const bp = @import("presentation/block_parse.zig");const payload = @import("presentation/payload.zig");const inline_render = @import("presentation/inline_render.zig");const block_render = @import("presentation/block_render.zig");
/// Prevents OSC 8 hyperlinks from coalescing across wrapped terminal rows.var link_id_counter: u32 = 1;
pub const setInlineCodeTheme = ansi.setInlineCodeTheme;pub const writeHorizontalRule = ansi.writeHorizontalRule;
pub const TableColumnAlign = payload.TableColumnAlign;pub const TableRow = payload.TableRow;pub const TablePayload = payload.TablePayload;pub const CodeBlockPayload = payload.CodeBlockPayload;pub const TableCompletion = payload.TableCompletion;pub const CodeBlockCompletion = payload.CodeBlockCompletion;pub const ThematicRuleCompletion = payload.ThematicRuleCompletion;pub const MarkdownCompletions = payload.MarkdownCompletions;
/// Allocator-owned assistant output queued for root or child presentation.pub const Event = union(enum) { text: []u8, table: TablePayload, code_block: CodeBlockPayload, thematic_rule,
pub fn clone(self: Event, alloc: Allocator) Allocator.Error!Event { return switch (self) { .text => |text| .{ .text = try alloc.dupe(u8, text) }, .table => |table| .{ .table = try table.clone(alloc) }, .code_block => |block| .{ .code_block = try block.clone(alloc) }, .thematic_rule => .thematic_rule, }; }
pub fn requiresTextDrain(self: Event) bool { return switch (self) { .text => false, .table, .code_block, .thematic_rule => true, }; }
pub fn retainedByteCount(self: Event) usize { return switch (self) { .text => |text| text.len, .table => |table| blk: { var total: usize = table.alignments.len; for (table.rows) |row| { total +|= row.cells.len * @sizeOf([]u8); for (row.cells) |cell| total +|= cell.len; } break :blk total; }, .code_block => |block| block.language.len +| block.code.len, .thematic_rule => 1, }; }
pub fn deinit(self: *Event, alloc: Allocator) void { switch (self.*) { .text => |text| alloc.free(text), .table => |*table| table.deinit(alloc), .code_block => |*block| block.deinit(alloc), .thematic_rule => {}, } self.* = undefined; }};
pub const renderCodeBlockPayload = block_render.renderCodeBlockPayload;pub const renderTablePayload = block_render.renderTablePayload;pub const writeTableHeaderCell = block_render.writeTableHeaderCell;
pub fn parseTablePayload(alloc: Allocator, buf: []const u8) !payload.TablePayload { return block_render.parseTablePayload(alloc, buf, &link_id_counter);}
test "assistant presentation event clone owns nested payloads" { const alloc = std.testing.allocator;
var text_source = [_]u8{ 'o', 'k' }; var text = try (Event{ .text = &text_source }).clone(alloc); defer text.deinit(alloc); text_source[0] = 'x'; try std.testing.expectEqualStrings("ok", text.text);
var block_source = [_]u8{ 'z', 'i', 'g' }; var block = try (Event{ .code_block = .{ .language = @constCast("zig"), .code = &block_source, } }).clone(alloc); defer block.deinit(alloc); block_source[0] = 'b'; try std.testing.expectEqualStrings("zig", block.code_block.language); try std.testing.expectEqualStrings("zig", block.code_block.code);
var table = try parseTablePayload(alloc, "| Name |\n|---|\n| api |\n"); defer table.deinit(alloc); const source_cell = table.rows[1].cells[0].ptr; var table_event = try (Event{ .table = table }).clone(alloc); defer table_event.deinit(alloc); try std.testing.expectEqualStrings("api", table_event.table.rows[1].cells[0]); try std.testing.expect(table_event.table.rows[1].cells[0].ptr != source_cell); try std.testing.expect(!(Event{ .text = @constCast("text") }).requiresTextDrain()); try std.testing.expect((Event{ .table = table }).requiresTextDrain()); try std.testing.expect(@as(Event, .thematic_rule).requiresTextDrain()); try std.testing.expectEqual(@as(usize, 1), @as(Event, .thematic_rule).retainedByteCount());}
const isPipeLine = bp.isPipeLine;const max_link_url_bytes = ansi.max_link_url_bytes;const horizontal_rule_width = ansi.horizontal_rule_width;const dim_open = ansi.dim_open;const dim_close = ansi.dim_close;const table_horiz = ansi.table_horiz;
const Footnote = struct { label: []u8, number: ?usize = null, body: std.ArrayList(u8) = .empty, has_definition: bool = false,
fn deinit(self: *Footnote, alloc: Allocator) void { alloc.free(self.label); self.body.deinit(alloc); }};
const ActiveFootnote = struct { index: usize, append_body: bool,};
pub const MarkdownProcessor = struct { line_buf: std.ArrayList(u8) = .empty, pending_top_level_line: std.ArrayList(u8) = .empty, pipe_buf: std.ArrayList(u8) = .empty, code_buf: std.ArrayList(u8) = .empty, code_language: std.ArrayList(u8) = .empty, in_code_block: bool = false, code_fence_marker: ?u8 = null, in_pipe_block: bool = false, pipe_last_line_has_lf: bool = false, active_blockquote: ?bp.BlockquotePrefix = null, active_definition: bool = false, footnotes: std.ArrayList(Footnote) = .empty, active_footnote: ?ActiveFootnote = null, next_footnote_number: usize = 0, previous_line_was_blank: bool = true,
pub fn deinit(self: *MarkdownProcessor, alloc: Allocator) void { self.line_buf.deinit(alloc); self.pending_top_level_line.deinit(alloc); self.pipe_buf.deinit(alloc); self.code_buf.deinit(alloc); self.code_language.deinit(alloc); self.deinitFootnotes(alloc); }
pub fn reset(self: *MarkdownProcessor, alloc: Allocator) void { self.line_buf.clearAndFree(alloc); self.pending_top_level_line.clearAndFree(alloc); self.pipe_buf.clearAndFree(alloc); self.code_buf.clearAndFree(alloc); self.code_language.clearAndFree(alloc); self.deinitFootnotes(alloc); self.in_code_block = false; self.code_fence_marker = null; self.in_pipe_block = false; self.pipe_last_line_has_lf = false; self.active_blockquote = null; self.active_definition = false; self.active_footnote = null; self.next_footnote_number = 0; self.previous_line_was_blank = true; }
pub fn push(self: *MarkdownProcessor, alloc: Allocator, input: []const u8, out: *std.ArrayList(u8)) !void { try self.pushWithCompletions(alloc, input, out, .{}); }
pub fn pushWithTableCompletion( self: *MarkdownProcessor, alloc: Allocator, input: []const u8, out: *std.ArrayList(u8), completion: ?*const payload.TableCompletion, ) !void { try self.pushWithCompletions(alloc, input, out, .{ .table = completion }); }
pub fn pushWithCompletions( self: *MarkdownProcessor, alloc: Allocator, input: []const u8, out: *std.ArrayList(u8), completions: payload.MarkdownCompletions, ) !void { for (input) |byte| { if (byte == '\n') { const line_end = self.line_buf.items.len - @intFromBool( self.line_buf.items.len > 0 and self.line_buf.items[self.line_buf.items.len - 1] == '\r', ); try self.handleLine(alloc, self.line_buf.items[0..line_end], true, out, completions); self.line_buf.clearRetainingCapacity(); } else { try self.line_buf.append(alloc, byte); } } }
/// Rebuilds structural Markdown state from source that is already visible. /// Buffered bytes are discarded so later chunks emit only new content. pub fn restorePresentedPrefix( self: *MarkdownProcessor, alloc: Allocator, source: []const u8, ) !void { self.reset(alloc); var discarded: std.ArrayList(u8) = .empty; defer discarded.deinit(alloc);
try self.push(alloc, source, &discarded); if (self.line_buf.items.len > 0) { try self.handleLine( alloc, self.line_buf.items, false, &discarded, .{}, ); self.line_buf.clearRetainingCapacity(); } self.pending_top_level_line.clearRetainingCapacity(); self.pipe_buf.clearRetainingCapacity(); self.in_pipe_block = false; self.pipe_last_line_has_lf = false; self.code_buf.clearRetainingCapacity(); }
pub fn flush(self: *MarkdownProcessor, alloc: Allocator, out: *std.ArrayList(u8)) !void { try self.flushWithCompletions(alloc, out, .{}); }
pub fn flushWithTableCompletion( self: *MarkdownProcessor, alloc: Allocator, out: *std.ArrayList(u8), completion: ?*const payload.TableCompletion, ) !void { try self.flushWithCompletions(alloc, out, .{ .table = completion }); }
pub fn flushWithCompletions( self: *MarkdownProcessor, alloc: Allocator, out: *std.ArrayList(u8), completions: payload.MarkdownCompletions, ) !void { defer self.active_blockquote = null; defer self.active_definition = false; defer self.active_footnote = null; const had_partial_line = self.line_buf.items.len > 0; const len_before = out.items.len; if (self.line_buf.items.len > 0) { try self.handleLine(alloc, self.line_buf.items, false, out, completions); self.line_buf.clearRetainingCapacity(); } try self.flushPendingTopLevelLine(alloc, out); if (had_partial_line and out.items.len > len_before and out.items[out.items.len - 1] == '\n') { out.items.len -= 1; } if (self.in_pipe_block) try self.finalizePipeBlock(alloc, out, completions.table); if (self.in_code_block) { try self.finalizeCodeBlock(alloc, out, completions.code); self.in_code_block = false; self.code_fence_marker = null; } try self.flushFootnotes(alloc, out); }
fn handleLine( self: *MarkdownProcessor, alloc: Allocator, line: []const u8, line_has_lf: bool, out: *std.ArrayList(u8), completions: payload.MarkdownCompletions, ) !void { const fs = self.footnoteSink(); defer self.previous_line_was_blank = tu.isBlankMarkdownLine(line);
if (self.in_code_block) { self.active_definition = false; if (self.code_fence_marker) |marker| { if (bp.codeFenceMarker(tu.leftTrim(line)) == marker) { try self.finalizeCodeBlock(alloc, out, completions.code); self.in_code_block = false; self.code_fence_marker = null; return; } } else if (!tu.isBlankMarkdownLine(line) and !bp.hasIndentedCodePrefix(line)) { try self.finalizeCodeBlock(alloc, out, completions.code); self.in_code_block = false; try self.handleLine(alloc, line, line_has_lf, out, completions); return; } const code_line = if (self.code_fence_marker == null and !tu.isBlankMarkdownLine(line)) bp.deindentCodeLine(line) else line; try self.appendCodeLine(alloc, code_line, line_has_lf, out, completions.code); return; }
if (self.in_pipe_block) { self.active_definition = false; if (bp.isPipeLine(line) and self.pipe_buf.items.len + line.len + 1 <= ansi.max_pipe_buffer_bytes) { try self.pipe_buf.appendSlice(alloc, line); try self.pipe_buf.append(alloc, '\n'); self.pipe_last_line_has_lf = line_has_lf; return; } try self.finalizePipeBlock(alloc, out, completions.table); }
if (self.active_footnote) |active| { if (bp.footnoteContinuationBody(line)) |body| { if (active.append_body) { var note = &self.footnotes.items[active.index]; try note.body.append(alloc, '\n'); try note.body.appendSlice(alloc, body); } return; } self.active_footnote = null; }
if (bp.parseFootnoteDefinition(line)) |definition| { self.active_definition = false; try self.flushPendingTopLevelLine(alloc, out); try self.beginFootnoteDefinition(alloc, definition); return; }
if (completions.thematic_rule != null and self.pending_top_level_line.items.len > 0) { if (bp.parseSetextUnderline(line)) |level| { self.active_definition = false; try block_render.writeHeading(alloc, level, tu.withoutTerminalHardBreakMarker(self.pending_top_level_line.items, true), out, &fs, &link_id_counter); try out.append(alloc, '\n'); self.pending_top_level_line.clearRetainingCapacity(); return; } if (bp.definitionMarkerBody(line)) |body| { try self.flushPendingTopLevelLine(alloc, out); try block_render.writeDefinitionLine(alloc, body, line_has_lf, out, &fs, &link_id_counter); self.active_definition = true; return; } self.active_definition = false; try self.flushPendingTopLevelLine(alloc, out); }
if (self.active_blockquote) |blockquote| { self.active_definition = false; if (bp.isLazyBlockquoteContinuation(line)) { try block_render.writeBlockquoteLine(alloc, blockquote, line, line_has_lf, out, &fs, &link_id_counter); try out.append(alloc, '\n'); return; } self.active_blockquote = null; }
if (bp.hasIndentedCodePrefix(line) and (bp.parseUnorderedList(line) != null or bp.parseOrderedList(line) != null)) { self.active_definition = false; try self.processLine(alloc, line, line_has_lf, out); try out.append(alloc, '\n'); return; }
if (self.previous_line_was_blank and bp.hasIndentedCodePrefix(line)) { self.active_definition = false; self.in_code_block = true; self.code_fence_marker = null; self.code_language.clearRetainingCapacity(); try self.appendCodeLine(alloc, bp.deindentCodeLine(line), line_has_lf, out, completions.code); return; }
if (!self.in_code_block and bp.isPipeLine(line)) { self.active_definition = false; self.in_pipe_block = true; try self.pipe_buf.appendSlice(alloc, line); try self.pipe_buf.append(alloc, '\n'); self.pipe_last_line_has_lf = line_has_lf; return; }
if (bp.codeFenceMarker(tu.leftTrim(line))) |marker| { self.active_definition = false; self.in_code_block = true; self.code_fence_marker = marker; self.code_language.clearRetainingCapacity(); try self.code_language.appendSlice(alloc, bp.codeFenceLanguage(tu.leftTrim(line))); return; }
if (self.active_definition) { if (bp.definitionMarkerBody(line)) |body| { try block_render.writeDefinitionLine(alloc, body, line_has_lf, out, &fs, &link_id_counter); return; } } self.active_definition = false;
if (line_has_lf and completions.thematic_rule != null and bp.isSetextCandidate(line)) { try self.pending_top_level_line.appendSlice(alloc, line); return; }
if (bp.isHorizontalRule(line)) { if (completions.thematic_rule) |completion| { try completion.deliver(completion.ctx, out); return; } }
try self.processLine(alloc, line, line_has_lf, out); try out.append(alloc, '\n'); }
fn appendCodeLine( self: *MarkdownProcessor, alloc: Allocator, line: []const u8, line_has_lf: bool, out: *std.ArrayList(u8), completion: ?*const payload.CodeBlockCompletion, ) !void { if (completion != null) { try self.code_buf.appendSlice(alloc, line); try self.code_buf.append(alloc, '\n'); return; } try self.processLine(alloc, line, line_has_lf, out); try out.append(alloc, '\n'); }
fn flushPendingTopLevelLine(self: *MarkdownProcessor, alloc: Allocator, out: *std.ArrayList(u8)) !void { if (self.pending_top_level_line.items.len == 0) return; try self.processLine(alloc, self.pending_top_level_line.items, true, out); try out.append(alloc, '\n'); self.pending_top_level_line.clearRetainingCapacity(); }
fn processLine( self: *MarkdownProcessor, alloc: Allocator, line: []const u8, line_has_lf: bool, out: *std.ArrayList(u8), ) !void { const fs = self.footnoteSink(); if (self.in_code_block) { try ansi.writeDim(alloc, out, ansi.vertical_rule_prefix); try out.appendSlice(alloc, line); return; }
if (bp.isHorizontalRule(line)) { try ansi.writeHorizontalRule(alloc, out); return; }
if (bp.parseHeader(line)) |header| { try block_render.writeHeading(alloc, header.level, tu.withoutTerminalHardBreakMarker(header.content, line_has_lf), out, &fs, &link_id_counter); return; }
if (bp.parseBlockquote(line)) |parsed| { const blockquote = bp.BlockquotePrefix{ .indent = parsed.indent.len, .depth = parsed.depth, }; self.active_blockquote = if (bp.isBlockquoteParagraph(parsed.content)) blockquote else null; try block_render.writeBlockquoteLine(alloc, blockquote, parsed.content, line_has_lf, out, &fs, &link_id_counter); return; }
if (bp.parseUnorderedList(line)) |parsed| { try out.appendSlice(alloc, parsed.indent); if (bp.parseTaskListItem(parsed.content)) |task| { try block_render.writeTaskListMarker(alloc, out, task); try inline_render.writeInline(alloc, tu.withoutTerminalHardBreakMarker(task.content, line_has_lf), out, false, &fs, &link_id_counter); return; } try ansi.writeDim(alloc, out, ansi.bullet_marker); try inline_render.writeInline(alloc, tu.withoutTerminalHardBreakMarker(parsed.content, line_has_lf), out, false, &fs, &link_id_counter); return; }
if (bp.parseOrderedList(line)) |parsed| { try out.appendSlice(alloc, parsed.indent); try ansi.writeDim(alloc, out, parsed.marker); try out.append(alloc, ' '); if (bp.parseTaskListItem(parsed.content)) |task| { try block_render.writeTaskListMarker(alloc, out, task); try inline_render.writeInline(alloc, tu.withoutTerminalHardBreakMarker(task.content, line_has_lf), out, false, &fs, &link_id_counter); return; } try inline_render.writeInline(alloc, tu.withoutTerminalHardBreakMarker(parsed.content, line_has_lf), out, false, &fs, &link_id_counter); return; }
try inline_render.writeInline(alloc, tu.withoutTerminalHardBreakMarker(line, line_has_lf), out, false, &fs, &link_id_counter); }
fn finalizePipeBlock( self: *MarkdownProcessor, alloc: Allocator, out: *std.ArrayList(u8), completion: ?*const payload.TableCompletion, ) !void { const fs = self.footnoteSink(); defer { self.pipe_buf.clearRetainingCapacity(); self.in_pipe_block = false; self.pipe_last_line_has_lf = false; }
if (bp.isValidTable(self.pipe_buf.items)) { if (completion) |sink| { var table = try block_render.parseTablePayloadWithFootnotes(alloc, self.pipe_buf.items, &fs, &link_id_counter); var delivered = false; errdefer if (!delivered) table.deinit(alloc); try sink.deliver(sink.ctx, table, out); delivered = true; return; } try block_render.renderTable(alloc, self.pipe_buf.items, out, &fs, &link_id_counter); return; }
var start: usize = 0; while (start < self.pipe_buf.items.len) { const end = std.mem.indexOfScalarPos(u8, self.pipe_buf.items, start, '\n') orelse self.pipe_buf.items.len; const line_has_lf = if (end + 1 == self.pipe_buf.items.len) self.pipe_last_line_has_lf else true; try self.processLine(alloc, self.pipe_buf.items[start..end], line_has_lf, out); if (line_has_lf) try out.append(alloc, '\n'); start = end + 1; } }
fn finalizeCodeBlock( self: *MarkdownProcessor, alloc: Allocator, out: *std.ArrayList(u8), completion: ?*const payload.CodeBlockCompletion, ) !void { defer { self.code_buf.clearRetainingCapacity(); self.code_language.clearRetainingCapacity(); }
const sink = completion orelse return; var language: ?[]u8 = try alloc.dupe(u8, self.code_language.items); errdefer if (language) |owned| alloc.free(owned); const code = try alloc.dupe(u8, self.code_buf.items); var block = payload.CodeBlockPayload{ .language = language.?, .code = code, }; language = null; var delivered = false; errdefer if (!delivered) block.deinit(alloc); try sink.deliver(sink.ctx, block, out); delivered = true; }
fn deinitFootnotes(self: *MarkdownProcessor, alloc: Allocator) void { for (self.footnotes.items) |*note| note.deinit(alloc); self.footnotes.clearAndFree(alloc); }
fn findOrAppendFootnote(self: *MarkdownProcessor, alloc: Allocator, label: []const u8) !usize { for (self.footnotes.items, 0..) |note, index| { if (std.mem.eql(u8, note.label, label)) return index; }
const owned_label = try alloc.dupe(u8, label); errdefer alloc.free(owned_label); try self.footnotes.append(alloc, .{ .label = owned_label }); return self.footnotes.items.len - 1; }
fn footnoteSink(self: *MarkdownProcessor) payload.FootnoteSink { return .{ .ctx = self, .register = registerFootnoteThunk }; }
fn registerFootnoteReference(self: *MarkdownProcessor, alloc: Allocator, label: []const u8) !usize { const index = try self.findOrAppendFootnote(alloc, label); if (self.footnotes.items[index].number == null) { self.next_footnote_number += 1; self.footnotes.items[index].number = self.next_footnote_number; } return self.footnotes.items[index].number.?; }
fn beginFootnoteDefinition( self: *MarkdownProcessor, alloc: Allocator, definition: bp.ParsedFootnoteDefinition, ) !void { const index = try self.findOrAppendFootnote(alloc, definition.label); const note = &self.footnotes.items[index]; if (note.has_definition) { self.active_footnote = .{ .index = index, .append_body = false }; return; } try note.body.appendSlice(alloc, definition.body); note.has_definition = true; self.active_footnote = .{ .index = index, .append_body = true }; }
fn flushFootnotes(self: *MarkdownProcessor, alloc: Allocator, out: *std.ArrayList(u8)) !void { const fs = self.footnoteSink(); defer self.deinitFootnotes(alloc); defer self.next_footnote_number = 0;
var has_note = false; for (self.footnotes.items) |note| { if (note.number != null and note.has_definition) { has_note = true; break; } } if (!has_note) return;
while (out.items.len > 0 and out.items[out.items.len - 1] == '\n') { out.items.len -= 1; } if (out.items.len > 0) { try out.appendSlice(alloc, "\n\n"); } else { try out.append(alloc, '\n'); }
var number: usize = 1; while (number <= self.next_footnote_number) : (number += 1) { for (self.footnotes.items) |*note| { if (note.number != number or !note.has_definition) continue; try block_render.writeFootnoteDefinitionMarker(alloc, out, number); try block_render.writeFootnoteBody(alloc, note.body.items, out, &fs, number, &link_id_counter); break; } } }};
fn registerFootnoteThunk(ctx: *anyopaque, alloc: Allocator, label: []const u8) anyerror!usize { const self: *MarkdownProcessor = @ptrCast(@alignCast(ctx)); return self.registerFootnoteReference(alloc, label);}
test "markdown link is blue and underlined inside its OSC 8 scope" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push(alloc, "see [docs](https://example.com) please\n", &out);
var expected_buf: [256]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "see \x1b]8;id=fx-{d};https://example.com\x1b\\\x1b[4mdocs\x1b[24m\x1b]8;;\x1b\\ please\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "markdown image renders its alt text with an image marker inside one OSC 8 scope" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push(alloc, "see  please\n", &out);
var expected_buf: [512]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "see \x1b]8;id=fx-{d};https://example.com/diagram.png\x1b\\\x1b[4m▧ architecture diagram\x1b[24m\x1b]8;;\x1b\\ please\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "markdown image uses a stable fallback for empty alt text" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push(alloc, "\n", &out);
var expected_buf: [256]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "\x1b]8;id=fx-{d};https://example.com/diagram.png\x1b\\\x1b[4m▧ image\x1b[24m\x1b]8;;\x1b\\\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "markdown image unescapes alt punctuation through the existing link emitter" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push(alloc, "\n", &out);
var expected_buf: [256]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "\x1b]8;id=fx-{d};https://example.com/diagram.png\x1b\\\x1b[4m▧ architecture *diagram*\x1b[24m\x1b]8;;\x1b\\\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "escaped and malformed markdown images remain literal without OSC 8" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "\\ and \\!\n", &out); try std.testing.expectEqualStrings(" and !\n", out.items); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;") == null);
out.clearRetainingCapacity(); try processor.push(alloc, "; try std.testing.expectEqualStrings("; try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;") == null);
out.clearRetainingCapacity(); try processor.push(alloc, "\n", &out); try std.testing.expectEqualStrings("\n", out.items); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;") == null);
var oversized_url: [max_link_url_bytes + 1]u8 = undefined; @memset(&oversized_url, 'a'); var input_buf: [max_link_url_bytes + 16]u8 = undefined; const oversized = try std.fmt.bufPrint(&input_buf, "\n", .{oversized_url[0..]}); out.clearRetainingCapacity(); try processor.push(alloc, oversized, &out); try std.testing.expectEqualStrings(oversized, out.items); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;") == null);}
test "markdown images preserve code isolation, chunk buffering, and heading underline" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "``\n", &out); try std.testing.expectEqualStrings( "\x1b[38;5;245m\x1b[39m\n", out.items, ); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;") == null);
out.clearRetainingCapacity(); try processor.push(alloc, "\n", &out); try std.testing.expect(std.mem.indexOf(u8, out.items, "▧ architecture") != null);
out.clearRetainingCapacity(); const id_before = link_id_counter; try processor.push(alloc, "### before  after\n", &out); var expected_buf: [512]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "\x1b[4mbefore \x1b]8;id=fx-{d};https://example.com/diagram.png\x1b\\\x1b[4m▧ diagram\x1b[24m\x1b]8;;\x1b\\\x1b[4m after\x1b[24m\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "table payload measures markdown images by their visible label" { const alloc = std.testing.allocator; var table = try parseTablePayload( alloc, "| Asset | Status |\n" ++ "| --- | --- |\n" ++ "|  | ready |\n", ); defer table.deinit(alloc);
const cell = table.rows[1].cells[0]; try std.testing.expect(std.mem.indexOf(u8, cell, "▧ diagram") != null); try std.testing.expect(std.mem.indexOf(u8, cell, "![diagram]") == null); try std.testing.expectEqual( display_width.visibleWidthIgnoringAnsi("▧ diagram"), display_width.visibleWidthIgnoringAnsi(cell), );}
test "table payload links use the shared OSC 8 identifier sequence" { const alloc = std.testing.allocator; const id_before = link_id_counter;
var first = try parseTablePayload( alloc, "| Link |\n" ++ "|------|\n" ++ "| [first](https://first.example) |\n", ); defer first.deinit(alloc);
var second = try parseTablePayload( alloc, "| Link |\n" ++ "|------|\n" ++ "| [second](https://second.example) |\n", ); defer second.deinit(alloc);
var first_id_buf: [64]u8 = undefined; const first_id = try std.fmt.bufPrint(&first_id_buf, "\x1b]8;id=fx-{d};https://first.example", .{id_before}); try std.testing.expect(std.mem.indexOf(u8, first.rows[1].cells[0], first_id) != null);
var second_id_buf: [64]u8 = undefined; const second_id = try std.fmt.bufPrint(&second_id_buf, "\x1b]8;id=fx-{d};https://second.example", .{id_before +% 1}); try std.testing.expect(std.mem.indexOf(u8, second.rows[1].cells[0], second_id) != null);}
test "bare URL is underlined and leaves sentence punctuation literal" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push(alloc, "visit https://example.com/docs, now\n", &out);
var expected_buf: [256]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "visit \x1b]8;id=fx-{d};https://example.com/docs\x1b\\\x1b[4mhttps://example.com/docs\x1b[24m\x1b]8;;\x1b\\, now\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "bare URL is recognized after streamed input chunks" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push(alloc, "visit https", &out); try std.testing.expectEqual(@as(usize, 0), out.items.len); try processor.push(alloc, "://example.com/docs\n", &out);
var expected_buf: [256]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "visit \x1b]8;id=fx-{d};https://example.com/docs\x1b\\\x1b[4mhttps://example.com/docs\x1b[24m\x1b]8;;\x1b\\\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "angle autolinks use literal URI and email labels" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push( alloc, "see <https://example.com/docs\\_literal> and <dev@example.com> plus <git+ssh://example.com/repo>\n", &out, );
var expected_buf: [1024]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "see \x1b]8;id=fx-{d};https://example.com/docs\\_literal\x1b\\\x1b[4mhttps://example.com/docs\\_literal\x1b[24m\x1b]8;;\x1b\\ and " ++ "\x1b]8;id=fx-{d};mailto:dev@example.com\x1b\\\x1b[4mdev@example.com\x1b[24m\x1b]8;;\x1b\\ plus " ++ "\x1b]8;id=fx-{d};git+ssh://example.com/repo\x1b\\\x1b[4mgit+ssh://example.com/repo\x1b[24m\x1b]8;;\x1b\\\n", .{ id_before, id_before +% 1, id_before +% 2 }, ); try std.testing.expectEqualStrings(expected, out.items);}
test "rejected angle candidates suppress nested link emission" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "<not-an-autolink https://inner.example>\n" ++ "\\<not-an-autolink https://inner.example>\n" ++ "<<https://inner.example>>\n" ++ "<[inner](https://inner.example)>\n" ++ "<[inner](https://one.example) https://two.example>\n" ++ "\\<https://escaped.example>\n" ++ "<a:x> <dev@bad-.example> <https://has space>\n" ++ "<not-an-autolink https://unterminated.example\n" ++ "`<https://code.example>`\n"; const expected = "<not-an-autolink https://inner.example>\n" ++ "<not-an-autolink https://inner.example>\n" ++ "<<https://inner.example>>\n" ++ "<[inner](https://inner.example)>\n" ++ "<[inner](https://one.example) https://two.example>\n" ++ "<https://escaped.example>\n" ++ "<a:x> <dev@bad-.example> <https://has space>\n" ++ "<not-an-autolink https://unterminated.example\n" ++ "\x1b[38;5;245m<https://code.example>\x1b[39m\n";
try processor.push(alloc, input, &out); try std.testing.expectEqualStrings(expected, out.items); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;") == null);}
test "angle email autolink applies the destination cap including mailto" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const suffix = "@a.com"; var local: [max_link_url_bytes]u8 = undefined; @memset(&local, 'a'); const local_len = max_link_url_bytes - "mailto:".len - suffix.len + 1; var input_buf: [max_link_url_bytes + 32]u8 = undefined; const input = try std.fmt.bufPrint(&input_buf, "<{s}{s}>\n", .{ local[0..local_len], suffix });
try processor.push(alloc, input, &out); try std.testing.expectEqualStrings(input, out.items); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;") == null);}
test "bare URL remains literal in code and excluded boundaries" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "`https://code.example` wordhttps://word.example <<https://angle.example>>\n", &out, ); try std.testing.expectEqualStrings( "\x1b[38;5;245mhttps://code.example\x1b[39m wordhttps://word.example <<https://angle.example>>\n", out.items, ); try std.testing.expect(std.mem.find(u8, out.items, "\x1b]8;") == null);}
test "unsafe bare URL renders literally" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
var oversized: [max_link_url_bytes + 1]u8 = undefined; @memset(&oversized, 'a'); var input_buf: [max_link_url_bytes + 16]u8 = undefined; const input = try std.fmt.bufPrint(&input_buf, "https://{s}\n", .{oversized[0..]});
try processor.push(alloc, input, &out); try std.testing.expectEqualStrings(input, out.items); try std.testing.expect(std.mem.find(u8, out.items, "\x1b]8;") == null);}
test "bare URLs leave closing emphasis delimiters for the inline scanner" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push( alloc, "**https://bold.example** *https://italic.example* ~~https://strike.example~~ tail\n", &out, );
var expected_buf: [1024]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "\x1b[1m\x1b]8;id=fx-{d};https://bold.example\x1b\\\x1b[4mhttps://bold.example\x1b[24m\x1b]8;;\x1b\\\x1b[22m " ++ "\x1b[3m\x1b]8;id=fx-{d};https://italic.example\x1b\\\x1b[4mhttps://italic.example\x1b[24m\x1b]8;;\x1b\\\x1b[23m " ++ "\x1b[9m\x1b]8;id=fx-{d};https://strike.example\x1b\\\x1b[4mhttps://strike.example\x1b[24m\x1b]8;;\x1b\\\x1b[29m tail\n", .{ id_before, id_before +% 1, id_before +% 2 }, ); try std.testing.expectEqualStrings(expected, out.items);}
test "malformed formatted link suppresses bare URL recognition" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "see [docs](https://example.com missing close\n", &out); try std.testing.expectEqualStrings("see [docs](https://example.com missing close\n", out.items); try std.testing.expect(std.mem.find(u8, out.items, "\x1b]8;") == null);}
test "heading underline resumes after a link closes its local underline" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push(alloc, "### before [link](https://example.com) after\nbody\n", &out);
var expected_buf: [512]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "\x1b[4mbefore \x1b]8;id=fx-{d};https://example.com\x1b\\\x1b[4mlink\x1b[24m\x1b]8;;\x1b\\\x1b[4m after\x1b[24m\nbody\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "two markdown links get distinct ids" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "[a](https://a.example) and [b](https://b.example)\n", &out); var seq_buf: [32]u8 = undefined; const first_marker = try std.fmt.bufPrint(&seq_buf, "id=fx-", .{}); var occurrences: usize = 0; var idx: usize = 0; while (std.mem.find(u8, out.items[idx..], first_marker)) |off| : (idx += off + first_marker.len) { occurrences += 1; } try std.testing.expectEqual(@as(usize, 2), occurrences);}
test "url over OSC 8 size cap renders literally" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
var oversized_buf: [3000]u8 = undefined; @memset(&oversized_buf, 'a'); const url = oversized_buf[0 .. max_link_url_bytes + 1]; var input_buf: [4000]u8 = undefined; const input = try std.fmt.bufPrint(&input_buf, "see [x]({s}) end\n", .{url});
try processor.push(alloc, input, &out); try std.testing.expect(std.mem.find(u8, out.items, "\x1b]8;") == null); try std.testing.expect(std.mem.find(u8, out.items, "[x](") != null);}
test "unmatched bracket renders literally" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "list [1, 2, 3] of items\n", &out); try std.testing.expectEqualStrings("list [1, 2, 3] of items\n", out.items);}
test "link with empty url renders literally" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "see [docs]() now\n", &out); try std.testing.expectEqualStrings("see [docs]() now\n", out.items);}
test "plain text passes through unchanged" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "hello world\n", &out); try std.testing.expectEqualStrings("hello world\n", out.items);}
test "backslash escapes keep inline punctuation literal" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "literal \\*em\\* \\*\\*bold\\*\\* \\_italic\\_ \\_\\_strong\\_\\_ \\~\\~strike\\~\\~ \\`code\\` \\[docs](https://example.com) \\\\ \\| \\! \\# \\>\n", &out, );
try std.testing.expectEqualStrings( "literal *em* **bold** _italic_ __strong__ ~~strike~~ `code` [docs](https://example.com) \\ | ! # >\n", out.items, ); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b") == null);}
test "backslash escapes survive heading preprocessing and code spans" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "## \\*\\*literal bold\\*\\* and `\\*code\\*`\n", &out); try std.testing.expectEqualStrings( "\x1b[1m**literal bold** and \x1b[38;5;245m\\*code\\*\x1b[39m\x1b[22m\n", out.items, );}
test "completed Markdown lines consume one terminal hard-break backslash" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "plain\\\n" ++ "# heading\\\n" ++ "- list\\\n" ++ "> quote\\\n" ++ "two\\\\\n" ++ "three\\\\\\\n", &out, );
try std.testing.expectEqualStrings( "plain\n" ++ "\x1b[1m\x1b[4mheading\x1b[24m\x1b[22m\n" ++ "\x1b[2m\xe2\x80\xa2 \x1b[22mlist\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mquote\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mtwo\\\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mthree\\\n", out.items, );}
test "terminal hard-break backslashes preserve EOF and code content" { const alloc = std.testing.allocator;
{ const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "eof\\", &out, .{ .thematic_rule = &completion }); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion }); try std.testing.expectEqualStrings("eof\\", out.items); }
{ var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "```\ncode\\\n```\n", &out); try std.testing.expectEqualStrings("\x1b[2m\xe2\x94\x82 \x1b[22mcode\\\n", out.items); }}
test "Setext and invalid pipe fallback retain source line completion" { const alloc = std.testing.allocator; const Capture = struct { calls: usize = 0,
fn deliver(raw: *anyopaque, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.calls += 1; } };
{ var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Setext\\\n---\n", &out, .{ .thematic_rule = &completion }, ); try std.testing.expectEqualStrings("\x1b[1mSetext\x1b[22m\n", out.items); try std.testing.expectEqual(@as(usize, 0), capture.calls); }
{ var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "| prior\\\n| eof\\", &out); try processor.flush(alloc, &out); try std.testing.expectEqualStrings("| prior\n| eof\\", out.items); }}
test "link labels unescape visible punctuation" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push(alloc, "[docs \\*literal\\*](https://example.com)\n", &out);
var expected_buf: [256]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "\x1b]8;id=fx-{d};https://example.com\x1b\\\x1b[4mdocs *literal*\x1b[24m\x1b]8;;\x1b\\\n", .{id_before}, ); try std.testing.expectEqualStrings(expected, out.items);}
test "backslash escapes stay literal in Setext headings" { const alloc = std.testing.allocator; const Capture = struct { calls: usize = 0,
fn deliver(raw: *anyopaque, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.calls += 1; } }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "\\*\\*literal bold\\*\\*\n---\n", &out, .{ .thematic_rule = &completion }, );
try std.testing.expectEqualStrings("\x1b[1m**literal bold**\x1b[22m\n", out.items); try std.testing.expectEqual(@as(usize, 0), capture.calls);}
test "bold double-asterisk wraps with ANSI" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "hi **there** friend\n", &out); try std.testing.expectEqualStrings("hi \x1b[1mthere\x1b[22m friend\n", out.items);}
test "italic single-asterisk wraps with ANSI" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "use *this* quickly\n", &out); try std.testing.expectEqualStrings("use \x1b[3mthis\x1b[23m quickly\n", out.items);}
test "underscore emphasis styles valid spans and preserves invalid markers" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "paragraph _italic_ and __bold__ with snake_case, snake__case, _ spaced_, and __ spaced__.\n", &out, ); try std.testing.expectEqualStrings( "paragraph \x1b[3mitalic\x1b[23m and \x1b[1mbold\x1b[22m with snake_case, snake__case, _ spaced_, and __ spaced__.\n", out.items, );}
test "underscore emphasis renders in list, blockquote, and table cells" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "- _item_\n> __quote__\n", &out); try std.testing.expectEqualStrings( "\x1b[2m• \x1b[22m\x1b[3mitem\x1b[23m\n" ++ "\x1b[2m│ \x1b[22m\x1b[1mquote\x1b[22m\n", out.items, );
var table = try parseTablePayload( alloc, "| Name | Value |\n" ++ "|------|-------|\n" ++ "| _row_ | __cell__ |\n", ); defer table.deinit(alloc); out.clearRetainingCapacity(); try renderTablePayload(alloc, table, &out); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[3mrow\x1b[23m") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[1mcell\x1b[22m") != null);}
test "underscore formatted bare URLs retain path underscores and matching closers" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const id_before = link_id_counter; try processor.push( alloc, "_https://example.com/snake_case_ tail __https://example.com/snake_case__ tail\n", &out, );
var expected_buf: [1024]u8 = undefined; const expected = try std.fmt.bufPrint( &expected_buf, "\x1b[3m\x1b]8;id=fx-{d};https://example.com/snake_case\x1b\\\x1b[4mhttps://example.com/snake_case\x1b[24m\x1b]8;;\x1b\\\x1b[23m tail " ++ "\x1b[1m\x1b]8;id=fx-{d};https://example.com/snake_case\x1b\\\x1b[4mhttps://example.com/snake_case\x1b[24m\x1b]8;;\x1b\\\x1b[22m tail\n", .{ id_before, id_before +% 1 }, ); try std.testing.expectEqualStrings(expected, out.items);}
test "underscore formatted URLs require exact active markers" { const alloc = std.testing.allocator; const no_link_inputs = [_][]const u8{ "snake_https://example.com\n", "snake__https://example.com\n", "_prefix__https://example.com\n", "__prefix__https://example.com\n", };
for (no_link_inputs) |input| { var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, input, &out); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;") == null); }
const wrong_closer_cases = [_]struct { input: []const u8, url: []const u8, tail: []const u8, }{ .{ .input = "_https://example.com/path__ tail\n", .url = "https://example.com/path__", .tail = " tail\x1b[23m\n" }, .{ .input = "__https://example.com/path_ tail\n", .url = "https://example.com/path_", .tail = " tail\x1b[22m\n" }, };
for (wrong_closer_cases) |case| { var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, case.input, &out); try std.testing.expect(std.mem.indexOf(u8, out.items, case.url) != null); try std.testing.expect(std.mem.endsWith(u8, out.items, case.tail)); }}
test "underscore emphasis preserves code literals and closes unpaired spans" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "_unclosed\n__unclosed\n`_literal_ __literal__`\n", &out); try std.testing.expectEqualStrings( "\x1b[3munclosed\x1b[23m\n" ++ "\x1b[1munclosed\x1b[22m\n" ++ "\x1b[38;5;245m_literal_ __literal__\x1b[39m\n", out.items, );}
test "headings preserve literal underscores and suppress valid double-underscore strong markers" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "## __Strong__ snake__case __ spaced__\n", &out); try std.testing.expectEqualStrings("\x1b[1mStrong snake__case __ spaced__\x1b[22m\n", out.items);}
test "cross-form nested strong spans reassert the remaining bold style" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "**outer __inner__ suffix** __outer **inner** suffix__\n", &out); try std.testing.expectEqualStrings( "\x1b[1mouter \x1b[1minner\x1b[22m\x1b[1m suffix\x1b[22m " ++ "\x1b[1mouter \x1b[1minner\x1b[22m\x1b[1m suffix\x1b[22m\n", out.items, );}
test "cross-form nested italic spans reassert the remaining italic style" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "*outer _inner_ suffix* _outer *inner* suffix_\n", &out); try std.testing.expectEqualStrings( "\x1b[3mouter \x1b[3minner\x1b[23m\x1b[3m suffix\x1b[23m " ++ "\x1b[3mouter \x1b[3minner\x1b[23m\x1b[3m suffix\x1b[23m\n", out.items, );}
test "table payload headers reassert outer bold after inline strong closes" { const alloc = std.testing.allocator; var table = try parseTablePayload( alloc, "| prefix __strong__ suffix |\n" ++ "|------|\n" ++ "| value |\n", ); defer table.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try renderTablePayload(alloc, table, &out); try std.testing.expect(std.mem.indexOf( u8, out.items, "\x1b[1mprefix \x1b[1mstrong\x1b[22m\x1b[1m suffix\x1b[22m", ) != null);}
test "inline code backticks wrap with ANSI" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "run `zig build` now\n", &out); try std.testing.expectEqualStrings("run \x1b[38;5;245mzig build\x1b[39m now\n", out.items);}
test "inline code uses the selected light background" { const alloc = std.testing.allocator; setInlineCodeTheme(true); defer setInlineCodeTheme(false);
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "run `zig build` now\n", &out); try std.testing.expectEqualStrings("run \x1b[38;5;247mzig build\x1b[39m now\n", out.items);}
test "stray asterisk between spaces stays literal" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "3 * 5 = 15\n", &out); try std.testing.expectEqualStrings("3 * 5 = 15\n", out.items);}
test "headings use level-specific ANSI styles" { const alloc = std.testing.allocator; const cases = [_]struct { input: []const u8, expected: []const u8 }{ .{ .input = "# Workspace overview\n", .expected = "\x1b[1m\x1b[4mWorkspace overview\x1b[24m\x1b[22m\n" }, .{ .input = "## Installation\n", .expected = "\x1b[1mInstallation\x1b[22m\n" }, .{ .input = "### macOS\n", .expected = "\x1b[4mmacOS\x1b[24m\n" }, .{ .input = "#### Shell setup\n", .expected = "\x1b[1m\x1b[2mShell setup\x1b[22m\n" }, .{ .input = "##### Optional tools\n", .expected = "\x1b[2m\x1b[4mOptional tools\x1b[24m\x1b[22m\n" }, .{ .input = "###### Troubleshooting\n", .expected = "\x1b[2mTroubleshooting\x1b[22m\n" }, };
for (cases) |case| { var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, case.input, &out); try std.testing.expectEqualStrings(case.expected, out.items); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[1;4m") == null); }}
test "setext headings use ATX styles and bypass thematic rule completion" { const alloc = std.testing.allocator; const Capture = struct { calls: usize = 0,
fn deliver(raw: *anyopaque, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.calls += 1; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "Workspace *overview*\n", &out, .{ .thematic_rule = &completion }); try std.testing.expectEqual(@as(usize, 0), out.items.len);
try processor.pushWithCompletions( alloc, "===\nInstallation **guide**\n---\n", &out, .{ .thematic_rule = &completion }, ); try std.testing.expectEqualStrings( "\x1b[1m\x1b[4mWorkspace \x1b[3moverview\x1b[23m\x1b[24m\x1b[22m\n" ++ "\x1b[1mInstallation guide\x1b[22m\n", out.items, ); try std.testing.expectEqual(@as(usize, 0), capture.calls);
try processor.pushWithCompletions(alloc, "\n---\n", &out, .{ .thematic_rule = &completion }); try std.testing.expectEqual(@as(usize, 1), capture.calls);}
test "setext candidate flushes at EOF and reset discards it" { const alloc = std.testing.allocator; const Capture = struct { calls: usize = 0,
fn deliver(raw: *anyopaque, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.calls += 1; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "ordinary title\n", &out, .{ .thematic_rule = &completion }); try std.testing.expectEqual(@as(usize, 0), out.items.len); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion }); try std.testing.expectEqualStrings("ordinary title\n", out.items);
out.clearRetainingCapacity(); try processor.pushWithCompletions(alloc, "discarded title\n", &out, .{ .thematic_rule = &completion }); processor.reset(alloc); try processor.pushWithCompletions(alloc, "---\n", &out, .{ .thematic_rule = &completion }); try std.testing.expectEqual(@as(usize, 1), capture.calls); try std.testing.expectEqual(@as(usize, 0), out.items.len);}
test "definition lists render adjacent markers through thematic completion" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Status\n: **Running**\n: second definition\n", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion });
try std.testing.expectEqualStrings( "Status\n" ++ "\x1b[2m \x1b[22m\x1b[1mRunning\x1b[22m\n" ++ "\x1b[2m \x1b[22msecond definition\n", out.items, );}
test "definition state stops before a fenced code block" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Status\n: accepted\n```\ncode\n```\n: stale\n", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion });
try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[2m \x1b[22maccepted\n") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\n: stale\n") != null);}
test "definition state stops before a pipe table" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Status\n: accepted\n| Name |\n| --- |\n| value |\n: stale\n", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion });
try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[2m \x1b[22maccepted\n") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\n: stale\n") != null);}
test "definition marker cannot skip a fenced code block" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Status\n```\ncode\n```\n: stale\n", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion });
try std.testing.expect(std.mem.indexOf(u8, out.items, "Status\n") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\n: stale\n") != null);}
test "definition marker cannot skip a pipe table" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Status\n| Name |\n| --- |\n| value |\n: stale\n", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion });
try std.testing.expect(std.mem.indexOf(u8, out.items, "Status\n") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\n: stale\n") != null);}
test "definition markers without a term stay literal" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, ": orphan\n: second marker\n", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion });
try std.testing.expectEqualStrings(": orphan\n: second marker\n", out.items);}
test "definition markers require a separator and adjacency" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
{ var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.pushWithCompletions( alloc, "Status\n:no-space\nEmpty\n: \t\nSeparated\n\n: body\n", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion }); try std.testing.expectEqualStrings( "Status\n:no-space\nEmpty\n: \t\nSeparated\n\n: body\n", out.items, ); }
{ var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "Direct\n: body\n", &out); try std.testing.expectEqualStrings("Direct\n: body\n", out.items); }}
test "definition bodies preserve LF and EOF hard-break behavior" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Status\n: line\\\n: eof\\", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion });
try std.testing.expectEqualStrings( "Status\n" ++ "\x1b[2m \x1b[22mline\n" ++ "\x1b[2m \x1b[22meof\\", out.items, );}
test "definition state resets with the processor" { const alloc = std.testing.allocator; const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "Status\n: accepted\n", &out, .{ .thematic_rule = &completion }); processor.reset(alloc); out.clearRetainingCapacity(); try processor.pushWithCompletions(alloc, ": stale\n", &out, .{ .thematic_rule = &completion }); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion });
try std.testing.expectEqualStrings(": stale\n", out.items);}
test "setext lookahead leaves structural predecessors as standalone rules" { const alloc = std.testing.allocator; const Capture = struct { calls: usize = 0,
fn deliver(raw: *anyopaque, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.calls += 1; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "# ATX heading\n---\n- list item\n---\n> quoted text\n---\nordinary prose\n___\n", &out, .{ .thematic_rule = &completion }, );
try std.testing.expectEqual(@as(usize, 4), capture.calls); try std.testing.expectEqualStrings( "\x1b[1m\x1b[4mATX heading\x1b[24m\x1b[22m\n" ++ "\x1b[2m\xe2\x80\xa2 \x1b[22mlist item\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mquoted text\n" ++ "ordinary prose\n", out.items, );}
fn checkSetextLookaheadAllocationFailures(alloc: Allocator) !void { const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "allocation title\n---\n", &out, .{ .thematic_rule = &completion }); try std.testing.expectEqualStrings("\x1b[1mallocation title\x1b[22m\n", out.items);}
test "setext lookahead frees allocation failures" { try std.testing.checkAllAllocationFailures( std.testing.allocator, checkSetextLookaheadAllocationFailures, .{}, );}
fn checkDefinitionListAllocationFailures(alloc: Allocator) !void { const Capture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} }; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Status\n: **Running**\n: second definition\n", &out, .{ .thematic_rule = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion }); try std.testing.expectEqualStrings( "Status\n" ++ "\x1b[2m \x1b[22m\x1b[1mRunning\x1b[22m\n" ++ "\x1b[2m \x1b[22msecond definition\n", out.items, );}
test "definition lists free allocation failures" { try std.testing.checkAllAllocationFailures( std.testing.allocator, checkDefinitionListAllocationFailures, .{}, );}
test "footnote references emit dim markers and defer definitions" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "The cache is scoped to this request.[^cache]\n" ++ "[^cache]: It is discarded after the request completes.\n", &out, ); try processor.flush(alloc, &out);
try std.testing.expectEqualStrings( "The cache is scoped to this request.\x1b[2m[1]\x1b[22m\n\n" ++ "\x1b[2m[1] \x1b[22mIt is discarded after the request completes.\n", out.items, );}
test "table cell footnote references project deferred definitions" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "| Component | State |\n" ++ "| --- | --- |\n" ++ "| api | [^state] |\n" ++ "[^state]: The state comes from the deployment record.\n", &out, ); try processor.flush(alloc, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, "[^state]") == null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[2m[1] \x1b[22m") != null); try std.testing.expect(std.mem.endsWith( u8, out.items, "\n\n\x1b[2m[1] \x1b[22mThe state comes from the deployment record.\n", ));}
test "footnotes normalize the final separator after blank source lines" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "The cache is scoped to this request.[^cache]\n\n" ++ "[^cache]: It is discarded after the request completes.\n", &out, ); try processor.flush(alloc, &out);
try std.testing.expectEqualStrings( "The cache is scoped to this request.\x1b[2m[1]\x1b[22m\n\n" ++ "\x1b[2m[1] \x1b[22mIt is discarded after the request completes.\n", out.items, );}
test "footnotes use first reference order and keep the first definition" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "[^second]: The second definition arrives first.\n" ++ "[^first]: The first definition arrives second.\n" ++ "First[^first], second[^second], and first again[^first].\n" ++ "[^first]: This duplicate definition is ignored.\n", &out, ); try processor.flush(alloc, &out);
try std.testing.expectEqualStrings( "First\x1b[2m[1]\x1b[22m, second\x1b[2m[2]\x1b[22m, and first again\x1b[2m[1]\x1b[22m.\n\n" ++ "\x1b[2m[1] \x1b[22mThe first definition arrives second.\n" ++ "\x1b[2m[2] \x1b[22mThe second definition arrives first.\n", out.items, );}
test "footnote definitions format multiline bodies and retain EOF separators" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "[^cache]: First **formatted** line.\n" ++ " Second continuation line.\n" ++ "\tThird continuation line.\n" ++ "The cache is scoped to this request.[^cache]", &out, ); try processor.flush(alloc, &out);
try std.testing.expectEqualStrings( "The cache is scoped to this request.\x1b[2m[1]\x1b[22m\n\n" ++ "\x1b[2m[1] \x1b[22mFirst \x1b[1mformatted\x1b[22m line.\n" ++ "\x1b[2m \x1b[22mSecond continuation line.\n" ++ "\x1b[2m \x1b[22mThird continuation line.\n", out.items, );}
test "escaped malformed and code footnote candidates remain literal" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "\\[^escaped] \x60[^code]\x60 [^] [^missing]:\n\n" ++ " [^block]: literal code\n", &out, ); try processor.flush(alloc, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, "[1]") == null); try std.testing.expect(std.mem.indexOf(u8, out.items, "[^escaped]") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "[^code]") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "[^missing]:") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "[^block]: literal code") != null);}
fn checkFootnoteAllocationFailures(alloc: Allocator) !void { var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "The cache is scoped to this request.[^cache]\n" ++ "[^cache]: First **formatted** line.\n" ++ " Second continuation line.\n", &out, ); try processor.flush(alloc, &out);}
test "footnotes free allocation failures" { try std.testing.checkAllAllocationFailures( std.testing.allocator, checkFootnoteAllocationFailures, .{}, );}
test "heading keeps inline emphasis without nested bold markers" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "# **Strong** *emphasis*\n", &out); try std.testing.expectEqualStrings( "\x1b[1m\x1b[4mStrong \x1b[3memphasis\x1b[23m\x1b[24m\x1b[22m\n", out.items, );}
test "hash without trailing space is literal" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "#notATag\n", &out); try std.testing.expectEqualStrings("#notATag\n", out.items);}
test "unordered list dash gets bullet" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "- first item\n", &out); try std.testing.expectEqualStrings("\x1b[2m\xe2\x80\xa2 \x1b[22mfirst item\n", out.items);}
test "unordered list asterisk gets bullet" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "* second item\n", &out); try std.testing.expectEqualStrings("\x1b[2m\xe2\x80\xa2 \x1b[22msecond item\n", out.items);}
test "ordered list keeps number marker" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "1. step one\n", &out); try std.testing.expectEqualStrings("\x1b[2m1.\x1b[22m step one\n", out.items);}
test "task list items render static pending and completed markers" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "- [ ] pending **task**\n" ++ "- [x] done\n" ++ " * [X] nested done\n" ++ "- [ ]\n", &out, ); try std.testing.expectEqualStrings( "\x1b[2m\xe2\x98\x90 \x1b[22mpending \x1b[1mtask\x1b[22m\n" ++ "\x1b[38;5;252m\xe2\x9c\x93\x1b[39m done\n" ++ " \x1b[38;5;252m\xe2\x9c\x93\x1b[39m nested done\n" ++ "\x1b[2m\xe2\x98\x90\x1b[22m\n", out.items, );}
test "ordered task list items retain their number markers" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "1. [ ] first\n2. [X] done\n", &out); try std.testing.expectEqualStrings( "\x1b[2m1.\x1b[22m \x1b[2m\xe2\x98\x90 \x1b[22mfirst\n" ++ "\x1b[2m2.\x1b[22m \x1b[38;5;252m\xe2\x9c\x93\x1b[39m done\n", out.items, );}
test "task list syntax remains literal outside its bounded grammar" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, "- [x]done\n" ++ "- [-] unsupported\n" ++ "- [ ]pending\n" ++ "ordinary [x] prose\n" ++ "```text\n" ++ "- [x] literal code\n" ++ "```\n", &out, ); try std.testing.expectEqualStrings( "\x1b[2m\xe2\x80\xa2 \x1b[22m[x]done\n" ++ "\x1b[2m\xe2\x80\xa2 \x1b[22m[-] unsupported\n" ++ "\x1b[2m\xe2\x80\xa2 \x1b[22m[ ]pending\n" ++ "ordinary [x] prose\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m- [x] literal code\n", out.items, );}
test "task list prefix is retained across streamed input chunks" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "- [x]", &out); try std.testing.expectEqual(@as(usize, 0), out.items.len); try processor.push(alloc, " streamed task\n", &out); try std.testing.expectEqualStrings("\x1b[38;5;252m\xe2\x9c\x93\x1b[39m streamed task\n", out.items);}
test "blockquote gets a dim vertical rule and renders inline markdown" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, " > **important** note\n", &out); try std.testing.expectEqualStrings(" \x1b[2m\xe2\x94\x82 \x1b[22m\x1b[1mimportant\x1b[22m note\n", out.items);}
test "lazy nested blockquote continuations retain their rules" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "> > first **quoted** line\n", &out); try processor.push(alloc, "lazy second line\n> > explicit third line\nlazy fourth line\n\noutside\n", &out); try std.testing.expectEqualStrings( "\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22mfirst \x1b[1mquoted\x1b[22m line\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22mlazy second line\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22mexplicit third line\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22mlazy fourth line\n\n" ++ "outside\n", out.items, );}
test "lazy blockquote continuations retain inline links" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "> source\nlazy [link](https://example.com/lazy)\n", &out); try std.testing.expect(std.mem.indexOf(u8, out.items, "\n\x1b[2m\xe2\x94\x82 \x1b[22mlazy ") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b]8;id=fx-") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "https://example.com/lazy") != null);}
test "lazy blockquotes stop before structural rows and preserve EOF backslashes" { const alloc = std.testing.allocator; const RuleCapture = struct { calls: usize = 0,
fn deliver(raw: *anyopaque, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.calls += 1; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = RuleCapture{}; var rule_completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = RuleCapture.deliver, };
try processor.pushWithCompletions( alloc, "> quote\nlazy continuation\n===\n---\noutside\n> quote again\n- list item\n> quote at EOF\nlazy EOF\\", &out, .{ .thematic_rule = &rule_completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &rule_completion }); try std.testing.expectEqualStrings( "\x1b[2m\xe2\x94\x82 \x1b[22mquote\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mlazy continuation\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m===\n" ++ "outside\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mquote again\n" ++ "\x1b[2m\xe2\x80\xa2 \x1b[22mlist item\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mquote at EOF\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mlazy EOF\\", out.items, ); try std.testing.expectEqual(@as(usize, 1), capture.calls);}
test "lazy blockquotes end before headings and fences" { const alloc = std.testing.allocator; const RuleCapture = struct { fn deliver(_: *anyopaque, _: *std.ArrayList(u8)) !void {} };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture: u8 = 0; var rule_completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = RuleCapture.deliver, };
try processor.pushWithCompletions( alloc, "> quote before heading\n# heading\nheading outside\n> quote before fence\n```zig\ncode\n```\nafter fence\n", &out, .{ .thematic_rule = &rule_completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &rule_completion }); try std.testing.expectEqualStrings( "\x1b[2m\xe2\x94\x82 \x1b[22mquote before heading\n" ++ "\x1b[1m\x1b[4mheading\x1b[24m\x1b[22m\n" ++ "heading outside\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mquote before fence\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22mcode\n" ++ "after fence\n", out.items, );}
test "reset clears lazy blockquote state" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "> quote\n", &out); processor.reset(alloc); try processor.push(alloc, "next turn\n", &out); try std.testing.expectEqualStrings( "\x1b[2m\xe2\x94\x82 \x1b[22mquote\nnext turn\n", out.items, );}
test "flushing ends lazy blockquote state" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "> quote\n", &out); try processor.flush(alloc, &out); try processor.push(alloc, "next stream\n", &out); try std.testing.expectEqualStrings( "\x1b[2m\xe2\x94\x82 \x1b[22mquote\nnext stream\n", out.items, );}
test "nested blockquotes render every valid marker and preserve malformed inner syntax" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push( alloc, " > > **deep** note\n" ++ "> > > third depth\n" ++ "> >\n" ++ ">> compact\n" ++ "> >not\n", &out, ); try std.testing.expectEqualStrings( " \x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[1mdeep\x1b[22m note\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22mthird depth\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22m\n" ++ ">> compact\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m>not\n", out.items, );}
test "nested blockquote remains buffered until its terminating newline" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "> > **chunked", &out); try std.testing.expectEqual(@as(usize, 0), out.items.len); try processor.push(alloc, " nested**\n", &out); try std.testing.expectEqualStrings( "\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[2m\xe2\x94\x82 \x1b[22m\x1b[1mchunked nested\x1b[22m\n", out.items, );}
test "blockquote without a marker separator stays literal" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, ">not a blockquote\n", &out); try std.testing.expectEqualStrings(">not a blockquote\n", out.items);}
test "code fence toggles block state" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "```zig\nconst x = 1;\n```\n", &out); const expected = "\x1b[2m\xe2\x94\x82 \x1b[22mconst x = 1;\n"; try std.testing.expectEqualStrings(expected, out.items); try std.testing.expect(!processor.in_code_block);}
test "presented prefix restores an unfinished code fence without replaying its bytes" { const alloc = std.testing.allocator; const Capture = struct { block: ?CodeBlockPayload = null,
fn deinit(self: *@This()) void { if (self.block) |*block| block.deinit(alloc); }
fn deliver(raw: *anyopaque, block: CodeBlockPayload, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.block = block; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var capture = Capture{}; defer capture.deinit(); var completion = CodeBlockCompletion{ .ctx = &capture, .deliver = Capture.deliver, }; var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.restorePresentedPrefix(alloc, "```zig\nconst value ="); try std.testing.expect(processor.in_code_block); try std.testing.expectEqual(@as(?u8, '`'), processor.code_fence_marker); try std.testing.expectEqualStrings("zig", processor.code_language.items); try std.testing.expectEqual(@as(usize, 0), processor.code_buf.items.len);
try processor.pushWithCompletions( alloc, " 1;\n```\nafter\n", &out, .{ .code = &completion }, ); try processor.flushWithCompletions(alloc, &out, .{ .code = &completion });
const block = capture.block orelse return error.TestUnexpectedResult; try std.testing.expectEqualStrings("zig", block.language); try std.testing.expectEqualStrings(" 1;\n", block.code); try std.testing.expectEqualStrings("after\n", out.items);}
test "code block preserves inline markers literally" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "```\nfoo **bar** baz\n```\n", &out); const expected = "\x1b[2m\xe2\x94\x82 \x1b[22mfoo **bar** baz\n"; try std.testing.expectEqualStrings(expected, out.items);}
test "tilde code fence keeps literal code and ignores backtick fence" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "~~~zig\nconst value = **1**;\n```\n~~~\n", &out);
const expected = "\x1b[2m\xe2\x94\x82 \x1b[22mconst value = **1**;\n" ++ "\x1b[2m\xe2\x94\x82 \x1b[22m```\n"; try std.testing.expectEqualStrings(expected, out.items); try std.testing.expect(!processor.in_code_block);}
test "tilde code fence completion retains language and literal source" { const alloc = std.testing.allocator; const Capture = struct { block: ?CodeBlockPayload = null,
fn deinit(self: *@This()) void { if (self.block) |*block| block.deinit(alloc); }
fn deliver(raw: *anyopaque, block: CodeBlockPayload, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.block = block; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; defer capture.deinit(); var completion = CodeBlockCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Before block.\n~~~ Zig example\n const value = **1**;\n```\n~~~\nAfter block.\n", &out, .{ .code = &completion }, );
try std.testing.expectEqualStrings("Before block.\nAfter block.\n", out.items); const block = capture.block orelse return error.TestUnexpectedResult; try std.testing.expectEqualStrings("Zig", block.language); try std.testing.expectEqualStrings(" const value = **1**;\n```\n", block.code);}
test "unterminated tilde code fence flushes its semantic payload" { const alloc = std.testing.allocator; const Capture = struct { block: ?CodeBlockPayload = null,
fn deinit(self: *@This()) void { if (self.block) |*block| block.deinit(alloc); }
fn deliver(raw: *anyopaque, block: CodeBlockPayload, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.block = block; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; defer capture.deinit(); var completion = CodeBlockCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "~~~text\nlast line", &out, .{ .code = &completion }); try processor.flushWithCompletions(alloc, &out, .{ .code = &completion });
const block = capture.block orelse return error.TestUnexpectedResult; try std.testing.expectEqualStrings("text", block.language); try std.testing.expectEqualStrings("last line\n", block.code);}
test "markdown completion normalizes CRLF across chunks before capturing code fences" { const alloc = std.testing.allocator; const Capture = struct { block: ?CodeBlockPayload = null,
fn deinit(self: *@This()) void { if (self.block) |*block| block.deinit(alloc); }
fn deliver(raw: *anyopaque, block: CodeBlockPayload, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.block = block; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; defer capture.deinit(); var completion = CodeBlockCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "Before block.\r\n``` Zig example\r", &out, .{ .code = &completion }, ); try processor.pushWithCompletions( alloc, "\n const value = **1**;\r\n```\r\nAfter block.\r\n", &out, .{ .code = &completion }, );
try std.testing.expectEqualStrings("Before block.\nAfter block.\n", out.items); const block = capture.block orelse return error.TestUnexpectedResult; try std.testing.expectEqualStrings("Zig", block.language); try std.testing.expectEqualStrings(" const value = **1**;\n", block.code);}
test "indented code completion deindents literal lines and reprocesses its terminator" { const alloc = std.testing.allocator; const Capture = struct { block: ?CodeBlockPayload = null,
fn deinit(self: *@This()) void { if (self.block) |*block| block.deinit(alloc); }
fn deliver(raw: *anyopaque, block: CodeBlockPayload, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.block = block; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; defer capture.deinit(); var completion = CodeBlockCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "\n | literal | pipe |\n ```zig\n const value = **1**;\n nested\nplain text\n", &out, .{ .code = &completion }, );
const block = capture.block orelse return error.TestUnexpectedResult; try std.testing.expectEqualStrings("", block.language); try std.testing.expectEqualStrings( "| literal | pipe |\n```zig\nconst value = **1**;\n nested\n", block.code, ); try std.testing.expectEqualStrings("\nplain text\n", out.items); try std.testing.expect(!processor.in_code_block);}
test "indented code completion accepts a response-leading tab and flushes at EOF" { const alloc = std.testing.allocator; const Capture = struct { block: ?CodeBlockPayload = null,
fn deinit(self: *@This()) void { if (self.block) |*block| block.deinit(alloc); }
fn deliver(raw: *anyopaque, block: CodeBlockPayload, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.block = block; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; defer capture.deinit(); var completion = CodeBlockCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "\t tail", &out, .{ .code = &completion }); try processor.flushWithCompletions(alloc, &out, .{ .code = &completion });
const block = capture.block orelse return error.TestUnexpectedResult; try std.testing.expectEqualStrings("", block.language); try std.testing.expectEqualStrings(" tail\n", block.code); try std.testing.expectEqual(@as(usize, 0), out.items.len);}
test "indented code requires a blank boundary and yields to list and lazy quote content" { const alloc = std.testing.allocator; const Capture = struct { block: ?CodeBlockPayload = null,
fn deinit(self: *@This()) void { if (self.block) |*block| block.deinit(alloc); }
fn deliver(raw: *anyopaque, block: CodeBlockPayload, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.block = block; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; defer capture.deinit(); var completion = CodeBlockCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions( alloc, "paragraph\n continuation\n\n three spaces\n\n - list item\n> quote\n lazy continuation\n\nafter quote\n", &out, .{ .code = &completion }, );
try std.testing.expect(capture.block == null); try std.testing.expect(std.mem.indexOf(u8, out.items, " continuation") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, " three spaces") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[2m\xe2\x94\x82 \x1b[22m lazy continuation") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[2m\xe2\x94\x82 \x1b[22m- list item") == null);}
test "reset clears an unfinished indented code block" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, " stale code\n", &out); try std.testing.expect(processor.in_code_block);
processor.reset(alloc); try std.testing.expect(!processor.in_code_block); try processor.push(alloc, "after reset\n", &out);
try std.testing.expectEqualStrings("\x1b[2m\xe2\x94\x82 \x1b[22mstale code\nafter reset\n", out.items);}
test "code block payload clone frees language if code allocation fails" { const alloc = std.testing.allocator; var source = CodeBlockPayload{ .language = try alloc.dupe(u8, "zig"), .code = try alloc.dupe(u8, "const value = 1;\n"), }; defer source.deinit(alloc);
var failing = std.testing.FailingAllocator.init(alloc, .{ .fail_index = 1 }); try std.testing.expectError(error.OutOfMemory, source.clone(failing.allocator()));}
test "markdown completion flushes an unterminated code fence" { const alloc = std.testing.allocator; const Capture = struct { block: ?CodeBlockPayload = null,
fn deinit(self: *@This()) void { if (self.block) |*block| block.deinit(alloc); }
fn deliver(raw: *anyopaque, block: CodeBlockPayload, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.block = block; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; defer capture.deinit(); var completion = CodeBlockCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "```text\nlast line", &out, .{ .code = &completion }); try processor.flushWithCompletions(alloc, &out, .{ .code = &completion });
const block = capture.block orelse return error.TestUnexpectedResult; try std.testing.expectEqualStrings("text", block.language); try std.testing.expectEqualStrings("last line\n", block.code);}
test "line intake buffers partial lines and preserves standalone carriage returns" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, ">", &out); try std.testing.expectEqual(@as(usize, 0), out.items.len);
try processor.push(alloc, "\n", &out); try std.testing.expectEqualStrings("\x1b[2m\xe2\x94\x82 \x1b[22m\n", out.items);
out.clearRetainingCapacity(); try processor.push(alloc, "**bol", &out); try std.testing.expectEqual(@as(usize, 0), out.items.len); try processor.push(alloc, "d** rest\n", &out); try std.testing.expectEqualStrings("\x1b[1mbold\x1b[22m rest\n", out.items);
out.clearRetainingCapacity(); try processor.push(alloc, "run `zig", &out); try std.testing.expectEqual(@as(usize, 0), out.items.len); try processor.push(alloc, " build` now\n", &out); try std.testing.expectEqualStrings("run \x1b[38;5;245mzig build\x1b[39m now\n", out.items);
out.clearRetainingCapacity(); try processor.push(alloc, "left\rright\n", &out); try std.testing.expectEqualStrings("left\rright\n", out.items);}
test "flush emits pending line without newline" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "partial", &out); try processor.flush(alloc, &out); try std.testing.expectEqualStrings("partial", out.items);}
test "flush closes open styles" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "oops **never closed", &out); try processor.flush(alloc, &out); try std.testing.expectEqualStrings("oops \x1b[1mnever closed\x1b[22m", out.items);}
test "flush closes an unpaired inline code span" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "run `zig build", &out); try processor.flush(alloc, &out); try std.testing.expectEqualStrings("run \x1b[38;5;245mzig build\x1b[39m", out.items);}
test "header with inline markdown" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "## Using `fx` in CI\n", &out); try std.testing.expectEqualStrings("\x1b[1mUsing \x1b[38;5;245mfx\x1b[39m in CI\x1b[22m\n", out.items);}
test "inline code ignores bold markers inside" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "use `**literal**` here\n", &out); try std.testing.expectEqualStrings("use \x1b[38;5;245m**literal**\x1b[39m here\n", out.items);}
test "pipe table header separator has junction aligned with column pipes" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "| Name | Age |\n" ++ "|------|-----|\n" ++ "| Ana | 30 |\n" ++ "| Bob | 7 |\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out);
const expected = "\x1b[1mName\x1b[22m \xe2\x94\x82 \x1b[1mAge\x1b[22m\n" ++ "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n" ++ "Ana \xe2\x94\x82 30 \n" ++ "Bob \xe2\x94\x82 7 \n"; try std.testing.expectEqualStrings(expected, out.items);}
test "single-column pipe table has no junction on separator" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "| Header |\n" ++ "|--------|\n" ++ "| data |\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x94\xbc") == null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80") != null);}
test "pipe table with markdown in cells aligns dividers across all rows" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "| Aspect | Value |\n" ++ "|--------|-------|\n" ++ "| **bold** | x |\n" ++ "| plain | y |\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out);
const expected = "\x1b[1mAspect\x1b[22m \xe2\x94\x82 \x1b[1mValue\x1b[22m\n" ++ "\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n" ++ "\x1b[1mbold\x1b[22m \xe2\x94\x82 x \n" ++ "plain \xe2\x94\x82 y \n"; try std.testing.expectEqualStrings(expected, out.items);}
test "escaped pipes stay inside table cells while even backslashes retain delimiters" { const alloc = std.testing.allocator; var table = try parseTablePayload( alloc, "| Command | Result |\n" ++ "| --- | --- |\n" ++ "| printf \\| grep | works |\n", ); defer table.deinit(alloc);
try std.testing.expectEqual(@as(usize, 2), table.column_count); try std.testing.expectEqualStrings("printf | grep", table.rows[1].cells[0]); try std.testing.expect(!isPipeLine("literal \\| pipe")); try std.testing.expect(isPipeLine("literal \\\\| delimiter"));}
test "three-column pipe table aligns junctions with every column pipe" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "| A | B | C |\n" ++ "|---|----|-----|\n" ++ "| 1 | 22 | 333 |\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out);
const expected_separator = "\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n"; try std.testing.expect(std.mem.indexOf(u8, out.items, expected_separator) != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "1 \xe2\x94\x82 22 \xe2\x94\x82 333\n") != null);}
test "pipe table without separator falls back to plain lines" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "| just one |\n| stray pipes |\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out); try std.testing.expectEqualStrings("| just one |\n| stray pipes |\n", out.items);}
test "pipe table preceded by paragraph and followed by paragraph" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "Before table.\n" ++ "| a | b |\n" ++ "|---|---|\n" ++ "| 1 | 2 |\n" ++ "After table.\n"; try processor.push(alloc, input, &out);
try std.testing.expect(std.mem.startsWith(u8, out.items, "Before table.\n")); try std.testing.expect(std.mem.endsWith(u8, out.items, "After table.\n"));}
test "borderless GFM table (no leading/trailing pipes) is detected and rendered" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "Name | Age\n" ++ "-----|-----\n" ++ "Ana | 30\n" ++ "Bob | 7\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x94\x82") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x94\xbc") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[1mName\x1b[22m") != null);}
test "borderless separator with spaces around pipe is accepted" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "Característica | Vercel | Cloudflare\n" ++ "-------------- | ------ | ----------\n" ++ "Enfoque principal | Frontend | Edge compute\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x94\x82") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x94\xbc") != null);}
test "paragraph with single inline pipe falls back to plain (no separator)" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "Use cmd | grep foo to filter.\n" ++ "Then review the output.\n"; try processor.push(alloc, input, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x94\x82") == null); try std.testing.expect(std.mem.indexOf(u8, out.items, "Use cmd | grep foo") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "Then review the output.") != null);}
test "header with nested **bold** stays fully bold across the whole line" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "## **Directory** Structure\n", &out); try std.testing.expectEqualStrings("\x1b[1mDirectory Structure\x1b[22m\n", out.items);}
test "header keeps italic and code inline" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "# *note* about `fx`\n", &out); try std.testing.expectEqualStrings( "\x1b[1m\x1b[4m\x1b[3mnote\x1b[23m about \x1b[38;5;245mfx\x1b[39m\x1b[24m\x1b[22m\n", out.items, );}
test "strikethrough wraps with ANSI" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "was ~~wrong~~ now right\n", &out); try std.testing.expectEqualStrings("was \x1b[9mwrong\x1b[29m now right\n", out.items);}
test "stray tildes between spaces stay literal" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "path is ~~ /tmp\n", &out); try std.testing.expectEqualStrings("path is ~~ /tmp\n", out.items);}
test "horizontal rule with dashes renders dim line" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "---\n", &out); try std.testing.expect(std.mem.startsWith(u8, out.items, dim_open)); try std.testing.expect(std.mem.endsWith(u8, out.items, dim_close ++ "\n")); const glyphs = std.mem.count(u8, out.items, table_horiz); try std.testing.expectEqual(@as(usize, horizontal_rule_width), glyphs);}
test "thematic rule completion handles newline and EOF without matching H6 content" { const alloc = std.testing.allocator; const Capture = struct { calls: usize = 0,
fn deliver(raw: *anyopaque, _: *std.ArrayList(u8)) !void { const self: *@This() = @ptrCast(@alignCast(raw)); self.calls += 1; } };
var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc); var capture = Capture{}; var completion = ThematicRuleCompletion{ .ctx = &capture, .deliver = Capture.deliver, };
try processor.pushWithCompletions(alloc, "---\n", &out, .{ .thematic_rule = &completion }); try std.testing.expectEqual(@as(usize, 1), capture.calls); try std.testing.expectEqual(@as(usize, 0), out.items.len);
try processor.pushWithCompletions(alloc, "___", &out, .{ .thematic_rule = &completion }); try processor.flushWithCompletions(alloc, &out, .{ .thematic_rule = &completion }); try std.testing.expectEqual(@as(usize, 2), capture.calls); try std.testing.expectEqual(@as(usize, 0), out.items.len);
var h6: std.ArrayList(u8) = .empty; defer h6.deinit(alloc); try h6.appendSlice(alloc, "###### "); var i: usize = 0; while (i < horizontal_rule_width) : (i += 1) try h6.appendSlice(alloc, table_horiz); try h6.append(alloc, '\n'); try processor.pushWithCompletions(alloc, h6.items, &out, .{ .thematic_rule = &completion }); try std.testing.expectEqual(@as(usize, 2), capture.calls); try std.testing.expect(out.items.len > 0);}
test "horizontal rule with asterisks and spaces also renders" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "* * *\n", &out); try std.testing.expect(std.mem.indexOf(u8, out.items, table_horiz) != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "*") == null);}
test "hyphen-space line is a list, not a rule" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, "- item\n", &out); try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x80\xa2") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "\xe2\x94\x80") == null);}
test "nested unordered list preserves indent" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, " - nested item\n", &out); try std.testing.expectEqualStrings(" \x1b[2m\xe2\x80\xa2 \x1b[22mnested item\n", out.items);}
test "nested ordered list preserves indent" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
try processor.push(alloc, " 1. sub-step\n", &out); try std.testing.expectEqualStrings(" \x1b[2m1.\x1b[22m sub-step\n", out.items);}
test "right-aligned GFM column pads cell on the left" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "| Name | Score |\n" ++ "|:-----|------:|\n" ++ "| Ana | 5 |\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, " 5\n") != null);}
test "center-aligned GFM column pads both sides" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "| Name | Note |\n" ++ "|------|:----:|\n" ++ "| Ana | ok |\n"; try processor.push(alloc, input, &out); try processor.flush(alloc, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, " ok \n") != null);}
test "pipe table parsing retains styled cells alignment and ragged rows" { const alloc = std.testing.allocator; var table = try parseTablePayload( alloc, "| Name | State | Count |\n" ++ "|:-----|:-----:|------:|\n" ++ "| **api** | ready | 7 | extra |\n" ++ "| worker | |\n", ); defer table.deinit(alloc);
try std.testing.expectEqual(@as(usize, 4), table.column_count); try std.testing.expectEqual(@as(usize, 3), table.rows.len); try std.testing.expectEqual(TableColumnAlign.center, table.alignments[1]); try std.testing.expectEqual(TableColumnAlign.right, table.alignments[2]); try std.testing.expectEqualStrings("\x1b[1mapi\x1b[22m", table.rows[1].cells[0]); try std.testing.expectEqualStrings("extra", table.rows[1].cells[3]); try std.testing.expectEqual(@as(usize, 2), table.rows[2].cells.len);}
test "pipe table inside code block stays literal" { const alloc = std.testing.allocator; var processor = MarkdownProcessor{}; defer processor.deinit(alloc); var out: std.ArrayList(u8) = .empty; defer out.deinit(alloc);
const input = "```\n" ++ "| not | a |\n" ++ "|-----|---|\n" ++ "| table | really |\n" ++ "```\n"; try processor.push(alloc, input, &out);
try std.testing.expect(std.mem.indexOf(u8, out.items, "| not | a |") != null); try std.testing.expect(std.mem.indexOf(u8, out.items, "| table | really |") != null);}