diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index 5aab90db..20d68887 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -276,18 +276,29 @@ let with_colorf s out fmt = (fun out -> Format.pp_close_tag out ()) out fmt -let sprintf format = +(* c: whether colors are enabled *) +let sprintf_ c format = let buf = Buffer.create 64 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 (fun _fmt -> Format.pp_print_flush fmt (); Buffer.contents buf) fmt format +let sprintf fmt = sprintf_ true fmt +let sprintf_no_color fmt = sprintf_ false fmt + (*$T sprintf "yolo %s %d" "a b" 42 = "yolo a b 42" sprintf "%d " 0 = "0 " + sprintf_no_color "%d " 0 = "0 " +*) + +(*$R + set_color_default true; + assert_equal "\027[31myolo\027[0m" (sprintf "@{yolo@}"); + assert_equal "yolo" (sprintf_no_color "@{yolo@}"); *) let ksprintf ~f fmt = diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index caf22b4f..efbd6eeb 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -140,6 +140,10 @@ val sprintf : ('a, t, unit, string) format4 -> 'a (** Print into a string any format string that would usually be compatible 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 (** Alias to {!Format.fprintf} @since 0.14 *)