Disabling Format wrapping

Hi fellow Caml-wranglers,

I ran across an unexpected behavior while trying do disable wrapping in Format. From what I understand the wrapping in Format is dependent on the value of margin, thus setting it to a large value (like Format.pp_infinity) should disable wrapping.

Format.printf "@[<hov>This is a long text that I want to print aaa bbb@ ccc ddd eee @[<hov>fff gg hh iii jjjj@] kkk lll mmm n o@]";;

This will wrap at the space hint. So

Format.set_margin 100000;
Format.printf "@[<hov>This is a long text that I want to print aaa bbb@ ccc ddd eee @[<hov>fff gg hh iii jjjj@] kkk lll mmm n o@]";;

this makes it all print out in one line. So far so good. But if I try the same with Format.asprintf:

Format.set_margin 100000;
Format.asprintf "@[<hov 2>This is a long text that I want to print aaa bbb@  ccc ddd eee @[<hov>fff gg hh iii jjjj@] kkk lll mmm n o@]";;

I get a \n in my string, thus it is wrapping, despite the margin setting.

On the other hand, if I specifically set the margin in the format string, it works properly:

Format.asprintf "%a@[<hov 2>This is a long text that I want to print aaa bbb@ ccc ddd eee @[<hov>fff gg hh iii jjjj@] kkk lll mmm n o@]" Format.pp_set_margin Int.max_int;;

What is going on and how can I disable the wrapping manually without having to annotate every format string?

Format.asprintf creates its own formatter each time it is called; and I do not think it is possible to modify the options of that formatter (like the margin).

But you can easily cook your own formatter using Format.formatter_of_buffer, change the margin with Format.pp_set_margin, and print to it using Format.fprintf.

Cheers,
Nicolas

1 Like

It is possible to get ahold of the formatter asprintf uses and set the margin:

  Format.asprintf "%tblah" (fun ppf ->
      Format.pp_set_margin ppf Format.pp_infinity ;
      Format.pp_set_max_indent ppf (Format.pp_infinity - 1) )
1 Like

Thanks you two, @nojb for the explanation and @jjb for the workaround. Ended up landing something that uses pp_set_margin in a place that gets called by all places that I cared about.