Emacs Lisp Example: wrap-html-tag

A little elisp command, useful if you do a lot HTML coding.

(defun wrap-html-tag (tagName &optional className ξid)
  "Add a HTML tag to beginning and ending of current word or text selection.

If tagName is empty or nil, use “span”.
If className is empty or nil, don't add any class attribute.
If ξid is empty or nil, don't add id attribute."
  (interactive "sEnter tag name:
sEnter class:
sEnter id:")
  (let (bds p1 p2 inputText outputText)
    (setq bds (get-selection-or-unit 'word))
    (setq inputText (elt bds 0) )
    (setq p1 (elt bds 1) )
    (setq p2 (elt bds 2) )

      (if (or (equal tagName nil) (string= tagName "")) "span" tagName)
      (if (or (equal ξid nil) (string= ξid "")) "" (concat " id=\"" ξid "\""))
      (if (or (equal className nil) (string-equal className "")) "" (concat " class=\"" className "\""))
      (if (or (equal tagName nil) (string= tagName "")) "span" tagName)
      ">" ) )

    (delete-region p1 p2)
    (goto-char p1)
    (insert outputText) ) )

Remember to bind it to a key.

I used some elisp utils i wrote. You'll need to get it at: code.google.com xeu_elisp_util.el. Or, replace the get-selection-or-unit part by thing-at-point. For tutorial, see: Emacs Lisp: Using thing-at-point.

by the way, you could define your own commands for all html tags, but you probably shouldn't. html-mode has keys to insert many basic html tags. (See: Emacs and HTML Tips) Also, yasnippet has a whole set of html templates. (See: Emacs Templates with YASnippet). Though, still sometimes they don't cover everything you need. That's when adding your own is helpful.

Popular posts from this blog

Browser User Agent Strings 2012

11 Years of Writing About Emacs

does md5 creates more randomness?