1

I author web apps with the web-mode in GNU Emacs, and I use 2 spaces for indentation.

After I examined the web-mode source, I found out that the mode defaults to the standard-indent variable, which in turn defaults to 4; and if standard-indent is unset, web-mode defaults to 2. I'm not sure if I got the terminology correct, and I guess some older versions of Emacs didn't set the variable, so I got 2-space indent out of the box.

Excerpt from web-mode.el:

(defcustom web-mode-css-indent-offset
  (if (and (boundp 'standard-indent) standard-indent) standard-indent 2)
  "CSS indentation level."
  :type 'integer
  :safe #'integerp
  :group 'web-mode)

Obviously, the custom variables' defaults are set during load.

How can I set standard-indent to 2 while web-mode loads? Given the way web-mode initializes its costomization variables, I think it has to be done while the mode is being loaded into Emacs, and not when I enter the major mode. How do I do that?

1 Answer 1

-1
(add-hook 'web-mode-hook
          (lambda () (setq standard-indent 2)))

99% of all modes define at least one hook variable. Hook variables just hold a list of functions that will be called in the case of some event, usually upon entering some specific mode. Any time you want something to happen when a mode is activated, you want to add it to a hook function.

Edit: Yes, you're right. Just change the web-mode-css-indent-offset variable instead:

(add-hook 'web-mode-hook
          (lambda () (setq web-mode-css-indent-offset 2)))

Incidentally, since the web-mode-css-indent-offset has a name starting with web-mode, you can be fairly certain that no other mode is going to care what value it has. So you could just customize it. Type M-x customize-variable web-mode-css-indent-offset and it'll give you a UI that tells you all the help information about the variable, as well as letting you edit the and save the value for the variable.

2
  • 1
    standard-indent isn't automatically buffer-local, so you want to setq-local. I would also use a named function -- lambdas in hook variables aren't a good idea IMHO.
    – phils
    Aug 28, 2020 at 5:57
  • Didn't work, I updated the question.
    – DannyNiu
    Aug 28, 2020 at 5:59

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.