From 9cca745fcf37ceb168c75cb58fcde5bd6da193ea Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Tue, 18 Apr 2017 21:19:50 +0200 Subject: [PATCH] add `CCFormat.text` (close #111) --- src/core/CCFormat.ml | 41 +++++++++++++++++++++++++++++++++++++++++ src/core/CCFormat.mli | 6 ++++++ 2 files changed, 47 insertions(+) diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index f82cbebe..12bd744d 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -44,6 +44,47 @@ let newline = Format.pp_force_newline let substring out (s,i,len): unit = string out (String.sub s i len) +let text out (s:string): unit = + let len = String.length s in + let i = ref 0 in + let search_ c = + try Some (String.index_from s !i c) with Not_found -> None + in + while !i < len do + let j_newline = search_ '\n' in + let j_space = search_ ' ' in + let on_newline j = + substring out (s, !i, j - !i); + newline out (); + i := j + 1 + and on_space j = + substring out (s, !i, j - !i); + Format.pp_print_space out (); + i := j + 1 + in + begin match j_newline, j_space with + | None, None -> + (* done *) + substring out (s, !i, len - !i); + i := len + | Some j, None -> on_newline j + | None, Some j -> on_space j + | Some j1, Some j2 -> + if j1CCFormat.sprintf "%S" s) + "a\nb\nc" (sprintf_no_color "@[%a@]%!" text "a b c") + "a b\nc" (sprintf_no_color "@[%a@]%!" text "a b\nc") + *) + +(*$Q + Q.(printable_string) (fun s -> \ + sprintf_no_color "@[%a@]%!" text s = \ + sprintf_no_color "@[%a@]%!" Format.pp_print_text s) +*) + let list ?(sep=return ",@ ") pp fmt l = let rec pp_list l = match l with | x::((_::_) as l) -> diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index a40e20a2..847de339 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -34,6 +34,12 @@ val substring : (string * int * int) printer describe a proper substring. @since NEXT_RELEASE *) +val text : string printer +(** Print string, but replacing spaces with breaks and newlines + with {!newline}. + See [pp_print_text] on recent versions of OCaml. + @since NEXT_RELEASE *) + val char : char printer (** @since 0.14 *) val int32 : int32 printer (** @since 0.14 *) val int64 : int64 printer (** @since 0.14 *)