Emacs Reference Guide: Tips, Tricks, and Troubleshooting

A collection of practical Emacs tips, keyboard shortcuts, configuration snippets, and solutions to common problems. This guide covers Magit, LSP integration, file management with Dired, and more.

Magit Tips and Tricks

Magit is a powerful Git interface for Emacs. Here are some useful techniques for working with it effectively.

Splitting Hunks for Partial Staging

To stage only part of a changed hunk:

  1. Navigate to the hunk in the Magit status buffer
  2. Select the specific lines you want to stage using the region
  3. Press s to stage only those selected lines

This creates two separate hunks - one staged and one unstaged. The same technique works for:

  • Stashing partial changes
  • Discarding partial changes with k

Ignoring Whitespace in Diffs

To configure Magit to ignore whitespace changes in diffs:

  1. In a Magit status buffer, press d to enter diff mode
  2. Press D to open the diff refresh popup
  3. Set the flags you want:
    • -w or --ignore-all-space to ignore all whitespace
    • -b or --ignore-space-change to ignore changes in whitespace amount
  4. Press g to refresh with these settings

To save these settings for future sessions:

  • Press C-x C-s or w after setting the flags

Eglot - Emacs LSP Client

Eglot is a lightweight LSP client for Emacs. Here are solutions to common issues:

Troubleshooting Eglot Issues

Error: “Symbol’s function definition is void: project-root”

This error occurs when the required project.el package is not properly loaded. To fix:

  1. Make sure project.el is installed: M-x package-install RET project RET
  2. Load the library manually: M-x load-library RET project RET
  3. Or restart Emacs to ensure all packages are loaded correctly

Error: “No current JSON-RPC connection”

This error typically occurs when:

  1. The language server is not running
  2. The connection between Eglot and the language server was lost
  3. The language server crashed

To troubleshoot:

  • Check if the language server is installed correctly
  • Try restarting the Eglot connection with M-x eglot-reconnect
  • Examine the *eglot-events* buffer for more detailed error information

Ripgrep (rg) Integration

Ripgrep is a fast search tool that can be integrated with Emacs.

Troubleshooting Path Issues

If you’re using exec-path-from-shell and experiencing issues with the rg package:

;; Make sure exec-path-from-shell is loaded BEFORE rg
(use-package exec-path-from-shell
  :ensure t
  :config
  (exec-path-from-shell-initialize))

(use-package rg
  :ensure t)

The key is to ensure exec-path-from-shell is initialized before loading packages that depend on external executables.

YASnippet Tips

YASnippet is a template system for Emacs.

Viewing Available Snippets

To see all available snippets for the current mode:

M-x yas-describe-tables

This command shows a buffer with all snippet templates organized by mode.

Rectangle Editing

Emacs has powerful rectangle editing capabilities for working with columnar text.

Common Rectangle Commands

CommandDescription
C-x r rCopy rectangle to register
C-x r kKill (cut) rectangle
C-x r yYank (paste) rectangle
C-x r oOpen rectangle - insert blank space, pushing text right
C-x r tReplace rectangle with text (string on each line)
C-x r cClear rectangle (replace with spaces)

Example Usage

  1. To insert spaces at a specific column position:

    • Set mark at the starting position
    • Move to the end position
    • Press C-x r o to open the rectangle
  2. To replace a column of text:

    • Select the rectangular region
    • Press C-x r t
    • Enter the replacement text
    • Each line in the rectangle will be replaced with this text

Dired File Management

Dired is Emacs’ powerful directory editor mode.

Efficient File Renaming in Dired

To rename a file to a similar name (preserving most of the original filename):

  1. Open Dired mode (C-x d)
  2. Navigate to the file you want to rename
  3. Press R to start the rename operation
  4. Press M-n to pull the existing filename into the minibuffer for editing
    • This uses the command ivy-next-history-item if you’re using Ivy
  5. Edit the filename as needed
  6. Press Enter to complete the rename

Tip: Use M-n and M-p to cycle through different filenames when renaming multiple files

HTML Formatting

To format HTML code in Emacs:

M-x sgml-pretty-print

This command indents HTML/XML code properly, making it more readable.

Multi-file Search and Replace

Emacs provides powerful tools for searching and replacing text across multiple files. Here’s a comprehensive approach:

Step 1: Mark Files by Pattern

  1. Open Dired mode (C-x d)
  2. Use % m (dired-mark-files-regexp) to mark files by regex pattern
  3. Enter a regex pattern to match filenames
    • Example: \.html$ to match all HTML files

Step 2: Perform Interactive Find-Replace

  1. With files marked in Dired, press Q (dired-do-query-replace-regexp)
  2. Enter the search pattern (regex supported)
    • Example: "queen"
  3. Enter the replacement text
    • Example: "princess"
  4. For each match, press:
    • y to replace
    • n to skip
    • ! to replace all remaining matches
    • q to exit

Step 3: Save Modified Files

After making changes, you can save all modified buffers:

  1. Use M-x ibuffer to list all open buffers
  2. Press * u to mark all unsaved buffers
  3. Press S to save all marked buffers
  4. Optionally, press D to close them

Alternatively, use C-x s (save-some-buffers) to be prompted for each unsaved buffer.

Regex Tip

To match a literal dot character (.), use [.] in your regex instead of just . (which matches any character).

Fixing “Too Many Open Files” Error

Emacs can sometimes hit the system limit for open file handles, especially when using file watchers. This commonly happens with packages that monitor file changes (like LSP servers, project management tools, etc.).

Solution: Remove File Watches

The following function removes all file notification watches from Emacs:

(defun file-notify-rm-all-watches ()
  "Remove all existing file notification watches from Emacs."
  (interactive)
  (maphash
   (lambda (key _value)
     (file-notify-rm-watch key))
   file-notify-descriptors))

How to Use

  1. Add this function to your Emacs configuration
  2. When you encounter the “Too many open files” error, run:
    M-x file-notify-rm-all-watches
  3. This will clear all file watches and resolve the issue immediately

Note: This is a workaround that clears all file watches. If you need persistent file watching, consider increasing your system’s file descriptor limit instead.

Buffer Navigation

Cycling Through Buffers

To navigate between recently visited buffers:

  • C-x left-arrow (previous-buffer) - Go to the previous buffer in the list
  • C-x right-arrow (next-buffer) - Go to the next buffer in the list

To see what a key combination does, use:

M-x describe-key C-x left

Font Information

To get information about fonts in Emacs:

  • M-x describe-font - Shows detailed information about the current font
  • M-x describe-char - Shows information about the character at point, including its font

These commands are useful for debugging font rendering issues or identifying which fonts are being used for different characters.

Text Manipulation

Replacing Newlines

To replace newlines with another character (or vice versa):

M-x replace-string RET ; RET C-q C-j

This replaces semicolons (;) with newlines. The key sequence works as follows:

  • C-q is quoted-insert, which allows you to insert control characters
  • C-j inserts a newline character

You can also replace in the other direction (newlines to another character):

M-x replace-string RET C-q C-j RET ; RET

Dired Selection Techniques

Selecting All Files

To select all files in a Dired buffer:

  1. First clear any existing marks with U (dired-unmark-all-marks) if needed
  2. Then press t (dired-toggle-marks) to mark all files

This is useful when you want to perform operations on all files in a directory.

macOS Troubleshooting

Fixing Permission Issues

If you encounter “Reading directory: Operation not permitted” errors when accessing certain folders (like Desktop) on macOS:

  1. Reset Emacs privacy permissions:
sudo tccutil reset All org.gnu.Emacs
  1. Grant full disk access to Emacs:
    • Open System Preferences/Settings
    • Go to Security & Privacy/Privacy
    • Select Full Disk Access
    • Add Emacs.app to the list of allowed applications

This resolves permission issues caused by macOS security features like Transparency, Consent, and Control (TCC).

Blogging with Org Mode

Using ox-hugo for Hugo Blogs

ox-hugo is an excellent package for maintaining Hugo blogs using Org mode.

For a detailed guide on setting up ox-hugo, see Using Org Mode with Hugo.

Key benefits:

  • Write blog posts in Org mode
  • Export to Hugo-compatible Markdown
  • Maintain metadata in Org properties
  • Support for Hugo shortcodes

macOS Emacs Setup

Essential External Tools

Install these tools to enhance your Emacs experience on macOS:

# Install ripgrep for fast searching
brew install ripgrep

# Install aspell for spell checking (used by flyspell-mode)
brew install aspell

LSP Mode Configuration

LSP Mode provides IDE-like features in Emacs through the Language Server Protocol.

Common LSP Server Installation Issues

If you see this error:

LSP :: The following servers support current file but do not have automatic installation: semgrep-ls golangci-lint gopls

You need to manually install the language servers. Visit the LSP Mode Languages page for detailed instructions.

Installing Common Language Servers

Semgrep

For static analysis with semgrep:

brew install semgrep

Go Language Servers

For Go development:

# Install gopls (Go language server)
go install golang.org/x/tools/gopls@latest

# Install golangci-lint (linter)
brew install golangci-lint

# Install golangci-lint-langserver
go install github.com/nametake/golangci-lint-langserver@latest

After installation, make sure these tools are in your PATH, and restart Emacs or the LSP workspace.

Visual Enhancements

Highlighting the Current Column

To highlight the current column (similar to how hl-line-mode highlights the current line):

  1. Install the hl-column package
  2. Enable it with M-x hl-column-mode

This is particularly useful when working with tabular data or aligning code.

Troubleshooting Emacs 30

Theme Compatibility Issues

If you’re using Nord theme with Emacs 30 and experiencing button rendering issues:

;; Fix for nord-theme in Emacs 30
;; See: https://github.com/cariandrum22/emacs/commit/e6977cf36f0cea5b290497add76f1db03b522a77
(with-eval-after-load 'nord-theme
  (custom-theme-set-faces
   'nord
   '(button ((t (:box (:line-width 1 :style pressed-button) :foreground nil :inherit (nord-blue)))))))

The issue is that sunken-button was removed in Emacs 30, so you need to replace it with pressed-button in .emacs.d/elpa/nord-theme.el.

Server Management

Restarting the Emacs Server

If you’re experiencing issues with emacsclient connections or Magit:

M-x server-start

This restarts the Emacs server process, which often resolves connection issues with external tools.