Skip to content

Text & Markdown: shape code blocks one Layout per line (El::by_line) - #1133

Merged
Hona merged 10 commits into
devfrom
stream-code-by-line
Nov 18, 2026
Merged

Hona merged 10 commits into
devfrom
stream-code-by-line

Conversation

@Hona

@Hona Hona commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Streaming a fenced code block previously laid out the entire block in one parley::Layout (TextLayout::Single), reshaping all 0..L lines on every appended token (O(L) per commit). This PR adds El::by_line (crates/rune/src/el/paragraphs.rs, crates/rune/src/text/paragraphs.rs) and applies it to Markdown Block::Code (crates/rune-kit/src/markdown/render.rs) so each newline-delimited line shapes into its own Rc<Layout<Ink>> inside one ParagraphLayout while unchanged lines are reused across commits (O(1) trailing line shaped per token; long plain/colour-only fixed-pitch ASCII interiors wait as compact AsciiLine runs, and colour-only syntax spans bypass layout keying via span::layout_spans).

flowchart LR
  D["Appended code token"] --> K["key_paragraphs + span::layout_spans<br/>(strip CRLF CR; pack interior fixed-pitch ASCII lines into AsciiLine runs;<br/>colour-only spans skip line/run keys)"]
  K --> M{"Line / run key matches<br/>previous ParagraphLayout?"}
  M -->|Yes: settled lines 0..L-1| R["Reuse Rc&lt;Layout&lt;Ink&gt;&gt; or waiting run<br/>(0 HarfBuzz shaping)"]
  M -->|No: open trailing line| S["Shape 1 line (Keep::Owned);<br/>rebreak_at_y(y - floor(y)) if wrapped"]
  R --> P["Pre-paint fill_visible_by_line (shared visible_text_rows) → Single Node:<br/>pills/span-bg → highlights → strikes/link-fx → marks → selection → glyphs"]
  S --> P
Loading

Design & post-review updates (e23dcc73 over dev 1505f921)

  1. One Layout per line on a single Node (El::by_line):

    • Block::Code remains a single El / Node inside frame (role("code")), marked .by_line() (TextSpec::by_line). Element paths, ElementInfo, accessibility, Taffy's node count, El::reveal (RevealPhase), and El::selection_group membership stay identical to TextLayout::Single.
    • Single-layout fallbacks & text flights (El::by_line doc): El::by_line silently falls back to TextLayout::Single when the text does not wrap (!spec.wrap), is truncated or line-clamped, is live (El::live / El::advance_in), is redacted, is an input, or is a shared-run cell (text_spec.rs:290-294), and a text flight landing on a by_line node is dropped (paint/text_flights.rs:20) so the text appears in place without flying (set_pretty_wrap stays active on proportional by_line blocks and greedy on editors, salted by 0x7072_6574_7479_0001 in TextSystem::paragraphs so identical field and by_line texts never collide in cache).
    • Large code blocks, first-frame jump shaping, shared visible_text_rows, & #1116 span::layout_spans (paragraphs.rs, keying.rs, lazy.rs, runtime/text_fill.rs, paint/content.rs): TextSystem::paragraphs counts LAYOUT_BASE (2 KiB) per shaped line, keeps interior printable-ASCII lines (48..N-48 past LAZY_MIN) in fixed-pitch monospace faces (AsciiLine::fixed_pitch) as deferred AsciiLine runs (512 lines/run), filters key_paragraphs and split_run hashes through #1116's span::layout_spans (s.hash_layout) so syntax recolouring reshapes 0 lines, and shares visible_text_rows between fill_visible_by_line and paint_content so jumping into the middle of a 2,000-line block shapes visible interior lines on frame 1 (0 diff px vs settled across 1x, 1.5x, 1.875x).
    • Complete screen-reader TextRuns without accessibility trade (a11y/text.rs, paragraphs.rs, keying.rs, lazy.rs): a11y::text::lines builds exact TextRuns (Lines) for waiting AsciiLine runs directly from their ASCII text, fixed-pitch AsciiLine advances/height, per-line f64 y accumulation, and icu_segmenter word starts, matching Parley's shaped push_bidi_line_runs bit-for-bit (0 differing ranges and 0 differing device-pixel boxes). Non-ASCII, raw-\t, empty, RTL, or wrapping lines in a by_line block are not deferred by key_paragraphs — they shape eagerly in lay_out_paragraphs (< 1–2% of lines in real source code) and emit shaped TextRuns beside their waiting ASCII neighbours, while a11y_lines allows spec.by_line blocks past RUN_MAX_BYTES (64 KiB) up to LINK_BASE - 2 (32,766 runs) so both < 64 KiB and > 64 KiB 2,000-line code blocks publish full line-by-line and character-by-character runs immediately before any scroll.
    • Unified highlight decorations & restored Z-order (text/decorations.rs, paint/content.rs): highlight_decorations and highlight_decorations_flow share one push_highlight_boxes body, and paint/content.rs paints pill_chips -> decorations_with_rings -> highlight_decorations_flow -> strike_decorations -> link_fx across visible pieces beneath strikethroughs and link hover effects.
  2. What changes in the shared by-paragraph path outside code blocks (multi-line text fields / composer):

    • Fractional-scale wrapped paragraphs (1 device px fix): wrapped paragraphs below an earlier paragraph now break with rebreak_at_y(y - floor(y)) and sit at floor(y), moving wrapped sub-lines by up to 1 device pixel at 1.5x and 1.875x so pressing Enter matches single-layout line placement.
    • Selected newline & blank-line boxes: a selected newline's width comes from the line's last run (0.25 * (ascent + descent)), and a selected blank line's baseline comes from quantized base-font extents (blank_box).
    • Cross-paragraph paint order & \r stripping: multi-paragraph fields paint all decorations, then marks, then selections, then glyphs across visible paragraphs, and strip \r before \n from shaped paragraph slices while keeping spec.content byte offsets intact.

Verification (e23dcc73 over dev 1505f921: 24 files, +955 −508, 0 test files/attributes, 0 unsafe)

  • Farm tests (adais): all 439 / 439 rune-kit tests (0 failed, 3 ignored across all 50 binaries; proof/proof-farm/700de94f-5a0e-4850-bba4-9efdb39c6c28), 129 / 129 rune lib a11y + text unit tests (0 failed, 1 ignored; proof/proof-farm/ee83e1da-9089-4808-972d-1ad89ea7f9b9), and 90 / 90 passing rune text/selection/caret/links/deco integration tests across 21 binaries (0 new failures; proof/proof-farm/fc43060e-f7c7-4af0-b264-69dbac475ae0).
  • Driven rows in one capture ticket (proof/stream/pr1133-final-rows/summary.json, OPENCODE_RUNE_OTEL=0, UIA client):
    1. 2,000-line < 64 KiB (34,898 B, including an interior non-ASCII line) & > 64 KiB (95,779 B) UIA line + char walk & arithmetic-vs-shaped equality: before any scroll, UIA walks all 2,000 lines by TextUnit_Line and all 34,895 / 95,779 characters by TextUnit_Character with 0 holes; after scrolling every waiting line into view so all 2,000 lines shape, 0 / 2,000 ranges and 0 / 2,000 device-pixel boxes differ on either block (mid_viewport_differing_boxes = 0).
    2. Middle jump frame 1 (y = 20,000 pt): 0 diff px vs settled across 1x, 1.5x, 1.875x.
    3. Recolour (500 -> 900 colour-only spans on 2,000 lines): 0 layouts reshaped (109 initial shaped layouts).
    4. Field vs by_line block wrapping: greedy in text_input, pretty in by_line (1,201 diff px between them, 0 diff px vs standalone in both cache orders).

Per-token streaming Block::Code cost (proof/stream/code-by-line-timing/summary.json, pre-09:10 valid blade window)

Metric (commit frames, integer µs) Before (TextLayout::Single) After (El::by_line) Delta
text_shape p50 / p95 / max 393 / 871 / 1,463 69 / 135 / 290 -324 µs (5.7x faster) / -736 µs / -1,173 µs
layout p50 491 228 -263 µs (-53.6%)
commit phase p50 1,478 1,171 -307 µs
Commit frame total p50 (CPU p50) 2,867 (2,782) 2,491 (2,415) -376 µs (-367 µs CPU)

Hona added 2 commits November 17, 2026 23:29
Streaming a fenced code block previously reshaped the whole block's text on every appended token (`O(L)` lines per commit).

- Add `El::by_line` (`TextSpec::by_line`), laying out a multi-line static text element as one `ParagraphLayout` (`Rc<Layout<Ink>>` per newline-ended line) while keeping a single selectable `Node` in its resolved base direction (`Direction::Ltr` on `Block::Code`).
- Carry `ParagraphLayout` across commits and relayouts on `by_line` nodes, slice disjoint spans by binary search, strip `\r` before `\n`, and re-break multi-line wrapped lines at their accumulated fractional `line_y` phase (`rebreak_at_y`) so wrapped lines at fractional display scales (such as `1.875x`) quantize identically to a single `Layout`.
- Support `TextFlow::Paragraphs` across static text selection (`selectable`, `rects`, `text_marks`, `links`), `stream_height_lag`, `RevealPhase` word-fade byte mapping, and `highlight_decorations_flow` (including multi-line Find highlights crossing `\n` and blank lines), and mark `Markdown` `Block::Code` with `.by_line()`.
Copilot AI balanced review requested due to automatic review settings November 17, 2026 15:21

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@Hona

Hona commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

TEXT-2 review of 1921b799. Yes on the design, with three checks before merge (below). I read the diff against the five points I was asked about.

Point Reading Evidence in the PR Verdict
Tab stops Monospace: mono_tab_stops counts columns from each layout's byte 0, so a per-line layout resets at the line's start, as Single resets at \n. Proportional: tabbed expands tabs before by_line, so both arms see the same text. wide-tabs-bidi-hl, wrapped-prose-tabs: 0 px at 1x, 1.5x, 1.875x Yes
A wrapped line rebreak_at_y seeds parley's line_y with y - floor(y) and the paragraph sits at floor(y), so each wrapped line rounds as Single's accumulated line_y does. At 1.875x, 20 pt lines (37.5 px) hit that phase on every other line. wrapped-prose-tabs at 1.875x: 0 px Yes, with check 1
Selection and Find across lines flow.hit, flow.range_boxes and highlight_decorations_flow cover \n, blank lines (blank_box) and ringed highlights. Paint keeps decorations → marks → selection → glyphs across pieces. selected-marks (5-line drag, 2-line marks), copy strings identical Yes
Bidirectional text by_line keeps BaseDirection::Ltr per line. UAX #9 already splits Single into paragraphs at \n (and CRLF), so per-line resolution is the same. RTL comments and strings in wide-tabs-bidi-hl: 0 px Yes, with check 2
Byte-identical captures 18 of 18 pairs equal in RGBA and PNG bytes, element counts and copy strings, at all three scales and both themes. summary.json Yes for rest frames, with check 3

Checks before merge:

  1. A width change above a wrapped line. When an earlier line's wrap count changes (a resize, or a scroll bar appearing), every line below moves by a fraction of a line at 1.875x, so its y_frac changes even though its text didn't. Please confirm the kept-line path re-runs rebreak_at_y with the new phase, not just the new width. One capture shows it: wrapped-prose-tabs at 1.875x at a second width where line 2 wraps differently, before and after.
  2. Separators other than \n. A lone \r, U+2028 and U+2029 are hard breaks and (U+2029) bidi paragraph separators inside Single. Here they stay inside one line's layout. That should be the same, but no scene has one: add one line to wide-tabs-bidi-hl.
  3. A frame mid-stream. The captures are at rest, but the reuse path only differs while tokens arrive. One pair captured mid-token (the open last line wrapped at 1.875x) covers it.

Outside code blocks. The by-paragraph path now passes spec.pretty() where it passed false, so any text laid out by paragraph with pretty wrapping on now wraps prettily. That matches Single and looks right to me, but it is a change outside code blocks: please name it in the changelog.

For my own work. by_line layouts are Keep::Owned, so Tx::prepare_text's time-and-bytes bound (my next PR) doesn't count them. A code block in a prepared page is laid out in full, outside the bound. I'll handle that on my side; nothing is needed here.

@Hona

Hona commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

Windows whole suite (-p rune -p rune-kit) on adais, judged against dev's own failures at 32eb7811 (this lane, whole suite) and eb5ae6c9 (FUNCTION's run, rune only) and 3468f3a3 and cca5df6f: #1133 1921b799 (18 Nov 05:46): 2841 passed, 18 failed in 170 binaries; also on dev: alloc::disabled_trace_hooks_neither_format_nor_allocate, canvas_input::the_middle_button_drags_only_elements_that_take_it, rune::edit::tests::hidden_multiline_pristine_replace_and_delete, rune::edit::tests::pill_edge_cases_words_lines_bidi_and_direct_text_mutation, rune::edit::tests::the_caret_steps_over_a_pill_in_one_move, rune::input::keycaps::tests::repeated_chords_count_and_named_keys_use_glyphs, rune::native_surface::gpu_tests::mirrored_video_is_exact_cropped_centred_and_toggles_without_a_new_frame, rune::native_surface::gpu_tests::video_gpu_colour_sharpness_geometry_and_lifetime, rune::render::breaker::tests::a_refused_blur_pipeline_draws_unblurred, rune::render::layers::cache_tests::live_scale_zoom_sweep_buckets_during_motion_and_settles_crisp, rune::render::layers::rebind_tests::a_texture_switch_binds_no_parked_target_until_one_returns, rune::render::layers::tests::clipped_single_draw_fades_do_not_allocate_targets, rune::runtime::tests::layout_rows::send_flight_follows_the_measured_bubble_while_earlier_rows_land, rune::runtime::tests::picture_scale::a_changing_static_scale_keeps_the_glyph_atlas_bounded, rune::runtime::tests::picture_scale::text_inside_a_scale_draws_at_that_size, rune::runtime::tests::scroll_children::scroll_xy_with_direct_children_scrolls_both_axes_and_warns_on_trailing_growth_sibling, rune::text::macos::smoothing::tests::pipelines_never_share_masks, selectable_text::copy_select_all_and_the_context_menu; none new. Base cca5df6f. Proof 5866f3f7.

@Hona

Hona commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

TEXT-2, on the independent read's two findings (notes/review-1133.md). I agree with both.

  1. Pretty wrapping in the composer's drafts (must fix). I flagged the spec.pretty() change outside code blocks in my review but called it right. The read shows it isn't: pretty wrapping re-scores the last lines as you type, so words before the caret move between lines, and editors keep greedy lines (text/pretty.rs:21-24). Use spec.by_line && spec.pretty(). Every other by-paragraph text then keeps false as before, and a proportional code block keeps its identity with Single.
  2. Highlight fills over strikethroughs and link effects (should fix). The order should stay highlight fills, then strikethroughs and link effects, then glyphs. That is the order before this PR, and it is Chromium's: a mark's background is under the text's decorations. Since the same path now paints single layouts too, please re-run one capture with a struck-through word inside a Find highlight, before and after, at 1x and 1.875x.

Hona added 3 commits November 18, 2026 08:14
…e by_line runs, and unify highlight decos

Address review findings on `El::by_line` (`notes/review-1133.md` and TEXT-2 review):
- Pass `spec.by_line && spec.pretty() && !input` in `lay_out_paragraphs` (`crates/rune/src/text/paragraphs.rs`) so multi-paragraph drafts in editors keep greedy line breaking (`pretty.rs`) instead of re-breaking earlier lines as the user types.
- Give an empty trailing slice after `\n` zero height on `spec.by_line` so `text("a\n").by_line()` and closed fences with a trailing blank line match `TextLayout::Single`'s height.
- Restore decoration paint order (`pill_chips` -> `decorations_with_rings` -> `highlight_decorations_flow` -> `strike_decorations` -> `link_fx`) in `crates/rune/src/runtime/paint/content.rs` so Find match fills paint beneath strikethroughs and link hover effects on both ringed and ringless paths.
- Count `LAYOUT_BASE` per shaped line in `TextSystem::paragraphs` cache entries, and keep `AsciiLine` waiting runs for off-screen lines of large plain or colour-only `by_line` blocks (`crates/rune/src/text/paragraphs/{keying,lazy}.rs`, `crates/rune/src/runtime/text_fill.rs`).
- Extend `a11y::text::lines` (`crates/rune/src/a11y/text.rs`) by 2 bytes over `\r\n` so screen-reader text runs cover CRLF code blocks end to end.
- Unify `highlight_decorations` and `highlight_decorations_flow` onto one `push_highlight_boxes` body in `crates/rune/src/text/decorations.rs`, and document `El::by_line`'s single-layout fallbacks and dropped text flights.
@Hona

Hona commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Addressed all five review findings and your three checks in fast-forward head f5bd107067b7586085043808ab4ca02eb340f194 (0 test attributes added, 0 unsafe lines added):

  1. Greedy editor wrapping (paragraphs.rs): lay_out_paragraphs now passes spec.by_line && spec.pretty() && !input to layout_keyed, so multi-paragraph drafts in editors and non-by_line dir_by_paragraph blocks keep false as on dev, while proportional by_line code blocks keep spec.pretty(). Also posted the 1-line notice on fractional-scale wrapped paragraphs (rebreak_at_y(y - floor(y)) + floor(y), up to 1 device px at 1.5x/1.875x) in notes/text-2-status.md and notes/layout-cards-status.md, and updated the changelog fragment and PR body.
  2. Highlight fills under strikethroughs and link effects (paint/content.rs, text/decorations.rs): restored pill_chips -> decorations_with_rings -> highlight_decorations_flow -> strike_decorations -> link_fx across visible pieces, and unified highlight_decorations and highlight_decorations_flow onto one push_highlight_boxes body. Verified on GPU captures (proof/stream/pr1133-review-gate/captures/after-struck-find-{noring,ringed}-{dark,light}-{1x,1.5x,1.875x}.png, using session-view/src/style.rs's exact ringless opaque #009fff active hit and 0.28-alpha inactive hits): 1921b799 differed by 86 (1x), 223 (1.5x), and 277 (1.875x) px over the strike line; f5bd1070 has 0 differing RGBA pixels at 1x, 1.5x, and 1.875x (dark & light).
  3. Your three checks (proof/stream/pr1133-review-gate/captures/):
    • Check 1 (width change above a kept wrapped line at 1.875x): paragraphs.rs compares (want_frac - have_frac).abs() > 1e-5 after computing the new y and re-runs rebreak_at_y + layout_ids.build on kept wrapped lines whenever an earlier line's wrap count shifts y_frac. Captured wrapped-resize-{dark,light}-1.875x.png (680 pt -> 430 pt, where line 2 wraps from 2 to 3 sub-lines above kept wrapped line 3): 0 differing RGBA pixels vs a fresh Single render at 430 pt.
    • Check 2 (lone \r, U+2028, U+2029): captured separators-cr-ls-ps-{dark,light}-{1x,1.5x,1.875x}.png (including U+2029 before Arabic RTL and 4-col tabs): 0 differing RGBA pixels across all 6 pairs. Also extended a11y/text.rs:37 over \r\n (2 bytes) and confirmed pulldown-cmark normalizes \r\n to \n at CommonMark intake.
    • Check 3 (mid-stream wrapped open line at 1.875x) + emoji/CJK/combining + trailing \n: captured mid-stream-wrapped-{dark,light}-1.875x.png, emoji-cjk-combining-{dark,light}-{1x,1.5x,1.875x}.png, and trailing-newline-{dark,light}-{1x,1.5x,1.875x}.png: 0 differing RGBA pixels across every pair.
  4. Large by_line blocks (paragraphs.rs, keying.rs, lazy.rs, runtime/text_fill.rs): TextSystem::paragraphs now counts LAYOUT_BASE per shaped line, and large plain/colour-only by_line blocks keep interior ASCII lines (48..N-48) as deferred AsciiLine runs (Keep::Owned remains on shaped lines, as you noted for prepare_text).

@Hona
Hona merged commit 698ad26 into dev Nov 18, 2026
1 check passed
overp0werj0int added a commit to overp0werj0int/rune that referenced this pull request Nov 18, 2026
This reverts commit 2bd88e5 and keeps its test. Upstream's reworked
paragraph painting (Piece and TextFlow::Paragraphs, anomalyco#1133, with
colour-only spans resolved at glyph emission, anomalyco#1116) cuts highlights to
each paragraph itself: tests/highlight_pieces.rs passes on upstream's dev
without this commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
overp0werj0int added a commit to overp0werj0int/rune that referenced this pull request Nov 18, 2026
This reverts commit 0d291cc. Upstream's highlight_boxes_in now reads a
field's boxes through TextLayout::view and TextFlow::range_boxes, which
covers a by-paragraph field (anomalyco#1057, with TextFlow::Paragraphs carried
through links, rects and selectable in anomalyco#1133), and links::origin takes a
TextFlow there too. Quire's find-in-source tests (wr_118_*) check it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Hona added a commit that referenced this pull request Nov 21, 2026
…1292)

* feat(rune-kit): native code-block soft wrapping and text-wrap icon

Add native code-block soft wrapping to `rune-kit::markdown` and the
`text-wrap` icon (`icons::TEXT_WRAP`) to `rune-theme-opencode` for
`anomalyco/opencode#64545`:

- `MarkdownStyle::wrap_code(bool)`, `Markdown::wrap_code(bool)`, and
  `Markdown::code_wrap(Fn(usize, &str) -> bool)` wrap long lines inside
  `Renderer::code` via `.by_line().wrap_anywhere().wrap_greedy()` while
  keeping `#1133` per-line shaping, screen-reader `TextRun` line runs,
  `#1130` `settled_code_card_digest` memoisation, Find highlights,
  streaming reveal, `.copy_breaks(2, 2)`, non-mono tab stops, and shell
  block colours.
- Unwrapped blocks (`!wrapped`) remain identical to before.
- `Source` computes longest-line tab-expanded stats once at parse time;
  `CodeFrame::overflows` answers overflow against `text_width - flow.inset`
  in O(1) on the ASCII monospace fast path (falling back to
  `rune::text::measure` only near the boundary or for non-ASCII/non-mono).
- `CodeFrame::wrapped` reports the block's active wrap state.
- `rune-theme-opencode::icons::TEXT_WRAP` adds Desktop's `text-wrap` SVG.

* fix(rune-kit): address review #1292 findings (stable body path, lazy exact overflows, lock-free font_epoch, line reuse, scoped memo)

* fix(rune-kit): revert paragraphs.rs scope creep, clear ascii/paragraphs on font switch, Acquire/Release font_epoch, bound control chars
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants