Wrapping selecting text in enclosing characters in Emacs

爱⌒轻易说出口 提交于 2019-11-30 00:04:39

For parens you can do M-(. For brackets/braces/quotes you could do:

(global-set-key (kbd "M-[") 'insert-pair)
(global-set-key (kbd "M-{") 'insert-pair)
(global-set-key (kbd "M-\"") 'insert-pair)

Note that if you don't have a region highlighted, it will just insert the pair of whatevers and put the cursor in between them. Also handy for deleting matching whatevers is

(global-set-key (kbd "M-)") 'delete-pair)

EDIT:

Good point in the comments about overriding backward-paragraph. You could bind it to C-{, which might interfere with something in a major mode. insert-pair takes the last key and does a lookup to see what pair to insert, so if you don't want to bind it to something-{ you could bind to this function instead:

(defun my-insert-braces ()
  (interactive)
  (if (region-active-p)
      (insert-pair 1 ?{ ?})
    (insert "{}")
    (backward-char)))

I use http://www.emacswiki.org/emacs/ParEdit. M-( does exactly this.

hekevintran

Autopair is the best one of these tools

https://github.com/capitaomorte/autopair

You can have a look at wrap-region.

I'd take a look also at skeleton-mode http://ggorjan.blogspot.com/2007/05/skeleton-pair-mode-in-emacs.html

It's very flexible expecially for parentheses.

There is textmate-mode.

From Emacswiki:

See textmate-mode for an attempt of having the TextMate behaviour for parenthesis and quotes (auto-closing, overwriting, smart delete).

http://code.google.com/p/emacs-textmate/

Since Emacs 24.1(released 2012-06).
Put this in your emacs init: (electric-pair-mode 1).
Now If you select a word and hit (, it will become (word). Same for ", [, { etc.

There's now Corral as well. Its "do what I mean" behavior makes this process a lot faster than manually selecting the text and hitting the key.

(disclaimer: I'm the author)

If you use smartparens just select the text and then type the pair. Smartparens wiki: Wrapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!