Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leave region selected after emacs operation

Tags:

emacs

elisp

My question builds on this answer by Trey Jackson to this question from SyntaxT3rr0r.

Trey proposes the following function for incrementing each two-digit number in the selected region of an Emacs buffer.

(defun add-1-to-2-digits (b e)
  "add 1 to every 2 digit number in the region"
  (interactive "r")
  (goto-char b)
  (while (re-search-forward "\\b[0-9][0-9]\\b" e t)
    (replace-match (number-to-string (+ 1 (string-to-int (match-string 0)))))))

I would like to use this function for my own purposes. However, I would like to increment the numbers many times successively. The problem with the function, in its current form, is that before each invocation, I have to select the region again with my mouse.

My question is: How can Trey's function be modified so that it leaves the region selected after invocation? (My ultimate aim is to assign this function to a keyboard shortcut (something like ctrl+) so that I if I keep the ctrl and keys held down, all the two-digit numbers in my selected region will continuously increase.)

By the way, I am aware of this answer by Brian Campbell, which suggests using exchange-point-and-mark to re-select a previously-selected region. However, I tried that, and it doesn't seem to help in this instance.

like image 694
John Wickerson Avatar asked Apr 14 '13 16:04

John Wickerson


2 Answers

Here's your function modified to use let (deactivate-mark) wrapped inside save-excursion as suggested in the answer user event_jr linked to:

https://stackoverflow.com/a/11080667/903943

(defun add-1-to-2-digits (b e)
  "add 1 to every 2 digit number in the region"
  (interactive "r")
  (save-excursion
    (let (deactivate-mark) 
      (goto-char b)
      (while (re-search-forward "\\b[0-9][0-9]\\b" e t)
        (replace-match (number-to-string (+ 1 (string-to-int (match-string 0)))))))))
like image 123
TacticalCoder Avatar answered Sep 18 '22 22:09

TacticalCoder


You need to bind deactivate-mark to prevent it from being set see:

https://stackoverflow.com/a/11080667/903943

manual: http://www.gnu.org/software/emacs/manual/html_node/elisp/The-Mark.html#index-deactivate_002dmark-2801

like image 23
event_jr Avatar answered Sep 21 '22 22:09

event_jr