lambda.xy.x February 2016

Indentation of boxes in Format.fprintf

Please consider the function f:

open Format

let rec f i = match i with
  | x when x <= 0 -> ()
  | i ->
    pp_open_hovbox std_formatter 2;
    printf "This is line %d@." i; 
    f (i-1);
    printf "This is line %d@." i; 
    close_box ();
    ()

It recursively opens hovboxes and prints something, followed by a newline hint (@.). When I call the f 3, i obtain the following output:

This is line 3
This is line 2
This is line 1
This is line 1
This is line 2
This is line 3

but I expected:

This is line 3
  This is line 2
    This is line 1
    This is line 1
  This is line 2
This is line 3

Can you explain why I obtain the first output and what I need to change to obtain the second one?

Answers


Daniel Bünzli February 2016

@. is not a newline hint, it is equivalent to print_newline which calls print_flush which closes all opened boxes and follows by a new line.

If you want to print line by line with Format you should open a vertical box with open_vbox and use print_cut ("@,") whenever you want to output a new line.


ivg February 2016

Instead of using @. you should use @\n specificator. The former, will flush the formatter and output a hard newline, actually breaking your pretty printing. It is intended to be used at the end of document, and, since it is not actually composable, I would warn against using it at all.

With @\n, you will get an output that is much closer to what you're expecting:

This is line 3
  This is line 2
    This is line 1
      This is line 1
      This is line 2
    This is line 3

The same output, by the way, can be obtained by using vbox and emitting @; good break hints, that is better.

Post Status

Asked in February 2016
Viewed 1,713 times
Voted 11
Answered 2 times

Search




Leave an answer