0

I'm trying to set the indentation in C++ files to be 4 spaces. To achieve this I have the following config:

(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)

(defun init-c-cpp ()
  (setq c-basic-offset 4)
  (setq indent-line-function 'c-indent-line)
  )

(add-hook 'c++-mode-hook 'lsp 'init-c-cpp '(lambda () (print "hello")))

I know there are already questions concerning this topic, but none of the answers worked for me.

The problem is that after opening a .cpp file in C++ mode, indentation is still at 2 spaces. In fact, C-h v c-basic-offset inside a C++ mode buffer shows that it is set to 2. Also "hello" is not printed to the minibuffer upon opening the C++ file, which I expected to happen. It seems like the hook is not being called at all. Why could this be? Thank you.

0

1 Answer 1

2

add-hook takes only a single hook function to add, plus two other optional arguments.

Do this instead:

(add-hook 'c++-mode-hook 'lsp)
(add-hook 'c++-mode-hook 'init-c-cpp)
(add-hook 'c++-mode-hook (lambda () (print "hello"))

(Note also that lambdas are not quoted.)

You can read the documentation for add-hook, which will tell you what arguments it takes, by typing C-h f and then typing the function name. If point is already on something that looks like a function name, it will be the default and you can just hit enter at the prompt.

4
  • This worked. Thanks. Also, why does the accepted answer in this question assert that chaining multiple hook functions is valid? emacs.stackexchange.com/questions/45322/…
    – Ciprum
    Jul 21 at 21:13
  • You misread that answer. matteol recommended creating a single function which calls the others, and then adding that one function to the hook list.
    – db48x
    Jul 21 at 22:06
  • "You can add multiple functions to the same hook" in the linked answer meant "you can call add-hook multiple times for the same hook, adding a different function each time." In this answer, c++-mode-hook is the hook, to which multiple functions are being added.
    – phils
    Jul 22 at 3:17
  • 1
    I edited the answer to remove the ambiguity
    – matteol
    Jul 22 at 5:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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