Skip to content

Instantly share code, notes, and snippets.

@agrafix
Last active January 13, 2017 14:31
Show Gist options
  • Save agrafix/6900e0505da0b7836aa0b849dc695905 to your computer and use it in GitHub Desktop.
Save agrafix/6900e0505da0b7836aa0b849dc695905 to your computer and use it in GitHub Desktop.
Some useful haskell utilities
(defconst hs-imports-imports-start-regexp
(rx (group (and bol "import "))))
(defconst hs-imports-language-start-regexp
(rx (group (and bol "{-# LANGUAGE "))))
(defun hs-imports--search-beg-point (start what &optional end)
"Search the first import line until reach the END point."
(save-excursion
(goto-char start)
(and (re-search-forward what end t)
(match-beginning 1))))
(defun hs-imports--search-end-point (begin what)
"Search the last import line starting from BEGIN point."
(let (end)
(save-excursion
(goto-char begin)
(goto-char (point-at-bol))
(while (not (or (not (looking-at what)) (eobp)))
(forward-line 1)
)
(forward-line -1)
(setq end (point-at-eol)))
end))
(defun hs-imports-buffer-what (what)
"Sort from current buffer."
(interactive)
(let* ((begin (hs-imports--search-beg-point (point-min) what))
(end (and begin (hs-imports--search-end-point begin what))))
(while (and begin end)
(sort-lines 'nil begin end)
(setq begin (hs-imports--search-beg-point end what))
(setq end (and begin (hs-imports--search-end-point begin what)))
)))
(defun hs-nice-buffer ()
"Sort haskell imports pragmas from current buffer."
(interactive)
(hs-imports-buffer-what hs-imports-imports-start-regexp)
)
(defun hs-nice-pragmas ()
"Sort haskell pragmas"
(interactive)
(hs-imports-buffer-what hs-imports-language-start-regexp)
)
(defun hs-insert-import (import-string)
"Insert an import"
(interactive)
(let* ((begin (hs-imports--search-beg-point (point-min) hs-imports-imports-start-regexp))
(end (and begin (hs-imports--search-end-point begin hs-imports-imports-start-regexp))))
(when (and begin end)
(save-excursion
(goto-char end)
(newline)
(insert import-string))))
)
(defun hs-usual-import ()
"Add an import"
(interactive)
(let
((x (read-string "Module: ")))
(hs-insert-import (format "import %s" x))))
(defun hs-qualified-import ()
"Add a qualified import"
(interactive)
(let
((x (read-string "Module: "))
(q (read-string "Qualified: ")))
(hs-insert-import (format "import qualified %s as %s" x q))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment