0

When you select a region normally, you can do a replace-string on only that region.

It would be very useful to select a rectangular region (via C-x SPC), and be able to replace-string on only that rectangle. Currently, it acts as though the region is everything between the beginning and end of the selection, not just the rectangle.

Is there any way to get the functionality described above? I've tried the multiple-cursors package, that doesn't provide this either.

Using Emacs 26.2, if it helps.

1

It might be easier to learn the commands for M-x query-replace. Once you have defined the match string and replacement string, it will pass over all the matches in a region (or the rest of the buffer after your cursor) and allow you to either replace or skip.

Here are the commands you can run (from the ? help text):

Query replacing A with B.

Type Space or ‘y’ to replace one match, Delete or ‘n’ to skip to next,
RET or ‘q’ to exit, Period to replace one match and exit,
Comma to replace but not move point immediately,
C-r to enter recursive edit (C-M-c to get out again),
C-w to delete match and recursive edit,
C-l to clear the screen, redisplay, and offer same replacement again,
! to replace all remaining matches in this buffer with no more questions,
^ to move point back to previous match,
u to undo previous replacement,
U to undo all replacements,
E to edit the replacement string.
In multi-buffer replacements type ‘Y’ to replace all remaining
matches in all remaining buffers with no more questions,
‘N’ to skip to the next buffer without replacing remaining matches
in the current buffer.
| improve this answer | |
1

C-x SPC turns on rectangle-mark-mode, activating the region as rectangular (noncontiguous).

Then you can use M-% (query-replace) to replace any string with another, within only the rectangle. You are prompted for the two strings. If you don't want to be queried about each occurrence in the rectangle you can use M-x replace-string instead of M-%.

You don't provide a step-by-step recipe of what you tried, starting from emacs -Q, but when I try it it just works: C-x SPC M-x replace-string.

You might need to do C-x C-x after C-x SPC, to ensure that point is at the start, not the end, of the rectangle, since the replacement commands move forward (by default).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.