2010-07-30

some handy key bindings

Emacs offers many handy key bindings; every now and then I come across a new one, which has been hiding there somewhere for a decade or more… Here are some of my favorites – I'm listing those that are (a) often useful, (b) might not be known by everyone already (c) don't require any external packages or setup.

  • M-27 x gives you xxxxxxxxxxxxxxxxxxxxxxxxxxx; and, believe it or not, works also with different characters and numbers;
  • M-m jumps to the first non-whitespace character on the current line;
  • M-^ joins two lines into one – like vi(m)'s :join, except that point must be on the second line, not the first;
  • M-/ auto-completes based on words in all your buffers; there are more powerful alternatives, but this one does not require any setup;
  • C-h k followed by some key or key combination tells you what it does, C-h m describes the currently active modes, with their key bindings;
  • C-h f documents the current function, C-h v does the same for variables. C-h a gives you information about commands - for example to get date-related commands, press C-h a date. This will, however, also get you commands related to update; instead, you can use C-h a \bdate (because C-h a accepts regular expressions);
  • C-x C-o will delete all the empty lines around your current cursor position, except for one;
  • M-q re-aligns the current paragraph; I use it all the time when writing e-mails etc. (you might want to check out filladapt for a version that gives you a bit more smartness with indentations, lists etc.);
  • C-x 8 RET in a recent emacs version gives you an auto-completable list of special characters to insert. So if I need, say, the Yen-character, I type C-x 8 RET ye TAB and I get YEN SIGN, which RET will then insert: ¥. Note that the completion only works on the start of the character name, so if you'd want to include the α-character, you'd need to know that its UCS-name is GREEK SMALL LETTER ALPHA… (you can try *alpha or TAB the empty string, and search in the results buffer, but that's rather slow);
  • C-h l shows your last 300 key presses ('lossage'). Interesting to see, and it might be useful when defining keyboard macros.

What are your favorites? Please share them in the comments.

2010-07-21

navigating through files and buffers with the lusty explorer

I think quite a few people are using ido-mode to navigate through files an and buffers; we discussed it here already a long time ago. I am a happy ido-user myself – it took me some time to fully get full accustomed to the key bindings, but now it feels very natural. Definitely an improvement of my emacs user experience.

However, I am always looking for new things – and one of those is a sort-of ido-mode substitute. It's called the Lusty Explorer and it's the emacs implementation of an existing vim-plugin. It's quite similar to ido-mode; the difference is mainly that it shows all the files or buffers at the same time, in the way that shells (say, bash or zsh) do auto-completion.

The best way to show how it works is using an screencast (note, this is of a slightly older version). Lusty Explorer uses fuzzy matching; that means that I can type /etc/fo, and all items in /etc/ with names f.*o match.

To install lusty-explorer, simply copy lusty-explorer.el to your load-path, and put something like the following in your .emacs:0

(when (require 'lusty-explorer nil 'noerror)

  ;; overrride the normal file-opening, buffer switching
  (global-set-key (kbd "C-x C-f") 'lusty-file-explorer)
  (global-set-key (kbd "C-x b")   'lusty-buffer-explorer))

Side-note, the (when (require 'lusty-explorer nil 'noerror) ...) is there just make sure that no error is raised when lusty-explorer is not found, and the rest is ignored in that case. I use this construct for all packages that are not necessarily available everywhere I use my .emacs; thus, they will simply be ignored and not cause startup errors.

I've been using Lusty Explorer for about a week now, and I am quite happy with it. I still need some time (and maybe some more customization) to get used to the way it works - for example, I found the way ido-mode handles backspace a bit smarter. Also, ido-mode can be customized to a much greater extent. That might merely be a factor of the relative age of the packages – and I haven't really felt the need to customize Lusty Explorer too much. For now, I think I'm going to keep on using it. It's worth a try at least!

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.