Emacs command to add HTML tags

A while back I asked Jason Fruit how to add HTML tags to text in Emacs, something like the format painter in Microsoft applications. He said he didn’t know of anything and wrote the following macro for me.

(defun tag-word-or-region (tag)
    "Surround current word or region with a given tag."
    (interactive "sEnter tag (without <>): ")
    (let (pos1 pos2 bds start-tag end-tag)
    (setq start-tag (concat "<" tag ">"))
    (setq end-tag (concat "</" tag ">"))
    (if (and transient-mark-mode mark-active)
            (goto-char (region-end))
            (insert end-tag)
            (goto-char (region-beginning))
            (insert start-tag))
            (setq bds (bounds-of-thing-at-point 'symbol))
            (goto-char (cdr bds))
            (insert end-tag)
            (goto-char (car bds))
            (insert start-tag)))))

I added the following line to my .emacs file to bind Jason’s macro to the key sequence C-x t.

    (global-set-key "C-xt" 'tag-word-or-region)

To add a tag to a single word, place the cursor before or in the word and execute the command. To tag a block of text, select the text first then execute the command.

More Emacs posts

4 thoughts on “Emacs command to add HTML tags

  1. Looks to me like it already exists:

    C-x C-f foo.html RET
    hello there
    C-a C-SPC C-e
    C-c C-t h1 RET RET

    (I found this by opening an HTML file and running “C-h m” to describe the HTML major mode, then “C-h k C-c C-t” to get documentation on the “C-c C-t” command.)

  2. Nemo, that’s certainly true — John asked me about nxhtml-mode specifically.

    Alex, I’d be interested to know what it’s called; I just looked again and still don’t see it. I know about C-c C-f to close a tag, and I just found out it will surround a region if you’re using completion, but I can’t find an equivalent to html-mode’s C-c C-t. I am certainly capable of overlooking things, though.

Comments are closed.