Skip to content

Document whitespace - #69

Merged
letmutex merged 8 commits into
letmutex:mainfrom
bjones1:document-whitespace
Dec 16, 2025
Merged

letmutex merged 8 commits into
letmutex:mainfrom
bjones1:document-whitespace

Conversation

@bjones1

@bjones1 bjones1 commented Dec 12, 2025 •

Copy link
Copy Markdown
Contributor

This follows #68. Please merge that first.

When operating on the DOM, this code should use document whitespace, not typical whitespace. The two exceptions: in emphasis and strong emphasis, pure whitespace is needed.

Therefore, switch most uses in htmd to use document whitespace and add a test. Although this PR looks large, it's mainly renames, not code changes. text_util.rs has the real changes. That's what needs the most review.

Summary by CodeRabbit

  • New Features

    • Added support for math spans with distinct inline and display rendering.
  • Bug Fixes

    • Improved whitespace handling across the renderer for more accurate trimming and preservation.
    • Better table cell rendering when cells contain block-level content.
  • Chores

    • Updated several project dependencies to newer versions.
  • Tests

    • Added tests covering math rendering and document-whitespace behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 12, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors whitespace trimming from ASCII-focused to document-aware semantics across the codebase, adds a new span handler to detect/render math spans, adjusts table cell serialization to detect block children in faithful mode, updates a macro's type cast, bumps several dependencies, and adds tests for math and document-whitespace behavior.

Changes

Cohort / File(s) Summary
Dependency updates
Cargo.toml
Bumped html5ever and markup5ever_rcdom to 0.36; updated dev-dependencies (scraper → 0.25, criterion → 0.8 with html_reports); removed indoc = "2.0.6" from dev-deps.
Whitespace trait & helpers
src/text_util.rs
Renamed TrimAsciiWhitespace → TrimDocumentWhitespace; renamed methods to trim_document_whitespace, trim_start_document_whitespace, trim_end_document_whitespace; added strip_leading_document_whitespace, strip_trailing_document_whitespace and helper is_document_whitespace.
Whitespace imports/usages
src/dom_walker.rs, src/element_handler/anchor.rs, src/element_handler/blockquote.rs, src/element_handler/code.rs, src/element_handler/headings.rs, src/element_handler/img.rs, src/element_handler/li.rs, src/element_handler/table.rs
Updated imports and call sites to use TrimDocumentWhitespace and document-whitespace trimming variants instead of ASCII variants; applied to content normalization and trimming logic.
New span handler
src/element_handler/mod.rs, src/element_handler/span.rs
Added span module and span_handler; registered handler for span tag; detects class="math math-inline" / math-display to emit $...$ or $$...$$, otherwise falls back to faithful serialization or child-walking with newline trimming.
Table/td_th changes
src/element_handler/td_th.rs, src/element_handler/element_util.rs
td_th_handler now checks for block children when in TranslationMode::Faithful and uses serialize_if_faithful(..., -1) to force HTML for block-containing cells; serialize_if_faithful macro comparison casts $element.attrs.len() to i64 before comparing to $num_attrs_allowed.
Minor documentation/commentary
src/element_handler/emphasis.rs
Added clarifying comment about emphasis whitespace per CommonMark; no behavior changes.
Tests
tests/basic_tests.rs, tests/table_tests.rs
Replaced find(...).is_some() with any(...); added math test for inline/display math and document_whitespace test for non-breaking-space preservation; added test_table_block_cells verifying table cell with block element serialization.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Pay attention to cross-file semantic impact of switching to document-whitespace predicates (handlers, trimming, and joining).
  • Review span_handler for correct class matching and escaping behavior inside math spans.
  • Verify td_th_handler block-detection logic and the -1 faithful serialization edge case.
  • Confirm the serialize_if_faithful i64 cast interacts safely with all callers.

Possibly related PRs

Poem

🐰
Soft hops replace ASCII dust, I trim with care, not rust.
Math in dollars — single, double — sparkles bright and tidy, subtle.
Tables learn to hold tall blocks, I nibble edges, leave no shocks.
Hooray — a quiet, clever change from this small rabbit's range!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Document whitespace' directly summarizes the main objective of the PR, which is to change HTMD to use document whitespace semantics instead of ASCII whitespace when operating on the DOM.
Docstring Coverage ✅ Passed Docstring coverage is 82.61% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between da95a38 and e9d8a26.

📒 Files selected for processing (1)
  • Cargo.toml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Cargo.toml

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/element_handler/table.rs (1)

208-215: Column widths are computed on non-normalized content but rendered with normalized content (possible padding miscalc).
compute_column_widths() counts chars on headers/rows raw strings, while rendering runs normalize_cell_content() (newline replacement + | escaping + trimming). This can produce visibly uneven padding for cells containing | or leading/trailing document whitespace.

Suggested fix: compute widths on normalized strings too.

 fn compute_column_widths(
     headers: &[String],
     rows: &[Vec<String>],
     num_columns: usize,
 ) -> Vec<usize> {
     let mut widths = vec![0; num_columns];
     for (i, header) in headers.iter().enumerate() {
-        widths[i] = header.chars().count();
+        widths[i] = normalize_cell_content(header).chars().count();
     }
     for row in rows {
         for (i, cell) in row.iter().enumerate().take(num_columns) {
-            let len = cell.chars().count();
+            let len = normalize_cell_content(cell).chars().count();
             if len > widths[i] {
                 widths[i] = len;
             }
         }
     }
     widths
 }

Also applies to: 217-226, 240-258

🧹 Nitpick comments (3)
src/element_handler/td_th.rs (1)

10-27: Faithful-mode fallback for block children in <td>/<th> is a solid guardrail.
Consider adding a regression test for a table cell containing a block element (e.g., <td><div>...</div></td>) to lock in the intended serialization behavior.

src/element_handler/element_util.rs (1)

179-204: Macro tweak works, but consider avoiding -1 sentinel long-term.
The cast enables the -1 behavior as documented, but an enum/Option-based API (e.g., FaithfulSerialize::Always | MaxAttrs(usize)) would be harder to misuse.

src/text_util.rs (1)

29-94: StripWhitespace document-variants: correctness looks fine; consider de-dup helper.

The new document-whitespace methods mirror the existing logic cleanly. Optional: extract a small internal helper to reduce the near-identical leading/trailing implementations.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d71970 and da95a38.

📒 Files selected for processing (17)
  • Cargo.toml (1 hunks)
  • src/dom_walker.rs (2 hunks)
  • src/element_handler/anchor.rs (3 hunks)
  • src/element_handler/blockquote.rs (2 hunks)
  • src/element_handler/code.rs (2 hunks)
  • src/element_handler/element_util.rs (1 hunks)
  • src/element_handler/emphasis.rs (1 hunks)
  • src/element_handler/headings.rs (1 hunks)
  • src/element_handler/img.rs (2 hunks)
  • src/element_handler/li.rs (2 hunks)
  • src/element_handler/mod.rs (3 hunks)
  • src/element_handler/span.rs (1 hunks)
  • src/element_handler/table.rs (5 hunks)
  • src/element_handler/td_th.rs (1 hunks)
  • src/text_util.rs (5 hunks)
  • tests/basic_tests.rs (2 hunks)
  • tests/table_tests.rs (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
src/element_handler/mod.rs (1)
src/element_handler/span.rs (1)
  • span_handler (10-36)
src/element_handler/li.rs (1)
src/text_util.rs (1)
  • indent_text_except_first_line (218-246)
src/element_handler/td_th.rs (5)
src/dom_walker.rs (1)
  • is_block_element (433-435)
src/element_handler/element_util.rs (1)
  • handle_or_serialize_by_parent (16-42)
src/node_util.rs (1)
  • get_node_tag_name (5-11)
src/element_handler/mod.rs (2)
  • options (317-317)
  • options (354-356)
src/lib.rs (1)
  • options (171-174)
tests/basic_tests.rs (3)
src/element_handler/list.rs (1)
  • attr (88-88)
src/lib.rs (2)
  • convert (30-32)
  • convert (106-144)
tests/common/mod.rs (1)
  • convert (8-16)
🔇 Additional comments (18)
src/element_handler/code.rs (1)

12-12: LGTM! Consistent whitespace handling update.

The transition from TrimAsciiWhitespace to TrimDocumentWhitespace aligns with the project-wide refactoring objective. The logic remains unchanged; only the whitespace trimming semantics are updated.

Also applies to: 137-137

src/element_handler/img.rs (1)

5-5: LGTM! Consistent whitespace handling update.

The transition from TrimAsciiWhitespace to TrimDocumentWhitespace aligns with the project-wide refactoring. The logic for processing alt and title text remains unchanged.

Also applies to: 31-31

tests/table_tests.rs (2)

7-7: LGTM! Appropriate use of indoc for test readability.

The addition of indoc::indoc import enhances test readability by enabling cleaner multi-line string formatting in the new test.


183-224: LGTM! Good test coverage for block elements in table cells.

This test verifies that tables containing block elements (like <p> tags) inside table headers are handled correctly in faithful mode. The test structure is sound and uses indoc! appropriately for multi-line HTML comparisons.

src/element_handler/li.rs (1)

7-7: LGTM! Consistent whitespace handling update.

The transition from TrimAsciiWhitespace to TrimDocumentWhitespace aligns with the project-wide refactoring. The list item content trimming logic remains unchanged.

Also applies to: 18-18

tests/basic_tests.rs (3)

552-552: LGTM! More idiomatic Rust.

Replacing find(...).is_some() with any(...) is cleaner and more idiomatic. The logic remains equivalent while improving readability.


656-673: LGTM! Comprehensive math rendering test.

The test covers:

  • Inline math with $...$ delimiters
  • Display math with $$...$$ delimiters
  • Verification that content inside math spans is not escaped (critical for LaTeX syntax preservation)

The test is well-structured and provides good coverage for the new math span handling.


675-690: LGTM! Good test for document whitespace semantics.

This test verifies that non-breaking spaces (\u{a0}, rendered as &nbsp; in HTML) are correctly preserved in the output, confirming they are not treated as document whitespace. This is critical for maintaining intended formatting.

src/element_handler/emphasis.rs (1)

18-19: LGTM! Valuable clarification comment.

This comment provides important context by distinguishing between regular whitespace (as defined by the CommonMark spec for emphasis) and document whitespace. This clarification helps prevent confusion during the broader whitespace refactoring and aids future maintainers.

src/element_handler/anchor.rs (1)

8-8: LGTM! Consistent whitespace handling update.

The transition from ASCII whitespace to document whitespace handling is applied consistently across:

  • Title processing (line 53)
  • Leading/trailing whitespace stripping in inlined anchors (lines 98-99)

The logic remains unchanged; only the whitespace trimming semantics are updated to align with the project-wide refactoring.

Also applies to: 53-53, 98-99

src/element_handler/table.rs (1)

6-7: Good switch to TrimDocumentWhitespace for captions/cells normalization.
This aligns table content trimming with the new “document whitespace” semantics and keeps the logic straightforward.

Also applies to: 43-47, 190-202, 208-215

src/element_handler/headings.rs (1)

1-7: Heading trimming update looks consistent (trim_document_whitespace() then newline trimming).

Also applies to: 11-15

src/element_handler/mod.rs (1)

17-23: span_handler registration/wiring looks correct.

Also applies to: 49-55, 175-182

src/element_handler/blockquote.rs (1)

1-6: Blockquote trimming change is consistent and safe.

Also applies to: 12-20

src/dom_walker.rs (1)

11-15: trim_buffer_end update to document-whitespace semantics looks good.

Also applies to: 257-265

src/element_handler/span.rs (1)

10-36: The math span detection logic is intentionally strict—it only matches the exact class format "math math-inline" or "math math-display" with a single text child. This aligns with the test suite, which confirms that inline math outputs as $...$ and display math as $$...$$ without surrounding newlines. If your HTML source uses different class ordering or additional classes, the current logic will not detect it as math and will fall through to default span handling.

If the HTML producer might emit classes in different order or with additional classes, consider extending the class matching to parse individual tokens, though this would require verifying the target markdown renderer accepts the output format.

src/text_util.rs (2)

1-27: Trait rename + trimming via trim_*_matches(is_document_whitespace) is coherent.

Implementation is straightforward and should behave correctly for &str/String via AsRef<str>.


218-246: indent_text_except_first_line: trimming switch to document whitespace matches PR intent.

Using trim_end_matches(is_document_whitespace) here is consistent with the new semantics and avoids trimming non-document ASCII whitespace.

Comment thread Cargo.toml Resolved
Comment thread src/text_util.rs
Comment on lines +211 to +216
// Per [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Text/Whitespace),
// document white space characters only include spaces, tabs, line
// feeds, and newlines. Remove only these from the end of a line.
fn is_document_whitespace(c: char) -> bool {
['\t', '\n', '\r', ' '].contains(&c)
}

@coderabbitai coderabbitai Bot Dec 12, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's read the full context around the function
cat -n src/text_util.rs | sed -n '200,230p'

Repository: letmutex/htmd

Length of output: 1247


🏁 Script executed:

# Search for any other references to is_document_whitespace or related whitespace handling
rg "is_document_whitespace" -B 3 -A 3

Repository: letmutex/htmd

Length of output: 1542


🏁 Script executed:

# Check if there are any comments or documentation about whitespace handling
rg "whitespace|white.space|form.feed" -i -B 2 -A 2 src/text_util.rs

Repository: letmutex/htmd

Length of output: 3994


🌐 Web query:

MDN CSS whitespace characters specification

💡 Result:

MDN describes which characters count as (ASCII) whitespace and how CSS handles them:

  • ASCII whitespace (per HTML/Infra Standard): U+0009 (TAB), U+000A (LF), U+000C (FF), U+000D (CR), U+0020 (SPACE). [1]
  • The CSS white-space property defines how those whitespace characters (and other Unicode space separators) are collapsed, preserved, or cause line breaks (values: normal, nowrap, pre, pre-wrap, pre-line, break-spaces, etc.). See the property reference and handling details. [2][3]

Sources:
[1] MDN Glossary — Whitespace.
[2] MDN — white-space (CSS) property.
[3] MDN — Handling whitespace in CSS.


is_document_whitespace omits form feed (\u{000C}), which is part of CSS/ASCII whitespace per MDN.

The code comment incorrectly states that MDN whitespace includes only "spaces, tabs, line feeds, and newlines." MDN explicitly defines ASCII whitespace as: U+0009 (TAB), U+000A (LF), U+000C (FF), U+000D (CR), U+0020 (SPACE). The current implementation ['\t', '\n', '\r', ' '] is missing form feed. Update the function to include '\u{000C}' and correct the comment.

 fn is_document_whitespace(c: char) -> bool {
-    ['\t', '\n', '\r', ' '].contains(&c)
+    ['\t', '\n', '\r', ' ', '\u{000C}'].contains(&c)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Per [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Text/Whitespace),
// document white space characters only include spaces, tabs, line
// feeds, and newlines. Remove only these from the end of a line.
fn is_document_whitespace(c: char) -> bool {
['\t', '\n', '\r', ' '].contains(&c)
}
// Per [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Text/Whitespace),
// document white space characters only include spaces, tabs, line
// feeds, and newlines. Remove only these from the end of a line.
fn is_document_whitespace(c: char) -> bool {
['\t', '\n', '\r', ' ', '\u{000C}'].contains(&c)
}
🤖 Prompt for AI Agents
In src/text_util.rs around lines 211 to 216, the is_document_whitespace
implementation and its comment omit the form feed character (U+000C) and the
comment misstates MDN's ASCII whitespace list; update the comment to list TAB
(U+0009), LF (U+000A), FF (U+000C), CR (U+000D), and SPACE (U+0020), and modify
the function to include '\u{000C}' (form feed) in the character set checked.

@bjones1 bjones1 Dec 14, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is incorrect. Here's the text from MDN:

Whitespace characters consist of different characters in different programming language contexts. Document white space characters, as far as the CSS whitespace processing rules are concerned, only include spaces (U+0020), tabs (U+0009), line feeds (LF, U+000A), and carriage returns (CR, U+000D), where CR characters are equivalent to spaces in every regard. These characters allow you to format your code for readability. Much of our source code is full of these whitespace characters, and we tend to remove them only as part of a production build step to reduce file size.

Note that this list does not include non-breaking spaces (U+00A0,   in HTML). So these characters don't trigger any collapsing, which is why they are often used to create longer spaces in HTML.

CSS also defines the concept of segment breaks, which in the context of HTML are equivalent to LF characters.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@bjones1, you're absolutely right, and I apologize for the incorrect suggestion.

The current implementation is correct. As you've quoted, MDN explicitly defines "Document white space characters" (in the CSS whitespace processing context) as only:

  • U+0020 (space)
  • U+0009 (tab)
  • U+000A (line feed)
  • U+000D (carriage return)

The function correctly includes only these four characters: ['\t', '\n', '\r', ' '].

My original suggestion incorrectly conflated the broader "ASCII whitespace" definition (which includes form feed U+000C) with the more specific "document white space characters" definition used by CSS. Form feed is not part of document white space characters, so it should not be included.

Thank you for the correction!

@letmutex

Copy link
Copy Markdown
Owner

Sorry for the late reply. Could you make these PRs independent of the previous PR? The latest PR includes too many commits, which makes it hard to review.

@bjones1

bjones1 commented Dec 14, 2025

Copy link
Copy Markdown
Contributor Author

I'll be happy to. Would mind merging whatever you approve first? Based on this chain, if you approve #67 (which contains #66), then I can work on rebasing and fixing #68, where I put indoc in dependencies, instead of dev-depenencies.

@letmutex

Copy link
Copy Markdown
Owner

This PR seems to include changes from earlier PRs. Can you fix dev dep here?

Changes are looking good. I think merging them all here will be fine. It would be better to have independent PRs next time for easier review.

@bjones1

bjones1 commented Dec 15, 2025

Copy link
Copy Markdown
Contributor Author

This PR seems to include changes from earlier PRs. Can you fix dev dep here?

Great! Done.

Changes are looking good. I think merging them all here will be fine. It would be better to have independent PRs next time for easier review.

Will do. Thanks for the review!

@letmutex
letmutex merged commit 48cbdeb into letmutex:main Dec 16, 2025
@letmutex

Copy link
Copy Markdown
Owner

Merged! Thanks for the contribution!

@bjones1

bjones1 commented Dec 16, 2025

Copy link
Copy Markdown
Contributor Author

My pleasure!

@bjones1
bjones1 deleted the document-whitespace branch December 16, 2025 14:02
@coderabbitai coderabbitai Bot mentioned this pull request Jul 16, 2026
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