Recording a macro in Emacs is a well known tasks, but today I struggled with applying the macro for the current region only. Thanks to this answer on SO, I ended with the following recipe:

  1. Select region
  2. F3
  3. M-x narrow-to-region
  4. … operations on region, M-< to jump to beginning of region, M-> to the end
  5. M-x widen
  6. F4

When you want to save your macro for later usage, run

  1. M-x name-last-kbd-macro Enter <mymacro> Enter
  2. Open .emacs
  3. M-x insert-kbd-macro Enter <mymacro> Enter
  4. Add line (global-set-key [f9] '<mymacro>) to bind F9 to your macro