Is it possible to auto-complete parentheses or quotation marks in emacs?

你说的曾经没有我的故事 提交于 2019-12-05 08:06:00

The basic variant would be AutoPairs. The same effect but a little more sophisticated can also be achieved with YASnippet.

If you type M-(, that will insert both a ( and a ), and leave point in between; if you then type M-), that will move point across the closing ). I use this all the time.

There is also a mode called "paredit" (available from http://mumble.net/~campbell/emacs/paredit.el) which does this sort of thing for quotes as well, and probably other stuff.

Paredit-mode inserts matching closing elements by default, so the while typing you'll see something like printf() then printf("") and the cursor would be positioned inside quotes.

I'm using code from http://cmarcelo.wordpress.com/2008/04/26/a-little-emacs-experiment/ to do "electric pairs". As I descibe in my blog other modes have problems with Python's triple quoted strings. (A Python peculiarity)

My 5 cents here as well.

(setq skeleton-pair t)
(defvar skeletons-alist
  '((?\( . ?\))
    (?\" . ?\")
    (?[  . ?])
    (?{  . ?})
    (?$  . ?$)))

(global-set-key (kbd "(") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "[") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "\"") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "\'") 'skeleton-pair-insert-maybe)

Next advice will enable the backspace to deletes the pairs: a(|)b -> ab

(defadvice delete-backward-char (before delete-empty-pair activate)
  (if (eq (cdr (assq (char-before) skeletons-alist)) (char-after))
      (and (char-after) (delete-char 1))))

Next advice will make backward-kill-word (for me is M-backspace) to delete matching par even if it separated by other text; very handy.

(defadvice backward-kill-word (around delete-pair activate)
  (if (eq (char-syntax (char-before)) ?\()
      (progn
 (backward-char 1)
 (save-excursion
   (forward-sexp 1)
   (delete-char -1))
 (forward-char 1)
 (append-next-kill)
 (kill-backward-chars 1))
    ad-do-it))

I am trying to move now to paredit, though.

The autopair minor mode does exactly what you ask for.

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