HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Emacs and HTML Tips

Advertise Here For Profit

Xah Lee, 2006-09, …, 2010-02, 2010-03-15

On the website xahlee.info, over 3000 HTML pages are manually created with emacs over a decade since 1998. This page provides some tips about using Emacs to create and edit HTML documents.

Which Mode To Use?

HTML

When you open a file ending in “html”, it'll automatically open in html-mode. This is a basic html mode.

If you work with mixed HTML, CSS, JavaScript, PHP, ASP, JSP codes, you are better with html-helper-mode (html-helper-mode is not bundled with FSF's GNU Emacs.)

XHTML

If your code is valid XML, you should use nxml-mode. nxml-mode is a mode for editing XML documents, written by XML expert James Clark, and has the feature of real-time xml validation. You should use nxml mode for all your xml needs.

nxml-mode comes with emacs 23, but is not the default mode loaded when you open a file ending in “.xml”. 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: How to Install Emacs Packages.

If your code has lots of CSS, JavaScript, PHP, ASP, JSP codes mixed, and is not likely valid xml, you should try the html-helper-mode or nXhtml mode. (html-helper-mode tries to be practical for all html/xhtml files. nXhtml mode is based on nxml mode, but as of mid 2009, i did not find this package very robust.)

About This Tutorial

The following tips is about using html-mode. However, this page also gives you several custom commands written in elisp. These elisp commands can be useful regardless which html/xml mode you use.

Inserting HTML Tags with Emacs

See: Inserting HTML Tags with Emacs.

Deleting Tags and Move By Tags

How to delete a tag?

Put your cursor on or inside the tag, then press 【Ctrl+c Ctrl+d】 (sgml-delete-tag). This will delete both starting and ending tags. Very convenient.

How to make the cursor jump to ending tag?

Type 【Ctrl+c Ctrl+f】 (sgml-skip-tag-forward) and【Ctrl+c Ctrl+b】 (sgml-skip-tag-backward).

You can assign a easier shortcut of 【Alt+】 and 【Alt+】. Use the following code:

(add-hook 'html-mode-hook
 (lambda ()
 (define-key html-mode-map (kbd "<M-left>") 'sgml-skip-tag-backward)
 (define-key html-mode-map (kbd "<M-right>") 'sgml-skip-tag-forward)
 )
)

If you don't need to do indenting in your html source, you can make the tab key to jump to the next ending tag (without matching anything), and shift-tab to jump to previous beginning tag. The following elisp code does it:

(defun html-next-content ()
  "Move cursor to the end of next html tag's content."
  (interactive)
  (forward-char 1)
  (search-forward-regexp "</")
  (backward-char 2)
  )

(defun html-previous-content ()
  "Move cursor to the beginning of previous html tag's content."
  (interactive)
  (search-backward-regexp ">\\([^§]+?\\)</")
  (forward-char 1)
  )

(add-hook 'html-mode-hook
 (lambda ()
 (local-set-key (kbd "<f7>") 'html-previous-content)
 (local-set-key (kbd "<f8>") 'html-next-content)
 )
)

Others

How to replace “&” by “&amp;” in a region?

Place the following in your emacs init file:

(defun replace-string-pairs-region (start end mylist)
  "Replace string pairs in region."
  (save-restriction 
    (narrow-to-region start end)
    (mapc
      (lambda (arg)
        (goto-char (point-min)) 
        (while (search-forward (car arg) nil t) (replace-match (cadr arg)) )
      ) mylist
    )
  )
)

(defun replace-html-chars (start end)
  "Replace “<” by “&lt;” and other similar HTML chars that needs to be encoded."
  (interactive "r")
(replace-string-pairs-region start end '(
("&" "&amp;")
("<" "&lt;")
(">" "&gt;")
    )
  )
)

With the above code, you can select a region, then press 【Alt+x replace-html-chars】, and have all “&”, “>”, “<” replaced by their encoded entity. You can define a keyboard shortcut for easy operation.

You can also use the code to replace some HTML entities by their actual unicode characters. For example:

text to replaceresult
&ldquo;
&rdquo;
&eacute;é
&copy;©
->
=>
Piπ
Infinity

This makes the HTML source code more elegant and readable. You need to declare your charset as one of unicode encodings. See Character Sets and Encoding in HTML.

How to preview in a browser?

Press 【Ctrl+c Ctrl+v】 (browse-url-of-buffer). You can also get a textual preview by pressing 【Ctrl+c Tab】 (sgml-tags-invisible), which will hide all the tags. Press 【Ctrl+c Tab】 again to show tags.

More Esoteric Tips

In CSS, is there a way to have color values colored by themselves?

Put the following code in your emacs init file:

(defvar hexcolour-keywords
  '(("#[abcdef[:digit:]]\\{6\\}"
     (0 (put-text-property
         (match-beginning 0)
         (match-end 0)
         'face (list :background 
                     (match-string-no-properties 0)))))))
(defun hexcolour-add-to-font-lock ()
  (font-lock-add-keywords nil hexcolour-keywords))

(add-hook 'css-mode-hook 'hexcolour-add-to-font-lock)

With the above code, when you open a css file, any text of color spec in hex form will be colored with its value, as the background color. Here's a sample screenshot:

emacs hexcode highlight

If you want it work in html file too, repeat the “add-hook” line with “'html-mode-hook”.

Is there a way to show a color palette and their RGB values?

Use the menu 〖Edit▸Text Properties▸Display Colors〗 or type 【Alt+x list-colors-display】. This is useful as a color reference for HTML coding. To show their RGB value in decimal: 【Ctrl+h v color-name-rgb-alist】.

emacs showing colors

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 press 【Alt+x ffap】. (ffap is a alias to the command find-file-at-point) You can also create a shortcut such as F8 key for this.

How t get a overview of a image directory?

In emacs version 22 or later, type 【Alt+x tumme】. Emacs will create thumbnails on the fly. (You need ImageMagick installed for tumme to work.) Here's a screenshot:

Emacs tumme image thumbnail index

How to open the current directory in Desktop?

(defun open-in-desktop ()
  "Open the current file in desktop.
Works in Microsoft Windows and Mac OS X."
  (interactive)
  (cond
   ((string-equal system-type "windows-nt")
    (w32-shell-execute "explore"
                       (replace-regexp-in-string "/" "\\" default-directory t t)))
   ((string-equal system-type "darwin") (shell-command "open ."))
   ) )

(global-set-key (kbd "<f7>") 'open-in-desktop) 

With above, pressing F7 will open the current dir in desktop on Windows or Mac.

blog comments powered by Disqus