add CCFormat.{with_color_sf,fprintf_dyn_color,sprintf_dyn_color}

more dynamic way of adding colors, switching colors on/off, etc.
This commit is contained in:
Simon Cruanes 2016-11-03 15:48:21 +01:00
parent 0d9d17d5db
commit 9045fcca0b
2 changed files with 48 additions and 0 deletions

View file

@ -279,8 +279,28 @@ let sprintf_ c format =
fmt
format
let with_color_sf s fmt =
let buf = Buffer.create 64 in
let out = Format.formatter_of_buffer buf in
if !color_enabled then set_color_tag_handling out;
Format.pp_open_tag out s;
Format.kfprintf
(fun out ->
Format.pp_close_tag out ();
Format.pp_print_flush out ();
Buffer.contents buf)
out fmt
let sprintf fmt = sprintf_ true fmt
let sprintf_no_color fmt = sprintf_ false fmt
let sprintf_dyn_color ~colors fmt = sprintf_ colors fmt
let fprintf_dyn_color ~colors out fmt =
let old_tags = Format.pp_get_mark_tags out () in
Format.pp_set_mark_tags out colors; (* enable/disable tags *)
Format.kfprintf
(fun out -> Format.pp_set_mark_tags out old_tags)
out fmt
(*$T
sprintf "yolo %s %d" "a b" 42 = "yolo a b 42"

View file

@ -137,6 +137,16 @@ val with_colorf : string -> t -> ('a, t, unit, unit) format4 -> 'a
{b status: experimental}
@since 0.16 *)
val with_color_sf : string -> ('a, t, unit, string) format4 -> 'a
(** [with_color_sf "Blue" out "%s %d" "yolo" 42] will behave like
{!sprintf}, but wrapping the content with the given style
Example:
{[
CCFormat.with_color_sf "red" "%a" CCFormat.Dump.(list int) [1;2;3] |> print_endline;;
]}
{b status: experimental}
@since NEXT_RELEASE *)
(** {2 IO} *)
val output : t -> 'a printer -> 'a -> unit
@ -153,10 +163,28 @@ val sprintf_no_color : ('a, t, unit, string) format4 -> 'a
(** Similar to {!sprintf} but never prints colors
@since 0.16 *)
val sprintf_dyn_color : colors:bool -> ('a, t, unit, string) format4 -> 'a
(** Similar to {!sprintf} but enable/disable colors depending on [colors].
Example:
{[
(* with colors *)
CCFormat.sprintf_dyn_color ~colors:true "@{<Red>%a@}"
CCFormat.Dump.(list int) [1;2;3] |> print_endline;;
(* without colors *)
CCFormat.sprintf_dyn_color ~colors:false "@{<Red>%a@}"
CCFormat.Dump.(list int) [1;2;3] |> print_endline;;
]}
@since NEXT_RELEASE *)
val fprintf : t -> ('a, t, unit ) format -> 'a
(** Alias to {!Format.fprintf}
@since 0.14 *)
val fprintf_dyn_color : colors:bool -> t -> ('a, t, unit ) format -> 'a
(** Similar to {!fprintf} but enable/disable colors depending on [colors]
@since NEXT_RELEASE *)
val ksprintf :
f:(string -> 'b) ->
('a, Format.formatter, unit, 'b) format4 ->