1

Is there a way to customize Auctex, and in particular LaTeX-env-item so that it does not automatically insert the first \item, but still have working LaTeX-insert-item so that C-c C-j works? Looking at the source code of LaTeX-env-item, it looks like a call to LaTeX-insert-item is baked in.

The situation when this would be useful is when I select text

\item foo
\item bar
\item baz

and press C-c C-e (insert environment), then get

\begin{itemize}
\item \item foo
\item bar
\item baz
\end{itemize}

It shouldn't be too hard for the machine to figure out that the extra \item is bogus.

1 Answer 1

1

In an advice of LaTeX-env-item-region (defined with advice-add), you can locally change the behavior of LaTeX-insert-item with the help of cl-letf*.
This is demonstrated in the code snippet below.
There, LaTeX-env-item uses my-LaTeX-insert-item when the region is active.
my-LaTeX-insert-item only inserts \item if it is not already present behind point.

(defun my-LaTeX-insert-item (old-insert-item &rest args)
  "Use `LaTeX-insert-item' only if there is no \\item or when called interactively.
This function can be used as :around advice for `LaTeX-insert-item'.
OLD-INSERT-ITEM is the original version of `LaTeX-insert-item'
and ARGS is the list of its original arguments (which is currently empty)."
  (if (looking-at "[[:space:]]*\\\\item\\_>")
      (progn
    (insert "\n")
    (indent-according-to-mode)
    (forward-sexp)
    (cond
     ((looking-at "[[:space:]]")
      (forward-char))
     ((eolp)
      (TeX-parse-arguments (cdr-safe (assoc "item" (TeX-symbol-list)))))
     (t
      (forward-sexp)
      (if (looking-at "[[:space:]]")
          (forward-char)
        (insert " ")))))
    (apply old-insert-item args)))

;; (advice-add 'LaTeX-insert-item :around #'maybe-LaTeX-insert-item)

(defun my-LaTeX-env-item-region (fun &rest args)
  "Do not insert first item if region is active.
This function can be used as :around advice for `LaTeX-env-item'
with ARGS as its original argument list."
  (if (use-region-p)
      (cl-letf* ((old-insert-item (symbol-function 'LaTeX-insert-item))
         ((symbol-function 'LaTeX-insert-item)
          (lambda (&rest args)
            (apply #'my-LaTeX-insert-item old-insert-item args))))
    (apply fun args))
    (apply fun args)))

(advice-add 'LaTeX-env-item :around #'my-LaTeX-env-item-region)
2
  • TIL about advice-add. Dec 22, 2021 at 7:33
  • 1
    @AndrejBauer I added links to the documentation of advice-add and cl-letf. While advice-add is for globally advising functions cl-letf can be used for locally advising functions (i.e., let-bound).
    – Tobias
    Dec 22, 2021 at 8:19

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.