Emacs: Select Current HTML Element

By Xah Lee. Date: . Last updated: .
(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 vector of begin end positions.

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

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