Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs: How to automatically insert space after colon in cc-mode derivatives

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?

Thank in advance.

like image 309
Ilya Khaprov Avatar asked Oct 09 '22 14:10

Ilya Khaprov


1 Answers

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 ": "))))))
like image 147
Tyler Avatar answered Oct 13 '22 11:10

Tyler