Berikut adalah versi yang secara non-interaktif menyisipkan sub / skrip super terakhir yang terjadi untuk token pada titik:
(defun my/electric-sub-super-script (arg)
"Insert typed character ARG times and possibly a sub/super-script.
Sub/super-script insertion is done only in a (La)TeX math mode region.
The inserted sub/super-script is copied from the last occurence of a
sub/superscript for the token at point."
(interactive "p")
(self-insert-command arg)
(when (texmathp)
(insert
(save-excursion
(let ((current-token (let ((end (point)))
(backward-sexp 1)
(buffer-substring-no-properties (point) end))))
(if (search-backward current-token nil t)
(progn
(search-forward current-token)
(let ((begin (point)))
(forward-sexp 1)
(buffer-substring-no-properties begin (point))))
""))))))
(define-key TeX-mode-map (kbd "_") #'my/electric-sub-super-script)
(define-key TeX-mode-map (kbd "^") #'my/electric-sub-super-script)
Mengambil contoh dalam pertanyaan, di bawah ini adalah urutan status buffer yang diperoleh dengan memulai dengan baris pertama dan mengetik _^SPCa_:
\sum_{i=1}^{\infty} a_i = \sum▮
\sum_{i=1}^{\infty} a_i = \sum_{i=1}▮
\sum_{i=1}^{\infty} a_i = \sum_{i=1}^{\infty}▮
\sum_{i=1}^{\infty} a_i = \sum_{i=1}^{\infty} a▮
\sum_{i=1}^{\infty} a_i = \sum_{i=1}^{\infty} a_i▮