Repository navigation
Document whitespace - #69
Conversation
…, in most cases.
Exception: Per the Commonmark spec, emphasis/strong emphasis use pure whitespace.
WalkthroughRefactors 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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. Comment |
There was a problem hiding this comment.
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 onheaders/rowsraw strings, while rendering runsnormalize_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-1sentinel long-term.
The cast enables the-1behavior 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:StripWhitespacedocument-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
📒 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
TrimAsciiWhitespacetoTrimDocumentWhitespacealigns 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
TrimAsciiWhitespacetoTrimDocumentWhitespacealigns 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::indocimport 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 usesindoc!appropriately for multi-line HTML comparisons.src/element_handler/li.rs (1)
7-7: LGTM! Consistent whitespace handling update.The transition from
TrimAsciiWhitespacetoTrimDocumentWhitespacealigns 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()withany(...)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 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 toTrimDocumentWhitespacefor 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_handlerregistration/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_endupdate 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 viatrim_*_matches(is_document_whitespace)is coherent.Implementation is straightforward and should behave correctly for
&str/StringviaAsRef<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.
| // 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) | ||
| } |
There was a problem hiding this comment.
🧩 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 3Repository: 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.rsRepository: 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.
| // 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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!
|
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. |
|
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. |
Great! Done.
Will do. Thanks for the review! |
|
Merged! Thanks for the contribution! |
|
My pleasure! |
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.rshas the real changes. That's what needs the most review.Summary by CodeRabbit
New Features
Bug Fixes
Chores
Tests
✏️ Tip: You can customize this high-level summary in your review settings.