I often have a situation where I need to apply text around a region. For HTML and simple cases there are libraries for this already. But what about the general case? I'd like to be asked what I'm gonna insert beginning and end of the region.
I googled around and found this post by John D. Cook. He demonstrates how to build a simple interactive function to get HTML/XML tags around region easily. From that I modified the function to ask twice.
(defun tag-word-or-region (text-begin text-end) "Surround current word or region with given text." (interactive "sStart tag: \nsEnd tag: ") (let (pos1 pos2 bds) (if (and transient-mark-mode mark-active) (progn (goto-char (region-end)) (insert text-end) (goto-char (region-beginning)) (insert text-begin)) (progn (setq bds (bounds-of-thing-at-point 'symbol)) (goto-char (cdr bds)) (insert text-end) (goto-char (car bds)) (insert text-begin)))))
More importantly, this function can be also used as an auxiliary tool, for instance when you want to bind keys to map some specific bits of text.
(defun tag-php () (interactive) (tag-word-or-region "<?php " "?>"))
I would suggest a different approach. When there is a region, by definition
point must be at the beginning (or end) of the region, and
mark will be at the end (or beginning). Which means you can enter the text you want at point, and then use
C-x C-x, to jump to the other end of the region. Enter the second half of your wrapper and you're done.
You don't get explicitly asked prompted for the insertion text, but I can't imagine there would be a way to accomplish the same thing with less effort.
Just for the sake of variety:
Another way to do this with some arbitrary start and end text would be to use
replace-regexp on the region: match
.+ and replace with
before \& after, or whatever text you want to use for
You could write a command do to this, but I'm thinking of a case where in a given file you want to apply the same start/end text in multiple places. You can record a macro or just use minibuffer history to repeat on another region.
Of course if the text you want to wrap can be expressed as a regular expression then you won't even need to select a region and can do a
query-replace-regexp on the buffer, but presumably the text you want to wrap is not that consistent.