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.

URL `http://ergoemacs.org/emacs/emacs_html_select_current_element.html'
Version 2021-06-19 2021-06-22"
  (interactive)
  (require 'sgml-mode)
  (let ($p0 $p1 $p2 $tagPos1 $tagPos2 $tagPos3 $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)
          (setq $tagPos2 (point))
          (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)
                    (setq $tagPos3 (point))
                    (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
        (setq $p0 (point))
        (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
                (message "is open" )
                (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))))))))

you need some commands in Emacs: Xah HTML Mode

XahTV 2021-06-22 emacs lisp live coding, extend xah-html-select-current-element

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