David Gomes
David Gomes

Reputation: 5845

How to change Emacs struct indents from 4 to 2 spaces

;; C++ Mode
(c-set-offset 'access-label '-2)
(c-set-offset 'inclass '4)
(setq c-default-style "k&r"
      c-basic-offset 2)

That is my C++ configuration. I want Emacs to indent structs with 2 spaces, just like it is indenting functions, if/while/for blocks, but currently it does this:

struct plane {
    //4 spaces'?
};

However, it does this:

typedef car {
  //2 spaces!
}

I tried using c-mode and c++-mode. When I do M-x c-set-offset inside a struct (where it is currently indenting with 4 spaces), it detects it as topmost-intro (0 spaces), even on C++ mode.

Basically, I want inside-structs to be indented with 2 spaces instead of 4 spaces as it is right now. (GNU Emacs 24.2.1)

Upvotes: 2

Views: 1810

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74118

You should remove your configuration and start with

(custom-set-variables
 '(c-basic-offset 2))

This sets all indentation at 2 spaces. Then you can improve from there on.

You can set c-offsets-alist for example, to customize indentation for various elements. Or c-hanging-braces-alist to configure, where your braces should be set, on the same or at the next line. And so on.

If you have installed CC Mode info files, you can browse through it with

Ctrl-h i mCC ModeRET

CC Mode doesn't distinguish between class and struct, for both the syntactic element is inclass. You can have a different indentation based on struct only with a Custom Line-Up Function

(defun my/c-lineup-inclass (langelem)
  (let ((inclass (assoc 'inclass c-syntactic-context)))
    (if (not inclass)
        0
      (save-excursion
        (goto-char (c-langelem-pos inclass))
        (if (looking-at "struct") 0 '+)))))

This function looks, if you are inside a class or struct or outside and returns an indentation level accordingly. You can then use this in your c-offsets-alist

(custom-set-variables
 '(c-offsets-alist (quote ((access-label . 0)
                           (topmost-intro . my/c-lineup-inclass)))))

Upvotes: 5

Related Questions