Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an Emacs function to wrap the marked region with specified text

I'm not too familiar with elisp, and am trying to learn. In emacs, I'd like to be able to do the following:

  1. Mark via C-space
  2. Go to where I want the the marking to end, so I have a region that is highlighted, suppose it is "highlighted text"
  3. Hit a key-sequence
  4. Have emacs ask me to input some text, say "plot", and
  5. Have that highlighted text change to be "plot(highlighted text)". That is, I'd like to wrap the highlited text with parentheses and precede it with the text I input.

    (defun wrap-text ()
        )
    

I suppose the input of the function would be the highlighted text, but I don't know where to start looking. The other hard part would be the input text part. Could someone guide me? Thanks.

like image 802
Vinh Nguyen Avatar asked Nov 19 '09 04:11

Vinh Nguyen


2 Answers

For your case, this should work:

(defun wrap-text (b e txt)
  "simple wrapper"
  (interactive "r\nMEnter text to wrap with: ")
  (save-restriction
    (narrow-to-region b e)
    (goto-char (point-min))
    (insert txt)
    (insert "(")
    (goto-char (point-max))
    (insert ")")))

(global-set-key (kbd "C-x M-w") 'wrap-text)
like image 153
Trey Jackson Avatar answered Sep 18 '22 19:09

Trey Jackson


Something a bit closer to your version, but with some changes :

  • you can use 'let' to create a local-variable
  • region-beginning and region-end gives you the equivalent of what trey did with

Here is an example :

 (defun wrap-in-function ()
   "Wrap marked region with a specified PREFIX and closing parentheses."
   (interactive)
   (let ((prefix (read-from-minibuffer "function: ")))
     (save-excursion
       (goto-char (region-beginning))
       (insert (concat prefix "(")))
     (save-excursion
       (goto-char (region-end))
       (insert ")"))))

Another difference between the two versions is the position of the point after you called the function ; trey version might be better to use (matter of taste).

EDIT : edited following vinh remarks.

like image 43
phtrivier Avatar answered Sep 21 '22 19:09

phtrivier