quasiTech

experiments

Emacs and JS: Finding Function Definitions

I started doing Javascript recently. The js2-mode is excellent. But I am spoilt by SLIME :). One of the things I most missed from there was to be able to lookup function definitions with M-. and to get back with M-,. I had been pair programming with a team-mate and editing a 1000 line file and in his vanilla ‘Sublime’ editor and it was a royal pain scrolling all over the place looking for function definitions. So I decided to try my hand at some elisp. This was the first time but I really felt the need.

This is pretty simple really :

  • Get the word at point
  • Prepend “function ” to it
  • Save current location on a stack to getting back
  • Go to top of buffer
  • Do a forward search with our search string
  • If successful center line
  • Else do nothing and show message.

Another function, bound to M-, pops a position off the stack and goes to it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
;;; Find JS function definition in your current buffer (and go back).

(defvar *quasi-js-current-pos* nil)

(defun quasi-js-function-search ()
  "Search for JS function definations. In a rather dumb way, but works, albeit
only for current buffer. Works recurcively too :)"
  (interactive)
  (let ((text (thing-at-point 'word)))
    (push (point) *quasi-js-current-pos*)
    (goto-char (point-min))
    (if (search-forward (concat "function " text) nil t)
        (recenter)
      (progn
        (goto-char (pop *quasi-js-current-pos*))
        (message "Could not find definition for %s" text)))))

(defun quasi-js-function-go-back ()
  "Go back to where you initiated search from"
  (interactive)
  (if *quasi-js-current-pos*
      (goto-char (pop *quasi-js-current-pos*))
    (message "Nowhere to jump!")))

;; Add hooks to js2-mode. It will cobbler the default tag-search bindings. Beware.
(add-hook 'js2-mode-hook
          (lambda ()
            (local-set-key (kbd "M-.") #'quasi-js-function-search)
            (local-set-key (kbd "M-,") #'quasi-js-function-go-back)))

It really felt good to have written my first useful elisp code.

Comments