美思 技術雜談:Edit HTML in Emacs with web-mode

Facebook Twitter LinkedIn LINE Skype EverNote GMail Yahoo Email

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)
{{< / highlight >}}

Set file extensions to relate them with web-mode:

```lisp
(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))
{{< / highlight >}}

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

```lisp
;; 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)
{{< / highlight >}}

I also set some syntax colors:

```lisp
;; 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")
{{< / highlight >}}

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

身為資訊領域碩士,美思認為開發應用程式的目的是為社會帶來價值。如果在這個過程中該軟體能成為永續經營的項目,那就是開發者和使用者雙贏的局面。

美思喜歡用開源技術來解決各式各樣的問題,但必要時對專有技術也不排斥。閒暇之餘,美思將所學寫成文章,放在這個網站上和大家分享。