Emacs Advent Calendar 16: Rectangles

Wed 2015-12-16

Another unique feature of Emacs is the ability to select rectangular parts of a buffer.

Emacs 24.4 introduced a new and convenient feature: rectangle-mark-mode. It is invoked with C-x SPC and highlights rectangles that can be killed an yanked with the usual commands (C-w, C-y, M-w). Other commands are unaware of this functionality yet.

In earlier versions, rectangle commands could only operate on the region. They just did not consider all text between point and mark, but only the text between the lines and columns of point and mark. To use them, set a region but remember that what is highlighted is not what will be used by the commands. These older, and still useful rectangle commands are as follows:

Command Action
C-x r k Kill rectangle
C-x r y Yank rectangle at point, shifting existing text to the right
C-x r o Insert empty rectangle, shifting existing text to the right
C-x r c Insert empty rectangle, overwriting existing text
C-x r N Inserts line numbers a the left edge of the rectangle
M-x string-insert-rectangle Prompt for string and insert on each line, shifting existing text to the right
C-x r t Prompt for string and replace rectangle contents by it

Note that C-x r t will act intelligently when the inserted string is longer or shorter than the specified rectangle; the remainder of the line will be shifted right or left accordingly. Only text inside the rectangle will be overwritten.

M-x string-insert-rectangle is especially useful to prefix a paragraph of text with any character or string. Rectangles can have a width of 0.

A rectangle can be copied to a register R with C-x r r R, inserting a rectangle from register R works identical to inserting normal text from a register: C-x r i R.

More Information in sections 12.5 (Rectangles) and 13.3 (Saving Rectangles in Registers).


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