Skip to content

feat(layout): add Preformatted, which keeps every space and tab - #662

Merged
Tim81 merged 8 commits into
mainfrom
feat/preformatted
Nov 21, 2026
Merged

Tim81 merged 8 commits into
mainfrom
feat/preformatted

Conversation

@Tim81

@Tim81 Tim81 commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Closes #591

What changed

A paragraph collapses runs of spaces and draws a tab as a space, so command blocks, configuration and ASCII tables lose their columns. Preformatted keeps them.

New public API in VellumPdf.Layout:

  • Preformatted(string text, TextStyle? style = null) with Text, Style, TabWidth (1 to 32, default 8), Margins and BreakBefore.
  • Document.Add(Preformatted).
  • LayoutDiagnosticCode.PreformattedLineWrapped = 104 (a warning) and LayoutElementKind.Preformatted = 11.

Behaviour:

  • Lines end at CR LF, a lone CR or a lone LF. "a\n" is one line, "a\n\n" two, "" one empty line.
  • Every space is kept. A tab becomes the spaces that reach the next stop, counted in extended grapheme clusters, before anything is measured or drawn, so the content stream holds no tab byte.
  • A line wider than the content box is split into segments. Each segment but the last holds the longest run of whole clusters that leaves room for a continuation marker (at least one cluster, so the wrap always advances). The marker is a stroked vector hook drawn as an artifact, so it enters neither the structure tree nor extracted text. No character is dropped. The save lists the wrapped lines as code 104, which strict mode saves.
  • The block splits between drawn lines. A wrapped line can continue on the next page, with its marker on the first.
  • A tagged document gets one P structure element per drawn piece. Nothing in the character stream separates two lines; this is documented on the type.
  • Show strings are cut into runs of at most 4,096 scalars with no positioning between them, so a line of zero-advance glyphs stays under the 32,767-byte string limit.
  • With no claim, a character the embedded font lacks is drawn as glyph 0 and listed as NotdefGlyph (102, an error), as for a paragraph, so StrictDiagnostics refuses that save. The runs go through TextEmitter, which lists the character. Under a claim the pre-layout refusal below runs first, so nothing is listed.
  • Default style is Courier 10 pt. Document.SetDefaultFont does not apply.

Refusals, all on the new type:

  • The constructor throws ArgumentException (text) for control characters other than tab, CR and LF, for U+2028 and U+2029, and for an unpaired surrogate, naming the index and code point. It throws ArgumentException (style) for a font size that is not finite, is below 0.000005 or is above 1e30 (a number past 3.403 × 10^38 fails ISO 32000-1, Annex C, Table C.1, and PDF/A-2 6.1.13), a non-finite leading, a colour channel outside 0 to 1, a Standard14 value the enumeration does not name, Symbol, ZapfDingbats, and any LinkUri.
  • TabWidth, Margins and BreakBefore refuse bad values from their init accessors with ArgumentOutOfRangeException.
  • Before any layout, the save throws InvalidOperationException when the content box is no wider than zero or shorter than one line. Under a PDF/A or PDF/UA-1 claim it also throws when the font is not embedded (ISO 19005-2:2011, 6.2.11.4.1; ISO 14289-1:2014, 7.21.4.1) or has no glyph for a character, a tab's spaces included (6.2.11.8; 7.21.8). Under PDF/A-2a, PDF/A-2u and PDF/UA-1 it also refuses U+FEFF and U+FFFE even when the font maps them (6.2.11.7.2; 7.21.7). These run before HasStartedLayout is set, so the document stays saveable once the named setting changes, and a retry saves once.
  • The character check needs a glyph lookup that does not register. The first commit adds TrueTypeFontEmbedder.PeekGlyphId (internal), so a refused save leaves nothing in the subset for a retry to inherit.

Doc updates: XML docs on every new member, one sentence on TextStyle.FontSize, Leading, Color, FontRef, LinkUri and ColorRgb, PageBreakMode (the element honours BreakBefore and refuses a form feed), the Document.Diagnostics code list, the capability table in both copies, and the CHANGELOG.

No deliberate output change: a document without the new element saves to the same bytes. Two new pins (untagged and tagged, with a paragraph, heading, list, table and both bands) were recorded before the element existed and also pass on the parent commit.

Follow-up, not in this PR: v2.5 adds a P > Code opt-in for text that is code. This PR tags each piece as P, because a preformatted block need not be code.

2.3.3 against this build

The type is new, so there is no 2.3.3 column for it. For existing input:

Input 2.3.3 This build
Any document without Preformatted (paragraph, heading, list, table, both bands; untagged and tagged) saves same normalised bytes, pinned in PreformattedByteIdentityTests, also passing on the parent commit
Paragraph("\tingesprongen\tmet tabs\n vier spaties dubbel"), Courier 10 (ingesprongen met tabs) Tj, (vier spaties dubbel) Tj unchanged

pdftotext 26.08.0 on a hand-drawn page with the same expanded text: -layout printed vier spaties dubbel (the two double spaces collapsed), while -fixed 6 returned every line exactly, shifted right by 12 columns (72 pt margin over a 6 pt pitch). So the tests use -fixed. The poppler pinned in CI is 24.02; it was not run locally, and the assertions compare non-blank lines only, so a different blank-line policy cannot fail them.

Tests

At 3b1daea (main at 9747913 merged in), Layout.Tests, Release, REQUIRE_ORACLES=1, REQUIRE_VERAPDF=1, veraPDF 1.30.4, qpdf 12.4.2, poppler 26.08.0: 3,548 tests over both frameworks, 3,544 pass, 4 skip (the two Linux-only pipe tests on each framework), 0 fail. Kernel.Tests: 5,328 pass over both frameworks. Build has 0 warnings, dotnet format --verify-no-changes, the clean-room check and the roadmap check pass.

New test classes: PreformattedTests (tabs, clusters, line ends, widths equal MeasureString bit for bit), PreformattedWrapTests (marker operators, report, break position, pages, show-string runs), PreformattedRefusalTests (every UTF-16 code unit against the refused set, each style and init refusal, exact messages, retry), PreformattedTaggedTests, PreformattedBoundTests, PreformattedOracleTests, PreformattedByteIdentityTests and, in Kernel.Tests, PeekGlyphIdTests (every scalar value, in LiberationMono and DejaVu Sans).

Oracles: pdftotext -fixed 6 on Courier and LiberationMono documents; veraPDF 1.30.4 with an empty failed-rule list on PDF/A-2u, PDF/A-2a and PDF/UA-1 documents holding tabs, wrapped lines and several pages; qpdf --check reporting "No syntax or stream encoding errors found" on the 2u and ua1 files. Each test first asserts the saved file holds the expanded text and no tab byte.

A footer takes room from every page: 200 lines of Courier 10 give pages of 58, 58, 58 and 26 lines with no footer, and 56, 56, 56 and 32 with a {page}/{pages} footer, in one measuring pass either way.

Mutations

Each mutant was applied in a detached worktree, built, run against the new test classes, and reverted. Every one fails at least one test.

# Mutant Failing tests (first)
1 every tab expands to TabWidth spaces ATabAddsTheSpacesToTheNextStop cases, the two -fixed oracle tests (9 tests)
2 columns counted in UTF-16 units AClusterIsOneColumn_whateverItsLength, AClusterOfTwoUnits_doesNotShortenTheTab
3 runs of spaces collapsed LinesEndWhereTheTextEndsThem..., exact-stream and -fixed tests (11 tests)
4 tab left in the text exact-stream, no-tab-byte and -fixed tests (12 tests)
5 remainder cut instead of wrapped WideLines_wrapAtTheMarkerReserve..., ABlockOfWrappedLines_... (6 tests)
6 no marker reserve WideLines_wrapAtTheMarkerReserve..., marker operator tests (6 tests)
7 marker reserved on the last segment too WideLines_wrapAtTheMarkerReserve..., AWrappedLine_thatStraddlesAPageEnd...
8 break by scalar, not cluster TheBreak_fallsBeforeACluster_notInsideIt
9 markers drawn before EMC TheMarker_isAnArtifactOutsideTheTaggedParagraph..., ABlockOfWrappedLines_keepsItsMarkersOutside..., the UA-1 veraPDF test
10 artifact wrapper dropped same three tests
11 font check dropped TheFirstFailingCheckWins_geometryBeforeFontBeforeCharacters
12 character check dropped ACharacterTheFontLacks_isRefusedUnderAClaim..., TheCharacterCheckCountsATabsSpaces..., ARefusedClaimThenNoClaim...
13 U+FEFF rule applied to PDF/A-2b AByteOrderMark_isAccepted_underPdfA2b
14 checks run after HasStartedLayout = true AContentBoxShorterThanOneLine..., AContentBoxNoWiderThanZero..., ARefusedClaimThenNoClaim...
15 severity Error TheWrapIsReported_onceForTheElement_asAWarning_andStrictModeSaves
16 report on every piece AWrappedLine_thatStraddlesAPageEnd_hasItsMarkerOnTheFirstPage_andIsReportedOnce
17 no wrap cache WithAFooter_... (WrapCalls), two bound tests
18 no show-string cut ALongShowString_isCutIntoRunsOf4096Scalars_withNoTmBetween
19 colour range check dropped ARefusedStyle_isRefusedAtTheConstructor (red above 1, green below 0)
20 PeekGlyphId registers PeekGlyphIdTests.Handle_peekLeavesTheSubsetAsItWas (3 of 4 cases fail)

Bounds

Allocation is read with GC.GetAllocatedBytesForCurrentThread(); no test asserts a time.

Case Measured (Release, net10.0)
constructor on 10^5 and 10^6 characters 72 bytes each after a warm-up (the first, unwarmed call at 10^4 allocated 2,032 bytes, JIT included); the test takes the minimum of five samples and pins it at most 65,536 bytes, which a copy of the 10^6-character text (about 2 MB) exceeds
save, 1,000 tabs against 10,000 tabs at TabWidth 32 (32,000 and 320,000 columns) 1,438,032 and 14,257,352 bytes, a ratio of 9.9
save, 100,000 against 1,000,000 characters of Courier 4,023,256 and 41,036,520 bytes, a ratio of 10.2
visual lines for those two lines 1,352 and 13,514, WrapCalls == 1

The tests assert the ratio stays within 15 and that the larger input costs more than the smaller.

A check that runs before drawing needs the glyph a character would get,
but GetGlyphId adds it to the subset and the ToUnicode map, so a refused
save left registrations for the retry to inherit. PeekGlyphId answers
the same and changes nothing.
A paragraph collapses runs of spaces and draws a tab as a space, so
command blocks, configuration and ASCII tables lose their columns.
Preformatted keeps every space, expands tabs to stops counted in
grapheme clusters, wraps a too-wide line with a vector marker, and
refuses what cannot be drawn faithfully: control characters at the
constructor, and under a PDF/A or PDF/UA claim an unembedded font or a
character with no glyph at the save, before any layout runs.
# Conflicts:
#	src/VellumPdf.Layout/Core/TextStyle.cs
#	src/VellumPdf.Layout/Document.cs
#	src/VellumPdf.Layout/LayoutDiagnosticCode.cs
#	src/VellumPdf.Layout/PublicAPI.Unshipped.txt
Preformatted drew its runs with GetGlyphIds and ShowGlyphs, which lists a
glyph 0 with no character. It now selects the font and shows each run
through TextEmitter, so the report names the character as for a
paragraph. The pre-layout refusals still run first under a claim.
A FontSize of 1e39 saved, wrote an operand past the 3.403e38 limit of
ISO 32000-1 Annex C Table C.1, and failed PDF/A-2 6.1.13. The
constructor now refuses a size above 1e30, which leaves a factor of
about 3.4e8 below the limit.

Also qualify the CHANGELOG column claim for zero-width characters,
drop a sentence about a DrawContext no caller can build, replace raw
characters in test sources with escapes, widen the allocation bound
test to the minimum of five samples, and add tests for the scalar cut
of a show run, the exact-width line, CR LF line numbers and the scalar
named for a non-BMP character.
… rules

The 1e30 ceiling is a margin below the 3.403 x 10^38 limit, not the
boundary, and only a zero-width character that forms a cluster of its
own shifts later columns. Reword the CHANGELOG, the type docs and the
refusal message to say so, and drop raw characters from test code.
@Tim81
Tim81 merged commit 2bff29c into main Nov 21, 2026
6 checks passed
@Tim81
Tim81 deleted the feat/preformatted branch November 26, 2026 20:21
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.

Layout: a preformatted element that keeps every space and tab

1 participant