Emacs Tips

Installing

If installing on macOS, install emacs-app or emacs-mac-app from MacPorts. The latter version is the Yamamoto Mitsuharu version which provides native GUI support for macOS. However, since Emacs 23, native GUI support is now included in the standard GNU distribution (MacPorts emacs-app), but emacs-mac-app has additional enhancements for the Mac.

However, it can be useful to have an independently built version for those occasions when a MacPorts upgrade fails, leaving a broken environment where Emacs may not run. Fortunately there's always vi or vim to fallback on, but if you prefer to use Emacs, you can create a minimal Emacs on macOS without installing many library dependencies, build from source with:

Installing GNU Emacs:

Download the latest Emacs version.

The configure options provide a working Emacs with minimal effort.

$ cd /usr/local/src
$ tar -xf emacs-27.1.tar.xz
$ cd emacs-27.1/
$ ./configure --without-makeinfo --with-gnutls=ifavailable
$ make
$ ./src/emacs

See the excellent documentation in the root of the Emacs source, particularly the INSTALL and README files for more information.

You can also run make install (which installs under ./nextstep without using root/sudo) and then copy ./nextstep/Emacs.app to the /Applications folder and run it from there.

See https://www.emacswiki.org/emacs/EmacsForMacOS for further details.

To configure the Emacs build to include GNU Mailutils;

first, build mailutils with the following arguments:

$ ./configure --disable-cxx --disable-python --disable-build-servers \
--without-readline

Build GnuTLS as described in the 'Building GnuTLS' section below, then configure Emacs with:

$ ./configure --with-gnutls --with-mailutils

Note: To rebuild a package using the same command line options as last passed to the ./configure command, run ./config.status --recheck. See makefile - How do you "echo" the last configure/make build --options within a source directory? - Stack Overflow.

You can also see how Emacs was built in a running Emacs with C-h v system-configuration-options.

See also self-contained portable emacs on stackoverflow

-- Frank Dean - 14 May 2021

Building GnuTLS

Building GnuTLS is a non-trivial task on macOS. There are a number of nested dependencies and one or two traps along the way. You need to read the INSTALL.md distributed with GnuTLS at the very least.

Below are some of the solutions I found to succeed in a build. I cannot vouch for how appropriate or correct these solutions are.

I would recommend examining the Portfiles for each of the MacPort installers, to assist in determining where to download packages from on the Internet and which versions may be appropriate. There may also be some useful patches to consider applying:

https://github.com/macports/macports-ports

The source packages can be built and installed in the following order:

pkg-config-0.29.1
coreutils-8.32
sed-4.8
gettext-0.19.8.1
gmp-6.2.0
libtool-2.4.6
libunistring-0.9.10 ???
libffi-3.3
glib-2.59.0
gc-8.0.4
libatomic_ops-7.6.10
openssl-1.1.1k
nettle-3.7.2
libtasn1-4.16.0
p11-kit-0.23.22
expat-2.3.0
unbound-1.13.1
guile-2.2.7 ???
libidn2-2.3.0
libiconv-1.16
gnutls-3.6.15
mailutils-3.6
emacs-27.2

Notes for packages which need to be built with specific ./configure options are listed in the following sub-sections.

pkgconfig

It's good to build pkgconfig early on as other artifact builds use it. pkgconfig has a circular dependency with glib. You get around it by building with its own internal version of glib.

./configure --with-internal-glib

coreutils

Optionally, so as to distinguish GNU coreutils from the BSD commands of the same name, prefix all the commands with g:

./configure --program-prefix=g

sed

Optionally, so as to distinguish the GNU sed command from the BSD sed command, prefix the command with g:

./configure --program-prefix=g

glib2

./configure --with-pcre=native

openssl

./config

nettle

nettle needs GMP to be built, otherwise it doesn't install hogweed, which gnutls requires, otherwise gnutls configure fails with Libnettle 3.4 was not found.

./configure --disable-openssl --enable-shared

p11-kit

./configure --without-trust-paths

unbound

After building and installing:

$ sudo /usr/local/sbin/unbound-anchor -a /usr/local/etc/unbound/root.key

gnutls

./configure --prefix=/usr/local --host=x86_64-apple-darwin11 \
--build=x86_64-apple-darwin11 \
--disable-guile --with-included-unistring \
--with-unbound-root-key-file="/usr/local/etc/unbound/root.key"

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:

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)

Specifying File Variables

See 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:

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.

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. It can be installed from the non-free section package named emacs-common-non-dfsg.

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

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.

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

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:

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

  • http://www.gnu.org/software/texinfo/manual/info/info.html#Add

-- Frank Dean - 09 Nov 2013

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

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:

-- 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


-- Frank Dean - 31 Jan 2009

Related Topics: CreatingDocuments, DocumentFormats, EmacsCCMode, FirefoxTips, InstallingMacPorts, LaTeX, Markdown, PanDoc, VimTips, XmlTips