Add markdown styling to tables

This commit is contained in:
Dimitri Lozeve 2022-09-09 18:40:45 +02:00
parent faad4f9d9d
commit 2a8dab805e

View file

@ -6,25 +6,47 @@
(import :std/misc/string (import :std/misc/string
:dlozeve/fancy/format) :dlozeve/fancy/format)
(defstruct table (names widths)) (defstruct table (names widths style)
constructor: :init!)
(def (column-text text width) (defmethod {:init! table}
(str " " (lambda (self names widths (style #f))
(parse-markup text) (set! (table-names self) names)
(make-string (- width (string-length (remove-markup text)) 1) #\ ))) (set! (table-widths self) widths)
(set! (table-style self) style)))
(def (column-text text width (style #f))
(match style
('markdown
(str " " (remove-markup text) (make-string (- width (string-length (remove-markup text)) 1) #\ )))
(else
(str " "
(parse-markup text)
(make-string (- width (string-length (remove-markup text)) 1) #\ )))))
(def (table-header tab) (def (table-header tab)
(with ((table names widths) tab) (match tab
(str "┌" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┬) "┐\n" ((table names widths 'markdown)
"│" (string-join (map (lambda (name width) (column-text name (+ 2 width))) names widths) #\│) "│\n" (str "|" (string-join (map (lambda (name width) (column-text name (+ 2 width) 'markdown)) names widths) #\|) "|\n"
"├" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┼) "┤\n"))) "|" (string-join (map (lambda (w) (make-string (+ 2 w) #\-)) widths) #\|) "|\n"))
((table names widths _)
(str "┌" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┬) "┐\n"
"│" (string-join (map (lambda (name width) (column-text name (+ 2 width))) names widths) #\│) "│\n"
"├" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┼) "┤\n"))))
(def (table-row tab . args) (def (table-row tab . args)
(with ((table names widths) tab) (match tab
(str "│" ((table names widths 'markdown)
(string-join (map (lambda (text width) (column-text text (+ 2 width))) args widths) #\│) (str "|"
"│\n"))) (string-join (map (lambda (text width) (column-text text (+ 2 width) 'markdown)) args widths) #\|)
"|\n"))
((table names widths _)
(str "│"
(string-join (map (lambda (text width) (column-text text (+ 2 width))) args widths) #\│)
"│\n"))))
(def (table-footer tab) (def (table-footer tab)
(with ((table names widths) tab) (match tab
(str "└" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┴) "┘\n"))) ((table names widths 'markdown) "\n")
((table names widths _)
(str "└" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┴) "┘\n"))))