lue-bird/elm-syntax-format/1.0.0

NOTE: the latest version is 1.1.20

Pretty print an elm-syntax tree as elm-format would (breaking lines and inserting comments in the right places).

import ElmSyntaxPrint
import Elm.Parser -- from stil4m/elm-syntax

"""
module   Sample  exposing(..)
plus2 (n)= {- this adds 2-} n
    + 2
"""
    |> Elm.Parser.parseToFile
    |> Result.map
        (\syntaxModule ->
            syntaxModule
                |> ElmSyntaxPrint.module_
                |> ElmSyntaxPrint.toString
        )
-->
Ok """module Sample exposing (..)

plus2 n =
    {- this adds 2 -}
    n
        + 2
"""

If you want to generate code, better bets are mdgriffith/elm-codegen or the-sett/elm-syntax-dsl.

known deviations in printing

  • ranges of of, exposing and as are needed to determine whether they should be on the next line or at the end of last line
  • ranges of =, :, ,, |, ->, the operators and the keywords are needed to determine whether comments are before or after
  • function types outputting a parenthesized function do not preserve the parens because type parens are not stored in the syntax tree
  • comments before/after parenthesized types will get eaten because type parens are not stored in the syntax tree
  • some floats in exponent representation are formatted to without it and the other way around
  • handling int (and float?) overflow (elm-format itself seems to have issues here, too https://github.com/avh4/elm-format/issues/635)
  • formatting documentation markdown

Please report others you notice <3

performance problems?

Great performance is not a primary goal but if you notice it's unusable for your use case, please open an issue.

Ideas:

  • combine LineSpreads lazily
  • pre-filter comments per declaration
  • pre-define prints for static parts like symbols
  • convert Print to defunctionalized (this will likely make Print.lineSpread faster)