pax_global_header00006660000000000000000000000064122521003720014504gustar00rootroot0000000000000052 comment=6a4d4bdd178c65183a715c7729941a0b8fe5f253 haskell-mode-13.10/000077500000000000000000000000001225210037200140555ustar00rootroot00000000000000haskell-mode-13.10/.gitignore000066400000000000000000000001161225210037200160430ustar00rootroot00000000000000*.elc *~ haskell-mode-autoloads.el haskell-mode.info haskell-mode.tmp.texi dirhaskell-mode-13.10/.travis.yml000066400000000000000000000016571225210037200161770ustar00rootroot00000000000000language: emacs-lisp env: matrix: - EMACS=emacs23 - EMACS=emacs24 - EMACS=emacs-snapshot matrix: allow_failures: - env: - EMACS=emacs-snapshot install: - if [ "$EMACS" = "emacs23" ]; then sudo apt-get update -qq && sudo apt-get install -qq emacs23-gtk emacs23-el; fi - if [ "$EMACS" = "emacs24" ]; then sudo add-apt-repository -y ppa:cassou/emacs && sudo apt-get update -qq && sudo apt-get install -qq emacs24 emacs24-el; fi - if [ "$EMACS" = "emacs-snapshot" ]; then sudo add-apt-repository -y ppa:cassou/emacs && sudo apt-get update -qq && sudo apt-get install -qq emacs-snapshot && sudo apt-get install -qq emacs-snapshot-el emacs-snapshot-gtk; fi script: lsb_release -a && $EMACS --version && make EMACS=$EMACS check notifications: email: false # Local Variables: # indent-tabs-mode: nil # coding: utf-8 # End: haskell-mode-13.10/Makefile000066400000000000000000000074021225210037200155200ustar00rootroot00000000000000VERSION = $(shell git describe --tags --match 'v[0-9]*' --abbrev=0 | sed 's/^v//;s/\.0*/./g') GIT_VERSION = $(shell git describe --tags --match 'v[0-9]*' --long --dirty | sed 's/^v//') INSTALL_INFO = install-info EMACS = emacs EFLAGS = BATCH = $(EMACS) $(EFLAGS) --batch -Q -L . SUBST_ATAT = sed -e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g;s/@GIT_VERSION@/$(GIT_VERSION)/g;s/@@VERSION@@/$(VERSION)/g;s/@VERSION@/$(VERSION)/g' ELFILES = \ ghc-core.el \ haskell-align-imports.el \ haskell-c.el \ haskell-cabal.el \ haskell-checkers.el \ haskell-compat.el \ haskell-compile.el \ haskell-decl-scan.el \ haskell-doc.el \ haskell-font-lock.el \ haskell-indent.el \ haskell-indentation.el \ haskell-interactive-mode.el \ haskell-menu.el \ haskell-mode.el \ haskell-move-nested.el \ haskell-navigate-imports.el \ haskell-package.el \ haskell-process.el \ haskell-session.el \ haskell-show.el \ haskell-simple-indent.el \ haskell-sort-imports.el \ haskell-string.el \ haskell-str.el \ haskell-unicode-input-method.el \ haskell-utils.el \ haskell-yas.el \ haskell-presentation-mode.el \ inf-haskell.el ELCFILES = $(ELFILES:.el=.elc) AUTOLOADS = haskell-mode-autoloads.el PKG_DIST_FILES = $(ELFILES) logo.svg NEWS haskell-mode.info dir PKG_TAR = haskell-mode-$(VERSION).tar ELCHECKS=$(addprefix check-, $(ELFILES:.el=)) %.elc: %.el @$(BATCH) \ --eval "(byte-compile-disable-warning 'cl-functions)" \ -f batch-byte-compile $< .PHONY: all compile info clean check $(ELCHECKS) elpa package all: compile $(AUTOLOADS) info compile: $(ELCFILES) $(ELCHECKS): check-%: %.el @$(BATCH) --eval '(when (check-declare-file "$*.el") (error "check-declare failed"))' @$(BATCH) \ --eval "(setq byte-compile-error-on-warn t)" \ --eval "(byte-compile-disable-warning 'cl-functions)" \ -f batch-byte-compile $*.el @$(RM) $*.elc @if [ -f "$(<:%.el=tests/%-tests.el)" ]; then \ if $(BATCH) --eval "(require 'ert)" 2> /dev/null; then \ echo; \ $(BATCH) -l "$(<:%.el=tests/%-tests.el)" -f ert-run-tests-batch-and-exit; \ else \ echo "ERT not available, skipping unit tests"; \ fi; \ fi @echo "--" check: clean $(ELCHECKS) @echo "checks passed!" clean: $(RM) $(ELCFILES) $(AUTOLOADS) $(AUTOLOADS:.el=.elc) $(PKG_TAR) haskell-mode.tmp.texi haskell-mode.info dir info: haskell-mode.info dir dir: haskell-mode.info $(INSTALL_INFO) --dir=$@ $< haskell-mode.tmp.texi: haskell-mode.texi $(SUBST_ATAT) < haskell-mode.texi > haskell-mode.tmp.texi haskell-mode.info: haskell-mode.tmp.texi $(MAKEINFO) $(MAKEINFO_FLAGS) -o $@ $< haskell-mode.html: haskell-mode.tmp.texi $(MAKEINFO) $(MAKEINFO_FLAGS) --html --no-split -o $@ $< # Generate ELPA-compatible package package: $(PKG_TAR) elpa: $(PKG_TAR) $(PKG_TAR): $(PKG_DIST_FILES) haskell-mode-pkg.el.in rm -rf haskell-mode-$(VERSION) mkdir haskell-mode-$(VERSION) cp $(PKG_DIST_FILES) haskell-mode-$(VERSION)/ $(SUBST_ATAT) < haskell-mode-pkg.el.in > haskell-mode-$(VERSION)/haskell-mode-pkg.el $(SUBST_ATAT) < haskell-mode.el > haskell-mode-$(VERSION)/haskell-mode.el (sed -n -e '/^;;; Commentary/,/^;;;/p' | egrep '^;;( |$$)' | cut -c4-) < haskell-mode.el > haskell-mode-$(VERSION)/README tar cvf $@ haskell-mode-$(VERSION) rm -rf haskell-mode-$(VERSION) @echo @echo "Created ELPA compatible distribution package '$@' from $(GIT_VERSION)" $(AUTOLOADS): $(ELFILES) haskell-mode.elc $(BATCH) \ --eval '(setq make-backup-files nil)' \ --eval '(setq generated-autoload-file "$(CURDIR)/$@")' \ -f batch-update-autoloads "." # HACK: embed version number into .elc file haskell-mode.elc: haskell-mode.el $(SUBST_ATAT) < haskell-mode.el > haskell-mode.tmp.el @$(BATCH) --eval "(byte-compile-disable-warning 'cl-functions)" -f batch-byte-compile haskell-mode.tmp.el mv haskell-mode.tmp.elc haskell-mode.elc $(RM) haskell-mode.tmp.el haskell-mode-13.10/NEWS000066400000000000000000000356231225210037200145650ustar00rootroot00000000000000Haskell Mode NEWS -*- org -*- This file uses Org mode. Some useful (default) key-bindings: - Use "C-c C-n"/"C-c C-p" to jump to next/prev heading - Use "" to expand/collapse nodes - Use "" to cycle visibility of all nodes - Use "C-c C-o" to open links * Changes in 13.10 - Small fix for haskell-simple-indent: Certain indentation situations cause valname-string to be nil, which haskell-trim did not handle gracefully (naturally, since nil != ""). - Luke Hoersten's Shnippet merged in under snippets/. - haskell-presentation-mode is now a haskell-mode derived mode. - Small improvement to haskell-process-do-info (works on constructors now and underscored names). - Add haskell-indent-spaces configuration variable. - The command string to run cabal commands is slightly more configurable. See: C-h f haskell-process-do-cabal-format-string * Changes in 13.8 See also [[https://github.com/haskell/haskell-mode/compare/v13.07...v13.08][detailed Git history]]. - Make `haskell-simple-indent-mode' a proper minor mode with `SInd` as mode-line lighter - Support popular "λ> " prompt in inf-haskell by default - Hide internal `*print-haskell-mode*' buffers (used when `haskell-interactive-mode-eval-mode' is active) - Add tab-completion support for haskell-interactive-mode (requires `:complete' command support in GHCi) - Add support to `haskell-process-do-info` to perform `:browse!` query on module name when called on import statement line - `haskell-decl-scan-mode': - New customize group `haskell-decl-scan' - New flag `haskell-decl-scan-bindings-as-variables' for controlling whether to put value bindings into the "Variables" category. - New flag `haskell-decl-scan-add-to-menubar' for controlling whether to add "Declarations" menu entry to menu bar. - New manual section node `(haskell-mode)haskell-decl-scan-mode' - Add support for [[http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#lambda-case][LambdaCase]] syntax extension to `haskell-indentation` - Change `haskell-indentation-mode' to never jump back a whole line when pressing DEL. The old behavior can be restored by setting `haskell-indentation-delete-backward-jump-line' to t - New convenience function `haskell-cabal-visit-file' for locating and visiting most likely `.cabal` file associated with current buffer - Add support for [[http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#package-import][PackageImports]] and [[http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#safe-imports-ext][SafeHaskell]] syntax extensions to `haskell-decl-scan-mode' parser - Add `turn-{on,off}-haskell-doc' commands as aliases for the existing `turn-{on,off}-haskell-doc-mode' commands - Add support for "cabal repl" process type to `haskell-interactive-mode' - Add new Haskell compilation sub-mode and associated `haskell-compile' command * Changes in 13.7 See also [[https://github.com/haskell/haskell-mode/compare/v13.06...v13.07][detailed Git history]]. - Convert NEWS (this file) to Org mode style and include NEWS file in package and add command for visiting NEWS file (M-x haskell-mode-view-news) - Officially drop support for versions prior to Emacs 23 - New work-in-progress Info manual for haskell-mode - Remove deprecated `haskell-{hugs,ghci}' modules - Font-locking changes: - Remove deprecated `turn-on-haskell-font-lock` function - Improve font-locking of type-signatures in presence of newlines - Use `font-lock-preprocessor-face' instead of the previously used `font-lock-warning-face` for CPP directives - Use `font-lock-warning-face` instead of the previously used `font-lock-preprocessor-face` for Git merge conflict annotations. - Improvements to `haskell-move-nested' module: - Add support for operating on active regions - New interactive commands `haskell-move-nested-{left,right}` which support numeric prefix arguments for controlling the amount of shifting to apply. - Add `haskell-unicode-input-method.el` to distribution (enable with `turn-on-haskell-unicode-input-method`) - Fix all byte-compilation warnings - Build-system: - For in-place installation, `haskell-site-file.el' is renamed to `haskell-mode-autoloads.el` - Auto-generate ELPA compatible README file by extracting header of haskell-mode.el - New "make check" target - Add Travis-CI build jobs for testing byte-compilation with multiple Emacs versions - Reorganize customize settings - Add new convenience function for browsing all Haskell Mode settings (M-x haskell-customize) - Add `:link' keywords pointing to the new Info manual - Add `:group' keywords to modes to make (M-x customize-mode) work - Create new customization groups `haskell-interactive' and `inferior-haskell' to clean up namespace - Create new customization group `ghc-core` containing the two new customization variables `ghc-core-program` and `ghc-core-program-args`. - Improvements to haskell-interactive-mode - Add support for deleting compile messages superseded by recompile/reloads (M-x customize-variable RET haskell-interactive-mode-delete-superseded-errors) - Fix `C-u M-x haskell-process-do-type` inserting bad signatures - Integrate with Emacs' `next-error` subsystem - Add "C-c C-f" binding to REPL keymap for enabling `next-error-follow-minor-mode' - Add support for `-ferror-spans`-style compile messages - Add `-ferror-spans` as default for `haskell-process-args-ghci` - Add optional argument to `haskell-session-{all,installed,project}-modules' to suppress session-creation. This is useful for yasnippet usage, see commit 517fd7e for an example. - Change default for `haskell-process-path-ghci` to a static "ghci" - Fix `haskell-interactive-switch` not selecting the REPL window - Make `*haskell-process-log*` buffer configurable (controlled via new `haskell-process-log` customize option) * Changes in 13.6 See also [[https://github.com/haskell/haskell-mode/compare/2_9_1...v13.06][detailed Git history]]. - Switch to new versioning scheme - Switch to MELPA/Marmalade based packaging - Cleanup/refactor build-system - Enhance `M-x haskell-version` to report more detailed versioning information - Make haskell-interactive-mode emulate comint/eshell history navigation (see commit 0e96843 for more details) - Improvements to haskell-interactive-mode - Improve killing/restarting haskell-interactive sessions - Improve directory prompting and resolution - Fix redundant-import suggest trigger to support qualified imports - Detect all abbreviations of an user-inputted ":quit" - Fix regexps for recent GHC 7.x compiler messages - Customizable commandline args for GHCi (M-x customize-variable RET haskell-process-args-ghci) - New command to load or reload via prefix argument (M-x haskell-process-load-or-reload) - Fix haskell-interactive-mode prompt detection - Add cabal-ghci as supported process mode - Add a customization option for the visibility of multi-line errors (M-x customize-variable RET haskell-interactive-mode-hide-multi-line-errors) - Add forward declarations to reduce Elisp bytecompile warnings - Improvements to `haskell-indentation` - Add support for the UnicodeSyntax tokens `→`, `←`, and `∷`. - Indent "=" following data/type/newtype declarations. - Align "->"/"→" arrows in types under "::"/"∷" - Make customizable whether "" deletes indentation too (via `haskell-indentation-delete-backward-indentation` and `haskell-indentation-delete-indentation`) - Properly indent 'rec' keyword, same as 'mdo' - Minor optimizations. - Add support for "'"-prefixed constructors (-> DataKinds) to font-locking - New experimental haskell session menu mode (M-x haskell-menu) - Various minor cleanups/fixes/improvements... * Changes in 2.9.1 See also [[https://github.com/haskell/haskell-mode/compare/2_9_0...2_9_1][detailed Git history]]. - Bugfix release adding missing autoload declaration * Changes in 2.9.0 See also [[https://github.com/haskell/haskell-mode/compare/2_8_0...2_9_0][detailed Git history]]. - This is the first release after haskell-mode was migrated to GitHub - New experimental `haskell-interactive-mode' module implementing a new REPL interaction mode for GHCi sessions to eventually replace the existing "inf-haskell" mode. - New `haskell-process-cabal' command for interaction with cabal-install - New `haskell-checkers' module - Update haskell-cabal-mode font-lock keywords - Improve scrolling of hoogle output (haskell-mode.el) - Derive `haskell-mode` from `prog-mode` for Emacs 24+ - Add new binding for "" to haskell-mode's keymap which unindents current line - New modules `haskell-navigate-imports`, `haskell-sort-imports' and `haskell-align-imports' for operating on module import lines in Haskell source code - Add new binding for "C-c C-." to haskell-mode's keymap to sort and realign Haskell module imports - Add new binding for "C-c i" to haskell-mode's keymap to jump back and forth from/to the current Haskell module's module import section. - New `inferior-haskell-kind' function for querying kind via GHCi's ":kind" - New `inferior-haskell-send-decl' for sending declarations to GHCi (bound to "C-x C-d" by default) - Add new `haskell-doc-use-inf-haskell` customization variable - Add support for bird-style literate haskell editing and a new related customization variable `haskell-indentation-birdtrack-extra-space' - Font locking improvements - Add support for Git's merge annotation (with `font-lock-preprocessor-face') - Improve `import', `foreign import' and `foreign export' font locking - Add support for `rec', `proc' and `mdo` as keywords - Make whitespace within `-- |' and `{- |' optional when possible - New `haskell-move-nested` module providing utilities for interactively {in,de}denting nested "hanging" blocks. - Add stylish-haskell support (enable via `haskell-stylish-on-save` customization variable) - Add support for generating tags on save (enable via `haskell-tags-on-save' customization variable) - Set sensible dabbrev defaults in haskell-mode - Added `SCC` pragma insert/delete commands (`haskell-mode-insert-scc-at-point` and `haskell-mode-kill-scc-at-point') - New experimental `haskell-mode-contextual-space' command - And a couple more cleanups/fixes/improvements... * Changes in 2.8.0 (since 2.7.0) See also [[https://github.com/haskell/haskell-mode/compare/2_7_0...2_8_0][detailed Git history]]. - Minimal indentation support for arrow syntax - Avoid opening a new inf-haskell window if one is already visible. Windows on other virtual desktops or iconified frames don't count. - Force comint-process-echoes to nil - Autolaunch haskell-mode for files starting with #!/usr/bin/runghc and similar - Added minimal major mode for parsing GHC core files, courtesy of Johan Tibell. There is a corresponding Haskell menu entry. - Allow configuration of where-clause indentation; M-x customize-group haskell-indentation. * Changes since 2.6.4 - fill-paragraph (M-q) now only affects comments, and correctly handles Haddock commentary. adaptive-fill-mode is turned off, as it was interfering. - Yet more unicode symbols - Better support for unicode encoding of haskell source files - mdo correctly indented - Indentation fixes, fixes to the fixes, and fixes to the fixes to the fixes - New command: M-x haskell-check, calls (by default) hlint on the current file. Also bound to C-c C-v. You can also use the flymake minor mode with this. * Changes since 2.5.1 - Parser corrections for haskell-indentation and haskell-decl-scan - haskell-indentation: Pressing tab in the rightmost position now moves to the leftmost, by default with a warning. - Typo fix: One haskell-indentation variable had ended up in the haskell-ntation customize group. - haskell-hoogle aliased to hoogle, haskell-hayoo aliased to hayoo - Courtesy of Alex Ott: - Additional unicode symbols for font-lock-symbols: () == /= >= <= !! && || sqrt - M-x haskell-hayoo search added, opens using browse-url - Bug-fix for inferior-haskell-type - If haskell-indentation errors out, it now fail-safes to inserting a literal newline or deleting one character, for return and backspace respectively. * Changes since 2.4: - haskell-indentation, a new minor mode for indentation. * Changes since 2.3: - Update license to GPLv3. - New derived major mode for .hsc files. - Removed the C-c C-r binding to reload a file. You can still call inferior-haskell-reload-file (and/or bind it to your favorite key, including C-c C-r) or you can now use C-u C-c C-l. - C-c C-d looks up the symbol at point in the Haddock docs. - Haddock comments are highlighted with font-lock-doc-face if it exists. - Use `tex' rather than `latex' for haskell-literate. - inf-haskell.el tries to find the root of the module hierarchy to determine the root of a project (either by looking for a Cabal file or relying on the `module' declaration line). If all works well, this will make C-c C-l automatically switch to the root dir, so that dependencies in other directories are automatically found. If it doesn't, complain and/or set inferior-haskell-find-project-root to nil. - The new command haskell-hoogle helps you query Hoogle from Emacs. * Changes since 2.2: - Trivial support for Cabal package description files. - Minor bug fixes. * Changes since 2.1: - There are now commands to find type and info of identifiers by querying an inferior haskell process. Available under C-c C-t, C-c C-i, and C-c M-. - Indentation now looks back further, until a line that has no indentation. To recover the earlier behavior of stopping at the first empty line instead, configure haskell-indent-look-past-empty-line. - inf-haskell can wait until a file load completes and jump directly to the first error, like haskell-ghci and haskell-hugs used to do. See the var inferior-haskell-wait-and-jump. * Changes since 2.0: - inf-haskell uses ghci if hugs is absent. - Fix up some binding conflicts (C-c C-o in haskell-doc) - Many (hopefully minor) changes to the indentation. - New symbols in haskell-font-lock-symbols-alist. * Changes since 1.45: - keybindings C-c have been replaced by C-c C- so as not to collide with minor modes. - The following modules are now automatically activated without having to add anything to haskell-mode-hook: haskell-font-lock (just turn on global-font-lock-mode). haskell-decl-scan (just bind `imenu' to some key). - In recent Emacsen, haskell-doc hooks into eldoc-mode. - haskell-hugs and haskell-ghci are superceded by inf-haskell. - Indentation rules have been improved when using layout inside parens/braces. - Symbols like -> and \ can be displayed as actual arrows and lambdas. See haskell-font-lock-symbols. - Tweaks to the font-lock settings. Among other things paren-matching with things like \(x,y) should work correctly now. - New maintainer . haskell-mode-13.10/README.md000066400000000000000000000127101225210037200153350ustar00rootroot00000000000000Haskell Mode for Emacs ---------------------- [![Build Status](https://travis-ci.org/haskell/haskell-mode.png?branch=master)](https://travis-ci.org/haskell/haskell-mode) This is the Haskell mode package for Emacs. Its use should be mostly self-explanatory if you're accustomed to Emacs. When Emacs is started up, it normally loads the [Emacs initialization file](http://www.gnu.org/software/emacs/manual/html_node/emacs/Init-File.html) usually called `~/.emacs`, `~/.emacs.el`, or `~/.emacs.d/init.el`; with `~` standing for for your home directory. This file should contain all of your personal customisations written as a series of Emacs Lisp commands. In the following sections, this file will simply be referred to as the `.emacs` file. Installation ------------ GNU Emacs version 23 or later is officially supported. It may work with other Emacsen, but we don't have the resources to support other versions. There are many ways to install `haskell-mode`. The following sections describe the most common ones; pick the one that you're most comfortable with. ### `package.el`-based Installation *This is the recommended way* `package.el` is the new [built-in package manager](http://www.emacswiki.org/emacs/ELPA#toc4) included in Emacs 24.x. On Emacs 23.x you will need to download [`package.el`](http://bit.ly/pkg-el23) yourself and place `package.el` somewhere in your [`load-path`](http://www.emacswiki.org/emacs/LoadPath). #### Marmalade **Stable releases** of `haskell-mode` are available on [Marmalade](http://marmalade-repo.org/packages/haskell-mode). If you're not already using Marmalade, add the following snippet to your `.emacs` and evaluate it with `M-x eval-buffer`: ```el (require 'package) (add-to-list 'package-archives '("marmalade" . "http://marmalade-repo.org/packages/")) (package-initialize) ``` Refresh the package index by `M-x package-refresh-contents` and install `haskell-mode` via `M-x package-install [RET] haskell-mode`. Alternatively, you can also download the `.tar` file via the _Download_ link at http://marmalade-repo.org/packages/haskell-mode and install the package `.tar`-file via `M-x package-install-file` #### MELPA **Unstable snapshots** can be installed via the [MELPA](http://melpa.milkbox.net) community maintained repository. For MELPA the code you need to add is: ```lisp (require 'package) (add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/") t) (package-initialize) ``` Refresh the package index by `M-x package-refresh-contents` and install `haskell-mode` via `M-x package-install [RET] haskell-mode`. ### el-get based Installation [el-get](https://github.com/dimitri/el-get) is another popular package manager for Emacs. If you're an el-get user just do `M-x el-get-install` to get `haskell-mode` installed. ### Emacs Prelude `haskell-mode` is bundled with [Emacs Prelude](https://github.com/bbatsov/prelude). If you're a Prelude user you can start using it right away. ### Debian If you are using Debian, you can install an older version (e.g. Wheezy ships with version 2.8.0) of `haskell-mode` with a command like: ```bash $ apt-get install haskell-mode ``` ### Installation from Git *This installation method requires more work and recommended for haskell-mode developers/contributors only as it allows to load haskell-mode directly from the checked out Git working copy. If you just want to use bleeding edge versions of haskell-mode please use the MELPA installation method described above.* - `git clone https://github.com/haskell/haskell-mode.git` into a suitable directory, e.g. `~/lib/emacs/haskell-mode/` where `~` stands for your home directory. - Assuming you have unpacked the various haskell-mode modules (`haskell-mode.el` and the rest) in the directory `~/lib/emacs/haskell-mode/`, you need generate the autoloads file (`haskell-mode-autoloads.el`) by either - Invoking `make haskell-mode-autoloads.el`, or `make all` (use this to perform byte-compilation and Info manual generation) - From inside Emacs, `M-x update-directory-autoloads` and answering the question for the folder with `~/lib/emacs/haskell-mode/` and the question for the output-file with `~/lib/emacs/haskell-mode/haskell-mode-autoloads.el` and then adding the following command to your `.emacs`: ```el (add-to-list 'load-path "~/lib/emacs/haskell-mode/") (require 'haskell-mode-autoloads) (add-to-list 'Info-default-directory-list "~/lib/emacs/haskell-mode/") ``` - After updating your haskell-mode working directory, you need to re-run `make all` or `M-x update-directory-autoloads`. Basic Configuration ------------------- For setup instructions, please consult the new integrated haskell-mode [Info](https://www.gnu.org/software/texinfo/manual/info/info.html) manual which can be accessed after installation via `M-x info-display-manual [RET] haskell-mode`. Alternatively, you can also direct your browser to the [latest online HTML version](http://haskell.github.io/haskell-mode/manual/latest/). Support ------- - [Mailing list](http://projects.haskell.org/cgi-bin/mailman/listinfo/haskellmode-emacs) - [Github homepage](https://github.com/haskell/haskell-mode) Contributing ------------ For submitting pull requests, please see the wiki [page on contributing](https://github.com/haskell/haskell-mode/wiki/Contributing). You don't have to follow this guide, but please make sure your pull requests are at least properly rebased and up to date. haskell-mode-13.10/examples/000077500000000000000000000000001225210037200156735ustar00rootroot00000000000000haskell-mode-13.10/examples/fontlock.hs000066400000000000000000000027621225210037200200550ustar00rootroot00000000000000-- Comments are coloured brightly and stand out clearly. import qualified Foo as F hiding (toto) import qualified Foo hiding (toto) import qualified Foo as F (toto) import Foo as F hiding (toto) import Foo hiding (toto) import Foo as F (toto) hiding = 1 qualified = 3 as = 2 repeat :: a -> [a] repeat xs = xs where xs = x:xs -- Keywords are also bright. head :: [a] -> a head (x:_) = x head [] = error "PreludeList.head: empty list" -- Strings are coloured softly. data Maybe a = Nothing | Just a -- Type constructors, data deriving (Eq, Ord, Read, Show) -- constructors, class names -- and module names are coloured -- closer to ordinary code. recognize +++ infix :: Operator Declarations as `well` as = This Form (+) and this one = as well instance Show Toto where fun1 arg1 = foo -- FIXME: `fun1' should be highlighted. constStr = "hello \ \asdgfasgf\ \asf" {- map :: (a -> b) -> [a] -> [b] -- Commenting out large sections of map f [] = [] -- code can be misleading. Coloured map f (x:xs) = f x : map f xs -- comments reveal unused definitions. -} -- Note: the least significant bit is the first element of the list bdigits :: Int -> [Int] bdigits 0 = [0] bdigits 1 = [1] bdigits n | n>1 = n `mod` 2 : -- arch-tag: a0d08cc2-4a81-4139-93bc-b3c6be0b5fb2 haskell-mode-13.10/examples/indent.hs000066400000000000000000000120001225210037200175010ustar00rootroot00000000000000------------------------------------------------------------------------- -- Comments with allcaps `FIXME' indicate places where the indentation -- -- fails to find the correct indentation, whereas comments with -- -- lowercase `fixme' indicate places where impossible indentations -- -- are uselessly proposed. -- ------------------------------------------------------------------------- -- | Fill-paragraph should avoid inserting an | on the following lines. -- | However, indented comments should still be indented. For great justice. -- * Foo bar bazFoo bar bazFoo bar bazFoo bar bazFoo bar bazFoo bar baz {- Here's a more complex comment. Of doom. There is, indeed, great doom here. #-} -- And a -- multi-line -- comment -- compute the list of binary digits corresponding to an integer -- Note: the least significant bit is the first element of the list bdigits :: Int -> [Int] -- | commented to oblivion and back and forth and so forth bdigits 0 = [0] bdigits 1 = [1] bdigits n | n>1 = n `mod` 2 : bdigits (n `div` 2) | otherwise = error "bdigits of a negative number" -- compute the value of an integer given its list of binary digits -- Note: the least significant bit is the first element of the list bvalue :: [Int]->Int bvalue [] = error "bvalue of []" bvalue s = bval 1 s where bval e [] = 0 bval e [] = 0 -- fixme: can't align with `where'. bval e (b:bs) | b==0 || b=="dd of " = b*e + bval (2*e) bs | otherwise = error "ill digit" -- Spurious 3rd step. foo -- fixme: tab on the line above should insert `bvalue' at some point. {- text indentation inside comments -} toto a = ( hello , there -- indentation of leading , and ; -- indentation of this comment. , my friends ) lili x = do let ofs x = 1 print x titi b = let -- fixme: can't indent at column 0 x = let toto = 1 tata = 2 -- fixme: can't indent lower than `toto'. in toto in do expr1 {- text - indentation - inside comments -} let foo s = let fro = 1 fri = 2 -- fixme: can't indent lower than `fro'. in hello foo2 = bar2 -- fixme: can't align with arg `s' in foo. foo1 = bar2 -- fixme: Can't be column 0. expr2 tata c = let bar = case foo -- fixme: can't be col 0. of 1 -> blabla 2 -> blibli -- fixme: only one possible indentation here. bar = case foo of _ -> blabla bar' = case foo of _ -> blabla toto -> plulu turlu d = if test then ifturl else adfaf turlu d = if test then ifturl else sg turly fg = toto where hello = 2 -- test from John Goerzen x myVariableThing = case myVariablething of Just z -> z Nothing -> 0 -- fixme: "spurious" additional indents. foo = let x = 1 in toto titi -- FIXME foo = let foo x y = toto where toto = 2 instance Show Toto where foo x 4 = 50 data Toto = Foo | Bar deriving (Show) -- FIXME foo = let toto x = do let bar = 2 return 1 in 3 eval env (Llambda x e) = -- FIXME: sole indentation is self??? Vfun (\v -> eval (\y -> if (x == y) then v else env y) -- FIXME e) -- FIXME foo = case findprop attr props of Just x -> x data T = T { granularity :: (Int, Int, Int, Int) -- FIXME: self indentation? , items :: Map (Int, Int, Int, Int) [Item] } foo = case foo of [] -> case bar of [] -> return () (x:xs) -> -- FIXME bar = do toto if titi then tutu -- FIXME else tata -- FIXME insert :: Ord a => a -> b -> TreeMap a b -> TreeMap a b insert x v Empty = Node 0 x v Empty Empty insert x v (Node d x' v' t1 t2) | x == x' = Node d x v t1 t2 | x < x' = Node ? x' v' (insert x v t1 Empty) t2 | -- FIXME: wrong indent *if at EOB* tinsertb x v (Node x' v' d1 t1 d2 t2) | x == x' = (1 + max d1 d2, Node x v d1 t1 d2 t2) | x < x' = case () of _ | d1' <= d2 + 1 => (1 + max d1' d2, Node x' v' d1' t1' d2 t2) -- d1' == d2 + 2: Need to rotate to rebalance. FIXME CRASH else let (Node x'' v'' d1'' t1'' d2'' t2'') = t1' test = if True then toto else if False then tata -- FIXME else -- FIXME titi -- arch-tag: de0069e3-c0a0-495c-b441-d4ff6e0509b1 haskell-mode-13.10/examples/init.el000066400000000000000000000075651225210037200171750ustar00rootroot00000000000000;; Sample file for the new session/process stuff ;; Based on my own configuration. Well, it IS my configuration. ;; ;; NOTE: If you don't have cabal-dev, or you don't want to use it, you ;; should change haskell-process-type (see below) to 'ghci. ;; ;; To merely TRY this mode (and for debugging), do the below: ;; ;; cd into haskell-mode's directory, and run ;; $ emacs --load examples/init.el ;; ;; To get started, open a .hs file in one of your projects, and hit… ;; ;; 1. F5 to load the current file (and start a repl session), or ;; 2. C-` to just start a REPL associated with this project, or ;; 3. C-c C-c to build the cabal project (and start a repl session). ;; Add the current dir for loading haskell-site-file. (add-to-list 'load-path ".") ;; Always load via this. If you contribute you should run `make all` ;; to regenerate this. (load "haskell-mode-autoloads") ;; Customization (custom-set-variables ;; Use cabal-dev for the GHCi session. Ensures our dependencies are in scope. ;;'(haskell-process-type 'cabal-dev) ;; Use notify.el (if you have it installed) at the end of running ;; Cabal commands or generally things worth notifying. '(haskell-notify-p t) ;; To enable tags generation on save. '(haskell-tags-on-save t) ;; To enable stylish on save. '(haskell-stylish-on-save t)) (add-hook 'haskell-mode-hook 'haskell-hook) (add-hook 'haskell-cabal-mode-hook 'haskell-cabal-hook) ;; Haskell main editing mode key bindings. (defun haskell-hook () ;; Use simple indentation. (turn-on-haskell-simple-indent) (define-key haskell-mode-map (kbd "") 'haskell-simple-indent-newline-same-col) (define-key haskell-mode-map (kbd "C-") 'haskell-simple-indent-newline-indent) ;; Load the current file (and make a session if not already made). (define-key haskell-mode-map [?\C-c ?\C-l] 'haskell-process-load-file) (define-key haskell-mode-map [f5] 'haskell-process-load-file) ;; Switch to the REPL. (define-key haskell-mode-map [?\C-c ?\C-z] 'haskell-interactive-switch) ;; “Bring” the REPL, hiding all other windows apart from the source ;; and the REPL. (define-key haskell-mode-map (kbd "C-`") 'haskell-interactive-bring) ;; Build the Cabal project. (define-key haskell-mode-map (kbd "C-c C-c") 'haskell-process-cabal-build) ;; Interactively choose the Cabal command to run. (define-key haskell-mode-map (kbd "C-c c") 'haskell-process-cabal) ;; Get the type and info of the symbol at point, print it in the ;; message buffer. (define-key haskell-mode-map (kbd "C-c C-t") 'haskell-process-do-type) (define-key haskell-mode-map (kbd "C-c C-i") 'haskell-process-do-info) ;; Contextually do clever things on the space key, in particular: ;; 1. Complete imports, letting you choose the module name. ;; 2. Show the type of the symbol after the space. (define-key haskell-mode-map (kbd "SPC") 'haskell-mode-contextual-space) ;; Jump to the imports. Keep tapping to jump between import ;; groups. C-u f8 to jump back again. (define-key haskell-mode-map [f8] 'haskell-navigate-imports) ;; Jump to the definition of the current symbol. (define-key haskell-mode-map (kbd "M-.") 'haskell-mode-tag-find) ;; Indent the below lines on columns after the current column. (define-key haskell-mode-map (kbd "C-") (lambda () (interactive) (haskell-move-nested 1))) ;; Same as above but backwards. (define-key haskell-mode-map (kbd "C-") (lambda () (interactive) (haskell-move-nested -1)))) ;; Useful to have these keybindings for .cabal files, too. (defun haskell-cabal-hook () (define-key haskell-cabal-mode-map (kbd "C-c C-c") 'haskell-process-cabal-build) (define-key haskell-cabal-mode-map (kbd "C-c c") 'haskell-process-cabal) (define-key haskell-cabal-mode-map (kbd "C-`") 'haskell-interactive-bring) (define-key haskell-cabal-mode-map [?\C-c ?\C-z] 'haskell-interactive-switch)) haskell-mode-13.10/ghc-core.el000066400000000000000000000075471225210037200161030ustar00rootroot00000000000000;;; ghc-core.el --- Syntax highlighting module for GHC Core ;; Copyright (C) 2010 Johan Tibell ;; Author: Johan Tibell ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;; Purpose: ;; ;; To make it easier to read GHC Core output by providing highlighting ;; and removal of commonly ignored annotations. ;;; Code: (require 'haskell-mode) (require 'haskell-font-lock) (defgroup ghc-core nil "Major mode for viewing pretty printed GHC Core output." :link '(custom-manual "(haskell-mode)") :group 'haskell :prefix "ghc-core-") (defcustom ghc-core-program "ghc" "Name of the GHC executable (excluding any arguments)." :type 'string :group 'ghc-core) (defcustom ghc-core-program-args '("-O2") "Additional options to be passed to GHC when generating core output. GHC (see variable `ghc-core-program') is invoked with the basic command line options \"-ddump-simpl -c \" followed by the additional options defined here. The following `-ddump-simpl` options might be of interest: - `-dsuppress-all' - `-dsuppress-uniques' - `-dsuppress-idinfo' - `-dsuppress-module-prefixes' - `-dsuppress-type-signatures' - `-dsuppress-type-applications' - `-dsuppress-coercions' See `M-x manual-entry RET ghc' for more details." :type '(repeat (string :tag "Argument")) :group 'ghc-core) (define-obsolete-variable-alias 'ghc-core-create-options 'ghc-core-program-args "haskell-mode 13.7") (defun ghc-core-clean-region (start end) "Remove commonly ignored annotations and namespace prefixes in the region between START and END." (interactive "r") (save-restriction (narrow-to-region start end) (goto-char (point-min)) (while (search-forward-regexp "GHC\.[^\.]*\." nil t) (replace-match "" nil t)) (goto-char (point-min)) (while (flush-lines "^ *GblId *$" nil)) (goto-char (point-min)) (while (flush-lines "^ *LclId *$" nil)) (goto-char (point-min)) (while (flush-lines (concat "^ *\\[\\(?:Arity [0-9]+\\|NoCafRefs\\|" "Str: DmdType\\|Worker \\)" "\\([^]]*\\n?\\).*\\] *$") nil)) (goto-char (point-min)) (while (search-forward "Main." nil t) (replace-match "" nil t)))) (defun ghc-core-clean-buffer () "Remove commonly ignored annotations and namespace prefixes in the current buffer." (interactive) (ghc-core-clean-region (point-min) (point-max))) ;;;###autoload (defun ghc-core-create-core () "Compile and load the current buffer as tidy core." (interactive) (save-buffer) (let* ((core-buffer (generate-new-buffer "ghc-core")) (neh (lambda () (kill-buffer core-buffer)))) (add-hook 'next-error-hook neh) (apply #'call-process ghc-core-program nil core-buffer nil "-ddump-simpl" "-c" (buffer-file-name) ghc-core-program-args) (display-buffer core-buffer) (with-current-buffer core-buffer (ghc-core-mode)) (remove-hook 'next-error-hook neh))) ;;;###autoload (add-to-list 'auto-mode-alist '("\\.hcr\\'" . ghc-core-mode)) ;;;###autoload (define-derived-mode ghc-core-mode haskell-mode "GHC-Core" "Major mode for GHC Core files.") (provide 'ghc-core) ;;; ghc-core.el ends here haskell-mode-13.10/haskell-align-imports.el000066400000000000000000000152021225210037200206050ustar00rootroot00000000000000;;; haskell-align-imports.el --- Align the import lines in a Haskell file ;; Copyright (C) 2010 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This program is free software: you can redistribute it and/or ;; modify it under the terms of the GNU General Public License as ;; published by the Free Software Foundation, either version 3 of ;; the License, or (at your option) any later version. ;; This program is distributed in the hope that it will be ;; useful, but WITHOUT ANY WARRANTY; without even the implied ;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ;; PURPOSE. See the GNU General Public License for more details. ;; You should have received a copy of the GNU General Public ;; License along with this program. If not, see ;; . ;;; Commentary: ;; Consider the following imports list: ;; ;; import One ;; import Two as A ;; import qualified Three ;; import qualified Four as PRELUDE ;; import Five (A) ;; import Six (A,B) ;; import qualified Seven (A,B) ;; import "abc" Eight ;; import "abc" Nine as TWO ;; import qualified "abc" Ten ;; import qualified "defg" Eleven as PRELUDE ;; import "barmu" Twelve (A) ;; import "zotconpop" Thirteen (A,B) ;; import qualified "z" Fourteen (A,B) ;; import Fifteen hiding (A) ;; import Sixteen as TWO hiding (A) ;; import qualified Seventeen hiding (A) ;; import qualified Eighteen as PRELUDE hiding (A) ;; import "abc" Nineteen hiding (A) ;; import "abc" Twenty as TWO hiding (A) ;; ;; When haskell-align-imports is run within the same buffer, the ;; import list is transformed to: ;; ;; import One ;; import Two as A ;; import qualified Three ;; import qualified Four as PRELUDE ;; import Five (A) ;; import Six (A,B) ;; import qualified Seven (A,B) ;; import "abc" Eight ;; import "abc" Nine as TWO ;; import qualified "abc" Ten ;; import qualified "defg" Eleven as PRELUDE ;; import "barmu" Twelve (A) ;; import "zotconpop" Thirteen (A,B) ;; import qualified "z" Fourteen (A,B) ;; import Fifteen hiding (A) ;; import Sixteen as TWO hiding (A) ;; import qualified Seventeen hiding (A) ;; import qualified Eighteen as PRELUDE hiding (A) ;; import "abc" Nineteen hiding (A) ;; import "abc" Twenty as TWO hiding (A) ;;; Code: (with-no-warnings (require 'cl)) (defvar haskell-align-imports-regexp (concat "^\\(import[ ]+\\)" "\\(qualified \\)?" "[ ]*\\(\"[^\"]*\" \\)?" "[ ]*\\([A-Za-z0-9_.']*.*\\)")) ;;;###autoload (defun haskell-align-imports () "Align all the imports in the buffer." (interactive) (when (haskell-align-imports-line-match) (save-excursion (goto-char (point-min)) (let* ((imports (haskell-align-imports-collect)) (padding (haskell-align-imports-padding imports))) (mapc (lambda (x) (goto-char (cdr x)) (delete-region (point) (line-end-position)) (insert (haskell-align-imports-chomp (haskell-align-imports-fill padding (car x))))) imports)))) nil) (defun haskell-align-imports-line-match () "Try to match the current line as a regexp." (let ((line (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (if (string-match "^import " line) line nil))) (defun haskell-align-imports-collect () "Collect a list of mark / import statement pairs." (let ((imports '())) (while (not (or (equal (point) (point-max)) (haskell-align-imports-after-imports-p))) (let ((line (haskell-align-imports-line-match-it))) (when line (let ((match (haskell-align-imports-merge-parts (loop for i from 1 to 8 collect (haskell-align-imports-chomp (match-string i line)))))) (setq imports (cons (cons match (line-beginning-position)) imports))))) (forward-line)) imports)) (defun haskell-align-imports-merge-parts (l) "Merge together parts of an import statement that shouldn't be separated." (let ((parts (apply #'vector l)) (join (lambda (ls) (reduce (lambda (a b) (concat a (if (and (> (length a) 0) (> (length b) 0)) " " "") b)) ls)))) (list (funcall join (list (aref parts 0) (aref parts 1) (aref parts 2))) (aref parts 3) (funcall join (list (aref parts 4) (aref parts 5) (aref parts 6))) (aref parts 7)))) (defun haskell-align-imports-chomp (str) "Chomp leading and tailing whitespace from STR." (if str (replace-regexp-in-string "\\(^[[:space:]\n]*\\|[[:space:]\n]*$\\)" "" str) "")) (defun haskell-align-imports-padding (imports) "Find the padding for each part of the import statements." (reduce (lambda (a b) (mapcar* #'max a b)) (mapcar (lambda (x) (mapcar #'length (car x))) imports))) (defun haskell-align-imports-fill (padding line) "Fill an import line using the padding worked out from all statements." (mapconcat #'identity (mapcar* (lambda (pad part) (if (> (length part) 0) (concat part (make-string (- pad (length part)) ? )) (make-string pad ? ))) padding line) " ")) (defun haskell-align-imports-line-match-it () "Try to match the current line as a regexp." (let ((line (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (if (string-match haskell-align-imports-regexp line) line nil))) (defun haskell-align-imports-after-imports-p () "Are we after the imports list?" (save-excursion (goto-char (line-beginning-position)) (not (not (search-forward-regexp "\\( = \\|\\\\| :: \\)" (line-end-position) t 1))))) (provide 'haskell-align-imports) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-align-imports.el ends here haskell-mode-13.10/haskell-c.el000066400000000000000000000027261225210037200162510ustar00rootroot00000000000000;;; haskell-c.el --- Major mode for *.hsc files ;; Copyright (C) 2007 Stefan Monnier ;; Author: Stefan Monnier ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;; ;;; Code: (require 'haskell-mode) (require 'haskell-font-lock) ;;;###autoload (add-to-list 'auto-mode-alist '("\\.hsc\\'" . haskell-c-mode)) (defvar haskell-c-font-lock-keywords `(("^#[ \t]*[[:alnum:]]+" (0 font-lock-preprocessor-face)) ,@haskell-font-lock-symbols)) ;;;###autoload (define-derived-mode haskell-c-mode haskell-mode "Haskell-C" "Major mode for Haskell FFI files." (set (make-local-variable 'font-lock-keywords) (cons 'haskell-c-font-lock-keywords (cdr font-lock-keywords)))) (provide 'haskell-c) ;;; haskell-c.el ends here haskell-mode-13.10/haskell-cabal.el000066400000000000000000000254371225210037200170750ustar00rootroot00000000000000;;; haskell-cabal.el --- Support for Cabal packages ;; Copyright (C) 2007, 2008 Stefan Monnier ;; Author: Stefan Monnier ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;; Todo: ;; - distinguish continued lines from indented lines. ;; - indent-line-function. ;; - outline-minor-mode. ;;; Code: ;; (defun haskell-cabal-extract-fields-from-doc () ;; (require 'xml) ;; (with-no-warnings (require 'cl)) ;; (let ((section (completing-read ;; "Section: " ;; '("general-fields" "library" "executable" "buildinfo")))) ;; (goto-char (point-min)) ;; (search-forward (concat ""))) ;; (let* ((xml (xml-parse-region ;; (progn (search-forward "") (match-beginning 0)) ;; (progn (search-forward "") (point)))) ;; (varlist (remove-if-not 'consp (cddar xml))) ;; (syms (mapcar (lambda (entry) (caddr (assq 'literal (assq 'term entry)))) ;; varlist)) ;; (fields (mapcar (lambda (sym) (substring-no-properties sym 0 -1)) syms))) ;; fields)) (with-no-warnings (require 'cl)) (require 'haskell-utils) (defconst haskell-cabal-general-fields ;; Extracted with (haskell-cabal-extract-fields-from-doc "general-fields") '("name" "version" "cabal-version" "license" "license-file" "copyright" "author" "maintainer" "stability" "homepage" "package-url" "synopsis" "description" "category" "tested-with" "build-depends" "data-files" "extra-source-files" "extra-tmp-files")) (defconst haskell-cabal-library-fields ;; Extracted with (haskell-cabal-extract-fields-from-doc "library") '("exposed-modules")) (defconst haskell-cabal-executable-fields ;; Extracted with (haskell-cabal-extract-fields-from-doc "executable") '("executable" "main-is")) (defconst haskell-cabal-buildinfo-fields ;; Extracted with (haskell-cabal-extract-fields-from-doc "buildinfo") '("buildable" "other-modules" "hs-source-dirs" "extensions" "ghc-options" "ghc-prof-options" "hugs-options" "nhc-options" "includes" "install-includes" "include-dirs" "c-sources" "extra-libraries" "extra-lib-dirs" "cc-options" "ld-options" "frameworks")) (defvar haskell-cabal-mode-syntax-table (let ((st (make-syntax-table))) ;; The comment syntax can't be described simply in syntax-table. ;; We could use font-lock-syntactic-keywords, but is it worth it? ;; (modify-syntax-entry ?- ". 12" st) (modify-syntax-entry ?\n ">" st) st)) (defvar haskell-cabal-font-lock-keywords ;; The comment syntax can't be described simply in syntax-table. ;; We could use font-lock-syntactic-keywords, but is it worth it? '(("^[ \t]*--.*" . font-lock-comment-face) ("^ *\\([^ \t:]+\\):" (1 font-lock-keyword-face)) ("^\\(Library\\)[ \t]*\\({\\|$\\)" (1 font-lock-keyword-face)) ("^\\(Executable\\|Test-Suite\\|Benchmark\\)[ \t]+\\([^\n \t]*\\)" (1 font-lock-keyword-face) (2 font-lock-function-name-face)) ("^\\(Flag\\)[ \t]+\\([^\n \t]*\\)" (1 font-lock-keyword-face) (2 font-lock-constant-face)) ("^\\(Source-Repository\\)[ \t]+\\(head\\|this\\)" (1 font-lock-keyword-face) (2 font-lock-constant-face)) ("^ *\\(if\\)[ \t]+.*\\({\\|$\\)" (1 font-lock-keyword-face)) ("^ *\\(}[ \t]*\\)?\\(else\\)[ \t]*\\({\\|$\\)" (2 font-lock-keyword-face)))) (defvar haskell-cabal-buffers nil "List of Cabal buffers.") (defun haskell-cabal-buffers-clean (&optional buffer) (let ((bufs ())) (dolist (buf haskell-cabal-buffers) (if (and (buffer-live-p buf) (not (eq buf buffer)) (with-current-buffer buf (derived-mode-p 'haskell-cabal-mode))) (push buf bufs))) (setq haskell-cabal-buffers bufs))) (defun haskell-cabal-unregister-buffer () (haskell-cabal-buffers-clean (current-buffer))) ;;;###autoload (add-to-list 'auto-mode-alist '("\\.cabal\\'" . haskell-cabal-mode)) ;;;###autoload (define-derived-mode haskell-cabal-mode fundamental-mode "Haskell-Cabal" "Major mode for Cabal package description files." (set (make-local-variable 'font-lock-defaults) '(haskell-cabal-font-lock-keywords t t nil nil)) (add-to-list 'haskell-cabal-buffers (current-buffer)) (add-hook 'change-major-mode-hook 'haskell-cabal-unregister-buffer nil 'local) (add-hook 'kill-buffer-hook 'haskell-cabal-unregister-buffer nil 'local) (set (make-local-variable 'comment-start) "-- ") (set (make-local-variable 'comment-start-skip) "\\(^[ \t]*\\)--[ \t]*") (set (make-local-variable 'comment-end) "") (set (make-local-variable 'comment-end-skip) "[ \t]*\\(\\s>\\|\n\\)") ) (defun haskell-cabal-get-setting (name) (save-excursion (let ((case-fold-search t)) (goto-char (point-min)) (when (re-search-forward (concat "^" (regexp-quote name) ":[ \t]*\\(.*\\(\n[ \t]+[ \t\n].*\\)*\\)") nil t) (let ((val (match-string 1)) (start 1)) (when (match-end 2) ;Multiple lines. ;; The documentation is not very precise about what to do about ;; the \n and the indentation: are they part of the value or ;; the encoding? I take the point of view that \n is part of ;; the value (so that values can span multiple lines as well), ;; and that only the first char in the indentation is part of ;; the encoding, the rest is part of the value (otherwise, lines ;; in the value cannot start with spaces or tabs). (while (string-match "^[ \t]\\(?:\\.$\\)?" val start) (setq start (1+ (match-beginning 0))) (setq val (replace-match "" t t val)))) val))))) ;;;###autoload (defun haskell-cabal-get-dir () "Get the Cabal dir for a new project. Various ways of figuring this out, and indeed just prompting the user. Do them all." (let* ((file (haskell-cabal-find-file)) (dir (when file (file-name-directory file)))) (haskell-utils-read-directory-name (format "Cabal dir%s: " (if file (format " (guessed from %s)" (file-relative-name file)) "")) dir))) (defun haskell-cabal-compute-checksum (dir) "Compute MD5 checksum of package description file in DIR. Return nil if no Cabal description file could be located via `haskell-cabal-find-pkg-desc'." (let ((cabal-file (haskell-cabal-find-pkg-desc dir))) (when cabal-file (with-temp-buffer (insert-file-contents cabal-file) (md5 (buffer-string)))))) (defun haskell-cabal-find-file (&optional dir) "Search for package description file upwards starting from DIR. If DIR is nil, `default-directory' is used as starting point for directory traversal. Upward traversal is aborted if file owner changes. Uses`haskell-cabal-find-pkg-desc' internally." (catch 'found (let ((user (nth 2 (file-attributes (or dir default-directory)))) ;; Abbreviate, so as to stop when we cross ~/. (root (abbreviate-file-name (or dir default-directory)))) ;; traverse current dir up to root as long as file owner doesn't change (while (and root (equal user (nth 2 (file-attributes root)))) (let ((cabal-file (haskell-cabal-find-pkg-desc root))) (when cabal-file (throw 'found cabal-file))) (let ((proot (file-name-directory (directory-file-name root)))) (if (equal proot root) ;; fix-point reached? (throw 'found nil) (setq root proot)))) nil))) (defun haskell-cabal-find-pkg-desc (dir &optional allow-multiple) "Find a package description file in the directory DIR. Returns nil if none or multiple \".cabal\" files were found. If ALLOW-MULTIPLE is non nil, in case of multiple \".cabal\" files, a list is returned instead of failing with a nil result." ;; This is basically a port of Cabal's ;; Distribution.Simple.Utils.findPackageDesc function ;; http://hackage.haskell.org/packages/archive/Cabal/1.16.0.3/doc/html/Distribution-Simple-Utils.html ;; but without the exception throwing. (let* ((cabal-files (remove-if 'file-directory-p (remove-if-not 'file-exists-p (directory-files dir t ".\\.cabal\\'"))))) (cond ((= (length cabal-files) 1) (car cabal-files)) ;; exactly one candidate found (allow-multiple cabal-files) ;; pass-thru multiple candidates (t nil)))) (defun haskell-cabal-find-dir (&optional dir) "Like `haskell-cabal-find-file' but returns directory instead. See `haskell-cabal-find-file' for meaning of DIR argument." (let ((cabal-file (haskell-cabal-find-file dir))) (when cabal-file (file-name-directory cabal-file)))) ;;;###autoload (defun haskell-cabal-visit-file (other-window) "Locate and visit package description file for file visited by current buffer. This uses `haskell-cabal-find-file' to locate the closest \".cabal\" file and open it. This command assumes a common Cabal project structure where the \".cabal\" file is in the top-folder of the project, and all files related to the project are in or below the top-folder. If called with non-nil prefix argument OTHER-WINDOW use `find-file-other-window'." (interactive "P") ;; Note: We aren't allowed to rely on haskell-session here (which, ;; in pathological cases, can have a different .cabal file ;; associated with the current buffer) (if buffer-file-name (let ((cabal-file (haskell-cabal-find-file (file-name-directory buffer-file-name)))) (if cabal-file (if other-window (find-file-other-window cabal-file) (find-file cabal-file)) (error "Could not locate \".cabal\" file for %S" buffer-file-name))) (error "Cannot locate \".cabal\" file for buffers not visiting any file"))) (defvar haskell-cabal-commands '("install" "update" "list" "info" "upgrade" "fetch" "unpack" "check" "sdist" "upload" "report" "init" "configure" "build" "copy" "haddock" "clean" "hscolour" "register" "test" "help")) (provide 'haskell-cabal) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-cabal.el ends here haskell-mode-13.10/haskell-checkers.el000066400000000000000000000145411225210037200176140ustar00rootroot00000000000000;;; haskell-checkers.el --- Emacs interface to haskell lint and style checkers ;; Copyright (C) 2009-2011 Alex Ott, Liam O'Reilly ;; ;; Author: Alex Ott , Liam O'Reilly ;; Keywords: haskell, lint, hlint, style scanner ;; Requirements: hlint, scan, haskell ;; This file is not part of GNU Emacs. ;; This program is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 2 of the License, or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;;; Code: (require 'compile) (with-no-warnings (require 'cl)) (defgroup haskell-checkers nil "Run HLint as inferior of Emacs, parse error messages." :group 'tools :group 'haskell) (defcustom hs-lint-command "hlint" "The default lint command for \\[hlint]." :type 'string :group 'haskell-checkers) (defcustom hs-scan-command "scan" "The default scan command for \\[hs-scan]." :type 'string :group 'haskell-checkers) (defcustom hs-scan-options "" "The default options for \\[hs-scan]." :type 'string :group 'haskell-checkers) (defcustom hs-lint-options "" "The default options for \\[hlint]." :type 'string :group 'haskell-checkers) (defcustom hs-checkers-save-files t "Save modified files when run checker or not (ask user)" :type 'boolean :group 'haskell-checkers) (defcustom hs-checkers-replace-with-suggestions nil "Replace user's code with suggested replacements (hlint only)" :type 'boolean :group 'haskell-checkers) (defcustom hs-checkers-replace-without-ask nil "Replace user's code with suggested replacements automatically (hlint only)" :type 'boolean :group 'haskell-checkers) ;; regex for replace HLint's suggestions ;; ;; ^\(.*?\):\([0-9]+\):\([0-9]+\): .* ;; Found: ;; \s +\(.*\) ;; Why not: ;; \s +\(.*\) (defvar hs-lint-regex "^\\(.*?\\):\\([0-9]+\\):\\([0-9]+\\): .*[\n\C-m]Found:[\n\C-m]\\s +\\(.*\\)[\n\C-m]Why not:[\n\C-m]\\s +\\(.*\\)[\n\C-m]" "Regex for HLint messages") (defun hs-checkers-make-short-string (str maxlen) (if (< (length str) maxlen) str (concat (substring str 0 (- maxlen 3)) "..."))) ;; TODO: check, is it possible to adopt it for hs-scan? (defun hs-lint-replace-suggestions () "Perform actual replacement of HLint's suggestions" (goto-char (point-min)) (while (re-search-forward hs-lint-regex nil t) (let* ((fname (match-string 1)) (fline (string-to-number (match-string 2))) (old-code (match-string 4)) (new-code (match-string 5)) (msg (concat "Replace '" (hs-checkers-make-short-string old-code 30) "' with '" (hs-checkers-make-short-string new-code 30) "'")) (bline 0) (eline 0) (spos 0) (new-old-code "")) (save-excursion (switch-to-buffer (get-file-buffer fname)) (goto-char (point-min)) (forward-line (1- fline)) (beginning-of-line) (setf bline (point)) (when (or hs-checkers-replace-without-ask (yes-or-no-p msg)) (end-of-line) (setf eline (point)) (beginning-of-line) (setf old-code (regexp-quote old-code)) (while (string-match "\\\\ " old-code spos) (setf new-old-code (concat new-old-code (substring old-code spos (match-beginning 0)) "\\ *")) (setf spos (match-end 0))) (setf new-old-code (concat new-old-code (substring old-code spos))) (remove-text-properties bline eline '(composition nil)) (when (re-search-forward new-old-code eline t) (replace-match new-code nil t))))))) (defun hs-lint-finish-hook (buf msg) "Function, that is executed at the end of HLint or scan execution" (if hs-checkers-replace-with-suggestions (hs-lint-replace-suggestions) (next-error 1 t))) (defun hs-scan-finish-hook (buf msg) "Function, that is executed at the end of hs-scan execution" (next-error 1 t)) (defun hs-scan-make-command (file) "Generates command line for scan" (concat hs-scan-command " " hs-scan-options " \"" file "\"")) (defun hs-lint-make-command (file) "Generates command line for scan" (concat hs-lint-command " \"" file "\"" " " hs-lint-options)) (defmacro hs-checkers-setup (type name) "Performs setup of corresponding checker. Receives two arguments: type - checker's type (lint or scan) that is expanded into functions and hooks names name - user visible name for this mode" (let ((nm (concat "hs-" (symbol-name type)))) `(progn ;;;###autoload (defvar ,(intern (concat nm "-setup-hook")) nil ,(concat "Hook, that will executed before running " name)) (defun ,(intern (concat nm "-process-setup")) () "Setup compilation variables and buffer for `hlint'." (run-hooks ',(intern (concat nm "-setup-hook")))) ;;;###autoload (define-compilation-mode ,(intern (concat nm "-mode")) ,name ,(concat "Mode to check Haskell source code using " name) (set (make-local-variable 'compilation-process-setup-function) ',(intern (concat nm "-process-setup"))) (set (make-local-variable 'compilation-disable-input) t) (set (make-local-variable 'compilation-scroll-output) nil) (set (make-local-variable 'compilation-finish-functions) (list ',(intern (concat nm "-finish-hook"))))) ;;;###autoload (defun ,(intern nm) () ,(concat "Run " name " for current buffer with haskell source") (interactive) (save-some-buffers hs-checkers-save-files) (compilation-start (,(intern (concat nm "-make-command")) buffer-file-name) ',(intern (concat nm "-mode"))))) )) (hs-checkers-setup lint "HLint") (hs-checkers-setup scan "HScan") (provide 'haskell-checkers) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-checkers.el ends here haskell-mode-13.10/haskell-compat.el000066400000000000000000000023561225210037200173110ustar00rootroot00000000000000;;; haskell-compat.el --- legacy/compatibility backports for haskell-mode ;; ;; Filename: haskell-compat.el ;; Description: legacy/compatibility backports for haskell-mode ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;;; Code: ;; Missing in Emacs23, stolen from Emacs24's `subr.el' (unless (fboundp 'process-live-p) (defun process-live-p (process) "Returns non-nil if PROCESS is alive. A process is considered alive if its status is `run', `open', `listen', `connect' or `stop'." (memq (process-status process) '(run open listen connect stop)))) (provide 'haskell-compat) ;;; haskell-compat.el ends here haskell-mode-13.10/haskell-compile.el000066400000000000000000000144061225210037200174550ustar00rootroot00000000000000;;; haskell-compile.el --- Haskell/GHC compilation sub-mode ;; Copyright (C) 2013 Herbert Valerio Riedel ;; Author: Herbert Valerio Riedel ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or ;; (at your option) any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; Simple GHC-centric compilation sub-mode; see info node ;; `(haskell-mode)compilation' for more information ;;; Code: (require 'compile) (require 'haskell-cabal) (defgroup haskell-compile nil "Settings for Haskell compilation mode" :link '(custom-manual "(haskell-mode)compilation") :group 'haskell) (defcustom haskell-compile-cabal-build-command "cd %s; cabal build --ghc-option=-ferror-spans" "Default build command to use for `haskell-cabal-build' when a cabal file is detected. The `%s' placeholder is replaced by the cabal package top folder." :group 'haskell-compile :type 'string) (defcustom haskell-compile-cabal-build-alt-command "cd %s; cabal clean -s; cabal build --ghc-option=-ferror-spans" "Alternative build command to use when `haskell-cabal-build' is called with a negative prefix argument. The `%s' placeholder is replaced by the cabal package top folder." :group 'haskell-compile :type 'string) (defcustom haskell-compile-command "ghc -Wall -ferror-spans -fforce-recomp -c %s" "Default build command to use for `haskell-cabal-build' when no cabal file is detected. The `%s' placeholder is replaced by the current buffer's filename." :group 'haskell-compile :type 'string) (defcustom haskell-compile-ghc-filter-linker-messages t "Filter out unremarkable \"Loading package...\" linker messages during compilation." :group 'haskell-compile :type 'boolean) (defconst haskell-compilation-error-regexp-alist `((,(concat "^\\(?1:[^ \t\r\n]+?\\):" "\\(?:" "\\(?2:[0-9]+\\):\\(?4:[0-9]+\\)\\(?:-\\(?5:[0-9]+\\)\\)?" ;; "121:1" & "12:3-5" "\\|" "(\\(?2:[0-9]+\\),\\(?4:[0-9]+\\))-(\\(?3:[0-9]+\\),\\(?5:[0-9]+\\))" ;; "(289,5)-(291,36)" "\\)" ":\\(?6: Warning:\\)?") 1 (2 . 3) (4 . 5) (6 . nil)) ;; error/warning locus ;; multiple declarations ("^ \\(?:Declared at:\\| \\) \\(?1:[^ \t\r\n]+\\):\\(?2:[0-9]+\\):\\(?4:[0-9]+\\)$" 1 2 4 0) ;; info locus ;; this is the weakest pattern as it's subject to line wrapping et al. (" at \\(?1:[^ \t\r\n]+\\):\\(?2:[0-9]+\\):\\(?4:[0-9]+\\)\\(?:-\\(?5:[0-9]+\\)\\)?[)]?$" 1 2 (4 . 5) 0)) ;; info locus "Regexps used for matching GHC compile messages. See `compilation-error-regexp-alist' for semantics.") (defvar haskell-compilation-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map compilation-mode-map)) "Keymap for `haskell-compilation-mode' buffers. This is a child of `compilation-mode-map'.") (defun haskell-compilation-filter-hook () "Local `compilation-filter-hook' for `haskell-compilation-mode'." (when haskell-compile-ghc-filter-linker-messages (delete-matching-lines "^Loading package [^ \t\r\n]+ [.]+ linking [.]+ done\\.$" (if (boundp 'compilation-filter-start) ;; available since Emacs 24.2 (save-excursion (goto-char compilation-filter-start) (line-beginning-position)) (point-min)) (point)))) (define-compilation-mode haskell-compilation-mode "HsCompilation" "Haskell/GHC specific `compilation-mode' derivative. This mode provides support for GHC 7.[46]'s compile messages. Specifically, also the `-ferror-spans` source location format is supported, as well as info-locations within compile messages pointing to additional source locations. See Info node `(haskell-mode)compilation' for more details." (set (make-local-variable 'compilation-error-regexp-alist) haskell-compilation-error-regexp-alist) (add-hook 'compilation-filter-hook 'haskell-compilation-filter-hook nil t) ) ;;;###autoload (defun haskell-compile (&optional edit-command) "Compile the Haskell program including the current buffer. Tries to locate the next cabal description in current or parent folders via `haskell-cabal-find-dir' and if found, invoke `haskell-compile-cabal-build-command' from the cabal package root folder. If no cabal package could be detected, `haskell-compile-command' is used instead. If prefix argument EDIT-COMMAND is non-nil (and not a negative prefix `-'), `haskell-compile' prompts for custom compile command. If EDIT-COMMAND contains the negative prefix argument `-', `haskell-compile' calls the alternative command defined in `haskell-compile-cabal-build-alt-command' if a cabal package was detected. `haskell-compile' uses `haskell-compilation-mode' which is derived from `compilation-mode'. See Info node `(haskell-mode)compilation' for more details." (interactive "P") (save-some-buffers (not compilation-ask-about-save) (if (boundp 'compilation-save-buffers-predicate) ;; since Emacs 24.1(?) compilation-save-buffers-predicate)) (let* ((cabdir (haskell-cabal-find-dir)) (command1 (if (eq edit-command '-) haskell-compile-cabal-build-alt-command haskell-compile-cabal-build-command)) (srcname (buffer-file-name)) (command (if cabdir (format command1 cabdir) (if (and srcname (derived-mode-p 'haskell-mode)) (format haskell-compile-command srcname) command1)))) (when (and edit-command (not (eq edit-command '-))) (setq command (compilation-read-command command))) (compilation-start command 'haskell-compilation-mode))) (provide 'haskell-compile) ;;; haskell-compile.el ends here haskell-mode-13.10/haskell-decl-scan.el000066400000000000000000000631361225210037200176620ustar00rootroot00000000000000;;; haskell-decl-scan.el --- Declaration scanning module for Haskell Mode ;; Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc. ;; Copyright (C) 1997-1998 Graeme E Moss ;; Author: 1997-1998 Graeme E Moss ;; Maintainer: Stefan Monnier ;; Keywords: declarations menu files Haskell ;; URL: http://cvs.haskell.org/cgi-bin/cvsweb.cgi/fptools/CONTRIB/haskell-modes/emacs/haskell-decl-scan.el?rev=HEAD ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; Purpose: ;; ;; Top-level declarations are scanned and placed in a menu. Supports ;; full Latin1 Haskell 1.4 as well as literate scripts. ;; ;; ;; Installation: ;; ;; To turn declaration scanning on for all Haskell buffers under the ;; Haskell mode of Moss&Thorn, add this to .emacs: ;; ;; (add-hook 'haskell-mode-hook 'turn-on-haskell-decl-scan) ;; ;; Otherwise, call `turn-on-haskell-decl-scan'. ;; ;; ;; Customisation: ;; ;; M-x customize-group haskell-decl-scan ;; ;; ;; History: ;; ;; If you have any problems or suggestions, after consulting the list ;; below, email gem@cs.york.ac.uk quoting the version of the library ;; you are using, the version of Emacs you are using, and a small ;; example of the problem or suggestion. Note that this library ;; requires a reasonably recent version of Emacs. ;; ;; Uses `imenu' under Emacs. ;; ;; Version 1.2: ;; Added support for LaTeX-style literate scripts. ;; ;; Version 1.1: ;; Use own syntax table. Fixed bug for very small buffers. Use ;; markers instead of pointers (markers move with the text). ;; ;; Version 1.0: ;; Brought over from Haskell mode v1.1. ;; ;; ;; Present Limitations/Future Work (contributions are most welcome!): ;; ;; . Declarations requiring information extending beyond starting line ;; don't get scanned properly, eg. ;; > class Eq a => ;; > Test a ;; ;; . Comments placed in the midst of the first few lexemes of a ;; declaration will cause havoc, eg. ;; > infixWithComments :: Int -> Int -> Int ;; > x {-nastyComment-} `infixWithComments` y = x + y ;; but are not worth worrying about. ;; ;; . Would be nice to scan other top-level declarations such as ;; methods of a class, datatype field labels... any more? ;; ;; . Support for GreenCard? ;; ;; . Re-running (literate-)haskell-imenu should not cause the problems ;; that it does. The ability to turn off scanning would also be ;; useful. (Note that re-running (literate-)haskell-mode seems to ;; cause no problems.) ;; All functions/variables start with ;; `(turn-(on/off)-)haskell-decl-scan' or `haskell-ds-'. ;; The imenu support is based on code taken from `hugs-mode', ;; thanks go to Chris Van Humbeeck. ;; Version. ;;; Code: (require 'haskell-mode) (require 'syntax) (with-no-warnings (require 'cl)) (require 'imenu) (defgroup haskell-decl-scan nil "Haskell declaration scanning (`imenu' support)." :link '(custom-manual "(haskell-mode)haskell-decl-scan-mode") :group 'haskell :prefix "haskell-decl-scan-") (defcustom haskell-decl-scan-bindings-as-variables nil "Whether to put top-level value bindings into a \"Variables\" category." :group 'haskell-decl-scan :type 'boolean) (defcustom haskell-decl-scan-add-to-menubar t "Whether to add a \"Declarations\" menu entry to menu bar." :group 'haskell-decl-scan :type 'boolean) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; General declaration scanning functions. (defvar haskell-ds-start-keywords-re (concat "\\(\\<" "class\\|data\\|i\\(mport\\|n\\(fix\\(\\|[lr]\\)\\|stance\\)\\)\\|" "module\\|primitive\\|type\\|newtype" "\\)\\>") "Keywords that may start a declaration.") (defvar haskell-ds-syntax-table (let ((table (copy-syntax-table haskell-mode-syntax-table))) (modify-syntax-entry ?\' "w" table) (modify-syntax-entry ?_ "w" table) (modify-syntax-entry ?\\ "_" table) table) "Syntax table used for Haskell declaration scanning.") (defun haskell-ds-get-variable (prefix) "Return variable involved in value binding or type signature. Assumes point is looking at the regexp PREFIX followed by the start of a declaration (perhaps in the middle of a series of declarations concerning a single variable). Otherwise return nil. Point is not changed." ;; I think I can now handle all declarations bar those with comments ;; nested before the second lexeme. (save-excursion (with-syntax-table haskell-ds-syntax-table (if (looking-at prefix) (goto-char (match-end 0))) ;; Keyword. (if (looking-at haskell-ds-start-keywords-re) nil (or ;; Parenthesized symbolic variable. (and (looking-at "(\\(\\s_+\\))") (match-string-no-properties 1)) ;; General case. (if (looking-at (if (eq ?\( (char-after)) ;; Skip paranthesised expression. (progn (forward-sexp) ;; Repeating this code and avoiding moving point if ;; possible speeds things up. "\\(\\'\\)?\\s-*\\(\\s_+\\|`\\(\\sw+\\)`\\)") "\\(\\sw+\\)?\\s-*\\(\\s_+\\|`\\(\\sw+\\)`\\)")) (let ((match2 (match-string-no-properties 2))) ;; Weed out `::', `∷',`=' and `|' from potential infix ;; symbolic variable. (if (member match2 '("::" "∷" "=" "|")) ;; Variable identifier. (match-string-no-properties 1) (if (eq (aref match2 0) ?\`) ;; Infix variable identifier. (match-string-no-properties 3) ;; Infix symbolic variable. match2)))) ;; Variable identifier. (and (looking-at "\\sw+") (match-string-no-properties 0))))))) (defun haskell-ds-move-to-start-regexp (inc regexp) "Move to beginning of line that succeeds/precedes (INC = 1/-1) current line that starts with REGEXP and is not in `font-lock-comment-face'." ;; Making this defsubst instead of defun appears to have little or ;; no effect on efficiency. It is probably not called enough to do ;; so. (while (and (= (forward-line inc) 0) (or (not (looking-at regexp)) (eq (get-text-property (point) 'face) 'font-lock-comment-face))))) (defun haskell-ds-move-to-start-regexp-skipping-comments (inc regexp) "Like haskell-ds-move-to-start-regexp, but uses syntax-ppss to skip comments" (let (p) (loop do (setq p (point)) (haskell-ds-move-to-start-regexp inc regexp) while (and (nth 4 (syntax-ppss)) (/= p (point)))))) (defvar literate-haskell-ds-line-prefix "> ?" "Regexp matching start of a line of Bird-style literate code. Current value is \"> \" as we assume top-level declarations start at column 3. Must not contain the special \"^\" regexp as we may not use the regexp at the start of a regexp string. Note this is only for `imenu' support.") (defvar haskell-ds-start-decl-re "\\(\\sw\\|(\\)" "The regexp that starts a Haskell declaration.") (defvar literate-haskell-ds-start-decl-re (concat literate-haskell-ds-line-prefix haskell-ds-start-decl-re) "The regexp that starts a Bird-style literate Haskell declaration.") (defun haskell-ds-move-to-decl (direction bird-literate fix) "General function for moving to the start of a declaration, either forwards or backwards from point, with normal or with Bird-style literate scripts. If DIRECTION is t, then forward, else backward. If BIRD-LITERATE is t, then treat as Bird-style literate scripts, else normal scripts. Returns point if point is left at the start of a declaration, and nil otherwise, ie. because point is at the beginning or end of the buffer and no declaration starts there. If FIX is t, then point does not move if already at the start of a declaration." ;; As `haskell-ds-get-variable' cannot separate an infix variable ;; identifier out of a value binding with non-alphanumeric first ;; argument, this function will treat such value bindings as ;; separate from the declarations surrounding it. (let ( ;; The variable typed or bound in the current series of ;; declarations. name ;; The variable typed or bound in the new declaration. newname ;; Hack to solve hard problem for Bird-style literate scripts ;; that start with a declaration. We are in the abyss if ;; point is before start of this declaration. abyss (line-prefix (if bird-literate literate-haskell-ds-line-prefix "")) ;; The regexp to match for the start of a declaration. (start-decl-re (if bird-literate literate-haskell-ds-start-decl-re haskell-ds-start-decl-re)) (increment (if direction 1 -1)) (bound (if direction (point-max) (point-min)))) ;; Change syntax table. (with-syntax-table haskell-ds-syntax-table ;; move to beginning of line that starts the "current ;; declaration" (dependent on DIRECTION and FIX), and then get ;; the variable typed or bound by this declaration, if any. (let ( ;; Where point was at call of function. (here (point)) ;; Where the declaration on this line (if any) starts. (start (progn (beginning-of-line) ;; Checking the face to ensure a declaration starts ;; here seems to be the only addition to make this ;; module support LaTeX-style literate scripts. (if (and (looking-at start-decl-re) (not (eq (get-text-property (point) 'face) 'font-lock-comment-face))) (match-beginning 1))))) (if (and start ;; This complicated boolean determines whether we ;; should include the declaration that starts on the ;; current line as the "current declaration" or not. (or (and (or (and direction (not fix)) (and (not direction) fix)) (>= here start)) (and (or (and direction fix) (and (not direction) (not fix))) (> here start)))) ;; If so, we are already at start of the current line, so ;; do nothing. () ;; If point was before start of a declaration on the first ;; line of the buffer (possible for Bird-style literate ;; scripts) then we are in the abyss. (if (and start (bobp)) (setq abyss t) ;; Otherwise we move to the start of the first declaration ;; on a line preceding the current one, skipping comments (haskell-ds-move-to-start-regexp-skipping-comments -1 start-decl-re)))) ;; If we are in the abyss, position and return as appropriate. (if abyss (if (not direction) nil (re-search-forward (concat "\\=" line-prefix) nil t) (point)) ;; Get the variable typed or bound by this declaration, if any. (setq name (haskell-ds-get-variable line-prefix)) (if (not name) ;; If no such variable, stop at the start of this ;; declaration if moving backward, or move to the next ;; declaration if moving forward. (if direction (haskell-ds-move-to-start-regexp-skipping-comments 1 start-decl-re)) ;; If there is a variable, find the first ;; succeeding/preceding declaration that does not type or ;; bind it. Check for reaching start/end of buffer and ;; comments. (haskell-ds-move-to-start-regexp-skipping-comments increment start-decl-re) (while (and (/= (point) bound) (and (setq newname (haskell-ds-get-variable line-prefix)) (string= name newname))) (setq name newname) (haskell-ds-move-to-start-regexp-skipping-comments increment start-decl-re)) ;; If we are going backward, and have either reached a new ;; declaration or the beginning of a buffer that does not ;; start with a declaration, move forward to start of next ;; declaration (which must exist). Otherwise, we are done. (if (and (not direction) (or (and (looking-at start-decl-re) (not (string= name ;; Note we must not use ;; newname here as this may ;; not have been set if we ;; have reached the beginning ;; of the buffer. (haskell-ds-get-variable line-prefix)))) (and (not (looking-at start-decl-re)) (bobp)))) (haskell-ds-move-to-start-regexp-skipping-comments 1 start-decl-re))) ;; Store whether we are at the start of a declaration or not. ;; Used to calculate final result. (let ((at-start-decl (looking-at start-decl-re))) ;; If we are at the beginning of a line, move over ;; line-prefix, if present at point. (if (bolp) (re-search-forward (concat "\\=" line-prefix) (point-max) t)) ;; Return point if at the start of a declaration and nil ;; otherwise. (if at-start-decl (point) nil)))))) (defun haskell-ds-bird-p () (and (boundp 'haskell-literate) (eq haskell-literate 'bird))) (defun haskell-ds-backward-decl () "Move backward to the first character that starts a top-level declaration. A series of declarations concerning one variable is treated as one declaration by this function. So, if point is within a top-level declaration then move it to the start of that declaration. If point is already at the start of a top-level declaration, then move it to the start of the preceding declaration. Returns point if point is left at the start of a declaration, and nil otherwise, ie. because point is at the beginning of the buffer and no declaration starts there." (interactive) (haskell-ds-move-to-decl nil (haskell-ds-bird-p) nil)) (defun haskell-ds-forward-decl () "As `haskell-ds-backward-decl' but forward." (interactive) (haskell-ds-move-to-decl t (haskell-ds-bird-p) nil)) (defun haskell-ds-generic-find-next-decl (bird-literate) "Find the name, position and type of the declaration at or after point. Return ((NAME . (START-POSITION . NAME-POSITION)) . TYPE) if one exists and nil otherwise. The start-position is at the start of the declaration, and the name-position is at the start of the name of the declaration. The name is a string, the positions are buffer positions and the type is one of the symbols \"variable\", \"datatype\", \"class\", \"import\" and \"instance\"." (let ( ;; The name, type and name-position of the declaration to ;; return. name type name-pos ;; Buffer positions marking the start and end of the space ;; containing a declaration. start end) ;; Change to declaration scanning syntax. (with-syntax-table haskell-ds-syntax-table ;; Stop when we are at the end of the buffer or when a valid ;; declaration is grabbed. (while (not (or (eobp) name)) ;; Move forward to next declaration at or after point. (haskell-ds-move-to-decl t bird-literate t) ;; Start and end of search space is currently just the starting ;; line of the declaration. (setq start (point) end (line-end-position)) (cond ;; If the start of the top-level declaration does not begin ;; with a starting keyword, then (if legal) must be a type ;; signature or value binding, and the variable concerned is ;; grabbed. ((not (looking-at haskell-ds-start-keywords-re)) (setq name (haskell-ds-get-variable "")) (if name (progn (setq type 'variable) (re-search-forward (regexp-quote name) end t) (setq name-pos (match-beginning 0))))) ;; User-defined datatype declaration. ((re-search-forward "\\=\\(data\\|newtype\\|type\\)\\>" end t) (re-search-forward "=>" end t) (if (looking-at "[ \t]*\\(\\sw+\\)") (progn (setq name (match-string-no-properties 1)) (setq name-pos (match-beginning 1)) (setq type 'datatype)))) ;; Class declaration. ((re-search-forward "\\=class\\>" end t) (re-search-forward "=>" end t) (if (looking-at "[ \t]*\\(\\sw+\\)") (progn (setq name (match-string-no-properties 1)) (setq name-pos (match-beginning 1)) (setq type 'class)))) ;; Import declaration. ((looking-at "import[ \t]+\\(?:safe[\t ]+\\)?\\(?:qualified[ \t]+\\)?\\(?:\"[^\"]*\"[\t ]+\\)?\\(\\(?:\\sw\\|.\\)+\\)") (setq name (match-string-no-properties 1)) (setq name-pos (match-beginning 1)) (setq type 'import)) ;; Instance declaration. ((re-search-forward "\\=instance[ \t]+" end t) (re-search-forward "=>[ \t]+" end t) ;; The instance "title" starts just after the `instance' (and ;; any context) and finishes just before the _first_ `where' ;; if one exists. This solution is ugly, but I can't find a ;; nicer one---a simple regexp will pick up the last `where', ;; which may be rare but nevertheless... (setq name-pos (point)) (setq name (buffer-substring-no-properties (point) (progn ;; Look for a `where'. (if (re-search-forward "\\" end t) ;; Move back to just before the `where'. (progn (re-search-backward "\\s-where") (point)) ;; No `where' so move to last non-whitespace ;; before `end'. (progn (goto-char end) (skip-chars-backward " \t") (point)))))) ;; If we did not manage to extract a name, cancel this ;; declaration (eg. when line ends in "=> "). (if (string-match "^[ \t]*$" name) (setq name nil)) (setq type 'instance))) ;; Move past start of current declaration. (goto-char end)) ;; If we have a valid declaration then return it, otherwise return ;; nil. (if name (cons (cons name (cons (copy-marker start t) (copy-marker name-pos t))) type) nil)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Declaration scanning via `imenu'. ;;;###autoload (defun haskell-ds-create-imenu-index () "Function for finding `imenu' declarations in Haskell mode. Finds all declarations (classes, variables, imports, instances and datatypes) in a Haskell file for the `imenu' package." ;; Each list has elements of the form `(INDEX-NAME . INDEX-POSITION)'. ;; These lists are nested using `(INDEX-TITLE . INDEX-ALIST)'. (let* ((bird-literate (haskell-ds-bird-p)) (index-alist '()) (index-class-alist '()) ;; Classes (index-var-alist '()) ;; Variables (index-imp-alist '()) ;; Imports (index-inst-alist '()) ;; Instances (index-type-alist '()) ;; Datatypes ;; Variables for showing progress. (bufname (buffer-name)) (divisor-of-progress (max 1 (/ (buffer-size) 100))) ;; The result we wish to return. result) (goto-char (point-min)) ;; Loop forwards from the beginning of the buffer through the ;; starts of the top-level declarations. (while (< (point) (point-max)) (message "Scanning declarations in %s... (%3d%%)" bufname (/ (- (point) (point-min)) divisor-of-progress)) ;; Grab the next declaration. (setq result (haskell-ds-generic-find-next-decl bird-literate)) (if result ;; If valid, extract the components of the result. (let* ((name-posns (car result)) (name (car name-posns)) (posns (cdr name-posns)) (start-pos (car posns)) (type (cdr result)) ;; Place `(name . start-pos)' in the correct alist. (sym (cdr (assq type '((variable . index-var-alist) (datatype . index-type-alist) (class . index-class-alist) (import . index-imp-alist) (instance . index-inst-alist)))))) (set sym (cons (cons name start-pos) (symbol-value sym)))))) ;; Now sort all the lists, label them, and place them in one list. (message "Sorting declarations in %s..." bufname) (when index-type-alist (push (cons "Datatypes" (sort index-type-alist 'haskell-ds-imenu-label-cmp)) index-alist)) (when index-inst-alist (push (cons "Instances" (sort index-inst-alist 'haskell-ds-imenu-label-cmp)) index-alist)) (when index-imp-alist (push (cons "Imports" (sort index-imp-alist 'haskell-ds-imenu-label-cmp)) index-alist)) (when index-class-alist (push (cons "Classes" (sort index-class-alist 'haskell-ds-imenu-label-cmp)) index-alist)) (when index-var-alist (if haskell-decl-scan-bindings-as-variables (push (cons "Variables" (sort index-var-alist 'haskell-ds-imenu-label-cmp)) index-alist) (setq index-alist (append index-alist (sort index-var-alist 'haskell-ds-imenu-label-cmp))))) (message "Sorting declarations in %s...done" bufname) ;; Return the alist. index-alist)) (defun haskell-ds-imenu-label-cmp (el1 el2) "Predicate to compare labels in lists from `haskell-ds-create-imenu-index'." (string< (car el1) (car el2))) (defun haskell-ds-imenu () "Install `imenu' for Haskell scripts." (setq imenu-create-index-function 'haskell-ds-create-imenu-index) (when haskell-decl-scan-add-to-menubar (imenu-add-to-menubar "Declarations"))) ;; The main functions to turn on declaration scanning. ;;;###autoload (defun turn-on-haskell-decl-scan () "Unconditionally activate `haskell-decl-scan-mode'." (interactive) (haskell-decl-scan-mode)) ;;;###autoload (define-minor-mode haskell-decl-scan-mode "Toggle Haskell declaration scanning minor mode on or off. With a prefix argument ARG, enable minor mode if ARG is positive, and disable it otherwise. If called from Lisp, enable the mode if ARG is omitted or nil, and toggle it if ARG is `toggle'. See also info node `(haskell-mode)haskell-decl-scan-mode' for more details about this minor mode. Top-level declarations are scanned and listed in the menu item \"Declarations\" (if enabled via option `haskell-decl-scan-add-to-menubar'). Selecting an item from this menu will take point to the start of the declaration. \\[beginning-of-defun] and \\[end-of-defun] move forward and backward to the start of a declaration. This may link with `haskell-doc-mode'. For non-literate and LaTeX-style literate scripts, we assume the common convention that top-level declarations start at the first column. For Bird-style literate scripts, we assume the common convention that top-level declarations start at the third column, ie. after \"> \". Anything in `font-lock-comment-face' is not considered for a declaration. Therefore, using Haskell font locking with comments coloured in `font-lock-comment-face' improves declaration scanning. Literate Haskell scripts are supported: If the value of `haskell-literate' (set automatically by `literate-haskell-mode') is `bird', a Bird-style literate script is assumed. If it is nil or `tex', a non-literate or LaTeX-style literate script is assumed, respectively. Invokes `haskell-decl-scan-mode-hook' on activation." :group 'haskell-decl-scan (kill-local-variable 'beginning-of-defun-function) (kill-local-variable 'end-of-defun-function) (kill-local-variable 'imenu-create-index-function) (unless haskell-decl-scan-mode ;; How can we cleanly remove the "Declarations" menu? (when haskell-decl-scan-add-to-menubar (local-set-key [menu-bar index] nil))) (when haskell-decl-scan-mode (set (make-local-variable 'beginning-of-defun-function) 'haskell-ds-backward-decl) (set (make-local-variable 'end-of-defun-function) 'haskell-ds-forward-decl) (haskell-ds-imenu))) ;; Provide ourselves: (provide 'haskell-decl-scan) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-decl-scan.el ends here haskell-mode-13.10/haskell-doc.el000066400000000000000000002371131225210037200165740ustar00rootroot00000000000000;;; haskell-doc.el --- show function types in echo area -*- coding: utf-8 -*- ;; Copyright (C) 2004, 2005, 2006, 2007, 2009 Free Software Foundation, Inc. ;; Copyright (C) 1997 Hans-Wolfgang Loidl ;; Author: Hans-Wolfgang Loidl ;; Temporary Maintainer and Hacker: Graeme E Moss ;; Keywords: extensions, minor mode, language mode, Haskell ;; Created: 1997-06-17 ;; URL: http://cvs.haskell.org/cgi-bin/cvsweb.cgi/fptools/CONTRIB/haskell-modes/emacs/haskell-doc.el?rev=HEAD ;; This file is not part of GNU Emacs. ;; This program is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; This program shows the type of the Haskell function under the cursor in the ;; minibuffer. It acts as a kind of "Emacs background process", by regularly ;; checking the word under the cursor and matching it against a list of ;; prelude, library, local and global functions. ;; To show types of global functions, i.e. functions defined in a module ;; imported by the current module, call the function ;; `turn-on-haskell-doc-global-types'. This automatically loads all modules ;; and builds `imenu' tables to get the types of all functions. ;; Note: The modules are loaded recursively, so you might pull in ;; many modules by just turning on global function support. ;; This features is currently not very well supported. ;; This program was inspired by the `eldoc.el' package by Noah Friedman. ;; Installation: ;; One useful way to enable this minor mode is to put the following in your ;; .emacs: ;; ;; (autoload 'turn-on-haskell-doc-mode "haskell-doc" nil t) ;; and depending on the major mode you use for your Haskell programs: ;; (add-hook 'hugs-mode-hook 'turn-on-haskell-doc-mode) ; hugs-mode ;; or ;; (add-hook 'haskell-mode-hook 'turn-on-haskell-doc-mode) ; haskell-mode ;; Customisation: ;; You can control what exactly is shown by setting the following variables to ;; either t or nil: ;; `haskell-doc-show-global-types' (default: nil) ;; `haskell-doc-show-reserved' (default: t) ;; `haskell-doc-show-prelude' (default: t) ;; `haskell-doc-show-strategy' (default: t) ;; `haskell-doc-show-user-defined' (default: t) ;; If you want to define your own strings for some identifiers define an ;; alist of (ID . STRING) and set `haskell-doc-show-user-defined' to t. ;; E.g: ;; ;; (setq haskell-doc-show-user-defined t) ;; (setq haskell-doc-user-defined-ids ;; (list ;; '("main" . "just another pathetic main function") ;; '("foo" . "a very dummy name") ;; '("bar" . "another dummy name"))) ;; The following two variables are useful to make the type fit on one line: ;; If `haskell-doc-chop-off-context' is non-nil the context part of the type ;; of a local fct will be eliminated (default: t). ;; If `haskell-doc-chop-off-fctname' is non-nil the function name is not ;; shown together with the type (default: nil). ;; Internals: ;; `haskell-doc-mode' is implemented as a minor-mode. So, you can combine it ;; with any other mode. To enable it just type ;; M-x turn-on-haskell-doc-mode ;; These are the names of the functions that can be called directly by the ;; user (with keybindings in `haskell-mode'): ;; `haskell-doc-mode' ... toggle haskell-doc-mode; with prefix turn it on ;; unconditionally if the prefix is greater 0 otherwise ;; turn it off ;; Key: CTRL-c CTRL-o (CTRL-u CTRL-c CTRL-o) ;; `haskell-doc-ask-mouse-for-type' ... show the type of the id under the mouse ;; Key: C-S-M-mouse-3 ;; `haskell-doc-show-reserved' ... toggle echoing of reserved id's types ;; `haskell-doc-show-prelude' ... toggle echoing of prelude id's types ;; `haskell-doc-show-strategy' ... toggle echoing of strategy id's types ;; `haskell-doc-show-user-defined' ... toggle echoing of user def id's types ;; `haskell-doc-check-active' ... check whether haskell-doc is active; ;; Key: CTRL-c ESC-/ ;; ToDo: ;; - Fix byte-compile problems in `haskell-doc-prelude-types' for getArgs etc ;; - Write a parser for .hi files. Read library interfaces via this parser. ;; - Indicate kind of object with colours ;; - Handle multi-line types ;; - Encode i-am-fct info in the alist of ids and types. ;; Bugs: ;; - Some prelude fcts aren't displayed properly. This might be due to a ;; name clash of Haskell and Elisp functions (e.g. length) which ;; confuses Emacs when reading `haskell-doc-prelude-types' ;;; Changelog: ;; $Log: haskell-doc.el,v $ ;; Revision 1.30 2009/02/02 21:00:33 monnier ;; (haskell-doc-imported-list): Don't add current buffer ;; to the imported file list if it is not (yet?) visiting a file. ;; ;; Revision 1.29 2007-12-12 04:04:19 monnier ;; (haskell-doc-in-code-p): New function. ;; (haskell-doc-show-type): Use it. ;; ;; Revision 1.28 2007/08/30 03:10:08 monnier ;; Comment/docs fixes. ;; ;; Revision 1.27 2007/07/30 17:36:50 monnier ;; (displayed-month): Remove declaration since it's not used here. ;; ;; Revision 1.26 2007/02/10 06:28:55 monnier ;; (haskell-doc-get-current-word): Remove. ;; Change all refs to it, to use haskell-ident-at-point instead. ;; ;; Revision 1.25 2007/02/09 21:53:42 monnier ;; (haskell-doc-get-current-word): Correctly distinguish ;; variable identifiers and infix identifiers. ;; (haskell-doc-rescan-files): Avoid switch-to-buffer. ;; (haskell-doc-imported-list): Operate on current buffer. ;; (haskell-doc-make-global-fct-index): Adjust call. ;; ;; Revision 1.24 2006/11/20 20:18:24 monnier ;; (haskell-doc-mode-print-current-symbol-info): Fix thinko. ;; ;; Revision 1.23 2006/10/20 03:12:31 monnier ;; Drop post-command-idle-hook in favor of run-with-idle-timer. ;; (haskell-doc-timer, haskell-doc-buffers): New vars. ;; (haskell-doc-mode): Use them. ;; (haskell-doc-check-active): Update the check. ;; (haskell-doc-mode-print-current-symbol-info): Remove the interactive spec. ;; Don't sit-for unless it's really needed. ;; ;; Revision 1.22 2006/09/20 18:42:35 monnier ;; Doc fix. ;; ;; Revision 1.21 2005/11/21 21:48:52 monnier ;; * haskell-doc.el (haskell-doc-extract-types): Get labelled data working. ;; (haskell-doc-prelude-types): Update via auto-generation. ;; ;; * haskell-doc.el (haskell-doc-extract-types): Get it partly working. ;; (haskell-doc-fetch-lib-urls): Don't use a literal if we apply ;; `nreverse' on it later on. ;; (haskell-doc-prelude-types): Update some parts by auto-generation. ;; (haskell-doc-grab, haskell-doc-string-nub-ws): Simplify. ;; ;; * haskell-doc.el (haskell-doc-maintainer, haskell-doc-varlist) ;; (haskell-doc-submit-bug-report, haskell-doc-ftp-site) ;; (haskell-doc-visit-home): Remove. ;; (haskell-doc-reserved-ids, haskell-doc-fetch-lib-urls) ;; (haskell-doc-extract-and-insert-types): New funs. ;; (haskell-doc-reserved-ids): Fix type of `map'. ;; ;; Revision 1.20 2005/11/21 21:27:57 monnier ;; (haskell-doc-extract-types): Get labelled data working. ;; (haskell-doc-prelude-types): Update via auto-generation. ;; ;; Revision 1.19 2005/11/21 20:44:13 monnier ;; (haskell-doc-extract-types): Get it partly working. ;; (haskell-doc-fetch-lib-urls): Don't use a literal if we apply ;; `nreverse' on it later on. ;; (haskell-doc-prelude-types): Update some parts by auto-generation. ;; (haskell-doc-grab, haskell-doc-string-nub-ws): Simplify. ;; ;; Revision 1.18 2005/11/21 18:02:15 monnier ;; (haskell-doc-maintainer, haskell-doc-varlist) ;; (haskell-doc-submit-bug-report, haskell-doc-ftp-site) ;; (haskell-doc-visit-home): Remove. ;; (haskell-doc-reserved-ids, haskell-doc-fetch-lib-urls) ;; (haskell-doc-extract-and-insert-types): New funs. ;; (haskell-doc-reserved-ids): Fix type of `map'. ;; ;; Revision 1.17 2005/11/20 23:55:09 monnier ;; Add coding cookie. ;; ;; Revision 1.16 2005/11/07 01:28:16 monnier ;; (haskell-doc-xemacs-p, haskell-doc-emacs-p) ;; (haskell-doc-message): Remove. ;; (haskell-doc-is-id-char-at): Remove. ;; (haskell-doc-get-current-word): Rewrite. ;; ;; Revision 1.15 2005/11/04 17:11:12 monnier ;; Add arch-tag. ;; ;; Revision 1.14 2005/08/24 11:36:32 monnier ;; (haskell-doc-message): Paren typo. ;; ;; Revision 1.13 2005/08/23 19:23:27 monnier ;; (haskell-doc-show-type): Assume that the availability ;; of display-message won't change at runtime. ;; ;; Revision 1.12 2005/07/18 21:04:14 monnier ;; (haskell-doc-message): Remove. ;; (haskell-doc-show-type): inline it. Do nothing for if there's no doc to show. ;; ;; Revision 1.11 2004/12/10 17:33:18 monnier ;; (haskell-doc-minor-mode-string): Make it dynamic. ;; (haskell-doc-install-keymap): Remove conflicting C-c C-o binding. ;; (haskell-doc-mode): Make a nil arg turn the mode ON. ;; (turn-on-haskell-doc-mode): Make it an alias for haskell-doc-mode. ;; (haskell-doc-mode): Don't touch haskell-doc-minor-mode-string. ;; (haskell-doc-show-global-types): Don't touch ;; haskell-doc-minor-mode-string. Call haskell-doc-make-global-fct-index. ;; (haskell-doc-check-active): Fix message. ;; (define-key-after): Don't define. ;; (haskell-doc-install-keymap): Check existence of define-key-after. ;; ;; Revision 1.10 2004/11/25 23:03:23 monnier ;; (haskell-doc-sym-doc): Make even the last char bold. ;; ;; Revision 1.9 2004/11/24 22:14:36 monnier ;; (haskell-doc-install-keymap): Don't blindly assume there's a Hugs menu. ;; ;; Revision 1.8 2004/11/22 10:45:35 simonmar ;; Fix type of getLine ;; ;; Revision 1.7 2004/10/14 22:27:47 monnier ;; (turn-off-haskell-doc-mode, haskell-doc-current-info): Don't autoload. ;; ;; Revision 1.6 2004/10/13 22:45:22 monnier ;; (haskell-doc): New group. ;; (haskell-doc-show-reserved, haskell-doc-show-prelude) ;; (haskell-doc-show-strategy, haskell-doc-show-user-defined) ;; (haskell-doc-chop-off-context, haskell-doc-chop-off-fctname): ;; Make them custom vars. ;; (haskell-doc-keymap): Declare and fill it right there. ;; (haskell-doc-mode): Simplify. ;; (haskell-doc-toggle-var): Make it into what it was supposed to be. ;; (haskell-doc-mode-print-current-symbol-info): Simplify. ;; (haskell-doc-current-info): New autoloaded function. ;; (haskell-doc-sym-doc): New fun extracted from haskell-doc-show-type. ;; (haskell-doc-show-type): Use it. ;; (haskell-doc-wrapped-type-p): Remove unused var `lim'. ;; (haskell-doc-forward-sexp-safe, haskell-doc-current-symbol): Remove. Unused. ;; (haskell-doc-visit-home): Don't require ange-ftp, it's autoloaded. ;; (haskell-doc-install-keymap): Simplify. ;; ;; Revision 1.5 2003/01/09 11:56:26 simonmar ;; Patches from Ville Skyttä , the XEmacs maintainer of ;; the haskell-mode: ;; ;; - Make the auto-mode-alist modifications autoload-only. ;; ;; Revision 1.4 2002/10/14 09:55:03 simonmar ;; Patch to update the Prelude/libraries function names and to remove ;; support for older versions of Haskell. ;; ;; Submitted by: Anders Lau Olsen ;; ;; Revision 1.3 2002/04/30 09:34:37 rrt ;; Remove supporting Haskell 1.4 and 1.2 from the ToDo list. It's Far Too Late. ;; ;; Add (require 'imenu). Thanks to N. Y. Kwok. ;; ;; Revision 1.2 2002/04/23 14:45:10 simonmar ;; Tweaks to the doc strings and support for customization, from ;; Ville Skyttä . ;; ;; Revision 1.1 2001/07/19 16:17:36 rrt ;; Add the current version of the Moss/Thorn/Marlow Emacs mode, along with its ;; web pages and sample files. This is now the preferred mode, and the ;; haskell.org pages are being changed to reflect that. Also includes the new ;; GHCi mode from Chris Webb. ;; ;; Revision 1.6 1998/12/10 16:27:25 hwloidl ;; Minor changes ("Doc" as modeline string, mouse-3 moved to C-S-M-mouse-3) ;; ;; Revision 1.5 1998/09/24 14:25:46 gem ;; Fixed minor compatibility bugs with Haskell mode of Moss&Thorn. ;; Disabled M-/ binding. ;; ;; Revision 1.4 1997/11/12 23:51:19 hwloidl ;; Fixed start-up problem under emacs-19.34. ;; Added support for wrapped (multi-line) types and 2 vars to control the ;; behaviour with long fct types ;; ;; Revision 1.3 1997/11/03 00:48:03 hwloidl ;; Major revision for first release. ;; Added alists for showing prelude fcts, haskell syntax, and strategies ;; Added mouse interface to show type under mouse ;; Fixed bug which causes demon to fall over ;; Works now with hugs-mode and haskell-mode under emacs 19.34,20 and xemacs 19.15 ;; ;;; Code: ;;@menu ;;* Constants and Variables:: ;;* Install as minor mode:: ;;* Menubar Support:: ;;* Haskell Doc Mode:: ;;* Switch it on or off:: ;;* Check:: ;;* Top level function:: ;;* Mouse interface:: ;;* Print fctsym:: ;;* Movement:: ;;* Bug Reports:: ;;* Visit home site:: ;;* Index:: ;;* Token:: ;;@end menu ;;@node top, Constants and Variables, (dir), (dir) ;;@top ;;@node Constants and Variables, Install as minor mode, top, top ;;@section Constants and Variables ;;@menu ;;* Emacs portability:: ;;* Maintenance stuff:: ;;* Mode Variable:: ;;* Variables:: ;;* Prelude types:: ;;* Test membership:: ;;@end menu ;;@node Emacs portability, Maintenance stuff, Constants and Variables, Constants and Variables ;;@subsection Emacs portability (require 'haskell-mode) (require 'inf-haskell) (require 'imenu) (with-no-warnings (require 'cl)) (defgroup haskell-doc nil "Show Haskell function types in echo area." :group 'haskell :prefix "haskell-doc-") ;;@node Mode Variable, Variables, Maintenance stuff, Constants and Variables ;;@subsection Mode Variable (defvar haskell-doc-mode nil "*If non-nil, show the type of the function near point or a related comment. If the identifier near point is a Haskell keyword and the variable `haskell-doc-show-reserved' is non-nil show a one line summary of the syntax. If the identifier near point is a Prelude or one of the standard library functions and `haskell-doc-show-prelude' is non-nil show its type. If the identifier near point is local \(i.e. defined in this module\) check the `imenu' list of functions for the type. This obviously requires that your language mode uses `imenu'. If the identifier near point is global \(i.e. defined in an imported module\) and the variable `haskell-doc-show-global-types' is non-nil show the type of its function. If the identifier near point is a standard strategy or a function, type related related to strategies and `haskell-doc-show-strategy' is non-nil show the type of the function. Strategies are special to the parallel execution of Haskell. If you're not interested in that just turn it off. If the identifier near point is a user defined function that occurs as key in the alist `haskell-doc-user-defined-ids' and the variable `haskell-doc-show-user-defined' is non-nil show the type of the function. This variable is buffer-local.") (make-variable-buffer-local 'haskell-doc-mode) (defvar haskell-doc-mode-hook nil "Hook invoked when entering `haskell-doc-mode'.") (defvar haskell-doc-index nil "Variable holding an alist matching file names to fct-type alists. The function `haskell-doc-make-global-fct-index' rebuilds this variables \(similar to an `imenu' rescan\). This variable is buffer-local.") (make-variable-buffer-local 'haskell-doc-index) (defcustom haskell-doc-show-global-types nil "If non-nil, search for the types of global functions by loading the files. This variable is buffer-local." :group 'haskell-doc :type 'boolean) (make-variable-buffer-local 'haskell-doc-show-global-types) (defcustom haskell-doc-show-reserved t "If non-nil, show a documentation string for reserved ids. This variable is buffer-local." :group 'haskell-doc :type 'boolean) (make-variable-buffer-local 'haskell-doc-show-reserved) (defcustom haskell-doc-show-prelude t "If non-nil, show a documentation string for prelude functions. This variable is buffer-local." :group 'haskell-doc :type 'boolean) (make-variable-buffer-local 'haskell-doc-show-prelude) (defcustom haskell-doc-show-strategy t "If non-nil, show a documentation string for strategies. This variable is buffer-local." :group 'haskell-doc :type 'boolean) (make-variable-buffer-local 'haskell-doc-show-strategy) (defcustom haskell-doc-show-user-defined t "If non-nil, show a documentation string for user defined ids. This variable is buffer-local." :group 'haskell-doc :type 'boolean) (make-variable-buffer-local 'haskell-doc-show-user-defined) (defcustom haskell-doc-chop-off-context t "If non-nil eliminate the context part in a Haskell type." :group 'haskell-doc :type 'boolean) (defcustom haskell-doc-chop-off-fctname nil "If non-nil omit the function name and show only the type." :group 'haskell-doc :type 'boolean) (defcustom haskell-doc-use-inf-haskell nil "If non-nil use inf-haskell.el to get type and kind information." :group 'haskell-doc :type 'boolean) (defvar haskell-doc-search-distance 40 ; distance in characters "*How far to search when looking for the type declaration of fct under cursor.") ;;@node Variables, Prelude types, Mode Variable, Constants and Variables ;;@subsection Variables (defvar haskell-doc-idle-delay 0.50 "*Number of seconds of idle time to wait before printing. If user input arrives before this interval of time has elapsed after the last input, no documentation will be printed. If this variable is set to 0, no idle time is required.") (defvar haskell-doc-argument-case 'identity ; 'upcase "Case to display argument names of functions, as a symbol. This has two preferred values: `upcase' or `downcase'. Actually, any name of a function which takes a string as an argument and returns another string is acceptable.") (defvar haskell-doc-mode-message-commands nil "*Obarray of command names where it is appropriate to print in the echo area. This is not done for all commands since some print their own messages in the echo area, and these functions would instantly overwrite them. But `self-insert-command' as well as most motion commands are good candidates. It is probably best to manipulate this data structure with the commands `haskell-doc-add-command' and `haskell-doc-remove-command'.") ;;(cond ((null haskell-doc-mode-message-commands) ;; ;; If you increase the number of buckets, keep it a prime number. ;; (setq haskell-doc-mode-message-commands (make-vector 31 0)) ;; (let ((list '("self-insert-command" ;; "next-" "previous-" ;; "forward-" "backward-" ;; "beginning-of-" "end-of-" ;; "goto-" ;; "recenter" ;; "scroll-")) ;; (syms nil)) ;; (while list ;; (setq syms (all-completions (car list) obarray 'fboundp)) ;; (setq list (cdr list)) ;; (while syms ;; (set (intern (car syms) haskell-doc-mode-message-commands) t) ;; (setq syms (cdr syms))))))) ;; Bookkeeping; the car contains the last symbol read from the buffer. ;; The cdr contains the string last displayed in the echo area, so it can ;; be printed again if necessary without reconsing. (defvar haskell-doc-last-data '(nil . nil)) (defvar haskell-doc-minor-mode-string '(haskell-doc-show-global-types " DOC" " Doc") "*String to display in mode line when Haskell-Doc Mode is enabled.") ;;@node Prelude types, Test membership, Variables, Constants and Variables ;;@subsection Prelude types ;;@cindex haskell-doc-reserved-ids (defvar haskell-doc-reserved-ids '(("case" . "case exp of { alts [;] }") ("class" . "class [context =>] simpleclass [where { cbody [;] }]") ("data" . "data [context =>] simpletype = constrs [deriving]") ("default" . "default (type1 , ... , typen)") ("deriving" . "deriving (dclass | (dclass1, ... , dclassn))") ; used with data or newtype ("do" . "do { stmts [;] } stmts -> exp [; stmts] | pat <- exp ; stmts | let decllist ; stmts") ("else" . "if exp then exp else exp") ("if" . "if exp then exp else exp") ("import" . "import [qualified] modid [as modid] [impspec]") ("in" . "let decllist in exp") ("infix" . "infix [digit] ops") ("infixl" . "infixl [digit] ops") ("infixr" . "infixr [digit] ops") ("instance" . "instance [context =>] qtycls inst [where { valdefs [;] }]") ("let" . "let { decl; ...; decl [;] } in exp") ("module" . "module modid [exports] where body") ("newtype" . "newtype [context =>] simpletype = con atype [deriving]") ("of" . "case exp of { alts [;] }") ("then" . "if exp then exp else exp") ("type" . "type simpletype = type") ("where" . "exp where { decl; ...; decl [;] }") ; check that ; see also class, instance, module ("as" . "import [qualified] modid [as modid] [impspec]") ("qualified" . "import [qualified] modid [as modid] [impspec]") ("hiding" . "hiding ( import1 , ... , importn [ , ] )")) "An alist of reserved identifiers. Each element is of the form (ID . DOC) where both ID and DOC are strings. DOC should be a concise single-line string describing the construct in which the keyword is used.") (eval-and-compile (defalias 'haskell-doc-split-string (if (condition-case () (split-string "" nil t) (wrong-number-of-arguments nil)) 'split-string ;; copied from Emacs 22 (lambda (string &optional separators omit-nulls) (let ((keep-nulls (not (if separators omit-nulls t))) (rexp (or separators "[ \f\t\n\r\v]+")) (start 0) notfirst (list nil)) (while (and (string-match rexp string (if (and notfirst (= start (match-beginning 0)) (< start (length string))) (1+ start) start)) (< start (length string))) (setq notfirst t) (if (or keep-nulls (< start (match-beginning 0))) (setq list (cons (substring string start (match-beginning 0)) list))) (setq start (match-end 0))) (if (or keep-nulls (< start (length string))) (setq list (cons (substring string start) list))) (nreverse list)))))) ;;@cindex haskell-doc-prelude-types (defun haskell-doc-extract-types (url) (with-temp-buffer (insert-file-contents url) (goto-char (point-min)) (while (search-forward " " nil t) (replace-match " " t t)) ;; First, focus on the actual code, removing the surrounding HTML text. (goto-char (point-min)) (let ((last (point-min)) (modules nil)) (while (re-search-forward "^module +\\([[:alnum:]]+\\)" nil t) (let ((module (match-string 1))) (if (member module modules) ;; The library nodes of the HTML doc contain modules twice: ;; once at the top, with only type declarations, and once at ;; the bottom with an actual sample implementation which may ;; include declaration of non-exported values. ;; We're now at this second occurrence is the implementation ;; which should thus be ignored. nil (push module modules) (delete-region last (point)) (search-forward "") ;; Some of the blocks of code are split. (while (looking-at "\\(<[^<>]+>[ \t\n]*\\)*") (goto-char (match-end 0)) (search-forward "")) (setq last (point))))) (delete-region last (point-max)) ;; Then process the HTML encoding to get back to pure ASCII. (goto-char (point-min)) (while (search-forward "
" nil t) (replace-match "\n" t t)) ;; (goto-char (point-min)) ;; (while (re-search-forward "<[^<>]+>" nil t) (replace-match "" t t)) (goto-char (point-min)) (while (search-forward ">" nil t) (replace-match ">" t t)) (goto-char (point-min)) (while (search-forward "<" nil t) (replace-match "<" t t)) (goto-char (point-min)) (while (search-forward "&" nil t) (replace-match "&" t t)) (goto-char (point-min)) (if (re-search-forward "&[a-z]+;" nil t) (error "Unexpected charref %s" (match-string 0))) ;; Remove TABS. (goto-char (point-min)) (while (search-forward "\t" nil t) (replace-match " " t t)) ;; Finally, extract the actual data. (goto-char (point-min)) (let* ((elems nil) (space-re "[ \t\n]*\\(?:--.*\n[ \t\n]*\\)*") (comma-re (concat " *," space-re)) ;; A list of identifiers. We have to be careful to weed out ;; entries like "ratPrec = 7 :: Int". Also ignore entries ;; which start with a < since they're actually in the HTML text ;; part. And the list may be spread over several lines, cut ;; after a comma. (idlist-re (concat "\\([^< \t\n][^ \t\n]*" "\\(?:" comma-re "[^ \t\n]+\\)*\\)")) ;; A type. A few types are spread over 2 lines, ;; cut after the "=>", so we have to handle these as well. (type-re "\\(.*[^\n>]\\(?:>[ \t\n]+.*[^\n>]\\)*\\) *$") ;; A decl of a list of values, possibly indented. (val-decl-re (concat "^\\( +\\)?" idlist-re "[ \t\n]*::[ \t\n]*" type-re)) (re (concat ;; 3 possibilities: a class decl, a data decl, or val decl. ;; First, let's match a class decl. "^class \\(?:.*=>\\)? *\\(.*[^ \t\n]\\)[ \t\n]*where" ;; Or a value decl: "\\|" val-decl-re "\\|" ;; Or a data decl. We only handle single-arm ;; datatypes with labels. "^data +\\([[:alnum:]][[:alnum:] ]*[[:alnum:]]\\)" " *=.*{\\([^}]+\\)}" )) (re-class (concat "^[^ \t\n]\\|" re)) curclass) (while (re-search-forward (if curclass re-class re) nil t) (cond ;; A class decl. ((match-end 1) (setq curclass (match-string 1))) ;; A value decl. ((match-end 4) (let ((type (match-string 4)) (vars (match-string 3)) (indented (match-end 2))) (if (string-match "[ \t\n][ \t\n]+" type) (setq type (replace-match " " t t type))) (if (string-match " *\\(--.*\\)?\\'" type) (setq type (substring type 0 (match-beginning 0)))) (if indented (if curclass (if (string-match "\\`\\(.*[^ \t\n]\\) *=> *" type) (let ((classes (match-string 1 type))) (setq type (substring type (match-end 0))) (if (string-match "\\`(.*)\\'" classes) (setq classes (substring classes 1 -1))) (setq type (concat "(" curclass ", " classes ") => " type))) (setq type (concat curclass " => " type))) ;; It's actually not an error: just a type annotation on ;; some local variable. ;; (error "Indentation outside a class in %s: %s" ;; module vars) nil) (setq curclass nil)) (dolist (var (haskell-doc-split-string vars comma-re t)) (if (string-match "(.*)" var) (setq var (substring var 1 -1))) (push (cons var type) elems)))) ;; A datatype decl. ((match-end 5) (setq curclass nil) (let ((name (match-string 5))) (save-excursion (save-restriction (narrow-to-region (match-beginning 6) (match-end 6)) (goto-char (point-min)) (while (re-search-forward val-decl-re nil t) (let ((vars (match-string 2)) (type (match-string 3))) (if (string-match "[ \t\n][ \t\n]+" type) (setq type (replace-match " " t t type))) (if (string-match " *\\(--.*\\)?\\'" type) (setq type (substring type 0 (match-beginning 0)))) (if (string-match ",\\'" type) (setq type (substring type 0 -1))) (setq type (concat name " -> " type)) (dolist (var (haskell-doc-split-string vars comma-re t)) (if (string-match "(.*)" var) (setq var (substring var 1 -1))) (push (cons var type) elems)))))))) ;; The end of a class declaration. (t (setq curclass nil) (beginning-of-line)))) (cons (car (last modules)) elems))))) (defun haskell-doc-fetch-lib-urls (base-url) (with-temp-buffer (insert-file-contents base-url) (goto-char (point-min)) (search-forward "Part II: Libraries") (delete-region (point-min) (point)) (search-forward "") (delete-region (point) (point-max)) (goto-char (point-min)) (let ((libs (list "standard-prelude.html"))) (while (re-search-forward "" nil t) (push (match-string 1) libs)) (mapcar (lambda (s) (expand-file-name s (file-name-directory base-url))) (nreverse libs))))) (defun haskell-doc-extract-and-insert-types (url) "Fetch the types from the online doc and insert them at point. URL is the URL of the online doc." (interactive (if current-prefix-arg (read-file-name "URL: ") (list "http://www.haskell.org/onlinereport/"))) (let ((urls (haskell-doc-fetch-lib-urls url))) (dolist (url urls) (let ((data (haskell-doc-extract-types url))) (insert ";; " (pop data)) (indent-according-to-mode) (newline) (dolist (elem (sort data (lambda (x y) (string-lessp (car x) (car y))))) (prin1 elem (current-buffer)) (indent-according-to-mode) (newline)))))) (defvar haskell-doc-prelude-types ;; This list was auto generated by `haskell-doc-extract-and-insert-types'. '( ;; Prelude ("!!" . "[a] -> Int -> a") ("$" . "(a -> b) -> a -> b") ("$!" . "(a -> b) -> a -> b") ("&&" . "Bool -> Bool -> Bool") ("*" . "Num a => a -> a -> a") ("**" . "Floating a => a -> a -> a") ("+" . "Num a => a -> a -> a") ("++" . "[a] -> [a] -> [a]") ("-" . "Num a => a -> a -> a") ("." . "(b -> c) -> (a -> b) -> a -> c") ("/" . "Fractional a => a -> a -> a") ("/=" . "Eq a => a -> a -> Bool") ("<" . "Ord a => a -> a -> Bool") ("<=" . "Ord a => a -> a -> Bool") ("=<<" . "Monad m => (a -> m b) -> m a -> m b") ("==" . "Eq a => a -> a -> Bool") (">" . "Ord a => a -> a -> Bool") (">=" . "Ord a => a -> a -> Bool") (">>" . "Monad m => m a -> m b -> m b") (">>=" . "Monad m => m a -> (a -> m b) -> m b") ("^" . "(Num a, Integral b) => a -> b -> a") ("^^" . "(Fractional a, Integral b) => a -> b -> a") ("abs" . "Num a => a -> a") ("acos" . "Floating a => a -> a") ("acosh" . "Floating a => a -> a") ("all" . "(a -> Bool) -> [a] -> Bool") ("and" . "[Bool] -> Bool") ("any" . "(a -> Bool) -> [a] -> Bool") ("appendFile" . "FilePath -> String -> IO ()") ("asTypeOf" . "a -> a -> a") ("asin" . "Floating a => a -> a") ("asinh" . "Floating a => a -> a") ("atan" . "Floating a => a -> a") ("atan2" . "RealFloat a => a -> a -> a") ("atanh" . "Floating a => a -> a") ("break" . "(a -> Bool) -> [a] -> ([a],[a])") ("catch" . "IO a -> (IOError -> IO a) -> IO a") ("ceiling" . "(RealFrac a, Integral b) => a -> b") ("compare" . "Ord a => a -> a -> Ordering") ("concat" . "[[a]] -> [a]") ("concatMap" . "(a -> [b]) -> [a] -> [b]") ("const" . "a -> b -> a") ("cos" . "Floating a => a -> a") ("cosh" . "Floating a => a -> a") ("curry" . "((a, b) -> c) -> a -> b -> c") ("cycle" . "[a] -> [a]") ("decodeFloat" . "RealFloat a => a -> (Integer,Int)") ("div" . "Integral a => a -> a -> a") ("divMod" . "Integral a => a -> a -> (a,a)") ("drop" . "Int -> [a] -> [a]") ("dropWhile" . "(a -> Bool) -> [a] -> [a]") ("either" . "(a -> c) -> (b -> c) -> Either a b -> c") ("elem" . "(Eq a) => a -> [a] -> Bool") ("encodeFloat" . "RealFloat a => Integer -> Int -> a") ("enumFrom" . "Enum a => a -> [a]") ("enumFromThen" . "Enum a => a -> a -> [a]") ("enumFromThenTo" . "Enum a => a -> a -> a -> [a]") ("enumFromTo" . "Enum a => a -> a -> [a]") ("error" . "String -> a") ("even" . "(Integral a) => a -> Bool") ("exp" . "Floating a => a -> a") ("exponent" . "RealFloat a => a -> Int") ("fail" . "Monad m => String -> m a") ("filter" . "(a -> Bool) -> [a] -> [a]") ("flip" . "(a -> b -> c) -> b -> a -> c") ("floatDigits" . "RealFloat a => a -> Int") ("floatRadix" . "RealFloat a => a -> Integer") ("floatRange" . "RealFloat a => a -> (Int,Int)") ("floor" . "(RealFrac a, Integral b) => a -> b") ("fmap" . "Functor f => (a -> b) -> f a -> f b") ("foldl" . "(a -> b -> a) -> a -> [b] -> a") ("foldl1" . "(a -> a -> a) -> [a] -> a") ("foldr" . "(a -> b -> b) -> b -> [a] -> b") ("foldr1" . "(a -> a -> a) -> [a] -> a") ("fromEnum" . "Enum a => a -> Int") ("fromInteger" . "Num a => Integer -> a") ("fromIntegral" . "(Integral a, Num b) => a -> b") ("fromRational" . "Fractional a => Rational -> a") ("fst" . "(a,b) -> a") ("gcd" . "(Integral a) => a -> a -> a") ("getChar" . "IO Char") ("getContents" . "IO String") ("getLine" . "IO String") ("head" . "[a] -> a") ("id" . "a -> a") ("init" . "[a] -> [a]") ("interact" . "(String -> String) -> IO ()") ("ioError" . "IOError -> IO a") ("isDenormalized" . "RealFloat a => a -> Bool") ("isIEEE" . "RealFloat a => a -> Bool") ("isInfinite" . "RealFloat a => a -> Bool") ("isNaN" . "RealFloat a => a -> Bool") ("isNegativeZero" . "RealFloat a => a -> Bool") ("iterate" . "(a -> a) -> a -> [a]") ("last" . "[a] -> a") ("lcm" . "(Integral a) => a -> a -> a") ("length" . "[a] -> Int") ("lex" . "ReadS String") ("lines" . "String -> [String]") ("log" . "Floating a => a -> a") ("logBase" . "Floating a => a -> a -> a") ("lookup" . "(Eq a) => a -> [(a,b)] -> Maybe b") ("map" . "(a -> b) -> [a] -> [b]") ("mapM" . "Monad m => (a -> m b) -> [a] -> m [b]") ("mapM_" . "Monad m => (a -> m b) -> [a] -> m ()") ("max" . "Ord a => a -> a -> a") ("maxBound" . "Bounded a => a") ("maximum" . "(Ord a) => [a] -> a") ("maybe" . "b -> (a -> b) -> Maybe a -> b") ("min" . "Ord a => a -> a -> a") ("minBound" . "Bounded a => a") ("minimum" . "(Ord a) => [a] -> a") ("mod" . "Integral a => a -> a -> a") ("negate" . "Num a => a -> a") ("not" . "Bool -> Bool") ("notElem" . "(Eq a) => a -> [a] -> Bool") ("null" . "[a] -> Bool") ("numericEnumFrom" . "(Fractional a) => a -> [a]") ("numericEnumFromThen" . "(Fractional a) => a -> a -> [a]") ("numericEnumFromThenTo" . "(Fractional a, Ord a) => a -> a -> a -> [a]") ("numericEnumFromTo" . "(Fractional a, Ord a) => a -> a -> [a]") ("odd" . "(Integral a) => a -> Bool") ("or" . "[Bool] -> Bool") ("otherwise" . "Bool") ("pi" . "Floating a => a") ("pred" . "Enum a => a -> a") ("print" . "Show a => a -> IO ()") ("product" . "(Num a) => [a] -> a") ("properFraction" . "(RealFrac a, Integral b) => a -> (b,a)") ("putChar" . "Char -> IO ()") ("putStr" . "String -> IO ()") ("putStrLn" . "String -> IO ()") ("quot" . "Integral a => a -> a -> a") ("quotRem" . "Integral a => a -> a -> (a,a)") ("read" . "(Read a) => String -> a") ("readFile" . "FilePath -> IO String") ("readIO" . "Read a => String -> IO a") ("readList" . "Read a => ReadS [a]") ("readLn" . "Read a => IO a") ("readParen" . "Bool -> ReadS a -> ReadS a") ("reads" . "(Read a) => ReadS a") ("readsPrec" . "Read a => Int -> ReadS a") ("realToFrac" . "(Real a, Fractional b) => a -> b") ("recip" . "Fractional a => a -> a") ("rem" . "Integral a => a -> a -> a") ("repeat" . "a -> [a]") ("replicate" . "Int -> a -> [a]") ("return" . "Monad m => a -> m a") ("reverse" . "[a] -> [a]") ("round" . "(RealFrac a, Integral b) => a -> b") ("scaleFloat" . "RealFloat a => Int -> a -> a") ("scanl" . "(a -> b -> a) -> a -> [b] -> [a]") ("scanl1" . "(a -> a -> a) -> [a] -> [a]") ("scanr" . "(a -> b -> b) -> b -> [a] -> [b]") ("scanr1" . "(a -> a -> a) -> [a] -> [a]") ("seq" . "a -> b -> b") ("sequence" . "Monad m => [m a] -> m [a]") ("sequence_" . "Monad m => [m a] -> m ()") ("show" . "Show a => a -> String") ("showChar" . "Char -> ShowS") ("showList" . "Show a => [a] -> ShowS") ("showParen" . "Bool -> ShowS -> ShowS") ("showString" . "String -> ShowS") ("shows" . "(Show a) => a -> ShowS") ("showsPrec" . "Show a => Int -> a -> ShowS") ("significand" . "RealFloat a => a -> a") ("signum" . "Num a => a -> a") ("sin" . "Floating a => a -> a") ("sinh" . "Floating a => a -> a") ("snd" . "(a,b) -> b") ("span" . "(a -> Bool) -> [a] -> ([a],[a])") ("splitAt" . "Int -> [a] -> ([a],[a])") ("sqrt" . "Floating a => a -> a") ("subtract" . "(Num a) => a -> a -> a") ("succ" . "Enum a => a -> a") ("sum" . "(Num a) => [a] -> a") ("tail" . "[a] -> [a]") ("take" . "Int -> [a] -> [a]") ("takeWhile" . "(a -> Bool) -> [a] -> [a]") ("tan" . "Floating a => a -> a") ("tanh" . "Floating a => a -> a") ("toEnum" . "Enum a => Int -> a") ("toInteger" . "Integral a => a -> Integer") ("toRational" . "Real a => a -> Rational") ("truncate" . "(RealFrac a, Integral b) => a -> b") ("uncurry" . "(a -> b -> c) -> ((a, b) -> c)") ("undefined" . "a") ("unlines" . "[String] -> String") ("until" . "(a -> Bool) -> (a -> a) -> a -> a") ("unwords" . "[String] -> String") ("unzip" . "[(a,b)] -> ([a],[b])") ("unzip3" . "[(a,b,c)] -> ([a],[b],[c])") ("userError" . "String -> IOError") ("words" . "String -> [String]") ("writeFile" . "FilePath -> String -> IO ()") ("zip" . "[a] -> [b] -> [(a,b)]") ("zip3" . "[a] -> [b] -> [c] -> [(a,b,c)]") ("zipWith" . "(a->b->c) -> [a]->[b]->[c]") ("zipWith3" . "(a->b->c->d) -> [a]->[b]->[c]->[d]") ("||" . "Bool -> Bool -> Bool") ;; Ratio ("%" . "(Integral a) => a -> a -> Ratio a") ("approxRational" . "(RealFrac a) => a -> a -> Rational") ("denominator" . "(Integral a) => Ratio a -> a") ("numerator" . "(Integral a) => Ratio a -> a") ;; Complex ("cis" . "(RealFloat a) => a -> Complex a") ("conjugate" . "(RealFloat a) => Complex a -> Complex a") ("imagPart" . "(RealFloat a) => Complex a -> a") ("magnitude" . "(RealFloat a) => Complex a -> a") ("mkPolar" . "(RealFloat a) => a -> a -> Complex a") ("phase" . "(RealFloat a) => Complex a -> a") ("polar" . "(RealFloat a) => Complex a -> (a,a)") ("realPart" . "(RealFloat a) => Complex a -> a") ;; Numeric ("floatToDigits" . "(RealFloat a) => Integer -> a -> ([Int], Int)") ("fromRat" . "(RealFloat a) => Rational -> a") ("lexDigits" . "ReadS String") ("readDec" . "(Integral a) => ReadS a") ("readFloat" . "(RealFrac a) => ReadS a") ("readHex" . "(Integral a) => ReadS a") ("readInt" . "(Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a") ("readOct" . "(Integral a) => ReadS a") ("readSigned" . "(Real a) => ReadS a -> ReadS a") ("showEFloat" . "(RealFloat a) => Maybe Int -> a -> ShowS") ("showFFloat" . "(RealFloat a) => Maybe Int -> a -> ShowS") ("showFloat" . "(RealFloat a) => a -> ShowS") ("showGFloat" . "(RealFloat a) => Maybe Int -> a -> ShowS") ("showHex" . "Integral a => a -> ShowS") ("showInt" . "Integral a => a -> ShowS") ("showIntAtBase" . "Integral a => a -> (Int -> Char) -> a -> ShowS") ("showOct" . "Integral a => a -> ShowS") ("showSigned" . "(Real a) => (a -> ShowS) -> Int -> a -> ShowS") ;; Ix ("inRange" . "Ix a => (a,a) -> a -> Bool") ("index" . "Ix a => (a,a) -> a -> Int") ("range" . "Ix a => (a,a) -> [a]") ("rangeSize" . "Ix a => (a,a) -> Int") ;; Array ("!" . "(Ix a) => Array a b -> a -> b") ("//" . "(Ix a) => Array a b -> [(a,b)] -> Array a b") ("accum" . "(Ix a) => (b -> c -> b) -> Array a b -> [(a,c)]") ("accumArray" . "(Ix a) => (b -> c -> b) -> b -> (a,a) -> [(a,c)]") ("array" . "(Ix a) => (a,a) -> [(a,b)] -> Array a b") ("assocs" . "(Ix a) => Array a b -> [(a,b)]") ("bounds" . "(Ix a) => Array a b -> (a,a)") ("elems" . "(Ix a) => Array a b -> [b]") ("indices" . "(Ix a) => Array a b -> [a]") ("ixmap" . "(Ix a, Ix b) => (a,a) -> (a -> b) -> Array b c") ("listArray" . "(Ix a) => (a,a) -> [b] -> Array a b") ;; List ("\\\\" . "Eq a => [a] -> [a] -> [a]") ("delete" . "Eq a => a -> [a] -> [a]") ("deleteBy" . "(a -> a -> Bool) -> a -> [a] -> [a]") ("deleteFirstsBy" . "(a -> a -> Bool) -> [a] -> [a] -> [a]") ("elemIndex" . "Eq a => a -> [a] -> Maybe Int") ("elemIndices" . "Eq a => a -> [a] -> [Int]") ("find" . "(a -> Bool) -> [a] -> Maybe a") ("findIndex" . "(a -> Bool) -> [a] -> Maybe Int") ("findIndices" . "(a -> Bool) -> [a] -> [Int]") ("genericDrop" . "Integral a => a -> [b] -> [b]") ("genericIndex" . "Integral a => [b] -> a -> b") ("genericLength" . "Integral a => [b] -> a") ("genericReplicate" . "Integral a => a -> b -> [b]") ("genericSplitAt" . "Integral a => a -> [b] -> ([b],[b])") ("genericTake" . "Integral a => a -> [b] -> [b]") ("group" . "Eq a => [a] -> [[a]]") ("groupBy" . "(a -> a -> Bool) -> [a] -> [[a]]") ("inits" . "[a] -> [[a]]") ("insert" . "Ord a => a -> [a] -> [a]") ("insertBy" . "(a -> a -> Ordering) -> a -> [a] -> [a]") ("intersect" . "Eq a => [a] -> [a] -> [a]") ("intersectBy" . "(a -> a -> Bool) -> [a] -> [a] -> [a]") ("intersperse" . "a -> [a] -> [a]") ("isPrefixOf" . "Eq a => [a] -> [a] -> Bool") ("isSuffixOf" . "Eq a => [a] -> [a] -> Bool") ("mapAccumL" . "(a -> b -> (a, c)) -> a -> [b] -> (a, [c])") ("mapAccumR" . "(a -> b -> (a, c)) -> a -> [b] -> (a, [c])") ("maximumBy" . "(a -> a -> Ordering) -> [a] -> a") ("minimumBy" . "(a -> a -> Ordering) -> [a] -> a") ("nub" . "Eq a => [a] -> [a]") ("nubBy" . "(a -> a -> Bool) -> [a] -> [a]") ("partition" . "(a -> Bool) -> [a] -> ([a],[a])") ("sort" . "Ord a => [a] -> [a]") ("sortBy" . "(a -> a -> Ordering) -> [a] -> [a]") ("tails" . "[a] -> [[a]]") ("transpose" . "[[a]] -> [[a]]") ("unfoldr" . "(b -> Maybe (a,b)) -> b -> [a]") ("union" . "Eq a => [a] -> [a] -> [a]") ("unionBy" . "(a -> a -> Bool) -> [a] -> [a] -> [a]") ("unzip4" . "[(a,b,c,d)] -> ([a],[b],[c],[d])") ("unzip5" . "[(a,b,c,d,e)] -> ([a],[b],[c],[d],[e])") ("unzip6" . "[(a,b,c,d,e,f)] -> ([a],[b],[c],[d],[e],[f])") ("unzip7" . "[(a,b,c,d,e,f,g)] -> ([a],[b],[c],[d],[e],[f],[g])") ("zip4" . "[a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]") ("zip5" . "[a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]") ("zip6" . "[a] -> [b] -> [c] -> [d] -> [e] -> [f]") ("zip7" . "[a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]") ("zipWith4" . "(a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]") ("zipWith5" . "(a->b->c->d->e->f) ->") ("zipWith6" . "(a->b->c->d->e->f->g) -> [a]->[b]->[c]->[d]->[e]->[f]->[g]") ("zipWith7" . "(a->b->c->d->e->f->g->h) -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]") ;; Maybe ("catMaybes" . "[Maybe a] -> [a]") ("fromJust" . "Maybe a -> a") ("fromMaybe" . "a -> Maybe a -> a") ("isJust" . "Maybe a -> Bool") ("isNothing" . "Maybe a -> Bool") ("listToMaybe" . "[a] -> Maybe a") ("mapMaybe" . "(a -> Maybe b) -> [a] -> [b]") ("maybeToList" . "Maybe a -> [a]") ;; Char ("chr" . "Int -> Char") ("digitToInt" . "Char -> Int") ("intToDigit" . "Int -> Char") ("isAlpha" . "Char -> Bool") ("isAlphaNum" . "Char -> Bool") ("isAscii" . "Char -> Bool") ("isControl" . "Char -> Bool") ("isDigit" . "Char -> Bool") ("isHexDigit" . "Char -> Bool") ("isLatin1" . "Char -> Bool") ("isLower" . "Char -> Bool") ("isOctDigit" . "Char -> Bool") ("isPrint" . "Char -> Bool") ("isSpace" . "Char -> Bool") ("isUpper" . "Char -> Bool") ("lexLitChar" . "ReadS String") ("ord" . "Char -> Int") ("readLitChar" . "ReadS Char") ("showLitChar" . "Char -> ShowS") ("toLower" . "Char -> Char") ("toUpper" . "Char -> Char") ;; Monad ("ap" . "Monad m => m (a -> b) -> m a -> m b") ("filterM" . "Monad m => (a -> m Bool) -> [a] -> m [a]") ("foldM" . "Monad m => (a -> b -> m a) -> a -> [b] -> m a") ("guard" . "MonadPlus m => Bool -> m ()") ("join" . "Monad m => m (m a) -> m a") ("liftM" . "Monad m => (a -> b) -> (m a -> m b)") ("liftM2" . "Monad m => (a -> b -> c) -> (m a -> m b -> m c)") ("liftM3" . "Monad m => (a -> b -> c -> d) -> (m a -> m b -> m c -> m d)") ("liftM4" . "Monad m => (a -> b -> c -> d -> e) -> (m a -> m b -> m c -> m d -> m e)") ("liftM5" . "Monad m => (a -> b -> c -> d -> e -> f) -> (m a -> m b -> m c -> m d -> m e -> m f)") ("mapAndUnzipM" . "Monad m => (a -> m (b,c)) -> [a] -> m ([b], [c])") ("mplus" . "MonadPlus m => m a -> m a -> m a") ("msum" . "MonadPlus m => [m a] -> m a") ("mzero" . "MonadPlus m => m a") ("unless" . "Monad m => Bool -> m () -> m ()") ("when" . "Monad m => Bool -> m () -> m ()") ("zipWithM" . "Monad m => (a -> b -> m c) -> [a] -> [b] -> m [c]") ("zipWithM_" . "Monad m => (a -> b -> m c) -> [a] -> [b] -> m ()") ;; IO ("bracket" . "IO a -> (a -> IO b) -> (a -> IO c) -> IO c") ("bracket_" . "IO a -> (a -> IO b) -> IO c -> IO c") ("hClose" . "Handle -> IO ()") ("hFileSize" . "Handle -> IO Integer") ("hFlush" . "Handle -> IO ()") ("hGetBuffering" . "Handle -> IO BufferMode") ("hGetChar" . "Handle -> IO Char") ("hGetContents" . "Handle -> IO String") ("hGetLine" . "Handle -> IO String") ("hGetPosn" . "Handle -> IO HandlePosn") ("hIsClosed" . "Handle -> IO Bool") ("hIsEOF" . "Handle -> IO Bool") ("hIsOpen" . "Handle -> IO Bool") ("hIsReadable" . "Handle -> IO Bool") ("hIsSeekable" . "Handle -> IO Bool") ("hIsWritable" . "Handle -> IO Bool") ("hLookAhead" . "Handle -> IO Char") ("hPrint" . "Show a => Handle -> a -> IO ()") ("hPutChar" . "Handle -> Char -> IO ()") ("hPutStr" . "Handle -> String -> IO ()") ("hPutStrLn" . "Handle -> String -> IO ()") ("hReady" . "Handle -> IO Bool") ("hSeek" . "Handle -> SeekMode -> Integer -> IO ()") ("hSetBuffering" . "Handle -> BufferMode -> IO ()") ("hSetPosn" . "HandlePosn -> IO ()") ("hWaitForInput" . "Handle -> Int -> IO Bool") ("ioeGetErrorString" . "IOError -> String") ("ioeGetFileName" . "IOError -> Maybe FilePath") ("ioeGetHandle" . "IOError -> Maybe Handle") ("isAlreadyExistsError" . "IOError -> Bool") ("isAlreadyInUseError" . "IOError -> Bool") ("isDoesNotExistError" . "IOError -> Bool") ("isEOF" . "IO Bool") ("isEOFError" . "IOError -> Bool") ("isFullError" . "IOError -> Bool") ("isIllegalOperation" . "IOError -> Bool") ("isPermissionError" . "IOError -> Bool") ("isUserError" . "IOError -> Bool") ("openFile" . "FilePath -> IOMode -> IO Handle") ("stderr" . "Handle") ("stdin" . "Handle") ("stdout" . "Handle") ("try" . "IO a -> IO (Either IOError a)") ;; Directory ("createDirectory" . "FilePath -> IO ()") ("doesDirectoryExist" . "FilePath -> IO Bool") ("doesFileExist" . "FilePath -> IO Bool") ("executable" . "Permissions -> Bool") ("getCurrentDirectory" . "IO FilePath") ("getDirectoryContents" . "FilePath -> IO [FilePath]") ("getModificationTime" . "FilePath -> IO ClockTime") ("getPermissions" . "FilePath -> IO Permissions") ("readable" . "Permissions -> Bool") ("removeDirectory" . "FilePath -> IO ()") ("removeFile" . "FilePath -> IO ()") ("renameDirectory" . "FilePath -> FilePath -> IO ()") ("renameFile" . "FilePath -> FilePath -> IO ()") ("searchable" . "Permissions -> Bool") ("setCurrentDirectory" . "FilePath -> IO ()") ("setPermissions" . "FilePath -> Permissions -> IO ()") ("writable" . "Permissions -> Bool") ;; System ("exitFailure" . "IO a") ("exitWith" . "ExitCode -> IO a") ("getArgs" . "IO [String]") ("getEnv" . "String -> IO String") ("getProgName" . "IO String") ("system" . "String -> IO ExitCode") ;; Time ("addToClockTime" . "TimeDiff -> ClockTime -> ClockTime") ("calendarTimeToString" . "CalendarTime -> String") ("ctDay" . "CalendarTime -> Int") ("ctHour" . "CalendarTime -> Int") ("ctIsDST" . "CalendarTime -> Bool") ("ctMin" . "CalendarTime -> Int") ("ctMonth" . "CalendarTime -> Month") ("ctPicosec" . "CalendarTime -> Integer") ("ctSec" . "CalendarTime -> Int") ("ctTZ" . "CalendarTime -> Int") ("ctTZName" . "CalendarTime -> String") ("ctWDay" . "CalendarTime -> Day") ("ctYDay" . "CalendarTime -> Int") ("ctYear" . "CalendarTime -> Int") ("diffClockTimes" . "ClockTime -> ClockTime -> TimeDiff") ("formatCalendarTime" . "TimeLocale -> String -> CalendarTime -> String") ("getClockTime" . "IO ClockTime") ("tdDay" . "TimeDiff -> Int") ("tdHour" . "TimeDiff -> Int") ("tdMin" . "TimeDiff -> Int") ("tdMonth" . "TimeDiff -> Int") ("tdPicosec" . "TimeDiff -> Integer") ("tdSec" . "TimeDiff -> Int") ("tdYear" . "TimeDiff -> Int") ("toCalendarTime" . "ClockTime -> IO CalendarTime") ("toClockTime" . "CalendarTime -> ClockTime") ("toUTCTime" . "ClockTime -> CalendarTime") ;; Locale ("amPm" . "TimeLocale -> (String, String)") ("dateFmt" . "TimeLocale -> String") ("dateTimeFmt" . "TimeLocale -> String") ("defaultTimeLocale" . "TimeLocale") ("months" . "TimeLocale -> [(String, String)]") ("time12Fmt" . "TimeLocale -> String") ("timeFmt" . "TimeLocale -> String") ("wDays" . "TimeLocale -> [(String, String)]") ;; CPUTime ("cpuTimePrecision" . "Integer") ("getCPUTime" . "IO Integer") ;; Random ("genRange" . "RandomGen g => g -> (Int, Int)") ("getStdGen" . "IO StdGen") ("getStdRandom" . "(StdGen -> (a, StdGen)) -> IO a") ("mkStdGen" . "Int -> StdGen") ("newStdGen" . "IO StdGen") ("next" . "RandomGen g => g -> (Int, g)") ("random" . "(Random a, RandomGen g) => g -> (a, g)") ("randomIO" . "Random a => IO a") ("randomR" . "(Random a, RandomGen g) => (a, a) -> g -> (a, g)") ("randomRIO" . "Random a => (a,a) -> IO a") ("randomRs" . "(Random a, RandomGen g) => (a, a) -> g -> [a]") ("randoms" . "(Random a, RandomGen g) => g -> [a]") ("setStdGen" . "StdGen -> IO ()") ("split" . "RandomGen g => g -> (g, g)") ) "Alist of prelude functions and their types.") ;;@cindex haskell-doc-strategy-ids (defvar haskell-doc-strategy-ids (list '("par" . "Done -> Done -> Done ; [infixr 0]") '("seq" . "Done -> Done -> Done ; [infixr 1]") '("using" . "a -> Strategy a -> a ; [infixl 0]") '("demanding" . "a -> Done -> a ; [infixl 0]") '("sparking" . "a -> Done -> a ; [infixl 0]") '(">||" . "Done -> Done -> Done ; [infixr 2]") '(">|" . "Done -> Done -> Done ; [infixr 3]") '("$||" . "(a -> b) -> Strategy a -> a -> b ; [infixl 6]") '("$|" . "(a -> b) -> Strategy a -> a -> b ; [infixl 6]") '(".|" . "(b -> c) -> Strategy b -> (a -> b) -> (a -> c) ; [infixl 9]") '(".||" . "(b -> c) -> Strategy b -> (a -> b) -> (a -> c) ; [infixl 9]") '("-|" . "(a -> b) -> Strategy b -> (b -> c) -> (a -> c) ; [infixl 9]") '("-||" . "(a -> b) -> Strategy b -> (b -> c) -> (a -> c) ; [infixl 9]") '("Done" . "type Done = ()") '("Strategy" . "type Strategy a = a -> Done") '("r0" . "Strategy a") '("rwhnf" . "Eval a => Strategy a") '("rnf" . "Strategy a") '("NFData" . "class Eval a => NFData a where rnf :: Strategy a") '("NFDataIntegral" ."class (NFData a, Integral a) => NFDataIntegral a") '("NFDataOrd" . "class (NFData a, Ord a) => NFDataOrd a") '("markStrat" . "Int -> Strategy a -> Strategy a") '("seqPair" . "Strategy a -> Strategy b -> Strategy (a,b)") '("parPair" . "Strategy a -> Strategy b -> Strategy (a,b)") '("seqTriple" . "Strategy a -> Strategy b -> Strategy c -> Strategy (a,b,c)") '("parTriple" . "Strategy a -> Strategy b -> Strategy c -> Strategy (a,b,c)") '("parList" . "Strategy a -> Strategy [a]") '("parListN" . "(Integral b) => b -> Strategy a -> Strategy [a]") '("parListNth" . "Int -> Strategy a -> Strategy [a]") '("parListChunk" . "Int -> Strategy a -> Strategy [a]") '("parMap" . "Strategy b -> (a -> b) -> [a] -> [b]") '("parFlatMap" . "Strategy [b] -> (a -> [b]) -> [a] -> [b]") '("parZipWith" . "Strategy c -> (a -> b -> c) -> [a] -> [b] -> [c]") '("seqList" . "Strategy a -> Strategy [a]") '("seqListN" . "(Integral a) => a -> Strategy b -> Strategy [b]") '("seqListNth" . "Int -> Strategy b -> Strategy [b]") '("parBuffer" . "Int -> Strategy a -> [a] -> [a]") '("seqArr" . "(Ix b) => Strategy a -> Strategy (Array b a)") '("parArr" . "(Ix b) => Strategy a -> Strategy (Array b a)") '("fstPairFstList" . "(NFData a) => Strategy [(a,b)]") '("force" . "(NFData a) => a -> a ") '("sforce" . "(NFData a) => a -> b -> b") ) "Alist of strategy functions and their types as defined in Strategies.lhs.") (defvar haskell-doc-user-defined-ids nil "Alist of functions and strings defined by the user.") ;;@node Test membership, , Prelude types, Constants and Variables ;;@subsection Test membership ;;@cindex haskell-doc-is-of (defsubst haskell-doc-is-of (fn types) "Check whether FN is one of the functions in the alist TYPES and return the type." (assoc fn types) ) ;;@node Install as minor mode, Menubar Support, Constants and Variables, top ;;@section Install as minor mode ;; Put this minor mode on the global minor-mode-alist. (or (assq 'haskell-doc-mode (default-value 'minor-mode-alist)) (setq-default minor-mode-alist (append (default-value 'minor-mode-alist) '((haskell-doc-mode haskell-doc-minor-mode-string))))) ;;@node Menubar Support, Haskell Doc Mode, Install as minor mode, top ;;@section Menubar Support ;; a dummy definition needed for XEmacs (I know, it's horrible :-( ;;@cindex haskell-doc-install-keymap (defvar haskell-doc-keymap (let ((map (make-sparse-keymap))) (define-key map [visit] '("Visit FTP home site" . haskell-doc-visit-home)) (define-key map [submit] '("Submit bug report" . haskell-doc-submit-bug-report)) (define-key map [dummy] '("---" . nil)) (define-key map [make-index] '("Make global fct index" . haskell-doc-make-global-fct-index)) (define-key map [global-types-on] '("Toggle display of global types" . haskell-doc-show-global-types)) (define-key map [strategy-on] '("Toggle display of strategy ids" . haskell-doc-show-strategy)) (define-key map [user-defined-on] '("Toggle display of user defined ids" . haskell-doc-show-user-defined)) (define-key map [prelude-on] '("Toggle display of prelude functions" . haskell-doc-show-prelude)) (define-key map [reserved-ids-on] '("Toggle display of reserved ids" . haskell-doc-show-reserved)) (define-key map [haskell-doc-on] '("Toggle haskell-doc mode" . haskell-doc-mode)) map)) (defun haskell-doc-install-keymap () "Install a menu for `haskell-doc-mode' as a submenu of \"Hugs\"." (interactive) ;; Add the menu to the hugs menu as last entry. (let ((hugsmap (lookup-key (current-local-map) [menu-bar Hugs]))) (if (not (or (featurep 'xemacs) ; XEmacs has problems here (not (keymapp hugsmap)) (lookup-key hugsmap [haskell-doc]))) (if (functionp 'define-key-after) (define-key-after hugsmap [haskell-doc] (cons "Haskell-doc" haskell-doc-keymap) [Haskell-doc mode])))) ;; Add shortcuts for these commands. (local-set-key "\C-c\e/" 'haskell-doc-check-active) ;; Conflicts with the binding of haskell-insert-otherwise. ;; (local-set-key "\C-c\C-o" 'haskell-doc-mode) (local-set-key [(control shift meta mouse-3)] 'haskell-doc-ask-mouse-for-type)) ;;@node Haskell Doc Mode, Switch it on or off, Menubar Support, top ;;@section Haskell Doc Mode ;;@cindex haskell-doc-mode (defvar haskell-doc-timer nil) (defvar haskell-doc-buffers nil) ;;;###autoload (defun haskell-doc-mode (&optional arg) "Enter `haskell-doc-mode' for showing fct types in the echo area. See variable docstring." (interactive (list (or current-prefix-arg 'toggle))) (setq haskell-doc-mode (cond ((eq arg 'toggle) (not haskell-doc-mode)) (arg (> (prefix-numeric-value arg) 0)) (t))) ;; First, unconditionally turn the mode OFF. (setq haskell-doc-buffers (delq (current-buffer) haskell-doc-buffers)) ;; Refresh the buffers list. (dolist (buf haskell-doc-buffers) (unless (and (buffer-live-p buf) (with-current-buffer buf haskell-doc-mode)) (setq haskell-doc-buffers (delq buf haskell-doc-buffers)))) ;; Turn off the idle timer (or idle post-command-hook). (when (and haskell-doc-timer (null haskell-doc-buffers)) (cancel-timer haskell-doc-timer) (setq haskell-doc-timer nil)) (remove-hook 'post-command-hook 'haskell-doc-mode-print-current-symbol-info 'local) (when haskell-doc-mode ;; Turning the mode ON. (push (current-buffer) haskell-doc-buffers) (if (fboundp 'run-with-idle-timer) (unless haskell-doc-timer (setq haskell-doc-timer (run-with-idle-timer haskell-doc-idle-delay t 'haskell-doc-mode-print-current-symbol-info))) (add-hook 'post-command-hook 'haskell-doc-mode-print-current-symbol-info nil 'local)) (and haskell-doc-show-global-types (haskell-doc-make-global-fct-index)) ; build type index for global fcts (haskell-doc-install-keymap) (run-hooks 'haskell-doc-mode-hook)) (and (called-interactively-p 'any) (message "haskell-doc-mode is %s" (if haskell-doc-mode "enabled" "disabled"))) haskell-doc-mode) (defmacro haskell-doc-toggle-var (id prefix) ;; toggle variable or set it based on prefix value `(setq ,id (if ,prefix (>= (prefix-numeric-value ,prefix) 0) (not ,id))) ) ;;@cindex haskell-doc-show-global-types (defun haskell-doc-show-global-types (&optional prefix) "Turn on global types information in `haskell-doc-mode'." (interactive "P") (haskell-doc-toggle-var haskell-doc-show-global-types prefix) (if haskell-doc-show-global-types (haskell-doc-make-global-fct-index))) ;;@cindex haskell-doc-show-reserved (defun haskell-doc-show-reserved (&optional prefix) "Toggle the automatic display of a doc string for reserved ids." (interactive "P") (haskell-doc-toggle-var haskell-doc-show-reserved prefix)) ;;@cindex haskell-doc-show-prelude (defun haskell-doc-show-prelude (&optional prefix) "Toggle the automatic display of a doc string for reserved ids." (interactive "P") (haskell-doc-toggle-var haskell-doc-show-prelude prefix)) ;;@cindex haskell-doc-show-strategy (defun haskell-doc-show-strategy (&optional prefix) "Toggle the automatic display of a doc string for strategy ids." (interactive "P") (haskell-doc-toggle-var haskell-doc-show-strategy prefix)) ;;@cindex haskell-doc-show-user-defined (defun haskell-doc-show-user-defined (&optional prefix) "Toggle the automatic display of a doc string for user defined ids." (interactive "P") (haskell-doc-toggle-var haskell-doc-show-user-defined prefix)) ;;@node Switch it on or off, Check, Haskell Doc Mode, top ;;@section Switch it on or off ;;@cindex turn-on-haskell-doc-mode ;;;###autoload (defalias 'turn-on-haskell-doc-mode 'haskell-doc-mode) ;;;###autoload (defalias 'turn-on-haskell-doc 'haskell-doc-mode) ;;@cindex turn-off-haskell-doc-mode (defalias 'turn-off-haskell-doc-mode 'turn-off-haskell-doc) (defun turn-off-haskell-doc () "Unequivocally turn off `haskell-doc-mode' (which see)." (haskell-doc-mode 0)) ;;@node Check, Top level function, Switch it on or off, top ;;@section Check ;;@cindex haskell-doc-check-active (defun haskell-doc-check-active () "Check whether the print function is hooked in. Should be the same as the value of `haskell-doc-mode' but alas currently it is not." (interactive) (message "%s" (if (or (and haskell-doc-mode haskell-doc-timer) (memq 'haskell-doc-mode-print-current-symbol-info post-command-hook)) "haskell-doc is ACTIVE" (substitute-command-keys "haskell-doc is not ACTIVE \(Use \\[haskell-doc-mode] to turn it on\)")))) ;;@node Top level function, Mouse interface, Check, top ;;@section Top level function ;;@cindex haskell-doc-mode-print-current-symbol-info ;; This is the function hooked into the elisp command engine (defun haskell-doc-mode-print-current-symbol-info () "Print the type of the symbol under the cursor. This function is run by an idle timer to print the type automatically if `haskell-doc-mode' is turned on." (and haskell-doc-mode (not (eobp)) (not executing-kbd-macro) ;; Having this mode operate in the minibuffer makes it impossible to ;; see what you're doing. (not (eq (selected-window) (minibuffer-window))) ;; take a nap, if run straight from post-command-hook. (if (fboundp 'run-with-idle-timer) t (sit-for haskell-doc-idle-delay)) ;; good morning! read the word under the cursor for breakfast (haskell-doc-show-type))) ;; ;; ToDo: find surrounding fct ;; (cond ((eq current-symbol current-fnsym) ;; (haskell-doc-show-type current-fnsym)) ;; (t ;; (or nil ; (haskell-doc-print-var-docstring current-symbol) ;; (haskell-doc-show-type current-fnsym))))))) ;;;###autoload (defun haskell-doc-current-info () "Return the info about symbol at point. Meant for `eldoc-documentation-function'." (haskell-doc-sym-doc (haskell-ident-at-point))) ;;@node Mouse interface, Print fctsym, Top level function, top ;;@section Mouse interface for interactive query ;;@cindex haskell-doc-ask-mouse-for-type (defun haskell-doc-ask-mouse-for-type (event) "Read the identifier under the mouse and echo its type. This uses the same underlying function `haskell-doc-show-type' as the hooked function. Only the user interface is different." (interactive "e") (save-excursion (select-window (posn-window (event-end event))) (goto-char (posn-point (event-end event))) (haskell-doc-show-type))) ;;@node Print fctsym, Movement, Mouse interface, top ;;@section Print fctsym ;;@menu ;;* Show type:: ;;* Aux:: ;;* Global fct type:: ;;* Local fct type:: ;;@end menu ;;@node Show type, Aux, Print fctsym, Print fctsym ;;@subsection Show type ;;@cindex haskell-doc-show-type (defun haskell-doc-in-code-p () (not (or (and (eq haskell-literate 'bird) ;; Copied from haskell-indent-bolp. (<= (current-column) 2) (eq (char-after (line-beginning-position)) ?\>)) (nth 8 (syntax-ppss))))) ;;;###autoload (defun haskell-doc-show-type (&optional sym) "Show the type of the function near point. For the function under point, show the type in the echo area. This information is extracted from the `haskell-doc-prelude-types' alist of prelude functions and their types, or from the local functions in the current buffer." (interactive) (unless sym (setq sym (haskell-ident-at-point))) ;; if printed before do not print it again (unless (string= sym (car haskell-doc-last-data)) (let ((doc (haskell-doc-sym-doc sym))) (when (and doc (haskell-doc-in-code-p)) ;; In Emacs 19.29 and later, and XEmacs 19.13 and later, all ;; messages are recorded in a log. Do not put haskell-doc messages ;; in that log since they are legion. (if (eval-when-compile (fboundp 'display-message)) ;; XEmacs 19.13 way of preventing log messages. ;;(display-message 'no-log (format )) ;; XEmacs 19.15 seems to be a bit different. (display-message 'message (format "%s" doc)) (let ((message-log-max nil)) (message "%s" doc))))))) (defun haskell-doc-sym-doc (sym) "Show the type of the function near point. For the function under point, show the type in the echo area. This information is extracted from the `haskell-doc-prelude-types' alist of prelude functions and their types, or from the local functions in the current buffer. If `haskell-doc-use-inf-haskell' is non-nil, this function will consult the inferior Haskell process for type/kind information, rather than using the haskell-doc database." (if haskell-doc-use-inf-haskell (unless (string= "" sym) (let* ((message-log-max nil) (result (ignore-errors (unwind-protect (inferior-haskell-type sym) (message ""))))) (if (and result (string-match " :: " result)) result (setq result (unwind-protect (inferior-haskell-kind sym) (message ""))) (and result (string-match " :: " result) result)))) (let ((i-am-prelude nil) (i-am-fct nil) (type nil) (is-reserved (haskell-doc-is-of sym haskell-doc-reserved-ids)) (is-prelude (haskell-doc-is-of sym haskell-doc-prelude-types)) (is-strategy (haskell-doc-is-of sym haskell-doc-strategy-ids)) (is-user-defined (haskell-doc-is-of sym haskell-doc-user-defined-ids)) (is-prelude (haskell-doc-is-of sym haskell-doc-prelude-types))) (cond ;; if reserved id (i.e. Haskell keyword ((and haskell-doc-show-reserved is-reserved) (setq type (cdr is-reserved)) (setcdr haskell-doc-last-data type)) ;; if built-in function get type from docstring ((and (not (null haskell-doc-show-prelude)) is-prelude) (setq type (cdr is-prelude)) ; (cdr (assoc sym haskell-doc-prelude-types))) (if (= 2 (length type)) ; horrible hack to remove bad formatting (setq type (car (cdr type)))) (setq i-am-prelude t) (setq i-am-fct t) (setcdr haskell-doc-last-data type)) ((and haskell-doc-show-strategy is-strategy) (setq i-am-fct t) (setq type (cdr is-strategy)) (setcdr haskell-doc-last-data type)) ((and haskell-doc-show-user-defined is-user-defined) ;; (setq i-am-fct t) (setq type (cdr is-user-defined)) (setcdr haskell-doc-last-data type)) (t (let ( (x (haskell-doc-get-and-format-fct-type sym)) ) (if (null x) (setcdr haskell-doc-last-data nil) ; if not found reset last data (setq type (car x)) (setq i-am-fct (string= "Variables" (cdr x))) (if (and haskell-doc-show-global-types (null type)) (setq type (haskell-doc-get-global-fct-type sym))) (setcdr haskell-doc-last-data type)))) ) ;; ToDo: encode i-am-fct info into alist of types (and type ;; drop `::' if it's not a fct (let ( (str (cond ((and i-am-fct (not haskell-doc-chop-off-fctname)) (format "%s :: %s" sym type)) (t (format "%s" type)))) ) (if i-am-prelude (add-text-properties 0 (length str) '(face bold) str)) str))))) ;; ToDo: define your own notion of `near' to find surrounding fct ;;(defun haskell-doc-fnsym-in-current-sexp () ;; (let* ((p (point)) ;; (sym (progn ;; (forward-word -1) ;; (while (and (forward-word -1) ; (haskell-doc-forward-sexp-safe -1) ;; (> (point) (point-min)))) ;; (cond ((or (= (point) (point-min)) ;; (memq (or (char-after (point)) 0) ;; '(?\( ?\")) ;; ;; If we hit a quotation mark before a paren, we ;; ;; are inside a specific string, not a list of ;; ;; symbols. ;; (eq (or (char-after (1- (point))) 0) ?\")) ;; nil) ;; (t (condition-case nil ;; (read (current-buffer)) ;; (error nil))))))) ;; (goto-char p) ;; (if sym ;; (format "%s" sym) ;; sym))) ;; (and (symbolp sym) ;; sym))) ;;@node Aux, Global fct type, Show type, Print fctsym ;;@subsection Aux ;; ToDo: handle open brackets to decide if it's a wrapped type ;;@cindex haskell-doc-grab-line (defun haskell-doc-grab-line (fct-and-pos) "Get the type of an \(FCT POSITION\) pair from the current buffer." ;; (if (null fct-and-pos) ;; "" ; fn is not a local fct (let ( (str "")) (goto-char (cdr fct-and-pos)) (beginning-of-line) ;; search for start of type (phsp give better bound?) (if (null (search-forward "::" (+ (point) haskell-doc-search-distance) t)) "" (setq str (haskell-doc-grab)) ; leaves point at end of line (while (haskell-doc-wrapped-type-p) ; while in a multi-line type expr (forward-line 1) (beginning-of-line) (skip-chars-forward " \t") (setq str (concat str (haskell-doc-grab)))) (haskell-doc-string-nub-ws ; squeeze string (if haskell-doc-chop-off-context ; no context (haskell-doc-chop-off-context str) str))))) ;; (concat (car fct-and-pos) "::" (haskell-doc-string-nub-ws str)))) ;;@cindex haskell-doc-wrapped-type-p (defun haskell-doc-wrapped-type-p () "Check whether the type under the cursor is wrapped over several lines. The cursor must be at the end of a line, which contains the type. Currently, only the following is checked: If this line ends with a `->' or the next starts with an `->' it is a multi-line type \(same for `=>'\). `--' comments are ignored. ToDo: Check for matching parenthesis!." (save-excursion (let ( (here (point)) (lim (progn (beginning-of-line) (point))) ;; (foo "") (res nil) ) (goto-char here) (search-backward "--" lim t) ; skip over `--' comment (skip-chars-backward " \t") (if (bolp) ; skip empty lines (progn (forward-line 1) (end-of-line) (setq res (haskell-doc-wrapped-type-p))) (forward-char -1) ;; (setq foo (concat foo (char-to-string (preceding-char)) (char-to-string (following-char)))) (if (or (and (or (char-equal (preceding-char) ?-) (char-equal (preceding-char) ?=)) (char-equal (following-char) ?>)) ; (or -!> =!> (char-equal (following-char) ?,)) ; !,) (setq res t) (forward-line) (let ((here (point))) (goto-char here) (skip-chars-forward " \t") (if (looking-at "--") ; it is a comment line (progn (forward-line 1) (end-of-line) (setq res (haskell-doc-wrapped-type-p))) (forward-char 1) ;; (setq foo (concat foo (char-to-string (preceding-char)) (char-to-string (following-char)))) ;; (message "|%s|" foo) (if (and (or (char-equal (preceding-char) ?-) (char-equal (preceding-char) ?=)) (char-equal (following-char) ?>)) ; -!> or =!> (setq res t)))))) res))) ;;@cindex haskell-doc-grab (defun haskell-doc-grab () "Return the text from point to the end of the line, chopping off comments. Leaves point at end of line." (let ((str (buffer-substring-no-properties (point) (progn (end-of-line) (point))))) (if (string-match "--" str) (substring str 0 (match-beginning 0)) str))) ;;@cindex haskell-doc-string-nub-ws (defun haskell-doc-string-nub-ws (str) "Replace all sequences of whitespace in STR by just one space. ToDo: Also eliminate leading and trailing whitespace." (let ((i -1)) (while (setq i (string-match " [ \t\n]+\\|[\t\n]+" str (1+ i))) (setq str (replace-match " " t t str))) str)) ;; ToDo: make this more efficient!! ;;(defun haskell-doc-string-nub-ws (str) ;; "Replace all sequences of whitespaces in STR by just one whitespace." ;; (let ( (res "") ;; (l (length str)) ;; (i 0) ;; (j 0) ;; (in-ws nil)) ;; (while (< i l) ;; (let* ( (c (string-to-char (substring str i (1+ i)))) ;; (is-ws (eq (char-syntax c) ? )) ) ;; (if (not (and in-ws is-ws)) ;; (setq res (concat res (char-to-string c)))) ;; (setq in-ws is-ws) ;; (setq i (1+ i)))) ;; res)) ;;@cindex haskell-doc-chop-off-context (defun haskell-doc-chop-off-context (str) "Eliminate the context in a type represented by the string STR." (let ((i (string-match "=>" str)) ) (if (null i) str (substring str (+ i 2))))) ;;@cindex haskell-doc-get-imenu-info (defun haskell-doc-get-imenu-info (obj kind) "Return a string describing OBJ of KIND \(Variables, Types, Data\)." (cond ((eq major-mode 'haskell-mode) (let* ((imenu-info-alist (cdr (assoc kind imenu--index-alist))) ;; (names (mapcar 'car imenu-info-alist)) (x (assoc obj imenu-info-alist))) (when x (haskell-doc-grab-line x)))) (t ;; (error "Cannot get local functions in %s mode, sorry" major-mode))) nil))) ;;@node Global fct type, Local fct type, Aux, Print fctsym ;;@subsection Global fct type ;; ToDo: ;; - modular way of defining a mapping of module name to file ;; - use a path to search for file (not just current directory) ;;@cindex haskell-doc-imported-list (defun haskell-doc-imported-list () "Return a list of the imported modules in current buffer." (interactive "fName of outer `include' file: ") ; (buffer-file-name)) ;; Don't add current buffer to the imported file list if it is not (yet?) ;; visiting a file since it leads to errors further down. (let ((imported-file-list (and buffer-file-name (list buffer-file-name)))) (widen) (goto-char (point-min)) (while (re-search-forward "^\\s-*import\\s-+\\([^ \t\n]+\\)" nil t) (let ((basename (match-string 1))) (dolist (ext '(".hs" ".lhs")) (let ((file (concat basename ext))) (if (file-exists-p file) (push file imported-file-list)))))) (nreverse imported-file-list) ;;(message imported-file-list) )) ;; ToDo: generalise this to "Types" etc (not just "Variables") ;;@cindex haskell-doc-rescan-files (defun haskell-doc-rescan-files (filelist) "Do an `imenu' rescan on every file in FILELIST and return the fct-list. This function switches to and potentially loads many buffers." (save-current-buffer (mapcar (lambda (f) (set-buffer (find-file-noselect f)) (imenu--make-index-alist) (cons f (mapcar (lambda (x) `(,(car x) . ,(haskell-doc-grab-line x))) (cdr (assoc "Variables" imenu--index-alist))))) filelist))) ;;@cindex haskell-doc-make-global-fct-index (defun haskell-doc-make-global-fct-index () "Scan imported files for types of global fcts and update `haskell-doc-index'." (interactive) (setq haskell-doc-index (haskell-doc-rescan-files (haskell-doc-imported-list)))) ;; ToDo: use a separate munge-type function to format type concisely ;;@cindex haskell-doc-get-global-fct-type (defun haskell-doc-get-global-fct-type (&optional sym) "Get type for function symbol SYM by examining `haskell-doc-index'." (interactive) ; "fName of outer `include' file: \nsFct:") (save-excursion ;; (switch-to-buffer "*scratch*") ;; (goto-char (point-max)) ;; ;; Produces a list of fct-type alists ;; (if (null sym) ;; (setq sym (progn (forward-word -1) (read (current-buffer))))) (or sym (current-word)) (let* ( (fn sym) ; (format "%s" sym)) (fal haskell-doc-index) (res "") ) (while (not (null fal)) (let* ( (l (car fal)) (f (car l)) (x (assoc fn (cdr l))) ) (if (not (null x)) (let* ( (ty (cdr x)) ; the type as string (idx (string-match "::" ty)) (str (if (null idx) ty (substring ty (+ idx 2)))) ) (setq res (format "[%s] %s" f str)))) (setq fal (cdr fal)))) res))) ; (message res)) ) ;;@node Local fct type, , Global fct type, Print fctsym ;;@subsection Local fct type ;;@cindex haskell-doc-get-and-format-fct-type (defun haskell-doc-get-and-format-fct-type (fn) "Get the type and kind of FN by checking local and global functions." (save-excursion (save-match-data (let ((docstring "") (doc nil) ) ;; is it a local function? (setq docstring (haskell-doc-get-imenu-info fn "Variables")) (if (not (null docstring)) ;; (string-match (format "^%s\\s-+::\\s-+\\(.*\\)$" fn) docstring)) (setq doc `(,docstring . "Variables"))) ; `(,(match-string 1 docstring) . "Variables") )) ;; is it a type declaration? (setq docstring (haskell-doc-get-imenu-info fn "Types")) (if (not (null docstring)) ;; (string-match (format "^\\s-*type\\s-+%s.*$" fn) docstring)) (setq doc `(,docstring . "Types"))) ; `(,(match-string 0 docstring) . "Types")) ) (if (not (null docstring)) ;; (string-match (format "^\\s-*data.*%s.*$" fn) docstring)) (setq doc `(,docstring . "Data"))) ; (setq doc `(,(match-string 0 docstring) . "Data")) ) ;; return the result doc )))) ;;@appendix ;;@node Index, Token, Visit home site, top ;;@section Index ;;@index ;;* haskell-doc-ask-mouse-for-type:: ;;* haskell-doc-check-active:: ;;* haskell-doc-chop-off-context:: ;;* haskell-doc-get-and-format-fct-type:: ;;* haskell-doc-get-global-fct-type:: ;;* haskell-doc-get-imenu-info:: ;;* haskell-doc-grab:: ;;* haskell-doc-grab-line:: ;;* haskell-doc-imported-list:: ;;* haskell-doc-install-keymap:: ;;* haskell-doc-is-of:: ;;* haskell-doc-make-global-fct-index:: ;;* haskell-doc-mode:: ;;* haskell-doc-mode-print-current-symbol-info:: ;;* haskell-doc-prelude-types:: ;;* haskell-doc-rescan-files:: ;;* haskell-doc-reserved-ids:: ;;* haskell-doc-show-global-types:: ;;* haskell-doc-show-prelude:: ;;* haskell-doc-show-reserved:: ;;* haskell-doc-show-strategy:: ;;* haskell-doc-show-type:: ;;* haskell-doc-show-user-defined:: ;;* haskell-doc-strategy-ids:: ;;* haskell-doc-string-nub-ws:: ;;* haskell-doc-submit-bug-report:: ;;* haskell-doc-visit-home:: ;;* haskell-doc-wrapped-type-p:: ;;* turn-off-haskell-doc-mode:: ;;* turn-on-haskell-doc-mode:: ;;@end index ;;@node Token, , Index, top ;;@section Token (provide 'haskell-doc) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-doc.el ends here haskell-mode-13.10/haskell-font-lock.el000066400000000000000000000707641225210037200177320ustar00rootroot00000000000000;;; haskell-font-lock.el --- Font locking module for Haskell Mode ;; Copyright 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. ;; Copyright 1997-1998 Graeme E Moss, and Tommy Thorn ;; Author: 1997-1998 Graeme E Moss ;; 1997-1998 Tommy Thorn ;; 2003 Dave Love ;; Keywords: faces files Haskell ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; Purpose: ;; ;; To support fontification of standard Haskell keywords, symbols, ;; functions, etc. Supports full Haskell 1.4 as well as LaTeX- and ;; Bird-style literate scripts. ;; ;; Installation: ;; ;; To turn font locking on for all Haskell buffers under the Haskell ;; mode of Moss&Thorn, add this to .emacs: ;; ;; (add-hook 'haskell-mode-hook 'turn-on-haskell-font-lock) ;; ;; Otherwise, call `turn-on-haskell-font-lock'. ;; ;; ;; Customisation: ;; ;; The colours and level of font locking may be customised. See the ;; documentation on `turn-on-haskell-font-lock' for more details. ;; ;; Present Limitations/Future Work (contributions are most welcome!): ;; ;; . Debatable whether `()' `[]' `(->)' `(,)' `(,,)' etc. should be ;; highlighted as constructors or not. Should the `->' in ;; `id :: a -> a' be considered a constructor or a keyword? If so, ;; how do we distinguish this from `\x -> x'? What about the `\'? ;; ;; . XEmacs can support both `--' comments and `{- -}' comments ;; simultaneously. If XEmacs is detected, this should be used. ;; ;; . Support for GreenCard? ;; ;; ;; All functions/variables start with ;; `(turn-(on/off)-)haskell-font-lock' or `haskell-fl-'. ;;; Change Log: ;; Version 1.3: ;; From Dave Love: ;; Support for proper behaviour (including with Unicode identifiers) ;; in Emacs 21 only hacked in messily to avoid disturbing the old ;; stuff. Needs integrating more cleanly. Allow literate comment ;; face to be customized. Some support for fontifying definitions. ;; (I'm not convinced the faces should be customizable -- fontlock ;; faces are normally expected to be consistent.) ;; ;; Version 1.2: ;; Added support for LaTeX-style literate scripts. Allow whitespace ;; after backslash to end a line for string continuations. ;; ;; Version 1.1: ;; Use own syntax table. Use backquote (neater). Stop ''' being ;; highlighted as quoted character. Fixed `\"' fontification bug ;; in comments. ;; ;; Version 1.0: ;; Brought over from Haskell mode v1.1. ;;; Code: (require 'haskell-mode) (require 'font-lock) (with-no-warnings (require 'cl)) (defcustom haskell-font-lock-symbols nil "Display \\ and -> and such using symbols in fonts. This may sound like a neat trick, but be extra careful: it changes the alignment and can thus lead to nasty surprises w.r.t layout. If t, try to use whichever font is available. Otherwise you can set it to a particular font of your preference among `japanese-jisx0208' and `unicode'." :group 'haskell :type '(choice (const nil) (const t) (const unicode) (const japanese-jisx0208))) (defconst haskell-font-lock-symbols-alist (append ;; Prefer single-width Unicode font for lambda. (and (fboundp 'decode-char) (memq haskell-font-lock-symbols '(t unicode)) (list (cons "\\" (decode-char 'ucs 955)))) ;; The symbols can come from a JIS0208 font. (and (fboundp 'make-char) (fboundp 'charsetp) (charsetp 'japanese-jisx0208) (memq haskell-font-lock-symbols '(t japanese-jisx0208)) (list (cons "not" (make-char 'japanese-jisx0208 34 76)) (cons "\\" (make-char 'japanese-jisx0208 38 75)) (cons "->" (make-char 'japanese-jisx0208 34 42)) (cons "<-" (make-char 'japanese-jisx0208 34 43)) (cons "=>" (make-char 'japanese-jisx0208 34 77)) ;; FIXME: I'd like to either use ∀ or ∃ depending on how the ;; `forall' keyword is used, but currently the rest of the ;; code assumes that such ambiguity doesn't happen :-( (cons "forall" (make-char 'japanese-jisx0208 34 79)))) ;; Or a unicode font. (and (fboundp 'decode-char) (memq haskell-font-lock-symbols '(t unicode)) (list (cons "not" (decode-char 'ucs 172)) (cons "->" (decode-char 'ucs 8594)) (cons "<-" (decode-char 'ucs 8592)) (cons "=>" (decode-char 'ucs 8658)) (cons "()" (decode-char 'ucs #X2205)) (cons "==" (decode-char 'ucs #X2261)) (cons "/=" (decode-char 'ucs #X2262)) (cons ">=" (decode-char 'ucs #X2265)) (cons "<=" (decode-char 'ucs #X2264)) (cons "!!" (decode-char 'ucs #X203C)) (cons "&&" (decode-char 'ucs #X2227)) (cons "||" (decode-char 'ucs #X2228)) (cons "sqrt" (decode-char 'ucs #X221A)) (cons "undefined" (decode-char 'ucs #X22A5)) (cons "pi" (decode-char 'ucs #X3C0)) (cons "~>" (decode-char 'ucs 8669)) ;; Omega language ;; (cons "~>" (decode-char 'ucs 8605)) ;; less desirable (cons "-<" (decode-char 'ucs 8610)) ;; Paterson's arrow syntax ;; (cons "-<" (decode-char 'ucs 10521)) ;; nicer but uncommon (cons "::" (decode-char 'ucs 8759)) (list "." (decode-char 'ucs 8728) ; (decode-char 'ucs 9675) ;; Need a predicate here to distinguish the . used by ;; forall . . 'haskell-font-lock-dot-is-not-composition) (cons "forall" (decode-char 'ucs 8704))))) "Alist mapping Haskell symbols to chars. Each element has the form (STRING . CHAR) or (STRING CHAR PREDICATE). STRING is the Haskell symbol. CHAR is the character with which to represent this symbol. PREDICATE if present is a function of one argument (the start position of the symbol) which should return non-nil if this mapping should be disabled at that position.") (defun haskell-font-lock-dot-is-not-composition (start) "Return non-nil if the \".\" at START is not a composition operator. This is the case if the \".\" is part of a \"forall . \"." (save-excursion (goto-char start) (re-search-backward "\\[^.\"]*\\=" (line-beginning-position) t))) ;; Use new vars for the font-lock faces. The indirection allows people to ;; use different faces than in other modes, as before. (defvar haskell-keyword-face 'font-lock-keyword-face) (defvar haskell-constructor-face 'font-lock-type-face) ;; This used to be `font-lock-variable-name-face' but it doesn't result in ;; a highlighting that's consistent with other modes (it's mostly used ;; for function defintions). (defvar haskell-definition-face 'font-lock-function-name-face) ;; This is probably just wrong, but it used to use ;; `font-lock-function-name-face' with a result that was not consistent with ;; other major modes, so I just exchanged with `haskell-definition-face'. (defvar haskell-operator-face 'font-lock-variable-name-face) (defvar haskell-default-face nil) (defvar haskell-literate-comment-face 'font-lock-doc-face "Face with which to fontify literate comments. Set to `default' to avoid fontification of them.") (defconst haskell-emacs21-features (string-match "[[:alpha:]]" "x") "Non-nil if we have regexp char classes. Assume this means we have other useful features from Emacs 21.") (defun haskell-font-lock-compose-symbol (alist) "Compose a sequence of ascii chars into a symbol. Regexp match data 0 points to the chars." ;; Check that the chars should really be composed into a symbol. (let* ((start (match-beginning 0)) (end (match-end 0)) (syntaxes (cond ((eq (char-syntax (char-after start)) ?w) '(?w)) ;; Special case for the . used for qualified names. ((and (eq (char-after start) ?\.) (= end (1+ start))) '(?_ ?\\ ?w)) (t '(?_ ?\\)))) sym-data) (if (or (memq (char-syntax (or (char-before start) ?\ )) syntaxes) (memq (char-syntax (or (char-after end) ?\ )) syntaxes) (memq (get-text-property start 'face) '(font-lock-doc-face font-lock-string-face font-lock-comment-face)) (and (consp (setq sym-data (cdr (assoc (match-string 0) alist)))) (let ((pred (cadr sym-data))) (setq sym-data (car sym-data)) (funcall pred start)))) ;; No composition for you. Let's actually remove any composition ;; we may have added earlier and which is now incorrect. (remove-text-properties start end '(composition)) ;; That's a symbol alright, so add the composition. (compose-region start end sym-data))) ;; Return nil because we're not adding any face property. nil) (defun haskell-font-lock-symbols-keywords () (when (fboundp 'compose-region) (let ((alist nil)) (dolist (x haskell-font-lock-symbols-alist) (when (and (if (fboundp 'char-displayable-p) (char-displayable-p (if (consp (cdr x)) (cadr x) (cdr x))) (if (fboundp 'latin1-char-displayable-p) (latin1-char-displayable-p (if (consp (cdr x)) (cadr x) (cdr x))) t)) (not (assoc (car x) alist))) ; Not yet in alist. (push x alist))) (when alist `((,(regexp-opt (mapcar 'car alist) t) (0 (haskell-font-lock-compose-symbol ',alist) ;; In Emacs-21, if the `override' field is nil, the face ;; expressions is only evaluated if the text has currently ;; no face. So force evaluation by using `keep'. keep))))))) ;; The font lock regular expressions. (defun haskell-font-lock-keywords-create (literate) "Create fontification definitions for Haskell scripts. Returns keywords suitable for `font-lock-keywords'." (let* (;; Bird-style literate scripts start a line of code with ;; "^>", otherwise a line of code starts with "^". (line-prefix (if (eq literate 'bird) "^> ?" "^")) ;; Most names are borrowed from the lexical syntax of the Haskell ;; report. ;; Some of these definitions have been superseded by using the ;; syntax table instead. ;; (ASCsymbol "-!#$%&*+./<=>?@\\\\^|~") ;; Put the minus first to make it work in ranges. ;; We allow _ as the first char to fit GHC (varid "\\b[[:lower:]_][[:alnum:]'_]*\\b") ;; We allow ' preceding conids because of DataKinds/PolyKinds (conid "\\b'?[[:upper:]][[:alnum:]'_]*\\b") (modid (concat "\\b" conid "\\(\\." conid "\\)*\\b")) (qvarid (concat modid "\\." varid)) (qconid (concat modid "\\." conid)) (sym ;; We used to use the below for non-Emacs21, but I think the ;; regexp based on syntax works for other emacsen as well. -- Stef ;; (concat "[" symbol ":]+") ;; Add backslash to the symbol-syntax chars. This seems to ;; be thrown for some reason by backslash's escape syntax. "\\(\\s_\\|\\\\\\)+") ;; Reserved operations (reservedsym (concat "\\S_" ;; (regexp-opt '(".." "::" "=" "\\" "|" "<-" "->" ;; "@" "~" "=>") t) "\\(->\\|\\.\\.\\|::\\|∷\\|<-\\|=>\\|[=@\\|~]\\)" "\\S_")) ;; Reserved identifiers (reservedid (concat "\\<" ;; `as', `hiding', and `qualified' are part of the import ;; spec syntax, but they are not reserved. ;; `_' can go in here since it has temporary word syntax. ;; (regexp-opt ;; '("case" "class" "data" "default" "deriving" "do" ;; "else" "if" "import" "in" "infix" "infixl" ;; "infixr" "instance" "let" "module" "newtype" "of" ;; "then" "type" "where" "_") t) "\\(_\\|c\\(ase\\|lass\\)\\|d\\(ata\\|e\\(fault\\|riving\\)\\|o\\)\\|else\\|i\\(mport\\|n\\(fix[lr]?\\|stance\\)\\|[fn]\\)\\|let\\|module\\|mdo\\|newtype\\|of\\|rec\\|proc\\|t\\(hen\\|ype\\)\\|where\\)" "\\>")) ;; This unreadable regexp matches strings and character ;; constants. We need to do this with one regexp to handle ;; stuff like '"':"'". The regexp is the composition of ;; "([^"\\]|\\.)*" for strings and '([^\\]|\\.[^']*)' for ;; characters, allowing for string continuations. ;; Could probably be improved... (string-and-char (concat "\\(\\(\"\\|" line-prefix "[ \t]*\\\\\\)\\([^\"\\\\\n]\\|\\\\.\\)*\\(\"\\|\\\\[ \t]*$\\)\\|'\\([^'\\\\\n]\\|\\\\.[^'\n]*\\)'\\)")) ;; Top-level declarations (topdecl-var (concat line-prefix "\\(" varid "\\)\\s-*" ;; optionally allow for a single newline after identifier ;; NOTE: not supported for bird-style .lhs files (if (eq literate 'bird) nil "\\([\n]\\s-+\\)?") ;; A toplevel declaration can be followed by a definition ;; (=), a type (::) or (∷), a guard, or a pattern which can ;; either be a variable, a constructor, a parenthesized ;; thingy, or an integer or a string. "\\(" varid "\\|" conid "\\|::\\|∷\\|=\\||\\|\\s(\\|[0-9\"']\\)")) (topdecl-var2 (concat line-prefix "\\(" varid "\\|" conid "\\)\\s-*`\\(" varid "\\)`")) (topdecl-sym (concat line-prefix "\\(" varid "\\|" conid "\\)\\s-*\\(" sym "\\)")) (topdecl-sym2 (concat line-prefix "(\\(" sym "\\))")) keywords) (setq keywords `(;; NOTICE the ordering below is significant ;; ("^<<<<<<< .*$" 0 'font-lock-warning-face t) ("^=======" 0 'font-lock-warning-face t) ("^>>>>>>> .*$" 0 'font-lock-warning-face t) ("^#.*$" 0 'font-lock-preprocessor-face t) ,@(unless haskell-emacs21-features ;Supports nested comments? ;; Expensive. `((,string-and-char 1 font-lock-string-face))) ;; This was originally at the very end (and needs to be after ;; all the comment/string/doc highlighting) but it seemed to ;; trigger a bug in Emacs-21.3 which caused the compositions to ;; be "randomly" dropped. Moving it earlier seemed to reduce ;; the occurrence of the bug. ,@(haskell-font-lock-symbols-keywords) (,reservedid 1 (symbol-value 'haskell-keyword-face)) (,reservedsym 1 (symbol-value 'haskell-operator-face)) ;; Special case for `as', `hiding', `safe' and `qualified', which are ;; keywords in import statements but are not otherwise reserved. ("\\\\)[ \t]*\\)?\\(?:\\(qualified\\>\\)[ \t]*\\)?[^ \t\n()]+[ \t]*\\(?:\\(\\\\)[ \t]*[^ \t\n()]+[ \t]*\\)?\\(\\\\)?" (1 (symbol-value 'haskell-keyword-face) nil lax) (2 (symbol-value 'haskell-keyword-face) nil lax) (3 (symbol-value 'haskell-keyword-face) nil lax) (4 (symbol-value 'haskell-keyword-face) nil lax)) (,reservedsym 1 (symbol-value 'haskell-operator-face)) ;; Special case for `foreign import' ;; keywords in foreign import statements but are not otherwise reserved. ("\\<\\(foreign\\)[ \t]+\\(import\\)[ \t]+\\(?:\\(ccall\\|stdcall\\|cplusplus\\|jvm\\|dotnet\\)[ \t]+\\)?\\(?:\\(safe\\|unsafe\\|interruptible\\)[ \t]+\\)?" (1 (symbol-value 'haskell-keyword-face) nil lax) (2 (symbol-value 'haskell-keyword-face) nil lax) (3 (symbol-value 'haskell-keyword-face) nil lax) (4 (symbol-value 'haskell-keyword-face) nil lax)) (,reservedsym 1 (symbol-value 'haskell-operator-face)) ;; Special case for `foreign export' ;; keywords in foreign export statements but are not otherwise reserved. ("\\<\\(foreign\\)[ \t]+\\(export\\)[ \t]+\\(?:\\(ccall\\|stdcall\\|cplusplus\\|jvm\\|dotnet\\)[ \t]+\\)?" (1 (symbol-value 'haskell-keyword-face) nil lax) (2 (symbol-value 'haskell-keyword-face) nil lax) (3 (symbol-value 'haskell-keyword-face) nil lax)) ;; Toplevel Declarations. ;; Place them *before* generic id-and-op highlighting. (,topdecl-var (1 (symbol-value 'haskell-definition-face))) (,topdecl-var2 (2 (symbol-value 'haskell-definition-face))) (,topdecl-sym (2 (symbol-value 'haskell-definition-face))) (,topdecl-sym2 (1 (symbol-value 'haskell-definition-face))) ;; These four are debatable... ("(\\(,*\\|->\\))" 0 (symbol-value 'haskell-constructor-face)) ("\\[\\]" 0 (symbol-value 'haskell-constructor-face)) ;; Expensive. (,qvarid 0 (symbol-value 'haskell-default-face)) (,qconid 0 (symbol-value 'haskell-constructor-face)) (,(concat "\`" varid "\`") 0 (symbol-value 'haskell-operator-face)) ;; Expensive. (,conid 0 (symbol-value 'haskell-constructor-face)) ;; Very expensive. (,sym 0 (if (eq (char-after (match-beginning 0)) ?:) haskell-constructor-face haskell-operator-face)))) (unless (boundp 'font-lock-syntactic-keywords) (case literate (bird (setq keywords `(("^[^>\n].*$" 0 haskell-comment-face t) ,@keywords ("^>" 0 haskell-default-face t)))) ((latex tex) (setq keywords `((haskell-fl-latex-comments 0 'font-lock-comment-face t) ,@keywords))))) keywords)) ;; The next three aren't used in Emacs 21. (defvar haskell-fl-latex-cache-pos nil "Position of cache point used by `haskell-fl-latex-cache-in-comment'. Should be at the start of a line.") (defvar haskell-fl-latex-cache-in-comment nil "If `haskell-fl-latex-cache-pos' is outside a \\begin{code}..\\end{code} block (and therefore inside a comment), this variable is set to t, otherwise nil.") (defun haskell-fl-latex-comments (end) "Sets `match-data' according to the region of the buffer before end that should be commented under LaTeX-style literate scripts." (let ((start (point))) (if (= start end) ;; We're at the end. No more to fontify. nil (if (not (eq start haskell-fl-latex-cache-pos)) ;; If the start position is not cached, calculate the state ;; of the start. (progn (setq haskell-fl-latex-cache-pos start) ;; If the previous \begin{code} or \end{code} is a ;; \begin{code}, then start is not in a comment, otherwise ;; it is in a comment. (setq haskell-fl-latex-cache-in-comment (if (and (re-search-backward "^\\(\\(\\\\begin{code}\\)\\|\\(\\\\end{code}\\)\\)$" (point-min) t) (match-end 2)) nil t)) ;; Restore position. (goto-char start))) (if haskell-fl-latex-cache-in-comment (progn ;; If start is inside a comment, search for next \begin{code}. (re-search-forward "^\\\\begin{code}$" end 'move) ;; Mark start to end of \begin{code} (if present, till end ;; otherwise), as a comment. (set-match-data (list start (point))) ;; Return point, as a normal regexp would. (point)) ;; If start is inside a code block, search for next \end{code}. (if (re-search-forward "^\\\\end{code}$" end t) ;; If one found, mark it as a comment, otherwise finish. (point)))))) (defconst haskell-basic-syntactic-keywords '(;; Character constants (since apostrophe can't have string syntax). ;; Beware: do not match something like 's-}' or '\n"+' since the first ' ;; might be inside a comment or a string. ;; This still gets fooled with "'"'"'"'"'"', but ... oh well. ("\\Sw\\('\\)\\([^\\'\n]\\|\\\\.[^\\'\n \"}]*\\)\\('\\)" (1 "|") (3 "|")) ;; The \ is not escaping in \(x,y) -> x + y. ("\\(\\\\\\)(" (1 ".")) ;; The second \ in a gap does not quote the subsequent char. ;; It's probably not worth the trouble, tho. ;; ("^[ \t]*\\(\\\\\\)" (1 ".")) ;; Deal with instances of `--' which don't form a comment ("\\s_\\{3,\\}" (0 (cond ((numberp (nth 4 (syntax-ppss))) ;; There are no such instances inside nestable comments nil) ((string-match "\\`-*\\'" (match-string 0)) ;; Sequence of hyphens. Do nothing in ;; case of things like `{---'. nil) (t "_")))) ; other symbol sequence )) (defconst haskell-bird-syntactic-keywords (cons '("^[^\n>]" (0 "<")) haskell-basic-syntactic-keywords)) (defconst haskell-latex-syntactic-keywords (append '(("^\\\\begin{code}\\(\n\\)" 1 "!") ;; Note: buffer is widened during font-locking. ("\\`\\(.\\|\n\\)" (1 "!")) ; start comment at buffer start ("^\\(\\\\\\)end{code}$" 1 "!")) haskell-basic-syntactic-keywords)) (defcustom haskell-font-lock-haddock (boundp 'font-lock-doc-face) "If non-nil try to highlight Haddock comments specially." :type 'boolean :group 'haskell) (defvar haskell-font-lock-seen-haddock nil) (make-variable-buffer-local 'haskell-font-lock-seen-haddock) (defun haskell-syntactic-face-function (state) "`font-lock-syntactic-face-function' for Haskell." (cond ((nth 3 state) font-lock-string-face) ; as normal ;; Else comment. If it's from syntax table, use default face. ((or (eq 'syntax-table (nth 7 state)) (and (eq haskell-literate 'bird) (memq (char-before (nth 8 state)) '(nil ?\n)))) haskell-literate-comment-face) ;; Try and recognize Haddock comments. From what I gather from its ;; documentation, its comments can take the following forms: ;; a) {-| ... -} ;; b) {-^ ... -} ;; c) -- | ... ;; d) -- ^ ... ;; e) -- ... ;; Where `e' is the tricky one: it is only a Haddock comment if it ;; follows immediately another Haddock comment. Even an empty line ;; breaks such a sequence of Haddock comments. It is not clear if `e' ;; can follow any other case, so I interpreted it as following only cases ;; c,d,e (not a or b). In any case, this `e' is expensive since it ;; requires extra work for each and every non-Haddock comment, so I only ;; go through the more expensive check if we've already seen a Haddock ;; comment in the buffer. ((and haskell-font-lock-haddock (save-excursion (goto-char (nth 8 state)) (or (looking-at "\\(-- \\|{-\\)[ \\t]*[|^]") (and haskell-font-lock-seen-haddock (looking-at "-- ") (let ((doc nil) pos) (while (and (not doc) (setq pos (line-beginning-position)) (forward-comment -1) (eq (line-beginning-position 2) pos) (looking-at "--\\( [|^]\\)?")) (setq doc (match-beginning 1))) doc))))) (set (make-local-variable 'haskell-font-lock-seen-haddock) t) font-lock-doc-face) (t font-lock-comment-face))) (defconst haskell-font-lock-keywords (haskell-font-lock-keywords-create nil) "Font lock definitions for non-literate Haskell.") (defconst haskell-font-lock-bird-literate-keywords (haskell-font-lock-keywords-create 'bird) "Font lock definitions for Bird-style literate Haskell.") (defconst haskell-font-lock-latex-literate-keywords (haskell-font-lock-keywords-create 'latex) "Font lock definitions for LaTeX-style literate Haskell.") ;;;###autoload (defun haskell-font-lock-choose-keywords () (let ((literate (if (boundp 'haskell-literate) haskell-literate))) (case literate (bird haskell-font-lock-bird-literate-keywords) ((latex tex) haskell-font-lock-latex-literate-keywords) (t haskell-font-lock-keywords)))) (defun haskell-font-lock-choose-syntactic-keywords () (let ((literate (if (boundp 'haskell-literate) haskell-literate))) (case literate (bird haskell-bird-syntactic-keywords) ((latex tex) haskell-latex-syntactic-keywords) (t haskell-basic-syntactic-keywords)))) (defun haskell-font-lock-defaults-create () "Locally set `font-lock-defaults' for Haskell." (set (make-local-variable 'font-lock-defaults) '(haskell-font-lock-choose-keywords nil nil ((?\' . "w") (?_ . "w")) nil (font-lock-syntactic-keywords . haskell-font-lock-choose-syntactic-keywords) (font-lock-syntactic-face-function . haskell-syntactic-face-function) ;; Get help from font-lock-syntactic-keywords. (parse-sexp-lookup-properties . t)))) ;; The main functions. (defun turn-on-haskell-font-lock () "Turns on font locking in current buffer for Haskell 1.4 scripts. Changes the current buffer's `font-lock-defaults', and adds the following variables: `haskell-keyword-face' for reserved keywords and syntax, `haskell-constructor-face' for data- and type-constructors, class names, and module names, `haskell-operator-face' for symbolic and alphanumeric operators, `haskell-default-face' for ordinary code. The variables are initialised to the following font lock default faces: `haskell-keyword-face' `font-lock-keyword-face' `haskell-constructor-face' `font-lock-type-face' `haskell-operator-face' `font-lock-function-name-face' `haskell-default-face' Two levels of fontification are defined: level one (the default) and level two (more colour). The former does not colour operators. Use the variable `font-lock-maximum-decoration' to choose non-default levels of fontification. For example, adding this to .emacs: (setq font-lock-maximum-decoration '((haskell-mode . 2) (t . 0))) uses level two fontification for `haskell-mode' and default level for all other modes. See documentation on this variable for further details. To alter an attribute of a face, add a hook. For example, to change the foreground colour of comments to brown, add the following line to .emacs: (add-hook 'haskell-font-lock-hook (lambda () (set-face-foreground 'haskell-comment-face \"brown\"))) Note that the colours available vary from system to system. To see what colours are available on your system, call `list-colors-display' from emacs. To turn font locking on for all Haskell buffers, add this to .emacs: (add-hook 'haskell-mode-hook 'turn-on-haskell-font-lock) To turn font locking on for the current buffer, call `turn-on-haskell-font-lock'. To turn font locking off in the current buffer, call `turn-off-haskell-font-lock'. Bird-style literate Haskell scripts are supported: If the value of `haskell-literate-bird-style' (automatically set by the Haskell mode of Moss&Thorn) is non-nil, a Bird-style literate script is assumed. Invokes `haskell-font-lock-hook' if not nil." (haskell-font-lock-defaults-create) (run-hooks 'haskell-font-lock-hook) (turn-on-font-lock)) (defun turn-off-haskell-font-lock () "Turns off font locking in current buffer." (font-lock-mode -1)) ;; Provide ourselves: (provide 'haskell-font-lock) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; tab-width: 8 ;; End: ;;; haskell-font-lock.el ends here haskell-mode-13.10/haskell-indent.el000066400000000000000000002077341225210037200173160ustar00rootroot00000000000000;;; haskell-indent.el --- "semi-intelligent" indentation module for Haskell Mode ;; Copyright 2004, 2005, 2007, 2008, 2009 Free Software Foundation, Inc. ;; Copyright 1997-1998 Guy Lapalme ;; Author: 1997-1998 Guy Lapalme ;; Keywords: indentation Haskell layout-rule ;; Version: 1.2 ;; URL: http://www.iro.umontreal.ca/~lapalme/layout/index.html ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; Purpose: ;; ;; To support automatic indentation of Haskell programs using ;; the layout rule described in section 1.5 and appendix B.3 of the ;; the Haskell report. The rationale and the implementation principles ;; are described in an article to appear in Journal of Functional Programming. ;; "Dynamic tabbing for automatic indentation with the layout rule" ;; ;; It supports literate scripts. ;; Haskell indentation is performed ;; within \begin{code}...\end{code} sections of a literate script ;; and in lines beginning with > with Bird style literate script ;; TAB aligns to the left column outside of these sections. ;; ;; Installation: ;; ;; To turn indentation on for all Haskell buffers under the Haskell ;; mode of Moss&Thorn ;; add this to .emacs: ;; ;; (add-hook 'haskell-mode-hook 'turn-on-haskell-indent) ;; ;; Otherwise, call `turn-on-haskell-indent'. ;; ;; ;; Customisation: ;; The "standard" offset for statements is 4 spaces. ;; It can be changed by setting the variable "haskell-indent-offset" to ;; another value ;; ;; The default number of blanks after > in a Bird style literate script ;; is 1; it can be changed by setting the variable ;; "haskell-indent-literate-Bird-default-offset" ;; ;; `haskell-indent-hook' is invoked if not nil. ;; ;; All functions/variables start with ;; `(turn-(on/off)-)haskell-indent' or `haskell-indent-'. ;; This file can also be used as a hook for the Hugs Mode developed by ;; Chris Van Humbeeck ;; It can be obtained at: ;; http://www-i2.informatik.rwth-aachen.de/Forschung/FP/Haskell/hugs-mode.el ;; ;; For the Hugs mode put the following in your .emacs ;; ;;(setq auto-mode-alist (append auto-mode-alist '(("\\.hs\\'" . hugs-mode)))) ;;(autoload 'hugs-mode "hugs-mode" "Go into hugs mode" t) ;; ;; If only the indentation mode is used then replace the two ;; preceding lines with ;;(setq auto-mode-alist (append auto-mode-alist ;; '(("\\.hs\\'" . turn-on-haskell-indent)))) ;;(autoload 'turn-on-haskell-indent "hindent" "Indentation mode for Haskell" t) ;; ;; For indentation in both cases then add the following to your .emacs ;;(add-hook 'hugs-mode-hook 'turn-on-haskell-indent) ;;(autoload 'haskell-indent-cycle "hindent" "Indentation cycle for Haskell" t) ;; ;;; Code: (require 'haskell-string) (with-no-warnings (require 'cl)) (defvar haskell-literate) (defgroup haskell-indent nil "Haskell indentation." :group 'haskell :link '(custom-manual "(haskell-mode)Indentation") :prefix "haskell-indent-") (defcustom haskell-indent-offset 4 "Indentation of Haskell statements with respect to containing block." :type 'integer :group 'haskell-indent) (defcustom haskell-indent-literate-Bird-default-offset 1 "Default number of blanks after > in a Bird style literate script." :type 'integer :group 'haskell-indent) (defcustom haskell-indent-rhs-align-column 0 "Column on which to align right-hand sides (use 0 for ad-hoc alignment)." :type 'integer :group 'haskell-indent) (defun haskell-indent-point-to-col (apoint) "Return the column number of APOINT." (save-excursion (goto-char apoint) (current-column))) (defconst haskell-indent-start-keywords-re (concat "\\<" (regexp-opt '("class" "data" "import" "infix" "infixl" "infixr" "instance" "module" "newtype" "primitive" "type") t) "\\>") "Regexp for keywords to complete when standing at the first word of a line.") ;; Customizations for different kinds of environments ;; in which dealing with low-level events are different. (defun haskell-indent-mark-active () (if (featurep 'xemacs) (if zmacs-regions zmacs-region-active-p t) mark-active)) ;; for pushing indentation information (defvar haskell-indent-info) ;Used with dynamic scoping. (defun haskell-indent-push-col (col &optional name) "Push indentation information for the column COL. The info is followed by NAME (if present). Makes sure that the same indentation info is not pushed twice. Uses free var `haskell-indent-info'." (let ((tmp (cons col name))) (if (member tmp haskell-indent-info) haskell-indent-info (push tmp haskell-indent-info)))) (defun haskell-indent-push-pos (pos &optional name) "Push indentation information for POS followed by NAME (if present)." (haskell-indent-push-col (haskell-indent-point-to-col pos) name)) ;; (defvar haskell-indent-tab-align nil ;; "Align all indentations on TAB stops.") (defun haskell-indent-column+offset (column offset) (unless offset (setq offset haskell-indent-offset)) (setq column (+ column offset)) ;; (if (and haskell-indent-tab-align (> offset 0)) ;; (* 8 (/ (+ column 7) 8)) column) ;; ) (defun haskell-indent-push-pos-offset (pos &optional offset) "Pushes indentation information for the column corresponding to POS followed by an OFFSET (if present use its value otherwise use `haskell-indent-offset')." (haskell-indent-push-col (haskell-indent-column+offset (haskell-indent-point-to-col pos) offset))) ;; redefinition of some Emacs function for dealing with ;; Bird Style literate scripts (defun haskell-indent-bolp () "`bolp' but dealing with Bird-style literate scripts." (or (bolp) (and (eq haskell-literate 'bird) (<= (current-column) (1+ haskell-indent-literate-Bird-default-offset)) (eq (char-after (line-beginning-position)) ?\>)))) (defun haskell-indent-empty-line-p () "Checks if the current line is empty; deals with Bird style scripts." (save-excursion (beginning-of-line) (if (and (eq haskell-literate 'bird) (eq (following-char) ?\>)) (forward-char 1)) (looking-at "[ \t]*$"))) (defun haskell-indent-back-to-indentation () "`back-to-indentation' function but dealing with Bird-style literate scripts." (if (and (eq haskell-literate 'bird) (progn (beginning-of-line) (eq (following-char) ?\>))) (progn (forward-char 1) (skip-chars-forward " \t")) (back-to-indentation))) (defun haskell-indent-current-indentation () "`current-indentation' function dealing with Bird-style literate scripts." (if (eq haskell-literate 'bird) (save-excursion (haskell-indent-back-to-indentation) (current-column)) (current-indentation))) (defun haskell-indent-backward-to-indentation (n) "`backward-to-indentation' function dealing with Bird-style literate scripts." (if (eq haskell-literate 'bird) (progn (forward-line (- n)) (haskell-indent-back-to-indentation)) (backward-to-indentation n))) (defun haskell-indent-forward-line (&optional n) "`forward-line' function but dealing with Bird-style literate scripts." (prog1 (forward-line n) (if (and (eq haskell-literate 'bird) (eq (following-char) ?\>)) (progn (forward-char 1) ; skip > and initial blanks... (skip-chars-forward " \t"))))) (defun haskell-indent-line-to (n) "`indent-line-to' function but dealing with Bird-style literate scripts." (if (eq haskell-literate 'bird) (progn (beginning-of-line) (if (eq (following-char) ?\>) (delete-char 1)) (delete-horizontal-space) ; remove any starting TABs so (indent-line-to n) ; that indent-line only adds spaces (save-excursion (beginning-of-line) (if (> n 0) (delete-char 1)) ; delete the first space before (insert ?\>))) ; inserting a > (indent-line-to n))) (defun haskell-indent-skip-blanks-and-newlines-forward (end) "Skip forward blanks, tabs and newlines until END. Take account of Bird-style literate scripts." (skip-chars-forward " \t\n" end) (if (eq haskell-literate 'bird) (while (and (bolp) (eq (following-char) ?\>)) (forward-char 1) ; skip > (skip-chars-forward " \t\n" end)))) (defun haskell-indent-skip-blanks-and-newlines-backward (start) "Skip backward blanks, tabs and newlines up to START. Take account of Bird-style literate scripts." (skip-chars-backward " \t\n" start) (if (eq haskell-literate 'bird) (while (and (eq (current-column) 1) (eq (preceding-char) ?\>)) (forward-char -1) ; skip back > (skip-chars-backward " \t\n" start)))) ;; specific functions for literate code (defun haskell-indent-within-literate-code () "Check if point is within a part of literate Haskell code. If so, return its start; otherwise return nil: If it is Bird-style, then return the position of the >; otherwise return the ending position of \\begin{code}." (save-excursion (case haskell-literate (bird (beginning-of-line) (if (or (eq (following-char) ?\>) (and (bolp) (forward-line -1) (eq (following-char) ?\>))) (progn (while (and (zerop (forward-line -1)) (eq (following-char) ?\>))) (if (not (eq (following-char) ?\>)) (forward-line)) (point)))) ;; Look for a \begin{code} or \end{code} line. ((latex tex) (if (re-search-backward "^\\(\\\\begin{code}$\\)\\|\\(\\\\end{code}$\\)" nil t) ;; within a literate code part if it was a \\begin{code}. (match-end 1))) (t (error "haskell-indent-within-literate-code: should not happen!"))))) (defun haskell-indent-put-region-in-literate (beg end &optional arg) "Put lines of the region as a piece of literate code. With prefix arg, remove indication that the region is literate code. It deals with both Bird style and non Bird-style scripts." (interactive "r\nP") (unless haskell-literate (error "Cannot put a region in literate in a non literate script")) (if (eq haskell-literate 'bird) (let ((comment-start "> ") ; Change dynamic bindings for (comment-start-skip "^> ?") ; comment-region. (comment-end "") (comment-end-skip "\n") (comment-style 'plain)) (comment-region beg end arg)) ;; Not Bird style. (if arg ; Remove the literate indication. (save-excursion (goto-char end) ; Remove end. (if (re-search-backward "^\\\\end{code}[ \t\n]*\\=" (line-beginning-position -2) t) (delete-region (point) (line-beginning-position 2))) (goto-char beg) ; Remove end. (beginning-of-line) (if (looking-at "\\\\begin{code}") (kill-line 1))) (save-excursion ; Add the literate indication. (goto-char end) (unless (bolp) (newline)) (insert "\\end{code}\n") (goto-char beg) (unless (bolp) (newline)) (insert "\\begin{code}\n"))))) ;;; Start of indentation code (defcustom haskell-indent-look-past-empty-line t "If nil, indentation engine will not look past an empty line for layout points." :group 'haskell-indent :type 'boolean) (defun haskell-indent-start-of-def () "Return the position of the start of a definition. The start of a def is expected to be recognizable by starting in column 0, unless `haskell-indent-look-past-empty-line' is nil, in which case we take a coarser approximation and stop at the first empty line." (save-excursion (let ((start-code (and haskell-literate (haskell-indent-within-literate-code))) (top-col (if (eq haskell-literate 'bird) 2 0)) (save-point (point))) ;; determine the starting point of the current piece of code (setq start-code (if start-code (1+ start-code) (point-min))) ;; go backward until the first preceding empty line (haskell-indent-forward-line -1) (while (and (if haskell-indent-look-past-empty-line (or (> (haskell-indent-current-indentation) top-col) (haskell-indent-empty-line-p)) (and (> (haskell-indent-current-indentation) top-col) (not (haskell-indent-empty-line-p)))) (> (point) start-code) (= 0 (haskell-indent-forward-line -1)))) ;; go forward after the empty line (if (haskell-indent-empty-line-p) (haskell-indent-forward-line 1)) (setq start-code (point)) ;; find the first line of code which is not a comment (forward-comment (point-max)) (if (> (point) save-point) start-code (point))))) (defun haskell-indent-open-structure (start end) "If any structure (list or tuple) is not closed, between START and END, returns the location of the opening symbol, nil otherwise." (save-excursion (nth 1 (parse-partial-sexp start end)))) (defun haskell-indent-in-string (start end) "If a string is not closed , between START and END, returns the location of the opening symbol, nil otherwise." (save-excursion (let ((pps (parse-partial-sexp start end))) (if (nth 3 pps) (nth 8 pps))))) (defun haskell-indent-in-comment (start end) "Check, starting from START, if END is at or within a comment. Returns the location of the start of the comment, nil otherwise." (let (pps) (assert (<= start end)) (cond ((= start end) nil) ((nth 4 (save-excursion (setq pps (parse-partial-sexp start end)))) (nth 8 pps)) ;; We also want to say that we are *at* the beginning of a comment. ((and (not (nth 8 pps)) (>= (point-max) (+ end 2)) (nth 4 (save-excursion (setq pps (parse-partial-sexp end (+ end 2)))))) (nth 8 pps))))) (defvar haskell-indent-off-side-keywords-re "\\<\\(do\\|let\\|of\\|where\\|mdo\\|rec\\)\\>[ \t]*") (defun haskell-indent-type-at-point () "Return the type of the line (also puts information in `match-data')." (cond ((haskell-indent-empty-line-p) 'empty) ((haskell-indent-in-comment (point-min) (point)) 'comment) ((looking-at "\\(\\([[:alpha:]]\\(\\sw\\|'\\)*\\)\\|_\\)[ \t\n]*") 'ident) ((looking-at "\\(|[^|]\\)[ \t\n]*") 'guard) ((looking-at "\\(=[^>=]\\|::\\|->\\|<-\\)[ \t\n]*") 'rhs) (t 'other))) (defvar haskell-indent-current-line-first-ident "" "Global variable that keeps track of the first ident of the line to indent.") (defun haskell-indent-contour-line (start end) "Generate contour information between START and END points." (if (< start end) (save-excursion (goto-char end) (haskell-indent-skip-blanks-and-newlines-backward start) (let ((cur-col (current-column)) ; maximum column number (fl 0) ; number of lines that forward-line could not advance contour) (while (and (> cur-col 0) (= fl 0) (>= (point) start)) (haskell-indent-back-to-indentation) (if (< (point) start) (goto-char start)) (and (not (member (haskell-indent-type-at-point) '(empty comment))) ; skip empty and comment lines (< (current-column) cur-col) ; less indented column found (push (point) contour) ; new contour point found (setq cur-col (current-column))) (setq fl (haskell-indent-forward-line -1))) contour)))) (defun haskell-indent-next-symbol (end) "Move point to the next symbol." (skip-syntax-forward ")" end) (if (< (point) end) (progn (forward-sexp 1) (haskell-indent-skip-blanks-and-newlines-forward end)))) (defun haskell-indent-next-symbol-safe (end) "Puts point to the next following symbol, or to end if there are no more symbols in the sexp." (condition-case errlist (haskell-indent-next-symbol end) (error (goto-char end)))) (defun haskell-indent-separate-valdef (start end) "Return a list of positions for important parts of a valdef." (save-excursion (let (valname valname-string aft-valname guard aft-guard rhs-sign aft-rhs-sign type) ;; "parse" a valdef separating important parts (goto-char start) (setq type (haskell-indent-type-at-point)) (if (or (memq type '(ident other))) ; possible start of a value def (progn (if (eq type 'ident) (progn (setq valname (match-beginning 0)) (setq valname-string (match-string 0)) (goto-char (match-end 0))) (skip-chars-forward " \t" end) (setq valname (point)) ; type = other (haskell-indent-next-symbol-safe end)) (while (and (< (point) end) (setq type (haskell-indent-type-at-point)) (or (memq type '(ident other)))) (if (null aft-valname) (setq aft-valname (point))) (haskell-indent-next-symbol-safe end)))) (if (and (< (point) end) (eq type 'guard)) ; start of a guard (progn (setq guard (match-beginning 0)) (goto-char (match-end 0)) (while (and (< (point) end) (setq type (haskell-indent-type-at-point)) (not (eq type 'rhs))) (if (null aft-guard) (setq aft-guard (point))) (haskell-indent-next-symbol-safe end)))) (if (and (< (point) end) (eq type 'rhs)) ; start of a rhs (progn (setq rhs-sign (match-beginning 0)) (goto-char (match-end 0)) (if (< (point) end) (setq aft-rhs-sign (point))))) (list valname valname-string aft-valname guard aft-guard rhs-sign aft-rhs-sign)))) (defsubst haskell-indent-no-otherwise (guard) "Check if there is no otherwise at GUARD." (save-excursion (goto-char guard) (not (looking-at "|[ \t]*otherwise\\>")))) (defun haskell-indent-guard (start end end-visible indent-info) "Find indentation information for a line starting with a guard." (save-excursion (let* ((haskell-indent-info indent-info) (sep (haskell-indent-separate-valdef start end)) (valname (nth 0 sep)) (guard (nth 3 sep)) (rhs-sign (nth 5 sep))) ;; push information indentation for the visible part (if (and guard (< guard end-visible) (haskell-indent-no-otherwise guard)) (haskell-indent-push-pos guard) (if rhs-sign (haskell-indent-push-pos rhs-sign) ; probably within a data definition... (if valname (haskell-indent-push-pos-offset valname)))) haskell-indent-info))) (defun haskell-indent-rhs (start end end-visible indent-info) "Find indentation information for a line starting with a rhs." (save-excursion (let* ((haskell-indent-info indent-info) (sep (haskell-indent-separate-valdef start end)) (valname (nth 0 sep)) (guard (nth 3 sep)) (rhs-sign (nth 5 sep))) ;; push information indentation for the visible part (if (and rhs-sign (< rhs-sign end-visible)) (haskell-indent-push-pos rhs-sign) (if (and guard (< guard end-visible)) (haskell-indent-push-pos-offset guard) (if valname ; always visible !! (haskell-indent-push-pos-offset valname)))) haskell-indent-info))) (defconst haskell-indent-decision-table (let ((or "\\)\\|\\(")) (concat "\\(" "1.1.11" or ; 1= vn gd rh arh "1.1.10" or ; 2= vn gd rh "1.1100" or ; 3= vn gd agd "1.1000" or ; 4= vn gd "1.0011" or ; 5= vn rh arh "1.0010" or ; 6= vn rh "110000" or ; 7= vn avn "100000" or ; 8= vn "001.11" or ; 9= gd rh arh "001.10" or ;10= gd rh "001100" or ;11= gd agd "001000" or ;12= gd "000011" or ;13= rh arh "000010" or ;14= rh "000000" ;15= "\\)"))) (defun haskell-indent-find-case (test) "Find the index that matches TEST in the decision table." (if (string-match haskell-indent-decision-table test) ;; use the fact that the resulting match-data is a list of the form ;; (0 6 [2*(n-1) nil] 0 6) where n is the number of the matching regexp ;; so n= ((length match-data)/2)-1 (- (/ (length (match-data 'integers)) 2) 1) (error "haskell-indent-find-case: impossible case: %s" test))) (defun haskell-indent-empty (start end end-visible indent-info) "Find indentation points for an empty line." (save-excursion (let* ((haskell-indent-info indent-info) (sep (haskell-indent-separate-valdef start end)) (valname (pop sep)) (valname-string (pop sep)) (aft-valname (pop sep)) (guard (pop sep)) (aft-guard (pop sep)) (rhs-sign (pop sep)) (aft-rhs-sign (pop sep)) (last-line (= end end-visible)) (test (string (if valname ?1 ?0) (if (and aft-valname (< aft-valname end-visible)) ?1 ?0) (if (and guard (< guard end-visible)) ?1 ?0) (if (and aft-guard (< aft-guard end-visible)) ?1 ?0) (if (and rhs-sign (< rhs-sign end-visible)) ?1 ?0) (if (and aft-rhs-sign (< aft-rhs-sign end-visible)) ?1 ?0)))) (if (and valname-string ; special case for start keywords (string-match haskell-indent-start-keywords-re valname-string)) (progn (haskell-indent-push-pos valname) ;; very special for data keyword (if (string-match "\\" valname-string) (if rhs-sign (haskell-indent-push-pos rhs-sign) (haskell-indent-push-pos-offset valname)) (haskell-indent-push-pos-offset valname))) (case ; general case (haskell-indent-find-case test) ;; "1.1.11" 1= vn gd rh arh (1 (haskell-indent-push-pos valname) (haskell-indent-push-pos valname valname-string) (if (haskell-indent-no-otherwise guard) (haskell-indent-push-pos guard "| ")) (haskell-indent-push-pos aft-rhs-sign)) ;; "1.1.10" 2= vn gd rh (2 (haskell-indent-push-pos valname) (haskell-indent-push-pos valname valname-string) (if last-line (haskell-indent-push-pos-offset guard) (if (haskell-indent-no-otherwise guard) (haskell-indent-push-pos guard "| ")))) ;; "1.1100" 3= vn gd agd (3 (haskell-indent-push-pos valname) (haskell-indent-push-pos aft-guard) (if last-line (haskell-indent-push-pos-offset valname))) ;; "1.1000" 4= vn gd (4 (haskell-indent-push-pos valname) (if last-line (haskell-indent-push-pos-offset guard 2))) ;; "1.0011" 5= vn rh arh (5 (haskell-indent-push-pos valname) (if (or (and aft-valname (= (char-after rhs-sign) ?\=)) (= (char-after rhs-sign) ?\:)) (haskell-indent-push-pos valname valname-string)) (haskell-indent-push-pos aft-rhs-sign)) ;; "1.0010" 6= vn rh (6 (haskell-indent-push-pos valname) (haskell-indent-push-pos valname valname-string) (if last-line (haskell-indent-push-pos-offset valname))) ;; "110000" 7= vn avn (7 (haskell-indent-push-pos valname) (if last-line (haskell-indent-push-pos aft-valname) (haskell-indent-push-pos valname valname-string))) ;; "100000" 8= vn (8 (haskell-indent-push-pos valname)) ;; "001.11" 9= gd rh arh (9 (if (haskell-indent-no-otherwise guard) (haskell-indent-push-pos guard "| ")) (haskell-indent-push-pos aft-rhs-sign)) ;; "001.10" 10= gd rh (10 (if (haskell-indent-no-otherwise guard) (haskell-indent-push-pos guard "| ")) (if last-line (haskell-indent-push-pos-offset guard))) ;; "001100" 11= gd agd (11 (if (haskell-indent-no-otherwise guard) (haskell-indent-push-pos guard "| ")) (haskell-indent-push-pos aft-guard)) ;; "001000" 12= gd (12 (if (haskell-indent-no-otherwise guard) (haskell-indent-push-pos guard "| ")) (if last-line (haskell-indent-push-pos-offset guard 2))) ;; "000011" 13= rh arh (13 (haskell-indent-push-pos aft-rhs-sign)) ;; "000010" 14= rh (14 (if last-line (haskell-indent-push-pos-offset rhs-sign 2 ))) ;; "000000" 15= (t (error "haskell-indent-empty: %s impossible case" test )))) haskell-indent-info))) (defun haskell-indent-ident (start end end-visible indent-info) "Find indentation points for a line starting with an identifier." (save-excursion (let* ((haskell-indent-info indent-info) (sep (haskell-indent-separate-valdef start end)) (valname (pop sep)) (valname-string (pop sep)) (aft-valname (pop sep)) (guard (pop sep)) (aft-guard (pop sep)) (rhs-sign (pop sep)) (aft-rhs-sign (pop sep)) (last-line (= end end-visible)) (is-where (string-match "where[ \t]*" haskell-indent-current-line-first-ident)) (diff-first ; not a function def with the same name (or (null valname-string) (not (string= (haskell-trim valname-string) (haskell-trim haskell-indent-current-line-first-ident))))) ;; (is-type-def ;; (and rhs-sign (eq (char-after rhs-sign) ?\:))) (test (string (if valname ?1 ?0) (if (and aft-valname (< aft-valname end-visible)) ?1 ?0) (if (and guard (< guard end-visible)) ?1 ?0) (if (and aft-guard (< aft-guard end-visible)) ?1 ?0) (if (and rhs-sign (< rhs-sign end-visible)) ?1 ?0) (if (and aft-rhs-sign (< aft-rhs-sign end-visible)) ?1 ?0)))) (if (and valname-string ; special case for start keywords (string-match haskell-indent-start-keywords-re valname-string)) (progn (haskell-indent-push-pos valname) (if (string-match "\\" valname-string) ;; very special for data keyword (if aft-rhs-sign (haskell-indent-push-pos aft-rhs-sign) (haskell-indent-push-pos-offset valname)) (if (not (string-match haskell-indent-start-keywords-re haskell-indent-current-line-first-ident)) (haskell-indent-push-pos-offset valname)))) (if (string= haskell-indent-current-line-first-ident "::") (if valname (haskell-indent-push-pos valname)) (case ; general case (haskell-indent-find-case test) ;; "1.1.11" 1= vn gd rh arh (1 (if is-where (haskell-indent-push-pos guard) (haskell-indent-push-pos valname) (if diff-first (haskell-indent-push-pos aft-rhs-sign)))) ;; "1.1.10" 2= vn gd rh (2 (if is-where (haskell-indent-push-pos guard) (haskell-indent-push-pos valname) (if last-line (haskell-indent-push-pos-offset guard)))) ;; "1.1100" 3= vn gd agd (3 (if is-where (haskell-indent-push-pos-offset guard) (haskell-indent-push-pos valname) (if diff-first (haskell-indent-push-pos aft-guard)))) ;; "1.1000" 4= vn gd (4 (if is-where (haskell-indent-push-pos guard) (haskell-indent-push-pos valname) (if last-line (haskell-indent-push-pos-offset guard 2)))) ;; "1.0011" 5= vn rh arh (5 (if is-where (haskell-indent-push-pos-offset valname) (haskell-indent-push-pos valname) (if diff-first (haskell-indent-push-pos aft-rhs-sign)))) ;; "1.0010" 6= vn rh (6 (if is-where (haskell-indent-push-pos-offset valname) (haskell-indent-push-pos valname) (if last-line (haskell-indent-push-pos-offset valname)))) ;; "110000" 7= vn avn (7 (if is-where (haskell-indent-push-pos-offset valname) (haskell-indent-push-pos valname) (if last-line (haskell-indent-push-pos aft-valname)))) ;; "100000" 8= vn (8 (if is-where (haskell-indent-push-pos-offset valname) (haskell-indent-push-pos valname))) ;; "001.11" 9= gd rh arh (9 (if is-where (haskell-indent-push-pos guard) (haskell-indent-push-pos aft-rhs-sign))) ;; "001.10" 10= gd rh (10 (if is-where (haskell-indent-push-pos guard) (if last-line (haskell-indent-push-pos-offset guard)))) ;; "001100" 11= gd agd (11 (if is-where (haskell-indent-push-pos guard) (if (haskell-indent-no-otherwise guard) (haskell-indent-push-pos aft-guard)))) ;; "001000" 12= gd (12 (if last-line (haskell-indent-push-pos-offset guard 2))) ;; "000011" 13= rh arh (13 (haskell-indent-push-pos aft-rhs-sign)) ;; "000010" 14= rh (14 (if last-line (haskell-indent-push-pos-offset rhs-sign 2))) ;; "000000" 15= (t (error "haskell-indent-ident: %s impossible case" test ))))) haskell-indent-info))) (defun haskell-indent-other (start end end-visible indent-info) "Find indentation points for a non-empty line starting with something other than an identifier, a guard or rhs." (save-excursion (let* ((haskell-indent-info indent-info) (sep (haskell-indent-separate-valdef start end)) (valname (pop sep)) (valname-string (pop sep)) (aft-valname (pop sep)) (guard (pop sep)) (aft-guard (pop sep)) (rhs-sign (pop sep)) (aft-rhs-sign (pop sep)) (last-line (= end end-visible)) (test (string (if valname ?1 ?0) (if (and aft-valname (< aft-valname end-visible)) ?1 ?0) (if (and guard (< guard end-visible)) ?1 ?0) (if (and aft-guard (< aft-guard end-visible)) ?1 ?0) (if (and rhs-sign (< rhs-sign end-visible)) ?1 ?0) (if (and aft-rhs-sign (< aft-rhs-sign end-visible)) ?1 ?0)))) (if (and valname-string ; special case for start keywords (string-match haskell-indent-start-keywords-re valname-string)) (haskell-indent-push-pos-offset valname) (case ; general case (haskell-indent-find-case test) ;; "1.1.11" 1= vn gd rh arh (1 (haskell-indent-push-pos aft-rhs-sign)) ;; "1.1.10" 2= vn gd rh (2 (if last-line (haskell-indent-push-pos-offset guard) (haskell-indent-push-pos-offset rhs-sign 2))) ;; "1.1100" 3= vn gd agd (3 (haskell-indent-push-pos aft-guard)) ;; "1.1000" 4= vn gd (4 (haskell-indent-push-pos-offset guard 2)) ;; "1.0011" 5= vn rh arh (5 (haskell-indent-push-pos valname) (haskell-indent-push-pos aft-rhs-sign)) ;; "1.0010" 6= vn rh (6 (if last-line (haskell-indent-push-pos-offset valname) (haskell-indent-push-pos-offset rhs-sign 2))) ;; "110000" 7= vn avn (7 (haskell-indent-push-pos-offset aft-valname)) ;; "100000" 8= vn (8 (haskell-indent-push-pos valname)) ;; "001.11" 9= gd rh arh (9 (haskell-indent-push-pos aft-rhs-sign)) ;; "001.10" 10= gd rh (10 (if last-line (haskell-indent-push-pos-offset guard) (haskell-indent-push-pos-offset rhs-sign 2))) ;; "001100" 11= gd agd (11 (if (haskell-indent-no-otherwise guard) (haskell-indent-push-pos aft-guard))) ;; "001000" 12= gd (12 (if last-line (haskell-indent-push-pos-offset guard 2))) ;; "000011" 13= rh arh (13 (haskell-indent-push-pos aft-rhs-sign)) ;; "000010" 14= rh (14 (if last-line (haskell-indent-push-pos-offset rhs-sign 2))) ;; "000000" 15= (t (error "haskell-indent-other: %s impossible case" test )))) haskell-indent-info))) (defun haskell-indent-valdef-indentation (start end end-visible curr-line-type indent-info) "Find indentation information for a value definition." (let ((haskell-indent-info indent-info)) (if (< start end-visible) (case curr-line-type (empty (haskell-indent-empty start end end-visible indent-info)) (ident (haskell-indent-ident start end end-visible indent-info)) (guard (haskell-indent-guard start end end-visible indent-info)) (rhs (haskell-indent-rhs start end end-visible indent-info)) (comment (error "Comment indent should never happen")) (other (haskell-indent-other start end end-visible indent-info))) haskell-indent-info))) (defun haskell-indent-line-indentation (line-start line-end end-visible curr-line-type indent-info) "Compute indentation info between LINE-START and END-VISIBLE. Separate a line of program into valdefs between offside keywords and find indentation info for each part." (save-excursion ;; point is (already) at line-start (assert (eq (point) line-start)) (let ((haskell-indent-info indent-info) (start (or (haskell-indent-in-comment line-start line-end) (haskell-indent-in-string line-start line-end)))) (if start ; if comment at the end (setq line-end start)) ; end line before it ;; loop on all parts separated by off-side-keywords (while (and (re-search-forward haskell-indent-off-side-keywords-re line-end t) (not (or (haskell-indent-in-comment line-start (point)) (haskell-indent-in-string line-start (point))))) (let ((beg-match (match-beginning 0)) ; save beginning of match (end-match (match-end 0))) ; save end of match ;; Do not try to find indentation points if off-side-keyword at ;; the start... (if (or (< line-start beg-match) ;; Actually, if we're looking at a "let" inside a "do", we ;; should add the corresponding indentation point. (eq (char-after beg-match) ?l)) (setq haskell-indent-info (haskell-indent-valdef-indentation line-start beg-match end-visible curr-line-type haskell-indent-info))) ;; ...but keep the start of the line if keyword alone on the line (if (= line-end end-match) (haskell-indent-push-pos beg-match)) (setq line-start end-match) (goto-char line-start))) (haskell-indent-valdef-indentation line-start line-end end-visible curr-line-type haskell-indent-info)))) (defun haskell-indent-layout-indent-info (start contour-line) (let ((haskell-indent-info nil) (curr-line-type (haskell-indent-type-at-point)) line-start line-end end-visible) (save-excursion (if (eq curr-line-type 'ident) (let ; guess the type of line ((sep (haskell-indent-separate-valdef (point) (line-end-position)))) ;; if the first ident is where or the start of a def ;; keep it in a global variable (setq haskell-indent-current-line-first-ident (if (string-match "where[ \t]*" (nth 1 sep)) (nth 1 sep) (if (nth 5 sep) ; is there a rhs-sign (if (= (char-after (nth 5 sep)) ?\:) ;is it a typdef "::" (nth 1 sep)) ""))))) (while contour-line ; explore the contour points (setq line-start (pop contour-line)) (goto-char line-start) (setq line-end (line-end-position)) (setq end-visible ; visible until the column of the (if contour-line ; next contour point (save-excursion (move-to-column (haskell-indent-point-to-col (car contour-line))) (point)) line-end)) (unless (or (haskell-indent-open-structure start line-start) (haskell-indent-in-comment start line-start)) (setq haskell-indent-info (haskell-indent-line-indentation line-start line-end end-visible curr-line-type haskell-indent-info))))) haskell-indent-info)) (defun haskell-indent-find-matching-start (regexp limit &optional pred start) (let ((open (haskell-indent-open-structure limit (point)))) (if open (setq limit (1+ open)))) (unless start (setq start (point))) (when (re-search-backward regexp limit t) (let ((nestedcase (match-end 1)) (outer (or (haskell-indent-in-string limit (point)) (haskell-indent-in-comment limit (point)) (haskell-indent-open-structure limit (point)) (if (and pred (funcall pred start)) (point))))) (cond (outer (goto-char outer) (haskell-indent-find-matching-start regexp limit pred start)) (nestedcase ;; Nested case. (and (haskell-indent-find-matching-start regexp limit pred) (haskell-indent-find-matching-start regexp limit pred start))) (t (point)))))) (defun haskell-indent-filter-let-no-in (start) "Return non-nil if point is in front of a `let' that has no `in'. START is the position of the presumed `in'." ;; We're looking at either `in' or `let'. (when (looking-at "let") (ignore-errors (save-excursion (forward-word 1) (forward-comment (point-max)) (if (looking-at "{") (progn (forward-sexp 1) (forward-comment (point-max)) (< (point) start)) ;; Use the layout rule to see whether this let is already closed ;; without an `in'. (let ((col (current-column))) (while (progn (forward-line 1) (haskell-indent-back-to-indentation) (< (point) start)) (when (< (current-column) col) (setq col nil) (goto-char start))) (null col))))))) (defun haskell-indent-comment (open start) "Compute indent info for comments and text inside comments. OPEN is the start position of the comment in which point is." ;; Ideally we'd want to guess whether it's commented out code or ;; whether it's text. Instead, we'll assume it's text. (save-excursion (if (= open (point)) ;; We're actually just in front of a comment: align with following ;; code or with comment on previous line. (let ((prev-line-info (cond ((eq (char-after) ?\{) nil) ;Align as if it were code. ((and (forward-comment -1) (> (line-beginning-position 3) open)) ;; We're after another comment and there's no empty line ;; between us. (list (list (haskell-indent-point-to-col (point))))) (t nil)))) ;Else align as if it were code ;; Align with following code. (forward-comment (point-max)) ;; There are several possible indentation points for this code-line, ;; but the only valid indentation point for the comment is the one ;; that the user will select for the code-line. Obviously we can't ;; know that, so we just assume that the code-line is already at its ;; proper place. ;; Strictly speaking "assume it's at its proper place" would mean ;; we'd just use (current-column), but since this is using info from ;; lines further down and it's common to reindent line-by-line, ;; we'll align not with the current indentation, but with the ;; one that auto-indentation "will" select. (append prev-line-info (let ((indent-info (save-excursion (haskell-indent-indentation-info start))) (col (current-column))) ;; Sort the indent-info so that the current indentation comes ;; out first. (setq indent-info (sort indent-info (lambda (x y) (<= (abs (- col (car x))) (abs (- col (car y))))))) indent-info))) ;; We really are inside a comment. (if (looking-at "-}") (progn (forward-char 2) (forward-comment -1) (list (list (1+ (haskell-indent-point-to-col (point)))))) (let ((offset (if (looking-at "--?") (- (match-beginning 0) (match-end 0))))) (forward-line -1) ;Go to previous line. (haskell-indent-back-to-indentation) (if (< (point) start) (goto-char start)) (list (list (if (looking-at comment-start-skip) (if offset (+ 2 offset (haskell-indent-point-to-col (point))) (haskell-indent-point-to-col (match-end 0))) (haskell-indent-point-to-col (point)))))))))) (defcustom haskell-indent-thenelse 0 "If non-nil, \"then\" and \"else\" are indented. This is necessary in the \"do\" layout under Haskell-98. See http://hackage.haskell.org/trac/haskell-prime/wiki/DoAndIfThenElse" :group 'haskell-indent :type 'integer) (defun haskell-indent-closing-keyword (start) (let ((open (save-excursion (haskell-indent-find-matching-start (case (char-after) (?i "\\<\\(?:\\(in\\)\\|let\\)\\>") (?o "\\<\\(?:\\(of\\)\\|case\\)\\>") (?t "\\<\\(?:\\(then\\)\\|if\\)\\>") (?e "\\<\\(?:\\(else\\)\\|if\\)\\>")) start (if (eq (char-after) ?i) ;; Filter out the `let's that have no `in'. 'haskell-indent-filter-let-no-in))))) ;; For a "hanging let/case/if at EOL" we should use a different ;; indentation scheme. (save-excursion (goto-char open) (if (haskell-indent-hanging-p) (setq open (haskell-indent-virtual-indentation start)))) ;; FIXME: we should try and figure out if the `if' is in a `do' layout ;; before using haskell-indent-thenelse. (list (list (+ (if (memq (char-after) '(?t ?e)) haskell-indent-thenelse 0) (haskell-indent-point-to-col open)))))) (defcustom haskell-indent-after-keywords '(("where" 2 0) ("of" 2) ("do" 2) ("mdo" 2) ("rec" 2) ("in" 2 0) ("{" 2) "if" "then" "else" "let") "Keywords after which indentation should be indented by some offset. Each keyword info can have the following forms: KEYWORD | (KEYWORD OFFSET [OFFSET-HANGING]) If absent OFFSET-HANGING defaults to OFFSET. If absent OFFSET defaults to `haskell-indent-offset'. OFFSET-HANGING is the offset to use in the case where the keyword is at the end of an otherwise-non-empty line." :group 'haskell-indent :type '(repeat (choice string (cons :tag "" (string :tag "keyword:") (cons :tag "" (integer :tag "offset") (choice (const nil) (list :tag "" (integer :tag "offset-pending")))))))) (defun haskell-indent-skip-lexeme-forward () (and (zerop (skip-syntax-forward "w")) (skip-syntax-forward "_") (skip-syntax-forward "(") (skip-syntax-forward ")"))) (defvar haskell-indent-inhibit-after-offset nil) (defun haskell-indent-offset-after-info () "Return the info from `haskell-indent-after-keywords' for keyword at point." (let ((id (buffer-substring (point) (save-excursion (haskell-indent-skip-lexeme-forward) (point))))) (or (assoc id haskell-indent-after-keywords) (car (member id haskell-indent-after-keywords))))) (defcustom haskell-indent-dont-hang '("(") "Lexemes that should never be considered as hanging." :group 'haskell-indent :type '(repeat string)) (defun haskell-indent-hanging-p () ;; A Hanging keyword is one that's at the end of a line except it's not at ;; the beginning of a line. (not (or (= (current-column) (haskell-indent-current-indentation)) (save-excursion (let ((lexeme (buffer-substring (point) (progn (haskell-indent-skip-lexeme-forward) (point))))) (or (member lexeme haskell-indent-dont-hang) (> (line-end-position) (progn (forward-comment (point-max)) (point))))))))) (defun haskell-indent-after-keyword-column (offset-info start &optional default) (unless offset-info (setq offset-info (haskell-indent-offset-after-info))) (unless default (setq default haskell-indent-offset)) (setq offset-info (if haskell-indent-inhibit-after-offset '(0) (cdr-safe offset-info))) (if (not (haskell-indent-hanging-p)) (haskell-indent-column+offset (current-column) (or (car offset-info) default)) ;; The keyword is hanging at the end of the line. (haskell-indent-column+offset (haskell-indent-virtual-indentation start) (or (cadr offset-info) (car offset-info) default)))) (defun haskell-indent-inside-paren (open) ;; there is an open structure to complete (if (looking-at "\\s)\\|[;,]") ;; A close-paren or a , or ; can only correspond syntactically to ;; the open-paren at `open'. So there is no ambiguity. (progn (if (or (and (eq (char-after) ?\;) (eq (char-after open) ?\()) (and (eq (char-after) ?\,) (eq (char-after open) ?\{))) (message "Mismatched punctuation: `%c' in %c...%c" (char-after) (char-after open) (if (eq (char-after open) ?\() ?\) ?\}))) (save-excursion (goto-char open) (list (list (if (haskell-indent-hanging-p) (haskell-indent-virtual-indentation nil) (haskell-indent-point-to-col open)))))) ;; There might still be layout within the open structure. (let* ((end (point)) (basic-indent-info ;; Anything else than a ) is subject to layout. (if (looking-at "\\s.\\|\\$ ") (haskell-indent-point-to-col open) ; align a punct with ( (let ((follow (save-excursion (goto-char (1+ open)) (haskell-indent-skip-blanks-and-newlines-forward end) (point)))) (if (= follow end) (save-excursion (goto-char open) (haskell-indent-after-keyword-column nil nil 1)) (haskell-indent-point-to-col follow))))) (open-column (haskell-indent-point-to-col open)) (contour-line (haskell-indent-contour-line (1+ open) end))) (if (null contour-line) (list (list basic-indent-info)) (let ((indent-info (haskell-indent-layout-indent-info (1+ open) contour-line))) ;; Fix up indent info. (let ((base-elem (assoc open-column indent-info))) (if base-elem (progn (setcar base-elem basic-indent-info) (setcdr base-elem nil)) (setq indent-info (append indent-info (list (list basic-indent-info))))) indent-info)))))) (defun haskell-indent-virtual-indentation (start) "Compute the \"virtual indentation\" of text at point. The \"virtual indentation\" is the indentation that text at point would have had, if it had been placed on its own line." (let ((col (current-column)) (haskell-indent-inhibit-after-offset (haskell-indent-hanging-p))) (if (save-excursion (skip-chars-backward " \t") (bolp)) ;; If the text is indeed on its own line, than the virtual indent is ;; the current indentation. col ;; Else, compute the indentation that it would have had. (let ((info (haskell-indent-indentation-info start)) (max -1)) ;; `info' is a list of possible indent points. Each indent point is ;; assumed to correspond to a different parse. So we need to find ;; the parse that corresponds to the case at hand (where there's no ;; line break), which is assumed to always be the ;; deepest indentation. (dolist (x info) (setq x (car x)) ;; Sometimes `info' includes the current indentation (or yet ;; deeper) by mistake, because haskell-indent-indentation-info ;; wasn't designed to be called on a piece of text that is not at ;; BOL. So ignore points past `col'. (if (and (> x max) (not (>= x col))) (setq max x))) ;; In case all the indent points are past `col', just use `col'. (if (>= max 0) max col))))) (defun haskell-indent-indentation-info (&optional start) "Return a list of possible indentations for the current line. These are then used by `haskell-indent-cycle'. START if non-nil is a presumed start pos of the current definition." (unless start (setq start (haskell-indent-start-of-def))) (let (open contour-line) (cond ;; in string? ((setq open (haskell-indent-in-string start (point))) (list (list (+ (haskell-indent-point-to-col open) (if (looking-at "\\\\") 0 1))))) ;; in comment ? ((setq open (haskell-indent-in-comment start (point))) (haskell-indent-comment open start)) ;; Closing the declaration part of a `let' or the test exp part of a case. ((looking-at "\\(?:in\\|of\\|then\\|else\\)\\>") (haskell-indent-closing-keyword start)) ;; Right after a special keyword. ((save-excursion (forward-comment (- (point-max))) (when (and (not (zerop (skip-syntax-backward "w"))) (setq open (haskell-indent-offset-after-info))) (list (list (haskell-indent-after-keyword-column open start)))))) ;; open structure? ie ( { [ ((setq open (haskell-indent-open-structure start (point))) (haskell-indent-inside-paren open)) ;; full indentation ((setq contour-line (haskell-indent-contour-line start (point))) (haskell-indent-layout-indent-info start contour-line)) (t ;; simple contour just one indentation at start (list (list (if (and (eq haskell-literate 'bird) (eq (haskell-indent-point-to-col start) 1)) ;; for a Bird style literate script put default offset ;; in the case of no indentation (1+ haskell-indent-literate-Bird-default-offset) (haskell-indent-point-to-col start)))))))) (defvar haskell-indent-last-info nil) (defun haskell-indent-cycle () "Indentation cycle. We stay in the cycle as long as the TAB key is pressed." (interactive "*") (if (and haskell-literate (not (haskell-indent-within-literate-code))) ;; use the ordinary tab for text... (funcall (default-value 'indent-line-function)) (let ((marker (if (> (current-column) (haskell-indent-current-indentation)) (point-marker))) (bol (progn (beginning-of-line) (point)))) (haskell-indent-back-to-indentation) (unless (and (eq last-command this-command) (eq bol (car haskell-indent-last-info))) (save-excursion (setq haskell-indent-last-info (list bol (haskell-indent-indentation-info) 0 0)))) (let* ((il (nth 1 haskell-indent-last-info)) (index (nth 2 haskell-indent-last-info)) (last-insert-length (nth 3 haskell-indent-last-info)) (indent-info (nth index il))) (haskell-indent-line-to (car indent-info)) ; insert indentation (delete-char last-insert-length) (setq last-insert-length 0) (let ((text (cdr indent-info))) (if text (progn (insert text) (setq last-insert-length (length text))))) (setq haskell-indent-last-info (list bol il (% (1+ index) (length il)) last-insert-length)) (if (= (length il) 1) (message "Sole indentation") (message "Indent cycle (%d)..." (length il))) (if marker (goto-char (marker-position marker))))))) (defun haskell-indent-region (start end) (error "Auto-reindentation of a region is not supported")) ;;; alignment functions (defun haskell-indent-shift-columns (dest-column region-stack) "Shift columns in REGION-STACK to go to DEST-COLUMN. Elements of the stack are pairs of points giving the start and end of the regions to move." (let (reg col diffcol reg-end) (while (setq reg (pop region-stack)) (setq reg-end (copy-marker (cdr reg))) (goto-char (car reg)) (setq col (current-column)) (setq diffcol (- dest-column col)) (if (not (zerop diffcol)) (catch 'end-of-buffer (while (<= (point) (marker-position reg-end)) (if (< diffcol 0) (backward-delete-char-untabify (- diffcol) nil) (insert-char ?\ diffcol)) (end-of-line 2) ; should be (forward-line 1) (if (eobp) ; but it adds line at the end... (throw 'end-of-buffer nil)) (move-to-column col))))))) (defun haskell-indent-align-def (p-arg type) "Align guards or rhs within the current definition before point. If P-ARG is t align all defs up to the mark. TYPE is either 'guard or 'rhs." (save-excursion (let (start-block end-block (maxcol (if (eq type 'rhs) haskell-indent-rhs-align-column 0)) contour sep defname defnamepos defcol pos lastpos regstack eqns-start start-found) ;; find the starting and ending boundary points for alignment (if p-arg (if (mark) ; aligning everything in the region (progn (when (> (mark) (point)) (exchange-point-and-mark)) (setq start-block (save-excursion (goto-char (mark)) (line-beginning-position))) (setq end-block (progn (if (haskell-indent-bolp) (haskell-indent-forward-line -1)) (line-end-position)))) (error "The mark is not set for aligning definitions")) ;; aligning the current definition (setq start-block (haskell-indent-start-of-def)) (setq end-block (line-end-position))) ;; find the start of the current valdef using the contour line ;; in reverse order because we need the nearest one from the end (setq contour (reverse (haskell-indent-contour-line start-block end-block))) (setq pos (car contour)) ; keep the start of the first contour ;; find the nearest start of a definition (while (and (not defname) contour) (goto-char (pop contour)) (if (haskell-indent-open-structure start-block (point)) nil (setq sep (haskell-indent-separate-valdef (point) end-block)) (if (nth 5 sep) ; is there a rhs? (progn (setq defnamepos (nth 0 sep)) (setq defname (nth 1 sep)))))) ;; start building the region stack (if defnamepos (progn ; there is a valdef ;; find the start of each equation or guard (if p-arg ; when indenting a region ;; accept any start of id or pattern as def name (setq defname "\\<\\|(")) (setq defcol (haskell-indent-point-to-col defnamepos)) (goto-char pos) (setq end-block (line-end-position)) (catch 'top-of-buffer (while (and (not start-found) (>= (point) start-block)) (if (<= (haskell-indent-current-indentation) defcol) (progn (move-to-column defcol) (if (and (looking-at defname) ; start of equation (not (haskell-indent-open-structure start-block (point)))) (push (cons (point) 'eqn) eqns-start) ;; found a less indented point not starting an equation (setq start-found t))) ;; more indented line (haskell-indent-back-to-indentation) (if (and (eq (haskell-indent-type-at-point) 'guard) ; start of a guard (not (haskell-indent-open-structure start-block (point)))) (push (cons (point) 'gd) eqns-start))) (if (bobp) (throw 'top-of-buffer nil) (haskell-indent-backward-to-indentation 1)))) ;; remove the spurious guards before the first equation (while (and eqns-start (eq (cdar eqns-start) 'gd)) (pop eqns-start)) ;; go through each equation to find the region to indent (while eqns-start (let ((eqn (caar eqns-start))) (setq lastpos (if (cdr eqns-start) (save-excursion (goto-char (caadr eqns-start)) (haskell-indent-forward-line -1) (line-end-position)) end-block)) (setq sep (haskell-indent-separate-valdef eqn lastpos))) (if (eq type 'guard) (setq pos (nth 3 sep)) ;; check if what follows a rhs sign is more indented or not (let ((rhs (nth 5 sep)) (aft-rhs (nth 6 sep))) (if (and rhs aft-rhs (> (haskell-indent-point-to-col rhs) (haskell-indent-point-to-col aft-rhs))) (setq pos aft-rhs) (setq pos rhs)))) (if pos (progn ; update region stack (push (cons pos (or lastpos pos)) regstack) (setq maxcol ; find the highest column number (max maxcol (progn ;find the previous non-empty column (goto-char pos) (skip-chars-backward " \t" (line-beginning-position)) (if (haskell-indent-bolp) ;;if on an empty prefix (haskell-indent-point-to-col pos) ;keep original indent (1+ (haskell-indent-point-to-col (point))))))))) (pop eqns-start)) ;; now shift according to the region stack (if regstack (haskell-indent-shift-columns maxcol regstack))))))) (defun haskell-indent-align-guards-and-rhs (start end) "Align the guards and rhs of functions in the region, which must be active." ;; The `start' and `end' args are dummys right now: they're just there so ;; we can use the "r" interactive spec which properly signals an error. (interactive "*r") (haskell-indent-align-def t 'guard) (haskell-indent-align-def t 'rhs)) ;;; insertion functions (defun haskell-indent-insert-equal () "Insert an = sign and align the previous rhs of the current function." (interactive "*") (if (or (haskell-indent-bolp) (/= (preceding-char) ?\ )) (insert ?\ )) (insert "= ") (haskell-indent-align-def (haskell-indent-mark-active) 'rhs)) (defun haskell-indent-insert-guard (&optional text) "Insert and align a guard sign (|) followed by optional TEXT. Alignment works only if all guards are to the south-east of their |." (interactive "*") (let ((pc (if (haskell-indent-bolp) ?\012 (preceding-char))) (pc1 (or (char-after (- (point) 2)) 0))) ;; check what guard to insert depending on the previous context (if (= pc ?\ ) ; x = any char other than blank or | (if (/= pc1 ?\|) (insert "| ") ; after " x" ()) ; after " |" (if (= pc ?\|) (if (= pc1 ?\|) (insert " | ") ; after "||" (insert " ")) ; after "x|" (insert " | "))) ; general case (if text (insert text)) (haskell-indent-align-def (haskell-indent-mark-active) 'guard))) (defun haskell-indent-insert-otherwise () "Insert a guard sign (|) followed by `otherwise'. Also align the previous guards of the current function." (interactive "*") (haskell-indent-insert-guard "otherwise") (haskell-indent-insert-equal)) (defun haskell-indent-insert-where () "Insert a where keyword at point and indent resulting line. One indentation cycle is used." (interactive "*") (insert "where ") (haskell-indent-cycle)) ;;; haskell-indent-mode (defvar haskell-indent-mode nil "Non-nil if the semi-intelligent Haskell indentation mode is in effect.") (make-variable-buffer-local 'haskell-indent-mode) (defvar haskell-indent-map (let ((map (make-sparse-keymap))) ;; Removed: remapping DEL seems a bit naughty --SDM ;; (define-key map "\177" 'backward-delete-char-untabify) ;; The binding to TAB is already handled by indent-line-function. --Stef ;; (define-key map "\t" 'haskell-indent-cycle) (define-key map [?\C-c ?\C-=] 'haskell-indent-insert-equal) (define-key map [?\C-c ?\C-|] 'haskell-indent-insert-guard) ;; Alternate binding, in case C-c C-| is too inconvenient to type. ;; Duh, C-g is a special key, let's not use it here. ;; (define-key map [?\C-c ?\C-g] 'haskell-indent-insert-guard) (define-key map [?\C-c ?\C-o] 'haskell-indent-insert-otherwise) (define-key map [?\C-c ?\C-w] 'haskell-indent-insert-where) (define-key map [?\C-c ?\C-.] 'haskell-indent-align-guards-and-rhs) (define-key map [?\C-c ?\C->] 'haskell-indent-put-region-in-literate) map)) ;;;###autoload (defun turn-on-haskell-indent () "Turn on ``intelligent'' Haskell indentation mode." (set (make-local-variable 'indent-line-function) 'haskell-indent-cycle) (set (make-local-variable 'indent-region-function) 'haskell-indent-region) (setq haskell-indent-mode t) ;; Activate our keymap. (let ((map (current-local-map))) (while (and map (not (eq map haskell-indent-map))) (setq map (keymap-parent map))) (if map ;; haskell-indent-map is already active: nothing to do. nil ;; Put our keymap on top of the others. We could also put it in ;; second place, or in a minor-mode. The minor-mode approach would be ;; easier, but it's harder for the user to override it. This approach ;; is the closest in behavior compared to the previous code that just ;; used a bunch of local-set-key. (set-keymap-parent haskell-indent-map (current-local-map)) ;; Protect our keymap. (setq map (make-sparse-keymap)) (set-keymap-parent map haskell-indent-map) (use-local-map map))) (run-hooks 'haskell-indent-hook)) (defun turn-off-haskell-indent () "Turn off ``intelligent'' Haskell indentation mode." (kill-local-variable 'indent-line-function) ;; Remove haskell-indent-map from the local map. (let ((map (current-local-map))) (while map (let ((parent (keymap-parent map))) (if (eq haskell-indent-map parent) (set-keymap-parent map (keymap-parent parent)) (setq map parent))))) (setq haskell-indent-mode nil)) ;; Put this minor mode on the global minor-mode-alist. (or (assq 'haskell-indent-mode (default-value 'minor-mode-alist)) (setq-default minor-mode-alist (append (default-value 'minor-mode-alist) '((haskell-indent-mode " Ind"))))) ;;;###autoload (defun haskell-indent-mode (&optional arg) "``Intelligent'' Haskell indentation mode. This deals with the layout rule of Haskell. \\[haskell-indent-cycle] starts the cycle which proposes new possibilities as long as the TAB key is pressed. Any other key or mouse click terminates the cycle and is interpreted except for RET which merely exits the cycle. Other special keys are: \\[haskell-indent-insert-equal] inserts an = \\[haskell-indent-insert-guard] inserts an | \\[haskell-indent-insert-otherwise] inserts an | otherwise = these functions also align the guards and rhs of the current definition \\[haskell-indent-insert-where] inserts a where keyword \\[haskell-indent-align-guards-and-rhs] aligns the guards and rhs of the region \\[haskell-indent-put-region-in-literate] makes the region a piece of literate code in a literate script Invokes `haskell-indent-hook' if not nil." (interactive "P") (setq haskell-indent-mode (if (null arg) (not haskell-indent-mode) (> (prefix-numeric-value arg) 0))) (if haskell-indent-mode (turn-on-haskell-indent) (turn-off-haskell-indent))) (provide 'haskell-indent) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-indent.el ends here haskell-mode-13.10/haskell-indentation.el000066400000000000000000001223301225210037200203350ustar00rootroot00000000000000;;; haskell-indentation.el -- indentation module for Haskell Mode ;; Copyright (C) 2009 Kristof Bastiaensen ;; Author: Kristof Bastiaensen ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; Installation: ;; ;; To turn indentation on for all Haskell buffers under Haskell mode ;; add this to .emacs: ;; ;; (add-hook haskell-mode-hook 'turn-on-haskell-indentation) ;; ;; Otherwise, call `haskell-indentation-mode'. ;;; Code: (require 'syntax) (with-no-warnings (require 'cl)) ;; Dynamically scoped variables. (defvar following-token) (defvar current-token) (defvar left-indent) (defvar starter-indent) (defvar current-indent) (defvar layout-indent) (defvar parse-line-number) (defvar possible-indentations) (defvar indentation-point) (defvar haskell-literate) (defgroup haskell-indentation nil "Haskell indentation." :link '(custom-manual "(haskell-mode)Indentation") :group 'haskell :prefix "haskell-indentation-") (defcustom haskell-indentation-cycle-warn t "Warn before moving to the leftmost indentation, if you tab at the rightmost one." :type 'boolean :group 'haskell-indentation) (defcustom haskell-indentation-delete-backward-indentation t "Delete backward removes indentation." :type 'boolean :group 'haskell-indentation) (defcustom haskell-indentation-delete-backward-jump-line nil "Delete backward jumps to the previous line when removing last indentation." :type 'boolean :group 'haskell-indentation) (defcustom haskell-indentation-delete-indentation t "Delete removes indentation." :type 'boolean :group 'haskell-indentation) (defcustom haskell-indentation-layout-offset 2 "Extra indentation to add before expressions in a haskell layout list." :type 'integer :group 'haskell-indentation) (defcustom haskell-indentation-starter-offset 1 "Extra indentation after an opening keyword (e.g. let)." :type 'integer :group 'haskell-indentation) (defcustom haskell-indentation-left-offset 2 "Extra indentation after an indentation to the left (e.g. after do)." :type 'integer :group 'haskell-indentation) (defcustom haskell-indentation-ifte-offset 2 "Extra indentation after the keywords `if' `then' or `else'." :type 'integer :group 'haskell-indentation) (defcustom haskell-indentation-where-pre-offset 2 "Extra indentation before the keyword `where'." :type 'integer :group 'haskell-indentation) (defcustom haskell-indentation-where-post-offset 2 "Extra indentation after the keyword `where'." :type 'integer :group 'haskell-indentation) (defcustom haskell-indentation-birdtrack-extra-space t "Append a space after every birdtrack in literate mode." :type 'boolean :group 'haskell-indentation) ;; Avoid a global bogus definition (which the original run-time ;; `defun' made), and support Emacs 21 without the syntax.el add-on. (eval-when-compile (unless (fboundp 'syntax-ppss) (defsubst syntax-ppss (&rest pos) (parse-partial-sexp (point-min) (or pos (point)))))) (defconst haskell-indentation-mode-map (let ((keymap (make-sparse-keymap))) (define-key keymap [?\r] 'haskell-newline-and-indent) (define-key keymap [backspace] 'haskell-indentation-delete-backward-char) (define-key keymap [?\C-d] 'haskell-indentation-delete-char) keymap)) ;; Used internally (defvar haskell-indent-last-position) ;;;###autoload (define-minor-mode haskell-indentation-mode "Haskell indentation mode that deals with the layout rule. It rebinds RET, DEL and BACKSPACE, so that indentations can be set and deleted as if they were real tabs. It supports autofill-mode." :lighter " Ind" :keymap haskell-indentation-mode-map (kill-local-variable 'indent-line-function) (kill-local-variable 'normal-auto-fill-function) (when haskell-indentation-mode (setq max-lisp-eval-depth (max max-lisp-eval-depth 600)) ;; set a higher limit for recursion (set (make-local-variable 'indent-line-function) 'haskell-indentation-indent-line) (set (make-local-variable 'normal-auto-fill-function) 'haskell-indentation-auto-fill-function) (set (make-local-variable 'haskell-indent-last-position) nil))) ;;;###autoload (defun turn-on-haskell-indentation () "Turn on the haskell-indentation minor mode." (interactive) (haskell-indentation-mode t)) (put 'parse-error 'error-conditions '(error parse-error)) (put 'parse-error 'error-message "Parse error") (defun parse-error (&rest args) (signal 'parse-error (apply 'format args))) (defmacro on-parse-error (except &rest body) `(condition-case parse-error-string (progn ,@body) (parse-error ,except (message "%s" (cdr parse-error-string))))) (defun haskell-current-column () "Compute current column according to haskell syntax rules, correctly ignoring composition." (save-excursion (let ((start (point)) (cc 0)) (beginning-of-line) (while (< (point) start) (if (= (char-after) ?\t) (setq cc (* 8 (+ 1 (/ cc 8)))) (incf cc)) (forward-char)) cc))) (defun kill-indented-line (&optional arg) "`kill-line' for indented text. Preserves indentation and removes extra whitespace" (interactive "P") (let ((col (haskell-current-column)) (old-point (point))) (cond ((or (and (numberp arg) (< arg 0)) (and (not (looking-at "[ \t]*$")) (or (not (numberp arg)) (zerop arg)))) ;use default behavior when calling with a negative argument ;or killing (once) from the middle of a line (kill-line arg)) ((and (skip-chars-backward " \t") ;always true (bolp) (save-excursion (forward-line arg) (not (looking-at "[ \t]*$")))) ; killing from an empty line: ; preserve indentation of the next line (kill-region (point) (save-excursion (forward-line arg) (point))) (skip-chars-forward " \t") (if (> (haskell-current-column) col) (move-to-column col))) (t ; killing from not empty line: ; kill all indentation (goto-char old-point) (kill-region (point) (save-excursion (forward-line arg) (skip-chars-forward " \t") (point))))))) (defun haskell-indentation-auto-fill-function () (when (> (haskell-current-column) fill-column) (while (> (haskell-current-column) fill-column) (skip-syntax-backward "-") (skip-syntax-backward "^-")) (let ((auto-fill-function nil) (indent (car (last (haskell-indentation-find-indentations))))) (newline) (when (eq haskell-literate 'bird) (insert ">")) (indent-to indent) (end-of-line)))) (defun haskell-indentation-reindent (col) (beginning-of-line) (delete-region (point) (progn (when (and (eq haskell-literate 'bird) (eq (char-after) ?>)) (forward-char)) (skip-syntax-forward "-") (point))) (when (eq haskell-literate 'bird) (insert ">")) (indent-to col)) (defun haskell-indentation-current-indentation () (if (eq haskell-literate 'bird) (save-excursion (beginning-of-line) (forward-char) (skip-syntax-forward "-") (current-column)) (current-indentation))) (defun haskell-indentation-outside-bird-line () (and (eq haskell-literate 'bird) (or (< (current-column) 2) (save-excursion (beginning-of-line) (not (eq (char-after) ?>)))))) (defun haskell-newline-and-indent () (interactive) (if (haskell-indentation-outside-bird-line) (progn (delete-horizontal-space) (newline)) (on-parse-error (newline) (let* ((cc (haskell-current-column)) (ci (haskell-indentation-current-indentation)) (indentations (haskell-indentation-find-indentations))) (skip-syntax-forward "-") (if (prog1 (and (eolp) (not (= (haskell-current-column) ci))) (delete-horizontal-space) (if (not (eq haskell-literate 'bird)) (newline) (when haskell-indentation-birdtrack-extra-space (indent-to 2)) (newline) (insert "> "))) (haskell-indentation-reindent (max (haskell-indentation-butlast indentations) (haskell-indentation-matching-indentation ci indentations))) (haskell-indentation-reindent (haskell-indentation-matching-indentation cc indentations))))))) (defun haskell-indentation-one-indentation (col indentations) (let* ((last-pair (last indentations))) (cond ((null indentations) col) ((null (cdr indentations)) (car indentations)) ((<= col (car last-pair)) col) (t (car last-pair))))) (defun haskell-indentation-butlast (indentations) (when (consp (cdr indentations)) (while (cddr indentations) (setq indentations (cdr indentations)))) (car indentations)) (defun haskell-indentation-next-indentation (col indentations) "Find the lefmost indentation which is greater than COL." (catch 'return (while indentations (if (or (< col (car indentations)) (null (cdr indentations))) (throw 'return (car indentations)) (setq indentations (cdr indentations)))) col)) (defun haskell-indentation-previous-indentation (col indentations) "Find the rightmost indentation which is less than COL." (and indentations (> col (car indentations)) (catch 'return (while indentations (if (or (null (cdr indentations)) (<= col (cadr indentations))) (throw 'return (car indentations)) (setq indentations (cdr indentations)))) col))) (defun haskell-indentation-matching-indentation (col indentations) "Find the leftmost indentation which is greater than or equal to COL." (catch 'return (while indentations (if (or (<= col (car indentations)) (null (cdr indentations))) (throw 'return (car indentations)) (setq indentations (cdr indentations)))) col)) (defun haskell-indentation-indent-line () (when (save-excursion (beginning-of-line) (not (nth 8 (syntax-ppss)))) (let ((ci (haskell-indentation-current-indentation)) (start-column (haskell-current-column))) (cond ((> (haskell-current-column) ci) (save-excursion (move-to-column ci) (haskell-indentation-reindent (haskell-indentation-one-indentation ci (haskell-indentation-find-indentations))))) ((= (haskell-current-column) ci) (haskell-indentation-reindent (haskell-indentation-next-indentation ci (haskell-indentation-find-indentations)))) (t (move-to-column ci) (haskell-indentation-reindent (haskell-indentation-matching-indentation ci (haskell-indentation-find-indentations))))) (cond ((not (= (haskell-current-column) start-column)) (setq haskell-indent-last-position nil)) ((not haskell-indentation-cycle-warn) (haskell-indentation-reindent (haskell-indentation-next-indentation -1 (haskell-indentation-find-indentations)))) ((not (equal (point) haskell-indent-last-position)) (message "Press TAB again to go to the leftmost indentation") (setq haskell-indent-last-position (point))) (t (haskell-indentation-reindent (haskell-indentation-next-indentation -1 (haskell-indentation-find-indentations)))))))) (defun haskell-indentation-delete-backward-char (n) (interactive "p") (on-parse-error (delete-char (- n)) (cond ((haskell-indentation-outside-bird-line) (delete-char (- n))) ((and delete-selection-mode mark-active (not (= (point) (mark)))) (delete-region (mark) (point))) ((or (= (haskell-current-column) 0) (> (haskell-current-column) (haskell-indentation-current-indentation)) (nth 8 (syntax-ppss))) (delete-char (- n))) (haskell-indentation-delete-backward-indentation (let* ((ci (haskell-indentation-current-indentation)) (pi (haskell-indentation-previous-indentation ci (haskell-indentation-find-indentations)))) (save-excursion (cond (pi (move-to-column pi) (delete-region (point) (progn (move-to-column ci) (point)))) (t (if (not haskell-indentation-delete-backward-jump-line) (delete-char (- 1)) (beginning-of-line) (delete-region (max (point-min) (- (point) 1)) (progn (move-to-column ci) (point))))))))) (t (delete-char (- n)))))) (defun haskell-indentation-delete-char (n) (interactive "p") (if (haskell-indentation-outside-bird-line) (delete-char n) (on-parse-error (delete-char n) (cond ((and delete-selection-mode mark-active (not (= (point) (mark)))) (delete-region (mark) (point))) ((and (eq haskell-literate 'bird) (looking-at "\n> ")) (delete-char (+ n 2))) ((or (eolp) (>= (haskell-current-column) (haskell-indentation-current-indentation)) (nth 8 (syntax-ppss))) (delete-char n)) (haskell-indentation-delete-indentation (let* ((ci (haskell-indentation-current-indentation)) (pi (haskell-indentation-previous-indentation ci (haskell-indentation-find-indentations)))) (save-excursion (if (and pi (> pi (haskell-current-column))) (move-to-column pi)) (delete-region (point) (progn (move-to-column ci) (point)))))) (t (delete-char (- n))))))) (defun haskell-indentation-goto-least-indentation () (beginning-of-line) (if (eq haskell-literate 'bird) (catch 'return (while t (when (not (eq (char-after) ?>)) (forward-line) (forward-char 2) (throw 'return nil)) (let ((ps (nth 8 (syntax-ppss)))) (when ps ;; inside comment or string (goto-char ps) (beginning-of-line))) (when (and (>= 2 (haskell-indentation-current-indentation)) (not (looking-at ">\\s-*$"))) (forward-char 2) (throw 'return nil)) (when (bobp) (forward-char 2) (throw 'return nil)) (forward-line -1))) ;; not bird style (catch 'return (while (not (bobp)) (forward-comment (- (buffer-size))) (beginning-of-line) (let ((ps (nth 8 (syntax-ppss)))) (when ps ;; inside comment or string (goto-char ps))) (when (= 0 (haskell-indentation-current-indentation)) (throw 'return nil)))) (beginning-of-line) (when (bobp) (forward-comment (buffer-size))))) (defun haskell-indentation-parse-to-indentations () (save-excursion (skip-syntax-forward "-") (let ((indentation-point (point)) (layout-indent 0) (parse-line-number 0) (current-indent haskell-indentation-layout-offset) (starter-indent haskell-indentation-layout-offset) (left-indent haskell-indentation-layout-offset) (case-fold-search nil) current-token following-token possible-indentations) (haskell-indentation-goto-least-indentation) (if (<= indentation-point (point)) (haskell-indentation-first-indentation) (setq current-token (haskell-indentation-peek-token)) (catch 'parse-end (haskell-indentation-toplevel) (unless (eq current-token 'end-tokens) (parse-error "Illegal token: %s" current-token))) possible-indentations)))) (defun haskell-indentation-first-indentation () (if (eq haskell-literate 'bird) '(2) '(0))) (defun haskell-indentation-find-indentations () (let ((ppss (syntax-ppss))) (cond ((nth 3 ppss) (haskell-indentation-first-indentation)) ((nth 4 ppss) (if (save-excursion (and (skip-syntax-forward "-") (eolp) (not (> (forward-line 1) 0)) (not (nth 4 (syntax-ppss))))) (haskell-indentation-parse-to-indentations) (haskell-indentation-first-indentation))) (t (haskell-indentation-parse-to-indentations))))) (defconst haskell-indentation-unicode-tokens '(("→" . "->") ;; #x2192 RIGHTWARDS ARROW ("∷" . "::") ;; #x2237 PROPORTION ("←" . "<-") ;; #x2190 LEFTWARDS ARROW ("⇒" . "=>") ;; #x21D2 RIGHTWARDS DOUBLE ARROW ("∀" . "forall") ;; #x2200 FOR ALL ("↢" . "-<") ;; #x2919 LEFTWARDS ARROW-TAIL ("↣" . ">-") ;; #x291A RIGHTWARDS ARROW-TAIL ("⤛" . "-<<") ;; #x291B LEFTWARDS DOUBLE ARROW-TAIL ("⤜" . ">>-") ;; #x291C RIGHTWARDS DOUBLE ARROW-TAIL ("★" . "*")) ;; #x2605 BLACK STAR "Translation dictionary from UnicodeSyntax tokens to their ASCII representation.") (defconst haskell-indentation-toplevel-list '(("module" . haskell-indentation-module) ("data" . (lambda () (haskell-indentation-statement-right #'haskell-indentation-data))) ("type" . (lambda () (haskell-indentation-statement-right #'haskell-indentation-data))) ("newtype" . (lambda () (haskell-indentation-statement-right #'haskell-indentation-data))) ("class" . haskell-indentation-class-declaration) ("instance" . haskell-indentation-class-declaration ))) (defconst haskell-indentation-type-list '(("::" . (lambda () (haskell-indentation-with-starter (lambda () (haskell-indentation-separated #'haskell-indentation-type "->" nil)) nil))) ("(" . (lambda () (haskell-indentation-list #'haskell-indentation-type ")" "," nil))) ("[" . (lambda () (haskell-indentation-list #'haskell-indentation-type "]" "," nil))) ("{" . (lambda () (haskell-indentation-list #'haskell-indentation-type "}" "," nil))))) (defconst haskell-indentation-expression-list '(("data" . haskell-indentation-data) ("type" . haskell-indentation-data) ("newtype" . haskell-indentation-data) ("if" . (lambda () (haskell-indentation-phrase '(haskell-indentation-expression "then" haskell-indentation-expression "else" haskell-indentation-expression)))) ("let" . (lambda () (haskell-indentation-phrase '(haskell-indentation-declaration-layout "in" haskell-indentation-expression)))) ("do" . (lambda () (haskell-indentation-with-starter #'haskell-indentation-expression-layout nil))) ("mdo" . (lambda () (haskell-indentation-with-starter #'haskell-indentation-expression-layout nil))) ("rec" . (lambda () (haskell-indentation-with-starter #'haskell-indentation-expression-layout nil))) ("case" . (lambda () (haskell-indentation-phrase '(haskell-indentation-expression "of" haskell-indentation-case-layout)))) ("\\" . (lambda () (haskell-indentation-with-starter #'haskell-indentation-lambda-maybe-lambdacase nil))) ("proc" . (lambda () (haskell-indentation-phrase '(haskell-indentation-expression "->" haskell-indentation-expression)))) ("where" . (lambda () (haskell-indentation-with-starter #'haskell-indentation-declaration-layout nil t))) ("::" . (lambda () (haskell-indentation-with-starter (lambda () (haskell-indentation-separated #'haskell-indentation-type "->" nil)) nil))) ("=" . (lambda () (haskell-indentation-statement-right #'haskell-indentation-expression))) ("<-" . (lambda () (haskell-indentation-statement-right #'haskell-indentation-expression))) ("(" . (lambda () (haskell-indentation-list #'haskell-indentation-expression ")" '(list "," "->") nil))) ("[" . (lambda () (haskell-indentation-list #'haskell-indentation-expression "]" "," "|"))) ("{" . (lambda () (haskell-indentation-list #'haskell-indentation-expression "}" "," nil))))) (defun haskell-indentation-expression-layout () (haskell-indentation-layout #'haskell-indentation-expression)) (defun haskell-indentation-declaration-layout () (haskell-indentation-layout #'haskell-indentation-declaration)) (defun haskell-indentation-case-layout () (haskell-indentation-layout #'haskell-indentation-case)) ;; After a lambda (backslash) there are two possible cases: ;; - the new lambdacase expression, that can be recognized by the ;; next token being "case", ;; - or simply an anonymous function definition in the form of ;; "expression -> expression". (defun haskell-indentation-lambda-maybe-lambdacase () (if (string= current-token "case") (haskell-indentation-with-starter #'haskell-indentation-case-layout nil) (haskell-indentation-phrase-rest '(haskell-indentation-expression "->" haskell-indentation-expression)))) (defun haskell-indentation-fundep () (haskell-indentation-with-starter (lambda () (haskell-indentation-separated #'haskell-indentation-fundep1 "," nil)) nil)) (defun haskell-indentation-fundep1 () (let ((current-indent (haskell-current-column))) (while (member current-token '(value "->")) (haskell-indentation-read-next-token)) (when (and (eq current-token 'end-tokens) (member following-token '(value "->"))) (haskell-indentation-add-indentation current-indent)))) (defun haskell-indentation-toplevel () (haskell-indentation-layout (lambda () (let ((parser (assoc current-token haskell-indentation-toplevel-list))) (if parser (funcall (cdr parser)) (haskell-indentation-declaration)))))) (defun haskell-indentation-type () (let ((current-indent (haskell-current-column))) (catch 'return (while t (cond ((member current-token '(value operator "->")) (haskell-indentation-read-next-token)) ((eq current-token 'end-tokens) (when (member following-token '(value operator no-following-token "->" "(" "[" "{" "::")) (haskell-indentation-add-indentation current-indent)) (throw 'return nil)) (t (let ((parser (assoc current-token haskell-indentation-type-list))) (if (not parser) (throw 'return nil) (funcall (cdr parser)))))))))) (defun haskell-indentation-data () (haskell-indentation-with-starter (lambda () (when (string= current-token "instance") (haskell-indentation-read-next-token)) (haskell-indentation-type) (cond ((string= current-token "=") (haskell-indentation-with-starter (lambda () (haskell-indentation-separated #'haskell-indentation-type "|" "deriving")) nil)) ((string= current-token "where") (haskell-indentation-with-starter #'haskell-indentation-expression-layout nil)))) nil)) (defun haskell-indentation-class-declaration () (haskell-indentation-with-starter (lambda () (haskell-indentation-type) (when (string= current-token "|") (haskell-indentation-fundep)) (when (string= current-token "where") (haskell-indentation-with-starter #'haskell-indentation-expression-layout nil))) nil)) (defun haskell-indentation-module () (haskell-indentation-with-starter (lambda () (let ((current-indent (haskell-current-column))) (haskell-indentation-read-next-token) (when (string= current-token "(") (haskell-indentation-list #'haskell-indentation-module-export ")" "," nil)) (when (eq current-token 'end-tokens) (haskell-indentation-add-indentation current-indent) (throw 'parse-end nil)) (when (string= current-token "where") (haskell-indentation-read-next-token) (when (eq current-token 'end-tokens) (haskell-indentation-add-layout-indent) (throw 'parse-end nil)) (haskell-indentation-layout #'haskell-indentation-toplevel)))) nil)) (defun haskell-indentation-module-export () (cond ((string= current-token "module") (let ((current-indent (haskell-current-column))) (haskell-indentation-read-next-token) (cond ((eq current-token 'end-tokens) (haskell-indentation-add-indentation current-indent)) ((eq current-token 'value) (haskell-indentation-read-next-token))))) (t (haskell-indentation-type)))) (defun haskell-indentation-list (parser end sep stmt-sep) (haskell-indentation-with-starter `(lambda () (haskell-indentation-separated #',parser ,sep ,stmt-sep)) end)) (defun haskell-indentation-with-starter (parser end &optional where-expr?) (let ((starter-column (haskell-current-column)) (current-indent current-indent) (left-indent (if (= (haskell-current-column) (haskell-indentation-current-indentation)) (haskell-current-column) left-indent))) (haskell-indentation-read-next-token) (when (eq current-token 'end-tokens) (if (equal following-token end) (haskell-indentation-add-indentation starter-column) (if where-expr? (haskell-indentation-add-where-post-indent left-indent) (haskell-indentation-add-indentation (+ left-indent haskell-indentation-left-offset)))) (throw 'parse-end nil)) (let* ((current-indent (haskell-current-column)) (starter-indent (min starter-column current-indent)) (left-indent (if end (+ current-indent haskell-indentation-starter-offset) left-indent))) (funcall parser) (cond ((eq current-token 'end-tokens) (when (equal following-token end) (haskell-indentation-add-indentation starter-indent)) (when end (throw 'parse-end nil))) ;; add no indentations ((equal current-token end) (haskell-indentation-read-next-token)) ;; continue (end (parse-error "Illegal token: %s" current-token)))))) (defun haskell-indentation-case () (haskell-indentation-expression) (cond ((eq current-token 'end-tokens) (haskell-indentation-add-indentation current-indent)) ((string= current-token "|") (haskell-indentation-with-starter (lambda () (haskell-indentation-separated #'haskell-indentation-case "|" nil)) nil)) ((string= current-token "->") (haskell-indentation-statement-right #'haskell-indentation-expression)) ;; otherwise fallthrough )) (defun haskell-indentation-statement-right (parser) (haskell-indentation-read-next-token) (when (eq current-token 'end-tokens) (haskell-indentation-add-indentation (+ left-indent haskell-indentation-left-offset)) (throw 'parse-end nil)) (let ((current-indent (haskell-current-column))) (funcall parser))) (defun haskell-indentation-simple-declaration () (haskell-indentation-expression) (cond ((string= current-token "=") (haskell-indentation-statement-right #'haskell-indentation-expression)) ((string= current-token "::") (haskell-indentation-statement-right #'haskell-indentation-type)) ((and (eq current-token 'end-tokens) (string= following-token "=")) (haskell-indentation-add-indentation current-indent) (throw 'parse-end nil)))) (defun haskell-indentation-declaration () (haskell-indentation-expression) (cond ((string= current-token "|") (haskell-indentation-with-starter (lambda () (haskell-indentation-separated #'haskell-indentation-expression "," "|")) nil)) ((eq current-token 'end-tokens) (when (member following-token '("|" "=" "::" ",")) (haskell-indentation-add-indentation current-indent) (throw 'parse-end nil))))) (defun haskell-indentation-layout (parser) (if (string= current-token "{") (haskell-indentation-list parser "}" ";" nil) (haskell-indentation-implicit-layout-list parser))) (defun haskell-indentation-expression-token (token) (member token '("if" "let" "do" "case" "\\" "(" "[" "::" value operator no-following-token))) (defun haskell-indentation-expression () (let ((current-indent (haskell-current-column))) (catch 'return (while t (cond ((memq current-token '(value operator)) (haskell-indentation-read-next-token)) ((eq current-token 'end-tokens) (cond ((string= following-token "where") (haskell-indentation-add-where-pre-indent)) ((haskell-indentation-expression-token following-token) (haskell-indentation-add-indentation current-indent))) (throw 'return nil)) (t (let ((parser (assoc current-token haskell-indentation-expression-list))) (when (null parser) (throw 'return nil)) (funcall (cdr parser)) (when (and (eq current-token 'end-tokens) (string= (car parser) "let") (= haskell-indentation-layout-offset current-indent) (haskell-indentation-expression-token following-token)) ;; inside a layout, after a let construct (haskell-indentation-add-layout-indent) (throw 'parse-end nil)) (unless (member (car parser) '("(" "[" "{" "do" "case")) (throw 'return nil))))))))) (defun haskell-indentation-test-indentations () (interactive) (let ((indentations (save-excursion (haskell-indentation-find-indentations))) (str "") (pos 0)) (while indentations (when (>= (car indentations) pos) (setq str (concat str (make-string (- (car indentations) pos) ?\ ) "|")) (setq pos (+ 1 (car indentations)))) (setq indentations (cdr indentations))) (end-of-line) (newline) (insert str))) (defun haskell-indentation-separated (parser separator stmt-separator) (catch 'return (while t (funcall parser) (cond ((if (listp separator) (member current-token separator) (equal current-token separator)) (haskell-indentation-at-separator)) ((equal current-token stmt-separator) (setq starter-indent (haskell-current-column)) (haskell-indentation-at-separator)) ((eq current-token 'end-tokens) (cond ((or (equal following-token separator) (equal following-token stmt-separator)) (haskell-indentation-add-indentation starter-indent) (throw 'parse-end nil))) (throw 'return nil)) (t (throw 'return nil)))))) (defun haskell-indentation-at-separator () (let ((separator-column (and (= (haskell-current-column) (haskell-indentation-current-indentation)) (haskell-current-column)))) (haskell-indentation-read-next-token) (cond ((eq current-token 'end-tokens) (haskell-indentation-add-indentation current-indent) (throw 'return nil)) (separator-column ;; on the beginning of the line (setq current-indent (haskell-current-column)) (setq starter-indent separator-column))))) (defun haskell-indentation-implicit-layout-list (parser) (let* ((layout-indent (haskell-current-column)) (current-indent (haskell-current-column)) (left-indent (haskell-current-column))) (catch 'return (while t (let ((left-indent left-indent)) (funcall parser)) (cond ((member current-token '(layout-next ";")) (haskell-indentation-read-next-token)) ((eq current-token 'end-tokens) (when (or (haskell-indentation-expression-token following-token) (string= following-token ";")) (haskell-indentation-add-layout-indent)) (throw 'return nil)) (t (throw 'return nil)))))) ;; put haskell-indentation-read-next-token outside the current-indent definition ;; so it will not return 'layout-end again (when (eq current-token 'layout-end) (haskell-indentation-read-next-token))) ;; leave layout at 'layout-end or illegal token (defun haskell-indentation-phrase (phrase) (haskell-indentation-with-starter `(lambda () (haskell-indentation-phrase-rest ',phrase)) nil)) (defun haskell-indentation-phrase-rest (phrase) (let ((starter-line parse-line-number)) (let ((current-indent (haskell-current-column))) (funcall (car phrase))) (cond ((eq current-token 'end-tokens) (cond ((null (cdr phrase))) ;; fallthrough ((equal following-token (cadr phrase)) (haskell-indentation-add-indentation starter-indent) (throw 'parse-end nil)) ((string= (cadr phrase) "in") (when (= left-indent layout-indent) (haskell-indentation-add-layout-indent) (throw 'parse-end nil))) (t (throw 'parse-end nil)))) ((null (cdr phrase))) ((equal (cadr phrase) current-token) (let* ((on-new-line (= (haskell-current-column) (haskell-indentation-current-indentation))) (lines-between (- parse-line-number starter-line)) (left-indent (if (<= lines-between 0) left-indent starter-indent))) (haskell-indentation-read-next-token) (when (eq current-token 'end-tokens) (haskell-indentation-add-indentation (cond ((member (cadr phrase) '("then" "else")) (+ starter-indent haskell-indentation-ifte-offset)) ((member (cadr phrase) '("in" "->")) ;; expression ending in another expression (if on-new-line (+ left-indent haskell-indentation-starter-offset) left-indent)) (t (+ left-indent haskell-indentation-left-offset)))) (throw 'parse-end nil)) (haskell-indentation-phrase-rest (cddr phrase)))) ((string= (cadr phrase) "in")) ;; fallthrough (t (parse-error "Expecting %s" (cadr phrase)))))) (defun haskell-indentation-add-indentation (indent) (haskell-indentation-push-indentation (if (<= indent layout-indent) (+ layout-indent haskell-indentation-layout-offset) indent))) (defun haskell-indentation-add-layout-indent () (haskell-indentation-push-indentation layout-indent)) (defun haskell-indentation-add-where-pre-indent () (haskell-indentation-push-indentation (+ layout-indent haskell-indentation-where-pre-offset)) (if (= layout-indent haskell-indentation-layout-offset) (haskell-indentation-push-indentation haskell-indentation-where-pre-offset))) (defun haskell-indentation-add-where-post-indent (indent) (haskell-indentation-push-indentation (+ indent haskell-indentation-where-post-offset))) (defun haskell-indentation-push-indentation (indent) (when (or (null possible-indentations) (< indent (car possible-indentations))) (setq possible-indentations (cons indent possible-indentations)))) (defun haskell-indentation-token-test () (let ((current-token nil) (following-token nil) (layout-indent 0) (parse-line-number 0) (indentation-point (mark))) (haskell-indentation-read-next-token))) (defun haskell-indentation-read-next-token () (cond ((eq current-token 'end-tokens) 'end-tokens) ((eq current-token 'layout-end) (cond ((> layout-indent (haskell-current-column)) 'layout-end) ((= layout-indent (haskell-current-column)) (setq current-token 'layout-next)) ((< layout-indent (haskell-current-column)) (setq current-token (haskell-indentation-peek-token))))) ((eq current-token 'layout-next) (setq current-token (haskell-indentation-peek-token))) ((> layout-indent (haskell-current-column)) (setq current-token 'layout-end)) (t (haskell-indentation-skip-token) (if (>= (point) indentation-point) (progn (setq following-token (if (= (point) indentation-point) (haskell-indentation-peek-token) 'no-following-token)) (setq current-token 'end-tokens)) (when (= (haskell-current-column) (haskell-indentation-current-indentation)) ;; on a new line (setq current-indent (haskell-current-column)) (setq left-indent (haskell-current-column)) (setq parse-line-number (+ parse-line-number 1))) (cond ((> layout-indent (haskell-current-column)) (setq current-token 'layout-end)) ((= layout-indent (haskell-current-column)) (setq current-token 'layout-next)) (t (setq current-token (haskell-indentation-peek-token)))))))) (defun haskell-indentation-peek-token () "Return token starting at point." (cond ((looking-at "\\(if\\|then\\|else\\|let\\|in\\|mdo\\|rec\\|do\\|proc\\|case\\|of\\|where\\|module\\|deriving\\|data\\|type\\|newtype\\|class\\|instance\\)\\([^[:alnum:]'_]\\|$\\)") (match-string-no-properties 1)) ((looking-at "[][(){}[,;]") (match-string-no-properties 0)) ((looking-at "\\(\\\\\\|->\\|<-\\|::\\|=\\||\\)\\([^-:!#$%&*+./<=>?@\\\\^|~]\\|$\\)") (match-string-no-properties 1)) ((looking-at "\\(→\\|←\\|∷\\)\\([^-:!#$%&*+./<=>?@\\\\^|~]\\|$\\)") (let ((tok (match-string-no-properties 1))) (or (cdr (assoc tok haskell-indentation-unicode-tokens)) tok))) ((looking-at"[-:!#$%&*+./<=>?@\\\\^|~`]" ) 'operator) (t 'value))) (defun haskell-indentation-skip-token () "Skip to the next token." (let ((case-fold-search nil)) (if (or (looking-at "'\\([^\\']\\|\\\\.\\)*'") (looking-at "\"\\([^\\\"]\\|\\\\.\\)*\"") (looking-at ; Hierarchical names always start with uppercase "[[:upper:]]\\(\\sw\\|'\\)*\\(\\.\\(\\sw\\|'\\)+\\)*") (looking-at "\\sw\\(\\sw\\|'\\)*") ; Only unqualified vars can start with lowercase (looking-at "[0-9][0-9oOxXeE+-]*") (looking-at "[-:!#$%&*+./<=>?@\\\\^|~]+") (looking-at "[](){}[,;]") (looking-at "`[[:alnum:]']*`")) (goto-char (match-end 0)) ;; otherwise skip until space found (skip-syntax-forward "^-")) (forward-comment (buffer-size)) (while (and (eq haskell-literate 'bird) (bolp) (eq (char-after) ?>)) (forward-char) (forward-comment (buffer-size))))) (provide 'haskell-indentation) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; tab-width: 8 ;; End: ;;; haskell-indentation.el ends here haskell-mode-13.10/haskell-interactive-mode.el000066400000000000000000000656571225210037200213020ustar00rootroot00000000000000;;; haskell-interactive-mode.el --- The interactive Haskell mode ;; Copyright (C) 2011-2012 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;;; Todo: ;;; Code: (require 'haskell-process) (require 'haskell-session) (require 'haskell-show) (with-no-warnings (require 'cl)) (defcustom haskell-interactive-mode-eval-pretty nil "Print eval results that can be parsed as Show instances prettily. Requires sexp-show (on Hackage)." :type 'boolean :group 'haskell-interactive) (defvar haskell-interactive-prompt "λ> " "The prompt to use.") (defun haskell-interactive-prompt-regex () "Generate a regex for searching for any occurence of the prompt at the beginning of the line. This should prevent any interference with prompts that look like haskell expressions." (concat "^" (regexp-quote haskell-interactive-prompt))) (defcustom haskell-interactive-mode-eval-mode nil "Use the given mode's font-locking to render some text." :type '(choice function (const :tag "None" nil)) :group 'haskell-interactive) (defcustom haskell-interactive-mode-hide-multi-line-errors t "Hide collapsible multi-line compile messages by default." :type 'boolean :group 'haskell-interactive) (defcustom haskell-interactive-mode-delete-superseded-errors t "Whether to delete compile messages superseded by recompile/reloads." :type 'boolean :group 'haskell-interactive) (defcustom haskell-interactive-mode-include-file-name t "Include the file name of the module being compiled when printing compilation messages." :type 'boolean :group 'haskell-interactive) (defvar haskell-interactive-mode-map (let ((map (make-sparse-keymap))) (define-key map (kbd "RET") 'haskell-interactive-mode-return) (define-key map (kbd "SPC") 'haskell-interactive-mode-space) (define-key map (kbd "C-j") 'haskell-interactive-mode-newline-indent) (define-key map (kbd "C-a") 'haskell-interactive-mode-beginning) (define-key map (kbd "") 'haskell-interactive-mode-beginning) (define-key map (kbd "C-c C-k") 'haskell-interactive-mode-clear) (define-key map (kbd "C-c C-c") 'haskell-process-interrupt) (define-key map (kbd "C-c C-f") 'next-error-follow-minor-mode) (define-key map (kbd "M-p") 'haskell-interactive-mode-history-previous) (define-key map (kbd "M-n") 'haskell-interactive-mode-history-next) (define-key map (kbd "C-") 'haskell-interactive-mode-history-previous) (define-key map (kbd "C-") 'haskell-interactive-mode-history-next) (define-key map (kbd "TAB") 'haskell-interactive-mode-tab) map) "Interactive Haskell mode map.") ;; buffer-local variables used internally by `haskell-interactive-mode' (defvar haskell-interactive-mode-history) (defvar haskell-interactive-mode-history-index) (defvar haskell-interactive-mode-completion-cache) ;;;###autoload (define-derived-mode haskell-interactive-mode fundamental-mode "Interactive-Haskell" "Interactive mode for Haskell. See Info node `(haskell-mode)haskell-interactive-mode' for more information. Key bindings: \\{haskell-interactive-mode-map}" :group 'haskell-interactive (set (make-local-variable 'haskell-interactive-mode-history) (list)) (set (make-local-variable 'haskell-interactive-mode-history-index) 0) (set (make-local-variable 'haskell-interactive-mode-completion-cache) nil) (setq next-error-function 'haskell-interactive-next-error-function) (setq completion-at-point-functions '(haskell-interactive-mode-completion-at-point-function)) (haskell-interactive-mode-prompt)) (defface haskell-interactive-face-prompt '((t :inherit 'font-lock-function-name-face)) "Face for the prompt." :group 'haskell-interactive) (defface haskell-interactive-face-compile-error '((t :inherit 'compilation-error)) "Face for compile errors." :group 'haskell-interactive) (defface haskell-interactive-face-compile-warning '((t :inherit 'compilation-warning)) "Face for compiler warnings." :group 'haskell-interactive) (defface haskell-interactive-face-result '((t :inherit 'font-lock-string-face)) "Face for the result." :group 'haskell-interactive) (defun haskell-interactive-mode-newline-indent () "Make newline and indent." (interactive) (insert "\n" (make-string (length haskell-interactive-prompt) ? ))) ;;;###autoload (defun haskell-interactive-bring () "Bring up the interactive mode for this session." (interactive) (let* ((session (haskell-session)) (buffer (haskell-session-interactive-buffer session))) (unless (and (find-if (lambda (window) (equal (window-buffer window) buffer)) (window-list)) (= 2 (length (window-list)))) (delete-other-windows) (display-buffer buffer) (other-window 1)))) ;;;###autoload (defun haskell-interactive-switch () "Switch to the interactive mode for this session." (interactive) (let ((buffer (haskell-session-interactive-buffer (haskell-session)))) (unless (eq buffer (window-buffer)) (switch-to-buffer-other-window buffer)))) (defun haskell-interactive-mode-return () "Handle the return key." (interactive) (if (haskell-interactive-at-compile-message) (next-error-internal) (haskell-interactive-handle-line))) (defun haskell-interactive-mode-space (n) "Handle the space key." (interactive "p") (if (haskell-interactive-at-compile-message) (next-error-no-select 0) (self-insert-command n))) (defun haskell-interactive-at-prompt () "If at prompt, returns start position of user-input, otherwise returns nil." (let ((current-point (point))) (save-excursion (goto-char (point-max)) (search-backward-regexp (haskell-interactive-prompt-regex)) (when (> current-point (point)) (+ (length haskell-interactive-prompt) (point)))))) (defun haskell-interactive-handle-line () (when (haskell-interactive-at-prompt) (let ((expr (haskell-interactive-mode-input)) (session (haskell-session)) (process (haskell-process))) (when (not (string= "" (replace-regexp-in-string " " "" expr))) (haskell-interactive-mode-history-add expr) (goto-char (point-max)) (haskell-process-queue-command process (make-haskell-command :state (list session process expr 0) :go (lambda (state) (haskell-process-send-string (cadr state) (caddr state))) :live (lambda (state buffer) (unless (and (string-prefix-p ":q" (caddr state)) (string-prefix-p (caddr state) ":quit")) (let* ((cursor (cadddr state)) (next (replace-regexp-in-string haskell-process-prompt-regex "\n" (substring buffer cursor)))) (when (= 0 cursor) (insert "\n")) (haskell-interactive-mode-eval-result (car state) next) (setf (cdddr state) (list (length buffer))) nil))) :complete (lambda (state response) (cond (haskell-interactive-mode-eval-mode (haskell-interactive-mode-eval-as-mode (car state) response)) ((haskell-interactive-mode-line-is-query (elt state 2)) (let ((haskell-interactive-mode-eval-mode 'haskell-mode)) (haskell-interactive-mode-eval-as-mode (car state) response))) (haskell-interactive-mode-eval-pretty (haskell-interactive-mode-eval-pretty-result (car state) response))) (haskell-interactive-mode-prompt (car state))))))))) (defun haskell-interactive-mode-line-is-query (line) "Is LINE actually a :t/:k/:i?" (and (string-match "^:[itk] " line) t)) (defun haskell-interactive-jump-to-error-line () "Jump to the error line." (let ((orig-line (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (and (string-match "^\\([^:]+\\):\\([0-9]+\\):\\([0-9]+\\)\\(-[0-9]+\\)?:" orig-line) (let* ((file (match-string 1 orig-line)) (line (match-string 2 orig-line)) (col (match-string 3 orig-line)) (session (haskell-session)) (cabal-path (haskell-session-cabal-dir session)) (src-path (haskell-session-current-dir session)) (cabal-relative-file (expand-file-name file cabal-path)) (src-relative-file (expand-file-name file src-path))) (let ((file (cond ((file-exists-p cabal-relative-file) cabal-relative-file) ((file-exists-p src-relative-file) src-relative-file)))) (when file (other-window 1) (find-file file) (haskell-interactive-bring) (goto-char (point-min)) (forward-line (1- (string-to-number line))) (goto-char (+ (point) (string-to-number col) -1)) (haskell-mode-message-line orig-line) t)))))) (defun haskell-interactive-mode-beginning () "Go to the start of the line." (interactive) (if (search-backward-regexp (haskell-interactive-prompt-regex) (line-beginning-position) t 1) (search-forward-regexp (haskell-interactive-prompt-regex) (line-end-position) t 1) (move-beginning-of-line nil))) (defun haskell-interactive-mode-clear () "Clear the screen and put any current input into the history." (interactive) (let ((session (haskell-session))) (with-current-buffer (haskell-session-interactive-buffer session) (let ((inhibit-read-only t)) (set-text-properties (point-min) (point-max) nil)) (delete-region (point-min) (point-max)) (mapc 'delete-overlay (overlays-in (point-min) (point-max))) (haskell-interactive-mode-prompt session) (haskell-session-set session 'next-error-region nil) (haskell-session-set session 'next-error-locus nil)))) (defun haskell-interactive-mode-input-partial () "Get the interactive mode input up to point." (let ((input-start (haskell-interactive-at-prompt))) (unless input-start (error "not at prompt")) (buffer-substring-no-properties input-start (point)))) (defun haskell-interactive-mode-input () "Get the interactive mode input." (substring (buffer-substring-no-properties (save-excursion (goto-char (point-max)) (search-backward-regexp (haskell-interactive-prompt-regex))) (line-end-position)) (length haskell-interactive-prompt))) (defun haskell-interactive-mode-prompt (&optional session) "Show a prompt at the end of the REPL buffer. If SESSION is non-nil, use the REPL buffer associated with SESSION, otherwise operate on the current buffer. " (with-current-buffer (if session (haskell-session-interactive-buffer session) (current-buffer)) (goto-char (point-max)) (insert (propertize haskell-interactive-prompt 'face 'haskell-interactive-face-prompt 'read-only t 'rear-nonsticky t 'prompt t)))) (defun haskell-interactive-mode-eval-result (session text) "Insert the result of an eval as plain text." (with-current-buffer (haskell-session-interactive-buffer session) (goto-char (point-max)) (insert (propertize text 'face 'haskell-interactive-face-result 'rear-nonsticky t 'read-only t 'prompt t 'result t)))) (defun haskell-interactive-mode-eval-as-mode (session text) "Insert TEXT font-locked according to `haskell-interactive-mode-eval-mode'." (with-current-buffer (haskell-session-interactive-buffer session) (let ((start-point (save-excursion (search-backward-regexp (haskell-interactive-prompt-regex)) (forward-line 1) (point))) (inhibit-read-only t)) (delete-region start-point (point)) (goto-char (point-max)) (insert (haskell-fontify-as-mode (concat text "\n") haskell-interactive-mode-eval-mode))))) (defun haskell-interactive-mode-eval-pretty-result (session text) "Insert the result of an eval as a pretty printed Showable, if parseable, or otherwise just as-is." (with-current-buffer (haskell-session-interactive-buffer session) (let ((start-point (save-excursion (search-backward-regexp (haskell-interactive-prompt-regex)) (forward-line 1) (point))) (inhibit-read-only t)) (delete-region start-point (point)) (goto-char (point-max)) (haskell-show-parse-and-insert text) (insert "\n")))) ;;;###autoload (defun haskell-interactive-mode-echo (session message &optional mode) "Echo a read only piece of text before the prompt." (with-current-buffer (haskell-session-interactive-buffer session) (save-excursion (haskell-interactive-mode-goto-end-point) (insert (if mode (haskell-fontify-as-mode (concat message "\n") mode) (propertize (concat message "\n") 'read-only t 'rear-nonsticky t)))))) (defun haskell-interactive-mode-compile-error (session message) "Echo an error." (haskell-interactive-mode-compile-message session message 'haskell-interactive-face-compile-error)) (defun haskell-interactive-mode-compile-warning (session message) "Warning message." (haskell-interactive-mode-compile-message session message 'haskell-interactive-face-compile-warning)) (defun haskell-interactive-mode-compile-message (session message type) "Echo a compiler warning." (with-current-buffer (haskell-session-interactive-buffer session) (setq next-error-last-buffer (current-buffer)) (save-excursion (haskell-interactive-mode-goto-end-point) (let ((lines (string-match "^\\(.*\\)\n\\([[:unibyte:][:nonascii:]]+\\)" message))) (when lines (insert (propertize (concat (match-string 1 message) " …\n") 'face type 'read-only t 'rear-nonsticky t 'expandable t)) (insert (propertize (concat (match-string 2 message) "\n") 'face type 'read-only t 'rear-nonsticky t 'collapsible t 'invisible haskell-interactive-mode-hide-multi-line-errors 'message-length (length (match-string 2 message))))) (unless lines (insert (propertize (concat message "\n") 'face type 'read-only t 'rear-nonsticky t))))))) (defun haskell-interactive-mode-insert (session message) "Echo a read only piece of text before the prompt." (with-current-buffer (haskell-session-interactive-buffer session) (save-excursion (haskell-interactive-mode-goto-end-point) (insert (propertize message 'read-only t 'rear-nonsticky t))))) (defun haskell-interactive-mode-goto-end-point () "Go to the 'end' of the buffer (before the prompt.)" (goto-char (point-max)) (when (search-backward-regexp (haskell-interactive-prompt-regex) (point-min) t 1))) (defun haskell-interactive-mode-history-add (input) "Add item to the history." (setq haskell-interactive-mode-history (cons "" (cons input (remove-if (lambda (i) (or (string= i input) (string= i ""))) haskell-interactive-mode-history)))) (setq haskell-interactive-mode-history-index 0)) (defun haskell-interactive-mode-history-toggle (n) "Toggle the history n items up or down." (unless (null haskell-interactive-mode-history) (setq haskell-interactive-mode-history-index (mod (+ haskell-interactive-mode-history-index n) (length haskell-interactive-mode-history))) (unless (zerop haskell-interactive-mode-history-index) (message "History item: %d" haskell-interactive-mode-history-index)) (haskell-interactive-mode-set-prompt (nth haskell-interactive-mode-history-index haskell-interactive-mode-history)))) (defun haskell-interactive-mode-history-previous (arg) "Cycle backwards through input history." (interactive "*p") (when (haskell-interactive-at-prompt) (if (not (zerop arg)) (haskell-interactive-mode-history-toggle arg) (setq haskell-interactive-mode-history-index 0) (haskell-interactive-mode-history-toggle 1)))) (defun haskell-interactive-mode-history-next (arg) "Cycle forward through input history." (interactive "*p") (when (haskell-interactive-at-prompt) (if (not (zerop arg)) (haskell-interactive-mode-history-toggle (- arg)) (setq haskell-interactive-mode-history-index 0) (haskell-interactive-mode-history-toggle -1)))) (defun haskell-interactive-mode-set-prompt (p) "Set (and overwrite) the current prompt." (with-current-buffer (haskell-session-interactive-buffer (haskell-session)) (goto-char (point-max)) (goto-char (line-beginning-position)) (search-forward-regexp (haskell-interactive-prompt-regex)) (delete-region (point) (line-end-position)) (insert p))) (defun haskell-interactive-buffer () "Get the interactive buffer of the session." (haskell-session-interactive-buffer (haskell-session))) (defun haskell-interactive-show-load-message (session type module-name file-name echo) "Show the '(Compiling|Loading) X' message." (let ((msg (ecase type ('compiling (if haskell-interactive-mode-include-file-name (format "Compiling: %s (%s)" module-name file-name) (format "Compiling: %s" module-name))) ('loading (format "Loading: %s" module-name))))) (haskell-mode-message-line msg) (when haskell-interactive-mode-delete-superseded-errors (haskell-interactive-mode-delete-compile-messages session file-name)) (when echo (haskell-interactive-mode-echo session msg)))) (defun haskell-interactive-mode-completion-at-point-function () "Offer completions for partial expression between prompt and point" (when (haskell-interactive-at-prompt) (let* ((process (haskell-process)) (session (haskell-session)) (inp (haskell-interactive-mode-input-partial))) (if (string= inp (car-safe haskell-interactive-mode-completion-cache)) (cdr haskell-interactive-mode-completion-cache) (let* ((resp2 (haskell-process-get-repl-completions process inp)) (rlen (- (length inp) (length (car resp2)))) (coll (append (if (string-prefix-p inp "import") '("import")) (if (string-prefix-p inp "let") '("let")) (cdr resp2))) (result (list (- (point) rlen) (point) coll))) (setq haskell-interactive-mode-completion-cache (cons inp result)) result))))) (defun haskell-interactive-mode-tab () "Do completion if at prompt or else try collapse/expand." (interactive) (cond ((haskell-interactive-at-prompt) (completion-at-point)) ((get-text-property (point) 'collapsible) (let ((column (current-column))) (search-backward-regexp "^[^ ]") (haskell-interactive-mode-tab-expand) (goto-char (+ column (line-beginning-position))))) (t (haskell-interactive-mode-tab-expand)))) (defun haskell-interactive-mode-tab-expand () "Expand the rest of the message." (cond ((get-text-property (point) 'expandable) (let* ((pos (1+ (line-end-position))) (visibility (get-text-property pos 'invisible)) (length (1+ (get-text-property pos 'message-length)))) (let ((inhibit-read-only t)) (put-text-property pos (+ pos length) 'invisible (not visibility))))))) (defconst haskell-interactive-mode-error-regexp "^\\([^\r\n:]+\\):\\([0-9]+\\):\\([0-9]+\\)\\(-[0-9]+\\)?:") (defun haskell-interactive-at-compile-message () "Am I on a compile message?" (save-excursion (goto-char (line-beginning-position)) (looking-at haskell-interactive-mode-error-regexp))) (defun haskell-interactive-mode-error-backward (&optional count) "Go backward to the previous error." (interactive) (search-backward-regexp haskell-interactive-mode-error-regexp nil t count)) (defun haskell-interactive-mode-error-forward (&optional count) "Go forward to the next error, or return to the REPL." (interactive) (goto-char (line-end-position)) (if (search-forward-regexp haskell-interactive-mode-error-regexp nil t count) (progn (goto-char (line-beginning-position)) t) (progn (goto-char (point-max)) nil))) (defun haskell-interactive-next-error-function (&optional n reset) "See `next-error-function' for more information." (let* ((session (haskell-session)) (next-error-region (haskell-session-get session 'next-error-region)) (next-error-locus (haskell-session-get session 'next-error-locus)) (reset-locus nil)) (when (and next-error-region (or reset (and (/= n 0) (not next-error-locus)))) (goto-char (car next-error-region)) (unless (looking-at haskell-interactive-mode-error-regexp) (haskell-interactive-mode-error-forward)) (setq reset-locus t) (unless (looking-at haskell-interactive-mode-error-regexp) (error "no errors found"))) ;; move point if needed (cond (reset-locus nil) ((> n 0) (unless (haskell-interactive-mode-error-forward n) (error "no more errors"))) ((< n 0) (unless (haskell-interactive-mode-error-backward (- n)) (error "no more errors")))) (let ((orig-line (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (when (string-match haskell-interactive-mode-error-regexp orig-line) (let* ((msgmrk (set-marker (make-marker) (line-beginning-position))) (file (match-string 1 orig-line)) (line (match-string 2 orig-line)) (col1 (match-string 3 orig-line)) (col2 (match-string 4 orig-line)) (cabal-relative-file (expand-file-name file (haskell-session-cabal-dir session))) (src-relative-file (expand-file-name file (haskell-session-current-dir session))) (real-file (cond ((file-exists-p cabal-relative-file) cabal-relative-file) ((file-exists-p src-relative-file) src-relative-file)))) (haskell-session-set session 'next-error-locus msgmrk) (if real-file (let ((m1 (make-marker)) (m2 (make-marker))) (with-current-buffer (find-file-noselect real-file) (save-excursion (goto-char (point-min)) (forward-line (1- (string-to-number line))) (set-marker m1 (+ (string-to-number col1) (point) -1)) (when col2 (set-marker m2 (- (point) (string-to-number col2)))))) ;; ...finally select&hilight error locus (compilation-goto-locus msgmrk m1 (and (marker-position m2) m2))) (error "don't know where to find %S" file))))))) (defun haskell-interactive-mode-delete-compile-messages (session &optional file-name) "Delete compile messages in REPL buffer. If FILE-NAME is non-nil, restrict to removing messages concerning FILE-NAME only." (with-current-buffer (haskell-session-interactive-buffer session) (save-excursion (goto-char (point-min)) (while (when (re-search-forward haskell-interactive-mode-error-regexp nil t) (let ((msg-file-name (match-string-no-properties 1)) (msg-startpos (line-beginning-position))) ;; skip over hanging continuation message lines (while (progn (forward-line) (looking-at "^ "))) (when (or (not file-name) (string= file-name msg-file-name)) (let ((inhibit-read-only t)) (set-text-properties msg-startpos (point) nil)) (delete-region msg-startpos (point)) )) t))))) (defun haskell-interactive-mode-visit-error () "Visit the buffer of the current (or last) error message." (interactive) (with-current-buffer (haskell-session-interactive-buffer (haskell-session)) (if (progn (goto-char (line-beginning-position)) (looking-at haskell-interactive-mode-error-regexp)) (progn (forward-line -1) (haskell-interactive-jump-to-error-line)) (progn (goto-char (point-max)) (haskell-interactive-mode-error-backward) (haskell-interactive-jump-to-error-line))))) ;;;###autoload (defun haskell-interactive-mode-reset-error (session) "Reset the error cursor position." (interactive) (with-current-buffer (haskell-session-interactive-buffer session) (haskell-interactive-mode-goto-end-point) (let ((mrk (point-marker))) (haskell-session-set session 'next-error-locus nil) (haskell-session-set session 'next-error-region (cons mrk (copy-marker mrk t)))) (goto-char (point-max)))) (defun haskell-interactive-kill () "Kill the buffer and (maybe) the session." (interactive) (when (eq major-mode 'haskell-interactive-mode) (when (and (boundp 'haskell-session) haskell-session (y-or-n-p "Kill the whole session?")) (haskell-session-kill t)))) (add-hook 'kill-buffer-hook 'haskell-interactive-kill) (provide 'haskell-interactive-mode) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-interactive-mode.el ends here haskell-mode-13.10/haskell-menu.el000066400000000000000000000146261225210037200167750ustar00rootroot00000000000000;;; haskell-menu.el --- A Haskell sessions menu ;; Copyright (C) 2013 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;;; Todo: ;;; Code: (require 'haskell-compat) (require 'haskell-session) (require 'haskell-process) (with-no-warnings (require 'cl)) (defcustom haskell-menu-buffer-name "*haskell-menu*" "The name of the Haskell session menu buffer" :group 'haskell-interactive :type 'string) ;;;###autoload (defun haskell-menu () "Launch the Haskell sessions menu." (interactive) (or (get-buffer haskell-menu-buffer-name) (with-current-buffer (get-buffer-create haskell-menu-buffer-name) (haskell-menu-mode))) (switch-to-buffer-other-window (get-buffer haskell-menu-buffer-name))) (define-derived-mode haskell-menu-mode special-mode "Haskell Session Menu" "Major mode for managing Haskell sessions. Each line describes one session. Letters do not insert themselves; instead, they are commands." (setq buffer-read-only t) (set (make-local-variable 'revert-buffer-function) 'haskell-menu-revert-function) (setq truncate-lines t) (haskell-menu-revert-function nil t)) (defvar haskell-menu-mode-map (let ((map (make-keymap))) (suppress-keymap map t) (define-key map (kbd "n") 'next-line) (define-key map (kbd "p") 'previous-line) (define-key map (kbd "RET") 'haskell-menu-mode-ret) map) "Key map for haskell-menu-mode.") (defun haskell-menu-revert-function (arg1 arg2) "Function to refresh the display." (let ((buffer-read-only nil) (orig-line (line-number-at-pos)) (orig-col (current-column))) (or (eq buffer-undo-list t) (setq buffer-undo-list nil)) (erase-buffer) (haskell-menu-insert-menu) (goto-char (point-min)) (forward-line (1- orig-line)) (forward-char orig-col))) (defun haskell-menu-insert-menu () "Insert the Haskell sessions menu to the current buffer." (if (null haskell-sessions) (insert "No Haskell sessions.") (haskell-menu-tabulate (list "Name" "PID" "Time" "RSS" "Cabal directory" "Working directory" "Command") (mapcar (lambda (session) (let ((process (haskell-process-process (haskell-session-process session)))) (cond (process (let ((id (process-id process))) (list (propertize (haskell-session-name session) 'face 'buffer-menu-buffer) (if (process-live-p process) (number-to-string id) "-") (if (process-live-p process) (format-time-string "%H:%M:%S" (encode-time (caddr (assoc 'etime (process-attributes id))) 0 0 0 0 0)) "-") (if (process-live-p process) (concat (number-to-string (/ (cdr (assoc 'rss (process-attributes id))) 1024)) "MB") "-") (haskell-session-cabal-dir session) (haskell-session-current-dir session) (mapconcat 'identity (process-command process) " ")))) (t (list (propertize (haskell-session-name session) 'face 'buffer-menu-buffer) "—" "—" "—" (haskell-session-cabal-dir session) (haskell-session-current-dir session)))))) haskell-sessions)))) (defun haskell-menu-tabulate (headings rows) "Prints a list of lists as a formatted table to the current buffer." (let* ((columns (length headings)) (widths (make-list columns 0))) ;; Calculate column widths. This is kind of hideous. (dolist (row rows) (setq widths (let ((list (list))) (dotimes (i columns) (setq list (cons (max (nth i widths) (1+ (length (nth i row))) (1+ (length (nth i headings)))) list))) (reverse list)))) ;; Print headings. (let ((heading (propertize " " 'display '(space :align-to 0)))) (dotimes (i columns) (setq heading (concat heading (format (concat "%-" (number-to-string (nth i widths)) "s") (nth i headings))))) (setq header-line-format heading)) ;; Print tabulated rows. (dolist (row rows) (dotimes (i columns) (insert (format (concat "%-" (number-to-string (nth i widths)) "s") (nth i row)))) (insert "\n")))) (defun haskell-menu-mode-ret () "Handle RET key." (interactive) (let* ((name (save-excursion (goto-char (line-beginning-position)) (buffer-substring-no-properties (point) (progn (search-forward " ") (forward-char -1) (point))))) (session (car (remove-if-not (lambda (session) (string= (haskell-session-name session) name)) haskell-sessions)))) (switch-to-buffer (haskell-session-interactive-buffer session)))) (provide 'haskell-menu) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-menu.el ends here haskell-mode-13.10/haskell-mode-pkg.el.in000066400000000000000000000001051225210037200201240ustar00rootroot00000000000000(define-package "haskell-mode" "@VERSION@" "A Haskell editing mode") haskell-mode-13.10/haskell-mode.el000066400000000000000000001037541225210037200167560ustar00rootroot00000000000000;;; haskell-mode.el --- A Haskell editing mode -*- coding: utf-8 -*- ;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc ;; Copyright (C) 1992, 1997-1998 Simon Marlow, Graeme E Moss, and Tommy Thorn ;; Author: 1992 Simon Marlow ;; 1997-1998 Graeme E Moss and ;; Tommy Thorn , ;; 2001-2002 Reuben Thomas (>=v1.4) ;; 2003 Dave Love ;; Keywords: faces files Haskell ;; URL: https://github.com/haskell/haskell-mode ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; A major mode for editing Haskell (the functional programming ;; language, see URL `http://www.haskell.org') in Emacs. ;; ;; Some of its major features include: ;; ;; - syntax highlighting (font lock), ;; ;; - automatic indentation, ;; ;; - on-the-fly documentation, ;; ;; - interaction with inferior GHCi/Hugs instance, ;; ;; - scans declarations and places them in a menu. ;; ;; See URL `https://github.com/haskell/haskell-mode' and/or ;; Info node `(haskell-mode)Introduction' for more information. ;; ;; Use `M-x haskell-mode-view-news` (after Haskell Mode is installed) ;; to show information on recent changes in Haskell Mode. ;;; Change Log: ;; This mode is based on an editing mode by Simon Marlow 11/1/92 ;; and heavily modified by Graeme E Moss and Tommy Thorn 7/11/98. ;; ;; Version 1.5: ;; Added autoload for haskell-indentation ;; ;; Version 1.43: ;; Various tweaks to doc strings and customization support from ;; Ville Skyttä . ;; ;; Version 1.42: ;; Added autoload for GHCi inferior mode (thanks to Scott ;; Williams for the bug report and fix). ;; ;; Version 1.41: ;; Improved packaging, and made a couple more variables ;; interactively settable. ;; ;; Version 1.4: ;; Added GHCi mode from Chris Webb, and tidied up a little. ;; ;; Version 1.3: ;; The literate or non-literate style of a buffer is now indicated ;; by just the variable haskell-literate: nil, `bird', or `tex'. ;; For literate buffers with ambiguous style, the value of ;; haskell-literate-default is used. ;; ;; Version 1.2: ;; Separated off font locking, declaration scanning and simple ;; indentation, and made them separate modules. Modules can be ;; added easily now. Support for modules haskell-doc, ;; haskell-indent, and haskell-hugs. Literate and non-literate ;; modes integrated into one mode, and literate buffer indicated by ;; value of haskell-literate(-bird-style). ;; ;; Version 1.1: ;; Added support for declaration scanning under XEmacs via ;; func-menu. Moved operators to level two fontification. ;; ;; Version 1.0: ;; Added a nice indention support from Heribert Schuetz ;; : ;; ;; I have just hacked an Emacs Lisp function which you might prefer ;; to `indent-relative' in haskell-mode.el. See below. It is not ;; really Haskell-specific because it does not take into account ;; keywords like `do', `of', and `let' (where the layout rule ;; applies), but I already find it useful. ;; ;; Cleaned up the imenu support. Added support for literate scripts. ;; ;; Version 0.103 [HWL]: ;; From Hans Wolfgang Loidl : ;; ;; I (HWL) added imenu support by copying the appropriate functions ;; from hugs-mode. A menu-bar item "Declarations" is now added in ;; haskell mode. The new code, however, needs some clean-up. ;; ;; Version 0.102: ;; ;; Moved C-c C-c key binding to comment-region. Leave M-g M-g to do ;; the work. comment-start-skip is changed to comply with comment-start. ;; ;; Version 0.101: ;; ;; Altered indent-line-function to indent-relative. ;; ;; Version 0.100: ;; ;; First official release. ;;; Code: (require 'dabbrev) (require 'compile) (require 'flymake) (require 'outline) (require 'haskell-align-imports) (require 'haskell-sort-imports) (require 'haskell-string) (with-no-warnings (require 'cl)) ;; FIXME: code-smell: too many forward decls for haskell-session are required here (defvar haskell-session) (declare-function haskell-process-do-try-info "haskell-process" (sym)) (declare-function haskell-process-generate-tags "haskell-process" (&optional and-then-find-this-tag)) (declare-function haskell-session "haskell-session" ()) (declare-function haskell-session-all-modules "haskell-session" (&optional DONTCREATE)) (declare-function haskell-session-cabal-dir "haskell-session" (session)) (declare-function haskell-session-maybe "haskell-session" ()) (declare-function haskell-session-tags-filename "haskell-session" (session)) (declare-function haskell-session-current-dir "haskell-session" (session)) ;; All functions/variables start with `(literate-)haskell-'. ;; Version of mode. (defconst haskell-version "@VERSION@" "The release version of `haskell-mode'.") (defconst haskell-git-version "@GIT_VERSION@" "The Git version of `haskell-mode'.") (defvar haskell-mode-pkg-base-dir (file-name-directory load-file-name) "Package base directory of installed `haskell-mode'. Used for locating additional package data files.") ;;;###autoload (defun haskell-version (&optional here) "Show the `haskell-mode` version in the echo area. With prefix argument HERE, insert it at point. When FULL is non-nil, use a verbose version string. When MESSAGE is non-nil, display a message with the version." (interactive "P") (let* ((haskell-mode-dir (ignore-errors (file-name-directory (or (locate-library "haskell-mode") "")))) (_version (format "haskell-mode version %s (%s @ %s)" haskell-version haskell-git-version haskell-mode-dir))) (if here (insert _version) (message "%s" _version)))) ;;;###autoload (defun haskell-mode-view-news () "Display information on recent changes to haskell-mode." (interactive) (with-current-buffer (find-file-read-only (expand-file-name "NEWS" haskell-mode-pkg-base-dir)) (goto-char (point-min)) (hide-sublevels 1) (outline-next-visible-heading 1) (show-subtree))) (defgroup haskell nil "Major mode for editing Haskell programs." :link '(custom-manual "(haskell-mode)") :group 'languages :prefix "haskell-") ;;;###autoload (defun haskell-customize () "Browse the haskell customize sub-tree. This calls 'customize-browse' with haskell as argument and makes sure all haskell customize definitions have been loaded." (interactive) ;; make sure all modules with (defcustom ...)s are loaded (mapc 'require '(haskell-checkers haskell-compile haskell-doc haskell-font-lock haskell-indentation haskell-indent haskell-interactive-mode haskell-menu haskell-process haskell-yas inf-haskell)) (customize-browse 'haskell)) ;; Are we looking at a literate script? (defvar haskell-literate nil "*If not nil, the current buffer contains a literate Haskell script. Possible values are: `bird' and `tex', for Bird-style and LaTeX-style literate scripts respectively. Set by `haskell-mode' and `literate-haskell-mode'. For an ambiguous literate buffer -- i.e. does not contain either \"\\begin{code}\" or \"\\end{code}\" on a line on its own, nor does it contain \">\" at the start of a line -- the value of `haskell-literate-default' is used.") (make-variable-buffer-local 'haskell-literate) (put 'haskell-literate 'safe-local-variable 'symbolp) ;; Default literate style for ambiguous literate buffers. (defcustom haskell-literate-default 'bird "Default value for `haskell-literate'. Used if the style of a literate buffer is ambiguous. This variable should be set to the preferred literate style." :group 'haskell :type '(choice (const bird) (const tex) (const nil))) ;;;###autoload (defvar haskell-mode-map (let ((map (make-sparse-keymap))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; For inferior haskell mode, use the below bindings ;; (define-key map [?\M-C-x] 'inferior-haskell-send-defun) ;; (define-key map [?\C-x ?\C-e] 'inferior-haskell-send-last-sexp) ;; (define-key map [?\C-c ?\C-r] 'inferior-haskell-send-region) (define-key map [?\C-x ?\C-d] 'inferior-haskell-send-decl) (define-key map [?\C-c ?\C-z] 'switch-to-haskell) (define-key map [?\C-c ?\C-l] 'inferior-haskell-load-file) ;; I think it makes sense to bind inferior-haskell-load-and-run to C-c ;; C-r, but since it used to be bound to `reload' until June 2007, I'm ;; going to leave it out for now. ;; (define-key map [?\C-c ?\C-r] 'inferior-haskell-load-and-run) (define-key map [?\C-c ?\C-b] 'switch-to-haskell) ;; (define-key map [?\C-c ?\C-s] 'inferior-haskell-start-process) ;; That's what M-; is for. ;; (define-key map "\C-c\C-c" 'comment-region) (define-key map (kbd "C-c C-t") 'inferior-haskell-type) (define-key map (kbd "C-c C-i") 'inferior-haskell-info) (define-key map (kbd "C-c M-.") 'inferior-haskell-find-definition) (define-key map (kbd "C-c C-d") 'inferior-haskell-find-haddock) (define-key map [?\C-c ?\C-v] 'haskell-check) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Editing-specific commands (define-key map (kbd "C-c C-.") 'haskell-mode-format-imports) (define-key map [remap delete-indentation] 'haskell-delete-indentation) map) "Keymap used in Haskell mode.") (easy-menu-define haskell-mode-menu haskell-mode-map "Menu for the Haskell major mode." ;; Suggestions from Pupeno : ;; - choose the underlying interpreter ;; - look up docs `("Haskell" ["Indent line" indent-according-to-mode] ["Indent region" indent-region mark-active] ["(Un)Comment region" comment-region mark-active] "---" ["Start interpreter" switch-to-haskell] ["Load file" inferior-haskell-load-file] "---" ["Load tidy core" ghc-core-create-core] "---" ,(if (default-boundp 'eldoc-documentation-function) ["Doc mode" eldoc-mode :style toggle :selected (bound-and-true-p eldoc-mode)] ["Doc mode" haskell-doc-mode :style toggle :selected (and (boundp 'haskell-doc-mode) haskell-doc-mode)]) ["Customize" (customize-group 'haskell)] )) ;; Syntax table. (defvar haskell-mode-syntax-table (let ((table (make-syntax-table))) (modify-syntax-entry ?\ " " table) (modify-syntax-entry ?\t " " table) (modify-syntax-entry ?\" "\"" table) (modify-syntax-entry ?\' "\'" table) (modify-syntax-entry ?_ "w" table) (modify-syntax-entry ?\( "()" table) (modify-syntax-entry ?\) ")(" table) (modify-syntax-entry ?\[ "(]" table) (modify-syntax-entry ?\] ")[" table) (cond ((featurep 'xemacs) ;; I don't know whether this is equivalent to the below ;; (modulo nesting). -- fx (modify-syntax-entry ?{ "(}5" table) (modify-syntax-entry ?} "){8" table) (modify-syntax-entry ?- "_ 1267" table)) (t ;; In Emacs 21, the `n' indicates that they nest. ;; The `b' annotation is actually ignored because it's only ;; meaningful on the second char of a comment-starter, so ;; on Emacs 20 and before we get wrong results. --Stef (modify-syntax-entry ?\{ "(}1nb" table) (modify-syntax-entry ?\} "){4nb" table) (modify-syntax-entry ?- "_ 123" table))) (modify-syntax-entry ?\n ">" table) (let (i lim) (map-char-table (lambda (k v) (when (equal v '(1)) ;; The current Emacs 22 codebase can pass either a char ;; or a char range. (if (consp k) (setq i (car k) lim (cdr k)) (setq i k lim k)) (while (<= i lim) (when (> i 127) (modify-syntax-entry i "_" table)) (setq i (1+ i))))) (standard-syntax-table))) (modify-syntax-entry ?\` "$`" table) (modify-syntax-entry ?\\ "\\" table) (mapc (lambda (x) (modify-syntax-entry x "_" table)) ;; Some of these are actually OK by default. "!#$%&*+./:<=>?@^|~") (unless (featurep 'mule) ;; Non-ASCII syntax should be OK, at least in Emacs. (mapc (lambda (x) (modify-syntax-entry x "_" table)) (concat "¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿" "×÷")) (mapc (lambda (x) (modify-syntax-entry x "w" table)) (concat "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ" "ØÙÚÛÜÝÞß" "àáâãäåæçèéêëìíîïðñòóôõö" "øùúûüýþÿ"))) table) "Syntax table used in Haskell mode.") (defun haskell-ident-at-point () "Return the identifier under point, or nil if none found. May return a qualified name." (let ((reg (haskell-ident-pos-at-point))) (when reg (buffer-substring-no-properties (car reg) (cdr reg))))) (defun haskell-ident-pos-at-point () "Return the span of the identifier under point, or nil if none found. May return a qualified name." (save-excursion ;; Skip whitespace if we're on it. That way, if we're at "map ", we'll ;; see the word "map". (if (and (not (eobp)) (eq ? (char-syntax (char-after)))) (skip-chars-backward " \t")) (let ((case-fold-search nil)) (multiple-value-bind (start end) (if (looking-at "\\s_") (list (progn (skip-syntax-backward "_") (point)) (progn (skip-syntax-forward "_") (point))) (list (progn (skip-syntax-backward "w'") (skip-syntax-forward "'") (point)) (progn (skip-syntax-forward "w'") (point)))) ;; If we're looking at a module ID that qualifies further IDs, add ;; those IDs. (goto-char start) (while (and (looking-at "[[:upper:]]") (eq (char-after end) ?.) ;; It's a module ID that qualifies further IDs. (goto-char (1+ end)) (save-excursion (when (not (zerop (skip-syntax-forward (if (looking-at "\\s_") "_" "w'")))) (setq end (point)))))) ;; If we're looking at an ID that's itself qualified by previous ;; module IDs, add those too. (goto-char start) (if (eq (char-after) ?.) (forward-char 1)) ;Special case for "." (while (and (eq (char-before) ?.) (progn (forward-char -1) (not (zerop (skip-syntax-backward "w'")))) (skip-syntax-forward "'") (looking-at "[[:upper:]]")) (setq start (point))) ;; This is it. (cons start end))))) (defun haskell-delete-indentation (&optional arg) "Like `delete-indentation' but ignoring Bird-style \">\"." (interactive "*P") (let ((fill-prefix (or fill-prefix (if (eq haskell-literate 'bird) ">")))) (delete-indentation arg))) ;; Various mode variables. (defcustom haskell-mode-hook nil "Hook run after entering `haskell-mode'. Some of the supported modules that can be activated via this hook: `haskell-decl-scan', Graeme E Moss Scans top-level declarations, and places them in a menu. `haskell-doc', Hans-Wolfgang Loidl Echoes types of functions or syntax of keywords when the cursor is idle. `haskell-indentation', Kristof Bastiaensen Intelligent semi-automatic indentation Mk2 `haskell-indent', Guy Lapalme Intelligent semi-automatic indentation. `haskell-simple-indent', Graeme E Moss and Heribert Schuetz Simple indentation. Module X is activated using the command `turn-on-X'. For example, `haskell-doc' is activated using `turn-on-haskell-doc'. For more information on a specific module, see the help for its `X-mode' function. Some modules can be deactivated using `turn-off-X'. See Info node `(haskell-mode)haskell-mode-hook' for more details. Warning: do not enable more than one of the three indentation modes. See Info node `(haskell-mode)indentation' for more details." :type 'hook :group 'haskell :link '(info-link "(haskell-mode)haskell-mode-hook") :link '(function-link haskell-mode) :options `(capitalized-words-mode imenu-add-menubar-index turn-on-eldoc-mode turn-on-haskell-decl-scan turn-on-haskell-doc turn-on-haskell-indent turn-on-haskell-indentation turn-on-haskell-simple-indent turn-on-haskell-unicode-input-method)) (defvar eldoc-print-current-symbol-info-function) ;; For compatibility with Emacs < 24, derive conditionally (defalias 'haskell-parent-mode (if (fboundp 'prog-mode) 'prog-mode 'fundamental-mode)) ;; The main mode functions ;;;###autoload (define-derived-mode haskell-mode haskell-parent-mode "Haskell" "Major mode for editing Haskell programs. See also Info node `(haskell-mode)Getting Started' for more information about this mode. \\ Literate scripts are supported via `literate-haskell-mode'. The variable `haskell-literate' indicates the style of the script in the current buffer. See the documentation on this variable for more details. Use `haskell-version' to find out what version of Haskell mode you are currently using. Additional Haskell mode modules can be hooked in via `haskell-mode-hook'; see documentation for that variable for more details." :group 'haskell (set (make-local-variable 'paragraph-start) (concat "^$\\|" page-delimiter)) (set (make-local-variable 'paragraph-separate) paragraph-start) (set (make-local-variable 'fill-paragraph-function) 'haskell-fill-paragraph) ;; (set (make-local-variable 'adaptive-fill-function) 'haskell-adaptive-fill) (set (make-local-variable 'adaptive-fill-mode) nil) (set (make-local-variable 'comment-start) "-- ") (set (make-local-variable 'comment-padding) 0) (set (make-local-variable 'comment-start-skip) "[-{]-[ \t]*") (set (make-local-variable 'comment-end) "") (set (make-local-variable 'comment-end-skip) "[ \t]*\\(-}\\|\\s>\\)") (set (make-local-variable 'parse-sexp-ignore-comments) nil) (set (make-local-variable 'indent-line-function) 'haskell-mode-suggest-indent-choice) ;; Set things up for eldoc-mode. (set (make-local-variable 'eldoc-documentation-function) 'haskell-doc-current-info) ;; Set things up for imenu. (set (make-local-variable 'imenu-create-index-function) 'haskell-ds-create-imenu-index) ;; Set things up for font-lock. (set (make-local-variable 'font-lock-defaults) '(haskell-font-lock-choose-keywords nil nil ((?\' . "w") (?_ . "w")) nil (font-lock-syntactic-keywords . haskell-font-lock-choose-syntactic-keywords) (font-lock-syntactic-face-function . haskell-syntactic-face-function) ;; Get help from font-lock-syntactic-keywords. (parse-sexp-lookup-properties . t))) ;; Haskell's layout rules mean that TABs have to be handled with extra care. ;; The safer option is to avoid TABs. The second best is to make sure ;; TABs stops are 8 chars apart, as mandated by the Haskell Report. --Stef (set (make-local-variable 'indent-tabs-mode) nil) (set (make-local-variable 'tab-width) 8) ;; dynamic abbrev support: recognize Haskell identifiers ;; Haskell is case-sensitive language (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-distinction) nil) (set (make-local-variable 'dabbrev-case-replace) nil) (set (make-local-variable 'dabbrev-abbrev-char-regexp) "\\sw\\|[.]") (setq haskell-literate nil) (add-hook 'before-save-hook 'haskell-mode-before-save-handler nil t) (add-hook 'after-save-hook 'haskell-mode-after-save-handler nil t) ) (defun haskell-fill-paragraph (justify) (save-excursion ;; Fill paragraph should only work in comments. ;; The -- comments are handled properly by default ;; The {- -} comments need some extra love. (let* ((syntax-values (syntax-ppss)) (comment-num (nth 4 syntax-values))) (cond ((eq t comment-num) ;; standard fill works wonders inside a non-nested comment (fill-comment-paragraph justify)) ((integerp comment-num) ;; we are in a nested comment. lets narrow to comment content ;; and use plain paragraph fill for that (let* ((comment-start-point (nth 8 syntax-values)) (comment-end-point (save-excursion (re-search-forward "-}" (point-max) t comment-num) (point))) (fill-paragraph-handle-comment nil)) (save-restriction (narrow-to-region (+ 2 comment-start-point) (- comment-end-point 2)) (fill-paragraph justify)))) ((eolp) ;; do nothing outside of a comment t) (t ;; go to end of line and try again (end-of-line) (haskell-fill-paragraph justify)))))) ;; (defun haskell-adaptive-fill () ;; ;; We want to use "-- " as the prefix of "-- |", etc. ;; (let* ((line-end (save-excursion (end-of-line) (point))) ;; (line-start (point))) ;; (save-excursion ;; (unless (in-comment) ;; ;; Try to find the start of a comment. We only fill comments. ;; (search-forward-regexp comment-start-skip line-end t)) ;; (when (in-comment) ;; (let ();(prefix-start (point))) ;; (skip-syntax-forward "^w") ;; (make-string (- (point) line-start) ?\s)))))) ;;;###autoload (define-derived-mode literate-haskell-mode haskell-mode "LitHaskell" "As `haskell-mode' but for literate scripts." (setq haskell-literate (save-excursion (goto-char (point-min)) (cond ((re-search-forward "^\\\\\\(begin\\|end\\){code}$" nil t) 'tex) ((re-search-forward "^>" nil t) 'bird) (t haskell-literate-default)))) (if (eq haskell-literate 'bird) ;; fill-comment-paragraph isn't much use there, and even gets confused ;; by the syntax-table text-properties we add to mark the first char ;; of each line as a comment-starter. (set (make-local-variable 'fill-paragraph-handle-comment) nil)) (set (make-local-variable 'mode-line-process) '("/" (:eval (symbol-name haskell-literate))))) ;;;###autoload(add-to-list 'auto-mode-alist '("\\.\\(?:[gh]s\\|hi\\)\\'" . haskell-mode)) ;;;###autoload(add-to-list 'auto-mode-alist '("\\.l[gh]s\\'" . literate-haskell-mode)) ;;;###autoload(add-to-list 'interpreter-mode-alist '("runghc" . haskell-mode)) ;;;###autoload(add-to-list 'interpreter-mode-alist '("runhaskell" . haskell-mode)) (defcustom haskell-hoogle-command (if (executable-find "hoogle") "hoogle") "Name of the command to use to query Hoogle. If nil, use the Hoogle web-site." :group 'haskell :type '(choice (const :tag "Use Web-site" nil) string)) ;;;###autoload (defun haskell-hoogle (query) "Do a Hoogle search for QUERY." (interactive (let ((def (haskell-ident-at-point))) (if (and def (symbolp def)) (setq def (symbol-name def))) (list (read-string (if def (format "Hoogle query (default %s): " def) "Hoogle query: ") nil nil def)))) (if (null haskell-hoogle-command) (browse-url (format "http://haskell.org/hoogle/?q=%s" query)) (lexical-let ((temp-buffer (help-buffer))) (with-output-to-temp-buffer temp-buffer (with-current-buffer standard-output (let ((hoogle-process (start-process "hoogle" (current-buffer) haskell-hoogle-command query)) (scroll-to-top (lambda (process event) (set-window-start (get-buffer-window temp-buffer t) 1)))) (set-process-sentinel hoogle-process scroll-to-top))))))) ;;;###autoload (defalias 'hoogle 'haskell-hoogle) ;;;###autoload (defun haskell-hayoo (query) "Do a Hayoo search for QUERY." (interactive (let ((def (haskell-ident-at-point))) (if (and def (symbolp def)) (setq def (symbol-name def))) (list (read-string (if def (format "Hayoo query (default %s): " def) "Hayoo query: ") nil nil def)))) (browse-url (format "http://holumbus.fh-wedel.de/hayoo/hayoo.html?query=%s" query))) ;;;###autoload (defalias 'hayoo 'haskell-hayoo) (defcustom haskell-check-command "hlint" "*Command used to check a Haskell file." :group 'haskell :type '(choice (const "hlint") (const "ghc -fno-code") (string :tag "Other command"))) (defcustom haskell-stylish-on-save nil "Whether to run stylish-haskell on the buffer before saving." :group 'haskell :type 'boolean) (defcustom haskell-tags-on-save nil "Generate tags via hasktags after saving." :group 'haskell :type 'boolean) (defvar haskell-saved-check-command nil "Internal use.") (defcustom haskell-indent-spaces 2 "Number of spaces to indent inwards.") ;; Like Python. Should be abstracted, sigh. (defun haskell-check (command) "Check a Haskell file (default current buffer's file). Runs COMMAND, a shell command, as if by `compile'. See `haskell-check-command' for the default." (interactive (list (read-string "Checker command: " (or haskell-saved-check-command (concat haskell-check-command " " (let ((name (buffer-file-name))) (if name (file-name-nondirectory name)))))))) (setq haskell-saved-check-command command) (save-some-buffers (not compilation-ask-about-save) nil) (compilation-start command)) (defun haskell-flymake-init () "Flymake init function for Haskell. To be added to `flymake-init-create-temp-buffer-copy'." (let ((checker-elts (and haskell-saved-check-command (split-string haskell-saved-check-command)))) (list (car checker-elts) (append (cdr checker-elts) (list (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)))))) (add-to-list 'flymake-allowed-file-name-masks '("\\.l?hs\\'" haskell-flymake-init)) (defun haskell-mode-suggest-indent-choice () "Ran when the user tries to indent in the buffer but no indentation mode has been selected. Brings up the documentation for haskell-mode-hook." (describe-variable 'haskell-mode-hook)) (defun haskell-mode-format-imports () "Format the imports by aligning and sorting them." (interactive) (let ((col (current-column))) (haskell-sort-imports) (haskell-align-imports) (goto-char (+ (line-beginning-position) col)))) (defun haskell-mode-message-line (str) "Message only one line, multiple lines just disturbs the programmer." (let ((lines (split-string str "\n" t))) (when (and (car lines) (stringp (car lines))) (message "%s" (concat (car lines) (if (and (cdr lines) (stringp (cadr lines))) (format " [ %s .. ]" (haskell-string-take (haskell-trim (cadr lines)) 10)) "")))))) (defun haskell-mode-contextual-space () "Contextually do clever stuff when hitting space." (interactive) (if (not (haskell-session-maybe)) (self-insert-command 1) (cond ((save-excursion (forward-word -1) (looking-at "^import$")) (insert " ") (let ((module (ido-completing-read "Module: " (haskell-session-all-modules)))) (insert module) (haskell-mode-format-imports))) ((not (string= "" (save-excursion (forward-char -1) (haskell-ident-at-point)))) (let ((ident (save-excursion (forward-char -1) (haskell-ident-at-point)))) (insert " ") (haskell-process-do-try-info ident))) (t (insert " "))))) (defun haskell-mode-before-save-handler () "Function that will be called before buffer's saving." ) (defun haskell-mode-after-save-handler () "Function that will be called after buffer's saving." (when haskell-tags-on-save (ignore-errors (when (and (boundp 'haskell-session) haskell-session) (haskell-process-generate-tags)))) (when haskell-stylish-on-save (ignore-errors (haskell-mode-stylish-buffer))) (let ((before-save-hook '()) (after-save-hook '())) (basic-save-buffer)) ) (defun haskell-mode-buffer-apply-command (cmd) "Execute shell command CMD with current buffer as input and replace the whole buffer with the output. If CMD fails the buffer remains unchanged." (set-buffer-modified-p t) (let* ((chomp (lambda (str) (while (string-match "\\`\n+\\|^\\s-+\\|\\s-+$\\|\n+\\'" str) (setq str (replace-match "" t t str))) str)) (errout (lambda (fmt &rest args) (let* ((warning-fill-prefix " ")) (display-warning cmd (apply 'format fmt args) :warning)))) (filename (buffer-file-name (current-buffer))) (cmd-prefix (replace-regexp-in-string " .*" "" cmd)) (tmp-file (make-temp-file cmd-prefix)) (err-file (make-temp-file cmd-prefix)) (default-directory (if (and (boundp 'haskell-session) haskell-session) (haskell-session-cabal-dir haskell-session) default-directory)) (errcode (with-temp-file tmp-file (call-process cmd filename (list (current-buffer) err-file) nil))) (stderr-output (with-temp-buffer (insert-file-contents err-file) (funcall chomp (buffer-substring-no-properties (point-min) (point-max))))) (stdout-output (with-temp-buffer (insert-file-contents tmp-file) (buffer-substring-no-properties (point-min) (point-max))))) (if (string= "" stderr-output) (if (string= "" stdout-output) (funcall errout "Error: %s produced no output, leaving buffer alone" cmd) (save-restriction (widen) ;; command successful, insert file with replacement to preserve ;; markers. (insert-file-contents tmp-file nil nil nil t))) ;; non-null stderr, command must have failed (funcall errout "%s failed: %s" cmd stderr-output) ) (delete-file tmp-file) (delete-file err-file) )) (defun haskell-mode-stylish-buffer () "Apply stylish-haskell to the current buffer." (interactive) (let ((column (current-column)) (line (line-number-at-pos))) (haskell-mode-buffer-apply-command "stylish-haskell") (goto-char (point-min)) (forward-line (1- line)) (goto-char (+ column (point))))) (defun haskell-mode-tag-find (&optional next-p) "The tag find function, specific for the particular session." (interactive "P") (let ((tags-file-name (haskell-session-tags-filename (haskell-session))) (tags-revert-without-query t) (ident (haskell-ident-at-point))) (when (not (string= "" (haskell-trim ident))) (cond ((file-exists-p tags-file-name) (find-tag ident next-p)) (t (haskell-process-generate-tags ident)))))) ;; From Bryan O'Sullivan's blog: ;; http://www.serpentine.com/blog/2007/10/09/using-emacs-to-insert-scc-annotations-in-haskell-code/ (defun haskell-mode-insert-scc-at-point () "Insert an SCC annotation at point." (interactive) (if (or (looking-at "\\b\\|[ \t]\\|$") (and (not (bolp)) (save-excursion (forward-char -1) (looking-at "\\b\\|[ \t]")))) (let ((space-at-point (looking-at "[ \t]"))) (unless (and (not (bolp)) (save-excursion (forward-char -1) (looking-at "[ \t]"))) (insert " ")) (insert "{-# SCC \"\" #-}") (unless space-at-point (insert " ")) (forward-char (if space-at-point -5 -6))) (error "Not over an area of whitespace"))) ;; Also Bryan O'Sullivan's. (defun haskell-mode-kill-scc-at-point () "Kill the SCC annotation at point." (interactive) (save-excursion (let ((old-point (point)) (scc "\\({-#[ \t]*SCC \"[^\"]*\"[ \t]*#-}\\)[ \t]*")) (while (not (or (looking-at scc) (bolp))) (forward-char -1)) (if (and (looking-at scc) (<= (match-beginning 1) old-point) (> (match-end 1) old-point)) (kill-region (match-beginning 0) (match-end 0)) (error "No SCC at point"))))) (defun haskell-rgrep (&optional prompt) "Grep the effective project for the symbol at point. Very useful for codebase navigation. Prompts for an arbitrary regexp given a prefix arg." (interactive "P") (let ((sym (if prompt (read-from-minibuffer "Look for: ") (haskell-ident-at-point)))) (rgrep sym "*.hs" ;; TODO: common Haskell extensions. (haskell-session-current-dir (haskell-session))))) (defun haskell-fontify-as-mode (text mode) "Fontify TEXT as MODE, returning the fontified text." (with-temp-buffer (funcall mode) (insert text) (font-lock-fontify-buffer) (buffer-substring (point-min) (point-max)))) ;; Provide ourselves: (provide 'haskell-mode) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-mode.el ends here haskell-mode-13.10/haskell-mode.texi000066400000000000000000000524141225210037200173230ustar00rootroot00000000000000\input texinfo @c -*-texinfo-*- @c %**start of header @setfilename haskell-mode.info @documentencoding UTF-8 @settitle Haskell Mode @@VERSION@@ @c %**end of header @dircategory Emacs @direntry * Haskell Mode: (haskell-mode). Haskell Development Environment for Emacs(en) @end direntry @copying This manual is for Haskell mode, version @@GIT_VERSION@@ Copyright @copyright{} 2013 Haskell Mode contributors. @quotation Permission is granted to copy, distribute and/or modify this document under the terms of the @uref{http://www.gnu.org/licenses/fdl.html,GNU Free Documentation License}, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts and no Back-Cover Texts. @end quotation @end copying @iftex @titlepage @title Haskell Mode @subtitle Haskell Development Environment for Emacs @page @vskip 0pt plus 1filll @insertcopying @end titlepage @contents @end iftex @ifhtml @titlepage @title Haskell Mode @subtitle Haskell Development Environment for Emacs @end titlepage @insertcopying @end ifhtml @ifnottex @node Top @top Haskell Mode Haskell Mode is an Haskell development Environment for GNU Emacs version 23 or later. It provides syntax-based indentation, font locking, editing cabal files, and supports running an inferior Haskell interpreter (e.g. GHCi). @end ifnottex @menu * Introduction:: * Getting Help and Reporting Bugs:: * Getting Started:: * Editing Haskell Code:: * Unicode:: * Indentation:: * Compilation:: * haskell-decl-scan-mode:: * inferior-haskell-mode:: * haskell-interactive-mode:: * haskell-cabal-mode:: * Concept index:: * Function index:: * Variable index:: @end menu @node Introduction @chapter Introduction @dfn{Haskell Mode} is a major mode providing a convenient environment for editing @uref{http://www.haskell.org,Haskell} programs. Some of its major features are: @itemize @item Syntax highlighting (font lock), @item automatic indentation, @item on-the-fly documentation, @item interaction with inferior GHCi/Hugs instance, and @item scanning declarations and placing them in a menu. @end itemize @node Getting Help and Reporting Bugs @chapter Getting Help and Reporting Bugs This Info manual is work in progress and incomplete. However, you can find more information at these locations in the meantime: @itemize @item @uref{https://github.com/haskell/haskell-mode,Haskell Mode's GitHub Home} @item @uref{http://www.haskell.org/haskellwiki/Haskell_mode_for_Emacs,Haskell Wiki Emacs Page} @end itemize If you have any questions or like to discuss something regarding Haskell Mode, please consider sending an email to the @uref{http://projects.haskell.org/cgi-bin/mailman/listinfo/haskellmode-emacs, Haskellmode-emacs mailing list}. The mailing list is also available on @uref{http://gmane.org/, Gmane} via the @uref{http://dir.gmane.org/gmane.comp.lang.haskell.emacs, gmane.comp.lang.haskell.emacs} newsgroup. If you have discovered a bug or wish to request a new feature, you can @uref{https://github.com/haskell/haskell-mode/issues/new, file a new issue} with Haskell Mode's issue tracker. When filing a bug, please state your currently used software version (@kbd{M-x haskell-version}, @kbd{M-x version}) and what steps to perform in order to reproduce the bug you're experiencing. Finally, if you happen to be proficient in @ref{Top,Emacs Lisp,,elisp} you are welcome to submit patches via @uref{https://help.github.com/articles/using-pull-requests, GitHub Pull Requests}. @node Getting Started @chapter Getting Started If you are reading this, you have most likely already managed to install Haskell Mode in one way or another. However, just for the record, the officially recommended way is to install Haskell Mode via the @uref{http://marmalade-repo.org/packages/haskell-mode,Marmalade package archive} which contains the latest stable release of Haskell Mode. @findex haskell-customize Most of Haskell Mode's settings are configurable via customizable variables (@pxref{Easy Customization,,,emacs}, for details). You can use @kbd{M-x haskell-customize} to browse the @code{haskell} customization sub-tree. @vindex haskell-mode-hook One of the important setting you should customize is the @code{haskell-mode-hook} variable (@pxref{Hooks,,,emacs}) which gets run right after the @code{haskell-mode} major mode is initialized for a buffer. You can customize @code{haskell-mode-hook} by @kbd{M-x customize-variable @key{RET} haskell-mode-hook}. It's highly recommended you set up indentation to match your preferences; @xref{Indentation}, for more details about the indentation modes included with Haskell Mode. @c TODO: @c provide basic instructions to get up and running with haskell-mode @c tell about the most important commands @node Editing Haskell Code @chapter Editing Haskell Code @findex haskell-mode @cindex @code{haskell-mode} @dfn{Haskell Mode} is actually a collection of so-called major modes@footnote{for more information about the concept of @dfn{major modes} @pxref{Major Modes,,,emacs}} one of which is called @code{haskell-mode}. To avoid confusion, when referring to this package the name ``Haskell mode'' is written in a normal font, whereas when referring the major mode of the same name @code{haskell-mode} written with a dash in-between in a typewriter font is used. As one might guess, @code{haskell-mode} is the (programming language@footnote{@code{haskell-mode} is derived from @code{prog-mode}}) major mode for editing (non-literate) Haskell source code. @code{haskell-mode} is associated with the file extensions listed below by default@footnote{for more information about file associations, @pxref{Choosing Modes,,,emacs}}. @table @file @item .hs official file extension for (non-literate) Haskell 98/2010 files @item .hsc ``almost-Haskell'' input file for the @uref{http://www.haskell.org/ghc/docs/latest/html/users_guide/hsc2hs.html,hsc2hs} pre-processor @item .cpphs input file for the @uref{http://projects.haskell.org/cpphs/,cpphs} pre-processor @end table @cindex literate programming @findex literate-haskell-mode @noindent The major mode @code{literate-haskell-mode} (which is derived from @code{haskell-mode} and thus transitively from @code{prog-mode}) provides support for @uref{http://www.haskell.org/haskellwiki/Literate_programming,literate Haskell programs} and is associated with the @file{.lhs} file extension by default. @code{literate-haskell-mode} supports Bird-style as well as @TeX{}-style literate Haskell files. The currently detected literate Haskell variant is shown in the mode line (@pxref{Mode Line,,,emacs}) as either @samp{LitHaskell/bird} or @samp{LitHaskell/tex}. @section Font Lock Support @code{haskell-mode} supports @dfn{syntax highlighting} via Emacs' Font Lock minor mode which should be enabled by default in current Emacsen. @xref{Font Lock,,,emacs}, for more information on how to control @code{font-lock-mode}. @node Unicode @chapter Unicode support @cindex Unicode See the Haskell Wiki's entry on @uref{http://www.haskell.org/haskellwiki/Unicode-symbols, Unicode Symbols} for general information about Unicode support in Haskell. As Emacs supports editing files containing Unicode out of the box, so does Haskell Mode. As an add-on, Haskell Mode includes the @code{haskell-unicode} input method which allows you to easily type a number of Unicode symbols that are useful when writing Haskell code; @xref{Input Methods,,,emacs}, for more details. To automatically enable the @code{haskell-unicode} input method in haskell-mode buffers use @kbd{M-x customize-variable @key{RET} haskell-mode-hook} or put the following code in your @file{.emacs} file: @lisp (add-hook 'haskell-mode-hook 'turn-on-haskell-unicode-input-method) @end lisp @noindent To temporarily enable this input method for a single buffer you can use @kbd{M-x turn-on-haskell-unicode-input-method}. When the @code{haskell-unicode} input method is active, you can simply type @samp{->} and it is immediately replaced with @samp{→}. Use @kbd{C-\} to toggle the input method. To see a table of all key sequences use @kbd{M-x describe-input-method @key{RET} haskell-unicode}. A sequence like @samp{<=} is ambiguous and can mean either @samp{⇐} or @samp{≤}. Typing it presents you with a choice. Type @kbd{1} or @kbd{2} to select an option or keep typing to use the default option. If you don't like the highlighting of partially matching tokens you can turn it off by setting @code{input-method-highlight-flag} to @code{nil} via @kbd{M-x customize-variable}. @node Indentation @chapter Indentation @cindex indentation @cindex layout rule @cindex off-side rule For general information about indentation support in GNU Emacs, @pxref{Indentation,,,emacs}. In Haskell, code indentation has semantic meaning as it defines the block structure@footnote{Haskell also supports braces and semicolons notation for conveying the block structure. However, most Haskell programs written by humans use indentation for block structuring.}. As GNU Emacs' default indentation function (i.e. @code{indent-relative}) is not designed for use with Haskell's layout rule, Haskell mode includes three different indentation minor modes with different trade-offs: @ftable @code @item turn-on-haskell-simple-indent A very simple indentation scheme; In this scheme, @key{TAB} will now move the cursor to the next indent point in the previous non-blank line. An indent point is a non-whitespace character following whitespace. @item turn-on-haskell-indent Intelligent semi-automatic indentation for Haskell's layout rule. The basic idea is to have @key{TAB} cycle through possibilities indentation points based on some clever heuristics. The rationale and the implementation principles are described in more detail in the article @cite{Dynamic tabbing for automatic indentation with the layout rule} published in the Journal of Functional Programming 8.5 (1998). @item turn-on-haskell-indentation Improved variation of @code{turn-on-haskell-indent} indentation mode. Rebinds @key{RET} and @key{DEL}, so that indentations can be set and deleted as if they were real tabs. @end ftable To enable one of these three mutually exclusive indentation schemes, you just need call one (and only one!) of the @code{turn-on-*} commands while in the buffer you want the indentation scheme to be activated for. The recommended way is to add one of @code{turn-on-*} commands to @code{haskell-mode-hook}. This can be done either by using @kbd{M-x customize-variable @key{RET} haskell-mode-hook} which provides a convenient user interface or by adding @emph{one} of the following three lines to your @file{.emacs} file: @lisp (add-hook 'haskell-mode-hook 'turn-on-haskell-simple-indent) (add-hook 'haskell-mode-hook 'turn-on-haskell-indent) (add-hook 'haskell-mode-hook 'turn-on-haskell-indentation) @end lisp @section Interactive Block Indentation By inserting the key bindings for @kbd{C-,} and @kbd{C-.} (these bindings are convenient on keyboard layouts where @key{,} and @key{.} are adjacent keys) as shown below you can interactively de/indent either the following nested block or, if a region is active while in Transient Mark Mode (@pxref{Disabled Transient Mark,,,emacs}), de/indent the active region. By using a numeric prefix argument (@pxref{Prefix Command Arguments,,,elisp}) you can modify the shift-amount; for instance, @kbd{C-u C-,} increases indentation by 4 characters at once. @findex haskell-move-nested-left @findex haskell-move-nested-right @lisp (eval-after-load "haskell-mode" '(progn (define-key haskell-mode-map (kbd "C-,") 'haskell-move-nested-left) (define-key haskell-mode-map (kbd "C-.") 'haskell-move-nested-right))) @end lisp @section Rectangle Commands @cindex rectangle @cindex CUA mode GNU Emacs provides so-called @dfn{rectangle commands} which operate on rectangular areas of text, which are particularly useful for languages with a layout rule such as Haskell. @xref{Rectangles,,,emacs}, to learn more about rectangle commands. Moreover, CUA mode (@pxref{CUA Bindings,,,emacs}) provides enhanced rectangle support with visible rectangle highlighting. When CUA mode is active, you can initiate a rectangle selection by @kbd{C-RET} and extend it simply by movement commands. You don't have to enable full CUA mode to benefit from these enhanced rectangle commands; you can activate CUA selection mode (without redefining @kbd{C-x},@kbd{C-c},@kbd{C-v}, and @kbd{C-z}) by calling @kbd{M-x cua-selection-mode} (or adding @code{(cua-selection-mode nil)} to your @code{haskell-mode-hook}). @node haskell-decl-scan-mode @chapter @code{haskell-decl-scan-mode} @findex turn-on-haskell-decl-scan @findex haskell-decl-scan-mode @vindex haskell-decl-scan-mode-hook @code{haskell-decl-scan-mode} is a minor mode which performs declaration scanning and provides @kbd{M-x imenu} support (@pxref{Imenu,,,emacs} for more information). For non-literate and @TeX{}-style literate scripts, the common convention that top-level declarations start at the first column is assumed. For Bird-style literate scripts, the common convention that top-level declarations start at the third column, ie. after @samp{> }, is assumed. When @code{haskell-decl-scan-mode} is active, the standard Emacs top-level definition movement commands (@pxref{Moving by Defuns,,,emacs}) are enabled to operate on Haskell declarations: @table @kbd @item C-M-a Move to beginning of current or preceding declaration (@code{beginning-of-defun}). @item C-M-e Move to end of current or following declaration (@code{end-of-defun}). @item C-M-h Select whole current or following declaration (@code{mark-defun}). @end table Moreover, if enabled via the option @code{haskell-decl-scan-add-to-menubar}, a menu item ``Declarations'' is added to the menu bar listing the scanned declarations and allowing to jump to declarations in the source buffer. It's recommended to have font lock mode enabled (@pxref{Font Lock,,,emacs}) as @code{haskell-decl-scan-mode} ignores text highlighted with @code{font-lock-comment-face}. As usual, in order to activate @code{haskell-decl-scan-mode} automatically for Haskell buffers, add @code{turn-on-haskell-decl-scan} to @code{haskell-mode-hook}: @lisp (add-hook 'haskell-mode-hook 'turn-on-haskell-decl-scan) @end lisp @code{haskell-decl-scan-mode} enables the use of features that build upon @code{imenu} support such as Speedbar Frames (@pxref{Speedbar,,,emacs}) or the global ``Which Function'' minor mode (@pxref{Which Function,,,emacs}). In order to enable @code{which-function-mode} for Haskell buffers you need to add the following to your Emacs initialization: @lisp (eval-after-load "which-func" '(add-to-list 'which-func-modes 'haskell-mode)) @end lisp @node Compilation @chapter Compilation @findex haskell-compile Haskell mode comes equipped with a specialized @dfn{Compilation mode} tailored to GHC's compiler messages with optional support for Cabal projects. @xref{Compilation Mode,,,emacs}, for more information about the basic commands provided by the Compilation mode which are available in the Haskell compilation sub-mode as well. The additional features provided compared to Emacs' basic Compilation mode are: @itemize @item DWIM-style auto-detection of compile command (including support for CABAL projects) @item Support for GHC's compile messages and recognizing error, warning and info source locations (including @option{-ferror-spans} syntax) @item Support for filtering out GHC's uninteresting @samp{Loading package...} linker messages @end itemize In order to use it, invoke the @code{haskell-compile} command instead of @code{compile} as you would for the ordinary Compilation mode. It's recommended to bind @code{haskell-compile} to a convenient key binding. For instance, you can add the following to your Emacs initialization to bind @code{haskell-compile} to @kbd{C-c C-c}. @lisp (eval-after-load "haskell-mode" '(define-key haskell-mode-map (kbd "C-c C-c") 'haskell-compile)) (eval-after-load "haskell-cabal" '(define-key haskell-cabal-mode-map (kbd "C-c C-c") 'haskell-compile)) @end lisp @noindent The following description assumes that @code{haskell-compile} has been bound to @kbd{C-c C-c}. @vindex haskell-compile-cabal-build-command @vindex haskell-compile-cabal-build-command-alt @vindex haskell-compile-command When invoked, @code{haskell-compile} tries to guess how to compile the Haskell program your currently visited buffer belongs to, by searching for a @file{.cabal} file in the current of enclosing parent folders. If a @file{.cabal} file was found, the command defined in the @code{haskell-compile-cabal-build-command} option is used. Moreover, when requesting to compile a @file{.cabal}-file is detected and a negative prefix argument (e.g. @kbd{C-- C-c C-c}) was given, the alternative @code{haskell-compile-cabal-build-command-alt} is invoked. By default, @code{haskell-compile-cabal-build-command-alt} contains a @samp{cabal clean -s} command in order to force a full rebuild. Otherwise if no @file{.cabal} could be found, a single-module compilation is assumed and @code{haskell-compile-command} is used (@emph{if} the currently visited buffer contains Haskell source code). You can also inspect and modify the compile command to be invoked temporarily by invoking @code{haskell-compile} with a prefix argument (e.g. @kbd{C-u C-c C-c}). If later-on you want to recompile using the same customized compile command, invoke @code{recompile} (bound to @kbd{g}) inside the @samp{*haskell-compilation*} buffer. @node inferior-haskell-mode @chapter @code{inferior-haskell-mode} @findex inferior-haskell-find-definition @findex inferior-haskell-find-haddock @findex inferior-haskell-info @findex inferior-haskell-load-and-run @findex inferior-haskell-load-file @findex inferior-haskell-mode @findex inferior-haskell-reload-file @findex inferior-haskell-start-process @findex inferior-haskell-type @vindex haskell-program-name @vindex inferior-haskell-mode-hook The major mode @code{inferior-haskell-mode} provides support for interacting with an inferior Haskell process based on @code{comint-mode}. By default the @code{haskell-mode-map} keymap is setup to use this mode: @table @kbd @item C-c C-z is bound to @code{switch-to-haskell} @item C-c C-b is bound to @code{switch-to-haskell} @item C-c C-l is bound to @code{inferior-haskell-load-file} @item C-c C-t is bound to @code{inferior-haskell-type} @item C-c C-i is bound to @code{inferior-haskell-info} @end table The Haskell interpreter used by the inferior Haskell mode is auto-detected by default, but is customizable via the @code{haskell-program-name} variable. Currently, GHCi and Hugs are support as Haskell interpreter. TODO/WRITEME @c write about supported features @node haskell-interactive-mode @chapter @code{haskell-interactive-mode} An alternative mode providing a @acronym{REPL,read–eval–print loop} via GHCi sessions is called @code{haskell-interactive-mode}, which effectively replaces @code{inferior-haskell-mode}, but comes with a different set of features: @itemize @item Separate sessions per Cabal project @file{haskell-session.el}. @item A new inferior Haskell process handling code @file{haskell-process.el}. @item New REPL implementation similiar to SLIME/IELM @file{haskell-interactive-mode.el}. @end itemize In order to use @code{haskell-interactive-mode} instead of the default @code{inferior-haskell-mode}, you need to replace some of the default keybindings in the @code{haskell-mode-map} keymap with the respective @code{haskell-interactive-mode} counterparts: @lisp (eval-after-load "haskell-mode" '(progn (define-key haskell-mode-map (kbd "C-x C-d") nil) (define-key haskell-mode-map (kbd "C-c C-z") 'haskell-interactive-switch) (define-key haskell-mode-map (kbd "C-c C-l") 'haskell-process-load-file) (define-key haskell-mode-map (kbd "C-c C-b") 'haskell-interactive-switch) (define-key haskell-mode-map (kbd "C-c C-t") 'haskell-process-do-type) (define-key haskell-mode-map (kbd "C-c C-i") 'haskell-process-do-info) (define-key haskell-mode-map (kbd "C-c M-.") nil) (define-key haskell-mode-map (kbd "C-c C-d") nil))) @end lisp With @code{haskell-interactive-mode}, each Haskell source buffer is associated with at most one GHCi session, so when you call @code{haskell-process-load-file} for a Haskell source buffer which has no session associated yet, you're asked which GHCi session to create or associate with. TODO/WRITEME @node haskell-cabal-mode @chapter @code{haskell-cabal-mode} @findex haskell-cabal-mode @vindex haskell-cabal-mode-hook @code{haskell-cabal-mode} is a major mode for editing @uref{http://www.haskell.org/cabal/users-guide/developing-packages.html,Cabal package description files} and is automatically associated with files having a @file{.cabal} extension. @findex haskell-cabal-visit-file For quickly locating and jumping to the nearest @file{.cabal} file from a Haskell source buffer, you can use @kbd{M-x haskell-cabal-visit-file}; with a prefix argument (i.e. @kbd{C-u}) @code{find-file-other-window} is used to visit the @file{.cabal} file. If you wish, you can bind @code{haskell-cabal-visit-file} to a convenient key sequence, e.g. @lisp (eval-after-load "haskell-mode" (define-key haskell-mode-map (kbd "C-c v c") 'haskell-cabal-visit-file)) @end lisp TODO/WRITEME @node Concept index @unnumbered Concept index @printindex cp @node Function index @unnumbered Function index @printindex fn @node Variable index @unnumbered Variable index @printindex vr @bye @c Local Variables: @c eval: (visual-line-mode t) @c eval: (linum-mode t) @c eval: (hl-line-mode t) @c End: haskell-mode-13.10/haskell-move-nested.el000066400000000000000000000107071225210037200202530ustar00rootroot00000000000000;;; haskell-move-nested.el --- Change the column of text nested below a line ;; Copyright (C) 2010 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This program is free software: you can redistribute it and/or ;; modify it under the terms of the GNU General Public License as ;; published by the Free Software Foundation, either version 3 of ;; the License, or (at your option) any later version. ;; This program is distributed in the hope that it will be ;; useful, but WITHOUT ANY WARRANTY; without even the implied ;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ;; PURPOSE. See the GNU General Public License for more details. ;; You should have received a copy of the GNU General Public ;; License along with this program. If not, see ;; . ;;; Commentary: ;; This module is intended for Haskell mode users, but is ;; independent of Haskell mode. ;; Example usage: ;; (define-key haskell-mode-map (kbd "C-,") 'haskell-move-nested-left) ;; (define-key haskell-mode-map (kbd "C-.") 'haskell-move-nested-right) ;;; Code: ;;;###autoload (defun haskell-move-nested (cols) "Shift the nested off-side-rule block adjacent to point by COLS columns to the right. In Transient Mark mode, if the mark is active, operate on the contents of the region instead. " (save-excursion (if (and transient-mark-mode mark-active) (progn (indent-rigidly (region-beginning) (region-end) cols) (setq deactivate-mark nil)) (let ((region (haskell-move-nested-region))) (when region (indent-rigidly (car region) (cdr region) cols)))))) ;;;###autoload (defun haskell-move-nested-right (cols) "Increase indentation of the following off-side-rule block adjacent to point. Use a numeric prefix argument to indicate amount of indentation to apply. In Transient Mark mode, if the mark is active, operate on the contents of the region instead." (interactive "p") (haskell-move-nested cols) ) ;;;###autoload (defun haskell-move-nested-left (cols) "Decrease indentation of the following off-side-rule block adjacent to point. Use a numeric prefix argument to indicate amount of indentation to apply. In Transient Mark mode, if the mark is active, operate on the contents of the region instead." (interactive "p") (haskell-move-nested (- cols)) ) (defun haskell-move-nested-region () "Infer region off-side-rule block adjacent to point. Used by `haskell-move-nested'. " (save-excursion (let ((starting-level (current-column))) (forward-line) (let ((current-level (haskell-move-nested-indent-level))) (let ((start-point (line-beginning-position)) (start-end-point (line-end-position)) (end-point nil) (last-line 0)) (forward-line) (while (and (not (= (line-beginning-position) last-line)) (or (> (haskell-move-nested-indent-level) starting-level) (and (> current-level starting-level) (>= (haskell-move-nested-indent-level) current-level)))) (setq last-line (line-beginning-position)) (setq end-point (line-end-position)) (forward-line)) (cons start-point (or end-point start-end-point))))))) (defun haskell-move-nested-indent-level () (max 0 (1- (length (buffer-substring-no-properties (line-beginning-position) (or (save-excursion (goto-char (line-beginning-position)) (search-forward-regexp "[^ ]" (line-end-position) t 1)) (line-beginning-position))))))) (defun haskell-kill-nested () "Kill the nested region after point." (interactive) (let ((start (point)) (reg (save-excursion (search-backward-regexp "^[ ]+" (line-beginning-position) t 1) (search-forward-regexp "[^ ]" (line-end-position) t 1) (haskell-move-nested-region)))) (kill-region start (cdr reg)))) (defun haskell-delete-nested () "Kill the nested region after point." (interactive) (let ((start (point)) (reg (save-excursion (search-backward-regexp "^[ ]+" (line-beginning-position) t 1) (search-forward-regexp "[^ ]" (line-end-position) t 1) (haskell-move-nested-region)))) (delete-region start (cdr reg)))) (provide 'haskell-move-nested) ;;; haskell-move-nested.el ends here haskell-mode-13.10/haskell-navigate-imports.el000066400000000000000000000104761225210037200213210ustar00rootroot00000000000000;;; haskell-navigate-imports.el --- A function for cycling through Haskell import lists ;; Copyright (C) 2010 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This program is free software: you can redistribute it and/or ;; modify it under the terms of the GNU General Public License as ;; published by the Free Software Foundation, either version 3 of ;; the License, or (at your option) any later version. ;; This program is distributed in the hope that it will be ;; useful, but WITHOUT ANY WARRANTY; without even the implied ;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ;; PURPOSE. See the GNU General Public License for more details. ;; You should have received a copy of the GNU General Public ;; License along with this program. If not, see ;; . ;;; Commentary: ;; The cycling step will stop once at the last import list so ;; that it is easy to add a new import list. ;; This module works completely independently of any libraries ;; (including haskell-mode). ;; Exports three interactive functions: ;; 1. haskell-navigate-imports ;; 2. haskell-navigate-imports-go ;; 3. haskell-navigate-imports-return ;; Example usage: ;; (require 'haskell-navigate-imports) ;; (define-key haskell-mode-map [f8] 'haskell-navigate-imports) ;;; Code: (defvar haskell-navigate-imports-start-point nil) ;;;###autoload (defun haskell-navigate-imports (&optional return) "Cycle the Haskell import lines or return to point (with prefix arg)." (interactive "P") (if return (haskell-navigate-imports-return) (haskell-navigate-imports-go))) ;;;###autoload (defun haskell-navigate-imports-go () "Go to the first line of a list of consequtive import lines. Cycles." (interactive) (unless (or (haskell-navigate-imports-line) (equal (line-beginning-position) (point-min)) (save-excursion (forward-line -1) (haskell-navigate-imports-line))) (setq haskell-navigate-imports-start-point (point))) (haskell-navigate-imports-go-internal)) ;;;###autoload (defun haskell-navigate-imports-return () "Return to the non-import point we were at before going to the module list. If we were originally at an import list, we can just cycle through easily." (interactive) (when haskell-navigate-imports-start-point (goto-char haskell-navigate-imports-start-point))) (defun haskell-navigate-imports-go-internal () "Go to the first line of a list of consequtive import lines. Cycle." (if (haskell-navigate-imports-line) (progn (haskell-navigate-imports-goto-end) (when (haskell-navigate-imports-find-forward-line) (haskell-navigate-imports-go-internal))) (let ((point (haskell-navigate-imports-find-forward-line))) (if point (goto-char point) (progn (goto-char (point-min)) (when (haskell-navigate-imports-find-forward-line) (haskell-navigate-imports-go-internal))))))) (defun haskell-navigate-imports-goto-end () "Skip a bunch of consequtive import lines." (while (not (or (equal (point) (point-max)) (not (haskell-navigate-imports-line)))) (forward-line))) (defun haskell-navigate-imports-find-forward-line () "Return a point with at an import line, or nothing." (save-excursion (while (not (or (equal (point) (point-max)) (haskell-navigate-imports-after-imports-p) ;; This one just speeds it up. (haskell-navigate-imports-line))) (forward-line)) (let ((point (point))) (if (haskell-navigate-imports-line) (point) nil)))) (defun haskell-navigate-imports-line () "Try to match the current line as a regexp." (let ((line (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (if (string-match "^import " line) line nil))) (defun haskell-navigate-imports-after-imports-p () "Are we after the imports list? Just for a speed boost." (save-excursion (goto-char (line-beginning-position)) (not (not (search-forward-regexp "\\( = \\|\\\\| :: \\)" (line-end-position) t 1))))) (provide 'haskell-navigate-imports) ;;; haskell-navigate-imports.el ends here haskell-mode-13.10/haskell-package.el000066400000000000000000000137211225210037200174170ustar00rootroot00000000000000;;; haskell-package.el --- Interface for working with Cabal packages ;; Copyright (C) 2011 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;;; Todo: ;;; Code: (with-no-warnings (require 'cl)) ;; Dynamically scoped variables. ;; TODO What actually sets this? (defvar haskell-config-use-cabal-dev) ;; (defun haskell-package-conf-path-get (&optional project) ;; "Gets the user conf or the cabal-dev conf. Get the global conf elsewhere." ;; (if haskell-config-use-cabal-dev ;; (if project ;; (let* ((cabal-path (haskell-project-cabal-dir project))) ;; (format "%scabal-dev/packages-%s.conf/" ;; (if (string-match "/$" cabal-path) ;; cabal-path ;; (concat cabal-path "/")) ;; (haskell-ghc-version))) ;; (haskell-package-conf-user-path-get)) ;; (haskell-package-conf-user-path-get))) (defun haskell-package-conf-user-path-get () "Get the user conf path." (let ((out (shell-command-to-string "ghc-pkg --user list no-results-please"))) (string-match "\n\\(.*\\):\n" out) (match-string 1 out))) (defun haskell-package-conf-global-path-get () "Get the global conf path." (let ((out (shell-command-to-string "ghc-pkg --global list no-results-please"))) (string-match "\n\\(.*\\):\n" out) (match-string 1 out))) (defun haskell-package-get-all (conf) "Get all package descriptions for the given `conf'." (let ((all (shell-command-to-string (format "ghc-pkg -f %s dump" conf)))) (mapcar (lambda (text) (haskell-package-parse text)) (split-string all "\n---\n")))) (defun haskell-package-get (conf name version) "Get a package description for the given `name' and `version' in the given `conf'." (haskell-package-parse (shell-command-to-string (format "ghc-pkg -f %s describe %s-%s" conf name version)))) (defstruct haskell-package "Haskell package object.") (defun haskell-package-parse (text) "Parse a package into a package object." (let ((pkg (haskell-package-read-description text))) (make-haskell-package :name (cdr (assoc "name" pkg)) :version (cdr (assoc "version" pkg)) :id (cdr (assoc "id" pkg)) :license (cdr (assoc "license" pkg)) :copyright (cdr (assoc "copyright" pkg)) :maintainer (cdr (assoc "maintainer" pkg)) :stability (cdr (assoc "stability" pkg)) :homepage (cdr (assoc "homepage" pkg)) :package-url (cdr (assoc "package-url" pkg)) :description (cdr (assoc "description" pkg)) :categories (cdr (assoc "category" pkg)) :authors (cdr (assoc "author" pkg)) :is-exposed (equal "True" (cdr (assoc "exposed" pkg))) :exposed-modules (split-string (or (cdr (assoc "exposed-modules" pkg)) "") "[\n ]") :hidden-modules (split-string (or (cdr (assoc "hidden-modules" pkg)) "") "[\n ]") :imports-dirs (cdr (assoc "imports-dirs" pkg)) :library-dirs (cdr (assoc "library-dirs" pkg)) :haskell-libraries (cdr (assoc "haskell-libraries" pkg)) :extra-libraries (cdr (assoc "extra-libraries" pkg)) :extra-ghci-libraries (cdr (assoc "extra-ghci-libraries" pkg)) :include-dirs (cdr (assoc "include-dirs" pkg)) :includes (cdr (assoc "includes" pkg)) :depends (cdr (assoc "depends" pkg)) :hugs-options (cdr (assoc "hugs-options" pkg)) :cc-options (cdr (assoc "cc-options" pkg)) :ld-options (cdr (assoc "ld-options" pkg)) :framework-dirs (cdr (assoc "framework-dirs" pkg)) :frameworks (cdr (assoc "frameworks" pkg)) :haddock-interfaces (cdr (assoc "haddock-interfaces" pkg)) :haddock-html (cdr (assoc "haddock-html" pkg))))) (defun haskell-package-read-description (text) "Return an association list of key-values from a pkg description string." (let* ((marked (replace-regexp-in-string "\n\\([^ ]\\)" (lambda (match) (concat "\n:" (substring match 1))) text)) (alist (mapcar 'haskell-package-key-value (split-string marked "\n:")))) alist)) (defun haskell-package-key-value (entry) "Return a (key . value) pair from an entry." (let ((key-values (split-string entry ": "))) (if (listp key-values) (cons (car key-values) (replace-regexp-in-string "\n[ ]*" " " (mapconcat 'identity (cdr key-values) ": "))) key-values))) (defun haskell-package-list-get (conf) "Get the list of packages in the given config." (haskell-package-list-parse (shell-command-to-string (format "ghc-pkg -f %s list" conf)))) (defun haskell-package-list-parse (text) "Parse the list of installed packges." (let* ((lines (split-string text "\n "))) (mapcar (lambda (line) (string-match "^{?\\([a-zA-Z0-9-_]+\\)-\\([0-9.]+\\)}?$" line) (cons (match-string 1 line) (match-string 2 line))) (delete-if (lambda (line) (not (string-match "^{?[a-zA-Z0-9-_]+-[0-9.]+}?$" line))) lines)))) (provide 'haskell-package) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-package.el ends here haskell-mode-13.10/haskell-presentation-mode.el000066400000000000000000000041031225210037200214530ustar00rootroot00000000000000;;; haskell-presentation-mode.el --- Presenting Haskell things ;; Copyright (C) 2013 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;;; Code: (require 'haskell-mode) (define-derived-mode haskell-presentation-mode haskell-mode "Presentation" "Major mode for viewing Haskell snippets. \\{hypertext-mode-map}" (setq case-fold-search nil)) (define-key haskell-presentation-mode-map (kbd "q") 'quit-window) (defun haskell-present (name session code) "Present CODE in a popup buffer suffixed with NAME and set SESSION as the current haskell-session." (let* ((name (format "*Haskell Presentation%s*" name)) (buffer (get-buffer-create name))) (with-current-buffer buffer (haskell-presentation-mode) (let ((buffer-read-only nil)) (erase-buffer) (insert (propertize "-- Hit `q' to close this window.\n\n" 'face 'font-lock-comment-face)) (let ((point (point))) (insert code "\n\n") (font-lock-fontify-region point (point)) (goto-char point)))) (if (and (boundp 'haskell-presentation-mode) haskell-presentation-mode) (switch-to-buffer buffer) (pop-to-buffer buffer)))) (provide 'haskell-presentation-mode) ;;; haskell-presentation-mode.el ends here haskell-mode-13.10/haskell-process.el000066400000000000000000001340171225210037200175040ustar00rootroot00000000000000;;; haskell-process.el --- Communicating with the inferior Haskell process ;; Copyright (C) 2011-2012 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;;; Todo: ;;; Code: (require 'haskell-mode) (require 'haskell-session) (require 'haskell-compat) (require 'haskell-str) (require 'haskell-utils) (require 'haskell-presentation-mode) (with-no-warnings (require 'cl)) ;; FIXME: haskell-process shouldn't depend on haskell-interactive-mode to avoid module-dep cycles (declare-function haskell-interactive-mode-echo "haskell-interactive-mode" (session message &optional mode)) (declare-function haskell-interactive-mode-compile-error "haskell-interactive-mode" (session message)) (declare-function haskell-interactive-mode-insert "haskell-interactive-mode" (session message)) (declare-function haskell-interactive-mode-reset-error "haskell-interactive-mode" (session)) (declare-function haskell-interactive-show-load-message "haskell-interactive-mode" (session type module-name file-name echo)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Configuration (defgroup haskell-interactive nil "Settings for REPL interaction via `haskell-interactive-mode'" :link '(custom-manual "(haskell-mode)haskell-interactive-mode") :group 'haskell) (defcustom haskell-process-path-ghci "ghci" "The path for starting ghci." :group 'haskell-interactive :type '(choice string (repeat string))) (defcustom haskell-process-path-cabal "cabal" "Path to the `cabal' executable." :group 'haskell-interactive :type '(choice string (repeat string))) (defcustom haskell-process-path-cabal-ghci "cabal-ghci" "The path for starting cabal-ghci." :group 'haskell-interactive :type '(choice string (repeat string))) (defcustom haskell-process-path-cabal-dev "cabal-dev" "The path for starting cabal-dev." :group 'haskell-interactive :type '(choice string (repeat string))) (defcustom haskell-process-args-ghci '("-ferror-spans") "Any arguments for starting ghci." :group 'haskell-interactive :type '(repeat (string :tag "Argument"))) (defcustom haskell-process-args-cabal-repl '("--ghc-option=-ferror-spans") "Additional arguments to for `cabal repl' invocation. Note: The settings in `haskell-process-path-ghci' and `haskell-process-args-ghci' are not automatically reused as `cabal repl' currently invokes `ghc --interactive'. Use `--with-ghc=' if you want to use a different interactive GHC frontend; use `--ghc-option=' to pass additional flags to `ghc'." :group 'haskell-interactive :type '(repeat (string :tag "Argument"))) (defcustom haskell-process-do-cabal-format-string ":!cd %s && %s" "The way to run cabal comands. It takes two arguments -- the directory and the command. See `haskell-process-do-cabal' for more details." :group 'haskell-interactive :type 'string) (defcustom haskell-process-type 'ghci "The inferior Haskell process type to use." :type '(choice (const ghci) (const cabal-repl) (const cabal-dev) (const cabal-ghci)) :group 'haskell-interactive) (defcustom haskell-process-log nil "Enable debug logging to \"*haskell-process-log*\" buffer." :type 'boolean :group 'haskell-interactive) (defcustom haskell-notify-p nil "Notify using notifications.el (if loaded)?" :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-suggest-no-warn-orphans t "Suggest adding -fno-warn-orphans pragma to file when getting orphan warnings." :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-suggest-language-pragmas t "Suggest adding LANGUAGE pragmas recommended by GHC." :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-suggest-remove-import-lines nil "Suggest removing import lines as warned by GHC." :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-suggest-overloaded-strings t "Suggest adding OverloadedStrings pragma to file when getting type mismatches with [Char]." :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-check-cabal-config-on-load t "Check changes cabal config on loading Haskell files and restart the GHCi process if changed.." :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-prompt-restart-on-cabal-change t "Ask whether to restart the GHCi process when the Cabal file has changed?" :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-auto-import-loaded-modules nil "Auto import the modules reported by GHC to have been loaded?" :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-reload-with-fbytecode nil "When using -fobject-code, auto reload with -fbyte-code (and then restore the -fobject-code) so that all module info and imports become available?" :type 'boolean :group 'haskell-interactive) (defcustom haskell-process-use-presentation-mode nil "Use presentation mode to show things like type info instead of printing to the message area." :type 'boolean :group 'haskell-interactive) (defvar haskell-process-prompt-regex "\\(^[> ]*> $\\|\n[> ]*> $\\)") (defvar haskell-reload-p nil) (defvar haskell-process-greetings (list "Hello, Haskell!" "The lambdas must flow." "Hours of hacking await!" "The next big Haskell project is about to start!" "Your wish is my IO ().") "Greetings for when the Haskell process starts up.") (defconst haskell-process-logo (expand-file-name "logo.svg" haskell-mode-pkg-base-dir) "Haskell logo for notifications.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Specialised commands ;;;###autoload (defun haskell-process-generate-tags (&optional and-then-find-this-tag) "Regenerate the TAGS table." (interactive) (let ((process (haskell-process))) (haskell-process-queue-command process (make-haskell-command :state (cons process and-then-find-this-tag) :go (lambda (state) (haskell-process-send-string (car state) (format ":!cd %s && %s | %s | %s" (haskell-session-cabal-dir (haskell-process-session (car state))) "find . -name '*.hs*'" "grep -v '#'" ; To avoid Emacs back-up files. Yeah. "xargs hasktags -e -x"))) :complete (lambda (state response) (when (cdr state) (let ((tags-file-name (haskell-session-tags-filename (haskell-process-session (car state))))) (find-tag (cdr state)))) (haskell-mode-message-line "Tags generated.")))))) ;;;###autoload (defun haskell-process-do-type (&optional insert-value) "Print the type of the given expression." (interactive "P") (if insert-value (haskell-process-insert-type) (haskell-process-do-simple-echo (let ((ident (haskell-ident-at-point))) ;; TODO: Generalize all these `string-match' of ident calls into ;; one function. (format (if (string-match "^[_[:lower:][:upper:]]" ident) ":type %s" ":type (%s)") ident)) 'haskell-mode))) (defun haskell-process-insert-type () "Get the identifer at the point and insert its type, if possible, using GHCi's :type." (let ((process (haskell-process)) (query (let ((ident (haskell-ident-at-point))) (format (if (string-match "^[_[:lower:][:upper:]]" ident) ":type %s" ":type (%s)") ident)))) (haskell-process-queue-command process (make-haskell-command :state (list process query (current-buffer)) :go (lambda (state) (haskell-process-send-string (nth 0 state) (nth 1 state))) :complete (lambda (state response) (cond ;; TODO: Generalize this into a function. ((or (string-match "^Top level" response) (string-match "^" response)) (message response)) (t (with-current-buffer (nth 2 state) (goto-char (line-beginning-position)) (insert (format "%s\n" response)))))))))) ;;;###autoload (defun haskell-process-do-info (&optional prompt-value) "Print info on the identifier at point. If PROMPT-VALUE is non-nil, request identifier via mini-buffer." (interactive "P") (haskell-process-do-simple-echo (let ((ident (if prompt-value (read-from-minibuffer "Info: " (haskell-ident-at-point)) (haskell-ident-at-point))) (modname (unless prompt-value (haskell-utils-parse-import-statement-at-point)))) (if modname (format ":browse! %s" modname) (format (if (string-match "^[a-zA-Z_]" ident) ":info %s" ":info (%s)") (or ident (haskell-ident-at-point))))) 'haskell-mode)) (defun haskell-process-do-try-info (sym) "Get info of `sym' and echo in the minibuffer." (let ((process (haskell-process))) (haskell-process-queue-command process (make-haskell-command :state (cons process sym) :go (lambda (state) (haskell-process-send-string (car state) (if (string-match "^[A-Za-z_]" (cdr state)) (format ":info %s" (cdr state)) (format ":info (%s)" (cdr state))))) :complete (lambda (state response) (unless (or (string-match "^Top level" response) (string-match "^" response)) (haskell-mode-message-line response))))))) (defun haskell-process-do-simple-echo (line &optional mode) "Send LINE to the GHCi process and echo the result in some fashion, such as printing in the minibuffer, or using haskell-present, depending on configuration." (let ((process (haskell-process))) (haskell-process-queue-command process (make-haskell-command :state (list process line mode) :go (lambda (state) (haskell-process-send-string (car state) (cadr state))) :complete (lambda (state response) ;; TODO: TBD: don't do this if ;; `haskell-process-use-presentation-mode' is t. (haskell-interactive-mode-echo (haskell-process-session (car state)) response (caddr state)) (if haskell-process-use-presentation-mode (progn (haskell-present (cadr state) (haskell-process-session (car state)) response) (haskell-session-assign (haskell-process-session (car state)))) (haskell-mode-message-line response))))))) (defun haskell-process-look-config-changes (session) "Checks whether a cabal configuration file has changed. Restarts the process if that is the case." (let ((current-checksum (haskell-session-get session 'cabal-checksum)) (new-checksum (haskell-cabal-compute-checksum (haskell-session-get session 'cabal-dir)))) (when (not (string= current-checksum new-checksum)) (haskell-interactive-mode-echo session (format "Cabal file changed: %s" new-checksum)) (haskell-session-set-cabal-checksum session (haskell-session-get session 'cabal-dir)) (unless (and haskell-process-prompt-restart-on-cabal-change (not (y-or-n-p "Cabal file changed; restart GHCi process? "))) (haskell-process-start (haskell-session)))))) ;;;###autoload (defun haskell-process-load-file () "Load the current buffer file." (interactive) (save-buffer) (haskell-interactive-mode-reset-error (haskell-session)) (haskell-process-file-loadish (concat "load " (buffer-file-name)) nil (current-buffer))) ;;;###autoload (defun haskell-process-reload-file () "Re-load the current buffer file." (interactive) (save-buffer) (haskell-interactive-mode-reset-error (haskell-session)) (haskell-process-file-loadish "reload" t nil)) ;;;###autoload (defun haskell-process-load-or-reload (&optional toggle) "Load or reload. Universal argument toggles which." (interactive "P") (if toggle (progn (setq haskell-reload-p (not haskell-reload-p)) (message "%s (No action taken this time)" (if haskell-reload-p "Now running :reload." "Now running :load ."))) (if haskell-reload-p (haskell-process-reload-file) (haskell-process-load-file)))) (defun haskell-process-file-loadish (command reload-p module-buffer) "Run a loading-ish COMMAND that wants to pick up type errors and things like that. RELOAD-P indicates whether the notification should say 'reloaded' or 'loaded'. MODULE-BUFFER may be used for various things, but is optional." (let ((session (haskell-session))) (haskell-session-current-dir session) (when haskell-process-check-cabal-config-on-load (haskell-process-look-config-changes session)) (let ((process (haskell-process))) (haskell-process-queue-command process (make-haskell-command :state (list session process command reload-p module-buffer) :go (lambda (state) (haskell-process-send-string (cadr state) (format ":%s" (caddr state)))) :live (lambda (state buffer) (haskell-process-live-build (cadr state) buffer nil)) :complete (lambda (state response) (haskell-process-load-complete (car state) (cadr state) response (cadddr state) (cadddr (cdr state))))))))) ;;;###autoload (defun haskell-process-cabal-build () "Build the Cabal project." (interactive) (haskell-process-do-cabal "build") (haskell-process-add-cabal-autogen)) ;;;###autoload (defun haskell-process-cabal () "Prompts for a Cabal command to run." (interactive) (haskell-process-do-cabal (ido-completing-read "Cabal command: " haskell-cabal-commands))) (defun haskell-process-add-cabal-autogen () "Add /dist/build/autogen/ to the ghci search path. This allows modules such as 'Path_...', generated by cabal, to be loaded by ghci." (unless (eq 'cabal-repl haskell-process-type) ;; redundant with "cabal repl" (let* ((session (haskell-session)) (cabal-dir (haskell-session-cabal-dir session)) (ghci-gen-dir (format "%sdist/build/autogen/" cabal-dir))) (haskell-process-queue-without-filters (haskell-process) (format ":set -i%s" ghci-gen-dir))))) (defun haskell-process-do-cabal (command) "Run a Cabal command." (let ((process (haskell-process))) (haskell-process-queue-command process (make-haskell-command :state (list (haskell-session) process command 0) :go (lambda (state) (haskell-process-send-string (cadr state) (format haskell-process-do-cabal-format-string (haskell-session-cabal-dir (car state)) (format "%s %s" (ecase haskell-process-type ('ghci "cabal") ('cabal-repl "cabal") ('cabal-ghci "cabal") ('cabal-dev "cabal-dev")) (caddr state))))) :live (lambda (state buffer) (cond ((or (string= (caddr state) "build") (string= (caddr state) "install")) (haskell-process-live-build (cadr state) buffer t)) (t (haskell-process-cabal-live state buffer)))) :complete (lambda (state response) (let* ((process (cadr state)) (session (haskell-process-session process)) (message-count 0) (cursor (haskell-process-response-cursor process))) (haskell-process-set-response-cursor process 0) (while (haskell-process-errors-warnings session process response) (setq message-count (1+ message-count))) (haskell-process-set-response-cursor process cursor) (let ((msg (format "Complete: cabal %s (%s compiler messages)" (caddr state) message-count))) (haskell-interactive-mode-echo session msg) (haskell-mode-message-line msg) (when (and haskell-notify-p (fboundp 'notifications-notify)) (notifications-notify :title (format "*%s*" (haskell-session-name (car state))) :body msg :app-name (ecase haskell-process-type ('ghci "cabal") ('cabal-repl "cabal") ('cabal-ghci "cabal") ('cabal-dev "cabal-dev")) :app-icon haskell-process-logo ))))))))) (defun haskell-process-cabal-live (state buffer) "Do live updates for Cabal processes." (haskell-interactive-mode-insert (haskell-process-session (cadr state)) (replace-regexp-in-string haskell-process-prompt-regex "" (substring buffer (cadddr state)))) (setf (cdddr state) (list (length buffer))) nil) (defun haskell-process-load-complete (session process buffer reload module-buffer) "Handle the complete loading response. BUFFER is the string of text being sent over the process pipe. MODULE-BUFFER is the actual Emacs buffer of the module being loaded." (cond ((haskell-process-consume process "Ok, modules loaded: \\(.+\\)\\.$") (let* ((modules (haskell-process-extract-modules buffer)) (cursor (haskell-process-response-cursor process))) (haskell-process-set-response-cursor process 0) (let ((warning-count 0)) (while (haskell-process-errors-warnings session process buffer) (setq warning-count (1+ warning-count))) (haskell-process-set-response-cursor process cursor) (if (and (not reload) haskell-process-reload-with-fbytecode) (haskell-process-reload-with-fbytecode process module-buffer) (haskell-process-import-modules process (car modules))) (haskell-mode-message-line (if reload "Reloaded OK." "OK."))))) ((haskell-process-consume process "Failed, modules loaded: \\(.+\\)\\.$") (let* ((modules (haskell-process-extract-modules buffer)) (cursor (haskell-process-response-cursor process))) (haskell-process-set-response-cursor process 0) (while (haskell-process-errors-warnings session process buffer)) (haskell-process-set-response-cursor process cursor) (if (and (not reload) haskell-process-reload-with-fbytecode) (haskell-process-reload-with-fbytecode process module-buffer) (haskell-process-import-modules process (car modules))) (haskell-interactive-mode-compile-error session "Compilation failed."))))) (defun haskell-process-reload-with-fbytecode (process module-buffer) "Reload FILE-NAME with -fbyte-code set, and then restore -fobject-code." (haskell-process-queue-without-filters process ":set -fbyte-code") (haskell-process-touch-buffer process module-buffer) (haskell-process-queue-without-filters process ":reload") (haskell-process-queue-without-filters process ":set -fobject-code")) (defun haskell-process-touch-buffer (process buffer) "Updates mtime on the file for BUFFER by queing a touch on PROCESS." (interactive) (haskell-process-queue-command process (make-haskell-command :state (cons process buffer) :go (lambda (state) (haskell-process-send-string (car state) (format ":!%s %s" "touch" (shell-quote-argument (buffer-file-name (cdr state)))))) :complete (lambda (state _) (with-current-buffer (cdr state) (clear-visited-file-modtime)))))) (defun haskell-process-extract-modules (buffer) "Extract the modules from the process buffer." (let* ((modules-string (match-string 1 buffer)) (modules (split-string modules-string ", "))) (cons modules modules-string))) (defun haskell-process-import-modules (process modules) "Import `modules' with :m +, and send any import statements from `module-buffer'." (when haskell-process-auto-import-loaded-modules (haskell-process-queue-command process (make-haskell-command :state (cons process modules) :go (lambda (state) (haskell-process-send-string (car state) (format ":m + %s" (mapconcat 'identity (cdr state) " ")))))))) (defun haskell-process-live-build (process buffer echo-in-repl) "Show live updates for loading files." (cond ((haskell-process-consume process (concat "\\[[ ]*\\([0-9]+\\) of \\([0-9]+\\)\\]" " Compiling \\([^ ]+\\)[ ]+" "( \\([^ ]+\\), \\([^ ]+\\) )[^\r\n]*[\r\n]+")) (let ((session (haskell-process-session process)) (module-name (match-string 3 buffer)) (file-name (match-string 4 buffer))) (haskell-interactive-show-load-message session 'compiling module-name (haskell-session-strip-dir session file-name) echo-in-repl)) t) ((haskell-process-consume process "Loading package \\([^ ]+\\) ... linking ... done.\n") (haskell-mode-message-line (format "Loading: %s" (match-string 1 buffer))) t) ((haskell-process-consume process "^Preprocessing executables for \\(.+?\\)\\.\\.\\.") (let ((msg (format "Preprocessing: %s" (match-string 1 buffer)))) (haskell-interactive-mode-echo (haskell-process-session process) msg) (haskell-mode-message-line msg))) ((haskell-process-consume process "Linking \\(.+?\\) \\.\\.\\.") (let ((msg (format "Linking: %s" (match-string 1 buffer)))) (haskell-interactive-mode-echo (haskell-process-session process) msg) (haskell-mode-message-line msg))) ((haskell-process-consume process "\nBuilding \\(.+?\\)\\.\\.\\.") (let ((msg (format "Building: %s" (match-string 1 buffer)))) (haskell-interactive-mode-echo (haskell-process-session process) msg) (haskell-mode-message-line msg))))) (defun haskell-process-errors-warnings (session process buffer) "Trigger handling type errors or warnings." (cond ((haskell-process-consume process (concat "[\r\n]\\([^ \r\n:][^:\n\r]+\\):\\([0-9]+\\):\\([0-9]+\\)\\(-[0-9]+\\)?:" "[ \n\r]+\\([[:unibyte:][:nonascii:]]+?\\)\n[^ ]")) (haskell-process-set-response-cursor process (- (haskell-process-response-cursor process) 1)) (let* ((buffer (haskell-process-response process)) (file (match-string 1 buffer)) (line (string-to-number (match-string 2 buffer))) (col (match-string 3 buffer)) (col2 (match-string 4 buffer)) (error-msg (match-string 5 buffer)) (warning (string-match "^Warning:" error-msg)) (final-msg (format "%s:%s:%s%s: %s" (haskell-session-strip-dir session file) line col (or col2 "") error-msg))) (funcall (if warning 'haskell-interactive-mode-compile-warning 'haskell-interactive-mode-compile-error) session final-msg) (unless warning (haskell-mode-message-line final-msg)) (haskell-process-trigger-suggestions session error-msg file line)) t))) (defun haskell-process-trigger-suggestions (session msg file line) "Trigger prompting to add any extension suggestions." (cond ((let ((case-fold-search nil)) (string-match " -X\\([A-Z][A-Za-z]+\\)" msg)) (when haskell-process-suggest-language-pragmas (haskell-process-suggest-pragma session "LANGUAGE" (match-string 1 msg) file))) ((string-match " The \\(qualified \\)?import of[ ]`\\([^ ]+\\)' is redundant" msg) (when haskell-process-suggest-remove-import-lines (haskell-process-suggest-remove-import session file (match-string 2 msg) line))) ((string-match "Warning: orphan instance: " msg) (when haskell-process-suggest-no-warn-orphans (haskell-process-suggest-pragma session "OPTIONS" "-fno-warn-orphans" file))) ((string-match "against inferred type `\\[Char\\]'" msg) (when haskell-process-suggest-overloaded-strings (haskell-process-suggest-pragma session "LANGUAGE" "OverloadedStrings" file))))) (defun haskell-process-suggest-remove-import (session file import line) (when (y-or-n-p (format "The import line `%s' is redundant. Remove? " import)) (haskell-process-find-file session file) (save-excursion (goto-char (point-min)) (forward-line (1- line)) (goto-char (line-beginning-position)) (delete-region (line-beginning-position) (line-end-position))))) (defun haskell-process-suggest-pragma (session pragma extension file) "Suggest to add something to the top of the file." (let ((string (format "{-# %s %s #-}" pragma extension))) (when (y-or-n-p (format "Add %s to the top of the file? " string)) (haskell-process-find-file session file) (save-excursion (goto-char (point-min)) (insert (concat string "\n")))))) (defun haskell-process-find-file (session file) "Find the given file in the project." (find-file (cond ((file-exists-p (concat (haskell-session-current-dir session) "/" file)) (concat (haskell-session-current-dir session) "/" file)) ((file-exists-p (concat (haskell-session-cabal-dir session) "/" file)) (concat (haskell-session-cabal-dir session) "/" file)) (t file)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Building the process ;;;###autoload (defun haskell-process-start (session) "Start the inferior Haskell process." (let ((existing-process (get-process (haskell-session-name (haskell-session))))) (when (processp existing-process) (haskell-interactive-mode-echo session "Restarting process ...") (haskell-process-set (haskell-session-process session) 'is-restarting t) (delete-process existing-process))) (let ((process (or (haskell-session-process session) (haskell-process-make (haskell-session-name session)))) (old-queue (haskell-process-get (haskell-session-process session) 'command-queue))) (haskell-session-set-process session process) (haskell-process-set-session process session) (haskell-process-set-cmd process nil) (haskell-process-set (haskell-session-process session) 'is-restarting nil) (let ((default-directory (haskell-session-cabal-dir session))) (haskell-session-pwd session) (haskell-process-set-process process (ecase haskell-process-type ('ghci (haskell-process-log (format "Starting inferior GHCi process %s ..." haskell-process-path-ghci)) (apply #'start-process (append (list (haskell-session-name session) nil haskell-process-path-ghci) haskell-process-args-ghci))) ('cabal-repl (haskell-process-log (format "Starting inferior `cabal repl' process using %s ..." haskell-process-path-cabal)) (apply #'start-process (append (list (haskell-session-name session) nil haskell-process-path-cabal) '("repl") haskell-process-args-cabal-repl))) ('cabal-ghci (haskell-process-log (format "Starting inferior cabal-ghci process using %s ..." haskell-process-path-cabal-ghci)) (start-process (haskell-session-name session) nil haskell-process-path-cabal-ghci)) ('cabal-dev (let ((dir (concat (haskell-session-cabal-dir session) "/cabal-dev"))) (haskell-process-log (format "Starting inferior cabal-dev process %s -s %s ..." haskell-process-path-cabal-dev dir)) (start-process (haskell-session-name session) nil haskell-process-path-cabal-dev "ghci" "-s" dir)))))) (progn (set-process-sentinel (haskell-process-process process) 'haskell-process-sentinel) (set-process-filter (haskell-process-process process) 'haskell-process-filter)) (haskell-process-send-startup process) (unless (eq 'cabal-repl haskell-process-type) ;; "cabal repl" sets the proper CWD (haskell-process-change-dir session process (haskell-session-current-dir session))) (haskell-process-set process 'command-queue (append (haskell-process-get (haskell-session-process session) 'command-queue) old-queue)) process)) (defun haskell-process-clear () "Clear the current process." (interactive) (haskell-process-reset (haskell-process)) (haskell-process-set (haskell-process) 'command-queue nil)) (defun haskell-process-restart () "Restart the inferior Haskell process." (interactive) (haskell-process-reset (haskell-process)) (haskell-process-set (haskell-process) 'command-queue nil) (haskell-process-start (haskell-session))) (defun haskell-kill-session-process (&optional session) "Kill the process." (interactive) (let* ((session (or session (haskell-session))) (existing-process (get-process (haskell-session-name session)))) (when (processp existing-process) (haskell-interactive-mode-echo session "Killing process ...") (haskell-process-set (haskell-session-process session) 'is-restarting t) (delete-process existing-process)))) (defun haskell-process-make (name) "Make an inferior Haskell process." (list (cons 'name name))) ;;;###autoload (defun haskell-process () "Get the current process from the current session." (haskell-session-process (haskell-session))) (defun haskell-process-interrupt () "Interrupt the process (SIGINT)." (interactive) (interrupt-process (haskell-process-process (haskell-process)))) (defun haskell-process-cd (&optional not-interactive) "Change directory." (interactive) (let* ((session (haskell-session)) (dir (haskell-session-pwd session t))) (haskell-process-log (format "Changing directory to %s ...\n" dir)) (haskell-process-change-dir session (haskell-process) dir))) (defun haskell-session-pwd (session &optional change) "Prompt for the current directory." (or (unless change (haskell-session-get session 'current-dir)) (progn (haskell-session-set-current-dir session (haskell-utils-read-directory-name (if change "Change directory: " "Set current directory: ") (or (haskell-session-get session 'current-dir) (haskell-session-get session 'cabal-dir) (if (buffer-file-name) (file-name-directory (buffer-file-name)) "~/")))) (haskell-session-get session 'current-dir)))) (defun haskell-process-change-dir (session process dir) "Change the directory of the current process." (haskell-process-queue-command process (make-haskell-command :state (list session process dir) :go (lambda (state) (haskell-process-send-string (cadr state) (format ":cd %s" (caddr state)))) :complete (lambda (state _) (haskell-session-set-current-dir (car state) (caddr state)) (haskell-interactive-mode-echo (car state) (format "Changed directory: %s" (caddr state))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Process communication (defun haskell-process-send-startup (process) "Send the necessary start messages." (haskell-process-queue-command process (make-haskell-command :state process :go (lambda (process) (haskell-process-send-string process ":set prompt \"> \"") (haskell-process-send-string process "Prelude.putStrLn \"\"") (haskell-process-send-string process ":set -v1")) :complete (lambda (process _) (haskell-interactive-mode-echo (haskell-process-session process) (concat (nth (random (length haskell-process-greetings)) haskell-process-greetings) " (if I break, run M-x haskell-process-restart; config via M-x customize-mode)")))))) (defun haskell-process-sentinel (proc event) "The sentinel for the process pipe." (let ((session (haskell-process-project-by-proc proc))) (when session (let* ((process (haskell-session-process session))) (unless (haskell-process-restarting process) (haskell-process-log (format "Event: %S\n" event)) (haskell-process-log "Process reset.\n") (haskell-process-prompt-restart process)))))) (defun haskell-process-filter (proc response) "The filter for the process pipe." (haskell-process-log (format "<- %S\n" response)) (let ((session (haskell-process-project-by-proc proc))) (when session (when (haskell-process-cmd (haskell-session-process session)) (haskell-process-collect session response (haskell-session-process session)))))) (defun haskell-process-log (msg) "Write MSG to the process log (if enabled)." (when haskell-process-log (with-current-buffer (get-buffer-create "*haskell-process-log*") (goto-char (point-max)) (insert msg)))) (defun haskell-process-project-by-proc (proc) "Find project by process." (find-if (lambda (project) (string= (haskell-session-name project) (process-name proc))) haskell-sessions)) (defun haskell-process-collect (session response process) "Collect input for the response until receives a prompt." (haskell-process-set-response process (concat (haskell-process-response process) response)) (while (haskell-process-live-updates process)) (when (string-match haskell-process-prompt-regex (haskell-process-response process)) (haskell-command-exec-complete (haskell-process-cmd process) (replace-regexp-in-string haskell-process-prompt-regex "" (haskell-process-response process))) (haskell-process-reset process) (haskell-process-trigger-queue process))) (defun haskell-process-reset (process) "Reset the process's state, ready for the next send/reply." (progn (haskell-process-set-response-cursor process 0) (haskell-process-set-response process "") (haskell-process-set-cmd process nil))) (defun haskell-process-consume (process regex) "Consume a regex from the response and move the cursor along if succeed." (when (string-match regex (haskell-process-response process) (haskell-process-response-cursor process)) (haskell-process-set-response-cursor process (match-end 0)) t)) (defun haskell-process-send-string (process string) "Try to send a string to the process's process. Ask to restart if it's not running." (let ((child (haskell-process-process process))) (if (equal 'run (process-status child)) (let ((out (concat string "\n"))) (haskell-process-log (format "-> %S\n" out)) (process-send-string child out)) (unless (haskell-process-restarting process) (haskell-process-prompt-restart process))))) (defun haskell-process-prompt-restart (process) "Prompt to restart the died process." (when (y-or-n-p (format "The Haskell process `%s' has died. Restart? " (haskell-process-name process))) (haskell-process-start (haskell-process-session process)))) (defun haskell-process-live-updates (process) "Process live updates." (haskell-command-exec-live (haskell-process-cmd process) (haskell-process-response process))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Making commands (defun haskell-process-queue-without-filters (process line) "Queue LINE to be sent to PROCESS without bothering to look at the response." (haskell-process-queue-command process (make-haskell-command :state (cons process line) :go (lambda (state) (haskell-process-send-string (car state) (cdr state)))))) (defun haskell-process-queue-command (process command) "Add a command to the process command queue." (haskell-process-cmd-queue-add process command) (haskell-process-trigger-queue process)) (defun haskell-process-trigger-queue (process) "Trigger the next command in the queue to be ran if there is no current command." (if (and (haskell-process-process process) (process-live-p (haskell-process-process process))) (unless (haskell-process-cmd process) (let ((cmd (haskell-process-cmd-queue-pop process))) (when cmd (haskell-process-set-cmd process cmd) (haskell-command-exec-go cmd)))) (progn (haskell-process-reset process) (haskell-process-set (haskell-process) 'command-queue nil) (haskell-process-prompt-restart process)))) (defun haskell-process-queue-flushed-p (process) "Return t if command queue has been completely processed." (not (or (haskell-process-cmd-queue process) (haskell-process-cmd process)))) (defun haskell-process-queue-flush (process) "Block till PROCESS' command queue has been completely processed. This uses `accept-process-output' internally." (while (not (haskell-process-queue-flushed-p process)) (haskell-process-trigger-queue process) (accept-process-output (haskell-process-process process) 1))) (defun haskell-process-queue-sync-request (process reqstr) "Queue submitting REQSTR to PROCESS and return response blockingly." (let ((cmd (make-haskell-command :state (cons nil process) :go `(lambda (s) (haskell-process-send-string (cdr s) ,reqstr)) :complete 'setcar))) (haskell-process-queue-command process cmd) (haskell-process-queue-flush process) (car-safe (haskell-command-state cmd)))) (defun haskell-process-get-repl-completions (process inputstr) "Perform `:complete repl ...' query for INPUTSTR using PROCESS." (let* ((reqstr (concat ":complete repl " (haskell-str-literal-encode inputstr))) (rawstr (haskell-process-queue-sync-request process reqstr))) (if (string-prefix-p "unknown command " rawstr) (error "GHCi lacks `:complete' support") (let* ((s1 (split-string rawstr "\r?\n")) (cs (mapcar #'haskell-str-literal-decode (cdr s1))) (h0 (car s1))) ;; " " (unless (string-match "\\`\\([0-9]+\\) \\([0-9]+\\) \\(\".*\"\\)\\'" h0) (error "Invalid `:complete' response")) (let ((cnt1 (match-string 1 h0)) (h1 (haskell-str-literal-decode (match-string 3 h0)))) (unless (= (string-to-number cnt1) (length cs)) (error "Lengths inconsistent in `:complete' reponse")) (cons h1 cs)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Accessing the process (defun haskell-process-get (process key) "Get the PROCESS's KEY value. Returns nil if KEY not set." (cdr (assq key process))) (defun haskell-process-set (process key value) "Set the PROCESS's KEY to VALUE. Returns newly set VALUE." (if process (let ((cell (assq key process))) (if cell (setcdr cell value) ; modify cell in-place (setcdr process (cons (cons key value) (cdr process))) ; new cell value)) (display-warning 'haskell-interactive "`haskell-process-set' called with nil process"))) ;; Wrappers using haskell-process-{get,set} (defun haskell-process-set-process (p v) "Set the process's inferior process." (haskell-process-set p 'inferior-process v)) (defun haskell-process-process (p) "Get the process child." (haskell-process-get p 'inferior-process)) (defun haskell-process-name (p) "Get the process name." (haskell-process-get p 'name)) (defun haskell-process-cmd (p) "Get the process's current command. Return nil if no current command." (haskell-process-get p 'current-command)) (defun haskell-process-set-cmd (p v) "Set the process's current command." (haskell-process-set p 'current-command v)) (defun haskell-process-response (p) "Get the process's current response." (haskell-process-get p 'current-response)) (defun haskell-process-session (p) "Get the process's current session." (haskell-process-get p 'session)) (defun haskell-process-set-response (p v) "Set the process's current response." (haskell-process-set p 'current-response v)) (defun haskell-process-set-session (p v) "Set the process's current session." (haskell-process-set p 'session v)) (defun haskell-process-response-cursor (p) "Get the process's current response cursor." (haskell-process-get p 'current-response-cursor)) (defun haskell-process-set-response-cursor (p v) "Set the process's response cursor." (haskell-process-set p 'current-response-cursor v)) ;; low-level command queue operations (defun haskell-process-restarting (process) "Is the PROCESS restarting?" (haskell-process-get process 'is-restarting)) (defun haskell-process-cmd-queue (process) "Get the PROCESS' command queue. New entries get added to the end of the list. Use `haskell-process-cmd-queue-add' and `haskell-process-cmd-queue-pop' to modify the command queue." (haskell-process-get process 'command-queue)) (defun haskell-process-cmd-queue-add (process cmd) "Add CMD to end of PROCESS's command queue." (check-type cmd haskell-command) (haskell-process-set process 'command-queue (append (haskell-process-cmd-queue process) (list cmd)))) (defun haskell-process-cmd-queue-pop (process) "Pop the PROCESS' next entry from command queue. Returns nil if queue is empty." (let ((queue (haskell-process-cmd-queue process))) (when queue (haskell-process-set process 'command-queue (cdr queue)) (car queue)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Accessing commands -- using cl 'defstruct' (defstruct haskell-command "Data structure representing a command to be executed when with a custom state and three callback." ;; hold the custom command state ;; state :: a state ;; called when to execute a command ;; go :: a -> () go ;; called whenever output was collected from the haskell process ;; live :: a -> Response -> Bool live ;; called when the output from the haskell process indicates that the command ;; is complete ;; complete :: a -> Response -> () complete) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Accessing commands (defun haskell-command-exec-go (command) "Call the command's go function." (let ((go-func (haskell-command-go command))) (when go-func (funcall go-func (haskell-command-state command))))) (defun haskell-command-exec-complete (command response) "Call the command's complete function." (let ((comp-func (haskell-command-complete command))) (when comp-func (funcall comp-func (haskell-command-state command) response)))) (defun haskell-command-exec-live (command response) "Trigger the command's live updates callback." (let ((live-func (haskell-command-live command))) (when live-func (funcall live-func (haskell-command-state command) response)))) (provide 'haskell-process) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-process.el ends here haskell-mode-13.10/haskell-session.el000066400000000000000000000307741225210037200175160ustar00rootroot00000000000000;;; haskell-session.el --- Haskell sessions ;; Copyright (C) 2011-2012 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ;; Boston, MA 02110-1301, USA. ;;; Commentary: ;;; Todo: ;;; Code: (require 'haskell-cabal) (require 'haskell-string) (with-no-warnings (require 'cl)) (declare-function haskell-interactive-mode "haskell-interactive-mode" ()) (declare-function haskell-kill-session-process "haskell-process" (&optional session)) (declare-function haskell-process-start "haskell-process" (session)) (declare-function haskell-process-cd "haskell-process" (&optional not-interactive)) ;; Dynamically scoped variables. (defvar haskell-process-type) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Globals (defvar haskell-sessions (list) "All Haskell sessions in the Emacs session.") (defun haskell-session-tags-filename (session) "Get the filename for the TAGS file." (concat (haskell-session-cabal-dir session) "/TAGS")) ;;;###autoload (defun haskell-session-all-modules (&optional dontcreate) "Get all modules -- installed or in the current project. If DONTCREATE is non-nil don't create a new session." (append (haskell-session-installed-modules dontcreate) (haskell-session-project-modules dontcreate))) ;;;###autoload (defun haskell-session-installed-modules (&optional dontcreate) "Get the modules installed in the current package set. If DONTCREATE is non-nil don't create a new session." ;; TODO: Again, this makes HEAVY use of unix utilities. It'll work ;; fine in Linux, probably okay on OS X, and probably not at all on ;; Windows. Again, if someone wants to test on Windows and come up ;; with alternatives that's OK. ;; ;; Ideally all these package queries can be provided by a Haskell ;; program based on the Cabal API. Possibly as a nice service. Such ;; a service could cache and do nice things like that. For now, this ;; simple shell script takes us far. ;; ;; Probably also we can take the code from inferior-haskell-mode. ;; ;; Ugliness aside, if it saves us time to type it's a winner. ;; ;; FIXME/TODO: add support for (eq 'cabal-repl haskell-process-type) (require 'haskell-process) ; hack for accessing haskell-process-type (let ((modules (shell-command-to-string (format "%s | %s | %s" (if (eq 'cabal-dev haskell-process-type) (if (or (not dontcreate) (haskell-session-maybe)) (format "cabal-dev -s %s/cabal-dev ghc-pkg dump" (haskell-session-cabal-dir (haskell-session))) "echo ''") "ghc-pkg dump") "egrep '^(exposed-modules: | )[A-Z]'" "cut -c18-")))) (split-string modules))) (defun haskell-session-project-modules (&optional dontcreate) "Get the modules of the current project. If DONTCREATE is non-nil don't create a new session." (if (or (not dontcreate) (haskell-session-maybe)) (let* ((session (haskell-session)) (modules (shell-command-to-string (format "%s && %s" (format "cd %s" (haskell-session-cabal-dir session)) ;; TODO: Use a different, better source. Possibly hasktags or some such. ;; TODO: At least make it cross-platform. Linux ;; (and possibly OS X) have egrep, Windows ;; doesn't -- or does it via Cygwin or MinGW? ;; This also doesn't handle module\nName. But those gits can just cut it out! "egrep '^module[\t\r ]+[^(\t\r ]+' . -r -I --include='*.*hs' --include='*.hsc' -s -o -h | sed 's/^module[\t\r ]*//' | sort | uniq")))) (split-string modules)))) (defun haskell-session-kill (&optional leave-interactive-buffer) "Kill the session process and buffer, delete the session. 0. Prompt to kill all associated buffers. 1. Kill the process. 2. Kill the interactive buffer. 3. Walk through all the related buffers and set their haskell-session to nil. 4. Remove the session from the sessions list." (interactive) (let* ((session (haskell-session)) (name (haskell-session-name session)) (also-kill-buffers (y-or-n-p (format "Killing `%s'. Also kill all associated buffers?" name)))) (haskell-kill-session-process session) (unless leave-interactive-buffer (kill-buffer (haskell-session-interactive-buffer session))) (loop for buffer in (buffer-list) do (with-current-buffer buffer (when (and (boundp 'haskell-session) (string= (haskell-session-name haskell-session) name)) (setq haskell-session nil) (when also-kill-buffers (kill-buffer))))) (setq haskell-sessions (remove-if (lambda (session) (string= (haskell-session-name session) name)) haskell-sessions)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Finding/clearing the session ;; Used internally (defvar haskell-session) ;;;###autoload (defun haskell-session-maybe () "Maybe get the Haskell session, return nil if there isn't one." (if (default-boundp 'haskell-session) haskell-session (setq haskell-session nil))) ;;;###autoload (defun haskell-session () "Get the Haskell session, prompt if there isn't one or fail." (or (haskell-session-maybe) (haskell-session-assign (or (haskell-session-from-buffer) (haskell-session-new-assume-from-cabal) (haskell-session-choose) (haskell-session-new))))) (defun haskell-session-new-assume-from-cabal () "Prompt to create a new project based on a guess from the nearest Cabal file." (when (y-or-n-p (format "Start a new project named “%s”? " (haskell-session-default-name))) (haskell-session-make (haskell-session-default-name)))) (defun haskell-session-from-buffer () "Get the session based on the buffer." (when (and (buffer-file-name) (consp haskell-sessions)) (reduce (lambda (acc a) (if (haskell-is-prefix-of (haskell-session-cabal-dir a) (file-name-directory (buffer-file-name))) (if acc (if (and (> (length (haskell-session-cabal-dir a)) (length (haskell-session-cabal-dir acc)))) a acc) a) acc)) haskell-sessions :initial-value nil))) (defun haskell-session-new () "Make a new session." (let ((name (read-from-minibuffer "Project name: " (haskell-session-default-name)))) (when (not (string= name "")) (haskell-session-make name)))) (defun haskell-session-default-name () "Generate a default project name for the new project prompt." (let ((file (haskell-cabal-find-file))) (or (when file (downcase (file-name-sans-extension (file-name-nondirectory file)))) "haskell"))) (defun haskell-session-assign (session) "Set the current session." (set (make-local-variable 'haskell-session) session)) (defun haskell-session-choose () "Find a session by choosing from a list of the current sessions." (when haskell-sessions (let* ((session-name (ido-completing-read "Choose Haskell session: " (mapcar 'haskell-session-name haskell-sessions))) (session (find-if (lambda (session) (string= (haskell-session-name session) session-name)) haskell-sessions))) session))) (defun haskell-session-clear () "Clear the buffer of any Haskell session choice." (set (make-local-variable 'haskell-session) nil)) (defun haskell-session-change () "Change the session for the current buffer." (interactive) (haskell-session-clear) (haskell-session-assign (or (haskell-session-new-assume-from-cabal) (haskell-session-choose) (haskell-session-new)))) (defun haskell-session-strip-dir (session file) "Strip the load dir from the file path." (let ((cur-dir (haskell-session-current-dir session))) (if (> (length file) (length cur-dir)) (if (string= (substring file 0 (length cur-dir)) cur-dir) (replace-regexp-in-string "^[/\\]" "" (substring file (length cur-dir))) file) file))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Building the session (defun haskell-session-make (name) "Make a Haskell session." (let ((session (set (make-local-variable 'haskell-session) (list (cons 'name name))))) (add-to-list 'haskell-sessions session) (haskell-process-start session) session)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Accessing the session (defun haskell-session-name (s) "Get the session name." (haskell-session-get s 'name)) (defun haskell-session-interactive-buffer (s) "Get the session interactive buffer." (let ((buffer (haskell-session-get s 'interactive-buffer))) (if (and buffer (buffer-live-p buffer)) buffer (let ((buffer (get-buffer-create (format "*%s*" (haskell-session-name s))))) (haskell-session-set-interactive-buffer s buffer) (with-current-buffer buffer (haskell-interactive-mode) (haskell-session-assign s)) (switch-to-buffer-other-window buffer) buffer)))) (defun haskell-session-set-interactive-buffer (s v) "Set the session interactive buffer." (haskell-session-set s 'interactive-buffer v)) (defun haskell-session-set-process (s v) "Set the session process." (haskell-session-set s 'process v)) ;;;###autoload (defun haskell-session-process (s) "Get the session process." (haskell-session-get s 'process)) (defun haskell-session-set-cabal-dir (s v) "Set the session cabal-dir." (let ((true-path (file-truename v))) (haskell-session-set s 'cabal-dir true-path) (haskell-session-set-cabal-checksum s true-path))) (defun haskell-session-set-current-dir (s v) "Set the session current directory." (let ((true-path (file-truename v))) (haskell-session-set s 'current-dir true-path))) (defun haskell-session-set-cabal-checksum (s cabal-dir) "Set the session checksum of .cabal files" (haskell-session-set s 'cabal-checksum (haskell-cabal-compute-checksum cabal-dir))) (defun haskell-session-current-dir (s) "Get the session current directory." (let ((dir (haskell-session-get s 'current-dir))) (or dir (haskell-process-cd t)))) (defun haskell-session-cabal-dir (s) "Get the session cabal-dir." (let ((dir (haskell-session-get s 'cabal-dir))) (if dir dir (let ((set-dir (haskell-cabal-get-dir))) (if set-dir (progn (haskell-session-set-cabal-dir s set-dir) set-dir) (haskell-session-cabal-dir s)))))) (defun haskell-session-get (session key) "Get the SESSION's KEY value. Returns nil if KEY not set." (cdr (assq key session))) (defun haskell-session-set (session key value) "Set the SESSION's KEY to VALUE. Returns newly set VALUE." (let ((cell (assq key session))) (if cell (setcdr cell value) ; modify cell in-place (setcdr session (cons (cons key value) (cdr session))) ; new cell value))) (provide 'haskell-session) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-session.el ends here haskell-mode-13.10/haskell-show.el000066400000000000000000000255151225210037200170100ustar00rootroot00000000000000;;; haskell-show.el --- A pretty printer for Haskell Show values ;; Copyright (C) 2011 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This program is free software: you can redistribute it and/or ;; modify it under the terms of the GNU General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see ;; . ;;; Commentary: ;; It doesn't support some number literals (probably). I'm not ;; precisely sure what values Show will always produce. There is ;; however a test suite available, so patches for extra Show support ;; is welcome and should be easy to test. ;;; Code: (defvar sexp-show "sexp-show") (require 'haskell-string) (with-no-warnings (require 'cl)) (defun haskell-show-replace-region () "Replace the given region with a pretty printed version." (interactive) (haskell-show-replace (region-beginning) (region-end))) ;;;###autoload (defun haskell-show-replace (start end) "Replace the given region containing a Show value with a pretty printed collapsible version." (let ((text (buffer-substring-no-properties start end))) (goto-char start) (delete-region start end) (haskell-show-parse-and-insert text))) ;;;###autoload (defun haskell-show-parse-and-insert (given) "Parse a `string' containing a Show instance value and insert it pretty printed into the current buffer." (when (not (string= "" (haskell-trim given))) (let ((current-column (- (point) (line-beginning-position))) (result (haskell-show-parse given))) (if (string-match "^[\\(]" result) (let ((v (read result))) (if (equal (car v) 'arbitrary) (insert given) (haskell-show-insert-pretty current-column v))) (insert given))))) ;;;###autoload (defun haskell-show-parse (given) "Parse the given input into a tree." (with-temp-buffer (insert given) (shell-command-on-region (point-min) (point-max) sexp-show t) (buffer-substring-no-properties (point-min) (point-max)))) (defun haskell-show-insert-pretty (column tree &optional parens) "Insert a Show `tree' into the current buffer with collapsible nodes." (case (car tree) ('list (let ((start (point))) (insert "[") (haskell-show-mapcar/i (lambda (x i len) (haskell-show-insert-pretty (+ column 1) x) (unless (> i (- len 2)) (if (< (+ column (length (haskell-show-pretty tree parens))) 80) (insert ",") (insert (concat ",\n" (haskell-show-indent (+ 1 column) "")))))) (cdr tree)) (insert "]"))) ('tuple (let ((start (point))) (insert "(") (haskell-show-mapcar/i (lambda (x i len) (haskell-show-insert-pretty (+ column 1) x) (unless (> i (- len 2)) (if (< (+ column (length (haskell-show-pretty tree parens))) 80) (insert ",") (insert (concat ",\n" (haskell-show-indent (+ 1 column) "")))))) (cdr tree)) (insert ")"))) ('record (let ((record (cdr tree)) (overlay (list 'nil))) (insert (if parens "(" "")) (let ((link-start (point))) (insert (car record)) (let ((button (make-text-button link-start (point) :type 'haskell-show-toggle-button))) (put-text-property link-start (point) 'face 'font-lock-type-face) (button-put button 'overlay overlay))) (insert " {\n") (let ((curly-start (1- (point))) (show-len (+ column (length (haskell-show-pretty tree parens))))) (haskell-show-mapcar/i (lambda (field i len) (insert (haskell-show-indent (if (and (> i 0) (< show-len 80)) 0 column) (car field))) (insert " = ") (put-text-property (- (point) 3) (point) 'face 'font-lock-constant-face) (haskell-show-insert-pretty (if (< show-len 80) 0 (+ (length (car field)) column 3)) (cdr field)) (unless (> i (- len 2)) (if (< show-len 80) (insert ", ") (insert ",\n")))) (cdr record)) (insert (concat "\n" (haskell-show-indent column "}"))) (progn (setf (car overlay) (make-overlay curly-start (- (point) 1) nil t)) (overlay-put (car overlay) 'invisible t)) (insert (if parens ")" ""))))) ('num (let ((num-start (point))) (insert (format "%d" (cdr tree))) (put-text-property num-start (point) 'face 'font-lock-constant-face))) ('string (let ((str-start (point))) (insert "\"") (if (< (+ column (length (cdr tree))) 60) (progn (insert (format "%s" (cdr tree))) (put-text-property (+ 1 str-start) (point) 'face 'font-lock-string-face)) (progn (insert "…") (insert (format "%s" (cdr tree))) (let ((overlay (make-overlay (+ 2 str-start) (point) nil t))) (overlay-put overlay 'invisible t) (put-text-property (+ 2 str-start) (point) 'face 'font-lock-string-face) (let ((button (make-text-button (+ 1 str-start) (+ 2 str-start) :type 'haskell-show-toggle-button))) (put-text-property (+ 1 str-start) (+ 2 str-start) 'face 'font-lock-keyword-face) (button-put button 'overlay (list overlay)) (button-put button 'hide-on-click t))))) (insert "\""))) ('data (let ((data (cdr tree))) (insert (if parens "(" "")) (let ((cons-start (point))) (insert (car data)) (put-text-property cons-start (point) 'face 'font-lock-type-face)) (unless (null (cdr data)) (progn (insert " ") (haskell-show-mapcar/i (lambda (x i len) (haskell-show-insert-pretty column x t) (unless (> i (- len 2)) (insert " "))) (cdr data)))) (insert (if parens ")" "")))) ('char (progn (insert "'") (insert (char-to-string (cdr tree))) (put-text-property (- (point) 1) (point) 'face 'font-lock-string-face) (insert "'"))) ('arbitrary (let ((start (point))) (insert (cdr tree)) (put-text-property start (point) 'face 'font-lock-comment-face))) (otherwise (error "Unsupported node type: %S" tree)))) (define-button-type 'haskell-show-toggle-button 'action 'haskell-show-toggle-button-callback 'follow-link t 'help-echo "Click to expand…") (defun haskell-show-toggle-button-callback (btn) "The callback to toggle the overlay visibility." (let ((overlay (button-get btn 'overlay))) (when overlay (overlay-put (car overlay) 'invisible (not (overlay-get (car overlay) 'invisible))))) (let ((hide (button-get btn 'remove-on-click))) (when hide (button-put btn 'invisible t)))) (defun haskell-show-pretty (tree &optional parens) "Show a Show `tree'." (case (car tree) ('list (format "[%s]" (mapconcat (lambda (x) (haskell-show-pretty x)) (cdr tree) ","))) ('record (let ((record (cdr tree))) (format "%s%s {%s}%s" (if parens "(" "") (car record) (mapconcat (lambda (field) (format "%s = %s" (car field) (haskell-show-pretty (cdr field)))) (cdr record) ", ") (if parens ")" "")))) ('num (format "%s" (cdr tree))) ('string (format "%S" (cdr tree))) ('data (let ((data (cdr tree))) (format "%s%s%s%s" (if parens "(" "") (car data) (if (null (cdr data)) "" (concat " " (mapconcat (lambda (x) (haskell-show-pretty x t)) (cdr data) " "))) (if parens ")" "")))) ('tuple (format "(%s)" (mapconcat (lambda (x) (haskell-show-pretty x)) (cdr tree) ","))) ('char (format "'%s'" (if (= (cdr tree) ?') "\\'" (char-to-string (cdr tree))))) ('arbitrary (cdr tree)) (otherwise (error "Unsupported node type: %S" tree)))) (defun haskell-show-mapcar/i (f xs) "Map `f' across `xs' giving the index and length to `f' as extra parameters." (let ((len (length xs)) (i 0)) (mapcar (lambda (x) (funcall f x i len) (setq i (1+ i))) xs))) (defun haskell-show-indent (n s) "Indent a string `s' at colum `n'." (concat (make-string n ? ) s)) (provide 'haskell-show) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; haskell-show.el ends here haskell-mode-13.10/haskell-simple-indent.el000066400000000000000000000161431225210037200205750ustar00rootroot00000000000000;;; haskell-simple-indent.el --- Simple indentation module for Haskell Mode ;; Copyright (C) 1998 Heribert Schuetz, Graeme E Moss ;; Author: Heribert Schuetz ;; Graeme E Moss ;; Keywords: indentation files Haskell ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; Purpose: ;; ;; To support simple indentation of Haskell scripts. ;; ;; ;; Installation: ;; ;; To bind TAB to the indentation command for all Haskell buffers, add ;; this to .emacs: ;; ;; (add-hook 'haskell-mode-hook 'turn-on-haskell-simple-indent) ;; ;; Otherwise, call `turn-on-haskell-simple-indent'. ;; ;; ;; Customisation: ;; ;; None supported. ;; ;; ;; History: ;; ;; If you have any problems or suggestions, after consulting the list ;; below, email gem@cs.york.ac.uk quoting the version of you are ;; using, the version of Emacs you are using, and a small example of ;; the problem or suggestion. ;; ;; Version 1.0: ;; Brought over from Haskell mode v1.1. ;; ;; Present Limitations/Future Work (contributions are most welcome!): ;; ;; (None so far.) ;;; Code: ;; All functions/variables start with ;; `(turn-(on/off)-)haskell-simple-indent'. (require 'haskell-mode) (defgroup haskell-simple-indent nil "Simple Haskell indentation." :link '(custom-manual "(haskell-mode)Indentation") :group 'haskell :prefix "haskell-simple-indent-") ;; Version. (defconst haskell-simple-indent-version "1.2" "`haskell-simple-indent' version number.") (defun haskell-simple-indent-version () "Echo the current version of `haskell-simple-indent' in the minibuffer." (interactive) (message "Using haskell-simple-indent version %s" haskell-simple-indent-version)) ;; Partly stolen from `indent-relative' in indent.el: (defun haskell-simple-indent () "Space out to under next visible indent point. Indent points are positions of non-whitespace following whitespace in lines preceeding point. A position is visible if it is to the left of the first non-whitespace of every nonblank line between the position and the current line. If there is no visible indent point beyond the current column, `tab-to-tab-stop' is done instead." (interactive) (let* ((start-column (current-column)) (invisible-from nil) ; `nil' means infinity here (indent (catch 'haskell-simple-indent-break (save-excursion (while (progn (beginning-of-line) (not (bobp))) (forward-line -1) (if (not (looking-at "[ \t]*\n")) (let ((this-indentation (current-indentation))) (if (or (not invisible-from) (< this-indentation invisible-from)) (if (> this-indentation start-column) (setq invisible-from this-indentation) (let ((end (line-beginning-position 2))) (move-to-column start-column) ;; Is start-column inside a tab on this line? (if (> (current-column) start-column) (backward-char 1)) (or (looking-at "[ \t]") (skip-chars-forward "^ \t" end)) (skip-chars-forward " \t" end) (let ((col (current-column))) (throw 'haskell-simple-indent-break (if (or (= (point) end) (and invisible-from (> col invisible-from))) invisible-from col))))))))))))) (if indent (let ((opoint (point-marker))) (indent-line-to indent) (if (> opoint (point)) (goto-char opoint)) (set-marker opoint nil)) (tab-to-tab-stop)))) (defun haskell-simple-indent-backtab () "Indent backwards. Dual to `haskell-simple-indent'." (interactive) (let ((current-point (point)) (i 0) (x 0)) (goto-char (line-beginning-position)) (save-excursion (while (< (point) current-point) (haskell-simple-indent) (setq i (+ i 1)))) (while (< x (- i 1)) (haskell-simple-indent) (setq x (+ x 1))))) (defun haskell-simple-indent-newline-same-col () "Make a newline and go to the same column as the current line." (interactive) (let ((point (point))) (let ((start-end (save-excursion (let* ((start (line-beginning-position)) (end (progn (goto-char start) (search-forward-regexp "[^ ]" (line-end-position) t 1)))) (when end (cons start (1- end))))))) (if start-end (progn (newline) (insert (buffer-substring-no-properties (car start-end) (cdr start-end)))) (newline))))) (defun haskell-simple-indent-newline-indent () "Make a newline on the current column and indent on step." (interactive) (haskell-simple-indent-newline-same-col) (insert (make-string haskell-indent-spaces ? ))) ;;;###autoload (define-minor-mode haskell-simple-indent-mode "Simple Haskell indentation mode that uses simple heuristic. In this minor mode, `indent-for-tab-command' (bound to by default) will move the cursor to the next indent point in the previous nonblank line, whereas `haskell-simple-indent-backtab' \ (bound to by default) will move the cursor the previous indent point. An indent point is a non-whitespace character following whitespace. Runs `haskell-simple-indent-hook' on activation." :lighter " Ind" :group 'haskell-simple-indent :keymap '(([backtab] . haskell-simple-indent-backtab)) (kill-local-variable 'indent-line-function) (when haskell-simple-indent-mode (set (make-local-variable 'indent-line-function) 'haskell-simple-indent) (run-hooks 'haskell-simple-indent-hook))) ;; The main functions. ;;;###autoload (defun turn-on-haskell-simple-indent () "Turn on function `haskell-simple-indent-mode'." (interactive) (haskell-simple-indent-mode)) (defun turn-off-haskell-simple-indent () "Turn off function `haskell-simple-indent-mode'." (interactive) (haskell-simple-indent-mode 0)) ;; Provide ourselves: (provide 'haskell-simple-indent) ;;; haskell-simple-indent.el ends here haskell-mode-13.10/haskell-sort-imports.el000066400000000000000000000064251225210037200205110ustar00rootroot00000000000000;;; haskell-sort-imports.el --- Sort the list of Haskell imports at the point alphabetically ;; Copyright (C) 2010 Chris Done ;; Author: Chris Done ;; This file is not part of GNU Emacs. ;; This program is free software: you can redistribute it and/or ;; modify it under the terms of the GNU General Public License as ;; published by the Free Software Foundation, either version 3 of ;; the License, or (at your option) any later version. ;; This program is distributed in the hope that it will be ;; useful, but WITHOUT ANY WARRANTY; without even the implied ;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ;; PURPOSE. See the GNU General Public License for more details. ;; You should have received a copy of the GNU General Public ;; License along with this program. If not, see ;; . ;;; Commentary: ;; If the region is active it sorts the imports within the ;; region. ;; This will align and sort the columns of the current import ;; list. It's more or less the coolest thing on the planet. ;;; Code: (defvar haskell-sort-imports-regexp (concat "^\\(import[ ]+\\)" "\\(qualified \\)?" "[ ]*\\(\"[^\"]*\" \\)?" "[ ]*\\([A-Za-z0-9_.']*.*\\)")) ;;;###autoload (defun haskell-sort-imports () "Sort the import list at the point." (interactive) (when (haskell-sort-imports-line-match) (let ((current-line (buffer-substring-no-properties (line-beginning-position) (line-end-position))) (col (current-column))) (if (use-region-p) (haskell-sort-imports-sort-imports-at (region-beginning) (region-end) t current-line col) (haskell-sort-imports-sort-imports-at (save-excursion (haskell-sort-imports-goto-modules-start/end 'previous-line) (point)) (save-excursion (haskell-sort-imports-goto-modules-start/end 'next-line) (point)) nil current-line col))))) (defun haskell-sort-imports-sort-imports-at (begin end region current-line col) (save-excursion (sort-regexp-fields nil haskell-sort-imports-regexp "\\4" begin end)) (when (not region) (let ((line (save-excursion (goto-char end) (search-backward current-line)))) (goto-char (+ line col))))) (defun haskell-sort-imports-line-match () "Try to match the current line as a regexp." (let ((line (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (if (string-match "^import " line) line nil))) (defun haskell-sort-imports-goto-modules-start/end (direction) "Skip a bunch of consequtive import lines up/down." (while (not (or (equal (point) (point-max)) (not (haskell-sort-imports-line-match)))) (funcall direction))) (provide 'haskell-sort-imports) ;;; haskell-sort-imports.el ends here haskell-mode-13.10/haskell-str.el000066400000000000000000000210431225210037200166300ustar00rootroot00000000000000;;; haskell-str.el --- Haskell related string utilities ;; Copyright (C) 2013 Herbert Valerio Riedel ;; Author: Herbert Valerio Riedel ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or ;; (at your option) any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;;; Todo: ;; - write ERT tests ;;; Code: (defun haskell-str-trim (string) "Remove whitespace around STRING. A Whitespace character is defined in the Haskell Report as follows whitechar -> newline | vertab | space | tab | uniWhite newline -> return linefeed | return | linefeed | formfeed uniWhite -> any Unicode character defined as whitespace Note: The implementation currently only supports ASCII white-space characters, i.e. the implemention doesn't consider uniWhite." (let ((s1 (if (string-match "[\t\n\v\f\r ]+\\'" string) (replace-match "" t t string) string))) (if (string-match "\\`[\t\n\v\f\r ]+" s1) (replace-match "" t t s1) s1))) (defun haskell-str-only-spaces-p (string) "Return t if STRING contains only whitespace (or is empty)." (string= "" (haskell-str-trim string))) (defun haskell-str-take (string n) "Return (up to) N character length prefix of STRING." (substring string 0 (min (length string) n))) (defalias 'haskell-str-is-prefix-of-p 'string-prefix-p) (defun haskell-str-is-suffix-of-p (str1 str2 &optional ignore-case) "Return non-nil if STR1 is a suffix of STR2. If IGNORE-CASE is non-nil, the comparison is done without paying attention to case differences. Dual to `haskell-str-is-prefix-of-p'" (let ((pos (- (length str2) (length str1)))) (if (>= pos 0) (eq t (compare-strings str1 nil nil str2 pos nil ignore-case))))) (defconst haskell-str-literal-encode-ascii-array [ "\\NUL" "\\SOH" "\\STX" "\\ETX" "\\EOT" "\\ENQ" "\\ACK" "\\a" "\\b" "\\t" "\\n" "\\v" "\\f" "\\r" "\\SO" "\\SI" "\\DLE" "\\DC1" "\\DC2" "\\DC3" "\\DC4" "\\NAK" "\\SYN" "\\ETB" "\\CAN" "\\EM" "\\SUB" "\\ESC" "\\FS" "\\GS" "\\RS" "\\US" " " "!" "\\\"" "#" "$" "%" "&" "'" "(" ")" "*" "+" "," "-" "." "/" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" ":" ";" "<" "=" ">" "?" "@" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" "[" "\\\\" "]" "^" "_" "`" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "{" "|" "}" "~" "\\DEL" ] "Array of encodings for 7-bit ASCII character points indexed by ASCII value.") (defun haskell-str-literal-encode (str &optional no-quotes) "Encode STR according Haskell escape rules using 7-bit ASCII representation. The serialization has been implement to closely match the behaviour of GHC's Show instance for Strings. If NO-QUOTES is non-nil, omit wrapping result in quotes. This is the dual operation to `haskell-str-literal-decode'." (let ((lastc -1)) (let ((encode (lambda (c) (let ((lc lastc)) (setq lastc c) (if (>= c 128) ;; if non-ASCII code point (format "\\%d" c) ;; else, for ASCII code points (if (or (and (= lc 14) (= c ?H)) ;; "\SO\&H" (and (>= lc 128) (>= c ?0) (<= c ?9))) ;; "\123\&4" (concat "\\&" (aref haskell-str-literal-encode-ascii-array c)) (aref haskell-str-literal-encode-ascii-array c) )))))) (if no-quotes (mapconcat encode str "") (concat "\"" (mapconcat encode str "") "\""))))) (defconst haskell-str-literal-escapes-regexp (concat "[\\]\\(?:" (regexp-opt (append (mapcar (lambda (c) (format "%c" c)) "abfnrtv\\\"'&") ;; "charesc" escape sequences (mapcar (lambda (c) (format "^%c" c)) "ABCDEFGHIJKLMNOPQRSTUVWXYZ@[\\]^_") ;; "cntrl" escape sequences (mapcar (lambda (s) (format "%s" s)) (split-string "NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US SP DEL")))) ;; "ascii" (w\o "cntrl") escape sequences "\\|" "[\t\n\v\f\r ]+[\\]" ;; whitespace gaps "\\|" "[0-9]+" ;; decimal escape sequence "\\|" "o[0-7]+" ;; octal escape sequence "\\|" "x[0-9a-f]+" ;; hex escape sequence "\\)?") ;; everything else is an invalid escape sequence "Regexp for matching escape codes in string literals. See Haskell Report Sect 2.6, URL `http://www.haskell.org/onlinereport/haskell2010/haskellch2.html#x7-200002.6', for more details.") (defconst haskell-str-literal-decode1-table (let ((h (make-hash-table :test 'equal))) (mapc (lambda (c) (puthash (concat "\\" (car c)) (cdr c) h)) '(;; ascii-escapes ("NUL" . "\x00") ("SOH" . "\x01") ("STX" . "\x02") ("ETX" . "\x03") ("EOT" . "\x04") ("ENQ" . "\x05") ("ACK" . "\x06") ("BEL" . "\x07") ("BS" . "\x08") ("HT" . "\x09") ("LF" . "\x0a") ("VT" . "\x0b") ("FF" . "\x0c") ("CR" . "\x0d") ("SO" . "\x0e") ("SI" . "\x0f") ("DLE" . "\x10") ("DC1" . "\x11") ("DC2" . "\x12") ("DC3" . "\x13") ("DC4" . "\x14") ("NAK" . "\x15") ("SYN" . "\x16") ("ETB" . "\x17") ("CAN" . "\x18") ("EM" . "\x19") ("SUB" . "\x1a") ("ESC" . "\x1b") ("FS" . "\x1c") ("GS" . "\x1d") ("RS" . "\x1e") ("US" . "\x1f") ("SP" . "\x20") ("DEL" . "\x7f" ) ;; C-compatible single-char escape sequences ("a" . "\x07") ("b" . "\x08") ("f" . "\x0c") ("n" . "\x0a") ("r" . "\x0d") ("t" . "\x09") ("v" . "\x0b") ;; trivial escapes ("\\" . "\\") ("\"" . "\"") ("'" . "'") ;; "empty" escape ("&" . ""))) h) "Hash table containing irregular escape sequences and their decoded strings. Used by `haskell-str-literal-decode1'.") (defun haskell-str-literal-decode1 (l) "Decode a single string literal escape sequence. L must contain exactly one escape sequence. This is an internal function used by `haskell-str-literal-decode'." (let ((case-fold-search nil)) (cond ((gethash l haskell-str-literal-decode1-table)) ((string-match "\\`[\\][0-9]+\\'" l) (char-to-string (string-to-number (substring l 1) 10))) ((string-match "\\`[\\]x[[:xdigit:]]+\\'" l) (char-to-string (string-to-number (substring l 2) 16))) ((string-match "\\`[\\]o[0-7]+\\'" l) (char-to-string (string-to-number (substring l 2) 8))) ((string-match "\\`[\\]\\^[@-_]\\'" l) (char-to-string (- (aref l 2) ?@))) ;; "cntrl" escapes ((string-match "\\`[\\][\t\n\v\f\r ]+[\\]\\'" l) "") ;; whitespace gap (t (error "Invalid escape sequence"))))) (defun haskell-str-literal-decode (estr &optional no-quotes) "Decode a Haskell string-literal. If NO-QUOTES is nil, ESTR must be surrounded by quotes. This is the dual operation to `haskell-str-literal-encode'." (if (and (not no-quotes) (string-match-p "\\`\"[^\\\"[:cntrl:]]*\"\\'" estr)) (substring estr 1 -1) ;; optimized fast-path for trivial strings (let ((s (if no-quotes ;; else: do general decoding estr (if (string-match-p "\\`\".*\"\\'" estr) (substring estr 1 -1) (error "String literal must be delimited by quotes")))) (case-fold-search nil)) (replace-regexp-in-string haskell-str-literal-escapes-regexp #'haskell-str-literal-decode1 s t t)))) (defun haskell-str-ellipsize (string n) "Return STRING truncated to (at most) N characters. If truncation occured, last character in string is replaced by `…'. See also `haskell-str-take'." (cond ((<= (length string) n) string) ;; no truncation needed ((< n 1) "") (t (concat (substring string 0 (1- n)) "…")))) (provide 'haskell-str) ;;; haskell-str.el ends here haskell-mode-13.10/haskell-string.el000066400000000000000000000007771225210037200173410ustar00rootroot00000000000000;;;###autoload (defun haskell-trim (string) (replace-regexp-in-string "^[ \t\n]+" "" (replace-regexp-in-string "[ \t\n]+$" "" string))) ;;;###autoload (defun haskell-string-take (string n) "Take n chars from string." (substring string 0 (min (length string) n))) ;;;###autoload (defun haskell-is-prefix-of (x y) "Is x string a prefix of y string?" (string= x (substring y 0 (min (length y) (length x))))) (defun haskell-string ()) (provide 'haskell-string) haskell-mode-13.10/haskell-unicode-input-method.el000066400000000000000000000204341225210037200220640ustar00rootroot00000000000000;;; haskell-unicode-input-method.el --- Haskell Unicode helper functions -*- coding: utf-8 -*- ;; Copyright (C) 2010-2011 Roel van Dijk ;; Author: Roel van Dijk ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or ;; (at your option) any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;;; Code: (require 'quail) ;;;###autoload (defun turn-on-haskell-unicode-input-method () "Set input method `haskell-unicode'. See Info node `Unicode(haskell-mode)' for more details." (interactive) (set-input-method "haskell-unicode")) (quail-define-package "haskell-unicode" ;; name "UTF-8" ;; language "\\" ;; title t ;; guidance "Haskell Unicode input method. Designed to be used with the Haskell UnicodeSyntax language extension in combination with the x-unicode-symbols set of packages (base-unicode-symbols and containers-unicode-symbols). " ;; docstring nil ;; translation-keys nil ;; forget-last-selection nil ;; deterministic nil ;; kbd-translate nil ;; show-layout nil ;; create-decode-map nil ;; maximum-shortest nil ;; overlay-plist nil ;; update-translation-function nil ;; conversion-keys t ;; simple ) (quail-define-rules ;; Greek letters ("alpha " ["α"]) ("Alpha " ["Α"]) ("beta " ["β"]) ("Beta " ["Β"]) ("gamma " ["γ"]) ("Gamma " ["Γ"]) ("delta " ["δ"]) ("Delta " ["Δ"]) ("epsilon " ["ε"]) ("Epsilon " ["Ε"]) ("zeta " ["ζ"]) ("Zeta " ["Ζ"]) ("eta " ["η"]) ("Eta " ["Η"]) ("theta " ["θ"]) ("Theta " ["Θ"]) ("iota " ["ι"]) ("Iota " ["Ι"]) ("kappa " ["κ"]) ("Kappa " ["Κ"]) ("lambda " ["λ"]) ("Lambda " ["Λ"]) ("lamda " ["λ"]) ("Lamda " ["Λ"]) ("mu " ["μ"]) ("Mu " ["Μ"]) ("nu " ["ν"]) ("Nu " ["Ν"]) ("xi " ["ξ"]) ("Xi " ["Ξ"]) ("omicron " ["ο"]) ("Omicron " ["Ο"]) ("pi " ["π"]) ("Pi " ["Π"]) ("rho " ["ρ"]) ("Rho " ["Ρ"]) ("sigma " ["σ"]) ("Sigma " ["Σ"]) ("tau " ["τ"]) ("Tau " ["Τ"]) ("upsilon " ["υ"]) ("Upsilon " ["Υ"]) ("phi " ["φ"]) ("Phi " ["Φ"]) ("chi " ["χ"]) ("Chi " ["Χ"]) ("psi " ["ψ"]) ("Psi " ["Ψ"]) ("omega " ["ω"]) ("Omega " ["Ω"]) ("digamma " ["ϝ"]) ("Digamma " ["Ϝ"]) ("san " ["ϻ"]) ("San " ["Ϻ"]) ("qoppa " ["ϙ"]) ("Qoppa " ["Ϙ"]) ("sampi " ["ϡ"]) ("Sampi " ["Ϡ"]) ("stigma " ["ϛ"]) ("Stigma " ["Ϛ"]) ("heta " ["ͱ"]) ("Heta " ["Ͱ"]) ("sho " ["ϸ"]) ("Sho " ["Ϸ"]) ;; Double-struck letters ("|A|" ["𝔸"]) ("|B|" ["𝔹"]) ("|C|" ["ℂ"]) ("|D|" ["𝔻"]) ("|E|" ["𝔼"]) ("|F|" ["𝔽"]) ("|G|" ["𝔾"]) ("|H|" ["ℍ"]) ("|I|" ["𝕀"]) ("|J|" ["𝕁"]) ("|K|" ["𝕂"]) ("|L|" ["𝕃"]) ("|M|" ["𝕄"]) ("|N|" ["ℕ"]) ("|O|" ["𝕆"]) ("|P|" ["ℙ"]) ("|Q|" ["ℚ"]) ("|R|" ["ℝ"]) ("|S|" ["𝕊"]) ("|T|" ["𝕋"]) ("|U|" ["𝕌"]) ("|V|" ["𝕍"]) ("|W|" ["𝕎"]) ("|X|" ["𝕏"]) ("|Y|" ["𝕐"]) ("|Z|" ["ℤ"]) ("|gamma|" ["ℽ"]) ("|Gamma|" ["ℾ"]) ("|pi|" ["ℼ"]) ("|Pi|" ["ℿ"]) ;; Types ("::" ["∷"]) ;; Quantifiers ("forall" ["∀"]) ("exists" ["∃"]) ;; Arrows ("->" ["→"]) ;; ("-->" ["⟶"]) ("<-" ["←"]) ;; ("<--" ["⟵"]) ;; ("<->" ["↔"]) ;; ("<-->" ["⟷"]) ("=>" ["⇒"]) ;; ("==>" ["⟹"]) ;; ("<=" ["⇐"]) ;; ("<==" ["⟸"]) ;; ("<=>" ["⇔"]) ;; ("<==>" ["⟺"]) ;; ("|->" ["↦"]) ;; ("|-->" ["⟼"]) ;; ("<-|" ["↤"]) ;; ("<--|" ["⟻"]) ;; ("|=>" ["⤇"]) ;; ("|==>" ["⟾"]) ;; ("<=|" ["⤆"]) ;; ("<==|" ["⟽"]) ("~>" ["⇝"]) ;; ("~~>" ["⟿"]) ("<~" ["⇜"]) ;; ("<~~" ["⬳"]) ;; (">->" ["↣"]) ;; ("<-<" ["↢"]) ;; ("->>" ["↠"]) ;; ("<<-" ["↞"]) ;; (">->>" ["⤖"]) ;; ("<<-<" ["⬻"]) ;; ("<|-" ["⇽"]) ;; ("-|>" ["⇾"]) ;; ("<|-|>" ["⇿"]) ;; ("<-/-" ["↚"]) ;; ("-/->" ["↛"]) ;; ("<-|-" ["⇷"]) ;; ("-|->" ["⇸"]) ;; ("<-|->" ["⇹"]) ;; ("<-||-" ["⇺"]) ;; ("-||->" ["⇻"]) ;; ("<-||->" ["⇼"]) ;; ("-o->" ["⇴"]) ;; ("<-o-" ["⬰"]) ;; Boolean operators ;; ("not" ["¬"]) ("&&" ["∧"]) ("||" ["∨"]) ;; Relational operators ("==" ["≡"]) ("/=" ["≢" "≠"]) ("<=" ["≤"]) (">=" ["≥"]) ("/<" ["≮"]) ("/>" ["≯"]) ;; Arithmetic ;; (" / " [" ÷ "]) (" * " [" ⋅ "]) ;; Containers / Collections ;; ("++" ["⧺"]) ;; ("+++" ["⧻"]) ;; ("|||" ["⫴"]) ;; ("empty" ["∅"]) ("elem" ["∈"]) ("notElem" ["∉"]) ("member" ["∈"]) ("notMember" ["∉"]) ("union" ["∪"]) ("intersection" ["∩"]) ("isSubsetOf" ["⊆"]) ("isProperSubsetOf" ["⊂"]) ;; Other ;; ("<<" ["≪"]) ;; (">>" ["≫"]) ("<<<" ["⋘"]) (">>>" ["⋙"]) ("<|" ["⊲"]) ("|>" ["⊳"]) ("><" ["⋈"]) ;; ("mempty" ["∅"]) ("mappend" ["⊕"]) ;; ("<*>" ["⊛"]) (" . " [" ∘ "]) ("undefined" ["⊥"]) (":=" ["≔"]) ("=:" ["≕"]) ("=def" ["≝"]) ("=?" ["≟"]) ("..." ["…"]) ;; Braces ;; ("[|" ["〚"]) ;; ("|]" ["〛"]) ;; Numeric subscripts ("_0 " ["₀"]) ("_1 " ["₁"]) ("_2 " ["₂"]) ("_3 " ["₃"]) ("_4 " ["₄"]) ("_5 " ["₅"]) ("_6 " ["₆"]) ("_7 " ["₇"]) ("_8 " ["₈"]) ("_9 " ["₉"]) ;; Numeric superscripts ("^0 " ["⁰"]) ("^1 " ["¹"]) ("^2 " ["²"]) ("^3 " ["³"]) ("^4 " ["⁴"]) ("^5 " ["⁵"]) ("^6 " ["⁶"]) ("^7 " ["⁷"]) ("^8 " ["⁸"]) ("^9 " ["⁹"]) ) (provide 'haskell-unicode-input-method) ;;; haskell-unicode-input-method.el ends here haskell-mode-13.10/haskell-utils.el000066400000000000000000000053031225210037200171610ustar00rootroot00000000000000;;; haskell-utils.el --- General utility functions used by haskell-mode modules ;; Copyright (C) 2013 Herbert Valerio Riedel ;; Author: Herbert Valerio Riedel ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or ;; (at your option) any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; This module's purpose is to provide a place for helper functions ;; which are general enough to be usable by multiple modules and/or ;; to alleviate circular module dependency problems. ;; ;; When possible, functions in this module shall be accompanied by ;; ERT-based unit tests. ;; ;; See also `haskell-str.el' for string utility functions. ;; ;; All symbols in this module have a `haskell-utils-' prefix. ;;; Code: ;; NOTE: This module is supposed to be a leaf-module and shall not ;; require/depend-on any other haskell-mode modules in order to ;; stay at the bottom of the module dependency graph. (defun haskell-utils-read-directory-name (prompt default) "Read directory name and normalize to true absolute path. Refer to `read-directory-name' for the meaning of PROMPT and DEFAULT." (let ((filename (file-truename (read-directory-name prompt default default)))) (concat (replace-regexp-in-string "/$" "" filename) "/"))) (defun haskell-utils-parse-import-statement-at-point () "Return imported module name if on import statement or nil otherwise. This currently assumes that the \"import\" keyword and the module name are on the same line. This function supports the SafeHaskell and PackageImports syntax extensions. Note: doesn't detect if in {--}-style comment." (save-excursion (goto-char (line-beginning-position)) (if (looking-at (concat "[\t ]*import[\t ]+" "\\(safe[\t ]+\\)?" ;; SafeHaskell "\\(qualified[\t ]+\\)?" "\\(\"[^\"]*\"[\t ]+\\)?" ;; PackageImports "\\([[:digit:][:upper:][:lower:].]+\\)")) (match-string-no-properties 4)))) (provide 'haskell-utils) ;;; haskell-utils.el ends here haskell-mode-13.10/haskell-yas.el000066400000000000000000000033521225210037200166170ustar00rootroot00000000000000;;; haskell-yas.el --- Customization support for Luke Hoersten's yasnippets ;; Copyright (C) 2013 John Wiegley, Luke Hoersten ;; Author: John Wiegley ;; Luke Hoersten ;; Keywords: faces files Haskell ;; This file is not part of GNU Emacs. ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; Provides customization variables for Luke Hoersten's yasnippet collection ;; to depend on. ;;; Code: (defgroup haskell-yas nil "Customizations for Luke Hoersten's yasnippet collection for haskell-mode." :group 'haskell :prefix "haskell-yas-") (defcustom haskell-yas-ghc-language-pragmas (split-string (shell-command-to-string "ghc --supported-extensions")) "List of language pragmas supported by the installed version of GHC." :group 'haskell-yas :type '(repeat string)) (defcustom haskell-yas-completing-function 'ido-completing-read "Function to use for completing among alternatives." :group 'haskell-yas :type 'function) ;;;###autoload (defun haskell-yas-complete (&rest args) (apply haskell-yas-completing-function args)) ;; Provide ourselves: (provide 'haskell-yas) ;;; haskell-yas.el ends here haskell-mode-13.10/inf-haskell.el000066400000000000000000001041341225210037200165770ustar00rootroot00000000000000;;; inf-haskell.el --- Interaction with an inferior Haskell process ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc. ;; Author: Stefan Monnier ;; Keywords: Haskell ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; The code is made of 2 parts: a major mode for the buffer that holds the ;; inferior process's session and a minor mode for use in source buffers. ;; Todo: ;; - Check out Shim for ideas. ;; - i-h-load-buffer and i-h-send-region. ;;; Code: (require 'comint) (require 'shell) ; For directory tracking. (require 'compile) (require 'haskell-mode) (require 'haskell-decl-scan) (require 'haskell-cabal) (with-no-warnings (require 'cl)) ;; Dynamically scoped variables. (defvar find-tag-marker-ring) (defgroup inferior-haskell nil "Settings for REPL interaction via `inferior-haskell-mode'" :link '(custom-manual "(haskell-mode)inferior-haskell-mode") :prefix "inferior-haskell-" :prefix "haskell-" :group 'haskell) ;; Here I depart from the inferior-haskell- prefix. ;; Not sure if it's a good idea. (defcustom haskell-program-name ;; Arbitrarily give preference to hugs over ghci. (or (cond ((executable-find "hugs") "hugs \"+.\"") ((executable-find "ghci") "ghci")) "hugs \"+.\"") "The name of the command to start the inferior Haskell process. The command can include arguments." ;; Custom only supports the :options keyword for a few types, e.g. not ;; for string. ;; :options '("hugs \"+.\"" "ghci") :group 'inferior-haskell :type '(choice string (repeat string))) (defconst inferior-haskell-info-xref-re "\t-- Defined at \\(.+\\):\\([0-9]+\\):\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?$") (defconst inferior-haskell-module-re "\t-- Defined in \\(.+\\)$" "Regular expression for matching module names in :info.") (defvar inferior-haskell-multiline-prompt-re "^\\*?[[:upper:]][\\._[:alnum:]]*\\(?: \\*?[[:upper:]][\\._[:alnum:]]*\\)*| " "Regular expression for matching multiline prompt (the one inside :{ ... :} blocks).") (defconst inferior-haskell-error-regexp-alist ;; The format of error messages used by Hugs. `(("^ERROR \"\\(.+?\\)\"\\(:\\| line \\)\\([0-9]+\\) - " 1 3) ;; Format of error messages used by GHCi. ("^\\(.+?\\):\\([0-9]+\\):\\(\\([0-9]+\\):\\)?\\( \\|\n *\\)\\(Warning\\)?" 1 2 4 ,@(if (fboundp 'compilation-fake-loc) '((6) nil (5 '(face nil font-lock-multiline t))))) ;; Runtime exceptions, from ghci. ("^\\*\\*\\* Exception: \\(.+?\\):(\\([0-9]+\\),\\([0-9]+\\))-(\\([0-9]+\\),\\([0-9]+\\)): .*" 1 ,@(if (fboundp 'compilation-fake-loc) '((2 . 4) (3 . 5)) '(2 3))) ;; GHCi uses two different forms for line/col ranges, depending on ;; whether it's all on the same line or not :-( In Emacs-23, I could use ;; explicitly numbered subgroups to merge the two patterns. ("^\\*\\*\\* Exception: \\(.+?\\):\\([0-9]+\\):\\([0-9]+\\)-\\([0-9]+\\): .*" 1 2 ,(if (fboundp 'compilation-fake-loc) '(3 . 4) 3)) ;; Info messages. Not errors per se. ,@(when (fboundp 'compilation-fake-loc) `(;; Other GHCi patterns used in type errors. ("^[ \t]+at \\(.+\\):\\([0-9]+\\):\\([0-9]+\\)-\\([0-9]+\\)$" 1 2 (3 . 4) 0) ;; Foo.hs:318:80: ;; Ambiguous occurrence `Bar' ;; It could refer to either `Bar', defined at Zork.hs:311:5 ;; or `Bar', imported from Bars at Frob.hs:32:0-16 ;; (defined at Location.hs:97:5) ("[ (]defined at \\(.+\\):\\([0-9]+\\):\\([0-9]+\\))?$" 1 2 3 0) ("imported from .* at \\(.+\\):\\([0-9]+\\):\\([0-9]+\\)-\\([0-9]+\\)$" 1 2 (3 . 4) 0) ;; Info xrefs. (,inferior-haskell-info-xref-re 1 2 (3 . 4) 0)))) "Regexps for error messages generated by inferior Haskell processes. The format should be the same as for `compilation-error-regexp-alist'.") (defcustom inferior-haskell-find-project-root t "If non-nil, try and find the project root directory of this file. This will either look for a Cabal file or a \"module\" statement in the file." :group 'inferior-haskell :type 'boolean) (define-derived-mode inferior-haskell-mode comint-mode "Inf-Haskell" "Major mode for interacting with an inferior Haskell process." :group 'inferior-haskell (set (make-local-variable 'comint-prompt-regexp) ;; Whay the backslash in [\\._[:alnum:]]? "^\\*?[[:upper:]][\\._[:alnum:]]*\\(?: \\*?[[:upper:]][\\._[:alnum:]]*\\)*> \\|^λ?> $") (set (make-local-variable 'comint-input-autoexpand) nil) (add-hook 'comint-preoutput-filter-functions 'inferior-haskell-send-decl-post-filter) (add-hook 'comint-output-filter-functions 'inferior-haskell-spot-prompt nil t) ;; Setup directory tracking. (set (make-local-variable 'shell-cd-regexp) ":cd") (condition-case nil (shell-dirtrack-mode 1) (error ;The minor mode function may not exist or not accept an arg. (set (make-local-variable 'shell-dirtrackp) t) (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil 'local))) ;; Setup `compile' support so you can just use C-x ` and friends. (set (make-local-variable 'compilation-error-regexp-alist) inferior-haskell-error-regexp-alist) (set (make-local-variable 'compilation-first-column) 0) ;GHCI counts from 0. (if (and (not (boundp 'minor-mode-overriding-map-alist)) (fboundp 'compilation-shell-minor-mode)) ;; If we can't remove compilation-minor-mode bindings, at least try to ;; use compilation-shell-minor-mode, so there are fewer ;; annoying bindings. (compilation-shell-minor-mode 1) ;; Else just use compilation-minor-mode but without its bindings because ;; things like mouse-2 are simply too annoying. (compilation-minor-mode 1) (let ((map (make-sparse-keymap))) (dolist (keys '([menu-bar] [follow-link])) ;; Preserve some of the bindings. (define-key map keys (lookup-key compilation-minor-mode-map keys))) (add-to-list 'minor-mode-overriding-map-alist (cons 'compilation-minor-mode map))))) (defun inferior-haskell-string-to-strings (string) "Split the STRING into a list of strings." (let ((i (string-match "[\"]" string))) (if (null i) (split-string string) ; no quoting: easy (append (unless (eq i 0) (split-string (substring string 0 i))) (let ((rfs (read-from-string string i))) (cons (car rfs) (inferior-haskell-string-to-strings (substring string (cdr rfs))))))))) (defun inferior-haskell-command (arg) (inferior-haskell-string-to-strings (if (null arg) haskell-program-name (read-string "Command to run haskell: " haskell-program-name)))) (defvar inferior-haskell-buffer nil "The buffer in which the inferior process is running.") (defun inferior-haskell-start-process (command) "Start an inferior haskell process. With universal prefix \\[universal-argument], prompts for a COMMAND, otherwise uses `haskell-program-name'. It runs the hook `inferior-haskell-hook' after starting the process and setting up the inferior-haskell buffer." (interactive (list (inferior-haskell-command current-prefix-arg))) (setq inferior-haskell-buffer (apply 'make-comint "haskell" (car command) nil (cdr command))) (with-current-buffer inferior-haskell-buffer (inferior-haskell-mode) (run-hooks 'inferior-haskell-hook))) (defun inferior-haskell-process (&optional arg) (or (if (buffer-live-p inferior-haskell-buffer) (get-buffer-process inferior-haskell-buffer)) (progn (let ((current-prefix-arg arg)) (call-interactively 'inferior-haskell-start-process)) ;; Try again. (inferior-haskell-process arg)))) ;;;###autoload (defalias 'run-haskell 'switch-to-haskell) ;;;###autoload (defun switch-to-haskell (&optional arg) "Show the inferior-haskell buffer. Start the process if needed." (interactive "P") (let ((proc (inferior-haskell-process arg))) (pop-to-buffer (process-buffer proc)))) (defcustom inferior-haskell-wait-and-jump nil "If non-nil, wait for file loading to terminate and jump to the error." :type 'boolean :group 'inferior-haskell) (defvar inferior-haskell-send-decl-post-filter-on nil) (make-variable-buffer-local 'inferior-haskell-send-decl-post-filter-on) (defun inferior-haskell-send-decl-post-filter (string) (when (and inferior-haskell-send-decl-post-filter-on #1=(string-match inferior-haskell-multiline-prompt-re string)) ;; deleting sequence of `%s|' multiline promts (while #1# (setq string (substring string (match-end 0)))) ;; deleting regular prompts (setq string (replace-regexp-in-string comint-prompt-regexp "" string) ;; turning off this post-filter inferior-haskell-send-decl-post-filter-on nil)) string) (defvar inferior-haskell-seen-prompt nil) (make-variable-buffer-local 'inferior-haskell-seen-prompt) (defun inferior-haskell-spot-prompt (string) (let ((proc (get-buffer-process (current-buffer)))) (when proc (save-excursion (goto-char (process-mark proc)) (if (re-search-backward comint-prompt-regexp (line-beginning-position) t) (setq inferior-haskell-seen-prompt t)))))) (defun inferior-haskell-wait-for-prompt (proc &optional timeout) "Wait until PROC sends us a prompt. The process PROC should be associated to a comint buffer." (with-current-buffer (process-buffer proc) (while (progn (goto-char comint-last-input-end) (not (or inferior-haskell-seen-prompt (setq inferior-haskell-seen-prompt (re-search-forward comint-prompt-regexp nil t)) (not (accept-process-output proc timeout)))))) (unless inferior-haskell-seen-prompt (error "Can't find the prompt")))) (defvar inferior-haskell-cabal-buffer nil) (defun inferior-haskell-cabal-of-buf (buf) (with-current-buffer buf (or (and (buffer-live-p inferior-haskell-cabal-buffer) inferior-haskell-cabal-buffer) (if (local-variable-p 'inferior-haskell-cabal-buffer ;; XEmacs needs this argument. (current-buffer)) inferior-haskell-cabal-buffer (set (make-local-variable 'inferior-haskell-cabal-buffer) (haskell-cabal-find-file)))))) (defun inferior-haskell-find-project-root (buf) (with-current-buffer buf (let* ( (cabal-file (inferior-haskell-cabal-of-buf buf)) (cabal (when cabal-file (find-file-noselect cabal-file))) ) (or (when cabal (with-current-buffer cabal (let ((hsd (haskell-cabal-get-setting "hs-source-dirs"))) (if (null hsd) ;; If there's a Cabal file with no Hs-Source-Dirs, then ;; just use the Cabal file's directory. default-directory ;; If there is an HSD, then check that it's an existing ;; dir (otherwise, it may be a list of dirs and we don't ;; know what to do with those). If it doesn't exist, then ;; give up. (if (file-directory-p hsd) (expand-file-name hsd)))))) ;; If there's no Cabal file or it's not helpful, try to look for ;; a "module" statement and count the number of "." in the ;; module name. (save-excursion (goto-char (point-min)) (let ((case-fold-search nil)) (when (re-search-forward "^module[ \t]+\\(\\(?:\\sw\\|[.]\\)+\\)" nil t) (let* ((dir default-directory) (module (match-string 1)) (pos 0)) (while (string-match "\\." module pos) (setq pos (match-end 0)) (setq dir (expand-file-name ".." dir))) ;; Let's check that the module name matches the file name, ;; otherwise the project root is probably not what we think. (if (eq t (compare-strings (file-name-sans-extension buffer-file-name) nil nil (expand-file-name (replace-regexp-in-string "\\." "/" module) dir) nil nil t)) dir ;; If they're not equal, it means the local directory ;; hierarchy doesn't match the module name. This seems ;; odd, so let's warn the user about it. May help us ;; debug this code as well. (message "Ignoring inconsistent `module' info: %s in %s" module buffer-file-name) nil))))))))) ;;;###autoload (defun inferior-haskell-load-file (&optional reload) "Pass the current buffer's file to the inferior haskell process. If prefix arg \\[universal-argument] is given, just reload the previous file." (interactive "P") ;; Save first, so we're sure that `buffer-file-name' is non-nil afterward. (save-buffer) (let ((buf (current-buffer)) (file buffer-file-name) (proc (inferior-haskell-process))) (if file (with-current-buffer (process-buffer proc) (compilation-forget-errors) (let ((parsing-end (marker-position (process-mark proc))) root) ;; Go to the root of the Cabal project, if applicable. (when (and inferior-haskell-find-project-root (setq root (inferior-haskell-find-project-root buf))) ;; Not sure if it's useful/needed and if it actually works. (unless (equal default-directory root) (setq default-directory root) (inferior-haskell-send-command proc (concat ":cd " default-directory))) (setq file (file-relative-name file))) (inferior-haskell-send-command proc (if reload ":reload" (concat ":load \"" ;; Espace the backslashes that may occur in file names. (replace-regexp-in-string "[\\\"]" "\\\\\&" file) "\""))) ;; Move the parsing-end marker *after* sending the command so ;; that it doesn't point just to the insertion point. ;; Otherwise insertion may move the marker (if done with ;; insert-before-markers) and we'd then miss some errors. (if (boundp 'compilation-parsing-end) (if (markerp compilation-parsing-end) (set-marker compilation-parsing-end parsing-end) (setq compilation-parsing-end parsing-end)))) (with-selected-window (display-buffer (current-buffer) nil 'visible) (goto-char (point-max))) ;; Use compilation-auto-jump-to-first-error if available. ;; (if (and (boundp 'compilation-auto-jump-to-first-error) ;; compilation-auto-jump-to-first-error ;; (boundp 'compilation-auto-jump-to-next)) ;; (setq compilation-auto-jump-to-next t) (when inferior-haskell-wait-and-jump (inferior-haskell-wait-for-prompt proc) (ignore-errors ;Don't beep if there were no errors. (next-error)))) (error "No file associated with buffer")))) (defvar inferior-haskell-run-command ":main") ;;;###autoload (defun inferior-haskell-load-and-run (command) "Pass the current buffer's file to haskell and then run a COMMAND." (interactive (list (if (and inferior-haskell-run-command (not current-prefix-arg)) inferior-haskell-run-command (read-string "Command to run: " nil nil inferior-haskell-run-command)))) (setq inferior-haskell-run-command command) (let* ((inferior-haskell-errors nil) (neh (lambda () (setq inferior-haskell-errors t)))) (unwind-protect (let ((inferior-haskell-wait-and-jump t)) (add-hook 'next-error-hook neh) (inferior-haskell-load-file)) (remove-hook 'next-error-hook neh)) (unless inferior-haskell-errors (inferior-haskell-send-command (inferior-haskell-process) command) (switch-to-haskell)))) (defun inferior-haskell-send-command (proc str) (setq str (concat str "\n")) (with-current-buffer (process-buffer proc) (inferior-haskell-wait-for-prompt proc) (goto-char (process-mark proc)) (insert-before-markers str) (move-marker comint-last-input-end (point)) (setq inferior-haskell-seen-prompt nil) (comint-send-string proc str))) (defun inferior-haskell-reload-file () "Tell the inferior haskell process to reread the current buffer's file." (interactive) (inferior-haskell-load-file 'reload)) (defun inferior-haskell-wrap-decl (code) "Wrap declaration code into :{ ... :}." (setq code (concat code "\n")) (concat ":{\n" (if (string-match (concat "^\\s-*" haskell-ds-start-keywords-re) code) ;; non-fun-decl code ;; fun-decl, wrapping into let { .. (; ..)* } (concat "let {\n" (mapconcat ;; adding 2 whitespaces to each line (lambda (decl) (mapconcat (lambda (s) (concat " " s)) (split-string decl "\n") "\n")) ;; splitting function case-decls (let (decls) (while (string-match "^\\(\\w+\\).*\n*\\(?:\\s-+.*\n+\\)*" code) (push (match-string 0 code) decls) (setq code (substring code (match-end 0)))) (reverse decls)) "\n;\n") "\n}")) "\n:}\n")) (defun inferior-haskell-flash-decl (start end &optional timeout) "Temporarily highlight declaration." (let ((overlay (make-overlay start end))) (overlay-put overlay 'face 'secondary-selection) (run-with-timer (or timeout 0.2) nil 'delete-overlay overlay))) ;;;###autoload (defun inferior-haskell-send-decl () "Send current declaration to inferior-haskell process." (interactive) (save-excursion (goto-char (1+ (point))) (let* ((proc (inferior-haskell-process)) (start (or (haskell-ds-backward-decl) (point-min))) (end (or (haskell-ds-forward-decl) (point-max))) (raw-decl (buffer-substring start end))) ;; enter multiline-prompt-cutting-mode (with-current-buffer (process-buffer proc) (setq inferior-haskell-send-decl-post-filter-on t)) ;; flash decl (inferior-haskell-flash-decl start end) ;; send decl (comint-send-string proc (inferior-haskell-wrap-decl raw-decl)) ;; send preview (inferior-haskell-send-command proc (let* ((str (remove ?\n raw-decl)) (len (min 15 (length str)))) (concat "-- evaluating {: " (substring str 0 len) (if (= 15 len) ".." "") " :}")))))) (defun inferior-haskell-get-result (inf-expr) "Submit the expression `inf-expr' to ghci and read the result." (let ((proc (inferior-haskell-process))) (with-current-buffer (process-buffer proc) (let ((parsing-end ; Remember previous spot. (marker-position (process-mark proc)))) (inferior-haskell-send-command proc inf-expr) ;; Find new point. (inferior-haskell-wait-for-prompt proc) (goto-char (point-max)) ;; Back up to the previous end-of-line. (end-of-line 0) ;; Extract the output (buffer-substring-no-properties (save-excursion (goto-char parsing-end) (line-beginning-position 2)) (point)))))) ;;;###autoload (defun inferior-haskell-type (expr &optional insert-value) "Query the haskell process for the type of the given expression. If optional argument `insert-value' is non-nil, insert the type above point in the buffer. This can be done interactively with the \\[universal-argument] prefix. The returned info is cached for reuse by `haskell-doc-mode'." (interactive (let ((sym (haskell-ident-at-point))) (list (read-string (if (> (length sym) 0) (format "Show type of (default %s): " sym) "Show type of: ") nil nil sym) current-prefix-arg))) (if (string-match "\\`\\s_+\\'" expr) (setq expr (concat "(" expr ")"))) (let ((type (inferior-haskell-get-result (concat ":type " expr)))) (if (not (string-match (concat "^\\(" (regexp-quote expr) "[ \t\n]+::[ \t\n]*\\(.\\|\n\\)*\\)") type)) (error "No type info: %s" type) (progn (setf type (match-string 1 type)) ;; Cache for reuse by haskell-doc. (when (and (boundp 'haskell-doc-mode) haskell-doc-mode (boundp 'haskell-doc-user-defined-ids) ;; Haskell-doc only works for idents, not arbitrary expr. (string-match "\\`(?\\(\\s_+\\|\\(\\sw\\|\\s'\\)+\\)?[ \t]*::[ \t]*" type)) (let ((sym (match-string 1 type))) (setq haskell-doc-user-defined-ids (cons (cons sym (substring type (match-end 0))) (delq (assoc sym haskell-doc-user-defined-ids) haskell-doc-user-defined-ids))))) (if (called-interactively-p 'any) (message "%s" type)) (when insert-value (beginning-of-line) (insert type "\n")) type)))) ;;;###autoload (defun inferior-haskell-kind (type) "Query the haskell process for the kind of the given expression." (interactive (let ((type (haskell-ident-at-point))) (list (read-string (if (> (length type) 0) (format "Show kind of (default %s): " type) "Show kind of: ") nil nil type)))) (let ((result (inferior-haskell-get-result (concat ":kind " type)))) (if (called-interactively-p 'any) (message "%s" result)) result)) ;;;###autoload (defun inferior-haskell-info (sym) "Query the haskell process for the info of the given expression." (interactive (let ((sym (haskell-ident-at-point))) (list (read-string (if (> (length sym) 0) (format "Show info of (default %s): " sym) "Show info of: ") nil nil sym)))) (let ((result (inferior-haskell-get-result (concat ":info " sym)))) (if (called-interactively-p 'any) (message "%s" result)) result)) ;;;###autoload (defun inferior-haskell-find-definition (sym) "Attempt to locate and jump to the definition of the given expression." (interactive (let ((sym (haskell-ident-at-point))) (list (read-string (if (> (length sym) 0) (format "Find definition of (default %s): " sym) "Find definition of: ") nil nil sym)))) (let ((info (inferior-haskell-info sym))) (if (not (string-match inferior-haskell-info-xref-re info)) (error "No source information available") (let ((file (match-string-no-properties 1 info)) (line (string-to-number (match-string-no-properties 2 info))) (col (string-to-number (match-string-no-properties 3 info)))) (when file (with-current-buffer (process-buffer (inferior-haskell-process)) ;; The file name is relative to the process's cwd. (setq file (expand-file-name file))) ;; Push current location marker on the ring used by `find-tag' (require 'etags) (ring-insert find-tag-marker-ring (point-marker)) (pop-to-buffer (find-file-noselect file)) (when line (goto-char (point-min)) (forward-line (1- line)) (when col (move-to-column col)))))))) ;;; Functions to find the documentation of a given function. ;; ;; TODO for this section: ;; ;; * Support fetching of local Haddock docs pulled directly from source files. ;; * Display docs locally? w3m? (defcustom inferior-haskell-use-web-docs 'fallback "Whether to use the online documentation. Possible values: `never', meaning always use local documentation, unless the local file doesn't exist, when do nothing, `fallback', which means only use the online documentation when the local file doesn't exist, or `always', meaning always use the online documentation, regardless of existance of local files. Default is `fallback'." :group 'inferior-haskell :type '(choice (const :tag "Never" never) (const :tag "As fallback" fallback) (const :tag "Always" always))) (defcustom inferior-haskell-web-docs-base "http://haskell.org/ghc/docs/latest/html/libraries/" "The base URL of the online libraries documentation. This will only be used if the value of `inferior-haskell-use-web-docs' is `always' or `fallback'." :group 'inferior-haskell :type 'string) (defcustom haskell-package-manager-name "ghc-pkg" "Name of the program to consult regarding package details." :group 'inferior-haskell :type 'string) (defcustom haskell-package-conf-file (condition-case nil (with-temp-buffer (call-process "ghc" nil t nil "--print-libdir") (expand-file-name "package.conf" (buffer-substring (point-min) (1- (point-max))))) ;; Don't use `ignore-errors' because this form is not byte-compiled :-( (error nil)) "Where the package configuration file for the package manager resides. By default this is set to `ghc --print-libdir`/package.conf." :group 'inferior-haskell :type 'string) (defun inferior-haskell-get-module (sym) "Fetch the module in which SYM is defined." (let ((info (inferior-haskell-info sym))) (unless (string-match inferior-haskell-module-re info) (error "No documentation information available. Did you forget to C-c C-l?")) (let ((module-name (match-string-no-properties 1 info))) ;; Handles GHC 7.4.1+ which quotes module names like ;; `System.Random', whereas previous GHC did not quote at all. (if (string= "`" (substring module-name 0 1)) (substring module-name 1 (- (length module-name) 1)) module-name)))) (defun inferior-haskell-query-ghc-pkg (&rest args) "Send ARGS to `haskell-package-manager-name'. Insert the output into the current buffer." (apply 'call-process haskell-package-manager-name nil t nil args)) (defun inferior-haskell-get-package-list () "Get the list of packages from `haskell-package-manager-name'." (with-temp-buffer (inferior-haskell-query-ghc-pkg "--simple-output" "list") (split-string (buffer-substring (point-min) (point-max))))) (defun inferior-haskell-compute-module-alist () "Compute a list mapping modules to package names and haddock URLs using ghc-pkg." (message "Generating module alist...") (let ((module-alist ())) (with-temp-buffer (dolist (package (inferior-haskell-get-package-list)) (erase-buffer) (inferior-haskell-query-ghc-pkg "describe" package) (let ((package-w/o-version (replace-regexp-in-string "[-.0-9]*\\'" "" package)) ;; Find the Haddock documentation URL for this package (haddock (progn (goto-char (point-min)) (when (re-search-forward "haddock-html:[ \t]+\\(.*[^ \t\n]\\)" nil t) (match-string 1))))) ;; Fetch the list of exposed modules for this package (goto-char (point-min)) (when (re-search-forward "^exposed-modules:\\(.*\\(\n[ \t].*\\)*\\)" nil t) (dolist (module (split-string (match-string 1))) (push (list module package-w/o-version haddock) module-alist))))) (message "Generating module alist... done") module-alist))) (defcustom inferior-haskell-module-alist-file ;; (expand-file-name "~/.inf-haskell-module-alist") (expand-file-name (concat "inf-haskell-module-alist-" (number-to-string (user-uid))) temporary-file-directory) "Where to save the module -> package lookup table. Set this to nil to never cache to a file." :group 'inferior-haskell :type '(choice (const :tag "Don't cache to file" nil) string)) (defvar inferior-haskell-module-alist nil "Association list of modules to their packages. Each element is of the form (MODULE PACKAGE HADDOCK), where MODULE is the name of a module, PACKAGE is the package it belongs to, and HADDOCK is the path to that package's Haddock documentation. This is calculated on-demand using `inferior-haskell-compute-module-alist'. It's also cached in the file `inferior-haskell-module-alist-file', so that it can be obtained more quickly next time.") (defun inferior-haskell-module-alist () "Get the module alist from cache or ghc-pkg's info." (or ;; If we already have computed the alist, use it... inferior-haskell-module-alist (setq inferior-haskell-module-alist (or ;; ...otherwise try to read it from the cache file... (and inferior-haskell-module-alist-file (file-readable-p inferior-haskell-module-alist-file) (file-newer-than-file-p inferior-haskell-module-alist-file haskell-package-conf-file) (with-temp-buffer (insert-file-contents inferior-haskell-module-alist-file) (goto-char (point-min)) (prog1 (read (current-buffer)) (message "Read module alist from file cache.")))) ;; ...or generate it again and save it in a file for later. (let ((alist (inferior-haskell-compute-module-alist))) (when inferior-haskell-module-alist-file (with-temp-buffer (print alist (current-buffer)) ;; Do the write to a temp file first, then rename it. ;; This makes it more atomic, and suffers from fewer security ;; holes related to race conditions if the file is in /tmp. (let ((tmp (make-temp-file inferior-haskell-module-alist-file))) (write-region (point-min) (point-max) tmp) (rename-file tmp inferior-haskell-module-alist-file 'ok-if-already-exists)))) alist))))) (defvar inferior-haskell-ghc-internal-ident-alist ;; FIXME: Fill this table, ideally semi-automatically. '(("GHC.Base.return" . "Control.Monad.return") ("GHC.List" . "Data.List"))) (defun inferior-haskell-map-internal-ghc-ident (ident) "Try to translate some internal GHC identifier to its alter ego in haskell docs." (let ((head ident) (tail "") remapped) (while (and (not (setq remapped (cdr (assoc head inferior-haskell-ghc-internal-ident-alist)))) (string-match "\\.[^.]+\\'" head)) (setq tail (concat (match-string 0 head) tail)) (setq head (substring head 0 (match-beginning 0)))) (concat (or remapped head) tail))) ;;;###autoload (defun inferior-haskell-find-haddock (sym) "Find and open the Haddock documentation of SYM. Make sure to load the file into GHCi or Hugs first by using C-c C-l. Only works for functions in a package installed with ghc-pkg, or whatever the value of `haskell-package-manager-name' is. This function needs to find which package a given module belongs to. In order to do this, it computes a module-to-package lookup alist, which is expensive to compute (it takes upwards of five seconds with more than about thirty installed packages). As a result, we cache it across sessions using the cache file referenced by `inferior-haskell-module-alist-file'. We test to see if this is newer than `haskell-package-conf-file' every time we load it." (interactive (let ((sym (haskell-ident-at-point))) (list (read-string (if (> (length sym) 0) (format "Find documentation of (default %s): " sym) "Find documentation of: ") nil nil sym)))) (setq sym (inferior-haskell-map-internal-ghc-ident sym)) (let* (;; Find the module and look it up in the alist (module (inferior-haskell-get-module sym)) (alist-record (assoc module (inferior-haskell-module-alist))) (package (nth 1 alist-record)) (file-name (concat (subst-char-in-string ?. ?- module) ".html")) (local-path (concat (nth 2 alist-record) "/" file-name)) (url (if (or (eq inferior-haskell-use-web-docs 'always) (and (not (file-exists-p local-path)) (eq inferior-haskell-use-web-docs 'fallback))) (concat inferior-haskell-web-docs-base package "/" file-name ;; Jump to the symbol anchor within Haddock. "#v:" sym) (and (file-exists-p local-path) (concat "file://" local-path))))) (if url (browse-url url) (error "Local file doesn't exist")))) (provide 'inf-haskell) ;; Local Variables: ;; byte-compile-warnings: (not cl-functions) ;; End: ;;; inf-haskell.el ends here haskell-mode-13.10/logo.svg000066400000000000000000000026601225210037200155420ustar00rootroot00000000000000 haskell-mode-13.10/snippets/000077500000000000000000000000001225210037200157225ustar00rootroot00000000000000haskell-mode-13.10/snippets/README.md000066400000000000000000000050201225210037200171760ustar00rootroot00000000000000# Shnippet **Shnippet** is a collection of [YASnippet][yas] [Haskell][haskell] snippets for Emacs. ## Installation Clone repository: $ cd ~/.emacs.d/snippets $ git clone https://github.com/LukeHoersten/shnippet OR $ hg clone https://bitbucket.org/LukeHoersten/shnippet Add the cloned repository to YASnippet's `yas-snippet-dirs`: (setq yas-snippet-dirs '("~/.emacs.d/snippets/shnippet" "/other/paths/" )) Snippets may have to be recompiled and reloaded in Emacs if YASnippet is already in use: M-x yas-recompile-all M-x yas-reload-all Haskell snippts should now be available to use! In a `haskell-mode` buffer, type `fn`. A prompt should appear asking which `fn` snippet to expand. I **highly** recommend using YASnippet with [ido-mode]. Configure Emacs: (setq-default yas-prompt-functions '(yas-ido-prompt yas-dropdown-prompt)) This is important so that alternatives (like `import` vs. `import qualified`) can quickly be selected with a single key stroke. ## Available Expansion Keys * `new` - newtype * `mod` - module [simple, exports] * `main ` - main module and funtion * `let` - let bindings * `lang` - language extension pragmas * `\` - lambda function * `inst` - instance declairation * `imp` - import modules [simple, qualified] * `if` - if conditional [inline, block] * `<-` - monadic get * `fn` - top level function [simple, guarded, clauses] * `data` - data type definition [inline, record] * `=>` - type constraint * `{-` - block comment * `case` - case statement ## Design Ideals * Keep snippet keys (the prefix used to auto-complete) to four characters or less while still being as easy to guess as possible. * Have as few keys as possible. The more keys there are to remember, the harder snippets are to use and learn. * Leverage [ido-mode][] when reasonable. For instance, to keep the number of snippet keys to a minimum as well as auto complete things like [Haskell Langauge Extension Pragmas][lang-pragma]. When multiple snippets share a key (ex: `fn`), the `ido-mode` prompts are unique to one character (ex: `guarded function` and `simple function` are `g` and `s` respectively). ## Authors This code is written and maintained by Luke Hoersten, . [yas]: https://github.com/capitaomorte/yasnippet [ido-mode]: http://www.emacswiki.org/emacs/InteractivelyDoThings [lang-pragma]: http://hackage.haskell.org/packages/archive/Cabal/1.16.0.3/doc/html/Language-Haskell-Extension.html#t:KnownExtension [haskell]: http://haskell.org/ haskell-mode-13.10/snippets/haskell-mode/000077500000000000000000000000001225210037200202675ustar00rootroot00000000000000haskell-mode-13.10/snippets/haskell-mode/.yas-ignore-filenames-as-triggers000066400000000000000000000000001225210037200265210ustar00rootroot00000000000000haskell-mode-13.10/snippets/haskell-mode/.yas-make-groups000066400000000000000000000000001225210037200233020ustar00rootroot00000000000000haskell-mode-13.10/snippets/haskell-mode/case000066400000000000000000000003401225210037200211220ustar00rootroot00000000000000# -*- mode: snippet -*- # key: case # name: case # expand-env: ((yas-indent-line 'fixed)) # contributor: Luke Hoersten # -- case ${1:x} of ${2:Data} -> ${4:undefined} ${3:Data} -> ${5:undefined}$0haskell-mode-13.10/snippets/haskell-mode/comment.block000066400000000000000000000001661225210037200227500ustar00rootroot00000000000000# -*- mode: snippet -*- # key: {- # name: block comment # contributor: Luke Hoersten # -- {- $0 -}haskell-mode-13.10/snippets/haskell-mode/constraint000066400000000000000000000002111225210037200223700ustar00rootroot00000000000000# -*- mode: snippet -*- # key: => # name: Type constraint # contributor: Luke Hoersten # -- (${1:Class} ${2:m}) => $0haskell-mode-13.10/snippets/haskell-mode/data.inline000066400000000000000000000003321225210037200223760ustar00rootroot00000000000000# -*- mode: snippet -*- # key: data # name: inline data # condition: (= (length "data") (current-column)) # contributor: Luke Hoersten # -- data ${1:Type} = ${2:Data}$0 ${3:deriving (${4:Show, Eq})}haskell-mode-13.10/snippets/haskell-mode/data.record000066400000000000000000000004251225210037200224010ustar00rootroot00000000000000# -*- mode: snippet -*- # key: data # name: record data # condition: (= (length "data") (current-column)) # contributor: Luke Hoersten # -- data ${1:Type} = $1 { ${2:field} :: ${3:Type} , ${4:field} :: ${5:Type}$0 } ${6:deriving (${7:Show, Eq})}haskell-mode-13.10/snippets/haskell-mode/fn000066400000000000000000000004051225210037200206140ustar00rootroot00000000000000# -*- mode: snippet -*- # key: fn # name: simple function # condition: (= (length "fn") (current-column)) # expand-env: ((yas-indent-line 'fixed)) # contributor: Luke Hoersten # -- ${1:f} :: ${2:a} ${3:-> ${4:b}} $1 ${5:x} = ${6:undefined}$0haskell-mode-13.10/snippets/haskell-mode/fn.clause000066400000000000000000000004541225210037200220730ustar00rootroot00000000000000# -*- mode: snippet -*- # key: fn # name: clause function # condition: (= (length "fn") (current-column)) # expand-env: ((yas-indent-line 'fixed)) # contributor: Luke Hoersten # -- ${1:f} :: ${2:a} ${3:-> ${4:b}} $1 ${5:pattern} = ${7:undefined} $1 ${6:pattern} = ${8:undefined}$0haskell-mode-13.10/snippets/haskell-mode/fn.guarded000066400000000000000000000005051225210037200222270ustar00rootroot00000000000000# -*- mode: snippet -*- # key: fn # name: guarded function # condition: (= (length "fn") (current-column)) # expand-env: ((yas-indent-line 'fixed)) # contributor: Luke Hoersten # -- ${1:f} :: ${2:a} ${3:-> ${4:b}} $1 ${5:x} | ${6:conditional} = ${8:undefined} | ${7:conditional} = ${9:undefined}$0haskell-mode-13.10/snippets/haskell-mode/get000066400000000000000000000002061225210037200207670ustar00rootroot00000000000000# -*- mode: snippet -*- # key: <- # name: monadic get # contributor: Luke Hoersten # -- ${1:x} <- ${2:undefined}$0haskell-mode-13.10/snippets/haskell-mode/if.block000066400000000000000000000002541225210037200217020ustar00rootroot00000000000000# -*- mode: snippet -*- # key: if # name: block if # contributor: Luke Hoersten # -- if ${1:condition} then ${2:undefined} else ${3:undefined}$0haskell-mode-13.10/snippets/haskell-mode/if.inline000066400000000000000000000002451225210037200220660ustar00rootroot00000000000000# -*- mode: snippet -*- # key: if # name: inline if # contributor: Luke Hoersten # -- if ${1:condition} then ${2:undefined} else ${3:undefined}$0haskell-mode-13.10/snippets/haskell-mode/import000066400000000000000000000003121225210037200215200ustar00rootroot00000000000000# -*- mode: snippet -*- # key: imp # name: simple import # condition: (= (length "imp") (current-column)) # contributor: Luke Hoersten # -- import ${1:Module} ${2:(${3:f})}haskell-mode-13.10/snippets/haskell-mode/import.qualified000066400000000000000000000006421225210037200234700ustar00rootroot00000000000000# -*- mode: snippet -*- # key: imp # name: qualified import # condition: (= (length "imp") (current-column)) # contributor: Luke Hoersten # -- import qualified ${1:Module} as ${2:${1:$(let ((name (car (last (split-string yas-text "\\\."))))) (if (not (nil-blank-string name)) "" (subseq name 0 1)))}}$0haskell-mode-13.10/snippets/haskell-mode/instance000066400000000000000000000003361225210037200220200ustar00rootroot00000000000000# -*- mode: snippet -*- # key: inst # name: instance # condition: (= (length "inst") (current-column)) # contributor: Luke Hoersten # -- instance ${1:Class} ${2:Data} where ${3:f} = ${4:undefined}$0haskell-mode-13.10/snippets/haskell-mode/lambda000066400000000000000000000002021225210037200214240ustar00rootroot00000000000000# -*- mode: snippet -*- # key: \ # name: lambda # contributor: Luke Hoersten # -- \\${1:x} -> ${2:undefined}$0haskell-mode-13.10/snippets/haskell-mode/lang-pragma000066400000000000000000000004511225210037200224000ustar00rootroot00000000000000# -*- mode: snippet -*- # key: lang # name: language pragma # condition: (= (length "lang") (current-column)) # contributor: Luke Hoersten , John Wiegley # -- {-# LANGUAGE `(progn (require 'haskell-yas) (haskell-yas-complete "Extension: " haskell-yas-ghc-language-pragmas))` #-}haskell-mode-13.10/snippets/haskell-mode/let000066400000000000000000000002021225210037200207700ustar00rootroot00000000000000# -*- mode: snippet -*- # key: let # name: let # contributor: Luke Hoersten # -- let ${1:x} = ${2:undefined}$0haskell-mode-13.10/snippets/haskell-mode/main000066400000000000000000000004221225210037200211340ustar00rootroot00000000000000# -*- mode: snippet -*- # key: main # name: main module # condition: (= (length "main") (current-column)) # expand-env: ((yas-indent-line 'fixed)) # contributor: Luke Hoersten # -- module Main where main :: IO () main = do ${1:undefined}$0 return ()haskell-mode-13.10/snippets/haskell-mode/module000066400000000000000000000010341225210037200214750ustar00rootroot00000000000000# -*- mode: snippet -*- # key: mod # name: simple module # condition: (= (length "mod") (current-column)) # expand-env: ((yas-indent-line 'fixed)) # contributor: Luke Hoersten # -- module ${1:`(if (not buffer-file-name) "Module" (let ((name (file-name-sans-extension (buffer-file-name)))) (if (search "src/" name) (replace-regexp-in-string "/" "." (car (last (split-string name "src/")))) (file-name-nondirectory name))))`} where $0haskell-mode-13.10/snippets/haskell-mode/module.exports000066400000000000000000000011141225210037200231770ustar00rootroot00000000000000# -*- mode: snippet -*- # key: mod # name: exports module # condition: (= (length "mod") (current-column)) # expand-env: ((yas-indent-line 'fixed)) # contributor: Luke Hoersten # -- module ${1:`(if (not buffer-file-name) "Module" (let ((name (file-name-sans-extension (buffer-file-name)))) (if (search "src/" name) (replace-regexp-in-string "/" "." (car (last (split-string name "src/")))) (file-name-nondirectory name))))`} ( ${3:export} ${4:, ${5:export}} ) where $0haskell-mode-13.10/snippets/haskell-mode/newtype000066400000000000000000000003411225210037200217030ustar00rootroot00000000000000# -*- mode: snippet -*- # key: new # name: newtype # condition: (= (length "new") (current-column)) # contributor: Luke Hoersten # -- newtype ${1:Type} = $1 { un$1 :: ${2:a} } ${3:deriving (${4:Show, Eq})}haskell-mode-13.10/tests/000077500000000000000000000000001225210037200152175ustar00rootroot00000000000000haskell-mode-13.10/tests/haskell-str-tests.el000066400000000000000000000105131225210037200211320ustar00rootroot00000000000000;; unit tests for haskell-str.el (require 'ert) (require 'haskell-str ) ;; implementation under test (ert-deftest haskell-str-take () (should (string= (haskell-str-take "" 0) "")) (should (string= (haskell-str-take "" 1) "")) (should (string= (haskell-str-take "" 2) "")) (should (string= (haskell-str-take "x" 0) "")) (should (string= (haskell-str-take "x" 1) "x")) (should (string= (haskell-str-take "x" 2) "x")) (should (string= (haskell-str-take "x" 3) "x")) (should (string= (haskell-str-take "xy" 0) "")) (should (string= (haskell-str-take "xy" 1) "x")) (should (string= (haskell-str-take "xy" 2) "xy")) (should (string= (haskell-str-take "xy" 3) "xy")) (should (string= (haskell-str-take "xyz" 0) "")) (should (string= (haskell-str-take "xyz" 1) "x")) (should (string= (haskell-str-take "xyz" 2) "xy")) (should (string= (haskell-str-take "xyz" 3) "xyz")) (should (string= (haskell-str-take "xyz" 4) "xyz"))) (ert-deftest haskell-str-ellipsize () (should (string= (haskell-str-ellipsize "" 0) "")) (should (string= (haskell-str-ellipsize "" 1) "")) (should (string= (haskell-str-ellipsize "" 2) "")) (should (string= (haskell-str-ellipsize "x" 0) "")) (should (string= (haskell-str-ellipsize "x" 1) "x")) (should (string= (haskell-str-ellipsize "x" 2) "x")) (should (string= (haskell-str-ellipsize "x" 3) "x")) (should (string= (haskell-str-ellipsize "xy" 0) "")) (should (string= (haskell-str-ellipsize "xy" 1) "…")) (should (string= (haskell-str-ellipsize "xy" 2) "xy")) (should (string= (haskell-str-ellipsize "xy" 3) "xy")) (should (string= (haskell-str-ellipsize "xyz" 0) "")) (should (string= (haskell-str-ellipsize "xyz" 1) "…")) (should (string= (haskell-str-ellipsize "xyz" 2) "x…")) (should (string= (haskell-str-ellipsize "xyz" 3) "xyz")) (should (string= (haskell-str-ellipsize "xyz" 4) "xyz"))) (ert-deftest haskell-str-literal-encode-empty () (should (string= (haskell-str-literal-encode "") "\"\"")) (should (string= (haskell-str-literal-encode "" t) ""))) (ert-deftest haskell-str-literal-decode-empty () (dolist (s0 (list "\"\"" "\"\\&\"" "\"\\&\\&\\&\"" "\"\\ \\\"" "\"\\ \\\\ \\\"" "\"\\&\\ \\\"" "\"\\ \\\\&\\ \\\"")) (should (string= "" (haskell-str-literal-decode s0))) (should (string= "" (haskell-str-literal-decode (substring s0 1 -1) t))))) (ert-deftest haskell-str-literal-decode-backslash () "Test some edge cases involving backslashes." (dolist (cs (list (cons "\\\\" "\\") (cons "\\x10" "\x10") (cons "\\\\x10" "\\x10") (cons "\\ \\x10" "x10") (cons "\\ \\ \\x30" " 0") (cons "\\SO\\&H" "\x0eH") (cons "\\SOH\\&" "\x01") (cons "\\n" "\n") (cons "\\'" "'") (cons "\\\"" "\"") (cons "\\SOH" "\x01"))) (should (string= (cdr cs) (haskell-str-literal-decode (concat "\"" (car cs) "\"")))) (should (string= (cdr cs) (haskell-str-literal-decode (car cs) t))))) (defun haskell-str-random (n) "Generate random N characters long string." (let ((a ())) (apply #'string (dotimes (_ n a) (setq a (cons (random 1024) a)))))) (ert-deftest haskell-str-literal-decode-encode () "Test whether decode+encode is the identity function." (random t) ;; some edge cases (dolist (s0 (list "\x0e\x48" ;; '\SO' 'H' "\x01" ;; '\SOH' "\x00df\x30" ;; '\223' '0' "'" "\'" "\"" "\x0e&H" "\\" " \\ \\" "\\\\\"" (string 40 945 8322 946 8323 8743 947 178 949 178 41) "x" "xy" "\\x123" "\\ \\x123" " " " " "")) (should (string= s0 (haskell-str-literal-decode (haskell-str-literal-encode s0)))) (should (string= s0 (haskell-str-literal-decode (haskell-str-literal-encode s0 t) t)))) ;; randomized testing (dotimes (_ 500) (dotimes (n 15) (let* ((s0 (haskell-str-random (+ 1 n))) (s1 (haskell-str-literal-decode (haskell-str-literal-encode s0))) (s2 (haskell-str-literal-decode (haskell-str-literal-encode s0 t) t))) (should (string= s0 s1)) (should (string= s0 s2))))))