Last Updated: 2020-02-07 Fri 16:57

Tool Time Session 1: Emacs Editing Basics

Table of Contents

1 Metadata

Session Synopsis: Emacs has been editing files for 40+ years and is still going strong. Why? It's an extremely powerful and flexible tool for manipulating text. This session will mitigate its difficult learning curve to show why Emacs can absorb most coding work and is truly the "hundred year editor."

2 What's About to Happen?

  • We'll talk about the Emacs text editor
  • Restrict our attention to built-in goodies
  • Survey what your presenter has found useful on a daily basis
  • Will show keystrokes as we go: underscore efficiency enabled by the home row
  • Try to surmount the difficult of getting acquainted with a very old but still relevant piece of software


2.1 Thank Yous

  • Joe Finnegan: for making the recordings possible and enshrining all my mistakes permanently the in the clogged tubes of the Internet
  • Computer Science Dept: for supporting and advertising the series
  • Institute of Mathematics and its Applications: for lending us Keller 3-180 to do this session
  • Students Past and Present: for showing interest in these tools, pestering me to show them how they work, and showing up today

3 A long time ago, in a lab downstairs…

  • A young professor Kauffman takes his first CSCI 1113 course
  • A forgotten lab TA tells students in the 3-hour lab they should use "Em-axe" to code
  • On looking at young Kauffman's code, that TA says 'press tab more' (demo in un-indented C file)
  • A 20-year love affair begins…

4 History and Philosophy

  • Emacs is an OLD program (first released 1976, presently on release 26.3)
  • Created in a time when graphics were a luxury and most editing was done in terminals. CONSEQUENCES:
    1. Default Emacs is not graphically pretty: menus clunky, text chunky, interaction funky (but ALL can be tweaked)
    2. Core functionality of Emacs is focused on the keyboard: the computer mouse became popular 5-10 years after Emacs's birth
    3. Emacs key bindings and editing concept names are different from their modern versions because Emacs predates the conventions set by other companies like Apple/IBM circa 1984

      1984     1976  
      Apple/IBM Concept   Emacs Equivalent
      Ctl-c "copy"   Meta-w "copy region"
      Ctl-x "cut"   Ctl-w "kill region"
      Ctl-v "paste"   Ctl-y "yank"
    4. Emacs runs in the terminal nearly identically to graphical version, extremely handy when one only has terminal access to a remote machine (in terminal run emacs -nw for non-windowed mode, default on non-graphical displays)
  • In its early life, was considered an extremely heavy-weight editor due it inclusion of an embedded Lisp interpreter, a stark contrast to its contemporaries like vi (predecessor to vim)

    • EMACS : Editor MACroS according to Emacsen [emacs users]
    • EMACS : Eight Megabytes And Constantly Swapping according to vi folk; historically this was a burn

    CONSEQUENCES of incorporating a Lisp interpreter into the editor

    1. Emacs is typically a bit slower to start than command line editors vim, nano, joe, etc.
    2. Emacs is WAY faster to start than typical IDEs like Atom, VSCode, Eclipse, etc.
    3. Emacs can be extended and customized via writing bits of Lisp code; this is why it is continues to thrive today.

    Emacs was built to grow and change making it worthwhile to learn about this model of software construction

5 Basic Info and Conventions

5.1 Appearance and Parts of Frame

  • Default appearance is on the bland side

    Sorry, your browser does not support SVG.

    • Emacs always starts with a "scratch buffer": text editing area not associated with any file
    • Menu Bar at top, beneath it the Toolbar (should be familiar to most)
    • Mode Line: Just above the bottom, usually a different color, shows info on buffer/file, state, position in buffer, editing mode, etc.
    • Minibuffer: Single line at the bottom of the screen, used for feedback from Emacs and input for certain commands
  • Kauffman Customized Emacs

    Sorry, your browser does not support SVG.

  • Observations
    • Buffers show text of some kind, sometimes associated with a file, other times associated with a process like a running shell or compilation
    • Each buffer has an editing area with Mode Line and Mini Buffer
    • Most activities have an associated Major Mode: c-mode for editing C files, Compilation for compiling, dired-mode for viewing/editing directories, etc.
    • Emacs can have many buffers open, each doing something different
    • Must have commands: how to split into multiple windows and change between them, how to switch between open buffers

5.2 Typing and Modeless Input

  • In Emacs, most keys on the keyboard insert associated characters
    • Pressing 'A' will insert 'a' into a buffer
    • Holding 'Shift' and pressing 'A' inserts 'A'
    • Pressing 'Backspace' deletes the preceding character
    • Pressing 'Enter' inserts a newline
  • Referred to as "normal", "modeless", "non-modal" behavior
  • Contrast: vi / vim use Modal Editing
    • vi is always in a 'mode', usually Command or Insertion
    • In Command mode pressing 'X' deletes a character
    • In Command mode pressing 'I' changes to Insertion mode
    • In Insertion mode pressing 'X' inserts 'x'
    • In Insertion mode pressing 'Esc' changes to Command mode
  • Principle: Pressing keys in runs commands in Vim Command mode
  • Principle: Pressing keys in Emacs always runs commands
    • Some commands insert characters
    • Other commands move cursor, delete text, open files, etc.
    • Emacs Modes establish certain key bindings appropriate to the type of text one is editing (text, code, shell, directory, etc.)

5.3 Basics of Key Strokes

  • Emacs has complex key bindings, often called chords (like pressing multiple keys on a piano)
  • Chords involve holding a bottom row key, have abbreviations
    • C-w : hold Control while pressing 'w'
    • M-f : hold Alt (Windows) / Cmd (Apple) while pressing 'f'
    • C-x b : Hold Control, press 'x', release both, then press 'b'
  • Common chord conventions
    • C-x keys: global manipulations (open files, switch buffers, quit)
    • C-c keys: mode-specific commands (evaluate code, compile, comment)
    • M-x command: run interactive commands by name
    • M-: lisp: execute lisp code
Keys Effect
C-f Move cursor forward one character
C-g Universal cancel (keyboard quit): used to get out of trouble
C-x C-f Find a file to edit, type its name in the minibuffer to open
C-x C-s Save the current buffer to disk
C-x C-v Find alternate file, replace editing this file with another one
C-x b Switch to a different open buffer (file) to edit
C-x C-b Open the buffer menu to select a buffer to edit

5.4 Key Strokes Run Commands

  • Emacs allows any key combination to bound to run a function
  • Core functions are written in C and compiled as part of the Emacs source code
  • Most functions are written in Emacs Lisp
  • M-x will jump to the mini buffer; type the name of an interactive function to run it (not all functions are "interactive")
  • All functions can be evaluated in their Lisp form via M-: which will prompt for Emacs Lisp code to evaluate
  • All of the below have the same effect
Keys Interactive Command Emacs Lisp Function Evaluation
C-f M-x forward-char M-: (forward-char)
C-g M-x keyboard-quit M-: (keyboard-quit)
C-x C-f M-x find-file M-: (find-file "~/.emacs")
C-x C-s M-x save-buffer M-: (save-buffer)
C-x C-v M-x find-alternate-file M-: (find-alternate-file "~/.bashrc")
C-x b M-x switch-to-buffer M-: (switch-to-buffer ".bashrc")
C-x C-b M-x buffer-menu M-: (buffer-menu)

6 Movement

6.1 Philosophy of Movement

  • Much of text editing is position the cursor
  • Efficient cursor movement -> efficient editing
  • Emacs born in the pre-Mouse era, provides TONS of movement commands
  • At first the quantity of movement commands seems ridiculous:
    • HOW could I ever learn all these?
    • WHY would I ever learn all these?
  • Promise: if you spend a year steadily practicing and absorbing movement using the keyboard, you will edit code an order of magnitude faster; after 3 hours of coding you'll realize you never touched your mouse because the ideas flowed from your fingers directly into the buffer

6.2 Basic Movement

  • The following are among the most common movement commands
  • Most are tied to easy to reach keys and have bindings that roughly reflect their effect ('f' for forward, 'b' for back, etc.)
  • Side benefit: default Shell command line interpreter bash uses similar bindings for movement when editing command lines

    Keys Effect In Bash?
    C-f Forward character Same
    C-b Backward character Same
    M-f Forward word Same
    M-b Backward word Same
    C-a Beginning of line Same
    C-e End of line Same
    C-p Previous line Prev Command
    C-n Next line Next Command
    M-e Forward/End of sentence -
    M-a Backward/Beginning of sentence -
    M-} Forward/End of paragraph -
    M-{ Backward/End of paragraph -
    M-> End of file  
    M-< Beginning of file  

6.3 Structural Movement

  • Emacs aware of some structural features of text docs
  • Parenthesized expressions in code modes
  • Heading in outline modes
  • Modes provide commands/key bindings for structural movement

    Keys Command Effect
    C-M-f forward-sexp Forward over pren expression
    C-M-b backward-sexp Backward over paren expression
    C-M-u backward-up-list Move "up" one level of parens
    C-M-d down-list Move "down" one level of parens
    M-n *-next-heading Move to next heading
    M-p *-prev-heading Move to previous heading

6.4 Searching

  • Interactive Search Forward/Backward: Extremely useful for navigation and search, TONS of cursor movement should be done via C-s or C-r
  • Search is SUPER easy to start up and uses Minibuffer for reporting
  • Versions that honor regular expressions available also
Key / Command Effect
C-s Start an interactive search forwards
  Type what is being search for
  Press C-s to search forward to the next location
  Most locations are highlighted
C-r Start an interactive search in reverse
  Can intermingle C-s / C-r to go forwards/backwards
  Feedback is shown in the Minibuffer
Enter End interactive search at the current match
  Saves mark where search started
C-g Cancel interactive search
  Returns Point to the search start
C-M-s Regular expression versions of interactive search
C-M-r Honors regex like 'n$' and '- [SMT]'

6.5 Going to Specific Spots

  • Some situations dictate moving cursor to specific locations
  • Usually going to specific line associated with an error: later associated with compilation
Key / Command Effect
M-g g Goto line entered in minibuffer
M-g n Goto next error after compilation
M-g p Goto previous error after compilation
  • Emacs also has a "bookmarking" facility to remember locations in files of interest AND an ability to store locations in "registers" for quick access

7 Text Manipulation

7.1 Basics

The Cursor in Emacs (aside for the sake all that his holy run cursor-blink-mode to disable blinking)
An invisible position that is "remembered" in the buffer, used to jump around and edit
The text that is between the Point and the Mark. Many commands affect the Region. Equivalent to the "highlighted text" in modern editors but always present and somewhat quirkier.
Key / Command Effect
C-space Place the Mark, usually to set up a copy/kill command
C-x C-x Swap the position of the Point and Mark (cheap bookmarking)
C-space C-space "Activate" the mark so the region is highlighted
M-x transient-mark-mode Always highlight the Region while it is active
C-u C-space Pop the mark: moves the point to a previously marked location

Emacs has Copy/Cut/Paste commands under slightly different names

Kill ~ Cut
Killing text is like "Cut" in most editors but there is a "history" of killed text called the Kill Ring
Yank ~ Paste
Put the top of the Kill Ring in at the point. Yanking multiple times in a row will Yank lower items in the Kill Ring.
Kill-ring-save will Copy text into the kill ring but don't remove it from the buffer
Key / Command Command Name Effect
C-k kill-line "Cut" from the Point to the end of the line
C-w kill-region "Cut" the Region : text between the Mark and the Point
M-w kill-ring-save "Copy" the region in the Kill Ring
C-y yank "Paste" the first element from the Kill Ring
C-y M-y yank "Paste" the second element of the Kill Ring which will now be at the top of Kill Ring
C-y M-y M-y yank "Paste" the third element of the Kill Ring…
  browse-kill-ring Open a buffer with the entire Kill Ring, 'y' will yank text into the other buffer
  • Emacs has Undo/Redo facilities for mistakes

    Key / Command Command Name Effect
    C-/ undo Undo the last action
    C-x u undo Same as above
    C-/ C-/ undo Undo the last 2 actions
    C-u 10 C-/ undo Undo the last 10 actions
  • Interestingly, any undone action can be redone by taking an arbitrary action (entering a character of text) and the repeatedly undoing
    1. Enter the text "apple orange banana"
    2. Press C-/ repeatedly until the text is gone
    3. Press Space to enter a space
    4. Press C-/ repeatedly to undo the space and recover "apple orange banana"
  • Undo/Redo history is kept in a Ring (like the Kill Ring) so has some interesting properties but most undo problems can be solved by typing a few characters and then pounding C-/ for dear life

7.2 Keyboard Macros

  • Emacs can record editing commands to automate repeated tasks that might otherwise require shell scripts
  • Can save macros to be used as named functions later

    Key / Command Command Name Effect
    C-x ( kmacro-start-macro Start recording a keyboard macro
    C-x ) kmacro-end-macro Stop recording a macro
    C-x e kmacro-end-and-call-macro Execute the last keyboard macro once
    C-x e e e   Repeatedly execute the last macro (3x)
    C-x h mark-whole-buffer Make the region the whole buffer
    C-x C-k r apply-macro-to-region-lines Repeatedly apply the macro through the whole region
      edit-last-kbd-macro Show macro /comments in a buffer allowing changes
    C-x C-k n name-last-kbd-macro Give a name to the last macro for further use
      insert-kbd-macro Insert a named macro as executable Lisp code
  • Demonstrate this for quick text transformation on the text in the survey-results/ directory

7.3 Rectangles

  • A common feature of modern editors is 'multiple cursors' : change text in columns
  • Emacs (and Vi) have this capability as well
  • Emacs calls them Rectangles and has chords/commands to edit them
  • Rectangle commands shift text left/right on all lines that the affect

    Key / Command Command Name Effect
    C-x r t string-rectangle Insert text in Rectangle defined by Point/Mark
    C-x r d delete-rectangle Delete text in Rectangle defined by Point/Mark
    C-x r k kill-rectangle Kill text in Rectangle defined by Point/Mark
    C-x r y yank-rectangle Yank last killed rectangle at the Point
  • Demo this using a buffer of numbers
    • Open a scratch buffer
    • Then C-u M-! seq 100 to populate with numbers
    • Play with various rectangle commands

7.4 Universal Argument / Repeating (some) Commands

  • Some commands can be modified by typing C-u before the command : C-u is the "Universal" argument
  • C-u followed numbers passes a numeric argument to a function
  • Both are used here and there in Emacs, effect varies by command, Examples:

    Key / Command Command Name Effect
    M-! shell-command Run a shell command typed into the minbuffer
    C-u M-! shell-command Run shell command and insert results at point
    C-f forward-char Move forward one character
    C-u 20 C-f forward-char Move forward 20 characters

7.5 Replacing Text

  • Common to replace some text in a buffer with other
  • Interactive and non-interactive functions for this
  • Also good spell-checking support

    Key / Command Command Name Effect
    M-% query-replace Prompt for text to search and replace
        Scan forwards replacing interactively
    C-M-% query-replace-regexp Regex version of above
      replace-string Prompt for query/replacement
        Non-interactively replace
      replace-regexp Regex version of above
      ispell Interactively check text for spelling
      ispell-comments-and-strings Better for code

8 Getting Help

  • Emacs features a robust help system
  • General C-h prefix will access help functions
  • C-h C-h is help on the help :-p
  • Useful to show key bindings, function documentation, access source code (!)

    Key / Command Command Name Effect
    C-h C-h help-for-help Show kinds of help that can be given
    C-h k describe-key Show what a key / chord does
    C-h k C-y   Shows what C-y does
    C-h b describe-bindings Shows ALL bindings for current buffer
    C-h m describe-mode Docs for active major and minor modes
    C-h f describe-function Docs for a lisp function, links to source
    C-h a apropos-command Search for a function by terms
    C-h i info Opens the Info documentation, hyperlinked format
  • Various other kinds of docs available
  • Info documentation has a lot of stuff in it, was a precursor to HTML and the web

9 Buffers, Files, Windows, Frames

  • Emacs is meant to be opened once and used for a long time, days at a time (knew a developer at Cray whose Emacs session was going on 6 months without restarting)
  • Typical to have dozens to hundreds of Buffers open in Emacs, each associated with a file, process, or other task
  • Must manage multiple open buffers and windows for efficiency

9.1 Multiple Buffer Management

  • Opening files will automatically create buffers
  • Switch between buffers or call up a listing of those buffers and pick one (in buffer)
  • Running sub-processes like Shells also creates buffers but these aren't tied to a file
  • Almost everything happens in buffers
Key / Command Command Name Effect
C-x C-f find-file Prompt for a file, open it in a new buffer
C-x b switch-buffer Type a buffer name and switch to it
C-x C-b buffer-menu Open a buffer with a list of buffers
    "Enter" will switch to buffer at Point
    Can also mark and delete buffers
  ido-mode Override standard file/buffer commands
    with versions that are better
C-x C-s save-buffer Save the current buffer to a file
C-x C-w write-file Write buffer to disk, prompt for new file name
C-x s save-some-buffers Interactively prompt to save open buffers

9.2 Dired : Directory Editing

  • One killer kind of buffer is a Dired buffer for "Directory Editor"
  • Allows one to navigate the file system in Emacs
  • Also allows changes to files/folders in Emacs using familiar editing techniques
Key / Command Command Name Effect
C-x d dired Prompt for a directory, open it in a new buffer
n   Next line
p   Previous line
Enter   Open a file/directory
o   Open file/directory in other window
^   Go up a directory
d   Mark for deletion
x   Delete marked files
g   Refresh directory (if changed externally)
i   Insert a subdirectory in the current buffer
C-x C-q   Edit directory as text (!!!!)
C-c C-c   Save changes to directory
  • It is worth emphasizing that the last two commands are EXTREMELY powerful
  • Allow text operations to be used to rename files with extreme efficiency

9.3 Splitting Windows and Resizing

  • Emacs notion of a window is a pane within the same window
  • Common to split windows horizontally and vertically for various tasks
  • Windows may show same buffer or different buffers
Key / Command Command Name Effect
C-x 0 delete-window Delete current window
C-x 1 delete-other-windows Make current window the only one
C-x 2 split-window-below Horizontally split current window
C-x 3 split-window-right Vertically split current window
C-x + balance-windows Resize windows equally (sort of)
Mouse Dragging   Manually change sizes for windows (GUI)
C-x o other-window Change to other window (rebind this to M-o)
C-x 4 c clone-… Duplicate buffer in a new window
    Edit independent of the other window
    Useful for editing at separate locations
  • Commands exist to change window sizes with keyboard but haven't found that they are tremendously useful

9.4 Frames ~ "Windows"

  • Emacs has GUI support for multiple "Windows" called "Frames" in Emacs parlance; single Emacs instance with multiple frames
  • Have not found this particularly useful but they exist, most commands start with C-x 5 ... such as C-x 5 f to find a file in a new frame.

10 Editing and Compiling Code

10.1 Major Modes

  • Haven't found a language yet for which someone hasn't written a Major Mode: Emacs code that supports editing that specific programming language
  • Most are named sensibly: c-mode, java-mode, python-mode, shell-script-mode etc.
  • Sometimes named strangely, Ex: Ocaml's "Tuareg Mode"
  • Major modes exist for other things like text-mode, org-mode, etc.

10.2 Compiling Code

Key / Command Command Name Effect
  compile Prompt for a command to run to compile code
    Rebind this globally to C-c c
    Often associated with make and Makefiles
    Retains history of compile commands
    Shows results and allows for jumping to errors
M-g n   Next error (after a compile)
M-g p   Previous error (after a compile)

With compile and error jumping, can quickly edit files to get code up and running.

11 Working with Interpreters

Emacs has robust facilities

11.1 Shell mode

Keys / Command Effect
M-x shell Run an interactive shell in the *shell* buffer
C-u M-x shell Start a second shell, or a third, fourth, etc.
Enter Send command at prompt to shell
M-p Previous shell command in history
M-n Next shell command
M-r Interactive reverse search command history
C-p / C-n Previous / Next line
C-r / C-s Interactive search reveres / forward
M-w / C-w / C-y Copy, kill, yank region
etc. All other command standard
  • Works mostly like a standard terminal/shell
  • Can edit it like a normal text file except hitting "Enter" in front of the prompt sends commands
  • NOT a fully function terminal so commands like top and nano will usually fail

11.2 Other Interpreters

  • Inferior shells for interpreted languages (python, ocaml, ruby, octave, etc.)
  • Demo: Python is fairly well supported via run-python, commands in python file can be sent to the interpreter easily, see
  • Demo: Emacs features Advanced interaction with debuggers via the Grand Unified Debugger interface (GUD); try M-x gdb in the c-list-applicaton/directory

12 Org Mode: A Killer Feature

  • Note taking
  • List making
  • Table baking
  • Multiple export formats
  • What you are looking at was generated with Org Mode
  • Demo in the 2021-hw01-c-basics directory

13 Other Major Modes of Note

13.1 Hexl Mode: Viewing and editing Binaries

  • Worth a look if you plan to edit binaries (not recommended)
  • Provides a few conveniences such as ASCII string recognition and raw byte entry


13.2 Doctor

  • When you need to talk to someone, try M-x doctor
  • Any insights you might gain were always there


13.3 Tetris

  • When the code just won't cooperate, take a break
  • Just don't lose too much time after discovering M-x tetris


Author: Chris Kauffman (
Date: 2020-02-07 Fri 16:57