add CCFormat.sprintf_no_color

This commit is contained in:
Simon Cruanes 2016-02-19 16:34:01 +01:00
parent 12ca402025
commit 526ea35495
2 changed files with 17 additions and 2 deletions

View file

@ -276,18 +276,29 @@ let with_colorf s out fmt =
(fun out -> Format.pp_close_tag out ()) (fun out -> Format.pp_close_tag out ())
out fmt out fmt
let sprintf format = (* c: whether colors are enabled *)
let sprintf_ c format =
let buf = Buffer.create 64 in let buf = Buffer.create 64 in
let fmt = Format.formatter_of_buffer buf in let fmt = Format.formatter_of_buffer buf in
if !color_enabled then set_color_tag_handling fmt; if c && !color_enabled then set_color_tag_handling fmt;
Format.kfprintf Format.kfprintf
(fun _fmt -> Format.pp_print_flush fmt (); Buffer.contents buf) (fun _fmt -> Format.pp_print_flush fmt (); Buffer.contents buf)
fmt fmt
format format
let sprintf fmt = sprintf_ true fmt
let sprintf_no_color fmt = sprintf_ false fmt
(*$T (*$T
sprintf "yolo %s %d" "a b" 42 = "yolo a b 42" sprintf "yolo %s %d" "a b" 42 = "yolo a b 42"
sprintf "%d " 0 = "0 " sprintf "%d " 0 = "0 "
sprintf_no_color "%d " 0 = "0 "
*)
(*$R
set_color_default true;
assert_equal "\027[31myolo\027[0m" (sprintf "@{<red>yolo@}");
assert_equal "yolo" (sprintf_no_color "@{<red>yolo@}");
*) *)
let ksprintf ~f fmt = let ksprintf ~f fmt =

View file

@ -140,6 +140,10 @@ val sprintf : ('a, t, unit, string) format4 -> 'a
(** Print into a string any format string that would usually be compatible (** Print into a string any format string that would usually be compatible
with {!fprintf}. Similar to {!Format.asprintf}. *) with {!fprintf}. Similar to {!Format.asprintf}. *)
val sprintf_no_color : ('a, t, unit, string) format4 -> 'a
(** Similar to {!sprintf} but never prints colors
@since NEXT_RELEASE *)
val fprintf : t -> ('a, t, unit ) format -> 'a val fprintf : t -> ('a, t, unit ) format -> 'a
(** Alias to {!Format.fprintf} (** Alias to {!Format.fprintf}
@since 0.14 *) @since 0.14 *)