Personal tools

Haskell mode for Emacs

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(Tips and use)
(Key bindings and usage)
Line 54: Line 54:
 
== Key bindings and usage ==
 
== Key bindings and usage ==
   
Handy key bindings in <code>haskell-mode</code> with <code>haskell-indent</code>.
+
Key bindings in <code>haskell-mode</code> (with <code>haskell-indent</code> and <code>inf-haskell.el</code>).
   
See the documentation <code>C-h m</code> for more information:
+
Code editing keys:
   
 
*<code>C-c C-=</code> inserts an <hask>=</hask> sign and lines up type signatures and other pattern matches nicely.
 
*<code>C-c C-=</code> inserts an <hask>=</hask> sign and lines up type signatures and other pattern matches nicely.
Line 63: Line 63:
 
*<code>C-c C-w</code> inserts a where keyword
 
*<code>C-c C-w</code> inserts a where keyword
 
*<code>C-c C-.</code> aligns code over a region in a "sensible" fashion.
 
*<code>C-c C-.</code> aligns code over a region in a "sensible" fashion.
  +
  +
Haskell interpreter keys:
  +
  +
*<code>C-c C-l</code> load current buffers file into Haskell interpreter
  +
*<code>C-c C-r</code> reload current Haskell interpreter session
 
*<code>C-c C-t</code> gets :type for symbol at point, and remembers it
 
*<code>C-c C-t</code> gets :type for symbol at point, and remembers it
 
*<code>C-u C-c C-t</code> inserts a type annotation, for symbol at point, on the line above
 
*<code>C-u C-c C-t</code> inserts a type annotation, for symbol at point, on the line above
 
*<code>C-c C-i</code> gets :info for symbol at point
 
*<code>C-c C-i</code> gets :info for symbol at point
 
*<code>C-c M-.</code> find definition of (interpreted) symbol at point
 
*<code>C-c M-.</code> find definition of (interpreted) symbol at point
  +
*<code>C-c C-b</code> or <code>C-c C-z</code> switch to Haskell interpreter (starts one if needed)
  +
*<code>C-c C-d</code> find haddock documentation about symbol
  +
*<code>C-c TAB</code> query the haskell interpreter for the info of the given expression
  +
*<code>C-c C-v</code> check current buffers file with hlint
  +
  +
(See <code>C-h m</code> for more information).
  +
   
 
Here's an example for <code>C-c C-=</code>. Put your cursor after <hask>myInt</hask> and hit <code>C-c C-=</code>
 
Here's an example for <code>C-c C-=</code>. Put your cursor after <hask>myInt</hask> and hit <code>C-c C-=</code>
Line 81: Line 93:
 
You could also achieve the same effect by selecting the region and typing <code>C-c C-.</code>
 
You could also achieve the same effect by selecting the region and typing <code>C-c C-.</code>
   
You can also use Haskell-Mode to load Emacs buffers with Haskell code in either Hugs or GHC. To load something in Hugs or ghci, type <code>C-c C-l</code> to load the file. Then, you can go on to type <code>C-c C-r</code> (or simply <code>C-c C-l</code> again) to reload the current module when you have made a change.
+
You can also use haskell-mode to load Emacs buffers with Haskell code in either Hugs or GHC. To load something in Hugs or ghci, type <code>C-c C-l</code> to load the file. Then, you can go on to type <code>C-c C-r</code> (or simply <code>C-c C-l</code> again) to reload the current module when you have made a change.
   
 
== Indentation using tab cycle ==
 
== Indentation using tab cycle ==

Revision as of 16:53, 23 February 2012

haskell-mode is a major mode for Emacs and XEmacs for writing Haskell code.

Contents

1 Where to get haskell-mode

You can get haskell-mode from:

http://projects.haskell.org/haskellmode-emacs

On Debian you can type

   $ apt-get install haskell-mode

2 Installation

Download and unpack the basic mode and modules into a suitable directory, e.g. ~/lib/emacs/haskell-mode/ where ~ stands for your home directory.

Assuming you have placed the basic mode haskell-mode.el and the modules you want to use in the directory ~/lib/emacs/haskell-mode/, add the following command to your init file (~/.emacs):

   (load "~/lib/emacs/haskell-mode/haskell-site-file")

adding the following lines according to which modules you want to use:

   (add-hook 'haskell-mode-hook 'turn-on-haskell-doc-mode)
   ;;(add-hook 'haskell-mode-hook 'turn-on-haskell-indentation)
   (add-hook 'haskell-mode-hook 'turn-on-haskell-indent)
   ;;(add-hook 'haskell-mode-hook 'turn-on-haskell-simple-indent)

Note that the three indentation modules are mutually exclusive - add at most one. Note that the line of code for simple indentation is commented out (using a preceding ;) in preference for the more advanced indentation module. Installation is now complete!

3 Getting help

There is a low traffic mailing list available:

http://projects.haskell.org/cgi-bin/mailman/listinfo/haskellmode-emacs

Issue tracker is hosted at this address:

http://trac.haskell.org/haskellmode-emacs/report/1

4 Development of haskell-mode

Haskell-mode is maintained by Philip Weaver. Official project is hosted on github:

   https://github.com/pheaver/haskell-mode

Use git to get development version of haskell-mode sources:

   $ git clone https://github.com/pheaver/haskell-mode.git

5 Key bindings and usage

Key bindings in haskell-mode (with haskell-indent and inf-haskell.el).

Code editing keys:

  • C-c C-= inserts an
    =
    sign and lines up type signatures and other pattern matches nicely.
  • C-c C-| inserts a guard
  • C-c C-o inserts a guard
    | otherwise =
    and lines up existing guards
  • C-c C-w inserts a where keyword
  • C-c C-. aligns code over a region in a "sensible" fashion.

Haskell interpreter keys:

  • C-c C-l load current buffers file into Haskell interpreter
  • C-c C-r reload current Haskell interpreter session
  • C-c C-t gets :type for symbol at point, and remembers it
  • C-u C-c C-t inserts a type annotation, for symbol at point, on the line above
  • C-c C-i gets :info for symbol at point
  • C-c M-. find definition of (interpreted) symbol at point
  • C-c C-b or C-c C-z switch to Haskell interpreter (starts one if needed)
  • C-c C-d find haddock documentation about symbol
  • C-c TAB query the haskell interpreter for the info of the given expression
  • C-c C-v check current buffers file with hlint

(See C-h m for more information).


Here's an example for C-c C-=. Put your cursor after
myInt
and hit C-c C-=
blah :: Int -> Int
blah myInt

note how the function signature is reindented to match the column of the = sign.

blah       :: Int -> Int
blah myInt =

You could also achieve the same effect by selecting the region and typing C-c C-.

You can also use haskell-mode to load Emacs buffers with Haskell code in either Hugs or GHC. To load something in Hugs or ghci, type C-c C-l to load the file. Then, you can go on to type C-c C-r (or simply C-c C-l again) to reload the current module when you have made a change.

6 Indentation using tab cycle

Haskell-mode offers intelligent indentation. As Haskell source code uses indentation aware code blocks, there is usually more than one column for which indentation makes sense.

Hit tab a few times to see a few different indentation possibilities.

For example, imagine the following is open in a haskell-mode buffer, where ! represents the point:

foo :: Int -> String
foo 0 = f 4 ++ s
  where f 4 = "hello" ++ 
!

If you ask haskell-mode to indent for you, where should it indent to? There are four basic options:

  1. You want to finish off the expression you were writing in the last line. Haskell-mode indents to be underneath the " character at the beginning of "hello":
    where f 4 = "hello" ++
                !

    This is debatably a bad choice as you'd probably want to indent a bit further in to make it clear that you were carrying on an expression, but the layout rule would accept something like the following:

    where f 4 = "hello" ++
                "world"
  2. You want to add a second equation for f. Haskell-mode will indent to line up with the first argument, and fill in the f in the equation:
    where f 4 = "hello" ++
          f !
    This is an unlikely choice as the expression in the previous line isn't complete, but haskell-mode isn't smart enough to know that. (If f had been something without arguments, like
    where f = "hello"
    , then it's impossible to have more than one equation and haskell-mode won't offer this indentation level.)
  3. You want to add a second binding to the where-block. Haskell-mode indents to line up with the f:
    where f 4 = "hello" ++
          !
  4. You want to start an entirely new top-level binding. Haskell-mode indents to the first column:
    foo :: Int -> String
    foo 0 = f 4 ++ s
      where f 4 = "hello" ++
    !

These four locations can be reached by repeatedly pressing TAB. This is what's known as the tab-cycle. The innermost location is offered first, then cycling progresses outwards. Although this may seem like an inefficient system (and it is indeed a shame that Haskell's design didn't result in an unambiguous indentation system), you do quickly get used to the tab-cycle and indenting Haskell code.

Notes:

Do not use indent-region

Using indent-region is generally a bad idea on Haskell code, because it would need to know which of the tab-cycle stops you wish to choose for each line. The innermost one is chosen in each case, which often results in unusable code. Moral: just don't use indent-region with haskell-mode.

Using Unicode symbols

In Haskell code, you can end up using a lot of mathematical symbols. It is possible to hack the fontifying features of Emacs to change the ASCII textual representations of arrows and operators into the nice-looking real symbols, much like you could with TeX. The following code is a compilation of Emacs lisp code found on the Emacs wiki on the Pretty Lambda page (that page also has examples of how to apply the general Unicode defuns to other languages):

HOWEVER: due to the symbols taking up less space, this has the unfortunate side effect of changing the indentation stops that the indent key offers. This will mean that your code may not look properly aligned to those who do not have this feature in their editor, or could even mean that your code means something different to how it looks. (It is possible to contrive an example that looks correct in emacs, but actually fails to compile). The following is left for interest, but probably should NOT be used.

Haskell-mode has included this feature for a long time now, so you probably just need to (setq haskell-font-lock-symbols t) in your .emacs to use this feature.

(defun unicode-symbol (name)
   "Translate a symbolic name for a Unicode character -- e.g., LEFT-ARROW                                      
 or GREATER-THAN into an actual Unicode character code. "
   (decode-char 'ucs (case name                                             
			(left-arrow 8592)
                       (up-arrow 8593)
                       (right-arrow 8594)
                       (down-arrow 8595)                                                
			(double-vertical-bar #X2551)                  
                       (equal #X003d)
                       (not-equal #X2260)
                       (identical #X2261)
                       (not-identical #X2262)
                       (less-than #X003c)
                       (greater-than #X003e)
   		        (less-than-or-equal-to #X2264)
            		(greater-than-or-equal-to #X2265)                        
                       (logical-and #X2227)
                       (logical-or #X2228)
                       (logical-neg #X00AC)                                                  
                       ('nil #X2205)
                       (horizontal-ellipsis #X2026)
                       (double-exclamation #X203C)
                       (prime #X2032)
                       (double-prime #X2033)
                       (for-all #X2200)
                       (there-exists #X2203)
                       (element-of #X2208)              
                       (square-root #X221A)
                       (squared #X00B2)
                       (cubed #X00B3)                                            
                       (lambda #X03BB)
                       (alpha #X03B1)
                       (beta #X03B2)
                       (gamma #X03B3)
                       (delta #X03B4))))
(defun substitute-pattern-with-unicode (pattern symbol)
    "Add a font lock hook to replace the matched part of PATTERN with the                                       
     Unicode symbol SYMBOL looked up with UNICODE-SYMBOL."
    (font-lock-add-keywords
    nil `((,pattern 
           (0 (progn (compose-region (match-beginning 1) (match-end 1)
                                     ,(unicode-symbol symbol)
                                     'decompose-region)
                             nil))))))
(defun substitute-patterns-with-unicode (patterns)
   "Call SUBSTITUTE-PATTERN-WITH-UNICODE repeatedly."
   (mapcar #'(lambda (x)
               (substitute-pattern-with-unicode (car x)
                                                (cdr x)))
           patterns))
(defun haskell-unicode ()
 (substitute-patterns-with-unicode
  (list (cons "\\(<-\\)" 'left-arrow)
        (cons "\\(->\\)" 'right-arrow)
        (cons "\\(==\\)" 'identical)
        (cons "\\(/=\\)" 'not-identical)
        (cons "\\(()\\)" 'nil)
        (cons "\\<\\(sqrt\\)\\>" 'square-root)
        (cons "\\(&&\\)" 'logical-and)
        (cons "\\(||\\)" 'logical-or)
        (cons "\\<\\(not\\)\\>" 'logical-neg)
        (cons "\\(>\\)\\[^=\\]" 'greater-than)
        (cons "\\(<\\)\\[^=\\]" 'less-than)
        (cons "\\(>=\\)" 'greater-than-or-equal-to)
        (cons "\\(<=\\)" 'less-than-or-equal-to)
        (cons "\\<\\(alpha\\)\\>" 'alpha)
        (cons "\\<\\(beta\\)\\>" 'beta)
        (cons "\\<\\(gamma\\)\\>" 'gamma)
        (cons "\\<\\(delta\\)\\>" 'delta)
        (cons "\\(''\\)" 'double-prime)
        (cons "\\('\\)" 'prime)
        (cons "\\(!!\\)" 'double-exclamation)
        (cons "\\(\\.\\.\\)" 'horizontal-ellipsis))))
(add-hook 'haskell-mode-hook 'haskell-unicode)

7 Inferior Haskell Mode

inf-haskell is a major mode for interacting with an inferior Haskell process. Supported are hugs and ghci.

inf-haskell automatically finds ghci or hugs in your PATH, but Haskell interpreter name may be customized. Use Emacs' customisation group Haskell, the option is called haskell-program-name. You may set it to "/some/where/ghci.exe" or even "cabal-dev ghci".

This section contain no useful information about what inf-haskell.el does. Please improve this section by writing an informative introduction if you have knowledge about inf-haskell.el.

inf-haskell.el is _awesome_. At one point I decided to sit down and write a list of functions I'd love to have in haskell-mode, intending to write them myself. I thought I'd check to see whether the key shortcuts I'd chosen were free but I was surprised to find that every one of these functions is already provided by inf-haskell.el! Here's a selection of the highlights:

7.1 Getting set up

inf-haskell.el is usually already setup as part of the haskell-mode package, so there is nothing special to do for it. On some systems, you may need this in your .emacs:

(require 'inf-haskell)

To use the following functions, first find a .hs file, then hit C-c C-l (inferior-haskell-load-file). This fires up Hugs or Ghci (you can change this by customising haskell-program-name) on your file. Don't worry if it's not an isolated module, GHCi will load all the modules it imports as normal. You can even load entire programs this way by using C-c C-l on the Main.hs file. If everything loads without errors, you'll be able to use the functions below.

7.2 inferior-haskell-type (C-c C-t)

This command finds the type of an expression (that defaults to the text under the cursor) and prints that to the echo area.

Say you have the following code:

foo = foldr (+) 0 [1..20]

Perhaps you've forgotten the order of arguments to foldr. It's easily done; I can never remember whether the operation or final value comes first. That's easy to check: just put your point between the 'f' and 'r' of 'foldr' and hit C-c C-t RET. The type of foldr will be revealed in the echo area. This isn't particularly impressive; haskell-doc.el already did this. However, this will work for any function in the module in question or in those modules imported by the current module (including the standard libs)!

If you find that the type shown in the echo area is overwritten after a short amount of time (or any other such problem, of course), please report it as a bug. We know of no such bug, but someone apparently bumped into some such problem which he says he worked around by disabling doc-mode and decl-scan:

To turn off haskell-doc-mode, add the following to your .emacs:

(remove-hook 'haskell-mode-hook 'turn-on-haskell-doc-mode)

To turn off haskell-decl-scan, just refrain from turning it on (it's not enabled by default).

(P.S. I re-use haskell-doc-mode to save queried type info, and re-display it in the minibuffer. Disabling doc mode would disable that. -- mrd)

Another nice feature of this function is the ability to automatically insert type signatures for the function at point on the line above. For example, suppose you have the below open in Emacs, with the point represented by -!-:

-!-map _ [] = []
map f (x:xs) = f x : map f xs

And press C-u C-c C-t (note the prefix argument), it will result in the following:

map :: (a -> b) -> [a] -> [b]
-!-map _ [] = []
map f (x:xs) = f x : map f xs

7.3 inferior-haskell-info (C-c C-i)

Prints information about a function or type to the echo area. Interface to the :info GHCi/Hugs command.

Details:

  • The definition of an algebraic datatype given its name. E.g. try :info Bool. The output will contain something like data Bool = True | False.
  • The classes a type instantiates given the type's name. :info Bool will also give you the classes Bool instantiates. If you can't see an instance you think should be there, make sure the module where that instance is declared is loaded.
  • The type of a function, given its name.
  • The types of the methods of a class, and the number of arguments of that class, given the class name.
  • The expansion of a type synonym given that synonym's name.

And for all of the above, :info will also tell you the filename and line where that thing is defined. inferior-haskell-info lets you hook into this power. Use it with C-c C-i on anything within a Haskell file.

7.4 inferior-haskell-find-definition (C-c M-.)

Opens the location of a type or function.

Sometimes you just need to find the source of a function, or datatype, or class, or type synonym etc. to see how it works, and this function lets you do just that. Unfortunately, it won't work on the standard lib modules or anything that isn't 'local' to your project. This is one of the most useful functions inf-haskell.el provides.

It only works on interpreted code, for which GHCi has location information. In particular, if you have compiled versions of your files (.o and .hi) laying around then GHCi will load those, instead of interpreting your .hs files, which breaks C-c M-.. This seems like a bug, but there is an easy workaround: when compiling your code, send the .hi and .o files to somewhere GHCi won't find them. This has the added benefit of keeping your source dir cleaner. E.g. ghc -odir tmp -hidir tmp --make Main.hs.

If you want a more general find-definition, use hasktags to create a TAGS file and then use the normal emacs M-. with that. -- mrd

Note that you can also create a TAGS file using GHCi's :etags command. DavidHouse 14:38, 29 April 2007 (UTC)
Again, :etags/:ctags only works for interpreted code.
inferior-haskell-mode is missing TAB completion, which in GHCi works basically for everything (GHCi commands, modules, functions, language extensions, file names etc.). -- Oleksandr Manzyuk

8 Tricks and tweaks

8.1 Automatic unit testing

Here's a cute trick I've evolved:

I'm a great fan of unit test first, as described by eXtremeProgramming on TheOriginalWiki.

With the code below, I can press F12 and immediately run all of my unit tests, and immediately see whether they all passed or not. I've put all of my unit tests into their own file with a main function that runs the tests and gives an exitcode according to the test results. I've specified that the compile-command for that file compiles and runs the file.

This elisp code will run the compile command from the F12 key in emacs. The output will popup a new window twelve lines tall. If the compilation is successful (exitcode zero) the window goes away. If the exitcode is 1 or greater, the window stays so you can see the output.

(require 'compile)

;; this means hitting the compile button always saves the buffer
;; having to separately hit C-x C-s is a waste of time
(setq mode-compile-always-save-buffer-p t)
;; make the compile window stick at 12 lines tall
(setq compilation-window-height 12)

;; from enberg on #emacs
;; if the compilation has a zero exit code, 
;; the windows disappears after two seconds
;; otherwise it stays
(setq compilation-finish-function
      (lambda (buf str)
        (unless (string-match "exited abnormally" str)
          ;;no errors, make the compilation window go away in a few seconds
          (run-at-time
           "2 sec" nil 'delete-windows-on
           (get-buffer-create "*compilation*"))
          (message "No Compilation Errors!"))))


;; one-button testing, tada!
(global-set-key [f12] 'compile)


This Haskell code has some Emacs local variable settings at the bottom specifying what the compile-command should be for this buffer.

import HUnit
import System
 
myTestList = 
    TestList [
              "add numbers" ~: 5 ~=? (3 + 2)
             ,"add numbers" ~: 5 ~=? (3 + 3)
             ]
 
h = runTestTT myTestList
 
main = do c <- h
          putStr $ show c
          let errs = errors c
              fails = failures c
          System.exitWith (codeGet errs fails)
 
codeGet errs fails
 | fails > 0       = ExitFailure 2
 | errs > 0        = ExitFailure 1
 | otherwise       = ExitSuccess
 
-- Local Variables:
-- compile-command: "ghc --make -o Test_Demo -i/home/shae/src/haskell/libraries/ HUnitDemo.hs && ./Test_Demo"
-- End:


If you have any questions, ideas, or suggestions for this code, the maintainer would love to hear them.

8.2 Hoogle integration

From haskell-mode version 2.4 onwards, the built-in function haskell-hoogle will hoogle the identifier at point.

8.3 Using rectangular region commands

Emacs has a set of commands which operate on the region as if it were rectangular. This turns out to be extremely useful when dealing with whitespace sensitive languages.

C-x r o is "Open Rectangle". It will shift any text within the rectangle to the right side. Also see:

C-x r t is "String Rectangle". It will shift any text within the rectangle over to the right, and insert a given string prefixing all the lines in the region. If comment-region didn't already exist, you could use this instead, for example.

C-x r d is "Delete Rectangle". It will delete the contents of the rectangle and move anything on the right over.

C-x r r is "Copy Rectangle to Register". It will prompt you for a register number so it can save it for later.

C-x r g is "Insert register". This will insert the contents of the given register, overwriting whatever happens to be within the target rectangle. (So make room)

C-x r k is "Kill rectangle". Delete rectangle and save contents for:

C-x r y is "Yank rectangle". This will insert the contents of the last killed rectangle.

As with all Emacs modifier combos, you can type C-x r C-h to find out what keys are bound beginning with the C-x r prefix.

8.4 Aligning code

Emacs22 has a neat tool called: align-regexp. Select a region you want to align text within, M-x align-regexp, and type a regexp representing the alignment delimiter.

For example, I often line up my Haddock comments:

f :: a -- ^ does a
  -> Foo b -- ^ and b
  -> c -- ^ to c

Select the region, and let the regexp be: --

f :: a     -- ^ does a
  -> Foo b -- ^ and b
  -> c     -- ^ to c

Of course, this works for just about anything. Personally, I've globally bound it to C-x a r:

(global-set-key (kbd "C-x a r") 'align-regexp).

8.5 Automatically building

Emacs 21 has a package that can be installed (included by default in 22 and up) called 'FlyMake'; the idea is that as you are editing away, it occasionally calls the interpreter/compiler automatically and keeps track of whether the code works or not. You can fairly easily get it to work for Haskell as well; see FlymakeHaskell on the Emacs wiki.

8.6 Emacs Integration with Hayoo

My newly installed system would not allow me to hoogle what I wanted (no xmonad or xmonadcontrib in hoogle) so someone suggested Hayoo.

(define-key haskell-mode-map (kbd "<f3>")

 (lambda ()
  (interactive)
  (browse-url (format "http://holumbus.fh-wedel.de/hayoo/hayoo.html?query=%s&start"
                      (region-or-word-at-point)))))

region-or-word-at-point is available in the thing-at-pt+.el library.

Added 22-12-2008 - Promt for hayoo word

(defun rgr/hayoo()

 (interactive)
 (let* ((default (region-or-word-at-point))

(term (read-string (format "Hayoo for the following phrase (%s): "

                                   default))))
   (let ((term (if (zerop (length term)) default term)))
     (browse-url (format "http://holumbus.fh-wedel.de/hayoo/hayoo.html?query=%s&start" term)))))


(define-key haskell-mode-map (kbd "<f3>") 'rgr/hayoo)

Alternatively use the excellent browse-apropos-url stuff:

http://www.emacswiki.org/emacs/BrowseAproposURL#toc6

Richard

Note: Using and URL like this should work too and will give better results (not yet tested as I'm not an emacs user):

http://holumbus.fh-wedel.de/hayoo/hayoo.html?query=%s

Tbh 00:56, 25 January 2009 (UTC)

8.7 Integration with HLint

HLint could be used directly from Emacs buffer. There is hs-lint.el package (in HLint distribution, in the data subdirectory), that allows user to run HLint and navigate through errors, or apply suggestions to the source code.

This package implements `hs-lint` command, that behaves differently depending on settings. If the `hs-lint-replace-with-suggestions` variable is set to `t`, then it will ask user and apply concrete suggested change to source code, otherwise you'll be able to navigate through list of suggestions with `next-error` command. If the `hs-lint-replace-without-ask` variable is also set to `t`, then all suggestions will applied automatically.

You can also bind `hs-lint` command to some key (in this example this is `C-c l`) with following code:

(defun my-haskell-mode-hook ()

 (local-set-key "\C-cl" 'hs-lint))

(add-hook 'haskell-mode-hook 'my-haskell-mode-hook)

All settings, described above are available for customization via `hs-lint` customization group.

8.8 Folding

For folding parts of code you can use

  • hide-show.el
  • and hs-outline-level (based on py-outline-level created by Gb)

;; this gets called by outline to determine the level. Just use the length of the whitespace
 (defun hsk-outline-level ()
   (let (buffer-invisibility-spec)
     (save-excursion
       (skip-chars-forward "\t ")
       (current-column))))
;; this get called after haskell mode is enabled 
   (add-hook
    'haskell-mode-hook
    (lambda ()
       ;; outline uses this regexp to find headers. I match lines with no indent and indented
       ;; some lines, such as "--" ... "class"
        (setq outline-regexp "^[^\t ].*\\|^.*[\t ]+\\(where\\|of\\|do\\|in\\|if\\|then\\|else\\|let\\|module\\|import\\|deriving\\|instance\\|class\\)[\t\n ]")
       ;; enable our level computation
         (setq outline-level 'hsk-outline-level)
       ;; do not use their \C-c@ prefix, too hard to type. Note this overides some python mode bindings
       ;;(setq outline-minor-mode-prefix "C-c")
       ;; turn on outline mode
         (outline-minor-mode t)
       ;; initially hide all but the headers
       ;;(hide-body)
        ))

  • Also, you can use toggle-selective-display for global folding

;; folding for all rows, starting on the current column
   (defun toggle-selective-display (column)
     (interactive "P")
     (set-selective-display
      (or column
          (unless selective-display
            (1+ (current-column))))))
 (global-set-key (kbd "C-x $") 'toggle-selective-display)
   (defun toggle-hiding (column)
     (interactive "P")
     (if hs-minor-mode
         (if (condition-case nil
                 (hs-toggle-hiding)
               (error t))
             (hs-show-all))
       (toggle-selective-display column)))
 (global-set-key (kbd "C-@") 'toggle-hiding)

  • and narrowing capabilities for folding the rest of code

   (put 'narrow-to-defun 'disabled nil)
   (put 'narrow-to-page 'disabled nil)
   (put 'narrow-to-region 'disabled nil)

  • or folding-mode, if you do not mind add markers such as {-{{{-} and {-}}}-} in code.

8.9 Speedbar

Emacs has a SpeedBar which works quite nice together with haskell-mode and also detects syntactic elements such as variables, imports, instances, classes.

Just add

   (require 'speedbar)
   (speedbar-add-supported-extension ".hs")

to your .emacs file and fire up speedbar with M-x speedbar.

8.10 Literate Haskell

Literate Haskell is supported directly by haskell-mode without having to use MMM or other tricks that may be found in old mailing list postings, so ignore that out of date information. If you load an .lhs file, then literate haskell should automatically work. If it doesn't then you should make sure that you are using a current version of haskell-mode and that the correct literate type is selected. You can switch between bird (the default) and tex by typing:

M-x customize-variable RET haskell-literate-default

8.11 Keeping Imports sorted and aligned

See this screencast about making imports automatically alphabetically ordered and indented.

The extension modules for that can be found at https://github.com/chrisdone/haskell-mode-exts#readme

8.12 Scion Integration

The Scion IDE library can be used to complement the haskell-mode with additional features, such as (quoting the documentation):

  • Highlights error messages directly in the source, together with a tool-tip
  • Optional on-the-fly typechecking (idle-time based, or whenever file is saved)
  • Completion on `LANGUAGE` names, pragmas, external module names and `OPTIONS`-flags
  • Go to definition sites of symbols at point

Documentation on how to use `scion.el` can be found in the `README.markdown` file.

The primary repository is at nominolo/scion. An experimental fork featuring GHC7 support can be found at hvr/scion. The hackage version is probably outdated, so better use the upstream version.

8.13 HSnippets, YASnippet snippets

YASnippet is a template system for Emacs. It allows you to type an abbreviation and automatically expand it into function templates.

HSnippets is designed for use with haskell-indentation-mode, i.e. it does not do any indentation itself, but relies on the mode (or the user) to do so. Also note that the snippets never add any unnecessary lines to the code listing, only the lines taken up by the snippet itself, leaving the user to manage empty space themselves...