From 9045fcca0b410a7f010a7b8748d57ecb1b4c52ee Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Thu, 3 Nov 2016 15:48:21 +0100 Subject: [PATCH] add `CCFormat.{with_color_sf,fprintf_dyn_color,sprintf_dyn_color}` more dynamic way of adding colors, switching colors on/off, etc. --- src/core/CCFormat.ml | 20 ++++++++++++++++++++ src/core/CCFormat.mli | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index 8e356930..9b1fddaa 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -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" diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index dd3f0194..9db0a194 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -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 "@{%a@}" + CCFormat.Dump.(list int) [1;2;3] |> print_endline;; + + (* without colors *) + CCFormat.sprintf_dyn_color ~colors:false "@{%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 ->