Is there a Haskell code formatter?
Asked Answered
T

4

44

I used to write

data A = A {
      a :: Double
    }
    deriving(Eq, Show)

but now i prefer

data A = A {
      a :: Double
    } deriving(Eq, Show)

I think the answer will be no, but i ask anyway: is there a code formatter for Haskell?

Triatomic answered 29/7, 2011 at 7:54 Comment(2)
A few years late but hindent exists now, I've updated my accept answer with it.Armandarmanda
check out brittanyPastypat
A
57

New answer

I have now written hindent, which is written in terms of haskell-src-exts. It has Emacs and Vim support.


Old answer

There is haskell-src-exts which will parse your code and it has a pretty printing module for printing the AST to a string. E.g.

import Language.Haskell.Exts

main = interact codeFormat

codeFormat = check . fmap reformat . parseModuleWithComments where
  reformat = prettyPrint
  check r = case r of
              ParseOk a -> a
              ParseFailed loc err -> error $ show (loc,err)

Example:

λ> putStrLn $ codeFormat "module X where x = 1 where { y 1 = 2; y _ = 2 }"
module X where
x = 1
  where y 1 = 2
        y _ = 2

Alternatively you can write a pretty printer yourself (even based on the above if you just want to specialise), and then you can have whatever style you want. Replace prettyPrint with your own. The AST is very straight-forward.

Then you can hook it up with Emacs to reformat every time you hit save or something.

Armandarmanda answered 29/7, 2011 at 8:49 Comment(3)
put this in your ~./ghci: :set prompt "λ>"Gleet
Your code does not type-check with haskell-src-exts-1.13.5. Also, is there a way to pretty-print it including the comments?Sulphide
the code can be type-checked if you change to other parse function, but seems there're no support to preserve comments in the source, only collecting comments into a list, don't know why it's useful to do that.Toon
C
12

There's stylish-haskell which can do precisely what you want.

Cloak answered 1/9, 2012 at 19:23 Comment(0)
M
4

I've written a small script for that same purpose: https://github.com/djv/small/blob/master/tidy.hs I call it from vim to reformat my code.

Massorete answered 12/8, 2011 at 6:34 Comment(0)
P
2

To print an AST with comments you would need ExactPrint

exactPrint :: ExactP ast => ast SrcSpanInfo -> [Comment] -> String

but exactPrint won't pretty print your sources.

I've written a small tool you can call it with Vim as an external formatter.

prettyHS :: String -> String
prettyHS src
  = case parseFileContentsWithComments defaultParseMode src of
        ParseOk (ast, _) -> prettyPrint ast
        _ -> src
Programmer answered 10/2, 2014 at 15:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.