Emacs Init: Organize Init File

By Xah Lee. Date: . Last updated: .

Emacs Init Mess Problem

This page is a guide on organizing your emacs init file.

Many emacs users, have thousands of lines in their emacs init file, accumulated over the years. Large emacs init file makes emacs start slow, and is a problem when you upgrade emacs.

When you find some elisp code on the web, you pile it in your emacs init and you can immediately go back to work on things you need done. That is the beauty of it.

The best way i find in keeping emacs init organized, is just to break them into multiple files.

Split Init File into Multiple Files

in your emacs init file, e.g.

change the file content to make it load several other files, like this:

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

;; HHHH---------------------------------------------------
;; code here that need to precede all others

(when (< emacs-major-version 27) (package-initialize))

(defun xah-get-fullpath (RelativePath)
  "Return the full path of RelativePath, relative to caller's file location.
Created: 2017-07-19
Version: 2021-07-17"
  (concat (file-name-directory (or load-file-name buffer-file-name)) RelativePath))

;; HHHH---------------------------------------------------
;; load the plain emacs settings
;; that does not require any external packages
;; e.g. font, theme, file encoding, default frame size, backup setting, etc

(load (xah-get-fullpath "my_settings"))

;; HHHH---------------------------------------------------
;; load packages. most important ones

(add-to-list 'load-path "~/git/xah-fly-keys/")
(require 'xah-fly-keys)

;; more here

;; HHHH---------------------------------------------------
;; load packages. less important ones

(add-to-list 'load-path "~/git/xah-find/")
(require 'xah-find)

;; more here

;; HHHH---------------------------------------------------
;; load other settings or packages

(load (xah-get-fullpath "my_abbr"))
(load (xah-get-fullpath "my_keybinding"))
(load (xah-get-fullpath "my_font"))
(load (xah-get-fullpath "my_settings_external_packages"))
(load (xah-get-fullpath "my_html"))

;; more here. catch all init
(load (xah-get-fullpath "my_misc"))

When next time you have more code you want to add, just pick a file and add there.

If you don't have time to think about where to add, can just dump it to the misc file. And when you have time, sort out code in that file to others.

The advantage of separate files is that you can selectively add or comment out which one to load. (as opposed to comment out blocks of code in a big file, which is less easy to manage)

Redirect Emacs Init File

sometimes you want your emacs init files to be in some other dir, such as your git repo dir.

you can do this, by replacing the entire init file content to this:

(load "~/git/xah_emacs_init/xah_emacs_init.el")