[back to UNIX]

Emacs notes

The great GNU editor

Last change April 2, 2004 AD

Index

Introduction

        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.

Glossary

Buffer
'the basic editing unit'. Corresponds to one opened file (text). The command "kill (or delete) buffer" means "close the file being edited".
Region
Part of a buffer, e.g. selected by mouse (you know what I mean by "select text", right? Usually it's highlighted)
Rectangle
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)"
 

Commands

[top]
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 ...).

Text editing

[top]

Other

[top]

RegExp

= regular expressions. For the syntax see M-x info RET g (emacs)Regexps. See als RegExp examples (Another page).

    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 \) )
Note: \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).

Macros

= recorded set of keystrokes.

Tools

Ediff

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*:

Modes

[top]

Some major modes

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)

html-mode (both)

It's different from the html-mode in Emacs.
Show/hide tags: sgml-show-tags resp. sgml-hide-tags (I bind them to the keys C-c + and C-c -).

Useful packages


Programming tools

Tags

[top]
This feature enables you to search for function names etc. over multiple files.
  1. 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 dir)
  2. 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.
  3. 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.

eLisp notes

Ebrowse

Ebrowse is a tool for browsing a hierarchy of C++ classes, for programmers.


Languages and coding

Czech in Emacs:

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.

End of line (Eol)

E.g. iso-8859-1-dos coding system specifies the DOS end-of-file conversion type.
DOS: Eol = carriage-return (CR). Unix: Eol = carriage-return linefeed sequences (CRLF).
See "inhibit-eol-conversion" (if "not", ^M is displayed for the DOS Eol).
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.

Appearance

See also .emacs file below.

Indentation rules (Java, C ... modes)

See web how to customize indentation.

  1. Interactive customization:
  2. 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?

  1. Linux: set it in .Xdefaults "emacs.reverseVideo:true"
  2. 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 first).

see faces.el: x-handle-reverse-video 
see http://mail.gnu.org/archive/html/help-gnu-emacs/2002-10/msg00060.html
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."
(when t
(let* ((params (frame-parameters frame))
(bg (cdr (assq 'foreground-color params)))
(fg (cdr (assq 'background-color params))))
(modify-frame-parameters frame
(list (cons 'foreground-color fg)
(cons 'background-color bg)))
(if (equal bg (cdr (assq 'border-color params)))
(modify-frame-parameters frame
(list (cons 'border-color fg))))
(if (equal bg (cdr (assq 'mouse-color params)))
(modify-frame-parameters frame
(list (cons 'mouse-color fg))))
(if (equal bg (cdr (assq 'cursor-color params)))
(modify-frame-parameters frame
(list (cons 'cursor-color fg)))))))

(x-handle-reverse-video nil )

Emacs Fonts and Faces

See: html-font.el
in *scratch* evaluate (x-list-fonts "*") (or (x-list-fonts "*2") for iso8859-2) to see what fonts are available

 


Examples

[top]

Index of examples

Search & Replace

Change your file into HTML:
  1. transform '&': M-x replace-string RET  & RET &amp;
  2. transform '<' : M-x replace-string RET  < RET &lt;
  3. transform '>' : M-x replace-string RET  > RET &gt;
  4. do whatever else you want
  5. add break.lines: M-x replace-regexp RET  $ RET <br>
  6. insert the HTML header (<html><body>) at the very beginning of the file (buffer)
  7. 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
/home/path/
or
/home/path/*.c
* If you are using Gnu Emacs, you can mark a subtree of directories by
M-x find-dired
/home/path/
-name "*.[ch]"
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
dired-mark
* Type 'Q' dired-do-query-replace
* Type in your replacements as regexps

Batch mode

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, ...
do
fcommand="$fcommand --find-file $i"
done

emacs -nw --batch --load ~/tabify-c++-buffers.el $fcommand --execute '(progn (tabify-all-c++-buffers) (kill-emacs 0))'


.emacs files

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.

initial-scratch-message
contains the message shown on start-up.
inhibit-eol-conversion
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 fr)
(autoload 'comint-dynamic-complete-filename "comint" "" t)
(global-set-key [S-tab] 'comint-dynamic-complete-filename)
.

;; Open recent file without mouse (from Emacs fr)

(defun recentf-open-files-compl ()
(interactive)
(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)))))
recentf-open-files-compl
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."
(interactive)
(with-output-to-temp-buffer "*Fonts*"
(save-excursion
(set-buffer standard-output)
(mapcar (lambda (font) (insert font "\n"))
(sort (x-list-fonts "*") 'string-lessp)))
(print-help-return-message)))

or in *scratch* evaluate (x-list-fonts "*")

;; Various

;; 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.
(add-hook 'comint-output-filter-functions
'comint-strip-ctrl-m)


;; Change colors:
(modify-frame-parameters nil
(list (cons 'foreground-color "black")))


Various notes


Useful packages

CmodeAddons

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 at Wiki.


Links

[top]
Jakub Holy 2002 AD