Elisp: HTML, 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 (@title)
  "Update the <title>…</title> and first <h1>…</h1> of current buffer.
When called in elisp code, @title is new title, a string.
URL `http://ergoemacs.org/emacs/elisp_update-html-title.html'
Version 2019-01-11 2021-02-09"
  (interactive
   (let ($oldTitle)
     (save-excursion
       (goto-char (point-min))
       (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 (point-min))
      (progn (search-forward "<title>")
             (setq $p1 (point))
             (search-forward "</title>")
             (setq $p2 (- (point) 8))
             (delete-region $p1 $p2 )
             (goto-char $p1)
             (insert @title ))
      (xah-html-update-first-h1 @title))))
(defun xah-html-update-first-h1 ( @h1Text)
  "Update the first <h1>…</h1> of current buffer.

URL `http://ergoemacs.org/emacs/elisp_update-html-title.html'
Version 2019-01-11"
  (interactive
   (let ($oldTitle)
     (save-excursion
       (goto-char (point-min))
       (re-search-forward "<h1>\\([^<]+?\\)</h1>")
       (setq $oldTitle (match-string 1 )))
     (list (read-string "New title:" $oldTitle nil $oldTitle "INHERIT-INPUT-METHOD"))))
  (let ($p1 $p2)
    (save-excursion
      (goto-char (point-min))
      (if (search-forward "<h1>")
          (progn
            (setq $p1 (point))
            (search-forward "</h1>")
            (search-backward "<")
            (setq $p2 (point))
            (delete-region $p1 $p2 )
            (goto-char $p1)
            (insert @h1Text ))
        (progn
          (message "<h1> tag not found."))))))

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.

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

HTML

Tags

Links

CSS

Misc

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial