2009-02-25

helpful emacs

Thus spoke the Emacs manual:
Emacs is the extensible, customizable, self-documenting real-time display editor.
And it is true - emacs documents itself and there is help available all around. I only fully appreciated the extend of this after years of using emacs, so I hope this will help other - I hope others will forgive me my long ignorance... Anyway, even though this is an impressive list, it's not complete. It's just the list that I have used at some stage.

Many of the help options have key bindings (shortcuts) that start with C-h (Ctrl+h).

So, let's start with some 'help' about emacs itself:

  • Get a list of all the new features in the latest emacs release: press C-h n; if your more interested in the known problems, press C-h C-p
  • Read the emacs reference manual: press C-h r, run the emacs tutorial with C-h t or read the emacs FAQ with C-h C-f.
Then, there are a number of help options to get information about key bindings (keyboard shortcuts):
  • What does this key do? Press C-h k and the key (combination) you are interested in. For example, suppose you want to know want C-a (Ctrl-a) does in emacs. Press C-h k and then C-a, emacs will open a little buffer with a short blurb that tells you that it means 'move-to-beginning-of-line'; if instead of C-h k you press C-h K (capital K), you get the emacs manual entry instead;
  • If you know what the command is, but wonder where the key binding is, you can use C-h w COMMAND; so, C-h w isearch-forward-regex will give you C-M-s;
  • You can also get a list of all current key bindings with C-h b.
There are also ways to get information about Lisp functions and variables/constants:
  • Maybe you find to find about a Lisp-function, but you only remember its name was someting with 'foo'. Press C-h a; then type foo and you get a list of all commands with 'foo'.
  • If you need help on a specific Elisp function, press C-h f; it defaults to the function the cursor is currently on (if any).

    This also works with your own functions if you add a 'docstring';

     (defun say-hello ()
        "here's my docstring: this function says 'hello' in the echo area"
        (interactive)
        (message (concat "Hello, " (user-login-name) "!")))
    Now, if you look for information about say-hello, emacs will give you its docstring.

    There's also a variant C-h F (capital F), which looks up the information for a function in the emacs-manual; note that it would have been more useful to use the ELisp-manual instead, if that is installed.

  • Similarly, you can information about Elisp variables and constants with C-h v (with C-h V to get information from the Emacs manual).
Programmers might also want to look for manpages (M-x man) and/or infopages (M-x info-apropos). That last function unfortunately searches all infopages, and it seems not cache any of it. Another rich source of documentations are the various describe- functions:
  • describe-face will give you information about a 'face' (which is, the font/color/decoration of a character on the screen). This is useful when there is something in your buffer with a funny color, and you wonder why it has that color;
  • describe-mode gives a lot of information about the current major and minor modes, any keybinding etc.;
  • There are describe- functions that may be useful; just press M-x describe-TAB to see what's available.

2009-02-18

transparent emacs

It may not be so useful, but emacs23 allows you to manipulate the transparency of your emacs frames (windows). If you use Windows or X with a compositing window manager on X, you can make your windows transparent. Examples of compositing window managers are Compiz/Beryl and even the good-old Metacity (gconftool-2 -s '/apps/metacity/general/compositing_manager' --type bool true).

The following code for your .emacs makes it easy to set transparency from within emacs:

(defun djcb-opacity-modify (&optional dec)
  "modify the transparency of the emacs frame; if DEC is t,
    decrease the transparency, otherwise increase it in 10%-steps"
  (let* ((alpha-or-nil (frame-parameter nil 'alpha)) ; nil before setting
          (oldalpha (if alpha-or-nil alpha-or-nil 100))
          (newalpha (if dec (- oldalpha 10) (+ oldalpha 10))))
    (when (and (>= newalpha frame-alpha-lower-limit) (<= newalpha 100))
      (modify-frame-parameters nil (list (cons 'alpha newalpha))))))

 ;; C-8 will increase opacity (== decrease transparency)
 ;; C-9 will decrease opacity (== increase transparency
 ;; C-0 will returns the state to normal
(global-set-key (kbd "C-8") '(lambda()(interactive)(djcb-opacity-modify)))
(global-set-key (kbd "C-9") '(lambda()(interactive)(djcb-opacity-modify t)))
(global-set-key (kbd "C-0") '(lambda()(interactive)
                               (modify-frame-parameters nil `((alpha . 100)))))
Now, you can make make emacs more transparent (less opaque) by pressing C-9, while C-8 has the opposite effect. C-0 brings us back to normality.

Admittedly, window transparency is a classical solution-looking-for-a-problem. But let that not stop us from using it -- now we can watch full-screen movies while still using emacs. That, my friends, is progress.

2009-02-11

emacs --daemon

Emacs23 has gone in pre-test. As I mentioned before, there are a lot of improvements, and there's little reason not to migrate to this new version. YMMV, of course. As always, you can see all the news with C-h n (Ctrl-H and then n) -- but obviously you need emacs 23 to see the news for emacs 23.

There's even an easter egg, as Giorgos Keramidas notes: M-x butterfly, inspired by xkcd...

A more useful new feature that I'll discuss here, is emacs --daemon. Since many versions, you can set up emacs as an emacs-server. The idea is that you start one emacs instance (the 'server'), and you can then use emacsclient to quickly pop up a new emacs-frame (window). This new frame is not a new emacs instance, it's just a new frame (window) for the already-running emacs. The nice thing is that emacsclient is very quick - it doesn't need to parse all the startup packages or your 5000-line .emacs. You could activate it by putting (server-start) in your .emacs, or calling M-x server-start. I've been happily using that for years with mutt.

Those were happy years. Still, things could be better. Emacs-client/server had its limitations: first, an emacs could have graphical or console (tty) clients, but not both at the same time. Second, you always needed to start emacs in the foreground before you could use emacslient.

Both of these limitations have gone now -- hurray! You simply start emacs as:

 $ emacs --daemon
and it starts running in the background. After that, you can start emacs client frames (windows) using:
 $ emacsclient -c
. This will give you a graphical version when running X, or a terminal (console) version otherwise. If you want a terminal version even in windows-mode, use:
 $ emacsclient -t
. If you don't want the controlling terminal to wait for the emacsclient to finish, you can add the -n argument, so:
 $ emacsclient -c -n
and you can even specify an alternate editor if emacs is not yet running, so:
  $ emacsclient -c -a nano    # if all else fails...
Of course, you can also start emacs itself as the 'alternate'.

Now, my new way to run emacs is a follows:

  1. I start emacs in the background (as daemon) when logging into X; this can be done automatically by adding to make emacs --daemon to your list of startup-programs. In GNOME, this can be set through the Preferences/Sessions/Startup Programs-menu. I am sure other environments have something similar. Alternatively, you could put emacs --daemon & in ~/.xinitrc.
  2. I fire up emacs frames (windows) with emacsclient -c (or emacsclient -t to run it in a console);
  3. That's it!
If you want to terminate emacs outside emacs, you'll have to kill it by hand (AFAIK) -- something like
 $ pkill -TERM -u $USER emacs
Make sure you have no unsaved data, and no other emacsen running...

You also might want to set some influential environment variables in your .~/.bashrc, ~/.zshenv, ..., so other programs will automatically use an emacsclient when available; e.g.,

   EDITOR="emacsclient -c"
   VISUAL="emacsclient -c"
  
With emacs --daemon there's no longer any need to use vi for quick-editing some file. In other words: alias vi="emacsclient -c"...

2009-02-05

switching buffers

In emacs, it's natural to have many buffers open: a couple of buffers you
work on, maybe a buffer with help, maybe some for e-mail, IRC, your
todo-list. Then, some general ones like *scratch*, and some generated ones
like *Completions* and *Messages*.


Note, elsewhere, we discuss managing all those buffer; here it's about
switching between them.

Some other programs use tabs to switch between buffers – and this is
possible with emacs too. However, this gets impractical quickly when you have
a lot of buffers open. And, more importantly, tabs (and menus) work best when
you use a mouse for navigation – but many emacs-users feel mouse usage
impairs their efficiency, and prefer to do their buffers-switching using the
keyboard.



iswitchb

To switch buffers with the keyboard in plain-vanilla emacs, you'd type C-x b
(Ctrl-X and then b). After doing that, the minibuffer (the area under
the modeline (statusbar)) will say something like:

Switch to buffer (default *scratch*):


You then type the beginning of the name of the buffer that you'd like to
switch to, with Tab-completion available. This all works fine, but it may
require some more typing than you'd like. Also, the completions will only be
visible after you push Tab. Because you this all the time, it quickly gets
annoying. To make it work better, there is iswitchb-mode, which you can
activate with M-x iswitchb-mode, or by putting


(iswitchb-mode t)


in your .emacs. With iswitchb-mode (which overtakes C-x b), the
completions are visible in the minibuffer itself, and typing any substring
(not just the beginning) of a buffer name will select it, something like:

iswitch {*Messages*,*scratch*,*Completions*,test.txt,foo.html}

Typing fo will move foo.html to the start of the list; pressing Enter

switches to the buffer at the start of the list. You can also rotate the items
in list with C-s and C-r. iswitchb-mode is such a great improvement that
I wonder why it's not the default.

ido

Some people wanted to use the kind of auto-completion that iswitch-mode
offers elsewhere as well, for example to open (eh, 'visit') a file. For this
reason, a supercharged replacement for iswitchb-mode was developed:
ido. This mode allows for autocompletion for both opening files and
switching buffers.

So, when opening a file (C-x C-f), you get:


Find file: ~/Desktop {test.html | notes.org | Leesmap/ | Documents/ | ...}

As with iswitchb, if you type some characters, your list of matches
('prospects') will shrink to the ones with matching substrings.

You can customize it in many ways; my customizations (.emacs) look something
like this:


;; ido makes competing buffers and finding files easier
;; http://www.emacswiki.org/cgi-bin/wiki/InteractivelyDoThings
(require 'ido) 
(ido-mode 'both) ;; for buffers and files
(setq 
  ido-save-directory-list-file "~/.emacs.d/cache/ido.last"

  ido-ignore-buffers ;; ignore these guys
  '("\\` " "^\*Mess" "^\*Back" ".*Completion" "^\*Ido" "^\*trace"

     "^\*compilation" "^\*GTAGS" "^session\.*" "^\*")
  ido-work-directory-list '("~/" "~/Desktop" "~/Documents" "~src")
  ido-case-fold  t                 ; be case-insensitive

  ido-enable-last-directory-history t ; remember last used dirs
  ido-max-work-directory-list 30   ; should be enough
  ido-max-work-file-list      50   ; remember many
  ido-use-filename-at-point nil    ; don't use filename at point (annoying)
  ido-use-url-at-point nil         ; don't use url at point (annoying)

  ido-enable-flex-matching nil     ; don't try to be too smart
  ido-max-prospects 8              ; don't spam my minibuffer
  ido-confirm-unique-completion t) ; wait for RET, even with unique completion

;; when using ido, the confirmation is rather annoying...
 (setq confirm-nonexistent-file-or-buffer nil)


I won't go through all of these – they are pretty well documented (just move
the cursor to the variables and enter C-h v).


icicles

If even ido is not enough for you, and you want almost magical completion
everywhere in emacs, the icicles-package may be something for you. icicles
is not included in the normal emacs package, so it takes some more time to
set up. Icicles adds autocompletion for just about anything; this is one reason
why many pages in EmacsWiki refer to some way that icicles could make things
better.


I have to admit that icicles scares me a bit. It's infinitely configurable,
but I found it hard to get it to do just what I want – which is basically
'do-as-ido', and then explore the many other features from there on. Still,
I guess I should spend some time to master it.

Of course there are more ways to switch buffers. In an earlier entry, I
already discussed switching buffer with Ctrl-Tab. Another way is to define
some key-bindings for often-used buffers, for example:


(global-set-key (kbd "<f5>")  ;make F5 switch to *scratch*     
  (lambda()(interactive)(switch-to-buffer "*scratch*")))
(global-set-key (kbd "<f6>") ; make F6 switch to .emacs; create if needed

  (lambda()(interactive)(find-file "~/.emacs"))) 

As often in emacs, there are many ways to do something. It may seem a bit
silly to spent so much energy on such a mundane activity as switching
buffers. However, as mentioned, emacs-users are picky about maintaining their
'flow', so all the tweaking might be worth it.

2009-02-03

fancy debugging with gdb

In emacs, you can start debugging your application with M-x gdb. If you come from a Eclipse/Visual Studio-background, you may find the experience somewhat spartan -- and the Spartans are known for many things, but debugging is not one of them. Still, I have debugged that way for years, until I only recently (really!) discovered gdb-many-windows. It's simple; start gdb inside emacs as you'd do normaly (M-x gdb), and after that, call M-x gdb-many-windows. This will split your frame ('window') in six buffers ('sub-windows'), something like the following:
gdb commandslocal variables / registers
source code
stackbreakpoints
I am usually a bit skeptical about putting too many GUI-distractions between me and my code, but this is really useful! All the information I need at my fingertips. Emacs is a place full of hidden treasures.

If we look at gdb itself, and compare it with e.g. the Visual Studio-debugger, there are still many features missing, even with gdb-many-windows. Of course, one could easily dismiss fancy debuggers as leading to bad programming practices - and there is some truth in that. But I think there is real value in at least some of the features. So, it's nice to see that there is progress in this area. One example is Python scripting support. Using that, it's much easier to have gdb print something reasonable when looking at std::string-objects or GErrors. Now if only we could use Elisp instead of Python...

If you are new to gdb, I would recommend you to read the GDB Tutorial, and after that the GDB User Manual. Gdb is a very powerful tool, but it requires some learning. Just like emacs.