My Emacs Configuration

Or: Emacs is Agar for Brain Worms

2020-09-14

This is my Emacs configuration, assembled over the course of more than ten years. I first started using Emacs in 2009 out of sheer necessity—I first learned to code using TextMate, but that wasn’t an option upon, after arriving at college, being required to SSH into some creaky Sun boxes running geologically-ancient versions of Solaris. As of this writing, it is 2020, some eleven years into my Emacs journey, and I have an incurable case of Emacs-induced brain worms; I’ve spent on the order of hundreds of hours tweaking and refining my configuration. This file is the result of that process.

If there’s anything that convinced me to take on this lifelong Emacs habit, it’s because both macOS and iOS come, out of the box, with support for Emacs keybindings in their text areas. Said keybindings aren’t hugely exhaustive, but they’re useful, especially given that the Ctrl-k and Ctrl-y inputs for copy and paste operate on a different pasteboard than do ⌘C and ⌘V. Once I discovered that, and the dorkily exhiliating feeling of juggling information through the various system pasteboards, I was more or less entirely beholden to the Emacs way, despite the merits of modal editingI’ve tried to reconfigure my brain to use modal editing, to little avail, but its model of a domain-specific-language for text editing is a hugely exciting one to me.

. But the forcing factor was, after I left Apple, arriving at a job where I had to test C code on macOS, Linux, FreeBSD, and SmartOS. The difficulty of remembering keyboard shortcuts between TextMate, Sublime Text, and Emacs was leagues beyond insupportable, and as such I took the Emacs plunge.

This file is an Org-mode document, like all the posts on my blog. And if you’re reading it on my blog in HTML form, it is because my blog pulls in my Emacs configuration as a submodule, and a conveniently-placed symlink means that it is treated like any other post, and its embedded code is rendered in fancy code blocks. If you’re reading it on its GitHub repository, you’ll see it rendered inline in the repository, as its filename is readme.org. And at Emacs boot time, Emacs itself runs org-babel, generates elisp code out of the code snippets embedded herein, and loads it; further updates to the blog entry are a git submodule command away. I feel both delight and shame in equal quantities at this state of affairs: having a really cherried-out, custom-builtMy configuration is not built atop one of the all-in-one Emacs distributions like Spacemacs or Doom Emacs. I probably would have if either had been around at the beginning of my Emacs journey, but at this point my own personal set of key bindings is burnt into my brain.

Emacs setup is one of those things that’s cool because of how uncool it is, like growing giant vegetables at a county fair, or being really good at Connect Four.

Yet I don’t feel bad about publishing something this self-indulgent. Not only because maybe it’ll demystify what the care and feeding of a very-intense Emacs setup looks like, and also because yak-shaving is an excellent way to occupy myself in quarantine Hello, future generations! If you’re reading this, please believe me when I say that 2020 was a truly enervating time to be a human being.

, but because I’m happier with my setup as an org-mode document, as Emacs configurations generally have a high propensity for entropy: it’s easy to leave a few computer-specific hacks in some dusty corner of a config, and then, upon returning years later, having absolutely no idea what that hack does. Forcing a literate style guilts me into documenting every inch of it. In addition, I have been thanked by strangers for the quality of my config, and my coworker described it as “inspiring”, which seems like sufficient justification to continue, at least with respect to my ego.

This configuration assumes you’re running Emacs 28, the latest version (though I live off of HEAD). Note that I strongly, strongly recommend using an Emacs built with native compilation enabled. The difference in speed is truly profound. Getting libgccjit and friends set up can be a bit of a bear (I use this script on macOS), but it’s absolutely essential if you want to live in Emacs to the degree that I do.

The most up-to-date version of this document is located on GitHub. A better-rendered version can be found on my blog, but might not be as current as the first version.

TODOs

  • Make a popper function that gives Magit a bit more breathing room

Configuration: start!

Preliminaries

We have to be sure to set lexical-binding in the file header to opt into Emacs lexical scope. Emacs Lisp really isn’t the worst language once you pull in the community’s de facto standard libraries, but you need lexical scope.

;; -*- coding: utf-8; lexical-binding: t -*-

Many of Emacs’s defaults are ill-suited for my purposes, but the first one that needs fixing is the shockingly low garbage-collection threshold, which defaults to a paltry 8kb. Setting it to 100mb seems to strike a nice balance between GC pauses and performance.

(setq gc-cons-threshold 100000000)

We use use-package everywhere (it is loaded in the init.el that bootstraps this whole enterprise), save for packages already built into Emacs, and by default we want it to install all mentioned packages. There are some bugs associated with this approach, I am told, but it tends to work for me, and if I get a message about a missing package I just call package-install.

(setq use-package-always-ensure t)

The most useful Emacs command is execute-extended-command. It should be painless to access from the home row. (bind-key* ensures that this setting is propagated through all major modes, which saves us a bunch of unbind-key calls in use-package stanzas.) Why not something even easier, like C-;, you ask? Unfortunately, macOS Terminal.app swallows that keybinding and does nothing with it. I’m sure this is correct behavior by some sort of standard, but I have to work around it, since occasionally I do use Emacs in the terminal.

(bind-key* "C-c ;" #'execute-extended-command)

Since subsequent packages like libgit may depend on executables like cmake, we need to ensure that Emacs has access to the PATH associated with the current environment.

(use-package exec-path-from-shell
  :init (exec-path-from-shell-initialize))

Fixing defaults

Fixing Emacs’s defaults is a nontrivial problem. We’ll start with UI concerns.

(setq
 ;; No need to see GNU agitprop.
 inhibit-startup-screen t
 ;; No need to remind me what a scratch buffer is.
 initial-scratch-message nil
 ;; Double-spaces after periods is morally wrong.
 sentence-end-double-space nil
 ;; Never ding at me, ever.
 ring-bell-function 'ignore
 ;; Save existing clipboard text into the kill ring before replacing it.
 save-interprogram-paste-before-kill t
 ;; Prompts should go in the minibuffer, not in a GUI.
 use-dialog-box nil
 ;; Fix undo in commands affecting the mark.
 mark-even-if-inactive nil
 ;; Let C-k delete the whole line.
 kill-whole-line t
 ;; search should be case-sensitive by default
 case-fold-search nil
 ;; no need to prompt for the read command _every_ time
 compilation-read-command nil
 ;; scroll to first error
 compilation-scroll-output 'first-error
 ;; accept 'y' or 'n' instead of yes/no
 ;; the documentation advises against setting this variable
 ;; the documentation can get bent imo
 use-short-answers t
 ;; my source directory
 default-directory "~/src/"
 ;; eke out a little more scrolling performance
 fast-but-imprecise-scrolling t
 ;; prefer newer elisp files
 load-prefer-newer t
 ;; when I say to quit, I mean quit
 confirm-kill-processes nil
 ;; if native-comp is having trouble, there's not very much I can do
 native-comp-async-report-warnings-errors 'silent
 ;; unicode ellipses are better
 truncate-string-ellipsis "…"
 )

;; Never mix tabs and spaces. Never use tabs, period.
;; We need the setq-default here because this becomes
;; a buffer-local variable when set.
(setq-default indent-tabs-mode nil)

It’s good that Emacs supports the wide variety of file encodings it does, but UTF-8 should always, always be the default.

(set-charset-priority 'unicode)
(prefer-coding-system 'utf-8-unix)

We also need to turn on a few modes to have behavior that’s even remotely modern.

(delete-selection-mode t)
(global-display-line-numbers-mode t)
(column-number-mode)

Emacs 27 comes with fast current-line highlight functionality, but it can produce some visual feedback in vterm buffers, so we only activate it in programming or text modes.

(require 'hl-line)
(add-hook 'prog-mode-hook #'hl-line-mode)
(add-hook 'text-mode-hook #'hl-line-mode)

Emacs is super fond of littering filesystems with backups and autosaves, since it was built with the assumption that multiple users could be using the same Emacs instance on the same filesystem. This was valid in 1980. It is no longer the case.

(setq
 make-backup-files nil
 auto-save-default nil
 create-lockfiles nil)

By default, Emacs stores any configuration you make through its UI by writing custom-set-variables invocations to your init file, or to the file specified by custom-file. Though this is convenient, it’s also an excellent way to cause aggravation when the variable you keep trying to modify is being set in some custom-set-variables invocation. We can disable this by mapping it to a temporary file. (I used to map this to /dev/null, but this started causing a bunch of inane save dialogues.)

(setq custom-file (make-temp-name "/tmp/"))

However, because Emacs stores theme-safety information in that file, we have to disable the warnings entirely. This is not particularly secure, but if someone has uploaded malicious code to MELPA inside a theme, I have bigger problems. (Besides, Emacs is not a secure system, and I see no need to try overmuch to make it one.)

(setq custom-safe-themes t)

Don’t copy this to your config. This just prevents inexplicable failures from elpa.

(setq package-check-signature nil)

By default, the list of recent files gets cluttered up with the contents of downloaded packages.

(use-package recentf
  :config
  (add-to-list 'recentf-exclude "\\elpa")
  (add-to-list 'recentf-exclude "private/tmp")
  (recentf-mode))

Emoji don’t work on Emacs versions < 27 (aside from the Mitsuharu Yamamoto emacs-mac port). However, we can just do this.

(set-fontset-font "fontset-default" 'unicode "Apple Color Emoji" nil 'prepend)

These libraries are helpful to have around when writing little bits of elisp, like the below. You can’t possibly force me to remember the difference between the mapcar, mapc, mapcan, mapconcat, and the cl- versions of some of the aforementioned. I refuse.

(use-package s)
(use-package dash)

There are a great many keybindings that are actively hostile, in that they are bound to useless or obsolete functions that are really easy to trigger accidentally. (The lambda is because unbind-key is a macro.)

(-map (lambda (x) (unbind-key x)) '("C-x C-f" ;; find-file-read-only
                                    "C-x C-d" ;; list-directory
                                    "C-z" ;; suspend-frame
                                    "C-x C-z" ;; again
                                    "M-o" ;; facemenu-mode
                                    "<mouse-2>" ;; pasting with mouse-wheel click
                                    "<C-wheel-down>" ;; text scale adjust
                                    "<C-wheel-up>" ;; ditto
                                    "s-n" ;; make-frame
                                    "C-x C-q" ;; read-only-mode
                                    ))

By default, I want paste operations to indent their results. I could express this as defadvice around the yank command, but I try to avoid such measures if possible.

(defun pt/yank ()
  "Call yank, then indent the pasted region, as TextMate does."
  (interactive)
  (let ((point-before (point)))
    (if mark-active (call-interactively 'delete-backward-char))
    (yank)
    (indent-region point-before (point))))

(bind-key "C-y" #'pt/yank)
(bind-key "s-v" #'pt/yank)
(bind-key "C-Y" #'yank)

Searching should be done with isearch, for UI purposes.

(bind-key "C-s" #'isearch-forward-regexp)
(bind-key "C-c s" #'isearch-forward-symbol)

The out-of-the-box treatment of whitespace is unfortunate, but fixable.

(add-hook 'before-save-hook #'delete-trailing-whitespace)
(setq require-final-newline t)

Emacs instances started outside the terminal do not pick up ssh-agent information unless we use keychain-environment. Note to self: if you keep having to enter your keychain password on macOS, make sure this is in .ssh/config:

Host *
  UseKeychain yes
(use-package keychain-environment
  :config
  (keychain-refresh-environment))

Emacs is also in love with showing you its NEWS file; it’s bound to like four different keybindings. Overriding the function makes it a no-op. You might say… no news is good news. For that matter, we can elide more GNU agitprop.

(defalias 'view-emacs-news 'ignore)
(defalias 'describe-gnu-project 'ignore)

Undo has always been problematic for me in Emacs. The beauty of undo-tree is that it means that, once you’ve typed something into a buffer, you’ll always be able to get it back. At least in theory. undo-tree has long-standing data loss bugs that are unlikely to be fixed. But no other package provides a comparable experience.

(use-package undo-tree
  :diminish
  :bind (("C-c _" . undo-tree-visualize))
  :config
  (global-undo-tree-mode +1)
  (unbind-key "M-_" undo-tree-map))

I define a couple of my own configuration variables with defvar, and no matter how many times I mark the variable as safe, it warns me every time I set it in the .dir-locals file. Disabling these warnings is probably (?) the right thing to do.

(setq enable-local-variables :all)

By default, Emacs wraps long lines, inserting a little icon to indicate this. I find this a bit naff. What we can do to mimic more modern behavior is to allow line truncation by default, but also allow touchpad-style scrolling of the document.

(setq mouse-wheel-tilt-scroll t
      mouse-wheel-flip-direction t)
(setq-default truncate-lines t)

By default, Emacs ships with a nice completion system based on buffer contents, but inexplicably cripples its functionality by setting this completion system to ignore case in inserted results. Absolutely remarkable choice of defaults.

(use-package dabbrev
  :bind (("C-/" . #'dabbrev-completion))
  :custom
  (dabbrev-case-replace nil))

;; TODO: I want to use the fancy-dabbrev package everywhere,
;; but it uses popup.el rather than read-completion, and
;; I don't like how quickly it operates on its inline suggestions

Visuals

Emacs looks a lot better when it has a modern monospaced font and VSCode-esque icons, as well as smooth scrolling.

(ignore-errors (set-frame-font "JuliaMono-12"))

(use-package all-the-icons)

(use-package all-the-icons-dired
  :after all-the-icons
  :hook (dired-mode . all-the-icons-dired-mode))

Every Emacs window should, by default occupy all the screen space it can.

(add-to-list 'default-frame-alist '(fullscreen . maximized))

Window chrome both wastes space and looks unappealing. (This is actually pasted into the first lines of my Emacs configuration so I never have to see the UI chrome, but it is reproduced here for the sake of people who might be taking this configuration for a spin themselves.)

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

I use the Doom Emacs themes, which are gorgeous. I sometimes also use Modus Vivendi, the excellent new theme that now ships with Emacs.

(use-package doom-themes
  :config
  (let ((chosen-theme 'doom-rouge))
    (doom-themes-visual-bell-config)
    (doom-themes-org-config)
    (setq doom-challenger-deep-brighter-comments t
          doom-challenger-deep-brighter-modeline t
          doom-rouge-brighter-comments t
          doom-ir-black-brighter-comments t
          modus-themes-org-blocks 'gray-background
          doom-dark+-blue-modeline nil)
    (load-theme chosen-theme)))

Most major modes pollute the modeline, so we pull in diminish.el to quiesce them.

(use-package diminish
  :config
  (diminish 'visual-line-mode))

The default modeline is pretty uninspiring, and mood-line is very minimal and pleasing.

(use-package mood-line
  :config (mood-line-mode))

I find it useful to have a slightly more apparent indicator of which buffer is active at the moment.

(use-package dimmer
  :custom (dimmer-fraction 0.3)
  :config (dimmer-mode))

Highlighting the closing/opening pair associated with a given parenthesis is essential. Furthermore, parentheses should be delimited by color. I may be colorblind, but it’s good enough, usually.

(use-package paren
  :config (show-paren-mode)
  :custom (show-paren-style 'expression))

(use-package rainbow-delimiters
  :hook ((prog-mode . rainbow-delimiters-mode)))

It’s nice to have the option to center a window, given the considerable size of my screen.

(use-package centered-window
  :custom
  (cwm-centered-window-width 180))

Compilation buffers should wrap their lines.

(add-hook 'compilation-mode-hook 'visual-line-mode)

Tree-sitter

As part of my day job, I hack on the tree-sitter parsing toolkit. Pleasingly enough, the parsers generated by tree-sitter can be used to spruce up syntax highlighting within Emacs: for example, highlighting Python with emacs-tree-sitter will correctly highlight code inside format strings, which is really quite useful. Note that for this to work you have to add the tree-sitter ELPA server.

(use-package tree-sitter
  :hook ((ruby-mode . tree-sitter-hl-mode)
         (js-mode . tree-sitter-hl-mode)
         (rust-mode . tree-sitter-hl-mode)
         (sh-mode . tree-sitter-hl-mode)
         (c-mode . tree-sitter-hl-mode)
         (typescript-mode . tree-sitter-hl-mode)
         (go-mode . tree-sitter-hl-mode)))
(use-package tree-sitter-langs)

Tabs

The long-awaited Emacs 27 support for native tabs is shaky, both visually and in terms of functionality. As such, centaur-tabs is the best way to simulate a conventional tabs setup, in which tab sets are grouped by the toplevel project working directory.

(use-package centaur-tabs
  :config
  (centaur-tabs-mode t)
  :custom
  (centaur-tabs-set-icons nil)
  (centaur-tabs-show-new-tab-button nil)
  (centaur-tabs-set-close-button nil)
  (centaur-tabs-enable-ido-completion nil)

  :bind
  (("s-{" . #'centaur-tabs-backward)
   ("s-}" . #'centaur-tabs-forward)))

Text manipulation

Being able to

Any modern editor should include multiple-cursor support. Sure, keyboard macros would suffice, sometimes. Let me live. I haven’t yet taken advantage of many of the multiple-cursors commands. Someday.

(use-package multiple-cursors
  :bind (("C-c C-e m" . #'mc/edit-lines)
         ("C-c C-e d" . #'mc/mark-all-dwim)))

The fill-paragraph (M-q) command can be useful for formatting long text lines in a pleasing matter. I don’t do it in every document, but when I do, I want more columns than the default 70.

(setq-default fill-column 135)

Textmate-style tap-to-expand-into-the-current-delimiter is very useful and curiously absent.

(use-package expand-region
  :bind (("C-c n" . er/expand-region)))

Emacs’s keybinding for comment-dwim is M-;, which is not convenient to type or particularly mnemonic outside of an elisp context (where commenting is indeed ;). Better to bind it somewhere sensible.

(bind-key* "C-c /" #'comment-dwim)

avy gives us fluent jump-to-line commands mapped to the home row.

(use-package avy
  :bind (:map prog-mode-map ("C-'" . avy-goto-line))
  :bind (:map org-mode-map ("C-'" . avy-goto-line))
  :bind (("C-c l" . avy-goto-line)
         ("C-c j" . avy-goto-char)))

iedit gives us the very popular idiom of automatically deploying multiple cursors to edit all occurrences of a particular word.

(use-package iedit :defer t)

Parenthesis matching is one of the flaws in my Emacs setup as of this writing. I know that there are a lot of options out there—paredit, smartparens, etc.—but I haven’t sat down and really capital-L Learned a better solution than the TextMate-style bracket completion (which Emacs calls, somewhat fancifully, ‘electric’).

(electric-pair-mode)

I got used to a number of convenient TextMate-style commands.

(defun pt/eol-then-newline ()
  "Go to end of line, then newline-and-indent."
  (interactive)
  (move-end-of-line nil)
  (newline-and-indent))

(bind-key "s-<return>" #'pt/eol-then-newline)

It’s occasionally useful to be able to search a Unicode character by name. And it’s a measure of Emacs’s performance, when using native-comp and Vertico, that you can search the entire Unicode character space without any keystroke latency.

(bind-key "C-c U" #'insert-char)

Quality-of-life improvements

We start by binding a few builtin commands to more-convenient keystrokes.

(defun pt/split-window-thirds ()
  "Split a window into thirds."
  (interactive)
  (split-window-right)
  (split-window-right)
  (balance-windows))

(bind-key "C-c 3" #'pt/split-window-thirds)

Given how often I tweak my config, I bind C-c e to take me to my config file.

(defun open-init-file ()
  "Open this very file."
  (interactive)
  (find-file "~/.config/emacs/readme.org"))

(bind-key "C-c e" #'open-init-file)

Standard macOS conventions would have s-w close the current buffer, not the whole window.

(bind-key "s-w" #'kill-this-buffer)

Emacs makes it weirdly hard to just, like, edit a file as root, probably due to supporting operating systems not built on sudo. Enter the sudo-edit package.

(use-package sudo-edit)

By default, Emacs uses a new buffer for every directory you visit in dired. This is not only terrible from a UI perspective—Emacs warns you if you try to use the sensible behavior (the a key, dired-find-alternate-file). Willfully obtuse. The dired+.el library fixes this, but because it’s not on MELPA, I refuse to use it out of principle (this man’s refusal to compromise is nothing short of crankery, and it would be intellectually remiss of me to abet his crankery). But, as always, we can make Emacs do the right thing. Manually. Furthermore, dired complains every time it’s opened on Darwin, so we should fix that.

(defun dired-up-directory-same-buffer ()
  "Go up in the same buffer."
  (find-alternate-file ".."))

(defun my-dired-mode-hook ()
  (put 'dired-find-alternate-file 'disabled nil) ; Disables the warning.
  (define-key dired-mode-map (kbd "RET") 'dired-find-alternate-file)
  (define-key dired-mode-map (kbd "^") 'dired-up-directory-same-buffer))

(add-hook 'dired-mode-hook #'my-dired-mode-hook)

(setq dired-use-ls-dired nil)

Emacs has problems with very long lines. so-long detects them and takes appropriate action. Good for minified code and whatnot.

(global-so-long-mode)

I’ve never needed a font panel in Emacs, not even once.

(unbind-key "s-t")

It’s genuinely shocking that there’s no “duplicate whatever’s marked” command built-in.

(use-package duplicate-thing
  :init
  (defun pt/duplicate-thing ()
    "Duplicate thing at point without changing the mark."
    (interactive)
    (save-mark-and-excursion (duplicate-thing 1))
    (call-interactively #'next-line))
  :bind (("C-c u" . pt/duplicate-thing)
         ("C-c C-u" . pt/duplicate-thing)))

We need to support reading large blobs of data for LSP’s sake.

(setq read-process-output-max (* 1024 1024)) ; 1mb

When I hit, accidentally or purposefully, a key chord that forms the prefix of some other chords, I want to see a list of possible completions and their info.

(use-package which-key
  :diminish
  :custom
  (which-key-enable-extended-define-key t)
  :config
  (which-key-mode)
  (which-key-setup-minibuffer))
(defun display-startup-echo-area-message ()
  "Override the normally tedious startup message."
  (message "Welcome back."))

Emacs has an executable-prefix-env command that adds a magic shebang line to scripts in interpreted languages. With a little cajoling, it can use env(1) instead of hardcoding the interpreter path, which is slightly more robust in certain circumstances.

(setq executable-prefix-env t)

The new context-menu-mode in Emacs 28 makes right-click a lot more useful. But for terminal emacs, it’s handy to have the menubar at hand.

(context-menu-mode)
(bind-key "C-c C-m" #'tmm-menubar)

Buffer management

I almost always want to default to a two-buffer setup.

(defun revert-to-two-windows ()
  "Delete all other windows and split it into two."
  (interactive)
  (delete-other-windows)
  (split-window-right))

(bind-key "C-x 1" #'revert-to-two-windows)
(bind-key "C-x !" #'delete-other-windows) ;; Access to the old keybinding.

keyboard-quit doesn’t exit the minibuffer, so I give abort-recursive-edit, which does, a more convenient keybinding.

(bind-key "s-g" #'abort-recursive-edit)

Completion systems make kill-buffer give you a list of possible results, which isn’t generally what I want.

(defun kill-this-buffer ()
  "Kill the current buffer."
  (interactive)
  (kill-buffer nil)
  )

(bind-key "C-x k" #'kill-this-buffer)
(bind-key "C-x K" #'kill-buffer)

Also, it’s nice to be able to kill all buffers.

(defun kill-all-buffers ()
  "Close all buffers."
  (interactive)
  (let ((lsp-restart 'ignore))
    ;; (maybe-unset-buffer-modified)
    (delete-other-windows)
    (save-some-buffers)
    (let
        ((kill-buffer-query-functions '()))
      (mapc 'kill-buffer (buffer-list)))))

(bind-key "C-c K" #'kill-all-buffers)

VS Code has a great feature where you can just copy a filename to the clipboard. We can write it in a more sophisticated manner in Emacs, which is nice.

(defun copy-file-name-to-clipboard (do-not-strip-prefix)
  "Copy the current buffer file name to the clipboard. The path will be relative to the project's root directory, if set. Invoking with a prefix argument copies the full path."
  (interactive "P")
  (letrec
      ((fullname (if (equal major-mode 'dired-mode) default-directory (buffer-file-name)))
       (root (project-root (project-current)))
       (relname (file-relative-name fullname root))
       (should-strip (and root (not do-not-strip-prefix)))
       (filename (if should-strip relname fullname)))
    (kill-new filename)
    (message "Copied buffer file name '%s' to the clipboard." filename)))

(bind-key "C-c p" #'copy-file-name-to-clipboard)

Normally I bind other-window to C-c ,, but on my ultra-wide-screen monitor, which supports up to 8 buffers comfortably, holding that key to move around buffers is kind of a drag. Some useful commands to remember here are aw-ignore-current and aw-ignore-on.

(use-package ace-window
  :config
  ;; Show the window designators in the modeline.
  (ace-window-display-mode)

  :bind* (("C-<" . other-window) ("C-," . ace-window))
  :custom
  (aw-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l) "Designate windows by home row keys, not numbers.")
  (aw-background nil))

Emacs allows you to, while the minibuffer is active, invoke another command that uses the minibuffer, in essence making the minibuffer from a single editing action into a stack of editing actions. In this particular instance, I think it’s appropriate to have it off by default, simply for the sake of beginners who don’t have a mental model of the minibuffer yet. But at this point, it’s too handy for me to discard. Handily enough, Emacs can report your current depth of recursive minibuffer invocations in the modeline.

(setq enable-recursive-minibuffers t)
(minibuffer-depth-indicate-mode)

It’s useful to have a scratch buffer around, and more useful to have a key chord to switch to it.

(defun switch-to-scratch-buffer ()
  "Switch to the current session's scratch buffer."
  (interactive)
  (switch-to-buffer "*scratch*"))

(bind-key "C-c a s" #'switch-to-scratch-buffer)

One of the main problems with Emacs is how many ephemeral buffers it creates. I’m giving popper-mode a try to see if it can stem the flood thereof. Note that vterm is not included here because vterm-toggle doesn’t play particularly nicely with popper.

(use-package popper
  :bind* ("C-c :" . popper-toggle-latest)
  :bind (("C-`"   . popper-toggle-latest)
         ("C-\\"  . popper-cycle)
         ("C-M-`" . popper-toggle-type))
  :config
  (popper-mode +1)
  (popper-echo-mode +1)
  :custom
  (popper-reference-buffers '("\\*Messages\\*"
                              "Output\\*$"
                              "\\*Async Shell Command\\*"
                              help-mode
                              prodigy-mode
                              "magit:.\*"
                              "\\*deadgrep.\*"
                              "\\*eldoc.\*"
                              "\\*xref\\*"
                              "\\*direnv\\*"
                              "\\*Warnings\\*"
                              "\\*Bookmark List\\*"
                              haskell-compilation-mode
                              compilation-mode
                              bqn-inferior-mode))
  )

Org-mode

Even though my whole-ass blogging workflow is built around org-mode, I still can’t say that I know it very well. I don’t take advantage of org-agenda, org-timer, org-calendar, org-capture, anything interesting to do with tags, et cetera. Someday I will learn these things, but not yet.

(use-package org
  :hook (org-mode . visual-line-mode)
  :bind (("C-c o c" . counsel-org-capture)
         ("C-c o a" . org-agenda)
         :map org-mode-map
         ("M-<left>" . nil)
         ("M-<right>" . nil)
         ("C-c c" . #'org-mode-insert-code)
         ("C-c a f" . #'org-shifttab)
         ("C-c a S" . #'zero-width))
  :custom
  (org-adapt-indentation nil)
  (org-directory "~/txt")
  (org-default-notes-file (concat org-directory "/notes.org"))
  (org-return-follows-link t)
  (org-src-ask-before-returning-to-edit-buffer nil "org-src is kinda needy out of the box")
  (org-src-window-setup 'current-window)
  (org-agenda-files (list (concat org-directory "/agenda.org")))

  :config
  (defun pt/org-mode-hook ()
    (when (s-suffix? "todo.org" (buffer-file-name (current-buffer)))
      (real-auto-save-mode)))
  (defun make-inserter (c) '(lambda () (interactive) (insert-char c)))
  (defun zero-width () (interactive) (insert "​"))

  (defun org-mode-insert-code ()
    "Like markdown-insert-code, but for org instead."
    (interactive)
    (org-emphasize ?~)))

(use-package org-bullets
  :hook (org-mode . org-bullets-mode))

(use-package org-ref
  :disabled ;; very slow to load
  :config (defalias 'dnd-unescape-uri 'dnd--unescape-uri))

(use-package org-roam
  :bind
  (("C-c o r" . org-roam-capture)
   ("C-c o f" . org-roam-node-find))
  :custom
  (org-roam-directory (expand-file-name "~/Dropbox/txt/roam"))
  (org-roam-v2-ack t)
  :config
  (org-roam-db-autosync-mode))

Keymacs support

I recently acquired a Keymacs A620N, a reproduction of the Symbolics 365407, from 1983. Though it’s expensive, it’s unquestionably the nicest keyboard I’ve ever used, given its vintage ALPS switches; of the keyboards I’ve used, only the keyboard.io comes close. It’s big enough that it has a preposterous amount of function keys.

(bind-key "<f12>" #'other-window)

IDE features

Magit

Magit is one of the top three reasons anyone should use Emacs. What a brilliant piece of software it is. I never thought I’d be faster with a git GUI than with the command line, since I’ve been using git for thirteen years at this point, but wonders really never cease. Magit is as good as everyone says, and more.

(use-package magit
  :diminish magit-auto-revert-mode
  :diminish auto-revert-mode
  :bind (("C-c g" . #'magit-status))
  :custom
  (magit-repository-directories '(("~/src" . 1)))
  :config
  (add-to-list 'magit-no-confirm 'stage-all-changes))

(use-package libgit :after magit)

(use-package magit-libgit
  :after (magit libgit))

Magit also allows integration with GitHub and other such forges (though I hate that term).

(use-package forge
  :after magit)

;; hack to eliminate weirdness
(unless (boundp 'bug-reference-auto-setup-functions)
  (defvar bug-reference-auto-setup-functions '()))

The code-review package allows for integration with pull request comments and such.

(use-package code-review
  :after magit
  :bind (:map forge-topic-mode-map ("C-c r" . #'code-review-forge-pr-at-point))
  :bind (:map code-review-mode-map (("C-c n" . #'code-review-comment-jump-next)
                                    ("C-c p" . #'code-review-comment-jump-previous))))

Project navigation

I used to use Projectile, but marginalia-mode doesn’t appear to work out of the box with it. Besides, there’s no reason to pull in a separate package when the builtin project.el works fine. We pin it to GNU ELPA to pull the latest version.

(use-package project
  :pin gnu
  :bind (("C-c k" . #'project-kill-buffers)
         ("C-c m" . #'project-compile)
         ("C-x f" . #'find-file)
         ("C-c f" . #'project-find-file)
         ("C-c F" . #'project-switch-project))
  :custom
  ;; This is one of my favorite things: you can customize
  ;; the options shown upon switching projects.
  (project-switch-commands
   '((project-find-file "Find file")
     (magit-project-status "Magit" ?g)
     (deadgrep "Grep" ?h)))
  (compilation-always-kill t)
  (project-vc-merge-submodules nil)
  )

Completion and input

My journey through the various Emacs completion facilities has been long and twisty. I started with Helm, then spent several years using Ivy, and am now using Vertico, with the consult and marginalia packages to yield an interface that is nicer and faster than Ivy.

(use-package vertico
  :config
  (vertico-mode)
  (vertico-mouse-mode)
  :custom
  (vertico-count 22)
  :bind (:map vertico-map
              ("C-'"       . #'vertico-quick-exit)
              ;; Have to rebind this because C-m is translated to RET.
              ("<return>"  . #'exit-minibuffer)
              ("C-m"       . #'vertico-insert)
              ("C-c SPC"   . #'vertico-quick-exit)
              ("DEL"       . #'vertico-directory-delete-char)))

(use-package consult
  :config
  (defun pt/yank-pop ()
    "As pt/yank, but calling consult-yank-pop."
    (interactive)
    (let ((point-before (point)))
      (consult-yank-pop)
      (indent-region point-before (point))))

  :bind (("C-c i"   . #'consult-imenu)
         ("C-c b"   . #'consult-buffer)
         ("C-x b"   . #'consult-buffer)
         ("C-c r"   . #'consult-recent-file)
         ("C-c y"   . #'pt/yank-pop)
         ("C-c R"   . #'consult-bookmark)
         ("C-c `"   . #'consult-flymake)
         ("C-c h"   . #'consult-ripgrep)
         ("C-x C-f" . #'find-file)
         ("C-h a"   . #'consult-apropos)
         )
  :custom
  (completion-in-region-function #'consult-completion-in-region)
  (xref-show-xrefs-function #'consult-xref)
  (xref-show-definitions-function #'consult-xref)
  (consult-project-root-function #'deadgrep--project-root) ;; ensure ripgrep works
  )

(use-package marginalia
  :config (marginalia-mode))

(use-package orderless
  :custom (completion-styles '(orderless)))

(use-package ctrlf
  :config (ctrlf-mode))

(use-package prescient
  :config (prescient-persist-mode))

Dumb-jump is pretty good at figuring out where declarations of things might be. I’m using it with C because I’m too lazy to set up true C LSP integration.

(use-package dumb-jump
  :bind (("C-c J" . #'dumb-jump-go)))

embark is a cool package for discoverability.

(use-package embark :bind ("C-c E" . #'embark-act))

Searching

deadgrep is the bee’s knees for project-wide search, as it uses ripgrep. I defer to the faster and live-previewing consult-ripgrep, but sometimes deadgrep is more useful.

(use-package deadgrep
  :bind (("C-c H" . #'deadgrep)))

I remember the days before Emacs had real regular expressions. Nowadays, we have them, but the find-and-replace UI is bad. visual-regexp fixes this. I have this bound to an incredibly stupid keybinding because I simply do not want to take the time to catabolize/forget that particular muscle memory.

(use-package visual-regexp
  :bind (("C-c 5" . #'vr/replace)))

Autocomplete

After a long journey with company, I’ve settled on just using the builtin completion-at-point facilities for autocomplete. The UI considerations afforded by Vertico make it even nicer than what Company offered, and consistently faster, too. Someday I want to look into a more aggressive inline autocompletion thing like VSCode supports, but I don’t know

(bind-key "C-." #'completion-at-point)

Debugging

In Haskell, my language of choice, I rarely need a step-through debugger, as designs that minimize mutable state make it so printf debugging is usually all you need. (Haskell’s unorthodox evaluation strategy, and its limited step-through debugging facilities, don’t help either.) However, now that I’m writing Rust and Go at work, a step-through debugger is indicated.

(use-package dap-mode
  :bind
  (:map dap-mode-map
   ("C-c b b" . dap-breakpoint-toggle)
   ("C-c b r" . dap-debug-restart)
   ("C-c b l" . dap-debug-last)
   ("C-c b d" . dap-debug))
  :init
  (require 'dap-go)
  ;; NB: dap-go-setup appears to be broken, so you have to download the extension from GH, rename its file extension
  ;; unzip it, and copy it into the config so that the following path lines up
  (setq dap-go-debug-program '("node" "/Users/patrickt/.config/emacs/.extension/vscode/golang.go/extension/dist/debugAdapter.js"))
  (defun pt/turn-on-debugger ()
    (interactive)
    (dap-mode)
    (dap-auto-configure-mode)
    (dap-ui-mode)
    (dap-ui-controls-mode)
    )
  )

LSP

Built-in xref and eldoc are powerful packages, though we pin them to GNU ELPA to pull in the latest versions.

(use-package xref
  :pin gnu
  :bind (("s-r" . #'xref-find-references)
         ("s-[" . #'xref-go-back)
         ("C-<down-mouse-2>" . #'xref-go-back)
         ("s-]" . #'xref-go-forward)))

(use-package eldoc
  :pin gnu
  :diminish
  :bind ("s-d" . #'eldoc)
  :custom (eldoc-echo-area-prefer-doc-buffer t))

Though I used lsp-mode for ages, in my old age I’ve grown happier with packages that try to do less, as they are in almost all cases faster and more reliable. eglot is such a mode.

(use-package eglot
  :hook ((go-mode . eglot-ensure)
         (haskell-mode . eglot-ensure)
         (rust-mode . eglot-ensure))
  :bind (:map eglot-mode-map
              ("C-c a r" . #'eglot-rename)
              ("C-<down-mouse-1>" . #'xref-find-definitions)
              ("C-S-<down-mouse-1>" . #'xref-find-references)
              ("C-c C-c" . #'eglot-code-actions))
  :custom
  (eglot-autoshutdown t)
  )

(use-package consult-eglot
  :bind (:map eglot-mode-map ("s-t" . #'consult-eglot-symbols)))

Haskell

Haskell is my day-to-day programming language, so I’ve tinkered with it a good deal. Featuring automatic ormolu or stylish-haskell invocation, as based on a per-project variable, so I can default to ormolu but choose stylish-haskell for the projects that don’t.

(use-package haskell-mode

  :config
  (defcustom haskell-formatter 'ormolu
    "The Haskell formatter to use. One of: 'ormolu, 'stylish, nil. Set it per-project in .dir-locals."
    :safe 'symbolp)

  (defun haskell-smart-format ()
    "Format a buffer based on the value of 'haskell-formatter'."
    (interactive)
    (cl-ecase haskell-formatter
      ('ormolu (ormolu-format-buffer))
      ('stylish (haskell-mode-stylish-buffer))
      (nil nil)
      ))


  (defun haskell-switch-formatters ()
    "Switch from ormolu to stylish-haskell, or vice versa."
    (interactive)
    (setq haskell-formatter
          (cl-ecase haskell-formatter
            ('ormolu 'stylish)
            ('stylish 'ormolu)
            (nil nil))))

  :bind (:map haskell-mode-map
         ("C-c a c" . haskell-cabal-visit-file)
         ("C-c a i" . haskell-navigate-imports)
         ("C-c m"   . haskell-compile)
         ("C-c a I" . haskell-navigate-imports-return)
         :map haskell-cabal-mode-map
         ("C-c m"   . haskell-compile)))

(use-package haskell-snippets
  :after (haskell-mode yasnippet)
  :defer)

My statements about Haskell autoformatters have, in the past, attracted controversy, so I have no further comment on the below lines.

(use-package ormolu)

vterm

The state of terminal emulation is, as a whole, a mess. Not just within Emacs, but across all of Unix. (To be fair, terminals are a fascinating study in backwards compatibility and generations upon generations of standards and conventions.) A recent bright spot has been libvterm, which, when integrated with Emacs’s new dynamic module support, enables us to have a very, very fast terminal inside Emacs.

A thing I want to do someday is to write a framework for sending things like compile commands to a running vterm buffer with vterm-send-string. I want a version of the compile command that sends that command to my current vterm buffer. That would be so badass.

(use-package vterm
  :config
  (defun turn-off-chrome ()
    (hl-line-mode -1)
    (display-line-numbers-mode -1))
  :hook (vterm-mode . turn-off-chrome))

(use-package vterm-toggle
  :custom
  (vterm-toggle-fullscreen-p nil "Open a vterm in another window.")
  (vterm-toggle-scope 'project)
  :bind (("C-c t" . #'vterm-toggle)
         :map vterm-mode-map
         ("C-\\" . #'popper-cycle)
         ("s-t" . #'vterm) ; Open up new tabs quickly
         ("s-v" . #'vterm-yank)
         ))

Process management

prodigy is a great and handsome frontend for managing long-running services. Since many of the services I need to run are closed-source, the calls to prodigy-define-service are located in an adjacent file. Unfortunately, prodigy doesn’t really have any good support for managing Homebrew services. Maybe I’ll write one, in my copious spare time.

(use-package prodigy
  :bind (("C-c 8" . #'prodigy)
         :map prodigy-view-mode-map
         ("$" . #'end-of-buffer))
  :custom (prodigy-view-truncate-by-default t)
  :config
  (load "~/.config/emacs/services.el" 'noerror))

Snippets

I grew up writing in TextMate, so I got extremely used to text-expansion snippets. I also think they’re extremely underrated for learning a new language’s idioms: one of the reasons I was able to get up to speed so fast with Rails (back in the 1.2 days) was because the TextMate snippets indicated pretty much everything you needed to know about things like ActiveRecord.

(use-package yasnippet
  :defer 15 ;; takes a while to load, so do it async
  :diminish yas-minor-mode
  :config (yas-global-mode)
  :custom (yas-prompt-functions '(yas-completing-prompt)))

Other Languages

General-purpose

Rust is one of my favorite languages in the world.

(use-package rust-mode
  :defer t
  :custom
  (rust-format-on-save t)
  (lsp-rust-server 'rust-analyzer))

I occasionally write Go, generally as a glue language to munge things together. I find certain aspects of its creators’ philosophies to be repellent, but a language is more than its creators, and it’s hard to argue with the success it’s found in industry or the degree to which people find it easy to pick up.

(use-package go-mode
  :defer t
  :config
  (add-hook 'before-save-hook #'gofmt-before-save))

(use-package go-snippets :defer t)

(defun fix-messed-up-gofmt-path ()
  (interactive)
  (setq gofmt-command (string-trim (shell-command-to-string "which gofmt"))))

(use-package gotest
  :bind (:map go-mode-map
              ("C-c a t" . #'go-test-current-test)))

Elm is a good language.

(use-package elm-mode
  :hook ((elm-mode . elm-format-on-save-mode)
         (elm-mode . elm-indent-mode)))

I don’t write a lot of Python, but when I do I like to use the extremely opinionated black formatter.

(use-package blacken
  :hook ((python-mode . blacken-mode)))

Some other miscellaneous languages that I don’t write often but for which I need syntax highlighting, at least.

(use-package typescript-mode :defer t)
(use-package csharp-mode :defer t)
(setq-default js-indent-level 2)

I’m trying to learn APL, because I’ve lost control of my life.

(use-package dyalog-mode :defer t)

Configuration

(use-package yaml-mode :defer t)
(use-package dockerfile-mode :defer t)
(use-package toml-mode :defer t)

I use Bazel for some Haskell projects.

(use-package bazel
  :defer t
  :config
  (add-hook 'bazel-mode-hook (lambda () (add-hook 'before-save-hook #'bazel-mode-buildifier nil t)))
  )

Interchange

(use-package protobuf-mode :defer t)

Markup

I generally use GitHub-flavored Markdown, so we default to that.

(use-package markdown-mode
  :bind (:map markdown-mode-map ("C-c C-s a" . markdown-table-align))
  :mode ("\\.md$" . gfm-mode))

Occasionally I need to edit Rails .erb templates, God help me.

(use-package web-mode
  :custom (web-mode-markup-indent-offset 2)
  :mode ("\\.html.erb$" . web-mode))

I usually use curly quotes when writing in markup languages, which typo-mode makes easy.

(use-package typo :defer t)

Shell

fish is the only shell that doesn’t make me want to defenestrate. The only time I use anything else is when I have to use TRAMP to connect to a codespace, in which case I need to use zsh, as fish is not POSIX-compliant.

(use-package fish-mode :defer t)

Miscellany

restclient is a terrific interface for running HTTP requests against local or remote services.

(use-package restclient
  :mode ("\\.restclient$" . restclient-mode))

Dash is the foremost documentation browser for macOS.

(use-package dash-at-point
  :bind ("C-c d" . dash-at-point))

TRAMP mode is excellent for editing files on a remote machine or Docker container, but it needs some TLC.

(require 'tramp)
(setq tramp-default-method "ssh"
      tramp-verbose 1
      tramp-default-remote-shell "/bin/bash"
      tramp-connection-local-default-shell-variables
        '((shell-file-name . "/bin/bash")
          (shell-command-switch . "-c")))

(connection-local-set-profile-variables 'tramp-connection-local-default-shell-profile
  '((shell-file-name . "/bin/bash")
   (shell-command-switch . "-c")))

(lsp-register-client
 (make-lsp-client :new-connection (lsp-stdio-connection "gopls")
                  :major-modes '(go-mode go-dot-mod-mode)
                  :language-id "go"
                  :remote? t
                  :priority 0
                  :server-id 'gopls-remote
                  :completion-in-comments? t
                  :library-folders-fn #'lsp-go--library-default-directories
                  :after-open-fn (lambda ()
                                   ;; https://github.com/golang/tools/commit/b2d8b0336
                                   (setq-local lsp-completion-filter-on-incomplete nil))))

;; add gh codespaces ssh method support for tramp editing
;; e.g. C-x C-f /ghcs:codespace-name:/path/to/file
;; thanks to my coworker Bas for this one
(let ((ghcs (assoc "ghcs" tramp-methods))
      (ghcs-methods '((tramp-login-program "gh")
                      (tramp-login-args (("codespace") ("ssh") ("-c") ("%h")))
                      (tramp-remote-shell "/bin/sh")
                      (tramp-remote-shell-login ("-l"))
                      (tramp-remote-shell-args ("-c")))))
  ;; just for debugging the methods
  (if ghcs (setcdr ghcs ghcs-methods)
    (push (cons "ghcs" ghcs-methods) tramp-methods)))

I use direnv to manage per-project environment variables. The Emacs direnv mode is quite sophisticated, automatically setting all relevant variables for you when you go in and out of a particular project.

(use-package direnv
  :config (direnv-mode)
  :custom (direnv-always-show-summary nil))

Initial screen setup

(defun my-default-window-setup ()
  "Called by emacs-startup-hook to set up my initial window configuration."

  (split-window-right)
  (other-window 1)
  (find-file "~/txt/todo.org")
  (other-window 1))

(add-hook 'emacs-startup-hook #'my-default-window-setup)

Adios

If you made it this far, well, may your deity of choice bless you. If you don’t use Emacs already, I hope I tempted you a little. If you do, I hope you learned a couple new tricks, just as I have learned so many tricks from reading dozens of other people’s configs.

Au revoir.

(provide 'init)