I\'ve read in several places that the rectangle functions in emacs are very useful. I\'ve read a bit about them, and I can\'t quite figure why. I mean, when you want to kill
I like to use rectangle for 2 main purposes, inserting the same text on every line, or killing a column of text (similar to Dave Webb's answer).
There are 2 useful shortcuts for these, C-x r k
will kill a rectangle, and C-x r t
to insert (there are other rectangle commands with a C-x r
prefix, but these are the ones I use).
So let's say you want to take some code and format it so that you can post it in a Stack Overflow post... you need to prefix with 4 spaces. So, go to the beginning of the first line, C-SPC
to mark, then go to the beginning of the last line and C-x r t <SPC> <SPC> <SPC> <SPC> <RET>
, and there you have it! Then you can just copy and paste it into Stack Overflow. I have run into more complex situations where this is useful, where you actually have text you want to insert on every line at a particular place.
So the other situation like Dave Webb's situation, if you want to kill a rectangle, use C-x r k
though, because it's just a lot quicker ;-)
Also, according to my reference card that I printed out when I first started, you can do the following:
C-x r r
: copy to a registerC-x r y
: yank a rectangleC-x r o
: open a rectangle, shifting text right (whatever that means...)C-x r c
: blank out a rectangle (I assume that means replace it with spaces, but you'd have to try it out to see)C-x r t
: prefix with text (as described above)C-x r k
: killing (as described above)In emacs24+ there's also function for numbering lines:
(rectangle-number-lines START END START-AT &optional FORMAT)
Insert numbers in front of the region-rectangle.
START-AT, if non-nil, should be a number from which to begin
counting. FORMAT, if non-nil, should be a format string to pass
to `format' along with the line count. When called interactively
with a prefix argument, prompt for START-AT and FORMAT.
It is binded to C-x r N by default.
If you have data in columns in a text file with M-x delete-rectangle
or M-x kill-rectangle
you can delete a single column of data. Similarly, M-x yank-rectangle
will paste in a column of text.
For example, take the following text:
1. alligator alphorn
2. baboon bugle
3. crocodile cornet
4. dog didgeridoo
5. elephant euphonium
6. fish flugelhorn
7. gopher guitar
Select from the a of alligator to the g of guitar. The beginning and end of the selection mark out two opposite corners of the rectangle. Enter M-x kill-rectangle
and you immediately have:
1. alphorn
2. bugle
3. cornet
4. didgeridoo
5. euphonium
6. flugelhorn
7. guitar
Next put the mark at the end of the top line, add a few spaces if required and enter M-x yank-rectangle
and ta-da! You have re-ordered the columns:
1. alphorn alligator
2. bugle baboon
3. cornet crocodile
4. didgeridoo dog
5. euphonium elephant
6. flugelhorn fish
7. guitar gopher