From 67c9a34e7a1e4c8aa314320edd29ff330d242885 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Fri, 1 May 2020 11:02:55 +0200 Subject: [PATCH] [#405] add clojure.pprint/*print-right-margin* --- src/babashka/impl/clojure/pprint.clj | 25 ++++++++++++++++--------- test/babashka/main_test.clj | 11 ++++++++++- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/babashka/impl/clojure/pprint.clj b/src/babashka/impl/clojure/pprint.clj index 5fc98945..69b687bc 100644 --- a/src/babashka/impl/clojure/pprint.clj +++ b/src/babashka/impl/clojure/pprint.clj @@ -1,20 +1,27 @@ (ns babashka.impl.clojure.pprint {:no-doc true} (:require [fipp.edn :as fipp] - [sci.core :as sci])) + [sci.core :as sci] + [sci.impl.namespaces :refer [copy-var]] + [sci.impl.vars :as vars])) + +(def pprint-ns (vars/->SciNamespace 'clojure.pprint nil)) + +(def print-right-margin (sci/new-dynamic-var 'print-right-margin 70 {:ns pprint-ns})) (defn pprint + "Substitution for clojure.pprint backed by fipp.edn/pprint." ([edn] - (binding [*out* @sci/out] - (fipp/pprint edn))) + (pprint edn @sci/out)) ([edn writer] - (fipp/pprint edn {:writer writer}))) + (fipp/pprint edn {:writer writer + :width @print-right-margin}))) (defn print-table "Prints a collection of maps in a textual table. Prints table headings ks, and then a line of output for each row, corresponding to the keys in ks. If ks are not specified, use the keys of the first item in rows." - {:added "1.3"} + ([rows] (print-table (keys (first rows)) rows)) ([ks rows] (binding [*out* @sci/out] (when (seq rows) @@ -34,9 +41,9 @@ (println (fmt-row "| " " | " " |" (zipmap ks ks))) (println (fmt-row "|-" "-+-" "-|" (zipmap ks spacers))) (doseq [row rows] - (println (fmt-row "| " " | " " |" row))))))) - ([rows] (print-table (keys (first rows)) rows))) + (println (fmt-row "| " " | " " |" row)))))))) (def pprint-namespace - {'pprint pprint - 'print-table print-table}) + {'pprint (copy-var pprint pprint-ns) + 'print-table (copy-var print-table pprint-ns) + '*print-right-margin* print-right-margin}) diff --git a/test/babashka/main_test.clj b/test/babashka/main_test.clj index 1947a1fa..805a934a 100644 --- a/test/babashka/main_test.clj +++ b/test/babashka/main_test.clj @@ -411,7 +411,16 @@ (deftest pprint-test (testing "writer" - (is (string? (bb nil "(let [sw (java.io.StringWriter.)] (clojure.pprint/pprint (range 10) sw) (str sw))"))))) + (is (string? (bb nil "(let [sw (java.io.StringWriter.)] (clojure.pprint/pprint (range 10) sw) (str sw))")))) + (testing "*print-right-margin*" + (is (= "(0\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9)\n" (bb nil " +(let [sw (java.io.StringWriter.)] + (binding [clojure.pprint/*print-right-margin* 5] + (clojure.pprint/pprint (range 10) sw)) (str sw))"))) + (is (= "(0 1 2 3 4 5 6 7 8 9)\n" (bb nil " +(let [sw (java.io.StringWriter.)] + (binding [clojure.pprint/*print-right-margin* 50] + (clojure.pprint/pprint (range 10) sw)) (str sw))"))))) (deftest read-string-test (testing "namespaced keyword via alias"