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. xah-html-select-current-element

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

URL `http://xahlee.info/emacs/emacs/emacs_html_select_current_element.html'
Version 2021-06-19 2021-08-08"
  (interactive)
  (require 'sgml-mode)
  (let ( $p1 $p2 $tagPos1 $tagPos4 )
    (if (eq this-command last-command)
        (progn
          (setq $p1 (region-beginning) $p2 (region-end))
          (goto-char $p1)
          (search-backward "<" nil t)
          (setq $tagPos1 (point))
          (search-forward ">" nil t)
          (if (xah-html--tag-self-closing-p (xah-html--get-tag-name $tagPos1))
              (progn
                (push-mark $tagPos1 t t)
                (goto-char $p2))
            (progn
              (if (xah-html--is-opening-tag-p $tagPos1)
                  (progn
                    (goto-char (1+ $tagPos1))
                    (sgml-skip-tag-forward 1)
                    (search-backward "<" nil t)
                    (search-forward ">" nil t)
                    (setq $tagPos4 (point))
                    (push-mark $tagPos1 t t)
                    (goto-char $tagPos4))
                (progn
                  (goto-char (1+ $tagPos1))
                  (sgml-skip-tag-backward 1)
                  (push-mark (point) t t)
                  (goto-char $p2))))))
      (progn
        (search-backward "<")
        (setq $p1 (point))
        (search-forward ">")
        (setq $p2 (point))
        (if (xah-html--tag-self-closing-p (xah-html--get-tag-name $p1))
            (progn
              (push-mark $p2 t t)
              (goto-char $p1))
          (if (xah-html--is-opening-tag-p $p1)
              (progn
                (goto-char (1+ $p1))
                (sgml-skip-tag-forward 1)
                (push-mark $p1 t t))
            (progn
              (goto-char (1+ $p1))
              (sgml-skip-tag-backward 1)
              (push-mark (point) t t)
              (goto-char $p2)))))))
  (set-transient-map (let (($kmap (make-sparse-keymap))) (define-key $kmap (kbd "t") 'xah-html-select-current-element ) $kmap)))

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