Elisp: Update HTML Title 🚀

By Xah Lee. Date: . Last updated: .

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

(defun xah-html-update-title (Title)
  "Update the <title>…</title> of current buffer.

URL `http://xahlee.info/emacs/emacs/elisp_update-html-title.html'
Created: 2019-01-11
Version: 2021-08-26"
  (interactive
   (let (xoldTitle)
     (save-excursion
       (goto-char (point-min))
       (re-search-forward "<title>\\([^<]+?\\)</title>")
       (setq xoldTitle (match-string-no-properties 1 )))
     (list (read-string "New title:" xoldTitle))))
  (let (xp1 xp2)
    (save-excursion
      (goto-char (point-min))
      (setq xp1 (search-forward "<title>"))
      (search-forward "</title>")
      (setq xp2 (match-beginning 0))
      (delete-region xp1 xp2 )
      (goto-char xp1)
      (insert Title ))))

(defun xah-html-update-first-h1 (H1Text)
  "Update the first <h1>…</h1> of current buffer.
When called in elisp code, H1Text is new title, a string.

todo, If h1 tag no exist, create it, after tag main.

URL `http://xahlee.info/emacs/emacs/elisp_update-html-title.html'
Created: 2019-01-11
Version: 2024-03-20"
  (interactive
   (let (xoldh1)
     (setq xoldh1
           (save-excursion
             (goto-char (point-min))
             (if (re-search-forward "<h1>\\([^<]+?\\)</h1>")
                 (match-string-no-properties 1)
               (progn ""))))

     (list (read-string "New title:" xoldh1))))
  (let (xp1 xp2)
    (save-excursion
      (goto-char (point-min))
      (when (search-forward "<h1>")
        (setq xp1 (point))
        (search-forward "</h1>")
        (setq xp2 (match-beginning 0))
        (delete-region xp1 xp2)
        (goto-char xp1)
        (insert H1Text)))))

(defun xah-html-update-title-h1 (Title)
  "Change the <title>…</title> and first <h1>…</h1> of current buffer.
When called in elisp code, Title is new title, a string.

URL `http://xahlee.info/emacs/emacs/elisp_update-html-title.html'
Created: 2023-06-07
Version: 2024-03-20"
  (interactive
   (let (xoldTitle)
     (save-excursion
       (goto-char (point-min))
       (re-search-forward "<title>\\([^<]+?\\)</title>")
       (setq xoldTitle (match-string-no-properties 1)))
     (list (string-trim (read-string "New title:" xoldTitle)))))
  (progn
    ;; (xah-html-update-twittercard-title Title)
    (xah-html-update-title Title)
    (xah-html-update-first-h1 Title)))