Emacs Advent Calendar 03: Deleting, Killing and Yanking

Thu 2015-12-03

In Emacs deleting text and killing text are two different concepts. Deleting something just removes it from the buffer. Stuff that is killed is appended to the kill ring from where it can be inserted (yanked) back into the buffer. Commands that only remove single characters or whitespace perform deletions. Most commands that remove a significant part a buffer's text are kill operations.

To delete the previous character press BACKSPACE, to delete the next character press Delete. If the region is active, both commands delete the text inside. C-d deletes the next character regardless of the state of the region.

There are several useful commands for deleting whitespace. To remove all spaces and tabs around point press M-\ , to keep exactly one space at point use M-SPC. Vertical whitespace is removed by C-x C-o. A very handy command is M-^ which joins two lines by deleting the newline and any indentation between them.

The smallest unit of text that is killed and not deleted are words. M-backspace kills the word before point, M-d kills words backwards. Note that consecutive kills append to the same entry in the kill ring and retain the original order of words. Take for example the sentence "This is a line of sample text" with point before "of"; killing words forwards, backwards, forwards and backwards (M-d M-backspace M-d M-backspace) leaves "This is text" while the kill ring now contains an entry reading "a line of sample".

Killing text by line is accomplished by the commands C-k or C-S-backspace. The former kills all text from point to the end of the line, the latter kills the whole line regardless of the position of point within the line. Both commands operate on logical lines.

A region is killed by pressing C-w. To only copy the region to the kill ring and use M-w.

Finally there is the zap-to-char command, which is called by pressing M-z CHAR, where CHAR is any character. It kills all text between point and the next occurrence of CHAR (including).

Entries from the kill ring can be recalled (yanked) back into the buffer by pressing C-y. Pressing M-y immediately afterwards cycles through the previous entries of the kill ring.

All of this can be found in sections 12.1 (Deletion and Killing) and 12.2 (Yanking) of the Emacs Reference Manual.


This text by Ludger Sandig is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.