Emacs: function for automatic symbols declaration

3 views
Skip to first unread message

Elena

unread,
Mar 19, 2009, 11:33:37 AM3/19/09
to Clojure
Hi,

I managed to put together an Emacs Lisp function to automatically
declare all defined symbols in a Clojure source file. The algorithm is
crude: it doesn't understand syntax, it just parses lines beginning
with either "(def " or "(defn ". A single line beginning with
"(declare " macro must already be present.

I wasn't able to match syntax of Clojure symbols inside the regex - it
should have been "(syntax symbol)", shouldn't it? - therefore I
resorted to:

(any "-" "a-z" "A-Z" "0-9")

which is incomplete.

You could hook the function to file saving or something like that. It
works for me.

Cheers


(require 'cl)
(require 'rx)

;; WARNING: IMPLEMENTED BY A NEWBIE. NO WARRANTIES!
(defun clj-auto-declare ()
(interactive "*") ;; Buffer contents are going to change.
(save-excursion
(save-restriction
(save-match-data
;; Scan buffer for defined symbols.
(widen)
(goto-char (point-min))
(let ((defined-symbols '()))
(while (re-search-forward (rx line-start "(" (or "def" "defn")
(one-or-more space)
(group (one-or-more (any "-" "a-z" "A-Z" "0-9"))))
nil t)
(push (match-string 1) defined-symbols))
;; Handle found symbols.
(if defined-symbols
;; Scan buffer for 'declare' and update it.
(progn (goto-char (point-min))
(unless (re-search-forward (rx line-start "(declare"
(group (zero-or-more (or space (any "-" "a-z" "A-Z"
"0-9"))))
")")
nil t)
(error "Global 'declare' not found. Have you entered it as
a single line?"))
(let ((uptodate-declare (concat "(declare " (mapconcat
'identity defined-symbols " ") ")")))
(replace-match uptodate-declare)
(message "Declarations have been updated.")))
(message "Nothing to declare, sir.")))))))

Elena

unread,
Mar 19, 2009, 1:37:14 PM3/19/09
to Clojure
The code is entirely misaligned. Reposted it as in the files section:

http://groups.google.com/group/clojure/web/clj-auto-declare.el

Tabs are too wide, I use four spaces wide tabs.
Reply all
Reply to author
Forward
0 new messages