(defun my/preview-automatic-math-region ()
  "Return the closed math region at point, or nil if it is still open.

Assumes that math regions cannot be nested."
  (ignore-errors
    (when (texmathp)
      (save-excursion
        (let* ((start-pos (cdr texmathp-why))
               (start-tag (car texmathp-why))
               (start-type (cadr
                            (cl-find start-tag
                                     texmathp-tex-commands-default
                                     :test (lambda (x y)
                                             (equal x (car y)))))))
          (goto-char start-pos)
          (pcase start-type
            ('sw-on
             (let ((re (concat
                        "\\("
                        (regexp-quote (pcase start-tag
                                        ("\\[" "\\]")
                                        ("\\(" "\\)")))
                        "\\)\\|\\("
                        (regexp-quote "\\[") "\\|" (regexp-quote "\\(")
                        "\\)")))
               (forward-char (length start-tag))
               (when (and (search-forward-regexp re nil t)
                          (match-beginning 1))
                 (cons start-pos (point)))))
            ('sw-toggle
             (forward-char (length start-tag))
             (when (search-forward start-tag nil t)
               (cons start-pos (point))))
            ('env-on
             (when (and (search-forward-regexp
                         (concat (regexp-quote TeX-esc) "begin[ \t]*"
                                 (regexp-quote TeX-grop)
                                 (regexp-quote start-tag)
                                 (regexp-quote TeX-grcl))
                         nil t)
                        (progn (LaTeX-find-matching-end) t))
               (cons start-pos (point))))
            ('arg-on
             (when (and (search-forward TeX-grop nil t)
                        (progn (forward-char -1) (forward-sexp) t))
               (cons start-pos (point))))))))))
