Repository navigation
Markdown -> ANSI terminal renderer (on by default for agent/tui) - #155
Conversation
Models emit markdown — bold, italic, headings, fenced code, lists,
links, blockquotes — and PasClaw was printing it verbatim with the
raw stars and hashes. picoclaw does the same (no markdown rendering
in its agent loop, just println). nanobot leans on Python's rich
library and renders markdown to styled ANSI for free. We pick the
nanobot direction.
New unit: src/pkg/markdown/PasClaw.Markdown.Render.pas
function RenderMarkdown(const S: string): string;
Subset covered (~95% of what models actually emit):
# / ## / ### / #### heading -> bold + colour
**bold** -> ANSI bold
*italic* / _italic_ -> ANSI italic (3m / 23m)
~~strikethrough~~ -> ANSI strikethrough (9m / 29m)
\`inline code\` -> dim + reverse
\`\`\`fenced block\`\`\` -> dim, multi-line, inline transforms
suppressed inside the fence
- / * bullet -> '•' bullet + indent + inline render
> blockquote -> '│ ' bar + italic body
[text](url) -> underline text + (url) in dim
Plain text (no markers) -> byte-identical passthrough (matters
for streaming chunks where we render mid-message).
Empty input -> empty output.
Idempotent for non-markdown content. No trailing newline added
to non-newline-terminated input.
Config knob: Cfg.RenderMarkdown (default True).
- Wired into pasclaw agent's RunSingleTurn + RunInteractive paths
via the new MaybeRender helper. Both PrintLn(Loop.Content) sites
now go through it.
- Wired into pasclaw tui via TTUI.RenderMarkdownEnabled (set from
Cfg.RenderMarkdown in Cmd_TUI_Run, default True on construction).
- serve and gateway commands never call the renderer — they emit
JSON to API clients and ANSI escapes would corrupt the wire
body. No change needed; they already PrintLn other strings only.
Operator can turn it off via "render_markdown": false in
config.json (round-trips: on-by-default emits no key, off
emits the key explicitly so save/load is idempotent).
Tests: src/tests/markdown_render_tests.pas
TestPlainPassThrough — plain text round-trips byte-identical
TestBold — ** consumed, content + Ansi.Bold present
TestItalic — * consumed, italic escapes present
TestInlineCode — backticks consumed, dim styling present
TestHeading — # consumed, BoldBlue applied
TestBulletList — -/* consumed, '•' glyph emitted
TestFencedCode — body preserved, **bold** inside stays
verbatim (no nested transforms)
TestLink — [text](url) becomes underlined text +
(url) in dim, brackets consumed
TestBlockquote — '> ' consumed, '│' bar emitted
TestEmpty — empty in, empty out
TestNoTrailingNewlineAdded — streaming-friendly: no extra '\n'
make test-markdown-render -> all 11 cases OK
make smoke -> all 11 commands OK
make test-gemini-schema-strip / test-anthropic-server-tools /
test-openai-server-tools -> all unchanged, OK
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 648c3966db
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Result := ReplaceFenced(Result, '`', '`', | ||
| Ansi.Dim + #27'[7m', #27'[27m' + Ansi.Reset); |
There was a problem hiding this comment.
Preserve markdown markers inside inline code
When a reply contains inline code that itself includes markdown-looking text (for example `**kwargs**`, `*.pas`, or `[x](y)`), this replacement only adds ANSI wrappers around the code span; the following bold/italic/link passes still scan the inserted body and consume those literal code characters. That contradicts the renderer’s stated behavior that inline transforms are suppressed inside code and causes common inline code snippets to be displayed incorrectly with markers stripped or styling spanning across separate code spans.
Useful? React with 👍 / 👎.
Codex P2: the original RenderInline ran inline-code wrapping FIRST
(\`code\` -> Ansi.Dim + reverse + body + reset) and then ran bold,
italic, strikethrough, and link transforms on the same string. The
later passes still saw the body characters inside the wrapped span
and ate any markdown markers that happened to appear there:
Input: use \`**kwargs**\` to splat
Buggy: the ** inside the code span gets transformed to bold,
so "kwargs" comes out bold and the literal ** is lost.
Input: the \`*.pas\` files
Buggy: the * starts an italic span that never closes, eating
everything after.
Input: see \`[x](y)\` syntax
Buggy: [x](y) inside the code becomes a styled link.
That contradicts the renderer's stated contract that inline
transforms are suppressed inside code spans.
Fix: standard placeholder pattern.
Pass 1 — extract every \`code\` span into a parallel array of
already-styled ANSI bodies. Leave a #1<index>#1 placeholder
in the string. SOH (#1) is the delimiter — models virtually
never emit it and it has no markdown meaning.
Pass 2 — bold (**), italic (*), strikethrough (~~), and link
transforms run on the placeholder-laden string. The
placeholders contain no markdown markers, so nothing scans
into them.
Pass 3 — substitute each placeholder back with its stored
code body. Final styled output drops in untouched.
5 assertions added to TestInlineCodeProtectsMarkdownMarkers:
- \`**kwargs**\` -> ** literals survive
- \`*.pas\` -> the * doesn't start an italic
- \`[x](y)\` -> the link syntax stays verbatim
- two adjacent code spans both stay intact
- a code span followed by genuine bold: code body protected,
real bold OUTSIDE still rendered.
make test-markdown-render -> all 12 cases OK (was 11)
make smoke -> all 11 commands OK
dcc64 reports:
[dcc64 Fatal Error] PasClaw.Cmd.Agent.pas(50): F2613 Unit
'PasClaw.Markdown.Render' not found.
The Makefile's UNIT_DIRS list got updated for FPC but the Delphi
project file didn't. .dproj has its own list — DCC_UnitSearchPath
plus an explicit DCCReference per .pas — and adds aren't
automatically synced from the Makefile side.
Two edits in PasClaw.dproj:
1. DCC_UnitSearchPath gains \`..\\pkg\\markdown\` so dcc64 finds
the directory on the search path (mirror of the Makefile's
UNIT_DIRS += src/pkg/markdown).
2. DCCReference Include="..\\pkg\\markdown\\PasClaw.Markdown.Render.pas"
added alongside the other pkg/* entries so the unit is part
of the project (and gets a build slot in the IDE).
No source changes. FPC build still clean.
dcc64 reports:
[dcc64 Fatal Error] PasClaw.Cmd.Agent.pas(50): F2613 Unit
'PasClaw.Markdown.Render' not found.
The Makefile's UNIT_DIRS list got updated for FPC but the Delphi
project file didn't. .dproj has its own list — DCC_UnitSearchPath
plus an explicit DCCReference per .pas — and adds aren't
automatically synced from the Makefile side.
Two edits in PasClaw.dproj:
1. DCC_UnitSearchPath gains \`..\\pkg\\markdown\` so dcc64 finds
the directory on the search path (mirror of the Makefile's
UNIT_DIRS += src/pkg/markdown).
2. DCCReference Include="..\\pkg\\markdown\\PasClaw.Markdown.Render.pas"
added alongside the other pkg/* entries so the unit is part
of the project (and gets a build slot in the IDE).
No source changes. FPC build still clean.
…+ localvector + Cmd.Memory dcc64 F2613 on PR FMXExpress#166: PasClaw.Cmd.Memory.pas(49): Unit 'LocalVector.Models' not found. Same shape as PR FMXExpress#156's miss after PR FMXExpress#155 — the FPC Makefile got the new unit dirs but the Delphi .dproj didn't. PR FMXExpress#165 added the in-tree localvector port under src/pkg/memory/localvector/ + the new PasClaw.Memory.Vector adapter; PR FMXExpress#166 added src/cmd/PasClaw.Cmd.Memory.pas. Neither was wired into PasClaw.dproj, so the Delphi build can't resolve LocalVector.Models / LocalVector.VectorStore / LocalVector.OrtProvision / LocalVector.VecProvision / LocalVector.Downloader / etc. Edits: DCC_UnitSearchPath Added `..\pkg\memory\localvector` (right after `..\pkg\memory` to keep the source-tree shape readable). DCCReference — pkg/memory Added `..\pkg\memory\PasClaw.Memory.Vector.pas` (PR FMXExpress#165 new file). Added all 13 in-tree localvector files under a fresh `pkg/memory/localvector` comment block: LocalVector.Models.pas LocalVector.Runtime.pas LocalVector.Sqlite3.pas LocalVector.Tokenizer.pas LocalVector.Embedder.pas LocalVector.VectorStore.pas LocalVector.VectorStore.Sqlite.pas LocalVector.VectorStore.FireDAC.pas LocalVector.Downloader.pas LocalVector.OrtProvision.pas LocalVector.VecProvision.pas onnxruntime.pas onnxruntime_pas_api.pas DCCReference — cmd Added `..\cmd\PasClaw.Cmd.Memory.pas` (PR FMXExpress#166 new file). Slotted next to PasClaw.Cmd.Membench.pas, matching the .pas filename ordering already present in this block. Stacks on PR FMXExpress#166 (which stacks on PR FMXExpress#165). Lands after both; merge order FMXExpress#165 → FMXExpress#166 → this.
TL;DR
Models emit markdown —
**bold**,# headings, fenced code, lists,[links](urls). PasClaw was printing all that verbatim with the raw stars and hashes showing through. picoclaw does the same (no markdown rendering in its agent loop, justprintln). nanobot uses Python'srichlibrary and renders markdown to styled ANSI for free. We pick the nanobot direction.New unit
src/pkg/markdown/PasClaw.Markdown.Render.pasSubset covered (~95% of what models actually emit):
# h1/## h2**bold***italic*/_italic_~~strikethrough~~`inline code````fenced```-/*bullet•glyph + indent> blockquote│bar + italic body[text](url)(url)in dimConfig knob
Cfg.RenderMarkdown— defaultTrue.pasclaw agent— wired via newMaybeRender(Cfg, Loop.Content)helper at bothRunSingleTurn+RunInteractivesites.pasclaw tui— wired via newTTUI.RenderMarkdownEnabledfield;Cmd_TUI_Runsets it fromCfg.RenderMarkdown.pasclaw serve/pasclaw gateway— left alone. They emit JSON to API clients; ANSI escapes would corrupt the wire body. TheirLoop.Contentflows throughWriteJSON/WriteSSE, not the renderer.Round-trips through
config.json: default-True emits no key; explicit"render_markdown": falsefrom operator preserves through save/load.Test plan
make test-markdown-renderruns 11 cases:TestPlainPassThrough— plain text byte-identicalTestBold,TestItalic,TestInlineCode— markers consumed, content + ANSI escapes presentTestHeading—#consumed,Ansi.BoldBlueappliedTestBulletList—-/*consumed,•glyph emittedTestFencedCode— body preserved, bold inside stays verbatim (no nested transforms)TestLink—[text](url)becomes underlined text +(url)in dimTestBlockquote—>consumed,│bar emittedTestEmpty— empty in, empty outTestNoTrailingNewlineAdded— streaming-friendlymake smoke— all 11 commands OKmake test-anthropic-server-tools/-openai-server-tools/-gemini-schema-strip— unchanged, OKpasclaw agent -m "in markdown, show me a heading, a bulleted list of three things, and a code block with hello world in python"— should render styled, no visible stars/hashes.Caveats (honest)
5 * 4 = 20would currently consume the asterisks. Same trap any non-word-boundary-aware markdown parser hits. Documented; can tighten if it bites.TStringBuildermath gets hairy. Easy to add later.CliUI_Inithas populatedAnsi.*— the test calls it explicitly. Production paths call it viaRunRootCommandstartup.https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code