开发者

Emacs css-mode auto closing of braces and auto insertion of semi-colon after colon (ala Textmate)

I'm looking for a way to mimic Textmate's CSS editing behavior in Emacs.

开发者_如何学编程In Textmate, when adding a CSS property:

#element {}  <-- Braces auto close.
#element {background: ;}  <-- after typing the colon, the semi-colon is automatically inserted and the cursor is placed between them.

I have taken a look at several css-modes (and textmate.el) but cannot see that anyone has implemented this.

I have absolutely zero knowledge of emacs-lisp would be be willing to give it a shot and write something myself, but does anyone know if this has been done already?


You want to look at some examples of electric functions (the naming convention used when additional input or formatting is performed when particular visible characters are typed).

There's nothing special about the implementation. The key in question is bound within the mode's keymap to a function which does the work. Aside from the fact that you must handle the insertion of the character typed, it's just like any other keybinding.

cc-mode has several examples. The basic approach looks like this:

(define-key c-mode-base-map "{" 'c-electric-brace)

(defun c-electric-brace (arg)
  (interactive "*P")
  ;; [...]
  (self-insert-command (prefix-numeric-value arg))
  ;; [...]
  )

Admittedly c-electric-brace is a far more complicated function than you might be expecting, but it would be trivial to have a function which simply inserted the same number of }s after inserting the {s.

(defun my-electric-brace (arg)
  "Automatically add a closing '}' for every '{' inserted."
  (interactive "*P")
  (let ((count (prefix-numeric-value arg)))
    (self-insert-command count)
    (save-excursion
      (insert-char ?} count))))

(defun my-css-mode-hook ()
  (local-set-key (kbd "{") 'my-electric-brace))

(add-hook 'css-mode-hook 'my-css-mode-hook)

You might find that is a little simplistic, and there are circumstances in which you don't want the matching brace to be inserted, however. You would probably also want to deal with automatically removing matching braces when you delete one of them, by defining electric delete functions.

Your electric colon requirement is also less trivial than the brace, as it should only occur in the right context (although in practice you might get away with a naive implementation, as I don't think you would be typing colons in a CSS file that were not in the correct context.)

Hopefully this points you in the right direction, if you decide to write your own solutions.

Obviously you would want to read some tutorials on elisp, but for understanding the code above, just note that you can use C-h f (describe-function) to read the documentation for any elisp function (or M-x find-function to view the code).


For general purpose autopairing of all sorts of braces, etc you might want to take a look at autopair-mode.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜