I use AUCTeX for type-setting mathematical texts. Often I have to type equations with sums, integrals etc. which all have the same sub- or superscripts. I'd like to autofill the current sub-/superscript with the value which it had before. Example:

\sum_{i=1}^{\infty} a_i = \sum…

When I press _ at the equation above Emacs should write _{i=1}. Optional it would be good if the second superscript also is filled in.

How can this be realised?

2 Answers 2


Add to your init file:

(defvar mg-TeX-insert-subscript-history nil)
(defvar mg-TeX-insert-superscript-history nil)

(defun TeX-insert-sub-or-superscript (arg)
  "Insert typed key ARG times and possibly a pair of braces.
Brace insertion is only done if point is in a math construct and
`TeX-electric-sub-and-superscript' has a non-nil value."
  (interactive "*p")
  (self-insert-command arg)
  (when (and TeX-electric-sub-and-superscript (texmathp))
    (let* ((history (cond
             ((equal last-input-event ?_)
             ((equal last-input-event ?^)
       (content (read-string "Content: " (car (symbol-value history)) history)))
      (insert (concat TeX-grop content TeX-grcl))
      (if (zerop (length content))

Make sure TeX-electric-sub-and-superscript is set to non-nil.

  • I knew you'd end up here eventually :) nice approach. Commented Nov 4, 2014 at 13:25

Here is a version which non-interactively inserts the last sub/super-script occuring for the token at point:

(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)
       (let ((current-token (let ((end (point)))
                              (backward-sexp 1)
                              (buffer-substring-no-properties (point) end))))
         (if (search-backward current-token nil t)
               (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)

Taking the example in the question, below is the sequence of buffer states obtained by starting with the first line and typing _^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▮

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.