From dc070dcba60c9810c2519341ddf6b3cd81fde277 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 19:11:25 +0000 Subject: [PATCH 1/5] Split stacks with a background or a border across pages A stack or a grid with a background or a border moved whole to the next page, and raised when it was higher than a page. It now breaks pages like a plain stack: its decoration is drawn on each page around what that page holds of it, beneath the content, with its padding kept clear at the top and bottom of every page. keep_together: true still moves it whole. Assisted-by: Claude [Claude Code] --- docs/guide.html | 2 +- lib/gamba/native/layout.rb | 130 +++++++++++++++++++++++++++++++++---- test/native_grid_test.rb | 11 +++- test/native_layout_test.rb | 48 +++++++++++++- 4 files changed, 171 insertions(+), 20 deletions(-) diff --git a/docs/guide.html b/docs/guide.html index abee7b6..f85d98c 100644 --- a/docs/guide.html +++ b/docs/guide.html @@ -121,7 +121,7 @@

Gamba’s own API

end end

Every container takes gap, padding (one number, [vertical, horizontal] or [top, right, bottom, left]), background, border_width and border_color.

-

A stack breaks pages between its children, and a text between its lines. A grid breaks them between its lines. A row, a line of a grid, and a stack or a grid with keep_together: true, a background or a border move whole to the next page when the rest of this one is too short; one that is higher than a page raises Prawn::Errors::CannotFit, saying which box and by how much.

+

A stack breaks pages between its children, and a text between its lines. A grid breaks them between its lines. A stack or a grid with a background or a border is drawn around each page’s part of it, its padding kept clear at the top and the bottom of every page. A row, a line of a grid, and a stack or a grid with keep_together: true move whole to the next page when the rest of this one is too short; one that is higher than a page raises Prawn::Errors::CannotFit, saying which box and by how much.

Pages break where a reader expects them. A paragraph never leaves fewer than orphans lines at the bottom of a page, nor fewer than widows at the top of the next: 2 each unless told, 1 to break anywhere. A paragraph too short to keep both moves whole to the next page; one that starts a page fills it whatever its rules.

A box with keep_with_next: true goes to the next page together with the start of the box after it: the first lines of a paragraph, the header and first row of a table, all of a box that cannot be split. Headings are the usual case, so the three can sit in a style:

document.style :heading, size: 16, weight: :bold, keep_with_next: true
diff --git a/lib/gamba/native/layout.rb b/lib/gamba/native/layout.rb
index a45a80c..37353eb 100644
--- a/lib/gamba/native/layout.rb
+++ b/lib/gamba/native/layout.rb
@@ -40,6 +40,90 @@ def next_page
         @prawn.bounds.move_past_bottom
         @page_top = @y = @prawn.y
       end
+
+      # Flows a decorated stack's children within its bounds, which keep its padding clear on every page.
+      def within(bounds)
+        @prawn.bounds = bounds
+        @page_top = bounds.absolute_top
+        yield
+      ensure
+        @prawn.bounds = bounds.outer
+        @page_top = @prawn.bounds.absolute_top
+      end
+    end
+
+    # The bounds of a stack with a background or a border while it flows across pages: its padding kept clear at
+    # the top and the bottom of each page, its decoration drawn on each page beneath what that page holds of it,
+    # as CSS's box-decoration-break: clone does. Text and tables break pages through these bounds, so each break
+    # closes the stack's part on one page and opens it on the next.
+    class DecoratedBounds < Prawn::Document::BoundingBox
+      def initialize(prawn, stack, left, width, padding_top, padding_bottom)
+        parent = prawn.bounds
+        super(prawn, parent, [parent.absolute_left, parent.absolute_top], width: parent.width, height: 0)
+        # The margin box is made anew on each page: bounds within it follow the current one.
+        @within_margins = parent.equal?(prawn.margin_box)
+        @stack = stack
+        @left = left
+        @box_width = width
+        @padding_top = padding_top
+        @padding_bottom = padding_bottom
+      end
+
+      def outer
+        @within_margins ? @document.margin_box : @parent
+      end
+
+      def absolute_left
+        outer.absolute_left + total_left_padding
+      end
+
+      def width
+        outer.width - total_left_padding - total_right_padding
+      end
+
+      def absolute_top
+        outer.absolute_top - @padding_top
+      end
+
+      def absolute_bottom
+        outer_bottom + @padding_bottom
+      end
+
+      def height
+        absolute_top - absolute_bottom
+      end
+
+      def stretchy?
+        false
+      end
+
+      # The stack's part on this page reaches down to the bottom of what holds it, and its next part starts at the
+      # top of the next page.
+      def move_past_bottom
+        end_part(outer_bottom, skip_empty: true)
+        outer.move_past_bottom
+        start_part(outer.absolute_top)
+        @document.y = absolute_top
+      end
+
+      # The stack's part on this page starts at top: what is drawn from here is drawn over its decoration.
+      def start_part(top)
+        @top = top
+        @offset = @document.page.content_stream.bytesize
+        @graphic_state = @document.graphic_state.dup
+      end
+
+      def end_part(bottom, skip_empty: false)
+        return if skip_empty && @document.page.content_stream.bytesize == @offset
+
+        @stack.decorate_beneath(@document, @offset, @graphic_state, @left, @top, @box_width, @top - bottom)
+      end
+
+      private
+
+      def outer_bottom
+        outer.stretchy? ? @document.margin_box.absolute_bottom : outer.absolute_bottom
+      end
     end
 
     class Node
@@ -446,6 +530,15 @@ def text(string, style: nil, width: nil, grow: nil, **attributes)
         add(Text.new(string, width:, grow:, **@styles.text_arguments(style, attributes)))
       end
 
+      # Draws the decoration under what the page's content stream holds from offset on, in the graphic state the
+      # stream was in there.
+      def decorate_beneath(prawn, offset, graphic_state, left, top, width, height)
+        stream = prawn.page.content_stream
+        start = stream.bytesize
+        decorate(prawn, left, top, width, height, graphic_state)
+        stream.insert(offset, stream.slice!(start..))
+      end
+
       private
 
       def add(node)
@@ -457,10 +550,10 @@ def decorated?
         @background || @border_width
       end
 
-      def decorate(prawn, left, top, width, height)
+      def decorate(prawn, left, top, width, height, graphic_state = nil)
         return unless decorated?
 
-        prawn.save_graphics_state do
+        prawn.save_graphics_state(graphic_state) do
           corner = relative(prawn, left, top)
           if @background
             prawn.fill_color(@background)
@@ -509,23 +602,22 @@ def paint(prawn, left, top, width, stretched_height = nil)
         end
       end
 
-      # A plain stack breaks pages between its children; one kept together, or with a background or a border to
-      # draw around the whole of it, moves as one box.
+      # A stack breaks pages between its children, and a text among them between its lines; one kept together
+      # moves as one box. A background or a border is drawn on each page around what it holds of the stack.
       def flow(prawn, cursor, left, width)
-        return super if @keep_together || decorated?
+        return super if @keep_together || (decorated? && cursor.fits?(height(prawn, width)))
+        return flow_children(prawn, cursor, left, width) unless decorated?
 
-        cursor.y -= @padding_top
-        @children.each_with_index do |child, index|
-          cursor.y -= @gap unless index.zero? || cursor.at_page_top?
-          keep_with_what_follows(prawn, cursor, width, index)
-          child.flow(prawn, cursor, left + @padding_left, child_width(child, width))
-        end
-        cursor.y -= @padding_bottom
+        cursor.next_page unless cursor.at_page_top? || cursor.fits?(first_height(prawn, width) + @padding_bottom)
+        bounds = DecoratedBounds.new(prawn, self, left, width, @padding_top, @padding_bottom)
+        bounds.start_part(cursor.y)
+        cursor.within(bounds) { flow_children(prawn, cursor, left, width) }
+        bounds.end_part(cursor.y)
       end
 
-      # A page can start with the top of this stack's first child, when the stack can be split.
+      # A page can start with the top of this stack's first child, unless the stack is kept together.
       def first_height(prawn, width)
-        return height(prawn, width) if @keep_together || decorated? || @children.empty?
+        return height(prawn, width) if @keep_together || @children.empty?
 
         first = @children.first
         @padding_top + first.first_height(prawn, child_width(first, width))
@@ -533,6 +625,16 @@ def first_height(prawn, width)
 
       private
 
+      def flow_children(prawn, cursor, left, width)
+        cursor.y -= @padding_top
+        @children.each_with_index do |child, index|
+          cursor.y -= @gap unless index.zero? || cursor.at_page_top?
+          keep_with_what_follows(prawn, cursor, width, index)
+          child.flow(prawn, cursor, left + @padding_left, child_width(child, width))
+        end
+        cursor.y -= @padding_bottom
+      end
+
       # Children kept with the next go to the next page together with the start of the one after them, when this
       # page is too short for all of it and a page is not.
       def keep_with_what_follows(prawn, cursor, width, index)
diff --git a/test/native_grid_test.rb b/test/native_grid_test.rb
index aeb860d..df75b2b 100644
--- a/test/native_grid_test.rb
+++ b/test/native_grid_test.rb
@@ -78,13 +78,18 @@ def test_a_line_with_a_cell_kept_with_the_next_goes_to_the_next_page_with_it
     assert_equal [0, 2], lines_by_page(document.to_s)
   end
 
-  def test_a_decorated_grid_moves_whole_to_the_next_page
-    document = Gamba.document do |yielded|
+  def test_a_decorated_grid_breaks_between_its_lines_unless_kept_together
+    split = Gamba.document do |yielded|
       yielded.prawn.move_down 700
       yielded.grid(columns: 2, background: "eeeeee") { |grid| 4.times { |index| grid.text "cell #{index}" } }
     end
+    kept = Gamba.document do |yielded|
+      yielded.prawn.move_down 700
+      yielded.grid(columns: 2, background: "eeeeee", keep_together: true) { |grid| 4.times { |index| grid.text "cell #{index}" } }
+    end
 
-    assert_equal [0, 2], lines_by_page(document.to_s)
+    assert_equal [1, 1], lines_by_page(split.to_s)
+    assert_equal [0, 2], lines_by_page(kept.to_s)
   end
 
   def test_a_grid_is_a_box_like_the_others
diff --git a/test/native_layout_test.rb b/test/native_layout_test.rb
index 81b8c24..490ac6e 100644
--- a/test/native_layout_test.rb
+++ b/test/native_layout_test.rb
@@ -103,15 +103,55 @@ def test_a_background_and_a_border_are_drawn_around_the_whole_box
     assert_equal glyphs(plain.to_s), glyphs(decorated.to_s)
   end
 
-  def test_a_decorated_stack_moves_whole_to_the_next_page
+  def test_a_decorated_stack_splits_across_pages_drawn_around_each_part_with_its_padding
+    document = Gamba.document do |yielded|
+      yielded.prawn.move_down 640
+      yielded.stack(padding: 10, background: "eeeeee", border_color: "ff0000") do |stack|
+        stack.text "line 0", color: "0000ff"
+        5.times { |index| stack.text "line #{index + 1}" }
+      end
+    end
+    first_page, second_page = pages(document.to_s)
+    contents = page_contents(document.to_s)
+
+    assert_equal [4, 2], lines_by_page(document.to_s)
+    # Each part reaches the page's margin where the stack is cut, and keeps the padding clear on either side.
+    assert_equal 2, contents[0].scan(/^36\.0 36\.0 540\.0 80\.0 re$/).size
+    assert_equal 2, contents[1].scan(/^36\.0 708\.256 540\.0 47\.744 re$/).size
+    assert_operator 792 - first_page.last[4] - 36, :>=, 10
+    assert_in_delta second_page.first[4], 36 + 10 + Prawn::Document.new.font.ascender, 0.01
+    # Each part is drawn under the text, in the colour space of the page where it starts.
+    contents.each { |content| assert_operator content.index(" re\n"), :<, content.index("BT") }
+    assert_nil with_file(document.to_s) { |path| Oracle.invalidity(path) }
+  end
+
+  def test_a_decorated_stack_kept_together_moves_whole_to_the_next_page
     document = Gamba.document do |yielded|
       yielded.prawn.move_down 660
-      yielded.stack(background: "eeeeee") { |stack| 6.times { |index| stack.text "line #{index}" } }
+      yielded.stack(background: "eeeeee", keep_together: true) { |stack| 6.times { |index| stack.text "line #{index}" } }
     end
 
     assert_equal [0, 6], lines_by_page(document.to_s)
   end
 
+  def test_nested_decorated_stacks_and_tables_split_inside_a_decorated_stack
+    document = Gamba.document do |yielded|
+      yielded.stack(padding: 12, border_color: "ff0000") do |outer|
+        outer.stack(padding: 6, background: "ccddff") { |inner| 30.times { |index| inner.text "inner #{index}" } }
+        outer.table(Array.new(60) { |index| {name: "row #{index}"} })
+      end
+    end
+    pages = pages(document.to_s)
+
+    assert_equal 3, pages.size
+    pages.each do |glyphs|
+      # Positions from the top: no line enters the outer stack's padding at either end of a page.
+      assert_operator glyphs.map(&:last).max, :<=, 792 - 36 - 12
+      assert_operator glyphs.map(&:last).min, :>=, 36 + 12
+    end
+    assert_nil with_file(document.to_s) { |path| Oracle.invalidity(path) }
+  end
+
   def test_a_box_that_cannot_be_split_and_is_higher_than_a_page_raises
     error = assert_raises(Prawn::Errors::CannotFit) do
       Gamba.document { |document| document.row { |row| row.text "word " * 5000 } }
@@ -220,6 +260,10 @@ def pages(pdf)
     with_file(pdf) { |path| Oracle.text_layout(path).map(&:glyphs) }
   end
 
+  def page_contents(pdf)
+    uncompressed(pdf).split("%% Contents for page ").drop(1)
+  end
+
   def uncompressed(pdf)
     with_file(pdf) { |path| Open3.capture2("qpdf", "--qdf", "--object-streams=disable", path, "-").first.b }
   end

From 51cad80a9536155eae6ff989478c7aa4c01824ce Mon Sep 17 00:00:00 2001
From: Claude 
Date: Fri, 13 Nov 2026 19:16:48 +0000
Subject: [PATCH 2/5] Fuzz random trees of native boxes across pages

Random stacks, rows and grids nested three levels deep, with gaps,
paddings, decorations and page break rules, holding texts and tables, are
placed and read back with mutool trace: nothing drawn leaves the margins,
no two lines overlap, a stack kept together stays on one page whenever it
fits an empty one, and rendering twice gives the same bytes. CI runs 1000
trees on a fresh seed.

Assisted-by: Claude [Claude Code]
---
 .github/workflows/ci.yml     |   2 +
 AGENTS.md                    |   3 +-
 test/layout_fuzz_test.rb     | 158 +++++++++++++++++++++++++++++++++++
 test/support/layout_trees.rb | 110 ++++++++++++++++++++++++
 4 files changed, 272 insertions(+), 1 deletion(-)
 create mode 100644 test/layout_fuzz_test.rb
 create mode 100644 test/support/layout_trees.rb

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index da7b6fe..24cbf6e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -110,6 +110,8 @@ jobs:
         run: FUZZ_SEED=$GITHUB_RUN_ID FUZZ_CASES=300 bundle exec ruby -Itest test/fuzz_test.rb
       - name: Fuzz 400 malformed inputs
         run: INPUT_FUZZ_SEED=$GITHUB_RUN_ID INPUT_FUZZ_CASES=400 bundle exec ruby -Itest test/input_fuzz_test.rb
+      - name: Fuzz 1000 trees of boxes
+        run: LAYOUT_FUZZ_SEED=$GITHUB_RUN_ID LAYOUT_FUZZ_CASES=1000 bundle exec ruby -Itest test/layout_fuzz_test.rb
 
   # Allowed to fail, and truffleruby-head takes twice as long as the others: CI passed doesn't wait for them.
   head:
diff --git a/AGENTS.md b/AGENTS.md
index d9bada1..73f145c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -14,11 +14,12 @@ bundle exec rake test                                           # needs: brew in
 ORACLE_CANDIDATE=prawn FUZZ_CASES=0 bundle exec rake test       # Prawn against itself: proves the oracle
 FUZZ_SEED=42 FUZZ_CASES=500 bundle exec ruby -Itest test/fuzz_test.rb
 INPUT_FUZZ_SEED=42 INPUT_FUZZ_CASES=400 bundle exec ruby -Itest test/input_fuzz_test.rb
+LAYOUT_FUZZ_SEED=42 LAYOUT_FUZZ_CASES=1000 bundle exec ruby -Itest test/layout_fuzz_test.rb
 bundle exec rubocop
 bundle exec rake bench                                          # Prawn against Gamba, writes docs/benchmarks.json
 ```
 
-CI also runs `ruby-head` and `truffleruby-head`, and the oracle and both fuzzers on a fresh seed.
+CI also runs `ruby-head` and `truffleruby-head`, and the oracle and the three fuzzers on a fresh seed.
 
 ## Traps
 
diff --git a/test/layout_fuzz_test.rb b/test/layout_fuzz_test.rb
new file mode 100644
index 0000000..3792be7
--- /dev/null
+++ b/test/layout_fuzz_test.rb
@@ -0,0 +1,158 @@
+# frozen_string_literal: true
+
+require_relative "test_helper"
+require_relative "support/layout_trees"
+require "open3"
+require "prawn"
+
+# Random trees of native boxes from a seed, placed across pages: nothing drawn leaves the margins, no two lines
+# overlap, a stack kept together stays on one page whenever it fits on an empty one, and rendering twice gives the
+# same bytes. LAYOUT_FUZZ_SEED and LAYOUT_FUZZ_CASES choose them; a failure names the file holding the document,
+# kept in tmp/layout_fuzz to reproduce it.
+class LayoutFuzzTest < Minitest::Test
+  SEED = Integer(ENV.fetch("LAYOUT_FUZZ_SEED", "20261113"))
+  CASES = Integer(ENV.fetch("LAYOUT_FUZZ_CASES", "60"))
+  DIRECTORY = File.join(Oracle::ROOT, "tmp/layout_fuzz")
+  TOLERANCE = 0.01
+  # Helvetica's ascender and descender, in ems: where a glyph's ink may reach above and below its baseline.
+  ASCENDER = 0.718
+  DESCENDER = 0.207
+  # A tree whose boxes cannot fit their page or their width is refused; most must be placed.
+  MINIMUM_PLACED_SHARE = 0.6
+
+  # Each stack kept together as it is flowed: whether it fits on an empty page, and the ids of what it holds.
+  module KeptStacks
+    class << self
+      attr_accessor :recorded
+    end
+
+    def flow(prawn, cursor, left, width)
+      if instance_variable_get(:@keep_together) && KeptStacks.recorded
+        fits = height(prawn, width) <= cursor.page_height + Gamba::Layout::FIT_TOLERANCE_POINTS
+        KeptStacks.recorded << [fits, KeptStacks.ids(self)]
+      end
+      super
+    end
+
+    def self.ids(node)
+      case node
+      when Gamba::Layout::Text then node.instance_variable_get(:@fragments).flat_map { _1[:text].split }.uniq
+      when Gamba::Layout::Table then node.instance_variable_get(:@rows).flat_map { _1.values.flat_map(&:split) }.uniq
+      when Gamba::Layout::Container then node.instance_variable_get(:@children).flat_map { ids(_1) }.uniq
+      else []
+      end
+    end
+  end
+  Gamba::Layout::Stack.prepend(KeptStacks)
+
+  def test_random_box_trees_are_placed_within_the_margins_without_overlaps
+    FileUtils.rm_rf(DIRECTORY)
+    FileUtils.mkdir_p(DIRECTORY)
+    generator = LayoutTrees.new(SEED)
+    placed = 0
+    failures = CASES.times.filter_map do |index|
+      source = generator.document
+      path = File.join(DIRECTORY, format("tree_%04d.rb", index))
+      File.write(path, source)
+      problem = problem(source)
+      next if problem == :refused
+
+      placed += 1
+      next File.delete(path) && nil unless problem
+
+      "#{path}: #{problem}"
+    end
+
+    assert_empty failures, "seed #{SEED}"
+    assert_operator placed, :>=, CASES * MINIMUM_PLACED_SHARE, "seed #{SEED}: too few trees fit their pages to test anything"
+  end
+
+  private
+
+  def problem(source)
+    KeptStacks.recorded = []
+    document = eval(source, binding, "tree.rb") # rubocop:disable Security/Eval
+    pdf = document.to_s
+    kept = KeptStacks.recorded
+    KeptStacks.recorded = nil
+    return "rendered twice, the bytes differ" unless eval(source, binding, "tree.rb").to_s == pdf # rubocop:disable Security/Eval
+
+    pages = trace(pdf)
+    margins = margin_box(document.prawn)
+    pages.each_with_index do |(paths, runs), page_index|
+      outside = (paths + runs.map(&:last)).find { |box| !inside?(box, margins) }
+      return "page #{page_index + 1}: #{outside.map { _1.round(2) }} leaves the margins #{margins}" if outside
+
+      overlap = runs.combination(2).find { |(_, first), (_, second)| overlap?(first, second) }
+      return "page #{page_index + 1}: #{overlap.map(&:first).inspect} overlap" if overlap
+    end
+    split_kept_stack(kept, pages)
+  rescue Prawn::Errors::CannotFit
+    :refused
+  ensure
+    KeptStacks.recorded = nil
+  end
+
+  def split_kept_stack(kept, pages)
+    page_numbers_by_id = Hash.new { |hash, id| hash[id] = [] }
+    pages.each_with_index do |(_paths, runs), page_index|
+      runs.each { |text, _box| text.scan(/[tc]\d+/) { page_numbers_by_id[_1] |= [page_index + 1] } }
+    end
+    kept.each do |fits, ids|
+      page_numbers = ids.flat_map { page_numbers_by_id[_1] }.uniq.sort
+      return "a stack kept together, fitting a page, is split over pages #{page_numbers}: #{ids.first(5)}" if fits && page_numbers.size > 1
+    end
+    nil
+  end
+
+  # Each page as [path bounds, [text, glyph box] for each run of glyphs on one baseline], in points, from MuPDF.
+  def trace(pdf)
+    output = Tempfile.create(["tree", ".pdf"]) do |file|
+      file.binmode
+      file.write(pdf)
+      file.flush
+      output, errors, status = Open3.capture3("mutool", "trace", file.path, binmode: true)
+      raise "mutool trace failed: #{errors}" unless status.success?
+
+      output
+    end
+    output.split("]*)>(.*?)}m).map do |kind, attributes, body|
+      points = body.scan(/x="([-\d.]+)" y="([-\d.]+)"/).map { |x, y| [Float(x), Float(y)] }
+      xs, ys = points.transpose
+      reach = (kind == "stroke") ? Float(attributes[/linewidth="([\d.]+)"/, 1]) / 2 : 0
+      [xs.min + reach, ys.min + reach, xs.max - reach, ys.max - reach]
+    end
+  end
+
+  def runs(page)
+    page.scan(%r{]*trm="([-\d.]+)[^"]*"[^>]*>(.*?)}m).flat_map do |size, body|
+      size = Float(size)
+      glyphs = body.scan(/unicode="([^"]*)"[^>]*x="([-\d.]+)" y="([-\d.]+)" adv="([-\d.]+)"/)
+      glyphs.chunk { |_, _, y, _| y }.map do |y, line|
+        baseline = Float(y)
+        left = Float(line.first[1])
+        right = Float(line.last[1]) + (Float(line.last[3]) * size)
+        text = line.map { |unicode, *| unicode.gsub(""", '"').gsub("&", "&") }.join
+        [text, [left, baseline - (DESCENDER * size), right, baseline + (ASCENDER * size)]]
+      end
+    end
+  end
+
+  def margin_box(prawn)
+    box = prawn.margin_box
+    [box.absolute_left, box.absolute_bottom, box.absolute_right, box.absolute_top]
+  end
+
+  def inside?((left, bottom, right, top), (margin_left, margin_bottom, margin_right, margin_top))
+    left >= margin_left - TOLERANCE && right <= margin_right + TOLERANCE && bottom >= margin_bottom - TOLERANCE && top <= margin_top + TOLERANCE
+  end
+
+  def overlap?(first, second)
+    [first[2], second[2]].min - [first[0], second[0]].max > TOLERANCE && [first[3], second[3]].min - [first[1], second[1]].max > TOLERANCE
+  end
+end
diff --git a/test/support/layout_trees.rb b/test/support/layout_trees.rb
new file mode 100644
index 0000000..054f326
--- /dev/null
+++ b/test/support/layout_trees.rb
@@ -0,0 +1,110 @@
+# frozen_string_literal: true
+
+# Random documents of native boxes from a seed, as Ruby source: stacks, rows and grids nested a few levels deep,
+# with gaps, paddings, backgrounds, borders and page break rules, holding texts and tables. Every word of a text
+# or a cell is its id, t1 or c1, so each line drawn says which box it belongs to.
+class LayoutTrees
+  PAGE_SIZES = ["LETTER", "A5", [400, 300]].freeze
+  MAX_DEPTH = 3
+  FONT_SIZES = [8, 10, 12, 14].freeze
+
+  def initialize(seed)
+    @random = Random.new(seed)
+  end
+
+  def document
+    @id = 0
+    page_size = PAGE_SIZES.sample(random: @random)
+    source = "Gamba.document(page_size: #{page_size.inspect}, margin: #{@random.rand(20..60)}) do |document|\n"
+    @random.rand(1..6).times { source << box("document", 1, :document) }
+    source << "end\n"
+  end
+
+  private
+
+  # A box added to receiver, a container of the given kind or the document. Within a row or a grid, boxes share a
+  # line of the page: they hold less, so that most trees fit their pages.
+  def box(receiver, depth, parent, inline: false)
+    kind = if depth > MAX_DEPTH
+      leaf(inline)
+    else
+      (inline ? %i[text text stack] : %i[text text text table stack stack row grid]).sample(random: @random)
+    end
+    indent = "  " * depth
+    case kind
+    when :text then "#{indent}#{receiver}.text #{words("t", @random.rand(1..(inline ? 12 : 80))).inspect}#{text_options(parent, inline)}\n"
+    when :table then "#{indent}#{receiver}.table(#{table_rows.inspect}#{", header: false" if chance(0.3)}#{width_options(parent, inline)})\n"
+    else container(receiver, depth, parent, kind, indent, inline || %i[row grid].include?(kind))
+    end
+  end
+
+  def leaf(inline)
+    (inline || chance(0.85)) ? :text : :table
+  end
+
+  def container(receiver, depth, parent, kind, indent, inline)
+    name = "box#{depth}"
+    options = container_options(kind, inline) + width_options(parent, inline)
+    source = "#{indent}#{receiver}.#{kind}(#{options.delete_prefix(", ")}) do |#{name}|\n"
+    @random.rand(1..(inline ? 3 : 5)).times { source << box(name, depth + 1, kind, inline:) }
+    source << "#{indent}end\n"
+  end
+
+  def container_options(kind, inline)
+    options = +""
+    options << ", columns: #{@random.rand(1..4)}" if kind == :grid
+    options << ", gap: #{gap(kind)}" if chance(0.6)
+    options << ", padding: #{padding}" if chance(0.5)
+    options << ", background: \"eeeeee\"" if chance(0.3)
+    options << ", border_width: #{[0.5, 1, 2].sample(random: @random)}" if chance(0.3)
+    options << ", keep_together: true" if kind != :row && chance(inline ? 0.1 : 0.2)
+    options << ", keep_with_next: true" if chance(0.15)
+    options
+  end
+
+  def text_options(parent, inline)
+    options = ", size: #{FONT_SIZES.sample(random: @random)}"
+    options << ", widows: #{@random.rand(1..3)}, orphans: #{@random.rand(1..3)}" if chance(0.4)
+    options << ", keep_with_next: true" if chance(0.15)
+    options + width_options(parent, inline)
+  end
+
+  # In a row, a box takes a width or a share of what is left; elsewhere, sometimes a width.
+  def width_options(parent, inline)
+    return "" if %i[grid document].include?(parent)
+    return ", grow: #{@random.rand(1..3)}" if parent == :row && chance(0.3)
+
+    if chance(0.15)
+      ", width: #{inline ? @random.rand(30..90) : @random.rand(60..250)}"
+    else
+      ""
+    end
+  end
+
+  def table_rows
+    Array.new(@random.rand(1..40)) { {name: words("c", @random.rand(1..6)), quantity: words("c", 1)} }
+  end
+
+  def gap(kind)
+    return "[#{@random.rand(0..12)}, #{@random.rand(0..12)}]" if kind == :grid && chance(0.5)
+
+    @random.rand(0..12)
+  end
+
+  def padding
+    case @random.rand(3)
+    when 0 then @random.rand(0..12).to_s
+    when 1 then "[#{@random.rand(0..12)}, #{@random.rand(0..12)}]"
+    else "[#{Array.new(4) { @random.rand(0..12) }.join(", ")}]"
+    end
+  end
+
+  def words(prefix, count)
+    id = "#{prefix}#{@id += 1}"
+    ([id] * count).join(" ")
+  end
+
+  def chance(probability)
+    @random.rand < probability
+  end
+end

From 19957165d275b9baaf18e7e0a7d7e5dc659bc37d Mon Sep 17 00:00:00 2001
From: Claude 
Date: Fri, 13 Nov 2026 19:41:10 +0000
Subject: [PATCH 3/5] Keep decorated stacks and tables within the page, as
 fuzzing found

The layout fuzzer, on fresh seeds, found three ways to draw past the
bottom margin. The gap below the last line of a decorated stack's part
took its frame past the page; the bottom padding of a plain stack inside
one did too; and a table row higher than a page ran past it, as Prawn's
table draws it. A decorated stack's part now ends where its padding
starts, a plain stack's bottom padding ends with the page, and a table
whose row cannot fit a page raises CannotFit naming its height.

Fuzz ids are zero-padded, so that a word broken across lines in a narrow
column cannot pass for another box's id.

Assisted-by: Claude [Claude Code]
---
 lib/gamba/native/layout.rb   | 10 +++++++++-
 lib/gamba/native/table.rb    | 12 ++++++++++++
 test/layout_fuzz_test.rb     |  2 +-
 test/native_boxes_test.rb    | 10 ++++++++++
 test/native_layout_test.rb   | 19 +++++++++++++++++++
 test/support/layout_trees.rb |  5 +++--
 6 files changed, 54 insertions(+), 4 deletions(-)

diff --git a/lib/gamba/native/layout.rb b/lib/gamba/native/layout.rb
index 37353eb..965c5a8 100644
--- a/lib/gamba/native/layout.rb
+++ b/lib/gamba/native/layout.rb
@@ -632,7 +632,15 @@ def flow_children(prawn, cursor, left, width)
           keep_with_what_follows(prawn, cursor, width, index)
           child.flow(prawn, cursor, left + @padding_left, child_width(child, width))
         end
-        cursor.y -= @padding_bottom
+        # The bottom padding of a plain stack ends with the page, so that a decorated stack holding it is not drawn
+        # past the page. A decorated stack's own is kept clear on every page, and the gap below its last line ends
+        # where its padding starts.
+        if decorated?
+          cursor.y -= cursor.remaining if cursor.remaining.negative?
+          cursor.y -= @padding_bottom
+        else
+          cursor.y -= @padding_bottom.clamp(0, [cursor.remaining, 0].max)
+        end
       end
 
       # Children kept with the next go to the next page together with the start of the one after them, when this
diff --git a/lib/gamba/native/table.rb b/lib/gamba/native/table.rb
index 1cd8f50..f18b18f 100644
--- a/lib/gamba/native/table.rb
+++ b/lib/gamba/native/table.rb
@@ -37,7 +37,9 @@ def paint(prawn, left, top, width)
         within(prawn, left, width) { table.draw }
       end
 
+      # Prawn draws a row higher than a page past its bottom: here it raises, as any box that cannot be split does.
       def flow(prawn, cursor, left, width)
+        check_rows_fit(prawn, cursor, width) unless data.empty?
         paint(prawn, left, cursor.y, width)
         cursor.y = prawn.y unless data.empty?
       end
@@ -59,6 +61,16 @@ def description
         "a table"
       end
 
+      def check_rows_fit(prawn, cursor, width)
+        heights = table(prawn, width).row_heights
+        header = @header ? heights.first : 0
+        tallest = (@header ? heights.drop(1) : heights).max || 0
+        return if header + tallest <= cursor.page_height + FIT_TOLERANCE_POINTS
+
+        raise Prawn::Errors::CannotFit, "#{description} has a row #{tallest.round(1)} pt high#{" under a #{header.round(1)} pt header" if @header}, " \
+          "the page has #{cursor.page_height.to_f.round(1)} pt"
+      end
+
       # Without columns, a table of hashes has those of its first row.
       def inferred_columns
         first = @rows.first
diff --git a/test/layout_fuzz_test.rb b/test/layout_fuzz_test.rb
index 3792be7..26c6863 100644
--- a/test/layout_fuzz_test.rb
+++ b/test/layout_fuzz_test.rb
@@ -96,7 +96,7 @@ def problem(source)
   def split_kept_stack(kept, pages)
     page_numbers_by_id = Hash.new { |hash, id| hash[id] = [] }
     pages.each_with_index do |(_paths, runs), page_index|
-      runs.each { |text, _box| text.scan(/[tc]\d+/) { page_numbers_by_id[_1] |= [page_index + 1] } }
+      runs.each { |text, _box| text.scan(/\b[tc]\d{4}\b/) { page_numbers_by_id[_1] |= [page_index + 1] } }
     end
     kept.each do |fits, ids|
       page_numbers = ids.flat_map { page_numbers_by_id[_1] }.uniq.sort
diff --git a/test/native_boxes_test.rb b/test/native_boxes_test.rb
index 558676a..27375af 100644
--- a/test/native_boxes_test.rb
+++ b/test/native_boxes_test.rb
@@ -157,6 +157,16 @@ def test_a_table_that_fills_the_page_to_the_point_is_not_cut
     assert_equal [0, 3], lines_by_page(document.to_s)
   end
 
+  def test_a_table_row_higher_than_a_page_raises_instead_of_running_past_the_bottom
+    error = assert_raises(Prawn::Errors::CannotFit) do
+      Gamba.document(page_size: [400, 300]) do |document|
+        document.stack(width: 60) { |stack| stack.table([{name: "alice " * 40, quantity: 1}]) }
+      end
+    end
+
+    assert_match(/\Aa table has a row [\d.]+ pt high under a [\d.]+ pt header, the page has 228\.0 pt\z/, error.message)
+  end
+
   def test_rows_as_arrays_missing_columns_and_unknown_options_raise
     document = Gamba.document
 
diff --git a/test/native_layout_test.rb b/test/native_layout_test.rb
index 490ac6e..f238b86 100644
--- a/test/native_layout_test.rb
+++ b/test/native_layout_test.rb
@@ -134,6 +134,25 @@ def test_a_decorated_stack_kept_together_moves_whole_to_the_next_page
     assert_equal [0, 6], lines_by_page(document.to_s)
   end
 
+  # Found by the layout fuzzer: the gap below a last line, or the bottom padding of a plain stack inside, reached
+  # past the page and took the frame with it. Three lines of 13.872 pt leave 1.5 pt of the last one's gap past the
+  # page, and a padding of 30 pt runs past it.
+  def test_a_decorated_stack_ending_at_the_bottom_of_a_page_stays_within_its_margins
+    [0, 30].each do |inner_padding|
+      document = Gamba.document(page_size: [400, 300], margin: 45) do |yielded|
+        yielded.prawn.move_down 210 - ((3 * 13.872) - 1.5)
+        yielded.stack(border_width: 1) do |frame|
+          2.times { frame.text "word" }
+          frame.stack(padding: [0, 0, inner_padding, 0]) { |inner| inner.text "word" }
+        end
+      end
+      bottoms = page_contents(document.to_s).flat_map { _1.scan(/^[\d.]+ ([\d.]+) [\d.]+ [\d.]+ re$/).flatten }
+
+      assert_equal 1, bottoms.size
+      assert_in_delta 45, Float(bottoms.first), 0.001, "inner padding #{inner_padding}"
+    end
+  end
+
   def test_nested_decorated_stacks_and_tables_split_inside_a_decorated_stack
     document = Gamba.document do |yielded|
       yielded.stack(padding: 12, border_color: "ff0000") do |outer|
diff --git a/test/support/layout_trees.rb b/test/support/layout_trees.rb
index 054f326..e19cb6d 100644
--- a/test/support/layout_trees.rb
+++ b/test/support/layout_trees.rb
@@ -2,7 +2,8 @@
 
 # Random documents of native boxes from a seed, as Ruby source: stacks, rows and grids nested a few levels deep,
 # with gaps, paddings, backgrounds, borders and page break rules, holding texts and tables. Every word of a text
-# or a cell is its id, t1 or c1, so each line drawn says which box it belongs to.
+# or a cell is its id, t0001 or c0001, so each line drawn says which box it belongs to: a word broken across lines
+# leaves pieces too short to pass for an id.
 class LayoutTrees
   PAGE_SIZES = ["LETTER", "A5", [400, 300]].freeze
   MAX_DEPTH = 3
@@ -100,7 +101,7 @@ def padding
   end
 
   def words(prefix, count)
-    id = "#{prefix}#{@id += 1}"
+    id = format("%s%04d", prefix, @id += 1)
     ([id] * count).join(" ")
   end
 

From faa931028968f6791e89024a4347d16867a2a0e1 Mon Sep 17 00:00:00 2001
From: Claude 
Date: Fri, 13 Nov 2026 19:26:12 +0000
Subject: [PATCH 4/5] Give boxes semantic roles, and bookmark headings

Each native box takes a role saying what it is to a reader, for tagged
PDF to read: a text is a paragraph, a heading from h1 to h6, a list item
or an artifact; a container groups, or is a list, a list item or a figure;
images and codes are figures with their alternative text in alt; tables
are tables. Unknown roles, and alt on anything but a figure, raise.

Headings already make the PDF's outline, nested by level, each pointing
at the top of its first line on the page where it lands. Those of a
header or a footer make none.

Assisted-by: Claude [Claude Code]
---
 docs/guide.html              |  10 +++
 lib/gamba/native/document.rb |   2 +-
 lib/gamba/native/layout.rb   |  81 +++++++++++++++++++++---
 lib/gamba/native/table.rb    |   3 +
 test/native_boxes_test.rb    |   2 +-
 test/native_document_test.rb |   2 +-
 test/native_layout_test.rb   |   2 +-
 test/native_roles_test.rb    | 118 +++++++++++++++++++++++++++++++++++
 test/support/layout_trees.rb |   1 +
 9 files changed, 210 insertions(+), 11 deletions(-)
 create mode 100644 test/native_roles_test.rb

diff --git a/docs/guide.html b/docs/guide.html
index f85d98c..f75ac56 100644
--- a/docs/guide.html
+++ b/docs/guide.html
@@ -163,6 +163,16 @@ 

Gamba’s own API

footer.text "Page #{page.number} of #{page.total}", align: :center, size: 8 end

Their room is taken from the page: the body, native or drawn with Prawn’s own calls, starts below the header and its gap and breaks pages above the footer and its gap. The room kept is the height each has on the page it is declared on, and it applies from that page on, so a cover page declared before them has neither. A header that comes out higher on a later page raises Prawn::Errors::CannotFit when the document is rendered, naming the page, instead of running over the body.

+

Each box can say what it is to a reader with role: a text is a paragraph (:p, unless told), a heading from :h1 to :h6, a :list_item or an :artifact; a container groups its children, or is a :list, a :list_item or a :figure; images and codes are figures, with their alternative text in alt; tables are tables. An :artifact only decorates the page. Roles draw nothing: tagged PDF will read them. Headings already make the PDF’s bookmarks, nested by level, each pointing at the top of its first line; those of a header or a footer make none.

+
document.style :chapter, size: 18, weight: :bold, role: :h1, keep_with_next: true
+
+document.text "Payment terms", style: :chapter
+document.text "Late payment", role: :h2
+document.image "chart.png", alt: "Sales by month, 2026"
+document.stack(role: :list) do |list|
+  list.text "Bank transfer", role: :list_item
+  list.text "Card", role: :list_item
+end

You don’t have to rewrite anything to start. In code written for Prawn, gamba opens a native block at the cursor, and leaves the cursor below what it drew:

Prawn::Document.generate("report.pdf") do
   text "Existing code, unchanged"
diff --git a/lib/gamba/native/document.rb b/lib/gamba/native/document.rb
index c2be8cc..cf68d2e 100644
--- a/lib/gamba/native/document.rb
+++ b/lib/gamba/native/document.rb
@@ -82,7 +82,7 @@ def declare_band(name, gap, block)
       raise ArgumentError, "the #{name} takes a block, which receives a stack and the page" unless block
       raise ArgumentError, "the #{name} is already declared: a document has one" if (@bands ||= {}).key?(name)
 
-      @bands[name] = Layout::Band.new(prawn, @styles, name, gap, block).tap(&:reserve)
+      @bands[name] = Layout::Band.new(prawn, @styles.without_bookmarks, name, gap, block).tap(&:reserve)
       self
     end
 
diff --git a/lib/gamba/native/layout.rb b/lib/gamba/native/layout.rb
index 965c5a8..9c35708 100644
--- a/lib/gamba/native/layout.rb
+++ b/lib/gamba/native/layout.rb
@@ -126,17 +126,27 @@ def outer_bottom
       end
     end
 
+    # A box. Its role says what it is to a reader, for tagged PDF: a heading of a level, a paragraph, a list and
+    # its items, a table, a figure with its alternative text, or an artifact, which only decorates the page.
     class Node
-      OPTIONS = %i[width grow keep_with_next].freeze
+      OPTIONS = %i[width grow keep_with_next role alt].freeze
+      ROLES = %i[artifact].freeze
+      DEFAULT_ROLE = nil
+      KIND = "a box"
 
-      attr_reader :width, :grow, :keep_with_next
+      attr_reader :width, :grow, :keep_with_next, :role, :alt
 
-      def initialize(width: nil, grow: nil, keep_with_next: false)
+      def initialize(width: nil, grow: nil, keep_with_next: false, role: self.class::DEFAULT_ROLE, alt: nil)
         raise ArgumentError, "width and grow exclude each other: a box is as wide as told, or shares what is left" if width && grow
+        accepted = self.class::ROLES + (self.class::DEFAULT_ROLE ? [] : [nil])
+        raise ArgumentError, "role is #{role.inspect}: #{self.class::KIND} takes #{self.class::ROLES.map(&:inspect).join(", ")}" unless accepted.include?(role)
+        raise ArgumentError, "alt is the alternative text of a figure: give it with role: :figure, not #{role.inspect}" if alt && role != :figure
 
         @width = width
         @grow = grow
         @keep_with_next = keep_with_next
+        @role = role
+        @alt = alt
       end
 
       # A box is measured when it is placed and again by the boxes around it: once per width is enough.
@@ -173,9 +183,14 @@ def relative(prawn, left, top)
     class Text < Node
       DEFAULT_WIDOWS = 2
       DEFAULT_ORPHANS = 2
+      HEADINGS = %i[h1 h2 h3 h4 h5 h6].freeze
+      ROLES = (%i[p] + HEADINGS + %i[list_item artifact]).freeze
+      DEFAULT_ROLE = :p
+      KIND = "a text"
 
-      def initialize(string, font:, font_options:, color:, text_options:, widows: DEFAULT_WIDOWS, orphans: DEFAULT_ORPHANS, **)
+      def initialize(string, font:, font_options:, color:, text_options:, widows: DEFAULT_WIDOWS, orphans: DEFAULT_ORPHANS, bookmarks: nil, **)
         super(**)
+        @bookmarks = bookmarks if HEADINGS.include?(role)
         @fragments = [color ? {text: string, color:} : {text: string}]
         @font = font
         @font_options = font_options
@@ -186,6 +201,7 @@ def initialize(string, font:, font_options:, color:, text_options:, widows: DEFA
 
       # The lines wrapped to measure the text are drawn as they are, when Prawn's box can draw them again.
       def paint(prawn, left, top, width)
+        bookmark(prawn, top)
         at = relative(prawn, left, top)
         with_font(prawn) do
           if @measured_width == width && @measured_box.layout_reusable?
@@ -217,6 +233,7 @@ def flow(prawn, cursor, left, width)
               next
             end
 
+            bookmark(prawn, cursor.y) if fragments.equal?(@fragments)
             # Most paragraphs fit whole: the lines wrapped to place them are drawn as they are.
             if height == MEASURING_HEIGHT_POINTS && probe.layout_reusable?
               probe.render_laid_out(at)
@@ -248,6 +265,11 @@ def first_height(prawn, width)
 
       private
 
+      # A heading is bookmarked where its first line is drawn, under the last heading of a higher level.
+      def bookmark(prawn, top)
+        @bookmarks&.add(HEADINGS.index(role) + 1, @fragments.sum("") { _1[:text] }.split.join(" "), top)
+      end
+
       def lines_option(name, lines)
         return lines if lines.is_a?(Integer) && lines >= 1
 
@@ -316,6 +338,9 @@ def advance(box)
     class Image < Node
       OPTIONS = (Node::OPTIONS + %i[height align]).freeze
       ALIGNMENTS = %i[left center right].freeze
+      ROLES = %i[figure artifact].freeze
+      DEFAULT_ROLE = :figure
+      KIND = "an image"
 
       def initialize(source, height: nil, align: :left, **)
         raise ArgumentError, "align is #{align.inspect}: accepted alignments are #{ALIGNMENTS.map(&:inspect).join(", ")}" unless ALIGNMENTS.include?(align)
@@ -377,6 +402,9 @@ def image(prawn)
     # module_size says; never wider than its box.
     class MatrixCode < Node
       OPTIONS = (Node::OPTIONS + %i[size module_size quiet_zone color align]).freeze
+      ROLES = Image::ROLES
+      DEFAULT_ROLE = :figure
+      KIND = "a code"
 
       def initialize(symbol, size: nil, module_size: Prawn::Barcodes::DEFAULT_MODULE_SIZE, quiet_zone: true, color: "000000", align: :left, **)
         raise ArgumentError, "align is #{align.inspect}: accepted alignments are #{Image::ALIGNMENTS.map(&:inspect).join(", ")}" unless Image::ALIGNMENTS.include?(align)
@@ -416,6 +444,9 @@ def description
     # module_size says; never wider than its box.
     class Barcode < Node
       OPTIONS = (Node::OPTIONS + %i[type module_size height text text_size color quiet_zone align]).freeze
+      ROLES = Image::ROLES
+      DEFAULT_ROLE = :figure
+      KIND = "a barcode"
 
       def initialize(data, type:, align: :left, **options)
         raise ArgumentError, "align is #{align.inspect}: accepted alignments are #{Image::ALIGNMENTS.map(&:inspect).join(", ")}" unless Image::ALIGNMENTS.include?(align)
@@ -514,6 +545,9 @@ class Container < Node
 
       OPTIONS = (Node::OPTIONS + %i[gap padding background border_width border_color]).freeze
       DEFAULT_BORDER_COLOR = "000000"
+      # Without a role, a container only groups its children.
+      ROLES = %i[list list_item figure artifact].freeze
+      KIND = "a container"
 
       def initialize(styles, gap: 0, padding: 0, background: nil, border_width: nil, border_color: nil, **)
         super(**)
@@ -813,11 +847,38 @@ def child_widths(width)
       end
     end
 
+    # The PDF's outline built from the headings as they are placed: each one under the last heading of a higher
+    # level, pointing at the top of its first line.
+    class Bookmarks
+      def initialize(prawn)
+        @prawn = prawn
+        # The headings that can still receive subsections, by level: [level, outline item].
+        @open = []
+      end
+
+      # Prawn's outline adds after its current item: it is pointed at the parent, then back at the end of the root.
+      def add(level, title, top)
+        @open.pop while @open.any? && @open.last.first >= level
+        outline = @prawn.outline
+        root = @prawn.outlines_reference
+        parent = @open.empty? ? root : @open.last.last
+        begin
+          outline.parent = parent
+          outline.prev = parent.data.last
+          outline.section(title, destination: [@prawn.page.dictionary, :XYZ, nil, top, nil])
+        ensure
+          outline.parent = root
+          outline.prev = root.data.last
+        end
+        @open << [level, parent.data.last]
+      end
+    end
+
     # Named text attributes, and what they come to for Prawn once a call's own are added.
     class Styles
-      TEXT_ATTRIBUTES = %i[font size weight italic color align leading widows orphans keep_with_next].freeze
+      TEXT_ATTRIBUTES = %i[font size weight italic color align leading widows orphans keep_with_next role].freeze
       # Attributes of the paragraph's place on the page, not of its glyphs: the layout reads them, Prawn does not.
-      LAYOUT_ATTRIBUTES = %i[widows orphans keep_with_next].freeze
+      LAYOUT_ATTRIBUTES = %i[widows orphans keep_with_next role].freeze
       FONT_STYLES = %i[normal bold italic bold_italic].freeze
       DEFAULT_STYLE = :default
 
@@ -841,6 +902,12 @@ def initialize(prawn, default_font_features)
         @prawn = prawn
         @default_font_features = default_font_features
         @attributes_by_name = {}
+        @bookmarks = Bookmarks.new(prawn)
+      end
+
+      # The same styles for a header or a footer, whose headings are drawn on every page and bookmark none.
+      def without_bookmarks
+        dup.tap { _1.instance_variable_set(:@bookmarks, nil) }
       end
 
       def define(name, attributes)
@@ -861,7 +928,7 @@ def text_arguments(style, attributes)
         attributes = attributes.except(*LAYOUT_ATTRIBUTES)
         font = attributes.delete(:font)
         font_options = (font.nil? || @prawn.font_families.key?(font)) ? {} : {features: @default_font_features}
-        {font:, font_options:, color: attributes.delete(:color), text_options: text_options(attributes), **layout}
+        {font:, font_options:, color: attributes.delete(:color), text_options: text_options(attributes), bookmarks: @bookmarks, **layout}
       end
 
       private
diff --git a/lib/gamba/native/table.rb b/lib/gamba/native/table.rb
index f18b18f..2825831 100644
--- a/lib/gamba/native/table.rb
+++ b/lib/gamba/native/table.rb
@@ -10,6 +10,9 @@ class Table < Node
       HEADER_OPTIONS = %i[align weight italic size color background].freeze
       CELL_OPTIONS = %i[padding size font color background borders border_width border_color].freeze
       DEFAULT_HEADER = {weight: :bold}.freeze
+      ROLES = %i[table artifact].freeze
+      DEFAULT_ROLE = :table
+      KIND = "a table"
       # A native name on the left, the name of Prawn's cell on the right.
       PRAWN_CELL_NAMES = {color: :text_color, background: :background_color}.freeze
       # Prawn starts a new page unless a row is strictly shorter than what is left of the page: a table that
diff --git a/test/native_boxes_test.rb b/test/native_boxes_test.rb
index 27375af..b83f2a3 100644
--- a/test/native_boxes_test.rb
+++ b/test/native_boxes_test.rb
@@ -182,7 +182,7 @@ def test_rows_as_arrays_missing_columns_and_unknown_options_raise
   def test_unknown_table_and_image_options_raise
     document = Gamba.document
 
-    assert_match(/\Aunknown option :headr: accepted options are :width, :grow, :keep_with_next, :columns, :header, :stripes, :cell\z/, assert_raises(ArgumentError) { document.table(LINES, headr: true) }.message)
+    assert_match(/\Aunknown option :headr: accepted options are :width, :grow, :keep_with_next, :role, :alt, :columns, :header, :stripes, :cell\z/, assert_raises(ArgumentError) { document.table(LINES, headr: true) }.message)
     assert_raises(ArgumentError) { document.image(IMAGE, hight: 40) }
     assert_raises(ArgumentError) { document.image(IMAGE, align: :middle) }
     assert_raises(ArgumentError) { document.image(IMAGE, grow: 1) }
diff --git a/test/native_document_test.rb b/test/native_document_test.rb
index 1ad0998..9201e18 100644
--- a/test/native_document_test.rb
+++ b/test/native_document_test.rb
@@ -27,7 +27,7 @@ def test_an_unknown_document_option_raises_with_the_accepted_ones
   def test_an_unknown_text_attribute_raises_with_the_accepted_ones
     error = assert_raises(ArgumentError) { Gamba.document.text("Hello", colour: "ff0000", sise: 3) }
 
-    assert_match(/\Aunknown options :colour, :sise: accepted options are :font, :size, :weight, :italic, :color, :align, :leading, :widows, :orphans, :keep_with_next\z/, error.message)
+    assert_match(/\Aunknown options :colour, :sise: accepted options are :font, :size, :weight, :italic, :color, :align, :leading, :widows, :orphans, :keep_with_next, :role\z/, error.message)
   end
 
   def test_an_unknown_style_attribute_raises_when_the_style_is_defined
diff --git a/test/native_layout_test.rb b/test/native_layout_test.rb
index f238b86..4dbce45 100644
--- a/test/native_layout_test.rb
+++ b/test/native_layout_test.rb
@@ -190,7 +190,7 @@ def test_children_wider_than_their_row_raise
   def test_unknown_or_contradictory_options_raise
     document = Gamba.document
 
-    assert_match(/\Aunknown option :gab: accepted options are :width, :grow, :keep_with_next, :gap, /, assert_raises(ArgumentError) { document.stack(gab: 2) { nil } }.message)
+    assert_match(/\Aunknown option :gab: accepted options are :width, :grow, :keep_with_next, :role, :alt, :gap, /, assert_raises(ArgumentError) { document.stack(gab: 2) { nil } }.message)
     assert_raises(ArgumentError) { document.row(keep_together: true) { nil } }
     assert_raises(ArgumentError) { document.stack(padding: [1, 2, 3]) { nil } }
     assert_raises(ArgumentError) { document.row { |row| row.text "A", width: 10, grow: 1 } }
diff --git a/test/native_roles_test.rb b/test/native_roles_test.rb
new file mode 100644
index 0000000..01d6ddd
--- /dev/null
+++ b/test/native_roles_test.rb
@@ -0,0 +1,118 @@
+# frozen_string_literal: true
+
+require_relative "test_helper"
+require "json"
+require "open3"
+require "prawn"
+
+# What each box is to a reader, for tagged PDF: headings, paragraphs, lists, tables, figures with their alternative
+# text, artifacts. Headings already make the PDF's outline, nested by level, each pointing at its first line.
+class NativeRolesTest < Minitest::Test
+  def test_headings_make_the_outline_nested_by_level_at_their_first_line
+    document = Gamba.document do |yielded|
+      yielded.style :title, size: 18, weight: :bold, role: :h1
+      yielded.text "Introduction", style: :title
+      yielded.text "Background", role: :h2
+      yielded.text "word " * 2000
+      yielded.text "Details", role: :h3
+      yielded.text "Methods", style: :title
+      yielded.text "Data", role: :h3
+    end
+    outline = outline(document.to_s)
+
+    assert_equal [["Introduction", [["Background", [["Details", []]]]]], ["Methods", [["Data", []]]]], titles(outline)
+    lines = text_lines(document.to_s)
+    flatten(outline).each do |item|
+      page, baseline, size = lines.fetch(item["title"])
+      assert_equal page, item["destpageposfrom1"], item["title"]
+      # The destination is the top of the line: its baseline plus Helvetica's ascender.
+      assert_in_delta 792 - baseline + (0.718 * size), item["dest"][3], 0.01, item["title"]
+    end
+    assert_operator lines.fetch("Methods").first, :>, 1
+  end
+
+  def test_a_heading_moved_to_the_next_page_points_at_that_page
+    document = Gamba.document do |yielded|
+      yielded.prawn.move_down 700
+      yielded.stack(background: "eeeeee", keep_together: true) do |stack|
+        stack.text "Totals", role: :h2
+        3.times { stack.text "line" }
+      end
+    end
+
+    assert_equal [2], flatten(outline(document.to_s)).map { _1["destpageposfrom1"] }
+  end
+
+  def test_headings_of_prawn_code_blocks_share_one_outline_and_headers_bookmark_nothing
+    prawn = Prawn::Document.new do
+      gamba do |document|
+        document.header { |stack, page| stack.text "Report, page #{page.number}", role: :h1 }
+        document.text "Part one", role: :h1
+      end
+      text "Prawn's own text"
+      gamba { |document| document.text "Section", role: :h2 }
+    end
+
+    assert_equal [["Part one", [["Section", []]]]], titles(outline(prawn.render))
+  end
+
+  def test_roles_are_checked_and_carried_by_each_box
+    assert_equal :figure, Gamba::Layout::Image.new("logo.png", alt: "Example logo").role
+    assert_equal "Example logo", Gamba::Layout::Image.new("logo.png", alt: "Example logo").alt
+    assert_equal :table, Gamba::Layout::Table.new([{name: "alice"}], nil, nil).role
+    assert_nil Gamba::Layout::Stack.new(Gamba::Layout::Styles.new(Prawn::Document.new, [])).role
+
+    error = assert_raises(ArgumentError) { Gamba.document { |document| document.text "Hi", role: :h7 } }
+    assert_equal "role is :h7: a text takes :p, :h1, :h2, :h3, :h4, :h5, :h6, :list_item, :artifact", error.message
+    error = assert_raises(ArgumentError) { Gamba.document { |document| document.stack(role: :list, alt: "x") { _1.text "a" } } }
+    assert_equal "alt is the alternative text of a figure: give it with role: :figure, not :list", error.message
+    assert_raises(ArgumentError) { Gamba.document { |document| document.table([{name: "alice"}], role: :figure) } }
+    assert_raises(ArgumentError) { Gamba.document { |document| document.qr_code("x", role: :p) } }
+  end
+
+  def test_roles_change_nothing_drawn
+    plain = Gamba.document do |document|
+      document.text "Title", size: 18
+      document.stack { |list| list.text "one" }
+      document.qr_code "https://example.com"
+    end
+    with_roles = Gamba.document do |document|
+      document.text "Title", size: 18, role: :artifact
+      document.stack(role: :list) { |list| list.text "one", role: :list_item }
+      document.qr_code "https://example.com", alt: "Example's site"
+    end
+
+    assert_equal plain.to_s, with_roles.to_s
+  end
+
+  private
+
+  def outline(pdf)
+    Tempfile.create(["roles", ".pdf"]) do |file|
+      file.binmode
+      file.write(pdf)
+      file.flush
+      JSON.parse(Open3.capture2("qpdf", "--json", "--json-key=outlines", file.path).first).fetch("outlines")
+    end
+  end
+
+  def titles(items)
+    items.map { [_1["title"], titles(_1["kids"])] }
+  end
+
+  def flatten(items)
+    items.flat_map { [_1, *flatten(_1["kids"])] }
+  end
+
+  # Each line's text: [page, baseline from the top, size].
+  def text_lines(pdf)
+    Tempfile.create(["roles", ".pdf"]) do |file|
+      file.binmode
+      file.write(pdf)
+      file.flush
+      Oracle.text_layout(file.path).each_with_index.flat_map do |page, index|
+        page.glyphs.group_by(&:last).map { |y, glyphs| [glyphs.map(&:first).join, [index + 1, y, glyphs.first[2]]] }
+      end.to_h
+    end
+  end
+end
diff --git a/test/support/layout_trees.rb b/test/support/layout_trees.rb
index e19cb6d..b0aea53 100644
--- a/test/support/layout_trees.rb
+++ b/test/support/layout_trees.rb
@@ -66,6 +66,7 @@ def container_options(kind, inline)
   def text_options(parent, inline)
     options = ", size: #{FONT_SIZES.sample(random: @random)}"
     options << ", widows: #{@random.rand(1..3)}, orphans: #{@random.rand(1..3)}" if chance(0.4)
+    options << ", role: :h#{@random.rand(1..6)}" if chance(0.1)
     options << ", keep_with_next: true" if chance(0.15)
     options + width_options(parent, inline)
   end

From 98cf60de8b486c2fc4c822991d3935ac4b5d86ba Mon Sep 17 00:00:00 2001
From: Claude 
Date: Sat, 21 Nov 2026 11:46:12 +0000
Subject: [PATCH 5/5] Guide Prawn code to the native API in three stages

A migration page takes the bench invoice from Prawn code to Gamba's own
API: the same code on Gamba, its table as one native block (byte for byte
the same PDF), then written natively and tagged. Five Prawn idioms sit
beside the native code that replaces them. A test runs every sample of
the page, checks the stages show the bench's code and draw the same
invoice, and that each pair draws the same text.

The bench measures the middle stage from bench/mixed, and the home page,
README and gemspec lead with the native API, Prawn compatibility second.

Assisted-by: Claude [Claude Code]
---
 README.md                   |  35 ++--
 Rakefile                    |   2 +-
 bench/compare.rb            |  15 +-
 bench/mixed/invoice.rb      |  10 ++
 docs/benchmarks.html        |   5 +-
 docs/compatibility.html     |   1 +
 docs/guide.html             |   3 +-
 docs/index.html             |  44 +++--
 docs/migration.html         | 310 ++++++++++++++++++++++++++++++++++++
 docs/site.js                |  31 +++-
 gamba.gemspec               |   7 +-
 test/migration_page_test.rb |  89 +++++++++++
 12 files changed, 512 insertions(+), 40 deletions(-)
 create mode 100644 bench/mixed/invoice.rb
 create mode 100644 docs/migration.html
 create mode 100644 test/migration_page_test.rb

diff --git a/README.md b/README.md
index 65b1217..706cdb4 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,13 @@
 # Gamba
 
 Gamba is a Ruby library that writes PDF files: invoices, reports, labels, anything you can lay out as text, tables,
-images and shapes. It is a faster rewrite of [Prawn](https://github.com/prawnpdf/prawn), the most widely used PDF
-library for Ruby, together with its two companion gems, prawn-table and prawn-svg.
+images and shapes. You describe the layout, stacks, rows, tables, headers and footers, and Gamba measures it, places
+it, breaks pages where a reader expects them, and tags the result for screen readers.
 
-Code written for Prawn 2.5 runs on Gamba unchanged and draws the same pages, down to the pixel. The difference is
-speed and size: a one-page invoice renders about four times faster and the file is a quarter lighter (see
-[Performance](#performance)).
+It also runs code written for [Prawn](https://github.com/prawnpdf/prawn) 2.5, the most widely used PDF library for
+Ruby, and for its companions prawn-table and prawn-svg, unchanged and down to the pixel: a one-page invoice renders
+about four times faster and the file is a quarter lighter (see [Performance](#performance)). An application moves
+from one API to the other one block at a time ([the migration guide](https://levups.github.io/gamba/migration.html)).
 
 Website and guide: https://levups.github.io/gamba/
 
@@ -24,6 +25,19 @@ without them.
 
 ## A first document
 
+```ruby
+require "gamba"
+
+Gamba.document do |document|
+  document.footer { |footer, page| footer.text "Page #{page.number} of #{page.total}" }
+  document.text "Hello, World!", role: :h1
+  document.table([{sku: "A-1", quantity: 2}], columns: {sku: {title: "SKU"}, quantity: {title: "Qty"}})
+end.write("hello.pdf")
+```
+
+This writes `hello.pdf` with a heading, which also makes the PDF's first bookmark, a two-row table and a footer
+numbering the pages. The same document with Prawn's API, which Gamba runs as it is:
+
 ```ruby
 require "prawn"
 
@@ -33,9 +47,9 @@ Prawn::Document.generate("hello.pdf") do
 end
 ```
 
-This writes `hello.pdf` with a line of text and a two-row table. Everything else Prawn documents works the same
-way: fonts, colors, images, columns, page numbers, links, encryption. Prawn's manual applies as it is, and
-[the guide](https://levups.github.io/gamba/guide.html) covers what Gamba adds.
+Everything else Prawn documents works the same way: fonts, colors, images, columns, page numbers, links,
+encryption. Prawn's manual applies as it is, and [the guide](https://levups.github.io/gamba/guide.html) covers what
+Gamba adds.
 
 The constant is still `Prawn`, so you don't have to rename anything. `Prawn::VERSION` reports `2.5.0`, the
 version of the API Gamba reproduces, for code that checks it. Gamba's own version is `Gamba::VERSION`.
@@ -83,8 +97,9 @@ document.table(lines, columns: {sku: {title: "SKU", width: 60}, description: {},
 Pages break where a reader expects them: a paragraph leaves no single line at the bottom or the top of a page
 (`widows` and `orphans`, 2 unless told), and a heading with `keep_with_next: true` moves with what follows it.
 
-Text, styles, components, stacks, rows, grids, tables, images, headers, footers and these page breaks are there today;
-boxes with a background split across pages come next ([the plan](https://github.com/levups/gamba/issues/69)).
+Text, styles, components, stacks, rows, grids, tables, images, codes, headers, footers, these page breaks and
+semantic roles are there today; forms, signatures and complex scripts come next
+([the plan](https://github.com/levups/gamba/issues/69)).
 
 Ligatures and kerning from OpenType fonts, per font:
 
diff --git a/Rakefile b/Rakefile
index 40817b1..82b2839 100644
--- a/Rakefile
+++ b/Rakefile
@@ -22,7 +22,7 @@ namespace :corpus do
   end
 end
 
-desc "Compare Gamba with Prawn on bench/documents, and Gamba's own API untagged and tagged on bench/native, into docs/benchmarks.json"
+desc "Compare Gamba with Prawn on bench/documents, one native block on bench/mixed, and Gamba's own API untagged and tagged on bench/native, into docs/benchmarks.json"
 task :bench do
   ruby "bench/compare.rb"
 end
diff --git a/bench/compare.rb b/bench/compare.rb
index 884c49a..385a205 100644
--- a/bench/compare.rb
+++ b/bench/compare.rb
@@ -1,7 +1,8 @@
 # frozen_string_literal: true
 
-# Renders each document of bench/documents with Prawn and with Gamba, and its bench/native version with Gamba's own
-# API untagged then tagged for PDF/UA, in PROCESSES fresh YJIT processes per column, and writes the median of each
+# Renders each document of bench/documents with Prawn and with Gamba, its bench/mixed version (Prawn code holding one
+# block of Gamba's own API) with Gamba, and its bench/native version with Gamba's own API untagged then tagged for
+# PDF/UA, in PROCESSES fresh YJIT processes per column, and writes the median of each
 # measure across them (time, allocations, peak memory, file weight) to docs/benchmarks.json. Peak memory varies by 20%
 # from one process to the next: one process proves nothing.
 
@@ -48,20 +49,22 @@ def median(values)
   sorted.all?(Integer) ? mean.round : mean.round(1)
 end
 
-# What each column of the results renders: the document with Prawn's API on each engine, and with Gamba's own API
-# where bench/native has it, untagged then tagged for PDF/UA.
+# What each column of the results renders: the document with Prawn's API on each engine, with one native block where
+# bench/mixed has it, and with Gamba's own API where bench/native has it, untagged then tagged for PDF/UA.
 def candidates(document)
+  mixed = File.join(__dir__, "mixed", File.basename(document))
   native = File.join(NativeBench::DIRECTORY, File.basename(document))
   columns = Oracle::ENGINES.keys.to_h { |engine| [engine, [engine, document]] }
+  columns["gamba_mixed"] = ["gamba", mixed] if File.exist?(mixed)
   return columns unless File.exist?(native)
 
   columns.merge("gamba_native" => ["gamba", native], "gamba_tagged" => ["gamba", native, "pdf_ua"])
 end
 
 # A Williams design: over as many rounds as columns, each column takes each place once and follows each other column
-# once (an even count of columns, as here), so neither a slower moment of the machine nor a heavier neighbour falls
+# once (for an even count of columns), so neither a slower moment of the machine nor a heavier neighbour falls
 # on one column more than another. Only a multiple of the columns balances all the rounds: 7, the default the site's
-# numbers were measured with, repeats the first three orders.
+# numbers were measured with, repeats the first orders.
 def order(count, round)
   first = [0] + (1...count).map { |step| step.odd? ? (step + 1) / 2 : count - (step / 2) }
   first.map { |index| (index + round) % count }
diff --git a/bench/mixed/invoice.rb b/bench/mixed/invoice.rb
new file mode 100644
index 0000000..486e8da
--- /dev/null
+++ b/bench/mixed/invoice.rb
@@ -0,0 +1,10 @@
+# The invoice of bench/documents, its table moved to one block of Gamba's own API: the middle step of a migration.
+font_families.update("DejaVuSans" => {normal: "#{DATA_DIRECTORY}/fonts/DejaVuSans.ttf", bold: "#{DATA_DIRECTORY}/fonts/DejaVuSans-Bold.ttf"})
+font "DejaVuSans", size: 9
+image "#{DATA_DIRECTORY}/images/letterhead.jpg", width: 200
+text "Invoice INV-2026-0001 — Alice Example", style: :bold, size: 14
+move_down 10
+lines = Array.new(10) { {sku: "SKU#{_1}", description: "Gadget, deluxe edition, model #{_1} with spare parts toolkit", quantity: "2", unit: "$1,299.00", total: "$2,598.00"} }
+gamba do |document|
+  document.table(lines, columns: {sku: {title: "SKU"}, description: {}, quantity: {title: "Qty"}, unit: {}, total: {}}, header: {weight: :normal}, cell: {padding: 3})
+end
diff --git a/docs/benchmarks.html b/docs/benchmarks.html
index f73f9e7..8f298f4 100644
--- a/docs/benchmarks.html
+++ b/docs/benchmarks.html
@@ -25,6 +25,7 @@