Emacs Reference Guide: Tips, Tricks, and Troubleshooting
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:
- Navigate to the hunk in the Magit status buffer
- Select the specific lines you want to stage using the region
- Press
sto 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:
- In a Magit status buffer, press
dto enter diff mode - Press
Dto open the diff refresh popup - Set the flags you want:
-wor--ignore-all-spaceto ignore all whitespace-bor--ignore-space-changeto ignore changes in whitespace amount
- Press
gto refresh with these settings
To save these settings for future sessions:
- Press
C-x C-sorwafter 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:
- Make sure
project.elis installed:M-x package-install RET project RET - Load the library manually:
M-x load-library RET project RET - Or restart Emacs to ensure all packages are loaded correctly
Error: “No current JSON-RPC connection”
This error typically occurs when:
- The language server is not running
- The connection between Eglot and the language server was lost
- 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
| Command | Description |
|---|---|
C-x r r | Copy rectangle to register |
C-x r k | Kill (cut) rectangle |
C-x r y | Yank (paste) rectangle |
C-x r o | Open rectangle - insert blank space, pushing text right |
C-x r t | Replace rectangle with text (string on each line) |
C-x r c | Clear rectangle (replace with spaces) |
Example Usage
-
To insert spaces at a specific column position:
- Set mark at the starting position
- Move to the end position
- Press
C-x r oto open the rectangle
-
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):
- Open Dired mode (
C-x d) - Navigate to the file you want to rename
- Press
Rto start the rename operation - Press
M-nto pull the existing filename into the minibuffer for editing- This uses the command
ivy-next-history-itemif you’re using Ivy
- This uses the command
- Edit the filename as needed
- Press
Enterto 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
- Open Dired mode (
C-x d) - Use
% m(dired-mark-files-regexp) to mark files by regex pattern - Enter a regex pattern to match filenames
- Example:
\.html$to match all HTML files
- Example:
Step 2: Perform Interactive Find-Replace
- With files marked in Dired, press
Q(dired-do-query-replace-regexp) - Enter the search pattern (regex supported)
- Example:
"queen"
- Example:
- Enter the replacement text
- Example:
"princess"
- Example:
- For each match, press:
yto replacento skip!to replace all remaining matchesqto exit
Step 3: Save Modified Files
After making changes, you can save all modified buffers:
- Use
M-x ibufferto list all open buffers - Press
* uto mark all unsaved buffers - Press
Sto save all marked buffers - Optionally, press
Dto 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
- Add this function to your Emacs configuration
- When you encounter the “Too many open files” error, run:
M-x file-notify-rm-all-watches - 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 listC-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 fontM-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-qisquoted-insert, which allows you to insert control charactersC-jinserts 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:
- First clear any existing marks with
U(dired-unmark-all-marks) if needed - 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:
- Reset Emacs privacy permissions:
sudo tccutil reset All org.gnu.Emacs
- 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):
- Install the
hl-columnpackage - 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.
You might also like
Designing Configuration for Open-Source Go Libraries
Best practices for balancing configuration, environment variables, and functional options when building open-source Go libraries.
Modern Python Package Structure with pyproject.toml, uv, Scripts, and FastAPI
A concise guide to building a clean, modern Python project using pyproject.toml, uv, scripts, and FastAPI.
Managing Multiple GPG Keys and YubiKey Setup
A practical guide to managing multiple GPG private keys — exporting, importing, backing up, and securely storing them on a YubiKey for signing, encryption, and SSH authentication.