[back to UNIX]
The great GNU editor
Last change April 2, 2004 AD
Introduction, short glossary
Commands (the basics, programming
Text editing - abbreviations, autom. completion,
Other ('more advanced': tags, RegExp
(RegExp examples ),
Tools (Ediff, Ebrowse)
Modes (major, minor) - some of the useful editing
modes found either in Emacs or XEmacs
- Languages & coding - various format of files
(dos, unix, windows ...), language support
Appearance (indentation rules, reverse video etc.)
Examples may help too (Batch
.emacs files & utils- customizing the editor
Various notes (Emacs
Fonts and Faces)
Links (.emacs init file)
Emacs is indeed a great editor
and, actually, it is much more than an editor. When I used it the first
time, I thought it was the worse program ever, because it worked in a very
different way than I was used to. But then I learned the basic and started
to discover how good it is.
Emacs can help you much
in editing various kinds of text (normal text, program source, HTML ...),
it can act as an interface to some programs (which makes you life much
easier, as you will find out) - e.g. debugger, compiler, shell, e-mail.
'the basic editing unit'. Corresponds to one opened file (text). The command
"kill (or delete) buffer" means "close the file being edited".
Part of a buffer, e.g. selected by mouse (you know what I mean by "select
text", right? Usually it's highlighted)
- A rectangular area of text defined by a top line, bottom line, leftmost
column and rightmost column. Commands that operate on a rectangle enable you
to remove particular columns etc.
Keys - notion
SPC = space, ESC = escape, TAB = tabulator, RET = Enter, M = hold
Meta (Alt or Escape[only press and release]), C = hold Control.
Note about the Meta key: usually it is not called 'Meta'; it can be Alt (the
left one, usually), on a Sun
keyboard there may be a diamond on that key, it may be called 'Edit' ...
Some notes on emacs & programming
Emacs has 'modes' e.g. for C, Lisp, Java. It enters the mode automatically
as soon as you open a file with the appropriate extension (.c, .lisp, .java)
Then you shall have highlighted syntax and other nice things.
A programming language mode - automat. indent: emacs indents the line
which you are just writing as soon as it knows how (e.g. as soon as you
press <enter> or write ';' or '}' etc.)
Highlighted syntax: from menu select Help->Options->"[ ] Global Font
Lock (highlights syntax)"
Some commands etc. ('C-x' means 'hold Control and press x'; 'M-x' means
'hold Alt and press x' or, if it doesn't work, "press Escape and then press
x"). Note: C-M-x, M-C-x and ESC C-x are equivalent( 99% )
Partial content: basics | moving
around | deleting | mouse
| programming | sexp
| customization | version
control | search & replace | printing
| copy&paste |
Emacs also contains or offers an interface to a number of applications (e-mails,
version control, comparing files, calendar ...).
Mule - abbreviation of "multi lang." - support for other character coding
than the basic English one (needed if you use for example French)
Tools->Display Speedbar - very useful thing, try it. Contains an 'index'
of the current file (or the current directory, if no file opened yet).
Great for finding a definition of a function in C source ... You can bring
it up by the command M-x speedbar . Use the 2nd mouse button to
"follow a link".
completition - Emacs has completition for symbol names, which you
can use normally in a buffer. For a programming language, it's based either
on the TAGS table or, for standard functions, on Info files for the particular
standard library; of course the Info file must be installed, TAGS file
created (see the unix etags command). In the Text mode, the completition
is based on the spell-checker's dictionary. See emacs(compl.)
gnu tutorial. The completition is "run" by M-TAB.
abbreviations (see gnu)
- there are 2 kinds of them. Normal ones, which must be defined and which
are expanded automatically as you type (e.g. if you define 'fw' as the abbreviation
for 'funny world', after you type 'fw ', it will be expanded
to it) and so called dynamic abbreviations, which don't need to be defined,
but their use must be explicitly demanded; Emacs then searches the previous
text to find the first word starting with the same prefix. You run the
expansion by using M-/. For example if I wrote 'Em' and typed M-/,
it would have been expanded to 'Emacs'.
static abbrevs (Abbrev mode must be enabled!) - definition: type
the expression the abbrev expands to, type the (following) command sequence
and then type the abbreviation. To define 'fw' as mentioned above, 1) type
world' 2) type C-u 2 C-x a g fw RET ('RET' means 'press return',
i.e. Enter). The first part (C-u 2) gives the input parameter 2 (which
means "the abbrev is abbreviation for the sequence of the tw previous words"
- the exp. 'funny world' has 2 words). the second part then defines the
abbrev (a - abbrev, g - global). Note: if the Abbrev mode isn't enabled,
you can still create and expand abbrevs, but the expansion must be explicitly
required (type the abbrev - e.g. 'fw' - and then C-x a e
[a - abbrev, e - expand]). You can save your abbrevs so they 'survive'
till the next time (see "abbrev-file-name", "write-abbrev-file" and "read-abbrev-file")
dynamic abbrevs (Abbrev mode doesn't need to be enabled): use the
sequence, as described above. If you use ESC C-/
instead, it will
not find the last matching word, but searches the whole buffer and presents
the possible completitions.
hippie-expand - this function can complete lines of text in addition to
narrowing - you can make temporarily a part of the buffer invisible
and inaccessible. Only the selected part (the region) stays 'normal': use
n n to narrow and C-x n w to 'widen', i.e. to remove the narrowing
text editing (normal human language text)
M-x text-mode to enter the text (normal language) editing
M-x auto-fill-mode toggles the auto-fill-mode (breaking the
text when the lines are too long). M-q 'refils' a paragraph.
C-h k displays a description (definition) of a command (e.g. the
C-h c as k, but only very short description
C-h f describes a function
C-h a apropos (finds any function/command/variable including the
C-h m describes the current mode (type q to close the result window)
(go to *scratch* and test it)
C-h b lists key bindings
- language related help -
C-h L describes the language environment (latin-1, Czech ...)
C-h I describes input methods of the current lang. environment (input
method are used to produce non-standard characters)
C-h C describes the current coding system
C-h v describes a variable: C-h v c-mode-map displays a keymap
for the c mode
special prefixes (input parameter, printing special characters)
C-u number another_command (give parameter) is used to give numeric parameters
to commands(lot of times it causes the command to repeat itself,
for instance C-u 20 C-p). Instead of C-u you can use ESC (Escape).
C-q (print spec. character) is used to type the 'characters' that
mean st. to emacs (e.g. if you want to inset Control into your file, use
= regular expressions. For the syntax see
info RET g (emacs)Regexps. See als RegExp examples
To match a newline type C-q C-j (it won't insert a symbol, instead it will make
a new line in the minibuffer).
. (dot) matches any character except a new line, c* = any number of occurrences of the
character c (greedy - the largest match possible), c*? (non-greedy, the smallest
match possible), c? matches 0 or 1 occurrence of c, \t matches a tabulator.
Reference the whole string: \&
The dth parentheses: \d (the substring matched by the regexp enclosed
in the d-th parentheses of the whole regexp; to match parens. use: \( and \) )
\s- matches any blank character; the string \s- behaves
as being only 1 character (special) => you don't need parens to use e.g.*: \s-*
During the search & replace operation, you can,
in the 'replace part' (replace string) refer to the string matched by the
search part by '\&'. E.g. to insert '!' at the end and beg. of all lines starting
with ';', you would issue (RET is Enter):
M-x replace-regexp RET
^;.*$ RET !\&! RET
Search&Replace for a tag:
(while (re-search-forward "\\(<\\(TAG\\)\\(.\\|\n\\)*?</\\2>\\)" nil t) (replace-match "X\\&X" t nil))
(We search for <TAG[.EOL]*</TAG> using minimal (x greedy) match)
See search (and replace).
non-English languages (Mule)
See "set-keyboard-coding-system" (use C-h f ), "set-buffer-file-coding-system",
help related to this topic (see help above), "iso-accents",
"set-language-environment", "buffer-file-coding-system" (variable), "coding-category-emacs-mule",
"mule-diag", "toggle-input-method". For Czech in Emacs see links.
key bindings can be changed for a session or permanently (by using the
M-x local-set-key prompts first for the key, then for the command
to be executed. There's also unset-key function.
M-x global-set-key is the same as above, but sets the key for
= recorded set of keystrokes.
C-x ( start recording a macro, finish it with
C-x e execute last macro
M-x apply-macro-to-region-lines = move to the beginning of
each line in the selection and execute the last macro.
C-x C-k C-x e)
name-last-kbd-macro give a name to the last macro
- insert-kbd-macro insert in buffer the definition of kbd macro NAME, as Lisp code.
Compares 2 or 3 files/buffers/directories. You can start it from the menu
(for example open the two files and use Tools->Compare->Two buffers).
In the ediff session there are few important buffers: the ones that
are being compared (named A and B [and C] and *Ediff Control Panel* which
appears as an independent window (you can also split the window into 3
buffers - 2 being compared and 1 for the control panel - issue C-x 2 twice).
The *Ediff Control Panel* is the place where you enter commands (and can
see help) - go into the buffer (click there, for instance) and try to type
Commands in the *Ediff Control Panel*:
j - jump to the first region which is different in the two compared buffers
n or SPC - jump to the next difference region
p or DEL - jump to the previous difference region
editing etc. (if you compare only two files/buffers/...)
a - copy the current region from A to B (replaces the region in B)
b - copy from A to B (as a, but the other way round)
! - recomputes the differences between the two regions (useful after you've
done some editing)
q - quit the Ediff session; the edited buffers are not closed, so you
can save them or whatever
and many more, for instance
## - skip the difference regions if they differ only in white spaces/newlines
Some major modes
hm--html-mode [XEmacs] - see 'homepage'
also a documentation)
html-mode [the XEmacs version is nicer]
html-helper-mode [?] - see html-helper-mode
Some minor modes
Note: the information in square brackets ([XEmacs], [emacs], [both]) indicates
under which of my Emacs it has been 'discovered' (the versions are > 20)
It's different from the html-mode in Emacs.
Pending-Delete minor mode (indicator PenDel) [XEmacs] - inserted text replaces
the selection (that's what we are normally accustomed to).But it seems to have an undesired influence on regions(if you select a region by mouse and than you scroll the screen, the region grows).
Font-Lock minor mode (indicator Font) [both] - highlighted syntax (text
auto-fill-mode [both] breaks line when it becomes too long (that
is, automatically inserts line-break [end-of-line], used in the Text major
abbrev-mode [both] enables automatic expansion of (static) abbreviations.
See abbreviations above.
- flyspell-mode automatically highlights misspelled words and offers possible corrections (click on the misspelled word by the middle mouse button).
- line-number-mode, column-number-mode - toggle on/off the display of the current line/column number in the mode line (above the
- recentf-mode - a menu for visiting files that
were operated on recently is maintained
- dispaly-time-mode displays current time in
the mode line
- pc-bindings-mode sets up certain key bindings for PC
compatibility: Delete (and its variants) delete forward instead of backward,
C-Backspace kills backward a word,
M-Backspace does undo,
Home and End move to beginning and end of line,
C-Home and C-End move to beginning and end of buffer,
C-Escape does list-buffers
- htmlize-buffer [both, must be downloaded
separately] transform text
into html (preserves visual appearance including font highlighting)
- iswitchb-mode [Emacs 21.3] - first M-x load-library RET iswitchb
RET . Fast switching of buffers.
- setnu-mode (download)
display line numbers to the left of lines
Show/hide tags: sgml-show-tags resp. sgml-hide-tags (I bind them to
the keys C-c + and C-c -).
- adds a menu to easily convert mac<>unix<>windows codings.
This feature enables you to search for function names etc. over multiple
create the tags table (e.g. to get tags for all .cc and .h files in the
current directory as well as its subdirs, run $>etags
-C */*.cc */*.h; it will create the file TAGS in the current
tell the Emacs to use the tags file you've just created: M-x visit-tags-table
(don't forget you can use the completition so you don't need to type the
whole command). It will prompt you for the file name.
use it! For example, to find a tag, use M-. tagname (for
instance M-. myFunction1). It enables you to do lot of cool things.
See the documentation.
- M-x visit-tags-table opens a tags table (necessary before tags are
- M-. tagname search for a tag called tagname
- M-* return to the place from which you started to search (try more
'.' is a special character (inside a string), you must escape it (use '\.'
Ebrowse is a tool for browsing a hierarchy of C++ classes, for programmers.
- Save a buffer as a MS DOS file: e.g. "C-x RET f
iso-latin-1-dos" (or -2- or any other)
Czech works correctly in my Emacs (on Mandrake Linux with support for Czech).
The setting is:
If there is an empty box instead of a letter, most likely
the system lacks a suitable font (applies to graphical displays). X server
must have a font that supports the emacs fontset, thus it's not enough that
the fontset is correctly set, there must also be a suitable font in the system.
Install the GNU Intlfonts package if it is not.
- Keyboard Coding System: nil
- Default Input Method: czech
- Current Language Environment( result of `set-language-environment'):
Czech (=> preferred coding system is Latin2)
- Enable Multibyte Characters: on
- Leim installed
End of line (Eol)
E.g. iso-8859-1-dos coding system specifies the DOS end-of-file conversion
DOS: Eol = carriage-return (CR). Unix: Eol = carriage-return linefeed sequences
See "inhibit-eol-conversion" (if "not", ^M is displayed for the DOS
The command `set-buffer-file-coding-system' may be used to set the coding (e.g.
iso-8859-2-dos) that will be subsequently used to store the file.
.emacs file below.
Indentation rules (Java, C ... modes)
See web how to customize
- Interactive customization:
- C-c C-s (c-show-syntactic-information) shows syntactic
context (symbol) of the current line.
- C-c C-o (c-set-offset) let's you set indentation for any
syntactic symbol (context), by default the one of the current line.
- Permanent customization: in .emacs file, e.g.:
(add-hook 'c-mode-common-hook ; Common across all languages (C, Java
'(lambda () (c-set-offset 'substatement-open 0) ) )
Reverse video by default
Normally you start emacs like this: emacs -rv for it to be in reverse
video (black background ...). How to set it as default?
- Linux: set it in .Xdefaults "emacs.reverseVideo:true"
- Windows: a) set it in Registry in HKEY_CURRENT_USER\SOFTWARE\GNU\Emacs -
add "emacs.reverseVideo" of the type REG_SZ (text variable)
and set it to "true". See the original advice
(HKEY_CURRENT_USER is preferable to HKEY_LOCAL_MACHINE: Emacs reads it
see faces.el: x-handle-reverse-video
see the variable inverse-video (setting it doesn't work?)
Solution 1 (which doesn't produce the same result as emacs -rv and is
worse, not reccomanded):
(defun x-handle-reverse-video (frame)
"Handle the reverse-video frame parameter and X resource.
`x-create-frame' does not handle this one."
(let* ((params (frame-parameters frame))
(bg (cdr (assq 'foreground-color params)))
(fg (cdr (assq 'background-color params))))
(list (cons 'foreground-color fg)
(cons 'background-color bg)))
(if (equal bg (cdr (assq 'border-color params)))
(list (cons 'border-color fg))))
(if (equal bg (cdr (assq 'mouse-color params)))
(list (cons 'mouse-color fg))))
(if (equal bg (cdr (assq 'cursor-color params)))
(list (cons 'cursor-color fg)))))))
(x-handle-reverse-video nil )
in *scratch* evaluate (x-list-fonts "*") (or (x-list-fonts
"*2") for iso8859-2) to see what fonts are available
Index of examples
Change your file into HTML:
transform '&': M-x replace-string RET & RET &
transform '<' : M-x replace-string RET < RET <
transform '>' : M-x replace-string RET > RET >
do whatever else you want
add break.lines: M-x replace-regexp RET $ RET <br>
insert the HTML header (<html><body>) at the very beginning
of the file (buffer)
insert the HTML footer (</body></html>) at the very end
of the file. Save it.
Replace Text In A Subdirectory
If you want to search & replace "foo" with "bar" in all your C files (which have names like "file.c" or "file.h"):
* M-x dired
* If you are using Gnu Emacs, you can mark a subtree of directories by
Note that Microsoft Windows comes with a default find.exe that comes first in PATH, and interferes with Cygwin's find.exe
* Mark the files you want to work on.
See "Mark" in menu, or C-h a
* Type 'Q' dired-do-query-replace
* Type in your replacements as regexps
Indent all C++ files
This shows how to run Emacs in batch mode against several files. See also ~/emacs/bin/unix/e-batchcompile for another example.
for i in *.[ch]* #.cpp, .h, .hxx, ...
fcommand="$fcommand --find-file $i"
emacs -nw --batch --load ~/tabify-c++-buffers.el $fcommand --execute '(progn (tabify-all-c++-buffers) (kill-emacs 0))'
For examples of customizing Emacs via its start-up file see examples under Links.
Important: after you've edited .emacs you must restart the
editor for all changes to take effect. If you call "evaluate-buffer"
or st. like that, only some changes do apply.
- contains the message shown on start-up.
- If 't' and you open a windows file you will see '^M' at the end of lines
otherwise you will see 'DOS' in the mode line.
;; Completition of a file path in a buffer (from Emacs
(autoload 'comint-dynamic-complete-filename "comint" "" t)
(global-set-key [S-tab] 'comint-dynamic-complete-filename)
;; Open recent file without mouse (from Emacs
(defun recentf-open-files-compl ()
(let* ((all-files recentf-list)
(tocpl (mapcar (function (lambda (x) (cons (file-name-nondirectory x) x))) all-files))
(prompt (append '("File name: ") tocpl))
(fname (completing-read (car prompt) (cdr prompt) nil nil)))
(find-file (cdr (assoc-ignore-representation fname tocpl)))))
Et puis un petit global-set-key qui va bien:
(global-set-key "\C-c r" 'recentf-open-files-compl)
;; Display available fonts (in font-menus.el)
(defun display-fonts ()
"Sorted display of all the fonts Emacs knows about."
(mapcar (lambda (font) (insert font "\n"))
(sort (x-list-fonts "*") 'string-lessp)))
or in *scratch* evaluate (x-list-fonts "*")
;; source of these ideas: http://www-stat.wharton.upenn.edu/~buja/STAT-540/.emacs
;;; current line to top of buffer:
;(global-set-key "\M-t" "\C-u0\C-l")
;;; bind F10 to man of topic at cursor location:
(global-set-key [(f10)] (lambda () (interactive) (manual-entry (current-word))))
Test equality: ;(if (equal x-display-name "castle5082.research.att.com:0.0") ...)
;; This removes unsightly ^M characters that would otherwise
;; appear in the output of java applications.
;; Change colors:
(list (cons 'foreground-color "black")))
- Get lot of info of current setting (eval as lisp expression):
(setq myparams (frame-parameters)) ; prints only part of the param. list;
;or: (setq myparams (current-frame-configuration))
; see also set-frame-configuration, (modify-frame-parameters frame alist)
;params: width, height, background-mode (=dark==inverse video||light), name ...
(frame-parameter nil 'background-mode) ;get value of backgr.mode
(modify-frame-parameters nil '((name . "Emacs: KUBA")))
This package helps C programmers by displaying information about the
arguments of C functions. It uses a C function database, which you can create
from man pages or from your own sources. See CmodeAddons
CEDET: Collection of Emacs Development Environment Tools
(smart code completition and more)
Emacs tutorial (fr)
Czech in Emacs - description
XEmacs homepage (see e.g. eLisp packages)
EmacsWiki - even more info about [X]Emacs, packages, the modes ...
Refcards.com - a collection of reference
cards in various formats, including Emacs and XEmacs (as well as ANSI C
Craigh F. - one of the guys
who worked with Emacs (lot of links, tools ...)
Emacs FAQ - a
long list (in XEmacs you can get also some FAQ via C-h F)
Elwood - the
Association of Lisp users homepage
Java DE (development environment)
for Emacs (JDEE)
Packages 4 Emacs
- Table editor for Emacs
(elisp package providing text based table creation and editing featur,
- preview-latex package
- ender your displayed LaTeX equations right into the editing window where they
- X-Symbol for WYSIWYG in Emacs
- display real characters for entities (LaTeX, HTML, BibTeX or TeXinfo)
- ! WebBot -
replace a text when saving; similar to webbot used in MS FrontPage;
timestamp, variable, navigation.
- beautifies html/xml code (indents, wraps lines etc)
- The Craft of Text Editing:
Emacs for the Modern World [Book, online]
Jakub Holy 2002 AD