Gradual Epiphany

An Emacs Mini-hack

There have been a whole host of changes in my life since my last blog post. I left “Ping”:http://www.pingidentity.com back in August and am now working at “The Hive”:http://thehive.com. My wife and I also welcomed our first child into the world a few weeks ago. :)

At any rate, I’m now using emacs on a regular basis for editing C/C++ code and got tired of switching buffers manually between header (.h/.hpp) and implementation (.c/.cpp) files. So I hacked a little lisp for my .emacs to make life better. Maybe someone else will find this useful too..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
;; Association list of extension -> inverse extension
(setq exts '(("cpp" . ("hpp" "h"))
             ("hpp" . ("cpp" "c"))
             ("h"   . ("cpp" "c"))))

;; Process the association list of extensions and find the last file
;; that exists
(defun find-other-file (fname fext)
  (dolist (value (cdr (assoc fext exts)) result)
    (if (file-exists-p (concat fname "." value))
        (setq result (concat fname "." value)))))

;; Toggle function that uses the current buffer name to open/find the 
;; other file
(defun toggle-header-buffer()
  (interactive)
  (let ((ext (file-name-extension buffer-file-name))
        (fname (file-name-sans-extension buffer-file-name)))
    (find-file (find-other-file fname ext))))

;; Bind the toggle function to a global key
(global-set-key "\M-t" 'toggle-header-buffer)