Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Haskell code formatter?

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?

like image 740
LennyStackOverflow Avatar asked Jul 29 '11 07:07

LennyStackOverflow


3 Answers

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.

like image 108
Christopher Done Avatar answered Oct 25 '22 13:10

Christopher Done


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

like image 39
user239558 Avatar answered Oct 25 '22 14:10

user239558


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.

like image 4
Daniel Avatar answered Oct 25 '22 13:10

Daniel