[Haskell-cafe] Code folding in Emacs

Johan Tibell johan.tibell at gmail.com
Mon Jan 14 05:41:48 EST 2008


It would be pretty neat for Haskell hacking if the Emacs Haskell mode
could do the following. Imagine you have written some code like so:

-- | The parse state.
data S = S {-# UNPACK #-} !B.ByteString  -- current chunk
           L.ByteString                  -- rest of the input
           {-# UNPACK #-} !Int64         -- bytes read

-- | The 'Parser' monad is just a State monad carrying around the
-- input ByteString.
newtype Parser a = Parser { unParser :: S -> Consumed (Reply a) }

-- | Match byte that fulfills predicate.
satisfy :: (Word8 -> Bool)  -- ^ Predicate that byte must fulfill.
        -> Parser Word8     -- ^ Matched byte.
satisfy p =
    Parser $ \(S s ss pos) ->
        if B.null s
          then (if L.null ss
            then Empty (Error (ParseError pos))
            else case L.splitAt 1 ss of
                   (consuming,rest) ->
                       let now = B.concat . L.toChunks $ consuming
                           b   = B.head now
                       in
                       if p b then
                           Consumed $ Ok b (S (B.tail now) rest (pos + 1))
                         else Empty $ Error $ ParseError pos
               )
          else let b = B.head s in
               if p b then Consumed $ Ok (B.head s) (S (B.tail s) ss (pos + 1))
               else Empty $ Error $ ParseError pos

Now you want an overview of your source file. One way would be to
replace all the implementation parts with ellipses, like so:

-- | The parse state.
data S = S {-# UNPACK #-} !B.ByteString  -- current chunk
           L.ByteString                  -- rest of the input
           {-# UNPACK #-} !Int64         -- bytes read

-- | The 'Parser' monad is just a State monad carrying around the
-- input ByteString.
newtype Parser a = Parser { unParser :: S -> Consumed (Reply a) }

-- | Match byte that fulfills predicate.
satisfy :: (Word8 -> Bool)  -- ^ Predicate that byte must fulfill.
        -> Parser Word8     -- ^ Matched byte.
satisfy p = ...

Binding a haskell-fold-source function to a key chain would enable you
to get a quick overview of your module showing only the comments and
type signatures. I've used the little function from
http://emacs.wordpress.com/2007/01/16/quick-and-dirty-code-folding/
but it doesn't work well together with indented type signatures like
in the example above.

Anyone with strong Emacs-fu that knows how one could implement such a function?

-- Johan


More information about the Haskell-Cafe mailing list