Emacs: A Basic Introduction

In 1976, while working at the Artificial Intelligence Laboratory at MIT, Richard Stallman compiled a set of macro extensions to make the TECO editor (more of a text manipulation program than an editor) somewhat user friendly. His package of macros changed TECO's look and feel sufficiently that it was considered a separate editor and became known as EMACS, meaning Editor MACroS. Emacs was rewritten various times. By the time it was implemented on Unix, it was written in C and used Lisp as an extension language to add new features and macros. Lisp is a functional language commonly used in artificial intelligence programming, but which is also used to customize Emacs. If you ever edit a file with a whole lot of parenthesis, the syntax you are witnessing is probably Lisp. Understanding Lisp can be handy if you ever want to add a feature to Emacs.

Because Emacs is so extensible, many people have written extensions to it. This has caused Emacs to become an editor with a kitchen sink, and everything else. Some people joke that Emacs is a good operating system. You can use it to play tetris, browse the web, and compose email. It can also be a very effective text editor and programming environment.

In 1984, Richard Stallman founded the `GNU project`_ to produce freely redistributable open source software under the GPL license. He then rewrote Emacs under this license and founded the Free Software Foundation to fund development of other GNU software through the sale of copies of Emacs. An explanation of the motives of Richard Stallman can be found in the `GNU Project History`_

Maintained by Richard Stallman, `GNU Emacs` has become the “standard” Emacs used on most Unix based systems. It is firmly committed to only using completely free patches, and only linking to completely free libraries.

There is a GNU Emacs port known to run on Windows 95/98/ME/NT/2K/XP. It is fully functional and supports all your favorite Emacs features.

See http://www.gnu.org/software/emacs/windows/ntemacs.html for details.

Fontlock colors must be set in the “Options”–>“Customize Emacs” menu selection, but your .emacs file should work correctly in enabling and configuring most features. To load the .emacs files it must be placed in either the root directory (e.g. ``c:.emacs``) of the drive Emacs is installed in, or in the user's profile in the “Documents and Settings” directory. You will need to experiment to find the correct location.

In 1991, Lucid Inc. wanted to incorporate Emacs into an IDE that they were developing. The added a lot of additional features and tried to get those features merged into the main GNU Emacs source tree. Due to philosophical differences between Richard Stallman and many of the Lucid Emacs developers, a schism resulted and Lucid forked GNU Emacs to make their own project called XEmacs. XEmacs mainly differs from GNU Emacs by their focus on a modern graphical user interface, their support for multimedia such as images and sound, their use of non-GPL libraries and patches, and their open development community which is independent of Richard Stallman. Many people prefer XEmacs to GNU Emacs, though the two frequently borrow ideas and features from one another. You can learn more at the XEmacs_ website.


There are many other Emacs clones. Most of them focus on a small footprint while maintaining a good feature set. Here are a few of the most popular:

The best way to become familiar with Emacs is to first launch Emacs by typing the command ``emacs`` from the command line. This brings up an Emacs window in your desktop environment. Use the mouse to click on the “Help” menu and select “Emacs Tutorial”. If you are using Emacs in a non-windowing environment, then you can hold down the control key and type the letter ``h`` (help), and then let go of the control key and type the letter ``t`` (tutorial). Both of these methods start the interactive Emacs tutorial to guide you through the basics of using Emacs.

In Emacs documentation, the key sequence “press control then type the letter h” is represented C-h. The key sequence for starting the help tutorial would be written C-h t. Another important key in Emacs is the “Meta” key, which is usually the `alt` key. The key sequence M-x <command> means: “simultaneously press Alt and X, then type the name of a command”. The meta key is used when you need to call Emacs functions. Emacs often refers to a “buffer”. A buffer is a region of memory where data is stored. When you are using Emacs, you interact with the data in the memory buffers through a pane in the Emacs window. When we refer to a “buffer opening” or a “buffer closing” we are referring to a pane in the Emacs window which opens for you to read and edit text. The main buffer occupies the bulk of the Emacs window and is where the file you are currently editing is displayed.

The rest of this tutorial assumes that you have read the Emacs tutorial.

Emacs can be customized to meet your own set of personal tastes and needs. Most of the customization for Emacs takes place in a .emacs file located in your home directory. This file is read by Emacs every time it is started. Here is a basic configuration file that turns on several options in Emacs that are explained in detail in the next section: Example .emacs file.

Font colors and highlighting can also be customized using a .Xresources file located in your home directory. Here is an example .Xresources file: Example .Xresources file. Customizing Emacs in this way only works on systems using an X server for the windowing environment. If you are using a graphical login then you will need to add the following commands to your .bash_profile file in your home directory:

 # import my color preferences
 xrdb - merge $HOME/.Xresources

The command loads your new color preferences into the X color database. If you download our example files, remember to change the names. Here is an example for doing this:

mv dot_emacs .emacs
mv dot_Xresources .Xresources

This section discusses various Emacs customizations that are very useful when using Emacs as an Editor. This section assumes that you have completed the tutorial and have a basic grasp on using Emacs as an Editor. Note that all of these commands, and more, are contained in the example ``.emacs`` file in section 4. This section is written with a bias to using the keyboard as the primary communication link with Emacs. All of the described command are accessible through the menus or tool bar too, although the menus do not appear until the appropriate mode is loaded. Loading the correct mode is covered in the discussion. It is also important to note that this document does not cover any one command in depth. You should consult the Emacs help system for in depth descriptions of features. The key sequence ``C-h f <command>`` provides a complete description of any command.

An “Electric Buffer” is a window that allows you to see all files that are open in Emacs and switch between those files quickly. The feature is activated with the command ``M-x electric-buffer-list``. The command creates a new pane in the main window showing the list of active buffers (opened files). Simply move the cursor to the desired files and hit RET (the return or enter key) to put the file in the main window and close the electric-buffer-list. This is a powerful tool that lets you load all relevant files into a single Emacs session and switch between files quickly as needed. Type ``C-h f electric-buffer-list`` to find out more about this feature. The “Electric Buffer” is only useful if you can get in and out of it quickly. The following entry in your .emacs file will bind the electric-buffer-list command to the key sequence C-x C-b making it easily accessible:

  ;; C-X C-B brings up a powerful list of the buffers currently in emacs.
  (global-set-key "\^X\^B" 'electric-buffer-list)

A common problem in programming is moving the cursor to a specific line in the file to correct an error or to figure out which line in the file the cursor is currently on. Both of these questions are addressed by the commands ``M-x goto-line`` and ``M-x what-line``. goto-line takes a numerical argument followed by RET. It then moves the cursor to the specified line. what-line takes no argument and displays in the minibuffer the line number of the cursor location. These commands can be tied to the key sequences M-g and M-G respectively with the following entries in your .emacs file:

  ;; M-g is now the same as M-x goto-line
  (global-set-key "eg" 'goto-line)
  ;; M-G is now the same as M-x what-line
  (global-set-key "eG" 'what-line)

More information is available in Emacs with the ``C-h f goto-line`` and ``C-h f what-line`` commands.

Emacs has many resources for highlighting text to make it more readable. This is very useful when using Emacs to write programs, HTML, or work in other programming languages. Text highlighting is enabled with the command ``M-x font-lock-mode``. The highlighting is determined by the type of file. Highlighting behaves differently in Perl than it does in C++. The colors can be customized in the Options–>Customize Emacs menu selection. Some limited amount of customization is available in the ``.Xresources`` file. See section 4 for details. font-lock-mode can be enabled by default in your ``.emacs`` file with the following:

  ;; Always fontify the buffers with highlighting
  ;; set the maximum.
  (global-font-lock-mode t)
  (setq font-lock-maximum-decoration t)
    (eval-after-load "font-lock"
     '(add-to-list 'c-font-lock-keywords-3
                   '("\" . font-lock-type-face)))

More information can be had with the command ``C-h f global-font-lock-mode``.

Emacs has major modes that provide editing features for many languages. If you are writing a C program, for example, then the command ``M-x c-mode`` will load editing features specific to the C language. When writing a C program, Emacs automatically matches ()'s, {}'s, handles indentation, allows the commenting of blocks, etc. All the features are listed in the help area (accessed with ``C-h f c-mode``). Emacs can autodetect the correct mode for a file based on the extension. It loads the correct mode in most cases. Specific modes can be specified for files by simply loading the desired mode with the ``M-x <mode>`` command or by associating extensions with modes in the .emacs file as follows:

  ;; This is how emacs tells the file type by the file suffix.
  (setq auto-mode-alist
        (append '(("\.java$" . java-mode))
                '(("\.h$" . c++-mode))
                '(("\.cpp$" . c++-mode))
                '(("\.c$" . c-mode))

In most cases, this type of customization is not needed. Emacs almost always gets it right.

The ability to cut, copy, and paste text without using the mouse is very convenient at times. Emacs, by default, will copy anything that is highlighted with the mouse (i.e, click and drag). It can be pasted using the middle mouse button or scroll button. If you do not have a 3-button mouse, then try clicking the left and right buttons simultaneously. On many systems, this is the default sequence to emulate a 3-button mouse. All mice aside, it is possible (and often preferred) to Cut, Copy, and Paste using the keyboard. Cut, Copy, and Paste are activated with the commands ``C-SPC`` followed by ``C-w`` for cut, ``C-o`` for copy, and ``C-y`` for paste. The first command ``C-SPC`` simply marks a point in the file. This is the starting point for the text you want to cut or copy. Use the mouse, arrow keys, or keyboard motions (``C-P``, ``C-N``, ``C-F``, ``C-P``, etc.) to move the cursor to the end of the text you want to cut or copy. At this point use ``,C-w``, to cut or ``,C-o``, to copy. To paste the text, simply move the cursor to the desired location and use the command ``,C-y``,. Emacs, by default, does not highlight the cut/copy region when moving the cursor with the keyboard. To turn on highlighting, add the following command to your .emacs file:

  ;; make marked region highlighted
  (setq transient-mark-mode t)

Note that C-o is not active by default in emacs. It is activated with the following entry in your ``.emacs`` file:

  ;; copy region
  (global-set-key "C-o" 'copy-region-as-kill)

Learning to use these commands without the help of the mouse pays big dividends in writing and programming efficiently. It keeps your hands on the keyboard over the keys rather than having to continue to reach away to manipulate the mouse.

If a file has been changed by another program, it is necessary to reread it from the disk to update it within Emacs. This is done with the command ``M-x revert-buffer``. The following .emacs entry binds it to the C-x C-r key sequence:

  ;; reread buffer from file
  (global-set-key "C-xC-r" 'revert-buffer)

Emacs can compile your program with the ``M-x compile`` command. This allows you to type in the actual compile command and run it (i.e., make foo, gcc test.c, etc.). Emacs captures the output, splits the current window, and displays the output in a buffer in the lower pane. If you are using gcc, g++, or any compiler command that outputs line numbers with errors, then Emacs can take you to the offending line with the ``M-x next-error`` command. The following .emacs entries bind the M-x compile command to C-xm, binds the M-x next-error command to C-x C-j, or C-`, and sets the size of the compilation output window.

  ; runs make in the "current directory"
  (global-set-key "C-xm" 'compile)
  ; Goes to the next error in the compile errors list...
  ; or it goes to the next grep match in the grep match list
  (global-set-key "C-xC-j" 'next-error)
  ;; Set the size of the compilation window height
  (setq compilation-window-height 10)
  ;;force compilation to scroll
  (setq compilation-scroll-output t)

Note that the last command simply forces the output from the compilation to scroll in the Emacs window so you can always see the most recent output. The next-error command starts at the first error, however.

By default, Emacs does not automatically insert line breaks when you are typing plain text. This means that as you type and reach the end of the line, Emacs will just wrap the text onto the next line without inserting the corresponding line break. This leaves all of your text as one very long line. Although automatic line breaks can be enabled, it can be annoying when writing programs. Emacs can line break a paragraph (i.e., text separated by blank lines) or a region with the commands ``M-x fill-paragraph`` or ``M-x fill-region``. The shortcut ``M-q`` exist for the fill-paragraph command. The following creates a C-xp shortcut for the fill-region command:

  ;; Fill region hotkey
  (global-set-key "C-xp" 'fill-region)

When you insert new text into a region that already includes line breaks, you can reformat the region using any of the above commands (i.e., add or remove text and then run the ``M-x fill-paragraph`` or ``M-x fill-region`` commands again). If you are using c-mode or other programming specific modes, then fill-region and fill-paragraph will often redistribute comment characters as appropriate too.

Emacs does have spell checking ability. You can spell check an entire buffer or a region. To activate spell checking, select “Tools” and then “Spell Checking” from the menu. Or use the combination M-x ispell RET to activate the command.

Emacs has integrated hooks for CVS and RCS, and hooks for Git and SVN can be added. It automatically detects files that are revision controlled and presents an appropriate submenu named “Version Control” in the “Tools” menu.

Commands key sequences that every user should know:

  • ``C-k``: delete a line (saves to be pasted if desired)
  • ``C-y``: paste
  • ``C-o``: copy
  • ``C-w``: cut
  • ``C-e``: Move cursor to end of line
  • ``C-a``: Move cursor to beginning of line
  • ``C-n``: Move cursor to next line
  • ``C-p``: Move cursor to previous line
  • ``C-f``: Move cursor forward one character
  • ``C-b``: Move cursor back one character
  • ``M-q``: Insert line breaks into a paragraph
  • ``C-x C-b``: Activate electric buffer list (must use example ``.emacs`` for this)
  • ``C-x C-s``: Save current buffer
  • ``C-x C-c``: Quit emacs
  • ``C-x C-f``: Load a new file
  • ``C-x C-i``: Insert a file into this buffer
  • ``C-x C-r``: Revert the file loaded in the current buffer (must use example ``.emacs``)
  • ``C-xm``: Compile command (must use example ``.emacs``)
  • ``C-```: Next error
  • ``C-s``: Search for string
  • ``M-%``: Query replace

Incidentally, most of these command apply to the command shell (bash and tcsh) as well as Mozilla and other X applications.

This section contains a few quirky commands and other features. These are interesting, but not essential.

The audible bell can be made visible (i.e., Emacs blinks the screen) by putting this command in your ``.emacs``

  ;;turn off the beep, but give visual notice of a beep
  (setq visible-bell t)

We personally cannot stand tool bars or button bars.

  ;;Get rid of the tool bar that is default on (i.e., this toggles it off)

The hide show package allows you to collapse and expands regions in programs. For example, if you have a really long function, then you can collapse that function into 1 line when you are not working in it so you can see other functions in the file:

  (load-library "hideshow")
  ;;add hide-show (folding) hooks
  (add-hook 'c-mode-hook                '(lambda () (hs-minor-mode 1)))
  (add-hook 'c++-mode-hook              '(lambda () (hs-minor-mode 1)))
  (add-hook 'perl-mode-hook             '(lambda () (hs-minor-mode 1)))
  (add-hook 'python-mode-hook           '(lambda () (hs-minor-mode 1)))
  (add-hook 'sh-mode-hook               '(lambda () (hs-minor-mode 1)))
  ;; Add hooks for LaTeX and Tex modes (does not load for auctex)
  (add-hook 'latex-mode-hook            '(lambda () (outline-minor-mode 1)))
  (add-hook 'tex-mode-hook            '(lambda () (outline-minor-mode 1)))

The help system details the use of this mode. It also creates a menu for you when it is loaded and active in a buffer.

  • emacs-a-basic-introduction.txt
  • Last modified: 2017/02/22 13:51
  • by brysonlt