Haskell mode for Emacs

From HaskellWiki

haskell-mode is a major mode for Emacs and XEmacs specifically for writing Haskell code. You can get haskell-mode from the web page: http://projects.haskell.org/haskellmode-emacs/ or on Debian you can type apt-get install haskell-mode (although this currently doesn't have the latest version). It is currently maintained by Svein Ove Aas[1].

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!

2.1 Inferior Mode

Normally, inf-haskell automatically finds ghci or hugs in your PATH, but if that's not the case (common under Windows), or if you need to specify your preference, just tell Emacs which executable to use with:

(setq haskell-program-name "/some/where/ghci.exe")

You can also use cabal-dev ghci inside Emacs:

(setq haskell-program-name "cabal-dev ghci")

If you want to use different settings when you use Cygwin Emacs and NTEmacs,
you can test the value of `system-type':

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.

3.1 Indentation

Indentation is one thing that nearly all programming modes provide. However, indenting Haskell code is very hard: for a given line, there are nearly always more than column for which indentation makes sense. 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:

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"

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.)

You want to add a second binding to the where-block. Haskell-mode indents to line up with the f:

where f 4="hello"++!

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.

3.1.1 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.

3.1.2 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.

4 Bugs

Bugs and feature requests should be sent to the maintainer Svein Ove Aas.
For people using the Debian package, Debian maintains a list of bugs for haskell-mode, they should be reported there.

4.1 XEmacs

On some the GNU/Linux systems with XEmacs, admittedly, only verified on Ubuntu and Debian and with haskell-mode 2.2, there is a system function missing that interferes with automatic indenting. Secondly, there seems to be an issue with setting the haskell-default-face to nil.

4.1.1 line-end-position

To fix this, find where the haskell mode package is installed on your system. (Usually /usr/share/emacs/site-lisp/haskell-mode). Edit the file haskell-indent.el and add the lines:

(eval-and-compile
;; If `line-end-position' isn't available provide one.
(unless (fboundp 'line-end-position)
(defun line-end-position (&optional n)
"Return the `point' of the end of the current line."
(save-excursion
(end-of-line n)
(point)))))

right after the comments at the top. That should fix the issue.

4.1.2 haskell-default-face

This one shows up when typing in code (at various spots - most often when typing a qualified function, such as

List.map

.)

To fix this one, edit the file haskell-font-lock.el. Look for the line that says:

(defvar haskell-default-face nil)

and change this to

(defvar haskell-default-face 'default)

In my version, this is line 168.

Then, look for the line that says:

(,qvarid 0 haskell-default-face)

and change it to

(,qvarid 0 (symbol-value 'haskell-default-face))

For me, this is line 326 of the file.
YMMV - hope this helps.

5 inf-haskell.el: the best thing since the breadknife

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:

5.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.

5.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:

5.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.

5.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)

6 Tricks and tweaks

6.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.

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

6.2 Hoogle integration

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

6.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.

6.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).

6.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.

6.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.

6.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.

6.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))))

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

6.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.

6.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:

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.

6.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...