dbuenzli / fmt

OCaml Format pretty-printer combinators
http://erratique.ch/software/fmt
ISC License
71 stars 26 forks source link

Fmt.styled doesn't return a formatter of the same type #55

Closed terencode closed 2 years ago

terencode commented 2 years ago

According to the documentation, applying Fmt.styled to a formatter returns one of the same type :

val styled : style -> 'a t -> 'a t styled s pp formats like pp but styled with s.

but in practice, the 'a is replaced by unit :

Format.formatter ->
('a, Format.formatter, unit, unit, unit, unit) format6 -> 'a

becomes

Format.formatter ->
(unit, Format.formatter, unit, unit, unit, unit) format6 -> unit

and is thus only usable with simple strings.

Here is an example I would expect to work but doesn't :

Fmt.set_style_renderer  Fmt.stdout `Ansi_tty;

let pf = Fmt.pf in
pf Fmt.stdout "Hello, %s\n" "World";
let pf = Fmt.styled `Red pf  in
pf Fmt.stdout "Hello, %s\n" "World"

I had the same behaviour on OCaml 4.08.1 & 4.14.0

dbuenzli commented 2 years ago

Not sure I understand you. The definition of 'a Fmt.t is:

type 'a t = Format.formatter -> 'a -> unit
terencode commented 2 years ago

Ok I might have wrongly understood how this works. How would I go about doing what I want in the example, that is, print to stdout a formatted string with a specific style ?

dbuenzli commented 2 years ago

Something like that:

let pp_hello ppf n = Fmt.pf ppf "Hello %s" n
let pp_red_hello = Fmt.styled (`Fg `Red) pp_hello
let () = 
  let () = Fmt.set_style_renderer Fmt.stdout `Ansi_tty in 
  Fmt.pr "%a" pp_red_hello "World"

If you have further questions about using the library, please ask them on https://discuss.ocaml.org/ (you can log in with your github account).

terencode commented 2 years ago

Ok, thanks for your help. I will use discuss next time (I just created an account).