3

I want to use Emacs for simple text annotation. Is there a command which surrounds a selected region of text with brackets or other characters?

Matthew Piziak
  • 3,430
  • 4
  • 35
  • 49
  • 2
    possible duplicate of [Wrapping selecting text in enclosing characters in Emacs](http://stackoverflow.com/questions/2951797/wrapping-selecting-text-in-enclosing-characters-in-emacs) – phils Mar 14 '12 at 21:06
  • Agreed. I'll delete this question shortly. Thank you for the link. – Matthew Piziak Mar 15 '12 at 03:45
  • I can't delete the question as answers exist, but I've flagged it as an exact duplicate. – Matthew Piziak Mar 18 '12 at 20:29

2 Answers2

4

The most structured and flexible way to do this is with autopair. I would say it has become the canonical solution for inserting paired delimiters and wrapping content in paired delimiters.

Joao (autopair's author) has also written yasnippet, which is a very popular templating library in Emacs. yasnippet can be used to wrap region in arbitrary text.

Both libraries model their behaviour on Textmate.

event_jr
  • 17,467
  • 4
  • 47
  • 62
2

I don't know if there is a standard emacs command to do this, but this one should do the trick:

(defun surround-brackets ()
  "Surround current region with brackets"
  (interactive)
  (when (use-region-p)
    (save-excursion
      (let ((beg (region-beginning))
            (end (region-end)))
        (goto-char end)
        (insert "]")
        (goto-char beg)
        (insert "[")))))

EDIT As noted in the comments, this question proposes the following solution, which is much simpler but requires you to use a key binding ending with [

(global-set-key (kbd "M-[") 'insert-pair)
Community
  • 1
  • 1
François Févotte
  • 19,520
  • 4
  • 51
  • 74