├── LICENSE ├── README.md ├── project.clj └── src └── net └── cgrand ├── packed_printer.cljc └── packed_printer ├── core.cljc ├── text.cljc └── text └── edn.cljc /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # packed-printer 2 | 3 | A Clojure and Clojurescript library to pretty print data in a packed manner. 4 | 5 | *This printer likes rectangular shapes (the wider the better) and despises staircases.* 6 | 7 | It's an adaptation of [minimum raggedness](https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap#Minimum_raggedness) (used by TeX for non-justified text) to data. 8 | 9 | ## Packed printer in one sentence 10 | 11 | ## Usage 12 | 13 | Coordinates `[net.cgrand/packed-printer "0.2.1"]`. 14 | 15 | ```clj 16 | (require '[net.cgrand.packed-printer :refer [pprint]]) 17 | ``` 18 | 19 | Relaxed mode: 20 | ```clj 21 | => (pprint (partition 10 (range 50)) :width 15) 22 | ;...5....0....5 23 | ((0 1 2 3 4 24 | 5 6 7 8 9) 25 | (10 11 12 13 14 26 | 15 16 17 18 19) 27 | (20 21 22 23 24 28 | 25 26 27 28 29) 29 | (30 31 32 33 34 30 | 35 36 37 38 39) 31 | (40 41 42 43 44 32 | 45 46 47 48 49)) 33 | ``` 34 | 35 | Strict mode: 36 | ```clj 37 | => (pprint (partition 10 (range 50)) :width 15 :strict true) 38 | ;...5....0....5 39 | ((0 1 2 3 4 40 | 5 6 7 8 9) 41 | (10 11 12 42 | 13 14 15 16 43 | 17 18 19) 44 | (20 21 22 45 | 23 24 25 26 46 | 27 28 29) 47 | (30 31 32 48 | 33 34 35 36 49 | 37 38 39) 50 | (40 41 42 51 | 43 44 45 46 52 | 47 48 49)) 53 | ``` 54 | 55 | On code (not intended for that): 56 | ```clj 57 | => (pprint '(defn render [lines] 58 | (doseq [{:keys [indent] [head & spans] :spans} lines] 59 | (prsp indent) (prsp (leading-spaces head true)) (print (str head)) 60 | (doseq [span spans] (prsp (leading-spaces span false)) (print (str span))) 61 | (newline))) 62 | :coll-indents {"(" 2}) 63 | (defn render [lines] 64 | (doseq [{:keys [indent], [head & spans] :spans} lines] 65 | (prsp indent) (prsp (leading-spaces head true)) (print (str head)) 66 | (doseq [span spans] (prsp (leading-spaces span false)) 67 | (print (str span))) 68 | (newline))) 69 | ``` 70 | 71 | Values are indented when they can't be set on the same line: 72 | 73 | ```clj 74 | => (pprint '{:foo :bar :baz :quux} :width 10) 75 | {:foo :bar, 76 | :baz :quux} 77 | => (pprint '{:foo :bar :baz :quux} :width 6) 78 | {:foo 79 | :bar, 80 | :baz 81 | :quux} 82 | ``` 83 | 84 | ## Comparison 85 | 86 | ### clojure.pprint 87 | ```clj 88 | => (binding [clojure.pprint/*print-right-margin* 30] 89 | (clojure.pprint/pprint {:a :b :c {:e :f :g :h :i :j :k :l} :m :n :o {:p {:q :r :s :t}}})) 90 | 91 | ; 1 1 2 2 3 92 | ;...5....0....5....0....5....0 93 | {:a :b, 94 | :c 95 | {:e :f, 96 | :g :h, 97 | :i :j, 98 | :k :l}, 99 | :m :n, 100 | :o {:p {:q :r, :s :t}}} 101 | ``` 102 | 103 | ### zprint 104 | ```clj 105 | => (czprint {:a :b :c {:e :f :g :h :i :j :k :l} :m :n :o {:p {:q :r :s :t}}} 30 {:map {:nl-separator? true}}) 106 | 107 | ; 1 1 2 2 3 108 | ;...5....0....5....0....5....0 109 | {:a :b, 110 | :c {:e :f, 111 | :g :h, 112 | :i :j, 113 | :k :l}, 114 | :m :n, 115 | :o {:p {:q :r, :s :t}}} 116 | ``` 117 | 118 | ### packed-printer 119 | ```clj 120 | => (pprint {:a :b :c {:e :f :g :h :i :j :k :l} :m :n :o {:p {:q :r :s :t}}} :width 30) 121 | 122 | ; 1 1 2 2 3 123 | ;...5....0....5....0....5....0 124 | {:a :b, :c {:e :f, :g :h, 125 | :i :j, :k :l}, 126 | :m :n, :o {:p {:q :r, :s :t}}} 127 | ``` 128 | 129 | And in strict mode: 130 | 131 | ```clj 132 | => (pprint {:a :b :c {:e :f :g :h :i :j :k :l} :m :n :o {:p {:q :r :s :t}}} :width 30 :strict true) 133 | 134 | ; 1 1 2 2 3 135 | ;...5....0....5....0....5....0 136 | {:a :b, :c {:e :f, :g :h, 137 | :i :j, :k :l}, 138 | :m :n, :o {:p {:q :r, 139 | :s :t}}} 140 | ``` 141 | 142 | And in between: 143 | 144 | ```clj 145 | => (pprint {:a :b :c {:e :f :g :h :i :j :k :l} :m :n :o {:p {:q :r :s :t}}} :width 30 :strict 1) 146 | 147 | ; 1 1 2 2 3 148 | ;...5....0....5....0....5....0 149 | {:a :b, :c {:e :f, :g :h, :i :j, :k :l}, 150 | :m :n, :o {:p {:q :r, :s :t}}} 151 | ``` 152 | 153 | ## Stages 154 | 155 | There are three stages: `spans` (which converts data into spans), `layout` (which finds the optimal layout), and `render` (which turns the layout in side effects). 156 | 157 | The main stage in `layout` and is fixed. `core/spans` and `core/render` are multimethods and thus can be extended. Dispatch occurs based on the values of options `:to` (the target, defaults is `:text` and `:as` the input format (default `:edn`). `core/spans` dispatches on the pair `[to as]` while `core/render` dispatches only on `to`. 158 | 159 | ### `core/spans` 160 | 161 | It must returns a sequences of spans (see protocol `core/Span`). 162 | 163 | ### `core/render` 164 | 165 | It takes a sequence of lines, a line being a map with keys `:indent` (the amount of whitespace by which to indent the line) and `:spans` a sequence of spans. 166 | 167 | When `:to` is `:text`, spans must implement the `text/Text` protocol. 168 | 169 | ## Implementation 170 | 171 | Complexity is `O(n * w^3)` where n is the length (in spans) of the data to layout and w is the desired width. 172 | 173 | The `w^3` may be frightening but it's just an upper bound: dynamic programming is used, giving a cache size of `O(n * w^3)` but in practice this cache is very sparsely populated. Binding `core/*print-stats*` to true causes the actual value for `w^3` to be printed out. 174 | 175 | ### Minimum raggedness 176 | 177 | The usual algorithm found for minimum raggedness is `O(n^2)` and uses dynamic programming. 178 | 179 | However if you are laying out things on a grid whose number of columns is low then `O(n*w)` is possible. The key insight is that the cost of a layout depends only of the position in the list of words/spans to layout and the position in the current line -- hence the `n*w`. 180 | 181 | ### Adaptation for data 182 | 183 | To layout data, two parameters are added: current indentation and next line indentation. Both are bounded by `w`. Well, they are bounded by `w` only when `:strict true`. 184 | 185 | In relaxed mode, how far in the margin can things be printed is bounded in practice by the cost function. Making the cost function more punitive (increasing strictness) will result in less margin prints. 186 | 187 | ## License 188 | 189 | Copyright © 2017 Christophe Grand 190 | 191 | Distributed under the Eclipse Public License either version 1.0 or (at 192 | your option) any later version. 193 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject net.cgrand/packed-printer "0.3.0" 2 | :description "A compact pretty printer" 3 | :author "Christophe Grand" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.9.0-RC1" :scope "provided"]]) 7 | -------------------------------------------------------------------------------- /src/net/cgrand/packed_printer.cljc: -------------------------------------------------------------------------------- 1 | (ns net.cgrand.packed-printer 2 | "Compact pretty printing." 3 | (:require 4 | [net.cgrand.packed-printer.core :as core] 5 | ; below requires have defmethods 6 | [net.cgrand.packed-printer.text :as text] 7 | [net.cgrand.packed-printer.text.edn])) 8 | 9 | (defn pprint 10 | "Packed prints x, core options are: 11 | * :width the desired output width (in chars, defaults to 72), 12 | * :strict, a number or boolean (defaults to true or 2), true when the desired width is a hard limit 13 | (pprint may throw when no suitable layout is found), the strictness factor influences the layout 14 | propension to write past the margin. 15 | * :as a keyword denoting the nature of the input (defaults to :edn), 16 | * :to a keyword denoting the expected output (defaults to :text). 17 | 18 | More options may be available depending on :as and :to. 19 | 20 | For [:text :edn], supported options are: 21 | * kv-indent the amount of spaces by which to indent a value when it appears 22 | at the start of a line (default 2), 23 | * coll-indents a map of collection start delimiters (as strings) to the amount 24 | by which to indent (default: length of the delimiter)." 25 | [x & {:as opts :keys [strict width as to] :or {strict false width 72 as :edn to :text}}] 26 | (if-some [layout (core/layout (core/spans x [to as] opts) width strict)] 27 | (core/render layout to opts) 28 | (throw (ex-info "Can't find a suitable layout. See ex-data." 29 | {:dispatch [to as] :data x :opts opts})))) -------------------------------------------------------------------------------- /src/net/cgrand/packed_printer/core.cljc: -------------------------------------------------------------------------------- 1 | (ns net.cgrand.packed-printer.core 2 | "Layout engine.") 3 | 4 | (defmulti spans (fn [x to+as opts] to+as)) 5 | 6 | (defmulti render (fn [x to opts] to)) 7 | 8 | (defprotocol Span 9 | (length [span start-of-line] 10 | "Returns the length of the span (depending on whether it 11 | appears at the start of a line) or nil if not acceptable.") 12 | (br-after? [span] "Returns whether a line break authorized after this span.") 13 | (indent [span] 14 | "Returns: 15 | * nil for a regular span, 16 | * a natural integer (so zero included) to indicate the start of a group and 17 | the amount by which to indent next lines of this group, 18 | * any negative number to indicate the end of a group.")) 19 | 20 | (defn block-head? [span] 21 | (some-> (indent span) (>= 0))) 22 | 23 | (defn trailer? 24 | "Returns true for span that can't appear at the start of a line." 25 | [span] 26 | (nil? (length span true))) 27 | 28 | (extend-protocol Span 29 | #?(:clj String :cljs string) 30 | (length [s _] (count s)) 31 | (br-after? [s] true) 32 | (indent [s] nil) 33 | #?(:clj clojure.lang.APersistentMap :cljs cljs.core/PersistentHashMap) 34 | (length [s start-of-line] (if start-of-line (:start-length s) (:length s))) 35 | (br-after? [s] (:br-after? s)) 36 | (indent [s] (:indent s)) 37 | #?@(:cljs 38 | [cljs.core/PersistentArrayMap 39 | (length [s start-of-line] (if start-of-line (:start-length s) (:length s))) 40 | (br-after? [s] (:br-after? s)) 41 | (indent [s] (:indent s))])) 42 | 43 | (def ^:private empty-layout {:cost 0 :line () :lines ()}) 44 | 45 | (defn- split-block 46 | "Returns a pair [block+trail bottom] where block-trail is the block and its trail 47 | (spans that must appear right after it) and bottom the remaining spans." 48 | [spans from to] 49 | (loop [from (inc from) n 1] 50 | (let [span (nth spans from nil)] 51 | (if (pos? n) 52 | (recur (inc from) (+ n (if-some [i (indent span)] (if (neg? i) -1 1) 0))) ; invariant: n >= 0 => from < to 53 | (if (< from to) 54 | (cond 55 | (length span true) from ; not a trailing span: it can appear at the start of a line 56 | (block-head? span) (recur (inc from) 1) 57 | :else (recur (inc from) n)) 58 | from))))) 59 | 60 | (defn- line-pos [pos spans] 61 | (reduce (fn [pos span] (+ pos (length span (zero? pos)))) pos spans)) 62 | 63 | (def ^:dynamic *print-stats* false) 64 | 65 | (defn layout 66 | ([spans full-width] (layout spans full-width false)) 67 | ([spans full-width strict] 68 | (let [relax (not (true? strict)) 69 | penalty (if (number? strict) strict 2) 70 | cache (atom {}) 71 | pending (atom []) 72 | spans (vec spans)] 73 | (when-not (pos? penalty) 74 | (throw (ex-info "Strictness can't be zero or negative." {:strict strict}))) 75 | (letfn [(safe-best-layout [& args] ; kind of a trampoline against SO 76 | (loop [todo [args]] 77 | (when-some [args (peek todo)] 78 | (recur (try 79 | (apply best-layout args) 80 | (pop todo) 81 | (catch #?(:clj StackOverflowError :cljs :default) e 82 | (let [todo (into todo @pending)] 83 | (reset! pending []) 84 | todo)))))) 85 | (apply best-layout args)) 86 | (best-layout [& args] 87 | (or (@cache args) 88 | (let [_ (swap! pending conj args) 89 | r (apply raw-best-layout args)] 90 | (swap! cache assoc args r) 91 | (swap! pending pop) 92 | r))) 93 | (raw-best-layout [from to i i' pos may-br] 94 | (when (or relax (<= i full-width)) 95 | (if (< from to) 96 | (let [span (nth spans from) 97 | ; the marginal cost is extra cost of adding the span to the current line and past the margin (sic) 98 | marginal-cost (when-some [end-pos (some-> (length span (= i pos)) (+ pos))] 99 | (when (< full-width end-pos) 100 | (- (line-cost i end-pos nil) (line-cost i pos nil)))) 101 | br-layout (when (and may-br (< i pos)) 102 | (br i' (raw-best-layout from to i' i' i' false))) 103 | inline-layout (when-not (and br-layout marginal-cost (< (:cost br-layout) marginal-cost)) 104 | ; avoid computing inline layout when it's bound to be more expensive 105 | (if (block-head? span) 106 | (layout-block from to i i' pos) 107 | (layout-regular from to i i' pos)))] 108 | ; inline before br in preference order 109 | (min-cost i pos inline-layout br-layout)) 110 | empty-layout))) 111 | (layout-regular [from to i i' pos] 112 | (let [span (nth spans from)] 113 | (when-some [n (length span (= i pos))] 114 | (let [end-pos (+ pos n)] 115 | (when (or relax (<= end-pos full-width)) 116 | (cat span (best-layout (inc from) to i i' end-pos (br-after? span)))))))) 117 | (layout-block [from to i bottom-i pos] 118 | (let [block-head (nth spans from) 119 | i' (+ pos (indent block-head)) 120 | block-to (split-block spans from to)] 121 | (when-some [{:keys [lines line cost] :as block-layout} (layout-regular from block-to i i' pos)] 122 | (if (seq lines) 123 | ; multiline 124 | (when-some [bottom-layout (br bottom-i (best-layout block-to to bottom-i bottom-i bottom-i false))] 125 | {:cost (+ cost (:cost bottom-layout)) 126 | :line line 127 | :lines (concat lines (:lines bottom-layout))}) 128 | ; single line 129 | (let [pos (line-pos pos line) 130 | bottom-layout (best-layout block-to to i bottom-i pos true)] 131 | (assoc bottom-layout :line (concat line (:line bottom-layout)))))))) 132 | (min-cost [i pos a b] 133 | (cond 134 | (nil? a) b 135 | (nil? b) a 136 | (<= (estimate i pos a) (estimate i pos b)) a 137 | :else b)) 138 | (estimate [indent pos {:keys [line cost]}] 139 | (+ cost (line-cost indent pos line))) 140 | (line-cost 141 | ([{:keys [spans indent]}] (line-cost indent indent spans)) 142 | ([indent pos spans] 143 | (if (or (seq spans) (< indent pos)) 144 | (let [left (min indent full-width) 145 | right (- (+ indent (line-pos (- pos indent) spans)) full-width)] 146 | (+ (* left left) (* right right (if (pos? right) penalty 1)))) 147 | 0))) 148 | (cat [span layout] 149 | (some-> layout (assoc :line (cons span (:line layout))))) 150 | (br [indent {:keys [line lines] :as layout}] 151 | (if (-> layout :line seq) 152 | {:cost (estimate indent indent layout) 153 | :line () 154 | :lines (cons {:spans line :indent indent} lines)} 155 | layout))] 156 | (when *print-stats* 157 | (safe-best-layout 0 (count spans) 0 0 0 false) ; populate cache 158 | (println "; in practice" (str full-width "^3") "is" (/ (double (count @cache)) (count spans)) "and not" (Math/pow full-width 3))) 159 | (some->> (safe-best-layout 0 (count spans) 0 0 0 false) (br 0) :lines))))) 160 | -------------------------------------------------------------------------------- /src/net/cgrand/packed_printer/text.cljc: -------------------------------------------------------------------------------- 1 | (ns net.cgrand.packed-printer.text 2 | "Compact pretty printing" 3 | (:require [net.cgrand.packed-printer.core :as core])) 4 | 5 | (defprotocol Text 6 | (text [span start-of-line])) 7 | 8 | (extend-protocol Text 9 | #?(:clj String :cljs string) 10 | (text [s _] s) 11 | #?(:clj clojure.lang.APersistentMap :cljs cljs.core/PersistentHashMap) 12 | (text [m start-of-line] (if start-of-line (:start-text m) (:text m))) 13 | #?@(:cljs [cljs.core/PersistentArrayMap 14 | (text [m start-of-line] (if start-of-line (:start-text m) (:text m)))])) 15 | 16 | (def ^:dynamic *ruler-width* nil) 17 | 18 | (defn print-ruler 19 | ([] 20 | (when (number? *ruler-width*) 21 | (print-ruler *ruler-width*))) 22 | ([n] 23 | (let [n (long n) 24 | digits (pr-str n)] 25 | (when (<= 2 n) 26 | (reduce 27 | (fn [stride digit] 28 | (println (apply str (concat (->> (if (< 1 stride) 29 | (->> "1234567890" cycle 30 | (mapcat (fn [d] (concat (repeat (dec stride) " ") [d])))) 31 | (->> "....5....0" cycle)) 32 | (drop 1) (cons \;) (take (dec n))) 33 | [digit]))) 34 | (/ stride 10)) 35 | (Math/pow 10 (dec (count digits))) digits))))) 36 | 37 | (defn render [lines] 38 | (print-ruler) 39 | (doseq [{:keys [spans indent]} lines] 40 | (print (apply str (repeat indent " "))) 41 | (reduce (fn [n span] 42 | (print (text span (zero? n))) 43 | (+ n (core/length span (zero? n)))) 44 | 0 spans) 45 | (newline))) 46 | 47 | (defmethod core/render :text [lines to opts] 48 | (render lines)) 49 | -------------------------------------------------------------------------------- /src/net/cgrand/packed_printer/text/edn.cljc: -------------------------------------------------------------------------------- 1 | (ns net.cgrand.packed-printer.text.edn 2 | "Compact pretty printing" 3 | (:require [net.cgrand.packed-printer.core :as core])) 4 | 5 | (def space {:length 1 :text " " :start-length 0 :start-text ""}) 6 | 7 | (defn opening [s i] 8 | {:start-length (count s) 9 | :start-text s 10 | :length (count s) 11 | :text s 12 | :indent i}) 13 | 14 | (defn closing [s] 15 | {:length (count s) 16 | :text s 17 | :br-after? true 18 | :indent -1}) 19 | 20 | (def delims 21 | (-> {} 22 | (into (map (fn [s] [s (opening s (count s))])) ["(" "[" "{" "#{"]) 23 | (into (map (fn [s] [s (closing s)])) [")" "]" "}"]))) 24 | 25 | (def comma {:length 1 26 | :text "," 27 | :br-after? true}) 28 | 29 | (def kv-close 30 | {:length 0 31 | :text "" 32 | :br-after? true 33 | :indent -1}) 34 | 35 | (defn spans 36 | "Turns x into a collection of spans for layout. Options supported are: 37 | * kv-indent the amount of spaces by which to indent a value when it appears 38 | at the start of a line (default 2), 39 | * coll-indents a map of collection start delimiters (as strings) to the amount 40 | by which to indent (default: length of the delimiter)." 41 | [x {:keys [kv-indent coll-indents] :or {kv-indent 2 coll-indents {}}}] 42 | (let [delims (into delims (map (fn [[s i]] [s (opening s i)])) coll-indents) 43 | kv-open 44 | {:length 0 45 | :text "" 46 | :start-length 0 47 | :start-text "" 48 | :indent kv-indent}] 49 | (letfn [(coll-spans 50 | ([x] (coll-spans x [space] spans)) 51 | ([x sp spans] 52 | (sequence (comp (map spans) (interpose sp) cat) x))) 53 | (kv-spans [[k v]] 54 | (-> [kv-open] (into (spans k)) (conj space) (into (spans v)) (conj kv-close))) 55 | (spans [x] 56 | (cond 57 | (tagged-literal? x) (concat [kv-open (str "#" (pr-str (:tag x))) space] (spans (:form x)) [kv-close]) 58 | (vector? x) (concat [(delims "[")] (coll-spans x) [(delims "]")]) 59 | (set? x) (concat [(delims "#{")] (coll-spans x) [(delims "}")]) 60 | (seq? x) (concat [(delims "(")] (coll-spans x) [(delims ")")]) 61 | (map? x) (concat [(delims "{")] (coll-spans x [comma space] kv-spans) [(delims "}")]) 62 | :else [(pr-str x)]))] 63 | (spans x)))) 64 | 65 | (defmethod core/spans [:text :edn] [x to-as opts] 66 | (spans x opts)) 67 | 68 | --------------------------------------------------------------------------------