Share your knowledge at the LQ Wiki.
Go Back > Blogs > flshope
User Name


Rate this Entry

Emacs rectangle search/replace

Posted 08-21-2016 at 07:43 PM by flshope

I use Emacs to write code occasionally, mostly Fortran. A common thing I need to do is search and replace everywhere in a region confined to a rectangle within the text. An example is altering an existing code from Fortran 77 format to Fortran 90, specifically changing all of the Cs in column one (indicating comments) to !s. In Emacs terminology, this is a rectangle of width 1 character and as high as the number of lines in the code.

I have had difficulty figuring out how to do this conveniently in Emacs. I previously used NEdit, where it is almost trivial, until I abandoned NEdit over the clipboard-lock problem. I am still slowly learning Emacs, but I am a light-weight user: I prefer Ctrl-x/Ctrl-c/Ctrl-v for cut/copy/paste and have the CUA (Common User Access) option activated. Under threat of water boarding, I might even admit to using the tool bar icons for copy and paste.

I have finally figured out how to do rectangle search/replace. I searched the documentation -- both hard copy (1) and what is given in the code's help facility -- as well as the Emacs Stack Exchange (, but I have never found an explicitly written out procedure that I could get to work. I am using Emacs 23.4.1 under Ubuntu 14.04 and Debian 8.5.

I have found the following to work easily:
- On the Options menu, activate 'C-x/C-c/C-v Cut and Paste (CUA)'
- Mark the rectangle containing the string to be replaced:
-- Place the cursor at the upper left corner of the rectangle
-- Type 'C-RET'
-- Using the arrow keys, move the cursor to the lower right corner of the
rectangle (the rectangle will be highlighted).
- Type 'M-r'
- Type 'oldstring RET'
- Type 'newstring RET'
- Type 'C-g'

If you are even newer to Emacs than I am, note the following Emacs notation used above:

C- : Simultaneously press Ctrl key and whatever character follows the "-"
M- : Simultaneously press Meta (Alt) key and whatever character follows the "-"
RET : Press return key

If there is some problem with the above procedure that I haven't discovered yet, please educate me. So far, this does what I want it to do.

(1) Stallman, Richard M., GNU Emacs Manual, 7th ed (Emacs version 24.2), Free Software Foundation, Inc., 2012.
Posted in Uncategorized
Views 1363 Comments 0
« Prev     Main     Next »
Total Comments 0




All times are GMT -5. The time now is 08:27 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration