Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In emacs, how to disable comment auto-indent in C/C++?

Sometimes I want to have temporary comments fully left justified on a line (//) or a block of lines /* */. However, CC Mode overrides this by auto-indenting upon typing the second key. In general, I like auto-indent for keywords, etc, but I would prefer it to be disabled for comments. (update: ie. I want to disable the way comment indentation is triggered by the c-electric- key-bindings, but comments should still indent normally othewise)

I've tried putting these lines in .emacs, but it doesn't prevent the behaviour.

(c-electric-slash nil)
(c-electric-star nil)
like image 569
Peter.O Avatar asked Jun 16 '12 06:06

Peter.O


1 Answers

Short answer:

(eval-after-load 'cc-mode
  '(progn
     (define-key c-mode-base-map "/" 'self-insert-command)
     (define-key c-mode-base-map "*" 'self-insert-command)))

Here's how I go about it:

Find out the function bound to /: C-h k /

It says "/ runs the command c-electric-slash, which is an interactive compiled Lisp function in 'cc-cmds.el'".

(If you don't see the link to cc-cmds.el, then you don’t have the elisp sources installed. Assuming you're not on Windows, you can use your system’s package manager to install the emacs-el package and try again.)

Follow that link to open cc-cmds.el. Searching for c-electric-slash doesn't find anything other than the function definition, so the keys aren't bound in this file. Searching in cc-mode.el from this directory reveals:

(define-key c-mode-base-map "/" 'c-electric-slash)

Now we know the name of the "keymap" in which to override the / keybinding.

If you add something like this to your init file, you'll probably get an error on startup:

(define-key c-mode-base-map "/" 'self-insert-command)

...because your init file is loaded before cc-mode.el is, and c-mode-base-map is undefined. So we use eval-after-load (as at the top of my answer). The first argument, 'cc-mode, has to match the provide statement at the very end of cc-mode.el. If you don't know what the progn means, do C-h f progn.

If you like this style of learning/discovering Emacs, you might consider reading my "How to learn Emacs".

like image 144
David Röthlisberger Avatar answered Oct 07 '22 13:10

David Röthlisberger