Module Fmt
Format pretty-printer combinators.
Consult naming conventions for your pretty-printers.
References
- The
Formatmodule documentation. - The required reading
Formatmodule tutorial.
Standard outputs
Formatting
val pf : Stdlib.Format.formatter -> ('a, Stdlib.Format.formatter, unit) Stdlib.format -> 'apfisFormat.fprintf.
val str : ('a, Stdlib.Format.formatter, unit, string) Stdlib.format4 -> 'astrisFormat.asprintf.Note. When using
strfutf_8andstyle_rendererare always respectively set totrueand`None. See alsostr_like.
val kpf : (Stdlib.Format.formatter -> 'a) -> Stdlib.Format.formatter -> ('b, Stdlib.Format.formatter, unit, 'a) Stdlib.format4 -> 'bkpfisFormat.kfprintf.
val kstr : (string -> 'a) -> ('b, Stdlib.Format.formatter, unit, 'a) Stdlib.format4 -> 'bkstris likestrbut continuation based.
val str_like : Stdlib.Format.formatter -> ('a, Stdlib.Format.formatter, unit, string) Stdlib.format4 -> 'astr_like ppfis likestrexcept itsutf_8andstyle_renderersettings are those ofppf.
val with_buffer : ?like:Stdlib.Format.formatter -> Stdlib.Buffer.t -> Stdlib.Format.formatterwith_buffer ~like bis a formatter whoseutf_8andstyle_renderersettings are copied from those oflike(if provided).
val failwith : ('a, Stdlib.Format.formatter, unit, 'b) Stdlib.format4 -> 'afailwithiskstr failwith, raisesStdlib.Failure with a pretty-printed string argument.
val failwith_notrace : ('a, Stdlib.Format.formatter, unit, 'b) Stdlib.format4 -> 'afailwith_notraceis likefailwithbut raises withraise_notrace.
val invalid_arg : ('a, Stdlib.Format.formatter, unit, 'b) Stdlib.format4 -> 'ainvalid_argiskstr invalid_arg, raisesStdlib.Invalid_argument with a pretty-printed string argument.
Formatters
val flush : 'a tflushhas the effect ofFormat.pp_print_flush
val nop : 'a tnopformats nothing.
val any : (unit, Stdlib.Format.formatter, unit) Stdlib.format -> 'a tany fmt ppf vformats any value with the constant formatfmt.
val fmt : ('a, Stdlib.Format.formatter, unit) Stdlib.format -> Stdlib.Format.formatter -> 'afmt fmt ppfispf ppf fmt. Iffmtis used with a single non-constant formatting directive, generates a value of typet.
Separators
val cut : 'a tcuthas the effect ofFormat.pp_print_cut.
val sp : 'a tsphas the effect ofFormat.pp_print_space.
val sps : int -> 'a tsps nhas the effect ofFormat.pp_print_breakn 0.
Sequencing
val concat : ?sep:unit t -> 'a t list -> 'a tconcat ~sep ppsformats a value using the formatersppsand separting each format withsep(defaults tocut).
Boxes
val box : ?indent:int -> 'a t -> 'a tbox ~indent pp ppfwrapsppin a pretty-printing box. The box tries to print as much as possible on every line, while emphasizing the box structure (seeFormat.pp_open_box). Break hints that lead to a new line addindentto the current indentation (defaults to0).
val hbox : 'a t -> 'a thboxis likeboxbut is a horizontal box: the line is not split in this box (but may be in sub-boxes). SeeFormat.pp_open_hbox.
val vbox : ?indent:int -> 'a t -> 'a tvboxis likeboxbut is a vertical box: every break hint leads to a new line which addsindentto the current indentation (defaults to0). SeeFormat.pp_open_vbox.
Brackets
Records
Stdlib types
Formatters for structures give full control to the client over the formatting process and do not wrap the formatted structures with boxes. Use the Dump module to quickly format values for inspection.
val bool : bool tboolisFormat.pp_print_bool.
val int : int tintispf ppf "%d".
val nativeint : nativeint tnativeint ppfispf ppf "%nd".
val int32 : int32 tint32 ppfispf ppf "%ld".
val int64 : int64 tint64 ppfispf ppf "%Ld".
val uint : int tuint ppfispf ppf "%u".
val unativeint : nativeint tunativeint ppfispf ppf "%nu".
val uint32 : int32 tuint32 ppfispf ppf "%lu".
val uint64 : int64 tuint64 ppfispf ppf "%Lu".
val float : float tfloat ppfispf ppf "%g".
val float_dfrac : int -> float tfloat_dfrac drounds the float to thedth decimal fractional digit and formats the result with"%g". Ties are rounded towards positive infinity. The result is only defined for0 <= d <= 16.
val float_dsig : int -> float tfloat_dsig drounds the normalized decimal significand of the float to thedth decimal fractional digit and formats the result with"%g". Ties are rounded towards positive infinity. The result is NaN on infinities and only defined for0 <= d <= 16.Warning. The current implementation overflows on large
dand floats.
val char : char tcharisFormat.pp_print_char.
val string : string tstringisFormat.pp_print_string.
val buffer : Stdlib.Buffer.t tbufferformats aBuffer.t value's current contents.
val exn : exn texnformats an exception.
val exn_backtrace : (exn * Stdlib.Printexc.raw_backtrace) texn_backtraceformats an exception backtrace.
val pair : ?sep:unit t -> 'a t -> 'b t -> ('a * 'b) tpair ~sep pp_fst pp_sndformats a pair. The first and second projection are formatted usingpp_fstandpp_sndand are separated bysep(defaults tocut).
val option : ?none:unit t -> 'a t -> 'a option toption ~none pp_vformats an optional value. TheSomecase usespp_vandNoneusesnone(defaults tonop).
val result : ok:'a t -> error:'b t -> ('a, 'b) Stdlib.result tresult ~ok ~errorformats a result value usingokfor theOkcase anderrorfor theErrorcase.
val list : ?sep:unit t -> 'a t -> 'a list tlist sep pp_vformats list elements. Each element of the list is formatted in order withpp_v. Elements are separated bysep(defaults tocut). If the list is empty, this isnop.
val array : ?sep:unit t -> 'a t -> 'a array tarray sep pp_vformats array elements. Each element of the array is formatted in order withpp_v. Elements are separated bysep(defaults tocut). If the array is empty, this isnop.
val seq : ?sep:unit t -> 'a t -> 'a Stdlib.Seq.t tseq sep pp_vformats sequence elements. Each element of the sequence is formatted in order withpp_v. Elements are separated bysep(defaults tocut). If the sequence is empty, this isnop.
val hashtbl : ?sep:unit t -> ('a * 'b) t -> ('a, 'b) Stdlib.Hashtbl.t thashtbl ~sep pp_bindingformats the bindings of a hash table. Each binding is formatted withpp_bindingand bindings are separated bysep(defaults tocut). If the hash table has multiple bindings for a given key, all bindings are formatted, with the most recent binding first. If the hash table is empty, this isnop.
val queue : ?sep:unit t -> 'a t -> 'a Stdlib.Queue.t tqueue ~sep pp_vformats queue elements. Each element of the queue is formatted in least recently added order withpp_v. Elements are separated bysep(defaults tocut). If the queue is empty, this isnop.
val stack : ?sep:unit t -> 'a t -> 'a Stdlib.Stack.t tstack ~sep pp_vformats stack elements. Each element of the stack is formatted from top to bottom order withpp_v. Elements are separated bysep(defaults tocut). If the stack is empty, this isnop.
module Dump : sig ... endFormatters for inspecting OCaml values.
Magnitudes
val si_size : scale:int -> string -> int tsi_size ~scale unitformats a non negative integer representing unitunitat scale 10scale * 3, depending on its magnitude, using power of 3 SI prefixes (i.e. all of them except deca, hector, deci and centi). Only US-ASCII characters are used,µ(10-6) is written usingu.scaleindicates the scale 10scale * 3 an integer represents, for example-1for munit(10-3),0forunit(100),1forkunit(103); it must be in the range [-8;8] orInvalid_argumentis raised.Except at the maximal yotta scale always tries to show three digits of data with trailing fractional zeros omited. Rounds towards positive infinity (over approximates).
val byte_size : int tbyte_sizeissi_size ~scale:0 "B".
val bi_byte_size : int tbi_byte_sizeformats a byte size according to its magnitude using binary prefixes up to pebi bytes (215).
val uint64_ns_span : int64 tuint64_ns_spanformats an unsigned nanosecond time span according to its magnitude using SI prefixes on seconds and accepted non-SI units. Years are counted in Julian years (365.25 SI-accepted days) as defined by the International Astronomical Union (IAU). Only US-ASCII characters are used (usis used forµs).
Binary data
type 'a vec= int * (int -> 'a)The type for random addressable, sized sequences. Each
(n, f)represents the sequencef 0, ..., f (n - 1).
val ascii : ?w:int -> ?subst:unit t -> unit -> char vec tascii ~w ~subst ()formats character sequences by printing characters in the printable US-ASCII range ([0x20];[0x7E]) as is, and replacing the rest withsubst(defaults tofmt ".").wcauses the output to be right padded to the size of formatting at leastwsequence elements (defaults to0).
val octets : ?w:int -> ?sep:unit t -> unit -> char vec toctets ~w ~sep ()formats character sequences as hexadecimal digits. It prints groups of successive characters of unspecified length together, separated bysep(defaults tosp).wcauses the output to be right padded to the size of formatting at leastwsequence elements (defaults to0).
Words, paragraphs, text and lines
Note. These functions only work on US-ASCII strings and/or with newlines ('\n'). If you are dealing with UTF-8 strings or different kinds of line endings you should use the pretty-printers from Uuseg_string.
White space. White space is one of the following US-ASCII characters: space ' ' (0x20), tab '\t' (0x09), newline '\n' (0x0A), vertical tab (0x0B), form feed (0x0C), carriage return '\r' (0x0D).
val words : string twordsformats words by suppressing initial and trailing white space and replacing consecutive white space with a singleFormat.pp_print_space.
val paragraphs : string tparagraphsformats paragraphs by suppressing initial and trailing spaces and newlines, replacing blank lines (a line made only of white space) by a twoFormat.pp_force_newline and remaining consecutive white space with a singleFormat.pp_print_space.
val text : string ttextformats text by respectively replacing spaces and newlines in the string withFormat.pp_print_space andFormat.pp_force_newline.
val lines : string tlinesformats lines by replacing newlines ('\n') in the string with calls toFormat.pp_force_newline.
val truncated : max:int -> string ttruncated ~maxformats a string using at mostmaxcharacters. If the string doesn't fit, it is truncated and ended with three consecutive dots which do count towardsmax.
val text_loc : ((int * int) * (int * int)) ttext_locformats a line-column text range according to GNU conventions.
HCI fragments
val one_of : ?empty:unit t -> 'a t -> 'a list tone_of ~empty pp_v ppf lformats according to the length ofl0, formatsempty(defaults tonop).1, formats the element withpp_v.2, formats"either %a or %a"with the list elementsn, formats"one of %a, ... or %a"with the list elements
val did_you_mean : ?pre:unit t -> ?post:unit t -> kind:string -> 'a t -> ('a * 'a list) tdid_you_mean ~pre kind ~post pp_vformats a faulty valuevof kindkindand a list ofhintsthatvcould have been mistaken for.predefaults tounit "Unknown",posttonopthey surround the faulty value before the "did you mean" part as follows"%a %s %a%a." pre () kind pp_v v post (). Ifhintsis empty no "did you mean" part is printed.
Conditional UTF-8 formatting
Note. Since Format is not UTF-8 aware using UTF-8 output may derail the pretty printing process. Use the pretty-printers from Uuseg_string if you are serious about UTF-8 formatting.
val if_utf_8 : 'a t -> 'a t -> 'a tif_utf_8 pp_u pp ppf vis:pp_u ppf vifutf_8 ppfistrue.pp ppf votherwise.
val utf_8 : Stdlib.Format.formatter -> boolutf_8 ppfistrueif UTF-8 output is enabled onppf. Ifset_utf_8hasn't been called onppfthis istrue.
Styled formatting
type color=[|`Black|`Blue|`Cyan|`Green|`Magenta|`Red|`White|`Yellow]The type for colors.
type style=[|`None|`Bold|`Faint|`Italic|`Underline|`Reverse|`Fg of [ color | `Hi of color ]|`Bg of [ color | `Hi of color ]|color]The type for styles:
`Noneresets the styling.`Bold,`Faint,`Italic,`Underlineand`Reverseare display attributes.`Fg _is the foreground color or high-intensity color on`Hi _.`Bg _is the foreground color or high-intensity color on`Hi _.#coloris the foreground colour, deprecated use`Fg #colorinstead.
Style rendering control
type style_renderer=[|`Ansi_tty|`None]The type for style renderers.
`Ansi_tty, renders styles using ANSI escape sequences.`None, styled rendering has no effect.
val style_renderer : Stdlib.Format.formatter -> style_rendererstyle_renderer ppfis the style renderer used byppf. Ifset_style_rendererhas never been called onppfthis is`None.
val set_style_renderer : Stdlib.Format.formatter -> style_renderer -> unitset_style_renderer ppf rsets the style renderer ofppftor.- raises Invalid_argument
if
ppfisFormat.str_formatter: its renderer is always`None.
Converting with string value converters
val of_to_string : ('a -> string) -> 'a tof_to_string f ppf visstring ppf (f v).
val to_to_string : 'a t -> 'a -> stringto_to_string pp_v visstrf "%a" pp_v v.
Deprecated
val strf : ('a, Stdlib.Format.formatter, unit, string) Stdlib.format4 -> 'a- deprecated
use
strinstead.
val kstrf : (string -> 'a) -> ('b, Stdlib.Format.formatter, unit, 'a) Stdlib.format4 -> 'b- deprecated
use
kstrinstead.
val strf_like : Stdlib.Format.formatter -> ('a, Stdlib.Format.formatter, unit, string) Stdlib.format4 -> 'a- deprecated
use
str_likeinstead.
Naming conventions
Given a type ty use:
pp_tyfor a pretty printer that provides full control to the client and does not wrap the formatted value in an enclosing box. See these examples.pp_dump_tyfor a pretty printer that provides little control over the pretty-printing process, wraps the rendering in an enclosing box and tries as much as possible to respect the OCaml syntax. These pretty-printers should make it easy to inspect and understand values of the given type, they are mainly used for quick printf debugging and/or toplevel interaction. See these examples.
If you are in a situation where making a difference between dump_ty and pp_ty doesn't make sense then use pp_ty.
For a type ty that is the main type of the module (the "M.t" convention) drop the suffix, that is simply use M.pp and M.pp_dump.