Showing posts with label updated. Show all posts
Showing posts with label updated. Show all posts

2012-08-20

introducing mu4e, an e-mail client for emacs

background

I've haven't written too much here lately. This is because I have spent most of my emacs hacking time on mu4e, an emacs e-mail client. It's only slightly over six months old since its first release, but it has progressed rather quickly! So, I think it is time to give it an introduction to a wider audience. In future posts, I'll go into more detail.

E-mail is a very important means of communication for me; and for purposes of integration, it prefer to do my e-mail with emacs. For a long time, I used mutt with emacs as the editor; a few years back I switched to Wanderlust, and wrote a few articles about it.

There's a lot to like about Wanderlust: it's very featureful, and allows for a lot of customization. Still, there were a few things I was not fully happy with; the most important one was the speed of some operations; another annoyance was the fact that I got rather frequent cache-corruptions when using newer emacs versions.

So, what was I to do? Well, a few years back, I had written an e-mail indexer/searcher, called mu. It takes the messages in a maildir-folder, and allows you to query them. I wondered if I could use mu as the backend for an emacs-based e-mail client. So, I fired up emacs, started writing some code and some later I had a first version of… mu4e.

how does it work?

mu4e is an emacs front-end for mu; when you start it, mu4e connects to a mu server process (started on-demand). It accepts simple commands, and responds with emacs s-expressions, in asynchronous fashion. In practice, all the heavy work is done in this server process, and emacs shows the results when it is ready (usually almost instantly). Emacs does not need to wait for the backend, and things stay snappy, even with tens of thousands (or more) e-mail messages. The only operation that may still require some waiting is sending mail, since that uses the emacs built-in smtpmail, which blocks during its operation.

mu expects your e-mail messages to be stored in a maildir (a one-file-per-message system); you can get these mails there through tools like offlineimap or fetchmail. mu periodically indexes the messages, and stores the results in a Xapian database. A lot of what mu4e does is querying this database – so for example, what you see as 'my inbox folder' in the mu4e-frontend, is in fact just the result of a query of all message that happen to live in that folder. You can query for many things – message sender, subject, date, words in the body and more.

mu4e does not just query messages; it can also move messages between folders, delete them, modify their flags and so on (and afterwards update the database). All 'state' is in the file system, and the database is just a quick way to get to it; if you delete the database and then re-index, nothing is lost, and changes made with other tools (e.g. mutt) are picked up by mu as well.

trying mu4e

Some Linux distributions ship mu4e, but not necessarily a very recent version; and because mu4e is developing quickly, you may want to use the latest official release, or (if you are more adventurous) check out the git repository. You'll need GNU/Emacs 23 or 24, GLib, GMime >= 2.4 and Xapian.

After installing mu4e, you can check the mu4e manual, which should be fairly complete. In fact, one of the goals of mu4e is to make it easy to set up; for that reason, the documentation includes complete examples of how to set things up. The Getting started chapter should get you up to speed quickly.

So, give it a try if you're interested; the mu=/=mu4e project is very open to suggestions (and even bugs reports!), so feel free to put them here or subscribe to the mu mailing list.

a small tour

I'll end this with a number of screenshots, to give you a rough idea of how things look.

The main screen

When you start mu4e (M-x mu4e), you're taken to the main screen, which list the things you can do. The entries should speak for themselves. Note that you can define you're own bookmarks. In general, mu4e tries to make things as easy as possible, and provide auto-completions where possible.

The headers / view split-screen

The results of your queries are shown as a list of headers; if you click one of the headers, mu4e splits the screen horizontally (optionally, you can split the screen vertically, or only show the message view). You can customize the headers shown, re-order them and so on.

The message view supports html message, inline images, and has a mechanism to associate user-functions with messages and attachments (such as 'view in browser' or 'pipe through command'); see the manual for some examples.

The message composition view

Obviously, you can reply to messages, forward them, or compose a new message. For writing and sending messages, mu4e reuses emacs' built-in message-mode. There's support for auto-completing addresses (based on the e-mails you've sent/received before).

There's even (experimental) support for writing you're messages using org-mode, and then sending them as rich-text (html) messages.

parting thoughts

So, this was a short introduction to mu4e, barely scratching the surface, but hopefully conveying the main ideas. The manual discusses things in much more detail, and I'll write more about it in the future.

mu4e is still a young project, but, for what's it worth, I've been using it full-time for over six months, and a growing number of people are doing the same. So, if you're interested, give it try and let us know you think!

Have fun!

2012-07-09

replace-regexp and numbering lines

I saw the Got Emacs? posting showing off the new emacs-24 rectangle-number-lines command, to number a bunch of lines in buffer, i.e..:

foo
bar
cuux

becomes:

1 foo
2 bar
3 cuux

Very cool! An alternative is to use cua-mode, mark the column for the numbers with cua-set-rectangle-mark (C-RET), and then use M-x cua-sequence-rectangle (which takes you throught the steps, and has a lot of flexibility.

But let's look at yet another way: using replace-regexp. If we select (mark) the list once more, we can do M-x replace-regexp RET ^ RET \#. RET Note that the # is a special meta-character that represents the number of replacements already made. This has the somewhat clumsy side-effect that your list be numbered, starting at 0 rather than 1, so you should add a dummy-element at the beginning. Clearly, replace-regexp is inferior for simply adding some line numbers – however, it has the flexibility to do some smarter things.

Smarter things? Yes! replace-regexp allows you to use arbitrary Lisp-expressions in the replace strings. So, let's suppose that we want to use letters instead of numbers for our lines. Easy – again, select (mark) your lines, M-x replace-regexp RET ^ RET \,(format "%c. " (+ ?a \#)) RET and we get:

a. foo
b. bar
c. cuux

Admittedly, not the most world-shattering thing, but it does show the powers hidden in something as common as replace-regexp.

2010-07-16

keyboard macros

Keyboard macros are a truly classic emacs feature. Still, I only started to use them years after I got sucked into emacs – not so uncommon for emacs features… There may be more people like me, so let's raise the awareness a bit.

Keyboard macros allow you to record a number of keystrokes, and replay those at some later point. This can be a great time-saver when you need to do repetitive things. In many cases, they are an easy alternative to writing some elisp to get a job done. Note, keyboard macros are should not be confused with elisp-macros, which are something else altogether.

an example

So, when would we want to use a keyboard macro? Let's take some tedious task -- for example, we have a list of a few hundred names:

Newton, Isaac
Einstein, Albert
Maxwell, James
Turing, Alan
...

and we want to turn that into:

Isaac Newton
James Maxwell
Alan Turing
...

so, roughly, put the last name after the first name, and remove the comma.

We can solve this in different ways; we could simple change each line by hand. That's a fine solution if there are only a few lines, but it gets boring rather quickly.

Another way is to use regular expressions (see Building regular expressions); in this case, it's fairly easy to come up with one (assuming you know regular expressions). But let's see how we can solve it with a keyboard macro.

Schematically, we can solve this with the following:

actionkey
go to beginning of a lineC-a
kill (cut) the first wordM-d
delete the next two charactersDEL DEL
go to the end of the lineC-e
insert a spaceSPC
yank (paste)C-y
go to the next lineC-n

This may look like some magical incantation, but it comes quite natural when you are actually doing the editing.

An important thing to remember when working with keyboard macros is that you do your commands in such a way that they can be repeated for each line. Suppose you would select Newton with shift-select, i.e., C-SPC at the beginning of the line and pressing the right arrow key 6 times – that works for Newton, but not for Einstein. Instead, we need to use M-d ('kill-word') instead.

defining a macro

Now that we have solved the problem for a single line, let's make a keyboard macro.

We move the cursor to the first line, and start the definition by pressing C-x (, or alternatively, F3. Then, we press the commands C-a, M-d, DEL DEL, C-e, SPC, C-y, C-n (as in the list above). To finish the definition, press C-x ), (or F4).

Hurray, we have our macro. Now, let's use it.

using the macro

Now, to execute the last defined macro, you press C-x e. We could repeat that for our whole list, but fortunately there's an easier way to repeat a macro n times, using a prefix argument. For example, to repeat the macro 123 times, you first press C-u 123 and then C-x e.

There's a slightly shorter way to do this: instead of C-u 123 we can write M-123, and for C-x e we can use F4 (kmacro=end-or-call-macro).

You can even repeat the macro until the end of the buffer is reached with C-u 0 C-x e; this only makes sense if the macros ever reaches the end of the buffer of course. (Remember that you can always terminate with C-g, keyboard-quit)

You can also apply your keyboard macro to all lines in the selected area (region) with M-x apply-macro-to-region-lines (or C-x C-k r). Important to remember: this will actually move the cursor (point) to the start of each line, and then execute the macro. If you want your macro like that, the go-to-the-next-line should not be part of your macro, or you will be skipping lines.

saving macros for later use

If you want to use multiple macros, you can name them. You can do this with M-x name-last-kbd-macro. If you name your macro, say, foo (inventive as we are), you can then execute it after that as M-x foo, which will be available until you exit emacs.

If you want to have the macro for future emacs sessions as well, you can use insert-kbd-macro, which will give you an elisp version of your macro. For our example, this will look like:

(fset 'foo 
   [?\C-a ?\M-d delete delete ?\C-e ?  ?\C-y ?\C-n])

Not very readable, but we can put this in .emacs, and we can use it the next time we start emacs as well. We can also add a key binding for this, for example:

(global-set-key (kbd "C-c f") 'foo)

This will bind foo to C-c f.

final notes

Keyboard macros can be useful and easy, but they are fundamentally connected to key presses – so, if you remap your keys to something different, your macros may not work anymore. Also, the macros are pretty much write-only in the way we use them here. You can edit them in the macro editor though, with M-x edit-kbd-macro M-x foo; we'll then get something like:

;; Keyboard Macro Editor.  Press C-c C-c to finish; press C-x k RET to cancel.
;; Original keys: C-a M-d 2*<delete> C-e SPC C-y C-n

Command: foo
Key: none

Macro:

C-a                     ;; move-beginning-of-line
M-d                     ;; kill-word
2*<delete>              ;; delete-char
C-e                     ;; move-end-of-line
SPC                     ;; self-insert-command
C-y                     ;; yank
C-n                     ;; next-line

Keyboard macros can be quite a useful trick in your arsenal. And I have not even gone into more advanced tricks like macros with variations or the macro ring. Please refer to the section Keyboard macros in the emacs manual (C-h r) for all the details.

And, finally, don't let the text-based example limit your imagination – you can turn just about any repetitive sequence of tasks into a macro.

2010-06-30

console apps in emacs with multi-term

multi-term

updated Whenever it makes sense, I try to use emacs for my computer-based activities; surely, programs like The Gimp or a graphical web browser cannot yet be replace by emacs, but I'm making progress. I like the ways emacs gives me to automate and speed-up my tasks; I get some return-on-time-investment.

2010 or not, I still spend quite a bit of time on the console. So why not do that from within emacs? There different ways to run shells within emacs.

The simplest one is shell (i.e,, M-x shell), which starts a simple shell, which does not support which does not support 'graphical' console applications, such as mutt, mc, htop.

Then there are term and ansi-term (M-x ansi-term) that do support such applications, which ansi-term supporting colors as well (it seems to have become the default for term in recent emacs versions).

Another one is the nifty EShell (included with emacs), which is not just a (simple) terminal, but also a full shell environment, and has integration with other things in emacs. It's nice, but has some of the limitations that shell has - you cannot run 'graphical' applications; also, I don't really need a shell, as I am quite happy with zsh (zed shell) already, which is more powerful, and I prefer a shell that works both inside and outside emacs.

For all these reasons, I am using MultiTerm, which has 'graphical' support that ansi-term has, but adds a nice extra, namely support for multiple terminals within emacs. I'm not fully up to date with the exact difference in the terminal support between the two, but I haven't had any problems so far.

You can install multi-term (put it in your load-path), and add the following to your .emacs:

(autoload 'multi-term "multi-term" nil t)
(autoload 'multi-term-next "multi-term" nil t)

(setq multi-term-program "/bin/bash")   ;; use bash
;; (setq multi-term-program "/bin/zsh") ;; or use zsh...

;; only needed if you use autopair
(add-hook 'term-mode-hook
  #'(lambda () (setq autopair-dont-activate t)))


(global-set-key (kbd "C-c t") 'multi-term-next)
(global-set-key (kbd "C-c T") 'multi-term) ;; create a new one

With this, C-c t will jump through your multi-term buffers (create a new one if it doesn not exist yet), while C-c T unconditionally creates a new terminal.

2010-06-17

automatic pairing of brackets and quotes

Some text-editors, notably TextMate for MacOS, have a nice feature where inserting a opening ( will automatically insert the closing ), and put the cursor in between them (and does same for [], {}, and various quote-marks).

Not surprisingly, there are some implementations for emacs as well; the best one I have found so far is called autopair, which was written by João Távora. It usually does things just right. Do things 'just right' is essential for such a tool; even small annoyances can disturb your flow. Autopair tries to do whatever makes the most sense for a given mode (programming language etc.), but it can be tuned as well.

After installation, you can automatically activate it for all modes with (in your .emacs):

(require 'autopair)
(autopair-global-mode 1)

Now, evaluate this or restart emacs, and enjoy the autopairing-magic!

Except for autopairing, autopair also takes care of autocleaning; that is, if I press ( it turns that into () (the pairing part), and if I press Backspace then, it removes the whole () (the cleaning part). This makes things much less annoying if you type a pair by accident. Autopairing is the kind of thing that can get annoying quickly if it does not things exactly right – and autopair succeeds!

Another nice trick it offers is autowrapping – that is, I select a word, press ", and automatically it's turned into "word". To enable that, you need to add the following:

(setq autopair-autowrap t)

Note: you might want to see the notes below about delete-selection-mode and cua-mode.

Anyway, autopair with autowrap makes for a really smooth editing experience, I love it! There are two small issues for me though. First, when the cursor in front of some non-whitespace, I'd like autopairing not to happen, and second, somehow I can't seem to get "-autopairing to work in org-mode; of course, that could be my own fault. These things might be tunable; I haven't tried very hard yet.

delete-selection-mode

Important to mention here is that autopair is (by default) not fully compatible with delete-selection-mode. As you may know, that is the mode that causes emacs to replace the current selection with a character typed, similar to what most other programs do. I think many people have it enabled in their .emacs with something like:

(delete-selection-mode 1)

If you want to keep on using that together with autopair, add the following to your .emacs:

(put 'autopair-insert-opening 'delete-selection t)
(put 'autopair-skip-close-maybe 'delete-selection t)
(put 'autopair-insert-or-skip-quote 'delete-selection t)
(put 'autopair-extra-insert-opening 'delete-selection t)
(put 'autopair-extra-skip-close-maybe 'delete-selection t)
(put 'autopair-backspace 'delete-selection 'supersede)
(put 'autopair-newline 'delete-selection t)

But, not that that still won't give you the autowrap behavior mentioned above. For that, we can use cua-mode.

cua-mode

We discussed CUA-mode before, focusing on its nice rectangle-editing features. But CUA-mode can also be an alternative for delete-selection-mode, and it goes together more nicely with autopair; so, instead of delete-selection-mode and the put's, add the following to your .emacs:

(setq cua-enable-cua-keys nil)           ;; don't add C-x,C-c,C-v
(cua-mode t)                             ;; for rectangles, CUA is nice

See the linked CUA-mode article for the 'why' of that first line. With this change, autopair should be working smoothly, including autowrap.

further customization

As I have hinted at, autopair can be tuned for different modes, and can differentiate between it's behaviour in literal strings, code, comments etc. The default are usually sane, but if you're interested, have a look at the documentation, in particular autopair-extra-pairs and the More tricks-section in the documentation.

2010-05-20

100th post

100

With that last post, emacs-fu reached the 100 posts milestone! Hurray! Thank you for all the support, it's been a great ride so far, and there's so much more to write about - if only there were 36 hours in a day.

Anyway, to celebrate, I'll be off for the coming weeks (Korea), and I'm not sure if I have much time to blog from there. So, let's take this opportunity for a small reader poll: what would you be interested to read about? More programming-related stuff, more org-mode, more about integration with other programs, more interviews, more …?

Please leave your ideas in the comments. I'd be interested to hear!

Update: I am back now; thanks for all the replies. It seems that many people are interested in CEDET. In fact, I am interested in it myself as well, but am not using it right now, so it will take a while. For the time being, Alex Ott's Gentle Introduction might be the best way to get started.

2010-02-23

wanderlust iii

Wanderlust

I have been using the Wanderlust E-mail client for almost a year now, and I am very happy with it. In previous postings I already discussed setup and some tips and tricks; and I also had somewhat related posts on bbdb (the address book) and warning you about new mail. But I think it's time for an update.

maintenance

One question that I have received quite a few times was about the maintenance of Wanderlust; it's may be a nice e-mail client, but little seems to have happened in the last few years. It's reasonable concern.

Fortunately, it seems the situation has improved significantly. There's more traffic on the mailing lists, both from old and new users. Various improvements are circulating; the place to get the latest stuff is in David Abrahams' git-repository: semi, flim, apel and wanderlust. The plan is to gradually apply the changes to the upstream (CVS) repository.

bugs

Although I have been quite happy with Wanderlust, there was one bug #5534 that has bitten me a few times, causing occasional hangs when saving (draft) messages with non-ascii characters. It seemed finally to be a bug in emacs itself, which is triggered by something in Wanderlust. A fix will probably be available for the next emacs version; until then, you can work around this by using an external MIME-encoder. To do this, add the following to your WL initialization code (thanks to various helpful people on the WL mailing list):

(setq mel-b-ccl-module nil)
(setq mel-q-ccl-module nil)
(setq base64-external-encoder '("mimencode"))
(setq base64-external-decoder '("mimencode" "-u"))
(setq base64-external-decoder-option-to-specify-file '("-o"))
(setq quoted-printable-external-encoder '("mimencode" "-q"))
(setq quoted-printable-external-decoder '("mimencode" "-q" "-u"))
(setq quoted-printable-external-decoder-option-to-specify-file '("-o"))
(setq base64-internal-decoding-limit 0)
(setq base64-internal-encoding-limit 0)
(setq quoted-printable-internal-decoding-limit 0)
(setq quoted-printable-internal-encoding-limit 0)

(setq-default mime-transfer-level 8)
(setq mime-header-accept-quoted-encoded-words t)

This requires the mimencode-program, which is part of the metamail-package. For the time being, this seems to be the best solution when using Wanderlust with Emacs 23.

one more trick: reformatting

Let's finish with one more trick. Sometimes, incoming mail is formatted quite badly; in particular, the new lines are too long for comfortable reading. From the WL-mailing list, here's a trick to deal with that:

(require 'filladapt)

;; from a WL mailing list post by Per b. Sederber
;; Re-fill messages that arrive poorly formatted
(defun wl-summary-refill-message (all)
  (interactive "P")
  (if (and wl-message-buffer (get-buffer-window wl-message-buffer))
      (progn
        (wl-summary-toggle-disp-msg 'on)
        (save-excursion
          (set-buffer wl-message-buffer)
          (goto-char (point-min))
          (re-search-forward "^$")
          (while (or (looking-at "^\\[[1-9]") (looking-at "^$"))
            (forward-line 1))
          (let* ((buffer-read-only nil)
                 (find (lambda (regexp)
                         (save-excursion
                           (if (re-search-forward regexp nil t)
                               (match-beginning 0)
                             (point-max)))))
                 (start (point))
                 (end (if all
                          (point-max)
                        (min (funcall find "^[^>\n]* wrote:[ \n]+")
                             (funcall find "^>>>>>")
                             (funcall find "^ *>.*\n *>")
                             (funcall find "^-----Original Message-----")))))
            (save-restriction
              (narrow-to-region start end)
              (filladapt-mode 1)
              (fill-region (point-min) (point-max)))))
        (message "Message re-filled"))
    (message "No message to re-fill")))

(define-key wl-summary-mode-map "\M-q" 'wl-summary-refill-message)

Now, you can refill your messages with M-q when in the Summary.

If you have any other nifty WL-tricks that could be useful for others, please share them in the comments, thanks!

2009-11-19

showing pop-ups

Updated: yes, it's %s, not %d Sometimes, it's nice when emacs can warn you when something is happening or should happen. For example, when a new e-mail has arrived, or when there's a meeting in 15 minutes you should attend.

As always, there are different way to do this, but here's what I've been using for while. Various versions of this have been circulating around mailing lists, so I don't know whom to credit with the original idea – anyway, this is the (modified) version that I'm using.

(defun djcb-popup (title msg &optional icon sound)
  "Show a popup if we're on X, or echo it otherwise; TITLE is the title
of the message, MSG is the context. Optionally, you can provide an ICON and
a sound to be played"

  (interactive)
  (when sound (shell-command
                (concat "mplayer -really-quiet " sound " 2> /dev/null")))
  (if (eq window-system 'x)
    (shell-command (concat "notify-send "

                     (if icon (concat "-i " icon) "")
                     " '" title "' '" msg "'"))
    ;; text only version

    (message (concat title ": " msg))))

A couple of notes:

  • I'm using notify-send for sending notifications; this assumes you are using that system (it's part of the libnotify-bin package in Debian/Ubuntu). You can of course replace it with whatever is available on your system. Alternatives are zenity or kdialog or xmessage (for old-timers) and their equivalents (?) on Windows, MacOS.
  • I'm now using mplayer for playing sounds. This is a bit heavy, but at least plays all kinds of audio files. If you only care about .wav-files, you could replace it with e.g. aplay;
  • as always, please ignore my ego-centric function names :-)

Now, we can use this function by evaluation e.g.

(djcb-popup "Warning" "The end is near"
   "/usr/share/icons/test.png" "/usr/share/sounds/beep.ogg")

showing pop-ups from org-mode appointments

The above popup function is most useful when it's does its work based on some event. To be notified of appointments and the like, there is the emacs appt facility. Here, we set up this appt, and then hook it up with org-mode, so appt can warn us when there's something happening soon…

;; the appointment notification facility
(setq
  appt-message-warning-time 15 ;; warn 15 min in advance

  appt-display-mode-line t     ;; show in the modeline
  appt-display-format 'window) ;; use our func
(appt-activate 1)              ;; active appt (appointment notification)
(display-time)                 ;; time display is required for this...

 ;; update appt each time agenda opened

(add-hook 'org-finalize-agenda-hook 'org-agenda-to-appt)

;; our little façade-function for djcb-popup
 (defun djcb-appt-display (min-to-app new-time msg)
    (djcb-popup (format "Appointment in %s minute(s)" min-to-app) msg 
      "/usr/share/icons/gnome/32x32/status/appointment-soon.png"

      "/usr/share/sounds/ubuntu/stereo/phone-incoming-call.ogg"))
  (setq appt-disp-window-function (function djcb-appt-display))

Of course, you can freely choose a icon / sound to your liking.

showing pop-ups for new mail

Another event you might want to be warned about is new mail. There is something to be set for not letting yourself be disturbed for new mail, but if you sufficiently filter your mails before they enter your inbox, it can be a good way to periodically bring you back from your deep sl ^H^H thinking. For Wanderlust, I use something like this:

(add-hook 'wl-biff-notify-hook
    (lambda()
      (djcb-popup "Wanderlust" "You have new mail!"
        "/usr/share/icons/gnome/32x32/status/mail-unread.png"
        "/usr/share/sounds/ubuntu/stereo/phone-incoming-call.ogg")))

Exercise for the reader: adapt this for your chosen mail client.

2009-10-18

writing presentations with org-mode and beamer

[Updated:fixed an error in the template] Things have been a bit quiet at Emacs-Fu lately; this is mostly because I have been very busy with work, traveling, traveling for work etc. Emacs-wise, this has been a very intensive time, and I have been able to move more and more task to emacs – both professionally and privately. This is mostly because thing become easier when I can do all my things in one place.

Anyhow, one of the tricks I picked up recently is to write presentations with the combination of org-mode and a LaTeX-package called beamer. The most common tool for doing presentations is Microsoft's Powerpoint program. It gets a lot of criticism, most famously from prof. Tufte in his Powerpoint is Evil essay. Of course, the problem is in misuse of the tool, not so much the tool itself.

Still, I didn't want to use Powerpoint (or Powerpoint-wannabees, like OpenOffice's Impress). For the technically-inclined, the knee-jerk reaction to this kind of problem is to shout 'LaTeX!'. Indeed - the LaTeX text-processing system offers a package called Beamer, which allows you to write presentations with LaTeX. It is quite powerful, and even allows for all kinds of fancy graphical bling (fade-in, fade out etc.); even better, it generates PDF-files, which can be viewed just about anywhere. The various themes and color settings it offers are quite nice, even though they tend to fill only a small corner of the design-universe…

beamer and org-mode

Now, while I am no stranger to LaTeX, especially for writing a quick presentation, it can be a painful to remember the various directives and options. I am not really a daily LaTeX-user, so I tend to forget these things. I am a daily org-mode user though, and org-mode can export to LaTeX (which then, in turn, are translated into PDFs). So why not use org-mode to generate presentations?

It turns out that that is quite easy.

First, we need to define some of the LaTeX-boilerplate, and tell org-mode about it, so we never need to think about it again. Put the following in your .emacs:

;; allow for export=>beamer by placing

;; #+LaTeX_CLASS: beamer in org files
(unless (boundp 'org-export-latex-classes)
  (setq org-export-latex-classes nil))
(add-to-list 'org-export-latex-classes
  ;; beamer class, for presentations
  '("beamer"
     "\\documentclass[11pt]{beamer}\n
      \\mode<{{{beamermode}}}>\n
      \\usetheme{{{{beamertheme}}}}\n
      \\usecolortheme{{{{beamercolortheme}}}}\n
      \\beamertemplateballitem\n
      \\setbeameroption{show notes}
      \\usepackage[utf8]{inputenc}\n
      \\usepackage[T1]{fontenc}\n
      \\usepackage{hyperref}\n
      \\usepackage{color}
      \\usepackage{listings}
      \\lstset{numbers=none,language=[ISO]C++,tabsize=4,
  frame=single,
  basicstyle=\\small,
  showspaces=false,showstringspaces=false,
  showtabs=false,
  keywordstyle=\\color{blue}\\bfseries,
  commentstyle=\\color{red},
  }\n
      \\usepackage{verbatim}\n
      \\institute{{{{beamerinstitute}}}}\n          
       \\subject{{{{beamersubject}}}}\n"

     ("\\section{%s}" . "\\section*{%s}")
     
     ("\\begin{frame}[fragile]\\frametitle{%s}"
       "\\end{frame}"
       "\\begin{frame}[fragile]\\frametitle{%s}"
       "\\end{frame}")))

  ;; letter class, for formal letters

  (add-to-list 'org-export-latex-classes

  '("letter"
     "\\documentclass[11pt]{letter}\n
      \\usepackage[utf8]{inputenc}\n
      \\usepackage[T1]{fontenc}\n
      \\usepackage{color}"
     
     ("\\section{%s}" . "\\section*{%s}")
     ("\\subsection{%s}" . "\\subsection*{%s}")
     ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
     ("\\paragraph{%s}" . "\\paragraph*{%s}")
     ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))

This is based on the template by Thomas S. Dye on the org-mode mailing list. You can of course add other packages to it with \usepackage. In my version, I have add the Listings-package for including syntax-highlighted snippets of source code in my presentations. Importantly, I added the [fragile] options to the frame-settings, otherwise you cannot include such source code fragments without LaTeX complaining in various unhelpful ways.

Note, you can customize the way the Listings package works by changing the template above; or by setting the options in the org-file; this involves some 'raw LaTeX' though. It might make sense to define some macros for that.

Now, we can easily make a presentation in org-mode; simply start the file with something like:

#+LaTeX_CLASS: beamer
#+MACRO: BEAMERMODE presentation
#+MACRO: BEAMERTHEME Antibes
#+MACRO: BEAMERCOLORTHEME lily
#+MACRO: BEAMERSUBJECT RMRF
#+MACRO: BEAMERINSTITUTE Miskatonic University, Astrology Dept.
#+TITLE: Presentation with Org-Mode and Beamer
#+AUTHOR: Someone

Of course, you can change these parameters; for example, you might want to change the BEAMERTHEME into Madrid or Warsaw, or … – see the Beamer User Guide (PDF).

After having set up these things, you can write presentations in the familiar org-mode mark-up.

including source code

As mentioned before, you can use the listings-package to include source code snippets in your presentation. You'd write this something like:

#+BEGIN_LaTeX
\begin{lstlisting}[language=c]
for (int i = 1; i != 10; ++i) 
    std::cout << i << ": hello, world!"
              << std::endl;
\end{lstlisting}

#+END_LaTeX

In other words, we include some 'raw' LaTeX to do this. Now, the org-mode-way of doing this, would be to use something like

#+BEGIN_SRC c
  /* code */
#+END_SRC

as discussed before. This works well when exporting to HTML, but at this moment this will simply translate into a verbatim environment in LaTeX - so we use lstlisting to get some syntax-highlighting.

including pictures

Of course, the full arsenal of org-mode tools is available as well, for example Ditaa, as discussed before. Ditaa is now shipped as part of org-mode, and you can use it to create picture which are then included in your presentation. Very nice.

For including existing images (PNGs, JPGs etc.), it's probably easiest to put use some raw LaTeX for that, e.g., something like

#+LaTeX:\includegraphics{/some/path/emacs.png}

putting it together

Now, let's put it all together. Below is an example presentation. Assuming you have everything installed (ie., LaTeX with the listings package, a fairly recent org-mode, ditaa), you create your presentation.org and then press C-c C-e d and your presentation (presentation.pdf) is generated and automatically shown in your PDF-viewer. Easy!

The intermediate files (such as presentation.tex) are there as well, so you can check them if something went wrong.

I have uploaded the resulting PDF to Slideshare, so you can see what it looks like. However, the Slideshare-converted version is extremely blurry, unlike the crisp PDF I actually created. I'd be happy to upload the file somewhere else if someone can point me to a good place, thanks!

So hopefully this shows that you can quite easily make presentations with org-mode, with some help from Beamer, LaTeX etc. Beamer actually provides a lot more, such as funky slide-transitions and other tricks – but the things here should give you a good starting point.

#+LaTeX_CLASS: beamer
#+MACRO: BEAMERMODE presentation
#+MACRO: BEAMERTHEME Antibes

#+MACRO: BEAMERCOLORTHEME lily
#+MACRO: BEAMERSUBJECT RMRF
#+MACRO: BEAMERINSTITUTE Miskatonic University, Astrology Dept.
#+TITLE: Presentation with Org-Mode and Beamer
#+AUTHOR: Someone

* My presentation

** Overview

   1. Introduction

   2. Main part

   3. Questions
    
    
** Some interesting stuff
    
*** an important point
    
    - subpoint a
      
    - subpoint b

** Graphics

*** a picture

#+begin_ditaa blue.png -r -S
+---------+
| cBLU    |
|    +----+
|    |cPNK|
+----+----+
#+end_ditaa

*** another picture
#+LaTeX:\includegraphics{emacs.png}

** More interesting stuff

*** some C++ code
#+begin_LaTeX
\begin{lstlisting}[language=c]
for (int i = 1; i != 10; ++i) 
    std::cout << i << ": hello, world!"
              << std::endl;
\end{lstlisting}
#+end_LaTeX

*** and some Python...

#+begin_LaTeX
\begin{lstlisting}[language=python]
for i in range(1,10):
        print i, "hello, world!"
\end{lstlisting}
#+end_LaTeX

2009-06-08

e-mail with wanderlust

e-mail with wanderlust

(This is part I of entry on the wanderlust e-mail client; part II will appear soon).

Earlier, I have written about how I am using mutt as my e-mailclient. I discussed running mutt inside emacs as well. Of course, mutt is an external program, which puts some limits on its integration with emacs. I did try various emacs-based clients, such as VM (ViewMail) and GNUS, but they always left me a bit unsatisfied.

To start with, it was rather hard to set these programs up – and I am an Emacs-user, I like tweaking things… Still, it was hard to get even simple things working. Maybe I have uncommon wishes, but my desired setup already sent me to the edges of the googleable universe.

But now I have found an emacs-based client that seems to work really well for me. It's called Wanderlust, and it's a fine piece of Japanese engineering. It can be a little bit intimidating to set up at first, even though I found it still much easier than the other emacs-based clients I tried. Anyway, I am sharing a very basic setup here, enough to get you going.

What about my setup? Well: I use maildirs – that is, I download my mail into a local ~/Maildir directory-tree, either with e.g. fetchmail or with offlineimap. It's a particulary nice setup for offline-usage: whenever there's a network connection, I suck up all the mails and have them available offline. I work like this since the days when there was only expensive dial-up access to the net, and later I found it very convenient when I was traveling with a laptop and had only occasional net-access.

So, Maildir access is pretty important for me, and I'll describe my setup for using Wanderlust with it here. If you're using IMAP instead of Maildirs, you might be interested in the Emacs with Wanderlust and GMail-article.

Getting started

So, how to get started with Wanderlust?

In short: install Wanderlust and put some stuff in two files (~/.wl and ~/.folders).

A little bit longer:

  • get wanderlist - I am using the wl-beta packages from Ubuntu/Debian, which makes this a painless process, but you can also use source packages;
  • put your Wanderlust-configuration in a special file: ~/.wl;
  • put a list of the mail folders you're interested in, in a file called

~/.folders. (yes, you can customize all this)

For the rest of the discussion, let's assume we have a Maildir which contains some folders:

  • inbox for incoming e-mail
  • bulk for incoming Mailing List mail
  • drafts for drafts
  • sent for sent e-mail
  • trash for junk email

All incoming mail is going to either inbox or bulk. I'm not going to discuss how to get the mails there – I assume you're already have these thing set up; otherwise, you can take a look at tools like fetchmail, retchmail, procmail and friends. Note that much of the discussion here applies as well if you're using Wanderlust with POP or IMAP.

What to put in ~/.wl?

So, how to setup Wanderlust to use this? Well, our configuration goes into a file called ~/.wl. There's a million more things you can set up here , but let's stick to the basics here. I'll discuss more tricks and extensions later.

;; mode:-*-emacs-lisp-*-
;; wanderlust 
(setq 
  elmo-maildir-folder-path "~/Maildir"          ;; where i store my mail

  wl-stay-folder-window t                       ;; show the folder pane (left)
  wl-folder-window-width 25                     ;; toggle on/off with 'i'
  
  wl-smtp-posting-server "localhost"            ;; put the smtp server here
  wl-local-domain "myhost.example.com"          ;; put something here...
  wl-message-id-domain "myhost.example.com"     ;; ...

  wl-from "Me <me@example.com>"                  ;; my From:

  ;; note: all below are dirs (Maildirs) under elmo-maildir-folder-path 
  ;; the '.'-prefix is for marking them as maildirs
  wl-fcc ".sent"                       ;; sent msgs go to the "sent"-folder
  wl-fcc-force-as-read t               ;; mark sent messages as read 
  wl-default-folder ".inbox"           ;; my main inbox 
  wl-draft-folder ".drafts"            ;; store drafts in 'postponed'
  wl-trash-folder ".trash"             ;; put trash in 'trash'
  wl-spam-folder ".trash"              ;; ...spam as well
  wl-queue-folder ".queue"             ;; we don't use this

  ;; check this folder periodically, and update modeline
  wl-biff-check-folder-list '(".todo") ;; check every 180 seconds
                                       ;; (default: wl-biff-check-interval)

  ;; hide many fields from message buffers
  wl-message-ignored-field-list '("^.*:")
  wl-message-visible-field-list
  '("^\\(To\\|Cc\\):"
    "^Subject:"
    "^\\(From\\|Reply-To\\):"
    "^Organization:"
    "^Message-Id:"
    "^\\(Posted\\|Date\\):"
    )
  wl-message-sort-field-list
  '("^From"
    "^Organization:"
    "^X-Attribution:"
     "^Subject"
     "^Date"
     "^To"
     "^Cc"))

What to put in ~/.folders?

So, that was the basic setup. Now we need to tell wanderlust about the folders we'd like to see in the user-interface: ~/.folders. Wanderlust does not automatically use all the folder in your ~/Maildir. The folder names in ~/.folders can refer to maildirs, newsgroups, POP-account, IMAP-folders and a couple of other ones. In particular, you can combine folders to show as aggregate folders in Wanderlust.

Wanderlust distinguishes the kind of folder something is by looking at a special prefix character. For maildirs, this is a dot ('.'), IMAP-folders get a '+', newsgroups get a '-' and so on. After the mailbox name, you can have a 'friendly name' in quotes, which is what will show up in the user-interface.

Something like this:

# WL folders (put the '#' always at the beginning of the line)
.inbox     "Inbox"
.bulk      "Mailinglists"
.drafts    "Drafts"
.sent      "Sent Mail"
.trash     "Junk"

Note, the little format has some more tricks; e.g., if you had some folders, you cold have something like:

# WL folders (put the '#' always at the beginning of the line)

# 'Lists' will be a tree node with three elements
Lists {
        .mailinglist1 "A mailinglist"
        .mailinglist2 "Another Mailinglist" 
        .mailinglist3 "Yet one more mailinglist"
}

# you make virtual folders from combined lists with the '*'
AllMyMailingLists  *.mailinglist1,.mailinglist2,.mailinglist3

Anyway, there's plenty of room for experimentation here…

Now, we're ready! Start Wanderlust with M-x wl. You will be greeted, and things are relatively easy from there on. You might want to use the menu at first at least, as the default keybindings are somewhat surprising (like a for reply, and w to compose a new message).

What's next?

As I said, there are 10E6 things to configure and to customize, but this should give you a reasonable setup to start with; you might want to change some details (like the folder names) to match your situation. Good luck!

As a true emacs-mailer, Wanderlust nicely integrates with e.g. BBDB (the addressbook) and org-mode. You can also use GPG (through mailcrypt), spamfiltering, and so on. I will discuss some of those things in the second part of the discussion of Wanderlust.

2009-05-26

tracking changes

It's sometimes nice to see the changes you've made to a file. If the file is under version control, you can use the 'diff'-features of the version control system of course; or you can use diff-buffer-with-file to compare your buffer with the version on disk. That obviously only. works when you haven't saved the file yet.

Anyway, a bit easier, straighforward way may be to use highlight-changes-mode. With that mode, emacs can give a special color to parts of the text that you have changed.

;; higlight changes in documents
(global-highlight-changes-mode t)
(setq highlight-changes-visibility-initial-state nil); initially hide

The last line tells me that the changes should not be visible unless I want to see them.

I defined a key binding (F6) so I can easily toggle between visible/invisible changes:

;; toggle visibility
(global-set-key (kbd "<f6>")      'highlight-changes-visible-mode) ;; changes
;; remove the change-highlight in region
(global-set-key (kbd "S-<f6>")    'highlight-changes-remove-highlight)

With this last keybinding S-<f6> (Shift-F6), I can remove the change-indication of the current region (selection). Here are some other useful keybindings to quickly jump between various changes:

;; alt-pgup/pgdown jump to the previous/next change

;; if you're not already using it for something else...
(global-set-key (kbd "<M-prior>") 'highlight-changes-next-change)
(global-set-key (kbd "<M-next>")  'highlight-changes-previous-change)

Another interesting thing you can do is M-x highlight-compare-with-file.

The only remaining problem with highlight-changes-mode is that the default colors are, well, hideous. But of course, that can easily be fixed by changing the faces:

(set-face-foreground 'highlight-changes nil)
(set-face-background 'highlight-changes "#382f2f")
(set-face-foreground 'highlight-changes-delete nil)
(set-face-background 'highlight-changes-delete "#916868")

Or adding to your color-scheme:

(highlight-changes ((t (:foreground nil :background "#382f2f"))))
(highlight-changes-delete ((t (:foreground nil :background "#916868")))) 

Now, with these color changes, the foreground stays the same, only the background changes a bit. I am using a dark theme, you might want to change the colors to fit in with your theme.

There are some more features - for example, to rotate through changes of different age. For such things I prefer to use a version control system, but you might want to check it out.

Tracking changes can be quite useful. And, unlike some word-processing software, emacs does not hide your highly embarrassing modifications somewhere in your document…

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-01-09

the kill-ring

Last time, I discussed registers, and mentioned the kill-ring. The kill-ring is the 'normal' clipboard emacs uses for cut/copy/paste of text. The cool name comes from the fact that in emacs terminology, 'killing' means what 'cutting' means in many other programs. The kill-ring contains the cut (and copied!) text parts; cut-copy-paste have their own entry.

As mentioned in the registers entry, many programs only allow you to paste the last copied/cut text block, and that is what the kill-ring does by default (when you press C-y). However, you can choose older ones using the menu (Edit/Paste from kill menu). Alternatively, you can use a prefix key (e.g., M-3 C-y will insert the third most recently killed ('cut') text).

The kill 'ring' behaves mostly like a list; by default (emacs 22, 23) there are 60 positions available in the ring, after which older entries are thrown away. You can put (setq kill-ring-max 120) in your .emacs in the unlikely case that 60 is not enough.

Update:An anonymous commenter mentions the useful M-y ('yank-pop') key binding, which lets you cycle through the items in the kill-ring. Quite useful indeed, thanks!

If you're using the GTK+-version of emacs (the graphical version in X/Linux/Unix environments), you can even have the Edit/Paste from kill menu-menu in a separate frame (window), and paste text by clicking there. To this, go to the menu Edit/Paste from kill menu, and click on the dotted line at the top of the sub menu.

2009-01-07

using registers

UPDATED Emacs is full of wonderful features, but sometimes it takes some time to find them. Today, let's discuss one such feature, registers. Registers are dicussed in the Emacs Manual, but it took me quite some time before I understood what they're good for. So let me discuss them here - maybe I am not the only one.

To explain the use of register, let's look at the normal cut-copy-pasting of text first. When you have cut or copied some text, it lives in a place we call the clipboard, from with you can then paste it. But in most programs, if you copy/cut text again, it replaces what was already on the clip board.

Now, what about registers? In emacs, we have a special clipboard with multiple places to store things, each named by a single number or letter. We call these places registers. Thus, you can save some text to register A, some other text to register B, and later paste the contents of register A or B. The key bindings (shortcuts) for this are good to remember:

C-x r s Rsave region (selection) into register R
C-x r i Rinsert the contents of register R
So, to save the current region/selection in register 2, you would type: C-x r s 2, and to insert the contents of that register later, you'd do C-x r i 2. It's a really useful thing to add to your emacs muscle memory.

(Note: the clipboard that emacs uses for 'normal' cut/copy/paste, the 'kill-ring', allows for multiple (but unnamed) entries as well - but we'll discuss the kill-ring in some other entry.)

viewing register contents

One obvious problem with registers is that for most people it's very hard to remember what went into which register, if you use more than two or three registers. There is M-x view-register, but that's only marginally useful. It would be much nicer if we could get a list of all registers in use and a preview of their contents. To do that, we can use the list-register.el package (see installing packages). The package adds a function list-registers (and some others). I use a key binding C-x r v for that, which somewhat logically follows the other ones:
C-x r vview registers
(require 'list-register)
(global-set-key (kbd "C-x r v") 'list-register)
An alternative would be to use C-x r l (for list registers), but that one has already been taken by bookmark-bmenu-list, which shows a list of your bookmarks -- to be discussed some other time).

I would vote for including the list-registers functionality in emacs. Having registers without a way to view them, makes them much less useful.

more than words

Personally, I seldomly use registers for anything but text; however, you can store other things in registers as well (see the Emacs Manual registers section for details):
objectstoreretrievenotes
rectangleC-x r r RC-x r i R save rectangle into register R (see working with rectangular selections, and insert it);
buffer/positionC-x r <SPC> RC-x r j Rsave buffer/position in register R, and jump back to it
windowC-x r w RC-x r j Rsave window configuration in register R, and jump back to it. Note that what emacs calls a window is called a window pane elsewhere, see emacs terminology)
frameC-x r f RC-x r j Rsave frame configuration in register R, and jump back to it. Note that what emacs calls a frame is called a window elsewhere, see emacs terminology
As you can see, some of the objects share the keybinding for retrieving them. In other words, what happens when you retrieve register R depends on the type of object you put in there before.

While registers are quite useful, I think they would be easier to use if they were integrated with the normal cut-copy-paste (the 'kill-ring'). Another issue is that you cannot access your registers from other programs. Actually, recent MS-Office versions do this in a bit nicer way...

2008-12-19

easy switching between visible buffers

It's common to split the emacs frame1, so we can see multiple buffers at the same time. For maximum efficiency, we'd like to use the keyboard (instead of the mouse) to switch the focus from one buffer to the next. The 'traditional' way is to use C-x o for that ('other-window'); it will take you to the next window (remember, 'window' may be what you think1); C-x o also accepts prefix arguments to go to the n-th next window.

However, its much easier to switch between visible buffers using the windmove-package (which is part of emacs):

(require 'windmove)
(windmove-default-keybindings 'meta)

After this, you can move the focus to some other window using Alt+arrow-key; so Alt-up (M-up) will go to the window above the current one, Alt-Left (M-left) goes to the left, and so on. That's a lot more intuitive C-x o multiple times to find the right window.

Note, by default, windmove uses the Shift-key instead of the Meta-key; but using the shift key conflicts with e.g. cua-mode. Because of that, I prefer the meta key; this is what the (windmove-default-keybindings 'meta) line is for. You can of course use another key if you're already using the Meta/Alt key for something else.

More recently, I have started to use the Windows-key, because org-mode already uses of meta + arrow keys for other things. Under X, you can usually find the Windows key as super key, so, you would use:

(require 'windmove)
(windmove-default-keybindings 'super)

That might not work in all places though - not on the console and, ironically, not on Windows.

Footnotes:

1 frame and a buffer are typical emacs-speak, see emacs-terminology for an overview)

2008-12-16

showing line numbers

Updated After the discussion of modes and installing packages, we can give some direct practical trick, courtesy of M-x all-things-emacs; note, I have updated this since, to work with Emacs 23.

Sometimes it is very useful to see the line numbers in a file – that is, on the left side of each line, the line number is shown. A use case for this is when showing something to a group of people. In that case, zooming and full-screen mode might also be useful.

The traditional way in emacs is to use setnu.el, but it's quite slow for big files. Fortunately, there is linum-mode; in your .emacs, add:

(autoload 'linum-mode "linum" "toggle line numbers on/off" t) 
(global-set-key (kbd "C-<f5>") 'linum-mode)    

Now, you can quickly show/hide linenumbers by pressing C-F5 (Control-F5).

You can also turn it on for specific modes; for example, to turn on line numbers when editing Perl code:

(add-hook 'perl-mode-hook
  (lambda() (linum-mode 1)))

2008-12-02

binding keys

In quite some of the blog entries we define key bindings (or keyboard shortcuts, as they are called in other places). Key bindings are an essential part of what makes emacs such a productive editor.

Key bindings are discussed in a lot of detail in the Emacs documentation; but what about the very useful little subset we need here for defining keybindings? Let's see…

kbd

When defining key bindings, it's important to understand the emacs-notation for them. Emacs allows for different ways to specify key combinations, but the easiest way is to use the kbd-macro. We're using this macro in the examples below.

To figure out how to find the notation for some key we want to bind, we can use describe-key, or C-h k (Ctrl-h k), and type the key you want to use. Emacs will tell you if it's already bound, and the representation of the key. So, for example, pressing C-h k and then Ctrl-Shift-Return shows the representation for that as <C-S-return>.

binding a function

Once we have figured out the notation for the keybinding we'd like to use, the next step is mapping it to some function. If the function takes no arguments, it's easy (see the examples below). But how to call a function that requires an argument? Suppose,we want to insert the word "hello" whenever we presses C-c h. For that, we need a lambda-function:

(global-set-key (kbd "C-c h") '(lambda () (interactive)(insert "hello")))

Also note the (interactive), to tell emacs that this is an interactive function, because we want to have some output to the current buffer. Lambda-functions require some more explanation, which deserves its own entry…

keymap

So, we have seen how we can figure out a keybinding, and how we can bind it to some function. The final important concept ist that of a keymap, which is a set of keybindings. In emacs, you have multiple keymaps, because in different situations, we'd like to use different (combinations of) keymaps. You can define keybindings that apply throughout emacs (in the global keymap), in specific modes, or in the current buffer (in the local keymap). Let's see how this works in practice.

In this entry we define a global keybinding for toggling full-screen mode; in .emacs:

(global-set-key (kbd "<f11>") 'djcb-full-screen-toggle)

Because there are so many functions available in emacs, it is impossible to have global key bindings for everything that are still easy to remember (a keybinding you have to look up is rather useless). Also, many bindings only make sense in a particular mode.

Because of that, we can have mode-specific keybindings. For example, the command ff-find-other-file (to jump from .c-file to .h-file and vice-versa, as mentioned here), is only useful in c-mode (and derivatives), so:

(define-key c-mode-map  (kbd "C-c o")    'ff-find-other-file)

Finally, to set a key only for the current buffer, we could use:

(local-set-key (kbd "<f11>")  'djcb-full-screen-toggle)

But note that usually, all buffers in a certain mode share their keymap. This means that adding a keybinding to the keymap for the current buffer will likely add it to all buffers of that type.

Conclusion

This should be enough to get you started; the big challenge now is to come up with a set of intuitive key bindings for your most-used function. That is not so easy…