editor  

Dec 2, 2014 • Michael Chen

Emacs has a built-in html-mode for HTML files. It is common that HTML files comes with other lauguages like CSS, JavaScript, PHP and so on. The built-in html-mode cannot handle these non-HTML parts well. For example, the indent of these parts in html-mode doesn’t work well. If you need an alternative major-mode for HTML, you can consider web-mode.

web-mode.el is an Emacs major-mode for editing web templates; it supports many features including syntax highlighting, smart indentation, compatibility with many template engines, comment and uncomment, etc. Since web-mode is a single file, just place it in your personal lisp files to install it. Like ~/.emacs.d/site-lisp. Add the following code in ~/.emacs to init it:

(require 'web-mode)

Set file extensions to relate them with web-mode:

(add-to-list 'auto-mode-alist '("\\.phtml\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.tpl\\.php\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.[agj]sp\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.as[cp]x\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.erb\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.mustache\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.djhtml\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.html?\\'" . web-mode))

That’s all needed steps to install web-mode.el. Personally, I set indent rules for eye candy:

;; set tab and space for web-mode
(setq web-mode-markup-indent-offset 2)
(setq web-mode-css-indent-offset 2)
(setq web-mode-style-padding 2)
(setq web-mode-script-padding 2)

I also set some syntax colors:

;; set color for web-mode
(set-face-attribute 'web-mode-doctype-face nil :foreground "SlateBlue")
(set-face-attribute 'web-mode-html-tag-face nil :foreground "MediumBlue")
(set-face-attribute 'web-mode-html-tag-bracket-face nil :foreground "red")
(set-face-attribute 'web-mode-html-attr-name-face nil :foreground "orange")
(set-face-attribute 'web-mode-css-at-rule-face nil :foreground "Pink3")
(set-face-attribute 'web-mode-variable-name-face nil :foreground "DarkGreen")
(set-face-attribute 'web-mode-comment-face nil :foreground "red")

You can check the website of web-mode to set your own perferred settings. web-mode lets HTML editing in Emacs more productive.