User:Ulm/Emacs guide

From Gentoo Wiki
Jump to:navigation Jump to:search
This article is a work in progress; treat its contents with caution - ulm (talk | contribs).

This guide is meant to be a nice introduction to GNU Emacs in Gentoo.

Introduction

What is GNU Emacs?

In short Emacs is an extensible, customizable, self-documenting real-time display editor, which says everything and nothing. At its core it is an interpreter for Emacs Lisp, an expression-oriented language. All functions are written in this language and a user can dive into that or not, just as he wishes. If he does he will find a well-documented structure of functions he can customise and extend, which makes Emacs a flexible tool for all editing tasks. But it is not limited to that: Reading news or mail, chatting over IRC, organising tasks and projects or using it as development environment with support for external debuggers and compilers in many different languages.

The original version of Emacs is nowadays called GNU Emacs as it is maintained by the GNU project, unlike some forks that appeared in the long history and some are still existent today. The most prominent is XEmacs, which is not the X version but a totally independent project. GNU Emacs has support for X and text mode itself to clarify a popular misunderstanding.

By the way, the name Emacs is derived from Editor Macros despite other rumours and interpretations. And we should an initial warning: Emacs is really old in computer terms, but still a powerful tool, and there is nothing like it out there. So prepare yourself for a completely usability experience and a lot of functionality, which might seem overwhelming at first. Try to use the subset you need and extend your knowledge as you see fit.

Scope of this document

This guide describes the basic concepts of GNU Emacs itself and the specialties for a Gentoo installation to manage it and the possibly installed extensions packets. A complete documentation is not possible and better done by the official manual (which is not complete either) and various third-party documents, see further reading suggestions at the bottom. We are sure you can use every possible task and Emacs as a search term in your favourite search engine to find a solution in this powerful beast.

Most intrinsic properties described here are also valid for XEmacs (to be found as app-editors/xemacs in the repository), but in-Gentoo management differs in some details, so do not wonder if the described behaviour does not occur with XEmacs.

Installation and setup

Pre-installation considerations

So you decided to install GNU Emacs on your system. There are several choices you can make, depending on your needs: All versions of app-editors/emacs can be installed in parallel, switching is achieved by the user through the emacs eselect module. All are officially supported and (except version 18) are able to handle external extension packages or optional Emacs support activated with USE=emacs for some packages. Please note that some packages need one of the more recent Emacs versions, but those cases are rare and you will note on emerge (the process will stop very early with a meaningful message).

As a new major version of GNU Emacs brings a lot of changes, an upgrade should not be done automatically by the package manager just because there is a new version. Emacs 30 for example can be emerged but the active version stays 29 until the user chooses otherwise.

Apart from that it comes in handy to have a small and lean Emacs (version 18 for example) for quick editing sessions over a remote connection at hand. There are several editors which support Emacs key bindings (so called micro-Emacsen) but don't have the full power, a list is provided by the Emacs team.

Some readers might have already noticed the *.9999 ebuilds that are live versions of GNU Emacs. This means you get the tip of the current development, freshly served to your computer. We spare you the gory details as you should use it only if you are curious and willing to deal with the typical breakage that appears during development.

Installing

First, you must install Emacs.

Todo:

  • Be more verbose


CODE Installation command, just have a peek
# emerge --pretend --verbose app-editors/emacs

USE flags for app-editors/emacs The extensible, customizable, self-documenting real-time display editor

+X Add support for X11
+gmp Use the GNU multiple precision arithmetic library (dev-libs/gmp) instead of the bundled mini-gmp subset
+inotify Enable inotify filesystem monitoring support
+threads Add elisp threading support
+xpm Add support for XPM graphics format
Xaw3d Add support for the 3d athena widget set
acl Add support for Access Control Lists
alsa Add support for media-libs/alsa-lib (Advanced Linux Sound Architecture)
aqua Include support for the Mac OS X Aqua (Carbon/Cocoa) GUI
athena Enable the MIT Athena widget set (x11-libs/libXaw)
cairo Enable support for the cairo graphics library
dbus Enable dbus support for anything that needs it (gpsd, gnomemeeting, etc)
dynamic-loading Enable loading of dynamic libraries (modules) at runtime
games Support shared score files for games
gfile Use gfile (dev-libs/glib) for file notification
gif Add GIF image support
gpm Add support for sys-libs/gpm (Console-based mouse driver)
gsettings Use gsettings (dev-libs/glib) to read the system font name
gtk Add support for x11-libs/gtk+ (The GIMP Toolkit)
gui Enable support for a graphical user interface
gzip-el Compress bundled Emacs Lisp source
harfbuzz Use media-libs/harfbuzz as text shaping engine
imagemagick Use media-gfx/imagemagick for image processing
jit Compile with Emacs Lisp native compiler support via libgccjit
jpeg Add JPEG image support
json Compile with native JSON support using dev-libs/jansson
kerberos Add kerberos support
lcms Add lcms support (color management engine)
libxml2 Use dev-libs/libxml2 to parse XML instead of the internal Lisp implementations
livecd !!internal use only!! DO NOT SET THIS FLAG YOURSELF!, used during livecd building
m17n-lib Enable m17n-lib support
mailutils Retrieve e-mail using net-mail/mailutils instead of the internal movemail substitute
motif Add support for the Motif toolkit
png Add support for libpng (PNG images)
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
sound Enable sound support
source Install C source files and make them available for find-function
sqlite Add support for sqlite - embedded sql database
ssl Add support for SSL/TLS connections (Secure Socket Layer / Transport Layer Security)
svg Add support for SVG (Scalable Vector Graphics)
systemd Enable use of systemd-specific libraries and features like socket activation or session tracking
tiff Add support for the TIFF image format
toolkit-scroll-bars Use the selected toolkit's scrollbars in preference to Emacs' own scrollbars
tree-sitter Support the dev-libs/tree-sitter parsing library
valgrind Enable annotations for accuracy. May slow down runtime slightly. Safe to use even if not currently using dev-debug/valgrind
webp Add support for the WebP image format
wide-int Prefer wide Emacs integers (typically 62-bit). This option has an effect only on 32-bit systems, where it increases the maximum buffer size from 0.5 to 2 GiB, at the cost of 10% to 30% Lisp slowdown.
xattr Add support for extended attributes (filesystem-stored metadata)
xft Build with support for XFT font renderer (x11-libs/libXft)
zlib Add support for zlib compression

You could unpack the Emacs sources and run ./configure --help to see the optional support. If you don't use the X or gtk flags, you will rely on the keyboard to use Emacs. Otherwise, emacs -nw is the terminal mode.

eselect

All Emacs versions can be installed alongside each other on the same system without collisions. Calling /usr/bin/emacs redirects (by a symbolic link) to the Emacs version you chose to be started. Switching the default Emacs is done through the emacs eselect module, which is presented in the following example.

CODE eselect
# emerge app-admin/eselect
# eselect emacs list
Available Emacs symlink targets:
[1]   emacs-29 *
[2]   emacs-30
[3]   emacs-31-vcs
# eselect emacs set 2
Switching emacs to emacs-30 ...
Switching ctags to exuberant-ctags ...
Switching etags to etags-emacs-30 ...
# eselect emacs list
Available Emacs symlink targets:
[1]   emacs-29
[2]   emacs-30 *
[3]   emacs-31-vcs
Note
All installed precompiled Emacs support files may be incompatible with the version you switched to. If you experience problems, please use app-admin/emacs-updater (described in the next section).

app-admin/emacs-updater

This tool is intended as a means to handle up- and downgrades of Emacs cleanly. First you need to install it.

CODE Installing app-admin/emacs-updater
# emerge app-admin/emacs-updater

Without any arguments /usr/sbin/emacs-updater will recompile all Emacs support files of additional packages that were not built with the current active Emacs version. That way a up- or downgrade of Emacs is easily possible if the format of the compiled files is differing (which is sometimes the case between different major versions). After switching the active version with the eselect module you can run emacs-updater afterwards and will not experience strange run-time errors.

An unconditional rebuild of all Emacs support files is also possible with

CODE Installing app-admin/emacs-updater
# /usr/sbin/emacs-updater --action=all

Basic editing commands

After installing Emacs itself we will describe some basics in editing which is quite different from anything you might know.

Todo:

  • What's a mode? Describe some concepts


Client/server

Todo:

  • Describe emacs-daemon


Emacs can work as a server for emacsclient. To use this type M-x server-start RET in a running Emacs session. Then it's emacsclient file1 file2 file3 to edit your files or mail.

Built-in tutorial

There is a tutorial for Emacs available.

CODE Start of tutorial
M-x help-with-tutorial RET

That is Meta then x. The Meta key is Escape or possibly Alt. Next you need to type help and use TAB twice to see the completions.

Additional packages

Separate package or USE=emacs?

Installation

Some types of files have modes created for them. If you edit Python or PHP code, this piece of information is for you. This is a convenient way to install elisp files (.el and byte-compiled .elc) thanks to the Emacs team! This is done as root. Note the # prompt.

Todo:

  • Describe canonical site-init loading


CODE Installation of extension packages
# emerge --pretend --verbose app-emacs/python-mode
# emerge --pretend --verbose app-emacs/php-mode
Cscope can work with Emacs very conveniently.
# echo "dev-util/cscope emacs" >> /etc/portage/package.use
That will append the quoted text to the file "/etc/portage/package.use".
# emerge dev-util/cscope

Loading on start-up

Basics

Macros

An introduction to Emacs would not be complete without a section on macros. This is "Editor Macros". In a buffer, type C-x ( to begin. Then type what you want in the macro. You are recording keystrokes. Now type C-x ) to finish the macro. Naming the macro is next with M-x name-last-kbd-macro RET. You could insert-kbd-macro into a .emacs file if you find it very useful. Perhaps you want to use that macro 10 times in a row. This is awkward, but C-u 10 M-x mymacro RET.

Emacs Lisp

You could use the lisp interpreter to make lists or do some simple math. Type these in and then type control-x, control-e with the cursor at the end of them. Watch the minibuffer at the bottom of the screen.

CODE Emacs Lisp code example
(list 'a 'b 'c)
(+ 1 2 3)
(* (* 2 2) (/ 22 7))
(message "%s" "This is an introduction to using Emacs in Gentoo.")

Understanding how to navigate the cursor over lists is quite useful. With the cursor pointed on a [, (, or {, use M-C-f to go to the end. Use M-C-b to go to the beginning of the list. That is Escape, Control-f and Escape, Control-b, respectively.

You could load your elisp.

CODE Load an elisp file
M-x load-file RET

Now, you may want to clean up your code or make replacements in a function. Click and drag or use C-SPACE to set a mark.

CODE Activate visual mark indicator
M-x transient-mark-mode RET

That will toggle the highlighting of selected text. Now, M-% will prompt you to search and replace or query-replace. Also, global-font-lock-mode will toggle the syntax highlighting; indent-region will nicely indent nested code blocks or HTML. A quick comment comes from M-; or Escape ;.

Invoking processes

Emacs can start subprocesses, like a shell or a debugger or even find and grep.

CODE Start some connectors
M-x shell RET
M-x gdb RET
M-x find-grep RET
Note
Emacs can be used on compressed text in the gzip and bzip2 formats by invoking decompressors.

Emacs and Bash equivalents

Bash has some keystrokes in common with Emacs. You can search your shell history with Control-r but not Control-s. If you try Control-s in bash, it will hide your typing. You can type Control-q to see input to bash again. To cancel a search, type Control-g. Just like Emacs, you can kill text several times with Control-k and get it back with Control-y. You can then use Escape y repetitions. You can suspend Emacs with Control-z. Try the jobs command to see what is suspended. Then type fg or fg 1 to get back to Emacs. Delete a whole word with Escape Backspace or Escape d. Undo with Control-/ and transpose two mistyped characters with Control-t.

Complete text

Now is where some completion becomes useful. There is M-/ to complete a string and also some elisp that does much more.

CODE Start-up of hippie-expand
M-x hippie-expand RET

This has try-expand-list, try-expand-line, try-complete-file-name and many other things. It will cycle through trying to match what is immediately on the left of the cursor. It is much nicer to bind this to a key.

CODE Start the global-set-key macro
M-x global-set-key RET

This could be persistent in a .emacs file.

CODE Example for the contents of the .emacs file
$ echo "(global-set-key [f2] 'hippie-expand)" >> ~/.emacs.d/init.el
Note
man man has this tip: (global-set-key [f1] (lambda () (interactive) (manual-entry (current-word))))

Remove comments

One common thing for Gentoo users is to strip comments from configuration files. This is convenient in Emacs with flush-lines.

CODE Start the flush-lines macro
M-x flush-lines RET

^# RET That will match lines beginning with a # which is a comment in most /etc configuration files.}}

Useful functions in GNU Emacs

Dired

Lets start by looking at some files.

CODE Open a file with Emacs
Control-x, control-f, enter

Now you have dired, the directory editor. When you press enter on directories, you traverse the file structure. It is possible to quickly back up the tree with ^, Shift-6. Over the course of editing, you may open many files.

CODE Switch buffers
Control-x, control-b

Now you may wish to do replacements in many files.

CODE Command completion in action
M-x dired <TAB> <TAB>
M-x command-apropos RET
This can show any dired command.

Now you see what is available. Here is one strategy.

CODE Code Sample
M-x find-grep-dired RET
%-m c$ This will mark C sources or filenames ending in c.
M-x dired-do-query-replace-regexp RET

That will split your screen and show the buffers that are open. When you want to split the screen, use Control-x followed by a number.

CODE Code Sample
C-x 0 This makes the current buffer go away.
C-x 1 This makes the current buffer take full screen.
C-x 2 This will initiate the split and you can browse two different parts of a file.
C-x 3 This is useful if you have a wide screen.

Speedbar for debugging and navigation

If you're coding C, and you use gcc -g for debugging symbols, Emacs can split your screen and follow the current line of source code. If you use Emacs with X try speedbar.

CODE Code Sample
M-x speedbar RET

Now watch variables change just like any other development environment. You could also browse directories in speedbar or do other things by right-clicking.

Ediff

Since Gentoo respects your /etc/ configuration files, you may like ediff for file foo and ._cfg0000_foo.

CODE Code Sample
You could run M-x find-dired RET with an argument like this: -name \._cfg*
Control-x, control-f, control-a, control-k, /etc, enter.
M-x ediff RET

Sample .emacs

Todo:

  • Describe the settings and add the canonical loading


CODE Code Sample
$ cat ~/.emacs.d/init.el
(prefer-coding-system 'utf-8)
(setq transient-mark-mode t)
(show-paren-mode t)
(setq column-number-mode t)
(global-set-key [f5] (lambda() (interactive) (woman (current-word))))
(global-set-key [f6] 'hippie-expand)
(global-set-key [f7] 'replace-regexp)
(global-set-key [f8] 'flush-lines)
(global-set-key [f9] 'dired-do-delete)

# cat /root/.emacs.d/init.el
(load "/home/username/.emacs.d/init.el")

Further reading

Resource Comment
Richard M. Stallman: GNU Emacs Manual. 19th edition, for GNU Emacs version 27.2. GNU Press, ISBN 978-0-9831592-8-5. (Online version updated for Emacs 30.1.) The official handbook of Emacs, also shipped with the editor. This covers the usage of Emacs, not the programming or deep internals.
Robert J. Chassell: An Introduction to Programming in Emacs Lisp. Revised 3rd edition. GNU Press, ISBN 1-882114-43-3. A primer on Elisp programming (very basic, but very good).
Various authors: GNU Emacs Lisp Reference Manual. All information needed for Elisp programming, dense and extensive, but not for beginners.
Craig A. Finseth: The Craft of Text Editing: Emacs for the Modern World. Springer-Verlag, New York 1991, ISBN 0-387-97616-7. Background information about user interfaces and the ergonomics of text editing.

This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: Marc Murphy, Christian Faulhammer
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article's associated history page.