Quick Tutorial

From WikEmacs
Revision as of 15:28, 31 March 2012 by Fredmorcos (talk | contribs) (The reference tutorial in mediawiki format, converted from latex using pandoc)
Jump to navigation Jump to search

This reference-like tutorial is aimed at Emacs beginners and probably others too. If you know how to do some basic editing and navigation in Emacs and want to quickly go through more of its capabilities, then this tutorial is for you. If you are looking for the semantics or key-bindings of a specific feature, this tutorial aims to be for you since it is a subset of the online Emacs documentation. If you are giving an introductory presentation about Emacs, this tutorial might help you.

The repository for the contents of this tutorial can be found here: https://github.com/fredmorcos/emacs-reference

Description and History

  • Emacs is an extensible, customizable, self-documenting, real-time display text editor.
  • Originally, a set of editing macros for the TECO editor.
  • GNU Emacs was developed by R. Stallman and G. Steele.
  • Technically, GNU Emacs is an elisp interpreter with text editing extensions.
  • GNU Emacs contains thousands of commands and allows the user to combine them into elisp procedures (called macros) to automate work.
  • Commands are, themselves, elisp procedures and the GNU Emacs configuration init file is an elisp program.

Technical Description

Extensible

  • The user can define, undefine and redefine commands as well as re-use available commands into macros.

Customizable

  • The user can change properties of emacs elements including the key-bindings and the display.

Self-documenting

  • All defined commands and macros get automatic preliminary documentation (bound keys and parameters).

Why Emacs?

  • Easily programmable
  • Kill ring
  • Rectangular editing
  • Registers
  • Command repetition
  • Macros and Lisp procedures
  • Modes
  • Init file
  • Remote files
  • ...
  • Shell, Terminal Emulator, IRC, Email, News, File Manager, Process Manager, Project Manager, Tetris, Doctor, ...

Terminology & Structure

  • Buffera container for data (text, completions, ...)
  • Pointthe current position in the buffer (cursor)
  • Windowa visual container for a buffer
  • Framea visual container for one or more windows
  • Killthe equivalent of cutting
  • Yankthe equivalent of copying
  • Kill Ringa circular clipboard (very handy)
  • Markthe coordinates of a selection
  • Regionthe text inside a mark
  • Modelinea status line
  • Minibuffera small buffer for commands and arguments
  • Modethe current type of data being edited

Modeline

The Modeline is used to report different pieces of information.

-cs:ch-fr  buf      pos line   (major minor)——

  • cscharacter set (or coding system)
  • :newline mode
  • chfile modification status
  • - or @file is local or remote
  • frframe name on text terminals
  • bufbuffer/file name
  • pospoint/cursor position
  • linecurrent line and column number
  • modescurrently loaded major and minor modes

Keybind Terms & Minibuffer

Emacs has some different naming of command/control keys (coming from the old days).

  • MMeta key, Alt or ESC
  • CControl key
  • SShift key
  • M-apress a while holding the meta key
  • C-M-apress a while holding the control and meta keys
  • C-a bpress a while holding the control key then press b
  • C-a C-bpress a and b both while holding the control key
  • C-a M-bpress a with control then b with meta

The Minibuffer is used to input commands, arguments and setting different modes (which some of are bound to keys or menu actions).

  • M-xexecute a command by name

Basic Usage

Loading

  • $ emacsopens at the scratch buffer
  • $ emacs <math>[file1]~[file2]~...</math>opens in split-window mode
  • C-x C-f <math>filename</math>loads a new buffer from filename

Saving

  • C-x C-ssaves the current buffer
  • C-x C-w <math>filename</math>saves the current buffer as filename

Other

  • C-x C-cquits emacs
  • C-g C-gcancels key-sequence

Windows

Windows are used to display buffer contents. Windows can be split and resized inside an Emacs frame. The minibuffer has its own window.

  • C-x 2open a window vertically
  • C-x 3open a window horizontally
  • C-x 0close the current window
  • C-x 1close all other windows
  • ESC ESC ESCclose all other windows
  • C-x omove to another window
  • C-x ^increase window size vertically
  • C-x }increase window size horizontally
  • C-x {decrease window size horizontally
  • C-x <math>-</math>shrink window to buffer size
  • C-x <math>+</math>make all windows equal in size

Navigation & Movement

Word

  • C-<math>\shortleftarrow</math>moves one word backwards
  • C-<math>\shortrightarrow</math>moves one word forward

Line

  • C-agoes to beginning of the line (Home)
  • C-egoes to end of the line (End)
  • M-agoes to beginning of the sentence
  • M-egoes to end of the sentence
  • M-g ggoes to given line by number

Paragraph

  • C-<math>\shortuparrow</math>moves up one paragraph
  • C-<math>\shortdownarrow</math>moves down one paragraph

Buffer

  • C-x [moves to the beginning of the buffer
  • C-x ]moves to the end of the buffer
  • C-lmoves the buffer to position point
  • C-x bswitches to another buffer by name
  • C-x switches to previous or next buffer
  • C-x kkills the current buffer

Editing

Character

  • C-ddeletes next character
  • C-ttransposes current character with previous one
  • C-q TABinserts a TAB verbatim

Word

  • M-dkills the next word
  • M-- M-dkills to the previous word
  • M-/expands current word
  • M-/ SPC M-/expands current word and grabs next one
  • M-C-/completes current word
  • M-ttransposes current word with next one
  • M-- M-ttransposes current word with previous one
  • M-ccapitalizes next word
  • M-- M-ccapitalizes previous word
  • M-llowercase next word
  • M-- M-llowercase previous word
  • M-uuppercase next word
  • M-- M-uuppercase previous word

Line

  • M-o M-scenter a line
  • C-S-BACKSPCkills current line
  • C-kkills from point to EOL
  • M-- C-kkills to the previous line
  • C-a C-kgoes to BOL then kills to EOL
  • TABindents line depending on current mode
  • C-obreaks line before/after point
  • C-x C-ttranspose current line with previous one
  • M-0 C-x C-ttranspose current line with one at mark
  • delete-matching-linesdelete lines matching a regexp

Prefix Arguments & Command Repetition

Passing numerical arguments to commands can alter their behavior (e.g., repetition or inversion). Passing an argument can be done before M-x or key bindings.

  • M-n comrun com with prefix arg n
  • M-- comrun com with negative prefix arg
  • C-u n comrun com with prefix arg n
  • C-u comrun com with prefix arg 4
  • C-u C-u comrun com with prefix arg 8
  • C-ualso terminates the prefix argument
  • C-x [z]+repeats the previous <math>z^{th}</math> command with args
  • C-x ESC ESCrepeats last command that uses the minibuffer

Examples:

  • C-u 5 0 C-kwill kill 50 lines
  • C-u 5 C-u 0will insert 5 zeros

Search & Replace

Incremental search

  • C-s <math>keyword</math>search forward
  • C-r <math>keyword</math>search backward

Non-incremental search

  • C-s RET <math>keyword</math>search forward
  • C-r RET <math>keyword</math>search backward

Regular Expression Search

  • C-M-s <math>expression</math>search regexp forward
  • C-M-r <math>expression</math>search regexp backward

Notes:

  • ESC will cancel and go to original point. RET will end at the current point.
  • Searches are case-insensitive unless an uppercase letter is found in the search string.
  • While searching, C-w will increment the search term with the current word.

Unconditional Replace

  • replace-stringreplaces a string with another
  • replace-regexpreplaces a regexp match with a string

Query Replace (Conditional Replace)

  • M-%conditional replace of a string
  • query-replace-regexpconditional replace of a regexp

Notes:

  • Replaces are case-insensitive unless an uppercase letter is found in the match string.
  • Replaces work from position to end of buffer unless a mark is active.
  • After a replace, the position will be at the end of the last match. C-u C-SPC to go back to the position before the replace started.
  • During a query replace, SPC will apply a replace and DEL will skip.

Undo & Redo

In Emacs, there is no special redo function. Instead, there is only an undo function and redo can be achieved by undo-ing an undo.

  • C-/undo a single change
  • C-gbreak the chain of undos

Notes:

  • If a mark is active, undo will only affect the marked region.

Regions

Emacs uses the mark and point to denote a region (i.e., a selection).

  • C-SPC creates a region (marks area)
  • C-x C-xswaps mark and point in a region
  • C-u C-x C-xswaps mark and point without region
  • C-x hmarks the entire document
  • M-hmarks the paragraph around
  • TABindents the current region
  • M-@incrementally mark next word

Kill, Yank and Paste Regions

  • C-wkills the currently selected region
  • M-wcopies the currently selected region
  • C-y (M-y)*yanks and cycles from the kill ring

Notes:

  • Yank is the copy command in vi and the paste command in emacs.

Rectangles

Rectangles are marked regions between the columns of the point and mark. Applying operations on rectangles is some sort of vertical editing.

  • C-x r kkill the rectangle
  • C-x r ddelete the rectangle
  • C-x r yyank the last killed rectangle
  • C-x r opush text to fill rectangle with spaces (open)
  • C-x r creplace rectangle text with spaces (clear)
  • C-x r treplace each line in rectangle with text

Registers

Registers are places where you can store anything: text, position, rectangle, configuration, filename, ... Registers are named: a, A and 3 are three different registers.

  • view-registerview the contents of a register
  • C-x r SPC rrecord current point position in register r
  • C-x r j rjump to position in register r
  • C-x r s rsave region to register r
  • C-u C-x r s rkill region to register r
  • C-x r i rinsert text from register r
  • append-to-registerappend region to register
  • prepend-to-registerprepend region to register
  • C-x r r rsave rectangle into register r

Bookmarks

Bookmarks are like registers but persistent. They can also be named.

  • C-x r m foobookmark file and point to foo
  • C-x r b foojump to bookmark called foo
  • C-x r llist all bookmarks
  • bookmark-savesave all bookmarks
  • bookmark-deletedelete a bookmark

Macros

Macros are user defined commands using the Emacs command language. A user can “record” and “replay” a macro, useful for simple repeatable tasks. More complex tasks (e.g., conditions, loops) must be implemented in elisp. Macros are recorded in a macro ring.

  • F3start macro definition or insert counter
  • C-x (start macro definition only
  • F4end macro definition or call macro
  • C-x eend macro definition and call macro
  • C-x )end macro definition only
  • C-u C-u F3append commands to last macro
  • C-u F3re-run last macro then append commands to it
  • C-x C-k rrun macro on region
  • C-x C-k C-nrotate to select the next macro in the ring
  • C-x C-k C-protate to select the previous macro in the ring

Every macro definition can have a counter to insert into the buffer.

  • F3inside a macro definition, inserts the counter
  • C-x C-k C-ioutside a macro definition, inserts the counter
  • C-x C-k C-cset the macro counter value
  • C-x C-k C-fset the macro counter format

Macros can be named and saved.

  • C-x C-k nname the most recently defined macro
  • C-x C-k bkeybind the most recently defined macro
  • insert-kbd-macroinsert macro into buffer as elisp code

Notes:

  • It is best to use the reserved key bindings C-x C-k [a-zA-Z0-9] as to not cause problems with other bindings. C-x C-k b 4 will define C-x C-k 4 as a binding.

Alignment

Emacs contains alignment commands. Sometimes those depend on the current mode (i.e., the language).

  • alignaligns depending on mode
  • align-regexpaligns using a regular expression
  • C-u align-regexpaligns using a regular expression helper
  • align-currentaligns current paragraph depending on mode

Sorting

When sorting, prefixing with C-u sorts in descending order.

  • sort-linessort region by lines
  • sort-paragraphssort region by paragraphs
  • C-u n sort-fieldssort lines in region by <math>\textit{\underline{n}}^{th}</math> field
  • C-u -n sort-fieldssort lines in region by <math>\textit{\underline{n}}^{th}</math> field from right
  • sort-numeric-fieldsinterpret field as number and not text
  • sort-columnssort by column specified by marked region
  • reverse-regionreverses current region

Tables

Emacs has support for creating and editing text-based tables by keeping track of their properties (e.g., position, size) in the buffer. When a buffer is saved to file, those properties are lost.

  • table-insertinteractively insert a table into buffer
  • table-recognizedetect properties of all tables in the buffer
  • table-unrecognizeremove special table properties
  • table-recognize-regiondetect properties of tables in region
  • table-unrecognize-regionforget properties of tables in region
  • table-recognize-tabledetect properties of table at point
  • table-unrecognize-tableremove properties of table at point

Cell resizing:

  • C-u n C-widen cell at point by n characters
  • C-u n C-narrow cell at point by n characters
  • C-u n C-}heighten cell at point by n lines
  • C-u n C-{shorten cell at point by n lines

Cell movement:

  • TABmove to cell on right
  • S-TABmove to cell on left

Cell merging/splitting:

  • C-c C-c *interactively merge two cells
  • C-split cell horizontally
  • C--split cell vertically

Rows & Columns:

  • C-u n table-insert-rowinsert n rows
  • C-u n table-delete-rowdelete n rows
  • C-u n table-insert-columninsert n columns
  • C-u n table-delete-columndelete n columns

Other:

  • C-:interactively justify cell, column or row text
  • C-!toggle table fixed width mode
  • table-generate-sourcetable code in Latex, HTML or Cals

Goodies

  • C-x TABforce an indentation on a region
  • M-qindents and breaks paragraph into multiple lines
  • M-;comments a region or adds comment to line
  • M-(inserts a new lisp function (parenthesis)
  • M-)checks balanced parenthesis and opens line
  • C-x iinserts file contents at point position
  • M-!run shell command
  • C-u M-!run shell command and insert output
  • M-<math>|</math>run shell command on marked region
  • C-u M-<math>|</math>run shell command on and replace marked region
  • insert-bufferinserts buffer contents at point position
  • copy-to-buffercopy region content to a buffer
  • kill-some-buffersinteractively kill buffers
  • electric-buffer-listinteractive buffer list
  • toggle-truncate-linesdo not split lines over visual lines
  • visual-line-modesplit lines by words
  • viper-modevi compatibility

Setting Key Bindings

Emacs has a global keymap which maps between keys and commands. Each major mode can define, redefine or undefine its own key bindings, creating a local keymap (e.g., c-mode). Each minor mode can do so too (e.g., flymake). Each portion of text can also do so (e.g., tables).

Description of some prefix keys:

  • C-xcommand prefix key
  • M-command prefix key
  • C-cmode specific prefix key
  • C-hhelp prefix key

Commands to bind keys:

  • global-set-key k combind key k to com globally
  • local-set-key k combind key k to com locally (major mode)

Notes:

  • Menu and mouse key bindings can also be set.

Storing Key Bindings

In the Emacs init file, you can either set global key bindings or “hook” local key bindings to mode hooks (i.e., callbacks, slots).

  • global-set-keyadds a binding to the global map
  • local-set-keyadds a binding to the local (major mode) map
  • kbdconverts a string to a key sequence

Examples:

Global key binding:

  • (global-set-key (kbd "C-c d") ’duplicate-line)
  • (global-set-key (kbd "C-c d") (kbd "C-a C-@ C-e M-w RET C-y"))
  • (global-set-key (kbd "C-c d") "\C-a\C- \C-n\M-w\C-y")

Local key binding:

  • (add-hook ’LaTeX-mode-hook

    (lambda () (local-set-key (kbd "C-c n")
                              ’forward-paragraph)))

The Emacs Help System

Emacs has a handy help system for quick lookup of various features, topics, functions and key bindings.

  • C-h ?show the help system shortcuts
  • C-h keyrun help system with shortcut key

Some useful help keys:

  • C-h ashow apropos page about a keyword
  • C-h k keybindshow help for function bound to keybind
  • C-h bshow all key bindings
  • C-h fshow documentation for function
  • C-h mshow documentation for current modes
  • C-h vshow documentation for variable
  • C-h wshow what keys a command is bound to
  • C-h tstart the emacs tutorial
  • prefix C-hshow all key binds starting with prefix

Modes

Modes are used to define the types of data being edited in buffers, or what Emacs calls “the language”.

Every buffer has exactly one major mode which defines its language (C, Java, English, IRC, ...) and provides basic elements like syntax highlighting and (re)defines functions and their key bindings for relevant actions (e.g., comments).

Each buffer can have zero or more minor modes enabled which provide non-specific functionality such as spell checking or line wrapping (i.e., mode independent).

ediff

ediff (emacs-diff) is a mode for Emacs where you can view and merge difference between two or three buffers.

  • ediffselect files to view their differences
  • ediff-buffersselect buffers to view their differences

In ediff-mode:

  • switch between horizontal/vertical view
  • ?view ediff help
  • pview previous difference
  • nview next difference
  • aset buffer b’s area to what’s in a’s
  • bset buffer a’s area to what’s in b’s
  • qquit ediff session

Spell Checking

  • M-$check spelling at word or active region
  • ispellcheck active region or entire buffer
    • iaccept word and insert into personal dictionary
    • ?show ispell help
    • RETend current ispell session
  • ESC TABcomplete current word from dictionary
  • flyspell-modeenable “on the fly” spell checking
  • flyspell-prog-modespell check comments and strings

References