feat(CCFormat): add string_lines combinator

This commit is contained in:
Simon Cruanes 2021-02-26 17:25:33 -05:00
parent 89d6feed98
commit 5593e28431
2 changed files with 25 additions and 0 deletions

View file

@ -56,6 +56,23 @@ let text = Format.pp_print_text
"a b\nc" (sprintf_no_color "@[<h>%a@]%!" text "a b\nc") "a b\nc" (sprintf_no_color "@[<h>%a@]%!" text "a b\nc")
*) *)
let string_lines out (s:string) : unit =
fprintf out "@[<v>";
let i = ref 0 in
let n = String.length s in
while !i < n do
let j =
try String.index_from s !i '\n' with Not_found -> n in
if !i>0 then fprintf out "@,";
substring out (s, !i, j - !i);
i := j+1;
done;
fprintf out "@]"
(*$= & ~printer:(fun s->CCFormat.sprintf "%S" s)
"(a\n b\n c)" (sprintf_no_color "(@[<v>%a@])" string_lines "a\nb\nc")
*)
let list ?(sep=return ",@ ") pp fmt l = let list ?(sep=return ",@ ") pp fmt l =
let rec pp_list l = match l with let rec pp_list l = match l with
| x::((_::_) as l) -> | x::((_::_) as l) ->

View file

@ -63,6 +63,14 @@ val text : string printer
See [pp_print_text] on recent versions of OCaml. See [pp_print_text] on recent versions of OCaml.
@since 1.2 *) @since 1.2 *)
val string_lines : string printer
(** [string_lines out s] prints [s] with all newlines (['\n']) replaced by
a cut, in a vertical box. It does {b NOT} insert breakable spaces in
place of spaces, unlike {!text}.
This means an already formatted string can be displayed inside another
formatter without mangling the indentation.
@since NEXT_RELEASE *)
val char : char printer (** @since 0.14 *) val char : char printer (** @since 0.14 *)
val int32 : int32 printer (** @since 0.14 *) val int32 : int32 printer (** @since 0.14 *)