In my ~/.emacs I have among other things, the following, at the end:

(define-key c++-mode-map (kbd "<C-tab>") 'company-irony)
(define-key c++-mode-map (kbd "<tab>") 'tab-to-tab-stop)
(define-key c++-mode-map (kbd "<backspace>") 'delete-backward-char)
(define-key c-mode-map (kbd "<C-tab>") 'company-irony)
(define-key c-mode-map (kbd "<tab>") 'tab-to-tab-stop)
(define-key c-mode-map (kbd "<backspace>") 'delete-backward-char)
(setq-default indent-tabs-mode t)
(setq tab-width 4)

Now, when I open Emacs within some c++ project, my TAB inserts 2 spaces instead of inserting 1 tab.

That, until I manually open ~/.emacs, press C-c C-e to evaluate current buffer. Then, back into C++ file, pressing TAB now correctly inserts TAB of size 8 (?). Until I manually execute M-: (setq tab-width 4). Now everything is correct.

Several questions:

  • why is my .emacs seem to be ignored on launch?
  • why tab size is still 8 when I specified 4 in .emacs?
  • 1
    Without seeing your entire init file there really is no way of answering those questions. Try eliminating everything except those 8 lines and trying again. You will probably find that it works as expected. Then add back elements from your init file until you find what is causing it to behave unexpectedly. If that’s not enough to clue you in, ask a question about your discovery.
    – db48x
    Dec 4, 2022 at 20:06

1 Answer 1


Fixed by wrapping those line into eval-after-load:

(eval-after-load 'cc-mode
     (define-key c++-mode-map (kbd "<C-tab>") 'company-irony)
     (define-key c++-mode-map (kbd "<tab>") 'tab-to-tab-stop)
     (define-key c++-mode-map (kbd "<backspace>") 'delete-backward-char)
     ;;(setq indent-tabs-mode t)
     ;;(setq tab-width 4)

EDIT: as the comment says, indeed, need to modify those variables in every buffer, so:

(add-hook 'c++-mode-hook (lambda ()
               (setq c-syntactic-indentation nil)
               (setq indent-tabs-mode t)
               (setq tab-width 4)

  • 2
    tab-width and indent-tabs-mode are automatically buffer-local variables -- you must set them in each and every buffer you want them to be set. You need to write (defun) a function for configuring your c++-mode settings, and then add that function to c++-mode-hook (which is run in each such buffer).
    – phils
    Dec 5, 2022 at 0:44
  • Again, I recommend defining a named function. It's bad practice to add lambda forms to hook variables, as it makes them unnecessarily awkward to inspect and/or update. You want hook variables to be a simple list of symbols.
    – phils
    Dec 22, 2022 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.