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
:dlozeve/fancy/format)
(defstruct table (names widths))
(defstruct table (names widths style)
constructor: :init!)
(def (column-text text width)
(defmethod {:init! table}
(lambda (self names widths (style #f))
(set! (table-names self) names)
(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) #\ )))
(make-string (- width (string-length (remove-markup text)) 1) #\ )))))
(def (table-header tab)
(with ((table names widths) tab)
(match tab
((table names widths 'markdown)
(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"))
((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")))
"├" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┼) "┤\n"))))
(def (table-row tab . args)
(with ((table names widths) tab)
(match tab
((table names widths 'markdown)
(str "|"
(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")))
"│\n"))))
(def (table-footer tab)
(with ((table names widths) tab)
(str "└" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┴) "┘\n")))
(match tab
((table names widths 'markdown) "\n")
((table names widths _)
(str "└" (string-join (map (lambda (w) (make-string (+ 2 w) #\─)) widths) #\┴) "┘\n"))))