diff --git a/src/matrix/render.clj b/src/matrix/render.clj index c701923..cafa381 100644 --- a/src/matrix/render.clj +++ b/src/matrix/render.clj @@ -30,10 +30,10 @@ (defn draw-row "Takes a seq of strs and a max length and draws a row. Optionally takes a left and right to surround with" - ([seq max-len add-bar] - (let [fmt-str (str "%" max-len "s")] + ([seq max-col-lens add-bar] + (let [mk-fmt-str #(str "%" (nth max-col-lens %) "s")] (->> seq - (map (partial format fmt-str)) + (map-indexed #(format (mk-fmt-str %1) %2)) ((if add-bar (partial add-before-last "│") identity)) @@ -49,20 +49,34 @@ (map count) (apply max 0))) +(defn str-len + "Returns the length of a value as a string" + [s] + (count (str s))) + (defn max-str-len-matrix "Returns the maximum length of the stringified elements of the matrix" [m] (apply max (map max-str-len m))) +(defn matrix-col-lens + "Returns the maximum length of each column of a matrix" + [m] + (for [col (range 0 (matrix-width m))] + (->> m + (map #(get % col)) + (map str-len) + (apply max)))) + ; could do latex, but what's the point (defn pretty-matrix-rows "Make a list of fancy display strings of the rows given matrix" ([m] (pretty-matrix-rows m false)) ([m add-bar] - (let [max-len (max-str-len-matrix m) + (let [max-col-lens (matrix-col-lens m) width (matrix-width m) - row-len (+ (- width 1) (* max-len width)) - middle (map #(draw-row % max-len add-bar "┃ " " ┃") m) + row-len (+ (- width 1) (reduce + max-col-lens)) + middle (map #(draw-row % max-col-lens add-bar "┃ " " ┃") m) space (apply str (repeat (+ (if add-bar 2 0) row-len) " "))] (concat [(str "┏ " space " ┓")] middle @@ -198,4 +212,4 @@ :add (pretty-add inner)))) ([op _] (with-inc-row-indices op))) -;TODO: better row formatting (each column is only as wide as the longest in the column) +;DONE: better row formatting (each column is only as wide as the longest in the column)