Search code examples
emacs

Emacs openfile in terminal don't load configuration correctly. But open file in emacs do load configuration correctly


Emacs openfile in terminal don't load configuration correctly. But open file in emacs do load configuration correctly.
I have tried several emacs configuration for cpp:

(eval-after-load "cc-vars" '(lambda() (c-set-style "linux")))

Another one

(add-hook 'c-mode-hook '(lambda() (c-set-style "linux")))

Another one

(eval-after-load "cc-vars" '(setq c-default-style "linux")))

If I type emacs filename they can't be loaded. It seems the emacs always load the default gnu style.

After I type M-x c-mode They can be load correctly. Or I open emacs in terminal and then C-x C-f load the file, those configuration will also be loaded.

Is there any reason for this?

I also tried putting

(c-set-style "linux")

in configuration directly.
They work with emacs filename. But when I open non cpp file there will be an error says can't apply c-set-style on that file.


Solution

  • From the CC-mode manual:

    When you create a new buffer, its style will be set from c-default-style.

    From the Emacs manual

    You can also set the variable c-default-style to specify the default style for various major modes

    From the documentation of the c-set-style function:

    Set the current buffer to use the style STYLENAME.

    This means that any call to c-set-style must ensure that the current buffer is the one you want to set the style for; placing such a call at the toplevel in your init file is then definitely a bad idea.

    The simplest fix is just to put (setq c-default-style "linux") at the top level, and then wrap it up in an eval-after-load if you really need one. The variable is intended for this, and hooks should be reserved to control more precisely the style of the current file if you need it (as is suggested by c-default-style documentation).

    It seems that for me, (eval-after-load "cc-vars" '(setq c-default-style "linux")) works fine: if I open any file covered by CC-mode, the Linux style is applied. Note that c-mode and CC modes are different things, that there exist the c-mode-hook, c++-mode-hook, c-mode-common-hook and they are all different and will run at different times.