Emacs - override indentation

2019-02-04 09:25发布

问题:

I have a multiply nested namespace:

namespace first {namespace second {namespace third {
              // emacs indents three times
    // I want to intend here
} } }

so emacs indents to the third position. However I just want a single indentation.
Is it possible to accomplish this effect simply?

回答1:

Use an an absolute indentation column inside namespace:

(defconst my-cc-style
  '("gnu"
    (c-offsets-alist . ((innamespace . [4])))))

(c-add-style "my-cc-style" my-cc-style)

Then use c-set-style to use your own style.

Note that this only works in c++-mode, c-mode doesn't know 'innamespace'.



回答2:

With c++-mode in Emacs 23, I had to do like this:

(defun my-c-setup ()
   (c-set-offset 'innamespace [4]))
(add-hook 'c++-mode-hook 'my-c-setup)

To disable the indentation in namespaces altogether, change [4] to 0.



回答3:

OK so this seems to work in both emacs 21 and 22 at least:

(defun followed-by (cases)
  (cond ((null cases) nil)
        ((assq (car cases) 
               (cdr (memq c-syntactic-element c-syntactic-context))) t)
        (t (followed-by (cdr cases)))))

(c-add-style  "foo"      
              `(( other . personalizations )
        (c-offsets-alist
         ( more . stuff )
         (innamespace
          . (lambda (x) 
          (if (followed-by 
               '(innamespace namespace-close)) 0 '+))))))

(The first solution doesn't support constructs like

namespace X { namespace Y {
    class A;
    namespace Z {
        class B;
    }
}}

)



回答4:

If you simply want to input a literal tab, rather than changing emacs' indentation scheme, C-q TAB should work.



回答5:

Unfortunately, I don't think emacs has a separate style for a namespace inside another namespace. If you go to the inner line and do C-c, C-o, you can change the topmost-intro style, and if you run customize-variable c-offsets-alist you can edit all the different indentation options emacs has, but one doesn't exist for your specific use case. You would need to write it manually in elisp



回答6:

This works for me, inherit from cc-mode and replace the name space indenting to 0, aka, disable it's indent.

(defconst my-cc-style
  '("cc-mode"
    (c-offsets-alist . ((innamespace . [0])))))

(c-add-style "my-cc-mode" my-cc-style)