├── .gitignore ├── LICENSE ├── README.md ├── dune-project ├── format-doc.opam ├── lib ├── compat.ml ├── compat.mli ├── doc.ml ├── doc.mli ├── dune ├── immutable.ml ├── immutable.mli ├── ref.ml └── ref.mli └── tests ├── boxes.expected ├── boxes.ml ├── dune ├── readme.expected └── readme.ml /.gitignore: -------------------------------------------------------------------------------- 1 | _build 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | In the following, "the OCaml Core System" refers to all files marked 2 | "Copyright INRIA" in this distribution. 3 | 4 | The OCaml Core System is distributed under the terms of the 5 | GNU Lesser General Public License (LGPL) version 2.1 (included below). 6 | 7 | As a special exception to the GNU Lesser General Public License, you 8 | may link, statically or dynamically, a "work that uses the OCaml Core 9 | System" with a publicly distributed version of the OCaml Core System 10 | to produce an executable file containing portions of the OCaml Core 11 | System, and distribute that executable file under terms of your 12 | choice, without any of the additional requirements listed in clause 6 13 | of the GNU Lesser General Public License. By "a publicly distributed 14 | version of the OCaml Core System", we mean either the unmodified OCaml 15 | Core System as distributed by INRIA, or a modified version of the 16 | OCaml Core System that is distributed under the conditions defined in 17 | clause 2 of the GNU Lesser General Public License. This exception 18 | does not however invalidate any other reasons why the executable file 19 | might be covered by the GNU Lesser General Public License. 20 | 21 | ---------------------------------------------------------------------- 22 | 23 | GNU LESSER GENERAL PUBLIC LICENSE 24 | 25 | Version 2.1, February 1999 26 | 27 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 28 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 29 | Everyone is permitted to copy and distribute verbatim copies 30 | of this license document, but changing it is not allowed. 31 | 32 | [This is the first released version of the Lesser GPL. It also counts 33 | as the successor of the GNU Library Public License, version 2, hence 34 | the version number 2.1.] 35 | 36 | Preamble 37 | 38 | The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. 39 | 40 | This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. 41 | 42 | When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. 43 | 44 | To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. 45 | 46 | For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. 49 | 50 | To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. 51 | 52 | Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. 53 | 54 | Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. 55 | 56 | When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. 57 | 58 | We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. 59 | 60 | For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. 61 | 62 | In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. 63 | 64 | Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. 65 | 66 | The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. 67 | 68 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 69 | 70 | 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". 71 | 72 | A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. 73 | 74 | The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) 75 | 76 | "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. 77 | 78 | Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 79 | 80 | 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. 81 | 82 | You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 83 | 84 | 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 85 | 86 | a) The modified work must itself be a software library. 87 | b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. 88 | c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. 89 | d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. 90 | 91 | (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) 92 | 93 | These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 94 | 95 | Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. 96 | 97 | In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 98 | 99 | 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. 100 | 101 | Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. 102 | 103 | This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 104 | 105 | 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. 106 | 107 | If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 108 | 109 | 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. 110 | 111 | However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. 112 | 113 | When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. 114 | 115 | If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) 116 | 117 | Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 118 | 119 | 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. 120 | 121 | You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: 122 | 123 | a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) 124 | b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. 125 | c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. 126 | d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. 127 | e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. 128 | 129 | For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 130 | 131 | It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 132 | 133 | 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: 134 | 135 | a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. 136 | b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 137 | 138 | 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 139 | 140 | 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 141 | 142 | 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 143 | 144 | 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. 145 | 146 | If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. 147 | 148 | It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 149 | 150 | This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 151 | 152 | 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 153 | 154 | 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 155 | 156 | Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 157 | 158 | 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 159 | 160 | NO WARRANTY 161 | 162 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 163 | 164 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 165 | END OF TERMS AND CONDITIONS 166 | 167 | How to Apply These Terms to Your New Libraries 168 | 169 | If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). 170 | 171 | To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. 172 | 173 | one line to give the library's name and an idea of what it does. 174 | Copyright (C) year name of author 175 | 176 | This library is free software; you can redistribute it and/or 177 | modify it under the terms of the GNU Lesser General Public 178 | License as published by the Free Software Foundation; either 179 | version 2.1 of the License, or (at your option) any later version. 180 | 181 | This library is distributed in the hope that it will be useful, 182 | but WITHOUT ANY WARRANTY; without even the implied warranty of 183 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 184 | Lesser General Public License for more details. 185 | 186 | You should have received a copy of the GNU Lesser General Public 187 | License along with this library; if not, write to the Free Software 188 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 189 | 190 | Also add information on how to contact you by electronic and paper mail. 191 | 192 | You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: 193 | 194 | Yoyodyne, Inc., hereby disclaims all copyright interest in 195 | the library `Frob' (a library for tweaking knobs) written 196 | by James Random Hacker. 197 | 198 | signature of Ty Coon, 1 April 1990 199 | Ty Coon, President of Vice 200 | 201 | That's all there is to it! 202 | 203 | -------------------------------------------------- 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Format-doc provides alternative interpreters for OCaml format strings: 2 | 3 | - `Format_doc.Immutable` provides an immutable interpreter that records formatting 4 | instruction that can be send subsequently to a Format.formatter. 5 | 6 | - `Format_doc.Ref` is a thin layer above `Format_doc.Immutable` that wraps the 7 | document in a reference cell in order to mimic the classical Format API. 8 | 9 | - `Format_doc.Compat` provides a compatibility interpreter that may work in either 10 | the classical Format mode or in the reference mode from above." 11 | 12 | ## Immutable interface 13 | 14 | The `Immutable` module provides a way to compose partial message 15 | without mutation 16 | 17 | ``` ocaml 18 | open Format_doc.Immutable 19 | module Doc = Format_doc.Doc 20 | 21 | type Doc.tag += Red 22 | 23 | let test_doc = 24 | Doc.empty 25 | |> open_box B 0 26 | |> string "Let's start with a string." 27 | |> printf "@,%s@ %t" "We can use regular" 28 | (list string ["format strings "; "and immutable printer"]) 29 | |> open_tag Red 30 | |> printf "@ and tag." 31 | |> close_tag 32 | |> close_box 33 | |> force_stop 34 | ``` 35 | 36 | The advantage is that the `Doc.t` consists in pure data and it is thus 37 | fully serializable and independent on the interpretation of tags and 38 | formatting hints. 39 | 40 | In particular, this means that we can easily print the same document with 41 | different interpretation of tags or geometry without resorting to a closure 42 | 43 | ``` ocaml 44 | let () = 45 | Format.set_geometry ~max_indent:19 ~margin:20; 46 | Doc.format Format.std_formatter test_doc 47 | ``` 48 | 49 | ## Compatibility interface 50 | 51 | The `Compat` module has been designed to be able to replace in-situ the `Format` 52 | module with exactly the same API while giving the possibility to use either the 53 | `Format_doc.Immutable` backend or the classical backend. 54 | 55 | ``` ocaml 56 | open Format_doc.Compat 57 | let print ppf () = 58 | pp_open_box ppf 0; 59 | pp_print_string ppf "Let's start with a string."; 60 | fprintf ppf "@,%s@ %a" 61 | "We can use regular" 62 | (pp_print_list pp_print_string) ["format strings "; "and immutable printer"]; 63 | pp_open_stag ppf Red; 64 | fprintf ppf "@ and tags."; 65 | pp_close_stag ppf (); 66 | pp_close_box ppf (); 67 | pp_print_newline ppf () 68 | ``` 69 | 70 | Switching to the classical backend is then just a function call away 71 | 72 | ``` ocaml 73 | let () = compat print Format.std_formatter () 74 | ``` 75 | but we can still choose the immutable backend with 76 | ``` ocaml 77 | let test_doc' = doc_printf "%t" print () 78 | ``` 79 | and use the fact that `Doc.t` is pure data to check that we ended up 80 | with the same `Doc.t` with the compatibility layer: 81 | 82 | ``` ocaml 83 | let _ = assert (test_doc = test_doc') 84 | ``` 85 | -------------------------------------------------------------------------------- /dune-project: -------------------------------------------------------------------------------- 1 | (lang dune 3.2) 2 | 3 | (generate_opam_files true) 4 | 5 | (source (github Octachron/format-doc)) 6 | (license LGPL-2.1-or-later WITH OCaml-LGPL-linking-exception) 7 | (authors "Florian Angeletti") 8 | (maintainers "octa@polychoron.fr") 9 | 10 | (package 11 | (name format-doc) 12 | (version 0.1) 13 | (synopsis "Alternative interpreters for OCaml format strings") 14 | (description "Format-doc provides alternative interpreters for OCaml format strings: 15 | - Format_doc.Immutable provides an immutable interpreter that records formatting 16 | instruction that can be send subsequently to a Format.formatter. 17 | - Format_doc.Ref is a thin layer above Format_doc.Immutable that wraps the 18 | document in a reference cell in order to mimic the classical Format API. 19 | - Format_doc.Compat provides a compatibility interpreter that may work in either 20 | the classical Format mode or in the reference mode from above.") 21 | ) 22 | -------------------------------------------------------------------------------- /format-doc.opam: -------------------------------------------------------------------------------- 1 | # This file is generated by dune, edit dune-project instead 2 | opam-version: "2.0" 3 | version: "0.1" 4 | synopsis: "Alternative interpreters for OCaml format strings" 5 | description: """ 6 | Format-doc provides alternative interpreters for OCaml format strings: 7 | - Format_doc.Immutable provides an immutable interpreter that records formatting 8 | instruction that can be send subsequently to a Format.formatter. 9 | - Format_doc.Ref is a thin layer above Format_doc.Immutable that wraps the 10 | document in a reference cell in order to mimic the classical Format API. 11 | - Format_doc.Compat provides a compatibility interpreter that may work in either 12 | the classical Format mode or in the reference mode from above.""" 13 | maintainer: ["octa@polychoron.fr"] 14 | authors: ["Florian Angeletti"] 15 | license: ["LGPL-2.1-or-later" "WITH" "OCaml-LGPL-linking-exception"] 16 | homepage: "https://github.com/Octachron/format-doc" 17 | bug-reports: "https://github.com/Octachron/format-doc/issues" 18 | depends: [ 19 | "dune" {>= "3.2"} 20 | "odoc" {with-doc} 21 | ] 22 | build: [ 23 | ["dune" "subst"] {dev} 24 | [ 25 | "dune" 26 | "build" 27 | "-p" 28 | name 29 | "-j" 30 | jobs 31 | "@install" 32 | "@runtest" {with-test} 33 | "@doc" {with-doc} 34 | ] 35 | ] 36 | dev-repo: "git+https://github.com/Octachron/format-doc.git" 37 | -------------------------------------------------------------------------------- /lib/compat.ml: -------------------------------------------------------------------------------- 1 | (**************************************************************************) 2 | (* *) 3 | (* OCaml *) 4 | (* *) 5 | (* Florian Angeletti, projet Cambium, Inria Paris *) 6 | (* *) 7 | (* Copyright 2021 Institut National de Recherche en Informatique et *) 8 | (* en Automatique. *) 9 | (* *) 10 | (* All rights reserved. This file is distributed under the terms of *) 11 | (* the GNU Lesser General Public License version 2.1, with the *) 12 | (* special exception on linking described in the file LICENSE. *) 13 | (* *) 14 | (**************************************************************************) 15 | 16 | open Doc 17 | 18 | (** Compatibility interface *) 19 | 20 | type rdoc = doc ref 21 | type _ formatter = 22 | | Format: Format.formatter -> Format.formatter formatter 23 | | Doc: rdoc -> rdoc formatter 24 | type doc_fmt = rdoc formatter 25 | 26 | 27 | type ('a,'impl) printer = 'impl formatter -> 'a -> unit 28 | 29 | type 'a final_printer = ('a, Format.formatter) printer 30 | type 'a generic_printer = { printer: 'impl. ('a,'impl) printer} 31 | 32 | let make_formatter fmt = Format fmt 33 | let formatter_of_out_channel chan = 34 | make_formatter (Format.formatter_of_out_channel chan) 35 | let make_doc d = Doc d 36 | 37 | let doc: rdoc formatter -> _ = function 38 | | Doc { contents = rd } -> rd 39 | | Format _ -> 40 | (* Format.formatter is not a ref *) 41 | assert false 42 | let formatter: Format.formatter formatter -> _ = function 43 | | Doc _ -> 44 | (* Format.formatter is not a ref *) 45 | assert false 46 | | Format ppf -> ppf 47 | 48 | 49 | (** {1 Primitive functions }*) 50 | 51 | 52 | let pp_print_string (type i) (ppf: i formatter) s = match ppf with 53 | | Format ppf -> Format.pp_print_string ppf s 54 | | Doc rdoc -> rdoc := Immutable.string s !rdoc 55 | 56 | let pp_print_text (type i) (ppf: i formatter) s = match ppf with 57 | | Format ppf -> Format.pp_print_text ppf s 58 | | Doc rdoc -> rdoc := Immutable.text s !rdoc 59 | 60 | let pp_print_char (type i) (ppf: i formatter) c = match ppf with 61 | | Format ppf -> Format.pp_print_char ppf c 62 | | Doc rdoc -> rdoc := Immutable.char c !rdoc 63 | 64 | let pp_print_int (type i) (ppf: i formatter) c = match ppf with 65 | | Format ppf -> Format.pp_print_int ppf c 66 | | Doc rdoc -> rdoc := Immutable.int c !rdoc 67 | 68 | let pp_print_float (type i) (ppf: i formatter) c = match ppf with 69 | | Format ppf -> Format.pp_print_float ppf c 70 | | Doc rdoc -> rdoc := Immutable.float c !rdoc 71 | 72 | let pp_close_box (type i) (ppf: i formatter) () = match ppf with 73 | | Format ppf -> Format.pp_close_box ppf () 74 | | Doc rdoc -> rdoc := Immutable.close_box !rdoc 75 | 76 | let pp_close_stag (type i) (ppf: i formatter) () = match ppf with 77 | | Format ppf -> Format.pp_close_stag ppf () 78 | | Doc rdoc -> rdoc := Immutable.close_tag !rdoc 79 | 80 | let pp_print_break (type i) (ppf: i formatter) spaces indent = match ppf with 81 | | Format ppf -> Format.pp_print_break ppf spaces indent 82 | | Doc rdoc -> rdoc := Immutable.break ~spaces ~indent !rdoc 83 | 84 | let pp_print_space ppf () = pp_print_break ppf 1 0 85 | let pp_print_cut ppf () = pp_print_break ppf 0 0 86 | 87 | 88 | let pp_print_flush (type i) (ppf: i formatter) () = match ppf with 89 | | Format ppf -> Format.pp_print_flush ppf () 90 | | Doc rdoc -> rdoc := Immutable.flush !rdoc 91 | 92 | let pp_force_newline (type i) (ppf: i formatter) () = match ppf with 93 | | Format ppf -> Format.pp_force_newline ppf () 94 | | Doc rdoc -> rdoc := Immutable.force_newline !rdoc 95 | 96 | let pp_print_newline (type i) (ppf: i formatter) () = match ppf with 97 | | Format ppf -> Format.pp_print_newline ppf () 98 | | Doc rdoc -> rdoc := Immutable.force_stop !rdoc 99 | 100 | 101 | let pp_print_as (type i) (ppf: i formatter) size x = match ppf with 102 | | Format ppf -> Format.pp_print_as ppf size x 103 | | Doc rdoc -> 104 | rdoc := !rdoc |> Immutable.with_size size |> Immutable.string x 105 | 106 | let pp_open_stag (type i) (ppf: i formatter) stag = match ppf with 107 | | Format ppf -> Format.pp_open_stag ppf stag 108 | | Doc rdoc -> rdoc := !rdoc |> Immutable.open_tag stag 109 | 110 | let pp_open_box_gen (type i) (ppf: i formatter) indent bxty = 111 | let box_type = Doc.box_type bxty in 112 | match ppf with 113 | | Format ppf -> format_open_box_gen ppf box_type indent 114 | | Doc rdoc -> rdoc := !rdoc |> Immutable.open_box box_type indent 115 | 116 | let pp_open_box ppf indent = pp_open_box_gen ppf indent Pp_box 117 | 118 | 119 | let pp_open_tbox (type i) (ppf: i formatter) () = 120 | match ppf with 121 | | Format ppf -> Format.pp_open_tbox ppf () 122 | | Doc rdoc -> rdoc := !rdoc |> Immutable.open_tbox 123 | 124 | let pp_close_tbox (type i) (ppf: i formatter) () = 125 | match ppf with 126 | | Format ppf -> Format.pp_close_tbox ppf () 127 | | Doc rdoc -> rdoc := !rdoc |> Immutable.close_tbox 128 | 129 | let pp_set_tab (type i) (ppf: i formatter) () = 130 | match ppf with 131 | | Format ppf -> Format.pp_set_tab ppf () 132 | | Doc rdoc -> rdoc := !rdoc |> Immutable.set_tab 133 | 134 | let pp_print_tab (type i) (ppf: i formatter) () = 135 | match ppf with 136 | | Format ppf -> Format.pp_print_tab ppf () 137 | | Doc rdoc -> rdoc := !rdoc |> Immutable.tab 138 | 139 | let pp_print_tbreak (type i) (ppf: i formatter) width offset = 140 | match ppf with 141 | | Format ppf -> Format.pp_print_tbreak ppf width offset 142 | | Doc rdoc -> rdoc := !rdoc |> Immutable.tab_break ~width ~offset 143 | 144 | 145 | let pp_doc (type i) (ppf: i formatter) doc = match ppf with 146 | | Format ppf -> format ppf doc 147 | | Doc rdoc -> rdoc := Doc.append !rdoc doc 148 | 149 | module Driver = struct 150 | (* Interpret a formatting entity on a formatter. *) 151 | let output_formatting_lit ppf 152 | (fmting_lit:CamlinternalFormatBasics.formatting_lit) 153 | = match fmting_lit with 154 | | Close_box -> pp_close_box ppf () 155 | | Close_tag -> pp_close_stag ppf () 156 | | Break (_, width, offset) -> pp_print_break ppf width offset 157 | | FFlush -> pp_print_flush ppf () 158 | | Force_newline -> pp_force_newline ppf () 159 | | Flush_newline -> pp_print_newline ppf () 160 | | Magic_size (_, _) -> () 161 | | Escaped_at -> pp_print_char ppf '@' 162 | | Escaped_percent -> pp_print_char ppf '%' 163 | | Scan_indic c -> pp_print_char ppf '@'; pp_print_char ppf c 164 | 165 | 166 | 167 | let compute_tag (type i) (main: i formatter) output tag_acc = 168 | let buf = Buffer.create 16 in 169 | let buf_fmt = Format.formatter_of_buffer buf in 170 | let ppf, commit = match main with 171 | | Format _ -> (Format buf_fmt: i formatter) , ignore 172 | | Doc _ -> 173 | let rdoc = ref empty in 174 | (Doc rdoc: i formatter), 175 | fun () -> format buf_fmt !rdoc; Format.pp_print_flush buf_fmt () 176 | in 177 | output ppf tag_acc; 178 | pp_print_flush ppf (); 179 | commit (); 180 | let len = Buffer.length buf in 181 | if len < 2 then Buffer.contents buf 182 | else Buffer.sub buf 1 (len - 2) 183 | 184 | (* Recursively output an "accumulator" containing a reversed list of 185 | printing entities (string, char, flus, ...) in an output_stream. *) 186 | (* Differ from Printf.output_acc by the interpretation of formatting. *) 187 | (* Used as a continuation of CamlinternalFormat.make_printf. *) 188 | let rec output_acc: type i. 189 | i formatter -> (i formatter, unit) CamlinternalFormat.acc -> unit = 190 | fun ppf acc -> 191 | match acc with 192 | | Acc_string_literal (Acc_formatting_lit (p, Magic_size (_, size)), s) 193 | | Acc_data_string (Acc_formatting_lit (p, Magic_size (_, size)), s) -> 194 | output_acc ppf p; 195 | pp_print_as ppf size s; 196 | | Acc_char_literal (Acc_formatting_lit (p, Magic_size (_, size)), c) 197 | | Acc_data_char (Acc_formatting_lit (p, Magic_size (_, size)), c) -> 198 | output_acc ppf p; 199 | pp_print_as ppf size (String.make 1 c); 200 | | Acc_formatting_lit (p, f) -> 201 | output_acc ppf p; 202 | output_formatting_lit ppf f; 203 | | Acc_formatting_gen (p, Acc_open_tag acc') -> 204 | output_acc ppf p; 205 | pp_open_stag ppf (Format.String_tag (compute_tag ppf output_acc acc')) 206 | | Acc_formatting_gen (p, Acc_open_box acc') -> 207 | output_acc ppf p; 208 | let (indent, bty) = 209 | let box_info = compute_tag ppf output_acc acc' in 210 | CamlinternalFormat.open_box_of_string box_info 211 | in 212 | pp_open_box_gen ppf indent bty 213 | | Acc_string_literal (p, s) 214 | | Acc_data_string (p, s) -> output_acc ppf p; pp_print_string ppf s; 215 | | Acc_char_literal (p, c) 216 | | Acc_data_char (p, c) -> output_acc ppf p; pp_print_char ppf c; 217 | | Acc_delay (p, f) -> output_acc ppf p; f ppf; 218 | | Acc_flush p -> output_acc ppf p; pp_print_flush ppf (); 219 | | Acc_invalid_arg (p, msg) -> output_acc ppf p; invalid_arg msg; 220 | | End_of_acc -> () 221 | end 222 | 223 | let kfprintf k ppf (CamlinternalFormatBasics.Format (fmt, _)) = 224 | CamlinternalFormat.make_printf 225 | (fun acc -> Driver.output_acc ppf acc; k ppf) 226 | End_of_acc fmt 227 | let fprintf doc fmt = kfprintf ignore doc fmt 228 | 229 | let kasprintf k fmt = 230 | let b = Buffer.create 20 in 231 | let ppf = make_formatter (Format.formatter_of_buffer b) in 232 | kfprintf 233 | (fun ppf -> pp_print_flush ppf (); 234 | let r = Buffer.contents b in 235 | Buffer.reset b; 236 | k r) 237 | ppf fmt 238 | 239 | let asprintf fmt = kasprintf Fun.id fmt 240 | 241 | let kdprintf k (CamlinternalFormatBasics.Format (fmt, _)) = 242 | CamlinternalFormat.make_printf 243 | (fun acc -> k (fun ppf -> Driver.output_acc ppf acc)) 244 | End_of_acc fmt 245 | 246 | let dprintf fmt = kdprintf (fun i -> i) fmt 247 | 248 | 249 | let doc_printf fmt = kfprintf (fun ppf -> doc ppf) (make_doc (ref empty)) fmt 250 | 251 | 252 | let doc_printer f x doc = 253 | let r = ref doc in 254 | f (Doc r) x; 255 | !r 256 | let format_printer f ppf x = f (make_formatter ppf) x 257 | 258 | let pp_print_list (type i) ?(pp_sep:(unit,i) printer=pp_print_cut) 259 | (elt: ('a,i) printer) (ppf: i formatter) l = match ppf with 260 | | Format ppf -> 261 | let pp_sep ppf x = pp_sep (Format ppf) x in 262 | let elt ppf x = elt(Format ppf) x in 263 | Format.pp_print_list ~pp_sep elt ppf l 264 | | Doc rdoc -> 265 | rdoc := 266 | Immutable.list ~sep:(doc_printer pp_sep ()) (doc_printer elt) l !rdoc 267 | 268 | 269 | let pp_print_option (type i) ?(none:(unit,i) printer=fun _ () -> ()) 270 | (elt: ('a,i) printer) (ppf: i formatter) o = match ppf with 271 | | Format ppf -> 272 | let none ppf x = none (Format ppf) x in 273 | let elt ppf x = elt(Format ppf) x in 274 | Format.pp_print_option ~none elt ppf o 275 | | Doc rdoc -> 276 | rdoc := 277 | Immutable.option ~none:(doc_printer none ()) (doc_printer elt) o !rdoc 278 | 279 | 280 | 281 | let pp_two_columns ?(sep = "|") ?max_lines ppf (lines: (string * string) list) = 282 | let left_column_size = 283 | List.fold_left (fun acc (s, _) -> Int.max acc (String.length s)) 0 lines in 284 | let lines_nb = List.length lines in 285 | let ellipsed_first, ellipsed_last = 286 | match max_lines with 287 | | Some max_lines when lines_nb > max_lines -> 288 | let printed_lines = max_lines - 1 in (* the ellipsis uses one line *) 289 | let lines_before = printed_lines / 2 + printed_lines mod 2 in 290 | let lines_after = printed_lines / 2 in 291 | (lines_before, lines_nb - lines_after - 1) 292 | | _ -> (-1, -1) 293 | in 294 | fprintf ppf "@["; 295 | List.iteri (fun k (line_l, line_r) -> 296 | if k = ellipsed_first then fprintf ppf "...@,"; 297 | if ellipsed_first <= k && k <= ellipsed_last then () 298 | else fprintf ppf "%*s %s %s@," left_column_size line_l sep line_r 299 | ) lines; 300 | fprintf ppf "@]" 301 | 302 | let compat = format_printer 303 | -------------------------------------------------------------------------------- /lib/compat.mli: -------------------------------------------------------------------------------- 1 | type doc := Doc.t 2 | 3 | type _ formatter 4 | type rdoc 5 | type doc_fmt = rdoc formatter 6 | 7 | 8 | type ('a,'impl) printer = 'impl formatter -> 'a -> unit 9 | type 'a final_printer = ('a, Format.formatter) printer 10 | type 'a generic_printer = { printer: 'impl. ('a,'impl) printer } 11 | 12 | val make_formatter: Format.formatter -> Format.formatter formatter 13 | val formatter_of_out_channel: out_channel -> Format.formatter formatter 14 | val make_doc: doc ref -> doc_fmt 15 | val compat: ('a,Format.formatter) printer -> Format.formatter -> 'a -> unit 16 | 17 | val doc: doc_fmt -> doc 18 | val formatter: Format.formatter formatter -> Format.formatter 19 | 20 | 21 | val fprintf : 'impl formatter -> ('a,'impl formatter,unit) format -> 'a 22 | val kfprintf: 23 | ('impl formatter -> 'a) -> 'impl formatter -> 24 | ('b, 'impl formatter, unit, 'a) format4 -> 'b 25 | 26 | 27 | val asprintf : ('a, Format.formatter formatter, unit, string) format4 -> 'a 28 | val kasprintf : (string -> 'a) -> 29 | ('b, Format.formatter formatter, unit, 'a) format4 -> 'b 30 | 31 | 32 | val dprintf : ('a,'impl formatter, unit, 'impl formatter -> unit) format4 -> 'a 33 | val kdprintf: 34 | (('impl formatter -> unit) -> 'a) -> 35 | ('b, 'impl formatter, unit, 'a) format4 -> 'b 36 | 37 | val doc_printf: ('a, rdoc formatter, unit, doc) format4 -> 'a 38 | 39 | 40 | 41 | val format_printer: 'a final_printer -> Format.formatter -> 'a -> unit 42 | val doc_printer:('a, rdoc) printer -> 'a -> Immutable.printer 43 | 44 | 45 | val pp_doc: (doc,_) printer 46 | 47 | val pp_print_string: (string,_) printer 48 | val pp_print_text: (string,_) printer 49 | val pp_print_char: (char,_) printer 50 | val pp_print_int: (int,_) printer 51 | val pp_print_float: (float,_) printer 52 | 53 | 54 | val pp_print_list: 55 | ?pp_sep:(unit,'impl) printer -> ('a,'impl) printer -> ('a list, 'impl) printer 56 | 57 | 58 | val pp_print_option: 59 | ?none:(unit,'impl) printer -> ('a,'impl) printer -> ('a option, 'impl) printer 60 | val pp_open_stag: (Format.stag,_) printer 61 | val pp_close_stag: (unit,_) printer 62 | 63 | val pp_open_box: (int,_) printer 64 | val pp_close_box: (unit,_) printer 65 | 66 | val pp_print_space: (unit,_) printer 67 | val pp_print_cut: (unit,_) printer 68 | val pp_print_break: _ formatter -> int -> int -> unit 69 | 70 | 71 | val pp_open_tbox: (unit,_) printer 72 | val pp_close_tbox: (unit,_) printer 73 | val pp_set_tab: (unit,_) printer 74 | val pp_print_tab: (unit,_) printer 75 | val pp_print_tbreak: 'impl formatter -> int -> int -> unit 76 | 77 | val pp_print_newline: (unit,_) printer 78 | val pp_force_newline: (unit,_) printer 79 | 80 | 81 | (** {1 Compiler output} *) 82 | 83 | 84 | val pp_two_columns : 85 | ?sep:string -> ?max_lines:int -> 86 | 'impl formatter -> (string * string) list -> unit 87 | (** [pp_two_columns ?sep ?max_lines ppf l] prints the lines in [l] as two 88 | columns separated by [sep] ("|" by default). [max_lines] can be used to 89 | indicate a maximum number of lines to print -- an ellipsis gets inserted at 90 | the middle if the input has too many lines. 91 | 92 | Example: 93 | 94 | {v pp_two_columns ~max_lines:3 Format.std_formatter [ 95 | "abc", "hello"; 96 | "def", "zzz"; 97 | "a" , "bllbl"; 98 | "bb" , "dddddd"; 99 | ] v} 100 | 101 | prints 102 | 103 | {v 104 | abc | hello 105 | ... 106 | bb | dddddd 107 | v} 108 | *) 109 | -------------------------------------------------------------------------------- /lib/doc.ml: -------------------------------------------------------------------------------- 1 | 2 | type box_type = 3 | | H 4 | | V 5 | | HV 6 | | HoV 7 | | B 8 | 9 | type tag = Format.stag = .. 10 | 11 | type element = 12 | | Data of string 13 | | With_size of int 14 | | Open_box of { kind: box_type ; indent:int } 15 | | Close_box 16 | | Open_tag of Format.stag 17 | | Close_tag 18 | | Open_tbox 19 | | Tab_break of { width : int; offset : int } 20 | | Set_tab 21 | | Close_tbox 22 | | Simple_break of { spaces : int; indent: int } 23 | | Break of { fits : string * int * string as 'a; breaks : 'a } 24 | | Flush of { newline:bool } 25 | | Newline 26 | | If_newline 27 | 28 | type doc = {front: element list; back:element list} 29 | 30 | type t = doc 31 | 32 | let empty : doc = { front = []; back = [] } 33 | 34 | let to_list doc = doc.front @ List.rev doc.back 35 | let _prepend x doc = { doc with front = x :: doc.front } 36 | let add x doc = { doc with back = x :: doc.back } 37 | 38 | let fold f acc doc = 39 | let first = List.fold_left f acc doc.front in 40 | let back = List.fold_left f first (List.rev doc.back) in 41 | back 42 | 43 | 44 | let append left right = fold (fun doc elt -> add elt doc) left right 45 | 46 | 47 | let format_open_box_gen ppf kind indent = 48 | match kind with 49 | | H-> Format.pp_open_hbox ppf () 50 | | V -> Format.pp_open_vbox ppf indent 51 | | HV -> Format.pp_open_hvbox ppf indent 52 | | HoV -> Format.pp_open_hovbox ppf indent 53 | | B -> Format.pp_open_box ppf indent 54 | 55 | let interpret_elt ppf = function 56 | | Data x -> Format.pp_print_string ppf x 57 | | Open_box { kind; indent } -> format_open_box_gen ppf kind indent 58 | | Close_box -> Format.pp_close_box ppf () 59 | | Open_tag tag -> Format.pp_open_stag ppf tag 60 | | Close_tag -> Format.pp_close_stag ppf () 61 | | Open_tbox -> Format.pp_open_tbox ppf () 62 | | Tab_break {width;offset} -> Format.pp_print_tbreak ppf width offset 63 | | Set_tab -> Format.pp_set_tab ppf () 64 | | Close_tbox -> Format.pp_close_tbox ppf () 65 | | Simple_break {spaces;indent} -> Format.pp_print_break ppf spaces indent 66 | | Break {fits;breaks} -> Format.pp_print_custom_break ppf ~fits ~breaks 67 | | Flush {newline=true} -> Format.pp_print_newline ppf () 68 | | Flush {newline=false} -> Format.pp_print_flush ppf () 69 | | Newline -> Format.pp_force_newline ppf () 70 | | If_newline -> Format.pp_print_if_newline ppf () 71 | | With_size _ -> () 72 | 73 | let rec interpret ppf = function 74 | | [] -> () 75 | | With_size n :: Data x :: q -> 76 | Format.pp_print_as ppf n x; 77 | interpret ppf q 78 | | x :: q -> 79 | interpret_elt ppf x; 80 | interpret ppf q 81 | 82 | let format ppf doc = interpret ppf (to_list doc) 83 | 84 | 85 | 86 | let box_type = 87 | let open CamlinternalFormatBasics in 88 | function 89 | | Pp_fits -> H 90 | | Pp_hbox -> H 91 | | Pp_vbox -> V 92 | | Pp_hovbox -> HoV 93 | | Pp_hvbox -> HV 94 | | Pp_box -> B 95 | 96 | 97 | let format_open_box_gen ppf kind indent = 98 | match kind with 99 | | H-> Format.pp_open_hbox ppf () 100 | | V -> Format.pp_open_vbox ppf indent 101 | | HV -> Format.pp_open_hvbox ppf indent 102 | | HoV -> Format.pp_open_hovbox ppf indent 103 | | B -> Format.pp_open_box ppf indent 104 | -------------------------------------------------------------------------------- /lib/doc.mli: -------------------------------------------------------------------------------- 1 | 2 | (** Composable document for the Format formatting engine *) 3 | 4 | type box_type = 5 | | H 6 | | V 7 | | HV 8 | | HoV 9 | | B 10 | val box_type: CamlinternalFormatBasics.block_type -> box_type 11 | val format_open_box_gen: Format.formatter -> box_type -> int -> unit 12 | 13 | type tag = Format.stag = .. 14 | 15 | type element = 16 | | Data of string 17 | | With_size of int 18 | | Open_box of { kind: box_type ; indent:int } 19 | | Close_box 20 | | Open_tag of Format.stag 21 | | Close_tag 22 | | Open_tbox 23 | | Tab_break of { width : int; offset : int } 24 | | Set_tab 25 | | Close_tbox 26 | | Simple_break of { spaces : int; indent : int } 27 | | Break of { fits : string * int * string as 'a; breaks : 'a } 28 | | Flush of { newline:bool } 29 | | Newline 30 | | If_newline 31 | 32 | 33 | type t 34 | type doc = t 35 | 36 | val empty: t 37 | 38 | val format: Format.formatter -> doc -> unit 39 | val fold: ('acc -> element -> 'acc) -> 'acc -> doc -> 'acc 40 | val add: element -> doc -> doc 41 | val append: doc -> doc -> doc 42 | -------------------------------------------------------------------------------- /lib/dune: -------------------------------------------------------------------------------- 1 | (library (public_name format-doc) (name format_doc)) 2 | -------------------------------------------------------------------------------- /lib/immutable.ml: -------------------------------------------------------------------------------- 1 | open Doc 2 | 3 | let open_box kind indent doc = add (Open_box {kind;indent}) doc 4 | let close_box doc = add Close_box doc 5 | 6 | let string s doc = add (Data s) doc 7 | let bytes b doc = add (Data (Bytes.to_string b)) doc 8 | let with_size n doc = add (With_size n) doc 9 | 10 | let int n doc = add (Data (string_of_int n)) doc 11 | let float f doc = add (Data (string_of_float f)) doc 12 | let char c doc = add (Data (String.make 1 c)) doc 13 | let bool c doc = add (Data (Bool.to_string c)) doc 14 | 15 | 16 | let break ~spaces ~indent doc = add (Simple_break {spaces; indent}) doc 17 | let space doc = break ~spaces:1 ~indent:0 doc 18 | let cut = break ~spaces:0 ~indent:0 19 | 20 | let custom_break ~fits ~breaks doc = add (Break {fits;breaks}) doc 21 | 22 | let force_newline doc = add Newline doc 23 | let if_newline doc = add If_newline doc 24 | 25 | let flush doc = add (Flush {newline=false}) doc 26 | let force_stop = add (Flush {newline=true}) 27 | 28 | let open_tbox doc = add Open_tbox doc 29 | let set_tab doc = add Set_tab doc 30 | let tab_break ~width ~offset doc = add (Tab_break {width;offset}) doc 31 | let tab doc = tab_break ~width:0 ~offset:0 doc 32 | let close_tbox doc = add Close_tbox doc 33 | 34 | let open_tag stag doc = add (Open_tag stag) doc 35 | let close_tag doc = add Close_tag doc 36 | 37 | let rec list ?(sep=Fun.id) elt l doc = match l with 38 | | [] -> doc 39 | | [a] -> elt a doc 40 | | a :: (_ :: _ as q) -> 41 | doc |> elt a |> sep |> list ~sep elt q 42 | 43 | 44 | let option ?(none=Fun.id) elt o doc = match o with 45 | | None -> none doc 46 | | Some x -> elt x doc 47 | 48 | (* To format free-flowing text *) 49 | let rec subtext len left right s doc = 50 | let flush doc = 51 | doc |> string (String.sub s left (right - left)) 52 | in 53 | let after_flush doc = subtext len (right+1) (right+1) s doc in 54 | if right = len then 55 | if left <> len then flush doc else doc 56 | else 57 | match s.[right] with 58 | | '\n' -> 59 | doc |> flush |> force_newline |> after_flush 60 | | ' ' -> 61 | doc |> flush |> space |> after_flush 62 | (* there is no specific support for '\t' 63 | as it is unclear what a right semantics would be *) 64 | | _ -> subtext len left (right + 1) s doc 65 | 66 | 67 | let text s doc = 68 | subtext (String.length s) 0 0 s doc 69 | 70 | type ('a,'b) fmt = ('a, doc, doc, 'b) format4 71 | type printer = doc -> doc 72 | 73 | 74 | 75 | 76 | let output_formatting_lit fmting_lit doc = 77 | let open CamlinternalFormatBasics in 78 | match fmting_lit with 79 | | Close_box -> close_box doc 80 | | Close_tag -> close_tag doc 81 | | Break (_, width, offset) -> break ~spaces:width ~indent:offset doc 82 | | FFlush -> flush doc 83 | | Force_newline -> force_newline doc 84 | | Flush_newline -> force_stop doc 85 | | Magic_size (_, n) -> with_size n doc 86 | | Escaped_at -> char '@' doc 87 | | Escaped_percent -> char '%' doc 88 | | Scan_indic c -> doc |> char '@' |> char c 89 | 90 | let to_buffer doc = 91 | let b = Buffer.create 20 in 92 | let convert = function 93 | | Data s -> Buffer.add_string b s 94 | | _ -> () 95 | in 96 | fold (fun () x -> convert x) () doc; 97 | b 98 | 99 | let to_string doc = Buffer.contents (to_buffer doc) 100 | 101 | let box_string doc = 102 | let b = to_buffer doc in 103 | let len = Buffer.length b in 104 | if len <= 2 then Buffer.contents b 105 | else 106 | Buffer.sub b 1 (len-2) 107 | 108 | let rec compose_acc acc doc = 109 | let open CamlinternalFormat in 110 | match acc with 111 | | CamlinternalFormat.Acc_formatting_lit (p, f) -> 112 | doc |> compose_acc p |> output_formatting_lit f 113 | | Acc_formatting_gen (p, Acc_open_tag acc') -> 114 | let tag = to_string (compose_acc acc' empty) in 115 | let doc = compose_acc p doc in 116 | doc |> open_tag (Format.String_tag tag) 117 | | Acc_formatting_gen (p, Acc_open_box acc') -> 118 | let doc = compose_acc p doc in 119 | let box = box_string (compose_acc acc' empty) in 120 | let (indent, bty) = CamlinternalFormat.open_box_of_string box in 121 | doc |> open_box (box_type bty) indent 122 | | Acc_string_literal (p, s) 123 | | Acc_data_string (p, s) -> 124 | doc |> compose_acc p |> string s 125 | | Acc_char_literal (p, c) 126 | | Acc_data_char (p, c) -> doc |> compose_acc p |> char c 127 | | Acc_delay (p, f) -> doc |> compose_acc p |> f 128 | | Acc_flush p -> doc |> compose_acc p |> flush 129 | | Acc_invalid_arg (_p, msg) -> invalid_arg msg; 130 | | End_of_acc -> doc 131 | 132 | let kprintf k (CamlinternalFormatBasics.Format (fmt, _)) = 133 | CamlinternalFormat.make_printf 134 | (fun acc doc -> doc |> compose_acc acc |> k ) 135 | End_of_acc fmt 136 | 137 | let printf doc = kprintf Fun.id doc 138 | let kmsg k (CamlinternalFormatBasics.Format (fmt, _)) = 139 | CamlinternalFormat.make_printf 140 | (fun acc -> k (compose_acc acc empty)) 141 | End_of_acc fmt 142 | 143 | let msg fmt = kmsg Fun.id fmt 144 | -------------------------------------------------------------------------------- /lib/immutable.mli: -------------------------------------------------------------------------------- 1 | type doc := Doc.t 2 | 3 | type ('a,'b) fmt = ('a, doc, doc,'b) format4 4 | 5 | type printer = doc -> doc 6 | 7 | val printf: ('a, printer) fmt -> 'a 8 | val msg: ('a,doc) fmt -> 'a 9 | val kmsg: (doc -> 'b) -> ('a,'b) fmt -> 'a 10 | val kprintf: (doc -> 'b) -> ('a, doc -> 'b) fmt -> 'a 11 | 12 | val open_box: Doc.box_type -> int -> printer 13 | val close_box: printer 14 | 15 | val text: string -> printer 16 | val string: string -> printer 17 | val bytes: bytes -> printer 18 | val with_size: int -> printer 19 | 20 | val int: int -> printer 21 | val float: float -> printer 22 | val char: char -> printer 23 | val bool: bool -> printer 24 | 25 | val space: printer 26 | val cut: printer 27 | val break: spaces:int -> indent:int -> printer 28 | 29 | val custom_break: 30 | fits:(string * int * string as 'a) -> breaks:'a -> printer 31 | val force_newline: printer 32 | val if_newline: printer 33 | 34 | val flush: printer 35 | val force_stop: printer 36 | 37 | val open_tbox: printer 38 | val set_tab: printer 39 | val tab: printer 40 | val tab_break: width:int -> offset:int -> printer 41 | val close_tbox: printer 42 | 43 | val open_tag: Doc.tag -> printer 44 | val close_tag: printer 45 | 46 | val list: 47 | ?sep:(doc->doc) -> ('a -> printer) -> 'a list -> printer 48 | 49 | val option: ?none:(doc->doc) -> ('a -> doc -> doc) -> 'a option -> doc -> doc 50 | 51 | 52 | val output_formatting_lit: CamlinternalFormatBasics.formatting_lit -> doc -> doc 53 | val to_string: doc -> string 54 | -------------------------------------------------------------------------------- /lib/ref.ml: -------------------------------------------------------------------------------- 1 | open Doc 2 | 3 | type ('a,'b) fmt = ('a, doc ref, unit,'b) format4 4 | 5 | open Immutable 6 | let rec update_acc doc (acc: (doc ref,unit) CamlinternalFormat.acc) : unit = 7 | match acc with 8 | | Acc_formatting_lit (p, f) -> 9 | update_acc doc p; 10 | doc := output_formatting_lit f !doc 11 | | Acc_formatting_gen (p, Acc_open_tag acc') -> 12 | let tag_doc = ref empty in 13 | update_acc doc p; 14 | update_acc tag_doc acc'; 15 | doc := open_tag (Format.String_tag (to_string !tag_doc)) !doc 16 | | Acc_formatting_gen (p, Acc_open_box acc') -> 17 | update_acc doc p; 18 | let tag_doc = ref empty in 19 | update_acc tag_doc acc'; 20 | let box = to_string !tag_doc in 21 | let (indent, bty) = CamlinternalFormat.open_box_of_string box in 22 | doc := open_box (box_type bty) indent !doc 23 | | Acc_string_literal (p, s) 24 | | Acc_data_string (p, s) -> 25 | update_acc doc p; 26 | doc := string s !doc 27 | | Acc_char_literal (p, c) 28 | | Acc_data_char (p, c) -> update_acc doc p; doc := char c !doc 29 | | Acc_delay (p, f) -> update_acc doc p; f doc 30 | | Acc_flush p -> update_acc doc p; doc := flush !doc 31 | | Acc_invalid_arg (p, msg) -> update_acc doc p; invalid_arg msg 32 | | End_of_acc -> () 33 | 34 | let kprintf k rdoc (CamlinternalFormatBasics.Format (fmt, _)) = 35 | CamlinternalFormat.make_printf 36 | (fun acc -> update_acc rdoc acc; k rdoc) 37 | End_of_acc fmt 38 | let printf doc fmt = kprintf ignore doc fmt 39 | -------------------------------------------------------------------------------- /lib/ref.mli: -------------------------------------------------------------------------------- 1 | type doc := Doc.t 2 | 3 | type ('a,'b) fmt = ('a, doc ref, unit,'b) format4 4 | val printf: doc ref -> ('a, unit) fmt -> 'a 5 | val kprintf: (doc ref -> 'b) -> doc ref -> ('a, 'b) fmt -> 'a 6 | -------------------------------------------------------------------------------- /tests/boxes.expected: -------------------------------------------------------------------------------- 1 | First box 2 | Second 3 | box -------------------------------------------------------------------------------- /tests/boxes.ml: -------------------------------------------------------------------------------- 1 | open Format_doc 2 | open Immutable 3 | 4 | let doc = 5 | printf "@[First box@ @[<%s>Second@ box@]@]" 6 | "v 4" 7 | Doc.empty 8 | 9 | let () = Doc.format Format.std_formatter doc 10 | -------------------------------------------------------------------------------- /tests/dune: -------------------------------------------------------------------------------- 1 | (tests (names readme boxes) (libraries format_doc)) 2 | -------------------------------------------------------------------------------- /tests/readme.expected: -------------------------------------------------------------------------------- 1 | Let's start with a string. 2 | We can use regular 3 | format strings 4 | and immutable printer 5 | and tags. 6 | Let's start with a string. 7 | We can use regular 8 | format strings 9 | and immutable printer 10 | and tags. 11 | Let's start with a string. 12 | We can use regular 13 | format strings 14 | and immutable printer 15 | and tags. 16 | 17 | -------------------------------------------------------------------------------- /tests/readme.ml: -------------------------------------------------------------------------------- 1 | open Format_doc.Immutable 2 | module Doc = Format_doc.Doc 3 | 4 | type Doc.tag += Red 5 | 6 | let test_doc = 7 | Doc.empty 8 | |> open_box B 0 9 | |> string "Let's start with a string." 10 | |> printf "@,%s@ %t" "We can use regular" 11 | (list ~sep:cut string ["format strings "; "and immutable printer"]) 12 | |> open_tag Red 13 | |> printf "@ and tags." 14 | |> close_tag 15 | |> close_box 16 | |> force_stop 17 | 18 | 19 | let () = 20 | Format.set_geometry ~max_indent:19 ~margin:20; 21 | Doc.format Format.std_formatter test_doc 22 | 23 | open Format_doc.Compat 24 | let print ppf () = 25 | pp_open_box ppf 0; 26 | pp_print_string ppf "Let's start with a string."; 27 | fprintf ppf "@,%s@ %a" 28 | "We can use regular" 29 | (pp_print_list pp_print_string) ["format strings "; "and immutable printer"]; 30 | pp_open_stag ppf Red; 31 | fprintf ppf "@ and tags."; 32 | pp_close_stag ppf (); 33 | pp_close_box ppf (); 34 | pp_print_newline ppf () 35 | 36 | 37 | let () = compat print Format.std_formatter () 38 | 39 | let test_doc' = doc_printf "%a" print () 40 | 41 | let _ = assert (test_doc = test_doc') 42 | 43 | let () = 44 | Format.printf "%a@." Doc.format test_doc' 45 | --------------------------------------------------------------------------------