Elisp: update-title

By Xah Lee. Date: . Last updated: .

Here's a command to update a existing HTML file's title.

(defun xah-html-update-title (newTitle)
  "Update a HTML article's title and h1 tags.
Update the <title>…</title> and <h1>…</h1> of current buffer."
  (interactive
   (let (oldTitle)
     (save-excursion
       (goto-char 1)
       (re-search-forward "<title>\\([^<]+?\\)</title>")
       (setq oldTitle (match-string 1 ) )
       )
     (list (read-string "New title:" oldTitle nil oldTitle "INHERIT-INPUT-METHOD")) ) )
  (let (p1 p2)
    (save-excursion
      (goto-char 1)

      (progn (search-forward "<title>")
             (setq p1 (point) )
             (search-forward "<")
             (setq p2 (- (point) 1) )
             (delete-region p1 p2 )
             (goto-char p1)
             (insert newTitle ) )

      (progn (search-forward "<h1>")
             (setq p1 (point) )
             (search-forward "<")
             (setq p2 (- (point) 1) )
             (delete-region p1 p2 )
             (goto-char p1)
             (insert newTitle ) )
      ) ))

When called, it'll prompt you for a new title. The update will happen on both the title tag and h1 tag. You can give it a hotkey. [see Emacs: How to Define Keys]

This saves me some 20 keystrokes and manual eyeballing processes. Without this command, i have to first move to the “title” tag, edit there, copy it, then move to the “h1” tag, paste over.

The interesting elisp part is the use of (interactive …) to get the existing title and put in minibuffer as default value. [see Elisp: Get User Input]

You might modify the code for any programing files or blog that you frequently need to update part of it.

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