Copying the previous line to current position in Emacs

Recently, I came across a scenario where I had to quickly copy the previous line in an Emacs buffer to the current position. The usual method for doing this has been to invoke:

C-p C-a C-k C-y RET C-y

Which basically does the following:

  1. Moves to the previous line (C-p)
  2. Moves to the beginning of the previous line (C-a)
  3. Kills the line (i.e., cuts the line with C-k)
  4. Yanks the line back (i.e., restores the original line with C-y)
  5. Creates a newline (RET), and
  6. Yanks another copy of the line with the final C-y (which is what we wanted in the first place)

While this works, it is certainly not the most optimal mechanism to perform such a simple (albeit infrequent) operation.

In searching the Net, and scanning the inbuilt functions using apropos and the excellent Icicles search, I stumbled upon the:

copy-from-above-command

function, which does exactly what is needed here. This function is available in misc.el, and needs to be enabled by requiring the file to be loaded in .emacs:

(require 'misc)

Also, the there is no default key-binding for the function, and one needs to be setup:

(global-set-key (kbd "H-y") 'copy-from-above-command)

In my case, I set up the Hyper-y key-stroke for the key, which nicely mirrors the yanking keys (C-y and M-y).

This function has another nice twist, which is that it will copy the characters from the previous line only from the current column, which allows partial lines to be copied over.

About these ads


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 81 other followers