Instead of invoking the hook function after each individual keystroke, it only makes sense to invoke it after entering > . This can be achieved by reassigning the > character in the keyboard layout used by sgml-mode
.
In addition, sgml-close-tag
should not be called if the tag is already closed. Therefore, the following code adds a simple regular expression for this:
(defun my-sgml-insert-gt () "Inserts a `>' character and calls `my-sgml-close-tag-if-necessary', leaving point where it is." (interactive) (insert ">") (save-excursion (my-sgml-close-tag-if-necessary))) (defun my-sgml-close-tag-if-necessary () "Calls sgml-close-tag if the tag immediately before point is an opening tag that is not followed by a matching closing tag." (when (looking-back "<\\s-*\\([^</> \t\r\n]+\\)[^</>]*>") (let ((tag (match-string 1))) (unless (and (not (sgml-unclosed-tag-p tag)) (looking-at (concat "\\s-*<\\s-*/\\s-*" tag "\\s-*>"))) (sgml-close-tag))))) (eval-after-load "sgml-mode" '(define-key sgml-mode-map ">" 'my-sgml-insert-gt))
source share