Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs, insert rectangular string interactively

Tags:

emacs

elisp

I often encounter situations in editing text or code where I want to insert a rectangle of spaces to align things, but I don't know exactly the number of spaces to insert.

For example, consider the following (very much contrived) snippet:

void *var = (void *)typedVar;
void *otherVar = voidStarOtherVar;
int intVar = x*y;
int intVar2 = y*z;

In default C-mode, M-x align results in this, which is better:

void *var      = (void *)typedVar;
void *otherVar = voidStarOtherVar;
int   intVar   = x*y;
int   intVar2  = y*z;

However, suppose my desired alignment (for some reason) is this:

void *var      = (void *)typedVar;
void *otherVar =         voidStarOtherVar;
int   intVar   =         x*y;
int   intVar2  =         y*z;

The only way I know to do that is with M-x string-rectangle on the bottom three lines, and type in the exact number of spaces.

However, I don't want to count the number of characters in (void *) before typing in the spaces, thus it would be nice to have an "interactive" rectangle string insert. For example, I type a space in this interactive mode, and I see it reflected immediately in the text. I enter another space, and it is inserted. In this way I can interactively align the text to my desired position.

Is there a built-in way to accomplish this? Or, failing that, can I create this functionality somehow?

like image 579
tdenniston Avatar asked Oct 19 '12 13:10

tdenniston


2 Answers

Open rectangle may be useful for your example:

C-x r o' Insert blank space to fill the space of the region-rectangle (open-rectangle'). This pushes the previous contents of the region-rectangle to the right.

So you mark the desired rectangle, and this function will push content to the right of the rectangle.

like image 84
Juancho Avatar answered Sep 30 '22 15:09

Juancho


Another alternative to those already presented is multiple-cursors on github, which is highly interactive and quite fun. There's a sublime Emacs Rocks! episode covering it on YouTube.

like image 31
Stuart Hickinbottom Avatar answered Sep 30 '22 15:09

Stuart Hickinbottom