Emacs C++-mode incorrect indentation?

前端 未结 5 1758
我在风中等你
我在风中等你 2020-12-07 12:54

I\'m running emacs 23 with c++-mode and having some indentation problems. Suppose I have this code:

void foo()
{
   if (cond)
     { <---
        int i;
          


        
5条回答
  •  不知归路
    2020-12-07 13:24

    The accepted answer is actually wrong. Emacswiki won't help.

    Insert following code into ~/.emacs:

    (defun fix-c-indent-offset-according-to-syntax-context (key val)
      ;; remove the old element
      (setq c-offsets-alist (delq (assoc key c-offsets-alist) c-offsets-alist))
      ;; new value
      (add-to-list 'c-offsets-alist (cons key val)))
    
    (add-hook 'c-mode-common-hook
              (lambda ()
                (when (derived-mode-p 'c-mode 'c++-mode 'java-mode)
                  ;; indent
                  (fix-c-indent-offset-according-to-syntax-context 'substatement-open 0))
                ))
    

    See http://blog.binchen.org/posts/ccjava-code-indentation-in-emacs.html for technical details.

    The key issue is c-set-offset is not reliable to detect syntax context any more (Emacs24.3.1). So the only reliable way is to analyze the original emacs code. The detailed steps to hack the code is listed in my article, basically you need read the function c-indent-line which is defined in /usr/share/emacs/24.3/lisp/progmodes/cc-cmds.el

    Some people complained that my setup does not work. Actually it works in all stable versions of Emacs (23.4, 24.3, 24.4) if you don't change default setup (The indention has different profiles, my setup is based on default profile).

    My key point is, on this specific issue, you need read the code.

提交回复
热议问题