Hi " - " hi
" + " comment-->hiFrom a84ebe545d13f4540d72cc0d3c719b35e171cc33 Mon Sep 17 00:00:00 2001
From: Joel Dueck Hi 12 "
+ " 12 hello Hi "
- " hi"
" "
"
Paragraph
" "abcdefghijklm" + "nop
\n")) + +(check-fmt 16 "Lines may fill the wrap width exactly (word preceded by a space)" + '(p "abcdef ghijkl m") + '("abcdef ghijkl" + "m
\n")) + +(check-fmt 12 "Whitespace-only strings between inline elements allow wrapping" + '(p (em "aaa") " " (em "bbb") " " (em "ccc")) + '("" + "aaa" + "bbb" + "ccc
\n")) + +(check-matches-tidy? 30 '(p (em "aaa") " " (em "bbb") " " (em "ccc"))) + +(check-fmt 12 "Whitespace-only strings between plain strings allow wrapping" + '(p "aaaa" " " "bbbb" " " "cccc") + '("aaaa bbbb" + "cccc
\n")) + +(check-fmt 25 "Newline strings between inline elements allow wrapping" + '(p (a ((href "x")) "one") "\n" (a ((href "y")) "two") "\n" (a ((href "z")) "three")) + '("\n")) + +(check-matches-tidy? 30 '(p (a ((href "x")) "one") "\n" (a ((href "y")) "two") "\n" (a ((href "z")) "three"))) + +(check-fmt 12 "Inline closing tag stays glued to its content when trailing whitespace is hoisted" + '(p (em "aaa ") (em "bbb ") (em "ccc")) + '("" + "aaa" + "bbb" + "ccc
\n")) + +(check-matches-tidy? 30 '(p (em "aaa ") (em "bbb ") (em "ccc"))) + +(check-fmt 40 "Flow element after text inside a flow parent is indented as a sibling of the text" + '(ul (li "Item" (ul (li "sub")))) + '("para
" + " bye" + "again
" + "" + " word" + " word" + " word
" + "Hi y
\n")) + +(check-fmt 40 "Closing tag of is indented when content ends with space + newline"
+ '(div (pre "line one\nline two \n"))
+ '(""
+ " line one"
+ "line two "
+ "
"
+ "\n"))
+
+(check-fmt 40 "Closing tag of is glued when content does not end with a newline"
+ '(div (pre "line one\nline two"))
+ '(""
+ " line one"
+ "line two
"
+ "\n"))
From b533e0ba05e38613bf1170364f2a6cd59a2a7591 Mon Sep 17 00:00:00 2001
From: Joel Dueck
Date: Sun, 6 Sep 2026 11:01:06 -0500
Subject: [PATCH 2/5] CI: enable tidy comparison checks
---
.github/workflows/push.yml | 2 ++
html-printer-lib/test.rkt | 40 ++++++++++++++++++++++++++++++++------
2 files changed, 36 insertions(+), 6 deletions(-)
diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml
index e5aac6d..dc4783f 100644
--- a/.github/workflows/push.yml
+++ b/.github/workflows/push.yml
@@ -26,6 +26,8 @@ jobs:
version: ${{ matrix.racket-version }}
- name: Install package with dependencies
run: raco pkg install --auto --batch --link html-printer-lib/
+ - name: Install HTML Tidy (the tests compare output against it when a new enough version is found)
+ run: sudo apt-get update && sudo apt-get install -y tidy && tidy --version
- name: Run tests
run: raco test -c html-printer
- name: Build docs
diff --git a/html-printer-lib/test.rkt b/html-printer-lib/test.rkt
index 00d330b..4c66633 100644
--- a/html-printer-lib/test.rkt
+++ b/html-printer-lib/test.rkt
@@ -111,8 +111,9 @@
" "
" "
@@ -204,8 +207,7 @@
"three"
"four\n"))
-; Tricky…currently the results are functionally the same but not byte-identical
-;(check-matches-tidy? 20 '(p (span "one two three ") (i "four")))
+(check-matches-tidy? 20 '(p (span "one two three ") (i "four")))
(check-fmt 20 "script and style tags are printed without alteration"
(xpr '(div
@@ -262,12 +264,16 @@
" three"
"\n"))
+(check-matches-tidy? 20 '(div (pre "\none\n two \n three")))
+
(check-fmt 20 "Pre tags handle contained xexprs"
'(div (pre "Hello " (i "World")))
'("Hello World" "
abcdefghijklm" "nop
\n")) +(check-matches-tidy? 16 '(p "abcdefghijklm nop")) + (check-fmt 16 "Lines may fill the wrap width exactly (word preceded by a space)" '(p "abcdef ghijkl m") '("abcdef ghijkl" "m
\n")) +(check-matches-tidy? 16 '(p "abcdef ghijkl m")) + (check-fmt 12 "Whitespace-only strings between inline elements allow wrapping" '(p (em "aaa") " " (em "bbb") " " (em "ccc")) '("" @@ -674,6 +692,8 @@ '("
aaaa bbbb" "cccc
\n")) +(check-matches-tidy? 12 '(p "aaaa" " " "bbbb" " " "cccc")) + (check-fmt 25 "Newline strings between inline elements allow wrapping" '(p (a ((href "x")) "one") "\n" (a ((href "y")) "two") "\n" (a ((href "z")) "three")) '("one" @@ -743,21 +763,29 @@ " " "
\n")) -;These checks will never succeed because HTML Tidy is not grapheme-aware (as of 5.8.0) -; (check-matches-tidy? 20 '(p "🧞♀️🧝♂️🧝♀️🧙🏽♂️🧚🏻🧟♂️🧜🏽♀️🧞♀️🧝♂️🧝♀️🧙🏽♂️🧚🏻🧟♂️🧜🏽♀️")) +(check-matches-tidy? 20 '(p "🧞♀️🧝♂️🧝♀️🧙🏽♂️🧚🏻🧟♂️🧜🏽♀️🧞♀️🧝♂️🧝♀️🧙🏽♂️🧚🏻🧟♂️🧜🏽♀️")) ; a single word: overflows either way + +;This check will never succeed because HTML Tidy is not grapheme-aware (as of 5.8.0) ; (check-matches-tidy? 20 '(p "Приве́т नमस्ते שָׁלוֹם")) ;; http://utf8everywhere.org — section 8.3 @@ -162,6 +163,8 @@ " " "\n")) +(check-matches-tidy? 20 '(p (em "Hello") "World again")) + (check-fmt 20 "linebreaks not inserted where they would introduce whitespace (tag close with only 1 element)" (xpr '(p [[class "x x x x x x x x x x x x x x x x x x x x"]] "hi")) '("
\n")) + +(check-matches-tidy? 20 '(body () (header () (h1 () "Title") (p () "a" (br ()) "b")))) (check-fmt 20 "
wraps/indents correctly"
'(html (head (link [[rel "stylesheet"] [href "style.css"]])
@@ -490,10 +498,14 @@
'(label (input [[type "checkbox"] [disabled ""]]) "Cheese")
'(""))
+(check-matches-tidy? 80 '(label (input [[type "checkbox"] [disabled ""]]) "Cheese"))
+
(check-fmt 80 "Whitespace preserved after inline element"
'(label (input [[type "checkbox"] [disabled ""]]) " Cheese")
'(""))
+(check-matches-tidy? 80 '(label (input [[type "checkbox"] [disabled ""]]) " Cheese"))
+
(check-fmt 20 "Comments wrap and indent properly inside flows and blocks"
`(body (main ,(comment "this is\na comment")
(article (p "Hi" ,(comment "also another comment")))))
@@ -614,6 +626,8 @@
" "
"\n"))
+(check-matches-tidy? 40 '(body (article (p "One") (aside [[class "me"]] "Two") (aside [[class "me"]] (p "three")))))
+
(check-fmt 40 "Indents for
after flow and block close"
'(body (table (tr (td "Hi"))) (br) (br) (p "Paragraph") (br))
'("
\n")) +(check-matches-tidy? 12 '(body (div (div (div (div (div (p "word word word")))))))) + (check-fmt 20 "Whitespace containing newlines after a comment is collapsed, not printed verbatim" `(p "Hi" ,(comment "x") " \n y") '("
Hi y
\n")) -(check-fmt 40 "Closing tag of
is indented when content ends with space + newline"
+(check-matches-tidy? 20 `(p "Hi" ,(comment "x") " \n y"))
+
+(check-fmt 40 "Closing tag of is at column 1 when content ends with a newline"
'(div (pre "line one\nline two \n"))
'(""
" line one"
"line two "
- " "
+ ""
"\n"))
+(check-matches-tidy? 40 '(div (pre "line one\nline two \n")))
+
(check-fmt 40 "Closing tag of is glued when content does not end with a newline"
'(div (pre "line one\nline two"))
'(""
" line one"
"line two"
"\n"))
+
+(check-matches-tidy? 40 '(div (pre "line one\nline two")))
From d699481c3b66965c25c66ca7eb5973074ec75c0e Mon Sep 17 00:00:00 2001
From: Joel Dueck
Date: Sun, 6 Sep 2026 11:05:47 -0500
Subject: [PATCH 3/5] Restructure printer around a token stream
---
html-printer-lib/main.rkt | 423 +++++++++++++--------------
html-printer-lib/private/printer.rkt | 301 +++++++------------
html-printer-lib/private/strings.rkt | 27 +-
3 files changed, 313 insertions(+), 438 deletions(-)
diff --git a/html-printer-lib/main.rkt b/html-printer-lib/main.rkt
index eb3258e..de2307f 100644
--- a/html-printer-lib/main.rkt
+++ b/html-printer-lib/main.rkt
@@ -19,236 +19,223 @@
(null? (cddr v))
(string? (cadr v))))
-(define (safe-rest lst)
- (or (and (not (null? lst))
- (cdr lst))
- '()))
-
-;; Given a list of attributes, return a flat list of strings for each attribute name
-;; and value. Each string ("chunk") in the list is considered a discrete “word” for
-;; line-wrapping purposes
-(define (attr-chunks attrs)
- (for/fold ([chunks '()]
- [remaining (safe-rest attrs)]
- #:result (reverse chunks))
- ([attr (in-list attrs)])
+;; An opening tag with its attributes, as a list of printer tokens. The tag name and the first
+;; attribute name are glued together (as in ``.
+(define (opener-tokens tag attrs)
+ (define (attr-tokens attr first? last?)
(match-define (list key val) attr)
- (define-values (key-str val-str)
- (cond
- [(boolean-attr? key)
- (values (format (if (null? remaining) "~a>" "~a ") key)
- "")]
- [else
- (values (format "~a=" key)
- (format (if (null? remaining) "\"~a\">" "\"~a\" ")
- (escape (string-normalize-spaces val) attribute-table)))]))
- (values (cons val-str (cons key-str chunks))
- (safe-rest remaining))))
+ (define lead (if first? (format "<~a " tag) ""))
+ (define end (if last? ">" ""))
+ (define sep (if first? '() (list 'space)))
+ (cond
+ [(boolean-attr? key)
+ (append sep (list (text (format "~a~a~a" lead key end))))]
+ [else
+ (append sep (list (text (format "~a~a=" lead key))
+ 'softbreak
+ (text (format "\"~a\"~a"
+ (escape (string-normalize-spaces val) attribute-table)
+ end))))]))
+ (cond
+ [(null? attrs) (list (text (format "<~a>" tag)))]
+ [else
+ (define last-i (- (length attrs) 1))
+ (apply append
+ (for/list ([attr (in-list attrs)] [i (in-naturals)])
+ (attr-tokens attr (= i 0) (= i last-i))))]))
(module+ test
(require rackunit)
- (check-equal? (attr-chunks '([href "a"] [title "x"]))
- '("href=" "\"a\" " "title=" "\"x\">")
- "attribute keys/vals correctly formatted as strings")
- (check-equal? (attr-chunks '([href "a"] [selected "x"]))
- '("href=" "\"a\" " "selected>" "")
+ (check-equal? (opener-tokens 'p '())
+ (list (text ""))
+ "no attributes")
+ (check-equal? (opener-tokens 'a '([href "a"] [title "x"]))
+ (list (text ""))
+ "attribute keys/vals correctly formatted as tokens")
+ (check-equal? (opener-tokens 'a '([href "a"] [selected "x"]))
+ (list (text ""))
"boolean attributes handled correctly (when last attribute)")
- (check-equal? (attr-chunks '([selected "x"] [href "a"]))
- '("selected " "" "href=" "\"a\">")
+ (check-equal? (opener-tokens 'a '([selected "x"] [href "a"]))
+ (list (text ""))
"boolean attributes handled correctly (when not last attribute)")
- (check-equal? (attr-chunks '([SELECTED "x"] [href "a"]))
- '("SELECTED " "" "href=" "\"a\">")
- "boolean attributes handled correctly regardless of case"))
-
-(define (opener tag attrs)
- (format (if (not (null? attrs)) "<~a " "<~a>") tag))
+ (check-equal? (opener-tokens 'a '([SELECTED "x"] [href "a"]))
+ (list (text ""))
+ "boolean attributes handled correctly regardless of case")
+ (check-equal? (opener-tokens 'p '([title "a \n b"]))
+ (list (text ""))
+ "whitespace in attribute values is normalized"))
(define (closer tag)
(if (self-closing? tag) "" (format "~a>" tag)))
-;; 'normal = inserting a line break before next element is allowed
-;; 'sticky = inserting a line break before next element is not allowed
-;; 'flow-opened = a line break+bump was already added directly after previous value
-;; 'flow-closed = a line break+unbump was already added directly after previous value
-;; 'block-closed = a line break was already added directly after the previous value
-
-(define (normal? v) (eq? v 'normal))
-(define (sticky? v) (eq? v 'sticky))
-(define (flow-opened? v) (eq? v 'flow-opened))
-(define (flow-closed? v) (eq? v 'flow-closed))
-(define (flow-any? v) (memq v '(first flow-opened flow-closed block-closed)))
-(define (block-closed? v) (eq? v 'block-closed))
-
-(define break-after-block? (make-parameter #f))
-(define (add-break? tag prev-tok)
- (and (break-after-block?)
- (not (memq tag '(meta link title)))
- (case prev-tok
- [(flow-closed block-closed) #t]
- [else #f])))
-
-(define (display-val yeet! v [prev-token 'first] #:in-inline? [inside-inline? #f])
- (match v
- [(? null?) prev-token]
- [(list* (and (? symbol?) (? br?)) _)
- (log-expr break-tag found v )
- (when (or (flow-closed? prev-token) (block-closed? prev-token)) (yeet! 'indent))
- (yeet! '(put/wrap "
") 'flush 'break/indent)
- 'flow-opened] ; hacky
-
- ; flow tag
- [(list (? flow? tag) (list (? attr? attrs) ...) elems ...)
- (log-expr flow starting… tag prev-token)
- (when (add-break? tag prev-token) (yeet! 'break))
- (define weird-flow? (or inside-inline? (not (flow-any? prev-token))))
- (when weird-flow?
- (log-expr "Flow tag ~a inside block/inline tag (considered weird)" tag)
- (when (not (memq prev-token '(block-closed flow-closed)))
- (yeet! 'flush 'break/++indent)))
-
- (unless (or (flow-opened? prev-token) weird-flow?)
- (yeet! 'indent))
-
- (yeet! `(put ,(opener tag attrs)))
- (for ([a (in-list (attr-chunks attrs))])
- (yeet! `(put/wrap ,a)))
- (yeet! 'flush 'break/++indent)
- (define last-tok
- (for/fold ([last-token 'flow-opened])
- ([elem (in-list elems)])
- (display-val yeet! elem last-token)))
- (cond
- [(or (block-closed? last-tok) (flow-closed? last-tok)) (yeet! '--indent)]
- [(flow-opened? last-tok) (yeet! 'break/--indent)]
- [else (yeet! 'flush 'break/--indent)])
- (log-expr flow …closing tag last-tok)
- (yeet! `(put/wrap ,(closer tag)))
- (if weird-flow?
- (yeet! 'flush 'break/--indent)
- (yeet! 'break))
- 'flow-closed]
-
- ; block tag
- [(list (? block? tag) (list (? attr? attrs) ...) elems ...)
- (when (add-break? tag prev-token) (yeet! 'break))
- (log-expr block starting… tag prev-token)
- (when inside-inline?
- (log-expr "Block tag ~a inside inline tag ~a (considered weird)" tag inside-inline?))
- (cond
- [(memq prev-token '(normal sticky)) (yeet! 'flush 'break/indent)]
- [else (unless (flow-opened? prev-token) (yeet! 'indent))])
- (yeet! `(put ,(opener tag attrs)))
- (for ([a (in-list (attr-chunks attrs))])
- (yeet! `(put/wrap ,a)))
- (define last-tok
- (for/fold ([last-token 'normal])
- ([elem (in-list elems)])
- (display-val yeet! elem last-token)))
- (log-expr block …closing tag last-tok)
- (yeet! 'check/flush `(put ,(closer tag)) 'break)
- 'block-closed]
-
- ; script, style, pre
- [(list (? preserve-contents? tag) (list (? attr? attrs) ...) elems ...)
- (log-expr preserve start… tag prev-token)
- (when (add-break? tag prev-token) (yeet! 'break))
- (unless (flow-opened? prev-token) (yeet! 'indent))
- (yeet! `(put ,(opener tag attrs)))
- (for ([a (in-list (attr-chunks attrs))])
- (yeet! `(put/wrap ,a)))
- (case tag
- [(script style)
- (for ([elem (in-list elems)]) (yeet! `(put ,elem)))]
- [(pre)
- (for ([elem (in-list elems)])
- (yeet! `(put ,(if (string? elem) (escape elem string-element-table) elem))))])
- (log-expr preserve …closing tag)
- (yeet! 'indent-if-col1
- `(put ,(closer tag))
- 'break)
- 'block-closed]
-
- ; inline tag
- [(list (? symbol? tag) (list (? attr? attrs) ...) elems ...)
- (log-expr inline start… tag prev-token)
- (when (add-break? tag prev-token) (yeet! 'break))
- (when (or (flow-closed? prev-token)
- (block-closed? prev-token))
- (yeet! 'indent))
- (yeet! `(,(if (sticky? prev-token) 'put 'put/wrap) ,(opener tag attrs)))
- (for ([a (in-list (attr-chunks attrs))])
- (yeet! `(put/wrap ,a)))
- (define last-token
- (for/fold ([last 'sticky]) ; was prev-token
- ([elem (in-list elems)])
- (display-val yeet! elem last #:in-inline? tag)))
- (define popped (yeet! 'pop-whitespace))
- (log-expr inline after popped tag)
- (log-expr inline …closing tag last-token)
- (yeet! `(,(if (sticky? last-token) 'put 'put/wrap) ,(closer tag)))
- (when popped (yeet! `(put/wrap ,popped)))
- (if (member last-token '(normal sticky))
- last-token
- 'normal)]
-
- ; no attributes = send it through again
- [(list* (? symbol? tag) elems)
- (display-val yeet! `(,tag () ,@elems) prev-token #:in-inline? inside-inline?)]
-
- ;; Strings are broken up and printed one word at a time. Much depends on the behavior of
- ;; in-words, which yields separate words for consecutive whitespace and for each individually
- ;; valid combination of CRLF characters (so "\r\r\n" becomes '("\r" "\r\n"), e.g.)
- ;; This match is never reached while inside and are indented, but
+ ;; goes at column 1: any indent there would be part of the preformatted content
+ (emit! (raw (closer tag) (not pre?)) 'newline)
+ #t]
+
+ ; inline tag
+ [(list (? symbol? tag) (list (? attr? attrs) ...) elems ...)
+ (log-expr inline starting… tag parent prev-block?)
+ (maybe-blank! tag prev-block?)
+ (apply emit! (opener-tokens tag attrs))
+ (walk-children elems 'inline)
+ ;; Trailing whitespace inside an inline tag is moved after the closing tag, so that
+ ;; word becomes word (and the closing tag stays glued to the word)
+ (define popped? (pop-space!))
+ (log-expr inline …closing tag popped?)
+ (emit! (text (closer tag)))
+ (when popped? (emit! 'space))
+ #f]
+
+ ; no attributes = send it through again
+ [(list* (? symbol? tag) elems)
+ (walk `(,tag () ,@elems) parent prev-block?)]
+
+ ;; Strings are split into words and whitespace; a line may break at any whitespace
+ [(? string? str)
+ (log-expr string found parent prev-block? str)
+ (for ([word (in-list (words str))])
+ (emit! (if (whitespace? word) 'space (text (escape word string-element-table)))))
+ (if (whitespace? str) prev-block? #f)]
+
+ ;; Comments are wrapped like text. A comment that starts a line (first thing after a flow tag
+ ;; opens, or after a block-level sibling) gets its own line(s); anywhere else it is inline.
+ [(? comment? c)
+ (log-expr comment found parent prev-block?)
+ (define own-line? (and (pair? acc) (eq? (car acc) 'newline)))
+ ;; A line break directly after a comment adds no significant whitespace if there was
+ ;; already whitespace directly before it (the two collapse together)
+ (define breakable-after? (and (not own-line?) (after-space?)))
+ (when own-line? (emit! 'newline))
+ (emit! (text ""))
+ (when own-line? (emit! 'newline))
+ (when breakable-after? (emit! 'softbreak))
+ prev-block?]
+
+ [(or (? symbol? v) (? exact-positive-integer? v))
+ (log-expr entity found v)
+ (emit! (text (->string v)))
+ #f]
+
+ ;; Anything else (CDATA, processing instructions…) is printed as-is, as one unbreakable
+ ;; chunk. As with comments, a break directly after it is harmless if whitespace preceded it.
+ [(? xexpr? v)
+ (log-expr other found v)
+ (define breakable-after? (after-space?))
+ (emit! (text (->string v)))
+ (when breakable-after? (emit! 'softbreak))
+ prev-block?]
+
+ [_
+ (raise-arguments-error 'xexpr->html5
+ "not a valid element (= txexpr, string, symbol, character integer, CDATA, or comment"
+ "value" v)]))
+
+ (walk v 'top #f)
+ (reverse acc))
(define (xexpr->html5 v #:wrap [wrap 100] #:add-breaks? [add-breaks? #f])
(with-output-to-string
(λ ()
- (when (and (list? v) (symbol? (car v)) (eq? 'html (symbol-downcase (car v))))
+ (when (and (pair? v) (symbol? (car v)) (eq? 'html (symbol-downcase (car v))))
(displayln ""))
- (define proc (make-wrapping-printer #:wrap-at wrap))
- (parameterize ([break-after-block? add-breaks?])
- (display-val proc v))
- (proc 'flush))))
\ No newline at end of file
+ (define print! (make-wrapping-printer #:wrap-at wrap))
+ (print! (xexpr->tokens v add-breaks?) 'flush))))
diff --git a/html-printer-lib/private/printer.rkt b/html-printer-lib/private/printer.rkt
index a13ff76..a310888 100644
--- a/html-printer-lib/private/printer.rkt
+++ b/html-printer-lib/private/printer.rkt
@@ -3,219 +3,118 @@
(require "strings.rkt"
"log.rkt"
racket/match
- (only-in racket/syntax format-symbol)
- (rename-in racket/mutable-treelist
- (mutable-treelist-first ~first)
- (mutable-treelist-last ~last)
- (mutable-treelist-add! ~add!)
- (mutable-treelist-take! ~take!)
- (mutable-treelist-drop! ~drop!)
- (mutable-treelist-drop-right! ~drop-right!)
- (mutable-treelist-empty? ~empty?)))
+ (only-in racket/syntax format-symbol))
-(provide make-wrapping-printer)
+(provide make-wrapping-printer
+ (struct-out text)
+ (struct-out raw))
(module+ test)
+;; The printer consumes a flat stream of tokens and lays them out greedily, one line at a time:
+;;
+;; (text str) An unbreakable run of characters. Adjacent text tokens are glued into one
+;; "cluster" which is always printed on a single line.
+;; 'space A break opportunity that prints as a single space if the line continues.
+;; Consecutive spaces collapse; a space at the start or end of a line is dropped.
+;; 'softbreak A zero-width break opportunity: prints nothing unless the line breaks there.
+;; 'newline A hard line break. Does nothing if nothing has been printed on the current line.
+;; 'blank A hard line break that always produces an empty line.
+;; 'indent+ Raise/lower the indent level. Takes effect the next time a line is started.
+;; 'indent-
+;; (raw str indent?)
+;; Verbatim output (contents and closing tags of ,