Emacs HTML Tips

By Xah Lee. Date: . Last updated: .

This page is a tutorial on working with HTML.

Which HTML Mode To Use?

html-mode for Simple HTML (in emacs)

When you open a file ending in “html”, it'll automatically open in html-mode. This is a basic HTML mode. It is writen by SGML/XML expert James Clark, in 1990s.

nxml-mode for Valid XHTML/XML (in emacs)

If your code is valid XML, you should use nxml-mode. “nxml-mode” is a mode for editing XML documents, also written by SGML/XML expert James Clark, in 2000s. It has the feature of real-time XML validation.

nxml-mode comes with emacs 23.1.1, but is not the default mode loaded when you open a file ending in “.xml”. (This is fixed in 23.2.x) To load “nxml-mode”, just type 【Alt+x nxml-mode】. To set emacs to always use nxml when files ending in “.xml” is opened, see: Emacs: Set File to Open in a Major Mode, or simply set a alias like this: (defalias 'xml-mode 'nxml-mode). [see Emacs: Use Alias for Fast M-x]

Mixed XHTML/XML/CSS/JavaScript/PHP

For HTML mixed with {CSS, JavaScript, PHP, ASP, JSP}, you have the following choices:

About This Tutorial

The following tips are about using html-mode. However, this page also gives you several custom commands written in elisp. These elisp commands can be useful in any mode.

Insert HTML Tag

Emacs: Insert HTML Tag

Delete HTML Tag

How to delete a tag?

Alt+x sgml-delete-tagCtrl+c Ctrl+d】. This will delete both start/end tags where the cursor is on.

WARNING: if your HTML tags do not always have ending tags, it might delete the wrong tag.

Jump to Tag

How to make the cursor jump to ending tag?

Alt+x sgml-skip-tag-forwardCtrl+c Ctrl+f】.

Alt+x sgml-skip-tag-backwardCtrl+c Ctrl+b】.

See also: Emacs: Move Cursor to Bracket/Quote.


How to replace & to &?

Elisp: Command to Replace HTML Entities with Unicode Characters

How to preview in a browser?

Alt+x browse-url-of-bufferCtrl+c Ctrl+v】.

Alt+x sgml-tags-invisibleCtrl+c Tab】, which will hide all the tags. Call again to show tags.

Compact CSS Source Code

You can define a command to compact CSS code. See: Emacs: CSS Compressor.

Working with Color Values

emacs hexcode highlight 32718

See: Emacs: Working with CSS Color Values.

More Tips

How to view the image in a image tag?

Suppose this is your text:

<img src="img/emacs_logo.png">

Move your curser on the file path, then Alt+x find-file-at-point. You should give it a key such as F8. [see Emacs: How to Define Keys]

How to view image thumbnails in a directory?

emacs tumme
emacs image-dired, showing image thumbnails.

See: Emacs: View Image Thumbnails

How to open the current directory in OS's desktop?

See: Emacs: Open File in External App.

Like my tutorial? Put $5 at patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

Ask me question on patreon