UP | HOME

Andrey's Opinionated Emacs Guide

Table of Contents

1 Introduction

Emacs is the red pill

Now that we got this out of the way, note that there are many Emacs flavours but what follows generally refers only to the eldest and most thriving at present - GNU Emacs. If something below doesn't work for you, then you are probably using version older than 24.

Emacs works in terminal almost at full capacity (imagine that under the Windows command line!). In graphical mode you get better colouring, fonts, more key-sequences, ability to see images and pdf documents.

1.1 Glossary

1.1.1 User terminology

Emacs is so ancient that it predates currently popular graphical layouts. As such, it has terminology that may seem odd to poor contemporary users. Here's a little correspondence table for some of the basics:

Emacs land (I'll call it Lala land below) Rest of the world
frame program window
window pane
buffer file or something that may have text in it
kill cut
yank paste
region selection

Buffer may not be associated to file?! What is this planet, Pluke? Furthermore buffers may be currently hidden. You can also have same buffer visible in several windows or frames. Confusing? Priceless when you have to look simultaneously at several parts of one huge file. Emacs frames are actually tiling window managers but I'll have mercy and stop here.

1.1.2 Keys

Emacsers like keyboard shortcuts so much that they often sequence several in a row. Here's how to read some examples:

M-x tetris

(M stands for <Alt>, so press and hold <Alt>, press <x>, release these keys, type tetris and press <Enter> …by the way this is a real command, try it!)

C-x C-f PATH-TO-SOME-FILE

(C stands for <Ctrl>, so press and hold <Ctrl>, press <x>, release these keys, press and hold <Ctrl>, press <f>, release these keys, type path to some file or directory and then press <Enter>)

C-x v d PATH-TO-VERSION-CONTROLLED-FOLDER

(press and hold <Ctrl>, press <x>, relese these keys, press <v>, release, press <d>, release, type path to some directory and then hit <Enter>)

1.1.3 Modes

Each buffer is associated with something called major mode and may have a bunch of active minor modes. What is this thing, a Monad? No, save me from another "Grok Monads in 2365 easy steps" tutorial!

Modes are sets of specific rules and key-bindings active for some buffer. There is a read-only mode that forbids you editing, there are language aware modes for shell scripts / makefiles / python / java / c / scheme / clojure / haskell / agda / (insert your favourite niche language here) that give proper colouring, automatic indentation rules, special key-bindings for specific niceties… There are modes that grow in packages for reading or composing mail, creating presentations/books, version control, shells, DB prompts, composing/reading documentation, calendar, stack calculator, dictionaries, agendas and organizers, spreadsheets, browsing the internetz, collaborative editing, audio desktop for visually impaired, ASCII drawing, media collection managers and players, games, psychotherapist, controlling vibrators… to name a few. Oops, overdid it somewhere.

To get description of the major mode for the current buffer:

C-h m

To get all currently available key-bindings grouped by modes:

C-h b

1.2 First steps

If you are new to Emacs, invoke:

C-h t

to get the intro tutorial. It's really good and will save you headbanging. Unless you are a metal-head \m/

1.3 Execute code/settings on the fly

Unlike other environments and programs that pretend to be interactive, Emacs actually is. When you see a code snippet closed between parenthesis (well, it needs to be somewhat valid Elisp) like for example:

(message "Mozart is a great %s."
         (if (> (string-to-number (emacs-uptime "%H")) 3)
             "programmer"
           "composer"))

it can be immediately executed by placing the cursor just after the last closing paren and pressing:

C-x C-e

You can (re)set/(re)define functions, variables, whatever this way and it immediately comes into effect. This holds for everything you see below.

1.4 Settings

Settings usually reside in ~/.emacs.d/init.el This is where you can paste the tips from below and expect to be in effect on each Emacs invocation.

If you somehow manage to push settings that make your Emacs unusable (I would expect that this would take some talent) like for example:

(fset 'self-insert-command
      (lambda () "Print message instead of entering characters."
        (interactive)
        (message "HALLO?")))

just fix it with Vim. Got the joke? Nah, run Emacs like this:

emacs -Q

and it will skip loading the init.el file, giving you a chance to clean the mess.

2 Practical essentials

2.1 Run Emacs as daemon

Stock Emacs is quick and nimble (extensions are loaded only when/if demanded), you can use it just like Vim, start it to edit a file, then kill it. However, Emacs is so much more useful that many emacsers prefer to start it once and reuse this single instance for many tasks. So…

Forget religious prejudices, run Emacs as daemon and connect to this hell of a creature in graphics mode or from terminal or…both…several times. Here's how:

emacs --daemon

Now, to connect in graphical frame, invoke:

emacsclient -c

and/or in terminal:

emacsclient -t

The –daemon option is certainly available under GNU/Linux and BSDs. It might even work for BSD rip-off like MacOS but not under Windows. Nah. A trve programmer should resort to the latter two only under death threat or starvation anyway.

2.2 Cancel current action

Sometimes you start some action, Emacs asks you questions, or you're in a middle of incremental search or whatever. Suddenly, you come to realize that you don't want to continue and stop immediately:

C-g

This is the universal cancel/quit command. If one press doesn't end it, press it again. Normally 2-3 invocations are enough to take you out of whatever complicated action.

2.3 Commands, completion and hints

Emacs is all running on commands. Press whatever button, bam, some command is invoked. There are so many that one can remember just a percent of what there is. So how to find something useful? Should you use menus like in other programs? Possible, but what kind of menu would hold 3 000+ commands in coherent way… Call the devil by name:

M-x SOME-COMMAND-NAME

<Tab> can be used for completion. Furthermore, you can do:

(custom-set-variables
 '(icomplete-mode t))

and you'll get smart hints what commands are available while entering characters.

2.4 Additional packages

Emacs has tons of them. Your grandmother probably has written one or two too. Until recently there was no canonical way to distribute and install extensions though (I'm talking about GNU Emacs specifically, XEmacs has had this for a decade or so). If you are using version 24 or above, you are one lucky bastard! GNU Emacs is living to its promise to become full fledged operating system and now has a packet manager that can be invoked with:

M-x list-packages

To install package from there, position on the line of the desired one and press <I> (yes, capital). You can do this several times. When done shopping, press <x>, answer some prompts and you'll soon have these extensions in your ~/.emacs.d/elpa/ directory ready to be used.

By default only the GNU package repository is used but you can add others too:

(custom-set-variables
 '(package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
                      ("elpa" . "http://tromey.com/elpa/")
                      ("melpa" . "http://melpa.milkbox.net/packages/")
                      ("marmalade" .
                       "http://marmalade-repo.org/packages/"))))

2.5 Assign key bindings to commands

You're in love with some command but there is no key sequence to invoke it and you have to resort to:

M-x BELOVED-COMMAND

Here's how to assign global key-binding:

(define-key global-map (kbd "C-c z") 'BELOVED-COMMAND)

Et voilà. Now you'll have your beloved command available anywhere through <Ctrl>-<c> + <z>. Some mode may override this very binding though. It is recommended that user defined combinations should be <Ctrl>-<c> followed by single letter (may be capital too). To see what is the key combination sequence syntax accepted by the `kbd' function see:

C-h f edmacro-mode

What if you want to assign special key combination only for some specific mode? You'll generally have to know the name of the key map variable for this mode:

(define-key occur-mode-map "n" 'occur-next)

2.6 Undo/redo

Your last changes are rubbish? Undo them:

C-/

Then, they were actually not that bad. Let's redo… You are in for a surprise - there is no redo in Emacs. Wat?! The reason is that the undo command is so mighty that it can undo itself (pun intended). After you stop a series of undos (by hitting whatever other button), you can start again undo-ing and it will eventually undo your previous undos, which is roughly equivalent to redo1. This is a very powerful mechanism but a brain-twister for novices. Try out Undo Tree2, it visualizes the states between series of undos and changes and can even allow you travel in time for your edits.

3 General tips and tricks

3.1 Yes-No prompts, why type so much?

Often Emacs asks something and expects you to type yes or no followed by <Enter>. Here's how to change this and when faced with such existential question be able to just press <y> or <n> instead:

(fset 'yes-or-no-p 'y-or-n-p)

3.2 Region

While you can do selection with mouse (and <Shift> in combination with the arrows) as years of brainwashing have taught us, Emacs allows some more. Press:

C-<SPC>

where you'd like to start a selection and then move around to where selection should end. Incremental search is allowed! Not only this, if you think that the initial point of selection needs to change, invoke:

C-x C-x

and cursor will move to the initial selection point, allowing you to refine it (again, searching is OK), while selection region is still active. In fact, you can jump like this between the selection ends and refine them as many times as you want. Neat.

3.3 Markers

Moving around selection ends is dandy and is result of a more general mechanism. Enter marks. Pressing:

C-<SPC> C-<SPC>

marks current cursor position as special. If you now move around the buffer, pressing:

C-u C-<SPC>

will move you back to the special position. You can keep pressing C-u C-<SPC> and it will cycle through all such special positions that have been marked at some point in the buffer3. Some commands automatically mark current position so don't be surprised if such cycling brings you to places where search or selection has been invoked.

3.4 Operations on selection/region

Lesser programs normally allow two actions on selection - copying and deletion. Emacs is not as boring. Beside the obvious, when a region is selected:

  • all sorts of string/regex replace work only on this region
  • undo acts only on the region

The last one is an Easter Egg. Think how useful it can be, undoing changes just in some selection. Here (and in the manual) is an overview of what more is supported.

3.5 Work with directories

Dired4 is the most capable file manager I've encountered. To start it:

C-x d PATH-TO-SOME-DIRECTORY

Now hit:

C-h m

to get summary of what it can do.

3.6 Fuzzy matching when navigating the file system

Sounds nice? Add this to init.el:

(custom-set-variables
 '(ido-enable-flex-matching t)
 '(ido-mode 'both)
 '(ido-use-virtual-buffers t))

If you now invoke:

C-x C-f

you'll be able to navigate directories and files of the current folder by entering parts of their name. To go directory up, <Backspace> would suffice. To open currently shown directory, press C-d. To create a new file, type its desired name and press C-j.

There's more magic. Using the traditional way to switch to a buffer:

C-x b

you'll get matching by parts of name and may also get suggestions for files that have been opened in previous sessions.

3.7 Remote network and sudo access

Why reside to primitive shell & ssh to peek/edit a file on some remote server? You can do it directly from Emacs:

C-x C-f /ssh:andrey@some-server:/path/to/some/file/or/folder <Enter> (enter password when/if prompted)

Some servers may have fancy colourful prompts that get in the way of the default settings though. Here's something that may work for you:

(custom-set-variables
 '(tramp-shell-prompt-pattern
   "\\(?:^\\|
\\)[^]#$%>\n]*#?[]#$%>] *\\(;?\\[[0-9;]*[a-zA-Z] *\\)*"))

Note that there are a couple of non-printing characters in the ugly regular expression above. Instead of new line, there is:

C-q C-m

Need to quickly edit some system file? Don't touch the shell, Emacs started by your user is just enough:

C-x C-f /sudo:root@localhost:/etc/fstab <Enter> (enter password when/if prompted)

TRAMP4 is a killer. It supports plethora of protocols. For more information invoke/type:

C-h i m TRAMP

3.8 Backup and file versions

By default Emacs creates backups for each edited file and places them in the same directory adding tilde to the original file name. This might be mildly annoying if you are Chuck Norris. There is an easy way to forbid this but I have a better proposition. How about saving all backups in a single place?

(setq backup-directory-alist
      `(("." . ,(concat user-emacs-directory "backup/")))
      tramp-backup-directory-alist backup-directory-alist)

While at it, how about some primitive form of version control for each file you edit with Emacs?

(custom-set-variables
 '(version-control t))

With the two above spells, all backup files are collected to ~/.emacs.d/backup/ and some number of old versions is kept. Borked some critical file somewhere and regret it? Do not panic! Go to the backup folder (it may be in root.emacs.d/backup/ if edited as root, including through TRAMP) and find some stable older version. This has saved my ass not once or twice. This backup/version scheme doesn't apply to files that are under "official" version control system. Guess what, you don't need it there anyway.

3.9 Manage GnuPG encrypted files

For this you'll need the GNU Privacy Guard program. Open new file like example.gpg (note the file extension). Write something there and save it. You'll be asked for symmetrical encryption password. Enter such, et voilà, your file is now encrypted. When attempting to open encrypted file with .gpg extension from Emacs, you'll be asked for password. Magic.

3.10 Don't ask for sudo or ssh passwords

Create a file ~/.authinfo.gpg and paste there something like:

machine localhost port sudo login root password very-very-secret
machine test-server port ssh login andrey password very-secret

Save this file (entering password for encryption). Now, when you attempt to ssh (to test-server) or sudo directly from Emacs as explained above, you'll be asked for the .authinfo.gpg password once and from there on (for this Emacs session), the passwords listed there will be automatically used when you try to access the respective resources.

3.11 Gnus for mail and news

Every program attempts to expand until it can read mail. – Jamie Zawinski

There are a lot of ways to manage mail within Emacs. I use the mail/news kitchen sink Gnus4. Here's its glory documented (it would be too much to give opinionated guide):

C-h i m Gnus

Here are my current mail settings. To summarize, it attaches to my gmail and work mail accounts (through imap) and also to the gmane/gwene news/rss server (I try to follow about 100 mailing lists and blogs). There are heuristics to guess default mail sender/server (yeah, I frequently send spam from both), workarounds for the flaky Exchange server, integration with the fortune(-mod) program (where all stupid quotes on the back of my mails come from), automatic spell-checking and line wrapping (don't you hate when mail text goes out of your wide screen?), integration with The Insidious Big Brother Database (BBDB)2 for managing contacts, automatic checking for new messages for selected (mail)boxes and notifications. For notifications I'm using notify.el2.

Wouldn't want to type passwords every now and then when dealing with mail accounts? authinfo(.gpg) to the rescue again!

machine gmail port 993 login andrey password very-very-secret
machine smtp.gmail.com port 587 login andrey password very-very-secret

3.12 Shell, terminal, console, whatever you call it

Tired of unable to search or copy properly inside the terminal program? Emacsers like shells (and don't start them on REPLs) so much that have tons of them and at least 3 somewhat differing are available by default. The first one integrates nicely with Elisp:

M-x eshell

The next one is an almost 1:1 wrapper for systems that provide Unix like terminals:

M-x ansi-term

Lastly, this is good for systems with somewhat dumb command line:

M-x shell

All of them have advantages and disadvantages to one another but it will be too much to go into details. The package manager offers some more.

3.13 Microsoft Windows (tm)

Death threat? Starvation? Feel for you, sis. Here is something to ease your pain:

M-x doctor

Emacs is generally good enough to make you forget what iron you are running upon. Until you reach for outside programs. To make your windows experience in general more acceptable, use Cygwin. It gives you bash terminal and package manager to the ever useful GNU tools and other ported stuff.

To make Emacs aware of the cygwin environment and prefer it instead of the crippled windows ecosystem, install cygwin-mount2 and then put this in your init.el:

(defconst +win-path+ "C:/" "Windows root path.")

;;; Cygwin
(let ((cygwin-dir (concat +win-path+ "cygwin/bin")))
  (when (file-exists-p cygwin-dir)
    (setq shell-file-name "bash"
          explicit-shell-file-name "bash")
    (setenv "SHELL" shell-file-name)
    (setenv "CYGWIN" "nodosfilewarning")

    (when (require 'cygwin-mount nil t)
      (cygwin-mount-activate)
      (setq w32shell-cygwin-bin cygwin-dir))))

This assumes that C:\cygwin is used for cygwin root and C:\cygwin\bin holds the binaries.

Dealing with what path is taken as home directory under Windows is a headache. And you need this to know where init.el should reside. I remotely remember setting HOME variable in some MyComputer settings (also modifying the PATH one to prefer cygwin's paths).

4 Programming tips and tricks

4.1 Grep on steroids

Like other GNU tools, grep has nice integration within Emacs. I most frequently need recursive searching within some directory and its sub-directories. Here's how to do it and get hyperlinks to the results:

M-x rgrep

On the second step you'll be asked what files the search should be constrained upon. Glob patterns are accepted like:

*.cpp *.h

Note that <SPC> invokes completion here. To actually insert a space character, "quote" it with C-q.

4.2 Edit grep results in place

Jumping to result locations is not enough for you? You, spoiled brat! Try wgrep2:

M-x wgrep-change-to-wgrep-mode

while in grep buffer. Now you can edit in place result lines (regex replacing M-% is intelligently acting only over the actual text and skipping file/line information). After you're done:

C-x C-s

Now all files that have had their lines edited are opened with your changes there waiting to be saved. If it happens to be a lot of files and you're confident that you want all these changes saved, use IBuffer4:

M-x ibuffer

Now all current Emacs buffer are listed. How convenient. Now hit:

* u

and all buffers with unsaved changes are marked. Now press capital <S> to save them all. Job done. As all within Lala land, IBuffer is full of tricks and neat features, I even have it bound to:

C-x C-b

instead the default `list-buffers'4.

4.3 Occur

Wanna grep something within the current buffer? It may not be a file but even then, why bother with grep? Try:

M-x occur

You'll again get a list of results and can jump between locations. Handy for quick indexes of whatever search pattern. You can even invoke occur over occur buffer! If using recent version of GNU Emacs, you can edit results in place pressing <e>.

4.4 If it moves - compile

Welcome 20 years back! You can compile through Emacs and get errors/warnings as hyperlinks to the offending locations:

M-x compile

You're asked for a compile command, WTF?! Here's what I usually type:

cd ~/branches/trunk/release && make -j4

…now get a cup of tea. Or if you're a minimalist like me and use Emacs as an OS - do whatever you like because your computer is as responsive as an idle machine of your colleagues.

You may keep the compilation buffer around even after compilation has finished. Within it, you can just press <g> to recompile.

4.5 Find file in project

Well, get find-file-in-project2 and then bind the same-named command to a key like:

(define-key global-map "\C-cf" 'find-file-in-project)

Now hit:

C-c f

And you'll be able to select a file. If you have ido-mode enabled for files, you'll get flex matching. Note that the GNU find command is expected, which means that under Windows, you'll probably need the Cygwin environment with the settings mentioned above.

Here's a sample customization for C++ project:

(setq-default
 ffip-project-file ".emacs-project"
 ffip-patterns (nconc '("*.cpp" "*.h" "*.hpp" "*.c")
                      ffip-patterns)
 ffip-find-options
 "-not -regex \".*\\(debug\\|release\\|svn\\|git\\).*\""
 ffip-limit 4096)

This makes directories that have file named .emacs-project root project folders. Also C-like sources are added to list of files to offer. Some source control and build directories are skipped from indexing and maximum amount of files offered is set to 4096.

I know this is nothing new for you, IDE cry-babies. But can we generalize a bit? I like this recursive locating of files, why do it just for projects? Let's get hands dirty then:

(eval-after-load "find-file-in-project"
  '(progn
     (defun my-ffip-project-root-function ()
       "Check for `ffip-project-file' and if no such, \
return current directory."
       (let ((project-directory
              (if (listp ffip-project-file)
                  (some (apply-partially 'locate-dominating-file
                                         default-directory)
                        ffip-project-file)
                (locate-dominating-file default-directory
                                        ffip-project-file))))
         (or project-directory default-directory)))

     (setq-default
      ffip-project-root-function 'my-ffip-project-root-function)))

With these magic incantations we get the expected behaviour when within a project directory tree. When not, current directory is treated like a root project directory, file name search will be done there and within all sub-folders as well. Sweet.

4.6 Source control

Are you tired of the different command line interfaces of the many version control systems that you use? Even worse if you use GUIs. Emacs provides unified interface to some of the widely used VCSes (and of course has additional packages for less popular ones). To see what I'm talking about:

C-x v d PATH-TO-FOLDER-UNDER-VERSION-CONTROL

Emacs also automatically detects if a file that you've opened is under some version control and gives you key-bindings to view diff of uncommitted changes, history of the file (and you can look at each individual diff), blame (annotate) and travel in time for lines functionality and more. To see what is available:

C-x v C-h

And these are commands that by default have been given keys. To see all available:

M-x vc-<Tab>

4.6.1 Magnificent git

If you happen to use Git, check out Magit2. It's a nice interface to some of the most often used Git commands. My favourite feature is the ability to iterate through the diff hunks and selectively choose which ones to stage, unstage or revert (works not just for hunks but for arbitrary marked region!). Makes partial file commits trivial.

4.7 Interactive diff and merging

Have you ever had two chunks of text with rare differences that you need to find, needle in a haystack? In Lala land you would yank each text in separate buffer and invoke:

M-x ediff-buffers

selecting names of the buffers to compare. Now you can jump difference by difference and throw them between buffers doing impromptu merging if you want. Ediff is really powerful and handy.

Could we use this to resolve conflicts under version control? Yes! If a file is in conflict state, open it and:

M-x smerge-ediff

4.8 Regular expressions

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. – Jamie Zawinski

Not surprisingly, regexes are supported all over the place. There are some differences to the popular PCRE style and if you're serious about it, you should read the appropriate sections in the great Emacs and Elisp info pages.

I would like to open your eyes about some gem however. If you invoke this in some buffer:

M-x regexp-builder

you'll be able to interactively build regular expression and on each character entered, matching terms will be highlighted in the initial buffer. Provided the regex is somewhat correct.

4.9 GDB

Remember Visual Studio? Aaaarrrrgh, the horror! Well, you can get some of it integrating with GNU Debugger:

(custom-set-variables
 '(gdb-many-windows t))

Now invoke (it will be nice if you open the destination directory first):

M-x gdb

You'll be asked how to run it, append the path of the desired executable and rock!

4.10 Semantic

Recently Emacs is acquiring infrastructure for more unified code awareness in the face of the CEDET utilities. Here are some customizations that give basic niceties like echoing information about object under cursor, colouring local variables instances, highlighting current function:

(eval-after-load "semantic"
   '(progn
      (add-to-list 'semantic-default-submodes
                   'global-semantic-decoration-mode)
      (add-to-list 'semantic-default-submodes
                   'global-semantic-idle-summary-mode)
      (add-to-list 'semantic-default-submodes
                   'global-semantic-idle-local-symbol-highlight-mode)
      (add-to-list 'semantic-default-submodes
                   'global-semantic-mru-bookmark-mode)))

To activate:

M-x semantic

4.11 Completion

There are many packages that deal with code (and not only) completion, but none are particularly good at C++. I use auto-complete2 which is for completion of anything, not just code. Here is some setup:

(when (ignore-errors (require 'auto-complete-config nil t))
  (ac-config-default)
  (ac-flyspell-workaround)

  (eval-after-load "semantic"
    '(setq-default ac-sources
                   (cons 'ac-source-semantic ac-sources))))

On the pros side, you'll get particularly useful suggestions for symbols typed anywhere in the currently opened buffers. Long function/variable names become non-issue.

4.12 General coding IDE

I'm sure your grannies have used IDEs all their life. There is a package called Emacs Code Browser (ECB)2 that may give you a breeze of life-supporting IDE familiarity. Furthermore, imagine how cool it is to have IDE working in terminal…yes, it does, just like rest of Emacs. Here are some settings for it (some of them are necessary to get it started at all):

(custom-set-variables
 '(ecb-options-version "2.40"))

(eval-after-load "ecb"
  `(let ((prog-path ,(concat +home-path+ "Programs"))) ; set folder where you store projects
     (ecb-add-source-path prog-path prog-path t))) ; not really important

Now fire it:

M-x ecb-activate

4.13 C++

Emacs doesn't come with shining C/C++ support, sorry. Here are a few ways to get something. Firstly some general customization:

(custom-set-variables
 '(c-default-style '((java-mode . "java")
                     (awk-mode . "awk")
                     (other . "stroustrup")))
 '(indent-tabs-mode nil)
 '(which-function-mode t))

It sets some automatic indent styles for C-like languages. Uses spaces instead of tabs and shows the name of function that the cursor is currently placed in the mode-line.

4.13.1 Jump to definitions

Emacs comes with a separate binary ebrowse4 that can annotate multiple C/C++ source files and create some form of DB which can be used for getting different kind of information for the indexed sources. Here's a little wrapper shell script that should be placed somewhere on your PATH (usr/local/bin preferably), named ebrowse-c++ and made executable:

#!/bin/sh

DIR=$1

if [ ! "$DIR" = "" ]; then
    cd $DIR
fi

find . -regex ".*\.\(hpp\|cpp\|h\|c\)" \
    -not -regex ".*\(debug\|release\|svn\|git\).*" | ebrowse

Again it needs the GNU find program. To make use of it:

(when (executable-find "ebrowse-c++")
  (defun my-ebrowse-refresh (arg)
    "Refresh existing ebrowse db or if *Tree* buffer is missing \
or ARG is non nil - locate project file for current directory."
    (interactive "P")
    (save-excursion
      (if (and (not arg) (ignore-errors (set-buffer "*Tree*")))
          (let ((ebrowse-file buffer-file-name))
            (call-process "ebrowse-c++")
            (kill-buffer)
            (find-file-noselect ebrowse-file))
        (let ((project-dir (locate-dominating-file default-directory
                                                   ".emacs-project")))
          (if project-dir
              (save-excursion
                (call-process "ebrowse-c++" nil nil nil project-dir)
                (find-file-noselect (concat project-dir
                                            "BROWSE")))))))))

Now, while in some project directory (again assuming .emacs-project is present in the root project folder):

M-x my-ebrowse-refresh

It loads/refreshes the DB for the current project and opens it in background. To jump over function/variable definition:

C-c C-m f NAME-OF-SOME-FUNCTION-OR-METHOD-OR-MEMBER

Don't worry, you'll get completion. To jump to declaration:

C-c C-m F NAME-OF-SOME-FUNCTION-OR-METHOD-OR-MEMBER

To see more unlocked functionality:

C-c C-m C-h

Unfortunately you can't use two ebrowse DBs at a time. To load another one (while being in another .emacs-project governed location):

C-u M-x my-ebrowse-refresh

5 Documentation

Emacs documentation is the most complete and easily accessible set of resources I have seen (only second to Lisp Machines's Genera operating systems but they are 20 years in the past and as one may observe, technology is stubbornly regressing in this along other aspects since then).

This is the only environment that has enabled me in a day learn relevant chunk of language and easily add useful functionality without internet access. And do this with pleasure and still have hair on my head. It's that good.

5.1 Info

To invoke the info reader4:

C-h i

Here's access to the info manuals on your system. Within it, you can jump to the Emacs documentation:

m Emacs

the Elisp documentation is top notch too:

m Elisp

Mostly Dick Stallman has initiated exceptional job, enjoy!

5.2 Browse system manuals

You can read system's man pages within Emacs too:

M-x woman

now choose with completion the desired manual. Woman is not always reliable though. In case it doesn't work, non-imaginatively try:

M-x man

5.3 Elisp live documentation

Not only is Emacs interactive, it's self-documenting! No need for doxygen or other such offline stuff. Once you declare function, macro, variable, constant or mode and document it properly with a docstring, for example:

(defmacro define-keys (mode &rest keys)
  "Define cascade of keys for a MODE.
KEYS is alternating key-value list."
  `(progn ,@(let ((res nil))
              (while keys
                (push `(define-key ,mode ,(car keys) ,(cadr keys))
                      res)
                (setq keys (cddr keys)))
              (nreverse res))))

The documentation becomes immediately available to the doc system for retrieval:

C-h f define-keys

This is for functions, macros and modes. For variables use:

C-h v SOME-VARIABLE-NAME

Completion should ease you in both cases.

If object is loaded from file, not only is documentation available, but you'll get hyperlink to the source. Invaluable way to explore the running system.

5.4 Apropos

The above is useful when you have vague idea about the first symbols, which normally denote package. If this is not the case, there is even better search for random Emacs objects:

M-x apropos

5.5 Discover available long key-binding sequences by their first part

I always have problems recalling what register commands there are. But I remember they start with:

C-x r

Can Emacs help me? Rhetorical! Add C-h to the end of some sequence and you'll get all command bindings starting this way:

C-x r C-h

5.6 Where is some command?

C-h b

lists you all available key-bindings for the current buffer. If you are lazy to invoke a search there to find some elusive command:

C-h w SOME-COMMAND-NAME

to see if SOME-COMMAND-NAME is currently available through some key combination.

5.7 In short

C-h C-h

6 Random

6.1 Org mode

I rarely write documents and presentations. When I do, I use Org mode. – Mahatma Gandhi

There is another wonderful thing that comes with Emacs known as Org mode. It's often quoted as prime reason for people starting to use Emacs, even former Vimmers. Here's what's written on their site:

"Org mode is for keeping notes, maintaining TODO lists, doing project planning, and authoring with a fast and effective plain-text system."

This guide is all done in Org mode and then exported to HTML (one of many available formats).

6.1.1 Basic usage

To launch Org mode either:

M-x org-mode

for existing buffer, or name your file with an .org extension.

You'll go a long way even with the minimum - number of stars at the beginning of line signifies heading in the document hierarchy. The less stars - the more important the heading. Here's a random Org rambling:

* This is important header

./img/funny-image.jpg

** This is sub-header

Here's a cool report:

|-------+-------------|
| month | revenue     |
|-------+-------------|
|     1 | 0           |
|     2 | 6 000       |
|     3 | - 1 000 000 |
|     4 |             |
|-------+-------------|

*** This is sub-sub-header (maybe even a bullet)

Outsourcing has betrayed us link

 # this is a comment, won't be exported

** Another sub-header

Some rescue plan.

****** This is so low, I don't even know how will be exported
****** At least there are two of us

You can press:

C-c C-e

and choose some format to export to.

You can easily reorder headers at the same level (reordering all sub-headers and content as well) with <Alt>+<Shift>+<Up> and <Alt>+<Shift>+<Down>, change nesting level of a header hierarchy with <Alt>+<Shift>+<Left> and <Alt>+<Shift>+<Right>, collapse/show different levels with <Shift>+<Tab> and so on. Have a look at the site or the manuals for more.

6.1.2 Tables

Org tables rock! Here's how to start one:

| heading1 | heading2 | bla |

Now press <Tab> and new row will be added. <Tab> now moves over the fields and automatically resizes the table if longer text is entered somewhere. To insert row separator enter:

|-

in the beginning of line and press <Tab>, it will expand as much as necessary. You can create tables from blocks of text that look like one (like coma or whitespace separated rows of values) with

M-x org-table-create-or-convert-from-region

You can do sorting on columns, calculations on rows or columns or parts of them and more - it has spreadsheet functionality. Very handy for quick dealing with formatted program output.

6.1.3 Lightening fast documents

Have to write some official document? Want to concentrate on content and structure rather than fonts, colours, headings and what not? Write an Org mode file and export it to PDF (through LaTeX)! It will take care of all details, add table of content even.

Setting up fancy header page may be a little work though. Here's a little example how to make one with some picture logo and integrate it within an Org document. I have added some optional information like author, title and export type as well. Tweak it however you want.

6.2 Vim

Can Vim emulate Emacs? Forget it! But the other way works. There are many packages that give some sort of Vim emulation. If you are such an insert/escape addict but still want the power of symbolic universe, you might try one of them. The current poster child is Evil2 and seems praised as the most potent emulation not just in Lala land.

By the way, I thought editor wars finished when Debian's Vim maintainer switched to Emacs.

7 Emacs for black belts

7.1 Keyboard macros

Being mainly keyboard driven, Emacs offers one simple yet extremely powerful facility for automation - keyboard macros. The idea is capturing multiple series of keystrokes and then automatically executing them on demand. Here's how to start one:

C-x (

Now do a series of actions that you'd like to automate. Be careful, take your time and try to think of a clean way to achieve the first round of what you'd like to do. When you are ready:

C-x )

To execute what you've just captured:

C-x e

To execute it 42 times:

C-u 42 C-x e

This C-u NUMBER combination, known as prefix/universal argument, is a way to pass additional argument to many commands and most often causes them to be executed number of times.

Note that you don't have to execute the captured macro immediately. It stays available for execution until you define another one. To cancel capture while still recording, do the usual:

C-g

It will probably take you some practice to get used to recording composable series of actions, see here for example. Once you master it, you'll thank me for life. Imagine the possibilities, jump to some e-mail buffer, copy something, switch to a shell buffer, write some command, paste what you copied and execute, copy last line of the result, go back to the prompt, switch to some result buffer, paste there and add new line, then go back to the e-mail buffer and move to the next line. Now execute this automatically 100 times.

7.2 Emacs Lisp

I have to tell you that probably of all the languages I've used, definitely, Emacs Lisp has been the most fun. – John Wiegley

I wonder if after all this stuff, you have decided for yourself what Emacs actually is. Is it an advanced editor, an integrated development environment, an operating system, a kitchen sink or maybe a Death Star? Time has come to tell you the truth. Luke, I'm your…

Emacs at its essence is an interpreter for a Lisp dialect - Emacs Lisp (Elisp). All magic interactivity and extensibility is a byproduct of this. All parenthesized settings and code snippets from above are actually Elisp program pieces. Here's a nice built-in introduction:

C-h i m Emacs Lisp Intro

I won't go into details how cool Lisp-like languages are, there is a lot of material out there. I won't tell you much about Elisp either for the built-in reference is outstanding:

C-h i m Elisp

However, I will tell you about one of my aha-moments and some practical consequences. While Elisp is becoming quite an adequate lisp5, it really shines at…

7.2.1 Text superpowers

I've come to appreciate that Elisp is the best programming language for text processing. No joke, it's because Emacs has a lot of primitives for dealing with text and buffers, after all, one of its specialties is text editing, doh. There is another thing though, I told you that each key stroke/sequence invokes some function…

7.2.2 Text processing automation for dummies

While combining built-in functionality with additional packages and especially keyboard macros can get you beyond what most people would imagine possible for a human, sometimes you may stumble onto something that requires some nastier text processing and probably editing and/or generating hundreds of files. A general recipe how to write such programs in Elisp follows.

1. Do by hand what you'd like to do.  Probably multiple times, till
   you extract a more or less clean general procedure.

2. Having concrete series of actions, for each of them check what
   function lies beneath.  This will help:

   C-h k

   followed by key-sequence will show what command is invoked.

3. (Optional) Jump to the definitions of the above commands and have a
   look at their code.  Not only will you see how idiomatic Elisp
   looks like, but you may also detect some more primitive function
   used that may fit your bill.

4. Use these functions in order to form your program.

So code literally follows the editing process, ingenious! Step 3 is very educational, manifest of free (as in speech) software, though with time you may need it less often.

This is a start. If you become serious practitioner, you'll randomly start at step 4 which is basically…programming. But you'll appreciate the availability of the other steps for true Emacsers never cease to learn. Happy lisping!

8 Where to go next?

Emacs is what you make of it. I don't know of other environment as malleable as it is. Play with it, make it comfortable. It's defaults are not set in stones, make them suit your tasks. Unlike most other tools, learning Emacs6 can pay off spectacularly, especially in terms of productivity. As with most other quality things in life, if you persist, it will deliver.

8.1 Random resources

The trash bin of Emacs resources - EmacsWiki.

Emacs rocks, literally.

Planet Emacsen is an aggregator of many related blogs.

Looking at other people settings is traditional for novices (and not only). You can always peek at mine as a source of mastery and inspiration.

Footnotes:

1

If you made it through the last sentence, require your award

2

Available through M-x list-packages

3

Well, there is a maximum number of marks that can be remembered for a buffer at time (16 by default). More general mechanism is offered by registers.

4

This is a built-in extension

5

Some people even write web servers nowadays

6

Realistically, no mortal can learn Emacs in its entirety

Author: Andrey Kotlarski

Created: 2018-07-30 пн 05:04

Emacs 26.1 (Org mode 9.1.9)

Validate