Emacs: Select Current HTML Element

By Xah Lee. Date: . Last updated: .

Here's a command that select current HTML element under cursor. Repeated call will extend selection.

(defun xah-html-select-element ()
  "Select previous element before cursor.
Repeated call will extend selection to previous element, possibly parent.
After this command is called, press `xah-repeat-key' to repeat it.

For lisp code, return a cons pair begin end positions.

URL `http://xahlee.info/emacs/emacs/emacs_html_select_current_element.html'
Created: 2021-06-19
Version: 2023-11-19 2024-03-26"
  (interactive)
  (set-transient-map (let ((xkmap (make-sparse-keymap))) (define-key xkmap (kbd (or xah-repeat-key "m")) real-this-command) xkmap))
  (let (xp1 xp2 xtagPos1 xbegin xend)
    (if (and (eq real-this-command real-last-command) (region-active-p))
        (progn
          (setq xp1 (region-beginning) xp2 (region-end))
          (goto-char xp1)
          (setq xtagPos1 (re-search-backward "<[a-z0-9]+\\|</[a-z0-9]+" nil t))
          (if (xah-html--tag-self-closing-p (xah-html--get-tag-name xtagPos1))
              (progn
                (setq xbegin xtagPos1)
                (setq xend xp2))
            (progn
              (if (xah-html--opening-tag-p xtagPos1)
                  (progn
                    (goto-char (1+ xtagPos1))
                    (xah-html-skip-tag-forward)
                    (search-backward "<" nil t)
                    (search-forward ">" nil t)
                    (setq xend (point))
                    (setq xbegin xtagPos1))
                (progn
                  (goto-char (1+ xtagPos1))
                  (xah-html-skip-tag-backward)
                  (setq xbegin (point))
                  (setq xend xp2))))))
      (progn
        (skip-chars-forward "^<>")
        (setq xp1 (re-search-backward "<[a-z0-9]+\\|</[a-z0-9]+"))
        (setq xp2 (search-forward ">"))
        (if (xah-html--tag-self-closing-p (xah-html--get-tag-name xp1))
            (progn
              (setq xbegin xp1)
              (setq xend xp2))
          (if (xah-html--opening-tag-p xp1)
              (progn
                (goto-char (1+ xp1))
                (xah-html-skip-tag-forward)
                (setq xend (point))
                (setq xbegin xp1))
            (progn
              (goto-char (1+ xp1))
              (xah-html-skip-tag-backward)
              (setq xbegin (point))
              (setq xend xp2))))))
    (progn
      (push-mark xend t t)
      (goto-char xbegin))
    (cons xbegin xend)))

you need some commands in Emacs: Xah HTML Mode 📦

Xah Talk Show 2021-06-22 emacs lisp live coding, extend xah-html-select-current-element