Keel v0.5.1 中文 GitHub

Markdown

ui/markdown renders Markdown into ui/el elements, aiming at the characteristics of AI chat: answers arrive in several words, and the longer they are written, the longer they are.

doc := markdown.New("").OnLink(openInBrowser)
doc.SetStreaming(true)

go func() { // Read streaming output of a model
    for tok := range tokens {
        core.Update(func() { doc.Append(tok) })
    }
    core.Update(func() { doc.SetStreaming(false) })
}()

// In the Render of the view
el.Div().Child(doc.Render(cx))

All methods of Doc must be called under the UI lock: directly in the callback, and other goroutines through core.Update.

Complete example: examples/chat, simulates streaming answers, the message area follows to the end, and can be stopped midway. The blank page provides six verification examples: cross-paragraph selection, mathematical formulas, long codes, double-click and triple-click, footnotes and references, and pictures; go run ./examples/chat -sample=all directly displays the complete content. Add -lang zh-CN for the Chinese UI and sample documents. The sample instructions list how to check for each interaction.

Markdown plugin

doc.Plugins(markdown.Plugin{...}) Registers Goldmark syntax extensions and native rendering factories for a single document. Extensions takes goldmark.Extender, which can install block-level/inline parsers or AST transformations; Blocks returns el.View by ast.NodeKind, Inlines returns InlineObject{Text, Widget}. Later registrants cover similar nodes. Use the built-in conversion when a block factory returns nil, or an inline factory returns an empty literal/nil widget.

Inline objects are measured and wrapped as a whole, bottom aligned to the text baseline; Text is a representation of a range of text that is selected, copied, and rendered. Double-click to select the entire object. The object itself provides semantics and interaction, and its dynamic size is remeasured every frame; its drawing does not participate in text fading. Block-level custom views render each frame, manage text selection by themselves, and do not add optional text to the document. Nodes inside code fences and generated by HTML transformations are not mapped by plugins.

Configure the plugin on initialization and don't re-register it every frame. Registration/removal will rebuild the parsing results, clear the selection and pending location requests. Documents containing plug-ins are parsed in their entirety, allowing custom blocks to work across empty lines, unless every plugin sets Local: true (its syntax never spans a blank line, as inline objects and per-block renderers): those documents keep blank-line chunks, so a streaming append reparses only the last chunk; the factory may be called again during editing, and the control status that needs to be retained is reused by the application according to business identifiers. The callback is executed within the UI lock and cannot modify the document being parsed; the incoming AST and source code are read-only. Plugins() Remove all plugins. Plug-in code is application code, there is no sandbox.

The component library text_view demonstrates rendering the specified reference into a reminder card and replacing the @Keel code snippet with an inline label. Automatic testing covers document isolation, default fallback, custom syntax and nested blocks, application state reuse, inline control click/select copy, append and logout. Native window interaction is still pending acceptance.

Registering a plugin does not disable the view/layout cache for ordinary completed blocks. Only blocks that contain an actual custom view or inline object (including objects nested in lists, quotes or table cells) rebuild each frame, so dynamic controls still update without rebuilding unrelated content.

Streaming fade in

doc.StreamFade(true) turns on the fade-in of new text, with a default of 350ms and three fade-outs; StreamFadeDuration(500*time.Millisecond) can be adjusted to 0–10 seconds, with zero indicating immediate display. The full text will not be animated for the first display; subsequent Append or SetSource whose content begins with the original text will be timed for the new text. The animation of consecutive clips overlaps, and previously started clips are not reset.

The timing is retained according to the rendered text and style, and the text that changes in font weight, color, etc. when completing Markdown will fade in again. The replacement full text is displayed directly, and it is also displayed immediately when the system or application turns on the reduced motion. The text is typed only once, and the animation draws glyphs and text decorations in segments; selections, range highlights, backgrounds, pictures, code card buttons and streaming cursors do not fade in. Custom code renderer manages animations on its own.

Passed continuous append, syntax completion, animation reduction and 1×/2× GPU pixel tests; stable text does not enter the transparency layer and avoids anti-aliasing color changes. Component library text_view's "Demo Streaming Fade" appends text, bold, and code snippets at 120ms intervals.

Collapse preview

Tables are as wide as their content: each column takes its widest cell's single-line width, the same in every row. Column widths follow the text scale (sp). Tables wider than the document scroll horizontally instead of shrinking columns; the scrollbar has space below the last row.

Internal row and column dividers use theme.Border. Column dividers span the full row height, including wrapped cells; these dividers remain visible with Palette.Frameless, which suppresses the table's outer outline.

doc.TableDividers(false) hides internal row and column dividers; TableDividers(true) restores them (the default). It takes effect on the next frame for existing and streamed tables without changing their layout, content or selection. The outer outline follows the palette independently.

doc.MaxLines(6) Limit the entire article height to six body lines (theme.BodySize × 1.6), with font scaling, headings, paragraph spacing, tables, and code cards all accounting for this budget. MaxLines(0) cancels the restriction; IsClamped() returns whether the content is indeed hidden in the previous drawing frame, and the expand button can be displayed accordingly. Limit is 1–100000 rows, negative numbers are considered cancelled.

doc.MaxHeight(dp) uses a density-independent height budget instead of body-line counts; it replaces MaxLines, and calling MaxLines replaces the height budget. Zero, negative or non-finite heights remove the limit. IsClamped, whole-line clipping and full-text selection/copy follow the same rules as MaxLines. This lets applications match a window-relative message preview without discarding the source.

For normal text, the entire line is hidden when it spans the bottom edge; for images and single lines above the entire budget, the portion that falls within the box is retained. When the next row of the table cannot even fit the first row of text, the leading border and white space of the row will be hidden. Components don't automatically add ellipses or expand buttons; custom code cards are cropped by the box. Ignore interval positioning requests during preview and call RevealRange after expansion. The full text remains in RenderedText and SELECT ALL COPY.

The double ratio layout test covers long text folding, expansion and content replacement, and the GPU pixel test checks that mixed table content does not cross the bottom edge of the preview. The component library text_view demonstrates the collapsed, expanded and truncated states.

Render text range

RenderedText() returns the most recently drawn selectable text, which was empty before the first draw; it retains the inter-block separator and does not include the contents of list markers, buttons, flow cursors and custom code cards. After replacing the source text, wait for the next frame to be drawn and then take the offset. TextRange{Start, End} uses the UTF-8 byte half-open range of this text and cannot directly apply the Markdown source code location.

SetRangeHighlights([]RangeHighlight) replaces the background highlight in the entire batch, and nil clears it. When out-of-bounds, reverse order, truncated UTF-8 characters or source text have not been drawn, return false and retain the original highlighting; empty intervals are not drawn. The subsequent item covers the previous item, and the selection is above the highlight. The separator itself does not have a rectangle, and the cross-block intervals are drawn behind each block of text. When the source text is updated, highlights that completely fall within a common prefix or suffix are retained and migrated, and highlights that involve intermediate changes are removed; intermediate moved text is not tracked.

RevealRange(r) Requests the nearest ScrollY to expose the line where the interval starts with minimal vertical scrolling, allowing empty intervals. Returning true only indicates that the range is valid and does not guarantee the existence of scrollable ancestors. Only the latest request will be kept, if the source text changes or it will be canceled after one second timeout. Do not adjust horizontal scrolling inside code blocks.

Automatic testing covers Chinese UTF-8 boundaries, invalid update atomic rejection, suffix migration, overlapping highlighted pixels and bidirectional scrolling positioning. The component library text_view provides highlight, clear and position buttons.

YAML front matter

The YAML metadata between --- at the beginning of the document (commonly used in static site generators and note-taking software) is not included in the text and is not displayed by default:

d := markdown.New(src)
d.Meta()["title"]        // Top-level key: value, remove the quotes at both ends
d.FrontMatter()          // Raw YAML, nested or list values ​​passed to YAML parser
d.ShowFrontMatter(true)  // Appears as a key-value table at the top of the document

Only the block at the beginning of the document with an end line (--- or ...) is recognized; it is also displayed as the original text when the end line is not written in streaming output. The --- in the middle of the document is still a separator.

Supported syntax

Paragraphs, headings, bold, italics, strikethrough, inline code (gray base), links (underlined on hover), automatic links, code blocks with syntax highlighting (when ui/highlight is introduced) and copy button, quotes, ordered/unordered/task lists, GFM tables (supports alignment), separators. Supports images, footnotes and cross-block reference links.

HTML: Render into rich text and do not display the source code.

  • In-line tags: <b> <strong> <i> <em> <u> <ins> <s> <del> <mark> (highlight background), <code> <kbd>, <sup> <sub>, <a href>, <br>, <img src alt>.
  • Block-level HTML is converted into corresponding Markdown blocks: <h1>–<h6>, <p>, <div>, <ul> <ol> <li>, <blockquote>, <pre><code class="language-go">, <table> (<th> or <thead> is used as the header, align is aligned), <hr>.
  • The <summary> of <details> is displayed in bold, and the content is expanded as usual; the Markdown content separated by blank lines is rendered as usual.
  • <script>, <style>, form, <iframe>, etc. are discarded together with their contents and nothing is executed.
  • Comments are hidden; "tags" that are not HTML element names are displayed as original text, so Vec<String>, List<T> will not disappear.

Selected Copy: Drag from a paragraph, title, quote, list, code block, or table cell to select text across blocks. Double-click to select words based on Unicode word boundaries (Chinese by word), triple-click to select the entire paragraph; triple-click the code block to select the current source code line. Double-click or triple-click then hold-drag to expand the selection by whole words or paragraphs. Cmd/Ctrl+C copies the selection, Cmd/Ctrl+A selects this document, and clicks elsewhere to cancel. When dragging to the top and bottom edges, the nearest ScrollY() container automatically scrolls; hold down the mouse or release it to use the scroll wheel. Copying is the plain text of the display: blank lines between blocks of text, tab-delimited table cells, and line breaks between lines; no list markers, language labels for code blocks, copy buttons, or streaming cursors. The copy button for a code block still only copies that block of code.

Code block: The code icon and language name are displayed on the left side of the rounded corner card. When no language is specified or marked as text, txt, plaintext, "plain text" is displayed; line break and copy icons are provided on the right side, operation prompts are displayed on hover, and the check icon is briefly displayed after the copy is successful. By default, the code lines of the source text are retained. Long lines can be viewed through the horizontal scroll wheel, touch pad or bottom scroll bar; the entire bottom track supports clicking and dragging. When the mouse is stopped on the scroll bar, the ordinary scroll wheel can also scroll left and right; click "Automatic Wrap" to wrap lines according to the width of the code area, and click again to restore the original line. The language name and button are fixed, each code block saves the newline and scrolling status independently, and streaming append will not reset these statuses.

Mathematical formula: $...$ is typeset with the text baseline, $$...$$ is independently centered. Native typesetting support:

  • Superscript and subscript, fraction, root sign, \binom;
  • Greek letters and variations, about 200 relations, arrows, operators, and miscellaneous symbols, \not negation;
  • Large operators: sum, integral, \bigoplus, etc. In display mode, the upper and lower limits of \sum, \lim, and \max are at the upper and lower limits;
  • Font: \mathbb, \mathcal, \mathfrak, \mathsf, \mathtt, \mathbf, \boldsymbol, \mathrm, \text;
  • Accent: \hat \bar \vec \dot \ddot \tilde \check \breve \acute \grave, and \widehat, \overline, \underline, \overrightarrow;
  • Structure: \overbrace, \underbrace (with label), \overset, \underset, \stackrel, \boxed;
  • Color: \color, \textcolor, \colorbox, common color names or #rrggbb can be used;
  • Spacing: \phantom, \quad, \hspace, etc.;
  • Environment: matrix, pmatrix, bmatrix, Bmatrix, vmatrix, Vmatrix, cases , aligned, align, split, gather, equation, array, smallmatrix, and \tag.

Matrices can be nested, with \left / \right separators scaling with the content (. hides one side). Supports \newcommand, \renewcommand, \providecommand and \def without separated parameters, up to 9 parameters; \newcommand can set the default value of the first parameter. Macros take effect in document order and are cleared after replacing the document. Fractions and matrices expand the line height, formulas are wrapped and selected as a whole, and the TeX source code with delimiters is retained when copied. The dollar sign in the code does not participate in parsing; formulas that are not closed, have syntax errors, or contain unknown commands will display the source code and be retyped after streaming completion. No external TeX service required.

Footnotes and Quotations: Quotation definitions can be placed in subsequent paragraphs, and full, collapsed, and abbreviated quotations share the document context. Footnotes are sorted by first occurrence; click on the superscript to jump to the footnote at the end of the text, and click on the return arrow to return to the corresponding reference. Repeated references have their own return positions, and multiple footnotes retain their format.

Image: Asynchronously load local path, file://, data URL, and HTTP(S) address after introducing ui/netimage, support PNG, JPEG, GIF first frame and WebP. Shrink to the width of the container according to the original aspect ratio, and display the placeholder with alternative text during loading and when it fails; the layout will be re-layout after loading is completed, and resources will be shared at the same address of the same document. The default path is relative to the working directory; when authentication or a relative document path is required, configure doc.ImageLoader(func(context.Context, string) (image.Image, error)) before rendering for the first time. Copy the alternative text of the image to the selected area, and the linked image is still clickable. Default loader limits 16 MiB files, 32 megapixels, and 15 seconds request time.

How to make streaming rendering fast and stable

1. Split by blocks and only parse changed blocks. The source text is cut into top-level blocks at "blank lines outside code blocks and independent formulas", and each block is parsed and cached separately. When appending text, only the content of the last block changes, and only it is reparsed. A blank line is not followed by indentation (line continuation of list items, indented code).

When there are footnotes, reference definitions or mathematical macros, they need to be parsed according to the entire document so that subsequent definitions can affect previous references and the macros can take effect across sections; unchanged blocks still reuse the view and layout cache. Ordinary documents keep tail blocks incrementally parsed.

Test TestStreamingReparsesOnlyTheTail appends 2KB of answers verbatim, parsing no more than "number of appends + 2 × number of blocks", not "number of appends × number of blocks".

2. Temporarily complete unclosed syntax. During streaming, unclosed **, *, backticks, ~~, and [text](url are temporarily completed before parsing. For example, **bold appears bold immediately rather than showing the asterisks and changing once the closing ** arrives. Unclosed code fences need no repair: the parser extends them to the end. When the answer finishes (SetStreaming(false)), the final paragraph and block are parsed again from the original text.

3. Completed blocks skip reconstruction and rearrangement. The written block is cached through cx.Cache: both the element tree and layout results are reused, spending almost no time on each frame; only the block being written is rebuilt each frame. Rich text blocks also cache measurement results to avoid being typed repeatedly in the same frame.

4. Don’t draw what you can’t see. Elements outside the scroll container skip drawing.

Results (Apple M series, appending one frame at a time rendering, layout, and drawing; go test -bench StreamingFrame ./ui/markdown):

Document size Time spent per frame Before optimization
2 KB 0.19 ms 1.3 ms
11 KB 0.52 ms 5.0 ms

The one frame budget at 60Hz is 16ms. The time before optimization is mainly spent on rich text being fully typeset three times per frame; see Design Decision for details.

Supporting capabilities of chat interface (in ui/el)

Capabilities Usage
Follow to the bottom Add StickToBottom() to the scrolling container: when it is at the bottom, it will stay at the bottom as the content grows; it will stop when the user scrolls up, and resume when scrolling back to the bottom
Send a message and jump to the bottom ScrollToEndOn(len(msgs)): Jump to the bottom and resume following when the parameters change
Copy The code block comes with a copy button; use el.WriteClipboard(text) for your own button
Cursor During streaming output, a cursor is displayed at the writing position

Custom made

Package-level variables, modified before rendering:

variable default description
CodeBg #f0f1f3 CODE BLOCK BACKGROUND
CodeBorder #e3e5e8 Code block border
CodeHover #e2e5e9 Code block button hover and selection background
InlineCode #1f2328 Inline code color
CodeStyle github chroma highlight style name (needs to introduce ui/highlight)
MonoFace theme.MonoFace Code font, Chinese falls back to the Chinese font in theme.Face

Title, text color and font size follow ui/theme.

What can Agent see?

The paragraph and title are text; each link in the paragraph is a separate link element, and the value is the URL, which can be directly click; the code block is code, the name is language or "plain text", and the code text, "auto wrap" or "cancel wrap" button, and "copy" or "copied" button are listed separately; the table is table and row. Image is image, name comes from alt text, value means loading, loaded or error; footnote is footnotes container, reference and return arrows are directly clickable.

Typesetter

Paragraphs and codes use the own rich text formatter in text.go. The line wrapping algorithm comes from gioui.org/x/styledtext. In addition, the position of each paragraph of text in each line is recorded, so it can draw things that Gio rich text cannot draw: the background color of the inline code, strikethrough, link underline and selection, and give each link a separate click area. The line height of ordinary text is fixed (1.6 times the text size, 1.45 times the code size; formulas and pictures can expand the line height), the fonts are vertically centered within the line, and different font sizes share the baseline, so mixed Chinese and English, and Chinese comments in the code will not make a certain line higher or higher.

selection.go Maintains a rune-count selection for the entire document. Before drawing, read the layout position of each text block, unify paragraph indentation, code inner margins, and table column positions to document coordinates, and then map the selection back to each block to draw highlights. After scrolling, it is still positioned according to the document coordinates; the selection is retained when the stream is appended or ended, and the selection is cleared when SetSource replaces the content. Dragging from a link does not open the link and clicking still triggers OnLink.

Known limitations

Mathematical typesetting covers common TeX in daily life and textbooks, but it is not a complete TeX engine: it does not execute TeX packages, file commands or arbitrary code; unsupported commands retain the source code. Macro expansion limits recursion depth and output length, and does not provide full TeX grouping scope or the delimited \def argument. The image does not decode SVG yet, nor does it play GIF animation.

Doc.CodeBlockActions(func(*el.Context, markdown.CodeBlockContext) el.Element) Adds an operation at the end of the default code block title bar, retaining the copy and line break buttons; returns nil to not add, and passes nil to remove the extension. The context contains the stable impression ID, language, original code text, and current wrapping status. The code does not execute automatically, the business behavior of the button is provided by the application.

Doc.CodeBlockRenderer(language, fn) Replaces the entire code block card by language, language keys ignore case, empty language matches no language code. Use the default code card when the callback returns nil, pass nil to log out. After replacing the display, buttons, text selection and copying are implemented by the application; CodeBlockActions are not automatically superimposed. Code source documentation remains unchanged.

The two types of callbacks only construct elements during rendering and should not modify the Doc; application state modifications are placed in the event handling function. Containing blocks such as lists and references where the code block is located will also be rebuilt to refresh the custom control state; the rest of the document continues to use the block cache. Presentation IDs are stable while the parser retains code block state and are not persistent document identifiers.

Example: go run ./examples/components -section text_view. Automated tests verify nested action clicks, wrap state and ID retention, cache updates after replace/logout, and default replication recovery. See above for the general parsing plug-in; the complete interaction with the native window has not yet been accepted.

Selection across documents

A Doc has an independent selection by default. Keep a SelectionGroup to join separate messages into one text flow, including messages in embedded roots or a virtual list:

var selection markdown.SelectionGroup // retain across frames
selection.SetDocuments(first, second, third) // complete reading order
// Inside Render, after constructing the common ancestor:
return selection.Decorate(cx, el.Div().Child(first.Render(cx), second.Render(cx), third.Render(cx)))

The ancestor must stay mounted during the drag; put the virtual scroller inside it. Embedded roots must use LayoutIn to inherit coordinates and scroll parents. Pass each document once, and omit collapsed details and controls. Dragging and Cmd/Ctrl+A/C work across document boundaries, with blank lines between messages. Selection stays attached to its documents when history is prepended or appended. Append retains endpoints; SetSource on a member clears the shared selection.

Idle rendering still mounts only visible rows. On selection, previously unseen documents are measured once offscreen to obtain their rendered text for copying. Text and document offsets are cached until content changes. Custom rendered controls are not part of the Markdown selection.

Body text, headings, table measurements and code labels follow theme.Material.Face, matching standard controls. Code retains markdown.MonoFace. Changing either font invalidates cached document views without changing source text.

Streaming fade boundaries before a space fall inside that space, preserving the preceding glyph’s overhanging ink when the font changes. Adjacent fade spans share the same boundary.