Search code examples
emacsemacs26

Emacs semicolon presses indent to width of entire previous line, declaring private class variables. How to fix & stop? (c-electric-semi&comma?)


Everything is indented normally in my .cpp file until the moment I press the semicolon ; on the following lines --- at which point emacs indents all the way to the full length of the last line typed...

This oddly doesn't happen if I remove the access modifier and declare vars int x and int y for any class or struct..

class Blah {
  private int x;
               private int y;
                            private int z;
};

If I highlight the whole field and press < TAB >, Emacs views this as the proper indent for the region. Can't seem to find anything else related on this besides other qs on indent customization


Additional details:

C-h k ; yields this description, so it might have to do with this feature ---- though I don't understand because the indentation described appears to refer to the immediate next newline not the current the cursor is on.

; runs the command c-electric-semi&comma (found in c++-mode-map),
  which is an interactive compiled Lisp function in ‘cc-cmds.el’.

It is bound to ,, ;.

(c-electric-semi&comma ARG)

Insert a comma or semicolon.

If ‘c-electric-flag’ is non-nil, point isn’t inside a literal and a
numeric ARG hasn’t been supplied, the command performs several electric
actions:

(a) When the auto-newline feature is turned on (indicated by "/la" on
the mode line) a newline might be inserted.  See the variable
‘c-hanging-semi&comma-criteria’ for how newline insertion is determined.

(b) Any auto-newlines are indented.  The original line is also
reindented unless ‘c-syntactic-indentation’ is nil.

(c) If auto-newline is turned on, a comma following a brace list or a
semicolon following a defun might be cleaned up, depending on the
settings of ‘c-cleanup-list’.


Solution

  • ; is one of many keys that triggers the "correct this line's indentation" command. There's nothing special about ; here, it's just that Emacs normally keeps your indentation right according to the style defined for the file.

    As 0x5453 says in a comment, your C++ file is syntactically invalid, and the indenter is trying its best to come up with a reasonable indentation for this incorrect file. If you fix your code to be legal, the indentation will also be resolved.