Emacs Tips
Installing
See BuildingEmacs
Optionally Requiring Modules
Modules can be optionally required in your .emacs file
by adding a third paramter of true. e.g.
(require 'json-mode nil t)
http://www.emacswiki.org/emacs/RequiredFeature
– Frank Dean - 5 Jan 2016
Emacsclient on macOS with MacPorts
$ sudo ln -s /Applications/MacPorts/EmacsMac.app/Contents/MacOS/bin/emacsclient /usr/local/bin
– Frank Dean - 21 Jul 2021
See https://emacsformacosx.com/tips
Line Wrap
M-x visual-line-mode
Seems to be equivalent to:
(setq word-wrap t) (setq visual-line-indicators (quote (nil nil))
Toggle long lines mode:
M-x toggle-truncate-lines
See also:
- http://www.emacswiki.org/emacs/LineWrap
- http://www.gnu.org/software/emacs/manual/html_node/emacs/Split-Window.html
Controlling Window Splitting
(setq split-height-threshold nil) (setq split-width-threshold 0)
e.g. Disable vertical splitting by (setq split-width-threshold 999)
Character Encoding
To change the character encoding for the current buffer, enter the following M-x command:
set-buffer-file-coding-system
Tab completion works for this command’s options, so e.g. type ‘utf-8’ then hitting tab shows all the file encoding options beginning with ‘utf-8’.
Indenting
To view tabs and spaces, turn on whitespace-mode
M-x whitespace-mode. Repeat the command to toggle it off
again.
JavaScript Mode Indent
Using the Js2Mode mode:
(setq js-indent-level 2)
Numbering and Renumbering Lists
See https://stackoverflow.com/questions/2607925/renumber-numbered-lists-in-emacs-muse
Using Regular Expressions
This will replace existing numbers at the start of each line:
M-x replace-regexp
^[0-9]+\.
\,(1+ \#).
Using Emacs Keybaord Macro Counter
Create the macro:
M-x kmacro-start-macro
M-x move-beginning-of-line
Optionally include any keys to delete the existing number,
e.g. M-x zap-to-char, type the space character and if
appropriate include M-x delete-horizontal-space to remove
additional whitespace.
Insert the current counter:
M-x kmacro-insert-counter
Type any characters you want after the number, e.g. a full-stop (period) and spaces:
M-x next-line
M-x move-beginning-of-line
M-x kmacro-end-macro
Optionally, reset the counter to one (if running macro a second time):
M-x kmacro-set-counter 1
Select the list by placing the cursor at the beginning of the list, then moving the cursor to select the lines:
M-x set-mark-command
Apply the macro to each line in the selected region:
M-x apply-macro-to-region-lines
See Keyboard Macro Counter (GNU Emacs Manual)
Specifying File Variables
Example property line for a text file:
;;; -*- mode: text; indent-tabs-mode: nil; fill-column: 78; -*-
Example property line for Markdown file:
<!-- -*- mode: markdown; indent-tabs-mode: t; fill-column: 78; -*- -->
You can use add-file-local-variable-prop-line to
interactively add variable values to the property line. The line is
created if it does not already exist.
Spelling
Change Default Dictionary
Emacs uses the ispell package. On a Debian system:
# apt-get install ispell iamerican wamerican ibritish wbritish
# dpkg-reconfigure dictionaries-common
Within a session, M-x ispell-change-dictionary - Press SPC to see a list of installed dictionaries
Using Hunspell
Install Hunspell and your required dictionaries.
On a Debian system:
$ sudo apt-get install hunspell hunspell-en-gb hunspell-en-us
Use customize-variable to set
ispell-program-name to hunspell.
Alternatively, add (setq ispell-program-name "hunspell")
to your ~/.emacs file, or a more intelligent lisp
expression that only sets the variable if the hunspell
executable is found on the system path:
;; Find hunspell
(let ((h (executable-find "hunspell")))
(when h (setq-default ispell-program-name h)))
On some operating systems (e.g. macOS), you may also need to set the
DICTIONARY environment variable in your .emacs
file, e.g. (setenv "DICTIONARY" "en_GB"), e.g:
(when (eq system-type 'darwin) ;; mac specific settings
(setenv "DICTIONARY" "en_GB"))
Note: Hunspell is broken in version 1.7.0 that ships with Debian 10.6 (Buster).
A workaround on Debian 10.6 (Buster) is to patch Emacs
ispell.el as follows:
$ sudo mkdir -p /usr/local/share/emacs/26.1/site-lisp
$ sudo chown -R $USER.$USER /usr/local/share/emacs/26.1
$ cd /usr/local/share/emacs/26.1/site-lisp/
$ gunzip /usr/share/emacs/26.1/lisp/textmodes/ispell.el.gz -c>ispell.el
$ sed -i~ -e 's/"-D")/"-D" null-device)/' ispell.el
$ emacs -batch -f batch-byte-compile ispell.el
See:
- https://github.com/hunspell/hunspell/issues/608
- https://github.com/emacs-mirror/emacs/commit/2925ce5a7ec1424cfaea9f2f86bd3cab27832584
- https://stackoverflow.com/questions/56429761/on-macos-hunspell-cant-find-existing-aff-and-dic-files-in-library-spelling
Inserting Control Characters
To insert a control character such as ^L (Form Feed), type C-q then the actual character (using the CTRL key).
Accented Characters and Unicode
Type C-x 8 followed by the appropriate punctuation mark
and letter to be accented. E.g.
Enter C-x 8 ' e to produce é
Enter C-x 8 RET NUMBER SIGN to produce #
For help, type C-x 8 C-h
Use C-u C-x =- shows information for the character
currently under the cursor, including input options.
Other C-x 8 prefixed results:
Key sequence Produces Unicode Name
------------ -------- ------------
~ n ñ LATIN SMALL LETTER N WITH TILDE
` e è LATIN SMALL LETTER E WITH GRAVE
^ o ô LATIN SMALL LETTER O WITH CIRCUMFLEX
" o ö LATIN SMALL LETTER O WITH DIAERESIS
' o ç LATIN SMALL LETTER C WITH CEDILLA
! ¡ INVERTED EXCLAMATION MARK
? ¿ INVERTED QUESTION MARK
L £ POUND SIGN
RET 23 # NUMBER SIGN
RET 5c \ REVERSE SOLIDUS
7c | VERTICAL LINE
RET 20ac € EURO SIGN
o ° DEGREE SIGN
C © COPYRIGHT SIGN
$ ® REGISTERED SIGN
3 / 4 ¾ VULGAR FRACTION THREE QUARTERS
1 / 2 ½ VULGAR FRACTION ONE HALF
1 / 4 ¼ VULGAR FRACTION ONE QUARTER
< « LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
> » RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
{ “ LEFT DOUBLE QUOTATION MARK
} ” RIGHT DOUBLE QUOTATION MARK
[ ‘ LEFT SINGLE QUOTATION MARK
] ’ RIGHT SINGLE QUOTATION MARK
_ h ‐ HYPHEN
_ H ‑ NON-BREAKING HYPHEN
_ q ― HORIZONTAL BAR
_ f ‒ FIGURE DASH
_ n – EN DASH
_ m — EM DASH
x × MULTIPLICATION SIGN
/ / ÷ DIVISION SIGN
/ = ≠ NOT EQUAL TO
a < ← LEFTWARDS ARROW
a > → RIGHTWARDS ARROW
a = ↔ LEFT RIGHT ARROW
RET 2191 ↑ UPWARDS ARROW
RET 2193 ↓ DOWNWARDS ARROW
RET 2195 ↕ UP DOWN ARROW
RET 1f600 😀 GRINNING FACE
See also:
– Frank Dean - 13 Aug 2020
Insert current date and time
One way is to simply run a shell command:
C-u M-! date +"%a,%e %b %Y %T %Z"
See https://www.emacswiki.org/emacs/InsertingTodaysDate for more information and options.
Emacs Server
See:
- Using Emacs as a Server in the Emacs Manual
- Replacing tmux and GNU screen with Emacs - Mastering Emacs
Daemon Mode
Set systemd to always start Emacs in daemon mode when you login:
$ systemctl --user enable emacs
Alternatively, start Emacs in daemon mode with:
$ emacs --daemon
Create a new frame with:
$ emacsclient -c
or use the following to also start the Emacs server in daemon mode or connect to an already running Emacs server:
$ emacsclient -c -a=""
Use M-x kill-emacs to kill the daemon from within Emacs
or execute emacsclient -e "(kill-emacs)" from the command
line.
Dired Omit Mode
Hides uninteresting files, such as hidden files.
See https://www.emacswiki.org/emacs/DiredOmitMode
Once enabled, dired-omit-mode toggles hiding, bound to
C-x, M-o.
Emacs Manual (Debian)
The Debian distribution doesn’t include the manual in the main
distribution section. The emacs-common-non-dfsg package
which includes the manual, can be installed from the ‘non-free
non-free-firmware’ section. You may need to add that section to the
entries in /etc/apt/sources.list.
See http://www.debian.org/vote/2006/vote_001 for an explanation of why the Emacs manual is not considered free.
– Frank Dean - 15 Aug 2020
Useful Emacs Add-Ons
- artist-mode
- org-mode
- org-brain
- Nullsoft Scriptable Installer System (Nsi mode)
- JavaScript mode
- Js2Mode
- magit—EmacsWiki: Magit
- TRAMP
Debian Packages
- emacs-goodies-el which includes Markdown-mode
- python-mode
- magit
- php-elisp
Magit
See “How to enter ssh passphrase when pushing remote branches” re using Magit with SSH.
Change the maximum summary length of the git commit message:
M-x customize-variable git-commit-summary-max-length
Web Browser
The web browser settings can be modified by customizing the
browse-url-browser-function variable. It can be found under
Options->Customize Emacs->Browse Customization Groups
then under Emacs->Hypermedia->Browse URL group.
Alternatively, enter the command:
customize-group browse-url
or
customize-variable browse-url-browser-function
Setting browse-url-browser-function to
browse-url-default-browser uses the system default
browser.
Using Emacs within Firefox
Install the MozEX Firefox extension.
There is also a fork of Mozex and can also be donwloaded from mac.softpedia.com
– Frank Dean - 28 Jan 2012
A recent add-on for Firefox (and other browsers) is It’s All Text!.
– Frank Dean - 21 Jan 2016
Using Emacs with Windows
Using Emacs with X
Window size and position
Set the geometry from the command line:
$ emacs -g 80x40
$ emacs -g 80x40+0+0
Add it to your ~/.XResources file (name may differ by distribution).
$ cat <<EOF >> ~/.XResources
emacs23*Geometry: 80x40-0+0
EOF
$ xrdb -merge ~/.Xresources
See also Xresources or Xdefaults
Collaborative Editing
- See Collaborative Editing for various options.
One way:
M-x make-frame-on-display <RET> display <RET>
See GNU Emacs Manual - Multiple-Displays
– Frank Dean - 13 Mar 2010
Keyboard Macros
For full information on using keyboard macros, refer to the Emacs manual. There is a whole section devoted to the subject and titled ‘Keyboard Macros’.
Start recording a new keyboard macro with <F3>.
End recording with <F4>. Thereafter
<F4> will execute the most recent keyboard macro.
Execute and append to the end of the last keyboard macro with
C-u <F3>. Use C-u C-u <F3> to
append without executing the last keyboard macro.
Select a range of lines, then use C-x C-k r to execute
the keyboard macro for each line.
Rotate to the next macro in the keyboard macro ring with
C-x C-k C-n, optionally followed by more presses of
C-n to continue rotating to the next in the ring. Rotate to
the previous macro with C-x C-k C-p optionally followed by
more presses of C-p to continue rotating to the previous in
the ring.
Name a macro with C-x C-k n. You can then run the macro
as a valid lisp command, e.g. M-x MACRO_NAME.
Bind the most recently defined keyboard macro to a key sequence with
C-x C-k b. This binding is only valid for the current
session. It is recommended to bind to the reserved key sequences of
C-x C-k 0 through to C-x C-k 9 or
C-x C-k A through to C-x C-k Z. You can use a
shortcut to bind to one of these keys, e.g. C-x C-k b 0
will bind the macro to C-x C-k 0.
To save a keyboard macro for another session, open a file and run the
command
M-x insert-kbd-macro <RET> MACRONAME </RET>. If
you use C-u to prefix the command, the generated lisp code
will include the keybinding associated with the keyboard macro.
Edit the last defined keyboard macro with
C-x C-k C-e.
Edit a named keyboard macro with C-x C-k e followed by
M-x MACRO_NAME. Use C-h m for help on editing
the macro. The top of the macro editor shows the key sequences to save
or cancel the edit.
See also: Adding a previously defined macro to the macro ring in Emacs.
– Frank Dean - 14 Aug 2020
Rmail
Since Emacs 23, Rmail uses the standard Unix inbox (mbox) format internally. Rmail prior to that can be exported to inbox format with M-x unrmail.
Note that movemail needs to be built with TLS support
for to use the IMAPS protocol. On MacPorts, install with
sudo port install mailutils +gnutls.
When using movemail to fetch mail from an IMAP server requiring a
username containing the @ character, replace the
@ character with %40.
See https://debbugs.gnu.org/cgi/bugreport.cgi?bug=16946
– Frank Dean - 23 Oct 2020
See also:
- Reading IMAP email in Emacs
- isync: free IMAP and MailDir mailbox synchronizer
- How do I save a copy of outgoing mail?
Handling Attachments
Rmail Mime is now part of Emacs (Emacs 23?). To view the Mime parts, press ‘v’ when viewing a message. Attachments will be listed and can saved by pressing RET with point on the attachment.
– Frank Dean - 6 Nov 2011
Other Emacs Flavours
Info Mode
- http://www.emacswiki.org/emacs/InfoPath
Adding Items to Emacs Info Directory
Modify the ./emacs/info/dir file
See 20.12.2 Listing a New Info File
– Frank Dean - 11 Feb 2025
Viewing an Info file in Info-mode
Use dired to view the directory containing the file in
Emacs. Select the file and press I.
– Frank Dean - 18 Sep 2022
YAML Mode
https://www.emacswiki.org/emacs/YamlMode
– Frank Dean - 09 Mar 2020
Emacs Package Repository
See https://www.emacswiki.org/emacs/MELPA for more information.
List MELPA packages
M-x package-list-packages
Press ‘i’ to mark a package for installatin, ‘U’ to mark upgradeable packages, then ‘x’ to execute the installs and deletions. See MELPA Getting Started.
Terminal Colours
When running emacs in a screen session,
$TERM is set to screen.xterm-256color. A
simple answer is to run emacs with:
$ TERM=xterm-256color emacs
Alternatively, you may be having issues with whether Emacs is using 8 or 256 colours. To see how many colours Emacs is using, use the following command:
M-x list-colors-display
If it lists only 8 colours, firstly check the value of the
TERM environment variable:
$ echo $TERM
E.g. if TERM is set to
screen.xterm-256color because you are running the terminal
in a screen session, you can add the following to your
~/.emacs startup file:
;; alias for screen terminal
(add-to-list 'term-file-aliases
'("screen.xterm-256color" . "xterm-256color"))
By default, Emacs determines whether your terminal is using light or dark foreground colours. For help on setting the frame background mode:
M-x describe-variable
frame-background-mode
To customize the variable:
M-x customize-variable
frame-background-mode
- https://stackoverflow.com/questions/7617458/terminal-emacs-colors-only-work-with-term-xterm-256color
If a particular range of text is difficult to read, you can change the face by moving the cursor to the relevant text, selecting M-x customize-face, which should default to the face setting set for the displayed character. You can then modify the foreground and background colours to suit. However, it does not necessarily identify all the faces that may apply to the current text.
Additionally, the font face may be changed by font lock mode.
M-x font-lock-mode toggles the mode on and off.
M-x list-faces-display lists all the currently defined
faces, which can then be customised. Also,
M-x customize-group and enter ‘faces’ as the group name
will list sub-groups, which may be a quicker way to identify the desired
face.
See also the ‘Display’, ‘Colors’ and ‘Font Lock’ sections of the Emacs manual.
A neater and easier solution is to use ‘Custom Themes’ (Visit the
Emacs manual with C-h r m and type ‘Custom Themes’ to
navigate to that node. There are some pre-defined ones distributed with
Emacs which can be readily activated and then modified as desired to
your personal taste. This has the advantage of making it very easy to
quickly switch to a different pre-defined theme when you have a
different environment, e.g. remote SSH terminal vs. GUI on the same
machine.
It’s also fairly straight-forward to create your own themes. See the
‘Creating Custom Themes’ info menu item. It’s also a good idea to
separate out all your customisations to a separate file to make them a
little easier to manage. See custom-file in the menu item
‘Saving Customizations’. Where the customize-create-theme
editor won’t let you add non-standard faces provided by packages, you
can use customize-face to save them to your
custom-file, then move the definitions from the
custom-file to the theme file in
~/.emacs.d/.
– Frank Dean - 24 Oct 2020
Shell
On macOS the Emacs M-x shell command opens using the
user’s default shell. This can be changed on macOS in
System Settings... > Users & Groups. Ctrl-click the
user name and choose Advanced Options... and select the
preferred shell.
See:
You can also choose the shell using Emacs configuration. From the
shell function help (C-h f shell RET):
If BUFFER exists but shell process is not running, make new shell.
If BUFFER exists and shell process is running, just switch to BUFFER.
Program used comes from variable ‘explicit-shell-file-name’,
or (if that is nil) from the ESHELL environment variable,
or (if that is nil) from ‘shell-file-name’.
Non-interactively, it can also be specified via the FILE-NAME arg.
See https://stackoverflow.com/questions/37409085/how-to-define-a-default-shell-for-emacs
– Frank Dean - 02 Mar 2024
Path
Emacs sets the variable exec-path on startup, but when
executing the shell-command it uses the value of
$PATH in the shell.
On a Mac, macOS sets the path differently when executing Emacs through the global UI than from within a shell.
See:
- elisp - exec-path and $PATH - Emacs Stack Exchange
- macos - Setting environment variables on OS X - Stack Overflow
– Frank Dean - 20 Jun 2021
Ctrl-S Not Working
https://superuser.com/questions/251446/problem-with-gnu-screen-when-using-emacs-c-x-c-s-save-buffer
This is screen treating it as XOFF. Disable it in screen with C-a :flow off
Miscellaneous
Some customized options have not been saved; Examine? (y or n)
If you have added a hook in your .emacs or init startup
file to prompt if any customised variables have been modified and are
running on a macOS computer, you may see the above prompt every time you
exit Emacs.
(add-hook 'kill-emacs-query-functions
'custom-prompt-customize-unsaved-options)
The only fix I could come up with, is to modify the source before
building, and remove the when statement from
lisp/term/ns-win.el (starting at line 729 in Emacs 27.2)
with the following patch:
--- lisp/term/ns-win.el~ 2021-01-28 17:52:38.000000000 +0000
+++ lisp/term/ns-win.el 2021-05-04 11:35:00.000000000 +0100
@@ -729,20 +729,6 @@
(defvar mouse-wheel-scroll-amount)
(defvar mouse-wheel-progressive-speed)
-;; FIXME: This doesn't look right. Is there a better way to do this
-;; that keeps customize happy?
-(when (featurep 'cocoa)
- (let ((appkit-version
- (progn (string-match "^appkit-\\([^\s-]*\\)" ns-version-string)
- (string-to-number (match-string 1 ns-version-string)))))
- ;; Appkit 1138 ~= macOS 10.7.
- (when (>= appkit-version 1138)
- (setq mouse-wheel-progressive-speed nil)
- (put 'mouse-wheel-progressive-speed 'customized-value
- (list (custom-quote
- (symbol-value 'mouse-wheel-progressive-speed)))))))
-
-
You will then probably want to customise the variable, setting its
value to nil, and saving it for future sessions to achieve
the same behaviour as the removed code:
M-x customize-variable mouse-wheel-progressive-speed
– Frank Dean - 04 May 2021
Troubleshooting
Installing Magit, Error: Emergency (magit): Magit requires ‘seq’ >= 2.24
Refresh package list
M-x package-refresh-contents
Display package list
M-x list-packages
Filter packages by name ‘seq’
/nseq
Mark package for installation
i
Execute marked changes
x
See https://emacs.stackexchange.com/questions/80871/how-to-provide-updated-seq-package-to-magit
– Frank Dean - 03 May 2024
– Frank Dean - 31 Jan 2009
Related Topics: BuildingEmacs, EmacsCCMode, CreatingDocuments, DocumentFormats, FirefoxTips, InstallingMacPorts, LaTeX, Markdown, PanDoc, VimTips, XmlTips