auctex-diffs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[AUCTeX-diffs] [elpa] externals/auctex 03ed9004cd 60/60: Merge remote-tr


From: Tassilo Horn
Subject: [AUCTeX-diffs] [elpa] externals/auctex 03ed9004cd 60/60: Merge remote-tracking branch 'origin/master' into externals/auctex
Date: Fri, 8 Apr 2022 11:52:57 -0400 (EDT)

branch: externals/auctex
commit 03ed9004cd5d317d1234c4f4afb18d75ec86e973
Merge: 8ff369bd92 fded69c292
Author: Tassilo Horn <tsdh@gnu.org>
Commit: Tassilo Horn <tsdh@gnu.org>

    Merge remote-tracking branch 'origin/master' into externals/auctex
---
 Makefile.in                             |    7 +-
 auctex.el.in                            |    2 +-
 context.el                              |   17 +-
 doc/auctex.texi                         |   87 +-
 doc/changes.texi                        |   53 +
 doc/faq.texi                            |   29 +-
 doc/todo.texi                           |    6 +-
 font-latex.el                           |   84 +-
 latex.el                                |  560 +++--
 plain-tex.el                            |   15 +-
 preview.el                              |   39 +-
 style/algpseudocode.el                  |  105 +-
 style/babel.el                          |    9 +-
 style/color.el                          |   15 +-
 style/csquotes.el                       |   15 +-
 style/doc.el                            |  488 ++++-
 style/exam.el                           |   16 +-
 style/fancyhdr.el                       |   11 +-
 style/german.el                         |   18 +-
 style/gloss-italian.el                  |   14 +-
 style/ifluatex.el                       |    1 -
 style/ifthen.el                         |   82 +
 style/italian.el                        |   17 +-
 style/l3doc.el                          |  270 +++
 style/longtable.el                      |   21 +-
 style/ltxtable.el                       |   16 +-
 style/newfloat.el                       |   14 +-
 style/ngerman.el                        |   18 +-
 style/ocg-p.el                          |   11 +-
 style/plext.el                          |   15 +-
 style/polyglossia.el                    |    1 -
 style/scrpage2.el                       |    4 +
 style/sidecap.el                        |  149 +-
 style/titleps.el                        |    6 +-
 style/titlesec.el                       |    6 +-
 style/xcolor.el                         |   15 +-
 style/xltabular.el                      |   28 +-
 tests/context/context-test.el           |    6 +
 tests/japanese/error-parsing.el         |    1 -
 tests/latex/conditionals-indent-in.tex  |  158 ++
 tests/latex/conditionals-indent-out.tex |  158 ++
 tests/latex/font-latex-test.el          |    6 +
 tests/latex/latex-test.el               |   34 +-
 tests/latex/tabular-in.tex              |   23 +
 tests/latex/tabular-out.tex             |   23 +
 tests/tex/command-expansion.el          |    2 +-
 tests/tex/error-parsing.el              |    1 -
 tex-bar.el                              |    5 +-
 tex-buf.el                              | 3510 ------------------------------
 tex-fold.el                             |    2 +-
 tex-info.el                             |    8 +-
 tex-ispell.el                           |    2 +-
 tex-jp.el                               |    3 +-
 tex-site.el.in                          |   50 +-
 tex.el                                  | 3587 ++++++++++++++++++++++++++++++-
 55 files changed, 5633 insertions(+), 4210 deletions(-)

diff --git a/Makefile.in b/Makefile.in
index 3ef294c247..9ee6db0c59 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -2,7 +2,7 @@
 
 # Maintainer: auctex-devel@gnu.org
 
-# Copyright (C) 2003-2008, 2010, 2013-2015, 2018-2021 Free Software
+# Copyright (C) 2003-2008, 2010, 2013-2015, 2018-2022 Free Software
 #   Foundation, Inc.
 
 # This file is part of AUCTeX.
@@ -79,7 +79,7 @@ CTANDIR = $(DIST_PREFIX)/ctan
 PREVIEW_BUILD_DIR = preview-build
 COMMITTER="`git config --get user.name`\ \ \<`git config --get user.email`\>"
 
-AUCSRC = tex.el tex-buf.el tex-style.el plain-tex.el latex.el tex-info.el \
+AUCSRC = tex.el tex-style.el plain-tex.el latex.el tex-info.el \
        texmathp.el multi-prompt.el tex-mik.el font-latex.el tex-font.el \
        context.el context-en.el context-nl.el tex-fold.el tex-jp.el \
        toolbar-x.el tex-bar.el bib-cite.el tex-ispell.el latex-flymake.el
@@ -178,7 +178,8 @@ STYLESRC = style/prosper.el \
           style/xr.el        style/cancel.el    style/unicodefonttable.el \
           style/cuted.el     style/floatpag.el  style/flushend.el \
           style/midfloat.el  style/stabular.el  style/stfloats.el \
-          style/rotating.el  style/sidecap.el
+          style/rotating.el  style/sidecap.el   style/l3doc.el \
+          style/ifthen.el
 
 STYLEELC = $(STYLESRC:.el=.elc)
 
diff --git a/auctex.el.in b/auctex.el.in
index 377c733913..014c0a2b8a 100644
--- a/auctex.el.in
+++ b/auctex.el.in
@@ -5,7 +5,7 @@
 ;; URL: https://www.gnu.org/software/auctex/
 ;; Maintainer: auctex-devel@gnu.org
 ;; Notifications-To: auctex-diffs@gnu.org
-;; Package-Requires: ((emacs "24.3"))
+;; Package-Requires: ((emacs "24.3") (nadvice "0.3"))
 ;; Keywords: TeX LaTeX Texinfo ConTeXt docTeX preview-latex
 
 ;; This file is part of AUCTeX.
diff --git a/context.el b/context.el
index dfcb66495b..2f5c57e8e8 100644
--- a/context.el
+++ b/context.el
@@ -1,6 +1,6 @@
 ;;; context.el --- Support for ConTeXt documents.  -*- lexical-binding: t; -*-
 
-;; Copyright (C) 2003-2021  Free Software Foundation, Inc.
+;; Copyright (C) 2003-2022  Free Software Foundation, Inc.
 
 ;; Maintainer: Berend de Boer <berend@pobox.com>
 ;; Keywords: tex
@@ -49,7 +49,6 @@
 
 ;;; Code:
 
-(require 'tex-buf)
 (require 'tex)
 (require 'latex) ; for functions like `TeX-look-at' and `LaTeX-split-long-menu'
 (require 'plain-tex) ; for `plain-TeX-common-initialization'
@@ -640,10 +639,7 @@ for a label to be inserted after the sectioning command."
 
 (TeX-auto-add-type "environment" "ConTeXt")
 
-(if (fboundp 'advice-add)               ;Emacs≥24.4 (or ELPA package nadvice)
-    (advice-add 'ConTeXt-add-environments :after #'ConTeXt--invalidate-menu)
-  (defadvice ConTeXt-add-environments (after ConTeXt-invalidate-menu (&rest 
environments) activate)
-    (ConTeXt--invalidate-menu)))
+(advice-add 'ConTeXt-add-environments :after #'ConTeXt--invalidate-menu)
 (defun ConTeXt--invalidate-menu (&rest _)
   "Mark the menu as being in need of a refresh."
   (setq ConTeXt-menu-changed t))
@@ -1318,8 +1314,10 @@ else.  There might be text before point."
   (let ((map (make-sparse-keymap)))
     (set-keymap-parent map TeX-mode-map)
 
-    (define-key map "\e\C-a"  #'ConTeXt-find-matching-start)
-    (define-key map "\e\C-e"  #'ConTeXt-find-matching-stop)
+    ;; We now set `beginning-of-defun-function' and
+    ;; `end-of-defun-function' instead.
+    ;; (define-key map "\e\C-a"  #'ConTeXt-find-matching-start)
+    ;; (define-key map "\e\C-e"  #'ConTeXt-find-matching-stop)
     ;; likely to change in the future
     (define-key map "\C-c!"    #'ConTeXt-work-on-environment)
     (define-key map "\C-c\C-e" #'ConTeXt-environment)
@@ -1776,6 +1774,9 @@ that is, you do _not_ have to cater for this yourself by 
adding \\\\' or $."
 
   (add-hook 'activate-menubar-hook #'ConTeXt-menu-update nil t)
 
+  (setq-local beginning-of-defun-function #'ConTeXt-find-matching-start
+              end-of-defun-function       #'ConTeXt-find-matching-stop)
+
   ;; Outline support
   (require 'outline)
   (set (make-local-variable 'outline-level) 'ConTeXt-outline-level)
diff --git a/doc/auctex.texi b/doc/auctex.texi
index 8723bb61d9..ca23668d1b 100644
--- a/doc/auctex.texi
+++ b/doc/auctex.texi
@@ -12,7 +12,7 @@ This manual is for @AUCTeX{}
 (version @value{VERSION} from @value{UPDATED}),
 a sophisticated @TeX{} environment for Emacs.
 
-Copyright @copyright{} 1992-1995, 2001, 2002, 2004-2021
+Copyright @copyright{} 1992-1995, 2001, 2002, 2004-2022
 Free Software Foundation, Inc.
 
 @quotation
@@ -1592,7 +1592,7 @@ seen indented in nested constructs.
 @vindex LaTeX-item-indent
 @vindex LaTeX-item-regexp
 
-You can explicitely indent single lines, usually by pressing @key{TAB},
+You can explicitly indent single lines, usually by pressing @key{TAB},
 or marked regions by calling @code{indent-region} on it.  If you have
 @code{auto-fill-mode} enabled and a line is broken while you type it,
 Emacs automatically cares about the indentation in the following line.
@@ -1632,6 +1632,11 @@ The check for the indentation function may be enabled or 
disabled by
 customizing the variable @code{LaTeX-indent-environment-check}.
 @vindex LaTeX-indent-environment-check
 
+For tabular-like environments, @AUCTeX{} has a built-in function to indent
+according to preceding @samp{&} signs and assigns it to all known
+tabular-like environments in the default value of
+@code{LaTeX-indent-environment-list}.
+
 @cindex align.el
 @findex align-current
 As a side note with regard to formatting special environments: Newer
@@ -1674,13 +1679,6 @@ upon typing @key{RET} as well.  The respective option is 
called
 List of environments with special indentation.  The second element in
 each entry is the function to calculate the indentation level in
 columns.
-
-@c FIXME: The situation has changed, hasn't it?
-The filling code currently cannot handle tabular-like environments
-which will be completely messed-up if you try to format them.  This is
-why most of these environments are included in this customization
-option without a special indentation function.  This will prevent that
-they get filled.
 @end defopt
 
 @defopt LaTeX-indent-level
@@ -1724,6 +1722,55 @@ behavior you only need to remove @code{\|\[} and 
@code{\|\]} from
 @code{LaTeX-begin-regexp} and @code{LaTeX-end-regexp} variables
 respectively.
 
+A closely related topic is indenting of text enclosed in square brackets,
+parentheses and other pairs.  @AUCTeX{} offers two variables which control
+if indentation happens inside these pairs.
+
+@defopt TeX-indent-open-delimiters
+This variable contains additional opening delimiters which increase
+indentation.  For example add @code{[} to this variable to get text after
+a square bracket indented.
+@end defopt
+
+@defopt TeX-indent-close-delimiters
+This is the accompanying variable to @code{TeX-indent-open-delimiters}
+decreasing the indentation again.  This variable should contain @code{]}
+if @code{TeX-indent-open-delimiters} is set like described above.
+@end defopt
+
+@noindent
+Note that this is an opt-in feature, both variables are initially set to
+an empty string.  That is because it introduces non-trivial side effects
+to include @code{[} and @code{]} in @code{TeX-indent-open-delimiters} and
+@code{TeX-indent-close-delimiters}; if you only have an opening square
+bracket in your text without closing it, wrong indentation persists in the
+following text.  For example, in math expression, half-open intervals are
+frequently written as @samp{[0,10)} or @samp{[0,10[}.  In such cases, you
+can put the closing part as a comment in the same line in order to have
+correct indentation after that:
+@example
+$[0,10)$ % ]
+$[0,10[$ % ]]
+@end example
+
+Another example is @samp{\left}-@samp{\right} pair in equations.  Similar
+workarounds are available:
+@example
+\begin@{equation@}
+  \left[ % ]
+    xyz
+  \right] % [
+  abc
+\end@{equation@}
+@end example
+
+You can include parens @samp{()} also in @code{TeX-indent-open-delimiters}
+and @code{TeX-indent-close-delimiters} to enable indent inside them.  Be
+prepared for similar side effects when you do.
+
+Note that commented curly braces @code{@{} and @code{@}} aren't counted
+when @AUCTeX{} computes indentation.
+
 @node Filling
 @section Filling
 @cindex Filling
@@ -1750,7 +1797,7 @@ init file:
 (add-hook 'LaTeX-mode-hook #'turn-on-auto-fill)
 @end lisp
 
-You can manually fill explicitely marked regions, paragraphs,
+You can manually fill explicitly marked regions, paragraphs,
 environments, complete sections, or the whole buffer.  (Note that manual
 filling in @AUCTeX{} will indent the start of the region to be filled in
 contrast to many other Emacs modes.)
@@ -1766,7 +1813,7 @@ comment and continues after it.  In order to prevent 
overfull lines in
 the source code, a linebreak will be inserted before the last
 non-comment word by default.  This can be changed by customizing
 @code{LaTeX-fill-break-before-code-comments}.  If you have overfull
-lines with code comments you can fill those explicitely by calling
+lines with code comments you can fill those explicitly by calling
 @code{LaTeX-fill-paragraph} or pressing @kbd{M-q} with the cursor
 positioned on them.  This will add linebreaks in the comment and indent
 subsequent comment lines to the column of the comment in the first line
@@ -2974,21 +3021,17 @@ activated mark, however, will always define a new 
region when calling
 @code{TeX-command-region}.
 @end deffn
 
-@c FIXME: The former half of this paragraph is incorrect.
-@c - `TeX-(La)TeX-sentinel' depends on `TeX-active-*', which act
-@c   according to the value of `TeX-current-process-region-p'.
-@c - Both C-c C-c and C-c C-r overwrite `TeX-current-process-region-p'.
-@c Therefore, if the user types C-c C-r before the process invoked by
-@c C-c C-c finishes, the sentinel for the latter process doesn't work
-@c as expected.
-@AUCTeX{} will allow one process for each document, plus one process
-for the region file to be active at the same time.  Thus, if you are
-editing @var{n} different documents, you can have @var{n} plus one
-processes running at the same time.  If the last process you started was
+If the last process you started was
 on the region, the commands described in @ref{Debugging} and
 @ref{Control} will work on that process, otherwise they will work on the
 process associated with the current document.
 
+Don't run more than one process at the same time.  @AUCTeX{} doesn't
+support simultaneous typeset including region typeset.  Wait for the
+previous process to finish before you start a new process, in particular
+when you are editing multiple documents in parallel.  This limitation
+applies for preview by @previewlatex{} as well.
+
 @node Selecting a Command
 @subsection Selecting and Executing a Command
 
diff --git a/doc/changes.texi b/doc/changes.texi
index ed298d1867..12acd0c247 100644
--- a/doc/changes.texi
+++ b/doc/changes.texi
@@ -8,6 +8,59 @@
 
 @end ifset
 
+@heading News since last release
+
+@itemize @bullet
+@item
+@AUCTeX{} tracks the change in Emacs where initial inputs in the
+minibuffer during queries are getting phased out.  Queries for the
+mandatory arguments of macros and environments are adjusted where
+applicable.  The value which will be used after hitting @kbd{RET} without
+other input is shown in the prompt in parentheses prefixed with
+@samp{default}.  For this change the signature of the function
+@code{TeX-arg-length} is altered.  The old argument list was:
+@lisp
+(defun TeX-arg-length (optional &optional prompt
+                                initial-input definition default)
+@end lisp
+
+whereas the new one is:
+@lisp
+(defun TeX-arg-length (optional &optional prompt
+                                default initial-input definition)
+@end lisp
+
+Note the position change of @code{DEFAULT}.
+
+@item
+Indenting of conditionals is improved.  Code inside constructs like
+@samp{\ifx . \else . \fi} is correctly indented.  An interface for style
+files is also introduced which can add their macros to the indentation
+engine.  Check the file @file{algpseudocode.el} for an example.
+
+@item
+You can optionally enable indent inside square brackets @samp{[]} by new
+user options @code{TeX-indent-open-delimiters} and
+@code{TeX-indent-close-delimiters}.
+@ifclear rawfile
+@xref{Indenting}.
+@end ifclear
+
+@item
+Now @file{tex-buf.el} is merged into @file{tex.el} and no longer exists.
+If your personal code has @code{(require 'tex-buf)}, one of the following
+prescriptions would serve.
+@enumerate
+@item
+Remove @code{(require 'tex-buf)}.
+@item
+Replace it with @code{(require 'tex)}.
+@item
+Replace it with @code{(require 'latex)}.
+@end enumerate
+
+@end itemize
+
 @heading News in 13.1
 
 @itemize @bullet
diff --git a/doc/faq.texi b/doc/faq.texi
index a9b2aa2d0d..da5576b122 100644
--- a/doc/faq.texi
+++ b/doc/faq.texi
@@ -1,5 +1,5 @@
 @c This is part of the AUCTeX Manual.
-@c Copyright (C) 2004-2014, 2021 Free Software Foundation, Inc.
+@c Copyright (C) 2004-2014, 2021, 2022 Free Software Foundation, Inc.
 @c See the file auctex.texi for copying conditions.
 @ifset rawfile
 @include macros.texi
@@ -43,9 +43,26 @@ in the bug report.
 
 Second, you can try to figure out if something in your personal or site
 configuration triggers the error by starting Emacs without such
-customizations.  You can do this by invoking Emacs with the command line
-@samp{emacs -q -no-site-file -l auctex}.  The @option{-l} option
-loads @file{auctex.el} which you normally do in your init file.  After you
+customizations.  You can do this by invoking Emacs with the following
+command line, depending on the installation scheme of @AUCTeX{} and your
+@acronym{OS}:
+@itemize
+@item
+If you installed @AUCTeX{} from @acronym{ELPA}, use @samp{emacs -q
+-no-site-file --eval "(progn (setq package-load-list '((auctex t)))
+(package-initialize))"}.  The @option{--eval} option activates only
+@AUCTeX{} among all installed @acronym{EPLA} packages.
+@item
+If you installed @AUCTeX{} via traditional
+@command{configure}--@command{make} scheme, use @samp{emacs -q
+-no-site-file -l auctex}.  The @option{-l} option loads @file{auctex.el}
+which you normally do in your init file.
+@item
+In both above cases, use @samp{runemacs} instead of @samp{emacs} on
+windows.
+@end itemize
+
+After you
 have started Emacs like this, you can load the file triggering the
 error.  If everything is working now, you know that you have to search
 either in the site configuration file or your personal init file for
@@ -132,10 +149,10 @@ this is) or by simply keeping the variable 
@code{TeX-file-line-error} to
 the default value of non-nil.
 
 @item
-What does AUC stand for?
+What does @samp{AUC} stand for?
 
 @AUCTeX{} came into being at Aalborg University in Denmark.  Back then
-the Danish name of the university was Aalborg Universitetscenter; AUC
+the Danish name of the university was Aalborg Universitetscenter; @samp{AUC}
 for short.
 
 @end enumerate
diff --git a/doc/todo.texi b/doc/todo.texi
index 2f09f29b33..218231d0bd 100644
--- a/doc/todo.texi
+++ b/doc/todo.texi
@@ -1,6 +1,6 @@
 @c This is part of the AUCTeX Manual.
 @c Copyright (C) 2004-2006, 2008, 2009, 2013-2015,
-@c               2020, 2021 Free Software Foundation, Inc.
+@c               2020-2022 Free Software Foundation, Inc.
 @c See the file auctex.texi for copying conditions.
 @ifset rawfile
 @include macros.texi
@@ -301,8 +301,8 @@ Make @code{TeX-insert-dollar} more robust.  Currently it 
can be fooled
 by @samp{\mbox}'es and escaped double dollar for example.
 
 @item
-Correct indentation for tabular, tabbing, table, math, and array
-environments.
+@c FIXME: Is support for table environment really necessary?
+Correct indentation for tabbing, table, and math environments.
 @end itemize
 
 @c Local Variables:
diff --git a/font-latex.el b/font-latex.el
index 8b1fec608d..2a90f3098b 100644
--- a/font-latex.el
+++ b/font-latex.el
@@ -1,6 +1,6 @@
 ;;; font-latex.el --- LaTeX fontification for Font Lock mode.  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 1996-2021  Free Software Foundation, Inc.
+;; Copyright (C) 1996-2022  Free Software Foundation, Inc.
 
 ;; Authors:    Peter S. Galbraith <psg@debian.org>
 ;;             Simon Marshall <Simon.Marshall@esrin.esa.it>
@@ -352,7 +352,8 @@ variable `font-latex-fontify-sectioning'." ',num)
       ("providecommand" "*|{\\[[{")
       ("newcounter" "{[") ("renewenvironment" "*{[[{{")
       ("renewcommand" "*|{\\[[{") ("renewtheorem" "{[{[")
-      ("usepackage" "[{[") ("fbox" "{") ("mbox" "{") ("rule" "[{{")
+      ("usepackage" "[{[") ("RequirePackage" "[{[")
+      ("fbox" "{") ("mbox" "{") ("rule" "[{{")
       ("framebox" "|[([{") ("makebox" "|[([{") ("newsavebox" "|{\\")
       ("parbox" "[[[{{") ("savebox" "|{\\|[([{") ("sbox" "|{\\{")
       ("usebox" "|{\\")
@@ -363,6 +364,7 @@ variable `font-latex-fontify-sectioning'." ',num)
       ("addcontentsline" "{{{") ("addtocontents" "{{")
       ("labelformat" "{{")
       ("AddToHook" "{[{") ("RemoveFromHook" "{[") ("AddToHookNext" "{{")
+      ("ProvidesClass" "{[") ("ProvidesPackage" "{[") ("ProvidesFile" "{[")
       ;; XXX: Should macros without arguments rather be listed in a
       ;; separate category with 'noarg instead of 'command handling?
       ("enspace" "") ("enskip" "") ("quad" "") ("qquad" "") ("nonumber" "")
@@ -1091,11 +1093,14 @@ have changed."
          (1 "|") (2 "|")))))
   (when font-latex-syntactic-keywords-extra
     (nconc font-latex-syntactic-keywords font-latex-syntactic-keywords-extra))
-  ;; Cater for docTeX mode.
-  (setq font-latex-doctex-syntactic-keywords
-        (append font-latex-syntactic-keywords
-                ;; For docTeX comment-in-doc.
-                '(("\\(\\^\\)\\^A" (1 (font-latex-doctex-^^A)))))))
+  ;; ;; Cater for docTeX mode.
+  ;; (setq font-latex-doctex-syntactic-keywords
+  ;;       (append font-latex-syntactic-keywords
+  ;;               ;; For docTeX comment-in-doc.
+  ;;               '(("\\(\\^\\)\\^A" (1 (font-latex-doctex-^^A))))))
+  ;; Finally, compute our `syntax-propertize-function' anew.
+  (setq-local syntax-propertize-function
+              (font-latex--make-syntax-propertize-function)))
 
 
 ;;; Syntactic fontification
@@ -1258,14 +1263,12 @@ triggers Font Lock to recognize the change."
   (when (fboundp 'font-lock-flush)
     (font-lock-flush)))
 
-(defun font-latex-syntax-propertize-function (start end)
-  "The `syntax-propertize-function' for (La)TeX documents."
-  (with-no-warnings
-    (let ((font-lock-syntactic-keywords
-           (if (derived-mode-p 'doctex-mode)
-               font-latex-doctex-syntactic-keywords
-             font-latex-syntactic-keywords)))
-      (font-lock-fontify-syntactic-keywords-region start end))))
+(defun font-latex--make-syntax-propertize-function ()
+  "Return a `syntax-propertize-function' for (La|Doc)TeX documents."
+  (let ((kws ;; (if (derived-mode-p 'doctex-mode)
+             ;;     font-latex-doctex-syntactic-keywords
+               font-latex-syntactic-keywords)) ;; )
+    (syntax-propertize-via-font-lock kws)))
 
 ;;;###autoload
 (defun font-latex-setup ()
@@ -1276,14 +1279,14 @@ triggers Font Lock to recognize the change."
   (set (make-local-variable 'font-lock-multiline) t)
 
   ;; The test for `major-mode' currently only works with docTeX mode
-  ;; because `TeX-install-font-lock' is called explicitely in
+  ;; because `TeX-install-font-lock' is called explicitly in
   ;; `doctex-mode'.  In case other modes have to be distinguished as
   ;; well, remove the call to `TeX-install-font-lock' from
   ;; `VirTeX-common-initialization' and place it in the different
   ;; `xxx-mode' calls instead, but _after_ `major-mode' is set.
   (let ((defaults
-          `((font-latex-keywords font-latex-keywords-1 font-latex-keywords-2)
-            nil nil ,font-latex-syntax-alist nil))
+         `((font-latex-keywords font-latex-keywords-1 font-latex-keywords-2)
+           nil nil ,font-latex-syntax-alist nil))
         (variables
          '((font-lock-mark-block-function . mark-paragraph)
            (font-lock-fontify-region-function
@@ -1297,8 +1300,6 @@ triggers Font Lock to recognize the change."
             font-latex-extend-region-backwards-command-in-braces
             font-latex-extend-region-backwards-quotation
             font-latex-extend-region-backwards-math)
-           (syntax-propertize-function
-            . font-latex-syntax-propertize-function)
            (syntax-propertize-extend-region-functions
             syntax-propertize-wholelines
             font-latex-sp-extend-region-backwards-verb-env))))
@@ -2251,32 +2252,27 @@ set to french, and >>german<< (and 8-bit) are used if 
set to german."
   :group 'font-latex-highlighting-faces)
 
 (defvar font-latex-doctex-keywords
-  (append font-latex-keywords-2
+  (append '((font-latex-doctex-match-^^A 0 font-lock-comment-face t))
+          font-latex-keywords-2
           '(("^%<[^>]*>" (0 font-latex-doctex-preprocessor-face t)))))
 
-;; Copy and adaptation of `doctex-font-lock-^^A' in `tex-mode.el' of
-;; CVS Emacs (March 2004)
-(defun font-latex-doctex-^^A ()
-  (if (eq (char-after (line-beginning-position)) ?\%)
-      (progn
-        (put-text-property
-         (1- (match-beginning 1)) (match-beginning 1) 'syntax-table
-         (if (= (1+ (line-beginning-position)) (match-beginning 1))
-             ;; The `%' is a single-char comment, which Emacs
-             ;; syntax-table can't deal with.  We could turn it
-             ;; into a non-comment, or use `\n%' or `%^' as the comment.
-             ;; Instead, we include it in the ^^A comment.
-             (eval-when-compile (string-to-syntax "< b"))
-           ;; FIXME: Those `eval-when-compile' shouldn't be needed any
-           ;; more since the byte-compiler will precompute those calls
-           ;; anyway (because `string-to-syntax'  is marked as pure).
-           (eval-when-compile (string-to-syntax ">"))))
-        (let ((end (line-end-position)))
-          (if (< end (point-max))
-              (put-text-property end (1+ end) 'syntax-table
-                                 (eval-when-compile
-                                   (string-to-syntax "> b")))))
-        (eval-when-compile (string-to-syntax "< b")))))
+(defun font-latex-doctex-match-^^A (limit)
+  "In docTeX mode, match comment started by ^^A and ^^X before LIMIT."
+  (catch 'found
+    (while (TeX-re-search-forward-unescaped "\\^\\^[AX]" limit t)
+      (when (eq (char-after (line-beginning-position)) ?\%)
+        (forward-line 1)
+        ;; Adjust `font-latex--updated-region-end' if necessary.
+        (let ((p (point)))
+          (if (< font-latex--updated-region-end limit)
+              (setq font-latex--updated-region-end limit))
+          (when (< font-latex--updated-region-end p)
+            (font-lock-unfontify-region
+             font-latex--updated-region-end p)
+            (setq font-latex--updated-region-end p))
+          ;; We assume that the above adjustment preserves match data.
+          (set-match-data (list (match-beginning 0) p)))
+        (throw 'found t)))))
 
 ;; Copy and adaptation of `doctex-font-lock-syntactic-face-function'
 ;; in `tex-mode.el' of CVS Emacs (March 2004)
diff --git a/latex.el b/latex.el
index 06627c4bdb..4527fbafb7 100644
--- a/latex.el
+++ b/latex.el
@@ -45,12 +45,8 @@
 (declare-function turn-off-filladapt-mode "ext:filladapt"
                   nil)
 
-;; These functions are reported to be unknown when built
+;; This function is reported to be unknown when built
 ;; `with-native-compilation':
-(declare-function LaTeX-command-section-change-level "tex-buf"
-                  (arg))
-(declare-function TeX-LaTeX-sentinel "tex-buf"
-                  (process name))
 (declare-function LaTeX-flymake "latex-flymake"
                   (report-fn &rest _args))
 
@@ -58,7 +54,6 @@
 (defvar outline-heading-alist)
 (defvar TeX-auto-file)
 (defvar LaTeX-section-list-changed)
-(defvar TeX-error-description-list-local)
 
 ;;; Syntax
 
@@ -111,9 +106,9 @@ This depends on `LaTeX-insert-into-comments'."
              (delete-region (match-beginning 0) (match-end 0))
              (indent-new-comment-line))
             ;; `indent-new-comment-line' does nothing when
-            ;; `comment-auto-fill-only-comments' is non-il, so we must be sure
-            ;; to be in a comment before calling it.  In any other case
-            ;; `newline' is used.
+            ;; `comment-auto-fill-only-comments' is non-nil, so we
+            ;; must be sure to be in a comment before calling it.  In
+            ;; any other case `newline' is used.
             ((TeX-in-comment)
              (indent-new-comment-line))
             (t
@@ -917,7 +912,7 @@ work analogously."
     (save-excursion
       (while (and (/= arg 0)
                   (re-search-backward
-                   "\\\\\\(begin\\|end\\) *{ *\\([A-Za-z*]+\\) *}" nil t))
+                   "\\\\\\(begin\\|end\\) *{\\([^}]+\\)}" nil t))
         (when (or (and LaTeX-syntactic-comments
                        (eq in-comment (TeX-in-commented-line))
                        (or (not in-comment)
@@ -925,7 +920,15 @@ work analogously."
                            ;; commented case.
                            (string= comment-prefix (TeX-comment-prefix))))
                   (and (not LaTeX-syntactic-comments)
-                       (not (TeX-in-commented-line))))
+                       (not (TeX-in-commented-line)))
+                  ;; macrocode*? in docTeX-mode is special since we
+                  ;; have also regular code lines not starting with a
+                  ;; comment-prefix.  Hence, the next check just looks
+                  ;; if we're inside such a group and returns t to
+                  ;; recognize such a situation.
+                  (and (eq major-mode 'doctex-mode)
+                       (member (match-string-no-properties 2)
+                               '("macrocode" "macrocode*"))))
           (setq arg (if (string= (match-string 1) "end") (1+ arg) (1- arg)))))
       (if (/= arg 0)
           "document"
@@ -1261,7 +1264,14 @@ Just like array and tabular."
   (let ((pos (and LaTeX-default-position ; LaTeX-default-position can
                                         ; be nil, i.e. do not prompt
                   (TeX-read-string "(Optional) Position: " 
LaTeX-default-position)))
-        (fmt (TeX-read-string "Format: " LaTeX-default-format)))
+        (fmt (TeX-read-string
+              (if (string= LaTeX-default-format "")
+                  "Format: "
+                (format "Format (default %s): " LaTeX-default-format))
+              nil nil
+              (if (string= LaTeX-default-format "")
+                  nil
+                LaTeX-default-format))))
     (setq LaTeX-default-position pos)
     (setq LaTeX-default-format fmt)
     (LaTeX-insert-environment environment
@@ -1274,9 +1284,18 @@ Just like array and tabular."
 (defun LaTeX-env-label (environment)
   "Insert ENVIRONMENT and prompt for label."
   (LaTeX-insert-environment environment)
+  (when (TeX-active-mark)
+    ;; Point is at the end of the region.  Move it back to the
+    ;; beginning of the region.
+    (exchange-point-and-mark)
+    (indent-according-to-mode))
   (when (LaTeX-label environment 'environment)
     (LaTeX-newline)
-    (indent-according-to-mode)))
+    (indent-according-to-mode))
+  (when (TeX-active-mark)
+    (indent-region (point) (mark))
+    ;; Restore the positions of point and mark.
+    (exchange-point-and-mark)))
 
 (defun LaTeX-env-list (environment)
   "Insert ENVIRONMENT and the first item."
@@ -1306,14 +1325,12 @@ Just like array and tabular."
                                               (concat TeX-esc (car elt)))
                                             (LaTeX-length-list)))))
          (inner-pos (when (and height (not (string= height "")))
-             (completing-read
-              (TeX-argument-prompt t nil "Inner position")
-              '("t" "b" "c" "s"))))
+                      (completing-read
+                       (TeX-argument-prompt t nil "Inner position")
+                       '("t" "b" "c" "s"))))
          (width (TeX-read-string
-                 (TeX-argument-prompt nil nil
-                                      (concat "Width (default "
-                                              LaTeX-default-width
-                                              ")"))
+                 (TeX-argument-prompt nil nil (format "Width (default %s)"
+                                                      LaTeX-default-width))
                  nil nil LaTeX-default-width)))
     (setq LaTeX-default-position pos)
     (setq LaTeX-default-width width)
@@ -1329,11 +1346,20 @@ Just like array and tabular."
 
 (defun LaTeX-env-tabular* (environment)
   "Insert ENVIRONMENT with width, position and column specifications."
-  (let ((width (TeX-read-string "Width: " LaTeX-default-width))
+  (let ((width (TeX-read-string
+                (format "Width (default %s): " LaTeX-default-width)
+                nil nil LaTeX-default-width))
         (pos (and LaTeX-default-position ; LaTeX-default-position can
                                         ; be nil, i.e. do not prompt
                   (TeX-read-string "(Optional) Position: " 
LaTeX-default-position)))
-        (fmt (TeX-read-string "Format: " LaTeX-default-format)))
+        (fmt (TeX-read-string
+              (if (string= LaTeX-default-format "")
+                  "Format: "
+                (format "Format (default %s): " LaTeX-default-format))
+              nil nil
+              (if (string= LaTeX-default-format "")
+                  nil
+                LaTeX-default-format))))
     (setq LaTeX-default-width width)
     (setq LaTeX-default-position pos)
     (setq LaTeX-default-format fmt)
@@ -1366,7 +1392,9 @@ Just like array and tabular."
   "Insert ENVIRONMENT with label for bibitem."
   (LaTeX-insert-environment environment
                             (concat TeX-grop
-                                    (TeX-read-string "Label for BibItem: " 
"99")
+                                    (TeX-read-string
+                                     (format "Label for BibItem (default %s): 
" "99")
+                                     nil nil "99")
                                     TeX-grcl))
   (end-of-line 0)
   (delete-char 1)
@@ -1736,27 +1764,29 @@ This is necessary since index entries may contain 
commands and stuff.")
 (defvar LaTeX-auto-regexp-list
   (append
    (let ((token TeX-token-char))
-     `((,(concat "\\\\\\(?:new\\|provide\\)command\\*?{?\\\\\\(" token 
"+\\)}?\\[\\([0-9]+\\)\\]\\[\\([^\n\r]*\\)\\]")
-        (1 2 3) LaTeX-auto-optional)
-       (,(concat "\\\\\\(?:new\\|provide\\)command\\*?{?\\\\\\(" token 
"+\\)}?\\[\\([0-9]+\\)\\]")
-        (1 2) LaTeX-auto-arguments)
+     `((,(concat "\\\\\\(re\\)?\\(?:new\\|provide\\)command\\*?"
+                 "{?\\\\\\(" token 
"+\\)}?\\[\\([0-9]+\\)\\]\\[\\([^\n\r]*\\)\\]")
+        (2 3 4 1) LaTeX-auto-optional)
+       (,(concat "\\\\\\(re\\)?\\(?:new\\|provide\\)command\\*?"
+                 "{?\\\\\\(" token "+\\)}?\\[\\([0-9]+\\)\\]")
+        (2 3 1) LaTeX-auto-arguments)
        (,(concat "\\\\\\(?:new\\|provide\\)command\\*?{?\\\\\\(" token 
"+\\)}?")
         1 TeX-auto-symbol)
-       (,(concat "\\\\newenvironment\\*?{?\\(" token 
"+\\)\\*?}?\\[\\([0-9]+\\)\\]\\[")
-        (1 2) LaTeX-auto-env-args-with-opt)
-       (,(concat "\\\\newenvironment\\*?{?\\(" token 
"+\\)\\*?}?\\[\\([0-9]+\\)\\]")
-        (1 2) LaTeX-auto-env-args)
-       (,(concat "\\\\newenvironment\\*?{?\\(" token "+\\)\\*?}?")
+       ("\\\\\\(re\\)?newenvironment\\*?{\\([^}]+\\)}\\[\\([0-9]+\\)\\]\\["
+        (2 3 1) LaTeX-auto-env-args-with-opt)
+       ("\\\\\\(re\\)?newenvironment\\*?{\\([^}]+\\)}\\[\\([0-9]+\\)\\]"
+        (2 3 1) LaTeX-auto-env-args)
+       ("\\\\newenvironment\\*?{\\([^}]+\\)}"
         1 LaTeX-auto-environment)
        (,(concat "\\\\newtheorem{\\(" token "+\\)}") 1 LaTeX-auto-environment)
        ("\\\\input{\\(\\.*[^#}%\\\\\\.\n\r]+\\)\\(\\.[^#}%\\\\\\.\n\r]+\\)?}"
         1 TeX-auto-file)
        ("\\\\include{\\(\\.*[^#}%\\\\\\.\n\r]+\\)\\(\\.[^#}%\\\\\\.\n\r]+\\)?}"
         1 TeX-auto-file)
-       (, (concat "\\\\bibitem{\\(" token "[^, \n\r\t%\"#'()={}]*\\)}")
-          1 LaTeX-auto-bibitem)
-       (, (concat "\\\\bibitem\\[[^][\n\r]+\\]{\\(" token "[^, 
\n\r\t%\"#'()={}]*\\)}")
-          1 LaTeX-auto-bibitem)
+       (,(concat "\\\\bibitem{\\(" token "[^, \n\r\t%\"#'()={}]*\\)}")
+        1 LaTeX-auto-bibitem)
+       (,(concat "\\\\bibitem\\[[^][\n\r]+\\]{\\(" token "[^, 
\n\r\t%\"#'()={}]*\\)}")
+        1 LaTeX-auto-bibitem)
        ("\\\\bibliography{\\([^#}\\\\\n\r]+\\)}" 1 LaTeX-auto-bibliography)
        ("\\\\addbibresource\\(?:\\[[^]]+\\]\\)?{\\([^#}\\\\\n\r]+\\)\\..+}"
         1 LaTeX-auto-bibliography)
@@ -1844,8 +1874,8 @@ For each element, the CAR is the name of the class, the 
CDR is
 the list of options provided to it.
 
 For example, its value will be
-  \(\(\"book\" \"a4paper\" \"11pt\" \"openany\" \"fleqn\"\)
-   ...\)
+  ((\"book\" \"a4paper\" \"11pt\" \"openany\" \"fleqn\")
+   ...)
 See also `LaTeX-provided-package-options'.")
 (make-variable-buffer-local 'LaTeX-provided-class-options)
 
@@ -1867,9 +1897,9 @@ For each element, the CAR is the name of the package, the 
CDR is
 the list of options provided to it.
 
 For example, its value will be
-  \(\(\"babel\" \"german\"\)
-   \(\"geometry\" \"a4paper\" \"top=2cm\" \"bottom=2cm\" \"left=2.5cm\" 
\"right=2.5cm\"\)
-   ...\)
+  ((\"babel\" \"german\")
+   (\"geometry\" \"a4paper\" \"top=2cm\" \"bottom=2cm\" \"left=2.5cm\" 
\"right=2.5cm\")
+   ...)
 See also `LaTeX-provided-class-options'.")
 (make-variable-buffer-local 'LaTeX-provided-package-options)
 
@@ -1945,7 +1975,8 @@ The value is actually the tail of the list of options 
given to PACKAGE."
                               ((member "12pt" options)
                                "12")
                               (t
-                               "10"))) t)
+                               "10")))
+                       t)
           (unless (equal options '(""))
             (TeX-add-to-alist 'LaTeX-provided-class-options
                               (list (cons style options)))))
@@ -1959,6 +1990,14 @@ The value is actually the tail of the list of options 
given to PACKAGE."
 
   ;; Cleanup optional arguments
   (mapc (lambda (entry)
+          ;; If we're renewcommand-ing and there is already an entry
+          ;; in `TeX-auto-symbol', delete it first:
+          (when (and (string= (nth 2 entry) "re")
+                     (assoc (car entry) TeX-auto-symbol))
+            (setq TeX-auto-symbol
+                  (assq-delete-all (car (assoc (car entry)
+                                               TeX-auto-symbol))
+                                   TeX-auto-symbol)))
           (add-to-list 'TeX-auto-symbol
                        (list (nth 0 entry)
                              (string-to-number (nth 1 entry)))))
@@ -1966,6 +2005,14 @@ The value is actually the tail of the list of options 
given to PACKAGE."
 
   ;; Cleanup default optional arguments
   (mapc (lambda (entry)
+          ;; If we're renewcommand-ing and there is already an entry
+          ;; in `TeX-auto-symbol', delete it first:
+          (when (and (string= (nth 3 entry) "re")
+                     (assoc (car entry) TeX-auto-symbol))
+            (setq TeX-auto-symbol
+                  (assq-delete-all (car (assoc (car entry)
+                                               TeX-auto-symbol))
+                                   TeX-auto-symbol)))
           (add-to-list 'TeX-auto-symbol
                        (list (nth 0 entry)
                              (vector "argument")
@@ -1974,12 +2021,29 @@ The value is actually the tail of the list of options 
given to PACKAGE."
 
   ;; Cleanup environments arguments
   (mapc (lambda (entry)
+          ;; If we're renewenvironment-ing and there is already an
+          ;; entry in `LaTeX-auto-environment', delete it first:
+          (when (and (string= (nth 2 entry) "re")
+                     (assoc (car entry) LaTeX-auto-environment))
+            (setq LaTeX-auto-environment
+                  (assq-delete-all (car (assoc (car entry)
+                                               LaTeX-auto-environment))
+                                   LaTeX-auto-environment)))
           (add-to-list 'LaTeX-auto-environment
                        (list (nth 0 entry)
                              (string-to-number (nth 1 entry)))))
         LaTeX-auto-env-args)
+
   ;; Ditto for environments with an optional arg
   (mapc (lambda (entry)
+          ;; If we're renewenvironment-ing and there is already an
+          ;; entry in `LaTeX-auto-environment', delete it first:
+          (when (and (string= (nth 2 entry) "re")
+                     (assoc (car entry) LaTeX-auto-environment))
+            (setq LaTeX-auto-environment
+                  (assq-delete-all (car (assoc (car entry)
+                                               LaTeX-auto-environment))
+                                   LaTeX-auto-environment)))
           (add-to-list 'LaTeX-auto-environment
                        (list (nth 0 entry) 'LaTeX-env-args (vector "argument")
                              (1- (string-to-number (nth 1 entry))))))
@@ -2010,11 +2074,7 @@ The value is actually the tail of the list of options 
given to PACKAGE."
 
 (add-hook 'TeX-auto-cleanup-hook #'LaTeX-auto-cleanup)
 
-(if (fboundp 'advice-add)               ;Emacs≥24.4 (or ELPA package nadvice)
-    (advice-add 'LaTeX-add-bibliographies :after #'TeX-run-style-hooks)
-  (defadvice LaTeX-add-bibliographies (after run-bib-style-hooks (&rest 
bibliographies) activate)
-    "Add BIBLIOGRAPHIES to the list of known bibliographies and style files."
-    (apply #'TeX-run-style-hooks bibliographies)))
+(advice-add 'LaTeX-add-bibliographies :after #'TeX-run-style-hooks)
 
 ;;; Biber support
 
@@ -2130,7 +2190,8 @@ If OPTIONAL is non-nil, insert the resulting value as an 
optional
 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 string.  ARGS is unused."
   (TeX-argument-insert
-   (TeX-read-string (TeX-argument-prompt optional prompt "Index tag")) 
optional))
+   (TeX-read-string (TeX-argument-prompt optional prompt "Index tag"))
+   optional))
 
 (defun TeX-arg-index (optional &optional prompt &rest _args)
   "Prompt for an index entry completing with known entries.
@@ -2213,25 +2274,35 @@ list of defined saveboxes."
         (LaTeX-add-saveboxes savebox))
     (TeX-argument-insert savebox optional TeX-esc)))
 
-(defun TeX-arg-length (optional &optional prompt initial-input definition)
+(defun TeX-arg-length (optional &optional prompt default initial-input
+                                definition)
   "Prompt for a LaTeX length.
 If OPTIONAL is non-nil, insert the resulting value as an optional
 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
-string.  If INITIAL-INPUT is non-nil, insert it in the minibuffer
-initially, with point positioned at the end.  If DEFINITION is
-non-nil, the length is added to the list of defined length."
-  (let ((length (completing-read (TeX-argument-prompt optional prompt "Length")
-                                 ;; A valid length can be a macro or a length 
of
-                                 ;; the form <value><dimension>.  Input 
starting
-                                 ;; with a `\' can be completed with length
-                                 ;; macros.
-                                 (mapcar (lambda(elt) (concat TeX-esc (car 
elt)))
-                                         (LaTeX-length-list))
-                                 ;; Some macros takes as argument only a length
-                                 ;; macro (e.g., `\setlength' in its first
-                                 ;; argument, and `\newlength'), in this case 
is
-                                 ;; convenient to set `\\' as initial input.
-                                 nil nil initial-input)))
+string.  DEFAULT is passed to `completing-read', which see.  If
+INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
+with point positioned at the end.  If DEFINITION is non-nil, the
+length is added to the list of defined length."
+  (let ((length
+         (completing-read
+          (TeX-argument-prompt optional
+                               ;; Cater for the case when PROMPT and
+                               ;; DEFAULT are both given:
+                               (if (and prompt default)
+                                   (concat prompt " (default " default ")")
+                                 prompt)
+                               (concat "Length"
+                                       (when (and default (not optional))
+                                         (concat " (default " default ")"))))
+          ;; A valid length can be a macro or a length of the form
+          ;; <value><dimension>.  Input starting with a `\' can be
+          ;; completed with length macros.
+          (mapcar (lambda (elt) (concat TeX-esc (car elt)))
+                  (LaTeX-length-list))
+          ;; Some macros takes as argument only a length macro (e.g.,
+          ;; `\setlength' in its first argument, and `\newlength'), in
+          ;; this case is convenient to set `\\' as initial input.
+          nil nil initial-input nil default)))
     (if (and definition (not (zerop (length length))))
         ;; Strip leading TeX-esc from macro name
         (LaTeX-add-lengths (substring length 1)))
@@ -2252,11 +2323,19 @@ string."
 Initial input is the name of the file being visited in the
 current buffer, with extension.  If OPTIONAL is non-nil, insert
 it as an optional argument.  Use PROMPT as the prompt string."
-  (TeX-argument-insert
-   (TeX-read-string
-    (TeX-argument-prompt optional prompt "Name")
-    (file-name-nondirectory buffer-file-name))
-   optional))
+  (let ((name (file-name-nondirectory buffer-file-name)))
+    (TeX-argument-insert
+     (TeX-read-string
+      (TeX-argument-prompt optional
+                           (when prompt
+                             (if optional
+                                 prompt
+                               (format (concat prompt " (default %s)") name)))
+                           (if optional
+                               "Name"
+                             (format "Name (default %s)" name)))
+      nil nil (if optional nil name))
+     optional)))
 
 (defun TeX-arg-file-name-sans-extension (optional &optional prompt)
   "Prompt for a file name.
@@ -2264,11 +2343,20 @@ Initial input is the name of the file being visited in 
the
 current buffer, without extension.  If OPTIONAL is non-nil,
 insert it as an optional argument.  Use PROMPT as the prompt
 string."
-  (TeX-argument-insert
-   (TeX-read-string
-    (TeX-argument-prompt optional prompt "Name")
-    (file-name-sans-extension (file-name-nondirectory buffer-file-name)))
-   optional))
+  (let ((name (file-name-sans-extension
+               (file-name-nondirectory buffer-file-name))))
+    (TeX-argument-insert
+     (TeX-read-string
+      (TeX-argument-prompt optional
+                           (when prompt
+                             (if optional
+                                 prompt
+                               (format (concat prompt " (default %s)") name)))
+                           (if optional
+                               "Name"
+                             (format "Name (default %s)" name)))
+      nil nil (if optional nil name))
+     optional)))
 
 (defun TeX-arg-define-label (optional &optional prompt)
   "Prompt for a label completing with known labels.
@@ -2347,7 +2435,7 @@ string."
 If OPTIONAL is non-nil, insert the resulting value as an optional
 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 string."
-  (TeX-arg-length optional prompt "\\" t))
+  (TeX-arg-length optional prompt nil "\\" t))
 
 (defcustom LaTeX-style-list '(("amsart")
                               ("amsbook")
@@ -2755,9 +2843,12 @@ argument, otherwise as a mandatory one.  Use PROMPT as 
the prompt
 string."
   (let ((default (format-time-string TeX-date-format (current-time))))
     (TeX-argument-insert
-     (TeX-read-string (TeX-argument-prompt
-                       optional prompt (format "Date (default %s)" default))
-                      nil nil default)
+     (TeX-read-string
+      (TeX-argument-prompt optional
+                           (when prompt
+                             (format (concat prompt " (default %s)") default))
+                           (format "Date (default %s)" default))
+      nil nil default)
      optional)))
 
 (defun TeX-arg-version (optional &optional prompt)
@@ -2765,10 +2856,15 @@ string."
 Use as initial input the current date.  If OPTIONAL is non-nil,
 insert the resulting value as an optional argument, otherwise as
 a mandatory one.  Use PROMPT as the prompt string."
-  (TeX-argument-insert
-   (TeX-read-string (TeX-argument-prompt optional prompt "Version")
-                    (format-time-string "%Y/%m/%d" (current-time)))
-   optional))
+  (let ((version (format-time-string "%Y/%m/%d" (current-time))))
+    (TeX-argument-insert
+     (TeX-read-string
+      (TeX-argument-prompt optional
+                           (when prompt
+                             (format (concat prompt " (default %s)") version))
+                           (format "Version (default %s)" version))
+      nil nil version)
+     optional)))
 
 (defun TeX-arg-pagestyle (optional &optional prompt definition)
   "Prompt for a LaTeX pagestyle with completion.
@@ -3138,16 +3234,16 @@ returning an alist.  Use PROMPT as the prompt string."
   (multi-prompt-key-value
    (TeX-argument-prompt optional prompt "Options (k=v)")
    (cond ((and (symbolp key-val-alist)
-              (boundp key-val-alist))
-         (symbol-value key-val-alist))
-        ((and (listp key-val-alist)
-              (symbolp (car key-val-alist))
-              (fboundp (car key-val-alist)))
-         (let ((head (car key-val-alist))
-               (tail (cdr key-val-alist)))
-           (apply head tail)))
-        (t
-         key-val-alist))))
+               (boundp key-val-alist))
+          (symbol-value key-val-alist))
+         ((and (listp key-val-alist)
+               (symbolp (car key-val-alist))
+               (fboundp (car key-val-alist)))
+          (let ((head (car key-val-alist))
+                (tail (cdr key-val-alist)))
+            (apply head tail)))
+         (t
+          key-val-alist))))
 
 (defun TeX-arg-key-val (optional key-val-alist &optional prompt)
   "Prompt for keys and values in KEY-VAL-ALIST.
@@ -3632,7 +3728,9 @@ consideration just as is in the non-commented source 
code."
     ("tabbing")
     ;; envs from amsmath.sty
     ("gather") ("gather*") ("gathered")
-    ("equation*") ("multline") ("multline*"))
+    ("equation*") ("multline") ("multline*")
+    ;; envs from doc.sty
+    ("macrocode") ("macrocode*"))
   "Alist of environments with special indentation.
 The second element in each entry is the function to calculate the
 indentation level in columns.
@@ -3682,9 +3780,11 @@ value."
 
 (defvar docTeX-indent-inner-fixed
   `((,(concat (regexp-quote TeX-esc)
-             "\\(begin\\|end\\)[ \t]*{macrocode\\*?}") 4 t)
+              "\\(begin\\|end\\)[ \t]*{macrocode\\*?}")
+     4 t)
     (,(concat (regexp-quote TeX-esc)
-             "\\(begin\\|end\\)[ \t]*{\\(macro\\|environment\\)\\*?}") 0 nil))
+              "\\(begin\\|end\\)[ \t]*{\\(macro\\|environment\\)\\*?}")
+     0 nil))
   "List of items which should have a fixed inner indentation.
 The items consist of three parts.  The first is a regular
 expression which should match the respective string.  The second
@@ -3693,6 +3793,110 @@ toggles if comment padding is relevant or not.  If t 
padding is
 part of the amount given, if nil the amount of spaces will be
 inserted after potential padding.")
 
+(defvar-local LaTeX-indent-begin-list nil
+  "List of macros increasing indentation.
+Each item in this list is a string with the name of the macro
+without a backslash.  The final regexp will be calculated by the
+function `LaTeX-indent-commands-regexp-make'.  A regexp for the
+\\if contructs is added by the function as well.  AUCTeX styles
+should add their macros to this variable and then run
+`LaTeX-indent-commands-regexp-make'.")
+
+(defvar-local LaTeX-indent-begin-exceptions-list nil
+  "List of macros which shouldn't increase the indentation.
+Each item in this list is a string without a backslash and will
+mostly start with 'if'.  These macros should not increase
+indentation although they start with 'if', for example the
+'ifthenelse' macro provided by the ifthen package.  AUCTeX styles
+should add their macros to this variable and then run
+`LaTeX-indent-commands-regexp-make'.")
+
+(defvar-local LaTeX-indent-mid-list nil
+  "List of macros which backindent the line where they appear.
+Each item in this list is a string with the name of the macro
+without a backslash.  The final regexp will be calculated by the
+function `LaTeX-indent-commands-regexp-make' which takes care of
+\\else and \\or.  AUCTeX styles should add their macros to this
+variable and then run `LaTeX-indent-commands-regexp-make'.")
+
+(defvar-local LaTeX-indent-end-list nil
+  "List of macros decreasing indentation.
+Each item in this list is a string with the name of the macro
+without a backslash.  The final regexp will be calculated by the
+function `LaTeX-indent-commands-regexp-make' which takes care of
+\\fi.  AUCTeX styles should add their macros to this variable and
+then run `LaTeX-indent-commands-regexp-make'.")
+
+(defvar-local LaTeX-indent-begin-regexp-local nil
+  "Regexp calculated from `LaTeX-indent-begin-list'.
+The value is calculated and set by the function
+`LaTeX-indent-commands-regexp-make' which already takes care of
+\\if constructs.")
+
+(defvar-local LaTeX-indent-begin-regexp-exceptions-local nil
+  "Regexp calculated from `LaTeX-indent-begin-exceptions-list'.
+The value is calculated and set by the function
+`LaTeX-indent-commands-regexp-make' which already takes care of
+\\ifthenelse.")
+
+(defvar-local LaTeX-indent-mid-regexp-local nil
+  "Regexp calculated from `LaTeX-indent-mid-list'.
+The value is calculated and set by the function
+`LaTeX-indent-commands-regexp-make' which already takes care of
+\\else and \\or.")
+
+(defvar-local LaTeX-indent-end-regexp-local nil
+  "Regexp calculated from `LaTeX-indent-end-list'.
+The value is calculated and set by the function
+`LaTeX-indent-commands-regexp-make' which already takes care of
+\\fi.")
+
+(defun LaTeX-indent-commands-regexp-make ()
+  "Calculate final regexp for adjusting indentation.
+This function takes the elements provided in
+`LaTeX-indent-begin-list', `LaTeX-indent-begin-exceptions-list',
+`LaTeX-indent-mid-list' and `LaTeX-indent-end-list' and generates
+the regexp's which are stored in
+`LaTeX-indent-begin-regexp-local',
+`LaTeX-indent-begin-regexp-exceptions-local',
+`LaTeX-indent-mid-regexp-local' and
+`LaTeX-indent-end-regexp-local' accordingly.  Some standard
+macros are added to the regexp's.  This function is called in
+`LaTeX-common-initialization' to set the regexp's."
+  (let* (cmds
+         symbs
+         (func (lambda (in regexp out)
+                 (setq cmds nil
+                       symbs nil)
+                 (dolist (elt in)
+                   (if (string-match "[^a-zA-Z@]" elt)
+                       (push elt symbs)
+                     (push elt cmds)))
+                 (set out (concat regexp
+                                  (when cmds
+                                    (concat "\\|"
+                                            (regexp-opt cmds)
+                                            "\\b"))
+                                  (when symbs
+                                    (concat "\\|"
+                                            (regexp-opt symbs))))))))
+    (funcall func
+             LaTeX-indent-begin-list
+             "if[a-zA-Z@]*\\b"
+             'LaTeX-indent-begin-regexp-local)
+    (funcall func
+             LaTeX-indent-mid-list
+             "else\\b\\|or\\b"
+             'LaTeX-indent-mid-regexp-local)
+    (funcall func
+             LaTeX-indent-end-list
+             "fi\\b"
+             'LaTeX-indent-end-regexp-local)
+    (funcall func
+             LaTeX-indent-begin-exceptions-list
+             "ifthenelse\\b"
+             'LaTeX-indent-begin-regexp-exceptions-local)))
+
 (defun LaTeX-indent-line ()
   "Indent the line containing point, as LaTeX source.
 Add `LaTeX-indent-level' indentation in each \\begin{ - \\end{ block.
@@ -3830,15 +4034,32 @@ outer indentation in case of a commented line.  The 
symbols
                                  "\\)"))
              ;; Items.
              (+ (LaTeX-indent-calculate-last force-type) LaTeX-item-indent))
-            ((looking-at "}")
+            ;; Other (La)TeX programming constructs which end
+            ;; something, \fi for example where we backindent:
+            ((looking-at (concat (regexp-quote TeX-esc)
+                                 "\\("
+                                 LaTeX-indent-end-regexp-local
+                                 "\\)"))
+             (- (LaTeX-indent-calculate-last force-type) LaTeX-indent-level))
+            ;; (La)TeX programming contructs which backindent only the
+            ;; current line, for example \or or \else where we backindent:
+            ((looking-at (concat (regexp-quote TeX-esc)
+                                 "\\("
+                                 LaTeX-indent-mid-regexp-local
+                                 "\\)"))
+             (- (LaTeX-indent-calculate-last force-type) LaTeX-indent-level))
+            ((memq (char-after) (append
+                                 TeX-indent-close-delimiters '(?\})))
              ;; End brace in the start of the line.
              (- (LaTeX-indent-calculate-last force-type)
                 TeX-brace-indent-level))
             (t (LaTeX-indent-calculate-last force-type))))))
 
 (defun LaTeX-indent-level-count ()
-  "Count indentation change caused by all \\left, \\right, \\begin, and
-\\end commands in the current line."
+  "Count indentation change caused by macros in the current line.
+Macros contain \\left, \\right, \\begin, \\end and \\if-\\fi
+constructs.  A special case is \\newif where the following
+\\if<foo> should not change the indentation."
   (save-excursion
     (save-restriction
       (let ((count 0))
@@ -3860,6 +4081,13 @@ outer indentation in case of a commented line.  The 
symbols
             (setq count (+ count LaTeX-indent-level)))
            ((looking-at LaTeX-end-regexp)
             (setq count (- count LaTeX-indent-level)))
+           ((looking-at "newif\\b")
+            (search-forward TeX-esc (line-end-position) t))
+           ((and (not (looking-at LaTeX-indent-begin-regexp-exceptions-local))
+                 (looking-at LaTeX-indent-begin-regexp-local))
+            (setq count (+ count LaTeX-indent-level)))
+           ((looking-at LaTeX-indent-end-regexp-local)
+            (setq count (- count LaTeX-indent-level)))
            ((looking-at (regexp-quote TeX-esc))
             (forward-char 1))))
         count))))
@@ -3972,7 +4200,19 @@ outer indentation in case of a commented line.  The 
symbols
                                            LaTeX-item-regexp
                                            "\\)"))
                        (- LaTeX-item-indent))
-                      ((looking-at "}")
+                      ((looking-at (concat (regexp-quote TeX-esc)
+                                           "\\("
+                                           LaTeX-indent-end-regexp-local
+                                           "\\)"))
+                       LaTeX-indent-level)
+                      ((looking-at (concat (regexp-quote TeX-esc)
+                                           "\\("
+                                           LaTeX-indent-mid-regexp-local
+                                           "\\)"))
+                       LaTeX-indent-level)
+                      ((memq (char-after) (append
+                                           TeX-indent-close-delimiters
+                                           '(?\})))
                        TeX-brace-indent-level)
                       (t 0)))))))
 
@@ -6000,8 +6240,10 @@ environments."
     ;; (define-key map "\eq"     'LaTeX-fill-paragraph) ;*** Alias
     ;; This key is now used by Emacs for face settings.
     ;; (define-key map "\eg"     'LaTeX-fill-region) ;*** Alias
-    (define-key map "\e\C-e"  #'LaTeX-find-matching-end)
-    (define-key map "\e\C-a"  #'LaTeX-find-matching-begin)
+    ;; We now set `beginning-of-defun-function' and
+    ;; `end-of-defun-function' instead.
+    ;; (define-key map "\e\C-e"  #'LaTeX-find-matching-end)
+    ;; (define-key map "\e\C-a"  #'LaTeX-find-matching-begin)
 
     (define-key map "\C-c\C-q\C-p" #'LaTeX-fill-paragraph)
     (define-key map "\C-c\C-q\C-r" #'LaTeX-fill-region)
@@ -6027,6 +6269,8 @@ environments."
     (define-key map "(" #'LaTeX-insert-left-brace)
     (define-key map "{" #'LaTeX-insert-left-brace)
     (define-key map "[" #'LaTeX-insert-left-brace)
+
+    (define-key map "\C-xne" #'LaTeX-narrow-to-environment)
     map)
   "Keymap used in `LaTeX-mode'.")
 
@@ -6155,10 +6399,7 @@ corresponds to the variables 
`LaTeX-environment-menu-name' and
                (mapcar #'LaTeX-environment-modify-menu-entry
                        (LaTeX-environment-list))))))))
 
-(if (fboundp 'advice-add)               ;Emacs≥24.4 (or ELPA package nadvice)
-    (advice-add 'LaTeX-add-environments :after #'LaTeX--invalidate-menus)
-  (defadvice LaTeX-add-environments (after LaTeX-invalidate-environment-menu 
(&rest environments) activate)
-    (LaTeX--invalidate-menus)))
+(advice-add 'LaTeX-add-environments :after #'LaTeX--invalidate-menus)
 (defun LaTeX--invalidate-menus (&rest _)
   "Mark the environment menus as being in need of a refresh."
   (setq LaTeX-environment-menu nil)
@@ -6399,8 +6640,9 @@ If prefix argument FORCE is non-nil, always insert a 
regular hyphen."
 
 (defun LaTeX-maybe-install-toolbar ()
   "Conditionally install tool bar buttons for LaTeX mode.
-Install tool bar if `LaTeX-enable-toolbar' is non-nil."
-  (when LaTeX-enable-toolbar
+Install tool bar if `LaTeX-enable-toolbar' and `tool-bar-mode'
+are non-nil."
+  (when (and LaTeX-enable-toolbar tool-bar-mode)
     ;; Defined in `tex-bar.el':
     (LaTeX-install-toolbar)))
 
@@ -6864,8 +7106,6 @@ This happens when \\left is inserted."
 
 (declare-function LaTeX-preview-setup "preview")
 
-(defvar TeX-sentinel-default-function) ;; Defined in tex-buf.el.
-
 ;;;###autoload
 (defun TeX-latex-mode ()
   ;; FIXME: Use `define-derived-mode'.
@@ -6884,9 +7124,8 @@ of `LaTeX-mode-hook'."
   (setq major-mode 'latex-mode)
   (setq TeX-command-default "LaTeX")
   (setq TeX-sentinel-default-function #'TeX-LaTeX-sentinel)
-  (add-hook 'tool-bar-mode-on-hook #'LaTeX-maybe-install-toolbar nil t)
-  (when (and (boundp 'tool-bar-mode) tool-bar-mode)
-    (LaTeX-maybe-install-toolbar))
+  (add-hook 'tool-bar-mode-hook #'LaTeX-maybe-install-toolbar nil t)
+  (LaTeX-maybe-install-toolbar)
   ;; Set the value of `LaTeX-using-Biber' based on the local value of
   ;; `LaTeX-biblatex-use-Biber'.  This should be run within
   ;; `TeX-update-style-hook' before toolbarx-refresh, otherwise the 
bibliography
@@ -7047,6 +7286,11 @@ function would return non-nil and `(match-string 1)' 
would return
   (set (make-local-variable 'TeX-search-files-type-alist)
        LaTeX-search-files-type-alist)
 
+  (setq-local beginning-of-defun-function #'LaTeX-find-matching-begin
+              end-of-defun-function       #'LaTeX-find-matching-end)
+
+  (LaTeX-indent-commands-regexp-make)
+
   (set (make-local-variable 'LaTeX-item-list) '(("description" . 
LaTeX-item-argument)
                                                 ("thebibliography" . 
LaTeX-item-bib)
                                                 ("array" . LaTeX-item-array)
@@ -7231,13 +7475,13 @@ function would return non-nil and `(match-string 1)' 
would return
    '("footnotemark"
      (TeX-arg-conditional TeX-arg-footnote-number-p ([ "Number" ]) nil))
    '("newlength" (TeX-arg-define-length "Length macro"))
-   '("setlength" (TeX-arg-length "Length macro" "\\")
+   '("setlength" (TeX-arg-length "Length macro" nil "\\")
      (TeX-arg-length "Length value"))
-   '("addtolength" (TeX-arg-length "Length macro" "\\")
+   '("addtolength" (TeX-arg-length "Length macro" nil "\\")
      (TeX-arg-length "Length to add"))
-   '("settowidth" (TeX-arg-length "Length macro" "\\") "Text")
-   '("settoheight" (TeX-arg-length "Length macro" "\\") "Text")
-   '("settodepth" (TeX-arg-length "Length macro" "\\") "Text")
+   '("settowidth" (TeX-arg-length "Length macro" nil "\\") "Text")
+   '("settoheight" (TeX-arg-length "Length macro" nil "\\") "Text")
+   '("settodepth" (TeX-arg-length "Length macro" nil "\\") "Text")
    '("\\" [ "Space" ])
    '("\\*" [ "Space" ])
    '("hyphenation" t)
@@ -7351,8 +7595,8 @@ function would return non-nil and `(match-string 1)' 
would return
      '("filecontents*" LaTeX-env-contents))
 
     (TeX-add-symbols
-     '("enlargethispage" TeX-arg-length)
-     '("enlargethispage*" TeX-arg-length)
+     '("enlargethispage"  (TeX-arg-length nil "1.0\\baselineskip"))
+     '("enlargethispage*" (TeX-arg-length nil "1.0\\baselineskip"))
      '("tabularnewline" [ TeX-arg-length ])
      '("suppressfloats" [ TeX-arg-tb "Suppress floats position" ])
      '("ensuremath" "Math commands")
@@ -7654,8 +7898,6 @@ function would return non-nil and `(match-string 1)' 
would return
 
   (use-local-map LaTeX-mode-map)
 
-  (define-key LaTeX-mode-map "\C-xne" #'LaTeX-narrow-to-environment)
-
   ;; Initialization of `add-log-current-defun-function':
   (set (make-local-variable 'add-log-current-defun-function)
        #'TeX-current-defun-name)
@@ -7737,22 +7979,40 @@ function would return non-nil and `(match-string 1)' 
would return
     (LaTeX-find-matching-begin)
     (cons (point) (current-column))))
 
-(defun LaTeX-hanging-ampersand-position ()
-  "Return indent column for a hanging ampersand (that is, ^\\s-*&)."
+(defun LaTeX-hanging-ampersand-position (&optional pos col)
+  "Return indent column for a hanging ampersand (that is, ^\\s-*&).
+When you know the position and column of the beginning of the
+current environment, supply them as optional arguments POS and
+COL for efficiency."
   (cl-destructuring-bind
       (beg-pos . beg-col)
-      (LaTeX-env-beginning-pos-col)
-    (let* ((cur-pos (point)))
+      (if pos
+          (cons pos col)
+        (LaTeX-env-beginning-pos-col))
+    (let ((cur-pos (point)))
       (save-excursion
-        (if (re-search-backward "\\\\\\\\" beg-pos t)
+        (if (and (search-backward "\\\\" beg-pos t)
+                 ;; Give up if the found "\\" belongs to an inner env.
+                 (= beg-pos
+                    (save-excursion
+                      (LaTeX-find-matching-begin)
+                      (point))))
+            ;; FIXME: This `how-many' fails to count correctly if
+            ;; there is an inner env with "&" but without "\\", e.g.
+            ;; \begin{pmatrix}
+            ;;   a & b
+            ;; \end{pmatrix}
             (let ((cur-idx (how-many "[^\\]&" (point) cur-pos)))
               (goto-char beg-pos)
-              (re-search-forward "[^\\]&" cur-pos t (+ 1 cur-idx))
-              ;; If the above searchs fails, i.e. no "&" found,
-              ;; (- (current-column) 1) returns -1, which is wrong.  So
-              ;; we use a fallback (+ 2 beg-col) whenever this happens:
-              (max (- (current-column) 1)
-                   (+ 2 beg-col)))
+              ;; FIXME: This regex search fails if there is an inner
+              ;; env with "&" in it.
+              (if (re-search-forward "[^\\]&" cur-pos t (+ 1 cur-idx))
+                  (- (current-column) 1)
+                ;; If the above searchs fails, i.e. no "&" found,
+                ;; (- (current-column) 1) returns -1, which is wrong.
+                ;; So we use a fallback (+ 2 beg-col) whenever this
+                ;; happens:
+                (+ 2 beg-col)))
           (+ 2 beg-col))))))
 
 (defun LaTeX-indent-tabular ()
@@ -7776,16 +8036,38 @@ function would return non-nil and `(match-string 1)' 
would return
              (+ 2 beg-col))
 
             ((looking-at "&")
-             (LaTeX-hanging-ampersand-position))
+             (LaTeX-hanging-ampersand-position beg-pos beg-col))
 
             (t
              (+ 2
-                (let ((any-col (save-excursion
-                                 (when (re-search-backward "\\\\\\\\\\|[^\\]&" 
beg-pos t)
-                                   (current-column)))))
-                  (if (and any-col (= ?& (char-before (match-end 0))))
-                      (1+ any-col)
-                    beg-col))))))))
+                (let ((any-col
+                       (save-excursion
+                         (when
+                             (catch 'found
+                               ;; Search "\\" or "&" which belongs to
+                               ;; the current env, not an inner env.
+                               (while (re-search-backward
+                                       "\\\\\\\\\\|[^\\]&" beg-pos t)
+                                 (let ((p (point)))
+                                   (when (= beg-pos
+                                            (progn
+                                              (LaTeX-find-matching-begin)
+                                              (point)))
+                                     ;; It belongs to the current env.
+                                     ;; Go to target position and exit
+                                     ;; the loop.
+                                     (goto-char (1+ p))
+                                     (throw 'found t)
+                                     ;; Otherwise it belongs to an
+                                     ;; inner env, so continue the
+                                     ;; loop.
+                                     ))))
+                           ;; If we found "&", then use its column as
+                           ;; `any-col'.  Else, `any-col' will be nil.
+                           (if (= ?& (char-after))
+                                  (current-column))))))
+                  (or any-col
+                      beg-col))))))))
 
 ;; Utilities:
 
diff --git a/plain-tex.el b/plain-tex.el
index 0d43fdba66..a525740643 100644
--- a/plain-tex.el
+++ b/plain-tex.el
@@ -1,6 +1,6 @@
 ;;; plain-tex.el --- Support for plain TeX documents. -*- lexical-binding: t; 
-*-
 
-;; Copyright (C) 2010, 2013, 2016-2018, 2021  Free Software Foundation, Inc.
+;; Copyright (C) 2010, 2013, 2016-2018, 2021-2022  Free Software Foundation, 
Inc.
 
 ;; Maintainer: auctex-devel@gnu.org
 ;; Keywords: tex
@@ -29,7 +29,6 @@
 ;;; Code:
 
 (require 'tex)
-(require 'tex-buf)
 
 ;;; Tool bar
 
@@ -40,8 +39,9 @@
 
 (defun plain-TeX-maybe-install-toolbar ()
   "Conditionally install tool bar buttons for plain TeX mode.
-Install tool bar if `plain-TeX-enable-toolbar' is non-nil."
-  (when plain-TeX-enable-toolbar
+Install tool bar if `plain-TeX-enable-toolbar' and
+`tool-bar-mode' are non-nil."
+  (when (and plain-TeX-enable-toolbar tool-bar-mode)
     ;; Defined in `tex-bar.el':
     (TeX-install-toolbar)))
 
@@ -132,10 +132,8 @@ of `plain-TeX-mode-hook'."
   (use-local-map plain-TeX-mode-map)
   (setq TeX-base-mode-name "TeX")
   (setq TeX-command-default "TeX")
-  (setq TeX-sentinel-default-function #'TeX-TeX-sentinel)
-  (add-hook 'tool-bar-mode-on-hook #'plain-TeX-maybe-install-toolbar nil t)
-  (when (and (boundp 'tool-bar-mode) tool-bar-mode)
-    (plain-TeX-maybe-install-toolbar))
+  (add-hook 'tool-bar-mode-hook #'plain-TeX-maybe-install-toolbar nil t)
+  (plain-TeX-maybe-install-toolbar)
   (run-mode-hooks 'text-mode-hook 'TeX-mode-hook 'plain-TeX-mode-hook)
   (TeX-set-mode-name))
 
@@ -145,6 +143,7 @@ of `plain-TeX-mode-hook'."
   (set-syntax-table TeX-mode-syntax-table)
   (setq local-abbrev-table plain-tex-mode-abbrev-table)
   (set (make-local-variable 'TeX-style-hook-dialect) plain-TeX-dialect)
+  (setq TeX-sentinel-default-function #'TeX-TeX-sentinel)
   (setq paragraph-start
         (concat
          "\\(?:[ \t]*$"
diff --git a/preview.el b/preview.el
index 0d5ec377ea..f60a7abf00 100644
--- a/preview.el
+++ b/preview.el
@@ -1,6 +1,6 @@
 ;;; preview.el --- embed preview LaTeX images in source buffer  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2001-2021  Free Software Foundation, Inc.
+;; Copyright (C) 2001-2022  Free Software Foundation, Inc.
 
 ;; Author: David Kastrup
 ;; Keywords: tex, wp, convenience
@@ -40,7 +40,6 @@
 
 (require 'tex-site)
 (require 'tex)
-(require 'tex-buf)
 (require 'latex)
 
 (eval-when-compile
@@ -2070,11 +2069,6 @@ overlays not in the active window."
       (preview-toggle ovr)
       (push ovr preview-temporary-opened))))
 
-(if (fboundp 'advice-add)               ;Emacs≥24.4 (or ELPA package nadvice)
-    nil ; See the defcustom below.
-  (defadvice replace-highlight (before preview)
-    (preview--open-for-replace (ad-get-arg 0) (ad-get-arg 1))))
-
 (defun preview--open-for-replace (beg end &rest _)
   "Make `query-replace' open preview text about to be replaced."
   (preview-open-overlays (overlays-in beg end)))
@@ -2086,16 +2080,11 @@ overlays not in the active window."
   :require 'preview
   :set (lambda (symbol value)
          (set-default symbol value)
-         (if (fboundp 'advice-add) ; COMPATIBILITY for Emacs<24.4
-             (if value
-                 (advice-add 'replace-highlight :before
-                             #'preview--open-for-replace)
-               (advice-remove 'replace-highlight
-                              #'preview--open-for-replace))
-           (if value
-               (ad-enable-advice 'replace-highlight 'before 'preview)
-             (ad-disable-advice 'replace-highlight 'before 'preview))
-           (ad-activate 'replace-highlight)))
+         (if value
+             (advice-add 'replace-highlight :before
+                         #'preview--open-for-replace)
+           (advice-remove 'replace-highlight
+                          #'preview--open-for-replace)))
   :initialize #'custom-initialize-reset)
 
 (defun preview-relaxed-string= (&rest args)
@@ -3062,14 +3051,6 @@ pp")
        #'desktop-buffer-preview-misc-data)
   (add-hook 'pre-command-hook #'preview-mark-point nil t)
   (add-hook 'post-command-hook #'preview-move-point nil t)
-  (unless preview-tb-icon
-    (setq preview-tb-icon (preview-filter-specs preview-tb-icon-specs)))
-  (when preview-tb-icon
-    (define-key LaTeX-mode-map [tool-bar preview]
-      `(menu-item "Preview at point" preview-at-point
-                  :image ,preview-tb-icon
-                  :help "Preview on/off at point"
-                  :vert-only t)))
   (when buffer-file-name
     (let* ((filename (expand-file-name buffer-file-name))
            format-cons)
@@ -3127,6 +3108,14 @@ to add the preview functionality."
         ["Report Bug" preview-report-bug]))
     (if (eq major-mode 'latex-mode)
         (preview-mode-setup))
+    (unless preview-tb-icon
+      (setq preview-tb-icon (preview-filter-specs preview-tb-icon-specs)))
+    (when preview-tb-icon
+      (define-key LaTeX-mode-map [tool-bar preview]
+        `(menu-item "Preview at point" preview-at-point
+                    :image ,preview-tb-icon
+                    :help "Preview on/off at point"
+                    :vert-only t)))
     (if (boundp 'desktop-buffer-misc)
         (preview-buffer-restore desktop-buffer-misc))))
 
diff --git a/style/algpseudocode.el b/style/algpseudocode.el
index b0c455fef1..1d8bdd7a03 100644
--- a/style/algpseudocode.el
+++ b/style/algpseudocode.el
@@ -1,6 +1,6 @@
 ;;; algpseudocode.el --- AUCTeX style for the (LaTeX) algpseudocode package  
-*- lexical-binding: t; -*-
 
-;; Copyright (C) 2020 Free Software Foundation, Inc.
+;; Copyright (C) 2020--2022 Free Software Foundation, Inc.
 
 ;; Author: Uwe Brauer <oub@mat.ucm.es>
 ;; Created: 2020-01-26
@@ -24,6 +24,7 @@
 ;; 02110-1301, USA.
 
 ;;; Commentary:
+
 ;; This file adds support for the algpseudocode package.
 
 ;;; Code:
@@ -31,46 +32,112 @@
 (require 'tex)
 (require 'latex)
 
+;; Silence the compiler:
+(declare-function font-latex-add-keywords
+                  "font-latex"
+                  (keywords class))
+
 (defvar LaTeX-algpseudocode-package-options
-  '("compatible" "nocompatible")
+  '("compatible" "nocompatible" "end" "noend")
   "Package options for the algpseudocode package.")
 
-
 (TeX-add-style-hook
  "algpseudocode"
  (lambda ()
    (TeX-add-symbols
-    '("algref" 2)
+    ;; 2.3 Simple lines
+    '("State"  (TeX-arg-literal " "))
+    '("Statex" 0)
+
+    ;; 2.4 Placing comments in sources
+    '("Comment" 1)
+
+    ;; 2.5 Labels and references
+    '("algref" (TeX-arg-ref "Algorithm") (TeX-arg-ref "Line"))
+
+    ;; 2.6 Breaking up long algorithms
     '("algstore" 1)
-    '("algrestore" 1)
     '("algstore*" 1)
+    '("algrestore" 1)
     '("algrestore*" 1)
-    '("Procedure" 2)
-    '("Comment" 1)
-    '("State" 0)
-    '("While" 0)
-    '("EndWhile" 0)
-    '("EndProcedure" 0)
-    '("Repeat" 0)
-    '("Until" 0)
+
+    ;; 3.1.1 The for block
     '("For" 1)
     '("ForAll" 1)
     '("EndFor" 0)
+
+    ;; 3.1.2 The while block
+    '("While" 1)
+    '("EndWhile" 0)
+
+    ;; 3.1.3 The repeat block
+    '("Repeat" 0)
+    '("Until" 1)
+
+    ;; 3.1.4 The if block
     '("If" 1)
     '("ElsIf" 1)
     '("Else" 0)
     '("EndIf" 0)
+
+    ;; 3.1.5 The procedure block
+    '("Procedure" 2)
+    '("EndProcedure" 0)
+
+    ;; 3.1.6 The function block
     '("Function" 2)
     '("EndFunction" 0)
+
+    ;; 3.1.7 The loop block
     '("Loop" 0)
     '("EndLoop" 0)
-    '("Require" 0)
-    '("Ensure" 0)
-    '("State" 0)
-    '("Statex" 0)
-    '("Call" 0))
+
+    ;; 3.1.8 Other commands in this layout
+    '("Require" (TeX-arg-literal " "))
+    '("Ensure"  (TeX-arg-literal " "))
+    '("Call" 2))
+
    (LaTeX-add-environments
     '("algorithmic" [ "Number" ]))
-   TeX-dialect))
+
+   ;; Indentation: Add the keywords above to the respective variables
+   ;; and run `LaTeX-indent-commands-regexp-make'.
+   (let ((beg '("For" "ForAll"
+                "While"
+                "Repeat"
+                "If"
+                "Procedure"
+                "Function"
+                "Loop"))
+         (mid '("ElsIf" "Else"))
+         (end '("EndFor"
+                "EndWhile"
+                "Until"
+                "EndIf"
+                "EndProcedure"
+                "EndFunction"
+                "EndLoop")))
+     (dolist (elt beg)
+       (add-to-list 'LaTeX-indent-begin-list elt t))
+     (dolist (elt mid)
+       (add-to-list 'LaTeX-indent-mid-list elt t))
+     (dolist (elt end)
+       (add-to-list 'LaTeX-indent-end-list elt t))
+     (LaTeX-indent-commands-regexp-make))
+
+   ;; Add the 'algorithmic' environment to a local version of
+   ;; `LaTeX-indent-environment-list'.  This effectively kills filling
+   ;; but indenting works as expected.  Hence, 'M-q' gives a better
+   ;; experience.
+   (add-to-list (make-local-variable 'LaTeX-indent-environment-list)
+                '("algorithmic")
+                t)
+
+   ;; Fontification
+   (when (and (featurep 'font-latex)
+              (eq TeX-install-font-lock 'font-latex-setup))
+     (font-latex-add-keywords '(("algref" "{{"))
+                              'reference)))
+ TeX-dialect)
 
 ;;; algpseudocode.el ends here
diff --git a/style/babel.el b/style/babel.el
index d8d980e3a4..a7d67479a8 100644
--- a/style/babel.el
+++ b/style/babel.el
@@ -1,6 +1,6 @@
 ;;; babel.el --- AUCTeX style for `babel.sty' version 3.31.  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2005-2021  Free Software Foundation, Inc.
+;; Copyright (C) 2005-2022  Free Software Foundation, Inc.
 
 ;; Author: Ralf Angeli <angeli@iwi.uni-sb.de>
 ;; Maintainer: auctex-devel@gnu.org
@@ -362,6 +362,13 @@
     ;; 1.25 Language attributes
     '("languageattribute" TeX-arg-babel-lang t))
 
+   ;; Don't increase indentation at various \if* macros:
+   (let ((exceptions '("ifbabelshorthand"
+                       "iflanguage")))
+     (dolist (elt exceptions)
+       (add-to-list 'LaTeX-indent-begin-exceptions-list elt t))
+     (LaTeX-indent-commands-regexp-make))
+
    ;; New environments: 1.8 Auxiliary language selectors
    (LaTeX-add-environments
     '("otherlanguage" LaTeX-env-babel-lang)
diff --git a/style/color.el b/style/color.el
index 517780f949..a98b01bd48 100644
--- a/style/color.el
+++ b/style/color.el
@@ -1,6 +1,6 @@
-;;; color.el --- AUCTeX style for `color.sty' (v1.1a)  -*- lexical-binding: t; 
-*-
+;;; color.el --- AUCTeX style for `color.sty' (v1.3d)  -*- lexical-binding: t; 
-*-
 
-;; Copyright (C) 2015--2020 Free Software Foundation, Inc.
+;; Copyright (C) 2015--2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -26,7 +26,7 @@
 
 ;;; Commentary:
 
-;; This file adds support for `color.sty' (v1.1a) from 2014/10/28.
+;; This file adds support for `color.sty' (v1.3d) from 2022/01/06.
 ;; `color.sty' is part of TeXLive.
 
 ;; Many thanks to Tassilo Horn for his percetive comments on
@@ -273,6 +273,10 @@
       ;; \textcolor[<model>]{<color spec>}{<text>}
       '("textcolor" TeX-arg-color "Text")
 
+      ;; \mathcolor{<name>}{<math>} or
+      ;; \mathcolor[<model>]{<color spec>}{<math>}
+      '("mathcolor" TeX-arg-color "Math")
+
       ;; \pagecolor{<name>} or
       ;; \pagecolor[<model>]{<color spec>}
       '("pagecolor" TeX-arg-color)
@@ -304,8 +308,9 @@
 
 (defvar LaTeX-color-package-options
   '("debugshow" "dvipdf" "dvipdfm" "dvipdfmx" "dvips" "dvipsnames"
-    "dvipsone" "dviwin" "dviwindo" "emtex" "monochrome" "nodvipsnames"
-    "oztex" "pctex32" "pctexhp" "pctexps" "pctexwin" "pdftex" "tcidvi"
+    "dvipsone" "dvisvgm" "dviwin" "dviwindo" "emtex" "luatex"
+    "monochrome" "nodvipsnames" "nosetpagesize" "oztex" "pctex32"
+    "pctexhp" "pctexps" "pctexwin" "pdftex" "setpagesize" "tcidvi"
     "textures" "truetex" "usenames" "vtex" "xdvi" "xetex")
   "Package options for the color package.")
 
diff --git a/style/csquotes.el b/style/csquotes.el
index 38e93091e4..d5714a3530 100644
--- a/style/csquotes.el
+++ b/style/csquotes.el
@@ -1,6 +1,6 @@
 ;;; csquotes.el --- AUCTeX style for `csquotes.sty' (v5.2j)  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2004, 2005, 2006, 2014, 2018, 2020 Free Software Foundation, 
Inc.
+;; Copyright (C) 2004--2022 Free Software Foundation, Inc.
 
 ;; Author: Ralf Angeli <angeli@caeruleus.net>
 ;; Maintainer: auctex-devel@gnu.org
@@ -245,6 +245,19 @@ PROMPT replaces the standard one \"Language\"."
       ;; 8.9 Configuring Punctuation Look-Ahead
       '("DeclareAutoPunct" "Characters"))
 
+     ;; Don't increase indentation at various \if* macros:
+     (let ((exceptions '("ifpunctmark"
+                         "ifpunct"
+                         "ifterm"
+                         "iftextpunctmark"
+                         "iftextpunct"
+                         "iftextterm"
+                         "ifblockquote"
+                         "ifblank")))
+       (dolist (elt exceptions)
+         (add-to-list 'LaTeX-indent-begin-exceptions-list elt t))
+       (LaTeX-indent-commands-regexp-make))
+
      ;; New environments
      (LaTeX-add-environments
 
diff --git a/style/doc.el b/style/doc.el
index 6818e0aad0..63c6580c07 100644
--- a/style/doc.el
+++ b/style/doc.el
@@ -1,6 +1,6 @@
 ;;; doc.el --- AUCTeX style for `doc.sty'  -*- lexical-binding: t; -*-
 
-;; Copyright (C) 2004-2021  Free Software Foundation, Inc.
+;; Copyright (C) 2004-2022  Free Software Foundation, Inc.
 
 ;; Author: Frank Küster <frank@kuesterei.ch>
 ;; Maintainer: auctex-devel@gnu.org
@@ -25,21 +25,24 @@
 
 ;;; Commentary:
 
-;; This file adds support for `doc.sty'.
+;; This file adds support for `doc.sty' (v3.0h) dated 2022/06/01.
 
 ;;; Code:
 
 (require 'tex)
 (require 'latex)
 
-(defun LaTeX-env-no-comment (environment)
+;; Silence the compiler:
+(declare-function font-latex-add-keywords
+                  "font-latex"
+                  (keywords class))
+(declare-function font-latex-add-to-syntax-alist
+                  "font-latex"
+                  (list))
+
+(defun LaTeX-env-doc-no-comment (environment)
   "Insert ENVIRONMENT and make sure there is no commented empty line inside."
-  (LaTeX-insert-environment environment
-                            (when (string-equal environment "macro")
-                              (let ((macroname (TeX-read-string
-                                                (TeX-argument-prompt nil nil 
"Macro")
-                                                TeX-esc)))
-                                (format "{%s}" macroname))))
+  (LaTeX-insert-environment environment)
   (unless (TeX-active-mark)
     (when (save-excursion
             (beginning-of-line)
@@ -48,9 +51,79 @@
       (delete-region (line-beginning-position) (line-end-position))
       (indent-according-to-mode))))
 
+(defun LaTeX-env-doc-commented (environment)
+  "Insert ENVIRONMENT and make sure all parts are in comments.
+This functions search for the begin and the end of the inserted
+environment and makes sure those parts are in comments.  The same
+applies also to the point inside after the insertion."
+  (LaTeX-insert-environment
+   environment
+   (if (string= environment "macro")
+       ;; For 'macro' environment, elements will start with a
+       ;; backslash, so we insert them initially:
+       (progn
+         (let ((opt (mapconcat #'identity
+                               (TeX-completing-read-multiple
+                                (TeX-argument-prompt t nil "Suppress option")
+                                '("noindex" "noprint"))
+                               ","))
+               (mac (TeX-read-string
+                     (TeX-argument-prompt nil nil "Macro(s)")
+                     TeX-esc)))
+           (concat (when (and opt (not (string= opt "")))
+                     (format "[%s]" opt))
+                   (format "{%s}" mac))))
+     ;; For other environments, we don't know about the elements,
+     ;; so do nothing.  For 'environment', we adjust the prompt in
+     ;; minibuffer.
+     (let ((opt (mapconcat #'identity
+                           (TeX-completing-read-multiple
+                            (TeX-argument-prompt t nil "Suppress option")
+                            '("noindex" "noprint"))
+                           ","))
+           (env (TeX-read-string
+                 (TeX-argument-prompt nil nil
+                                      (if (string= environment "environment")
+                                          "Environment(s)"
+                                        "Element(s)")))))
+       (concat
+        (when (and opt (not (string= opt "")))
+          (format "[%s]" opt))
+        (format "{%s}" env)))))
+  ;; Now make sure everything is commented:
+  (let ((p (point-marker))
+        (active-mark (and (TeX-active-mark)
+                          (not (eq (mark) (point)))))
+        (func (lambda ()
+                (if (TeX-in-line-comment)
+                    (indent-according-to-mode)
+                  (delete-horizontal-space)
+                  (beginning-of-line)
+                  (insert "%")
+                  (indent-according-to-mode)))))
+    ;; Go to the start of the env we have inserted:
+    (search-backward (concat "\\begin" TeX-grop environment TeX-grcl)
+                     (if active-mark nil (line-beginning-position 0))
+                     t)
+    ;; If the line is not commented, insert %
+    (funcall func)
+    (goto-char p)
+    ;; Do the same for the end of the environment
+    (search-forward (concat "\\end" TeX-grop environment TeX-grcl)
+                    (if active-mark nil (line-end-position 2))
+                    t)
+    (goto-char (match-beginning 0))
+    (funcall func)
+    ;; Finally for where we started and clean up only when region was
+    ;; not active:
+    (goto-char p)
+    (unless active-mark (funcall func))
+    (set-marker p nil)))
+
 (defun LaTeX-doc-after-insert-macrocode (env start end)
   "Make sure the macrocode environment is properly formatted after insertion."
-  (when (TeX-member env '("macro" "macrocode" "macrocode*") #'string-equal)
+  (when (TeX-member env '("macrocode" "macrocode*")
+                    #'string-equal)
     (save-excursion
       (goto-char end)
       (skip-chars-backward " \t")
@@ -63,134 +136,331 @@
         (insert "%")
         (indent-according-to-mode)))))
 
+(defvar LaTeX-doc-newdocelement-key-val-options
+  '(("macrolike" ("true" "false"))
+    ("envlike" ("true" "false"))
+    ("toplevel" ("true" "false"))
+    ("notoplevel" ("true" "false"))
+    ("idxtype")
+    ("printtype")
+    ("idxgroup")
+    ("noindex" ("true" "false"))
+    ("noprint" ("true" "false")))
+  "Key=value options for '\\NewDocElement' macro.")
+
+;; Setup for \NewDocElement:
+
+(TeX-auto-add-type "doc-NewDocElement" "LaTeX")
+
+(defvar LaTeX-doc-NewDocElement-regexp
+  `(,(concat  "^[ \t%]*"
+              "\\\\NewDocElement"
+              "[ \t\n\r%]*"
+              "\\(?:"
+              (LaTeX-extract-key-value-label 'none)
+              "\\)?"
+              "[ \t\n\r%]*"
+              "{\\([^}]+\\)}"
+              "[ \t\n\r%]*"
+              "{\\([^}]+\\)}")
+    (1 2) LaTeX-auto-doc-NewDocElement)
+  "Matches the arguments of '\\NewDocElement' from doc package.
+AUCTeX parser doesn't look for text parts commented out.
+Therefore, the regexp in this variable explicitly looks for a
+percent sign at the beginning of a line before
+'\\NewDocElement'.")
+
+(defun LaTeX-doc-auto-prepare ()
+  "Clear `LaTeX-auto-doc-NewDocElement' before parsing."
+  (setq LaTeX-auto-doc-NewDocElement nil))
+
+(defun LaTeX-doc-auto-cleanup ()
+  "Process elements defined with '\\NewDocElement'."
+  (when (LaTeX-doc-NewDocElement-list)
+    ;; Make sure `docTeX-indent-inner-fixed' is local:
+    (make-local-variable 'docTeX-indent-inner-fixed)
+
+    ;; \NewDocElement[<options>]{<element-name>}{<env-name>} defines:
+    ;; 1. \Describe<element-name>[<options>]{<element>}
+    ;; 2. \begin{<env-name>}[<options>]{<element>}
+    ;; 3. \PrintDescribe<element-name>{<element>}
+    ;; 4. \Print<element-name>Name
+    (let (macs)
+      (dolist (elt (LaTeX-doc-NewDocElement-list))
+        (let ((eltname (car elt))
+              (envname (cadr elt)))
+          (TeX-add-symbols
+           ;; Cater for \Describe<eltname>[options]{<elements query>}
+           `(,(concat "Describe" eltname)
+             [TeX-arg-eval completing-read
+                           (TeX-argument-prompt t nil "Suppress option")
+                           '("noindex" "noprint")]
+             "Element")
+
+           ;; Cater for \PrintDescribe<eltname>{<elements query>}
+           `(,(concat "PrintDescribe" eltname) "Element")
+
+           ;; Cater for \Print<eltname>Name
+           (concat "Print" eltname "Name"))
+
+          ;; Add the \Describe<element-name> to macs
+          (push (concat "Describe" eltname) macs)
+
+          ;; Cater for \begin{<envname>}[options]{<elements query>}
+          (LaTeX-add-environments
+           `(,envname LaTeX-env-doc-commented))
+
+          ;; Make sure we have fixed inner indent for our environments:
+          (add-to-list 'docTeX-indent-inner-fixed
+                       `(,(concat (regexp-quote TeX-esc)
+                                  "\\(begin\\|end\\)[ \t]*"
+                                  (regexp-quote TeX-grop)
+                                  envname
+                                  (regexp-quote TeX-grcl))
+                         0 nil)
+                       t)
+          ;; Add fontification:
+          (when (and (featurep 'font-latex)
+                     (eq TeX-install-font-lock 'font-latex-setup))
+            (font-latex-add-keywords `((,(concat "Describe" eltname) "[|{\\" ))
+                                     'variable))))
+
+      ;; Let \Describe<element-name> stay in their own lines:
+      (LaTeX-paragraph-commands-add-locally macs))))
+
+(add-hook 'TeX-auto-prepare-hook #'LaTeX-doc-auto-prepare t)
+(add-hook 'TeX-auto-cleanup-hook #'LaTeX-doc-auto-cleanup t)
+(add-hook 'TeX-update-style-hook #'TeX-auto-parse t)
+
 (TeX-add-style-hook
  "doc"
  (lambda ()
-   (add-to-list (make-local-variable 'LaTeX-indent-environment-list)
-                '("macrocode" current-indentation) t)
-   (add-to-list 'LaTeX-indent-environment-list
-                '("macrocode*" current-indentation) t)
-   (add-to-list 'LaTeX-indent-environment-list
-                '("macro" current-indentation) t)
+
+   ;; Add doc to the parser:
+   (TeX-auto-add-regexp LaTeX-doc-NewDocElement-regexp)
+
    (add-hook 'LaTeX-after-insert-env-hook #'LaTeX-doc-after-insert-macrocode
              nil t)
+
    (LaTeX-add-environments
-    "theglossary"
-    '("macrocode" LaTeX-env-no-comment)
-    '("macrocode*" LaTeX-env-no-comment)
-    '("macro" LaTeX-env-no-comment))
+    ;; 2.3 General conventions
+    '("macrocode"  LaTeX-env-doc-no-comment)
+    '("macrocode*" LaTeX-env-doc-no-comment)
+
+    ;; 2.5 Describing the definition of macros and environments
+    '("macro"       LaTeX-env-doc-commented)
+    '("environment" LaTeX-env-doc-commented)
+
+    '("theglossary" LaTeX-env-item))
+
    (TeX-add-symbols
-    "EnableCrossrefs"
-    "DisableCrossrefs"
-    '("DoNotIndex" t)
-    "DontCheckModules"
-    "CheckModules"
-    "Module"
-    '("DescribeMacro" (TeX-arg-eval
-                       (lambda ()
-                         (let ((name (TeX-read-string
-                                      (TeX-argument-prompt nil nil "Macro")
-                                      TeX-esc)))
-                           (format "%s" name)))))
-    '("DescribeEnv" "Environment")
-    "verbatim"
-    "verb"
-    '("parg" "Argument")
-    '("oarg" "Argument")
-    '("marg" "Argument")
-    '("meta" "Text")
-    '("cs" "Name")
-    '("cmd" (TeX-arg-eval
-             (lambda ()
-               (let ((name (TeX-read-string
-                            (TeX-argument-prompt nil nil "Name")
-                            TeX-esc)))
-                 (format "%s" name)))))
-    "makelabel"
-    '("MacroFont" t)
-    '("AltMacroFont" t)
+    ;; 2.1 The driver file
+    '("DocInput"
+      (TeX-arg-eval
+       (lambda ()
+         (let ((file (file-relative-name
+                      (read-file-name
+                       "File to input: " nil nil nil nil
+                       (lambda (x)
+                         (or (file-directory-p x)
+                             (string-match "\\.\\(fdd\\|dtx\\)\\'" x))))
+                      (TeX-master-directory))))
+           (format "%s" file)))))
+
+    '("IndexInput"
+      (TeX-arg-eval
+       (lambda ()
+         (let ((file (file-relative-name
+                      (read-file-name
+                       "File to input: " nil nil nil nil
+                       (lambda (x)
+                         (or (file-directory-p x)
+                             (string-match "\\.\\(tex\\|ltx\\|fdd\\|dtx\\)\\'" 
x))))
+                      (TeX-master-directory))))
+           (format "%s" file)))))
+
+    ;; 2.2 Package options
+    '("SetupDoc" (TeX-arg-eval mapconcat #'identity
+                               (TeX-completing-read-multiple
+                                (TeX-argument-prompt nil nil "Options")
+                                LaTeX-doc-package-options)
+                               ","))
+
+    ;; 2.4 Describing the usage of macros and environments
+    '("DescribeMacro"
+      [TeX-arg-eval completing-read
+                    (TeX-argument-prompt t nil "Suppress option")
+                    '("noindex" "noprint")]
+      (TeX-arg-eval
+       (lambda ()
+         (let ((name (TeX-read-string
+                      (TeX-argument-prompt nil nil "Macro")
+                      TeX-esc)))
+           (format "%s" name)))))
+    '("DescribeEnv"
+      [TeX-arg-eval completing-read
+                    (TeX-argument-prompt t nil "Suppress option")
+                    '("noindex" "noprint")]
+      "Environment")
+
+    ;; 2.5 Describing the definition of macros and environments
+    "MacroFont"
+
+    ;; 2.6 Formatting names in the margin
+    '("PrintDescribeMacro" "Element")
+    '("PrintDescribeEnv"   "Element")
     "PrintMacroName"
-    "PrintDescribeMacro"
-    "PrintDescribeEnv"
     "PrintEnvName"
-    "MakePrivateLetters"
+
+    ;; 2.7 Providing further documentation items
+    '("NewDocElement"
+      [TeX-arg-key-val LaTeX-doc-newdocelement-key-val-options]
+      "Element name" "Environment name")
+
+    ;; 2.8 Displaying sample code verbatim
+    ;; "verbatim" environment and "verb" macro are provided by
+    ;; latex.el, so we don't add them here again.
+
+    ;; 2.9 Using a special escape character
+    '("SpecialEscapechar" "Character")
+
+    ;; 2.10 Cross-referencing all macros used
+    "DisableCrossrefs"
+    "EnableCrossrefs"
+    ;; We don't fontify the next macro since it is a one-liner anyway
+    '("DoNotIndex" t)
+    "CodelineIndex"
+    "PageIndex"
+    "theCodelineNo"
+    "CodelineNumbered"
+
+    ;; 2.11 Producing the actual index entries
     "actualchar"
     "quotechar"
-    "levelchar"
     "encapchar"
-    "verbatimchar"
-    "SpecialIndex"
-    "SpecialMainIndex"
+    "levelchar"
+
+    "SpecialMainMacroIndex"
     "SpecialMainEnvIndex"
-    "SpecialUsageIndex"
+    "SpecialMacroIndex"
     "SpecialEnvIndex"
+    "SpecialIndex"
+    "SpecialShortIndex"
     "SortIndex"
-    "LeftBraceIndex"
-    "RightBraceIndex"
-    "PercentIndex"
-    "OldMakeindex"
-    "PercentIndex"
-    "IndexPrologue"
-    "IndexParms"
+    "verbatimchar"
+
     "subitem"
     "subsubitem"
     "indexspace"
     "efill"
     "pfill"
+
+    ;; 2.12 Setting the index entries: theindex environment is
+    ;; provided by latex.el.
     "PrintIndex"
+    '("IndexPrologue" t)
+    "IndexParms"
+    "main"
+    "usage"
+    "code"
+
+    ;; 2.13 Changing the default values of style parameters
+    "DocstyleParms"
+
+    ;; 2.14 Short input of verbatim text pieces: These macros are
+    ;; provided by 'shortvrb.el' which is run later
+
+    ;; 2.15 Additional bells and whistles
+    "Web"
+    "AmSTeX"
+    "BibTeX"
+    "SliTeX"
+    "PlainTeX"
+    '("meta" "Text")
+    "OnlyDescription"
+    '("StopEventually" t)
+    '("MaybeStop" t)
+    "Finale"
+    "AlsoImplementation"
+    "IndexInput"
     '("changes" "version" TeX-arg-date t)
     "generalname"
     "RecordChanges"
+    "PrintChanges"
     "GlossaryPrologue"
     "GlossaryParms"
-    "PrintChanges"
-    "AlsoImplementation"
-    '("StopEventually" t)
-    "OnlyDescription"
-    "Finale"
-    "IndexInput"
-    "maketitle"
-    "MakeShortVerb"
-    "DeleteShortVerb"
-    "MakeShortverb"
-    "DeleteShortverb"
-    "CheckSum"
-    "CharacterTable"
-    "CharTableChanges"
-    "CodelineNumbered"
-    "CodelineIndex"
-    "PageIndex"
-    "theCodelineNo"
-    "DocstyleParms"
-    "MakePercentIgnore"
-    "MakePercentComment"
-    '("DocInput"
-      (TeX-arg-eval
-       (lambda ()
-         (let ((file (file-relative-name
-                      (read-file-name
-                       "File to input: " nil nil nil nil
-                       (lambda (x)
-                         (string-match "\\.fdd$\\|\\.dtx$" x)))
-                      (TeX-master-directory))))
-           (format "%s" file)))))
-    '("DocInclude"
-      (TeX-arg-eval
-       (lambda ()
-         (let ((file (file-relative-name
-                      (read-file-name
-                       "File to include: " nil nil nil nil
-                       (lambda (x)
-                         (string-match "\\.fdd$\\|\\.dtx$" x)))
-                      (TeX-master-directory))))
-           (format "%s" file)))))
-    "GetFileInfo"
-    "filename"
-    "fileinfo")
+    "bslash"
+    "MakePrivateLetters"
+    "DontCheckModules"
+    "CheckModules"
+    "Module"
+    '("AltMacroFont" t)
+
+    ;; 5.1 makeindex bugs
+    "PercentIndex"
+    ;; 5.2 File transmission issues
+    '("CheckSum" t)
+    '("CharacterTable" t))
+
    (TeX-run-style-hooks "shortvrb")
-   (LaTeX-add-lengths "MacrocodeTopsep" "MacroTopsep" "MacroIndent"))
+
+   (LaTeX-add-lengths "MacrocodeTopsep" "MacroTopsep" "MacroIndent"
+                      "IndexMin" "GlossaryMin")
+   (LaTeX-add-counters "IndexColumns" "GlossaryColumns" "StandardModuleDepth")
+
+   ;; Macros which should be on their own line:
+   (LaTeX-paragraph-commands-add-locally '("DescribeEnv"
+                                           "DescribeMacro"
+                                           "changes"))
+
+   ;; Fontification
+   (when (and (featurep 'font-latex)
+              (eq TeX-install-font-lock 'font-latex-setup))
+     (font-latex-add-keywords '(("SetupDoc"           "{")
+                                ("NewDocElement"      "[{{")
+                                ("RenewDocElement"    "[{{")
+                                ("SpecialEscapechar"  "{")
+                                ("DisableCrossrefs"   "")
+                                ("EnableCrossrefs"    "")
+                                ("CodelineIndex"      "")
+                                ("PageIndex"          "")
+                                ("CodelineNumbered"   "")
+                                ("PrintIndex"         "")
+                                ("IndexPrologue"      "")
+                                ("AmSTeX"             "")
+                                ("BibTeX"             "")
+                                ("SliTeX"             "")
+                                ("PlainTeX"           "")
+                                ("OnlyDescription"    "")
+                                ("StopEventually"     "")
+                                ("MaybeStop"          "")
+                                ("Finale"             "")
+                                ("AlsoImplementation" "")
+                                ("changes"            "{{{")
+                                ("PrintChanges"       "")
+                                ("RecordChanges"      ""))
+                              'function)
+     (font-latex-add-keywords '(("DescribeMacro" "[|{\\")
+                                ("DescribeEnv"   "[{"))
+                              'variable)
+     (font-latex-add-keywords '(("meta"       "{"))
+                              'textual)
+     (font-latex-add-keywords '(("DocInput"   "{")
+                                ("DocInclude" "{" )
+                                ("IndexInput" "{"))
+                              'reference)))
  TeX-dialect)
 
+(defvar LaTeX-doc-package-options
+  '("hyperref" "nohyperref"
+    "multicol" "nomulticol"
+    "debugshow"
+    "noindex" "noprint"
+    "reportchangedates")
+  "Package options for the doc package.")
+
 ;; Local Variables:
 ;; coding: utf-8
 ;; End:
+
+;;; doc.el ends here
diff --git a/style/exam.el b/style/exam.el
index 0ca7c63d57..370a923ef3 100644
--- a/style/exam.el
+++ b/style/exam.el
@@ -1,6 +1,6 @@
 ;;; exam.el --- AUCTeX style for the (LaTeX) exam class  -*- lexical-binding: 
t; -*-
 
-;; Copyright (C) 2016--2020 Free Software Foundation, Inc.
+;; Copyright (C) 2016--2022 Free Software Foundation, Inc.
 
 ;; Author: Uwe Brauer <oub@mat.ucm.es>
 ;; Created: 2016-03-06
@@ -301,9 +301,9 @@ Arguments NAME and TYPE are the same as for the function
     '("hqword" 1)
     '("hsword" 1)
     '("htword" 1)
-    '("ifcontinuation" 0)
-    '("ifincomplete" 0)
-    '("iflastpage" 0)
+    '("ifcontinuation" 2)
+    '("ifincomplete" 2)
+    '("iflastpage" 2)
     '("ifprintanswers" 0)
     '("lfoot" 1)
     '("lhead" 1)
@@ -391,6 +391,14 @@ Arguments NAME and TYPE are the same as for the function
     )
    (LaTeX-add-lengths "answerlinelength" "answerskip")
 
+   ;; Don't increase indentation at various \if* macros:
+   (let ((exceptions '("ifcontinuation"
+                       "ifincomplete"
+                       "iflastpage")))
+     (dolist (elt exceptions)
+       (add-to-list 'LaTeX-indent-begin-exceptions-list elt t))
+     (LaTeX-indent-commands-regexp-make))
+
    ;; Fontification
    (when (and (featurep 'font-latex)
               (eq TeX-install-font-lock 'font-latex-setup))
diff --git a/style/fancyhdr.el b/style/fancyhdr.el
index e849f4e946..eb9751a43e 100644
--- a/style/fancyhdr.el
+++ b/style/fancyhdr.el
@@ -1,6 +1,6 @@
 ;;; fancyhdr.el --- AUCTeX style for `fancyhdr.sty'  -*- lexical-binding: t; 
-*-
 
-;; Copyright (C) 2012, 2013, 2018-2021 Free Software Foundation, Inc.
+;; Copyright (C) 2012, 2013, 2018-2022 Free Software Foundation, Inc.
 
 ;; Author: Mads Jensen <mje@inducks.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -123,6 +123,15 @@ for H(eader) or F(ooter)."
     ;; 15 The scoop on LATEX’s marks
     '("nouppercase" t))
 
+   ;; Don't increase indentation at various \if* macros:
+   (let ((exceptions '("iftopfloat"
+                       "ifbotfloat"
+                       "iffloatpage"
+                       "iffootnote")))
+     (dolist (elt exceptions)
+       (add-to-list 'LaTeX-indent-begin-exceptions-list elt t))
+     (LaTeX-indent-commands-regexp-make))
+
    ;; 30 Deprecated commands
    ;; Don't offer deprecated commands in V4.0 for completion anymore.
    ;; '("lhead" t)
diff --git a/style/german.el b/style/german.el
index 9ae3328053..5dd1c3e509 100644
--- a/style/german.el
+++ b/style/german.el
@@ -30,24 +30,8 @@
  "german"
  (lambda ()
    (set-syntax-table LaTeX-german-mode-syntax-table)
-   ;; XXX: Handle former customizations of the now defunct
-   ;; German-specific variables.  References to the respective
-   ;; variables are to be deleted in future versions. (now = 2005-04-01)
    (unless (eq (car TeX-quote-language) 'override)
-     (let ((open-quote (if (and (boundp 'LaTeX-german-open-quote)
-                                LaTeX-german-open-quote)
-                           LaTeX-german-open-quote
-                         "\"`"))
-           (close-quote (if (and (boundp 'LaTeX-german-close-quote)
-                                 LaTeX-german-close-quote)
-                            LaTeX-german-close-quote
-                          "\"'"))
-           (q-after-q (if (and (boundp 'LaTeX-german-quote-after-quote)
-                               LaTeX-german-quote-after-quote)
-                          LaTeX-german-quote-after-quote
-                        t)))
-       (setq TeX-quote-language
-             `("german" ,open-quote ,close-quote ,q-after-q))))
+     (setq TeX-quote-language '("german" "\"`" "\"'" t)))
    (setq LaTeX-babel-hyphen-language "german")
    ;; Fontification of quotation marks.
    (when (and (eq TeX-install-font-lock 'font-latex-setup)
diff --git a/style/gloss-italian.el b/style/gloss-italian.el
index 68bbcb4048..c13f9f2f1a 100644
--- a/style/gloss-italian.el
+++ b/style/gloss-italian.el
@@ -1,6 +1,6 @@
 ;;; gloss-italian.el --- Italian support for polyglossia package.  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2015, 2018, 2020 Free Software Foundation, Inc.
+;; Copyright (C) 2015, 2018, 2020, 2022 Free Software Foundation, Inc.
 
 ;; Maintainer: auctex-devel@gnu.org
 ;; Author: Mosè Giordano <mose@gnu.org>
@@ -55,16 +55,8 @@
    (when (or (LaTeX-polyglossia-lang-option-member "italian" 
"babelshorthands=true")
              (LaTeX-polyglossia-lang-option-member "italian" 
"babelshorthands"))
      (unless (eq (car TeX-quote-language) 'override)
-       (let ((open-quote (if (and (boundp 'LaTeX-italian-open-quote)
-                                  LaTeX-italian-open-quote)
-                             LaTeX-italian-open-quote
-                           "\"<"))
-             (close-quote (if (and (boundp 'LaTeX-italian-close-quote)
-                                   LaTeX-italian-close-quote)
-                              LaTeX-italian-close-quote
-                            "\">")))
-         (setq TeX-quote-language
-               `("italian" ,open-quote ,close-quote ,TeX-quote-after-quote))))
+       (setq TeX-quote-language
+             `("italian" "\"<" "\">" ,TeX-quote-after-quote)))
 
      ;; Fontification of quotation marks.
      (when (fboundp 'font-latex-add-quotes)
diff --git a/style/ifluatex.el b/style/ifluatex.el
index c32de5c267..86a7638ac9 100644
--- a/style/ifluatex.el
+++ b/style/ifluatex.el
@@ -30,7 +30,6 @@
 ;;; Code:
 
 (require 'tex)
-(require 'tex-buf)
 
 ;; Silence the compiler:
 (declare-function font-latex-add-keywords
diff --git a/style/ifthen.el b/style/ifthen.el
new file mode 100644
index 0000000000..2f426029ef
--- /dev/null
+++ b/style/ifthen.el
@@ -0,0 +1,82 @@
+;;; ifthen.el --- AUCTeX style for `ifthen.sty'  -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2022 Free Software Foundation, Inc.
+
+;; Author: Arash Esbati <arash@gnu.org>
+;; Maintainer: auctex-devel@gnu.org
+;; Created: 2022-03-16
+;; Keywords: tex
+
+;; This file is part of AUCTeX.
+
+;; AUCTeX is free software; you can redistribute it and/or modify it
+;; under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; AUCTeX is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with AUCTeX; see the file COPYING.  If not, write to the Free
+;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+;; 02110-1301, USA.
+
+;;; Commentary:
+
+;; This file adds support for `ifthen.sty' v1.1c, dated 2020/11/24.
+
+;;; Code:
+
+(require 'tex)
+
+;; Silence the compiler:
+(declare-function font-latex-add-keywords
+                  "font-latex"
+                  (keywords class))
+
+(defun LaTeX-arg-ifthen-test (optional &optional prompt)
+  "Query and insert skeleton for a test in ifthen macros."
+  (TeX-argument-insert
+   (completing-read
+    (TeX-argument-prompt optional prompt "Test")
+    '("<" "=" ">"
+      "\\isodd{}"
+      "\\isundefined{}"
+      "\\equal{}{}"
+      "\\lengthtest{<}"
+      "\\lengthtest{=}"
+      "\\lengthtest{>}"
+      "\\boolean{}"))
+   optional))
+
+(TeX-add-style-hook
+ "ifthen"
+ (lambda ()
+   (TeX-add-symbols
+    '("ifthenelse" LaTeX-arg-ifthen-test t nil)
+    '("whiledo"    LaTeX-arg-ifthen-test t)
+    "AND"
+    "OR"
+    "NOT"
+    '("newboolean" "Name")
+    '("provideboolean" "Name")
+    '("setboolean" "Name" (TeX-arg-eval completing-read
+                                        (TeX-argument-prompt nil nil "Value")
+                                        '("true" "false"))))
+
+   ;; Fontification
+   (when (and (featurep 'font-latex)
+              (eq TeX-install-font-lock 'font-latex-setup))
+     ;; Only fontify macros which will be used top-level:
+     (font-latex-add-keywords '(("newboolean"     "{")
+                                ("provideboolean" "{"))
+                              'function)))
+ TeX-dialect)
+
+(defvar LaTeX-ifthen-package-options nil
+  "Package options for the ifthen package.")
+
+;;; ifthen.el ends here
diff --git a/style/italian.el b/style/italian.el
index 0d202b518f..16db7188be 100644
--- a/style/italian.el
+++ b/style/italian.el
@@ -1,6 +1,6 @@
 ;;; italian.el --- Setup AUCTeX for editing Italian text.  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2004, 2005, 2018, 2020 Free Software Foundation, Inc.
+;; Copyright (C) 2004, 2005, 2018, 2020, 2022 Free Software Foundation, Inc.
 
 ;; Author: Davide G. M. Salvetti <salve@debian.org>
 ;; Maintainer: Davide G. M. Salvetti <salve@debian.org>
@@ -44,20 +44,9 @@
 (TeX-add-style-hook
  "italian"
  (lambda ()
-   ;; XXX: Handle former customizations of the now defunct
-   ;; Italian-specific variables.  References to the respective
-   ;; variables are to be deleted in future versions. (now = 2005-04-01)
    (unless (eq (car TeX-quote-language) 'override)
-     (let ((open-quote (if (and (boundp 'LaTeX-italian-open-quote)
-                                LaTeX-italian-open-quote)
-                           LaTeX-italian-open-quote
-                         "\"<"))
-           (close-quote (if (and (boundp 'LaTeX-italian-close-quote)
-                                 LaTeX-italian-close-quote)
-                            LaTeX-italian-close-quote
-                          "\">")))
-       (setq TeX-quote-language
-             `("italian" ,open-quote ,close-quote ,TeX-quote-after-quote))))
+     (setq TeX-quote-language
+           `("italian" "\"<" "\">" ,TeX-quote-after-quote)))
    ;; Fontification of quotation marks.
    (when (fboundp 'font-latex-add-quotes)
      (font-latex-add-quotes '("\"<" "\">" french)))
diff --git a/style/l3doc.el b/style/l3doc.el
new file mode 100644
index 0000000000..e51e83a472
--- /dev/null
+++ b/style/l3doc.el
@@ -0,0 +1,270 @@
+;;; l3doc.el --- AUCTeX style for `l3doc.cls'  -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2022 Free Software Foundation, Inc.
+
+;; Author: Arash Esbati <arash@gnu.org>
+;; Maintainer: auctex-devel@gnu.org
+;; Created: 2022-03-05
+;; Keywords: tex
+
+;; This file is part of AUCTeX.
+
+;; AUCTeX is free software; you can redistribute it and/or modify it
+;; under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; AUCTeX is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with AUCTeX; see the file COPYING.  If not, write to the Free
+;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+;; 02110-1301, USA.
+
+;;; Commentary:
+
+;; This file adds support for `l3doc.cls' dated 2022/02/24.
+
+;;; Code:
+
+(require 'tex)
+(require 'latex)
+
+;; Silence the compiler:
+(declare-function font-latex-add-keywords
+                  "font-latex"
+                  (keywords class))
+(defvar LaTeX-article-class-options)
+
+(defvar LaTeX-l3doc-cmd-key-val-options
+  '(("index")
+    ("noindex")
+    ("module" ("TeX"))
+    ("replace" ("true" "false")))
+  "Key=value options for l3doc macros.")
+
+(defun LaTeX-env-l3doc-function (environment)
+  "Insert the ENVIRONMENT provided by l3doc.cls.
+This function should be used for the environments 'function' and
+'variable' provided by the l3doc class.  Also ask the user if a
+'syntax' environment should be added as well."
+  (let* ((time (format-time-string "%Y-%m-%d" (current-time)))
+         (exp-flag (TeX-read-key-val t `(("added" (,time))
+                                         ("updated" (,time))
+                                         ("deprecated")
+                                         ("tested")
+                                         ("EXP")
+                                         ("rEXP")
+                                         ("TF")
+                                         ("pTF")
+                                         ("noTF")
+                                         ("label")
+                                         ("verb"))
+                                     "Flags (k=v)"))
+         (mac (TeX-read-string
+               (TeX-argument-prompt nil nil "Macro(s)")
+               TeX-esc))
+         (active-mark (and (TeX-active-mark)
+                           (not (eq (mark) (point)))))
+         (elt-count 0)
+         (count 1)
+         (comment-func (lambda ()
+                         (if (TeX-in-line-comment)
+                             (indent-according-to-mode)
+                           (delete-horizontal-space)
+                           (beginning-of-line)
+                           (insert "%")
+                           (indent-according-to-mode))))
+         p)
+    (LaTeX-insert-environment environment
+                              (concat
+                               (unless (zerop (length exp-flag))
+                                 (format "[%s]" exp-flag))
+                               TeX-grop mac TeX-grcl))
+    ;; Remember where we start:
+    (setq p (point-marker))
+    ;; Now make sure we have '%' everywhere, start at the beginning:
+    (search-backward (concat TeX-esc "begin" TeX-grop environment TeX-grcl)
+                     (if active-mark nil (line-beginning-position 0))
+                     t)
+    (funcall comment-func)
+    ;; Now at the end:
+    (goto-char p)
+    (search-forward (concat TeX-esc "end" TeX-grop environment TeX-grcl)
+                    (if active-mark nil (line-end-position 2))
+                    t)
+    (goto-char (match-beginning 0))
+    (funcall comment-func)
+    ;; Finally for where we started and clean up only when region was
+    ;; not active:
+    (goto-char p)
+    (unless active-mark (funcall comment-func))
+    (set-marker p nil)
+    ;; Ask if we should insert a 'syntax' environment:
+    (when (and (not active-mark)
+               (y-or-n-p "Insert syntax environment? "))
+      (LaTeX-environment-menu "syntax")
+      (funcall comment-func)
+      ;; Try to be smart: insert \cs{mac} into buffer.  First, delete
+      ;; any whitespaces after the ',' if inserted:
+      (setq mac (split-string
+                 (replace-regexp-in-string "[[:blank:]]"
+                                           ""
+                                           mac)
+                 "," t))
+      ;; Count the number of elements for the number of linebreaks:
+      (setq elt-count (length mac))
+      ;; Now insert the functions wrapped in \cs:
+      (save-excursion
+        (dolist (elt mac)
+          (insert TeX-esc "cs" TeX-grop (substring elt 1) TeX-grcl)
+          (when (< count elt-count)
+            (LaTeX-newline)
+            (setq count (1+ count)))))
+      ;; Now move to end of the first line:
+      (end-of-line)
+      (just-one-space))))
+
+(defun LaTeX-item-l3doc-syntax ()
+  "Insert line break macro on the last line.
+For syntax environment from l3doc class."
+  (save-excursion
+    (end-of-line 0)
+    (just-one-space)
+    (TeX-insert-macro "\\")))
+
+(TeX-add-style-hook
+ "l3doc"
+ (lambda ()
+
+   ;; l3doc.cls loads shortvrb.sty and sets '|' and '"' as shorthands.
+   ;; We append them to a local version of `LaTeX-shortvrb-chars'
+   ;; before running the style hook for 'shortvrb' which is done
+   ;; inside 'doc.el':
+   (make-local-variable 'LaTeX-shortvrb-chars)
+   (dolist (elt '(?| ?\"))
+     (add-to-list 'LaTeX-shortvrb-chars elt t))
+
+   (TeX-run-style-hooks "expl3" "doc" "ltx-base"
+                        "article" "array" "amsmath" "booktabs"
+                        "color" "colortbl" "hologo" "enumitem"
+                        "textcomp" "csquotes" "fancyvrb" "verbatim"
+                        "underscore")
+
+   (TeX-add-symbols
+    ;; 4.2 Partitioning documentation and implementation
+    '("EnableDocumentation" 0)
+    '("EnableImplementation" 0)
+    '("DisableDocumentation" 0)
+    '("DisableImplementation" 0)
+    '("DocInputAgain" 0)
+
+    ;; 4.3 General text markup
+    '("cmd"
+      [TeX-arg-key-val LaTeX-l3doc-cmd-key-val-options]
+      TeX-arg-macro)
+    '("cs"
+      [TeX-arg-key-val LaTeX-l3doc-cmd-key-val-options]
+      (TeX-arg-eval completing-read
+                    (TeX-argument-prompt nil nil "Macro")
+                    (TeX-symbol-list)))
+    '("tn"
+      [TeX-arg-key-val LaTeX-l3doc-key-val-options]
+      (TeX-arg-eval completing-read
+                    (TeX-argument-prompt nil nil "Macro")
+                    (TeX-symbol-list)))
+
+    ;; "meta" is provided by doc.el, so don't add here again
+    '("Arg" "Argument")
+    '("marg" "Mandatory argument")
+    '("oarg" "Optional argument")
+    '("parg" "Picture mode argument")
+
+    '("file" "File name")
+    '("env" LaTeX-env-args
+      (TeX-arg-eval completing-read
+                    (TeX-argument-prompt nil nil "Environment")
+                    (LaTeX-environment-list)))
+    '("pkg" "Package name")
+    '("cls" "Class name")
+
+    '("NB" "Tag" t)
+
+    '("DocInput"
+      (TeX-arg-eval
+       (lambda ()
+         (let ((file (TeX-read-string
+                      (format "File(s) to include (default %s): " 
(current-buffer))
+                      nil nil (current-buffer))))
+           (format "%s" file)))))
+
+    ;; 4.5 Describing functions in the implementation
+    '("TestFiles" "File(s)")
+    '("UnitTested" 0)
+    '("TestMissing" t))
+
+   (LaTeX-add-environments
+    '("documentation")
+    '("implementation")
+    '("NOTE" "Tag")
+    '("function" LaTeX-env-l3doc-function)
+    '("variable" LaTeX-env-l3doc-function)
+    ;; Feature in 'syntax' environment: Hit 'M-RET' to insert '\\':
+    '("syntax")
+    '("texnote")
+    '("arguments" LaTeX-env-item))
+
+   ;; Do not indent the content of the 'documentation' and
+   ;; 'implementation' environments; it is odd when major parts of the
+   ;; document are indented.  Append them to a local version of
+   ;; `LaTeX-document-regexp':
+   (unless (string-match-p "\\<implementation\\>" LaTeX-document-regexp)
+     (set (make-local-variable 'LaTeX-document-regexp)
+          (concat LaTeX-document-regexp
+                  "\\|documentation\\|implementation")))
+
+   ;; Append syntax to `LaTeX-item-list' with `LaTeX-item-l3doc-syntax'
+   (add-to-list 'LaTeX-item-list '("syntax" . LaTeX-item-l3doc-syntax) t)
+
+   ;; Fontification
+   (when (and (featurep 'font-latex)
+              (eq TeX-install-font-lock 'font-latex-setup))
+     (font-latex-add-keywords '(("cmd"  "[{")
+                                ("cs"   "[{")
+                                ("Arg"  "{")
+                                ("marg" "{")
+                                ("oarg" "{")
+                                ("parg" "{")
+                                ("file" "{")
+                                ("env"  "{")
+                                ("pkg"  "{")
+                                ("cls"  "{")
+                                ("NB"   "{{"))
+                              'textual)
+     (font-latex-add-keywords '(("EnableDocumentation"   "")
+                                ("EnableImplementation"  "")
+                                ("DisableDocumentation"  "")
+                                ("DisableImplementation" "")
+                                ("DocInputAgain"         "")
+                                ("TestFiles"             "{")
+                                ("UnitTested"            "")
+                                ("TestMissing"           "{"))
+                              'function)
+     (font-latex-add-keywords '("DocInput" "{")
+                              'reference)))
+ TeX-dialect)
+
+(defvar LaTeX-l3doc-class-options
+  (progn
+    (TeX-load-style "article")
+    (append (remove "a5paper" LaTeX-article-class-options)
+            '("full" "onlydoc" "check" "nocheck" "checktest"
+              "nochecktest" "kernel" "stdmodule" "cm-default"
+              "lm-default" "cs-break-off" "cs-break-nohyphen"
+              "show-notes" "hide-notes")))
+  "Class options for the l3doc class.")
+
+;;; l3doc.el ends here
diff --git a/style/longtable.el b/style/longtable.el
index 2646e339ab..8db4083c66 100644
--- a/style/longtable.el
+++ b/style/longtable.el
@@ -1,6 +1,6 @@
 ;;; longtable.el --- AUCTeX style for `longtable.sty'.  -*- lexical-binding: 
t; -*-
 
-;; Copyright (C) 2013--2020  Free Software Foundation, Inc.
+;; Copyright (C) 2013--2022  Free Software Foundation, Inc.
 
 ;; Maintainer: auctex-devel@gnu.org
 ;; Author: Mosè Giordano <mose@gnu.org>
@@ -56,13 +56,24 @@ insert line break macro."
 
 (defun LaTeX-env-longtable (environment)
   "Insert a longtable-like ENVIRONMENT with caption and label."
-  (let* ((pos (completing-read (TeX-argument-prompt t nil "Position")
-                               '(("l") ("r") ("c"))))
-         (fmt (TeX-read-string "Format: " LaTeX-default-format))
+  (let* ((pos (and LaTeX-default-position ; `LaTeX-default-position'
+                                        ; can be nil, i.e. no prompt
+                   (completing-read (TeX-argument-prompt t nil "Position")
+                                    '("l" "r" "c")
+                                    nil nil LaTeX-default-position)))
+         (fmt (TeX-read-string
+               (if (string= LaTeX-default-format "")
+                   "Format: "
+                 (format "Format (default %s): " LaTeX-default-format))
+               nil nil
+               (if (string= LaTeX-default-format "")
+                   nil
+                 LaTeX-default-format)))
          (caption (TeX-read-string "Caption: "))
          (short-caption (when (>= (length caption) 
LaTeX-short-caption-prompt-length)
                           (TeX-read-string "(Optional) Short caption: "))))
-    (setq LaTeX-default-format fmt)
+    (setq LaTeX-default-position pos
+          LaTeX-default-format   fmt)
     (LaTeX-insert-environment environment
                               (concat
                                (unless (zerop (length pos))
diff --git a/style/ltxtable.el b/style/ltxtable.el
index f73c0e7a5d..51b9b02550 100644
--- a/style/ltxtable.el
+++ b/style/ltxtable.el
@@ -1,6 +1,6 @@
-;;; ltxtable.el --- AUCTeX style for `ltxtable.sty' (v0.2)  -*- 
lexical-binding: t; -*-
+;;; ltxtable.el --- AUCTeX style for `ltxtable.sty' (v0.4)  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2015, 2018, 2020 Free Software Foundation, Inc.
+;; Copyright (C) 2015--2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -26,7 +26,7 @@
 
 ;;; Commentary:
 
-;; This file adds support for `ltxtable.sty' (v0.2) from 1995/12/11.
+;; This file adds support for `ltxtable.sty' (v0.4) from 2021/06/13.
 ;; `ltxtable.sty' is part of TeXLive.
 
 ;;; Code:
@@ -63,7 +63,13 @@ The regexp for the 2. argument is the same as for \"input\" 
and
       (TeX-arg-eval
        (lambda ()
          (let ((longtable (file-relative-name
-                           (read-file-name "File with longtable: "))))
+                           (read-file-name
+                            "File with longtable: "
+                            nil nil nil nil
+                            (lambda (x)
+                              (or (file-directory-p x)
+                                  (string-match "\\.\\(tex\\|ltx\\)\\'" x))))
+                           (TeX-master-directory))))
            (format "%s" longtable))))))
 
    ;; Make sure that \LTXtable stays in its own line:
@@ -86,7 +92,7 @@ The regexp for the 2. argument is the same as for \"input\" 
and
    (when (and (featurep 'font-latex)
               (eq TeX-install-font-lock 'font-latex-setup))
      (font-latex-add-keywords '(("LTXtable"  "{{"))
-                              'textual)))
+                              'reference)))
  TeX-dialect)
 
 (defvar LaTeX-ltxtable-package-options nil
diff --git a/style/newfloat.el b/style/newfloat.el
index 74185bd67d..5cde1d4c7a 100644
--- a/style/newfloat.el
+++ b/style/newfloat.el
@@ -1,6 +1,6 @@
 ;;; newfloat.el --- AUCTeX style for `newfloat.sty' (v1.1-109)  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2015--2021 Free Software Foundation, Inc.
+;; Copyright (C) 2015--2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -82,15 +82,15 @@
 ;; Setup parsing for \DeclareFloatingEnvironment:
 (TeX-auto-add-type "newfloat-DeclareFloatingEnvironment" "LaTeX")
 
-(defvar LaTeX-newfloat-DeclareFloatingEnvironment-regex
+(defvar LaTeX-newfloat-DeclareFloatingEnvironment-regexp
   `(,(concat "\\\\DeclareFloatingEnvironment"
              "[ \t\n\r%]*"
-             "\\["
-             "[ \t\n\r%{}a-zA-Z0-9=,-]*"
-             "\\]"
+             "\\(?:"
+             (LaTeX-extract-key-value-label 'none)
+             "\\)?"
              "[ \t\n\r%]*"
              "{\\([^}]+\\)}"
-             "\\(?:[ %]*{\\([^}]*\\)}\\)?")
+             "\\(?:[ %]*{\\(figure\\|table\\|verbatim\\)}\\)?")
     (1 2) LaTeX-auto-newfloat-DeclareFloatingEnvironment)
   "Matches the argument of `\\DeclareFloatingEnvironment' from 
`newfloat.sty'.")
 
@@ -152,7 +152,7 @@ If `caption.el' is loaded, add the new floating environment 
to
  (lambda ()
 
    ;; Add newfloat to the parser.
-   (TeX-auto-add-regexp LaTeX-newfloat-DeclareFloatingEnvironment-regex)
+   (TeX-auto-add-regexp LaTeX-newfloat-DeclareFloatingEnvironment-regexp)
 
    ;; Commands:
    (TeX-add-symbols
diff --git a/style/ngerman.el b/style/ngerman.el
index 0fd41acb26..6081615f43 100644
--- a/style/ngerman.el
+++ b/style/ngerman.el
@@ -30,24 +30,8 @@
  "ngerman"
  (lambda ()
    (set-syntax-table LaTeX-german-mode-syntax-table)
-   ;; XXX: Handle former customizations of the now defunct
-   ;; German-specific variables.  References to the respective
-   ;; variables are to be deleted in future versions. (now = 2005-04-01)
    (unless (eq (car TeX-quote-language) 'override)
-     (let ((open-quote (if (and (boundp 'LaTeX-german-open-quote)
-                                LaTeX-german-open-quote)
-                           LaTeX-german-open-quote
-                         "\"`"))
-           (close-quote (if (and (boundp 'LaTeX-german-close-quote)
-                                 LaTeX-german-close-quote)
-                            LaTeX-german-close-quote
-                          "\"'"))
-           (q-after-q (if (and (boundp 'LaTeX-german-quote-after-quote)
-                               LaTeX-german-quote-after-quote)
-                          LaTeX-german-quote-after-quote
-                        t)))
-       (setq TeX-quote-language
-             `("ngerman" ,open-quote ,close-quote ,q-after-q))))
+     (setq TeX-quote-language '("ngerman" "\"`" "\"'" t)))
    (setq LaTeX-babel-hyphen-language "ngerman")
    ;; Fontification
    (when (and (eq TeX-install-font-lock 'font-latex-setup)
diff --git a/style/ocg-p.el b/style/ocg-p.el
index 26f881f445..d3ab40da89 100644
--- a/style/ocg-p.el
+++ b/style/ocg-p.el
@@ -1,6 +1,6 @@
 ;;; ocg-p.el --- AUCTeX style for `ocg-p.sty' (v0.4)  -*- lexical-binding: t; 
-*-
 
-;; Copyright (C) 2018, 2020 Free Software Foundation, Inc.
+;; Copyright (C) 2018--2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -123,7 +123,14 @@ Just like array and tabular."
   (let ((pos (and LaTeX-default-position ; LaTeX-default-position can
                                         ; be nil, i.e. do not prompt
                   (TeX-read-string "(Optional) Position: " 
LaTeX-default-position)))
-        (fmt (TeX-read-string "Format: " LaTeX-default-format))
+        (fmt (TeX-read-string
+              (if (string= LaTeX-default-format "")
+                  "Format: "
+                (format "Format (default %s): " LaTeX-default-format))
+              nil nil
+              (if (string= LaTeX-default-format "")
+                  nil
+                LaTeX-default-format)))
         (dbase (TeX-read-string "Database name: "))
         (opts (TeX-read-string "Additional options: ")))
     (setq LaTeX-default-position pos)
diff --git a/style/plext.el b/style/plext.el
index 8b4cf0b3f3..26e564e584 100644
--- a/style/plext.el
+++ b/style/plext.el
@@ -1,6 +1,6 @@
 ;;; plext.el --- AUCTeX style for the plext package.  -*- lexical-binding: t; 
-*-
 
-;; Copyright (C) 2014, 2020 Free Software Foundation, Inc.
+;; Copyright (C) 2014, 2020, 2022 Free Software Foundation, Inc.
 
 ;; Author: Ikumi Keita <ikumi@ikumi.que.jp>
 ;; Maintainer: auctex-devel@gnu.org
@@ -55,11 +55,20 @@
 (defun LaTeX-plext-env-array (env)
   (let ((dir (TeX-read-string "(Optional) Direction (t or y or z): "))
         (width (if (string= env "tabular*")
-                   (TeX-read-string "Width: " LaTeX-default-width)))
+                   (TeX-read-string
+                    (format "Width (default %s): " LaTeX-default-width)
+                    nil nil LaTeX-default-width)))
         (pos (and LaTeX-default-position ; LaTeX-default-position can
                                         ; be nil, i.e. do not prompt
                   (TeX-read-string "(Optional) Position: " 
LaTeX-default-position)))
-        (fmt (TeX-read-string "Format: " LaTeX-default-format)))
+        (fmt (TeX-read-string
+              (if (string= LaTeX-default-format "")
+                  "Format: "
+                (format "Format (default %s): " LaTeX-default-format))
+              nil nil
+              (if (string= LaTeX-default-format "")
+                  nil
+                LaTeX-default-format))))
     (unless (zerop (length dir))
       (setq dir (concat "<" dir ">")))
     (if (string= env "tabular*")
diff --git a/style/polyglossia.el b/style/polyglossia.el
index 4bfb93e66f..204923b608 100644
--- a/style/polyglossia.el
+++ b/style/polyglossia.el
@@ -37,7 +37,6 @@
 
 (require 'tex) ;Indispensable when compiling the call to `TeX-auto-add-type'.
 (require 'latex)
-(require 'tex-buf)
 
 ;; Silence the compiler:
 (declare-function font-latex-add-keywords
diff --git a/style/scrpage2.el b/style/scrpage2.el
index 33cc7c5f8e..dca55909e4 100644
--- a/style/scrpage2.el
+++ b/style/scrpage2.el
@@ -81,6 +81,10 @@
     '("renewpagestyle" "Name" "Head definition" "Foot definition")
     '("providepagestyle" "Name" "Head definition" "Foot definition"))
 
+   ;; Don't increase indent at \ifoot:
+   (add-to-list 'LaTeX-indent-begin-exceptions-list "ifoot" t)
+   (LaTeX-indent-commands-regexp-make)
+
    ;; Fontification
    (when (and (featurep 'font-latex)
               (eq TeX-install-font-lock 'font-latex-setup))
diff --git a/style/sidecap.el b/style/sidecap.el
index bcd019c964..ff175173e6 100644
--- a/style/sidecap.el
+++ b/style/sidecap.el
@@ -1,6 +1,6 @@
 ;;; sidecap.el --- AUCTeX style for `sidecap.sty' (v1.6f)  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2021 Free Software Foundation, Inc.
+;; Copyright (C) 2021, 2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -36,94 +36,58 @@
 
 (defun LaTeX-env-sidecap-float (environment)
   "Create ENVIRONMENT with \\caption and \\label commands.
-This function is a copy of `LaTeX-env-figure' and adjusted to
-read the first optional argument 'relwidth' provided by
-environments of the package sidecap."
-  (let* ((relwidth (TeX-read-string
-                    (TeX-argument-prompt t nil "Relative caption width")))
-         (float (and LaTeX-float        ; LaTeX-float can be nil, i.e.
-                                        ; do not prompt
-                     (TeX-read-string "(Optional) Float position: " 
LaTeX-float)))
-         (caption (TeX-read-string "Caption: "))
-         (short-caption (when (>= (length caption) 
LaTeX-short-caption-prompt-length)
-                          (TeX-read-string "(Optional) Short caption: ")))
-         (center (y-or-n-p "Center? "))
-         (active-mark (and (TeX-active-mark)
-                           (not (eq (mark) (point)))))
-         start-marker end-marker)
-    (when active-mark
-      (if (< (mark) (point))
-          (exchange-point-and-mark))
-      (setq start-marker (point-marker))
-      (set-marker-insertion-type start-marker t)
-      (setq end-marker (copy-marker (mark))))
-    (setq LaTeX-float float)
-    (LaTeX-insert-environment environment
-                              (concat
-                               ;; First check if 'relwidth' is given:
-                               (when (and relwidth
-                                          (not (string= relwidth "")))
-                                 (concat LaTeX-optop relwidth
-                                         LaTeX-optcl))
-                               ;; We have to insert a pair of brackets
-                               ;; if 'float' is given and 'relwidth'
-                               ;; was empty, otherwise 'float' becomes
-                               ;; 'relwidth':
-                               (unless (zerop (length float))
-                                 (concat
-                                  (when (or (null relwidth)
-                                            (string= relwidth ""))
-                                    (concat LaTeX-optop LaTeX-optcl))
-                                  LaTeX-optop float LaTeX-optcl))))
-    (when active-mark
-      (goto-char start-marker)
-      (set-marker start-marker nil))
-    (when center
-      (insert TeX-esc "centering")
-      (indent-according-to-mode)
-      (LaTeX-newline)
-      (indent-according-to-mode))
-    ;; Insert caption and ask for a label, do nothing if user skips caption
-    (unless (zerop (length caption))
-      (if (member environment LaTeX-top-caption-list)
-          ;; top caption
-          (progn
-            (insert (LaTeX-compose-caption-macro caption short-caption))
-            ;; If `auto-fill-mode' is active, fill the caption.
-            (if auto-fill-function (LaTeX-fill-paragraph))
-            (LaTeX-newline)
-            (indent-according-to-mode)
-            ;; ask for a label and insert a new line only if a label is
-            ;; actually inserted
-            (when (LaTeX-label environment 'environment)
-              (LaTeX-newline)
-              (indent-according-to-mode)))
-        ;; bottom caption (default)
-        (when active-mark (goto-char end-marker))
-        (save-excursion
-          (LaTeX-newline)
-          (indent-according-to-mode)
-          ;; If there is an active region point is before the backslash of
-          ;; "\end" macro, go one line upwards.
-          (when active-mark (forward-line -1) (indent-according-to-mode))
-          (insert (LaTeX-compose-caption-macro caption short-caption))
-          ;; If `auto-fill-mode' is active, fill the caption.
-          (if auto-fill-function (LaTeX-fill-paragraph))
-          ;; ask for a label and if necessary insert a new line between caption
-          ;; and label
-          (when (save-excursion (LaTeX-label environment 'environment))
-            (LaTeX-newline)
-            (indent-according-to-mode)))
-        ;; Insert an empty line between caption and marked region, if any.
-        (when active-mark (LaTeX-newline) (forward-line -1))
-        (indent-according-to-mode)))
-    (when (markerp end-marker)
-      (set-marker end-marker nil))
+This function runs `LaTeX-env-figure' and inserts the first
+optional argument 'relwidth' provided by environments of the
+package sidecap."
+  (let ((relwidth (TeX-read-string
+                   (TeX-argument-prompt t nil "Relative caption width")))
+        (sc-active-mark (and (TeX-active-mark)
+                             (not (eq (mark) (point)))))
+        (p (point-marker))
+        s)
+    ;; Run `LaTeX-env-figure' which does the major part of the job:
+    (LaTeX-env-figure environment)
+    ;; Now save the position:
+    (setq s (point-marker))
+    ;; Search backwards to see if an optional float-placement arg is
+    ;; inserted; this would be the 2nd arg for sidecap environments:
+    (save-excursion
+      (re-search-backward (concat (regexp-quote TeX-esc)
+                                  "begin"
+                                  "[ \t]*"
+                                  TeX-grop
+                                  (regexp-quote environment)
+                                  "\\(" TeX-grcl "\\)"
+                                  "[ \t]*"
+                                  "\\("
+                                  (regexp-quote LaTeX-optop)
+                                  ;; Float placement:
+                                  "\\([a-zA-Z!]*\\)"
+                                  (regexp-quote LaTeX-optcl)
+                                  "\\)?")
+                          p t))
+    (cond (;; Insert the first optional arg at any rate if non-empty:
+           (and relwidth (not (string= relwidth "")))
+           (goto-char (match-end 1))
+           (insert LaTeX-optop relwidth LaTeX-optcl))
+          ;; Insert a pair of empty brackets if relwidth is empty and
+          ;; float-placement is given:
+          ((and (or (null relwidth)
+                    (string= relwidth ""))
+                (match-string 3))
+           (goto-char (match-beginning 2))
+           (insert LaTeX-optop LaTeX-optcl))
+          (t nil))
+    ;; Go back to where we started if we have moved at all:
+    (unless (= s (point))
+      (goto-char s))
+    ;; Insert a tabular stored in `LaTeX-default-tabular-environment':
     (when (and (member environment '("SCtable" "SCtable*"))
-               ;; Suppose an existing tabular environment should just
-               ;; be wrapped into a table if there is an active region.
-               (not active-mark))
-      (LaTeX-environment-menu LaTeX-default-tabular-environment))))
+               (not sc-active-mark))
+      (LaTeX-environment-menu LaTeX-default-tabular-environment))
+    ;; Clean up the markers:
+    (set-marker s nil)
+    (set-marker p nil)))
 
 (TeX-add-style-hook
  "sidecap"
@@ -147,7 +111,14 @@ environments of the package sidecap."
    ;; The next 2 can be set with '\renewcommand':
    (TeX-add-symbols
     "sidecaptionsep"
-    "sidecaptionrelwidth"))
+    "sidecaptionrelwidth")
+
+   ;; Run the style hook for 'ragged2e' if necessary:
+   (when (or (LaTeX-provided-package-options-member "sidecap" "raggedright")
+             (LaTeX-provided-package-options-member "sidecap" "raggedleft")
+             (LaTeX-provided-package-options-member "sidecap" "ragged"))
+     (TeX-run-style-hooks "ragged2e")))
+
  TeX-dialect)
 
 (defvar LaTeX-sidecap-package-options
diff --git a/style/titleps.el b/style/titleps.el
index 33801b46b2..8de8b1d3d7 100644
--- a/style/titleps.el
+++ b/style/titleps.el
@@ -1,6 +1,6 @@
 ;;; titleps.el --- AUCTeX style for `titleps.sty' (v1.1.1)  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2016, 2018, 2020 Free Software Foundation, Inc.
+;; Copyright (C) 2016--2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -210,6 +210,10 @@ Removal is based on the return value of function
     ;; until then, I ignore them
     )
 
+   ;; Don't increase indent at \ifsamemark:
+   (add-to-list 'LaTeX-indent-begin-exceptions-list "ifsamemark" t)
+   (LaTeX-indent-commands-regexp-make)
+
    (when (and (featurep 'font-latex)
               (eq TeX-install-font-lock 'font-latex-setup))
      (font-latex-add-keywords '(("newpagestyle"         "{[{")
diff --git a/style/titlesec.el b/style/titlesec.el
index 12621861e0..c3af038228 100644
--- a/style/titlesec.el
+++ b/style/titlesec.el
@@ -1,6 +1,6 @@
 ;;; titlesec.el --- AUCTeX style for `titlesec.sty' (v2.11)  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2016--2020 Free Software Foundation, Inc.
+;; Copyright (C) 2016--2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -190,6 +190,10 @@ insert the argument in brackets."
                     (TeX-argument-prompt t nil "Super level command")
                     (LaTeX-titlesec-section-command-list)]) )
 
+   ;; Don't increase indent at \iftitlemeasuring:
+   (add-to-list 'LaTeX-indent-begin-exceptions-list "iftitlemeasuring" t)
+   (LaTeX-indent-commands-regexp-make)
+
    ;; 3.4. Rules: A variant of \titleline to be used only with calcwidth
    (when (LaTeX-provided-package-options-member "titlesec" "calcwidth")
      (TeX-add-symbols
diff --git a/style/xcolor.el b/style/xcolor.el
index 6399516a60..06bd28f73b 100644
--- a/style/xcolor.el
+++ b/style/xcolor.el
@@ -1,6 +1,6 @@
 ;; xcolor.el --- AUCTeX style for `xcolor.sty' (v2.12)  -*- lexical-binding: 
t; -*-
 
-;; Copyright (C) 2016--2020 Free Software Foundation, Inc.
+;; Copyright (C) 2016--2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -26,7 +26,7 @@
 
 ;;; Commentary:
 
-;; This file adds support for `xcolor.sty' (v2.12) from 2016/05/11.
+;; This file adds support for `xcolor.sty' (v2.13) from 2021/10/31.
 ;; `xcolor.sty' is part of TeXLive.
 
 ;; `xcolor.sty' and `color.sty' share many command namens, but the
@@ -463,6 +463,10 @@ xcolor package.")
     ;; \textcolor[<model>]{<color spec>}{<text>}
     '("textcolor" TeX-arg-xcolor "Text")
 
+    ;; \mathcolor{<name>}{<math>} or
+    ;; \mathcolor[<model>]{<color spec>}{<math>}
+    '("mathcolor" TeX-arg-xcolor "Math")
+
     ;; \pagecolor{<name>} or
     ;; \pagecolor[<model>]{<color spec>}
     '("pagecolor" TeX-arg-xcolor)
@@ -627,9 +631,10 @@ xcolor package.")
 
 (defvar LaTeX-xcolor-package-options
   '(;; options that determine the color driver
-    "dvips" "xdvi" "dvipdf" "dvipdfm" "dvipdfmx" "pdftex" "dvipsone"
-    "dviwindo" "emtex" "dviwin" "oztex" "textures" "pctexps" "pctexwin"
-    "pctexhp" "pctex32" "truetex" "tcidvi" "vtex" "xetex"
+    "dvipdf" "dvipdfm" "dvipdfmx" "dvips" "dvipsone" "dvisvgm"
+    "dviwin" "dviwindo" "emtex" "luatex" "oztex" "pctex32"
+    "pctexhp" "pctexps" "pctexwin" "pdftex" "tcidvi" "textures"
+    "truetex" "vtex" "xdvi" "xetex"
 
     ;; options that determine the target color model
     "natural" "rgb" "cmy" "cmyk" "hsb" "gray" "RGB" "HTML"
diff --git a/style/xltabular.el b/style/xltabular.el
index 09c5a97248..3fb3e0d220 100644
--- a/style/xltabular.el
+++ b/style/xltabular.el
@@ -1,6 +1,6 @@
 ;;; xltabular.el --- AUCTeX style for `xltabular.sty' (v0.05)  -*- 
lexical-binding: t; -*-
 
-;; Copyright (C) 2017, 2020 Free Software Foundation, Inc.
+;; Copyright (C) 2017--2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
@@ -49,15 +49,29 @@ nested curly brace pair nor escaped \"}\".")
   ;; Optional <hPos> comes before <width>, hence we cannot use
   ;; `LaTeX-env-tabular*' here and has to cook our own function which
   ;; is a combination of `LaTeX-env-tabular*' and
-  ;; `LaTeX-env-longtable':
-  (let* ((pos (completing-read (TeX-argument-prompt t nil "Position")
-                               '("l" "r" "c")))
-         (width (TeX-read-string "Width: " LaTeX-default-width))
-         (fmt (TeX-read-string "Format: " LaTeX-default-format))
+  ;; `LaTeX-env-longtable'.  Note that `LaTeX-default-position' can be
+  ;; nil, i.e. do not prompt:
+  (let* ((pos (and LaTeX-default-position
+                   (completing-read (TeX-argument-prompt t nil "Position")
+                                    '("l" "r" "c")
+                                    nil nil LaTeX-default-position)))
+         (width (TeX-read-string
+                 (format "Width (default %s): " LaTeX-default-width)
+                 nil nil LaTeX-default-width))
+         (fmt (TeX-read-string
+               (if (string= LaTeX-default-format "")
+                   "Format: "
+                 (format "Format (default %s): " LaTeX-default-format))
+               nil nil
+               (if (string= LaTeX-default-format "")
+                   nil
+                 LaTeX-default-format)))
          (caption (TeX-read-string "Caption: "))
          (short-caption (when (>= (length caption) 
LaTeX-short-caption-prompt-length)
                           (TeX-read-string "(Optional) Short caption: "))))
-    (setq LaTeX-default-format fmt)
+    (setq LaTeX-default-position pos
+          LaTeX-default-width    width
+          LaTeX-default-format   fmt)
     (LaTeX-insert-environment environment
                               (concat
                                (unless (zerop (length pos))
diff --git a/tests/context/context-test.el b/tests/context/context-test.el
index 4eeab4b67a..cc7c8d549f 100644
--- a/tests/context/context-test.el
+++ b/tests/context/context-test.el
@@ -24,6 +24,12 @@
 (require 'ert)
 (require 'context)
 
+;; We need to ensure that font-lock has put the syntax properties
+;; already which won't happen in batch mode.  So trigger font-lock
+;; immediately.
+(define-advice ConTeXt-mode-common-initialization (:after ())
+  (font-lock-ensure))
+
 (AUCTeX-set-ert-path
  'ConTeXt-indent-test/in
  "context-indentation-in.tex"
diff --git a/tests/japanese/error-parsing.el b/tests/japanese/error-parsing.el
index 36f3ca5fa9..599e1cdab3 100644
--- a/tests/japanese/error-parsing.el
+++ b/tests/japanese/error-parsing.el
@@ -22,7 +22,6 @@
 ;;; Code:
 
 (require 'ert)
-(require 'tex-buf)
 (setq japanese-TeX-error-messages t)
 (require 'tex-jp)
 
diff --git a/tests/latex/conditionals-indent-in.tex 
b/tests/latex/conditionals-indent-in.tex
new file mode 100644
index 0000000000..2d8634e1b5
--- /dev/null
+++ b/tests/latex/conditionals-indent-in.tex
@@ -0,0 +1,158 @@
+\documentclass{article}
+
+\usepackage{algpseudocode}
+\usepackage[%
+  key = val , %
+               key = val , %
+]{package}
+
+\begin{document}
+
+\newif\ifluatex
+\ifluatex
+luatex specific code
+\else
+code for other engines
+\fi
+
+\def\IfFileExists#1#2#3{%
+\openin\@inputcheck#1 %
+\ifeof\@inputcheck
+#3\relax
+\else
+\read\@inputcheck to \reserved@a
+\ifx\reserved@a\today
+\typeout{#1 found}#2\relax
+\else
+\typeout{BAD: old file \reserved@a (should be \today)}%
+#3\relax
+\fi
+\fi
+\closein\@inputcheck}
+
+\def\filename@simple#1.#2\\{%
+\ifx\\#2\\%
+\let\filename@ext\relax
+\edef\filename@base{#1}%
+\else
+\filename@dots{#1}#2\\%
+\fi}
+
+\ifx\directlua\@undefined
+\def\newwrite {\e@alloc\write
+\chardef{\count17}
+\m@ne\sixt@@n}
+\else
+\def\newwrite {\e@alloc\write {%
+\ifnum\allocationnumber=18
+\advance\count17\@ne
+\allocationnumber\count17 %
+        \fi
+\global\chardef
+}%
+{\count17}%
+\m@ne
+{128}}
+\fi
+
+\gdef\e@ch@ck#1#2#3#4{%
+\ifnum#1<#2\else
+ \ifnum#1=#2\relax
+ \global#1\@cclvi
+      \ifx\count#4\global\advance#1 10 \fi
+            \fi
+  \ifnum#1<#3\relax
+ \else
+ \errmessage{No room for a new \string#4}%
+ \fi
+   \fi
+}%
+
+\def\newinsert#1{%
+\@tempswafalse
+\global\advance\insc@unt\m@ne
+\ifnum\count10<\insc@unt
+\ifnum\count11<\insc@unt
+\ifnum\count12<\insc@unt
+\ifnum\count14<\insc@unt
+\@tempswatrue
+\fi\fi\fi\fi
+\if@tempswa
+\allocationnumber\insc@unt
+\else
+\global\advance\insc@unt\@ne
+\extrafloats\@ne
+\@next\@currbox\@freelist
+ {%
+\ifnum\@currbox<\e@insert@top
+\allocationnumber\@currbox
+\else
+\ch@ck0\m@ne\insert
+  \fi
+}%
+ {\ch@ck0\m@ne\insert}%
+\fi
+\global\chardef#1\allocationnumber
+\wlog{\string#1=\string\insert\the\allocationnumber}%
+}
+
+\begin{algorithmic}[1]
+ \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
+  \State $r\gets a\bmod b$
+  \While{$r\not=0$}\Comment{We have the answer if r is 0 and what
+   about a large comment}
+   \State $a\gets b$
+\State $b\gets r$
+ \State $r\gets a\bmod b$
+ \EndWhile\label{euclidendwhile}
+ \State \textbf{return} $b$\Comment{The gcd is b}
+ \State
+\Statex
+ \EndProcedure
+\end{algorithmic}
+
+\begin{algorithmic}[1]
+\State $sum\gets 0$
+\For{$i\gets 1, n$}
+\State $sum\gets sum+i$
+\EndFor
+\end{algorithmic}
+
+\begin{algorithmic}[1]
+\State $sum\gets 0$
+\State $i\gets 1$
+\While{$i\le n$}
+\State $sum\gets sum+i$
+ \State $i\gets i+1$
+           \EndWhile
+\end{algorithmic}
+
+\begin{algorithmic}[1]
+ \If{$quality\ge 9$}
+ \State $a\gets perfect$
+ \ElsIf{$quality\ge 7$}
+ \State $a\gets good$
+ \ElsIf{$quality\ge 5$}
+ \State $a\gets medium$
+ \ElsIf{$quality\ge 3$}
+             \State $a\gets bad$
+  \Else
+                 \State $a\gets unusable$
+  \EndIf
+\end{algorithmic}
+
+\begin{algorithmic}[1]
+            \Require $x\ge5$
+\Ensure $x\le-5$
+             \Statex
+\While{$x>-5$}
+                  \State $x\gets x-1$
+                                \EndWhile
+\end{algorithmic}
+
+\end{document}
+
+%%% Local Variables:
+%%% mode: latex
+%%% TeX-master: t
+%%% End:
diff --git a/tests/latex/conditionals-indent-out.tex 
b/tests/latex/conditionals-indent-out.tex
new file mode 100644
index 0000000000..b99319ebd6
--- /dev/null
+++ b/tests/latex/conditionals-indent-out.tex
@@ -0,0 +1,158 @@
+\documentclass{article}
+
+\usepackage{algpseudocode}
+\usepackage[%
+  key = val , %
+  key = val , %
+]{package}
+
+\begin{document}
+
+\newif\ifluatex
+\ifluatex
+  luatex specific code
+\else
+  code for other engines
+\fi
+
+\def\IfFileExists#1#2#3{%
+  \openin\@inputcheck#1 %
+  \ifeof\@inputcheck
+    #3\relax
+  \else
+    \read\@inputcheck to \reserved@a
+    \ifx\reserved@a\today
+      \typeout{#1 found}#2\relax
+    \else
+      \typeout{BAD: old file \reserved@a (should be \today)}%
+      #3\relax
+    \fi
+  \fi
+  \closein\@inputcheck}
+
+\def\filename@simple#1.#2\\{%
+  \ifx\\#2\\%
+    \let\filename@ext\relax
+    \edef\filename@base{#1}%
+  \else
+    \filename@dots{#1}#2\\%
+  \fi}
+
+\ifx\directlua\@undefined
+  \def\newwrite {\e@alloc\write
+    \chardef{\count17}
+    \m@ne\sixt@@n}
+\else
+  \def\newwrite {\e@alloc\write {%
+      \ifnum\allocationnumber=18
+        \advance\count17\@ne
+        \allocationnumber\count17 %
+      \fi
+      \global\chardef
+    }%
+    {\count17}%
+    \m@ne
+    {128}}
+\fi
+
+\gdef\e@ch@ck#1#2#3#4{%
+  \ifnum#1<#2\else
+    \ifnum#1=#2\relax
+      \global#1\@cclvi
+      \ifx\count#4\global\advance#1 10 \fi
+    \fi
+    \ifnum#1<#3\relax
+    \else
+      \errmessage{No room for a new \string#4}%
+    \fi
+  \fi
+}%
+
+\def\newinsert#1{%
+  \@tempswafalse
+  \global\advance\insc@unt\m@ne
+  \ifnum\count10<\insc@unt
+    \ifnum\count11<\insc@unt
+      \ifnum\count12<\insc@unt
+        \ifnum\count14<\insc@unt
+          \@tempswatrue
+        \fi\fi\fi\fi
+  \if@tempswa
+    \allocationnumber\insc@unt
+  \else
+    \global\advance\insc@unt\@ne
+    \extrafloats\@ne
+    \@next\@currbox\@freelist
+    {%
+      \ifnum\@currbox<\e@insert@top
+        \allocationnumber\@currbox
+      \else
+        \ch@ck0\m@ne\insert
+      \fi
+    }%
+    {\ch@ck0\m@ne\insert}%
+  \fi
+  \global\chardef#1\allocationnumber
+  \wlog{\string#1=\string\insert\the\allocationnumber}%
+}
+
+\begin{algorithmic}[1]
+  \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
+    \State $r\gets a\bmod b$
+    \While{$r\not=0$}\Comment{We have the answer if r is 0 and what
+        about a large comment}
+      \State $a\gets b$
+      \State $b\gets r$
+      \State $r\gets a\bmod b$
+    \EndWhile\label{euclidendwhile}
+    \State \textbf{return} $b$\Comment{The gcd is b}
+    \State
+    \Statex
+  \EndProcedure
+\end{algorithmic}
+
+\begin{algorithmic}[1]
+  \State $sum\gets 0$
+  \For{$i\gets 1, n$}
+    \State $sum\gets sum+i$
+  \EndFor
+\end{algorithmic}
+
+\begin{algorithmic}[1]
+  \State $sum\gets 0$
+  \State $i\gets 1$
+  \While{$i\le n$}
+    \State $sum\gets sum+i$
+    \State $i\gets i+1$
+  \EndWhile
+\end{algorithmic}
+
+\begin{algorithmic}[1]
+  \If{$quality\ge 9$}
+    \State $a\gets perfect$
+  \ElsIf{$quality\ge 7$}
+    \State $a\gets good$
+  \ElsIf{$quality\ge 5$}
+    \State $a\gets medium$
+  \ElsIf{$quality\ge 3$}
+    \State $a\gets bad$
+  \Else
+    \State $a\gets unusable$
+  \EndIf
+\end{algorithmic}
+
+\begin{algorithmic}[1]
+  \Require $x\ge5$
+  \Ensure $x\le-5$
+  \Statex
+  \While{$x>-5$}
+    \State $x\gets x-1$
+  \EndWhile
+\end{algorithmic}
+
+\end{document}
+
+%%% Local Variables:
+%%% mode: latex
+%%% TeX-master: t
+%%% End:
diff --git a/tests/latex/font-latex-test.el b/tests/latex/font-latex-test.el
index 9cc7ac527f..0c81392add 100644
--- a/tests/latex/font-latex-test.el
+++ b/tests/latex/font-latex-test.el
@@ -27,6 +27,12 @@
 (defvar font-lock-beg)
 (defvar font-lock-end)
 
+;; We need to ensure that font-lock has put the syntax properties
+;; already which won't happen in batch mode.  So trigger font-lock
+;; immediately.
+(define-advice LaTeX-common-initialization (:after ())
+  (font-lock-ensure))
+
 (ert-deftest font-latex-three-dollars ()
   "Test three consecutive dollar is ignored."
   ;; When the function `font-latex-match-dollar-math' encounters three
diff --git a/tests/latex/latex-test.el b/tests/latex/latex-test.el
index aff0adcc60..d10b98a6e1 100644
--- a/tests/latex/latex-test.el
+++ b/tests/latex/latex-test.el
@@ -1,6 +1,6 @@
 ;;; latex-test.el --- tests for LaTeX mode  -*- lexical-binding: t; -*-
 
-;; Copyright (C) 2014-2021  Free Software Foundation, Inc.
+;; Copyright (C) 2014-2022  Free Software Foundation, Inc.
 
 ;; This file is part of AUCTeX.
 
@@ -24,6 +24,12 @@
 (require 'ert)
 (require 'latex)
 
+;; We need to ensure that font-lock has put the syntax properties
+;; already which won't happen in batch mode.  So trigger font-lock
+;; immediately.
+(define-advice LaTeX-common-initialization (:after ())
+  (font-lock-ensure))
+
 (AUCTeX-set-ert-path
  'LaTeX-indent-tabular-test/in
  "tabular-in.tex"
@@ -44,7 +50,11 @@
  'tabular-count-ampersands/in
  "tabular-count-ampersands-in.tex"
  'tabular-count-ampersands/out
- "tabular-count-ampersands-out.tex")
+ "tabular-count-ampersands-out.tex"
+ 'LaTeX-conditionals-indent/in
+ "conditionals-indent-in.tex"
+ 'LaTeX-conditionals-indent/out
+ "conditionals-indent-out.tex")
 
 ;; Test for detecting \& in a table cell added; see
 ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=26010
@@ -642,4 +652,24 @@ ghi"))
       (or orig-mode
           (electric-pair-mode -1)))))
 
+(ert-deftest LaTeX-conditionals-indent ()
+  "Test if conditionals are indented correctly.
+The code inside the test is randomely taken from source2e.  This
+test also sets the variables `TeX-indent-open-delimiters' and
+`TeX-indent-close-delimiters' to opening and closing brackets to
+check the indentation for optional argument of \\usepackage."
+  (should (string=
+           (with-temp-buffer
+             (insert-file-contents LaTeX-conditionals-indent/in)
+             (LaTeX-mode)
+             (let ((TeX-indent-open-delimiters "[")
+                   (TeX-indent-close-delimiters "]")
+                   (TeX-parse-self t))
+               (TeX-update-style t)
+               (indent-region (point-min) (point-max))
+               (buffer-string)))
+           (with-temp-buffer
+             (insert-file-contents LaTeX-conditionals-indent/out)
+             (buffer-string)))))
+
 ;;; latex-test.el ends here
diff --git a/tests/latex/tabular-in.tex b/tests/latex/tabular-in.tex
index faaf4057d1..4bb20156f4 100644
--- a/tests/latex/tabular-in.tex
+++ b/tests/latex/tabular-in.tex
@@ -53,6 +53,29 @@ detraxit          & no.        & Ne sea doming   & deserunt.
 \end{aligned}
 \end{equation}
 
+% Another example given by Uwe Brauer <oub@mat.ucm.es>.
+% (https://lists.gnu.org/r/auctex-devel/2022-02/msg00039.html)
+\begin{align}
+A
+& =
+\begin{bmatrix}
+a & b \\
+c & d
+\end{bmatrix}
+,\qquad
+B =
+\begin{bmatrix}
+1 \\
+0
+\end{bmatrix}
+, \\
+C & =
+\begin{bmatrix}
+b_{1} & b_{2}
+\end{bmatrix}
+,\qquad D = 0.
+\end{align}
+
 % Next table tests filling with a control symbol \& inside a cell; the
 % function `LaTeX-indent-tabular' now (March 2017) detects \&, see:
 % https://debbugs.gnu.org/cgi/bugreport.cgi?bug=26010
diff --git a/tests/latex/tabular-out.tex b/tests/latex/tabular-out.tex
index 9e4cec1a72..66de0641fa 100644
--- a/tests/latex/tabular-out.tex
+++ b/tests/latex/tabular-out.tex
@@ -53,6 +53,29 @@
   \end{aligned}
 \end{equation}
 
+% Another example given by Uwe Brauer <oub@mat.ucm.es>.
+% (https://lists.gnu.org/r/auctex-devel/2022-02/msg00039.html)
+\begin{align}
+  A
+  & =
+    \begin{bmatrix}
+      a & b \\
+      c & d
+    \end{bmatrix}
+    ,\qquad
+    B =
+    \begin{bmatrix}
+      1 \\
+      0
+    \end{bmatrix}
+    , \\
+  C & =
+      \begin{bmatrix}
+        b_{1} & b_{2}
+      \end{bmatrix}
+      ,\qquad D = 0.
+\end{align}
+
 % Next table tests filling with a control symbol \& inside a cell; the
 % function `LaTeX-indent-tabular' now (March 2017) detects \&, see:
 % https://debbugs.gnu.org/cgi/bugreport.cgi?bug=26010
diff --git a/tests/tex/command-expansion.el b/tests/tex/command-expansion.el
index 5407867175..9834487fa4 100644
--- a/tests/tex/command-expansion.el
+++ b/tests/tex/command-expansion.el
@@ -22,7 +22,7 @@
 ;;; Code:
 
 (require 'ert)
-(require 'tex-buf)
+(require 'latex)
 
 (ert-deftest TeX-command-expansion ()
   "Check whether \"%%%%\" is correctly expanded when before \"%`\"."
diff --git a/tests/tex/error-parsing.el b/tests/tex/error-parsing.el
index 6cde540a05..0bca37d798 100644
--- a/tests/tex/error-parsing.el
+++ b/tests/tex/error-parsing.el
@@ -22,7 +22,6 @@
 ;;; Code:
 
 (require 'ert)
-(require 'tex-buf)
 
 (AUCTeX-set-ert-path
  'TeX-test-compilation-log
diff --git a/tex-bar.el b/tex-bar.el
index 0bfd43169e..a9863f8893 100644
--- a/tex-bar.el
+++ b/tex-bar.el
@@ -1,6 +1,6 @@
 ;;; tex-bar.el --- toolbar icons on AUCTeX in GNU emacs.  -*- lexical-binding: 
t; -*-
 
-;; Copyright (C) 2004-2021  Free Software Foundation, Inc.
+;; Copyright (C) 2004-2022  Free Software Foundation, Inc.
 
 ;; This program is free software; you can redistribute it and/or
 ;; modify it under the terms of the GNU General Public License as
@@ -62,8 +62,7 @@
 
 (require 'toolbar-x)
 
-;; for error handling
-(require 'tex-buf)
+(require 'tex)
 
 ;; For the symbol toolbar
 (require 'latex)
diff --git a/tex-buf.el b/tex-buf.el
deleted file mode 100644
index eeff2fc06c..0000000000
--- a/tex-buf.el
+++ /dev/null
@@ -1,3510 +0,0 @@
-;;; tex-buf.el --- External commands for AUCTeX.  -*- lexical-binding: t; -*-
-
-;; Copyright (C) 1991-2021  Free Software Foundation, Inc.
-
-;; Maintainer: auctex-devel@gnu.org
-;; Keywords: tex, wp
-
-;; This file is part of AUCTeX.
-
-;; AUCTeX is free software; you can redistribute it and/or modify it
-;; under the terms of the GNU General Public License as published by
-;; the Free Software Foundation; either version 3, or (at your option)
-;; any later version.
-
-;; AUCTeX is distributed in the hope that it will be useful, but
-;; WITHOUT ANY WARRANTY; without even the implied warranty of
-;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-;; General Public License for more details.
-
-;; You should have received a copy of the GNU General Public License
-;; along with AUCTeX; see the file COPYING.  If not, write to the Free
-;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-;; 02110-1301, USA.
-
-;;; Commentary:
-
-;; This file provides support for external commands.
-
-;;; Code:
-
-(require 'tex)
-(require 'latex)
-(require 'comint)
-
-;;; Customization:
-
-(defcustom TeX-process-asynchronous (not (eq system-type 'ms-dos))
-  "Use asynchronous processes."
-  :group 'TeX-command
-  :type 'boolean)
-
-(defcustom TeX-shell
-  (if (memq system-type '(ms-dos emx windows-nt))
-      shell-file-name
-    "/bin/sh")
-  "Name of shell used to parse TeX commands."
-  :group 'TeX-command
-  :type 'file)
-
-(defcustom TeX-shell-command-option
-  (cond ((memq system-type '(ms-dos emx windows-nt))
-         shell-command-switch)
-        (t                              ;Unix & EMX (Emacs 19 port to OS/2)
-         "-c"))
-  "Shell argument indicating that next argument is the command."
-  :group 'TeX-command
-  :type 'string)
-
-;;; Interactive Commands
-;;
-;; The general idea is, that there is one process and process buffer
-;; associated with each master file, and one process and process buffer
-;; for running TeX on a region.   Thus, if you have N master files, you
-;; can run N + 1 processes simultaneously.
-;;
-;; Some user commands operates on ``the'' process.  The following
-;; algorithm determine what ``the'' process is.
-;;
-;; IF   last process started was on a region
-;; THEN ``the'' process is the region process
-;; ELSE ``the'' process is the master file (of the current buffer) process
-
-(defun TeX-save-document (name-or-file-fn)
-  "Save all files belonging to the current document.
-Return non-nil if document needs to be re-TeX'ed.
-In Lisp program, NAME-OR-FILE-FN specifies the current document.
-It is either the master name without extension or the function
-`TeX-master-file'."
-  (interactive (list #'TeX-master-file))
-  (TeX-check-files (TeX--concat-ext name-or-file-fn (TeX-output-extension))
-                   (cons (TeX--concat-ext name-or-file-fn) (TeX-style-list))
-                   TeX-file-extensions))
-
-(defun TeX--concat-ext (name-or-file-fn &optional extension)
-  "Append EXTENSION to a filename specified by NAME-OR-FILE-FN.
-
-If NAME-OR-FILE-FN is a string, interpret it as the filename.
-Otherwise, assume it is a callable function and call it with
-EXTENSION as an argument and return the result without
-modification.  EXTENSION is a string which should not start with
-'.'."
-  (if (stringp name-or-file-fn)
-      (if extension
-          (concat name-or-file-fn "." extension)
-        name-or-file-fn)
-    (funcall name-or-file-fn extension)))
-
-(defun TeX-command-master (&optional override-confirm)
-  "Run command on the current document.
-
-If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
-depend on it being positive instead of the entry in `TeX-command-list'."
-  (interactive "P")
-  (TeX-master-file nil nil t)  ;; call to ask if necessary
-  (TeX-command (TeX-command-query #'TeX-master-file)
-               #'TeX-master-file override-confirm))
-
-(defcustom TeX-region-extra ""
-  "String to insert in the region file between the header and the text."
-  :group 'TeX-command
-  :type 'string)
-
-;; This was "{\\makeatletter\\gdef\\AucTeX@cite#1[#2]#3{[#3#1#2]}\
-;;           \\gdef\\cite{\\@ifnextchar[{\\AucTeX@cite{, }}\
-;;           {\\AucTeX@cite{}[]}}}\n"
-;; However, that string is inappropriate for plain TeX and ConTeXt.
-;; This needs reconsideration.
-
-(defvar TeX-command-region-begin nil)
-(defvar TeX-command-region-end nil)
-;; Used for marking the last region.
-
-(make-variable-buffer-local 'TeX-command-region-begin)
-(make-variable-buffer-local 'TeX-command-region-end)
-
-(defun TeX-current-offset (&optional pos)
-  "Calculate line offset of POS, or of point if POS is nil."
-  (save-restriction
-    (widen)
-    (save-excursion
-      (let ((inhibit-point-motion-hooks t)
-            (inhibit-field-text-motion t))
-        (if pos (goto-char pos))
-        (+ (count-lines (point-min) (point))
-           (if (bolp) 0 -1))))))
-
-(defun TeX-pin-region (begin end)
-  "Pin the TeX region specified by BEGIN and END.
-If BEGIN is nil, the region is unpinned.
-
-In interactive use, a positive prefix arg will pin the region,
-a non-positive one will unpin it.  Without a prefix arg, if
-a region is actively marked, it will get pinned.  If not, a
-pinned region will get unpinned and vice versa."
-  (interactive
-   (if
-       (if current-prefix-arg
-           (> (prefix-numeric-value current-prefix-arg) 0)
-         (or (TeX-active-mark)
-             (null TeX-command-region-begin)))
-       (list (region-beginning) (region-end))
-     '(nil nil)))
-  (if begin
-      (progn
-        (unless (markerp TeX-command-region-begin)
-          (setq TeX-command-region-begin (make-marker))
-          (setq TeX-command-region-end (make-marker)))
-        (set-marker TeX-command-region-begin begin)
-        (set-marker TeX-command-region-end end)
-        (message "TeX region pinned."))
-    (when (markerp TeX-command-region-begin)
-      (set-marker TeX-command-region-begin nil)
-      (set-marker TeX-command-region-end nil))
-    (setq TeX-command-region-begin nil)
-    (setq TeX-command-region-end nil)
-    (message "TeX region unpinned.")))
-
-(defun TeX-region-update ()
-  "Update the TeX-region file."
-  ;; Note that TeX-command-region-begin is not a marker when called
-  ;; from TeX-command-buffer.
-  (and (or (null TeX-command-region-begin)
-           (markerp TeX-command-region-begin))
-       (TeX-active-mark)
-       (TeX-pin-region (region-beginning) (region-end)))
-  (let* ((begin (or TeX-command-region-begin (region-beginning)))
-         (end (or TeX-command-region-end (region-end)))
-         (TeX-region-extra
-          ;; Write out counter information to region.
-          (concat (and (fboundp 'preview--counter-information)
-                       (preview--counter-information begin))
-                  TeX-region-extra)))
-    (TeX-region-create (TeX-region-file TeX-default-extension)
-                       (buffer-substring-no-properties begin end)
-                       (file-name-nondirectory (buffer-file-name))
-                       (TeX-current-offset begin))))
-
-(defun TeX-command-region (&optional override-confirm)
-  "Run TeX on the current region.
-
-Query the user for a command to run on the temporary file specified by
-the variable `TeX-region'.  If there is an explicitly active region,
-it is stored for later commands.  If not, a previously stored region
-\(can be also be set with `TeX-pin-region') overrides the current region,
-if present.
-
-If a prefix argument OVERRIDE-CONFIRM is given, prompting will
-ignore the prompting flag from `TeX-command-list' and instead
-will prompt only if the prefix is positive.
-
-If the master file for the document has a header, it is written to the
-temporary file before the region itself.  The document's header is all
-text before `TeX-header-end'.
-
-If the master file for the document has a trailer, it is written to
-the temporary file after the region itself.  The document's trailer is
-all text after `TeX-trailer-start'."
-  (interactive "P")
-  (TeX-region-update)
-  ;; In the next line, `TeX-region-file' should be called with nil
-  ;; `nondirectory' argument, otherwise `TeX-command-default' called
-  ;; within `TeX-command-query' won't work in included files not
-  ;; placed in `TeX-master-directory'.
-  (TeX-command (TeX-command-query #'TeX-region-file) #'TeX-region-file
-               override-confirm))
-
-(defun TeX-command-buffer (&optional override-confirm)
-  "Run TeX on the current buffer.
-
-Query the user for a command to run on the temporary file specified by
-the variable `TeX-region'.  The region file will be recreated from the
-visible part of the buffer.
-
-If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
-depend on it being positive instead of the entry in `TeX-command-list'."
-  (interactive "P")
-  (let ((TeX-command-region-begin (point-min))
-        (TeX-command-region-end (point-max)))
-    (TeX-command-region override-confirm)))
-
-(defcustom TeX-record-buffer nil
-  "Whether to record buffer names of generated TeX buffers.
-When non-nil, these buffers are put at the front of the list of
-recently selected ones."
-  :group 'TeX-command
-  :type 'boolean)
-
-(defun TeX-pop-to-buffer (buffer &optional other-window norecord)
-  "Compatibility wrapper for `pop-to-buffer'.
-
-Select buffer BUFFER in some window, preferably a different one.
-BUFFER may be a buffer, a string (a buffer name), or nil.
-If BUFFER is a string which is not the name of an existing buffer,
-then this function creates a buffer with that name.
-If BUFFER is nil, then it chooses some other buffer.
-If `pop-up-windows' is non-nil, windows can be split to do this.
-If optional second arg OTHER-WINDOW is non-nil, insist on finding another
-window even if BUFFER is already visible in the selected window,
-and ignore `same-window-regexps' and `same-window-buffer-names'.
-This function returns the buffer it switched to.
-This uses the function `display-buffer' as a subroutine; see the documentation
-of `display-buffer' for additional customization information.
-
-Optional third arg NORECORD non-nil means do not put this buffer
-at the front of the list of recently selected ones."
-  (pop-to-buffer buffer other-window (and norecord (not TeX-record-buffer))))
-
-(defun TeX-recenter-output-buffer (line)
-  "Redisplay buffer of TeX job output so that most recent output can be seen.
-The last line of the buffer is displayed on line LINE of the window, or
-at bottom if LINE is nil."
-  (interactive "P")
-  (let ((buffer (TeX-active-buffer)))
-    (if buffer
-        (let ((old-buffer (current-buffer)))
-          (TeX-pop-to-buffer buffer t t)
-          (bury-buffer buffer)
-          (goto-char (point-max))
-          (recenter (if line
-                        (prefix-numeric-value line)
-                      (/ (window-height) 2)))
-          (TeX-pop-to-buffer old-buffer nil t))
-      (message "No process for this document."))))
-
-(defun TeX-kill-job ()
-  "Kill the currently running TeX job."
-  (interactive)
-  (let ((process (TeX-active-process)))
-    (if process
-        (kill-process process)
-      ;; Should test for TeX background process here.
-      (error "No TeX process to kill"))))
-
-;; FIXME: The vars below are defined in this file, but they're defined too
-;; far down (i.e. further down than their first use), so we have to pre-declare
-;; them here to explain it to the compiler.
-;; We should move those vars's definitions earlier instead!
-(defvar TeX-current-process-region-p)
-(defvar TeX-save-query)
-(defvar TeX-parse-function)
-(defvar TeX-sentinel-function)
-(defvar TeX-sentinel-default-function)
-(defvar compilation-in-progress)
-(defvar TeX-current-page)
-(defvar TeX-error-overview-open-after-TeX-run)
-(defvar TeX-error-list)
-(defvar TeX-command-buffer)
-(defvar TeX-region)
-
-(defun TeX-home-buffer ()
-  "Go to the buffer where you last issued a TeX command.
-If there is no such buffer, or you already are in that buffer, find
-the master file."
-  (interactive)
-  (if (or (null TeX-command-buffer)
-          (null (buffer-name TeX-command-buffer))
-          (eq TeX-command-buffer (current-buffer)))
-      (find-file (TeX-master-file TeX-default-extension))
-    (switch-to-buffer TeX-command-buffer)))
-
-(defvar TeX-error-last-visited -1
-  "Index of the last visited error listed in `TeX-error-list'.
-
-This variable is intended to be set only in output buffer so it
-will be shared among all files of the same document.")
-(make-variable-buffer-local 'TeX-error-last-visited)
-
-(defun TeX-get-parse-function ()
-  "Get the parse function for the current buffer."
-  (with-current-buffer TeX-command-buffer
-    (TeX-process-get-variable (TeX-active-master) 'TeX-parse-function)))
-
-(defun TeX-next-error (&optional arg reparse)
-  "Find the next error in the TeX output buffer.
-
-A prefix ARG specifies how many error messages to move;
-negative means move back to previous error messages, if possible.
-
-If REPARSE is non-nil, reparse the error message buffer.
-
-\\[universal-argument] as a prefix means reparse the error
-message buffer and start at the first error."
-  (interactive "P")
-  (if (or (null (TeX-active-buffer))
-          (eq 'compilation-mode (with-current-buffer TeX-command-buffer
-                                  major-mode)))
-      (next-error arg reparse)
-
-    ;; Force reparsing when the function is called with a universal-argument.
-    (if (consp arg) (setq reparse t arg nil))
-
-    (funcall (TeX-get-parse-function) arg reparse)))
-
-(defun TeX-previous-error (arg)
-  "Find the previous error in the TeX output buffer.
-
-Prefix arg N says how many error messages to move backward (or
-forward, if negative).
-
-This works only with TeX commands and if the
-`TeX-parse-all-errors' variable is non-nil."
-  (interactive "p")
-  (if (or (null (TeX-active-buffer))
-          (eq 'compilation-mode (with-current-buffer TeX-command-buffer
-                                  major-mode)))
-      (previous-error arg)
-
-    (let ((parse-function (TeX-get-parse-function)))
-      (if (and TeX-parse-all-errors (equal parse-function #'TeX-parse-TeX))
-          ;; When `TeX-parse-all-errors' is non-nil and the parsing function is
-          ;; `TeX-parse-TeX' we can move backward in the errors.
-          (TeX-parse-TeX (- arg) nil)
-        ;; XXX: moving backward in the errors hasn't yet been implemented for
-        ;; other parsing functions.
-        (error "Jumping to previous error not supported")))))
-
-;;; Command Query
-
-(defvar TeX-error-overview-frame nil
-  "The frame of the error overview.")
-
-(defconst TeX-error-overview-buffer-name "*TeX errors*"
-  "Name of the buffer in which to show error list.")
-
-(defvar LaTeX-idx-md5-alist nil
-  "Alist of MD5 hashes of idx file.
-
-Car is the idx file, cdr is its md5 hash.")
-
-(defvar LaTeX-idx-changed-alist nil
-  "Whether the idx files changed.
-
-Car is the idx file, cdr is whether idx changed after LaTeX
-run.")
-
-(defcustom TeX-check-engine t
-  "Check the correct engine has been set before running TeX commands."
-  :group 'TeX-command
-  :type 'boolean)
-
-(defvar TeX-check-engine-list '(default luatex omega xetex)
-  "List of engines required by the loaded TeX packages.
-
-Do not set this variable directly, use
-`TeX-check-engine-add-engines' to specify required engines.")
-(make-variable-buffer-local 'TeX-check-engine-list)
-
-(defun TeX-check-engine-add-engines (&rest engines)
-  "Add ENGINES to list of required engines.
-
-Set `TeX-check-engine-list' to the intersection between the list
-itself and the list of provided engines.
-
-See for example style/fontspec.el"
-  (let ((list TeX-check-engine-list)
-        (res nil))
-    (setq TeX-check-engine-list
-          ;; The following is based on the definition of `cl-intersection' of
-          ;; GNU Emacs.
-          (and list engines
-               (if (equal list engines) list
-                 (or (>= (length list) (length engines))
-                     (setq list (prog1 engines (setq engines list))))
-                 (while engines
-                   (if (memq (car engines) list)
-                       (push (car engines) res))
-                   (pop engines))
-                 res)))))
-
-(defun TeX-check-engine (name)
-  "Check the correct engine has been set.
-
-Look into `TeX-check-engine-list' for the required engines.
-
-NAME is the command to be run.  Actually do the check only if the
-variable `TeX-check-engine' is non-nil and LaTeX is the command
-to be run."
-  (and
-   (string= name "LaTeX")
-   TeX-check-engine
-   TeX-check-engine-list
-   (null (memq TeX-engine TeX-check-engine-list))
-   (memq TeX-engine '(default luatex omega xetex))
-   ;; The set engine is not listed in `TeX-check-engine-list'.  We check only
-   ;; builtin engines because we can't take care of custom ones.  Do nothing if
-   ;; there is no allowed engine, we don't know what to do in that case.
-   (let ((length (length TeX-check-engine-list))
-         (name-alist '((default . "TeX")
-                       (luatex  . "LuaTeX")
-                       (omega   . "Omega")
-                       (xetex   . "XeTeX")))
-         (completion-ignore-case t)
-         (engine nil))
-     (when
-         (cond
-          ;; There is exactly one allowed engine.
-          ((= length 1)
-           (setq engine (car TeX-check-engine-list))
-           (y-or-n-p (format "%s is required to build this document.
-Do you want to use this engine? " (cdr (assoc engine name-alist)))))
-          ;; More than one engine is allowed.
-          ((> length 1)
-           (if (y-or-n-p (format "It appears %s are required to build this 
document.
-Do you want to select one of these engines? "
-                                 (mapconcat
-                                  (lambda (elt) (cdr (assoc elt name-alist)))
-                                  TeX-check-engine-list ", ")))
-               (setq engine
-                     (car (rassoc
-                           (completing-read
-                            (format
-                             "Choose between %s: "
-                             (mapconcat
-                              (lambda (elt) (cdr (assoc elt name-alist)))
-                              TeX-check-engine-list ", "))
-                            (mapcar
-                             (lambda (elt) (cdr (assoc elt name-alist)))
-                             TeX-check-engine-list))
-                           name-alist)))
-             ;; Don't keep asking.  If user doesn't want to change engine,
-             ;; probably has a good reason.  In order to do so, without adding
-             ;; yet another variable we just hack `TeX-check-engine-list' and
-             ;; make it nil.
-             (setq TeX-check-engine-list nil))))
-       (TeX-engine-set engine)
-       (when (y-or-n-p "Do you want to remember the choice? ")
-         (add-file-local-variable 'TeX-engine engine)
-         (save-buffer))))))
-
-(defcustom TeX-check-TeX t
-  "Whether AUCTeX should check if a working TeX distribution is present."
-  :group 'TeX-command
-  :type 'boolean)
-
-(defcustom TeX-check-TeX-command-not-found 127
-  "Numerical code returned by shell for a command not found error."
-  :group 'TeX-command
-  :type 'integer)
-
-(defun TeX-command (name file-fn &optional override-confirm)
-  "Run command NAME on the file returned by calling FILE-FN.
-
-FILE-FN is the symbol of a function returning a file name.  The
-function has one optional argument, the extension to use on the
-file.  Valid choices are `TeX-master-file' and `TeX-region-file'.
-
-Use the information in `TeX-command-list' to determine how to run
-the command.
-
-If OVERRIDE-CONFIRM is a prefix argument, confirmation will be
-asked if it is positive, and suppressed if it is not.
-
-Run function `TeX-check-engine' to check the correct engine has
-been set."
-  (TeX-check-engine name)
-
-  ;; Make sure that `TeX-command-buffer' is set always.
-  ;; It isn't safe to remove similar lines in `TeX-run-command' etc.
-  ;; because preview-latex calls `TeX-run-command' directly.
-  (setq-default TeX-command-buffer (current-buffer))
-
-  (cond ((eq file-fn #'TeX-region-file)
-         (setq TeX-current-process-region-p t))
-        ((eq file-fn #'TeX-master-file)
-         (setq TeX-current-process-region-p nil)))
-
-  ;; When we're operating on a region, we need to update the position
-  ;; of point in the region file so that forward search works.
-  (if (string= name "View") (TeX-region-update-point))
-
-  (let ((command (TeX-command-expand (nth 1 (assoc name TeX-command-list))))
-        (hook (nth 2 (assoc name TeX-command-list)))
-        (confirm (if override-confirm
-                     (> (prefix-numeric-value override-confirm) 0)
-                   (nth 3 (assoc name TeX-command-list)))))
-
-    ;; Verify the expanded command
-    (if confirm
-        (setq command
-              (read-from-minibuffer (concat name " command: ") command
-                                    nil nil)))
-
-    ;; Kill the frame and buffer associated to the error overview before 
running
-    ;; the command, but keep them if the command to be run is View.
-    (unless (string= name "View")
-      (if (frame-live-p TeX-error-overview-frame)
-          (delete-frame TeX-error-overview-frame))
-      (if (get-buffer TeX-error-overview-buffer-name)
-          (kill-buffer TeX-error-overview-buffer-name)))
-
-    ;; Before running some commands, check that AUCTeX is able to find "tex"
-    ;; program.
-    (and TeX-check-TeX
-         (member name '("TeX" "LaTeX" "AmSTeX" "ConTeXt" "ConTeXt Full"))
-         (= TeX-check-TeX-command-not-found
-            (call-process TeX-shell nil nil nil
-                          TeX-shell-command-option TeX-command))
-         (error (format "ERROR: AUCTeX cannot find a working TeX distribution.
-Make sure you have one and that TeX binaries are in PATH environment 
variable%s"
-                        (if (eq system-type 'darwin)
-                            ".
-If you are using OS X El Capitan or later
-remember to add /Library/TeX/texbin/ to your PATH"
-                          ""))))
-
-    ;; Now start the process
-    (let ((file (funcall file-fn)))
-      (TeX-process-set-variable file 'TeX-command-next TeX-command-Show)
-      (funcall hook name command file))))
-
-(defun TeX-command-expand (command &optional list)
-  "Expand COMMAND for `TeX-active-master' as described in LIST.
-LIST default to `TeX-expand-list'.  As a special exception,
-`%%' can be used to produce a single `%' sign in the output
-without further expansion."
-  (let ((TeX-expand-command command)
-        TeX-expand-pos
-        TeX-command-text
-        TeX-command-pos
-        pat entry case-fold-search string expansion arguments)
-    (setq list (cons
-                (list "%%" (lambda nil
-                             (setq TeX-expand-pos (1+ TeX-expand-pos))
-                             "%"))
-                (or list (TeX-expand-list)))
-          pat (regexp-opt (mapcar #'car list)))
-    (while (setq TeX-expand-pos (string-match pat TeX-expand-command 
TeX-expand-pos))
-      (setq string (match-string 0 TeX-expand-command)
-            entry (assoc string list)
-            expansion (car (cdr entry)) ;Second element
-            arguments (cdr (cdr entry)) ;Remaining elements
-            string (save-match-data
-                     (cond
-                      ((functionp expansion)
-                       (apply expansion arguments))
-                      ((boundp expansion)
-                       (apply (symbol-value expansion) arguments))
-                      (t
-                       (error "Nonexpansion %s" expansion)))))
-      (if (stringp string)
-          (setq TeX-expand-command
-                (replace-match string t t TeX-expand-command))))
-    TeX-expand-command))
-
-(defun TeX-active-master-with-quotes
-    (&optional extension nondirectory ask extra preprocess-fn)
-  "Return the current master or region file name with quote for shell.
-Pass arguments EXTENSION NONDIRECTORY ASK to `TeX-active-master'.
-If the returned file name contains space, enclose it within
-quotes `\"' when \" \\input\" is supplemented (indicated by
-dynamically bound variable `TeX-command-text' having string
-value.) Also enclose the file name within \\detokenize{} when
-the following three conditions are met:
-  1. compiling with standard (pdf)LaTeX or upLaTeX
-  2. \" \\input\" is supplemented
-  3. EXTRA is non-nil (default when expanding \"%T\")
-Adjust dynamically bound variable `TeX-expand-pos' to avoid possible
-infinite loop in `TeX-command-expand'.
-If PREPROCESS-FN is non-nil then it is called with the filename
-as an argument and the result is enclosed instead of the
-filename.
-
-Helper function of `TeX-command-expand'. Use only within entries in
-`TeX-expand-list-builtin' and `TeX-expand-list'."
-  (let* ((raw (TeX-active-master extension nondirectory ask))
-         ;; String `TeX-command-text' means that the file name is
-         ;; given through \input command.
-         (quote-for-space (if (and (stringp TeX-command-text)
-                                   (string-match " " raw))
-                              "\"" ""))
-         (res
-          (shell-quote-argument
-           (format
-            (if (and extra
-                     (stringp TeX-command-text)
-                     (memq major-mode '(latex-mode doctex-mode))
-                     (memq TeX-engine '(default uptex)))
-                ;; Since TeXLive 2018, the default encoding for LaTeX
-                ;; files has been changed to UTF-8 if used with
-                ;; classic TeX or pdfTeX.  I.e.,
-                ;; \usepackage[utf8]{inputenc} is enabled by default
-                ;; in (pdf)latex.
-                ;; c.f. LaTeX News issue 28
-                ;; Due to this change, \detokenize is required to
-                ;; recognize non-ascii characters in the file name
-                ;; when \input precedes.
-                "\\detokenize{ %s }" "%s")
-            (concat quote-for-space
-                    (if preprocess-fn
-                        (funcall preprocess-fn raw)
-                      raw)
-                    quote-for-space)))))
-    ;; Advance past the file name in order to
-    ;; prevent expanding any substring of it.
-    (setq TeX-expand-pos
-          (+ TeX-expand-pos (length res)))
-    res))
-
-(defun TeX-check-files (derived originals extensions)
-  "Check if DERIVED is newer than any of the ORIGINALS.
-Try each original with each member of EXTENSIONS, in all directories
-in `TeX-check-path'.  Returns true if any of the ORIGINALS with any of the
-EXTENSIONS are newer than DERIVED.  Will prompt to save the buffer of any
-ORIGINALS which are modified but not saved yet."
-  (let (existingoriginals
-        found
-        (extensions (TeX-delete-duplicate-strings extensions))
-        (buffers (buffer-list)))
-    (dolist (path (TeX-delete-duplicate-strings
-                   (mapcar (lambda (dir)
-                             (expand-file-name (file-name-as-directory dir)))
-                           (append
-                            TeX-check-path
-                            ;; In `TeX-command-default', this function is used 
to
-                            ;; check whether bibliography databases are newer
-                            ;; than generated *.bbl files, but bibliography
-                            ;; database are relative to `TeX-master-directory'
-                            ;; and the test can be run also from included files
-                            ;; that are in directories different from
-                            ;; `TeX-master-directory'.
-                            (list (TeX-master-directory))))))
-      (dolist (orig originals)
-        (dolist (ext extensions)
-          (let ((filepath (concat path orig "." ext)))
-            (if (or (file-exists-p filepath)
-                    (get-file-buffer filepath))
-                (setq existingoriginals (cons filepath existingoriginals)))))))
-    (while buffers
-      (let* ((buffer (car buffers))
-             (name (buffer-file-name buffer)))
-        (setq buffers (cdr buffers))
-        (if (and name (member name existingoriginals))
-            (progn
-              (and (buffer-modified-p buffer)
-                   (or (not TeX-save-query)
-                       (y-or-n-p (concat "Save file "
-                                         (buffer-file-name buffer)
-                                         "? ")))
-                   (with-current-buffer buffer (save-buffer)))))))
-    (dolist (eo existingoriginals)
-      (if (file-newer-than-file-p eo derived)
-          (setq found t)))
-    found))
-
-(defcustom TeX-command-sequence-max-runs-same-command 4
-  "Maximum number of runs of the same command."
-  :type 'integer
-  :group 'TeX-command)
-
-(defcustom TeX-command-sequence-max-runs 12
-  "Maximum number of total runs."
-  :type 'integer
-  :group 'TeX-command)
-
-(defvar TeX-command-sequence-count-same-command 1
-  "Counter for the runs of the same command in `TeX-command-sequence'.")
-
-(defvar TeX-command-sequence-count 1
-  "Counter for the total runs of `TeX-command-sequence'.")
-
-(defvar TeX-command-sequence-last-command nil
-  "Last command run in `TeX-command-sequence'.")
-
-(defvar TeX-command-sequence-sentinel nil
-  "Sentinel for `TeX-command-sequence'.")
-
-(defvar TeX-command-sequence-file-function nil
-  "File function for `TeX-command-sequence'.")
-
-(defvar TeX-command-sequence-command nil
-  "Command argument for `TeX-command-sequence'.
-
-It is set in `TeX-command-sequence' and used in
-`TeX-command-sequence-sentinel' to call again
-`TeX-command-sequence' with the appropriate command argument.")
-
-(defun TeX-command-sequence (command &optional reset file-fn)
-  "Run a sequence of TeX commands defined by COMMAND.
-
-The COMMAND argument may be
-
-  * nil: no command will be run in this case
-
-  * a string with a command from `TeX-command-list'
-
-  * a non-nil list of strings, which are commands from
-    `TeX-command-list'; the car of the list is used as command to
-    be executed in the first run of `TeX-command-sequence', the
-    cdr of the list will be passed to the function in the next
-    run, etc.
-
-  * a function name, returning a string which is command from
-    `TeX-command-list'; it will be funcall'd (without arguments!)
-    and used again in the next run of `TeX-command-sequence'.
-
-  * with any other value the function `TeX-command-default' is
-    used to determine the command to run, until a stopping
-    condition is met.
-
-This function runs at most
-`TeX-command-sequence-max-runs-same-command' times the same
-command in a row, and `TeX-command-sequence-max-runs' times in
-total in any case.  It ends when `TeX-command-Show' is the
-command to be run.
-
-A non-nil value for the optional argument RESET means this is the
-first run of the function and some variables need to be reset.
-
-FILE-FN is a function of zero arguments returning the current
-filename.  Valid choices are `TeX-master-file' (default if
-omitted) and `TeX-region-file'."
-  (setq TeX-command-sequence-file-function (or file-fn #'TeX-master-file))
-  (if (null command)
-      (message "No command to run.")
-    (let (cmd process)
-      (cond
-       ((stringp command)
-        (setq cmd command
-              TeX-command-sequence-command nil))
-       ((listp command)
-        (setq cmd (pop command)
-              TeX-command-sequence-command command))
-       ((functionp command)
-        (setq cmd (funcall command)
-              TeX-command-sequence-command command))
-       (t
-        ;; We first call `TeX-master-file' with the third argument
-        ;; (`ask') set to t, so that the master file is properly set.
-        ;; This is also what `TeX-command-master' does.
-        (funcall TeX-command-sequence-file-function nil nil t)
-        (setq cmd (TeX-command-default TeX-command-sequence-file-function)
-              TeX-command-sequence-command t)))
-      (TeX-command cmd TeX-command-sequence-file-function 0)
-      (when reset
-        (setq TeX-command-sequence-count-same-command 1
-              TeX-command-sequence-count 1
-              TeX-command-sequence-last-command nil))
-      (cond
-       ;; Stop when the same command has been run
-       ;; `TeX-command-sequence-max-runs-same-command' times in a row.
-       ((>= TeX-command-sequence-count-same-command
-            TeX-command-sequence-max-runs-same-command)
-        (message "Stopping after running %S %d times in a row."
-                 TeX-command-sequence-last-command
-                 TeX-command-sequence-count-same-command))
-       ;; Stop when there have been `TeX-command-sequence-max-runs' total
-       ;; compilations.
-       ((>= TeX-command-sequence-count TeX-command-sequence-max-runs)
-        (message "Stopping after %d compilations." TeX-command-sequence-count))
-       ;; The command just run is `TeX-command-Show'.
-       ((equal command TeX-command-Show))
-       ;; In any other case continue: increase counters (when needed), update
-       ;; `TeX-command-sequence-last-command' and run the sentinel.
-       (t
-        (if (equal cmd TeX-command-sequence-last-command)
-            (setq TeX-command-sequence-count-same-command
-                  (1+ TeX-command-sequence-count-same-command))
-          (setq TeX-command-sequence-count-same-command 1))
-        (setq TeX-command-sequence-count (1+ TeX-command-sequence-count)
-              TeX-command-sequence-last-command cmd)
-        (and (setq process (get-buffer-process (current-buffer)))
-             (setq TeX-command-sequence-sentinel (process-sentinel process))
-             (set-process-sentinel process
-                                   #'TeX-command-sequence-sentinel)))))))
-
-(defcustom TeX-save-query t
-  "If non-nil, ask user for permission to save files before starting TeX."
-  :group 'TeX-command
-  :type 'boolean)
-
-(defvar TeX-command-history nil)
-
-(defun TeX-command-default (name-or-file-fn)
-  "Guess the next command to be run on NAME-OR-FILE-FN."
-  (let ((command-next nil)
-        (name (TeX--concat-ext name-or-file-fn)))
-    (cond ((if (eq name-or-file-fn #'TeX-region-file)
-               (TeX-check-files (TeX-region-file (TeX-output-extension))
-                                ;; Each original will be checked for all dirs
-                                ;; in `TeX-check-path' so this needs to be just
-                                ;; a filename without directory.
-                                (list (file-relative-name name))
-                                TeX-file-extensions)
-             (TeX-save-document name-or-file-fn))
-           TeX-command-default)
-          ((and (memq major-mode '(doctex-mode latex-mode))
-                ;; Want to know if bib file is newer than .bbl
-                ;; We don't care whether the bib files are open in emacs
-                (TeX-check-files (TeX--concat-ext name-or-file-fn "bbl")
-                                 (mapcar #'car
-                                         (LaTeX-bibliography-list))
-                                 (append BibTeX-file-extensions
-                                         TeX-Biber-file-extensions)))
-           ;; We should check for bst files here as well.
-           (if LaTeX-using-Biber TeX-command-Biber TeX-command-BibTeX))
-          ((and
-            ;; Rationale: makeindex should be run when final document is almost
-            ;; complete (see
-            ;; https://tex-talk.net/2012/09/dont-forget-to-run-makeindex/),
-            ;; otherwise, after following latex runs, index pages may change 
due
-            ;; to changes in final document, resulting in extra makeindex and
-            ;; latex runs.
-            (member
-             (setq command-next
-                   (TeX-process-get-variable
-                    name
-                    'TeX-command-next
-                    (or (and TeX-PDF-mode (TeX-PDF-from-DVI))
-                        TeX-command-Show)))
-             (list "Dvips" "Dvipdfmx" TeX-command-Show))
-            (cdr (assoc (expand-file-name (TeX--concat-ext name-or-file-fn 
"idx"))
-                        LaTeX-idx-changed-alist)))
-           "Index")
-          (command-next)
-          (TeX-command-Show))))
-
-(defun TeX-command-query (name-or-file-fn)
-  "Query the user for what TeX command to use."
-  (let* ((default (TeX-command-default name-or-file-fn))
-         (completion-ignore-case t)
-         (answer (or TeX-command-force
-                     (completing-read
-                      (concat "Command (default " default "): ")
-                      (TeX-mode-specific-command-list major-mode) nil t
-                      nil 'TeX-command-history default))))
-    ;; If the answer is "latex" it will not be expanded to "LaTeX"
-    (setq answer (car-safe (assoc-string answer TeX-command-list t)))
-    (if (and answer
-             (not (string-equal answer "")))
-        answer
-      default)))
-
-(defvar TeX-command-next nil
-  "The default command next time `TeX-command' is invoked.")
-
- (make-variable-buffer-local 'TeX-command-next)
-
-(defun TeX-printer-query (&optional queue)
-  "Query the user for a printer name.
-QUEUE is non-nil when we are checking for the printer queue."
-  (let (command element printer)
-    (if queue
-        (unless (setq element 2 command TeX-queue-command)
-          (error "Need to customize `TeX-queue-command'"))
-      (unless (setq element 1 command TeX-print-command)
-          (error "Need to customize `TeX-print-command'")))
-    (while (progn
-             (setq printer (if TeX-printer-list
-                               (let ((completion-ignore-case t))
-                                 (completing-read
-                                  (format "Printer%s: "
-                                          (if TeX-printer-default
-                                              (format " (default %s)" 
TeX-printer-default) ""))
-                                  TeX-printer-list))
-                             ""))
-             (setq printer (or (car-safe (assoc-string printer 
TeX-printer-list t))
-                               printer))
-             (not (if (or (null printer) (string-equal "" printer))
-                      (setq printer TeX-printer-default)
-                    (setq TeX-printer-default printer)))))
-
-    (let ((expansion (let ((entry (assoc printer TeX-printer-list)))
-                       (or (nth element entry)
-                           command))))
-      (if (string-match "%p" printer)
-          (error "Don't use %s in printer names" "%p"))
-      (while (string-match "%p" expansion)
-        (setq expansion (replace-match printer t t expansion 0)))
-      expansion)))
-
-(defun TeX-style-check (styles)
-  "Check STYLES compared to the current style options."
-  (let ((files (TeX-style-list)))
-    (while (and styles
-                (not (TeX-member (car (car styles)) files #'string-match)))
-      (setq styles (cdr styles))))
-  (if styles
-      (nth 1 (car styles))
-    ""))
-
-(defun TeX-output-extension ()
-  "Get the extension of the current TeX output file."
-  (if (listp TeX-output-extension)
-      (car TeX-output-extension)
-    (or (TeX-process-get-variable (TeX-active-master)
-                                  'TeX-output-extension
-                                  TeX-output-extension)
-        TeX-output-extension)))
-
-(defun TeX-view-mouse (event)
-  "Start `TeX-view' at mouse position."
-  (interactive "e")
-  (with-current-buffer (window-buffer (posn-window (event-start event)))
-    (goto-char (posn-point (event-start event)))
-    (TeX-view)))
-
-(defun TeX-region-update-point ()
-  "Syncs the location of point in the region file with the current file.
-
-Thereafter, point in the region file is on the same text as in
-the current buffer.
-
-Do nothing in case the last command hasn't operated on the region
-or `TeX-source-correlate-mode' is disabled."
-  (when (and TeX-current-process-region-p TeX-source-correlate-mode)
-    (let ((region-buf (get-file-buffer (TeX-region-file t)))
-          (orig-line (TeX-current-offset))
-          (pos-in-line (- (point) (max (line-beginning-position)
-                                       (or TeX-command-region-begin
-                                           (region-beginning))))))
-      (when region-buf
-        (with-current-buffer region-buf
-          (goto-char (point-min))
-          (when (re-search-forward "!offset(\\(-?[0-9]+\\)" nil t)
-            (let ((offset (string-to-number (match-string 1))))
-              (goto-char (point-min))
-              (forward-line (- orig-line offset))
-              (forward-char pos-in-line))))))))
-
-(defun TeX-view ()
-  "Start a viewer without confirmation.
-The viewer is started either on region or master file,
-depending on the last command issued."
-  (interactive)
-  (let ((output-file (TeX-active-master (TeX-output-extension))))
-    (if (file-exists-p output-file)
-        (TeX-command "View" #'TeX-active-master 0)
-      (message "Output file %S does not exist." output-file))))
-
-;;; Command Hooks
-
-(defvar TeX-after-compilation-finished-functions nil
-  "Hook being run after TeX/LaTeX/ConTeXt finished successfully.
-The functions in this hook are run with the DVI/PDF output file
-given as argument.  Using this hook can be useful for updating
-the viewer automatically after re-compilation of the document.
-
-If you use an emacs-internal viewer such as `doc-view-mode' or
-`pdf-view-mode', add `TeX-revert-document-buffer' to this hook.")
-
-(make-obsolete-variable 'TeX-after-TeX-LaTeX-command-finished-hook
-                        'TeX-after-compilation-finished-functions
-                        "11.89")
-
-(defun TeX-revert-document-buffer (file)
-  "Revert the buffer visiting FILE.
-This function is intended to be used in
-`TeX-after-compilation-finished-functions' for users that view
-their compiled document with an emacs viewer such as
-`doc-view-mode' or `pdf-view-mode'.  (Note that this function
-just calls `revert-buffer' in the respective buffer and thus
-requires that the corresponding mode defines a sensible
-`revert-buffer-function'.)"
-  (let ((buf (find-buffer-visiting file)))
-    (when buf
-      (with-current-buffer buf
-        (revert-buffer nil t t)))))
-
-(defvar TeX-after-start-process-function
-  #'TeX-adjust-process-coding-system
-  "Function to adjust coding system of an asynchronous process.
-Called with one argument PROCESS.")
-
-(defun TeX-adjust-process-coding-system (process)
-  "Adjust coding system of PROCESS to suitable value.
-Usually coding system is the same as the TeX file with eol format
-adjusted to OS default value.  Take care of Japanese TeX, which
-requires special treatment."
-  (if (and (boundp 'japanese-TeX-mode)
-           (fboundp 'japanese-TeX-set-process-coding-system)
-           (with-current-buffer TeX-command-buffer
-             japanese-TeX-mode))
-      (japanese-TeX-set-process-coding-system process)
-    (let ((cs (coding-system-base (with-current-buffer TeX-command-buffer
-                                    buffer-file-coding-system))))
-      ;; The value of `buffer-file-coding-system' is sometimes
-      ;; undecided-{unix,dos,mac}.  That happens when the file
-      ;; contains no multibyte chars and only end of line format is
-      ;; determined.  Emacs lisp reference recommends not to use
-      ;; undecided-* for process coding system, so it might seem
-      ;; reasonable to change `undecided' into some fixed coding
-      ;; system like this:
-      ;; (if (eq 'undecided cs)
-      ;;     (setq cs 'utf-8))
-      ;; However, that can lose when the following conditions are met:
-      ;; (1) The document is divided into multiple files.
-      ;; (2) The command buffer contains no multibyte chars.
-      ;; (3) The other files contain mutlibyte chars and saved in a
-      ;;     coding system other than the one chosen above.
-      ;; So we leave `undecided' unchanged here.  Although `undecided'
-      ;; is not quite safe for the coding system for encoding, i.e.,
-      ;; keyboard input to the TeX process, we expect that this does
-      ;; not raise serious problems because it is pretty rare that TeX
-      ;; process needs keyboard input of multibyte chars.
-
-      ;; `utf-8-with-signature' (UTF-8 with BOM) doesn't suit at all
-      ;; for the coding system for encoding because it always injects
-      ;; 3-byte BOM in front of its return value (even when the string
-      ;; to be sent has only ascii characters!)  Thus we change it
-      ;; into `utf-8'.  On decoding, `utf-8' can decode UTF-8 with
-      ;; BOM.  So it is safe for both decoding and encoding.
-      (if (eq cs 'utf-8-with-signature)
-          (setq cs 'utf-8))
-
-      ;; Eol format of TeX files can differ from OS default. TeX
-      ;; binaries accept all type of eol format in the given files
-      ;; and output messages according to OS default.  So we set eol
-      ;; format to OS default value.
-      (setq cs (coding-system-change-eol-conversion
-                cs
-                ;; The eol of macosX is LF, not CR.  So we choose
-                ;; other than `unix' only for w32 system.
-                ;; FIXME: what should we do for cygwin?
-                (if (eq system-type 'windows-nt) 'dos 'unix)))
-      (set-process-coding-system process cs cs))))
-
-(defcustom TeX-show-compilation nil
-  "If non-nil, show output of TeX compilation in other window."
-  :group 'TeX-command
-  :type 'boolean)
-
-(defun TeX-run-command (name command file)
-  "Create a process for NAME using COMMAND to process FILE.
-Return the new process."
-  (let ((default TeX-command-default)
-        (buffer (TeX-process-buffer-name file))
-        (dir (TeX-master-directory))
-        (command-buff (current-buffer)))
-    (TeX-process-check file)            ; Check that no process is running
-    (setq-default TeX-command-buffer command-buff)
-    (get-buffer-create buffer)
-    (set-buffer buffer)
-    (buffer-disable-undo)
-    (erase-buffer)
-    (set (make-local-variable 'line-number-display-limit) 0)
-    (setq TeX-output-extension nil)
-    (set (make-local-variable 'TeX-command-buffer) command-buff)
-    (if dir (cd dir))
-    (insert "Running `" name "' on `" file "' with ``" command "''\n")
-    (TeX-output-mode)
-    (if TeX-show-compilation
-        (display-buffer buffer)
-      (message "Type `%s' to display results of compilation."
-               (substitute-command-keys
-                "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
-    (setq TeX-parse-function #'TeX-parse-command)
-    (setq TeX-command-default default)
-    (setq TeX-sentinel-function
-          (lambda (_process name)
-            (message (concat name ": done."))))
-    (if TeX-process-asynchronous
-        (let ((process (start-process name buffer TeX-shell
-                                      TeX-shell-command-option command)))
-          (if TeX-after-start-process-function
-              (funcall TeX-after-start-process-function process))
-          (TeX-command-mode-line process)
-          (set-process-filter process #'TeX-command-filter)
-          (set-process-sentinel process #'TeX-command-sentinel)
-          (set-marker (process-mark process) (point-max))
-          (setq compilation-in-progress (cons process compilation-in-progress))
-          process)
-      (setq mode-line-process ": run")
-      (force-mode-line-update)
-      (call-process TeX-shell nil buffer nil
-                    TeX-shell-command-option command))))
-
-(defun TeX-run-set-command (name command)
-  "Remember TeX command to use to NAME and set corresponding output extension."
-  (setq TeX-command-default name
-        TeX-output-extension
-        (if (and (null (TeX-PDF-from-DVI)) TeX-PDF-mode) "pdf" "dvi"))
-  (let ((case-fold-search t)
-        (lst TeX-command-output-list))
-    (while lst
-      (if (string-match (car (car lst)) command)
-          (setq TeX-output-extension (car (cdr (car lst)))
-                lst nil)
-        (setq lst (cdr lst))))))
-
-(defvar TeX-error-report-switches nil
-  "Reports presence of errors after `TeX-run-TeX'.
-Actually, `TeX-run-format' sets it.
-To test whether the current buffer has a compile error from last
-run of `TeX-run-format', use
-  (TeX-error-report-has-errors-p)")
-
-(defun TeX-error-report-has-errors-p ()
-  "Return non-nil if current buffer has compile errors from last TeX run."
-  (plist-get TeX-error-report-switches (intern (TeX-master-file))))
-
-(defun TeX-run-format (name command file)
-  "Create a process for NAME using COMMAND to format FILE with TeX."
-  (TeX-run-set-command name command)
-  (let ((current-master (TeX-master-file))
-        (buffer (TeX-process-buffer-name file))
-        (process (TeX-run-command name command file)))
-
-    ;; Save information in TeX-error-report-switches
-    ;; Initialize error to nil (no error) for current master.
-    ;; Presence of error is reported inside `TeX-TeX-sentinel-check'
-
-    ;; the current master file is saved because error routines are
-    ;; parsed in other buffers;
-    (setq TeX-error-report-switches
-          (plist-put TeX-error-report-switches
-                     'TeX-current-master current-master))
-    ;; reset error to nil (no error)
-    (setq TeX-error-report-switches
-          (plist-put TeX-error-report-switches
-                     (intern current-master) nil))
-
-    ;; Hook to TeX debugger.
-    (with-current-buffer buffer
-      (TeX-parse-reset)
-      (setq TeX-parse-function #'TeX-parse-TeX)
-      (setq TeX-sentinel-function #'TeX-TeX-sentinel)
-      (if TeX-process-asynchronous
-          (progn
-            ;; Updating the mode line.
-            (setq TeX-current-page "[0]")
-            (TeX-format-mode-line process)
-            (set-process-filter process #'TeX-format-filter)))
-      process)))
-
-(defun TeX-run-TeX (name command file)
-  "Create a process for NAME using COMMAND to format FILE with TeX."
-
-  (let ((idx-file nil) (element nil))
-    ;; Store md5 hash of the index file before running LaTeX.
-    (and (memq major-mode '(doctex-mode latex-mode))
-         (prog1 (file-exists-p
-                 (setq idx-file (expand-file-name (TeX-active-master "idx"))))
-           ;; In order to avoid confusion and pollution of
-           ;; `LaTeX-idx-md5-alist', remove from this alist all md5 hashes of
-           ;; the current index file.  Note `assq-delete-all' doesn't work with
-           ;; string keys and has problems with non-list elements in Emacs 21
-           ;; (see file tex-site.el).
-           (while (setq element (assoc idx-file LaTeX-idx-md5-alist))
-             (setq LaTeX-idx-md5-alist (delq element LaTeX-idx-md5-alist))))
-         (with-temp-buffer
-           (insert-file-contents-literally idx-file)
-           (push (cons idx-file (md5 (current-buffer))) LaTeX-idx-md5-alist))))
-
-  ;; can we assume that TeX-sentinel-function will not be changed
-  ;; during (TeX-run-format ..)? --pg
-  ;; rather use let* ? --pg
-
-  (if TeX-interactive-mode
-      (TeX-run-interactive name command file)
-    (let* ((sentinel-function TeX-sentinel-default-function)
-           (process (TeX-run-format name command file)))
-      (setq TeX-sentinel-function sentinel-function)
-      (if TeX-process-asynchronous
-          process
-        (TeX-synchronous-sentinel name file process)))))
-
-;; backward compatibilty
-
-(defalias 'TeX-run-LaTeX #'TeX-run-TeX)
-
-
-(defun TeX-run-BibTeX (name command file)
-  "Create a process for NAME using COMMAND to format FILE with BibTeX."
-  (let ((process (TeX-run-command name command file)))
-    (setq TeX-sentinel-function #'TeX-BibTeX-sentinel)
-    (if TeX-process-asynchronous
-        process
-      (TeX-synchronous-sentinel name file process))))
-
-(defun TeX-run-Biber (name command file)
-  "Create a process for NAME using COMMAND to format FILE with Biber."
-  (let ((process (TeX-run-command name command file)))
-    (setq TeX-sentinel-function #'TeX-Biber-sentinel)
-    (if TeX-process-asynchronous
-        process
-      (TeX-synchronous-sentinel name file process))))
-
-(defun TeX-run-dvips (name command file)
-  "Create a process for NAME using COMMAND to convert FILE with dvips."
-  (let ((process (TeX-run-command name command file)))
-    (setq TeX-sentinel-function #'TeX-dvips-sentinel)
-    (if TeX-process-asynchronous
-        process
-      (TeX-synchronous-sentinel name file process))))
-
-(defun TeX-run-dvipdfmx (name command file)
-  "Create a process for NAME using COMMAND to convert FILE with dvipdfmx."
-  (let ((process (TeX-run-command name command file)))
-    (setq TeX-sentinel-function #'TeX-dvipdfmx-sentinel)
-    (if TeX-process-asynchronous
-        process
-      (TeX-synchronous-sentinel name file process))))
-
-(defun TeX-run-ps2pdf (name command file)
-  "Create a process for NAME using COMMAND to convert FILE with ps2pdf."
-  (let ((process (TeX-run-command name command file)))
-    (setq TeX-sentinel-function #'TeX-ps2pdf-sentinel)
-    (if TeX-process-asynchronous
-        process
-      (TeX-synchronous-sentinel name file process))))
-
-(defun TeX-run-index (name command file)
-  "Create a process for NAME using COMMAND to compile the index file."
-  (let ((process (TeX-run-command name command file))
-        (element nil))
-    (setq TeX-sentinel-function #'TeX-index-sentinel)
-    ;; Same cleaning as that for `LaTeX-idx-md5-alist' in `TeX-run-TeX'.
-    (while (setq element
-                 ;; `file' has been determined in `TeX-command-buffer', while
-                 ;; this function has `TeX-master-directory' as
-                 ;; `default-directory', then we have to expand `file' 
file-name
-                 ;; in the same directory of `TeX-command-buffer'.
-                 (assoc (with-current-buffer TeX-command-buffer
-                            (expand-file-name (TeX-active-master "idx")))
-                        LaTeX-idx-changed-alist))
-      (setq LaTeX-idx-changed-alist (delq element LaTeX-idx-changed-alist)))
-    (if TeX-process-asynchronous
-        process
-      (TeX-synchronous-sentinel name file process))))
-
-(defun TeX-run-compile (_name command _file)
-  "Ignore first and third argument, start compile with second argument."
-  (let ((default-directory (TeX-master-directory)))
-    (setq TeX-command-buffer (compile command)))
-  ;; Make `compilation-mode' recognize file names with spaces.
-  ;; (bug#36483)
-  ;; FIXME: This is just an ad-hoc workaround and it's better to fix
-  ;; the regular expression in compile.el properly, if possible.  But
-  ;; there was no response to such request in emacs-devel@gnu.org.
-  (with-current-buffer TeX-command-buffer
-    (make-local-variable 'compilation-error-regexp-alist)
-    ;; Add slightly modified entry of the one associated with `comma'
-    ;; in `compilation-error-regexp-alist-alist' to pick up file names
-    ;; with spaces.
-    (add-to-list 'compilation-error-regexp-alist
-                 '("^\"\\([^,\"\n\t]+\\)\", line \\([0-9]+\\)\
-\\(?:[(. pos]+\\([0-9]+\\))?\\)?[:.,; (-]\\( warning:\\|[-0-9 ]*(W)\\)?" 1 2 3 
(4))
-                 t)))
-
-(defun TeX-run-shell (_name command _file)
-  "Ignore first and third argument, start shell-command with second argument."
-  (let ((default-directory (TeX-master-directory)))
-    (shell-command command)
-    (if (eq system-type 'ms-dos)
-        (redraw-display))))
-
-(defun TeX-run-discard (_name command _file)
-  "Start COMMAND as process, discarding its output.
-NAME and FILE are ignored."
-  (let ((default-directory (TeX-master-directory)))
-    (call-process TeX-shell
-                  nil 0 nil
-                  TeX-shell-command-option
-                  command)))
-
-(defun TeX-run-discard-foreground (_name command _file)
-  "Call process with second argument in the foreground, discarding its output.
-With support for MS-DOS, especially when dviout is used with PC-9801 series."
-  (if (and (boundp 'dos-machine-type) (eq dos-machine-type 'pc98)) ;if PC-9801
-      (send-string-to-terminal "\e[2J")) ; clear screen
-  (call-process TeX-shell (if (eq system-type 'ms-dos) "con") nil nil
-                TeX-shell-command-option command)
-  (if (eq system-type 'ms-dos)
-      (redraw-display)))
-(defalias 'TeX-run-dviout #'TeX-run-discard-foreground)
-
-(defun TeX-run-background (name command _file)
-  "Start process with second argument, show output when and if it arrives."
-  (let ((dir (TeX-master-directory)))
-    (set-buffer (get-buffer-create "*TeX background*"))
-    (if dir (cd dir))
-    (erase-buffer)
-    (let ((process (start-process (concat name " background")
-                                  nil TeX-shell
-                                  TeX-shell-command-option command)))
-      (if TeX-after-start-process-function
-          (funcall TeX-after-start-process-function process))
-      (set-process-filter process #'TeX-background-filter)
-      (set-process-query-on-exit-flag process nil))))
-
-(defun TeX-run-silent (name command _file)
-  "Start process with second argument."
-  (let ((dir (TeX-master-directory)))
-    (set-buffer (get-buffer-create "*TeX silent*"))
-    (if dir (cd dir))
-    (erase-buffer)
-    (let ((process (start-process (concat name " silent")
-                                  (current-buffer) TeX-shell
-                                  TeX-shell-command-option command)))
-      (if TeX-after-start-process-function
-          (funcall TeX-after-start-process-function process))
-      (set-process-query-on-exit-flag process nil))))
-
-(defun TeX-run-interactive (name command file)
-  "Run TeX interactively.
-Run command in a buffer (in comint-shell-mode) so that it accepts user
-interaction. If you return to the file buffer after the TeX run,
-Error parsing on \\[next-error] should work with a bit of luck."
-  (TeX-run-set-command name command)
-  (require 'comint)
-  (let ((default TeX-command-default)
-        (buffer (TeX-process-buffer-name file))
-        (process nil)
-        (dir (TeX-master-directory))
-        (command-buff (current-buffer))
-        (sentinel-function TeX-sentinel-default-function)) ; inherit from 
major mode
-    (TeX-process-check file)            ; Check that no process is running
-    (setq-default TeX-command-buffer command-buff)
-    (with-output-to-temp-buffer buffer)
-    (set-buffer buffer)
-    (set (make-local-variable 'TeX-command-buffer) command-buff)
-    (setq buffer-read-only nil)
-    (if dir (cd dir))
-    (insert "Running `" name "' on `" file "' with ``" command "''\n")
-    (comint-exec buffer name TeX-shell nil
-                 (list TeX-shell-command-option command))
-    (comint-mode)
-    (add-hook 'comint-output-filter-functions #'TeX-interactive-goto-prompt)
-    (setq mode-name name)
-    (setq TeX-command-default default)
-    (setq process (get-buffer-process buffer))
-    (if TeX-after-start-process-function
-        (funcall TeX-after-start-process-function process))
-    (TeX-command-mode-line process)
-    (set-process-sentinel process #'TeX-command-sentinel)
-    (set-marker (process-mark process) (point-max))
-    (setq compilation-in-progress (cons process compilation-in-progress))
-    (TeX-parse-reset)
-    (setq TeX-parse-function #'TeX-parse-TeX)
-    ;; use the sentinel-function that the major mode sets, not the LaTeX one
-    (setq TeX-sentinel-function sentinel-function)))
-
-(defun TeX-run-function (_name command _file)
-  "Execute Lisp function or function call given as the string COMMAND.
-Parameters NAME and FILE are ignored."
-  (let ((fun (car (read-from-string command))))
-    (if (functionp fun) (funcall fun) (eval fun t))))
-
-(defun TeX-run-discard-or-function (name command file)
-  "Start COMMAND as process or execute it as a Lisp function.
-If run as a process, the output is discarded.  COMMAND is
-expected to be a string.  NAME and FILE are ignored."
-  (if (functionp (car (read-from-string command)))
-      (TeX-run-function name command file)
-    (TeX-run-discard name command file)))
-
-(defun TeX-run-ispell-on-document (_command _ignored _name)
-  "Run Ispell on all open files belonging to the current document.
-This function is *obsolete* and only here for compatibility
-reasons.  Use `TeX-run-function' instead."
-  (interactive)
-  (TeX-ispell-document ""))
-
-
-;;; Command Sentinels
-
-(defun TeX-synchronous-sentinel (name file result)
-  "Process TeX command output buffer after the process dies."
-  (let ((buffer (TeX-process-buffer (file-name-nondirectory file))))
-    (with-current-buffer buffer
-
-      ;; Append post-mortem information to the buffer
-      (goto-char (point-max))
-      (insert "\n" mode-name (if (and result (zerop result))
-                                 " finished" " exited") " at "
-              (substring (current-time-string) 0 -5))
-      (setq mode-line-process ": exit")
-
-      ;; Do command specific actions.
-      (setq TeX-command-next TeX-command-Show)
-      (goto-char (point-min))
-      (apply TeX-sentinel-function nil name nil)
-
-      ;; Force mode line redisplay soon
-      (force-mode-line-update))))
-
-(defun TeX-command-sentinel (process msg)
-  "Process TeX command output buffer after the PROCESS dies.
-Insert MSG with some additional information."
-  ;; Set `TeX-transient-master' here because `preview-parse-messages'
-  ;; may open files and thereby trigger master file questions which we
-  ;; don't want and need because we already know the master.  Use
-  ;; `TeX-master-file' instead of `TeX-active-master' to determine the
-  ;; master because the region file should never be the master.
-  (let* ((TeX-transient-master (TeX-master-file))
-         (buffer (process-buffer process))
-         (name (process-name process)))
-    (cond ((null (buffer-name buffer))  ; buffer killed
-           (set-process-buffer process nil)
-           (set-process-sentinel process nil))
-          ((memq (process-status process) '(signal exit))
-           (with-current-buffer buffer
-
-             ;; Append post-mortem information to the buffer
-             (goto-char (point-max))
-             (insert-before-markers "\n" mode-name " " msg)
-             (forward-char -1)
-             (insert " at "
-                     (substring (current-time-string) 0 -5))
-             (forward-char 1)
-
-             ;; Do command specific actions.
-             (TeX-command-mode-line process)
-             (setq TeX-command-next TeX-command-Show)
-             (goto-char (point-min))
-             (apply TeX-sentinel-function process name nil)
-
-
-             ;; If buffer and mode line will show that the process
-             ;; is dead, we can delete it now.  Otherwise it
-             ;; will stay around until M-x list-processes.
-             (delete-process process))
-
-           ;; Force mode line redisplay soon
-           ;; Do this in all buffers (bug#38058 and bug#40965)
-           (force-mode-line-update t))))
-
-  (setq compilation-in-progress (delq process compilation-in-progress)))
-
-
-(defvar TeX-sentinel-function (lambda (_process _name) nil)
-  "Hook to cleanup TeX command buffer after termination of PROCESS.
-NAME is the name of the process.")
-
-(make-variable-buffer-local 'TeX-sentinel-function)
-
-
-(defvar TeX-sentinel-default-function (lambda (_process _name) nil)
-  "Default for `TeX-sentinel-function'.  To be set in major mode.
-Hook to cleanup TeX command buffer after termination of PROCESS.
-NAME is the name of the process.")
-
-(make-variable-buffer-local 'TeX-sentinel-default-function)
-
-(defun TeX-TeX-sentinel (process name)
-  "Cleanup TeX output buffer after running TeX.
-
-Parse the output buffer to collect errors and warnings if the
-variable `TeX-parse-all-errors' is non-nil.
-
-Open the error overview if
-`TeX-error-overview-open-after-TeX-run' is non-nil and there are
-errors or warnings to show."
-  (if (TeX-TeX-sentinel-check process name)
-      (progn
-        (if TeX-parse-all-errors
-            (TeX-parse-all-errors))
-        (if (and TeX-error-overview-open-after-TeX-run
-                 (TeX-error-overview-make-entries
-                  (TeX-master-directory) (TeX-active-buffer)))
-            (TeX-error-overview)))
-    (message (concat name ": formatted " (TeX-current-pages)))
-    (let (dvi2pdf)
-        (if (with-current-buffer TeX-command-buffer
-           (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
-         (setq TeX-command-next dvi2pdf)
-       (setq TeX-command-next TeX-command-Show)))))
-
-(defun TeX-current-pages ()
-  "Return string indicating the number of pages formatted."
-  (cond ((null TeX-current-page)
-         "some pages")
-        ((string-match "[^0-9]1[^0-9]" TeX-current-page)
-         (concat TeX-current-page " page"))
-        (t
-         (concat TeX-current-page " pages"))))
-
-(defun TeX-TeX-sentinel-check (process name)
-  "Cleanup TeX output buffer after running TeX.
-Return nil only if no errors were found."
-  (save-excursion
-    (goto-char (point-max))
-    (cond
-     ((and (string-match "ConTeXt" name) (boundp 'ConTeXt-Mark-version)
-           (with-current-buffer TeX-command-buffer
-             (string= ConTeXt-Mark-version "IV")))
-      (when (re-search-backward " > result saved in file: \\(.*?\\), " nil t)
-        (let ((output-file (TeX-match-buffer 1)))
-          ;; Shave off quotation marks if present.
-          (when (string-match "\\`\"\\(.*\\)\"\\'" output-file)
-            (setq output-file (match-string 1 output-file)))
-          (setq TeX-output-extension
-                (if (string-match "\\.\\([^.]*\\)$" output-file)
-                    (match-string 1 output-file)
-                  "dvi")))
-        (if (re-search-forward ", \\([0-9]+\\) shipped pages, " nil t)
-            (setq TeX-current-page (concat "{" (TeX-match-buffer 1) "}")))))
-     (t
-      (if (re-search-backward "^Output written on \\(.*?\\) (\\([0-9]+\\) page"
-                              nil t)
-          (let ((output-file (TeX-match-buffer 1)))
-            (setq TeX-current-page (concat "{" (TeX-match-buffer 2) "}"))
-            ;; Shave off quotation marks if present.
-            (when (string-match "\\`\"\\(.*\\)\"\\'" output-file)
-              (setq output-file (match-string 1 output-file)))
-            (setq TeX-output-extension
-                  (if (string-match "\\.\\([^.]*\\)$" output-file)
-                      (match-string 1 output-file)
-                    "dvi")))))))
-  (if process (TeX-format-mode-line process))
-  (if (re-search-forward "^\\(!\\|.*:[0-9]+:\\) " nil t)
-      (progn
-        (message "%s errors in `%s'. Use %s to display." name (buffer-name)
-                 (substitute-command-keys
-                  "\\<TeX-mode-map>\\[TeX-next-error]"))
-        (setq TeX-command-next TeX-command-default)
-        ;; error reported to TeX-error-report-switches
-        (setq TeX-error-report-switches
-              (plist-put TeX-error-report-switches
-                         (intern (plist-get TeX-error-report-switches
-                                            'TeX-current-master))
-                         t))
-        t)
-    (let (dvi2pdf)
-        (if (with-current-buffer TeX-command-buffer
-           (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
-         (setq TeX-command-next dvi2pdf)
-       (setq TeX-command-next TeX-command-Show)))
-    nil))
-
-;; This regexp should catch warnings of the type
-;;   LaTeX Warning: ...
-;;   LaTeX Font Warning: ...
-;;   Package xyz123 Warning: ...
-;;   Class xyz123 Warning: ...
-(defvar LaTeX-warnings-regexp
-  "\\(?:LaTeX\\|Class\\|Package\\|\\*\\) [-A-Za-z0-9]* ?[Ww]arning:"
-  "Regexp matching LaTeX warnings.")
-
-(defun TeX-LaTeX-sentinel-has-warnings ()
-  "Return non-nil, if the output buffer contains warnings.
-Warnings can be indicated by LaTeX or packages."
-  (save-excursion
-    (goto-char (point-min))
-    (re-search-forward (concat "^" LaTeX-warnings-regexp) nil t)))
-
-(defun TeX-LaTeX-sentinel-has-bad-boxes ()
-  "Return non-nil, if LaTeX output indicates overfull or underfull boxes."
-  (save-excursion
-    (goto-char (point-min))
-    (re-search-forward "^\\(Ov\\|Und\\)erfull \\\\" nil t)))
-
-;; should go into latex.el? --pg
-(defun TeX-LaTeX-sentinel (process name)
-  "Cleanup TeX output buffer after running LaTeX.
-
-Parse the output buffer to collect errors and warnings if the
-variable `TeX-parse-all-errors' is non-nil.
-
-Open the error overview if
-`TeX-error-overview-open-after-TeX-run' is non-nil and there are
-errors or warnings to show."
-  (if TeX-parse-all-errors
-      (TeX-parse-all-errors))
-  (if (and TeX-error-overview-open-after-TeX-run
-           (TeX-error-overview-make-entries
-            (TeX-master-directory) (TeX-active-buffer)))
-      (TeX-error-overview))
-  (cond ((TeX-TeX-sentinel-check process name))
-        ((and (save-excursion
-                (re-search-forward
-                 "^Package biblatex Warning: Please (re)run Biber on the file"
-                 nil t))
-              (with-current-buffer TeX-command-buffer
-                (and (LaTeX-bibliography-list)
-                     (TeX-check-files (TeX-master-file "bbl")
-                                      (TeX-style-list)
-                                      (append TeX-file-extensions
-                                              BibTeX-file-extensions
-                                              TeX-Biber-file-extensions)))))
-         (message "%s%s" "You should run Biber to get citations right, "
-                  (TeX-current-pages))
-         (setq TeX-command-next (with-current-buffer TeX-command-buffer
-                                  TeX-command-Biber)))
-        ((and (save-excursion
-                (re-search-forward
-                 "^\\(?:LaTeX\\|Package natbib\\) Warning: Citation" nil t))
-              (with-current-buffer TeX-command-buffer
-                (and (LaTeX-bibliography-list)
-                     (TeX-check-files (TeX-master-file "bbl")
-                                      (TeX-style-list)
-                                      (append TeX-file-extensions
-                                              BibTeX-file-extensions
-                                              TeX-Biber-file-extensions)))))
-         (message "%s%s" "You should run BibTeX to get citations right, "
-                  (TeX-current-pages))
-         (setq TeX-command-next (with-current-buffer TeX-command-buffer
-                                  TeX-command-BibTeX)))
-        ((re-search-forward "Package biblatex Warning: Please rerun LaTeX" nil 
t)
-         (message "%s%s" "You should run LaTeX again, " (TeX-current-pages))
-         (setq TeX-command-next TeX-command-default))
-        ((re-search-forward "^(biblatex)\\W+Page breaks have changed" nil t)
-         (message "%s%s" "You should run LaTeX again - page breaks have 
changed, "
-                  (TeX-current-pages))
-         (setq TeX-command-next TeX-command-default))
-        ((re-search-forward "^\\(?:LaTeX Warning: Label(s)\\|\
-Package natbib Warning: Citation(s)\\)" nil t)
-         (message "%s%s" "You should run LaTeX again to get references right, "
-                  (TeX-current-pages))
-         (setq TeX-command-next TeX-command-default))
-        ((re-search-forward
-          "^\\(?:(rerunfilecheck)\\|Package hyperref Warning:\\)\\W+\
-Rerun to get outlines right" nil t)
-         (message "%s%s" "You should run LaTeX again to get outlines right, "
-                  (TeX-current-pages))
-         (setq TeX-command-next TeX-command-default))
-        ((re-search-forward "^LaTeX Warning: Reference" nil t)
-         (message "%s%s%s" name ": there were unresolved references, "
-                  (TeX-current-pages))
-         (let (dvi2pdf)
-           (if (with-current-buffer TeX-command-buffer
-                 (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
-               (setq TeX-command-next dvi2pdf)
-             (setq TeX-command-next TeX-command-Show))))
-        ((re-search-forward "^\\(?:LaTeX Warning: Citation\\|\
-Package natbib Warning:.*undefined citations\\)" nil t)
-         (message "%s%s%s" name ": there were unresolved citations, "
-                  (TeX-current-pages))
-         (let (dvi2pdf)
-           (if (with-current-buffer TeX-command-buffer
-                 (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
-               (setq TeX-command-next dvi2pdf)
-             (setq TeX-command-next TeX-command-Show))))
-        ((re-search-forward "^No file .*\\.\\(toc\\|lof\\|lot\\)\\.$" nil t)
-         (message "%s" (concat "You should run LaTeX again to get "
-                               (upcase (match-string-no-properties 1))
-                               " right"))
-         (setq TeX-command-next TeX-command-default))
-        ((re-search-forward "Package longtable Warning: Table widths have \
-changed\\. Rerun LaTeX\\." nil t)
-         (message
-          "%s" "You should run LaTeX again to get table formatting right")
-         (setq TeX-command-next TeX-command-default))
-        ((re-search-forward "^hf-TikZ Warning: Mark '.*' changed\\. \
-Rerun to get mark in right position\\." nil t)
-         (message
-          "%s" "You should run LaTeX again to get TikZ marks in right 
position")
-         (setq TeX-command-next TeX-command-default))
-        ((re-search-forward "^\\* xsim warning: \"rerun\"" nil t)
-         (message
-          "%s" "You should run LaTeX again to synchronize exercise properties")
-         (setq TeX-command-next TeX-command-default))
-        ((re-search-forward
-          "^\\(\\*\\* \\)?J?I?p?\\(La\\|Sli\\)TeX\\(2e\\)? \
-\\(Version\\|ver\\.\\|<[0-9/-]*\\(?:u[^>]*\\)?>\\)" nil t)
-         (let* ((warnings (and TeX-debug-warnings
-                               (TeX-LaTeX-sentinel-has-warnings)))
-                (bad-boxes (and TeX-debug-bad-boxes
-                                (TeX-LaTeX-sentinel-has-bad-boxes)))
-                (add-info (when (or warnings bad-boxes)
-                            (concat " (with "
-                                    (when warnings "warnings")
-                                    (when (and warnings bad-boxes) " and ")
-                                    (when bad-boxes "bad boxes")
-                                    ")"))))
-           (message "%s" (concat name ": successfully formatted "
-                                 (TeX-current-pages) add-info)))
-         (let (dvi2pdf)
-           (if (with-current-buffer TeX-command-buffer
-                 (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
-               (setq TeX-command-next dvi2pdf)
-             (setq TeX-command-next TeX-command-Show))))
-        (t
-         (message "%s%s%s" name ": problems after " (TeX-current-pages))
-         (setq TeX-command-next TeX-command-default)))
-
-  ;; Check whether the idx file changed.
-  (let (idx-file)
-    (and (file-exists-p
-          (setq idx-file
-                (with-current-buffer TeX-command-buffer
-                  (expand-file-name (TeX-active-master "idx")))))
-         ;; imakeidx package automatically runs makeindex, thus, we need to be
-         ;; sure .ind file isn't newer than .idx.
-         (TeX-check-files (with-current-buffer TeX-command-buffer
-                            (expand-file-name (TeX-active-master "ind")))
-                          (with-current-buffer TeX-command-buffer
-                            (list (file-name-nondirectory 
(TeX-active-master))))
-                          '("idx"))
-         (with-temp-buffer
-           (insert-file-contents-literally idx-file)
-           (not (equal
-                 ;; Compare old md5 hash of the idx file with the new one.
-                 (cdr (assoc idx-file LaTeX-idx-md5-alist))
-                 (md5 (current-buffer)))))
-         (push (cons idx-file t) LaTeX-idx-changed-alist)))
-
-  (unless (TeX-error-report-has-errors-p)
-    (run-hook-with-args 'TeX-after-compilation-finished-functions
-                        (with-current-buffer TeX-command-buffer
-                          (expand-file-name
-                           (TeX-active-master (TeX-output-extension)))))))
-
-;; should go into latex.el? --pg
-(defun TeX-BibTeX-sentinel (_process _name)
-  "Cleanup TeX output buffer after running BibTeX."
-  (goto-char (point-max))
-  (cond
-   ;; Check whether BibTeX reports any warnings or errors.
-   ((re-search-backward (concat
-                         "^(There \\(?:was\\|were\\) \\([0-9]+\\) "
-                         "\\(warnings?\\|error messages?\\))")
-                        nil t)
-    ;; Tell the user their number so that she sees whether the
-    ;; situation is getting better or worse.
-    (message (concat "BibTeX finished with %s %s. "
-                     "Type `%s' to display output.")
-             (match-string 1) (match-string 2)
-             (substitute-command-keys
-              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
-   (t
-    (message (concat "BibTeX finished successfully. "
-                     "Run LaTeX again to get citations right."))))
-  ;; In any case, run the default next command.
-  (setq TeX-command-next TeX-command-default))
-
-(defun TeX-Biber-sentinel (_process _name)
-  "Cleanup TeX output buffer after running Biber."
-  (goto-char (point-max))
-  (cond
-   ((re-search-backward "^INFO - \\(WARNINGS\\|ERRORS\\): \\([0-9]+\\)" nil t)
-    (message (concat "Biber finished with %s %s. "
-                     "Type `%s' to display output.")
-             (match-string 2) (downcase (match-string 1))
-             (substitute-command-keys
-              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]"))
-    (setq TeX-command-next TeX-command-default))
-   ((re-search-backward "^FATAL" nil t)
-    (message (concat "Biber had a fatal error and did not finish! "
-                     "Type `%s' to display output.")
-             (substitute-command-keys
-              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]"))
-    (setq TeX-command-next TeX-command-Biber))
-   (t
-    (message (concat "Biber finished successfully. "
-                     "Run LaTeX again to get citations right."))
-    (setq TeX-command-next TeX-command-default))))
-
-(defun TeX-dvips-sentinel (_process _name)
-  "Cleanup TeX output buffer after running dvips."
-  (goto-char (point-max))
-  (cond
-   ((search-backward "TeX Output exited abnormally" nil t)
-    (message "Dvips failed.  Type `%s' to display output."
-             (substitute-command-keys
-              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
-   (t
-    (if (with-current-buffer TeX-command-buffer
-          (and (equal (TeX-PDF-from-DVI) "Dvips") TeX-PDF-mode))
-        (setq TeX-output-extension "ps"
-              TeX-command-next "Ps2pdf"))
-    (message "Dvips finished successfully. "))))
-
-(defun TeX-dvipdfmx-sentinel (_process _name)
-  "Cleanup TeX output buffer after running dvipdfmx."
-  (goto-char (point-max))
-  (cond
-   ((search-backward "TeX Output exited abnormally" nil t)
-    (message "Dvipdfmx failed.  Type `%s' to display output."
-             (substitute-command-keys
-              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
-   (t
-    (if (with-current-buffer TeX-command-buffer
-          (and (equal (TeX-PDF-from-DVI) "Dvipdfmx") TeX-PDF-mode))
-        (setq TeX-output-extension "pdf"
-              TeX-command-next TeX-command-Show))
-    (message "Dvipdfmx finished successfully. "))))
-
-(defun TeX-ps2pdf-sentinel (_process _name)
-  "Cleanup TeX output buffer after running ps2pdf."
-  (goto-char (point-max))
-  (cond
-   ((search-backward "TeX Output exited abnormally" nil t)
-    (message "ps2pdf failed.  Type `%s' to display output."
-             (substitute-command-keys
-              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
-   (t
-    (if (with-current-buffer TeX-command-buffer
-          (and (equal (TeX-PDF-from-DVI) "Dvips") TeX-PDF-mode))
-        (setq TeX-command-next TeX-command-Show
-              TeX-output-extension "pdf"))
-    (message "ps2pdf finished successfully. "))))
-
-(defun TeX-index-sentinel (_process _name)
-  "Cleanup TeX output buffer after compiling index."
-  (goto-char (point-max))
-  (cond
-   ((search-backward "TeX Output exited abnormally" nil t)
-    (message "Index failed.  Type `%s' to display output."
-             (substitute-command-keys
-              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
-   (t
-    (setq TeX-command-next TeX-command-default)
-    (message (concat "Index finished successfully. "
-                     "Run LaTeX again to get index right.")))))
-
-(defun TeX-command-sequence-sentinel (process string)
-  "Call the appropriate sentinel for the current PROCESS.
-Pass two arguments PROCESS and STRING to the sentinel.
-
-If there are no errors, call back `TeX-command-sequence' using
-`TeX-command-sequence-command' as command argument, unless this
-variable is nil."
-  (with-current-buffer (process-buffer process)
-    (funcall TeX-command-sequence-sentinel process string)
-    (if (string-match "\\(finished\\|exited\\)" string)
-        (with-current-buffer TeX-command-buffer
-          (unless
-              (or
-               (TeX-error-report-has-errors-p)
-               (null TeX-command-sequence-command))
-            (TeX-command-sequence TeX-command-sequence-command nil
-                                  TeX-command-sequence-file-function))))))
-
-;;; Process Control
-
-;; COMPATIBILITY for emacs < 27
-(if (< emacs-major-version 27)
-    (or (assq 'compilation-in-progress minor-mode-alist)
-        (setq minor-mode-alist (cons '(compilation-in-progress " Compiling")
-                                     minor-mode-alist))))
-
-(defun TeX-process-get-variable (name symbol &optional default)
-  "Return the value in the process buffer for NAME of SYMBOL.
-
-Return DEFAULT if the process buffer does not exist or SYMBOL is not
-defined."
-  (let ((buffer (TeX-process-buffer name)))
-    (if (and buffer
-             (local-variable-p symbol buffer))
-        (with-current-buffer buffer
-          (symbol-value symbol))
-      default)))
-
-(defun TeX-process-set-variable (name symbol value)
-  "Set the variable SYMBOL in the process buffer to VALUE.
-Return nil only if no process buffer exists."
-  (let ((buffer (TeX-process-buffer name)))
-    (if buffer
-        (with-current-buffer buffer
-          (set symbol value)
-          t)
-      nil)))
-
-(defun TeX-process-check (name)
-  "Check if a process for the TeX document NAME already exist.
-If so, give the user the choice of aborting the process or the current
-command."
-  (let (process)
-    (while (and (setq process (TeX-process name))
-                (eq (process-status process) 'run))
-      (cond
-       ((yes-or-no-p (concat "Process `"
-                             (process-name process)
-                             "' for document `"
-                             name
-                             "' running, kill it? "))
-        (delete-process process))
-       ((eq (process-status process) 'run)
-           (error "Cannot have two processes for the same document"))))))
-
-(defun TeX-process-buffer-name (name)
-  "Return name of AUCTeX buffer associated with the document NAME."
-  (concat "*" (abbreviate-file-name (expand-file-name name)) " output*"))
-
-(defun TeX-process-buffer (name)
-  "Return the AUCTeX buffer associated with the document NAME."
-  (get-buffer (TeX-process-buffer-name name)))
-
-(defun TeX-process (name)
-  "Return AUCTeX process associated with the document NAME."
-  (and TeX-process-asynchronous
-       (get-buffer-process (TeX-process-buffer name))))
-
-;;; Process Filters
-
-(defun TeX-command-mode-line (process)
-  "Format the mode line for a buffer containing output from PROCESS."
-    (setq mode-line-process (concat ": "
-                                    (symbol-name (process-status process))))
-    (force-mode-line-update))
-
-(defun TeX-command-filter (process string)
-  "Filter to process normal output."
-  (with-current-buffer (process-buffer process)
-    (save-excursion
-      (goto-char (process-mark process))
-      (insert-before-markers string)
-      (set-marker (process-mark process) (point)))))
-
-(defvar TeX-current-page nil
-  "The page number currently being formatted, enclosed in brackets.")
-
- (make-variable-buffer-local 'TeX-current-page)
-
-(defun TeX-format-mode-line (process)
-  "Format the mode line for a buffer containing TeX output from PROCESS."
-    (setq mode-line-process (concat " " TeX-current-page ": "
-                                    (symbol-name (process-status process))))
-    (force-mode-line-update))
-
-(defun TeX-format-filter (process string)
-  "Filter to process TeX output."
-  (with-current-buffer (process-buffer process)
-    (let (str pos end (pt (marker-position (process-mark process))))
-      (save-excursion
-        (goto-char pt)
-        (insert-before-markers string)
-        (set-marker (process-mark process) (point))
-        ;; Remove line breaks at columns 79 and 80
-        (while (> (point) pt)
-          (end-of-line 0)
-          (when (and (memq (- (point) (line-beginning-position)) '(79 80))
-                     ;; Heuristic: Don't delete the linebreak if the next line
-                     ;; is empty or starts with an opening parenthesis, or if
-                     ;; point is located after a period and in the next line no
-                     ;; word char follows.
-                     (not (memq (char-after (1+ (point))) '(?\n ?\()))
-                     (not (and (eq (char-before) ?.)
-                               (char-after (1+ (point)))
-                               (not (eq ?w (char-syntax (char-after (1+ 
(point)))))))))
-            (delete-char 1)))
-        (goto-char (marker-position (process-mark process)))
-        ;; Determine current page
-        (while (and pt
-                    (skip-chars-backward "^]" pt)
-                    (> (point) pt))
-          (setq end (point))
-          (backward-char)
-          (skip-chars-backward "-0-9\n." (max (point-min) (- pt 128)))
-          (when (and (eq ?\[ (char-before))
-                     (not (eq ?\] (char-after)))
-                     (progn
-                       (setq str (buffer-substring (1- (point)) end)
-                             pos nil)
-                       (while (setq pos (string-match "\n" str pos))
-                         (setq str (replace-match "" t t str)))
-                       (string-match
-                        "\\`\\[-?[0-9]+\\(\\.-?[0-9]+\\)\\{0,9\\}\\]\\'"
-                        str)))
-            (setq TeX-current-page str
-                  pt nil)
-            (TeX-format-mode-line process)))))))
-
-(defvar TeX-parse-function nil
-  "Function to call to parse content of TeX output buffer.")
-(make-variable-buffer-local 'TeX-parse-function)
-
-(defun TeX-background-filter (_process string)
-  "Filter to process background output."
-  (let ((old-window (selected-window))
-        (pop-up-windows t))
-    (TeX-pop-to-buffer "*TeX background*" nil t)
-    (goto-char (point-max))
-    (insert string)
-    (select-window old-window)))
-
-;; Copy and adaption of `comint-postoutput-scroll-to-bottom' from CVS
-;; Emacs of 2005-04-24.
-(defun TeX-interactive-goto-prompt (string)
-  "Move point to prompt of an interactive TeX run."
-  (let* ((selected (selected-window))
-         (current (current-buffer))
-         (process (get-buffer-process current)))
-    (unwind-protect
-        (when process
-          (walk-windows
-           (lambda (window)
-             (when (eq (window-buffer window) current)
-               (select-window window)
-               (when (and (< (point) (process-mark process))
-                          (string-match "^\\? $" string))
-                 (goto-char (process-mark process)))
-               (select-window selected)))
-           nil t))
-      (set-buffer current))))
-
-
-;;; Active Process
-
-(defvar TeX-current-process-region-p nil
-  "Non-nil means that the last TeX command is on a region.")
-
-(defun TeX-active-process ()
-  "Return the active process for the current buffer."
-  (TeX-process (TeX-active-master)))
-
-(defun TeX-active-buffer ()
-  "Return the buffer of the active process for this buffer."
-  (and TeX-command-buffer
-       (with-current-buffer TeX-command-buffer
-         (TeX-process-buffer (TeX-active-master)))))
-
-(defun TeX-active-master (&optional extension nondirectory _ignore)
-  "The master file currently being compiled.
-
-If optional argument EXTENSION is non-nil, add that file extension to
-the name.  Special value t means use `TeX-default-extension'.
-
-If optional second argument NONDIRECTORY is non-nil, do not include
-the directory.
-
-The compatibility argument IGNORE is ignored."
-  ;; The third argument `_ignore' is kept for symmetry with
-  ;; `TeX-master-file's third argument `ask'.  For example, it's used
-  ;; in `TeX-active-master-with-quotes' for backward compatibility.
-  ;; Keep this in mind should you want to use another argument here.
-  ;; See also the similar comment in `TeX-region-file'.
-  (if TeX-current-process-region-p
-      (TeX-region-file extension nondirectory)
-    (TeX-master-file extension nondirectory)))
-
-(defvar TeX-command-buffer nil
-  "The buffer from where the last TeX command was issued.")
-
-;;; Region File
-
-
-(defvar TeX-region-hook nil
-  "List of hooks to run before the region file is saved.
-The hooks are run in the region buffer, you may use the variable
-`master-buffer' to access the buffer of the master file and
-`orig-buffer' to access the buffer where \\[TeX-command-region] or
-\\[TeX-command-buffer] is invoked from.")
-
-(defun TeX-quote-filename (file)
-  "Convert file name into a form acceptable to TeX."
-  (let (pos)
-    (while (setq pos (string-match "\\\\" file pos))
-      (setq file (replace-match "/" t t file 0)
-            pos (1+ pos)))
-    (while (setq pos (string-match "[~#]" file pos))
-      (setq file (replace-match "\\\\string\\&" t nil file 0)
-            pos (+ pos 8))))
-  ;; Use \unexpanded so that \message outputs the raw file name.
-  ;; When \usepackage[utf8]{inputenc} is used in standard (pdf)latex,
-  ;; \message does not output non-ascii file name in raw form without
-  ;; \unexpanded, which makes AUCTeX to fail to recognize the file
-  ;; names right when analysing the process output buffer.
-  ;; Note that \usepackage[utf8]{inputenc} is enabled by default in
-  ;; standard (pdf)latex since TeXLive 2018.
-  (if (and (memq major-mode '(latex-mode doctex-mode))
-           ;; Japanese upLaTeX requires the same treatment with
-           ;; respect to non-ascii characters other than Japanese, in
-           ;; file names within \message{}.
-           ;; However, pLaTeX (non u- version) does not support
-           ;; non-ascii file name encoded in UTF-8.  So considering
-           ;; `ptex' doesn't make sense here.  We cater for only
-           ;; `default' and `uptex' engines.
-           (memq TeX-engine '(default uptex)))
-      ;; It would fail to put entire `file' inside \unexpanded{} when
-      ;; the above loop injects \string before "#" and "~".  So put
-      ;; only multibyte characters inside \unexpanded{}.
-      ;; It is safe in upLaTeX to use \unexpanded{} on Japanese
-      ;; characters though they are handled by upLaTeX in a totally
-      ;; different way from inputenc.
-      ;; Thus put all multibyte characters, without considering
-      ;; whether they are Japanese or not, inside \unexpanded{}.
-      (replace-regexp-in-string "[[:multibyte:]]+"
-                                "\\\\unexpanded{\\&}" file t)
-    file))
-
-(defvar TeX-region-orig-buffer nil
-  "The original buffer in which the TeX-region was created.")
-(make-variable-buffer-local 'TeX-region-orig-buffer)
-
-(defun TeX-region-create (file region original offset)
-  "Create a new file named FILE with the string REGION.
-The region is taken from ORIGINAL starting at line OFFSET.
-
-The current buffer and master file is searched, in order to ensure
-that the TeX header and trailer information is also included.
-
-The OFFSET is used to provide the debugger with information about the
-original file."
-  (if (fboundp 'preview--skip-preamble-region)
-      (let ((temp (preview--skip-preamble-region region offset)))
-        (if temp
-            ;; Skip preamble for the sake of predumped formats.
-            (setq region (car temp)
-                  offset (cdr temp)))))
-
-  (let* (;; We shift buffer a lot, so we must keep track of the buffer
-         ;; local variables.
-         (header-end TeX-header-end)
-         (trailer-start TeX-trailer-start)
-
-         ;; We seach for header and trailer in the master file.
-         (orig-buffer (current-buffer))
-         (master-name (TeX-master-file TeX-default-extension))
-         (master-buffer (find-file-noselect master-name))
-
-         ;; Attempt to disable font lock.
-         (font-lock-mode-hook nil)
-         ;; And insert them into the FILE buffer.
-         (file-buffer (let (;; Don't query for master file
-                            (TeX-transient-master t)
-                            ;; Don't choose a special mode (and call its hooks)
-                            (auto-mode-alist nil)
-                            (magic-mode-alist nil)
-                            (enable-local-variables nil)
-                            ;; Don't run any f-f hooks
-                            (find-file-hook nil))
-                        (find-file-noselect file t)))
-         ;; But remember original content.
-         original-content
-
-         ;; We search for the header from the master file, if it is
-         ;; not present in the region.
-         (header (if (string-match header-end region)
-                     ""
-                   (save-excursion
-                     (save-restriction
-                       (set-buffer master-buffer)
-                       (save-excursion
-                         (save-restriction
-                           (widen)
-                           (goto-char (point-min))
-                           ;; NOTE: We use the local value of
-                           ;; TeX-header-end from the master file.
-                           (if (not (re-search-forward TeX-header-end nil t))
-                               ""
-                             (re-search-forward "[\r\n]" nil t)
-                             (buffer-substring-no-properties
-                              (point-min) (point)))))))))
-         (header-offset 0)
-         first-line
-         ;; We search for the trailer from the master file, if it is
-         ;; not present in the region.
-         (trailer-offset 0)
-         (trailer (if (string-match trailer-start region)
-                      ""
-                    (save-excursion
-                      (save-restriction
-                        (set-buffer master-buffer)
-                        (save-excursion
-                          (save-restriction
-                            (widen)
-                            (goto-char (point-max))
-                            ;; NOTE: We use the local value of
-                            ;; TeX-trailer-start from the master file.
-                            (if (not (re-search-backward TeX-trailer-start nil 
t))
-                                ""
-                              ;;(beginning-of-line 1)
-                              (re-search-backward "[\r\n]" nil t)
-                              (setq trailer-offset (TeX-current-offset))
-                              (buffer-substring-no-properties
-                               (point) (point-max))))))))))
-    ;; file name should be relative to master
-    (setq original (TeX-quote-filename (file-relative-name
-                                        original (TeX-master-directory)))
-          master-name (TeX-quote-filename master-name))
-
-    ;; If the first line begins with "%&", put that line separately on
-    ;; the very first line of the region file so that the first line
-    ;; parsing will work.
-    (setq first-line (if (and (> (length header) 1)
-                              (string= (substring header 0 2) "%&"))
-                         ;; This would work even if header has no newline.
-                         (substring header 0 (string-match "\n" header))
-                       ""))
-    (unless (string= first-line "")
-      ;; Remove first-line from header.
-      (setq header (substring header (length first-line)))
-      (setq first-line (concat first-line "\n")))
-
-    (with-current-buffer file-buffer
-      (setq buffer-read-only t
-            buffer-undo-list t)
-      (setq original-content (buffer-string))
-      (let ((inhibit-read-only t))
-        (erase-buffer)
-        (setq buffer-file-coding-system
-              (with-current-buffer master-buffer buffer-file-coding-system))
-        (insert first-line
-                "\\message{ !name(" master-name ")}"
-                header
-                TeX-region-extra
-                "\n\\message{ !name(" original ") !offset(")
-        (setq header-offset (- offset
-                               (1+ (TeX-current-offset))))
-        (insert (int-to-string header-offset)
-                ") }\n"
-                region
-                "\n\\message{ !name("  master-name ") !offset(")
-        (insert (int-to-string (- trailer-offset
-                                  (1+ (TeX-current-offset))))
-                ") }\n"
-                trailer)
-        (setq TeX-region-orig-buffer orig-buffer)
-        (run-hooks 'TeX-region-hook)
-        (if (string-equal (buffer-string) original-content)
-            (set-buffer-modified-p nil)
-          (save-buffer 0))))))
-
-(defun TeX-region-file (&optional extension nondirectory _ignore)
-  "Return TeX-region file name with EXTENSION.
-If optional second argument NONDIRECTORY is non-nil, do not include
-the directory.
-
-The compatibility argument IGNORE is ignored."
-  ;; The third argument `_ignore' is kept for symmetry with `TeX-master-file's
-  ;; third argument `ask'.  For example, it's used in `TeX-command-sequence',
-  ;; where we don't know which function has to be called.  Keep this in mind
-  ;; should you want to use another argument here.
-  (let ((master-dir (TeX-master-directory)))
-    (concat (or (TeX--master-output-dir master-dir nondirectory)
-                (if nondirectory "" master-dir))
-            (cond ((eq extension t)
-                   (concat TeX-region "." TeX-default-extension))
-                  (extension
-                   (concat TeX-region "." extension))
-                  (t
-                   TeX-region)))))
-
-(defcustom TeX-region "_region_"
-  "Base name of temporary file for `TeX-command-region' and 
`TeX-command-buffer'."
-  :group 'TeX-command
-  :type 'string)
-
-(defvar LaTeX-command-section-level nil
-  "The section level used for `LaTeX-command-section'.
-Will be initialized to `LaTeX-largest-level' buffer-locally.")
-(make-variable-buffer-local 'LaTeX-command-section-level)
-
-(defun LaTeX-command-section-level ()
-  "Return the value of `LaTeX-command-section-level'.
-Initialize it to `LaTeX-largest-level' if needed."
-  (unless LaTeX-command-section-level
-    (setq LaTeX-command-section-level LaTeX-largest-level))
-  LaTeX-command-section-level)
-
-
-(defun LaTeX-command-section-change-level (arg)
-  "Change `LaTeX-command-section-level' by ARG.
-`LaTeX-command-section-level' is the sectioning level used to
-determine the current section by `LaTeX-command-section'.
-The levels are defined by `LaTeX-section-list'."
-  (interactive "p")
-  (let ((old-level (car (rassoc (list (LaTeX-command-section-level))
-                                LaTeX-section-list))))
-    (setq LaTeX-command-section-level (+ LaTeX-command-section-level arg))
-    (cond
-     ((> LaTeX-command-section-level 6)
-      (setq LaTeX-command-section-level 6)
-      (message "Cannot shrink LaTeX-command-section-level below 
subparagraph."))
-     ((< LaTeX-command-section-level 0)
-      (setq LaTeX-command-section-level 0)
-      (message "Cannot enlarge LaTeX-command-section-level above part."))
-     (t (message "Changed level from %s to %s."
-                 old-level (car (rassoc (list LaTeX-command-section-level)
-                                        LaTeX-section-list)))))))
-
-(defun LaTeX-command-section-boundaries ()
-  "Return the boundaries of the current section as (start . end).
-The section is determined by `LaTeX-command-section-level'."
-  (let* ((case-fold-search nil)
-         (rx (concat "\\\\" (regexp-opt
-                             (mapcar
-                              (lambda (level)
-                                (car (rassoc (list level) LaTeX-section-list)))
-                              (let (r)
-                                (dotimes (i (1+ (LaTeX-command-section-level)))
-                                  (push i r))
-                                r)))
-                     "{")))
-    (cons (save-excursion
-            (re-search-backward rx nil t)
-            (point))
-          (save-excursion
-            (re-search-forward (concat rx "\\|\\\\end{document}") nil t)
-            (forward-line 0)
-            (point)))))
-
-(defun LaTeX-command-section (&optional override-confirm)
-  "Run a command on the current section.
-
-What makes the current section is defined by
-`LaTeX-command-section-level' which can be enlarged or shrunken
-with `LaTeX-command-section-change-level'.
-
-Query the user for a command to run on the temporary file
-specified by the variable `TeX-region'.  The region file will be
-recreated from current section.
-
-If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
-depend on it being positive instead of the entry in
-`TeX-command-list'."
-  (interactive "P")
-  (if (eq major-mode 'latex-mode)
-      (let* ((bounds (LaTeX-command-section-boundaries))
-             (TeX-command-region-begin (car bounds))
-             (TeX-command-region-end (cdr bounds)))
-        (TeX-command-region override-confirm))
-    (error "LaTeX-command-section can only be run on LaTeX documents")))
-
-(defun TeX-command-run-all-region ()
-  "Compile the current region until an error occurs or it is finished."
-  (interactive)
-  (TeX-region-update)
-  (TeX-command-sequence t t #'TeX-region-file))
-
-(defun LaTeX-command-run-all-section ()
-  "Compile the current section until an error occurs or it is finished."
-  (interactive)
-  (if (eq major-mode 'latex-mode)
-      (let* ((bounds (LaTeX-command-section-boundaries))
-             (TeX-command-region-begin (car bounds))
-             (TeX-command-region-end (cdr bounds)))
-        (TeX-region-update)
-        (TeX-command-sequence t t #'TeX-region-file))
-    (error "LaTeX-command-run-all-section can only be run on LaTeX 
documents")))
-
-(defun TeX-command-run-all (arg)
-  "Compile the current document until an error occurs or it is finished.
-With a prefix ARG (`\\[universal-argument] \\[TeX-command-run-all]'),
-compile the current region instead, that is, call
-`TeX-command-run-all-region'.  With multiple prefix
-arguments (`\\[universal-argument] \\[universal-argument] 
\\[TeX-command-run-all]'),
-compile the current section instead, that is, call
-`LaTeX-command-run-all-section'."
-  (interactive "P")
-  (cond
-   ((null arg)       (TeX-command-sequence t t))
-   ((= 4 (car arg))  (TeX-command-run-all-region))
-   (t                (LaTeX-command-run-all-section))))
-
-;;; Parsing
-
-;;; - Global Parser Variables
-
-(defvar TeX-error-point nil
-  "How far we have parsed until now.")
-
-(make-variable-buffer-local 'TeX-error-point)
-
-(defvar TeX-error-file nil
-  "Stack of files in which errors have occurred.")
-
-(make-variable-buffer-local 'TeX-error-file)
-
-(defvar TeX-error-offset nil
-  "Add this to any line numbers from TeX.  Stack like `TeX-error-file'.")
-
-(make-variable-buffer-local 'TeX-error-offset)
-
-(defun TeX-parse-reset (&optional reparse)
-  "Reset all variables used for parsing TeX output.
-If optional argument REPARSE is non-nil, reparse the output log."
-  (setq TeX-error-point (point-min)
-        TeX-error-offset nil
-        TeX-error-file nil
-        TeX-error-list nil
-        TeX-error-last-visited -1)
-  (if reparse
-      (TeX-parse-all-errors)))
-
-;;; - Parsers Hooks
-
-;; All this parsers hooks should have the same arguments even though they will
-;; be ignored, because `TeX-next-error' can call any of these functions.
-(defun TeX-parse-command (_arg _reparse)
-  "We can't parse anything but TeX."
-  (error "I cannot parse %s output, sorry"
-         (if (TeX-active-process)
-             (process-name (TeX-active-process))
-           "this")))
-
-(defun TeX-error-list-skip-warning-p (type ignore)
-  "Decide if a warning of `TeX-error-list' should be skipped.
-
-TYPE is one of the types listed in `TeX-error-list', IGNORE
-is the flag to choose if the warning should be skipped."
-  ;; The warning should be skipped if it...
-  (or
-   ;; ...is a warning and we want to ignore all warnings, or...
-   (and (null TeX-debug-warnings)
-        (equal type 'warning))
-   ;; ...is a bad-box and we want to ignore all bad-boxes, or...
-   (and (null TeX-debug-bad-boxes)
-        (equal type 'bad-box))
-   ;; ...is a warning to be ignored.
-   (and TeX-suppress-ignored-warnings
-        ignore)))
-
-(defun TeX-parse-TeX (arg reparse)
-  "Find the next error produced by running TeX.
-
-ARG specifies how many error messages to move, when possible;
-negative means move back to previous error messages.
-
-If REPARSE is non-nil, reparse the output log.
-
-If the file occurs in an included file, the file is loaded (if not
-already in an Emacs buffer) and the cursor is placed at the error."
-  (let ((old-buffer (current-buffer))
-        max-index item)
-
-    ;; Switch to the output buffer.
-    (with-current-buffer (TeX-active-buffer)
-      (if reparse
-          (TeX-parse-reset reparse))
-      (if TeX-parse-all-errors
-          (progn
-            (setq arg (or arg 1)
-                  max-index (length TeX-error-list))
-            ;; This loop is needed to skip ignored warnings, when
-            ;; `TeX-suppress-ignored-warnings' is non-nil and there are ignore
-            ;; warnings.
-            (while (null (zerop arg))
-              (setq TeX-error-last-visited
-                    ;; Increase or decrese `TeX-error-last-visited' depending 
on
-                    ;; the sign of `arg'.  Note: `signum' is a function from
-                    ;; `cl' library, do not be tempted to use it.
-                    (if (> arg 0)
-                        (1+ TeX-error-last-visited)
-                      (1- TeX-error-last-visited))
-                    item (nth TeX-error-last-visited TeX-error-list))
-              ;; Increase or decrease `arg' only if the warning isn't to be
-              ;; skipped.
-              (unless (TeX-error-list-skip-warning-p (nth 0 item) (nth 10 
item))
-                ;; Note: `signum' is a function from `cl' library, do not be
-                ;; tempted to use it.
-                (setq arg (if (> arg 0)
-                              (1- arg)
-                            (1+ arg)))))
-            (if (< TeX-error-last-visited -1)
-                (setq TeX-error-last-visited -1))
-            (cond ((or (null item)
-                       (< TeX-error-last-visited 0))
-                   (if (> TeX-error-last-visited max-index)
-                       (setq TeX-error-last-visited max-index))
-                   (message "No more errors.")
-                   (beep)
-                   (TeX-pop-to-buffer old-buffer))
-                  (t
-                   (apply #'TeX-find-display-help item))))
-
-        (goto-char TeX-error-point)
-        (TeX-parse-error old-buffer)))))
-
-;;; - Parsing (La)TeX
-
-(defvar TeX-translate-location-file nil)
-(defvar TeX-translate-location-offset nil)
-(defvar TeX-translate-location-line nil)
-(defvar TeX-translate-location-string nil)
-(defvar TeX-translate-location-error nil)
-(defvar TeX-translate-location-context nil)
-
-(defvar TeX-translate-location-hook nil
-  "List of functions to be called before showing an error or warning.
-
-You might want to examine and modify the dynamically bound
-variables
-  `TeX-translate-location-file',
-  `TeX-translate-location-offset',
-  `TeX-translate-location-line',
-  `TeX-translate-location-string',
-  `TeX-translate-location-error', and
-  `TeX-translate-location-context'
-from this hook.")
-
-;; `ignore' flag should be the always the last one in the list of information
-;; for each error/warning, because it can be set within `TeX-warning' by a
-;; custom function taking as argument all information present in
-;; `TeX-error-list' but `ignore', see `TeX-ignore-warnings'.
-(defvar TeX-error-list nil
-  "List of warnings and errors.
-
-Each element of the list is a list of information for a specific
-error or warning.  This is the structure of each element:
- *  0: type (error, warning, bad-box)
- *  1: file
- *  2: line
- *  3: message of the error or warning
- *  4: offset
- *  5: context, to be displayed in the help window
- *  6: string to search in the buffer, in order to find location
-       of the error or warning
- *  7: for warnings referring to multiple lines (for exapmle, bad boxes),
-       the last line mentioned in the warning message
- *  8: t if it is a bad-box, nil otherwise
- *  9: value of `TeX-error-point'
- * 10: whether the warning should be ignored
-
-This variable is intended to be set only in output buffer so it
-will be shared among all files of the same document.")
-(make-variable-buffer-local 'TeX-error-list)
-
-(defun TeX-parse-all-errors ()
-  "Parse TeX output buffer to collect all warnings and errors."
-  ;; Reset error list.
-  (setq TeX-error-list nil)
-  (save-excursion
-    (goto-char (point-min))
-    (while (TeX-parse-error nil t)))
-  ;; Reset last visited error.
-  (setq TeX-error-last-visited -1))
-
-(defun TeX-parse-error (old &optional store)
-  "Goto next error.  Pop to OLD buffer if no more errors are found.
-
-If the optional argument STORE is non-nil, the function will
-store the found warning or error in `TeX-error-list' instead of
-displaying the issue.
-
-Return non-nil if an error or warning is found."
-  (let ((regexp
-         (concat
-          ;; TeX error
-          "^\\(!\\|\\(.*?\\):[0-9]+:\\) \\|"
-          ;; New file
-          "(\n?\\([^\n()]+\\)\\|"
-          ;; End of file.
-          "\\()\\)\\|"
-          ;; Hook to change line numbers
-          " !\\(?:offset(\\([---0-9]+\\))\\|"
-          ;; Hook to change file name
-          "name(\\([^)]+\\))\\)\\|"
-          ;; Start of LaTeX bad box
-          "^\\(\\(?:Overfull\\|Underfull\\|Tight\\|Loose\\) "
-          ;;   Horizontal bad box
-          "\\(?:\\\\hbox.* at lines? [0-9]+\\(?:--[0-9]+\\)?$\\|"
-          ;;   Vertical bad box.  See also `TeX-warning'.
-          "\\\\vbox ([ a-z0-9]+) has occurred while \\\\output is active 
\\[[^]]+\\]\\)\\)\\|"
-          ;; LaTeX warning
-          "^\\(" LaTeX-warnings-regexp ".*\\)"))
-        (error-found nil))
-    (while
-        (cond
-         ((null
-           (re-search-forward regexp nil t))
-          ;; No more errors.
-          (unless store
-            (message "No more errors.")
-            (beep)
-            (TeX-pop-to-buffer old))
-          nil)
-         ;; TeX error
-         ((match-beginning 1)
-          (when (match-beginning 2)
-            (unless TeX-error-file
-              (push nil TeX-error-file)
-              (push nil TeX-error-offset))
-            (unless (car TeX-error-offset)
-              (rplaca TeX-error-file (TeX-match-buffer 2))))
-          (setq error-found t)
-          (if (looking-at "Preview ")
-              t
-            (TeX-error store)
-            nil))
-         ;; LaTeX bad box
-         ((match-beginning 7)
-          ;; In `TeX-error-list' we collect all warnings, also if they're going
-          ;; to be actually skipped.
-          (if (or store TeX-debug-bad-boxes)
-              (progn
-                (setq error-found t)
-                (TeX-warning (TeX-match-buffer 7) (match-beginning 7) t store)
-                nil)
-            (re-search-forward "\r?\n\
-\\(?:.\\{79\\}\r?\n\
-\\)*.*\r?$")
-            t))
-         ;; LaTeX warning
-         ((match-beginning 8)
-          ;; In `TeX-error-list' we collect all warnings, also if they're going
-          ;; to be actually skipped.
-          (if (or store TeX-debug-warnings)
-              (progn
-                (setq error-found t)
-                (TeX-warning (TeX-match-buffer 8) (match-beginning 8) nil 
store)
-                nil)
-            t))
-
-         ;; New file -- Push on stack
-         ((match-beginning 3)
-          (let ((file (TeX-match-buffer 3))
-                (end (match-end 3)))
-            ;; Strip quotation marks and remove newlines if necessary
-            (when (or (eq (string-to-char file) ?\")
-                      (string-match "[ \t\n]" file))
-              (setq file (mapconcat #'identity (split-string file "[\"\n]+") 
"")))
-            ;; Polish `file' string
-            (setq file
-                  (let ((string file))
-                    (setq string
-                          (if (string-match "\\`[ \t\n\r]+" string)
-                              (replace-match "" t t string)
-                            string))
-                    ;; Sometimes `file' is something like
-                    ;;     "./path/to/file.tex [9] [10 <./path/to/file>] "
-                    ;; where "[9]" and "[10 <./path/to/file>]" are pages of the
-                    ;; output file, with path to an included file.  Remove 
these
-                    ;; numbers together with whitespaces at the end of the
-                    ;; string.
-                    (if (string-match "\\( *\\(\\[[^]]+\\]\\)? *\\)*\\'" 
string)
-                        (replace-match "" t t string)
-                      string)))
-            (push file TeX-error-file)
-            (push nil TeX-error-offset)
-            (goto-char end))
-          t)
-
-         ;; End of file -- Pop from stack
-         ((match-beginning 4)
-          (when (> (length TeX-error-file) 0)
-            (pop TeX-error-file)
-            (pop TeX-error-offset))
-          (goto-char (match-end 4))
-          t)
-
-         ;; Hook to change line numbers
-         ((match-beginning 5)
-          (setq TeX-error-offset
-                (list (string-to-number (TeX-match-buffer 5))))
-          t)
-
-         ;; Hook to change file name
-         ((match-beginning 6)
-          (setq TeX-error-file
-                (list (TeX-match-buffer 6)))
-          t)))
-    error-found))
-
-(defun TeX-find-display-help (type file line error offset context string
-                                   line-end _bad-box error-point _ignore)
-  "Find the error and display the help.
-
-For a description of arguments, see `TeX-error-list'.  IGNORE
-value is not used here."
-  ;; Go back to TeX-buffer
-  (let ((runbuf (TeX-active-buffer))
-        (master (with-current-buffer TeX-command-buffer
-                  (expand-file-name (TeX-master-file))))
-        (command-buffer TeX-command-buffer)
-        (TeX-translate-location-file file)
-        (TeX-translate-location-line line)
-        (TeX-translate-location-error error)
-        (TeX-translate-location-offset offset)
-        (TeX-translate-location-context context)
-        (TeX-translate-location-string string)
-        error-file-buffer start)
-
-    (run-hooks 'TeX-translate-location-hook)
-
-    (if TeX-translate-location-file
-        (progn
-          (setq error-file-buffer
-                (find-file
-                 (expand-file-name TeX-translate-location-file
-                                   (file-name-directory master))))
-          ;; Use the major mode of `TeX-command-buffer' when visiting
-          ;; the error point.
-          (if (eq major-mode (default-value 'major-mode))
-              (funcall (buffer-local-value 'major-mode command-buffer)))
-          ;; Set the value of `TeX-command-buffer' in the next file
-          ;; with an error to be displayed to the value it has in the
-          ;; current buffer.
-          (setq-local TeX-command-buffer command-buffer)
-
-          ;; Find the location of the error or warning.
-          (when TeX-translate-location-line
-            (goto-char (point-min))
-            (forward-line (+ TeX-translate-location-offset
-                             TeX-translate-location-line -1))
-            (cond
-             ;; Error.
-             ((equal type 'error)
-              (if (not (string= TeX-translate-location-string " "))
-                  (search-forward TeX-translate-location-string nil t)))
-             ;; Warning or bad box.
-             (t
-              (beginning-of-line 0)
-              (setq start (point))
-              (goto-char (point-min))
-              (forward-line (+ TeX-translate-location-offset
-                               line-end -1))
-              (end-of-line)
-              (when TeX-translate-location-string
-                (search-backward TeX-translate-location-string start t)
-                (search-forward TeX-translate-location-string nil t))))))
-      ;; When the file cannot be determined stay here but issue a
-      ;; warning.
-      (message "Could not determine file for %s"
-               (if (eq type 'error) "error" "warning"))
-      (beep))
-
-    ;; Display the help.
-    (cond ((eq TeX-display-help 'expert)
-           (TeX-pop-to-buffer runbuf nil t)
-           (goto-char error-point)
-           (if error-file-buffer
-               (TeX-pop-to-buffer error-file-buffer nil t)))
-          (TeX-display-help
-           (TeX-help-error
-            TeX-translate-location-error
-            (if (equal type 'warning)
-                (concat "\n" TeX-translate-location-context)
-              TeX-translate-location-context)
-            runbuf type))
-          (t
-           (message "! %s" TeX-translate-location-error)))))
-
-(defun TeX-error (&optional store)
-  "Display an error.
-
-If optional argument STORE is non-nil, store the error
-information in `TeX-error-list' instead of displaying the error."
-
-  (let* ( ;; We need the error message to show the user.
-         (error (progn
-                  (re-search-forward "\\(.*\\)")
-                  (TeX-match-buffer 1)))
-
-         ;; And the context for the help window.
-         (context-start (point))
-         context-available
-
-         ;; And the line number to position the cursor.
-         (line (cond
-                ;; regular style
-                ((re-search-forward "l\\.\\([0-9]+\\)" nil t)
-                 (setq context-available t)
-                 (string-to-number (TeX-match-buffer 1)))
-                ;; file:line:error style
-                ((save-excursion
-                   (re-search-backward ":\\([0-9]+\\): "
-                                       (line-beginning-position) t))
-                 (string-to-number (TeX-match-buffer 1)))
-                ;; nothing found
-                (t 1)))
-
-         ;; And a string of the context to search for.
-         (string (progn
-                   (beginning-of-line)
-                   (re-search-forward " \\(\\([^ \t]*$\\)\\|\\($\\)\\)")
-                   (TeX-match-buffer 1)))
-
-         ;; And we have now found to the end of the context.
-         (context (if context-available
-                      (buffer-substring context-start (progn (forward-line 1)
-                                                             (end-of-line)
-                                                             (point)))
-                    ;; There is no real context available, so we
-                    ;; simply show the line with the error message.
-                    (buffer-substring (1- (line-beginning-position))
-                                      context-start)))
-         ;; We may use these in another buffer.
-         (offset (or (car TeX-error-offset) 0))
-         (file (car TeX-error-file))
-         info-list)
-
-    ;; Remember where we was.
-    (setq TeX-error-point (point)
-          info-list (list 'error file line error offset context string nil nil
-                          TeX-error-point nil))
-    (if store
-        ;; Store the error information.
-        (add-to-list 'TeX-error-list info-list t)
-      ;; Find the error point and display the help.
-      (apply #'TeX-find-display-help info-list))))
-
-(defun TeX-warning (warning warning-start bad-box &optional store)
-  "Display a warning for WARNING.
-
-WARNING-START is the position where WARNING starts.  If BAD-BOX
-is non-nil, the warning refers to a bad-box, otherwise it is a
-generic warning.
-
-If optional argument STORE is non-nil, store the warning
-information in `TeX-error-list' instead of displaying the
-warning."
-
-  (let* ( ;; line-string: match 1 is beginning line, match 2 is end line
-         (line-string (if bad-box
-                          "at lines? \\([0-9]*\\)\\(?:--\\([0-9]*\\)\\)?"
-                        ;; Traditional messages say "on input line X",
-                        ;; the LaTeX3 \msg_line_context:. just reads
-                        ;; "on line X".
-                        "on \\(?:input \\)?line \\([0-9]*\\)\\."))
-         ;; word-string: match 1 is the word
-         (word-string (if bad-box "[][\\W() ---]\\(\\w+\\)[][\\W() ---]*$"
-                        ;; Match "ref" in both "Reference `ref' on page NN
-                        ;; undefined" and "Citation 'ref' on page NN 
undefined".
-                        "\\(?:`\\|'\\)\\([-a-zA-Z0-9:]+\\)'"))
-
-         ;; Get error-line (warning).  Don't search before `warning-start' to
-         ;; avoid catching completely unrelated line numbers.
-         (line (when (save-excursion (re-search-backward line-string
-                                                         warning-start t))
-                 (string-to-number (TeX-match-buffer 1))))
-         ;; If this is a bad box and the warning ends with "...at lines MM--NN"
-         ;; we can use "NN" as `line-end', in any other case (including bad
-         ;; boxes ending with "...at line NN") just use `line'.
-         (line-end (if (and bad-box (match-beginning 2))
-                       (string-to-number (TeX-match-buffer 2))
-                     line))
-
-         ;; Find the context
-         (context-start (progn (cond
-                                ((and bad-box (string-match "\\\\hbox" 
warning))
-                                 ;; Horizontal bad box
-                                 (end-of-line))
-                                (bad-box
-                                 ;; Vertical bad box (by exclusion), don't move
-                                 ;; point.  In the output buffer, unlike in the
-                                 ;; actual *.log file, these warnings do not 
end
-                                 ;; with "...is active []", but in the same 
line
-                                 ;; there may be something else, including a 
new
-                                 ;; file opened.  Thus, point shouldn't move
-                                 ;; from the end of the actual bad box warning.
-                                 ;; This is why the corresponding regexp in
-                                 ;; `TeX-parse-error' doesn't match everything
-                                 ;; until the end of the line.
-                                 nil)
-                                (t
-                                 ;; Generic warning.
-                                 (beginning-of-line)))
-                               (point)))
-
-         (context (cond ((string-match LaTeX-warnings-regexp warning)
-                         ;; The warnings matching `LaTeX-warnings-regexp' are
-                         ;; emitted by \GenericWarning macro, or macros based 
on
-                         ;; it (\ClassWarning, \PackageWarning, etc).  After
-                         ;; such warnings there is an empty line, just look for
-                         ;; it to find the end.
-                         (beginning-of-line)
-                         (while (null (eolp))
-                           (forward-line 1))
-                         (buffer-substring context-start (progn (end-of-line)
-                                                                (point))))
-
-                        ((and bad-box (string-match "\\\\vbox" warning))
-                         ;; Vertical bad boxes don't provide any additional
-                         ;; information.  In this case, reuse the `warning' as
-                         ;; `context' and don't move point, so that we avoid
-                         ;; eating the next line that may contain another
-                         ;; warning.  See also comment for `context-start'.
-                         (concat "\n" warning))
-
-                        (t
-                         ;; Horizontal bad boxes.
-                         (forward-line 1)
-                         (end-of-line)
-                         (while (equal (current-column) 79)
-                           (forward-line 1)
-                           (end-of-line))
-                         (buffer-substring context-start (point)))))
-
-         ;; This is where we want to be.
-         (error-point (point))
-
-         ;; Now find the error word.
-         (string (when (save-excursion
-                         (re-search-backward word-string context-start t))
-                   (TeX-match-buffer 1)))
-
-         ;; We might use these in another file.
-         (offset (or (car TeX-error-offset) 0))
-         (file (car TeX-error-file))
-         info-list ignore)
-
-    ;; Second chance to get line number right.  If `line' is nil, check whether
-    ;; the reference to the line number is in `context'.  For example, this is
-    ;; the case for warnings emitted with \ClassWarning and \PackageWarning.
-    ;; XXX: maybe it suffices to evaluate `line' after `context' above, but I
-    ;; don't know if there are cases in which it's important to get `line'
-    ;; before `context'.
-    (and (null line)
-         (string-match line-string context)
-         (setq line-end
-               (setq line (and (match-beginning 1)
-                               (string-to-number (match-string 1 context))))))
-
-    ;; This is where we start next time.
-    (goto-char error-point)
-    (setq TeX-error-point (point))
-
-    ;; Explanation of what follows: we add the warning to `TeX-error-list' even
-    ;; if it has to be ignored, with a flag specifying whether it is ignored.
-    ;; We do so in order to be able to change between "ignore" and 
"dont-ignore"
-    ;; behavior by just looking to the flag, without the need to reparse the
-    ;; output log.
-
-    ;; Store the list of information about the warning.
-    (setq info-list (list (if bad-box 'bad-box 'warning) file line warning
-                          offset context string line-end bad-box
-                          TeX-error-point)
-          ;; Decide whether it should be ignored.
-          ignore (and TeX-ignore-warnings
-                      (cond
-                       ((stringp TeX-ignore-warnings)
-                        (string-match TeX-ignore-warnings warning))
-                       ((fboundp TeX-ignore-warnings)
-                        (apply TeX-ignore-warnings info-list))))
-          ;; Update `info-list'.
-          info-list (append info-list (list ignore)))
-
-    (if store
-        ;; Store the warning information.
-        (add-to-list 'TeX-error-list info-list t)
-      ;; Find the warning point and display the help.
-      (apply #'TeX-find-display-help info-list))))
-
-;;; Error Messages
-
-(defcustom TeX-error-description-list nil
-  "User defined help messages for errors in TeX run.
-See `TeX-error-description-list-local' for its format.  All
-entries have higher priority than those in
-`TeX-error-description-list-local'.
-It must not have a fallback entry that matches any error."
-  :group 'TeX-output
-  :type '(repeat (cons :tag "Entry"
-                       (regexp :tag "Match")
-                       (string :format "Description:\n%v"))))
-
-(defvar TeX-error-description-list-local
-  '((".*" . "No help available"))
-  "Buffer local help messages for errors in TeX run.
-A list of the form (ERR-REGEXP . CONTEXT) used by function
-`TeX-help-error' to display help-text on an error message or warning.
-ERR-REGEXP should be a regular expression matching the error message
-given from TeX/LaTeX, and CONTEXT should be some lines describing that
-error.
-Major modes of AUCTeX can set its own catalogue as buffer local
-value of this variable, as LaTeX mode does.
-Style files of AUCTeX can also add their own entries to buffer local
-value of this variable to provide their own help messages.
-It must end with a fallback entry that matches any error, for example
-\(\".*\" . \"No help available\")")
-
-;;; - Help
-
-(defgroup TeX-error-description-faces nil
-  "Faces used in error descriptions."
-  :prefix "TeX-error-description-"
-  :group 'TeX-output)
-
-(defface TeX-error-description-error
-  ;; This is the same as `error' face in latest GNU Emacs versions.
-  '((((class color) (min-colors 88) (background light))
-     :foreground "Red1" :weight bold)
-    (((class color) (min-colors 88) (background dark))
-     :foreground "Pink" :weight bold)
-    (((class color) (min-colors 16) (background light))
-     :foreground "Red1" :weight bold)
-    (((class color) (min-colors 16) (background dark))
-     :foreground "Pink" :weight bold)
-    (((class color) (min-colors 8))
-     :foreground "red" :weight bold)
-    (t (:inverse-video t :weight bold)))
-  "Face for \"Error\" string in error descriptions.")
-
-(defface TeX-error-description-warning
-  ;; This is the same as `warning' face in latest GNU Emacs versions.
-  '((((class color) (min-colors 16)) :foreground "DarkOrange" :weight bold)
-    (((class color)) :foreground "yellow" :weight bold))
-  "Face for \"Warning\" string in error descriptions.")
-
-(defface TeX-error-description-tex-said
-  ;; This is the same as `font-lock-function-name-face' face in latest GNU
-  ;; Emacs versions.
-  '((((class color) (min-colors 88) (background light))
-     :foreground "Blue1")
-    (((class color) (min-colors 88) (background dark))
-     :foreground "LightSkyBlue")
-    (((class color) (min-colors 16) (background light))
-     :foreground "Blue")
-    (((class color) (min-colors 16) (background dark))
-     :foreground "LightSkyBlue")
-    (((class color) (min-colors 8))
-     :foreground "blue" :weight bold)
-    (t (:inverse-video t :weight bold)))
-  "Face for \"TeX said\" string in error descriptions.")
-
-(defface TeX-error-description-help
-  '((t (:inherit TeX-error-description-tex-said)))
-  "Face for \"Help\" string in error descriptions.")
-
-(defun TeX-help-error (error output runbuffer type)
-  "Print ERROR in context OUTPUT from RUNBUFFER in another window.
-TYPE is a symbol specifing if ERROR is a real error, a warning or
-a bad box."
-
-  (let ((old-buffer (current-buffer))
-        (log-file (with-current-buffer runbuffer
-                    (with-current-buffer TeX-command-buffer
-                      (expand-file-name (TeX-active-master "log")))))
-        (error-description-list
-         (append TeX-error-description-list
-                 (buffer-local-value 'TeX-error-description-list-local
-                                     (buffer-local-value
-                                      'TeX-command-buffer
-                                      runbuffer))))
-        (TeX-error-pointer 0))
-
-    ;; Find help text entry.
-    (while (not (string-match (car (nth TeX-error-pointer
-                                        error-description-list))
-                              error))
-      (setq TeX-error-pointer (+ TeX-error-pointer 1)))
-
-    (TeX-pop-to-buffer (get-buffer-create "*TeX Help*") nil t)
-    (let ((inhibit-read-only t))
-      (erase-buffer)
-      (insert
-       (cond
-        ((equal type 'error)
-         (propertize "ERROR" 'font-lock-face 'TeX-error-description-error))
-        ((equal type 'warning)
-         (propertize "WARNING" 'font-lock-face 'TeX-error-description-warning))
-        ((equal type 'bad-box)
-         (propertize "BAD BOX" 'font-lock-face 
'TeX-error-description-warning)))
-       ": " error
-       (propertize "\n\n--- TeX said ---" 'font-lock-face
-                   'TeX-error-description-tex-said)
-       output
-       (propertize "\n--- HELP ---\n" 'font-lock-face
-                   'TeX-error-description-help)
-       (let ((help (cdr (nth TeX-error-pointer
-                             error-description-list))))
-         (save-excursion
-           (if (and (= (1+ TeX-error-pointer)
-                       (length error-description-list))
-                    (let* ((log-buffer (find-buffer-visiting log-file)))
-                      (if log-buffer
-                          (progn
-                            (set-buffer log-buffer)
-                            (revert-buffer t t))
-                        (setq log-buffer
-                              (find-file-noselect log-file))
-                        (set-buffer log-buffer))
-                      (auto-save-mode nil)
-                      (setq buffer-read-only t)
-                      (goto-char (point-min))
-                      (search-forward error nil t 1))
-                    (re-search-forward "^l\\." nil t)
-                    (re-search-forward "^ [^\n]+$" nil t))
-               (let ((start (1+ (point))))
-                 (forward-char 1)
-                 (re-search-forward "^$")
-                 (concat "From the .log file...\n\n"
-                         (buffer-substring start (point))))
-             help)))))
-    (goto-char (point-min))
-    (TeX-special-mode)
-    (TeX-pop-to-buffer old-buffer nil t)))
-
-;;; Error Overview
-
-(defvar TeX-error-overview-active-buffer nil
-  "The active buffer for the current error overview.")
-
-(defvar TeX-error-overview-orig-frame nil
-  "Frame from which the error overview has been launched.")
-
-(defvar TeX-error-overview-orig-window nil
-  "Window from which the error overview has been launched.")
-
-(defcustom TeX-error-overview-setup nil
-  "The frame setup of the error overview.
-
-The possible value is: `separate-frame' (error oveview in a
-separate frame); with a nil value the current frame is used.
-
-If the display does not support multi frame, the current frame
-will be used regardless of the value of this variable."
-  :group 'TeX-output
-  :type '(choice
-          (const :tag "Error overview in separate frame" separate-frame)
-          (const :tag "Use current frame" nil)))
-
-(defun TeX-error-overview-setup ()
-  "Return the frame setup of the error overview for the current display."
-  (and (display-multi-frame-p) TeX-error-overview-setup))
-
-(defun TeX-error-overview-goto-source (&optional button)
-  "Go to the error point in the source.
-If optional argument BUTTON is non-nil, go to source associated
-to the selected error."
-  (interactive)
-  (let ((index (if button (button-get button 'id) (tabulated-list-get-id)))
-        item window)
-    (if index
-        (progn
-          ;; Select the source frame/window, if still live.
-          (if (TeX-error-overview-setup)
-              (if (frame-live-p TeX-error-overview-orig-frame)
-                  (select-frame TeX-error-overview-orig-frame)
-                (error "You have deleted a vital frame---\
-please restart TeX error overview"))
-            (if (window-live-p TeX-error-overview-orig-window)
-                (select-window TeX-error-overview-orig-window)
-              (error "You have deleted a vital window---\
-please restart TeX error overview")))
-          ;; Get the error details.
-          (with-current-buffer TeX-error-overview-active-buffer
-            (setq item (nth index TeX-error-list)
-                  TeX-error-last-visited index))
-          ;; Find the error and display the help.
-          (with-current-buffer TeX-command-buffer
-            ;; Find the error and display the help.
-            (apply #'TeX-find-display-help item))
-          ;; Return to the error overview.
-          (if (TeX-error-overview-setup)
-              (select-frame TeX-error-overview-frame)
-            (if (setq window
-                      (get-buffer-window TeX-error-overview-buffer-name))
-                ;; If error overview window is visible just select it.
-                (select-window window)
-              ;; Otherwise, split the help window and display the error 
overview
-              ;; near to it.  This should be the only reason for the error
-              ;; overview window not being still visible after the beginning of
-              ;; the function.
-              (select-window
-               (get-buffer-window (cond
-                                   ((eq TeX-display-help 'expert)
-                                    TeX-error-overview-active-buffer)
-                                   (TeX-display-help  "*TeX Help*"))))
-              (if (window-splittable-p (selected-window) t)
-                  (split-window-horizontally)
-                (split-window-vertically))
-              (switch-to-buffer TeX-error-overview-buffer-name))))
-      (message "No more errors.")
-      (beep))))
-
-(defun TeX-error-overview-make-entries (&optional master-dir active-buffer)
-  "Generate the list of errors to be printed using `tabulated-list-entries'.
-Write file names relative to MASTER-DIR when they are not absolute.
-
-ACTIVE-BUFFER is used as buffer from which to extract the list of
-errors.  If nil, defaults to `TeX-error-overview-active-buffer'."
-  (with-current-buffer (or active-buffer TeX-error-overview-active-buffer)
-    (let ((id 0)
-          type file line msg entries)
-      (mapc
-       (lambda (entry)
-         (setq type (nth 0 entry)
-               file (nth 1 entry)
-               line (nth 2 entry)
-               msg  (nth 3 entry))
-         ;; Add the entry only if it isn't to be skipped.
-         (unless (TeX-error-list-skip-warning-p type (nth 10 entry))
-           (push
-            (list
-             ;; ID.
-             id
-             (vector
-              ;; File.
-              (if (stringp file)
-                  (if (file-name-absolute-p file)
-                      file
-                    (file-relative-name file master-dir))
-                "")
-              ;; Line.
-              (if (numberp line)
-                  (number-to-string line)
-                "")
-              ;; Type.
-              (cond
-               ((equal type 'error)
-                (propertize "Error" 'font-lock-face 
'TeX-error-description-error))
-               ((equal type 'warning)
-                (propertize "Warning" 'font-lock-face
-                            'TeX-error-description-warning))
-               ((equal type 'bad-box)
-                (propertize "Bad box" 'font-lock-face
-                            'TeX-error-description-warning))
-               (t
-                ""))
-              ;; Message.
-              (list (if (stringp msg)
-                        ;; Sometimes, the message can be longer than one line,
-                        ;; but print here only the first one.
-                        (progn
-                          (string-match "^.*" msg)
-                          (match-string 0 msg))
-                      "")
-                    'face 'link
-                    'follow-link t
-                    'id id
-                    'action #'TeX-error-overview-goto-source)))
-            entries))
-         ;; Increase the `id' counter in any case.
-         (setq id (1+ id)))
-       TeX-error-list)
-      (reverse entries))))
-
-(defun TeX-error-overview-next-error (&optional arg)
-  "Move to the next line and find the associated error.
-
-A prefix ARG specifies how many error messages to move; negative
-means move back to previous error messages."
-  (interactive "p")
-  (if (= (forward-line arg) 0)
-      (TeX-error-overview-goto-source)
-    ;; If there are lines left to move we are at the beginning or at the end of
-    ;; the buffer and there are no more errors.
-    (message "No more errors.")
-    (beep)))
-
-(defun TeX-error-overview-previous-error (&optional arg)
-  "Move to the previous line and find the associated error.
-
-Prefix ARG says how many error messages to move backward (or
-forward, if negative)."
-  (interactive "p")
-  (TeX-error-overview-next-error (- arg)))
-
-(defun TeX-error-overview-jump-to-source ()
-  "Display the help and move point to the error source."
-  (interactive)
-  (TeX-error-overview-goto-source)
-  (pop-to-buffer
-   (save-window-excursion
-     (select-window TeX-error-overview-orig-window)
-     (current-buffer))))
-
-(defun TeX-error-overview-goto-log ()
-  "Display the current error in log buffer."
-  (interactive)
-  (let ((TeX-display-help 'expert))
-    (TeX-error-overview-goto-source)))
-
-(defun TeX-error-overview-toggle-debug-bad-boxes ()
-  "Run `TeX-toggle-debug-bad-boxes' and update entries list."
-  (interactive)
-  (TeX-toggle-debug-bad-boxes)
-  (setq tabulated-list-entries
-        (TeX-error-overview-make-entries
-         (with-current-buffer TeX-command-buffer (TeX-master-directory))))
-  (tabulated-list-init-header)
-  (tabulated-list-print))
-
-(defun TeX-error-overview-toggle-debug-warnings ()
-  "Run `TeX-toggle-debug-warnings' and update entries list."
-  (interactive)
-  (TeX-toggle-debug-warnings)
-  (setq tabulated-list-entries
-        (TeX-error-overview-make-entries
-         (with-current-buffer TeX-command-buffer (TeX-master-directory))))
-  (tabulated-list-init-header)
-  (tabulated-list-print))
-
-(defun TeX-error-overview-toggle-suppress-ignored-warnings ()
-  "Toggle visibility of ignored warnings and update entries list."
-  (interactive)
-  (TeX-toggle-suppress-ignored-warnings)
-  (setq tabulated-list-entries
-        (TeX-error-overview-make-entries
-         (with-current-buffer TeX-command-buffer (TeX-master-directory))))
-  (tabulated-list-init-header)
-  (tabulated-list-print))
-
-(defun TeX-error-overview-quit ()
-  "Delete the window or the frame of the error overview."
-  (interactive)
-  (if (TeX-error-overview-setup)
-      (delete-frame TeX-error-overview-frame)
-    (delete-window))
-  (setq TeX-error-overview-orig-frame nil))
-
-(defvar TeX-error-overview-mode-map
-  (let ((map (make-sparse-keymap)))
-    (define-key map "b"    #'TeX-error-overview-toggle-debug-bad-boxes)
-    (define-key map "j"    #'TeX-error-overview-jump-to-source)
-    (define-key map "l"    #'TeX-error-overview-goto-log)
-    (define-key map "n"    #'TeX-error-overview-next-error)
-    (define-key map "p"    #'TeX-error-overview-previous-error)
-    (define-key map "q"    #'TeX-error-overview-quit)
-    (define-key map "w"    #'TeX-error-overview-toggle-debug-warnings)
-    (define-key map "x"    
#'TeX-error-overview-toggle-suppress-ignored-warnings)
-    (define-key map "\C-m" #'TeX-error-overview-goto-source)
-    map)
-  "Local keymap for `TeX-error-overview-mode' buffers.")
-
-(easy-menu-define TeX-error-overview-menu
-  TeX-error-overview-mode-map
-  "Menu used in TeX error overview mode."
-  '("TeX errors"
-    ["Next error" TeX-error-overview-next-error
-     :help "Jump to the next error"]
-    ["Previous error" TeX-error-overview-previous-error
-     :help "Jump to the previous error"]
-    ["Go to source" TeX-error-overview-goto-source
-     :help "Show the error in the source"]
-    ["Jump to source" TeX-error-overview-jump-to-source
-     :help "Move point to the error in the source"]
-    ["Go to log" TeX-error-overview-goto-log
-     :help "Show the error in the log buffer"]
-    "-"
-    ["Debug Bad Boxes" TeX-error-overview-toggle-debug-bad-boxes
-     :style toggle :selected TeX-debug-bad-boxes
-     :help "Show overfull and underfull boxes"]
-    ["Debug Warnings" TeX-error-overview-toggle-debug-warnings
-     :style toggle :selected TeX-debug-warnings
-     :help "Show warnings"]
-    ["Ignore Unimportant Warnings"
-     TeX-error-overview-toggle-suppress-ignored-warnings
-     :style toggle :selected TeX-suppress-ignored-warnings
-     :help "Hide specified warnings"]
-    "-"
-    ["Quit" TeX-error-overview-quit
-     :help "Quit"]))
-
-(defvar TeX-error-overview-list-entries nil
-  "List of errors to be used in the error overview.")
-
-(define-derived-mode TeX-error-overview-mode tabulated-list-mode
-                     "TeX errors"
-  "Major mode for listing TeX errors."
-  (setq tabulated-list-format [("File" 25 nil)
-                               ("Line" 4 nil :right-align t)
-                               ("Type" 7 nil)
-                               ("Message" 0 nil)]
-        tabulated-list-padding 1
-        tabulated-list-entries TeX-error-overview-list-entries)
-  (tabulated-list-init-header)
-  (tabulated-list-print))
-
-(defcustom TeX-error-overview-frame-parameters
-  '((name . "TeX errors")
-    (title . "TeX errors")
-    (height . 10)
-    (width . 80)
-    (top . (- 0))
-    (left . (- 0))
-    (unsplittable . t)
-    (minibuffer . nil)
-    (vertical-scroll-bars . t)
-    (tool-bar-lines . 0))
-  "Parameters of the error overview frame."
-  :group 'TeX-output
-  :type 'alist
-  :options '((name string) (title string) (height integer) (width integer)
-             (top integer) (left integer) (unsplittable boolean)
-             (minibuffer boolean) (vertical-scroll-bars boolean)
-             (tool-bar-lines integer)))
-
-(defcustom TeX-error-overview-open-after-TeX-run nil
-  "Whether to open automatically the error overview after running TeX."
-  :group 'TeX-output
-  :type 'boolean)
-
-(defun TeX-error-overview ()
-  "Show an overview of the errors occurred in the last TeX run."
-  (interactive)
-  ;; Check requirements before start.
-  (if (setq TeX-error-overview-active-buffer (TeX-active-buffer))
-      ;; `TeX-error-overview-list-entries' is going to be used only as value
-      ;; of `tabulated-list-entries' in `TeX-error-overview-mode'.  In
-      ;; principle, we don't need `TeX-error-overview-list-entries', but
-      ;; `tabulated-list-entries' is buffer-local and we need the list of
-      ;; entries before creating the error overview buffer in order to
-      ;; decide whether we need to show anything.
-      (if (setq TeX-error-overview-list-entries
-                (TeX-error-overview-make-entries
-                 (TeX-master-directory)))
-          (progn
-            (setq TeX-error-overview-orig-window (selected-window)
-                  TeX-error-overview-orig-frame
-                  (window-frame TeX-error-overview-orig-window))
-            ;; Create the error overview buffer.  This is
-            ;; automatically killed before running TeX commands, so if
-            ;; exists it is up-to-date and doesn't need to be
-            ;; re-created.
-            (unless (get-buffer TeX-error-overview-buffer-name)
-              (with-current-buffer
-                  (get-buffer-create TeX-error-overview-buffer-name)
-                (TeX-error-overview-mode)))
-            ;; Move point to the line associated to the last visited
-            ;; error.
-            (with-current-buffer TeX-error-overview-buffer-name
-              (goto-char (point-min))
-              (forward-line (with-current-buffer
-                                TeX-error-overview-active-buffer
-                              TeX-error-last-visited))
-              ;; Create a new frame for the error overview or display the
-              ;; buffer in the same frame, depending on the setup.
-              (if (TeX-error-overview-setup)
-                  (if (frame-live-p TeX-error-overview-frame)
-                      ;; Do not create a duplicate frame if there is
-                      ;; already one, just select it.
-                      (select-frame-set-input-focus
-                       TeX-error-overview-frame)
-                    ;; Create a new frame and store its name.
-                    (select-frame
-                     (setq TeX-error-overview-frame
-                           (make-frame
-                            TeX-error-overview-frame-parameters)))
-                    (set-window-buffer (selected-window)
-                                       TeX-error-overview-buffer-name)
-                    (set-window-dedicated-p (selected-window) t))
-                (TeX-pop-to-buffer TeX-error-overview-buffer-name))))
-        (error (concat "No error or warning to show"
-                       ;; Suggest to display warnings and bad boxes with the
-                       ;; appropriate key-bindings if there are such
-                       ;; messages in the output buffer.  Rationale of the
-                       ;; test: `TeX-error-overview-list-entries' is nil,
-                       ;; but if `TeX-error-list' is not nil it means that
-                       ;; there are hidden warnings/bad boxes.
-                       (when (TeX-process-get-variable (TeX-active-master)
-                                                       'TeX-error-list)
-                         (format ".  Type `%s' and `%s' to display \
-warnings and bad boxes"
-                                 (substitute-command-keys
-                                  
"\\<TeX-mode-map>\\[TeX-toggle-debug-warnings]")
-                                 (substitute-command-keys
-                                  
"\\<TeX-mode-map>\\[TeX-toggle-debug-bad-boxes]"))))))
-    (error "No process for this document")))
-
-;;; Output mode
-
-(define-derived-mode TeX-special-mode special-mode "TeX")
-
-(defvar TeX-output-mode-map
-  (let ((map (make-sparse-keymap)))
-    (set-keymap-parent map TeX-special-mode-map)
-    (define-key map "n" #'TeX-next-error)
-    (define-key map "p" #'TeX-previous-error)
-    (define-key map "b" #'TeX-toggle-debug-bad-boxes)
-    (define-key map "w" #'TeX-toggle-debug-warnings)
-    (define-key map "i" (lambda ()
-                          (interactive)
-                          (with-current-buffer TeX-command-buffer
-                            (TeX-interactive-mode (if TeX-interactive-mode -1 
1)))))
-    (define-key map "s" (lambda ()
-                          (interactive)
-                          (with-current-buffer TeX-command-buffer
-                            (TeX-source-correlate-mode (if 
TeX-source-correlate-mode -1 1)))))
-    map)
-  "Keymap for `TeX-output-mode'.")
-
-(define-derived-mode TeX-output-mode TeX-special-mode "TeX Output"
-  "Major mode for viewing TeX output.
-\\{TeX-output-mode-map} "
-  :syntax-table nil
-  (set (make-local-variable 'revert-buffer-function)
-       #'TeX-output-revert-buffer)
-  ;; special-mode makes it read-only which prevents input from TeX.
-  (setq buffer-read-only nil))
-
-(defun TeX-output-revert-buffer (_ignore-auto _noconfirm)
-  "Rerun the TeX command which of which this buffer was the output."
-  (goto-char (point-min))
-  (if (looking-at "Running `\\(.*\\)' on `\\(.*\\)' with ``\\(.*\\)''$")
-      (let ((name (match-string 1))
-            (file (match-string 2)))
-        (with-current-buffer TeX-command-buffer
-          (TeX-command name (if (string-match TeX-region file)
-                                #'TeX-region-file
-                              #'TeX-master-file))))
-    (error "Unable to find what command to run")))
-
-(provide 'tex-buf)
-
-;;; tex-buf.el ends here
diff --git a/tex-fold.el b/tex-fold.el
index ec348b9429..54f0a70fd2 100644
--- a/tex-fold.el
+++ b/tex-fold.el
@@ -1,6 +1,6 @@
 ;;; tex-fold.el --- Fold TeX macros.  -*- lexical-binding: t; -*-
 
-;; Copyright (C) 2004-2021  Free Software Foundation, Inc.
+;; Copyright (C) 2004-2022  Free Software Foundation, Inc.
 
 ;; Author: Ralf Angeli <angeli@caeruleus.net>
 ;; Maintainer: auctex-devel@gnu.org
diff --git a/tex-info.el b/tex-info.el
index da9d9b963a..a05920ddcf 100644
--- a/tex-info.el
+++ b/tex-info.el
@@ -1,6 +1,6 @@
 ;;; tex-info.el --- Support for editing Texinfo source.  -*- lexical-binding: 
t; -*-
 
-;; Copyright (C) 1993-2021  Free Software Foundation, Inc.
+;; Copyright (C) 1993-2022  Free Software Foundation, Inc.
 
 ;; Maintainer: auctex-devel@gnu.org
 ;; Keywords: tex
@@ -31,10 +31,6 @@
 
 (require 'texinfo)
 
-;; Silence the compiler for Emacs compiled `--with-native-compilation':
-(declare-function TeX-TeX-sentinel "tex-buf"
-                  (process name))
-
 ;;; Environments:
 (defvar Texinfo-environment-list
   '(("cartouche") ("command") ("copying") ("defcv") ("deffn") ("defivar")
@@ -634,8 +630,6 @@ is assumed by default."
 ;;;###autoload
 (defalias 'Texinfo-mode #'texinfo-mode)
 
-(defvar TeX-sentinel-default-function) ;; Defined in tex-buf.el.
-
 ;;;###autoload
 (defun TeX-texinfo-mode ()
   "Major mode in AUCTeX for editing Texinfo files.
diff --git a/tex-ispell.el b/tex-ispell.el
index ed1ca38337..c743bafdad 100644
--- a/tex-ispell.el
+++ b/tex-ispell.el
@@ -1,6 +1,6 @@
 ;;; tex-ispell.el --- AUCTeX skip additions for Ispell  -*- lexical-binding: 
t; -*-
 
-;; Copyright (C) 2016--2022 Free Software Foundation, Inc.
+;; Copyright (C) 2016-2022 Free Software Foundation, Inc.
 
 ;; Author: Arash Esbati <arash@gnu.org>
 ;; Maintainer: auctex-devel@gnu.org
diff --git a/tex-jp.el b/tex-jp.el
index 714aa7a541..8428c3793a 100644
--- a/tex-jp.el
+++ b/tex-jp.el
@@ -1,6 +1,6 @@
 ;;; tex-jp.el --- Support for Japanese TeX.  -*- lexical-binding: t; -*-
 
-;; Copyright (C) 1999, 2001-2008, 2012-2013, 2016-2018, 2020-2021
+;; Copyright (C) 1999, 2001-2008, 2012-2013, 2016-2018, 2020-2022
 ;;   Free Software Foundation, Inc.
 
 ;; Author:     KOBAYASHI Shinji <koba@flab.fujitsu.co.jp>,
@@ -35,7 +35,6 @@
 ;;; Code:
 
 (require 'latex)
-(require 'tex-buf)
 
 ;;; Customization
 
diff --git a/tex-site.el.in b/tex-site.el.in
index 42d81bf2d1..dda7d22256 100644
--- a/tex-site.el.in
+++ b/tex-site.el.in
@@ -1,6 +1,6 @@
 ;;; tex-site.el - Site specific variables.  Don't edit.  -*- lexical-binding: 
t; -*-
 
-;; Copyright (C) 2005-2021  Free Software Foundation, Inc.
+;; Copyright (C) 2005-2022  Free Software Foundation, Inc.
 ;;
 ;; completely rewritten.
 
@@ -95,49 +95,22 @@ shared by all users of a site."
 
 (add-hook 'tex-site-unload-hook
           (lambda ()
-            (if (fboundp 'advice-add)
-                (TeX-modes-set 'TeX-modes nil)
-              (let ((list after-load-alist))
-                (while list
-                  ;; Adapted copy of the definition of `assq-delete-all'
-                  ;; from Emacs 21 as substitute for
-                  ;; `(assq-delete-all'TeX-modes-set (car list))' which
-                  ;; fails on non-list elements in Emacs 21.
-                  (let* ((alist (car list))
-                         (tail alist)
-                         (key #'TeX-modes-set))
-                    (while tail
-                      (if (and (consp (car tail))
-                               (eq (car (car tail)) key))
-                          (setq alist (delq (car tail) alist)))
-                      (setq tail (cdr tail))))
-                  (setq list (cdr list)))))
+            (TeX-modes-set 'TeX-modes nil)
             (setq load-path (delq TeX-lisp-directory load-path))))
 
-(defun TeX-modes-set (var value &optional update)
+(defun TeX-modes-set (var value &optional _ignored)
   "Set VAR (which should be `TeX-modes') to VALUE.
 
 This places either the standard or the AUCTeX versions of
-functions into the respective function cell of the mode.
-If UPDATE is set, a previously saved value for
-the non-AUCTeX function gets overwritten with the current
-definition."
+functions into the respective function cell of the mode."
   (custom-set-default var value)
   (let ((list TeX-mode-alist) elt)
     (while list
       (setq elt (car (pop list)))
       (let ((dst (intern (concat "TeX-" (symbol-name elt)))))
-        (if (fboundp 'advice-add)
-            (if (memq elt value)
-                (advice-add elt :override dst)
-              (advice-remove elt dst))
-          (when (or update (null (get elt 'tex-saved)))
-            (when (fboundp elt)
-              (put elt 'tex-saved (symbol-function elt))))
-          (defalias elt
-            (if (memq elt value)
-                dst
-              (get elt 'tex-saved))))))))
+        (if (memq elt value)
+            (advice-add elt :override dst)
+          (advice-remove elt dst))))))
 
 (defcustom TeX-modes
   (mapcar #'car TeX-mode-alist)
@@ -148,14 +121,7 @@ set it with `TeX-modes-set'."
   :type (cons 'set
               (mapcar (lambda(x) (list 'const (car x))) TeX-mode-alist))
   :set #'TeX-modes-set
-  :initialize(lambda (var value)
-               (custom-initialize-reset var value)
-               (unless (fboundp 'advice-add)
-                 (let ((list TeX-mode-alist))
-                   (while list
-                     (eval-after-load (cdar list)
-                       `(TeX-modes-set ',var ,var t))
-                     (setq list (cdr list)))))) )
+  :initialize #'custom-initialize-reset)
 
 (defconst AUCTeX-version "@AUCTEXVERSION@"
     "AUCTeX version.
diff --git a/tex.el b/tex.el
index e3f4d118e7..ca4b8ad35b 100644
--- a/tex.el
+++ b/tex.el
@@ -1,6 +1,6 @@
 ;;; tex.el --- Support for TeX documents.  -*- lexical-binding: t; -*-
 
-;; Copyright (C) 1985-2021 Free Software Foundation, Inc.
+;; Copyright (C) 1985-2022 Free Software Foundation, Inc.
 
 ;; Maintainer: auctex-devel@gnu.org
 ;; Keywords: tex
@@ -55,6 +55,12 @@
                   (bus service path interface signal handler &rest args))
 (declare-function LaTeX-environment-list "latex"
                   nil)
+(declare-function LaTeX-bibliography-list "latex"
+                  nil)
+(declare-function comint-exec
+                  (buffer name command startfile switches))
+(declare-function comint-mode
+                  nil)
 (declare-function tex--prettify-symbols-compose-p "ext:tex-mode"
                   (start end match))
 (declare-function gnuserv-start "ext:gnuserv"
@@ -78,22 +84,24 @@
 (defvar TeX-source-specials-places)
 (defvar TeX-source-specials-tex-flags)
 (defvar TeX-synctex-tex-flags)
+(defvar TeX-current-process-region-p)
+(defvar TeX-region)
+(defvar TeX-region-orig-buffer)
 ;; Variables defined in other AUCTeX libraries:
 ;; latex.el:
 (defvar LaTeX-default-verb-delimiter)
 (defvar LaTeX-optcl)
 (defvar LaTeX-optop)
+(defvar LaTeX-largest-level)
+(defvar LaTeX-section-list)
 (defvar TeX-output-dir)
-;; tex-buf.el
-(defvar TeX-current-process-region-p)
-(defvar TeX-region)
-(defvar TeX-region-orig-buffer)
 ;; tex-ispell.el
 (defvar TeX-ispell-verb-delimiters)
 ;; Others:
 (defvar tex--prettify-symbols-alist)    ; tex-mode.el
 (defvar Info-file-list-for-emacs)       ; info.el
 (defvar ispell-parser)                  ; ispell.el
+(defvar compilation-error-regexp-alist) ; compile.el
 
 (defgroup TeX-file nil
   "Files used by AUCTeX."
@@ -694,38 +702,6 @@ sure \"%p\" is the first entry."
    TeX-expand-list
    TeX-expand-list-builtin))
 
-;; The following dependencies are not done with autoload cookies since
-;; they are only useful when tex.el is loaded, anyway.  tex-buf.el
-;; should remain unloaded as long as one is only editing files, so
-;; requiring it here would be wrong.
-
-(autoload 'LaTeX-command-run-all-section "tex-buf" nil t)
-(autoload 'LaTeX-command-section "tex-buf" nil t)
-(autoload 'TeX-active-master "tex-buf")
-(autoload 'TeX-check-engine-add-engines "tex-buf")
-(autoload 'TeX-command "tex-buf")
-(autoload 'TeX-command-buffer "tex-buf" nil t)
-(autoload 'TeX-command-expand "tex-buf")
-(autoload 'TeX-command-master "tex-buf" nil t)
-(autoload 'TeX-command-region "tex-buf" nil t)
-(autoload 'TeX-command-run-all "tex-buf" nil t)
-(autoload 'TeX-command-run-all-region "tex-buf" nil t)
-(autoload 'TeX-current-offset "tex-buf")
-(autoload 'TeX-error-overview "tex-buf" nil t)
-(autoload 'TeX-home-buffer "tex-buf" nil t)
-(autoload 'TeX-kill-job "tex-buf" nil t)
-(autoload 'TeX-next-error "tex-buf" nil t)
-(autoload 'TeX-previous-error "tex-buf" nil t)
-(autoload 'TeX-output-extension "tex-buf")
-(autoload 'TeX-pin-region "tex-buf" nil t)
-(autoload 'TeX-pop-to-buffer "tex-buf")
-(autoload 'TeX-process-set-variable "tex-buf")
-(autoload 'TeX-recenter-output-buffer "tex-buf" nil t)
-(autoload 'TeX-region-create "tex-buf")
-(autoload 'TeX-region-file "tex-buf")
-(autoload 'TeX-save-document "tex-buf" nil t)
-(autoload 'TeX-view "tex-buf" nil t)
-
 ;; This variable used to be defined in tex-buf.el.  It is used in
 ;; `TeX-mode-specific-command-menu-entries' in this file.  It is now
 ;; (June 2021) moved into this file to avoid `void-variable' errors
@@ -770,14 +746,10 @@ emacs 24.1 and is then later run by emacs 24.5."
                           (add-to-list 'Info-file-list-for-emacs
                                        (cons elt "AUCTeX"))))
 
-(if (fboundp 'advice-add)               ;Emacs≥24.4 (or ELPA package nadvice)
-    (advice-add 'hack-one-local-variable :after #'TeX--call-minor-mode)
-  (defadvice hack-one-local-variable (after TeX-hack-one-local-variable-after
-                                          activate)
-    (TeX--call-minor-mode (ad-get-arg 0) (ad-get-arg 1))))
+(advice-add 'hack-one-local-variable :after #'TeX--call-minor-mode)
 (defun TeX--call-minor-mode (var val &rest _)
   "Call minor mode function if minor mode variable is found."
-    ;; Instead of checking for each mode explicitely `minor-mode-list'
+    ;; Instead of checking for each mode explicitly `minor-mode-list'
     ;; could be used.  But this may make the byte compiler pop up.
     (when (memq var '(TeX-PDF-mode
                       TeX-source-correlate-mode TeX-interactive-mode
@@ -1878,7 +1850,7 @@ SyncTeX are recognized."
   :group 'TeX-view
   ;; Since this is a global minor mode and we don't want to require
   ;; tex.el when the mode variable is set, the mode function is called
-  ;; explicitely (if necessary) in `VirTeX-common-initialization'.  We
+  ;; explicitly (if necessary) in `VirTeX-common-initialization'.  We
   ;; do it there because otherwise `kill-all-local-variables' would
   ;; reset `TeX-source-correlate-output-page-function' which is
   ;; buffer-local.
@@ -3809,8 +3781,6 @@ The algorithm is as follows:
   ;; we enter TeX mode the first time.
   (add-hook 'write-contents-functions #'TeX-safe-auto-write nil t)
 
-  (define-key TeX-mode-map "\C-xng" #'TeX-narrow-to-group)
-
   ;; Minor modes
   (when TeX-source-correlate-mode
     (TeX-source-correlate-mode 1))
@@ -5005,7 +4975,6 @@ Brace insertion is only done if point is in a math 
construct and
     (define-key map "\C-c\C-t\C-w"   #'TeX-toggle-debug-warnings)
     (define-key map "\C-c\C-t\C-x"   #'TeX-toggle-suppress-ignored-warnings)
     (define-key map "\C-c\C-v" #'TeX-view)
-    ;; From tex-buf.el
     (define-key map "\C-c\C-d" #'TeX-save-document)
     (define-key map "\C-c\C-r" #'TeX-command-region)
     (define-key map "\C-c\C-b" #'TeX-command-buffer)
@@ -5024,6 +4993,8 @@ Brace insertion is only done if point is in a math 
construct and
 
     ;; Multifile
     (define-key map "\C-c_" #'TeX-master-file-ask)  ;*** temporary
+
+    (define-key map "\C-xng" #'TeX-narrow-to-group)
     map)
   "Keymap for common TeX and LaTeX commands.")
 
@@ -5410,6 +5381,20 @@ regardless of its data type."
   :group 'TeX-indentation
   :type 'integer)
 
+(defcustom TeX-indent-open-delimiters ""
+  "Additional open delimiters to increase indentation.
+Include \"[\" to indent inside square brackets.
+See `TeX-brace-count-line' and `TeX-indent-close-delimiters'."
+  :group  'TeX-indentation
+  :type '(string :tag "Open delimiters"))
+
+(defcustom TeX-indent-close-delimiters ""
+  "Additional close delimiters to increase indentation.
+Include \"]\" to indent inside square brackets.
+See `TeX-brace-count-line' and `TeX-indent-open-delimiters'."
+  :group  'TeX-indentation
+  :type '(string :tag "Close delimiters"))
+
 (defun TeX-comment-indent ()
   "Determine the indentation of a comment."
   (if (looking-at "%%%")
@@ -5419,17 +5404,32 @@ regardless of its data type."
          comment-column)))
 
 (defun TeX-brace-count-line ()
-  "Count number of open/closed braces."
+  "Count indent caused by open/closed braces.
+In addition to \"{\" and \"}\", characters in
+`TeX-indent-open-delimiters' and `TeX-indent-close-delimiters'
+are also taken into account.  Ignore them when they are escaped
+by \"\\\".  In comments, ignore \"{\" and \"}\" but don't ignore
+additional characters."
   (save-excursion
     (let ((count 0) (limit (line-end-position)) char)
       (while (progn
-               (skip-chars-forward "^{}\\\\" limit)
-               (when (and (< (point) limit) (not (TeX-in-comment)))
-                 (setq char (char-after))
+               (skip-chars-forward
+                (concat "^{}\\\\"
+                        TeX-indent-open-delimiters
+                        TeX-indent-close-delimiters)
+                limit)
+               (when (and (< (point) limit)
+                          (not (and (memq (setq char (char-after))
+                                          '(?\{ ?\} ?\\))
+                                    (TeX-in-comment))))
                  (forward-char)
-                 (cond ((eq char ?\{)
+                 (cond ((memq char (append
+                                    TeX-indent-open-delimiters
+                                    '(?\{)))
                         (setq count (+ count TeX-brace-indent-level)))
-                       ((eq char ?\})
+                       ((memq char (append
+                                    TeX-indent-close-delimiters
+                                    '(?\})))
                         (setq count (- count TeX-brace-indent-level)))
                        ((eq char ?\\)
                         (when (< (point) limit)
@@ -5443,7 +5443,7 @@ regardless of its data type."
   (let ((table (make-syntax-table (make-char-table 'syntax-table))))
     ;; Preset mode-independent syntax entries.  (Mode-dependent
     ;; entries are set in the function `TeX-search-syntax-table'.)
-    ;; ?\", ?\( and ?\) explicitely get whitespace syntax because
+    ;; ?\", ?\( and ?\) explicitly get whitespace syntax because
     ;; Emacs 21.3 and XEmacs don't generate a completely empty syntax
     ;; table.
     (dolist (elt '((?\f . ">") (?\n . ">") (?\" . " ") (?\( . " ") (?\) . " 
")))
@@ -6731,6 +6731,3485 @@ Used as function for validating a variable's 
`safe-local-variable' property."
          (when (> e2 (line-end-position))
            (concat "..." TeX-grcl)))))))
 
+;;; Customization:
+
+(defcustom TeX-process-asynchronous (not (eq system-type 'ms-dos))
+  "Use asynchronous processes."
+  :group 'TeX-command
+  :type 'boolean)
+
+(defcustom TeX-shell
+  (if (memq system-type '(ms-dos emx windows-nt))
+      shell-file-name
+    "/bin/sh")
+  "Name of shell used to parse TeX commands."
+  :group 'TeX-command
+  :type 'file)
+
+(defcustom TeX-shell-command-option
+  (cond ((memq system-type '(ms-dos emx windows-nt))
+         shell-command-switch)
+        (t                              ;Unix & EMX (Emacs 19 port to OS/2)
+         "-c"))
+  "Shell argument indicating that next argument is the command."
+  :group 'TeX-command
+  :type 'string)
+
+;;; Interactive Commands
+;;
+;; The general idea is, that there is one process and process buffer
+;; associated with each master file, and one process and process
+;; buffer for running TeX on a region.
+;;
+;; Some user commands operates on ``the'' process, which is the last
+;; process still running or already finished.  Note that you cannot
+;; run more than one process simultaneously, including preview by
+;; preview-latex, because process filters and sentinels refer to
+;; certain set of global variables which each invokation of the
+;; process overwrites.  If you dare to do, the result is thus
+;; unpredictable.
+
+(defun TeX-save-document (name-or-file-fn)
+  "Save all files belonging to the current document.
+Return non-nil if document needs to be re-TeX'ed.
+In Lisp program, NAME-OR-FILE-FN specifies the current document.
+It is either the master name without extension or the function
+`TeX-master-file'."
+  (interactive (list #'TeX-master-file))
+  (TeX-check-files (TeX--concat-ext name-or-file-fn (TeX-output-extension))
+                   (cons (TeX--concat-ext name-or-file-fn) (TeX-style-list))
+                   TeX-file-extensions))
+
+(defun TeX--concat-ext (name-or-file-fn &optional extension)
+  "Append EXTENSION to a filename specified by NAME-OR-FILE-FN.
+
+If NAME-OR-FILE-FN is a string, interpret it as the filename.
+Otherwise, assume it is a callable function and call it with
+EXTENSION as an argument and return the result without
+modification.  EXTENSION is a string which should not start with
+'.'."
+  (if (stringp name-or-file-fn)
+      (if extension
+          (concat name-or-file-fn "." extension)
+        name-or-file-fn)
+    (funcall name-or-file-fn extension)))
+
+(defun TeX-command-master (&optional override-confirm)
+  "Run command on the current document.
+
+If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
+depend on it being positive instead of the entry in `TeX-command-list'."
+  (interactive "P")
+  (TeX-master-file nil nil t)  ;; call to ask if necessary
+  (TeX-command (TeX-command-query #'TeX-master-file)
+               #'TeX-master-file override-confirm))
+
+(defcustom TeX-region-extra ""
+  "String to insert in the region file between the header and the text."
+  :group 'TeX-command
+  :type 'string)
+
+;; This was "{\\makeatletter\\gdef\\AucTeX@cite#1[#2]#3{[#3#1#2]}\
+;;           \\gdef\\cite{\\@ifnextchar[{\\AucTeX@cite{, }}\
+;;           {\\AucTeX@cite{}[]}}}\n"
+;; However, that string is inappropriate for plain TeX and ConTeXt.
+;; This needs reconsideration.
+
+(defvar TeX-command-region-begin nil)
+(defvar TeX-command-region-end nil)
+;; Used for marking the last region.
+
+(make-variable-buffer-local 'TeX-command-region-begin)
+(make-variable-buffer-local 'TeX-command-region-end)
+
+(defun TeX-current-offset (&optional pos)
+  "Calculate line offset of POS, or of point if POS is nil."
+  (save-restriction
+    (widen)
+    (save-excursion
+      (let ((inhibit-point-motion-hooks t)
+            (inhibit-field-text-motion t))
+        (if pos (goto-char pos))
+        (+ (count-lines (point-min) (point))
+           (if (bolp) 0 -1))))))
+
+(defun TeX-pin-region (begin end)
+  "Pin the TeX region specified by BEGIN and END.
+If BEGIN is nil, the region is unpinned.
+
+In interactive use, a positive prefix arg will pin the region,
+a non-positive one will unpin it.  Without a prefix arg, if
+a region is actively marked, it will get pinned.  If not, a
+pinned region will get unpinned and vice versa."
+  (interactive
+   (if
+       (if current-prefix-arg
+           (> (prefix-numeric-value current-prefix-arg) 0)
+         (or (TeX-active-mark)
+             (null TeX-command-region-begin)))
+       (list (region-beginning) (region-end))
+     '(nil nil)))
+  (if begin
+      (progn
+        (unless (markerp TeX-command-region-begin)
+          (setq TeX-command-region-begin (make-marker))
+          (setq TeX-command-region-end (make-marker)))
+        (set-marker TeX-command-region-begin begin)
+        (set-marker TeX-command-region-end end)
+        (message "TeX region pinned."))
+    (when (markerp TeX-command-region-begin)
+      (set-marker TeX-command-region-begin nil)
+      (set-marker TeX-command-region-end nil))
+    (setq TeX-command-region-begin nil)
+    (setq TeX-command-region-end nil)
+    (message "TeX region unpinned.")))
+
+(defun TeX-region-update ()
+  "Update the TeX-region file."
+  ;; Note that TeX-command-region-begin is not a marker when called
+  ;; from TeX-command-buffer.
+  (and (or (null TeX-command-region-begin)
+           (markerp TeX-command-region-begin))
+       (TeX-active-mark)
+       (TeX-pin-region (region-beginning) (region-end)))
+  (let* ((begin (or TeX-command-region-begin (region-beginning)))
+         (end (or TeX-command-region-end (region-end)))
+         (TeX-region-extra
+          ;; Write out counter information to region.
+          (concat (and (fboundp 'preview--counter-information)
+                       (preview--counter-information begin))
+                  TeX-region-extra)))
+    (TeX-region-create (TeX-region-file TeX-default-extension)
+                       (buffer-substring-no-properties begin end)
+                       (file-name-nondirectory (buffer-file-name))
+                       (TeX-current-offset begin))))
+
+(defun TeX-command-region (&optional override-confirm)
+  "Run TeX on the current region.
+
+Query the user for a command to run on the temporary file specified by
+the variable `TeX-region'.  If there is an explicitly active region,
+it is stored for later commands.  If not, a previously stored region
+\(can be also be set with `TeX-pin-region') overrides the current region,
+if present.
+
+If a prefix argument OVERRIDE-CONFIRM is given, prompting will
+ignore the prompting flag from `TeX-command-list' and instead
+will prompt only if the prefix is positive.
+
+If the master file for the document has a header, it is written to the
+temporary file before the region itself.  The document's header is all
+text before `TeX-header-end'.
+
+If the master file for the document has a trailer, it is written to
+the temporary file after the region itself.  The document's trailer is
+all text after `TeX-trailer-start'."
+  (interactive "P")
+  (TeX-region-update)
+  ;; In the next line, `TeX-region-file' should be called with nil
+  ;; `nondirectory' argument, otherwise `TeX-command-default' called
+  ;; within `TeX-command-query' won't work in included files not
+  ;; placed in `TeX-master-directory'.
+  (TeX-command (TeX-command-query #'TeX-region-file) #'TeX-region-file
+               override-confirm))
+
+(defun TeX-command-buffer (&optional override-confirm)
+  "Run TeX on the current buffer.
+
+Query the user for a command to run on the temporary file specified by
+the variable `TeX-region'.  The region file will be recreated from the
+visible part of the buffer.
+
+If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
+depend on it being positive instead of the entry in `TeX-command-list'."
+  (interactive "P")
+  (let ((TeX-command-region-begin (point-min))
+        (TeX-command-region-end (point-max)))
+    (TeX-command-region override-confirm)))
+
+(defcustom TeX-record-buffer nil
+  "Whether to record buffer names of generated TeX buffers.
+When non-nil, these buffers are put at the front of the list of
+recently selected ones."
+  :group 'TeX-command
+  :type 'boolean)
+
+(defun TeX-pop-to-buffer (buffer &optional other-window norecord)
+  "Compatibility wrapper for `pop-to-buffer'.
+
+Select buffer BUFFER in some window, preferably a different one.
+BUFFER may be a buffer, a string (a buffer name), or nil.
+If BUFFER is a string which is not the name of an existing buffer,
+then this function creates a buffer with that name.
+If BUFFER is nil, then it chooses some other buffer.
+If `pop-up-windows' is non-nil, windows can be split to do this.
+If optional second arg OTHER-WINDOW is non-nil, insist on finding another
+window even if BUFFER is already visible in the selected window,
+and ignore `same-window-regexps' and `same-window-buffer-names'.
+This function returns the buffer it switched to.
+This uses the function `display-buffer' as a subroutine; see the documentation
+of `display-buffer' for additional customization information.
+
+Optional third arg NORECORD non-nil means do not put this buffer
+at the front of the list of recently selected ones."
+  (pop-to-buffer buffer other-window (and norecord (not TeX-record-buffer))))
+
+(defun TeX-recenter-output-buffer (line)
+  "Redisplay buffer of TeX job output so that most recent output can be seen.
+The last line of the buffer is displayed on line LINE of the window, or
+at bottom if LINE is nil."
+  (interactive "P")
+  (let ((buffer (TeX-active-buffer)))
+    (if buffer
+        (let ((old-buffer (current-buffer)))
+          (TeX-pop-to-buffer buffer t t)
+          (bury-buffer buffer)
+          (goto-char (point-max))
+          (recenter (if line
+                        (prefix-numeric-value line)
+                      (/ (window-height) 2)))
+          (TeX-pop-to-buffer old-buffer nil t))
+      (message "No process for this document."))))
+
+(defun TeX-kill-job ()
+  "Kill the currently running TeX job."
+  (interactive)
+  (let ((process (TeX-active-process)))
+    (if process
+        (kill-process process)
+      ;; Should test for TeX background process here.
+      (error "No TeX process to kill"))))
+
+;; FIXME: The vars below are defined in this file, but they're defined too
+;; far down (i.e. further down than their first use), so we have to pre-declare
+;; them here to explain it to the compiler.
+;; We should move those vars's definitions earlier instead!
+(defvar TeX-current-process-region-p)
+(defvar TeX-save-query)
+(defvar TeX-parse-function)
+(defvar TeX-sentinel-function)
+(defvar TeX-sentinel-default-function)
+(defvar compilation-in-progress)
+(defvar TeX-current-page)
+(defvar TeX-error-overview-open-after-TeX-run)
+(defvar TeX-error-list)
+(defvar TeX-command-buffer)
+(defvar TeX-region)
+
+(defun TeX-home-buffer ()
+  "Go to the buffer where you last issued a TeX command.
+If there is no such buffer, or you already are in that buffer, find
+the master file."
+  (interactive)
+  (if (or (null TeX-command-buffer)
+          (null (buffer-name TeX-command-buffer))
+          (eq TeX-command-buffer (current-buffer)))
+      (find-file (TeX-master-file TeX-default-extension))
+    (switch-to-buffer TeX-command-buffer)))
+
+(defvar TeX-error-last-visited -1
+  "Index of the last visited error listed in `TeX-error-list'.
+
+This variable is intended to be set only in output buffer so it
+will be shared among all files of the same document.")
+(make-variable-buffer-local 'TeX-error-last-visited)
+
+(defun TeX-get-parse-function ()
+  "Get the parse function for the current buffer."
+  (with-current-buffer TeX-command-buffer
+    (TeX-process-get-variable (TeX-active-master) 'TeX-parse-function)))
+
+(defun TeX-next-error (&optional arg reparse)
+  "Find the next error in the TeX output buffer.
+
+A prefix ARG specifies how many error messages to move;
+negative means move back to previous error messages, if possible.
+
+If REPARSE is non-nil, reparse the error message buffer.
+
+\\[universal-argument] as a prefix means reparse the error
+message buffer and start at the first error."
+  (interactive "P")
+  (if (or (null (TeX-active-buffer))
+          (eq 'compilation-mode (with-current-buffer TeX-command-buffer
+                                  major-mode)))
+      (next-error arg reparse)
+
+    ;; Force reparsing when the function is called with a universal-argument.
+    (if (consp arg) (setq reparse t arg nil))
+
+    (funcall (TeX-get-parse-function) arg reparse)))
+
+(defun TeX-previous-error (arg)
+  "Find the previous error in the TeX output buffer.
+
+Prefix arg N says how many error messages to move backward (or
+forward, if negative).
+
+This works only with TeX commands and if the
+`TeX-parse-all-errors' variable is non-nil."
+  (interactive "p")
+  (if (or (null (TeX-active-buffer))
+          (eq 'compilation-mode (with-current-buffer TeX-command-buffer
+                                  major-mode)))
+      (previous-error arg)
+
+    (let ((parse-function (TeX-get-parse-function)))
+      (if (and TeX-parse-all-errors (equal parse-function #'TeX-parse-TeX))
+          ;; When `TeX-parse-all-errors' is non-nil and the parsing function is
+          ;; `TeX-parse-TeX' we can move backward in the errors.
+          (TeX-parse-TeX (- arg) nil)
+        ;; XXX: moving backward in the errors hasn't yet been implemented for
+        ;; other parsing functions.
+        (error "Jumping to previous error not supported")))))
+
+;;; Command Query
+
+(defvar TeX-error-overview-frame nil
+  "The frame of the error overview.")
+
+(defconst TeX-error-overview-buffer-name "*TeX errors*"
+  "Name of the buffer in which to show error list.")
+
+(defvar LaTeX-idx-md5-alist nil
+  "Alist of MD5 hashes of idx file.
+
+Car is the idx file, cdr is its md5 hash.")
+
+(defvar LaTeX-idx-changed-alist nil
+  "Whether the idx files changed.
+
+Car is the idx file, cdr is whether idx changed after LaTeX
+run.")
+
+(defcustom TeX-check-engine t
+  "Check the correct engine has been set before running TeX commands."
+  :group 'TeX-command
+  :type 'boolean)
+
+(defvar TeX-check-engine-list '(default luatex omega xetex)
+  "List of engines required by the loaded TeX packages.
+
+Do not set this variable directly, use
+`TeX-check-engine-add-engines' to specify required engines.")
+(make-variable-buffer-local 'TeX-check-engine-list)
+
+(defun TeX-check-engine-add-engines (&rest engines)
+  "Add ENGINES to list of required engines.
+
+Set `TeX-check-engine-list' to the intersection between the list
+itself and the list of provided engines.
+
+See for example style/fontspec.el"
+  (let ((list TeX-check-engine-list)
+        (res nil))
+    (setq TeX-check-engine-list
+          ;; The following is based on the definition of `cl-intersection' of
+          ;; GNU Emacs.
+          (and list engines
+               (if (equal list engines) list
+                 (or (>= (length list) (length engines))
+                     (setq list (prog1 engines (setq engines list))))
+                 (while engines
+                   (if (memq (car engines) list)
+                       (push (car engines) res))
+                   (pop engines))
+                 res)))))
+
+(defun TeX-check-engine (name)
+  "Check the correct engine has been set.
+
+Look into `TeX-check-engine-list' for the required engines.
+
+NAME is the command to be run.  Actually do the check only if the
+variable `TeX-check-engine' is non-nil and LaTeX is the command
+to be run."
+  (and
+   (string= name "LaTeX")
+   TeX-check-engine
+   TeX-check-engine-list
+   (null (memq TeX-engine TeX-check-engine-list))
+   (memq TeX-engine '(default luatex omega xetex))
+   ;; The set engine is not listed in `TeX-check-engine-list'.  We check only
+   ;; builtin engines because we can't take care of custom ones.  Do nothing if
+   ;; there is no allowed engine, we don't know what to do in that case.
+   (let ((length (length TeX-check-engine-list))
+         (name-alist '((default . "TeX")
+                       (luatex  . "LuaTeX")
+                       (omega   . "Omega")
+                       (xetex   . "XeTeX")))
+         (completion-ignore-case t)
+         (engine nil))
+     (when
+         (cond
+          ;; There is exactly one allowed engine.
+          ((= length 1)
+           (setq engine (car TeX-check-engine-list))
+           (y-or-n-p (format "%s is required to build this document.
+Do you want to use this engine? " (cdr (assoc engine name-alist)))))
+          ;; More than one engine is allowed.
+          ((> length 1)
+           (if (y-or-n-p (format "It appears %s are required to build this 
document.
+Do you want to select one of these engines? "
+                                 (mapconcat
+                                  (lambda (elt) (cdr (assoc elt name-alist)))
+                                  TeX-check-engine-list ", ")))
+               (setq engine
+                     (car (rassoc
+                           (completing-read
+                            (format
+                             "Choose between %s: "
+                             (mapconcat
+                              (lambda (elt) (cdr (assoc elt name-alist)))
+                              TeX-check-engine-list ", "))
+                            (mapcar
+                             (lambda (elt) (cdr (assoc elt name-alist)))
+                             TeX-check-engine-list))
+                           name-alist)))
+             ;; Don't keep asking.  If user doesn't want to change engine,
+             ;; probably has a good reason.  In order to do so, without adding
+             ;; yet another variable we just hack `TeX-check-engine-list' and
+             ;; make it nil.
+             (setq TeX-check-engine-list nil))))
+       (TeX-engine-set engine)
+       (when (y-or-n-p "Do you want to remember the choice? ")
+         (add-file-local-variable 'TeX-engine engine)
+         (save-buffer))))))
+
+(defcustom TeX-check-TeX t
+  "Whether AUCTeX should check if a working TeX distribution is present."
+  :group 'TeX-command
+  :type 'boolean)
+
+(defcustom TeX-check-TeX-command-not-found 127
+  "Numerical code returned by shell for a command not found error."
+  :group 'TeX-command
+  :type 'integer)
+
+(defun TeX-command (name file-fn &optional override-confirm)
+  "Run command NAME on the file returned by calling FILE-FN.
+
+FILE-FN is the symbol of a function returning a file name.  The
+function has one optional argument, the extension to use on the
+file.  Valid choices are `TeX-master-file' and `TeX-region-file'.
+
+Use the information in `TeX-command-list' to determine how to run
+the command.
+
+If OVERRIDE-CONFIRM is a prefix argument, confirmation will be
+asked if it is positive, and suppressed if it is not.
+
+Run function `TeX-check-engine' to check the correct engine has
+been set."
+  (TeX-check-engine name)
+
+  ;; Make sure that `TeX-command-buffer' is set always.
+  ;; It isn't safe to remove similar lines in `TeX-run-command' etc.
+  ;; because preview-latex calls `TeX-run-command' directly.
+  (setq-default TeX-command-buffer (current-buffer))
+
+  (cond ((eq file-fn #'TeX-region-file)
+         (setq TeX-current-process-region-p t))
+        ((eq file-fn #'TeX-master-file)
+         (setq TeX-current-process-region-p nil)))
+
+  ;; When we're operating on a region, we need to update the position
+  ;; of point in the region file so that forward search works.
+  (if (string= name "View") (TeX-region-update-point))
+
+  (let ((command (TeX-command-expand (nth 1 (assoc name TeX-command-list))))
+        (hook (nth 2 (assoc name TeX-command-list)))
+        (confirm (if override-confirm
+                     (> (prefix-numeric-value override-confirm) 0)
+                   (nth 3 (assoc name TeX-command-list)))))
+
+    ;; Verify the expanded command
+    (if confirm
+        (setq command
+              (read-from-minibuffer (concat name " command: ") command
+                                    nil nil)))
+
+    ;; Kill the frame and buffer associated to the error overview before 
running
+    ;; the command, but keep them if the command to be run is View.
+    (unless (string= name "View")
+      (if (frame-live-p TeX-error-overview-frame)
+          (delete-frame TeX-error-overview-frame))
+      (if (get-buffer TeX-error-overview-buffer-name)
+          (kill-buffer TeX-error-overview-buffer-name)))
+
+    ;; Before running some commands, check that AUCTeX is able to find "tex"
+    ;; program.
+    (and TeX-check-TeX
+         (member name '("TeX" "LaTeX" "AmSTeX" "ConTeXt" "ConTeXt Full"))
+         (= TeX-check-TeX-command-not-found
+            (call-process TeX-shell nil nil nil
+                          TeX-shell-command-option TeX-command))
+         (error (format "ERROR: AUCTeX cannot find a working TeX distribution.
+Make sure you have one and that TeX binaries are in PATH environment 
variable%s"
+                        (if (eq system-type 'darwin)
+                            ".
+If you are using OS X El Capitan or later
+remember to add /Library/TeX/texbin/ to your PATH"
+                          ""))))
+
+    ;; Now start the process
+    (let ((file (funcall file-fn)))
+      (TeX-process-set-variable file 'TeX-command-next TeX-command-Show)
+      (funcall hook name command file))))
+
+(defun TeX-command-expand (command &optional list)
+  "Expand COMMAND for `TeX-active-master' as described in LIST.
+LIST default to `TeX-expand-list'.  As a special exception,
+`%%' can be used to produce a single `%' sign in the output
+without further expansion."
+  (let ((TeX-expand-command command)
+        TeX-expand-pos
+        TeX-command-text
+        TeX-command-pos
+        pat entry case-fold-search string expansion arguments)
+    (setq list (cons
+                (list "%%" (lambda nil
+                             (setq TeX-expand-pos (1+ TeX-expand-pos))
+                             "%"))
+                (or list (TeX-expand-list)))
+          pat (regexp-opt (mapcar #'car list)))
+    (while (setq TeX-expand-pos (string-match pat TeX-expand-command 
TeX-expand-pos))
+      (setq string (match-string 0 TeX-expand-command)
+            entry (assoc string list)
+            expansion (car (cdr entry)) ;Second element
+            arguments (cdr (cdr entry)) ;Remaining elements
+            string (save-match-data
+                     (cond
+                      ((functionp expansion)
+                       (apply expansion arguments))
+                      ((boundp expansion)
+                       (apply (symbol-value expansion) arguments))
+                      (t
+                       (error "Nonexpansion %s" expansion)))))
+      (if (stringp string)
+          (setq TeX-expand-command
+                (replace-match string t t TeX-expand-command))))
+    TeX-expand-command))
+
+(defun TeX-active-master-with-quotes
+    (&optional extension nondirectory ask extra preprocess-fn)
+  "Return the current master or region file name with quote for shell.
+Pass arguments EXTENSION NONDIRECTORY ASK to `TeX-active-master'.
+If the returned file name contains space, enclose it within
+quotes `\"' when \" \\input\" is supplemented (indicated by
+dynamically bound variable `TeX-command-text' having string
+value.) Also enclose the file name within \\detokenize{} when
+the following three conditions are met:
+  1. compiling with standard (pdf)LaTeX or upLaTeX
+  2. \" \\input\" is supplemented
+  3. EXTRA is non-nil (default when expanding \"%T\")
+Adjust dynamically bound variable `TeX-expand-pos' to avoid possible
+infinite loop in `TeX-command-expand'.
+If PREPROCESS-FN is non-nil then it is called with the filename
+as an argument and the result is enclosed instead of the
+filename.
+
+Helper function of `TeX-command-expand'. Use only within entries in
+`TeX-expand-list-builtin' and `TeX-expand-list'."
+  (let* ((raw (TeX-active-master extension nondirectory ask))
+         ;; String `TeX-command-text' means that the file name is
+         ;; given through \input command.
+         (quote-for-space (if (and (stringp TeX-command-text)
+                                   (string-match " " raw))
+                              "\"" ""))
+         (res
+          (shell-quote-argument
+           (format
+            (if (and extra
+                     (stringp TeX-command-text)
+                     (memq major-mode '(latex-mode doctex-mode))
+                     (memq TeX-engine '(default uptex)))
+                ;; Since TeXLive 2018, the default encoding for LaTeX
+                ;; files has been changed to UTF-8 if used with
+                ;; classic TeX or pdfTeX.  I.e.,
+                ;; \usepackage[utf8]{inputenc} is enabled by default
+                ;; in (pdf)latex.
+                ;; c.f. LaTeX News issue 28
+                ;; Due to this change, \detokenize is required to
+                ;; recognize non-ascii characters in the file name
+                ;; when \input precedes.
+                "\\detokenize{ %s }" "%s")
+            (concat quote-for-space
+                    (if preprocess-fn
+                        (funcall preprocess-fn raw)
+                      raw)
+                    quote-for-space)))))
+    ;; Advance past the file name in order to
+    ;; prevent expanding any substring of it.
+    (setq TeX-expand-pos
+          (+ TeX-expand-pos (length res)))
+    res))
+
+(defun TeX-check-files (derived originals extensions)
+  "Check if DERIVED is newer than any of the ORIGINALS.
+Try each original with each member of EXTENSIONS, in all directories
+in `TeX-check-path'.  Returns true if any of the ORIGINALS with any of the
+EXTENSIONS are newer than DERIVED.  Will prompt to save the buffer of any
+ORIGINALS which are modified but not saved yet."
+  (let (existingoriginals
+        found
+        (extensions (TeX-delete-duplicate-strings extensions))
+        (buffers (buffer-list)))
+    (dolist (path (TeX-delete-duplicate-strings
+                   (mapcar (lambda (dir)
+                             (expand-file-name (file-name-as-directory dir)))
+                           (append
+                            TeX-check-path
+                            ;; In `TeX-command-default', this function is used 
to
+                            ;; check whether bibliography databases are newer
+                            ;; than generated *.bbl files, but bibliography
+                            ;; database are relative to `TeX-master-directory'
+                            ;; and the test can be run also from included files
+                            ;; that are in directories different from
+                            ;; `TeX-master-directory'.
+                            (list (TeX-master-directory))))))
+      (dolist (orig originals)
+        (dolist (ext extensions)
+          (let ((filepath (concat path orig "." ext)))
+            (if (or (file-exists-p filepath)
+                    (get-file-buffer filepath))
+                (setq existingoriginals (cons filepath existingoriginals)))))))
+    (while buffers
+      (let* ((buffer (car buffers))
+             (name (buffer-file-name buffer)))
+        (setq buffers (cdr buffers))
+        (if (and name (member name existingoriginals))
+            (progn
+              (and (buffer-modified-p buffer)
+                   (or (not TeX-save-query)
+                       (y-or-n-p (concat "Save file "
+                                         (buffer-file-name buffer)
+                                         "? ")))
+                   (with-current-buffer buffer (save-buffer)))))))
+    (dolist (eo existingoriginals)
+      (if (file-newer-than-file-p eo derived)
+          (setq found t)))
+    found))
+
+(defcustom TeX-command-sequence-max-runs-same-command 4
+  "Maximum number of runs of the same command."
+  :type 'integer
+  :group 'TeX-command)
+
+(defcustom TeX-command-sequence-max-runs 12
+  "Maximum number of total runs."
+  :type 'integer
+  :group 'TeX-command)
+
+(defvar TeX-command-sequence-count-same-command 1
+  "Counter for the runs of the same command in `TeX-command-sequence'.")
+
+(defvar TeX-command-sequence-count 1
+  "Counter for the total runs of `TeX-command-sequence'.")
+
+(defvar TeX-command-sequence-last-command nil
+  "Last command run in `TeX-command-sequence'.")
+
+(defvar TeX-command-sequence-sentinel nil
+  "Sentinel for `TeX-command-sequence'.")
+
+(defvar TeX-command-sequence-file-function nil
+  "File function for `TeX-command-sequence'.")
+
+(defvar TeX-command-sequence-command nil
+  "Command argument for `TeX-command-sequence'.
+
+It is set in `TeX-command-sequence' and used in
+`TeX-command-sequence-sentinel' to call again
+`TeX-command-sequence' with the appropriate command argument.")
+
+(defun TeX-command-sequence (command &optional reset file-fn)
+  "Run a sequence of TeX commands defined by COMMAND.
+
+The COMMAND argument may be
+
+  * nil: no command will be run in this case
+
+  * a string with a command from `TeX-command-list'
+
+  * a non-nil list of strings, which are commands from
+    `TeX-command-list'; the car of the list is used as command to
+    be executed in the first run of `TeX-command-sequence', the
+    cdr of the list will be passed to the function in the next
+    run, etc.
+
+  * a function name, returning a string which is command from
+    `TeX-command-list'; it will be funcall'd (without arguments!)
+    and used again in the next run of `TeX-command-sequence'.
+
+  * with any other value the function `TeX-command-default' is
+    used to determine the command to run, until a stopping
+    condition is met.
+
+This function runs at most
+`TeX-command-sequence-max-runs-same-command' times the same
+command in a row, and `TeX-command-sequence-max-runs' times in
+total in any case.  It ends when `TeX-command-Show' is the
+command to be run.
+
+A non-nil value for the optional argument RESET means this is the
+first run of the function and some variables need to be reset.
+
+FILE-FN is a function of zero arguments returning the current
+filename.  Valid choices are `TeX-master-file' (default if
+omitted) and `TeX-region-file'."
+  (setq TeX-command-sequence-file-function (or file-fn #'TeX-master-file))
+  (if (null command)
+      (message "No command to run.")
+    (let (cmd process)
+      (cond
+       ((stringp command)
+        (setq cmd command
+              TeX-command-sequence-command nil))
+       ((listp command)
+        (setq cmd (pop command)
+              TeX-command-sequence-command command))
+       ((functionp command)
+        (setq cmd (funcall command)
+              TeX-command-sequence-command command))
+       (t
+        ;; We first call `TeX-master-file' with the third argument
+        ;; (`ask') set to t, so that the master file is properly set.
+        ;; This is also what `TeX-command-master' does.
+        (funcall TeX-command-sequence-file-function nil nil t)
+        (setq cmd (TeX-command-default TeX-command-sequence-file-function)
+              TeX-command-sequence-command t)))
+      (TeX-command cmd TeX-command-sequence-file-function 0)
+      (when reset
+        (setq TeX-command-sequence-count-same-command 1
+              TeX-command-sequence-count 1
+              TeX-command-sequence-last-command nil))
+      (cond
+       ;; Stop when the same command has been run
+       ;; `TeX-command-sequence-max-runs-same-command' times in a row.
+       ((>= TeX-command-sequence-count-same-command
+            TeX-command-sequence-max-runs-same-command)
+        (message "Stopping after running %S %d times in a row."
+                 TeX-command-sequence-last-command
+                 TeX-command-sequence-count-same-command))
+       ;; Stop when there have been `TeX-command-sequence-max-runs' total
+       ;; compilations.
+       ((>= TeX-command-sequence-count TeX-command-sequence-max-runs)
+        (message "Stopping after %d compilations." TeX-command-sequence-count))
+       ;; The command just run is `TeX-command-Show'.
+       ((equal command TeX-command-Show))
+       ;; In any other case continue: increase counters (when needed), update
+       ;; `TeX-command-sequence-last-command' and run the sentinel.
+       (t
+        (if (equal cmd TeX-command-sequence-last-command)
+            (setq TeX-command-sequence-count-same-command
+                  (1+ TeX-command-sequence-count-same-command))
+          (setq TeX-command-sequence-count-same-command 1))
+        (setq TeX-command-sequence-count (1+ TeX-command-sequence-count)
+              TeX-command-sequence-last-command cmd)
+        (and (setq process (get-buffer-process (current-buffer)))
+             (setq TeX-command-sequence-sentinel (process-sentinel process))
+             (set-process-sentinel process
+                                   #'TeX-command-sequence-sentinel)))))))
+
+(defcustom TeX-save-query t
+  "If non-nil, ask user for permission to save files before starting TeX."
+  :group 'TeX-command
+  :type 'boolean)
+
+(defvar TeX-command-history nil)
+
+(defun TeX-command-default (name-or-file-fn)
+  "Guess the next command to be run on NAME-OR-FILE-FN."
+  (let ((command-next nil)
+        (name (TeX--concat-ext name-or-file-fn)))
+    (cond ((if (eq name-or-file-fn #'TeX-region-file)
+               (TeX-check-files (TeX-region-file (TeX-output-extension))
+                                ;; Each original will be checked for all dirs
+                                ;; in `TeX-check-path' so this needs to be just
+                                ;; a filename without directory.
+                                (list (file-relative-name name))
+                                TeX-file-extensions)
+             (TeX-save-document name-or-file-fn))
+           TeX-command-default)
+          ((and (memq major-mode '(doctex-mode latex-mode))
+                ;; Want to know if bib file is newer than .bbl
+                ;; We don't care whether the bib files are open in emacs
+                (TeX-check-files (TeX--concat-ext name-or-file-fn "bbl")
+                                 (mapcar #'car
+                                         (LaTeX-bibliography-list))
+                                 (append BibTeX-file-extensions
+                                         TeX-Biber-file-extensions)))
+           ;; We should check for bst files here as well.
+           (if (bound-and-true-p LaTeX-using-Biber)
+               TeX-command-Biber TeX-command-BibTeX))
+          ((and
+            ;; Rationale: makeindex should be run when final document is almost
+            ;; complete (see
+            ;; https://tex-talk.net/2012/09/dont-forget-to-run-makeindex/),
+            ;; otherwise, after following latex runs, index pages may change 
due
+            ;; to changes in final document, resulting in extra makeindex and
+            ;; latex runs.
+            (member
+             (setq command-next
+                   (TeX-process-get-variable
+                    name
+                    'TeX-command-next
+                    (or (and TeX-PDF-mode (TeX-PDF-from-DVI))
+                        TeX-command-Show)))
+             (list "Dvips" "Dvipdfmx" TeX-command-Show))
+            (cdr (assoc (expand-file-name (TeX--concat-ext name-or-file-fn 
"idx"))
+                        LaTeX-idx-changed-alist)))
+           "Index")
+          (command-next)
+          (TeX-command-Show))))
+
+(defun TeX-command-query (name-or-file-fn)
+  "Query the user for what TeX command to use."
+  (let* ((default (TeX-command-default name-or-file-fn))
+         (completion-ignore-case t)
+         (answer (or TeX-command-force
+                     (completing-read
+                      (concat "Command (default " default "): ")
+                      (TeX-mode-specific-command-list major-mode) nil t
+                      nil 'TeX-command-history default))))
+    ;; If the answer is "latex" it will not be expanded to "LaTeX"
+    (setq answer (car-safe (assoc-string answer TeX-command-list t)))
+    (if (and answer
+             (not (string-equal answer "")))
+        answer
+      default)))
+
+(defvar TeX-command-next nil
+  "The default command next time `TeX-command' is invoked.")
+
+ (make-variable-buffer-local 'TeX-command-next)
+
+(defun TeX-printer-query (&optional queue)
+  "Query the user for a printer name.
+QUEUE is non-nil when we are checking for the printer queue."
+  (let (command element printer)
+    (if queue
+        (unless (setq element 2 command TeX-queue-command)
+          (error "Need to customize `TeX-queue-command'"))
+      (unless (setq element 1 command TeX-print-command)
+          (error "Need to customize `TeX-print-command'")))
+    (while (progn
+             (setq printer (if TeX-printer-list
+                               (let ((completion-ignore-case t))
+                                 (completing-read
+                                  (format "Printer%s: "
+                                          (if TeX-printer-default
+                                              (format " (default %s)" 
TeX-printer-default) ""))
+                                  TeX-printer-list))
+                             ""))
+             (setq printer (or (car-safe (assoc-string printer 
TeX-printer-list t))
+                               printer))
+             (not (if (or (null printer) (string-equal "" printer))
+                      (setq printer TeX-printer-default)
+                    (setq TeX-printer-default printer)))))
+
+    (let ((expansion (let ((entry (assoc printer TeX-printer-list)))
+                       (or (nth element entry)
+                           command))))
+      (if (string-match "%p" printer)
+          (error "Don't use %s in printer names" "%p"))
+      (while (string-match "%p" expansion)
+        (setq expansion (replace-match printer t t expansion 0)))
+      expansion)))
+
+(defun TeX-style-check (styles)
+  "Check STYLES compared to the current style options."
+  (let ((files (TeX-style-list)))
+    (while (and styles
+                (not (TeX-member (car (car styles)) files #'string-match)))
+      (setq styles (cdr styles))))
+  (if styles
+      (nth 1 (car styles))
+    ""))
+
+(defun TeX-output-extension ()
+  "Get the extension of the current TeX output file."
+  (if (listp TeX-output-extension)
+      (car TeX-output-extension)
+    (or (TeX-process-get-variable (TeX-active-master)
+                                  'TeX-output-extension
+                                  TeX-output-extension)
+        TeX-output-extension)))
+
+(defun TeX-view-mouse (event)
+  "Start `TeX-view' at mouse position."
+  (interactive "e")
+  (with-current-buffer (window-buffer (posn-window (event-start event)))
+    (goto-char (posn-point (event-start event)))
+    (TeX-view)))
+
+(defun TeX-region-update-point ()
+  "Syncs the location of point in the region file with the current file.
+
+Thereafter, point in the region file is on the same text as in
+the current buffer.
+
+Do nothing in case the last command hasn't operated on the region
+or `TeX-source-correlate-mode' is disabled."
+  (when (and TeX-current-process-region-p TeX-source-correlate-mode)
+    (let ((region-buf (get-file-buffer (TeX-region-file t)))
+          (orig-line (TeX-current-offset))
+          (pos-in-line (- (point) (max (line-beginning-position)
+                                       (or TeX-command-region-begin
+                                           (region-beginning))))))
+      (when region-buf
+        (with-current-buffer region-buf
+          (goto-char (point-min))
+          (when (re-search-forward "!offset(\\(-?[0-9]+\\)" nil t)
+            (let ((offset (string-to-number (match-string 1))))
+              (goto-char (point-min))
+              (forward-line (- orig-line offset))
+              (forward-char pos-in-line))))))))
+
+(defun TeX-view ()
+  "Start a viewer without confirmation.
+The viewer is started either on region or master file,
+depending on the last command issued."
+  (interactive)
+  (let ((output-file (TeX-active-master (TeX-output-extension))))
+    (if (file-exists-p output-file)
+        (TeX-command "View" #'TeX-active-master 0)
+      (message "Output file %S does not exist." output-file))))
+
+;;; Command Hooks
+
+(defvar TeX-after-compilation-finished-functions nil
+  "Hook being run after TeX/LaTeX/ConTeXt finished successfully.
+The functions in this hook are run with the DVI/PDF output file
+given as argument.  Using this hook can be useful for updating
+the viewer automatically after re-compilation of the document.
+
+If you use an emacs-internal viewer such as `doc-view-mode' or
+`pdf-view-mode', add `TeX-revert-document-buffer' to this hook.")
+
+(make-obsolete-variable 'TeX-after-TeX-LaTeX-command-finished-hook
+                        'TeX-after-compilation-finished-functions
+                        "11.89")
+
+(defun TeX-revert-document-buffer (file)
+  "Revert the buffer visiting FILE.
+This function is intended to be used in
+`TeX-after-compilation-finished-functions' for users that view
+their compiled document with an emacs viewer such as
+`doc-view-mode' or `pdf-view-mode'.  (Note that this function
+just calls `revert-buffer' in the respective buffer and thus
+requires that the corresponding mode defines a sensible
+`revert-buffer-function'.)"
+  (let ((buf (find-buffer-visiting file)))
+    (when buf
+      (with-current-buffer buf
+        (revert-buffer nil t t)))))
+
+(defvar TeX-after-start-process-function
+  #'TeX-adjust-process-coding-system
+  "Function to adjust coding system of an asynchronous process.
+Called with one argument PROCESS.")
+
+(defun TeX-adjust-process-coding-system (process)
+  "Adjust coding system of PROCESS to suitable value.
+Usually coding system is the same as the TeX file with eol format
+adjusted to OS default value.  Take care of Japanese TeX, which
+requires special treatment."
+  (if (and (boundp 'japanese-TeX-mode)
+           (fboundp 'japanese-TeX-set-process-coding-system)
+           (with-current-buffer TeX-command-buffer
+             japanese-TeX-mode))
+      (japanese-TeX-set-process-coding-system process)
+    (let ((cs (coding-system-base (with-current-buffer TeX-command-buffer
+                                    buffer-file-coding-system))))
+      ;; The value of `buffer-file-coding-system' is sometimes
+      ;; undecided-{unix,dos,mac}.  That happens when the file
+      ;; contains no multibyte chars and only end of line format is
+      ;; determined.  Emacs lisp reference recommends not to use
+      ;; undecided-* for process coding system, so it might seem
+      ;; reasonable to change `undecided' into some fixed coding
+      ;; system like this:
+      ;; (if (eq 'undecided cs)
+      ;;     (setq cs 'utf-8))
+      ;; However, that can lose when the following conditions are met:
+      ;; (1) The document is divided into multiple files.
+      ;; (2) The command buffer contains no multibyte chars.
+      ;; (3) The other files contain mutlibyte chars and saved in a
+      ;;     coding system other than the one chosen above.
+      ;; So we leave `undecided' unchanged here.  Although `undecided'
+      ;; is not quite safe for the coding system for encoding, i.e.,
+      ;; keyboard input to the TeX process, we expect that this does
+      ;; not raise serious problems because it is pretty rare that TeX
+      ;; process needs keyboard input of multibyte chars.
+
+      ;; `utf-8-with-signature' (UTF-8 with BOM) doesn't suit at all
+      ;; for the coding system for encoding because it always injects
+      ;; 3-byte BOM in front of its return value (even when the string
+      ;; to be sent has only ascii characters!)  Thus we change it
+      ;; into `utf-8'.  On decoding, `utf-8' can decode UTF-8 with
+      ;; BOM.  So it is safe for both decoding and encoding.
+      (if (eq cs 'utf-8-with-signature)
+          (setq cs 'utf-8))
+
+      ;; Eol format of TeX files can differ from OS default. TeX
+      ;; binaries accept all type of eol format in the given files
+      ;; and output messages according to OS default.  So we set eol
+      ;; format to OS default value.
+      (setq cs (coding-system-change-eol-conversion
+                cs
+                ;; The eol of macosX is LF, not CR.  So we choose
+                ;; other than `unix' only for w32 system.
+                ;; FIXME: what should we do for cygwin?
+                (if (eq system-type 'windows-nt) 'dos 'unix)))
+      (set-process-coding-system process cs cs))))
+
+(defcustom TeX-show-compilation nil
+  "If non-nil, show output of TeX compilation in other window."
+  :group 'TeX-command
+  :type 'boolean)
+
+(defun TeX-run-command (name command file)
+  "Create a process for NAME using COMMAND to process FILE.
+Return the new process."
+  (let ((default TeX-command-default)
+        (buffer (TeX-process-buffer-name file))
+        (dir (TeX-master-directory))
+        (command-buff (current-buffer)))
+    (TeX-process-check file)            ; Check that no process is running
+    (setq-default TeX-command-buffer command-buff)
+    (get-buffer-create buffer)
+    (set-buffer buffer)
+    (buffer-disable-undo)
+    (erase-buffer)
+    (set (make-local-variable 'line-number-display-limit) 0)
+    (setq TeX-output-extension nil)
+    (set (make-local-variable 'TeX-command-buffer) command-buff)
+    (if dir (cd dir))
+    (insert "Running `" name "' on `" file "' with ``" command "''\n")
+    (TeX-output-mode)
+    (if TeX-show-compilation
+        (display-buffer buffer)
+      (message "Type `%s' to display results of compilation."
+               (substitute-command-keys
+                "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
+    (setq TeX-parse-function #'TeX-parse-command)
+    (setq TeX-command-default default)
+    (setq TeX-sentinel-function
+          (lambda (_process name)
+            (message (concat name ": done."))))
+    (if TeX-process-asynchronous
+        (let ((process (start-process name buffer TeX-shell
+                                      TeX-shell-command-option command)))
+          (if TeX-after-start-process-function
+              (funcall TeX-after-start-process-function process))
+          (TeX-command-mode-line process)
+          (set-process-filter process #'TeX-command-filter)
+          (set-process-sentinel process #'TeX-command-sentinel)
+          (set-marker (process-mark process) (point-max))
+          (setq compilation-in-progress (cons process compilation-in-progress))
+          process)
+      (setq mode-line-process ": run")
+      (force-mode-line-update)
+      (call-process TeX-shell nil buffer nil
+                    TeX-shell-command-option command))))
+
+(defun TeX-run-set-command (name command)
+  "Remember TeX command to use to NAME and set corresponding output extension."
+  (setq TeX-command-default name
+        TeX-output-extension
+        (if (and (null (TeX-PDF-from-DVI)) TeX-PDF-mode) "pdf" "dvi"))
+  (let ((case-fold-search t)
+        (lst TeX-command-output-list))
+    (while lst
+      (if (string-match (car (car lst)) command)
+          (setq TeX-output-extension (car (cdr (car lst)))
+                lst nil)
+        (setq lst (cdr lst))))))
+
+(defvar TeX-error-report-switches nil
+  "Reports presence of errors after `TeX-run-TeX'.
+Actually, `TeX-run-format' sets it.
+To test whether the current buffer has a compile error from last
+run of `TeX-run-format', use
+  (TeX-error-report-has-errors-p)")
+
+(defun TeX-error-report-has-errors-p ()
+  "Return non-nil if current buffer has compile errors from last TeX run."
+  (plist-get TeX-error-report-switches (intern (TeX-master-file))))
+
+(defun TeX-run-format (name command file)
+  "Create a process for NAME using COMMAND to format FILE with TeX."
+  (TeX-run-set-command name command)
+  (let ((current-master (TeX-master-file))
+        (buffer (TeX-process-buffer-name file))
+        (process (TeX-run-command name command file)))
+
+    ;; Save information in TeX-error-report-switches
+    ;; Initialize error to nil (no error) for current master.
+    ;; Presence of error is reported inside `TeX-TeX-sentinel-check'
+
+    ;; the current master file is saved because error routines are
+    ;; parsed in other buffers;
+    (setq TeX-error-report-switches
+          (plist-put TeX-error-report-switches
+                     'TeX-current-master current-master))
+    ;; reset error to nil (no error)
+    (setq TeX-error-report-switches
+          (plist-put TeX-error-report-switches
+                     (intern current-master) nil))
+
+    ;; Hook to TeX debugger.
+    (with-current-buffer buffer
+      (TeX-parse-reset)
+      (setq TeX-parse-function #'TeX-parse-TeX)
+      (setq TeX-sentinel-function #'TeX-TeX-sentinel)
+      (if TeX-process-asynchronous
+          (progn
+            ;; Updating the mode line.
+            (setq TeX-current-page "[0]")
+            (TeX-format-mode-line process)
+            (set-process-filter process #'TeX-format-filter)))
+      process)))
+
+(defun TeX-run-TeX (name command file)
+  "Create a process for NAME using COMMAND to format FILE with TeX."
+
+  (let ((idx-file nil) (element nil))
+    ;; Store md5 hash of the index file before running LaTeX.
+    (and (memq major-mode '(doctex-mode latex-mode))
+         (prog1 (file-exists-p
+                 (setq idx-file (expand-file-name (TeX-active-master "idx"))))
+           ;; In order to avoid confusion and pollution of
+           ;; `LaTeX-idx-md5-alist', remove from this alist all md5 hashes of
+           ;; the current index file.  Note `assq-delete-all' doesn't work with
+           ;; string keys and has problems with non-list elements in Emacs 21
+           ;; (see file tex-site.el).
+           (while (setq element (assoc idx-file LaTeX-idx-md5-alist))
+             (setq LaTeX-idx-md5-alist (delq element LaTeX-idx-md5-alist))))
+         (with-temp-buffer
+           (insert-file-contents-literally idx-file)
+           (push (cons idx-file (md5 (current-buffer))) LaTeX-idx-md5-alist))))
+
+  ;; can we assume that TeX-sentinel-function will not be changed
+  ;; during (TeX-run-format ..)? --pg
+  ;; rather use let* ? --pg
+
+  (if TeX-interactive-mode
+      (TeX-run-interactive name command file)
+    (let* ((sentinel-function TeX-sentinel-default-function)
+           (process (TeX-run-format name command file)))
+      (setq TeX-sentinel-function sentinel-function)
+      (if TeX-process-asynchronous
+          process
+        (TeX-synchronous-sentinel name file process)))))
+
+;; backward compatibilty
+
+(defalias 'TeX-run-LaTeX #'TeX-run-TeX)
+
+
+(defun TeX-run-BibTeX (name command file)
+  "Create a process for NAME using COMMAND to format FILE with BibTeX."
+  (let ((process (TeX-run-command name command file)))
+    (setq TeX-sentinel-function #'TeX-BibTeX-sentinel)
+    (if TeX-process-asynchronous
+        process
+      (TeX-synchronous-sentinel name file process))))
+
+(defun TeX-run-Biber (name command file)
+  "Create a process for NAME using COMMAND to format FILE with Biber."
+  (let ((process (TeX-run-command name command file)))
+    (setq TeX-sentinel-function #'TeX-Biber-sentinel)
+    (if TeX-process-asynchronous
+        process
+      (TeX-synchronous-sentinel name file process))))
+
+(defun TeX-run-dvips (name command file)
+  "Create a process for NAME using COMMAND to convert FILE with dvips."
+  (let ((process (TeX-run-command name command file)))
+    (setq TeX-sentinel-function #'TeX-dvips-sentinel)
+    (if TeX-process-asynchronous
+        process
+      (TeX-synchronous-sentinel name file process))))
+
+(defun TeX-run-dvipdfmx (name command file)
+  "Create a process for NAME using COMMAND to convert FILE with dvipdfmx."
+  (let ((process (TeX-run-command name command file)))
+    (setq TeX-sentinel-function #'TeX-dvipdfmx-sentinel)
+    (if TeX-process-asynchronous
+        process
+      (TeX-synchronous-sentinel name file process))))
+
+(defun TeX-run-ps2pdf (name command file)
+  "Create a process for NAME using COMMAND to convert FILE with ps2pdf."
+  (let ((process (TeX-run-command name command file)))
+    (setq TeX-sentinel-function #'TeX-ps2pdf-sentinel)
+    (if TeX-process-asynchronous
+        process
+      (TeX-synchronous-sentinel name file process))))
+
+(defun TeX-run-index (name command file)
+  "Create a process for NAME using COMMAND to compile the index file."
+  (let ((process (TeX-run-command name command file))
+        (element nil))
+    (setq TeX-sentinel-function #'TeX-index-sentinel)
+    ;; Same cleaning as that for `LaTeX-idx-md5-alist' in `TeX-run-TeX'.
+    (while (setq element
+                 ;; `file' has been determined in `TeX-command-buffer', while
+                 ;; this function has `TeX-master-directory' as
+                 ;; `default-directory', then we have to expand `file' 
file-name
+                 ;; in the same directory of `TeX-command-buffer'.
+                 (assoc (with-current-buffer TeX-command-buffer
+                            (expand-file-name (TeX-active-master "idx")))
+                        LaTeX-idx-changed-alist))
+      (setq LaTeX-idx-changed-alist (delq element LaTeX-idx-changed-alist)))
+    (if TeX-process-asynchronous
+        process
+      (TeX-synchronous-sentinel name file process))))
+
+(defun TeX-run-compile (_name command _file)
+  "Ignore first and third argument, start compile with second argument."
+  (let ((default-directory (TeX-master-directory)))
+    (setq TeX-command-buffer (compile command)))
+  ;; Make `compilation-mode' recognize file names with spaces.
+  ;; (bug#36483)
+  ;; FIXME: This is just an ad-hoc workaround and it's better to fix
+  ;; the regular expression in compile.el properly, if possible.  But
+  ;; there was no response to such request in emacs-devel@gnu.org.
+  (with-current-buffer TeX-command-buffer
+    (make-local-variable 'compilation-error-regexp-alist)
+    ;; Add slightly modified entry of the one associated with `comma'
+    ;; in `compilation-error-regexp-alist-alist' to pick up file names
+    ;; with spaces.
+    (add-to-list 'compilation-error-regexp-alist
+                 '("^\"\\([^,\"\n\t]+\\)\", line \\([0-9]+\\)\
+\\(?:[(. pos]+\\([0-9]+\\))?\\)?[:.,; (-]\\( warning:\\|[-0-9 ]*(W)\\)?" 1 2 3 
(4))
+                 t)))
+
+(defun TeX-run-shell (_name command _file)
+  "Ignore first and third argument, start shell-command with second argument."
+  (let ((default-directory (TeX-master-directory)))
+    (shell-command command)
+    (if (eq system-type 'ms-dos)
+        (redraw-display))))
+
+(defun TeX-run-discard (_name command _file)
+  "Start COMMAND as process, discarding its output.
+NAME and FILE are ignored."
+  (let ((default-directory (TeX-master-directory)))
+    (call-process TeX-shell
+                  nil 0 nil
+                  TeX-shell-command-option
+                  command)))
+
+(defun TeX-run-discard-foreground (_name command _file)
+  "Call process with second argument in the foreground, discarding its output.
+With support for MS-DOS, especially when dviout is used with PC-9801 series."
+  (if (and (boundp 'dos-machine-type) (eq dos-machine-type 'pc98)) ;if PC-9801
+      (send-string-to-terminal "\e[2J")) ; clear screen
+  (call-process TeX-shell (if (eq system-type 'ms-dos) "con") nil nil
+                TeX-shell-command-option command)
+  (if (eq system-type 'ms-dos)
+      (redraw-display)))
+(defalias 'TeX-run-dviout #'TeX-run-discard-foreground)
+
+(defun TeX-run-background (name command _file)
+  "Start process with second argument, show output when and if it arrives."
+  (let ((dir (TeX-master-directory)))
+    (set-buffer (get-buffer-create "*TeX background*"))
+    (if dir (cd dir))
+    (erase-buffer)
+    (let ((process (start-process (concat name " background")
+                                  nil TeX-shell
+                                  TeX-shell-command-option command)))
+      (if TeX-after-start-process-function
+          (funcall TeX-after-start-process-function process))
+      (set-process-filter process #'TeX-background-filter)
+      (set-process-query-on-exit-flag process nil))))
+
+(defun TeX-run-silent (name command _file)
+  "Start process with second argument."
+  (let ((dir (TeX-master-directory)))
+    (set-buffer (get-buffer-create "*TeX silent*"))
+    (if dir (cd dir))
+    (erase-buffer)
+    (let ((process (start-process (concat name " silent")
+                                  (current-buffer) TeX-shell
+                                  TeX-shell-command-option command)))
+      (if TeX-after-start-process-function
+          (funcall TeX-after-start-process-function process))
+      (set-process-query-on-exit-flag process nil))))
+
+(defun TeX-run-interactive (name command file)
+  "Run TeX interactively.
+Run command in a buffer (in comint-shell-mode) so that it accepts user
+interaction. If you return to the file buffer after the TeX run,
+Error parsing on \\[next-error] should work with a bit of luck."
+  (TeX-run-set-command name command)
+  (require 'comint)
+  (let ((default TeX-command-default)
+        (buffer (TeX-process-buffer-name file))
+        (process nil)
+        (dir (TeX-master-directory))
+        (command-buff (current-buffer))
+        (sentinel-function TeX-sentinel-default-function)) ; inherit from 
major mode
+    (TeX-process-check file)            ; Check that no process is running
+    (setq-default TeX-command-buffer command-buff)
+    (with-output-to-temp-buffer buffer)
+    (set-buffer buffer)
+    (set (make-local-variable 'TeX-command-buffer) command-buff)
+    (setq buffer-read-only nil)
+    (if dir (cd dir))
+    (insert "Running `" name "' on `" file "' with ``" command "''\n")
+    (comint-exec buffer name TeX-shell nil
+                 (list TeX-shell-command-option command))
+    (comint-mode)
+    (add-hook 'comint-output-filter-functions #'TeX-interactive-goto-prompt)
+    (setq mode-name name)
+    (setq TeX-command-default default)
+    (setq process (get-buffer-process buffer))
+    (if TeX-after-start-process-function
+        (funcall TeX-after-start-process-function process))
+    (TeX-command-mode-line process)
+    (set-process-sentinel process #'TeX-command-sentinel)
+    (set-marker (process-mark process) (point-max))
+    (setq compilation-in-progress (cons process compilation-in-progress))
+    (TeX-parse-reset)
+    (setq TeX-parse-function #'TeX-parse-TeX)
+    ;; use the sentinel-function that the major mode sets, not the LaTeX one
+    (setq TeX-sentinel-function sentinel-function)))
+
+(defun TeX-run-function (_name command _file)
+  "Execute Lisp function or function call given as the string COMMAND.
+Parameters NAME and FILE are ignored."
+  (let ((fun (car (read-from-string command))))
+    (if (functionp fun) (funcall fun) (eval fun t))))
+
+(defun TeX-run-discard-or-function (name command file)
+  "Start COMMAND as process or execute it as a Lisp function.
+If run as a process, the output is discarded.  COMMAND is
+expected to be a string.  NAME and FILE are ignored."
+  (if (functionp (car (read-from-string command)))
+      (TeX-run-function name command file)
+    (TeX-run-discard name command file)))
+
+(defun TeX-run-ispell-on-document (_command _ignored _name)
+  "Run Ispell on all open files belonging to the current document.
+This function is *obsolete* and only here for compatibility
+reasons.  Use `TeX-run-function' instead."
+  (interactive)
+  (TeX-ispell-document ""))
+
+
+;;; Command Sentinels
+
+(defun TeX-synchronous-sentinel (name file result)
+  "Process TeX command output buffer after the process dies."
+  (let ((buffer (TeX-process-buffer (file-name-nondirectory file))))
+    (with-current-buffer buffer
+
+      ;; Append post-mortem information to the buffer
+      (goto-char (point-max))
+      (insert "\n" mode-name (if (and result (zerop result))
+                                 " finished" " exited") " at "
+              (substring (current-time-string) 0 -5))
+      (setq mode-line-process ": exit")
+
+      ;; Do command specific actions.
+      (setq TeX-command-next TeX-command-Show)
+      (goto-char (point-min))
+      (apply TeX-sentinel-function nil name nil)
+
+      ;; Force mode line redisplay soon
+      (force-mode-line-update))))
+
+(defun TeX-command-sentinel (process msg)
+  "Process TeX command output buffer after the PROCESS dies.
+Insert MSG with some additional information."
+  ;; Set `TeX-transient-master' here because `preview-parse-messages'
+  ;; may open files and thereby trigger master file questions which we
+  ;; don't want and need because we already know the master.  Use
+  ;; `TeX-master-file' instead of `TeX-active-master' to determine the
+  ;; master because the region file should never be the master.
+  (let* ((TeX-transient-master (TeX-master-file))
+         (buffer (process-buffer process))
+         (name (process-name process)))
+    (cond ((null (buffer-name buffer))  ; buffer killed
+           (set-process-buffer process nil)
+           (set-process-sentinel process nil))
+          ((memq (process-status process) '(signal exit))
+           (with-current-buffer buffer
+
+             ;; Append post-mortem information to the buffer
+             (goto-char (point-max))
+             (insert-before-markers "\n" mode-name " " msg)
+             (forward-char -1)
+             (insert " at "
+                     (substring (current-time-string) 0 -5))
+             (forward-char 1)
+
+             ;; Do command specific actions.
+             (TeX-command-mode-line process)
+             (setq TeX-command-next TeX-command-Show)
+             (goto-char (point-min))
+             (apply TeX-sentinel-function process name nil)
+
+
+             ;; If buffer and mode line will show that the process
+             ;; is dead, we can delete it now.  Otherwise it
+             ;; will stay around until M-x list-processes.
+             (delete-process process))
+
+           ;; Force mode line redisplay soon
+           ;; Do this in all buffers (bug#38058 and bug#40965)
+           (force-mode-line-update t))))
+
+  (setq compilation-in-progress (delq process compilation-in-progress)))
+
+
+(defvar TeX-sentinel-function (lambda (_process _name) nil)
+  "Hook to cleanup TeX command buffer after termination of PROCESS.
+NAME is the name of the process.")
+
+(make-variable-buffer-local 'TeX-sentinel-function)
+
+
+(defvar TeX-sentinel-default-function (lambda (_process _name) nil)
+  "Default for `TeX-sentinel-function'.  To be set in major mode.
+Hook to cleanup TeX command buffer after termination of PROCESS.
+NAME is the name of the process.")
+
+(make-variable-buffer-local 'TeX-sentinel-default-function)
+
+(defun TeX-TeX-sentinel (process name)
+  "Cleanup TeX output buffer after running TeX.
+
+Parse the output buffer to collect errors and warnings if the
+variable `TeX-parse-all-errors' is non-nil.
+
+Open the error overview if
+`TeX-error-overview-open-after-TeX-run' is non-nil and there are
+errors or warnings to show."
+  (if (TeX-TeX-sentinel-check process name)
+      (progn
+        (if TeX-parse-all-errors
+            (TeX-parse-all-errors))
+        (if (and TeX-error-overview-open-after-TeX-run
+                 (TeX-error-overview-make-entries
+                  (TeX-master-directory) (TeX-active-buffer)))
+            (TeX-error-overview)))
+    (message (concat name ": formatted " (TeX-current-pages)))
+    (let (dvi2pdf)
+        (if (with-current-buffer TeX-command-buffer
+           (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
+         (setq TeX-command-next dvi2pdf)
+       (setq TeX-command-next TeX-command-Show)))))
+
+(defun TeX-current-pages ()
+  "Return string indicating the number of pages formatted."
+  (cond ((null TeX-current-page)
+         "some pages")
+        ((string-match "[^0-9]1[^0-9]" TeX-current-page)
+         (concat TeX-current-page " page"))
+        (t
+         (concat TeX-current-page " pages"))))
+
+(defun TeX-TeX-sentinel-check (process name)
+  "Cleanup TeX output buffer after running TeX.
+Return nil only if no errors were found."
+  (save-excursion
+    (goto-char (point-max))
+    (cond
+     ((and (string-match "ConTeXt" name) (boundp 'ConTeXt-Mark-version)
+           (with-current-buffer TeX-command-buffer
+             (string= ConTeXt-Mark-version "IV")))
+      (when (re-search-backward " > result saved in file: \\(.*?\\), " nil t)
+        (let ((output-file (TeX-match-buffer 1)))
+          ;; Shave off quotation marks if present.
+          (when (string-match "\\`\"\\(.*\\)\"\\'" output-file)
+            (setq output-file (match-string 1 output-file)))
+          (setq TeX-output-extension
+                (if (string-match "\\.\\([^.]*\\)$" output-file)
+                    (match-string 1 output-file)
+                  "dvi")))
+        (if (re-search-forward ", \\([0-9]+\\) shipped pages, " nil t)
+            (setq TeX-current-page (concat "{" (TeX-match-buffer 1) "}")))))
+     (t
+      (if (re-search-backward "^Output written on \\(.*?\\) (\\([0-9]+\\) page"
+                              nil t)
+          (let ((output-file (TeX-match-buffer 1)))
+            (setq TeX-current-page (concat "{" (TeX-match-buffer 2) "}"))
+            ;; Shave off quotation marks if present.
+            (when (string-match "\\`\"\\(.*\\)\"\\'" output-file)
+              (setq output-file (match-string 1 output-file)))
+            (setq TeX-output-extension
+                  (if (string-match "\\.\\([^.]*\\)$" output-file)
+                      (match-string 1 output-file)
+                    "dvi")))))))
+  (if process (TeX-format-mode-line process))
+  (if (re-search-forward "^\\(!\\|.*:[0-9]+:\\) " nil t)
+      (progn
+        (message "%s errors in `%s'. Use %s to display." name (buffer-name)
+                 (substitute-command-keys
+                  "\\<TeX-mode-map>\\[TeX-next-error]"))
+        (setq TeX-command-next TeX-command-default)
+        ;; error reported to TeX-error-report-switches
+        (setq TeX-error-report-switches
+              (plist-put TeX-error-report-switches
+                         (intern (plist-get TeX-error-report-switches
+                                            'TeX-current-master))
+                         t))
+        t)
+    (let (dvi2pdf)
+        (if (with-current-buffer TeX-command-buffer
+           (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
+         (setq TeX-command-next dvi2pdf)
+       (setq TeX-command-next TeX-command-Show)))
+    nil))
+
+;; This regexp should catch warnings of the type
+;;   LaTeX Warning: ...
+;;   LaTeX Font Warning: ...
+;;   Package xyz123 Warning: ...
+;;   Class xyz123 Warning: ...
+(defvar LaTeX-warnings-regexp
+  "\\(?:LaTeX\\|Class\\|Package\\|\\*\\) [-A-Za-z0-9]* ?[Ww]arning:"
+  "Regexp matching LaTeX warnings.")
+
+(defun TeX-LaTeX-sentinel-has-warnings ()
+  "Return non-nil, if the output buffer contains warnings.
+Warnings can be indicated by LaTeX or packages."
+  (save-excursion
+    (goto-char (point-min))
+    (re-search-forward (concat "^" LaTeX-warnings-regexp) nil t)))
+
+(defun TeX-LaTeX-sentinel-has-bad-boxes ()
+  "Return non-nil, if LaTeX output indicates overfull or underfull boxes."
+  (save-excursion
+    (goto-char (point-min))
+    (re-search-forward "^\\(Ov\\|Und\\)erfull \\\\" nil t)))
+
+;; should go into latex.el? --pg
+(defun TeX-LaTeX-sentinel (process name)
+  "Cleanup TeX output buffer after running LaTeX.
+
+Parse the output buffer to collect errors and warnings if the
+variable `TeX-parse-all-errors' is non-nil.
+
+Open the error overview if
+`TeX-error-overview-open-after-TeX-run' is non-nil and there are
+errors or warnings to show."
+  (if TeX-parse-all-errors
+      (TeX-parse-all-errors))
+  (if (and TeX-error-overview-open-after-TeX-run
+           (TeX-error-overview-make-entries
+            (TeX-master-directory) (TeX-active-buffer)))
+      (TeX-error-overview))
+  (cond ((TeX-TeX-sentinel-check process name))
+        ((and (save-excursion
+                (re-search-forward
+                 "^Package biblatex Warning: Please (re)run Biber on the file"
+                 nil t))
+              (with-current-buffer TeX-command-buffer
+                (and (LaTeX-bibliography-list)
+                     (TeX-check-files (TeX-master-file "bbl")
+                                      (TeX-style-list)
+                                      (append TeX-file-extensions
+                                              BibTeX-file-extensions
+                                              TeX-Biber-file-extensions)))))
+         (message "%s%s" "You should run Biber to get citations right, "
+                  (TeX-current-pages))
+         (setq TeX-command-next (with-current-buffer TeX-command-buffer
+                                  TeX-command-Biber)))
+        ((and (save-excursion
+                (re-search-forward
+                 "^\\(?:LaTeX\\|Package natbib\\) Warning: Citation" nil t))
+              (with-current-buffer TeX-command-buffer
+                (and (LaTeX-bibliography-list)
+                     (TeX-check-files (TeX-master-file "bbl")
+                                      (TeX-style-list)
+                                      (append TeX-file-extensions
+                                              BibTeX-file-extensions
+                                              TeX-Biber-file-extensions)))))
+         (message "%s%s" "You should run BibTeX to get citations right, "
+                  (TeX-current-pages))
+         (setq TeX-command-next (with-current-buffer TeX-command-buffer
+                                  TeX-command-BibTeX)))
+        ((re-search-forward "Package biblatex Warning: Please rerun LaTeX" nil 
t)
+         (message "%s%s" "You should run LaTeX again, " (TeX-current-pages))
+         (setq TeX-command-next TeX-command-default))
+        ((re-search-forward "^(biblatex)\\W+Page breaks have changed" nil t)
+         (message "%s%s" "You should run LaTeX again - page breaks have 
changed, "
+                  (TeX-current-pages))
+         (setq TeX-command-next TeX-command-default))
+        ((re-search-forward "^\\(?:LaTeX Warning: Label(s)\\|\
+Package natbib Warning: Citation(s)\\)" nil t)
+         (message "%s%s" "You should run LaTeX again to get references right, "
+                  (TeX-current-pages))
+         (setq TeX-command-next TeX-command-default))
+        ((re-search-forward
+          "^\\(?:(rerunfilecheck)\\|Package hyperref Warning:\\)\\W+\
+Rerun to get outlines right" nil t)
+         (message "%s%s" "You should run LaTeX again to get outlines right, "
+                  (TeX-current-pages))
+         (setq TeX-command-next TeX-command-default))
+        ((re-search-forward "^LaTeX Warning: Reference" nil t)
+         (message "%s%s%s" name ": there were unresolved references, "
+                  (TeX-current-pages))
+         (let (dvi2pdf)
+           (if (with-current-buffer TeX-command-buffer
+                 (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
+               (setq TeX-command-next dvi2pdf)
+             (setq TeX-command-next TeX-command-Show))))
+        ((re-search-forward "^\\(?:LaTeX Warning: Citation\\|\
+Package natbib Warning:.*undefined citations\\)" nil t)
+         (message "%s%s%s" name ": there were unresolved citations, "
+                  (TeX-current-pages))
+         (let (dvi2pdf)
+           (if (with-current-buffer TeX-command-buffer
+                 (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
+               (setq TeX-command-next dvi2pdf)
+             (setq TeX-command-next TeX-command-Show))))
+        ((re-search-forward "^No file .*\\.\\(toc\\|lof\\|lot\\)\\.$" nil t)
+         (message "%s" (concat "You should run LaTeX again to get "
+                               (upcase (match-string-no-properties 1))
+                               " right"))
+         (setq TeX-command-next TeX-command-default))
+        ((re-search-forward "Package longtable Warning: Table widths have \
+changed\\. Rerun LaTeX\\." nil t)
+         (message
+          "%s" "You should run LaTeX again to get table formatting right")
+         (setq TeX-command-next TeX-command-default))
+        ((re-search-forward "^hf-TikZ Warning: Mark '.*' changed\\. \
+Rerun to get mark in right position\\." nil t)
+         (message
+          "%s" "You should run LaTeX again to get TikZ marks in right 
position")
+         (setq TeX-command-next TeX-command-default))
+        ((re-search-forward "^\\* xsim warning: \"rerun\"" nil t)
+         (message
+          "%s" "You should run LaTeX again to synchronize exercise properties")
+         (setq TeX-command-next TeX-command-default))
+        ((re-search-forward
+          "^\\(\\*\\* \\)?J?I?p?\\(La\\|Sli\\)TeX\\(2e\\)? \
+\\(Version\\|ver\\.\\|<[0-9/-]*\\(?:u[^>]*\\)?>\\)" nil t)
+         (let* ((warnings (and TeX-debug-warnings
+                               (TeX-LaTeX-sentinel-has-warnings)))
+                (bad-boxes (and TeX-debug-bad-boxes
+                                (TeX-LaTeX-sentinel-has-bad-boxes)))
+                (add-info (when (or warnings bad-boxes)
+                            (concat " (with "
+                                    (when warnings "warnings")
+                                    (when (and warnings bad-boxes) " and ")
+                                    (when bad-boxes "bad boxes")
+                                    ")"))))
+           (message "%s" (concat name ": successfully formatted "
+                                 (TeX-current-pages) add-info)))
+         (let (dvi2pdf)
+           (if (with-current-buffer TeX-command-buffer
+                 (and TeX-PDF-mode (setq dvi2pdf (TeX-PDF-from-DVI))))
+               (setq TeX-command-next dvi2pdf)
+             (setq TeX-command-next TeX-command-Show))))
+        (t
+         (message "%s%s%s" name ": problems after " (TeX-current-pages))
+         (setq TeX-command-next TeX-command-default)))
+
+  ;; Check whether the idx file changed.
+  (let (idx-file)
+    (and (file-exists-p
+          (setq idx-file
+                (with-current-buffer TeX-command-buffer
+                  (expand-file-name (TeX-active-master "idx")))))
+         ;; imakeidx package automatically runs makeindex, thus, we need to be
+         ;; sure .ind file isn't newer than .idx.
+         (TeX-check-files (with-current-buffer TeX-command-buffer
+                            (expand-file-name (TeX-active-master "ind")))
+                          (with-current-buffer TeX-command-buffer
+                            (list (file-name-nondirectory 
(TeX-active-master))))
+                          '("idx"))
+         (with-temp-buffer
+           (insert-file-contents-literally idx-file)
+           (not (equal
+                 ;; Compare old md5 hash of the idx file with the new one.
+                 (cdr (assoc idx-file LaTeX-idx-md5-alist))
+                 (md5 (current-buffer)))))
+         (push (cons idx-file t) LaTeX-idx-changed-alist)))
+
+  (unless (TeX-error-report-has-errors-p)
+    (run-hook-with-args 'TeX-after-compilation-finished-functions
+                        (with-current-buffer TeX-command-buffer
+                          (expand-file-name
+                           (TeX-active-master (TeX-output-extension)))))))
+
+;; should go into latex.el? --pg
+(defun TeX-BibTeX-sentinel (_process _name)
+  "Cleanup TeX output buffer after running BibTeX."
+  (goto-char (point-max))
+  (cond
+   ;; Check whether BibTeX reports any warnings or errors.
+   ((re-search-backward (concat
+                         "^(There \\(?:was\\|were\\) \\([0-9]+\\) "
+                         "\\(warnings?\\|error messages?\\))")
+                        nil t)
+    ;; Tell the user their number so that she sees whether the
+    ;; situation is getting better or worse.
+    (message (concat "BibTeX finished with %s %s. "
+                     "Type `%s' to display output.")
+             (match-string 1) (match-string 2)
+             (substitute-command-keys
+              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
+   (t
+    (message (concat "BibTeX finished successfully. "
+                     "Run LaTeX again to get citations right."))))
+  ;; In any case, run the default next command.
+  (setq TeX-command-next TeX-command-default))
+
+(defun TeX-Biber-sentinel (_process _name)
+  "Cleanup TeX output buffer after running Biber."
+  (goto-char (point-max))
+  (cond
+   ((re-search-backward "^INFO - \\(WARNINGS\\|ERRORS\\): \\([0-9]+\\)" nil t)
+    (message (concat "Biber finished with %s %s. "
+                     "Type `%s' to display output.")
+             (match-string 2) (downcase (match-string 1))
+             (substitute-command-keys
+              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]"))
+    (setq TeX-command-next TeX-command-default))
+   ((re-search-backward "^FATAL" nil t)
+    (message (concat "Biber had a fatal error and did not finish! "
+                     "Type `%s' to display output.")
+             (substitute-command-keys
+              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]"))
+    (setq TeX-command-next TeX-command-Biber))
+   (t
+    (message (concat "Biber finished successfully. "
+                     "Run LaTeX again to get citations right."))
+    (setq TeX-command-next TeX-command-default))))
+
+(defun TeX-dvips-sentinel (_process _name)
+  "Cleanup TeX output buffer after running dvips."
+  (goto-char (point-max))
+  (cond
+   ((search-backward "TeX Output exited abnormally" nil t)
+    (message "Dvips failed.  Type `%s' to display output."
+             (substitute-command-keys
+              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
+   (t
+    (if (with-current-buffer TeX-command-buffer
+          (and (equal (TeX-PDF-from-DVI) "Dvips") TeX-PDF-mode))
+        (setq TeX-output-extension "ps"
+              TeX-command-next "Ps2pdf"))
+    (message "Dvips finished successfully. "))))
+
+(defun TeX-dvipdfmx-sentinel (_process _name)
+  "Cleanup TeX output buffer after running dvipdfmx."
+  (goto-char (point-max))
+  (cond
+   ((search-backward "TeX Output exited abnormally" nil t)
+    (message "Dvipdfmx failed.  Type `%s' to display output."
+             (substitute-command-keys
+              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
+   (t
+    (if (with-current-buffer TeX-command-buffer
+          (and (equal (TeX-PDF-from-DVI) "Dvipdfmx") TeX-PDF-mode))
+        (setq TeX-output-extension "pdf"
+              TeX-command-next TeX-command-Show))
+    (message "Dvipdfmx finished successfully. "))))
+
+(defun TeX-ps2pdf-sentinel (_process _name)
+  "Cleanup TeX output buffer after running ps2pdf."
+  (goto-char (point-max))
+  (cond
+   ((search-backward "TeX Output exited abnormally" nil t)
+    (message "ps2pdf failed.  Type `%s' to display output."
+             (substitute-command-keys
+              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
+   (t
+    (if (with-current-buffer TeX-command-buffer
+          (and (equal (TeX-PDF-from-DVI) "Dvips") TeX-PDF-mode))
+        (setq TeX-command-next TeX-command-Show
+              TeX-output-extension "pdf"))
+    (message "ps2pdf finished successfully. "))))
+
+(defun TeX-index-sentinel (_process _name)
+  "Cleanup TeX output buffer after compiling index."
+  (goto-char (point-max))
+  (cond
+   ((search-backward "TeX Output exited abnormally" nil t)
+    (message "Index failed.  Type `%s' to display output."
+             (substitute-command-keys
+              "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
+   (t
+    (setq TeX-command-next TeX-command-default)
+    (message (concat "Index finished successfully. "
+                     "Run LaTeX again to get index right.")))))
+
+(defun TeX-command-sequence-sentinel (process string)
+  "Call the appropriate sentinel for the current PROCESS.
+Pass two arguments PROCESS and STRING to the sentinel.
+
+If there are no errors, call back `TeX-command-sequence' using
+`TeX-command-sequence-command' as command argument, unless this
+variable is nil."
+  (with-current-buffer (process-buffer process)
+    (funcall TeX-command-sequence-sentinel process string)
+    (if (string-match "\\(finished\\|exited\\)" string)
+        (with-current-buffer TeX-command-buffer
+          (unless
+              (or
+               (TeX-error-report-has-errors-p)
+               (null TeX-command-sequence-command))
+            (TeX-command-sequence TeX-command-sequence-command nil
+                                  TeX-command-sequence-file-function))))))
+
+;;; Process Control
+
+;; COMPATIBILITY for emacs < 27
+(if (< emacs-major-version 27)
+    (or (assq 'compilation-in-progress minor-mode-alist)
+        (setq minor-mode-alist (cons '(compilation-in-progress " Compiling")
+                                     minor-mode-alist))))
+
+(defun TeX-process-get-variable (name symbol &optional default)
+  "Return the value in the process buffer for NAME of SYMBOL.
+
+Return DEFAULT if the process buffer does not exist or SYMBOL is not
+defined."
+  (let ((buffer (TeX-process-buffer name)))
+    (if (and buffer
+             (local-variable-p symbol buffer))
+        (with-current-buffer buffer
+          (symbol-value symbol))
+      default)))
+
+(defun TeX-process-set-variable (name symbol value)
+  "Set the variable SYMBOL in the process buffer to VALUE.
+Return nil only if no process buffer exists."
+  (let ((buffer (TeX-process-buffer name)))
+    (if buffer
+        (with-current-buffer buffer
+          (set symbol value)
+          t)
+      nil)))
+
+(defun TeX-process-check (name)
+  "Check if a process for the TeX document NAME already exist.
+If so, give the user the choice of aborting the process or the current
+command."
+  (let (process)
+    (while (and (setq process (TeX-process name))
+                (eq (process-status process) 'run))
+      (cond
+       ((yes-or-no-p (concat "Process `"
+                             (process-name process)
+                             "' for document `"
+                             name
+                             "' running, kill it? "))
+        (delete-process process))
+       ((eq (process-status process) 'run)
+           (error "Cannot have two processes for the same document"))))))
+
+(defun TeX-process-buffer-name (name)
+  "Return name of AUCTeX buffer associated with the document NAME."
+  (concat "*" (abbreviate-file-name (expand-file-name name)) " output*"))
+
+(defun TeX-process-buffer (name)
+  "Return the AUCTeX buffer associated with the document NAME."
+  (get-buffer (TeX-process-buffer-name name)))
+
+(defun TeX-process (name)
+  "Return AUCTeX process associated with the document NAME."
+  (and TeX-process-asynchronous
+       (get-buffer-process (TeX-process-buffer name))))
+
+;;; Process Filters
+
+(defun TeX-command-mode-line (process)
+  "Format the mode line for a buffer containing output from PROCESS."
+    (setq mode-line-process (concat ": "
+                                    (symbol-name (process-status process))))
+    (force-mode-line-update))
+
+(defun TeX-command-filter (process string)
+  "Filter to process normal output."
+  (with-current-buffer (process-buffer process)
+    (save-excursion
+      (goto-char (process-mark process))
+      (insert-before-markers string)
+      (set-marker (process-mark process) (point)))))
+
+(defvar TeX-current-page nil
+  "The page number currently being formatted, enclosed in brackets.")
+
+ (make-variable-buffer-local 'TeX-current-page)
+
+(defun TeX-format-mode-line (process)
+  "Format the mode line for a buffer containing TeX output from PROCESS."
+    (setq mode-line-process (concat " " TeX-current-page ": "
+                                    (symbol-name (process-status process))))
+    (force-mode-line-update))
+
+(defun TeX-format-filter (process string)
+  "Filter to process TeX output."
+  (with-current-buffer (process-buffer process)
+    (let (str pos end (pt (marker-position (process-mark process))))
+      (save-excursion
+        (goto-char pt)
+        (insert-before-markers string)
+        (set-marker (process-mark process) (point))
+        ;; Remove line breaks at columns 79 and 80
+        (while (> (point) pt)
+          (end-of-line 0)
+          (when (and (memq (- (point) (line-beginning-position)) '(79 80))
+                     ;; Heuristic: Don't delete the linebreak if the next line
+                     ;; is empty or starts with an opening parenthesis, or if
+                     ;; point is located after a period and in the next line no
+                     ;; word char follows.
+                     (not (memq (char-after (1+ (point))) '(?\n ?\()))
+                     (not (and (eq (char-before) ?.)
+                               (char-after (1+ (point)))
+                               (not (eq ?w (char-syntax (char-after (1+ 
(point)))))))))
+            (delete-char 1)))
+        (goto-char (marker-position (process-mark process)))
+        ;; Determine current page
+        (while (and pt
+                    (skip-chars-backward "^]" pt)
+                    (> (point) pt))
+          (setq end (point))
+          (backward-char)
+          (skip-chars-backward "-0-9\n." (max (point-min) (- pt 128)))
+          (when (and (eq ?\[ (char-before))
+                     (not (eq ?\] (char-after)))
+                     (progn
+                       (setq str (buffer-substring (1- (point)) end)
+                             pos nil)
+                       (while (setq pos (string-match "\n" str pos))
+                         (setq str (replace-match "" t t str)))
+                       (string-match
+                        "\\`\\[-?[0-9]+\\(\\.-?[0-9]+\\)\\{0,9\\}\\]\\'"
+                        str)))
+            (setq TeX-current-page str
+                  pt nil)
+            (TeX-format-mode-line process)))))))
+
+(defvar TeX-parse-function nil
+  "Function to call to parse content of TeX output buffer.")
+(make-variable-buffer-local 'TeX-parse-function)
+
+(defun TeX-background-filter (_process string)
+  "Filter to process background output."
+  (let ((old-window (selected-window))
+        (pop-up-windows t))
+    (TeX-pop-to-buffer "*TeX background*" nil t)
+    (goto-char (point-max))
+    (insert string)
+    (select-window old-window)))
+
+;; Copy and adaption of `comint-postoutput-scroll-to-bottom' from CVS
+;; Emacs of 2005-04-24.
+(defun TeX-interactive-goto-prompt (string)
+  "Move point to prompt of an interactive TeX run."
+  (let* ((selected (selected-window))
+         (current (current-buffer))
+         (process (get-buffer-process current)))
+    (unwind-protect
+        (when process
+          (walk-windows
+           (lambda (window)
+             (when (eq (window-buffer window) current)
+               (select-window window)
+               (when (and (< (point) (process-mark process))
+                          (string-match "^\\? $" string))
+                 (goto-char (process-mark process)))
+               (select-window selected)))
+           nil t))
+      (set-buffer current))))
+
+
+;;; Active Process
+
+(defvar TeX-current-process-region-p nil
+  "Non-nil means that the last TeX command is on a region.")
+
+(defun TeX-active-process ()
+  "Return the active process for the current buffer."
+  (TeX-process (TeX-active-master)))
+
+(defun TeX-active-buffer ()
+  "Return the buffer of the active process for this buffer."
+  (and TeX-command-buffer
+       (with-current-buffer TeX-command-buffer
+         (TeX-process-buffer (TeX-active-master)))))
+
+(defun TeX-active-master (&optional extension nondirectory _ignore)
+  "The master file currently being compiled.
+
+If optional argument EXTENSION is non-nil, add that file extension to
+the name.  Special value t means use `TeX-default-extension'.
+
+If optional second argument NONDIRECTORY is non-nil, do not include
+the directory.
+
+The compatibility argument IGNORE is ignored."
+  ;; The third argument `_ignore' is kept for symmetry with
+  ;; `TeX-master-file's third argument `ask'.  For example, it's used
+  ;; in `TeX-active-master-with-quotes' for backward compatibility.
+  ;; Keep this in mind should you want to use another argument here.
+  ;; See also the similar comment in `TeX-region-file'.
+  (if TeX-current-process-region-p
+      (TeX-region-file extension nondirectory)
+    (TeX-master-file extension nondirectory)))
+
+(defvar TeX-command-buffer nil
+  "The buffer from where the last TeX command was issued.")
+
+;;; Region File
+
+
+(defvar TeX-region-hook nil
+  "List of hooks to run before the region file is saved.
+The hooks are run in the region buffer, you may use the variable
+`TeX-region-master-buffer' to access the buffer of the master
+file and `TeX-region-orig-buffer' to access the buffer where
+\\[TeX-command-region] or \\[TeX-command-buffer] is invoked
+from.")
+
+(defun TeX-quote-filename (file)
+  "Convert file name into a form acceptable to TeX."
+  (let (pos)
+    (while (setq pos (string-match "\\\\" file pos))
+      (setq file (replace-match "/" t t file 0)
+            pos (1+ pos)))
+    (while (setq pos (string-match "[~#]" file pos))
+      (setq file (replace-match "\\\\string\\&" t nil file 0)
+            pos (+ pos 8))))
+  ;; Use \unexpanded so that \message outputs the raw file name.
+  ;; When \usepackage[utf8]{inputenc} is used in standard (pdf)latex,
+  ;; \message does not output non-ascii file name in raw form without
+  ;; \unexpanded, which makes AUCTeX to fail to recognize the file
+  ;; names right when analysing the process output buffer.
+  ;; Note that \usepackage[utf8]{inputenc} is enabled by default in
+  ;; standard (pdf)latex since TeXLive 2018.
+  (if (and (memq major-mode '(latex-mode doctex-mode))
+           ;; Japanese upLaTeX requires the same treatment with
+           ;; respect to non-ascii characters other than Japanese, in
+           ;; file names within \message{}.
+           ;; However, pLaTeX (non u- version) does not support
+           ;; non-ascii file name encoded in UTF-8.  So considering
+           ;; `ptex' doesn't make sense here.  We cater for only
+           ;; `default' and `uptex' engines.
+           (memq TeX-engine '(default uptex)))
+      ;; It would fail to put entire `file' inside \unexpanded{} when
+      ;; the above loop injects \string before "#" and "~".  So put
+      ;; only multibyte characters inside \unexpanded{}.
+      ;; It is safe in upLaTeX to use \unexpanded{} on Japanese
+      ;; characters though they are handled by upLaTeX in a totally
+      ;; different way from inputenc.
+      ;; Thus put all multibyte characters, without considering
+      ;; whether they are Japanese or not, inside \unexpanded{}.
+      (replace-regexp-in-string "[[:multibyte:]]+"
+                                "\\\\unexpanded{\\&}" file t)
+    file))
+
+(defvar-local TeX-region-orig-buffer nil
+  "The original buffer in which the TeX-region was created.")
+
+(defvar-local TeX-region-master-buffer nil
+  "The TeX-master buffer of the document for which the TeX-region
+was created.")
+
+(defun TeX-region-create (file region original offset)
+  "Create a new file named FILE with the string REGION.
+The region is taken from ORIGINAL starting at line OFFSET.
+
+The current buffer and master file is searched, in order to ensure
+that the TeX header and trailer information is also included.
+
+The OFFSET is used to provide the debugger with information about the
+original file."
+  (if (fboundp 'preview--skip-preamble-region)
+      (let ((temp (preview--skip-preamble-region region offset)))
+        (if temp
+            ;; Skip preamble for the sake of predumped formats.
+            (setq region (car temp)
+                  offset (cdr temp)))))
+
+  (let* (;; We shift buffer a lot, so we must keep track of the buffer
+         ;; local variables.
+         (header-end TeX-header-end)
+         (trailer-start TeX-trailer-start)
+
+         ;; We seach for header and trailer in the master file.
+         (orig-buffer (current-buffer))
+         (master-name (TeX-master-file TeX-default-extension))
+         (master-buffer (find-file-noselect master-name))
+
+         ;; Attempt to disable font lock.
+         (font-lock-mode-hook nil)
+         ;; And insert them into the FILE buffer.
+         (file-buffer (let (;; Don't query for master file
+                            (TeX-transient-master t)
+                            ;; Don't choose a special mode (and call its hooks)
+                            (auto-mode-alist nil)
+                            (magic-mode-alist nil)
+                            (enable-local-variables nil)
+                            ;; Don't run any f-f hooks
+                            (find-file-hook nil))
+                        (find-file-noselect file t)))
+         ;; But remember original content.
+         original-content
+
+         ;; We search for the header from the master file, if it is
+         ;; not present in the region.
+         (header (if (string-match header-end region)
+                     ""
+                   (save-excursion
+                     (save-restriction
+                       (set-buffer master-buffer)
+                       (save-excursion
+                         (save-restriction
+                           (widen)
+                           (goto-char (point-min))
+                           ;; NOTE: We use the local value of
+                           ;; TeX-header-end from the master file.
+                           (if (not (re-search-forward TeX-header-end nil t))
+                               ""
+                             (re-search-forward "[\r\n]" nil t)
+                             (buffer-substring-no-properties
+                              (point-min) (point)))))))))
+         (header-offset 0)
+         first-line
+         ;; We search for the trailer from the master file, if it is
+         ;; not present in the region.
+         (trailer-offset 0)
+         (trailer (if (string-match trailer-start region)
+                      ""
+                    (save-excursion
+                      (save-restriction
+                        (set-buffer master-buffer)
+                        (save-excursion
+                          (save-restriction
+                            (widen)
+                            (goto-char (point-max))
+                            ;; NOTE: We use the local value of
+                            ;; TeX-trailer-start from the master file.
+                            (if (not (re-search-backward TeX-trailer-start nil 
t))
+                                ""
+                              ;;(beginning-of-line 1)
+                              (re-search-backward "[\r\n]" nil t)
+                              (setq trailer-offset (TeX-current-offset))
+                              (buffer-substring-no-properties
+                               (point) (point-max))))))))))
+    ;; file name should be relative to master
+    (setq original (TeX-quote-filename (file-relative-name
+                                        original (TeX-master-directory)))
+          master-name (TeX-quote-filename master-name))
+
+    ;; If the first line begins with "%&", put that line separately on
+    ;; the very first line of the region file so that the first line
+    ;; parsing will work.
+    (setq first-line (if (and (> (length header) 1)
+                              (string= (substring header 0 2) "%&"))
+                         ;; This would work even if header has no newline.
+                         (substring header 0 (string-match "\n" header))
+                       ""))
+    (unless (string= first-line "")
+      ;; Remove first-line from header.
+      (setq header (substring header (length first-line)))
+      (setq first-line (concat first-line "\n")))
+
+    (with-current-buffer file-buffer
+      (setq buffer-read-only t
+            buffer-undo-list t)
+      (setq original-content (buffer-string))
+      (let ((inhibit-read-only t))
+        (erase-buffer)
+        (setq buffer-file-coding-system
+              (with-current-buffer master-buffer buffer-file-coding-system))
+        (insert first-line
+                "\\message{ !name(" master-name ")}"
+                header
+                TeX-region-extra
+                "\n\\message{ !name(" original ") !offset(")
+        (setq header-offset (- offset
+                               (1+ (TeX-current-offset))))
+        (insert (int-to-string header-offset)
+                ") }\n"
+                region
+                "\n\\message{ !name("  master-name ") !offset(")
+        (insert (int-to-string (- trailer-offset
+                                  (1+ (TeX-current-offset))))
+                ") }\n"
+                trailer)
+        (setq TeX-region-orig-buffer orig-buffer)
+        (setq TeX-region-master-buffer master-buffer)
+        (run-hooks 'TeX-region-hook)
+        (if (string-equal (buffer-string) original-content)
+            (set-buffer-modified-p nil)
+          (save-buffer 0))))))
+
+(defun TeX-region-file (&optional extension nondirectory _ignore)
+  "Return TeX-region file name with EXTENSION.
+If optional second argument NONDIRECTORY is non-nil, do not include
+the directory.
+
+The compatibility argument IGNORE is ignored."
+  ;; The third argument `_ignore' is kept for symmetry with `TeX-master-file's
+  ;; third argument `ask'.  For example, it's used in `TeX-command-sequence',
+  ;; where we don't know which function has to be called.  Keep this in mind
+  ;; should you want to use another argument here.
+  (let ((master-dir (TeX-master-directory)))
+    (concat (or (TeX--master-output-dir master-dir nondirectory)
+                (if nondirectory "" master-dir))
+            (cond ((eq extension t)
+                   (concat TeX-region "." TeX-default-extension))
+                  (extension
+                   (concat TeX-region "." extension))
+                  (t
+                   TeX-region)))))
+
+(defcustom TeX-region "_region_"
+  "Base name of temporary file for `TeX-command-region' and 
`TeX-command-buffer'."
+  :group 'TeX-command
+  :type 'string)
+
+(defvar LaTeX-command-section-level nil
+  "The section level used for `LaTeX-command-section'.
+Will be initialized to `LaTeX-largest-level' buffer-locally.")
+(make-variable-buffer-local 'LaTeX-command-section-level)
+
+(defun LaTeX-command-section-level ()
+  "Return the value of `LaTeX-command-section-level'.
+Initialize it to `LaTeX-largest-level' if needed."
+  (unless LaTeX-command-section-level
+    (setq LaTeX-command-section-level LaTeX-largest-level))
+  LaTeX-command-section-level)
+
+
+(defun LaTeX-command-section-change-level (arg)
+  "Change `LaTeX-command-section-level' by ARG.
+`LaTeX-command-section-level' is the sectioning level used to
+determine the current section by `LaTeX-command-section'.
+The levels are defined by `LaTeX-section-list'."
+  (interactive "p")
+  (let ((old-level (car (rassoc (list (LaTeX-command-section-level))
+                                LaTeX-section-list))))
+    (setq LaTeX-command-section-level (+ LaTeX-command-section-level arg))
+    (cond
+     ((> LaTeX-command-section-level 6)
+      (setq LaTeX-command-section-level 6)
+      (message "Cannot shrink LaTeX-command-section-level below 
subparagraph."))
+     ((< LaTeX-command-section-level 0)
+      (setq LaTeX-command-section-level 0)
+      (message "Cannot enlarge LaTeX-command-section-level above part."))
+     (t (message "Changed level from %s to %s."
+                 old-level (car (rassoc (list LaTeX-command-section-level)
+                                        LaTeX-section-list)))))))
+
+(defun LaTeX-command-section-boundaries ()
+  "Return the boundaries of the current section as (start . end).
+The section is determined by `LaTeX-command-section-level'."
+  (let* ((case-fold-search nil)
+         (rx (concat "\\\\" (regexp-opt
+                             (mapcar
+                              (lambda (level)
+                                (car (rassoc (list level) LaTeX-section-list)))
+                              (let (r)
+                                (dotimes (i (1+ (LaTeX-command-section-level)))
+                                  (push i r))
+                                r)))
+                     "{")))
+    (cons (save-excursion
+            (re-search-backward rx nil t)
+            (point))
+          (save-excursion
+            (re-search-forward (concat rx "\\|\\\\end{document}") nil t)
+            (forward-line 0)
+            (point)))))
+
+(defun LaTeX-command-section (&optional override-confirm)
+  "Run a command on the current section.
+
+What makes the current section is defined by
+`LaTeX-command-section-level' which can be enlarged or shrunken
+with `LaTeX-command-section-change-level'.
+
+Query the user for a command to run on the temporary file
+specified by the variable `TeX-region'.  The region file will be
+recreated from current section.
+
+If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
+depend on it being positive instead of the entry in
+`TeX-command-list'."
+  (interactive "P")
+  (if (eq major-mode 'latex-mode)
+      (let* ((bounds (LaTeX-command-section-boundaries))
+             (TeX-command-region-begin (car bounds))
+             (TeX-command-region-end (cdr bounds)))
+        (TeX-command-region override-confirm))
+    (error "LaTeX-command-section can only be run on LaTeX documents")))
+
+(defun TeX-command-run-all-region ()
+  "Compile the current region until an error occurs or it is finished."
+  (interactive)
+  (TeX-region-update)
+  (TeX-command-sequence t t #'TeX-region-file))
+
+(defun LaTeX-command-run-all-section ()
+  "Compile the current section until an error occurs or it is finished."
+  (interactive)
+  (if (eq major-mode 'latex-mode)
+      (let* ((bounds (LaTeX-command-section-boundaries))
+             (TeX-command-region-begin (car bounds))
+             (TeX-command-region-end (cdr bounds)))
+        (TeX-region-update)
+        (TeX-command-sequence t t #'TeX-region-file))
+    (error "LaTeX-command-run-all-section can only be run on LaTeX 
documents")))
+
+(defun TeX-command-run-all (arg)
+  "Compile the current document until an error occurs or it is finished.
+With a prefix ARG (`\\[universal-argument] \\[TeX-command-run-all]'),
+compile the current region instead, that is, call
+`TeX-command-run-all-region'.  With multiple prefix
+arguments (`\\[universal-argument] \\[universal-argument] 
\\[TeX-command-run-all]'),
+compile the current section instead, that is, call
+`LaTeX-command-run-all-section'."
+  (interactive "P")
+  (cond
+   ((null arg)       (TeX-command-sequence t t))
+   ((= 4 (car arg))  (TeX-command-run-all-region))
+   (t                (LaTeX-command-run-all-section))))
+
+;;; Parsing
+
+;;; - Global Parser Variables
+
+(defvar TeX-error-point nil
+  "How far we have parsed until now.")
+
+(make-variable-buffer-local 'TeX-error-point)
+
+(defvar TeX-error-file nil
+  "Stack of files in which errors have occurred.")
+
+(make-variable-buffer-local 'TeX-error-file)
+
+(defvar TeX-error-offset nil
+  "Add this to any line numbers from TeX.  Stack like `TeX-error-file'.")
+
+(make-variable-buffer-local 'TeX-error-offset)
+
+(defun TeX-parse-reset (&optional reparse)
+  "Reset all variables used for parsing TeX output.
+If optional argument REPARSE is non-nil, reparse the output log."
+  (setq TeX-error-point (point-min)
+        TeX-error-offset nil
+        TeX-error-file nil
+        TeX-error-list nil
+        TeX-error-last-visited -1)
+  (if reparse
+      (TeX-parse-all-errors)))
+
+;;; - Parsers Hooks
+
+;; All this parsers hooks should have the same arguments even though they will
+;; be ignored, because `TeX-next-error' can call any of these functions.
+(defun TeX-parse-command (_arg _reparse)
+  "We can't parse anything but TeX."
+  (error "I cannot parse %s output, sorry"
+         (if (TeX-active-process)
+             (process-name (TeX-active-process))
+           "this")))
+
+(defun TeX-error-list-skip-warning-p (type ignore)
+  "Decide if a warning of `TeX-error-list' should be skipped.
+
+TYPE is one of the types listed in `TeX-error-list', IGNORE
+is the flag to choose if the warning should be skipped."
+  ;; The warning should be skipped if it...
+  (or
+   ;; ...is a warning and we want to ignore all warnings, or...
+   (and (null TeX-debug-warnings)
+        (equal type 'warning))
+   ;; ...is a bad-box and we want to ignore all bad-boxes, or...
+   (and (null TeX-debug-bad-boxes)
+        (equal type 'bad-box))
+   ;; ...is a warning to be ignored.
+   (and TeX-suppress-ignored-warnings
+        ignore)))
+
+(defun TeX-parse-TeX (arg reparse)
+  "Find the next error produced by running TeX.
+
+ARG specifies how many error messages to move, when possible;
+negative means move back to previous error messages.
+
+If REPARSE is non-nil, reparse the output log.
+
+If the file occurs in an included file, the file is loaded (if not
+already in an Emacs buffer) and the cursor is placed at the error."
+  (let ((old-buffer (current-buffer))
+        max-index item)
+
+    ;; Switch to the output buffer.
+    (with-current-buffer (TeX-active-buffer)
+      (if reparse
+          (TeX-parse-reset reparse))
+      (if TeX-parse-all-errors
+          (progn
+            (setq arg (or arg 1)
+                  max-index (length TeX-error-list))
+            ;; This loop is needed to skip ignored warnings, when
+            ;; `TeX-suppress-ignored-warnings' is non-nil and there are ignore
+            ;; warnings.
+            (while (null (zerop arg))
+              (setq TeX-error-last-visited
+                    ;; Increase or decrese `TeX-error-last-visited' depending 
on
+                    ;; the sign of `arg'.  Note: `signum' is a function from
+                    ;; `cl' library, do not be tempted to use it.
+                    (if (> arg 0)
+                        (1+ TeX-error-last-visited)
+                      (1- TeX-error-last-visited))
+                    item (nth TeX-error-last-visited TeX-error-list))
+              ;; Increase or decrease `arg' only if the warning isn't to be
+              ;; skipped.
+              (unless (TeX-error-list-skip-warning-p (nth 0 item) (nth 10 
item))
+                ;; Note: `signum' is a function from `cl' library, do not be
+                ;; tempted to use it.
+                (setq arg (if (> arg 0)
+                              (1- arg)
+                            (1+ arg)))))
+            (if (< TeX-error-last-visited -1)
+                (setq TeX-error-last-visited -1))
+            (cond ((or (null item)
+                       (< TeX-error-last-visited 0))
+                   (if (> TeX-error-last-visited max-index)
+                       (setq TeX-error-last-visited max-index))
+                   (message "No more errors.")
+                   (beep)
+                   (TeX-pop-to-buffer old-buffer))
+                  (t
+                   (apply #'TeX-find-display-help item))))
+
+        (goto-char TeX-error-point)
+        (TeX-parse-error old-buffer)))))
+
+;;; - Parsing (La)TeX
+
+(defvar TeX-translate-location-file nil)
+(defvar TeX-translate-location-offset nil)
+(defvar TeX-translate-location-line nil)
+(defvar TeX-translate-location-string nil)
+(defvar TeX-translate-location-error nil)
+(defvar TeX-translate-location-context nil)
+
+(defvar TeX-translate-location-hook nil
+  "List of functions to be called before showing an error or warning.
+
+You might want to examine and modify the dynamically bound
+variables
+  `TeX-translate-location-file',
+  `TeX-translate-location-offset',
+  `TeX-translate-location-line',
+  `TeX-translate-location-string',
+  `TeX-translate-location-error', and
+  `TeX-translate-location-context'
+from this hook.")
+
+;; `ignore' flag should be the always the last one in the list of information
+;; for each error/warning, because it can be set within `TeX-warning' by a
+;; custom function taking as argument all information present in
+;; `TeX-error-list' but `ignore', see `TeX-ignore-warnings'.
+(defvar TeX-error-list nil
+  "List of warnings and errors.
+
+Each element of the list is a list of information for a specific
+error or warning.  This is the structure of each element:
+ *  0: type (error, warning, bad-box)
+ *  1: file
+ *  2: line
+ *  3: message of the error or warning
+ *  4: offset
+ *  5: context, to be displayed in the help window
+ *  6: string to search in the buffer, in order to find location
+       of the error or warning
+ *  7: for warnings referring to multiple lines (for exapmle, bad boxes),
+       the last line mentioned in the warning message
+ *  8: t if it is a bad-box, nil otherwise
+ *  9: value of `TeX-error-point'
+ * 10: whether the warning should be ignored
+
+This variable is intended to be set only in output buffer so it
+will be shared among all files of the same document.")
+(make-variable-buffer-local 'TeX-error-list)
+
+(defun TeX-parse-all-errors ()
+  "Parse TeX output buffer to collect all warnings and errors."
+  ;; Reset error list.
+  (setq TeX-error-list nil)
+  (save-excursion
+    (goto-char (point-min))
+    (while (TeX-parse-error nil t)))
+  ;; Reset last visited error.
+  (setq TeX-error-last-visited -1))
+
+(defun TeX-parse-error (old &optional store)
+  "Goto next error.  Pop to OLD buffer if no more errors are found.
+
+If the optional argument STORE is non-nil, the function will
+store the found warning or error in `TeX-error-list' instead of
+displaying the issue.
+
+Return non-nil if an error or warning is found."
+  (let ((regexp
+         (concat
+          ;; TeX error
+          "^\\(!\\|\\(.*?\\):[0-9]+:\\) \\|"
+          ;; New file
+          "(\n?\\([^\n()]+\\)\\|"
+          ;; End of file.
+          "\\()\\)\\|"
+          ;; Hook to change line numbers
+          " !\\(?:offset(\\([---0-9]+\\))\\|"
+          ;; Hook to change file name
+          "name(\\([^)]+\\))\\)\\|"
+          ;; Start of LaTeX bad box
+          "^\\(\\(?:Overfull\\|Underfull\\|Tight\\|Loose\\) "
+          ;;   Horizontal bad box
+          "\\(?:\\\\hbox.* at lines? [0-9]+\\(?:--[0-9]+\\)?$\\|"
+          ;;   Vertical bad box.  See also `TeX-warning'.
+          "\\\\vbox ([ a-z0-9]+) has occurred while \\\\output is active 
\\[[^]]+\\]\\)\\)\\|"
+          ;; LaTeX warning
+          "^\\(" LaTeX-warnings-regexp ".*\\)"))
+        (error-found nil))
+    (while
+        (cond
+         ((null
+           (re-search-forward regexp nil t))
+          ;; No more errors.
+          (unless store
+            (message "No more errors.")
+            (beep)
+            (TeX-pop-to-buffer old))
+          nil)
+         ;; TeX error
+         ((match-beginning 1)
+          (when (match-beginning 2)
+            (unless TeX-error-file
+              (push nil TeX-error-file)
+              (push nil TeX-error-offset))
+            (unless (car TeX-error-offset)
+              (rplaca TeX-error-file (TeX-match-buffer 2))))
+          (setq error-found t)
+          (if (looking-at "Preview ")
+              t
+            (TeX-error store)
+            nil))
+         ;; LaTeX bad box
+         ((match-beginning 7)
+          ;; In `TeX-error-list' we collect all warnings, also if they're going
+          ;; to be actually skipped.
+          (if (or store TeX-debug-bad-boxes)
+              (progn
+                (setq error-found t)
+                (TeX-warning (TeX-match-buffer 7) (match-beginning 7) t store)
+                nil)
+            (re-search-forward "\r?\n\
+\\(?:.\\{79\\}\r?\n\
+\\)*.*\r?$")
+            t))
+         ;; LaTeX warning
+         ((match-beginning 8)
+          ;; In `TeX-error-list' we collect all warnings, also if they're going
+          ;; to be actually skipped.
+          (if (or store TeX-debug-warnings)
+              (progn
+                (setq error-found t)
+                (TeX-warning (TeX-match-buffer 8) (match-beginning 8) nil 
store)
+                nil)
+            t))
+
+         ;; New file -- Push on stack
+         ((match-beginning 3)
+          (let ((file (TeX-match-buffer 3))
+                (end (match-end 3)))
+            ;; Strip quotation marks and remove newlines if necessary
+            (when (or (eq (string-to-char file) ?\")
+                      (string-match "[ \t\n]" file))
+              (setq file (mapconcat #'identity (split-string file "[\"\n]+") 
"")))
+            ;; Polish `file' string
+            (setq file
+                  (let ((string file))
+                    (setq string
+                          (if (string-match "\\`[ \t\n\r]+" string)
+                              (replace-match "" t t string)
+                            string))
+                    ;; Sometimes `file' is something like
+                    ;;     "./path/to/file.tex [9] [10 <./path/to/file>] "
+                    ;; where "[9]" and "[10 <./path/to/file>]" are pages of the
+                    ;; output file, with path to an included file.  Remove 
these
+                    ;; numbers together with whitespaces at the end of the
+                    ;; string.
+                    (if (string-match "\\( *\\(\\[[^]]+\\]\\)? *\\)*\\'" 
string)
+                        (replace-match "" t t string)
+                      string)))
+            (push file TeX-error-file)
+            (push nil TeX-error-offset)
+            (goto-char end))
+          t)
+
+         ;; End of file -- Pop from stack
+         ((match-beginning 4)
+          (when (> (length TeX-error-file) 0)
+            (pop TeX-error-file)
+            (pop TeX-error-offset))
+          (goto-char (match-end 4))
+          t)
+
+         ;; Hook to change line numbers
+         ((match-beginning 5)
+          (setq TeX-error-offset
+                (list (string-to-number (TeX-match-buffer 5))))
+          t)
+
+         ;; Hook to change file name
+         ((match-beginning 6)
+          (setq TeX-error-file
+                (list (TeX-match-buffer 6)))
+          t)))
+    error-found))
+
+(defun TeX-find-display-help (type file line error offset context string
+                                   line-end _bad-box error-point _ignore)
+  "Find the error and display the help.
+
+For a description of arguments, see `TeX-error-list'.  IGNORE
+value is not used here."
+  ;; Go back to TeX-buffer
+  (let ((runbuf (TeX-active-buffer))
+        (master (with-current-buffer TeX-command-buffer
+                  (expand-file-name (TeX-master-file))))
+        (command-buffer TeX-command-buffer)
+        (TeX-translate-location-file file)
+        (TeX-translate-location-line line)
+        (TeX-translate-location-error error)
+        (TeX-translate-location-offset offset)
+        (TeX-translate-location-context context)
+        (TeX-translate-location-string string)
+        error-file-buffer start)
+
+    (run-hooks 'TeX-translate-location-hook)
+
+    (if TeX-translate-location-file
+        (progn
+          (setq error-file-buffer
+                (find-file
+                 (expand-file-name TeX-translate-location-file
+                                   (file-name-directory master))))
+          ;; Use the major mode of `TeX-command-buffer' when visiting
+          ;; the error point.
+          (if (eq major-mode (default-value 'major-mode))
+              (funcall (buffer-local-value 'major-mode command-buffer)))
+          ;; Set the value of `TeX-command-buffer' in the next file
+          ;; with an error to be displayed to the value it has in the
+          ;; current buffer.
+          (setq-local TeX-command-buffer command-buffer)
+
+          ;; Find the location of the error or warning.
+          (when TeX-translate-location-line
+            (goto-char (point-min))
+            (forward-line (+ TeX-translate-location-offset
+                             TeX-translate-location-line -1))
+            (cond
+             ;; Error.
+             ((equal type 'error)
+              (if (not (string= TeX-translate-location-string " "))
+                  (search-forward TeX-translate-location-string nil t)))
+             ;; Warning or bad box.
+             (t
+              (beginning-of-line 0)
+              (setq start (point))
+              (goto-char (point-min))
+              (forward-line (+ TeX-translate-location-offset
+                               line-end -1))
+              (end-of-line)
+              (when TeX-translate-location-string
+                (search-backward TeX-translate-location-string start t)
+                (search-forward TeX-translate-location-string nil t))))))
+      ;; When the file cannot be determined stay here but issue a
+      ;; warning.
+      (message "Could not determine file for %s"
+               (if (eq type 'error) "error" "warning"))
+      (beep))
+
+    ;; Display the help.
+    (cond ((eq TeX-display-help 'expert)
+           (TeX-pop-to-buffer runbuf nil t)
+           (goto-char error-point)
+           (if error-file-buffer
+               (TeX-pop-to-buffer error-file-buffer nil t)))
+          (TeX-display-help
+           (TeX-help-error
+            TeX-translate-location-error
+            (if (equal type 'warning)
+                (concat "\n" TeX-translate-location-context)
+              TeX-translate-location-context)
+            runbuf type))
+          (t
+           (message "! %s" TeX-translate-location-error)))))
+
+(defun TeX-error (&optional store)
+  "Display an error.
+
+If optional argument STORE is non-nil, store the error
+information in `TeX-error-list' instead of displaying the error."
+
+  (let* ( ;; We need the error message to show the user.
+         (error (progn
+                  (re-search-forward "\\(.*\\)")
+                  (TeX-match-buffer 1)))
+
+         ;; And the context for the help window.
+         (context-start (point))
+         context-available
+
+         ;; And the line number to position the cursor.
+         (line (cond
+                ;; regular style
+                ((re-search-forward "l\\.\\([0-9]+\\)" nil t)
+                 (setq context-available t)
+                 (string-to-number (TeX-match-buffer 1)))
+                ;; file:line:error style
+                ((save-excursion
+                   (re-search-backward ":\\([0-9]+\\): "
+                                       (line-beginning-position) t))
+                 (string-to-number (TeX-match-buffer 1)))
+                ;; nothing found
+                (t 1)))
+
+         ;; And a string of the context to search for.
+         (string (progn
+                   (beginning-of-line)
+                   (re-search-forward " \\(\\([^ \t]*$\\)\\|\\($\\)\\)")
+                   (TeX-match-buffer 1)))
+
+         ;; And we have now found to the end of the context.
+         (context (if context-available
+                      (buffer-substring context-start (progn (forward-line 1)
+                                                             (end-of-line)
+                                                             (point)))
+                    ;; There is no real context available, so we
+                    ;; simply show the line with the error message.
+                    (buffer-substring (1- (line-beginning-position))
+                                      context-start)))
+         ;; We may use these in another buffer.
+         (offset (or (car TeX-error-offset) 0))
+         (file (car TeX-error-file))
+         info-list)
+
+    ;; Remember where we was.
+    (setq TeX-error-point (point)
+          info-list (list 'error file line error offset context string nil nil
+                          TeX-error-point nil))
+    (if store
+        ;; Store the error information.
+        (add-to-list 'TeX-error-list info-list t)
+      ;; Find the error point and display the help.
+      (apply #'TeX-find-display-help info-list))))
+
+(defun TeX-warning (warning warning-start bad-box &optional store)
+  "Display a warning for WARNING.
+
+WARNING-START is the position where WARNING starts.  If BAD-BOX
+is non-nil, the warning refers to a bad-box, otherwise it is a
+generic warning.
+
+If optional argument STORE is non-nil, store the warning
+information in `TeX-error-list' instead of displaying the
+warning."
+
+  (let* ( ;; line-string: match 1 is beginning line, match 2 is end line
+         (line-string (if bad-box
+                          "at lines? \\([0-9]*\\)\\(?:--\\([0-9]*\\)\\)?"
+                        ;; Traditional messages say "on input line X",
+                        ;; the LaTeX3 \msg_line_context:. just reads
+                        ;; "on line X".
+                        "on \\(?:input \\)?line \\([0-9]*\\)\\."))
+         ;; word-string: match 1 is the word
+         (word-string (if bad-box "[][\\W() ---]\\(\\w+\\)[][\\W() ---]*$"
+                        ;; Match "ref" in both "Reference `ref' on page NN
+                        ;; undefined" and "Citation 'ref' on page NN 
undefined".
+                        "\\(?:`\\|'\\)\\([-a-zA-Z0-9:]+\\)'"))
+
+         ;; Get error-line (warning).  Don't search before `warning-start' to
+         ;; avoid catching completely unrelated line numbers.
+         (line (when (save-excursion (re-search-backward line-string
+                                                         warning-start t))
+                 (string-to-number (TeX-match-buffer 1))))
+         ;; If this is a bad box and the warning ends with "...at lines MM--NN"
+         ;; we can use "NN" as `line-end', in any other case (including bad
+         ;; boxes ending with "...at line NN") just use `line'.
+         (line-end (if (and bad-box (match-beginning 2))
+                       (string-to-number (TeX-match-buffer 2))
+                     line))
+
+         ;; Find the context
+         (context-start (progn (cond
+                                ((and bad-box (string-match "\\\\hbox" 
warning))
+                                 ;; Horizontal bad box
+                                 (end-of-line))
+                                (bad-box
+                                 ;; Vertical bad box (by exclusion), don't move
+                                 ;; point.  In the output buffer, unlike in the
+                                 ;; actual *.log file, these warnings do not 
end
+                                 ;; with "...is active []", but in the same 
line
+                                 ;; there may be something else, including a 
new
+                                 ;; file opened.  Thus, point shouldn't move
+                                 ;; from the end of the actual bad box warning.
+                                 ;; This is why the corresponding regexp in
+                                 ;; `TeX-parse-error' doesn't match everything
+                                 ;; until the end of the line.
+                                 nil)
+                                (t
+                                 ;; Generic warning.
+                                 (beginning-of-line)))
+                               (point)))
+
+         (context (cond ((string-match LaTeX-warnings-regexp warning)
+                         ;; The warnings matching `LaTeX-warnings-regexp' are
+                         ;; emitted by \GenericWarning macro, or macros based 
on
+                         ;; it (\ClassWarning, \PackageWarning, etc).  After
+                         ;; such warnings there is an empty line, just look for
+                         ;; it to find the end.
+                         (beginning-of-line)
+                         (while (null (eolp))
+                           (forward-line 1))
+                         (buffer-substring context-start (progn (end-of-line)
+                                                                (point))))
+
+                        ((and bad-box (string-match "\\\\vbox" warning))
+                         ;; Vertical bad boxes don't provide any additional
+                         ;; information.  In this case, reuse the `warning' as
+                         ;; `context' and don't move point, so that we avoid
+                         ;; eating the next line that may contain another
+                         ;; warning.  See also comment for `context-start'.
+                         (concat "\n" warning))
+
+                        (t
+                         ;; Horizontal bad boxes.
+                         (forward-line 1)
+                         (end-of-line)
+                         (while (equal (current-column) 79)
+                           (forward-line 1)
+                           (end-of-line))
+                         (buffer-substring context-start (point)))))
+
+         ;; This is where we want to be.
+         (error-point (point))
+
+         ;; Now find the error word.
+         (string (when (save-excursion
+                         (re-search-backward word-string context-start t))
+                   (TeX-match-buffer 1)))
+
+         ;; We might use these in another file.
+         (offset (or (car TeX-error-offset) 0))
+         (file (car TeX-error-file))
+         info-list ignore)
+
+    ;; Second chance to get line number right.  If `line' is nil, check whether
+    ;; the reference to the line number is in `context'.  For example, this is
+    ;; the case for warnings emitted with \ClassWarning and \PackageWarning.
+    ;; XXX: maybe it suffices to evaluate `line' after `context' above, but I
+    ;; don't know if there are cases in which it's important to get `line'
+    ;; before `context'.
+    (and (null line)
+         (string-match line-string context)
+         (setq line-end
+               (setq line (and (match-beginning 1)
+                               (string-to-number (match-string 1 context))))))
+
+    ;; This is where we start next time.
+    (goto-char error-point)
+    (setq TeX-error-point (point))
+
+    ;; Explanation of what follows: we add the warning to `TeX-error-list' even
+    ;; if it has to be ignored, with a flag specifying whether it is ignored.
+    ;; We do so in order to be able to change between "ignore" and 
"dont-ignore"
+    ;; behavior by just looking to the flag, without the need to reparse the
+    ;; output log.
+
+    ;; Store the list of information about the warning.
+    (setq info-list (list (if bad-box 'bad-box 'warning) file line warning
+                          offset context string line-end bad-box
+                          TeX-error-point)
+          ;; Decide whether it should be ignored.
+          ignore (and TeX-ignore-warnings
+                      (cond
+                       ((stringp TeX-ignore-warnings)
+                        (string-match TeX-ignore-warnings warning))
+                       ((fboundp TeX-ignore-warnings)
+                        (apply TeX-ignore-warnings info-list))))
+          ;; Update `info-list'.
+          info-list (append info-list (list ignore)))
+
+    (if store
+        ;; Store the warning information.
+        (add-to-list 'TeX-error-list info-list t)
+      ;; Find the warning point and display the help.
+      (apply #'TeX-find-display-help info-list))))
+
+;;; Error Messages
+
+(defcustom TeX-error-description-list nil
+  "User defined help messages for errors in TeX run.
+See `TeX-error-description-list-local' for its format.  All
+entries have higher priority than those in
+`TeX-error-description-list-local'.
+It must not have a fallback entry that matches any error."
+  :group 'TeX-output
+  :type '(repeat (cons :tag "Entry"
+                       (regexp :tag "Match")
+                       (string :format "Description:\n%v"))))
+
+(defvar TeX-error-description-list-local
+  '((".*" . "No help available"))
+  "Buffer local help messages for errors in TeX run.
+A list of the form (ERR-REGEXP . CONTEXT) used by function
+`TeX-help-error' to display help-text on an error message or warning.
+ERR-REGEXP should be a regular expression matching the error message
+given from TeX/LaTeX, and CONTEXT should be some lines describing that
+error.
+Major modes of AUCTeX can set its own catalogue as buffer local
+value of this variable, as LaTeX mode does.
+Style files of AUCTeX can also add their own entries to buffer local
+value of this variable to provide their own help messages.
+It must end with a fallback entry that matches any error, for example
+\(\".*\" . \"No help available\")")
+
+;;; - Help
+
+(defgroup TeX-error-description-faces nil
+  "Faces used in error descriptions."
+  :prefix "TeX-error-description-"
+  :group 'TeX-output)
+
+(defface TeX-error-description-error
+  ;; This is the same as `error' face in latest GNU Emacs versions.
+  '((((class color) (min-colors 88) (background light))
+     :foreground "Red1" :weight bold)
+    (((class color) (min-colors 88) (background dark))
+     :foreground "Pink" :weight bold)
+    (((class color) (min-colors 16) (background light))
+     :foreground "Red1" :weight bold)
+    (((class color) (min-colors 16) (background dark))
+     :foreground "Pink" :weight bold)
+    (((class color) (min-colors 8))
+     :foreground "red" :weight bold)
+    (t (:inverse-video t :weight bold)))
+  "Face for \"Error\" string in error descriptions.")
+
+(defface TeX-error-description-warning
+  ;; This is the same as `warning' face in latest GNU Emacs versions.
+  '((((class color) (min-colors 16)) :foreground "DarkOrange" :weight bold)
+    (((class color)) :foreground "yellow" :weight bold))
+  "Face for \"Warning\" string in error descriptions.")
+
+(defface TeX-error-description-tex-said
+  ;; This is the same as `font-lock-function-name-face' face in latest GNU
+  ;; Emacs versions.
+  '((((class color) (min-colors 88) (background light))
+     :foreground "Blue1")
+    (((class color) (min-colors 88) (background dark))
+     :foreground "LightSkyBlue")
+    (((class color) (min-colors 16) (background light))
+     :foreground "Blue")
+    (((class color) (min-colors 16) (background dark))
+     :foreground "LightSkyBlue")
+    (((class color) (min-colors 8))
+     :foreground "blue" :weight bold)
+    (t (:inverse-video t :weight bold)))
+  "Face for \"TeX said\" string in error descriptions.")
+
+(defface TeX-error-description-help
+  '((t (:inherit TeX-error-description-tex-said)))
+  "Face for \"Help\" string in error descriptions.")
+
+(defun TeX-help-error (error output runbuffer type)
+  "Print ERROR in context OUTPUT from RUNBUFFER in another window.
+TYPE is a symbol specifing if ERROR is a real error, a warning or
+a bad box."
+
+  (let ((old-buffer (current-buffer))
+        (log-file (with-current-buffer runbuffer
+                    (with-current-buffer TeX-command-buffer
+                      (expand-file-name (TeX-active-master "log")))))
+        (error-description-list
+         (append TeX-error-description-list
+                 (buffer-local-value 'TeX-error-description-list-local
+                                     (buffer-local-value
+                                      'TeX-command-buffer
+                                      runbuffer))))
+        (TeX-error-pointer 0))
+
+    ;; Find help text entry.
+    (while (not (string-match (car (nth TeX-error-pointer
+                                        error-description-list))
+                              error))
+      (setq TeX-error-pointer (+ TeX-error-pointer 1)))
+
+    (TeX-pop-to-buffer (get-buffer-create "*TeX Help*") nil t)
+    (let ((inhibit-read-only t))
+      (erase-buffer)
+      (insert
+       (cond
+        ((equal type 'error)
+         (propertize "ERROR" 'font-lock-face 'TeX-error-description-error))
+        ((equal type 'warning)
+         (propertize "WARNING" 'font-lock-face 'TeX-error-description-warning))
+        ((equal type 'bad-box)
+         (propertize "BAD BOX" 'font-lock-face 
'TeX-error-description-warning)))
+       ": " error
+       (propertize "\n\n--- TeX said ---" 'font-lock-face
+                   'TeX-error-description-tex-said)
+       output
+       (propertize "\n--- HELP ---\n" 'font-lock-face
+                   'TeX-error-description-help)
+       (let ((help (cdr (nth TeX-error-pointer
+                             error-description-list))))
+         (save-excursion
+           (if (and (= (1+ TeX-error-pointer)
+                       (length error-description-list))
+                    (let* ((log-buffer (find-buffer-visiting log-file)))
+                      (if log-buffer
+                          (progn
+                            (set-buffer log-buffer)
+                            (revert-buffer t t))
+                        (setq log-buffer
+                              (find-file-noselect log-file))
+                        (set-buffer log-buffer))
+                      (auto-save-mode nil)
+                      (setq buffer-read-only t)
+                      (goto-char (point-min))
+                      (search-forward error nil t 1))
+                    (re-search-forward "^l\\." nil t)
+                    (re-search-forward "^ [^\n]+$" nil t))
+               (let ((start (1+ (point))))
+                 (forward-char 1)
+                 (re-search-forward "^$")
+                 (concat "From the .log file...\n\n"
+                         (buffer-substring start (point))))
+             help)))))
+    (goto-char (point-min))
+    (TeX-special-mode)
+    (TeX-pop-to-buffer old-buffer nil t)))
+
+;;; Error Overview
+
+(defvar TeX-error-overview-active-buffer nil
+  "The active buffer for the current error overview.")
+
+(defvar TeX-error-overview-orig-frame nil
+  "Frame from which the error overview has been launched.")
+
+(defvar TeX-error-overview-orig-window nil
+  "Window from which the error overview has been launched.")
+
+(defcustom TeX-error-overview-setup nil
+  "The frame setup of the error overview.
+
+The possible value is: `separate-frame' (error oveview in a
+separate frame); with a nil value the current frame is used.
+
+If the display does not support multi frame, the current frame
+will be used regardless of the value of this variable."
+  :group 'TeX-output
+  :type '(choice
+          (const :tag "Error overview in separate frame" separate-frame)
+          (const :tag "Use current frame" nil)))
+
+(defun TeX-error-overview-setup ()
+  "Return the frame setup of the error overview for the current display."
+  (and (display-multi-frame-p) TeX-error-overview-setup))
+
+(defun TeX-error-overview-goto-source (&optional button)
+  "Go to the error point in the source.
+If optional argument BUTTON is non-nil, go to source associated
+to the selected error."
+  (interactive)
+  (let ((index (if button (button-get button 'id) (tabulated-list-get-id)))
+        item window)
+    (if index
+        (progn
+          ;; Select the source frame/window, if still live.
+          (if (TeX-error-overview-setup)
+              (if (frame-live-p TeX-error-overview-orig-frame)
+                  (select-frame TeX-error-overview-orig-frame)
+                (error "You have deleted a vital frame---\
+please restart TeX error overview"))
+            (if (window-live-p TeX-error-overview-orig-window)
+                (select-window TeX-error-overview-orig-window)
+              (error "You have deleted a vital window---\
+please restart TeX error overview")))
+          ;; Get the error details.
+          (with-current-buffer TeX-error-overview-active-buffer
+            (setq item (nth index TeX-error-list)
+                  TeX-error-last-visited index))
+          ;; Find the error and display the help.
+          (with-current-buffer TeX-command-buffer
+            ;; Find the error and display the help.
+            (apply #'TeX-find-display-help item))
+          ;; Return to the error overview.
+          (if (TeX-error-overview-setup)
+              (select-frame TeX-error-overview-frame)
+            (if (setq window
+                      (get-buffer-window TeX-error-overview-buffer-name))
+                ;; If error overview window is visible just select it.
+                (select-window window)
+              ;; Otherwise, split the help window and display the error 
overview
+              ;; near to it.  This should be the only reason for the error
+              ;; overview window not being still visible after the beginning of
+              ;; the function.
+              (select-window
+               (get-buffer-window (cond
+                                   ((eq TeX-display-help 'expert)
+                                    TeX-error-overview-active-buffer)
+                                   (TeX-display-help  "*TeX Help*"))))
+              (if (window-splittable-p (selected-window) t)
+                  (split-window-horizontally)
+                (split-window-vertically))
+              (switch-to-buffer TeX-error-overview-buffer-name))))
+      (message "No more errors.")
+      (beep))))
+
+(defun TeX-error-overview-make-entries (&optional master-dir active-buffer)
+  "Generate the list of errors to be printed using `tabulated-list-entries'.
+Write file names relative to MASTER-DIR when they are not absolute.
+
+ACTIVE-BUFFER is used as buffer from which to extract the list of
+errors.  If nil, defaults to `TeX-error-overview-active-buffer'."
+  (with-current-buffer (or active-buffer TeX-error-overview-active-buffer)
+    (let ((id 0)
+          type file line msg entries)
+      (mapc
+       (lambda (entry)
+         (setq type (nth 0 entry)
+               file (nth 1 entry)
+               line (nth 2 entry)
+               msg  (nth 3 entry))
+         ;; Add the entry only if it isn't to be skipped.
+         (unless (TeX-error-list-skip-warning-p type (nth 10 entry))
+           (push
+            (list
+             ;; ID.
+             id
+             (vector
+              ;; File.
+              (if (stringp file)
+                  (if (file-name-absolute-p file)
+                      file
+                    (file-relative-name file master-dir))
+                "")
+              ;; Line.
+              (if (numberp line)
+                  (number-to-string line)
+                "")
+              ;; Type.
+              (cond
+               ((equal type 'error)
+                (propertize "Error" 'font-lock-face 
'TeX-error-description-error))
+               ((equal type 'warning)
+                (propertize "Warning" 'font-lock-face
+                            'TeX-error-description-warning))
+               ((equal type 'bad-box)
+                (propertize "Bad box" 'font-lock-face
+                            'TeX-error-description-warning))
+               (t
+                ""))
+              ;; Message.
+              (list (if (stringp msg)
+                        ;; Sometimes, the message can be longer than one line,
+                        ;; but print here only the first one.
+                        (progn
+                          (string-match "^.*" msg)
+                          (match-string 0 msg))
+                      "")
+                    'face 'link
+                    'follow-link t
+                    'id id
+                    'action #'TeX-error-overview-goto-source)))
+            entries))
+         ;; Increase the `id' counter in any case.
+         (setq id (1+ id)))
+       TeX-error-list)
+      (reverse entries))))
+
+(defun TeX-error-overview-next-error (&optional arg)
+  "Move to the next line and find the associated error.
+
+A prefix ARG specifies how many error messages to move; negative
+means move back to previous error messages."
+  (interactive "p")
+  (if (= (forward-line arg) 0)
+      (TeX-error-overview-goto-source)
+    ;; If there are lines left to move we are at the beginning or at the end of
+    ;; the buffer and there are no more errors.
+    (message "No more errors.")
+    (beep)))
+
+(defun TeX-error-overview-previous-error (&optional arg)
+  "Move to the previous line and find the associated error.
+
+Prefix ARG says how many error messages to move backward (or
+forward, if negative)."
+  (interactive "p")
+  (TeX-error-overview-next-error (- arg)))
+
+(defun TeX-error-overview-jump-to-source ()
+  "Display the help and move point to the error source."
+  (interactive)
+  (TeX-error-overview-goto-source)
+  (pop-to-buffer
+   (save-window-excursion
+     (select-window TeX-error-overview-orig-window)
+     (current-buffer))))
+
+(defun TeX-error-overview-goto-log ()
+  "Display the current error in log buffer."
+  (interactive)
+  (let ((TeX-display-help 'expert))
+    (TeX-error-overview-goto-source)))
+
+(defun TeX-error-overview-toggle-debug-bad-boxes ()
+  "Run `TeX-toggle-debug-bad-boxes' and update entries list."
+  (interactive)
+  (TeX-toggle-debug-bad-boxes)
+  (setq tabulated-list-entries
+        (TeX-error-overview-make-entries
+         (with-current-buffer TeX-command-buffer (TeX-master-directory))))
+  (tabulated-list-init-header)
+  (tabulated-list-print))
+
+(defun TeX-error-overview-toggle-debug-warnings ()
+  "Run `TeX-toggle-debug-warnings' and update entries list."
+  (interactive)
+  (TeX-toggle-debug-warnings)
+  (setq tabulated-list-entries
+        (TeX-error-overview-make-entries
+         (with-current-buffer TeX-command-buffer (TeX-master-directory))))
+  (tabulated-list-init-header)
+  (tabulated-list-print))
+
+(defun TeX-error-overview-toggle-suppress-ignored-warnings ()
+  "Toggle visibility of ignored warnings and update entries list."
+  (interactive)
+  (TeX-toggle-suppress-ignored-warnings)
+  (setq tabulated-list-entries
+        (TeX-error-overview-make-entries
+         (with-current-buffer TeX-command-buffer (TeX-master-directory))))
+  (tabulated-list-init-header)
+  (tabulated-list-print))
+
+(defun TeX-error-overview-quit ()
+  "Delete the window or the frame of the error overview."
+  (interactive)
+  (if (TeX-error-overview-setup)
+      (delete-frame TeX-error-overview-frame)
+    (delete-window))
+  (setq TeX-error-overview-orig-frame nil))
+
+(defvar TeX-error-overview-mode-map
+  (let ((map (make-sparse-keymap)))
+    (define-key map "b"    #'TeX-error-overview-toggle-debug-bad-boxes)
+    (define-key map "j"    #'TeX-error-overview-jump-to-source)
+    (define-key map "l"    #'TeX-error-overview-goto-log)
+    (define-key map "n"    #'TeX-error-overview-next-error)
+    (define-key map "p"    #'TeX-error-overview-previous-error)
+    (define-key map "q"    #'TeX-error-overview-quit)
+    (define-key map "w"    #'TeX-error-overview-toggle-debug-warnings)
+    (define-key map "x"    
#'TeX-error-overview-toggle-suppress-ignored-warnings)
+    (define-key map "\C-m" #'TeX-error-overview-goto-source)
+    map)
+  "Local keymap for `TeX-error-overview-mode' buffers.")
+
+(easy-menu-define TeX-error-overview-menu
+  TeX-error-overview-mode-map
+  "Menu used in TeX error overview mode."
+  '("TeX errors"
+    ["Next error" TeX-error-overview-next-error
+     :help "Jump to the next error"]
+    ["Previous error" TeX-error-overview-previous-error
+     :help "Jump to the previous error"]
+    ["Go to source" TeX-error-overview-goto-source
+     :help "Show the error in the source"]
+    ["Jump to source" TeX-error-overview-jump-to-source
+     :help "Move point to the error in the source"]
+    ["Go to log" TeX-error-overview-goto-log
+     :help "Show the error in the log buffer"]
+    "-"
+    ["Debug Bad Boxes" TeX-error-overview-toggle-debug-bad-boxes
+     :style toggle :selected TeX-debug-bad-boxes
+     :help "Show overfull and underfull boxes"]
+    ["Debug Warnings" TeX-error-overview-toggle-debug-warnings
+     :style toggle :selected TeX-debug-warnings
+     :help "Show warnings"]
+    ["Ignore Unimportant Warnings"
+     TeX-error-overview-toggle-suppress-ignored-warnings
+     :style toggle :selected TeX-suppress-ignored-warnings
+     :help "Hide specified warnings"]
+    "-"
+    ["Quit" TeX-error-overview-quit
+     :help "Quit"]))
+
+(defvar TeX-error-overview-list-entries nil
+  "List of errors to be used in the error overview.")
+
+(define-derived-mode TeX-error-overview-mode tabulated-list-mode
+                     "TeX errors"
+  "Major mode for listing TeX errors."
+  (setq tabulated-list-format [("File" 25 nil)
+                               ("Line" 4 nil :right-align t)
+                               ("Type" 7 nil)
+                               ("Message" 0 nil)]
+        tabulated-list-padding 1
+        tabulated-list-entries TeX-error-overview-list-entries)
+  (tabulated-list-init-header)
+  (tabulated-list-print))
+
+(defcustom TeX-error-overview-frame-parameters
+  '((name . "TeX errors")
+    (title . "TeX errors")
+    (height . 10)
+    (width . 80)
+    (top . (- 0))
+    (left . (- 0))
+    (unsplittable . t)
+    (minibuffer . nil)
+    (vertical-scroll-bars . t)
+    (tool-bar-lines . 0))
+  "Parameters of the error overview frame."
+  :group 'TeX-output
+  :type 'alist
+  :options '((name string) (title string) (height integer) (width integer)
+             (top integer) (left integer) (unsplittable boolean)
+             (minibuffer boolean) (vertical-scroll-bars boolean)
+             (tool-bar-lines integer)))
+
+(defcustom TeX-error-overview-open-after-TeX-run nil
+  "Whether to open automatically the error overview after running TeX."
+  :group 'TeX-output
+  :type 'boolean)
+
+(defun TeX-error-overview ()
+  "Show an overview of the errors occurred in the last TeX run."
+  (interactive)
+  ;; Check requirements before start.
+  (if (setq TeX-error-overview-active-buffer (TeX-active-buffer))
+      ;; `TeX-error-overview-list-entries' is going to be used only as value
+      ;; of `tabulated-list-entries' in `TeX-error-overview-mode'.  In
+      ;; principle, we don't need `TeX-error-overview-list-entries', but
+      ;; `tabulated-list-entries' is buffer-local and we need the list of
+      ;; entries before creating the error overview buffer in order to
+      ;; decide whether we need to show anything.
+      (if (setq TeX-error-overview-list-entries
+                (TeX-error-overview-make-entries
+                 (TeX-master-directory)))
+          (progn
+            (setq TeX-error-overview-orig-window (selected-window)
+                  TeX-error-overview-orig-frame
+                  (window-frame TeX-error-overview-orig-window))
+            ;; Create the error overview buffer.  This is
+            ;; automatically killed before running TeX commands, so if
+            ;; exists it is up-to-date and doesn't need to be
+            ;; re-created.
+            (unless (get-buffer TeX-error-overview-buffer-name)
+              (with-current-buffer
+                  (get-buffer-create TeX-error-overview-buffer-name)
+                (TeX-error-overview-mode)))
+            ;; Move point to the line associated to the last visited
+            ;; error.
+            (with-current-buffer TeX-error-overview-buffer-name
+              (goto-char (point-min))
+              (forward-line (with-current-buffer
+                                TeX-error-overview-active-buffer
+                              TeX-error-last-visited))
+              ;; Create a new frame for the error overview or display the
+              ;; buffer in the same frame, depending on the setup.
+              (if (TeX-error-overview-setup)
+                  (if (frame-live-p TeX-error-overview-frame)
+                      ;; Do not create a duplicate frame if there is
+                      ;; already one, just select it.
+                      (select-frame-set-input-focus
+                       TeX-error-overview-frame)
+                    ;; Create a new frame and store its name.
+                    (select-frame
+                     (setq TeX-error-overview-frame
+                           (make-frame
+                            TeX-error-overview-frame-parameters)))
+                    (set-window-buffer (selected-window)
+                                       TeX-error-overview-buffer-name)
+                    (set-window-dedicated-p (selected-window) t))
+                (TeX-pop-to-buffer TeX-error-overview-buffer-name))))
+        (error (concat "No error or warning to show"
+                       ;; Suggest to display warnings and bad boxes with the
+                       ;; appropriate key-bindings if there are such
+                       ;; messages in the output buffer.  Rationale of the
+                       ;; test: `TeX-error-overview-list-entries' is nil,
+                       ;; but if `TeX-error-list' is not nil it means that
+                       ;; there are hidden warnings/bad boxes.
+                       (when (TeX-process-get-variable (TeX-active-master)
+                                                       'TeX-error-list)
+                         (format ".  Type `%s' and `%s' to display \
+warnings and bad boxes"
+                                 (substitute-command-keys
+                                  
"\\<TeX-mode-map>\\[TeX-toggle-debug-warnings]")
+                                 (substitute-command-keys
+                                  
"\\<TeX-mode-map>\\[TeX-toggle-debug-bad-boxes]"))))))
+    (error "No process for this document")))
+
+;;; Output mode
+
+(define-derived-mode TeX-special-mode special-mode "TeX")
+
+(defvar TeX-output-mode-map
+  (let ((map (make-sparse-keymap)))
+    (set-keymap-parent map TeX-special-mode-map)
+    (define-key map "n" #'TeX-next-error)
+    (define-key map "p" #'TeX-previous-error)
+    (define-key map "b" #'TeX-toggle-debug-bad-boxes)
+    (define-key map "w" #'TeX-toggle-debug-warnings)
+    (define-key map "i" (lambda ()
+                          (interactive)
+                          (with-current-buffer TeX-command-buffer
+                            (TeX-interactive-mode (if TeX-interactive-mode -1 
1)))))
+    (define-key map "s" (lambda ()
+                          (interactive)
+                          (with-current-buffer TeX-command-buffer
+                            (TeX-source-correlate-mode (if 
TeX-source-correlate-mode -1 1)))))
+    map)
+  "Keymap for `TeX-output-mode'.")
+
+(define-derived-mode TeX-output-mode TeX-special-mode "TeX Output"
+  "Major mode for viewing TeX output.
+\\{TeX-output-mode-map} "
+  :syntax-table nil
+  (set (make-local-variable 'revert-buffer-function)
+       #'TeX-output-revert-buffer)
+  ;; special-mode makes it read-only which prevents input from TeX.
+  (setq buffer-read-only nil))
+
+(defun TeX-output-revert-buffer (_ignore-auto _noconfirm)
+  "Rerun the TeX command which of which this buffer was the output."
+  (goto-char (point-min))
+  (if (looking-at "Running `\\(.*\\)' on `\\(.*\\)' with ``\\(.*\\)''$")
+      (let ((name (match-string 1))
+            (file (match-string 2)))
+        (with-current-buffer TeX-command-buffer
+          (TeX-command name (if (string-match TeX-region file)
+                                #'TeX-region-file
+                              #'TeX-master-file))))
+    (error "Unable to find what command to run")))
+
 (provide 'tex)
 
 ;; Local Variables:




reply via email to

[Prev in Thread] Current Thread [Next in Thread]