Easy indentation setup in Emacs for web development

  |   Source

CREATED: 2015-04-02

UPPDATE: 2015-10-05

This question has been asked so many times, so I answered it here once for all.

Solution

Insert below code into ~/.emacs:

(defun my-setup-indent (n)
  ;; java/c/c++
  (setq c-basic-offset n)
  ;; web development
  (setq coffee-tab-width n) ; coffeescript
  (setq javascript-indent-level n) ; javascript-mode
  (setq js-indent-level n) ; js-mode
  (setq js2-basic-offset n) ; js2-mode, in latest js2-mode, it's alias of js-indent-level
  (setq web-mode-markup-indent-offset n) ; web-mode, html tag in html file
  (setq web-mode-css-indent-offset n) ; web-mode, css in html file
  (setq web-mode-code-indent-offset n) ; web-mode, js code in html file
  (setq css-indent-offset n) ; css-mode
  )

(defun my-office-code-style ()
  (interactive)
  (message "Office code style!")
  (setq indent-tabs-mode t) ; use tab instead of space
  (my-setup-indent 4) ; indent 4 spaces width
  )

(defun my-personal-code-style ()
  (interactive)
  (message "My personal code style!")
  (setq indent-tabs-mode nil) ; use space instead of tab
  (my-setup-indent 2) ; indent 2 spaces width
  )

(defun my-setup-develop-environment ()
  (interactive)
  (let ((proj-dir (file-name-directory (buffer-file-name))))
    ;; if hobby project path contains string "hobby-proj1"
    (if (string-match-p "hobby-proj1" proj-dir)
        (my-personal-code-style))

    ;; if commericial project path contains string "commerical-proj"
    (if (string-match-p "commerical-proj" proj-dir)
        (my-office-code-style))))

;; prog-mode-hook requires emacs24+
(add-hook 'prog-mode-hook 'my-setup-develop-environment)

As you can see, you can use `prog-mode-hook` and `buffer-file-name` to do the per project setup easily.

For any new programming language not covered in this post, there are two steps:

  • Know your major-mode by pressing `Alt-X major-mode ENTER`. Say you got "org-mode".
  • Google "Emacs org-mode indent offset"

Tips (OPTIONAL)

  • Please note the first paramter of `string-match-p` is actually regular expression. So you can write regular expression like "\\(/proj1\\|work.org\\)"
  • Emacs gives you full freedom to setup project. If you prefer per computer setup instead of per project setup, you only need re-write `my-setup-develop-environment',
(defun my-setup-develop-environment ()
  (interactive)
  (let ((hostname (with-temp-buffer
                    (shell-command "hostname" t)
                    (goto-char (point-max))
                    (delete-char -1)
                    (buffer-string))))

  (if (string-match-p "home-pc" hostname)
      (my-personal-code-style))

  (if (string-match-p "office-pc" hostname)
      (my-office-code-style))))
  • Instead of press TAB manually to indent code line by line, you can select a region and press `Alt-x indent-region ENTER`
  • Because I use Evil, indenting the whole file is as simple as pressing `gg=G`
Comments powered by Disqus