简体   繁体   中英

Applying a keyboard macro to an active region in Emacs

I am trying to learn to use keyboard macros more but wasn't sure how to approach this.

I need to select a region, then run two query-replacements on that region. The region will be different each time, but the query replacements will be the same.

The problem comes because the first query replace (or replace-string ) removes the active region. If I use Cu C-SPC , it appears the beginning mark is saved, but the point is not saved, so the active region is not available for the second replace operation.

How can I apply two operations, which remove the active region as a side effect, to the same region in a keyboard macro?

As I don't perfom tasks like the one described that often I'm not sure I can advice you the quickest solution but here at least two approaches that will work.

Option 1

This option involves using narrowing to reduce the buffer to the active region prior to performing query-replace, or whatever you want to do with the region. The workflow would be as follows:

  • ... start recording your keyboard macro with region active
  • Mx narrow-to-region
  • ... perform the operations you want to perform happily jumping back to the start via M-< (beginning-of-buffer) and the like
  • Mx widen
  • ... stop recording your keyboard macro

You should be able to happily apply it to any highlighted region.

BTW: narrow-to-region and widen have a default bindings of Cx nn (narrow-to-region) and Cx nw (widen) so you could use them either in case you haven't changed your keybindings

Option 2

This options involves using registers to store the locations of the region prior to "destroying" it. The actual workflow would look like

  • ... start recording your keyboard macro with region active
  • Cx r SPC 1 (point-to-register)
  • Cx Cx (exchange-point-and-mark)
  • Cx r SPC 2 (point-to-register)
  • ... perform the operation that "destroys" the region
  • Cx rj 2 (jump-to-register)
  • C-SPC
  • Cx rj 1 (jump-to-register)
  • ... now your region should be back again, so happily apply any other operations not "destroying" the region
  • ... stop recording your keyboard macro

What you're missing is exchange-point-and-mark Cx Cx . This has the effect of re-activating the mark.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM