Killing, yanking and copying lines

Kind reader William Annis noticed how clumsily i copied a line in the kill ring in my last screencast. I went to the beginning of the line (C-a), killed it (C-k) so i got it in my kill-ring, and yanked it back (C-y). Admittedly, a bit cumbersome, my only excuse being that i have this keystroke sequence hardwired in my nervous system from the dawn of my emacs times; approximately the same epoch when i put in my .emacs this setting to make kill-line eat also the final carry return:

(setq kill-whole-line t)

But, as William notices, there’re better ways of copying the current line. A quick one would be:

(defun jao-copy-line ()
  "Copy current line in the kill ring"
  (interactive)
  (kill-ring-save (line-beginning-position) 
                  (line-beginning-position 2))
  (message "Line copied"))

which can be easily extended to take as a prefix argument the number of lines to copy (with 1 as the default)

(defun jao-copy-line (arg)
  "Copy lines (as many as prefix argument) in the kill ring"
  (interactive "p")
  (kill-ring-save (line-beginning-position) 
                  (line-beginning-position (+ 1 arg)))
  (message "%d line%s copied" arg (if (= 1 arg) "" "s")))

Assign the new function to a handy shortcut, and you’re done. These functions have the additional benefit of leaving the point untouched.

Next thing you’ll do after using your new shiny shortcut will most probably be yanking those lines somewhere. And it may well happen that they’ll be mis-indented in their new location. A relatively quick way of realigning them is to take advantage of the fact that after a yank the region is set to the yanked text and use indent-region, which is bound to C-M-\. But i prefer to let Emacs do that for me, using this piece of advice in my .emacs:

(defadvice yank (after indent-region activate)
  (if (member major-mode '(emacs-lisp-mode scheme-mode lisp-mode
                           c-mode c++-mode objc-mode
                           LaTeX-mode TeX-mode))
      (indent-region (region-beginning) (region-end) nil)))

where, as you can see, i’m limiting the advice to some modes: just delete the major-mode check if you want it to work everywhere.

Record, play, re-play

Gentle reader Marc Donner has sent me an email sharing one of his favorite emacs hacks:

(global-set-key [f10]  'start-kbd-macro)
(global-set-key [f11]  'end-kbd-macro)
(global-set-key [f12]  'call-last-kbd-macro)

Yes, I could type C-x ( to start the macro and C-x ) to end the macro and C-x e to execute the macro, but that requires that my fingers be more nimble than they really are. Particularly because ( and ) are shifted keys.

This way I can start a macro with a single button push, finish it with another, and then repetitively run it by pressing a third button over and over.

As it happens, Emacs 22 comes with the functionality Marc assigns to his F12 key built-in: press just e right after executing the macro the first time, as many times as you need. There’s also the possibility of using a numerical prefix to specify how many times the macro should be executed (as in M-10 C-x e to execute it ten times), and passing zero as the prefix will keep on (re)executing it until the end of the buffer is reached.

One can also achieve macro re-plays with the command repeat, bound by default to C-x z. repeat works quite a bit like Vim’s ‘.’: it, well, repeats the most recently executed command, and keeps repeating if you keep pressing z. So, instead of C-x e e e e e ..., one can C-x e C-z z z z.... Not as convenient, but this works in Emacs 21, and, besides, repeat is an interesting command on its own.

Saying that keyboard macro recording is a useful Emacs feature would be an understatement. You can record almost any Emacs operation and, therefore, keyboard macros can automate quite non-trivial tasks. For instance, i’ve just used them a couple hours ago to generate C function body stubs from their declarations in a header file. Just for the fun of it, here’s a screencast:

Note how you’re not limited to a single buffer, and how we use generic operations (like searching for next space to kill and yank the function’s return type). It’s also important to left the cursor in the right position for the next execution of the macro. At first you’ll make little mistakes, but fear not: you can actually edit the last recorded macro with kmacro-edit-lossage (Emacs 22 only). Just type C-xC-kl and you’ll be teletransported to a *Edit macro* buffer where you can edit your last keystrokes and record them as needed. Nifty, no?

As you get used to macros, you’ll surely discover many other tricks, but you can speed up your learning by means of the excellent pages KeyboardMacros and KeyboardMacrosTricks in the Emacs wiki. (One of my favourite tricks is using Elisp in macros to dynamically change what gets inserted). This Linux Journal article by Jesper Pedersen is also a good way to get you started as a power macro user.

Happy recording!

Quick and dirty code folding

Code folding, the ability to hide code or text blocks in source or text files, is a feature present in most editors nowadays. Emacs has several modes providing this functionality with various degrees of sophistication: outline-mode, allout, hide-show or folding-mode come to mind. One can even use Emacs narrowing capabilities to cook up custom folding.

Over the years, i’ve used several of these packages (and perhaps i’ll share some tips on them in future postings). But i’ve noticed that, at the end of the day, i have usually little use for folding. I strive for short functions (whenever a function body extends a half-page, i feel a strong refactoring urge), and as a consequence i seldom need to hide their bodies, nor to mention blocks within them.

There is however one folding trick that i use all the time. I often want to hide all function bodies in a file, to get a quick summary of it contents. As it happens, you don’t need any package or extra configuration for that. Just go to any source file, type

        M-1 C-x $

and magic happens! As usual, it’s white magic: C-x $ will bring your code back.

We can use Emacs’ help system to discover what’s going on: C-h k C-x $ tells us that the above key combination is calling set-selective-display, a function that takes one numerical argument (the M-1 prefix passes 1 as the value of that argument) and, unsurprisingly, sets the variable selective-display to the value of that argument. I’ll let you read about the details in Emacs help itself, although i’m sure that by now you get the idea.

If you find yourself setting and unsetting selective-display as often as i do, next thing will be defining a handy keyboard shortcut, right?

(defun jao-toggle-selective-display ()
  (interactive)
  (set-selective-display (if selective-display nil 1)))

(global-set-key [f1] 'jao-toggle-selective-display)

or we can also use an optional numerical prefix (with 1 as default) with a little modification:

(defun jao-toggle-selective-display (column)
  (interactive "P")
  (set-selective-display 
   (if selective-display nil (or column 1))))

Happy folding!

Editing your file names

In my experience, dired is one of the most underused modes of Emacs. Just C-xC-f to any directory in your hard disk and you’ll be presented with a list of its files and directories. One can browse this list, and execute all kinds of commands and transformations on them. If you’ve never done that before, just give it a try, and look at the menubar for a list of nifty things you can do inside dired. There’re several ways to mark files and operate on them afterwards: for instance, just type A to find inside the selected files any regexp, or Q to search and substitute.

One of my favorites dired functionalities is wdired-change-to-wdired-mode. When you invoke this interactive function (using M-x wdired-change-to-wdired-mode), the dired buffer becomes editable. That is, you can go around and edit directly the filenames as you would edit any other emacs text buffer. And that means you have all the regular editing commands at your disposal. For instance, if i enter wdired-mode in my emacs configuration directory:

Emacs-Dired

and want to change the name of all those jao-*.el files to, say, jao-config-*.el, all i have to do is to search and replace as i would do in any other text file (i.e., using M-%). Or maybe put the cursor on the first file name, mark (C-SPC), got to the end of the jao-files list, put my cursor after the last dash (as shown in the figure), and use C-xrt to replace the text in the marked rectangle. When you’re happy editing the buffer, just press C-cC-c and all your changes will be reflected in the underlying files.

Nifty.

Follow

Get every new post delivered to your Inbox.