How can I set Emacs tab settings by file type?

Viewed 10905

I need to be able to set the tab settings for the following file types:

  • .rb: 2 soft spaces
  • .css, .html.erb: 4 space tabs

I have tried the following, but none of it seems to alter my default tab settings for each of the file types.

;; js-mode-hook has also been tried
(add-hook 'javascript-mode-hook 
      '(lambda() 
        (setq tab-width 4)))

(add-hook 'css-mode-hook 
      '(lambda() 
        (setq tab-width 4)))

(add-hook 'html-mode-hook 
      '(lambda() 
        (setq tab-width 8)))

I am pretty new to emacs so my knowledge of configuration is pretty low.

5 Answers

js-mode uses js-indent-level so put (setq js-indent-level 4) into your ~/.emacs (shouldn't have to be in a hook, even, but if you're wondering, it's js-mode-hook, not javascript-mode-hook).

If setting tab-width doesn't change your indentation level for a certain mode, it's often simplest to just open the source for that mode. I found this variable by doing C-h f js-mode, clicking the link "js.el", then searching for "indent", second hit from the top.


However, if you collaborate a lot with other people, it's often better to put a cookie at the top of the file. I typically do // -*- tab-width: 8 -*- in the file, and then I have stuff like this in my ~/.emacs:

(defvaralias 'c-basic-offset 'tab-width)
(defvaralias 'cperl-indent-level 'tab-width)
(defvaralias 'perl-indent-level 'tab-width)
(defvaralias 'js-indent-level 'tab-width)

so that I have less variables to deal with (and don't have to get warnings about the file-local variable being unsafe or whatever if the mode-writer forgot to declare it as safe)

Related