From 2a8dab805ed101cd14172b8c8608474c4e0287e4 Mon Sep 17 00:00:00 2001 From: Dimitri Lozeve Date: Fri, 9 Sep 2022 18:40:45 +0200 Subject: [PATCH] Add markdown styling to tables --- fancy/table.ss | 52 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/fancy/table.ss b/fancy/table.ss index 1beef97..00e2f22 100644 --- a/fancy/table.ss +++ b/fancy/table.ss @@ -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) - (str " " - (parse-markup text) - (make-string (- width (string-length (remove-markup text)) 1) #\ ))) +(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) #\ ))))) (def (table-header tab) - (with ((table names widths) tab) - (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"))) + (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")))) (def (table-row tab . args) - (with ((table names widths) tab) - (str "│" - (string-join (map (lambda (text width) (column-text text (+ 2 width))) args widths) #\│) - "│\n"))) + (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")))) (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"))))