5

Suppose I have this code:

{
  "type"  : "home",
  "number":"212 555-1234"
}

I want my emacs to automatically insert space after colon in some modes.

Particularly I'm using javascript-mode based on cc-mode. Can it help?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Ilya Khaprov
  • 2,546
  • 14
  • 23

1 Answers1

4

The simplest way to do this would be something like this (in your .emacs):

(defun my-js-hook ()
  (local-set-key ":" '(lambda () (interactive) (insert ": "))))

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

More sophisticated alternatives include yasnippet or skeleton mode. They are probably overkill for something this simple, but are useful tools if you want more sophisticated templating.

EDIT: I'm not aware of any cc-mode magic that allows for different behaviour inside comments. I don't use cc-mode much, but I don't see anything obvious in the manual. Here's a bit of code that may do what you want though:

(defun my-js-hook ()
  (local-set-key ":" 
             '(lambda () 
                (interactive)
                (let ((in-comment-p))
                  (save-excursion
                    (setq in-comment-p (comment-beginning)))
                  (if in-comment-p 
                      (insert ":")
                    (insert ": "))))))
Tyler
  • 9,872
  • 2
  • 33
  • 57
  • Thank you for replay. This looks good but will override behavior for comments too. I asked specifically about cc-mode because I believe it can be done with some cc-mode magic (I believe they have something for that because the project exist since 1992) – Ilya Khaprov Oct 31 '11 at 18:28
  • you made my day :-) looks like it's somethings to start autoformat minor mode from =). But I don't understand this line: (save-excursion (setq in-comment-p (comment-beginning))). Why we can't initialize it in let? – Ilya Khaprov Oct 31 '11 at 22:32
  • `comment-beginning` moves point as a side effect. So it needs to be wrapped in `save-excursion`, otherwise the `:` will get inserted at the beginning of the comment. Maybe you could move the `save-excursion` into the let variable declarations? Try it out! – Tyler Oct 31 '11 at 22:38