diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index 3ec8956a..e3946688 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -12,6 +12,19 @@ type 'a printer = t -> 'a -> unit let silent _fmt _ = () +let return fmt_str out () = Format.fprintf out "%(%)" fmt_str + +(*$inject + let to_string_test s = CCFormat.sprintf_no_color "@[%a@]%!" s () +*) + +(*$= & ~printer:(fun s->CCFormat.sprintf "%S" s) + "a b" (to_string_test (return "a@ b")) + ", " (to_string_test (return ",@ ")) + "and then" (to_string_test (return "@{and then@}@,")) + "a b" (to_string_test (return "@[a@ b@]")) +*) + let unit fmt () = Format.pp_print_string fmt "()" let int fmt i = Format.pp_print_string fmt (string_of_int i) let string = Format.pp_print_string @@ -114,6 +127,14 @@ let hbox pp out x = pp out x; Format.pp_close_box out () +let of_to_string f out x = Format.pp_print_string out (f x) + +let const pp x out () = pp out x + +let some pp out = function + | None -> () + | Some x -> pp out x + (** {2 IO} *) let output fmt pp x = pp fmt x diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index dce09267..ff9f7119 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -15,6 +15,8 @@ type 'a printer = t -> 'a -> unit val silent : 'a printer (** Prints nothing *) val unit : unit printer +(** Prints "()" *) + val int : int printer val string : string printer val bool : bool printer @@ -75,6 +77,33 @@ val hbox : 'a printer -> 'a printer (** Wrap the printer in an horizontal box @since 0.16 *) +val return : ('a, _, _, 'a) format4 -> unit printer +(** [return "some_format_string"] takes a argument-less format string + and returns a printer actionable by [()]. + Examples: + - [return ",@ "] + - [return "@{and then@}@,"] + - [return "@[a@ b@]"] + + @since NEXT_RELEASE +*) + +val of_to_string : ('a -> string) -> 'a printer +(** [of_to_string f] converts its input to a string using [f], + then prints the string + @since NEXT_RELEASE *) + +val const : 'a printer -> 'a -> unit printer +(** [const pp x] is a unit printer that uses [pp] on [x] + @since NEXT_RELEASE *) + +val some : 'a printer -> 'a option printer +(** [some pp] will print options as follows: + - [Some x] is printed using [pp] on [x] + - [None] is not printed at all + @since NEXT_RELEASE +*) + (** {2 ANSI codes} Use ANSI escape codes https://en.wikipedia.org/wiki/ANSI_escape_code