easy-format icon indicating copy to clipboard operation
easy-format copied to clipboard

Separator before closing?

Open yunxing opened this issue 8 years ago • 3 comments

Is it possible to support adding a separator before closing so we can support trailing comma like this?

[
  1,
  2,
];

or

[ 1, 2, ]

?

yunxing avatar Mar 12 '16 02:03 yunxing

This might be a dupe of this issue: https://github.com/mjambon/easy-format/issues/2

jordwalke avatar Mar 12 '16 06:03 jordwalke

If the trailing comma should always be printed no matter how the code gets formatted, it's much simpler than issue #2.

Currently, one way of achieving this is:

#use "topfind";;
#require "easy-format";;

open Easy_format

let add_trailing_string x s =
  List (
    ("", "", "", { list with
                   space_after_opening = false;
                   space_after_separator = false;
                   space_before_closing = false;
                   wrap_body = `No_breaks }),
    [x; Atom (s, atom)]
  )

let () =
  let element = Atom (String.make 90 'a', atom) in
  let element_with_sticky_comma = add_trailing_string element "," in
  let elements =
    List (
      ("[", "", "]", list),
      [element_with_sticky_comma; element_with_sticky_comma]
    ) in
  Pretty.to_stdout elements

Output:

[
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
]

It looks like a good idea to add a trailing_separator option to list_param to avoid having to go through this.

mjambon avatar Mar 13 '16 03:03 mjambon

@mjambon for my usecase (printing JavaScript) we need to only print the trailing comma if we break. I tried to implement it with the above approach and using Format.pp_print_if_newline inside a Custom node but i was unable to get it to break correctly, it would never print if part of the list and if i moved it to after the list it would always print :/

This is what i was using:

let string_on_break s =>
    Custom (
      fun fmt => {
        Format.pp_print_if_newline fmt ();
        Format.pp_print_string fmt s
      }
    );

I did manage to implement with a hack (as suggested by @jordwalke, but not a good long term solution) where we insert a token in places we potental want trailing commas and then after printing from EasyFormat to string we find the instances of the token followed by a "\n" and replace with ",\n" otherwise strip it. It mostly works but does mess with the indentation a little since you remove chars after doing all the breaking.

pieterv avatar Dec 29 '16 19:12 pieterv