Skip to content

SophieBosio/.emacs.d

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sophie’s Emacs Configuration

./images/config-screenshot.png

About

This is my attempt at keeping my Emacs configuration organised and readable.

I write all my initialisation code in this document as code blocks and then use org-babel-tangle to extract those code blocks into a separate file. That new, generated file becomes my init.el. This way, I can document my code and explain my choices to my future self - and to anyone else who might be interested in looking at it. I’ve stolen the code for doing this and several other tidbits from Lars Tveito.

If you’re interested in this approach to writing and sharing your config, it’s called a “literate configuration” and there are lots of great blog posts out there with inspiration and tips!

I’ve lifted a lot of code from other people’s configurations, including:

I can heartily recommend checking those out.

You likely do not want to copy my configuration file, since it’s full of idiosyncrasies and pretty subjective choices. But I do encourage you to take any bits and pieces that seem interesting, try them out, and incorporate the ones you like into your own config.

Table of Contents

Setup

Prerequisites

You probably don’t want to run this configuration as-is, since it’s highly personal and very likely contains things you don’t want in your Emacs.

However, if you do want to try it, or if you want to steal a chunk and something’s not working right, this is the software that I have installed in addition to Emacs and that is present in this config, one way or another.

This doubles as a memo to myself for when I need to set up a new machine.

Here are the programming languages and utils I set up. The configuration for other languages I have in here shouldn’t break anything if you don’t have the accompanying software.

I use these fonts. They are used both in Visuals > Fonts and in Org > Visuals > Fonts.

The rest of what you need should be downloaded by this configuration file. If you try it and find anything missing from this list, please let me know!

init.el Code

As mentioned, I use org-babel-tangle and this document, written in Org mode.

The code below extracts the elisp configuration code and creates/overwrites the ~/.emacs.d/init.el configuration file when the .org-file is saved. Therefore, changes are only done in the .org-file, where writing longer comments about how things work and why things are added is easier, and then the resulting init.el-file remains clean and without excessive comments.

This is what the init.el file should look like, prompting it to tangle the init.org file and replace itself with that code.

;; We need org in order to make use of the tangling functionality
(require 'org)
;; Open the org-mode configuration
(find-file (concat user-emacs-directory "init.org"))
;; Tangle the file
(org-babel-tangle)
;; Load the tangled file
(load-file (concat user-emacs-directory "init.el"))
;; Byte-compile it
(byte-compile-file (concat user-emacs-directory "init.el"))

Git Tracking & Practicalities

Now we also don’t need to track the generated init.el file on Git, since it is directly derived from init.org.

This code makes Git ignore changes to init.el:

git update-index --assume-unchanged init.el

If you do want to start tracking the file again, you can use:

git update-index --no-assume-unchanged init.el

Lexical Scoping

First, I want lexical scoping for the init-file, so I will add that to the top of the file.

;;; -*- lexical-binding: t -*-

Tangling

Now to tangling! The rest of the text and code in this section is lifted directly from Lars’ configuration.

The init.el should (after the first run) mirror the source blocks in the init.org. We can use C-c C-v t to run org-babel-tangle, which extracts the code blocks from the current file into a source-specific file (in this case a .el-file).

To avoid doing this each time a change is made we can add a function to the after-save-hook ensuring to always tangle and byte-compile .org-document after changes.

(defun tangle-init ()
  "If the current buffer is init.org the code-blocks are
tangled, and the tangled file is compiled."
  (when (equal (buffer-file-name)
               (expand-file-name (concat user-emacs-directory "init.org")))
    ;; Avoid running hooks when tangling.
    (let ((prog-mode-hook nil))
      (org-babel-tangle)
      (byte-compile-file (concat user-emacs-directory "init.el")))))

(add-hook 'after-save-hook 'tangle-init)

Start-Up

Garbage Collection

Famously, the Emacs garbage collector can impede startup times quite dramatically. Therefore, a common tweak is to disable the garbage collector during initialisation, and then resetting it afterwards. Luckily, there exists a package exactly for this purpose called the Garbage Collector Magic Hack-

(setq gc-cons-percentage      0.6)
(setq read-process-output-max (* 1024 1024)) ;; 1mb

(use-package gcmh
  :config
  (setq gcmh-idle-delay 5
        gcmh-high-cons-threshold (* 100 1024 1024))  ; 100mb
  (gcmh-mode 1))

Optimisations

We can set the file-name-handler-alist, which is supposed to help startup times a little.

(setq file-name-handler-alist-original file-name-handler-alist)
(setq file-name-handler-alist nil)

I also get quite a lot of compilation warnings, especially from native compilation, but they are usually safe to ignore.

(setq native-comp-async-report-warnings-errors 'silent) ;; native-comp warning
(setq byte-compile-warnings '(not free-vars unresolved noruntime lexical make-local))

Disable warnings about obsolete functions when compiling.

(eval-when-compile
  (dolist (sym '(cl-flet lisp-complete-symbol))
    (setplist sym (use-package-plist-delete
                   (symbol-plist sym) 'byte-obsolete-info))))

This is an optimisation borrowed from Doom Emacs’ core.el.

(setq idle-update-delay 1.0)

Fix IO bugs.

(setq process-adaptive-read-buffering nil)
(setq read-process-output-max (* 4 1024 1024))

Prevent Emacs from freezing when updating ELPA.

(setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")

House-Keeping

Then I want to do some house keeping. First, let’s set the Emacs user and default directories explicitly:

(setq user-emacs-directory "~/.emacs.d/")
(setq default-directory "~/")

Set UFT-8 as preferred coding system.

(set-language-environment    "UTF-8")
(setq locale-coding-system   'utf-8)
(prefer-coding-system        'utf-8)
(set-default-coding-systems  'utf-8)
(set-terminal-coding-system  'utf-8)
(set-keyboard-coding-system  'utf-8)
(set-terminal-coding-system  'utf-8)
(set-keyboard-coding-system  'utf-8)
(set-selection-coding-system 'utf-8)

Don’t warn me when opening files unless over 50 MB.

(setq large-file-warning-threshold (* 50 1024 1024))

Package Sources

To manage downloaded packages, Emacs comes with package.el installed. In addition, I want to use use-package, so let’s make sure we have those loaded.

(require 'package)
(require 'use-package)
(require 'use-package-ensure)
(setq use-package-always-ensure t)

Next, I’ll set up my package sources. These are very common and well-maintained mirrors.

(setq package-archives
      '(("GNU ELPA"     . "https://elpa.gnu.org/packages/")
        ("MELPA"        . "https://melpa.org/packages/")
        ("ORG"          . "https://orgmode.org/elpa/")
        ("MELPA Stable" . "https://stable.melpa.org/packages/")
        ("nongnu"       . "https://elpa.nongnu.org/nongnu/"))
      package-archive-priorities
      '(("GNU ELPA"     . 20)
        ("MELPA"        . 15)
        ("ORG"          . 10)
        ("MELPA Stable" . 5)
        ("nongnu"       . 0)))
(package-initialize)

Local Files

I have a folder with extensions that have been downloaded manually. I’ll add these to the load-path so Emacs knows where to look for them. My folder is called “local-lisp”.

(defvar local-lisp (concat user-emacs-directory "local-lisp/"))
(add-to-list 'load-path  local-lisp)
(let ((default-directory local-lisp))
  (normal-top-level-add-subdirs-to-load-path))

I’ll initialise the list of Org agenda files to an empty list. There are used for task management and for my calendar, and I’ll add to the list both in private.el and in the Org section Tasks.

(setq org-agenda-files '())

And load custom settings from custom.el and private settings from private.el if they exist.

(add-hook
 'after-init-hook
 (lambda ()
   (let ((private-file (concat user-emacs-directory "private.el"))
		 (custom-file (concat user-emacs-directory "custom.el")))
     (when (file-exists-p private-file)
       (load-file private-file))
     (when custom-file
       (load-file custom-file))
     (server-start))))

Terminal Setup

Track current directory in shell.

(dirtrack-mode t)

Mac OS Environment Variables

On Mac, the environment variables aren’t synchronised automatically between the shell and Emacs. exec-path-from-shell fixes that.

(use-package exec-path-from-shell
  :if (memq window-system '(mac ns))
  :config
  (exec-path-from-shell-initialize))

On Mac, I ran into some trouble with my shell, so I specify the shell as a safeguard against random errors.

(when (eq system-type 'darwin)
  (setq vterm-shell "/opt/homebrew/bin/fish"))

DWIM Shell Commands

DWIM Shell Commands (“Do What I Mean” shell commands) are a collection of command-line utilities integrated with Emacs. We’ll load the optional package with pre-configured commands as well.

(use-package dwim-shell-command
  :defer t
  :config
  (require 'dwim-shell-commands))

Custom Keybindings

Custom Keymap

I keep a custom keybinding map that I add to per package, and then activate at the end of the configuration. This keeps my custom bindings from being overwritten by extensions’ own bindings.

The first step is to create the custom keybinding map. We’ll add bindings to it throughout the config, and then activate it at the end of the config file, at Activating Custom Keybindings.

(defvar custom-bindings-map (make-keymap)
  "A keymap for custom keybindings.")

Mac OS Modifier Keys

On a Mac, I would want to add some specific settings. As a note to myself, I have the following settings in Mac OS:

caps-lock -> control (ctrl)
control   -> control (ctrl)
option    -> option  (alt)
command   -> command (meta)
(setq mac-command-modifier       'meta
      mac-right-command-modifier 'meta
      mac-option-modifier        nil
      mac-right-option-modifier  nil)

Unbind Some Default Keys

Some of the default keybindings are annoying, so let’s unbind them.

I never mean to press C-x C-z, which hides the current Emacs frame.

I also don’t like using C-<wheel up/down> to zoom, which I often do accidentally.

Finally, I often press C-x C-b when I only mean to press C-x b. If I want to open the list of all buffers, I’ll call it with M-x list-buffers.

(global-unset-key (kbd "C-x C-z"))
(global-unset-key (kbd "C-<wheel-up>"))
(global-unset-key (kbd "C-<wheel-down>"))
(global-unset-key (kbd "C-x C-b"))

Visuals

Decluttering

Let’s declutter a little. This should have gone into early-init.el, but I get strange compilation warnings (optimiser says there’s too much on the stack).

(dolist (mode
         '(tool-bar-mode       ;; Remove toolbar
           scroll-bar-mode     ;; Remove scollbars
           menu-bar-mode       ;; Remove menu bar
           blink-cursor-mode)) ;; Solid cursor, not blinking
  (funcall mode 0))

This wouldn’t go into early-init anyways.

(setq inhibit-startup-message           t       ;; No startup message
      inhibit-startup-echo-area-message t       ;; No startup message in echo area
      inhibit-startup-screen            t       ;; No default startup screen
      initial-scratch-message           nil     ;; Empty scratch buffer
      initial-buffer-choice             t       ;; *scratch* is default startup buffer
      initial-major-mode                'fundamental-mode
      ring-bell-function                'ignore ;; No bell
      display-time-default-load-average nil     ;; Don't show me load time
      scroll-margin                     0       ;; Space between top/bottom
      use-dialog-box                    nil)    ;; Disable dialog

Frames & Windows

Open in Fullscreen

When I open Emacs, I want it to open maximised and fullscreen by default.

(add-to-list 'default-frame-alist     '(fullscreen . maximized))
;; (add-hook 'window-setup-hook          'toggle-frame-fullscreen t)  ;; F11

Frame Transparency

This doesn’t work ideally, but it does the job. I use it very rarely.

(defun toggle-transparency ()
  (interactive)
  (let ((alpha (frame-parameter nil 'alpha)))
    (set-frame-parameter
     nil 'alpha
     (if (eql (cond ((numberp alpha) alpha)
                    ((numberp (cdr alpha)) (cdr alpha))
                    ;; Also handle undocumented (<active> <inactive>) form.
                    ((numberp (cadr alpha)) (cadr alpha)))
              100)
         '(90 . 55) '(100 . 100)))))
(global-set-key (kbd "C-c h t") 'toggle-transparency)

Frame Border

I want a small border around the whole frame, because I think it looks nicer.

(add-to-list 'default-frame-alist '(internal-border-width . 16))

Some settings to fringes.

(set-fringe-mode 10)                          ;; Set fringe width to 10

(setq-default fringes-outside-margins nil)
(setq-default indicate-buffer-boundaries nil) ;; Otherwise shows a corner icon on the edge
(setq-default indicate-empty-lines nil)       ;; Otherwise there are weird fringes on blank lines

(set-face-attribute 'header-line t :inherit 'default)

Splitting Windows

I want maximum two windows by default. I have a function, taken from this Stack Overflow post, that rewrites the split-window-sensibly function to reverse its preference and essentially prefer splitting side-by-side.

(defun split-window-sensibly-prefer-horizontal (&optional window)
"Based on `split-window-sensibly', but prefers to split WINDOW side-by-side."
  (let ((window (or window (selected-window))))
    (or (and (window-splittable-p window t)
         ;; Split window horizontally
         (with-selected-window window
           (split-window-right)))
    (and (window-splittable-p window)
         ;; Split window vertically
         (with-selected-window window
           (split-window-below)))
    (and
         ;; If WINDOW is the only usable window on its frame (it is
         ;; the only one or, not being the only one, all the other
         ;; ones are dedicated) and is not the minibuffer window, try
         ;; to split it horizontally disregarding the value of
         ;; `split-height-threshold'.
         (let ((frame (window-frame window)))
           (or
            (eq window (frame-root-window frame))
            (catch 'done
              (walk-window-tree (lambda (w)
                                  (unless (or (eq w window)
                                              (window-dedicated-p w))
                                    (throw 'done nil)))
                                frame)
              t)))
     (not (window-minibuffer-p window))
     (let ((split-width-threshold 0))
       (when (window-splittable-p window t)
         (with-selected-window window
               (split-window-right))))))))

(defun split-window-really-sensibly (&optional window)
  (let ((window (or window (selected-window))))
    (if (> (window-total-width window) (* 2 (window-total-height window)))
        (with-selected-window window (split-window-sensibly-prefer-horizontal window))
      (with-selected-window window (split-window-sensibly window)))))

(setq split-window-preferred-function 'split-window-really-sensibly)

If I have already split the frame into two windows and then call a function that opens a new window (for example a Magit or a compilation buffer), then I want Emacs to reuse the inactive window instead of creating a new one. Setting both split-height-threshold and split-width-threshold to nil seems to ensure this.

(setq-default split-height-threshold nil
              split-width-threshold  nil
              fill-column            80) ;; Maximum line width
              ;; window-min-width       80) ;; No smaller windows than this

Title Bar on Mac OS

I use Emacs Plus port for Mac OS. With it, you can get a transparent title bar (i.e., title bar is same colour as theme background) which I think is really nice.

First, install Emacs Plus.

# enable tap
brew tap d12frosted/emacs-plus

# install
brew install emacs-plus [options]

Then add the corresponding settings to your init-file.

There are two different styles you can choose from. You can have absolutely no title bar on your window or you can have a transparent bar, which still has the three stoplight buttons in the upper-left corner.

For natural title bar, use ns-transparent-titlebar and for no title bar, use undecorated or undercorated-round.

I also set some other options. For example, I don’t need info in the title bar about which buffer is in focus, since this info is already in the mode line. I found these options in this blog post.

(when (eq system-type 'darwin)
  ; no title bar
  (add-to-list 'default-frame-alist '(undecorated-round . t))
  ; don't use proxy icon
  (setq ns-use-proxy-icon nil)
  ; don't show buffer name in title bar
  (setq frame-title-format ""))

Finally, in your terminal, run these commands to use transparent title bar and to hide the icon from the middle of the title bar. I found these in the aforementioned blog post and in the Emacs-Mac Port’s wiki page on the subject.

# for dark themes
defaults write org.gnu.Emacs TransparentTitleBar DARK

# for light themes
defaults write org.gnu.Emacs TransparentTitleBar LIGHT

# hide document icon from title bar
defaults write org.gnu.Emacs HideDocumentIcon YES

Plain Title Bar on GNOME

On GNOME, I can’t get a transparent/native title bar. But I can remove the text from the middle, so it’s completely plain.

(when (eq system-type 'gnu/linux)
  ; don't show buffer name in title bar
  (setq frame-title-format nil))

Programming-Specific Visuals

Cursor

I prefer a bar cursor over a block cursor.

(setq-default cursor-type 'bar)

Having a thin cursor can make it hard to see where you are after switching buffers or jumping around. Beacon highlights your cursor temporarily, which immediately answers the question “Woah, where am I now?”

(use-package beacon
  :defer t
  :init  (beacon-mode 1)
  :bind (:map custom-bindings-map ("C-:" . beacon-blink))
  :config
  (setq beacon-blink-when-window-scrolls nil))

Delimiters (Parentheses etc.)

When coding, I want my delimiters (parentheses, brackets, etc.) to be colourised in pairs. rainbow-delimiters does exactly that.

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

Also, please highlight matching parentheses/delimiters.

(show-paren-mode t) ;; Highlight matching parentheses

Line Numbers

I usually only need line numbers in programming mode.

(add-hook 'prog-mode-hook 'display-line-numbers-mode)

Uniquify Buffers

When opening the files foo/bar/name and baz/bar/name, use forward slashes to distinguish them. Default behaviour is angle brackets, which would yield name<foo/bar> and name<baz/bar>..

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

Highlight Long Lines

Highlight lines over 120 characters long.

(setq my-whitespace-style '(face tabs lines-tail)
      whitespace-style my-whitespace-style
      whitespace-line-column 120
      fill-column 120
      whitespace-display-mappings
      '((space-mark 32 [183] [46])
        (newline-mark 10 [36 10])
        (tab-mark 9 [9655 9] [92 9])))

;; in e.g. clojure-mode-hook
;; (whitespace-mode 1)
;; or globally
;; (global-whitespace-mode 1)
(add-hook 'prog-mode 'whitespace-mode)

Fonts

Default, Fixed, and Variable Fonts

Please note that I scale and set Org-specific faces in the Org > Visuals section.

For the fixed-pitch font, I’m using the excellent Fragment Mono, which has great ligature support.

I have Open Sans configured as my variable-pitch font.

(defvar soph/font-height 102)

(when (eq system-type 'darwin)
  (setq soph/font-height 134))

(when (member "Fragment Mono" (font-family-list))
  (set-face-attribute 'default nil :font "Fragment Mono" :height soph/font-height)
  (set-face-attribute 'fixed-pitch nil :family "Fragment Mono"))

(when (member "Open Sans" (font-family-list))
  (set-face-attribute 'variable-pitch nil :family "Open Sans"))

Mixed Pitch Fonts

mixed-pitch allows you to mix fixed and variable pitched faces in Org and LaTeX mode.

(use-package mixed-pitch
  :defer t
  :hook ((org-mode   . mixed-pitch-mode)
         (LaTeX-mode . mixed-pitch-mode)))

Ligatures

The package ligature.el provides support for displaying the ligatures of fonts that already have ligatures. Mine does, and seems to work just fine out of the box with the ligatures defined on the package’s page,

(defvar ligature-def '("|||>" "<|||" "<==>" "<!--" "####" "~~>" "***" "||=" "||>"
                       ":::" "::=" "=:=" "===" "==>" "=!=" "=>>" "=<<" "=/=" "!=="
                       "!!." ">=>" ">>=" ">>>" ">>-" ">->" "->>" "-->" "---" "-<<"
                       "<~~" "<~>" "<*>" "<||" "<|>" "<$>" "<==" "<=>" "<=<" "<->"
                       "<--" "<-<" "<<=" "<<-" "<<<" "<+>" "</>" "###" "#_(" "..<"
                       "..." "+++" "/==" "///" "_|_" "www" "&&" "^=" "~~" "~@" "~="
                       "~>" "~-" "**" "*>" "*/" "||" "|}" "|]" "|=" "|>" "|-" "{|"
                       "[|" "]#" "::" ":=" ":>" ":<" "$>" "==" "=>" "!=" "!!" ">:"
                       ">=" ">>" ">-" "-~" "-|" "->" "--" "-<" "<~" "<*" "<|" "<:"
                       "<$" "<=" "<>" "<-" "<<" "<+" "</" "#{" "#[" "#:" "#=" "#!"
                       "##" "#(" "#?" "#_" "%%" ".=" ".-" ".." ".?" "+>" "++" "?:"
                       "?=" "?." "??" ";;" "/*" "/=" "/>" "//" "__" "~~" "(*" "*)"
                       "\\\\" "://"))

(use-package ligature
  :config
  (ligature-set-ligatures 'prog-mode ligature-def)
  (global-ligature-mode t))

Zoom

The default zoom step is a little much on my Linux (Gnome 46) laptop, so let’s decrease it a little.

(setq text-scale-mode-step 1.1)

Icons & Emojis

Add nerd-icons.

(use-package nerd-icons)

I also want to be able to display emojis with the Apple emoji font. I usually don’t use it, though, so I won’t activate the global mode.

(use-package emojify
  :config
  (when (member "Apple Color Emoji" (font-family-list))
    (set-fontset-font
      t 'symbol (font-spec :family "Apple Color Emoji") nil 'prepend)))

Themes

I really like the doom-themes package.

(use-package doom-themes
  :config
  (setq doom-themes-enable-bold t     ; if nil, bold is universally disabled
        doom-themes-enable-italic t)) ; if nil, italics is universally disabled

I also have a custom light theme I’m working on called South. Let’s add the path to that so I can load it.

(setq custom-theme-directory "~/Dropbox/projects/south-theme/")

Default Dark & Light Themes

My favourite dark theme is doom-nord. I haven’t been able to find any light themes I really love, so I made South to act as Nord’s bright counterpart. I’ll set these two as my default dark and light themes respectively, and load the dark theme by default.

(defvar soph/default-dark-theme  'doom-nord)
(defvar soph/default-light-theme 'south)

(load-theme soph/default-dark-theme t)

Changing Theme With System Theme

auto-dark-emacs is a package for switching themes with the system theme. It works both on Linux and on MacOS.

(use-package autothemer
  :defer t)

(use-package auto-dark
  :ensure t
  :config
  (setq auto-dark-dark-theme               soph/default-dark-theme
        auto-dark-light-theme              soph/default-light-theme
        auto-dark-polling-interval-seconds 5
        auto-dark-allow-osascript          nil
        auto-dark-allow-powershell         nil)
  (auto-dark-mode t))

We can even change the system theme from within Emacs using a dwim-shell-command for Mac OS. The Gnome extension Night Theme Switcher takes care of things on my Linux machine.

(when (eq system-type 'darwin)
  (define-key custom-bindings-map (kbd "M-T") 'dwim-shell-commands-macos-toggle-dark-mode))

Conflict-Free Theme Changing

When changing themes interactively, as with M-x load-theme, the current custom theme is not disabled and this causes some weird issues. For example, the borders around posframes disappear. This snippet from Lars’ config advises load-theme to always disable the currently enabled themes before switching.

(defadvice load-theme
    (before disable-before-load (theme &optional no-confirm no-enable) activate)
  (mapc 'disable-theme custom-enabled-themes))

Mode Line

Column Number

Show current column number in mode line.

(column-number-mode      t) ;; Show current column number in mode line

Custom Mode Line

Customising the default modeline is thankfully pretty easy. Note that I use the nerd-icons package for the VC branch symbol in the code below. I’ve also borrowed some code from this blog post by Amit Patel on writing a custom mode line.

This mode line is heavily inspired by Nicolas Rougier’s Nano Modeline and he even helped me figure out how to add vertical padding to it.

(setq-default mode-line-format
  '("%e"
	(:propertize " " display (raise +0.4)) ;; Top padding
	(:propertize " " display (raise -0.4)) ;; Bottom padding

	(:propertize "λ " face font-lock-comment-face)
	mode-line-frame-identification
	mode-line-buffer-identification

	;; Version control info
	(:eval (when-let (vc vc-mode)
			 ;; Use a pretty branch symbol in front of the branch name
					 (list (propertize "" 'face 'font-lock-comment-face)
						   (propertize (substring vc 5)
									   'face 'font-lock-comment-face))))

	;; Add space to align to the right
	(:eval (propertize
			 " " 'display
			 `((space :align-to
					  (-  (+ right right-fringe right-margin)
						 ,(+ 2 (string-width "%4l:3%c")))))))
	
	;; Line and column numbers
	(:propertize "%4l:%c" face mode-line-buffer-id)))

Hide Mode Line

hide-mode-line-mode is extracted from Doom Emacs, and does what it says on the tin. It can also be added to hooks to hide the mode line in certain modes. I have it bound to C-c h m - mneumonically “User command: Hide Modeline”.

(use-package hide-mode-line
  :defer t
  :bind (:map custom-bindings-map ("C-c h m" . hide-mode-line-mode)))

Text Display Modes

Olivetti

Olivetti is a minor mode for centering text. For convenience, I’ll bind it to C-c o to activate/deactivate it on the fly.

(use-package olivetti
  :defer t
  :bind (:map custom-bindings-map ("C-c o" . olivetti-mode))
  :config
  (setq olivetti-style t))

Adaptive Wrap

In addition, I use adaptive-wrap to visually wrap lines.

(use-package adaptive-wrap
  :defer t
  :hook (visual-line-mode . adaptive-wrap-prefix-mode))

Writeroom Mode

Writeroom Mode gives you a distraction-free writing environment.

(use-package writeroom-mode
  :defer t)

Focus

Focus dims surrounding text in a semantic manner (sentences, paragraphs, sections, code blocks, etc.) making it easier to, well, focus. I find this especially helpful when editing LaTeX.

(use-package focus
  :defer t)

Presentation Mode

For presenting (e.g., code or Org mode buffers), it’s useful to increase the font size, without necessarily increasing the size of everything else.

(use-package presentation
  :defer t
  :config
  (setq presentation-default-text-scale 2.5))

General Editing

Built-In Options

(delete-selection-mode   t) ;; Replace selected text when yanking
(global-so-long-mode     t) ;; Mitigate performance for long lines
(global-visual-line-mode t) ;; Break lines instead of truncating them
(global-auto-revert-mode t) ;; Revert buffers automatically when they change
(recentf-mode            t) ;; Remember recently opened files
(savehist-mode           t) ;; Remember minibuffer prompt history
(save-place-mode         t) ;; Remember last cursor location in file
(setq auto-revert-interval         1         ;; Refresh buffers fast
      auto-revert-verbose          nil       ;; Don't notify me about reverts
      echo-keystrokes              0.1       ;; Show keystrokes fast
      frame-inhibit-implied-resize 1         ;; Don't resize frame implicitly
      sentence-end-double-space    nil       ;; No double spaces
      recentf-max-saved-items      1000      ;; Show more recent files
      use-short-answers            t         ;; 'y'/'n' instead of 'yes'/'no' etc.
      save-interprogram-paste-before-kill t  ;; Save copies between programs
      history-length               25        ;; Only save the last 25 minibuffer prompts
      global-auto-revert-non-file-buffers t) ;; Revert Dired and other buffers
(setq-default tab-width              4  ;; Smaller tabs
              frame-resize-pixelwise t) ;; Fine-grained frame resize

Smoother Scrolling

I want scrolling to be a lot slower than it is by default.

(setq scroll-conservatively            101
      mouse-wheel-follow-mouse         't
      mouse-wheel-progressive-speed    nil
      ;; Scroll 1 line at a time, instead of default 5
      ;; Hold shift to scroll faster and meta to scroll very fast
      mouse-wheel-scroll-amount        '(1 ((shift) . 3) ((meta) . 6)))

(setq mac-redisplay-dont-reset-vscroll t
      mac-mouse-wheel-smooth-scroll    nil)

Tabs & Indentation

One of the things that drove me the most insane when I first downloaded Emacs, was the way it deals with indentation.

I want to use spaces instead of tabs. But if I’m working on a project that does use tabs, I don’t want to mess with other people’s code, so I’ve used this snippet from the Emacs Wiki to infer indentation style.

(defun infer-indentation-style ()
  "Default to no tabs, but use tabs if already in project"
  (let ((space-count (how-many "^  " (point-min) (point-max)))
        (tab-count   (how-many "^\t" (point-min) (point-max))))
    (if (> space-count tab-count) (setq-default indent-tabs-mode nil))
    (if (> tab-count space-count) (setq-default indent-tabs-mode t))))

(setq-default indent-tabs-mode nil)
(infer-indentation-style)

I want to disable electric indent mode.

(electric-indent-mode -1)

Set backtab to indent-rigidly-left. Then I can easily unindent regions that use spaces instead of tabs.

(define-key custom-bindings-map (kbd "<backtab>") 'indent-rigidly-left)

And finally, make backspace remove the whole tab instead of just deleting one space.

(setq backward-delete-char-untabify-method 'hungry)

Deleting Instead of Killing

Another thing that bothered me, was how the backward-kill-word command (C-delete/backspace) would delete not only trailing backspaces, but everything behind it until it had deleted a word. Additionally, this was automatically added to the kill ring. With this the help of some regexps, it behaves more like normal Ctrl-Backspace.

The code is taken from this and this Stack Exchange/Overflow post.

(defun soph/delete-dont-kill (arg)
  "Delete characters backward until encountering the beginning of a word.
   With argument ARG, do this that many times. Don't add to kill ring."
  (interactive "p")
  (delete-region (point) (progn (backward-word arg) (point))))

(defun soph/backward-delete ()
  "Delete a word, a character, or whitespace."
  (interactive)
  (cond
   ;; If you see a word, delete all of it
   ((looking-back (rx (char word)) 1)
    (soph/delete-dont-kill 1))
   ;; If you see a single whitespace and a word, delete both together
   ((looking-back (rx (seq (char word) (= 1 blank))) 1)
	(soph/delete-dont-kill 1))
   ;; If you see several whitespaces, delete them until the next word
   ((looking-back (rx (char blank)) 1)
    (delete-horizontal-space t))
   ;; If you see a single non-word character, delete that
   (t
    (backward-delete-char 1))))

Let’s bind this in my custom keybindings map.

(define-key custom-bindings-map [C-backspace] 'soph/backward-delete)

Browse Kill Ring

Speaking of killing text, it’s nice to be able to browse the kill ring.

(use-package browse-kill-ring
  :defer t)

Auto-Saving

To avoid clutter, let’s put all the auto-saved files into one and the same directory.

(defvar emacs-autosave-directory
  (concat user-emacs-directory "autosaves/")
  "This variable dictates where to put auto saves. It is set to a
  directory called autosaves located wherever your .emacs.d/ is
  located.")

;; Sets all files to be backed up and auto saved in a single directory.
(setq backup-directory-alist
      `((".*" . ,emacs-autosave-directory))
      auto-save-file-name-transforms
      `((".*" ,emacs-autosave-directory t)))

I prefer having my files save automatically. Any changes I don’t want, I just don’t commit to git. I use auto-save-buffers-enhanced to automatically save all buffers, not just the ones I have open.

But since saving this file - the init.org-file - triggers recompilation of init.el, it’s really annoying if this file is autosaved when I write to it. Therefore, I’ll disable automatic saving for this file in particular.

(use-package auto-save-buffers-enhanced
  :ensure t
  :config
  (auto-save-buffers-enhanced t)
  (setq auto-save-buffers-enhanced-exclude-regexps '("init.org")))

Text Editing Functions

Selecting Regions

expand-region expand the region (selected text) with semantic units (e.g., symbol, word, sentence, paragraph). It’s super handy!

(use-package expand-region
  :defer t
  :bind (:map custom-bindings-map ("C-+" . er/expand-region)))

Filling/Unfilling

In Emacs, paragraphs can be padded by a bunch of newlines, meaning a what looks like a normal paragraph in Emacs (one line) is actually several lines with \n all over. This function removes those and makes the selected region one line again.

;;; Stefan Monnier <foo at acm.org>. It is the opposite of fill-paragraph
(defun unfill-paragraph (&optional region)
  "Takes a multi-line paragraph and makes it into a single line of text."
  (interactive (progn (barf-if-buffer-read-only) '(t)))
  (let ((fill-column (point-max))
		;; This would override `fill-column' if it's an integer.
		(emacs-lisp-docstring-fill-column t))
	(fill-paragraph nil region)))
;; Handy key definition
(define-key custom-bindings-map (kbd "C-c n q") 'unfill-paragraph)

Multiple Cursors

Makes life so much easier! I often use it to create several cursors directly above one another.

(use-package multiple-cursors
  :defer t
  :bind (:map custom-bindings-map
              ("M-n" . mc/mark-next-like-this)
			  ("M-p" . mc/mark-previous-like-this)))

IEdit

iedit is similar to multiple-cursors, but they have slightly different use cases. IEdit will highlight all matching occurrences of a word/symbol and allow you to edit them simultaneously. Sometimes, I use it just to highlight matches in the buffer. The default binding for entering iedit-mode is C-;.

(use-package iedit
  :defer t
  :custom
  (setq iedit-toggle-key-default (kbd "C-;")))

Undo/Redo

The default “undo until you can redo” behaviour of Emacs still trips me up. undo-fu lets me specify keys to “only undo” or “only redo”.

(use-package undo-fu
  :defer t
  :bind (:map custom-bindings-map
              ("C-_" . undo-fu-only-undo)
              ("M-_" . undo-fu-only-redo)))

Move Lines

move-dup provides bindings for moving and duplicating whole lines. It’s super convenient.

(use-package move-dup
  :bind (:map prog-mode-map
              (("M-<up>"     . move-dup-move-lines-up)
               ("C-M-<up>"   . move-dup-duplicate-up)
               ("M-<down>"   . move-dup-move-lines-down)
               ("C-M-<down>" . move-dup-duplicate-down))))

Join Lines

From What the .emacs.d!?, a keybinding to join the line below with the one above.

(define-key custom-bindings-map
            (kbd "M-j")
            (lambda ()
              (interactive)
              (join-line -1)))

Buffers & Navigation

Killing Buffers

Sometimes, I’m putting some work away and I don’t want those files to show up in the buffer list. Killing a buffer with C-x k or marking several buffers in the buffer list to kill them is fine, but can be a bit cumbersome.

I found this function in a Stack Exchange answer. It allows me to close the current buffer easily by pressing C-c k. If I prefix it, by writing C-u C-c k, then all “interesting” buffers are killed, leaving internal Emacs buffers intact. This cleans up all the buffers I’ve opened or used myself.

(defun soph/kill-buffer (&optional arg)
"When called with a prefix argument -- i.e., C-u -- kill all interesting
buffers -- i.e., all buffers without a leading space in the buffer-name.
When called without a prefix argument, kill just the current buffer
-- i.e., interesting or uninteresting."
(interactive "P")
  (cond
    ((and (consp arg) (equal arg '(4)))
      (mapc
        (lambda (x)
          (let ((name (buffer-name x)))
            (unless (eq ?\s (aref name 0))
              (kill-buffer x))))
        (buffer-list)))
    (t
      (kill-buffer (current-buffer)))))

(define-key custom-bindings-map (kbd "C-c k") 'soph/kill-buffer)

Opening, Closing, & Switching Windows

Opening, switching and deleting windows becomes super easy with switch-window.

(use-package switch-window
  :bind (:map custom-bindings-map
              ("C-x o" . 'switch-window)
              ("C-x 1" . 'switch-window-then-maximize)
              ("C-x 2" . 'switch-window-then-split-below)
              ("C-x 3" . 'switch-window-then-split-right)
              ("C-x 0" . 'switch-window-then-delete)))

I often need to switch back and forth between the current and the last opened buffer, which usually takes three keystrokes: C-x b RET. Let’s bind it to C-. for convenience, with a function I got from What the .emacs.d!?.

(fset 'quick-switch-buffer [?\C-x ?b return])
(define-key custom-bindings-map (kbd "C-.") 'quick-switch-buffer)

And Transpose Frame has some nice functions for shifting windows around. I only really use the one to swap the left- and right-hand sides of the frame, but there are others you might find useful.

(use-package transpose-frame
  :bind (:map custom-bindings-map
              ("C-c f" . 'flop-frame)))

Project Management

Projectile provides a convenient project interaction interface. I keep most of my projects in a specific folder, so I’ll set Projectile to check that path specifically.

(use-package projectile
  :defer t
  :bind (:map custom-bindings-map ("C-c p" . projectile-command-map))
  :config
  (setq projectile-project-search-path '("~/Dropbox/projects/"))
  (projectile-mode))

Search & Completion

For completions and search, I use Vertico and a suite of other packages that play well together:

Search Utilities

Projectile also comes with a ton of built-in functionality to search in your projects. Other packages I use also depend on search utilities.

I use both ripgrep and ag (The Silver Searcher). wgrep also comes in handy sometimes. I’ll install all the corresponding Emacs packages.

(use-package ripgrep
  :defer t)

(use-package rg
  :defer t)

(use-package ag
  :defer t)

(use-package wgrep
  :defer t)

I want to use ripgrep as grep.

(setq grep-command "rg -nS --no-heading "
      grep-use-null-device nil)

Vertico

Vertico is heart of this completion UI! I’ll use the function from this What the .emacs.d!? post which lets me type ~ at the Vertico prompt to go directly to the home directory. For use with Vertico, I add a call to delete-minibuffer-contents so that old path is cleared before starting the new file path (starting at ~/).

(defun soph/take-me-home ()
  (interactive)
  (if (looking-back "/" nil)
      (progn (call-interactively 'delete-minibuffer-contents) (insert "~/"))
    (call-interactively 'self-insert-command)))

(use-package vertico
  :defer t
  :bind (:map vertico-map ("~" . soph/take-me-home))
  :config
  (vertico-mode)
  (vertico-multiform-mode)
  (setq read-extended-command-predicate       'command-completion-default-include-p
        vertico-count                         28  ; Show more candidates
        read-file-name-completion-ignore-case t   ; Ignore case of file names
        read-buffer-completion-ignore-case    t   ; Ignore case in buffer completion
        completion-ignore-case                t)) ; Ignore case in completion

Vertico Posframe

vertico-posframe makes Vertico appear in a small child frame, instead of as a traditional minibuffer. I like to have mine in the middle of the frame, with small fringes on either side.

I temporarily disable vertico-posframe-mode when searching with consult. When selecting a search match, a preview is provided. That’s kind of hard to see with the posframe in the middle of the screen, so while searching I just use the normal minibuffer.

(use-package vertico-posframe
  :config
  (vertico-posframe-mode 1)
  (setq vertico-posframe-width        88                      ;; Narrow frame
        vertico-posframe-height       vertico-count           ;; Default height
        vertico-posframe-parameters   '((left-fringe  . 12)   ;; Fringes
                                        (right-fringe . 12)
                                        (undecorated  . nil)) ;; Rounded frame
        ;; Don't create posframe for these commands
        vertico-multiform-commands    '((consult-line    (:not posframe))
                                        (consult-ripgrep (:not posframe)))))

Consult

Consult provides a ton of search, navigation, and completion functionality. I would definitely recommend looking at the documentation to learn more about all that it can do.

(use-package consult
  :bind (:map custom-bindings-map
              ("C-s"   . consult-line)
              ("C-M-s" . consult-ripgrep)
              ("C-x b" . consult-buffer)
              ("M-g g" . consult-goto-line)))

Marginalia

Marginalia gives me annotations in the minibuffer.

(use-package marginalia
  :init 
  (marginalia-mode 1))

Corfu & Cape

corfu gives me text completion at point.

I’ll set it to start suggesting candidates automatically and quickly.

By default, the completion’s command for inserting a candidate is bound to RET and typically, when I press RET, I want to create a new line, so I’ll unbind RET in the corfu map.

(use-package corfu
  :custom
  (corfu-auto            t)       ;; Enable auto completion
  (corfu-cycle           t)       ;; Enable cycling for `corfu-next/previous'
  (corfu-auto-delay      0)       ;; No delay
  (corfu-auto-prefix     2)       ;; Start with this many characters typed
  (corfu-popupinfo-delay 0.5)     ;; Short delay
  (corfu-preselect       'prompt) ;; Preselect the prompt
  :bind (:map corfu-map
              ("RET" . nil))
  :init
  (global-corfu-mode))

(use-package emacs
  :bind ("C-<tab>" . 'corfu-insert-separator)
  :init
  ;; Hide commands in M-x which do not apply to the current mode.
  ;; Corfu commands are hidden, since they are not supposed to be used via M-x.
  (setq read-extended-command-predicate
        #'command-completion-default-include-p))

corfu also uses some of cape’s functionalities, so let’s add that, too.

(use-package cape
  :init
  ;; Add `completion-at-point-functions', used by `completion-at-point'.
  ;; NOTE: The order matters!
  (add-to-list 'completion-at-point-functions #'cape-dabbrev)
  (add-to-list 'completion-at-point-functions #'cape-file)
  (add-to-list 'completion-at-point-functions #'cape-elisp-block)
  (add-to-list 'completion-at-point-functions #'cape-history)
  (add-to-list 'completion-at-point-functions #'cape-keyword)
  (add-to-list 'completion-at-point-functions #'cape-tex)
  (add-to-list 'completion-at-point-functions #'cape-dict)
  ;;(add-to-list 'completion-at-point-functions #'cape-sgml)
  ;;(add-to-list 'completion-at-point-functions #'cape-rfc1345)
  ;;(add-to-list 'completion-at-point-functions #'cape-abbrev)
  ;;(add-to-list 'completion-at-point-functions #'cape-symbol)
  ;;(add-to-list 'completion-at-point-functions #'cape-line)
)

Orderless

And Orderless is a package for a completion style, that matches multiple regexes, in any order. Let’s use it together with Corfu.

(use-package orderless
  :ensure t
  :config
  (setq completion-styles '(orderless basic partial-completion)
        completion-category-overrides '((file (styles basic partial-completion)))
        orderless-component-separator "[ |]"))

Misc. Packages

Dired

Emacs’s default file manager is nice, but contains a bit more info than I usually need. dired-hide-details-mode does what it says on the tin, and I can easily activate/deactivate it on the fly with the default keybinding, (.

(add-hook 'dired-mode-hook 'dired-hide-details-mode)
(add-hook 'dired-mode-hook 'olivetti-mode)
(when (and (eq system-type 'darwin) (executable-find "gls"))
    (setq dired-use-ls-dired nil))

diredfl adds extra font lock rules for dired to colour files differently depending on type.

(use-package diredfl
  :defer t
  :init  (diredfl-global-mode))

Terminal Emulator

vterm

I like vterm and usually just use that. I don’t want it to double check with me before killing an instance of the terminal, so I’ll set it to just kill it. I also really Lars’ vterm functions, so I’ll use those as well. One is for toggling the vterm buffer with the other open buffer, and another binds a separate vterm instance to each M-n keystroke.

Lastly, deleting whole words doesn’t work well in vterm by default, so if anyone has a good tip for how to overwrite my custom bindings map in just vterm, please do let me know :~)

(use-package vterm
  :defer t

  :preface
  (let ((last-vterm ""))
    (defun toggle-vterm ()
      (interactive)
      (cond ((string-match-p "^\\vterm<[1-9][0-9]*>$" (buffer-name))
             (goto-non-vterm-buffer))
            ((get-buffer last-vterm) (switch-to-buffer last-vterm))
            (t (vterm (setq last-vterm "vterm<1>")))))

    (defun goto-non-vterm-buffer ()
      (let* ((r "^\\vterm<[1-9][0-9]*>$")
             (vterm-buffer-p (lambda (b) (string-match-p r (buffer-name b))))
             (non-vterms (cl-remove-if vterm-buffer-p (buffer-list))))
        (when non-vterms
          (switch-to-buffer (car non-vterms)))))

	(defun switch-vterm (n)
      (let ((buffer-name (format "vterm<%d>" n)))
        (setq last-vterm buffer-name)
        (cond ((get-buffer buffer-name)
               (switch-to-buffer buffer-name))
              (t (vterm buffer-name)
                 (rename-buffer buffer-name))))))

  :bind (:map custom-bindings-map
              ("C-z" . toggle-vterm)
              ("M-1" . (lambda () (interactive) (switch-vterm 1)))
              ("M-2" . (lambda () (interactive) (switch-vterm 2)))
              ("M-3" . (lambda () (interactive) (switch-vterm 3)))
              ("M-4" . (lambda () (interactive) (switch-vterm 4)))
              ("M-5" . (lambda () (interactive) (switch-vterm 5)))
              ("M-6" . (lambda () (interactive) (switch-vterm 6)))
              ("M-7" . (lambda () (interactive) (switch-vterm 7)))
              ("M-8" . (lambda () (interactive) (switch-vterm 8)))
              ("M-9" . (lambda () (interactive) (switch-vterm 9))))
  :bind (:map vterm-mode-map
			  ("C-c C-c" . (lambda () (interactive) (vterm-send-key (kbd "C-c")))))

  :config
  ;; Don't query about killing vterm buffers, just kill it
  (defadvice vterm (after kill-with-no-query nil activate)
    (set-process-query-on-exit-flag (get-buffer-process ad-return-value) nil)))

Version Control (Magit & Friends)

Magit is a Git client specifically for Emacs, and it’s super powerful. It’s the centre of all my version control packages.

Git Gutter with diff-hl

Let’s first make sure we’re highlighting uncommitted changes with diff-hl. It highlights added, deleted, and modified code segments by adding a coloured bar to the left-hand gutter of the buffer.

(use-package diff-hl
  :config
  (global-diff-hl-mode))

Magit

Then configure Magit. I’ll add hooks to have diff-hl update the gutter whenever Magit refreshes.

(use-package magit
  :defer t
  :hook
  ((magit-pre-refresh  . diff-hl-magit-pre-refresh)
   (magit-post-refresh . diff-hl-magit-post-refresh))
  :config
  (setq magit-mode-quit-window 'magit-restore-window-configuration
		magit-auto-revert-mode t))

Magit TODOs

I’ll use magit-todos to show the project’s TODOs directly in the Magit buffer.

(use-package magit-todos
  :after magit
  :config
  (magit-todos-mode 1))

Magit Forge

And Magit Forge to be able to work with Git forges (e.g., GitHub, and GitLab) directly from Magit.

(use-package forge
  :after magit)

Git Link

git-link creates URL links to the current position in your buffer in the corresponding forge repo. Super handy for sending to others.

(use-package git-link
  :defer t
  :init
  (setq git-link-use-commit t
        git-link-open-in-browser t))

Git Timemachine

Git Time Machine lets you step through different versions of a Git-controlled file directly in the current buffer, without even needing to hop over to the Magit status buffer.

(use-package git-timemachine
  :defer t)

Trying Packages

Lars Tveito’s Try package lets you try out packages and only save them temporarily, saving you the hassle of cleaning up afterwards if you decide you don’t want to keep using the package. You can even try packages from .el files from URLs directly.

(use-package try)

Snippets

YASnippet is a template system for Emacs that allows you to predefine snippets you use often and insert them easily. I want snippets for basic Org-files, Roam-notes, and other sequences often used.

(use-package yasnippet
  :diminish yas-minor-mode
  :defer 5
  :config
  (setq yas-snippet-dirs '("~/.emacs.d/snippets/"))
  (yas-global-mode 1)) ;; or M-x yas-reload-all if you've started YASnippet already.

;; Silences the warning when running a snippet with backticks (runs a command in the snippet)
(require 'warnings)
(add-to-list 'warning-suppress-types '(yasnippet backquote-change)) 

Better Help Buffers

Helpful is an improvement on Emacs’ built-in help buffer. It’s more user-friendly and easier to read.

(use-package helpful
  :bind (:map custom-bindings-map
			  ("C-h f" . #'helpful-function)
			  ("C-h v" . #'helpful-variable)
			  ("C-h k" . #'helpful-key)
			  ("C-h x" . #'helpful-command)
			  ("C-h d" . #'helpful-at-point)
			  ("C-h c" . #'helpful-callable)))

which-key shows you available keybindings in the minibuffer. When you’ve started to enter a command, it will show you where you can go from there.

(use-package which-key
  :config
  (which-key-mode))

Jinx Spellchecker

Jinx is a libenchant-powered spellchecker with a super nice UI. I’m trying it out instead of Flyspell, which I used before.

(use-package jinx
  :hook (emacs-startup . global-jinx-mode)
  :bind (("M-$"   . jinx-correct)
         ("C-M-$" . jinx-languages))
  :config
  (setq jinx-languages "en_GB"))

LaTeX

I use AUCTeX to work with LaTeX files from within Emacs and it’s a massive help. It has a lot of different features, and I’d recommend checking out the documentation to see all the stuff you can do with it.

I also really like reftex-mode, which gives you a table of contents with clickable links for your file with the keybinding C-c =.

(use-package auctex
  :hook
  (LaTeX-mode . turn-on-prettify-symbols-mode)
  (LaTeX-mode . reftex-mode)
  (LaTeX-mode . (lambda () (corfu-mode -1)))
  (LaTeX-mode . outline-minor-mode)
  (LaTeX-mode . olivetti-mode))

When the reftex window opens, I want it on the left side of the screen and I want it to take up less than half the screen.

(setq reftex-toc-split-windows-horizontally t
	  reftex-toc-split-windows-fraction     0.2)

PDF Tools

PDF Tools is an improved version of the built-in DocView for viewing PDFs. It has extensive features, but does not play well with consult, so I’ll rebind C-s to isearch-forward.

(use-package pdf-tools
  :defer t
  :init (pdf-loader-install)
  :bind (:map pdf-view-mode-map
              ("C-s"   . isearch-forward)
              ("C-M-s" . pdf-occur)))

Editor Config

I want to use the EditorConfig plugin, which helps maintain consistent coding styles across editors when collaborating.

(use-package editorconfig
  :defer t)

Browser Preference

Open links with Firefox by default.

(when (eq system-type 'darwin)
  (setq browse-url-browser-function 'browse-url-default-macosx-browser))

(when (eq system-type 'gnu/linux)
  (setq browse-url-browser-function 'browse-url-generic
		browse-url-generic-program "firefox"))

Elfeed

Elfeed is a feed reader for Emacs!

(use-package elfeed
  :bind (:map custom-bindings-map ("C-x w" . elfeed))
  :config
  (setq elfeed-feeds
      '("http://nullprogram.com/feed/"
        "https://planet.emacslife.com/atom.xml"
        "https://deniskyashif.com/index.xml"
        "https://sophiebos.io/index.xml")))

Config Profiling

ESUP is a package for profiling your config. You can use it to shave precious seconds off your startup time, which is useful to me because I keep closing it when I’m done with a task and then immediately needing it again.

(use-package esup
  :defer t
  :config
  (setq esup-depth 0))

Org

Org Mode is a smart text system that is used for organising notes, literate programming, time management, and a wide variety of other use cases. I’ve been interested in switching from my previous note-taking app, Obsidian, to using Org and Roam (described in the next section).

Let’s first make sure we’re using Org. Note that I am leaving the last parenthesis open, to include some options from the “Visuals” section inside the use-package declaration for Org mode.

(use-package org
  :defer t

Visuals

Text Centring

Note: We are still in the :config section of the use-package declaration for Org mode.

I always want to center the text and enable linebreaks in Org. I’ve added a hook to activate olivetti-mode, and visual-fill-mode is always on.

:hook (org-mode . olivetti-mode)

Fonts

Note: We are in the :config section of the use-package declaration for Org mode.

Set the sizes and fonts for the various headings.

:config
;; Resize Org headings
(custom-set-faces
'(org-document-title ((t (:height 1.8))))
'(outline-1          ((t (:height 1.35))))
'(outline-2          ((t (:height 1.3))))
'(outline-3          ((t (:height 1.2))))
'(outline-4          ((t (:height 1.1))))
'(outline-5          ((t (:height 1.1))))
'(outline-6          ((t (:height 1.1))))
'(outline-8          ((t (:height 1.1))))
'(outline-9          ((t (:height 1.1)))))

LaTeX Previews

Note: We are in the :config section of the use-package declaration for Org mode.

Preview LaTeX fragments by default.

(setq org-startup-with-latex-preview t)

Increase the size of LaTeX previews in Org.

(plist-put org-format-latex-options :scale 1.35)

I’ve been struggling a little to get LaTeX previews to work on my work Mac. I symlinked my LaTeX texbin directory to /usr/local/bin, and it still didn’t work. Eventually I found this Stack Exchange post that correctly diagnosed the issue.

(let ((png (cdr (assoc 'dvipng org-preview-latex-process-alist))))
    (plist-put png :latex-compiler '("latex -interaction nonstopmode -output-directory %o %F"))
    (plist-put png :image-converter '("dvipng -D %D -T tight -o %O %F"))
    (plist-put png :transparent-image-converter '("dvipng -D %D -T tight -bg Transparent -o %O %F")))

Folded Startup

Note: We are still in the :config section of the use-package declaration for Org mode.

In general, show me all the headings.

(setq org-startup-folded 'content)

Decluttering

Note: We are still in the :config section of the use-package declaration for Org mode.

We’ll declutter by adapting the indentation and hiding leading starts in headings. We’ll also use “pretty entities”, which allow us to insert special characters LaTeX-style by using a leading backslash (e.g., \alpha to write the greek letter alpha) and display ellipses in a condensed way.

(setq org-adapt-indentation t
      org-hide-leading-stars t
      org-pretty-entities t
      org-ellipsis "  ·")

For source code blocks specifically, I want Org to display the contents using the major mode of the relevant language. I also want TAB to behave inside the source code block like it normally would when writing code in that language.

(setq org-src-fontify-natively t
      org-src-tab-acts-natively t
      org-edit-src-content-indentation 0)

Some Org options to deal with headers and TODO’s nicely.

(setq org-log-done                       t
      org-auto-align-tags                t
      org-tags-column                    -80
      org-fold-catch-invisible-edits     'show-and-error
      org-special-ctrl-a/e               t
      org-insert-heading-respect-content t)

Let’s finally close the use-package declaration with a parenthesis.

)

Hide Emphasis Markers

Many people hide emphasis markers (e.g., /.../ for italics, *...* for bold, etc.) to have a cleaner visual look, but I got frustrated trying to go back and edit text in these markers, as sometimes I would delete the markers itself or write outside the markers. org-appear is the solution to all my troubles. It displays the markers when the cursor is within them and hides them otherwise, making edits easy while looking pretty.

(use-package org-appear
  :commands (org-appear-mode)
  :hook     (org-mode . org-appear-mode)
  :config 
  (setq org-hide-emphasis-markers t)  ;; Must be activated for org-appear to work
  (setq org-appear-autoemphasis   t   ;; Show bold, italics, verbatim, etc.
        org-appear-autolinks      t   ;; Show links
        org-appear-autosubmarkers t)) ;; Show sub- and superscripts

Inline Images

Show inline images by default

(setq org-startup-with-inline-images t)

Variable Pitch

Make sure variable-pitch-mode is always active in Org buffers. I normally wouldn’t need this, since I use the mixed-pitch package in the font section, but for some reason, it seems the header bullet in Org mode are affected by this.

(add-hook 'org-mode-hook 'variable-pitch-mode)

LaTeX Fragtog

org-fragtog works like org-appear, but for LaTeX fragments: It toggles LaTeX previews on and off automatically, depending on the cursor position. If you move the cursor to a preview, it’s toggled off so you can edit the LaTeX snippet. When you move the cursor away, the preview is turned on again.

(use-package org-fragtog
  :after org
  :hook (org-mode . org-fragtog-mode))

Bullets

org-superstar styles some of my UI elements, such as bullets and special checkboxes for TODOs.

(use-package org-superstar
  :after org
  :config
  (setq org-superstar-leading-bullet " ")
  (setq org-superstar-headline-bullets-list '("" "" "" "" "" ""))
  (setq org-superstar-special-todo-items t) ;; Makes TODO header bullets into boxes
  (setq org-superstar-todo-bullet-alist '(("TODO"  . 9744)
                                          ("PROG"  . 9744)
                                          ("NEXT"  . 9744)
                                          ("WAIT"  . 9744)
                                          ("DONE"  . 9745)))
  :hook (org-mode . org-superstar-mode))

SVG Elements

svg-tag-mode lets you replace keywords such as TODOs, tags, and progress bars with nice SVG graphics. I use it for dates, progress bars, and citations.

(use-package svg-tag-mode
  :after org
  :config
  (defconst date-re "[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}")
  (defconst time-re "[0-9]\\{2\\}:[0-9]\\{2\\}")
  (defconst day-re "[A-Za-z]\\{3\\}")
  (defconst day-time-re (format "\\(%s\\)? ?\\(%s\\)?" day-re time-re))

  (defun svg-progress-percent (value)
	(svg-image (svg-lib-concat
				(svg-lib-progress-bar (/ (string-to-number value) 100.0)
			      nil :margin 0 :stroke 2 :radius 3 :padding 2 :width 11)
				(svg-lib-tag (concat value "%")
				  nil :stroke 0 :margin 0)) :ascent 'center))

  (defun svg-progress-count (value)
	(let* ((seq (mapcar #'string-to-number (split-string value "/")))
           (count (float (car seq)))
           (total (float (cadr seq))))
	  (svg-image (svg-lib-concat
				  (svg-lib-progress-bar (/ count total) nil
					:margin 0 :stroke 2 :radius 3 :padding 2 :width 11)
				  (svg-lib-tag value nil
					:stroke 0 :margin 0)) :ascent 'center)))
  (setq svg-tag-tags
      `(
        ;; Org tags
        ;; (":\\([A-Za-z0-9]+\\)" . ((lambda (tag) (svg-tag-make tag))))
        ;; (":\\([A-Za-z0-9]+[ \-]\\)" . ((lambda (tag) tag)))
        
        ;; Task priority
        ("\\[#[A-Z]\\]" . ( (lambda (tag)
                              (svg-tag-make tag :face 'org-priority 
                                            :beg 2 :end -1 :margin 0))))

        ;; Progress
        ("\\(\\[[0-9]\\{1,3\\}%\\]\\)" . ((lambda (tag)
          (svg-progress-percent (substring tag 1 -2)))))
        ("\\(\\[[0-9]+/[0-9]+\\]\\)" . ((lambda (tag)
          (svg-progress-count (substring tag 1 -1)))))
        
        ;; TODO / DONE
        ;; ("TODO" . ((lambda (tag) (svg-tag-make "TODO" :face 'org-todo
		;; 									           :inverse t :margin 0))))
        ;; ("DONE" . ((lambda (tag) (svg-tag-make "DONE" :face 'org-done :margin 0))))


        ;; Citation of the form [cite:@Knuth:1984] 
        ("\\(\\[cite:@[A-Za-z]+:\\)" . ((lambda (tag)
                                          (svg-tag-make tag
                                                        :inverse t
                                                        :beg 7 :end -1
                                                        :crop-right t))))
        ("\\[cite:@[A-Za-z]+:\\([0-9]+\\]\\)" . ((lambda (tag)
                                                (svg-tag-make tag
                                                              :end -1
                                                              :crop-left t))))

        
        ;; Active date (with or without day name, with or without time)
        (,(format "\\(<%s>\\)" date-re) .
         ((lambda (tag)
            (svg-tag-make tag :beg 1 :end -1 :margin 0))))
        (,(format "\\(<%s \\)%s>" date-re day-time-re) .
         ((lambda (tag)
            (svg-tag-make tag :beg 1 :inverse nil :crop-right t :margin 0))))
        (,(format "<%s \\(%s>\\)" date-re day-time-re) .
         ((lambda (tag)
            (svg-tag-make tag :end -1 :inverse t :crop-left t :margin 0))))

        ;; Inactive date  (with or without day name, with or without time)
         (,(format "\\(\\[%s\\]\\)" date-re) .
          ((lambda (tag)
             (svg-tag-make tag :beg 1 :end -1 :margin 0 :face 'org-date))))
         (,(format "\\(\\[%s \\)%s\\]" date-re day-time-re) .
          ((lambda (tag)
             (svg-tag-make tag :beg 1 :inverse nil
						       :crop-right t :margin 0 :face 'org-date))))
         (,(format "\\[%s \\(%s\\]\\)" date-re day-time-re) .
          ((lambda (tag)
             (svg-tag-make tag :end -1 :inverse t
						       :crop-left t :margin 0 :face 'org-date)))))))

(add-hook 'org-mode-hook 'svg-tag-mode)

Prettify Tags & Keywords

I have a custom function to prettify tags and other elements, lifted from Jake B’s Emacs setup.

(defun soph/prettify-symbols-setup ()
  "Beautify keywords"
  (setq prettify-symbols-alist
		(mapcan (lambda (x) (list x (cons (upcase (car x)) (cdr x))))
				'(; Greek symbols
				  ("lambda" . )
				  ("delta"  . )
				  ("gamma"  . )
				  ("phi"    . )
				  ("psi"    . )
				  ; Org headers
				  ("#+title:"  . "")
				  ("#+author:" . "")
				  ; Checkboxes
				  ("[ ]" . "")
				  ("[X]" . "")
				  ("[-]" . "")
				  ; Blocks
				  ("#+begin_src"   . "") ;
				  ("#+end_src"     . "")
				  ("#+begin_QUOTE" . "")
				  ("#+begin_QUOTE" . "")
				  ; Drawers
				  ;    ⚙️
				  (":properties:" . "")
				  ; Agenda scheduling
				  ("SCHEDULED:"   . "🕘")
				  ("DEADLINE:"    . "")
				  ; Agenda tags  
				  (":@projects:"  . "")
				  (":work:"       . "🚀")
				  (":@inbox:"     . "✉️")
				  (":goal:"       . "🎯")
				  (":task:"       . "📋")
				  (":@thesis:"    . "📝")
				  (":thesis:"     . "📝")
				  (":uio:"        . "🏛️")
				  (":emacs:"      . "")
				  (":learn:"      . "🌱")
				  (":code:"       . "💻")
				  (":fix:"        . "🛠️")
				  (":bug:"        . "🚩")
				  (":read:"       . "📚")
				  ; Roam tags
				  ("#+filetags:"  . "📎")
				  (":wip:"        . "🏗️")
				  (":ct:"         . "➡️") ; Category Theory
				  )))
  (prettify-symbols-mode))

(add-hook 'org-mode-hook        #'soph/prettify-symbols-setup)
(add-hook 'org-agenda-mode-hook #'soph/prettify-symbols-setup)

Right-Align Tags

Code snippet from this Reddit post. It actually right-aligns tags, using font-lock and the display property.

(add-to-list 'font-lock-extra-managed-props 'display)
(font-lock-add-keywords 'org-mode
                        `(("^.*?\\( \\)\\(:[[:alnum:]_@#%:]+:\\)$"
                           (1 `(face nil
                                     display (space :align-to (- right ,(org-string-width (match-string 2)) 3)))
                              prepend))) t)

General Interaction

Opening Links

By default, when opening an Org-link, the current window is split into two. I’d like for the new window to replace the current one. To do this, we need to edit org-link-frame-setup and change the default cons (file . find-file-other-window) to (file . find-file).

(setq org-link-frame-setup
      '((vm      . vm-visit-folder-other-frame)
        (vm-imap . vm-visit-imap-folder-other-frame)
        (gnus    . org-gnus-no-new-news)
        (file    . find-file)
        (wl      . wl-other-frame)))

I’d also like to open links with RET.

(setq org-return-follows-link t)

Editing

Don’t insert a blank newline before new entries (e.g., list bullets and section headings). I find it annoying when I want to insert a new task under the current one in my agenda if there’s a blank newline between the previous entry and the next.

(setq org-blank-before-new-entry '((heading . nil)
                                   (plain-list-item . nil)))

Tasks

Task Priorities

Let’s increase the number of possible priorities for Org tasks. I’ll set mine to E so that we have A through E, in total five levels.

(setq org-lowest-priority  ?F) ;; Gives us priorities A through F
(setq org-default-priority ?E) ;; If an item has no priority, it is considered [#E].

(setq org-priority-faces
      '((65 . "#BF616A")
        (66 . "#EBCB8B")
        (67 . "#B48EAD")
        (68 . "#81A1C1")
        (69 . "#5E81AC")
        (70 . "#4C566A")))

Custom TODO States

I’ll expand the list of default task states.

(setq org-todo-keywords
      '((sequence
         ;; Needs further action
		 "TODO(t)" "WAIT(w)" "NEXT(n)" "PROG(p)" "QUESTION(q)"
		 "|"
         ;; Needs no action currently
		 "DONE(d)")))

Mark As Done

Finally, to mark any TODO task, of any state, as DONE quickly, I have a helper function that I’ll bind to C-c d.

(defun org-mark-as-done ()
  (interactive)
  (save-excursion
    (org-back-to-heading t) ;; Make sure command works even if point is
                            ;; below target heading
    (cond ((looking-at "\*+ TODO")
           (org-todo "DONE"))
		  ((looking-at "\*+ NEXT")
           (org-todo "DONE"))
          ((looking-at "\*+ WAIT")
           (org-todo "DONE"))
		  ((looking-at "\*+ PROG")
           (org-todo "DONE"))
		  ((looking-at "\*+ DONE")
           (org-todo "DONE"))
          (t (message "Undefined TODO state.")))))

(define-key custom-bindings-map (kbd "C-c d") 'org-mark-as-done)

“Get Things Done” Setup

I’m trying out the Get Things Done method by David Allen, using Nicolas Rougier’s GTD configuration and Nicolas Petton’s blog post on the subject.

The first step is to set the relevant directories.

(setq org-directory "~/Dropbox/org/")
(add-to-list 'org-agenda-files "inbox.org")
(add-to-list 'org-agenda-files "thesis.org")

Set the archive location to a unified archive.

(setq org-archive-location (concat org-directory "archive.org::"))

Then to set up the relevant capture templates, with accompanying keybindings.

(setq org-capture-templates
       `(("i" "Inbox" entry  (file "inbox.org")
        ,(concat "* TODO %?\n"
                 "/Entered on/ %U"))
		 ("t" "Thesis" entry  (file "thesis.org")
        ,(concat "* TODO %?\n"
                 "/Entered on/ %U"))))
(defun org-capture-inbox ()
     (interactive)
     (call-interactively 'org-store-link)
     (org-capture nil "i"))

Keybindings

For basic agenda and TODO-related keybindings, I’ll use C-c followed by a single, lower-case letter.

(define-key custom-bindings-map (kbd "C-c l") 'org-store-link)
(define-key custom-bindings-map (kbd "C-c a") 'org-agenda)
(define-key custom-bindings-map (kbd "C-c c") 'org-capture)
(define-key custom-bindings-map (kbd "C-c t") 'org-todo)

For whatever reason, I’ve had an issue with clocking in, where the default keybinding used TAB instead of C-i to clock in, so I’ll set that manually.

(define-key org-mode-map (kbd "C-c C-x C-i") 'org-clock-in)

Registers

Registers are easier to access than bookmarks and much more flexible. I’ll set up registers for my GTD files.

(set-register ?1 (cons 'file (concat org-directory "inbox.org")))
(set-register ?2 (cons 'file (concat org-directory "thesis.org")))
(set-register ?3 (cons 'file (concat org-directory "roam/20240128135100-roam.org")))
(set-register ?4 (cons 'file (concat org-directory "projects.org")))
(set-register ?5 (cons 'file "~/Documents/playground/clj-playground/src/clj_playground/playground.clj"))

Since I have C-s bound to consult-line which lets me search everywhere in a file, I don’t really need C-r to be bound to the default isearch-backward. Instead, I can use it as the leader key combination to jump to a register.

(define-key custom-bindings-map (kbd "C-r") 'jump-to-register)

Agenda

First, some regular agenda settings.

I want to open my agenda on the current day, not on any specific weekday.

I also don’t want to have a divider line separating my different agenda blocks. This is because I sometimes use packages like Olivetti to center the agenda, which makes the divider line wrap around and take up multiple lines.

Similarly, I right-align my tags, so they also end up shifted around and often on a new line. org-agenda-remove-tags doesn’t remove them, but for some reason it disables the right-alignment in the agenda, which is perfect.

(setq org-agenda-start-on-weekday nil
      org-agenda-block-separator  nil
      org-agenda-remove-tags      t)

Super Agenda

org-super-agenda lets you group agenda items into sections, so it’s easier to navigate.

(use-package org-super-agenda
  :after org
  :config
  (setq org-super-agenda-header-prefix "\n")
  ;; Hide the thin width char glyph
  (add-hook 'org-agenda-mode-hook
            #'(lambda () (setq-local nobreak-char-display nil)))
  (org-super-agenda-mode))

Org QL

org-ql is a query language for Org mode. It’s super powerful and doesn’t really belong in the Agenda section of my config, but for now, I only use it to find things and to set up a pretty calendar view.

(use-package org-ql
  :defer t)

Agenda Views

With Super Agenda and Org QL, we can now define some display groups for the agenda, to show us exactly the info we want.

We’ll set up some groups with the Super Agenda syntax.

;; Delete default agenda commands
(setq org-agenda-custom-commands nil)

(defvar regular-view-groups
  '((:name "Scheduled"
     :scheduled t
     :order 1)
	(:name "Deadlines"
     :deadline t
     :order 2)))

Now I’ll set up commands to open the day view with C-c a d and extended three-day view with C-c a e. Notice that I’m first setting some options for the built-in agenda, and then defining a block with Super Agenda groups and Org QL queries.

(add-to-list 'org-agenda-custom-commands
	  '("d" "Day View"
		 ((agenda "" ((org-agenda-overriding-header "Day View")
                      (org-agenda-span 'day)
                      (org-super-agenda-groups regular-view-groups)))
		  (org-ql-block '(todo "PROG") ((org-ql-block-header "\n❯ In Progress")))
		  (org-ql-block '(todo "NEXT") ((org-ql-block-header "\n❯ Next Up")))
          (org-ql-block '(todo "WAIT") ((org-ql-block-header "\n❯ Waiting")))
		  (org-ql-block '(priority "A") ((org-ql-block-header "\n❯ Important"))))))


(add-to-list 'org-agenda-custom-commands
		'("e" "Three-Day View"
               ((agenda "" ((org-agenda-span 3)
                            (org-agenda-start-on-weekday nil)
                            (org-deadline-warning-days 0))))))

Displaying Scheduled & Deadline Items

Don’t show me deadlines or scheduled items if they are done.

(setq org-agenda-skip-deadline-if-done  t
	  org-agenda-skip-scheduled-if-done t)

Modify dealine leader text.

(setq org-agenda-deadline-leaders '("Deadline:  " "In %2d d.: " "%2d d. ago: "))

Startup with Agenda View

I used to have a nice dashboard as a welcome screen, but when I open Emacs, I usually just open a recently opened buffer with C-x b or I open a project with C-c p p. It’s more useful to me to immediately get an overview of my tasks so I can jump right into it. The below hook runs my custom agenda function to open a day view, and deletes other windows so I don’t see the agenda and the scratch buffer.

(defun soph/show-day-agenda ()
  (progn (org-agenda nil "d")
		 (delete-other-windows)
		 (olivetti-mode)))

(add-hook 'emacs-startup-hook 'soph/show-day-agenda)

Babel

For working with code blocks in Org mode, I want to make sure code blocks are not evaluated by default on export. I also want to add some languages.

(setq org-export-use-babel       nil
      org-confirm-babel-evaluate nil)
;; (org-babel-do-load-languages
;;  'org-babel-load-languages
;;  '((emacs-lisp . t)
;;    (python     . t)
;;    (haskell    . t)
;;    (clojure    . t)))

For Python, use whatever interpreter is set by python-shell-interpreter.

(use-package ob-python
  :ensure nil
  :after (ob python)
  :config
  (setq org-babel-python-command python-shell-interpreter))

Roam

Roam is a smart note-taking system in the style of a personal knowledge management system. org-roam is a port of this system that uses all plain-text Org-files.

I set up a Roam directory and added a simple configuration for navigating Roam nodes.

(use-package org-roam
  :after org
  :hook (org-roam-mode . org-roam-db-autosync-mode)
  :init
  (setq org-roam-v2-ack t)
  :custom
  (org-roam-directory "~/Dropbox/org/roam")
  (org-roam-completion-everywhere t)
  :bind
  ("C-c n t" . org-roam-buffer-toggle)
  ("C-c n f" . org-roam-node-find)
  ("C-c n i" . org-roam-node-insert)
  ("C-c q"   . org-roam-tag-add)
  :config
  ;; Sync my Org Roam database automatically
  (org-roam-db-autosync-enable)
  (org-roam-db-autosync-mode)
  ;; Open Org files in same window
  (add-to-list 'org-link-frame-setup '(file . find-file)))

Consult Org Roam

(use-package consult-org-roam
   :ensure t
   :after org-roam
   :init
   (require 'consult-org-roam)
   ;; Activate the minor mode
   (consult-org-roam-mode 1)
   :custom
   ;; Use `ripgrep' for searching with `consult-org-roam-search'
   (consult-org-roam-grep-func #'consult-ripgrep)
   ;; Configure a custom narrow key for `consult-buffer'
   (consult-org-roam-buffer-narrow-key ?r)
   ;; Display org-roam buffers right after non-org-roam buffers
   ;; in consult-buffer (and not down at the bottom)
   (consult-org-roam-buffer-after-buffers t)
   :config
   ;; Eventually suppress previewing for certain functions
   (consult-customize
    consult-org-roam-forward-links
    :preview-key "M-.")
   :bind
   ;; Define some convenient Org Roam keybindings
   ("C-c n e" . consult-org-roam-file-find)
   ("C-c n b" . consult-org-roam-backlinks)
   ("C-c n l" . consult-org-roam-forward-links)
   ("C-c n r" . consult-org-roam-search))

Show Tags in Search

When searching for nodes, you can search either by name or by tag. Both are shown in the menu.

(setq org-roam-node-display-template
      (concat "${title:*} "
        (propertize "${tags:10}" 'face 'org-tag)))

Follow Links

Follow links with RET.

(setq org-return-follows-link t)

Graph UI

Org Roam UI gives you a pretty and functional graph of your notes, Obsidian-style.

(use-package org-roam-ui
    :after org-roam
    :config
    (setq org-roam-ui-sync-theme t
          org-roam-ui-follow t
          org-roam-ui-update-on-save t
          org-roam-ui-open-on-start t))

Hugo

Hugo is a static site generator. By default, it uses a Markdown flavour called Blackfriday. The package ox-hugo can export Org files to this format, and also generate appropriate front-matter. I use it to write my blog in Org and easily put it online.

(use-package ox-hugo
  :after org)

I’ve had a great time blogging with ox-hugo, but it’s a little bothersome to have to rewrite the front-matter required in the blog post for it to export property every time, so below is a little snippet lifted from ox-hugo’s blog.

The file all-posts,org needs to be present in ‘org-directory’ and the file’s heading must be “Blog Posts”. It can even be a symlink pointing to the actual location of all-posts.org! If you’ve named yours differently, change these values.

(with-eval-after-load 'org-capture
  (defun org-hugo-new-subtree-post-capture-template ()
    "Returns `org-capture' template string for new Hugo post.
See `org-capture-templates' for more information."
    (let* ((title (read-from-minibuffer "Post Title: "))
           (fname (org-hugo-slug title)))
      (mapconcat #'identity
                 `(
                   ,(concat "* TODO " title)
                   ":PROPERTIES:"
                   ,(concat ":EXPORT_FILE_NAME: " fname)
                   ":END:"
                   "%?\n")          ;Place the cursor here finally
                 "\n")))

  (add-to-list 'org-capture-templates
               '("h"                ;`org-capture' binding + h
                 "Hugo post"
                 entry
                 (file+olp "all-posts.org" "Blog Posts")
                 (function org-hugo-new-subtree-post-capture-template))))

Org Present

org-present is a mode for creating straightforward and nice presentations from Org-files. Most of this config is from System Crafters’ blog post on the subject.

(defun soph/org-present-prepare-slide ()
  ;; Show only top-level headlines
  (org-overview)
  ;; Unfold the current entry
  (org-fold-show-entry)
  ;; Show only direct subheadings of the slide but don't expand them
  (org-fold-show-children))

(defun soph/org-present-start ()
  ;; Tweak font sizes
  (setq-local
   face-remapping-alist '((default (:height 1.5) variable-pitch)
                          (header-line (:height 3.0) variable-pitch)
                          (org-document-title (:height 1.75) org-document-title)
                          (org-code (:height 1.55) org-code)
                          (org-verbatim (:height 1.55) org-verbatim)
                          (org-block (:height 1.25) org-block)
                          (org-block-begin-line (:height 0.7) org-block)))
  ;; Set a blank header line string to create blank space at the top
  (setq header-line-format " "))

(defun soph/org-present-end ()
  ;; Reset font customizations
  (setq-local face-remapping-alist '((default variable-pitch default)))
  ;; Clear the header line string so that it isn't displayed
  (setq header-line-format nil))


(use-package org-present
  :defer t
  :hook
  ((org-present-after-navigate-functions . soph/org-present-prepare-slide)
  (org-present-mode                      . soph/org-present-start)
  (org-present-mode-quit                 . soph/org-present-end)))

Org Conveniencies

Pasting Images with org-download

org-download lets me easily put copied screenshots into my org-documents.

(use-package org-download
  :after org
  :bind
  (:map org-mode-map
        (("s-t" . org-download-screenshot)
         ("s-y" . org-download-clipboard))))

TOC in Org Files

toc-org creates nice, Markdown compatible tables of content for your Org files. Perfect for GitHub READMEs.

(use-package toc-org
  :after org
  :config
  (add-hook 'org-mode-hook 'toc-org-mode)

  ;; enable in markdown, too
  (add-hook 'markdown-mode-hook 'toc-org-mode))

Programming

Preferences & Extras

Custom File Endings

For my MSc thesis, I’m implementing a small functional programming language called Contra. It’s pretty similar to Haskell, so using Haskell mode does a fairly good job of syntax highlighting my .con-files.

(add-to-list 'auto-mode-alist '("\\.con\\'" . haskell-mode))

Language-Specific Commenting

I use C-ø to comment/uncomment lines with Evil Nerd Commenter. It automatically detects most programming languages and applies appropriate comment style.

(use-package evil-nerd-commenter
  :defer t
  :bind (:map custom-bindings-map ("C-ø" . evilnc-comment-or-uncomment-lines)))

Subword Mode

subword-mode lets you work on each subword in camel case words as individual words. It makes it much easier to delete and mark parts of function and variable names.

(add-hook 'prog-mode-hook 'subword-mode)

Markdown

Need-to-have for programmers.

(use-package markdown-mode
  :defer t)

Flycheck

Flycheck is an on-the-fly syntax checker.

(use-package flycheck
  :ensure t
  :init (global-flycheck-mode))

Eldoc

Eldoc is Emacs’ built-in language documentation feature. It will show function documentation as applicable while you’re programming.

(use-package eldoc
  :defer t
  :config
  (global-eldoc-mode))

HTTP

restclient.el lets you run HTTP requests from a static, plain-text query file.

(use-package restclient
  :defer t)

Programming Languages

Emacs Lisp

The holy trinity of Elisp libraries: dash, s, and f.

(use-package dash
  :defer t)

(use-package s
  :defer t)

(use-package f
  :defer t)

Haskell

For Haskell, I think the regular haskell-mode is nice. I’ll add haskell-doc-mode which uses eldoc consistently throughout.

I also want to use the tool Hoogle from directly within Emacs to quickly look up functions and packages. I’ve set it up according to the GitHub docs, so that C-c h opens a prompt and querying the database opens a help buffer inside Emacs with the results.

(use-package haskell-mode
  :defer t
  :hook (haskell-mode . haskell-doc-mode)
  :config
  (setq haskell-hoogle-command                  "hoogle"
        haskell-compile-stack-build-command     "stack build"
        haskell-compile-stack-build-alt-command "stack build --pedantic"
        haskell-compile-command                 "stack build")
  :bind (:map haskell-mode-map
              ("C-c C-h" . haskell-hoogle)
              ("C-c C-c" . haskell-compile)))

Clojure

CIDER adds support for interactive Clojure programming in Emacs. It’s provides built-in support for firing up a REPL and looking up documentation and source code, but it also has very Emacs-like shortcuts for expected actions, such as C-x C-e to evaluate the s-exp at point.

ParEdit will protect your parentheses and keep you sane.

I’ll also disable corfu-mode when CIDER is active, because otherwise the corfu completion pop-up overlaps completions provided by company-mode, which I believe is the default backend for LSP-mode. I dont want to turn it off whenever LSP-mode is active, though, because some languages don’t provide completions through LSP-mode and then corfu is better than nothing.

(use-package clojure-mode
  :defer t
  :config
  (require 'flycheck-clj-kondo))

(use-package cider
  :defer t
  :hook ((cider-mode      . paredit-mode)
         (cider-repl-mode . paredit-mode)
         (cider-mode      . (lambda () (corfu-mode -1)))
         (clojure-mode    . paredit-mode)
         (clojure-mode    . whitespace-mode))
  :bind (:map cider-repl-mode-map ("C-l" . cider-repl-clear-buffer))
  :config
  (setq cider-repl-display-help-banner nil))

clj-kondo is a linter for Clojure. It even has its own flycheck-mode, flycheck-clj-kondo. We need to install it first.

(use-package flycheck-clj-kondo
  :ensure t)

clj-refactor is a CIDER extension for refactoring.

 (use-package clj-refactor
	:after clojure-mode
	:hook (clojure-mode . clj-refactor-mode))

cider-eval-sexp-fu provides small improvements on the default way CIDER evaluates sexpressions.

(use-package cider-eval-sexp-fu
  :defer t)

Agda

To install Agda, you need Haskell - stack or cabal - and a few other programs. Once those are installed, you can add this to your init.el. Or you can just let agda-mode setup do it for you.

(load-file (let ((coding-system-for-read 'utf-8))
                (shell-command-to-string "agda-mode locate")))

OCaml

OCaml requires some setup for ocp-indent,

(use-package ocp-indent
  :defer t)

and for merlin.

(let ((opam-share (ignore-errors (car (process-lines "opam" "var" "share")))))
      (when (and opam-share (file-directory-p opam-share))
		;; Register Merlin
		(add-to-list 'load-path (expand-file-name "emacs/site-lisp" opam-share))
		(autoload 'merlin-mode "merlin" nil t nil)
		;; Automatically start it in OCaml buffers
		(add-hook 'tuareg-mode-hook 'merlin-mode t)
		(add-hook 'caml-mode-hook 'merlin-mode t)
		;; Use opam switch to lookup ocamlmerlin binary
		(setq merlin-command 'opam)))

Then I want integration with Dune, Merlin, and utop for the full IDE-experience.

;; Major mode for OCaml programming
(use-package tuareg
  :defer t
  :mode (("\\.ocamlinit\\'" . tuareg-mode)))

;; Major mode for editing Dune project files
(use-package dune
  :defer t)

;; Merlin provides advanced IDE features
(use-package merlin
  :defer t
  :config
  (add-hook 'tuareg-mode-hook #'merlin-mode)
  ;; we're using flycheck instead
  (setq merlin-error-after-save nil))

(use-package merlin-eldoc
  :defer t
  :hook ((tuareg-mode) . merlin-eldoc-setup))

;; utop REPL configuration
(use-package utop
  :defer t
  :config
  (add-hook 'tuareg-mode-hook #'utop-minor-mode))

Python

Let’s first set the language interpreter.

(use-package python
  :interpreter ("python3" . python-mode)
  :defer t
  :config
  (setq python-shell-interpreter "python3.11")
  (add-hook 'python-mode
			 (lambda () (setq forward-sexp-function nil))))

Note that you also need pyright for this! Installation will depend on your system. It’s available from PyPI. On Ubuntu, I had the most luck installing via snap:

sudo snap install pyright --classic

Then, I want to hide the modeline for inferior Python processes to save screen space. There’s a dedicated package for this.

(use-package hide-mode-line
  :defer t
  :hook (inferior-python-mode . hide-mode-line-mode))

Nix

(use-package nix-mode
  :defer t)

LSP Mode

lsp-mode is an Emacs client for the Language Server Protocol (LSP). I have LSP mode setup for Clojure and Haskell.

As far as I can tell, LSP-mode uses company-mode as its default completion backend, so I’ll set some options for company-mode. Elsewhere, I use corfu, so I should probably consolidate these two eventually.

(use-package company
  :defer t
  :bind (:map company-active-map
              ("TAB" . 'company-complete-selection))
  :config
  (setq company-minimum-prefix-length 2
        company-idle-delay            0))

I disable a few of the default features. If you want to know more about these and how to enable/disable other lsp-mode features, there’s a handy guide on lsp-mode’s website.

(use-package lsp-mode
  :defer t
  :bind (:map lsp-mode-map
              ("M-<return>" . lsp-execute-code-action)
              ("C-M-."      . lsp-find-references)
              ("C-c r"      . lsp-rename))
  :hook ((clojure-mode  . lsp)
         (clojurec-mode . lsp)
         (lsp-mode      . lsp-enable-which-key-integration))
  :config
  (setq lsp-headerline-breadcrumb-enable nil   ;; No breadcrumbs
        lsp-ui-sideline-enable           nil   ;; No sideline
        lsp-ui-doc-enable                nil   ;; No childframes with info
        lsp-lens-enable                  nil   ;; No lenses

        ;; Disable all mode line features, since I use a custom mode line
        lsp-modeline-code-actions-enable nil
        lsp-modeline-diagnostics-enable  nil))

(use-package lsp-haskell
  :after lsp-mode
  :hook (haskell-mode  . lsp))

Activating Custom Keybindings

Extra Keybindings

Most of my custom keybindings are bound directly in the section with the relevant package, but here are a few extra ones.

Switch to the other window C-x oM-o.

(define-key custom-bindings-map (kbd "M-o") 'other-window)

Activating the Keymap

Throughout the configuration, I’ve added bindings to my custom-bindings-map. The last thing we need to to before we can call it a day, is to define a minor mode for it and activate that mode. The below code does just that.

(define-minor-mode custom-bindings-mode
  "A mode that activates custom keybindings."
  :init-value t
  :keymap custom-bindings-map)

TODOs

  • [ ] Find prose font that scales well with TODO boxes and verbatim code
  • [ ] Figure out nice way to search PDFs via pdf-tools (nicer than ISearch, preferrably something consult-related)
  • [ ] Check out origami
  • [ ] Check out embark
  • [ ] Check out harpoon
  • [ ] Check out bufler
  • [ ] Check out fold-this
  • [ ] Configure Magit Forge

About

Sophie's Emacs configuration

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published