Making Emacs Work For Me

Development Consulting



Configuring Emacs: A Yak Shaving Diary

This is my ∞th attempt at creating a readable and maintainable Emacs configuration. I’m hopeful that using Org-Babel and a literate programming style will help tame the bit-rot and spaghettification.

How to use my configuration

Obtaining the source

You can find the latest public version of the configuration in the Github repository. The meat of it (and the source of this document) is the file.


This configuration is intended to be installable from scratch. It uses Cask to specify the package dependencies. Pallet is installed to sync actual installed packages with the dependency spec.

Installation procedure

Issues installing

  • Emacs failing to load pallet can indicate that cask is attempting to install packages using a different Emacs version than the one you’re starting. Check your $PATH and/or aliases.

Graphics and looks

Color theme

Leuven theme is awesome! Except for the font sizes.

(defun single-font-size ()
  "Reset all faces to the height of the default face."
  (dolist (f (face-list))
    (when (not (equal 'default f))
      (set-face-attribute f nil :height 1.0))))

(load-theme 'leuven t)
(add-hook 'after-init-hook


I like Inconsolata, but it doesn’t support a wide range of Unicode characters, so I fall back on DejaVu Sans for those.

(set-face-attribute 'default nil
                    :family "Inconsolata"
                    :height 150
                    :weight 'normal
                    :width 'normal)

(when (functionp 'set-fontset-font)
  (set-fontset-font "fontset-default"
                    (font-spec :family "DejaVu Sans Mono"
                               :width 'normal
                               :size 15.5
                               :weight 'normal)))

Reduce clutter

Remove the toolbar. It’s ugly and I never use it. Also remove the scroll bars; below, I set up the fringe to show my position in a buffer.

(when (window-system)
  (tool-bar-mode -1)
  (scroll-bar-mode -1))

When running emacs in a terminal, remove the menu bar.

(when (not (window-system))
  (menu-bar-mode -1))

Fringe decorations

The fringe is the vertical region at the right and left of the buffer. Emacs lets you customize it of course.

Here I set up git diffs and buffer position in the fringe.

(when (window-system)
  (require 'git-gutter-fringe))

(global-git-gutter-mode +1)

(setq-default indicate-buffer-boundaries 'left)
(setq-default indicate-empty-lines +1)

Mode line

I’m using smart mode line to clean up the modeline display a little.

(sml/apply-theme 'light)
(setq sml/shorten-directory t)
(setq sml/shorten-modes t)
(nyan-mode +1)
(setq nyan-wavy-trail nil)
(setq nyan-animate-nyancat t)

I like to see the current time.

(setq display-time-24hr-format t)
(display-time-mode +1)

There’s a lot of modes that I don’t need to see.

(add-to-list 'after-init-hook
             (lambda ()
               (dolist (m '(projectile company git-gutter eldoc paredit))
                          (diminish (my/->mode m) ""))))

Scrolling behavior

Emacs’s default scrolling behavior, like a lot of the default Emacs experience, is pretty idiosyncratic. The following snippet makes for a smoother scrolling behavior when using keyboard navigation.

(setq redisplay-dont-pause t
      scroll-margin 1
      scroll-step 1
      scroll-conservatively 10000
      scroll-preserve-screen-position 1)

This snippet makes mouse wheel and trackpad scrolling bearable. Scroll in 1-line increments the buffer under the mouse.

(setq mouse-wheel-follow-mouse 't)
(setq mouse-wheel-scroll-amount '(1 ((shift) . 1)))

Buffer names

Setup uniquify so that non-unique buffer names get the parent path included to make them unique.

(require 'uniquify)
(setq uniquify-buffer-name-style 'forward)

Window systems and terminals.

Emacs runs very fine in a terminal as is, but there are a few tweaks that make terminal usage even nicer.

Make mouse clicks work in xterm (and iTerm).

(when (not (window-system))
  (xterm-mouse-mode +1))

Prefer single frames

(setq ediff-window-setup-function 'ediff-setup-windows-plain)

Start up

Start with an empty scratch buffer in org mode; no start up screen.

(setq inhibit-startup-screen +1)
(setq initial-major-mode 'org-mode)
(setq initial-scratch-message nil)

Formatting and white-space

(setq-default indent-tabs-mode nil)

(defun my/clean-buffer-formatting ()
  "Indent and clean up the buffer"
  (indent-region (point-min) (point-max))

(global-set-key "\C-cn" 'my/clean-buffer-formatting)

;; by default,
;; highlight trailing whitespace
;; and show form-feed chars as horizontal rules

(defun my/general-formatting-hooks ()
  (setq show-trailing-whitespace 't)
  (my/turn-on 'form-feed))

(dolist (mode-hook (my/normal-mode-hooks))
  (add-hook mode-hook 'my/general-formatting-hooks))

(defun fixup-json ()
  "Re-indent json buffers with broken literal strings. Needs jsonpp installed (available using homebrew)"
  (shell-command-on-region (point-min) (point-max) "sed -e ':a' -e 'N' -e '$!ba' -e 's/\\n/ /g'|jsonpp"  nil t))

Text (non-code) formatting

For writing text, I prefer Emacs to do line wrapping for me. Also, superfluous white-space should be shown.

(defun my/text-formatting-hooks ()
  (my/turn-on 'auto-fill)) ; turn on automatic hard line wraps

(add-hook 'text-mode-hook


General programming

I want to use pretty-symbols mode for all programming.

(setq my/clojure-mode-symbol-patterns
      '((?λ "\\<fn\\>" (clojure-mode))))

(dolist ((p my/clojure-mode-symbol-patterns))
  (add-to-list 'pretty-symbol-patterns p))

(setq pretty-symbol-categories '(lambda))

(defun my/prog-mode-hooks ()
  (my/turn-on 'pretty-symbols))

(add-hook 'prog-mode-hook

Pair programming

Normally, I think line numbers in code editors just take up space, but they can be useful when pair programming; calling out a line number is probably more efficient than pointing at the screen.

I wrapped this in a global minor mode so turning that stuff on and off is easy.

(define-minor-mode my/pair-programming-mode
  "Toggle visualizations for pair programming.

Interactively with no argument, this command toggles the mode.  A
positive prefix argument enables the mode, any other prefix
argument disables it.  From Lisp, argument omitted or nil enables
the mode, `toggle' toggles the state.

This turns on hightlighting the current line, line numbers and
  ;; The initial value.
  ;; The indicator for the mode line.
  " Pairing"
  ;; The minor mode bindings.
  :group 'my/pairing
  (my/set-modes (if my/pair-programming-mode 1 -1)
                '(linum hl-line command-log)))

(define-global-minor-mode my/global-pair-programming-mode
  (lambda () (my/pair-programming-mode 1)))

(global-set-key "\C-c\M-p" 'my/global-pair-programming-mode)


For lisp code, I want ParEdit plus general highlighting etc.

(setq my/lisps
      '(emacs-lisp lisp clojure))

;;  Install local bindings for paredit that work under ssh/terminal
(require 'paredit)
(define-key paredit-mode-map
  (kbd "C-c s <right>")

(define-key paredit-mode-map
  (kbd "C-c s <left>")

(defun my/general-lisp-hooks ()
  (my/turn-on 'paredit

(dolist (mode (mapcar 'my/->mode-hook my/lisps))
  (add-hook mode

Emacs Lisp

(defun my/emacs-lisp-hooks ()
  (my/turn-on 'eldoc-mode))

(add-hook 'emacs-lisp-mode-hook 'my/emacs-lisp-hooks)


I’m using CIDER (formerly nrepl.el) for clojure source/repl interaction.

(defun my/cider-mode-hooks ()
  "Clojure specific setup code that should only be run when we
  have a CIDER REPL connection"

(add-hook 'cider-mode-hook

(setq cider-repl-history-file (expand-file-name "~/.emacs.d/.cider-repl-history"))

Clojure-specific enhancements to lisp config.

(require 'clojure-mode-extra-font-locking)

(defun my/clojure-mode-hooks ()
  (my/turn-on 'subword)
  (my/turn-on 'clj-refactor))

(add-hook 'clojure-mode-hook

(cljr-add-keybindings-with-prefix "C-c r")

I treat the REPL mode specially, since certain hooks that work in clojure-mode won’t make sense or break functionality in cider-repl-mode.

(defun my/cider-repl-mode-hooks ()
  (my/turn-on 'paredit

(add-hook 'cider-repl-mode-hook


Tell Emacs rake files are Ruby files.

(dolist (exp '("Rakefile\\'" "\\.rake\\'"))
  (add-to-list 'auto-mode-alist
               (cons exp 'ruby-mode)))

Having some kind of navigation support for rails projects can be very handy. I’ve contributed a few things to Emacs-Rails mode in the past, but for the moment, I’m going to try the slightly more light-weight Rinari mode.

(global-rinari-mode +1)


I still occasionally need to work on Perl code, so I have a few basic settings to make that reasonably painless.

(fset 'perl-mode 'cperl-mode) ;; force cperl mode

(defun my/cperl-mode-hooks ()
  (my/turn-on 'flycheck))

(add-hook 'cperl-mode-hook 'my/cperl-mode-hooks)


I use JS2-mode for javascript source.

(add-to-list 'auto-mode-alist '("\\.js[x]?\\'" . js2-mode))


For JSON-formatted files, I use the default js-mode, which accepts top-level bare objects (which is incorrect behaviour for javascript, but the default in JSON).

(add-to-list 'auto-mode-alist '("\\.json\\'\\|\\.jshintrc\\'" . js-mode))

(setq js-indent-level 2)


(add-hook 'css-mode-hook

Compilation mode improvements

ANSI Colors


(require 'ansi-color)
(defun colorize-compilation-buffer ()
  (ansi-color-apply-on-region (point-min) (point-max))
(add-hook 'compilation-filter-hook 'colorize-compilation-buffer)

Follow output

(setq compilation-scroll-output t)

Database client

Don’t wrap lines (query rows) when working with a database.

(add-hook 'sql-interactive-mode-hook
          (lambda ()
            (toggle-truncate-lines t)))


Make dired-move and friends default to “other dired window” if there is one.

(setq dired-dwim-target t)

TODO Auto Complete

Getting auto completion to work right tends to be a messy process of trial and error, though in recent years the situation has improved, with auto-complete mode being more or less the defacto standard.

  • Fuzzy matching isn’t working the way I expected, though. Need to work on that.
;; (require 'fuzzy)
;; (require 'auto-complete)
;; (setq ac-auto-show-menu t
;;       ac-quick-help-delay 0.5
;;       ac-use-fuzzy t)
;; (global-auto-complete-mode +1)

Company mode seems to be better supported by CIDER, so let’s try that for now.

(require 'company)
(add-hook 'after-init-hook 'global-company-mode)

Global key bindings

As far as reasonable, I try to keep my custom key bindings within the “official” restraints. Specifically, I want my global key bindings to start with C-c [lower case letter].

(global-set-key "\C-cg" 'magit-status)
(global-set-key "\C-cq" 'delete-indentation)
(global-set-key "\C-cx" 'er/expand-region)
(global-set-key "\C-ct" 'git-timemachine)
(global-set-key "\C-s" 'isearch-forward-regexp)


When tracking a branch from a remote, use the same name.

    (setq magit-default-tracking-name-function #'magit-default-tracking-name-branch-only)
(setq magit-last-seen-setup-instructions "1.4.0")

Global navigation

I like ido and smex for narrowing down files, commands, buffers etc.


Projectile is useful. Especially, projectile-replace and projectile-find-file.

Projectile commands are bound with the default C-c p prefix. So I can type C-c p C-h to list all of them.

Org Mode


Use Dropbox for syncing my agenda files with my Android phone. Worry about the security implications later.

(setq org-mobile-directory "~/Dropbox/MobileOrg")

Global keys

Short key bindings for capturing notes/links and switching to agenda.

(global-set-key "\C-cl" 'org-store-link)
(global-set-key "\C-cc" 'org-capture)
(global-set-key "\C-ca" 'org-agenda)
(global-set-key "\C-cb" 'org-iswitchb)

Org-Agenda needs to be loaded before calling org-agenda works.

(require 'org-agenda)

I prefer a forthnight’s overview on the agenda.

(setq org-agenda-span 14)

Store new notes in ~/org/

(setq org-default-notes-file (concat org-directory "/"))

Notes / Tasks / TODOs

Make custom markers for todo items:

something that needs to be done at some point. If it has a date, it should be done on that day but it may be moved.
something that’s awaiting feedback from someone else. If it has a date, it needs followup if there hasn’t been any feedback at that time.
a scheduled meeting and cannot easily be rescheduled.
In progress, needs to be finished
can be ignored. May include a note on why it’s been cancelled.
(setq org-todo-keywords
      '((sequence "TODO(t)" "DOING(i)" "PENDING(p)" "MEETING(m)" "|" "DONE(d)" "CANCELED(c)")))

Automatically mark todo items with todo subitems as DONE when all subitems are done.

(defun my-org-autodone (n-done n-not-done)
  "Switch entry to DONE when all subentries are done, to TODO otherwise."
  (let (org-log-done org-log-states)   ; turn off logging
    (org-todo (if (= n-not-done 0) "DONE" "TODO"))))

(add-hook 'org-after-todo-statistics-hook 'my-org-autodone)

I want to file and refile notes to any main header in any file in my org-agenda-files list.

(setq org-refile-targets '((nil :level . 1)
                           (org-agenda-files :level . 1)))


Fontifying source blocks

Enable syntax highlighting in src blocks.

(setq-default org-src-fontify-natively t)

Use the minted package for syntax highlighting source blocks in LaTeX / PDF exports. Configuration copied from a blog post by Florian Bergmann.

;; Include the latex-exporter
(require 'ox-latex)
;; Add minted to the defaults packages to include when exporting.
(add-to-list 'org-latex-packages-alist '("" "minted"))
;; Tell the latex export to use the minted package for source
;; code coloration.
(setq org-latex-listings 'minted)
;; Let the exporter use the -shell-escape option to let latex
;; execute external programs.
;; This obviously and can be dangerous to activate!

;; I use pdflatex instead of xelatex because that seems to work
;; much better with utf-8 files
(setq org-latex-pdf-process
      '("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
        "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
        "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))

Untangle files.

(global-set-key "\C-cu" 'my/org-babel-untangle)

(defun my/org-babel-untangle (path)
  (interactive "fFile to include: ")
  (message "Untangling '%s'..." path)
    (let ((lang (save-current-buffer
                  (set-buffer (find-file-noselect path))
                  (my/mode->language major-mode))))
      (insert (format "\n** %s\n\n#+BEGIN_SRC %s :tangle %s\n"
                      (capitalize (replace-regexp-in-string "\\[_-\\]" " " (file-name-base path)))
                      (file-relative-name path)))
      (forward-char (cadr (insert-file-contents path)))
      (insert "\n#+" "END_SRC\n"))))

(defun my/mode->language (mode)
  "Return the language for the given mode"
  (intern (replace-regexp-in-string "\\-mode$" "" (my/->string mode))))

(defun my/org-babel-untangle-tree (path)
  (interactive "Droot directory to untangle: ")
  (mapc 'my/org-babel-untangle
        (cl-remove-if 'file-directory-p
                      (f-files path (lambda (p) t) t))))

Language evaluation support

Org-Babel needs to be told that evaluation of certain languages is allowed. I collect all languages here, then enable all of them at the end of the section.

;; List of languages that may be evaluated in Org documents
(setq my/org-babel-evaluated-languages
  '(emacs-lisp sh))


 (mapcar (lambda (lang)
           (cons lang t))


I like Graphviz for generating graphs. It takes a few lines of code to link graphviz’s dot mode to org-babel so I can include dot source in org mode and export with nice looking diagrams.

(add-to-list 'org-src-lang-modes (quote ("dot" . graphviz-dot)))

(add-to-list 'my/org-babel-evaluated-languages 'dot)

Ditaa is another nice package for turning ASCII art into PNG/EPS diagrams. Turn that on, too.

(add-to-list 'my/org-babel-evaluated-languages 'ditaa)

PlantUml is built on top of Graphviz.

(add-to-list 'my/org-babel-evaluated-languages 'plantuml)

Exporting to slides

(require 'ox-latex)
(require 'ox-beamer)

Configuration file layout

Here I define the emacs.el file that gets generated by the code in this org file.

;;;; Do not modify this file by hand.  It was automatically generated
;;;; from `` in the same directory. See that file for more
;;;; information.
;;;; If you cannot find the `` file, see the source
;;;; repository at

(defvar outline-minor-mode-prefix "\M-#")


This section defines some functionality used elsewhere in this configuration.

Hooks and modes

(defun my/->string (str)
   ((stringp str) str)
   ((symbolp str) (symbol-name str))))

(defun my/->mode-hook (name)
  "Turn mode name into hook symbol"
  (intern (replace-regexp-in-string "\\(-mode\\)?\\(-hook\\)?$"
                                    (my/->string name))))

(defun my/->mode (name)
  "Turn mode name into mode symbol"
  (intern (replace-regexp-in-string "\\(-mode\\)?$"
                                    (my/->string name))))

(defun my/set-modes (arg mode-list)
  (dolist (m mode-list)
    (if (fboundp (my/->mode m))
        (funcall (my/->mode m) arg)
      (message "No mode %s found" m))))

(defun my/turn-on (&rest mode-list)
  "Turn on the given (minor) modes."
  (my/set-modes +1 mode-list))

(defvar my/normal-base-modes
  (mapcar 'my/->mode '(text prog))
  "The list of modes that are considered base modes for
  programming and text editing. In an ideal world, this should
  just be text-mode and prog-mode, however, some modes that
  should derive from prog-mode derive from fundamental-mode
  instead. They are added here.")

(defun my/normal-mode-hooks ()
  "Returns the mode-hooks for `my/normal-base-modes`"
  (mapcar 'my/->mode-hook my/normal-base-modes))


OSX doesn’t set the environment from the shell init files for graphical applications, but I set PATH and a bunch of other stuff there. The exec-path-from-shell package will take care of that. Thanks to Ting-Yu Lin for pointing it out.

(when (memq window-system '(mac ns))

External packages may be dropped in the .emacs.d/ext directory.

(add-to-list 'load-path "~/.emacs.d/ext")

Options set using the customize interface

By default, Emacs saves the options you set via the `customize-*` functions in the user init file, which is “~/.emacs.d/init.el” in this setup. I prefer to have it put that data in a seperate file.

(setq custom-file "~/.emacs.d/custom.el")
(load custom-file)