"Fossies" - the Fresh Open Source Software Archive

Member "auctex-12.3/latex.el" (18 Oct 2020, 271956 Bytes) of package /linux/misc/auctex-12.3.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Lisp source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "latex.el": 12.2_vs_12.3.

    1 ;;; latex.el --- Support for LaTeX documents.
    2 
    3 ;; Copyright (C) 1991, 1993-2020 Free Software Foundation, Inc.
    4 
    5 ;; Maintainer: auctex-devel@gnu.org
    6 ;; Keywords: tex
    7 
    8 ;; This file is part of AUCTeX.
    9 
   10 ;; AUCTeX is free software; you can redistribute it and/or modify it
   11 ;; under the terms of the GNU General Public License as published by
   12 ;; the Free Software Foundation; either version 3, or (at your option)
   13 ;; any later version.
   14 
   15 ;; AUCTeX is distributed in the hope that it will be useful, but
   16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
   17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   18 ;; General Public License for more details.
   19 
   20 ;; You should have received a copy of the GNU General Public License
   21 ;; along with AUCTeX; see the file COPYING.  If not, write to the Free
   22 ;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
   23 ;; 02110-1301, USA.
   24 
   25 ;;; Commentary:
   26 
   27 ;; This file provides AUCTeX support for LaTeX.
   28 
   29 ;;; Code:
   30 
   31 (require 'tex)
   32 (require 'tex-style)
   33 (require 'tex-ispell)
   34 (when (<= 26 emacs-major-version)
   35   ;; latex-flymake requires Emacs 26.
   36   (require 'latex-flymake))
   37 (eval-when-compile
   38   (require 'cl-lib))
   39 
   40 ;; Silence the compiler for functions:
   41 (declare-function outline-level "ext:outline"
   42           nil)
   43 (declare-function outline-mark-subtree "ext:outline"
   44           nil)
   45 (declare-function turn-off-filladapt-mode "ext:filladapt"
   46           nil)
   47 
   48 ;; Silence the compiler for variables:
   49 (defvar outline-heading-alist)
   50 (defvar TeX-auto-file)
   51 (defvar LaTeX-section-list-changed)
   52 
   53 ;;; Syntax
   54 
   55 (defvar LaTeX-optop "["
   56   "The LaTeX optional argument opening character.")
   57 
   58 (defvar LaTeX-optcl "]"
   59   "The LaTeX optional argument closeing character.")
   60 
   61 ;;; Style
   62 
   63 (defcustom LaTeX-default-style "article"
   64   "*Default when creating new documents."
   65   :group 'LaTeX-environment
   66   :type 'string)
   67 
   68 (defcustom LaTeX-default-options nil
   69   "Default options to documentclass.
   70 A comma-seperated list of strings."
   71   :group 'LaTeX-environment
   72   :type '(repeat (string :format "%v")))
   73 
   74 (make-variable-buffer-local 'LaTeX-default-options)
   75 
   76 (defcustom LaTeX-insert-into-comments t
   77   "*Whether insertion commands stay in comments.
   78 This allows using the insertion commands even when
   79 the lines are outcommented, like in dtx files."
   80   :group 'LaTeX-environment
   81   :type 'boolean)
   82 
   83 (defun LaTeX-newline ()
   84   "Start a new line potentially staying within comments.
   85 This depends on `LaTeX-insert-into-comments'."
   86   (interactive)
   87   (if LaTeX-insert-into-comments
   88       (cond ((and (save-excursion (skip-chars-backward " \t") (bolp))
   89           (save-excursion
   90             (skip-chars-forward " \t")
   91             (looking-at (concat TeX-comment-start-regexp "+"))))
   92          (beginning-of-line)
   93          (insert (buffer-substring-no-properties
   94               (line-beginning-position) (match-end 0)))
   95          (newline))
   96         ((and (not (bolp))
   97           (save-excursion
   98             (skip-chars-forward " \t") (not (TeX-escaped-p)))
   99           (looking-at
  100            (concat "[ \t]*" TeX-comment-start-regexp "+[ \t]*")))
  101          (delete-region (match-beginning 0) (match-end 0))
  102          (indent-new-comment-line))
  103         ;; `indent-new-comment-line' does nothing when
  104         ;; `comment-auto-fill-only-comments' is non-il, so we must be sure
  105         ;; to be in a comment before calling it.  In any other case
  106         ;; `newline' is used.
  107         ((TeX-in-comment)
  108          (indent-new-comment-line))
  109         (t
  110          (newline)))
  111     (newline)))
  112 
  113 
  114 ;;; Syntax Table
  115 
  116 (defvar LaTeX-mode-syntax-table (copy-syntax-table TeX-mode-syntax-table)
  117   "Syntax table used in LaTeX mode.")
  118 
  119 (progn ; set [] to match for LaTeX.
  120   (modify-syntax-entry (string-to-char LaTeX-optop)
  121                (concat "(" LaTeX-optcl)
  122                LaTeX-mode-syntax-table)
  123   (modify-syntax-entry (string-to-char LaTeX-optcl)
  124                (concat ")" LaTeX-optop)
  125                LaTeX-mode-syntax-table))
  126 
  127 ;;; Sections
  128 
  129 ;; Declare dynamically scoped vars.
  130 ;; N.B.: These forms are commented out since they produce a "lack of
  131 ;; prefix" warning during byte-compilation.  This way they produce
  132 ;; only a "reference to free variable" one.
  133 ;; (defvar title)
  134 ;; (defvar name)
  135 ;; (defvar level)
  136 ;; (defvar done-mark)
  137 ;; (defvar toc)
  138 
  139 (defun LaTeX-section (arg)
  140   "Insert a template for a LaTeX section.
  141 Determine the type of section to be inserted, by the argument ARG.
  142 
  143 If ARG is nil or missing, use the current level.
  144 If ARG is a list (selected by \\[universal-argument]), go downward one level.
  145 If ARG is negative, go up that many levels.
  146 If ARG is positive or zero, use absolute level:
  147 
  148   0 : part
  149   1 : chapter
  150   2 : section
  151   3 : subsection
  152   4 : subsubsection
  153   5 : paragraph
  154   6 : subparagraph
  155 
  156 The following variables can be set to customize:
  157 
  158 `LaTeX-section-hook'    Hooks to run when inserting a section.
  159 `LaTeX-section-label'   Prefix to all section labels."
  160 
  161   (interactive "*P")
  162   (let* ((val (prefix-numeric-value arg))
  163      (level (cond ((null arg)
  164                (LaTeX-current-section))
  165               ((listp arg)
  166                (LaTeX-down-section))
  167               ((< val 0)
  168                (LaTeX-up-section (- val)))
  169               (t val)))
  170      (name (LaTeX-section-name level))
  171      (toc nil)
  172      (title (if (TeX-active-mark)
  173             (buffer-substring (region-beginning)
  174                       (region-end))
  175           ""))
  176      (done-mark (make-marker)))
  177     (run-hooks 'LaTeX-section-hook)
  178     (LaTeX-newline)
  179     (if (marker-position done-mark)
  180     (goto-char (marker-position done-mark)))
  181     (set-marker done-mark nil)))
  182 
  183 (defun LaTeX-current-section ()
  184   "Return the level of the section that contain point.
  185 See also `LaTeX-section' for description of levels."
  186   (save-excursion
  187     (max (LaTeX-largest-level)
  188      (if (re-search-backward (LaTeX-outline-regexp) nil t)
  189          (- (LaTeX-outline-level) (LaTeX-outline-offset))
  190        (LaTeX-largest-level)))))
  191 
  192 (defun LaTeX-down-section ()
  193   "Return the value of a section one level under the current.
  194 Tries to find what kind of section that have been used earlier in the
  195 text, if this fail, it will just return one less than the current
  196 section."
  197   (save-excursion
  198     (let ((current (LaTeX-current-section))
  199       (next nil)
  200       (regexp (LaTeX-outline-regexp)))
  201       (if (not (re-search-backward regexp nil t))
  202       (1+ current)
  203     (while (not next)
  204       (cond
  205        ((eq (LaTeX-current-section) current)
  206         (if (re-search-forward regexp nil t)
  207         (if (<= (setq next (LaTeX-current-section)) current) ;Wow!
  208             (setq next (1+ current)))
  209           (setq next (1+ current))))
  210        ((not (re-search-backward regexp nil t))
  211         (setq next (1+ current)))))
  212     next))))
  213 
  214 (defun LaTeX-up-section (arg)
  215   "Return the value of the section ARG levels above this one."
  216   (save-excursion
  217     (if (zerop arg)
  218     (LaTeX-current-section)
  219       (let ((current (LaTeX-current-section)))
  220     (while (and (>= (LaTeX-current-section) current)
  221             (re-search-backward (LaTeX-outline-regexp)
  222                     nil t)))
  223     (LaTeX-up-section (1- arg))))))
  224 
  225 (defvar LaTeX-section-list '(("part" 0)
  226                  ("chapter" 1)
  227                  ("section" 2)
  228                  ("subsection" 3)
  229                  ("subsubsection" 4)
  230                  ("paragraph" 5)
  231                  ("subparagraph" 6))
  232   "List which elements is the names of the sections used by LaTeX.")
  233 
  234 (defun LaTeX-section-list-add-locally (sections &optional clean)
  235   "Add SECTIONS to `LaTeX-section-list'.
  236 SECTIONS can be a single list containing the section macro name
  237 as a string and the level as an integer or a list of such lists.
  238 
  239 If optional argument CLEAN is non-nil, remove any existing
  240 entries from `LaTeX-section-list' before adding the new ones.
  241 
  242 The function will make `LaTeX-section-list' buffer-local and
  243 invalidate the section submenu in order to let the menu filter
  244 regenerate it.  It is mainly a convenience function which can be
  245 used in style files."
  246   (when (stringp (car sections))
  247     (setq sections (list sections)))
  248   (make-local-variable 'LaTeX-section-list)
  249   (when clean (setq LaTeX-section-list nil))
  250   (dolist (elt sections) (add-to-list 'LaTeX-section-list elt t))
  251   (setq LaTeX-section-list
  252     (sort (copy-sequence LaTeX-section-list)
  253           (lambda (a b) (< (nth 1 a) (nth 1 b)))))
  254   (setq LaTeX-section-menu nil))
  255 
  256 (defun LaTeX-section-name (level)
  257   "Return the name of the section corresponding to LEVEL."
  258   (let ((entry (TeX-member level LaTeX-section-list
  259                (lambda (a b) (equal a (nth 1 b))))))
  260     (if entry
  261     (nth 0 entry)
  262       nil)))
  263 
  264 (defun LaTeX-section-level (name)
  265   "Return the level of the section NAME."
  266   (let ((entry (TeX-member name LaTeX-section-list
  267                (lambda (a b) (equal a (nth 0 b))))))
  268 
  269     (if entry
  270     (nth 1 entry)
  271       nil)))
  272 
  273 (defcustom TeX-outline-extra nil
  274   "List of extra TeX outline levels.
  275 
  276 Each element is a list with two entries.  The first entry is the
  277 regular expression matching a header, and the second is the level of
  278 the header.  See `LaTeX-section-list' for existing header levels."
  279   :group 'LaTeX
  280   :type '(repeat (group (regexp :tag "Match")
  281             (integer :tag "Level"))))
  282 
  283 (defun LaTeX-outline-regexp (&optional anywhere)
  284   "Return regexp for LaTeX sections.
  285 
  286 If optional argument ANYWHERE is not nil, do not require that the
  287 header is at the start of a line."
  288   (concat (if anywhere "" "^")
  289       "[ \t]*"
  290       (regexp-quote TeX-esc)
  291       "\\(appendix\\|documentstyle\\|documentclass\\|"
  292       (mapconcat 'car LaTeX-section-list "\\|")
  293       "\\)\\b"
  294       (if TeX-outline-extra
  295           "\\|"
  296         "")
  297       (mapconcat 'car TeX-outline-extra "\\|")
  298       "\\|" TeX-header-end
  299       "\\|" TeX-trailer-start))
  300 
  301 (defvar LaTeX-largest-level nil
  302   "Largest sectioning level with current document class.")
  303 
  304 (make-variable-buffer-local 'LaTeX-largest-level)
  305 
  306 (defun LaTeX-largest-level ()
  307   "Return largest sectioning level with current document class.
  308 Run style hooks before it has not been done."
  309   (TeX-update-style)
  310   LaTeX-largest-level)
  311 
  312 (defun LaTeX-largest-level-set (section)
  313   "Set `LaTeX-largest-level' to the level of SECTION.
  314 SECTION has to be a string contained in `LaTeX-section-list'.
  315 Additionally the function will invalidate the section submenu in
  316 order to let the menu filter regenerate it."
  317   (setq LaTeX-largest-level (LaTeX-section-level section))
  318   (let ((offset (LaTeX-outline-offset)))
  319     (when (> offset 0)
  320       (let (lst)
  321     (dolist (tup outline-heading-alist)
  322       (setq lst (cons (cons (car tup)
  323                 (+ offset (cdr tup)))
  324               lst)))
  325     (setq outline-heading-alist (nreverse lst)))))
  326   (setq LaTeX-section-menu nil))
  327 
  328 (defun LaTeX-outline-offset ()
  329   "Offset to add to `LaTeX-section-list' levels to get outline level."
  330   (- 2 (LaTeX-largest-level)))
  331 
  332 (defun TeX-look-at (list)
  333   "Check if we are looking at the first element of a member of LIST.
  334 If so, return the second element, otherwise return nil."
  335   (while (and list
  336           (not (looking-at (nth 0 (car list)))))
  337     (setq list (cdr list)))
  338   (if list
  339       (nth 1 (car list))
  340     nil))
  341 
  342 (defun LaTeX-outline-level ()
  343   "Find the level of current outline heading in an LaTeX document."
  344   (cond ((looking-at LaTeX-header-end) 1)
  345     ((looking-at LaTeX-trailer-start) 1)
  346     ((TeX-look-at TeX-outline-extra)
  347      (max 1 (+ (TeX-look-at TeX-outline-extra)
  348            (LaTeX-outline-offset))))
  349     (t
  350      (save-excursion
  351       (skip-chars-forward " \t")
  352       (forward-char 1)
  353       (cond ((looking-at "appendix") 1)
  354         ((looking-at "documentstyle") 1)
  355         ((looking-at "documentclass") 1)
  356         ((TeX-look-at LaTeX-section-list)
  357          (max 1 (+ (TeX-look-at LaTeX-section-list)
  358                (LaTeX-outline-offset))))
  359         (t (outline-level)))))))
  360 
  361 (defun LaTeX-outline-name ()
  362   "Guess a name for the current header line."
  363   (save-excursion
  364     (if (re-search-forward "{\\([^\}]*\\)}" (+ (point) fill-column 10) t)
  365     (match-string 1)
  366       (buffer-substring (point) (min (point-max) (+ 20 (point)))))))
  367 
  368 (add-hook 'TeX-remove-style-hook
  369       (lambda () (setq LaTeX-largest-level nil)))
  370 
  371 (defcustom LaTeX-section-hook
  372   '(LaTeX-section-heading
  373     LaTeX-section-title
  374 ;; LaTeX-section-toc        ; Most people won't want this
  375     LaTeX-section-section
  376     LaTeX-section-label)
  377   "List of hooks to run when a new section is inserted.
  378 
  379 The following variables are set before the hooks are run
  380 
  381 level - numeric section level, see the documentation of `LaTeX-section'.
  382 name - name of the sectioning command, derived from `level'.
  383 title - The title of the section, default to an empty string.
  384 toc - Entry for the table of contents list, default nil.
  385 done-mark - Position of point afterwards, default nil (meaning end).
  386 
  387 The following standard hook exist -
  388 
  389 LaTeX-section-heading: Query the user about the name of the
  390 sectioning command.  Modifies `level' and `name'.
  391 
  392 LaTeX-section-title: Query the user about the title of the
  393 section.  Modifies `title'.
  394 
  395 LaTeX-section-toc: Query the user for the toc entry.  Modifies
  396 `toc'.
  397 
  398 LaTeX-section-section: Insert LaTeX section command according to
  399 `name', `title', and `toc'.  If `toc' is nil, no toc entry is
  400 inserted.  If `toc' or `title' are empty strings, `done-mark' will be
  401 placed at the point they should be inserted.
  402 
  403 LaTeX-section-label: Insert a label after the section command.
  404 Controled by the variable `LaTeX-section-label'.
  405 
  406 To get a full featured `LaTeX-section' command, insert
  407 
  408  (setq LaTeX-section-hook
  409        '(LaTeX-section-heading
  410      LaTeX-section-title
  411      LaTeX-section-toc
  412      LaTeX-section-section
  413      LaTeX-section-label))
  414 
  415 in your .emacs file."
  416   :group 'LaTeX-macro
  417   :type 'hook
  418   :options '(LaTeX-section-heading
  419          LaTeX-section-title
  420          LaTeX-section-toc
  421          LaTeX-section-section
  422          LaTeX-section-label))
  423 
  424 
  425 (defcustom LaTeX-section-label
  426   '(("part" . "part:")
  427     ("chapter" . "chap:")
  428     ("section" . "sec:")
  429     ("subsection" . "sec:")
  430     ("subsubsection" . "sec:"))
  431   "Default prefix when asking for a label.
  432 
  433 Some LaTeX packages \(such as `fancyref'\) look at the prefix to generate some
  434 text around cross-references automatically.  When using those packages, you
  435 should not change this variable.
  436 
  437 If it is a string, it it used unchanged for all kinds of sections.
  438 If it is nil, no label is inserted.
  439 If it is a list, the list is searched for a member whose car is equal
  440 to the name of the sectioning command being inserted.  The cdr is then
  441 used as the prefix.  If the name is not found, or if the cdr is nil,
  442 no label is inserted."
  443   :group 'LaTeX-label
  444   :type '(choice (const :tag "none" nil)
  445          (string :format "%v" :tag "Common")
  446          (repeat :menu-tag "Level specific"
  447              :format "\n%v%i"
  448              (cons :format "%v"
  449                    (string :tag "Type")
  450                    (choice :tag "Prefix"
  451                        (const :tag "none" nil)
  452                        (string  :format "%v"))))))
  453 
  454 ;;; Section Hooks.
  455 
  456 (defun LaTeX-section-heading ()
  457   "Hook to prompt for LaTeX section name.
  458 Insert this hook into `LaTeX-section-hook' to allow the user to change
  459 the name of the sectioning command inserted with `\\[LaTeX-section]'."
  460   (let ((string (completing-read
  461          (concat "Level (default " name "): ")
  462          LaTeX-section-list
  463          nil nil nil nil name)))
  464     ;; Update name
  465     (if (not (zerop (length string)))
  466     (setq name string))
  467     ;; Update level
  468     (setq level (LaTeX-section-level name))))
  469 
  470 (defun LaTeX-section-title ()
  471   "Hook to prompt for LaTeX section title.
  472 Insert this hook into `LaTeX-section-hook' to allow the user to change
  473 the title of the section inserted with `\\[LaTeX-section]."
  474   (setq title (TeX-read-string "Title: " title))
  475   (let ((region (and (TeX-active-mark)
  476              (cons (region-beginning) (region-end)))))
  477     (when region (delete-region (car region) (cdr region)))))
  478 
  479 (defun LaTeX-section-toc ()
  480   "Hook to prompt for the LaTeX section entry in the table of content .
  481 Insert this hook into `LaTeX-section-hook' to allow the user to insert
  482 a different entry for the section in the table of content."
  483   (setq toc (TeX-read-string "Toc Entry: "))
  484   (if (zerop (length toc))
  485       (setq toc nil)))
  486 
  487 (defun LaTeX-section-section ()
  488   "Hook to insert LaTeX section command into the file.
  489 Insert this hook into `LaTeX-section-hook' after those hooks that set
  490 the `name', `title', and `toc' variables, but before those hooks that
  491 assume that the section is already inserted."
  492   ;; insert a new line if the current line and the previous line are
  493   ;; not empty (except for whitespace), with one exception: do not
  494   ;; insert a new line if the previous (or current, sigh) line starts
  495   ;; an environment (i.e., starts with `[optional whitespace]\begin')
  496   (unless (save-excursion
  497         (re-search-backward
  498          (concat "^\\s-*\n\\s-*\\=\\|^\\s-*" (regexp-quote TeX-esc)
  499              "begin")
  500          (line-beginning-position 0) t))
  501     (LaTeX-newline))
  502   (insert TeX-esc name)
  503   (cond ((null toc))
  504     ((zerop (length toc))
  505      (insert LaTeX-optop)
  506      (set-marker done-mark (point))
  507      (insert LaTeX-optcl))
  508     (t
  509      (insert LaTeX-optop toc LaTeX-optcl)))
  510   (insert TeX-grop)
  511   (if (zerop (length title))
  512       (set-marker done-mark (point)))
  513   (insert title TeX-grcl)
  514   (LaTeX-newline)
  515   ;; If RefTeX is available, tell it that we've just made a new section
  516   (and (fboundp 'reftex-notice-new-section)
  517        (reftex-notice-new-section)))
  518 
  519 (defun LaTeX-section-label ()
  520   "Hook to insert a label after the sectioning command.
  521 Insert this hook into `LaTeX-section-hook' to prompt for a label to be
  522 inserted after the sectioning command.
  523 
  524 The behaviour of this hook is controlled by variable `LaTeX-section-label'."
  525   (and (LaTeX-label name 'section)
  526        (LaTeX-newline)))
  527 
  528 ;;; Environments
  529 
  530 (defgroup LaTeX-environment nil
  531   "Environments in AUCTeX."
  532   :group 'LaTeX-macro)
  533 
  534 (defcustom LaTeX-default-environment "itemize"
  535   "*The default environment when creating new ones with `LaTeX-environment'.
  536 It is overridden by `LaTeX-default-document-environment' when it
  537 is non-nil and the current environment is \"document\"."
  538   :group 'LaTeX-environment
  539   :type 'string)
  540 (make-variable-buffer-local 'LaTeX-default-environment)
  541 
  542 (defvar LaTeX-default-document-environment nil
  543   "The default environment when creating new ones with
  544 `LaTeX-environment' and the current one is \"document\".  This
  545 variable overrides `LaTeX-default-environment'.")
  546 (make-variable-buffer-local 'LaTeX-default-document-environment)
  547 
  548 (defvar LaTeX-default-tabular-environment "tabular"
  549   "The default tabular-like environment used when inserting a table env.
  550 Styles such as tabularx may set it according to their needs.")
  551 (make-variable-buffer-local 'LaTeX-default-tabular-environment)
  552 
  553 (defvar LaTeX-environment-history nil)
  554 
  555 ;; Variable used to cache the current environment, e.g. for repeated
  556 ;; tasks in an environment, like indenting each line in a paragraph to
  557 ;; be filled.  It must not have a non-nil value in general.  That
  558 ;; means it is usually let-bound for such operations.
  559 (defvar LaTeX-current-environment nil)
  560 
  561 (defun LaTeX-environment (arg)
  562   "Make LaTeX environment (\\begin{...}-\\end{...} pair).
  563 With optional ARG, modify current environment.
  564 
  565 It may be customized with the following variables:
  566 
  567 `LaTeX-default-environment'       Your favorite environment.
  568 `LaTeX-default-style'             Your favorite document class.
  569 `LaTeX-default-options'           Your favorite document class options.
  570 `LaTeX-float'                     Where you want figures and tables to float.
  571 `LaTeX-table-label'               Your prefix to labels in tables.
  572 `LaTeX-figure-label'              Your prefix to labels in figures.
  573 `LaTeX-default-format'            Format for array and tabular.
  574 `LaTeX-default-width'             Width for minipage and tabular*.
  575 `LaTeX-default-position'          Position for array and tabular."
  576 
  577   (interactive "*P")
  578   (let* ((default (cond
  579            ((TeX-near-bobp) "document")
  580            ((and LaTeX-default-document-environment
  581              (string-equal (LaTeX-current-environment) "document"))
  582             LaTeX-default-document-environment)
  583            (t LaTeX-default-environment)))
  584      (environment (completing-read (concat "Environment type (default "
  585                            default "): ")
  586                        (LaTeX-environment-list-filtered) nil nil
  587                        nil 'LaTeX-environment-history default)))
  588     ;; Use `environment' as default for the next time only if it is different
  589     ;; from the current default.
  590     (unless (equal environment default)
  591       (setq LaTeX-default-environment environment))
  592 
  593     (let ((entry (assoc environment (LaTeX-environment-list))))
  594       (if (null entry)
  595       (LaTeX-add-environments (list environment)))
  596 
  597       (if arg
  598       (LaTeX-modify-environment environment)
  599     (LaTeX-environment-menu environment)))))
  600 
  601 (defun LaTeX-environment-menu (environment)
  602   "Insert ENVIRONMENT around point or region."
  603   (let ((entry (assoc environment (LaTeX-environment-list))))
  604     (cond ((not (and entry (nth 1 entry)))
  605        (LaTeX-insert-environment environment))
  606       ((numberp (nth 1 entry))
  607        (let ((count (nth 1 entry))
  608          (args ""))
  609          (while (> count 0)
  610            (setq args (concat args TeX-grop TeX-grcl))
  611            (setq count (- count 1)))
  612          (LaTeX-insert-environment environment args)))
  613       ((or (stringp (nth 1 entry)) (vectorp (nth 1 entry)))
  614        (let ((prompts (cdr entry))
  615          (args ""))
  616          (dolist (elt prompts)
  617            (let* ((optional (vectorp elt))
  618               (elt (if optional (elt elt 0) elt))
  619               (arg (TeX-read-string (concat (when optional "(Optional) ")
  620                         elt ": "))))
  621          (setq args (concat args
  622                     (cond ((and optional (> (length arg) 0))
  623                        (concat LaTeX-optop arg LaTeX-optcl))
  624                       ((not optional)
  625                        (concat TeX-grop arg TeX-grcl)))))))
  626          (LaTeX-insert-environment environment args)))
  627       (t
  628        (apply (nth 1 entry) environment (nthcdr 2 entry))))))
  629 
  630 (defun LaTeX-close-environment (&optional reopen)
  631   "Create an \\end{...} to match the current environment.
  632 With prefix-argument, reopen environment afterwards."
  633   (interactive "*P")
  634   (if (> (point)
  635      (save-excursion
  636        (beginning-of-line)
  637        (when LaTeX-insert-into-comments
  638          (if (looking-at comment-start-skip)
  639          (goto-char (match-end 0))))
  640        (skip-chars-forward " \t")
  641        (point)))
  642       (LaTeX-newline))
  643   (let ((environment (LaTeX-current-environment 1)) marker)
  644     (insert "\\end{" environment "}")
  645     (indent-according-to-mode)
  646     (if (or (not (looking-at "[ \t]*$"))
  647         (and (TeX-in-commented-line)
  648          (save-excursion (beginning-of-line 2)
  649                  (not (TeX-in-commented-line)))))
  650     (LaTeX-newline)
  651       (unless (= (forward-line 1) 0)
  652         (insert "\n")))
  653     (indent-according-to-mode)
  654     (when reopen
  655       (save-excursion
  656     (setq marker (point-marker))
  657     (set-marker-insertion-type marker t)
  658     (LaTeX-environment-menu environment)
  659     (delete-region (point)
  660                (if (save-excursion (goto-char marker)
  661                        (bolp))
  662                (1- marker)
  663              marker))
  664     (move-marker marker nil)))))
  665 
  666 (define-obsolete-variable-alias 'LaTeX-after-insert-env-hooks 'LaTeX-after-insert-env-hook "11.89")
  667 
  668 (defvar LaTeX-after-insert-env-hook nil
  669   "List of functions to be run at the end of `LaTeX-insert-environment'.
  670 Each function is called with three arguments: the name of the
  671 environment just inserted, the buffer position just before
  672 \\begin and the position just before \\end.")
  673 
  674 (defun LaTeX-insert-environment (environment &optional extra)
  675   "Insert LaTeX ENVIRONMENT with optional argument EXTRA."
  676   (let ((active-mark (and (TeX-active-mark) (not (eq (mark) (point)))))
  677     prefix content-start env-start env-end)
  678     (when (and active-mark (< (mark) (point))) (exchange-point-and-mark))
  679     ;; Compute the prefix.
  680     (when (and LaTeX-insert-into-comments (TeX-in-commented-line))
  681       (save-excursion
  682     (beginning-of-line)
  683     (looking-at
  684      (concat "^\\([ \t]*" TeX-comment-start-regexp "+\\)+[ \t]*"))
  685     (setq prefix (match-string 0))))
  686     ;; What to do with the line containing point.
  687     ;; - Open a new empty line for later insertion of "\begin{foo}" and
  688     ;;   put the point there.
  689     ;; - If there were at first any non-whitespace texts between the
  690     ;;   point and EOL, send them into their new own line with possible
  691     ;;   comment prefix.
  692     (cond (;; When the entire line consists of whitespaces except
  693        ;; possible prefix...
  694        (save-excursion (beginning-of-line)
  695                (looking-at (concat prefix "[ \t]*$")))
  696        ;; ...make the line empty and put the point there.
  697        (delete-region (match-beginning 0) (match-end 0)))
  698       (;; When there are only whitespaces except possible prefix
  699        ;; between the point and BOL (including the case the point
  700        ;; is at BOL)...
  701        (TeX-looking-at-backward (if prefix
  702                     (concat "^\\(" prefix "\\)?[ \t]*")
  703                       "^[ \t]*")
  704                     (line-beginning-position))
  705        ;; ...in this case, we have non-whitespace texts between
  706        ;; the point and EOL, so send the entire line into a new
  707        ;; next line and put the point on the empty line just
  708        ;; created.
  709        (beginning-of-line)
  710        (newline)
  711        (beginning-of-line 0))
  712       (;; In all other cases...
  713        t
  714        ;; ...insert a new empty line after deleting all
  715        ;; whitespaces around the point, put the point there...
  716        (delete-horizontal-space)
  717        (if (eolp)
  718            (newline)
  719          ;; ...and if there were at first any non-whitespace texts
  720          ;; between (the original position of) the point and EOL,
  721          ;; send them into a new next line with possible comment
  722          ;; prefix.
  723          (newline 2)
  724          (when prefix (insert prefix))
  725          (beginning-of-line 0))))
  726     ;; What to do with the line containing mark.
  727     ;; If there is active region...
  728     (when active-mark
  729       ;; - Open a new empty line for later insertion of "\end{foo}"
  730       ;;   and put the mark there.
  731       ;; - If there were at first any non-whitespace texts between the
  732       ;;   mark and EOL, pass them over the empty line and put them on
  733       ;;   their own line with possible comment prefix.
  734       (save-excursion
  735     (goto-char (mark))
  736     (cond (;; When the entire line consists of whitespaces except
  737            ;; possible prefix...
  738            (save-excursion (beginning-of-line)
  739                    (looking-at
  740                 (if prefix
  741                     (concat "\\(" prefix "\\)?[ \t]*$")
  742                   "[ \t]*$")))
  743            ;; ...make the line empty and put the mark there.
  744            (delete-region (match-beginning 0) (match-end 0)))
  745           (;; When there are only whitespaces except possible prefix
  746            ;; between the mark and BOL (including the case the mark
  747            ;; is at BOL)...
  748            (TeX-looking-at-backward (if prefix
  749                         (concat "^\\(" prefix "\\)?[ \t]*")
  750                       "^[ \t]*")
  751                     (line-beginning-position))
  752            ;; ...in this case, we have non-whitespace texts
  753            ;; between the mark and EOL, so send the entire line
  754            ;; into a new next line and put the mark on the empty
  755            ;; line just created.
  756            (beginning-of-line)
  757            (set-mark (point))
  758            (newline))
  759           (;; In all other cases...
  760            t
  761            ;; ...make a new empty line after deleting all
  762            ;; whitespaces around the mark, put the mark there...
  763            (delete-horizontal-space)
  764            (insert-before-markers "\n")
  765            ;; ...and if there were at first any non-whitespace
  766            ;; texts between (the original position of) the mark
  767            ;; and EOL, send them into a new next line with
  768            ;; possible comment prefix.
  769            (unless (eolp)
  770          (newline)
  771          (when prefix (insert prefix)))))))
  772     ;; Now insert the environment.
  773     (when prefix (insert prefix))
  774     (setq env-start (point))
  775     (insert TeX-esc "begin" TeX-grop environment TeX-grcl)
  776     (indent-according-to-mode)
  777     (when extra (insert extra))
  778     (setq content-start (line-beginning-position 2))
  779     (unless active-mark
  780       (newline)
  781       (when prefix (insert prefix))
  782       (newline))
  783     (when active-mark (goto-char (mark)))
  784     (when prefix (insert prefix))
  785     (insert TeX-esc "end" TeX-grop environment TeX-grcl)
  786     (end-of-line 0)
  787     (if active-mark
  788     (progn
  789       (or (assoc environment LaTeX-indent-environment-list)
  790           (if auto-fill-function
  791           ;; Fill the region only when `auto-fill-mode' is active.
  792           (LaTeX-fill-region content-start (line-beginning-position 2))))
  793       (set-mark content-start))
  794       (indent-according-to-mode))
  795     (save-excursion (beginning-of-line 2) (indent-according-to-mode))
  796     (TeX-math-input-method-off)
  797     (setq env-end (save-excursion
  798             (search-forward
  799              (concat TeX-esc "end" TeX-grop
  800                  environment TeX-grcl))
  801             (match-beginning 0)))
  802     (run-hook-with-args 'LaTeX-after-insert-env-hooks
  803             environment env-start env-end)))
  804 
  805 (defun LaTeX-environment-name-regexp ()
  806   "Return the regexp matching the name of a LaTeX environment.
  807 This matches everything different from a TeX closing brace but
  808 allowing one level of TeX group braces."
  809   (concat "\\([^" (regexp-quote TeX-grcl) (regexp-quote TeX-grop) "]*\\("
  810       (regexp-quote TeX-grop) "[^" (regexp-quote TeX-grcl)
  811       (regexp-quote TeX-grop) "]*" (regexp-quote TeX-grcl) "\\)*[^"
  812       (regexp-quote TeX-grcl) (regexp-quote TeX-grop) "]*\\)"))
  813 
  814 (defvar LaTeX-after-modify-env-hook nil
  815   "List of functions to be run at the end of `LaTeX-modify-environment'.
  816 Each function is called with four arguments: the new name of the
  817 environment, the former name of the environment, the buffer
  818 position just before \\begin and the position just before
  819 \\end.")
  820 
  821 (defun LaTeX-modify-environment (environment)
  822   "Modify current ENVIRONMENT."
  823   (let ((goto-end (lambda ()
  824             (LaTeX-find-matching-end)
  825             (re-search-backward (concat (regexp-quote TeX-esc)
  826                         "end"
  827                         (regexp-quote TeX-grop)
  828                         "\\("
  829                         (LaTeX-environment-name-regexp)
  830                         "\\)"
  831                         (regexp-quote TeX-grcl))
  832                     (save-excursion (beginning-of-line 1) (point)))))
  833     (goto-begin (lambda ()
  834               (LaTeX-find-matching-begin)
  835               (prog1 (point)
  836             (re-search-forward (concat (regexp-quote TeX-esc)
  837                            "begin"
  838                            (regexp-quote TeX-grop)
  839                            "\\("
  840                            (LaTeX-environment-name-regexp)
  841                            "\\)"
  842                            (regexp-quote TeX-grcl))
  843                        (save-excursion (end-of-line 1) (point)))))))
  844     (save-excursion
  845       (funcall goto-end)
  846       (let ((old-env (match-string 1)))
  847     (replace-match environment t t nil 1)
  848     (beginning-of-line 1)
  849     (funcall goto-begin)
  850     (replace-match environment t t nil 1)
  851     (end-of-line 1)
  852     (run-hook-with-args 'LaTeX-after-modify-env-hook
  853                 environment old-env
  854                 (save-excursion (funcall goto-begin))
  855                 (progn (funcall goto-end) (point)))))))
  856 
  857 (defun LaTeX-current-environment (&optional arg)
  858   "Return the name (a string) of the enclosing LaTeX environment.
  859 With optional ARG>=1, find that outer level.
  860 
  861 If function is called inside a comment and
  862 `LaTeX-syntactic-comments' is enabled, try to find the
  863 environment in commented regions with the same comment prefix.
  864 
  865 The functions `LaTeX-find-matching-begin' and `LaTeX-find-matching-end'
  866 work analogously."
  867   (setq arg (if arg (if (< arg 1) 1 arg) 1))
  868   (let* ((in-comment (TeX-in-commented-line))
  869      (comment-prefix (and in-comment (TeX-comment-prefix)))
  870      (case-fold-search nil))
  871     (save-excursion
  872       (while (and (/= arg 0)
  873           (re-search-backward
  874            "\\\\\\(begin\\|end\\) *{ *\\([A-Za-z*]+\\) *}" nil t))
  875     (when (or (and LaTeX-syntactic-comments
  876                (eq in-comment (TeX-in-commented-line))
  877                (or (not in-comment)
  878                ;; Consider only matching prefixes in the
  879                ;; commented case.
  880                (string= comment-prefix (TeX-comment-prefix))))
  881           (and (not LaTeX-syntactic-comments)
  882                (not (TeX-in-commented-line))))
  883       (setq arg (if (string= (match-string 1) "end") (1+ arg) (1- arg)))))
  884       (if (/= arg 0)
  885       "document"
  886     (match-string-no-properties 2)))))
  887 
  888 (defun docTeX-in-macrocode-p ()
  889   "Determine if point is inside a macrocode environment."
  890   (let ((case-fold-search nil))
  891     (save-excursion
  892       (re-search-backward
  893        (concat "^%    " (regexp-quote TeX-esc)
  894            "\\(begin\\|end\\)[ \t]*{macrocode\\*?}") nil 'move)
  895       (not (or (bobp)
  896            (= (char-after (match-beginning 1)) ?e))))))
  897 
  898 
  899 ;;; Environment Hooks
  900 
  901 (defvar LaTeX-document-style-hook nil
  902   "List of hooks to run when inserting a document environment.
  903 
  904 To insert a hook here, you must insert it in the appropriate style file.")
  905 
  906 (defun LaTeX-env-document (&optional _ignore)
  907   "Create new LaTeX document.
  908 Also inserts a \\documentclass macro if there's none already and
  909 prompts for the insertion of \\usepackage macros.
  910 
  911 The compatibility argument IGNORE is ignored."
  912   ;; just assume a single valid \\documentclass, i.e., one not in a
  913   ;; commented line
  914   (let ((found nil))
  915     (save-excursion
  916       (while (and (not found)
  917           (re-search-backward
  918            "\\\\documentclass\\(\\[[^]\n\r]*\\]\\)?\\({[^}]+}\\)"
  919            nil t))
  920     (and (not (TeX-in-commented-line))
  921          (setq found t))))
  922     (when (not found)
  923       (TeX-insert-macro "documentclass")
  924       (LaTeX-newline)
  925       (LaTeX-newline)
  926       ;; Add a newline only if some `\usepackage' has been inserted.
  927       (if (LaTeX-insert-usepackages)
  928       (LaTeX-newline))
  929       (LaTeX-newline)
  930       (end-of-line 0)))
  931   (LaTeX-insert-environment "document")
  932   (run-hooks 'LaTeX-document-style-hook)
  933   (setq LaTeX-document-style-hook nil))
  934 
  935 (defcustom LaTeX-float ""
  936   "Default float position for figures and tables.
  937 If nil, act like the empty string is given, but do not prompt.
  938 \(The standard LaTeX classes use [tbp] as float position if the
  939 optional argument is omitted.)"
  940   :group 'LaTeX-environment
  941   :type '(choice (const :tag "Do not prompt" nil)
  942          (const :tag "Empty" "")
  943          (string :format "%v")))
  944 (make-variable-buffer-local 'LaTeX-float)
  945 
  946 (defcustom LaTeX-top-caption-list nil
  947   "*List of float environments with top caption."
  948   :group 'LaTeX-environment
  949   :type '(repeat (string :format "%v")))
  950 
  951 (defgroup LaTeX-label nil
  952   "Adding labels for LaTeX commands in AUCTeX."
  953   :group 'LaTeX)
  954 
  955 (defcustom LaTeX-label-function nil
  956   "*A function inserting a label at point or returning a label string.
  957 Sole mandatory argument of the function is the environment.  The
  958 function has to return the label inserted, or nil if no label was
  959 inserted.  If the optional argument NO-INSERT is non-nil, then
  960 the function has to return the label as string without any
  961 insertion or nil if no label was read in."
  962   :group 'LaTeX-label
  963   :type 'function)
  964 
  965 (defcustom LaTeX-figure-label "fig:"
  966   "*Default prefix to figure labels."
  967   :group 'LaTeX-label
  968   :group 'LaTeX-environment
  969   :type 'string)
  970 
  971 (defcustom LaTeX-table-label "tab:"
  972   "*Default prefix to table labels."
  973   :group 'LaTeX-label
  974   :group 'LaTeX-environment
  975   :type 'string)
  976 
  977 (defcustom LaTeX-listing-label "lst:"
  978   "Default prefix to listing labels.
  979 This prefix should apply to all environments which typeset
  980 code listings and take a caption and label."
  981   :group 'LaTeX-label
  982   :group 'LaTeX-environment
  983   :type 'string)
  984 
  985 (defcustom LaTeX-default-format ""
  986   "Default format for array and tabular environments."
  987   :group 'LaTeX-environment
  988   :type 'string)
  989 (make-variable-buffer-local 'LaTeX-default-format)
  990 
  991 (defcustom LaTeX-default-width "1.0\\linewidth"
  992   "Default width for minipage and tabular* environments."
  993   :group 'LaTeX-environment
  994   :type 'string)
  995 (make-variable-buffer-local 'LaTeX-default-width)
  996 
  997 (defcustom LaTeX-default-position ""
  998   "Default position for array and tabular environments.
  999 If nil, act like the empty string is given, but do not prompt."
 1000   :group 'LaTeX-environment
 1001   :type '(choice (const :tag "Do not prompt" nil)
 1002          (const :tag "Empty" "")
 1003          string))
 1004 (make-variable-buffer-local 'LaTeX-default-position)
 1005 
 1006 (defcustom LaTeX-equation-label "eq:"
 1007   "*Default prefix to equation labels."
 1008   :group 'LaTeX-label
 1009   :type 'string)
 1010 
 1011 (defcustom LaTeX-eqnarray-label LaTeX-equation-label
 1012   "*Default prefix to eqnarray labels."
 1013   :group 'LaTeX-label
 1014   :type 'string)
 1015 
 1016 (defun LaTeX-env-item (environment)
 1017   "Insert ENVIRONMENT and the first item."
 1018   (LaTeX-insert-environment environment)
 1019   (if (TeX-active-mark)
 1020       (progn
 1021     (LaTeX-find-matching-begin)
 1022     (end-of-line 1))
 1023     (end-of-line 0))
 1024   (delete-char 1)
 1025   (when (looking-at (concat "^[ \t]+$\\|"
 1026                 "^[ \t]*" TeX-comment-start-regexp "+[ \t]*$"))
 1027     (delete-region (point) (line-end-position)))
 1028   (delete-horizontal-space)
 1029   ;; Deactivate the mark here in order to prevent `TeX-parse-macro'
 1030   ;; from swapping point and mark and the \item ending up right after
 1031   ;; \begin{...}.
 1032   (deactivate-mark)
 1033   (LaTeX-insert-item)
 1034   ;; The inserted \item may have outdented the first line to the
 1035   ;; right.  Fill it, if appropriate.
 1036   (when (and (not (looking-at "$"))
 1037          (not (assoc environment LaTeX-indent-environment-list))
 1038          (> (- (line-end-position) (line-beginning-position))
 1039         (current-fill-column)))
 1040     (LaTeX-fill-paragraph nil)))
 1041 
 1042 (defcustom LaTeX-label-alist
 1043   '(("figure" . LaTeX-figure-label)
 1044     ("table" . LaTeX-table-label)
 1045     ("figure*" . LaTeX-figure-label)
 1046     ("table*" . LaTeX-table-label)
 1047     ("equation" . LaTeX-equation-label)
 1048     ("eqnarray" . LaTeX-eqnarray-label))
 1049   "Lookup prefixes for labels.
 1050 An alist where the CAR is the environment name, and the CDR
 1051 either the prefix or a symbol referring to one.
 1052 
 1053 If the name is not found, or if the CDR is nil, no label is
 1054 automatically inserted for that environment.
 1055 
 1056 If you want to automatically insert a label for a environment but
 1057 with an empty prefix, use the empty string \"\" as the CDR of the
 1058 corresponding entry."
 1059   :group 'LaTeX-label
 1060   :type '(repeat (cons (string :tag "Environment")
 1061                (choice (string :tag "Label prefix")
 1062                    (symbol :tag "Label prefix symbol")))))
 1063 
 1064 (make-variable-buffer-local 'LaTeX-label-alist)
 1065 
 1066 (defun LaTeX-label (name &optional type no-insert)
 1067   "Insert a label for NAME at point.
 1068 The optional TYPE argument can be either environment or section:
 1069 in the former case this function looks up `LaTeX-label-alist' to
 1070 choose which prefix to use for the label, in the latter case
 1071 `LaTeX-section-label' will be looked up instead.  If TYPE is nil,
 1072 you will be always prompted for a label, with an empty default
 1073 prefix.
 1074 
 1075 If `LaTeX-label-function' is a valid function, LaTeX label will
 1076 transfer the job to this function.
 1077 
 1078 If the optional NO-INSERT is non-nil, only the label is returned
 1079 and no insertion happens.  Otherwise the inserted label is
 1080 returned, nil if it is empty."
 1081   (let ((TeX-read-label-prefix
 1082      (cond
 1083       ((eq type 'environment)
 1084        (cdr (assoc name LaTeX-label-alist)))
 1085       ((eq type 'section)
 1086        (if (assoc name LaTeX-section-list)
 1087            (if (stringp LaTeX-section-label)
 1088            LaTeX-section-label
 1089          (and (listp LaTeX-section-label)
 1090               (cdr (assoc name LaTeX-section-label))))
 1091          ""))
 1092       ((null type)
 1093        "")
 1094       (t
 1095        nil)))
 1096     label)
 1097     (when (symbolp TeX-read-label-prefix)
 1098       (setq TeX-read-label-prefix (symbol-value TeX-read-label-prefix)))
 1099     (when TeX-read-label-prefix
 1100       (if (and (fboundp LaTeX-label-function))
 1101       (funcall LaTeX-label-function name no-insert)
 1102     ;; Use completing-read as we do with `C-c C-m \label RET'
 1103     (setq label (TeX-read-label t "What label" t))
 1104     ;; No label or empty string entered?
 1105     (if (or (string= TeX-read-label-prefix label)
 1106         (string= "" label))
 1107         (setq label nil)
 1108       ;; We have a label; when NO-INSERT is nil, insert
 1109       ;; \label{label} in the buffer, add new label to list of
 1110       ;; known labels and return it
 1111       (unless no-insert
 1112         (insert TeX-esc "label" TeX-grop label TeX-grcl))
 1113       (LaTeX-add-labels label)
 1114       label)))))
 1115 
 1116 (defcustom LaTeX-short-caption-prompt-length 40
 1117   "The length that the caption of a figure should be before
 1118   propting for \\caption's optional short-version."
 1119   :group 'LaTeX-environment
 1120   :type 'integer)
 1121 
 1122 (defun LaTeX-compose-caption-macro (caption &optional short-caption)
 1123   "Return a \\caption macro for a given CAPTION as a string.
 1124 If SHORT-CAPTION is non-nil pass it as an optional argument to
 1125 \\caption."
 1126   (let ((short-caption-string
 1127          (if (and short-caption
 1128                   (not (string= short-caption "")))
 1129              (concat LaTeX-optop short-caption LaTeX-optcl))))
 1130     (concat TeX-esc "caption" short-caption-string
 1131             TeX-grop caption TeX-grcl)))
 1132 
 1133 (defun LaTeX-env-figure (environment)
 1134   "Create ENVIRONMENT with \\caption and \\label commands."
 1135   (let* ((float (and LaTeX-float        ; LaTeX-float can be nil, i.e.
 1136                     ; do not prompt
 1137                      (TeX-read-string "(Optional) Float position: " LaTeX-float)))
 1138          (caption (TeX-read-string "Caption: "))
 1139          (short-caption (when (>= (length caption) LaTeX-short-caption-prompt-length)
 1140                           (TeX-read-string "(Optional) Short caption: ")))
 1141          (center (y-or-n-p "Center? "))
 1142          (active-mark (and (TeX-active-mark)
 1143                            (not (eq (mark) (point)))))
 1144          start-marker end-marker)
 1145     (when active-mark
 1146       (if (< (mark) (point))
 1147       (exchange-point-and-mark))
 1148       (setq start-marker (point-marker))
 1149       (set-marker-insertion-type start-marker t)
 1150       (setq end-marker (copy-marker (mark))))
 1151     (setq LaTeX-float float)
 1152     (LaTeX-insert-environment environment
 1153                   (unless (zerop (length float))
 1154                 (concat LaTeX-optop float
 1155                     LaTeX-optcl)))
 1156     (when active-mark (goto-char start-marker))
 1157     (when center
 1158       (insert TeX-esc "centering")
 1159       (indent-according-to-mode)
 1160       (LaTeX-newline)
 1161       (indent-according-to-mode))
 1162     ;; Insert caption and ask for a label, do nothing if user skips caption
 1163     (unless (zerop (length caption))
 1164       (if (member environment LaTeX-top-caption-list)
 1165       ;; top caption
 1166       (progn
 1167         (insert (LaTeX-compose-caption-macro caption short-caption))
 1168         ;; If `auto-fill-mode' is active, fill the caption.
 1169         (if auto-fill-function (LaTeX-fill-paragraph))
 1170         (LaTeX-newline)
 1171         (indent-according-to-mode)
 1172         ;; ask for a label and insert a new line only if a label is
 1173         ;; actually inserted
 1174         (when (LaTeX-label environment 'environment)
 1175           (LaTeX-newline)
 1176           (indent-according-to-mode)))
 1177     ;; bottom caption (default)
 1178     (when active-mark (goto-char end-marker))
 1179     (save-excursion
 1180       (LaTeX-newline)
 1181       (indent-according-to-mode)
 1182       ;; If there is an active region point is before the backslash of
 1183       ;; "\end" macro, go one line upwards.
 1184       (when active-mark (forward-line -1) (indent-according-to-mode))
 1185       (insert (LaTeX-compose-caption-macro caption short-caption))
 1186       ;; If `auto-fill-mode' is active, fill the caption.
 1187       (if auto-fill-function (LaTeX-fill-paragraph))
 1188       ;; ask for a label and if necessary insert a new line between caption
 1189       ;; and label
 1190       (when (save-excursion (LaTeX-label environment 'environment))
 1191         (LaTeX-newline)
 1192         (indent-according-to-mode)))
 1193     ;; Insert an empty line between caption and marked region, if any.
 1194     (when active-mark (LaTeX-newline) (forward-line -1))
 1195     (indent-according-to-mode)))
 1196     (when (and (member environment '("table" "table*"))
 1197            ;; Suppose an existing tabular environment should just
 1198            ;; be wrapped into a table if there is an active region.
 1199            (not active-mark))
 1200       (LaTeX-environment-menu LaTeX-default-tabular-environment))))
 1201 
 1202 (defun LaTeX-env-array (environment)
 1203   "Insert ENVIRONMENT with position and column specifications.
 1204 Just like array and tabular."
 1205   (let ((pos (and LaTeX-default-position ; LaTeX-default-position can
 1206                     ; be nil, i.e. do not prompt
 1207           (TeX-read-string "(Optional) Position: " LaTeX-default-position)))
 1208     (fmt (TeX-read-string "Format: " LaTeX-default-format)))
 1209     (setq LaTeX-default-position pos)
 1210     (setq LaTeX-default-format fmt)
 1211     (LaTeX-insert-environment environment
 1212                   (concat
 1213                    (unless (zerop (length pos))
 1214                  (concat LaTeX-optop pos LaTeX-optcl))
 1215                    (concat TeX-grop fmt TeX-grcl)))
 1216     (LaTeX-item-array t)))
 1217 
 1218 (defun LaTeX-env-label (environment)
 1219   "Insert ENVIRONMENT and prompt for label."
 1220   (LaTeX-insert-environment environment)
 1221   (when (LaTeX-label environment 'environment)
 1222     (LaTeX-newline)
 1223     (indent-according-to-mode)))
 1224 
 1225 (defun LaTeX-env-list (environment)
 1226   "Insert ENVIRONMENT and the first item."
 1227   (let ((label (TeX-read-string "Default Label: ")))
 1228     (LaTeX-insert-environment environment
 1229                   (format "{%s}{}" label))
 1230     (end-of-line 0)
 1231     (delete-char 1)
 1232     (delete-horizontal-space))
 1233   (LaTeX-insert-item))
 1234 
 1235 (defun LaTeX-env-minipage (environment)
 1236   "Create new LaTeX minipage or minipage-like ENVIRONMENT."
 1237   (let ((pos (and LaTeX-default-position ; LaTeX-default-position can
 1238                     ; be nil, i.e. do not prompt
 1239           (TeX-read-string "(Optional) Position: " LaTeX-default-position)))
 1240     (width (TeX-read-string "Width: " LaTeX-default-width)))
 1241     (setq LaTeX-default-position pos)
 1242     (setq LaTeX-default-width width)
 1243     (LaTeX-insert-environment environment
 1244                   (concat
 1245                    (unless (zerop (length pos))
 1246                  (concat LaTeX-optop pos LaTeX-optcl))
 1247                    (concat TeX-grop width TeX-grcl)))))
 1248 
 1249 (defun LaTeX-env-tabular* (environment)
 1250   "Insert ENVIRONMENT with width, position and column specifications."
 1251   (let ((width (TeX-read-string "Width: " LaTeX-default-width))
 1252     (pos (and LaTeX-default-position ; LaTeX-default-position can
 1253                     ; be nil, i.e. do not prompt
 1254           (TeX-read-string "(Optional) Position: " LaTeX-default-position)))
 1255     (fmt (TeX-read-string "Format: " LaTeX-default-format)))
 1256     (setq LaTeX-default-width width)
 1257     (setq LaTeX-default-position pos)
 1258     (setq LaTeX-default-format fmt)
 1259     (LaTeX-insert-environment environment
 1260                   (concat
 1261                    (concat TeX-grop width TeX-grcl) ;; not optional!
 1262                    (unless (zerop (length pos))
 1263                  (concat LaTeX-optop pos LaTeX-optcl))
 1264                    (concat TeX-grop fmt TeX-grcl)))
 1265     (LaTeX-item-tabular* t)))
 1266 
 1267 (defun LaTeX-env-picture (environment)
 1268   "Insert ENVIRONMENT with width, height specifications."
 1269   (let ((width (TeX-read-string "Width: "))
 1270     (height (TeX-read-string "Height: "))
 1271     (x-offset (TeX-read-string "X Offset: "))
 1272     (y-offset (TeX-read-string "Y Offset: ")))
 1273     (if (zerop (length x-offset))
 1274     (setq x-offset "0"))
 1275     (if (zerop (length y-offset))
 1276     (setq y-offset "0"))
 1277     (LaTeX-insert-environment environment
 1278                   (concat
 1279                    (format "(%s,%s)" width height)
 1280                    (if (not (and (string= x-offset "0")
 1281                          (string= y-offset "0")))
 1282                    (format "(%s,%s)" x-offset y-offset))))))
 1283 
 1284 (defun LaTeX-env-bib (environment)
 1285   "Insert ENVIRONMENT with label for bibitem."
 1286   (LaTeX-insert-environment environment
 1287                 (concat TeX-grop
 1288                     (TeX-read-string "Label for BibItem: " "99")
 1289                     TeX-grcl))
 1290   (end-of-line 0)
 1291   (delete-char 1)
 1292   (delete-horizontal-space)
 1293   (LaTeX-insert-item))
 1294 
 1295 (defun LaTeX-env-contents (environment)
 1296   "Insert ENVIRONMENT with optional argument and filename for contents."
 1297   (let* ((opt '("overwrite" "force" "nosearch"))
 1298      (arg (mapconcat #'identity
 1299              (TeX-completing-read-multiple
 1300               (TeX-argument-prompt t nil "Options")
 1301               (if (string= environment "filecontents*")
 1302                   opt
 1303                 (cons "noheader" opt)))
 1304              ",")))
 1305     (LaTeX-insert-environment environment
 1306                   (concat
 1307                    (when (and arg (not (string= arg "")))
 1308                  (concat LaTeX-optop arg LaTeX-optcl))
 1309                    TeX-grop
 1310                    (TeX-read-string "File: ")
 1311                    TeX-grcl)))
 1312   (delete-horizontal-space))
 1313 
 1314 (defun LaTeX-env-args (environment &rest args)
 1315   "Insert ENVIRONMENT and arguments defined by ARGS."
 1316   (LaTeX-insert-environment environment)
 1317   (save-excursion
 1318     (LaTeX-find-matching-begin)
 1319     (end-of-line)
 1320     (let ((exit-mark (if (boundp 'exit-mark)
 1321              exit-mark
 1322                (make-marker))))
 1323       (TeX-parse-arguments args))))
 1324 
 1325 (defun LaTeX-env-label-as-keyval (_optional &optional keyword keyvals environment)
 1326   "Query for a label and insert it in the optional argument of an environment.
 1327 OPTIONAL is ignored.  Optional KEYWORD is a string to search for
 1328 in the optional argument, label is only included if KEYWORD is
 1329 found.  KEYVALS is a string with key=val's read in.  If nil, this
 1330 function searchs for key=val's itself.  ENVIRONMENT is a string
 1331 with the name of environment, if non-nil, don't bother to find
 1332 out."
 1333   (let ((env-start (make-marker))
 1334     (body-start (make-marker))
 1335     (opt-start (make-marker))
 1336     (opt-end   (make-marker))
 1337     (currenv (or environment (LaTeX-current-environment))))
 1338     ;; Save the starting point as we will come back here
 1339     (set-marker body-start (point))
 1340     ;; Go to the start of the current environment and save the position
 1341     (LaTeX-find-matching-begin)
 1342     (set-marker env-start (point))
 1343     ;; Check if an opt. argument is there; assume that it starts in
 1344     ;; the same line and save the points in markers
 1345     (when (re-search-forward
 1346        (concat "\\\\begin{" currenv "}[ \t]*\\[") body-start t)
 1347       (set-marker opt-start (1- (point)))
 1348       (goto-char opt-start)
 1349       (forward-sexp)
 1350       (set-marker opt-end (1- (point))))
 1351     ;; If keyword argument is given and keyvals argument is not given,
 1352     ;; parse the optional argument and put it into keyvals
 1353     (when (and keyword
 1354            (marker-position opt-start)
 1355            (not keyvals))
 1356       (setq keyvals (buffer-substring-no-properties
 1357              (1+ opt-start) opt-end)))
 1358     ;; If keyword is given, only insert a label when keyword is found
 1359     ;; inside the keyvals.  If keyword is nil, then insert a label
 1360     ;; anyways
 1361     (if (stringp keyword)
 1362     (when (and (stringp keyvals)
 1363            (not (string= keyvals ""))
 1364            (string-match (concat keyword "[ \t]*=") keyvals))
 1365       (goto-char opt-end)
 1366       (let ((opt-label (LaTeX-label currenv 'environment t)))
 1367         (when opt-label
 1368           (insert (if (equal (preceding-char) ?,)
 1369               "label="
 1370             ",label=")
 1371               TeX-grop opt-label TeX-grcl))))
 1372       (let ((opt-label (LaTeX-label currenv 'environment t)))
 1373     (when opt-label
 1374       ;; Check if an opt. argument is found and go to the end if
 1375       (if (marker-position opt-end)
 1376           (progn
 1377         (goto-char opt-end)
 1378         (insert (if (equal (preceding-char) ?,)
 1379                 "label="
 1380               ",label=")
 1381             TeX-grop opt-label TeX-grcl))
 1382         ;; Otherwise start at the beginning of environment in
 1383         ;; order to not mess with any other mandatory arguments
 1384         ;; which can be there
 1385         (goto-char env-start)
 1386         (re-search-forward (concat "\\\\begin{" currenv "}"))
 1387         (insert LaTeX-optop "label=" TeX-grop opt-label TeX-grcl LaTeX-optcl)))))
 1388     ;; Go to where we started and clean up the markers
 1389     (goto-char body-start)
 1390     (set-marker env-start nil)
 1391     (set-marker body-start nil)
 1392     (set-marker opt-start nil)
 1393     (set-marker opt-end nil)))
 1394 
 1395 ;;; Item hooks
 1396 
 1397 (defvar LaTeX-item-list nil
 1398   "A list of environments where items have a special syntax.
 1399 The cdr is the name of the function, used to insert this kind of items.")
 1400 
 1401 (defun LaTeX-insert-item ()
 1402   "Insert a new item in an environment.
 1403 You may use `LaTeX-item-list' to change the routines used to insert the item."
 1404   (interactive "*")
 1405   (let ((environment (LaTeX-current-environment)))
 1406     (when (and (TeX-active-mark)
 1407            (> (point) (mark)))
 1408       (exchange-point-and-mark))
 1409     (unless (bolp) (LaTeX-newline))
 1410     (if (assoc environment LaTeX-item-list)
 1411     (funcall (cdr (assoc environment LaTeX-item-list)))
 1412       (TeX-insert-macro "item"))
 1413     (indent-according-to-mode)))
 1414 
 1415 (defvar TeX-arg-item-label-p)
 1416 
 1417 (defun LaTeX-item-argument ()
 1418   "Insert a new item with an optional argument."
 1419   (let ((TeX-arg-item-label-p t)
 1420     (TeX-insert-macro-default-style 'show-optional-args))
 1421     (TeX-insert-macro "item")))
 1422 
 1423 (defun LaTeX-item-bib ()
 1424   "Insert a new bibitem."
 1425   (TeX-insert-macro "bibitem"))
 1426 
 1427 (defvar LaTeX-array-skipping-regexp (regexp-opt '("[t]" "[b]" ""))
 1428    "Regexp matching between \\begin{xxx} and column specification.
 1429 For array and tabular environments.  See `LaTeX-insert-ampersands' for
 1430 detail.")
 1431 
 1432 (defvar LaTeX-tabular*-skipping-regexp
 1433   ;; Assume width specification contains neither nested curly brace
 1434   ;; pair nor escaped "}".
 1435   (concat "{[^}]*}[ \t]*" (regexp-opt '("[t]" "[b]" "")))
 1436    "Regexp matching between \\begin{tabular*} and column specification.
 1437 For tabular* environment only.  See `LaTeX-insert-ampersands' for detail.")
 1438 
 1439 (defun LaTeX-item-array (&optional suppress)
 1440   "Insert line break macro on the last line and suitable number of &'s.
 1441 For array and tabular environments.
 1442 
 1443 If SUPPRESS is non-nil, do not insert line break macro."
 1444   (unless suppress
 1445     (save-excursion
 1446       (end-of-line 0)
 1447       (just-one-space)
 1448       (TeX-insert-macro "\\")))
 1449   (LaTeX-insert-ampersands
 1450    LaTeX-array-skipping-regexp 'LaTeX-array-count-columns))
 1451 
 1452 (defun LaTeX-item-tabular* (&optional suppress)
 1453   "Insert line break macro on the last line and suitable number of &'s.
 1454 For tabular* environment only.
 1455 
 1456 If SUPPRESS is non-nil, do not insert line break macro."
 1457   (unless suppress
 1458     (save-excursion
 1459       (end-of-line 0)
 1460       (just-one-space)
 1461       (TeX-insert-macro "\\")))
 1462   (LaTeX-insert-ampersands
 1463    LaTeX-tabular*-skipping-regexp 'LaTeX-array-count-columns))
 1464 
 1465 (defun LaTeX-insert-ampersands (regexp func)
 1466   "Insert suitable number of ampersands for the current environment.
 1467 The number is calculated from REGEXP and FUNC.
 1468 
 1469 Example 1:
 1470 Consider the case that the current environment begins with
 1471 \\begin{array}[t]{|lcr|}
 1472 .  REGEXP must be chosen to match \"[t]\", i.e., the text between just
 1473 after \"\\begin{array}\" and just before \"{|lcr|}\", which encloses
 1474 the column specification.  FUNC must return the number of ampersands to
 1475 be inserted, which is 2 since this example specifies three columns.
 1476 FUNC is called with two arguments START and END, which spans the column
 1477 specification (without enclosing braces.)  REGEXP is used to determine
 1478 these START and END.
 1479 
 1480 Example 2:
 1481 This time the environment begins with
 1482 \\begin{tabular*}{1.0\\linewidth}[b]{c@{,}p{5ex}}
 1483 .  REGEXP must match \"{1.0\\linewidth}[b]\" and FUNC must return 1 from
 1484 the text \"c@{,}p{5ex}\" between START and END specified two columns.
 1485 
 1486 FUNC should return nil if it cannot determine the number of ampersands."
 1487   (let* ((cur (point))
 1488      (num
 1489       (save-excursion
 1490         (ignore-errors
 1491           (LaTeX-find-matching-begin)
 1492           ;; Skip over "\begin{xxx}" and possible whitespaces.
 1493           (forward-list 1)
 1494           (skip-chars-forward " \t")
 1495           ;; Skip over the text specified by REGEXP and whitespaces.
 1496           (when (let ((case-fold-search nil))
 1497               (re-search-forward regexp cur))
 1498         (skip-chars-forward " \t")
 1499         (when (eq (following-char) ?{)
 1500           ;; We have reached the target "{yyy}" part.
 1501           (forward-char 1)
 1502           ;; The next line doesn't move point, so point
 1503           ;; is left just after the opening brace.
 1504           (let ((pos (TeX-find-closing-brace)))
 1505             (if pos
 1506             ;; Calculate number of ampersands to be inserted.
 1507             (funcall func (point) (1- pos))))))))))
 1508     (if (natnump num)
 1509     (save-excursion (insert (make-string num ?&))))))
 1510 
 1511 (defvar LaTeX-array-column-letters "clrp"
 1512   "Column letters for array-like environments.
 1513 See `LaTeX-array-count-columns' for detail.")
 1514 
 1515 (defun LaTeX-array-count-columns (start end)
 1516   "Count number of ampersands to be inserted.
 1517 The columns are specified by the letters found in the string
 1518 `LaTeX-array-column-letters' and the number of those letters within the
 1519 text between START and END is basically considered to be the number of
 1520 columns.  The arguments surrounded between braces such as p{30pt} do not
 1521 interfere the count of columns.
 1522 
 1523 Return one less number than the columns, or nil on failing to count the
 1524 right number."
 1525   (save-excursion
 1526     (let (p (cols 0))
 1527       (goto-char start)
 1528       (while (< (setq p (point)) end)
 1529 
 1530     ;; The below block accounts for one unit of move for
 1531     ;; one column.
 1532     (setq cols (+ cols
 1533               ;; treat *-operator specially.
 1534               (if (eq (following-char) ?*)
 1535               ;; *-operator is there.
 1536               (progn
 1537                 ;; pick up repetition number and count
 1538                 ;; how many columns are repeated.
 1539                 (re-search-forward
 1540                  "\\*[ \t\r\n%]*{[ \t\r\n%]*\\([0-9]+\\)[ \t\r\n%]*}" end)
 1541                 (let ((n (string-to-number
 1542                       (match-string-no-properties 1)))
 1543                   ;; get start and end of repeated spec.
 1544                   (s (progn (down-list 1) (point)))
 1545                   (e (progn (up-list 1) (1- (point)))))
 1546                   (* n (1+ (LaTeX-array-count-columns s e)))))
 1547             ;; not *-operator.
 1548             (skip-chars-forward
 1549              LaTeX-array-column-letters end))))
 1550     ;; Do not skip over `*' (see above) and `[' (siunitx has `S[key=val]':):
 1551     (skip-chars-forward (concat
 1552                  "^" LaTeX-array-column-letters "*"
 1553                  TeX-grop LaTeX-optop) end)
 1554     (when (or (eq (following-char) ?\{)
 1555           (eq (following-char) ?\[))
 1556       (forward-list 1))
 1557 
 1558     ;; Not sure whether this is really necessary or not, but
 1559     ;; prepare for possible infinite loop anyway.
 1560     (when (eq p (point))
 1561       (setq cols nil)
 1562       (goto-char end)))
 1563       ;; The number of ampersands is one less than column.
 1564       (if cols (1- cols)))))
 1565 
 1566 ;;; Parser
 1567 
 1568 (defvar LaTeX-auto-style nil)
 1569 (defvar LaTeX-auto-arguments nil)
 1570 (defvar LaTeX-auto-optional nil)
 1571 (defvar LaTeX-auto-env-args nil)
 1572 (defvar LaTeX-auto-env-args-with-opt nil)
 1573 
 1574 (TeX-auto-add-type "label" "LaTeX")
 1575 (TeX-auto-add-type "bibitem" "LaTeX")
 1576 (TeX-auto-add-type "environment" "LaTeX")
 1577 (TeX-auto-add-type "bibliography" "LaTeX" "bibliographies")
 1578 (TeX-auto-add-type "index-entry" "LaTeX" "index-entries")
 1579 (TeX-auto-add-type "pagestyle" "LaTeX")
 1580 (TeX-auto-add-type "counter" "LaTeX")
 1581 (TeX-auto-add-type "length" "LaTeX")
 1582 (TeX-auto-add-type "savebox" "LaTeX" "saveboxes")
 1583 
 1584 (defvar LaTeX-auto-minimal-regexp-list
 1585   '(("\\\\document\\(style\\|class\\)\
 1586 \\(\\[\\(\\([^#\\%]\\|%[^\n\r]*[\n\r]\\)*\\)\\]\\)?\
 1587 {\\([^#\\.\n\r]+?\\)}"
 1588      (3 5 1) LaTeX-auto-style)
 1589     ("\\\\use\\(package\\)\\(\\[\\([^]]*\\)\\]\\)?\
 1590 {\\(\\([^#}\\.%]\\|%[^\n\r]*[\n\r]\\)+?\\)}"
 1591      (3 4 1) LaTeX-auto-style))
 1592   "Minimal list of regular expressions matching LaTeX macro definitions.")
 1593 
 1594 (defvar LaTeX-auto-label-regexp-list
 1595   '(("\\\\label{\\([^\n\r%\\{}]+\\)}" 1 LaTeX-auto-label))
 1596   "List of regular expression matching LaTeX labels only.")
 1597 
 1598 (defvar LaTeX-auto-index-regexp-list
 1599    '(("\\\\\\(index\\|glossary\\){\\([^}{]*\\({[^}{]*\\({[^}{]*\\({[^}{]*}[^}{]*\\)*}[^}{]*\\)*}[^}{]*\\)*\\)}"
 1600     2 LaTeX-auto-index-entry))
 1601    "List of regular expression matching LaTeX index/glossary entries only.
 1602 Regexp allows for up to 3 levels of parenthesis inside the index argument.
 1603 This is necessary since index entries may contain commands and stuff.")
 1604 
 1605 (defvar LaTeX-auto-class-regexp-list
 1606   '(;; \RequirePackage[<options>]{<package>}[<date>]
 1607     ("\\\\Require\\(Package\\)\\(\\[\\([^]]*\\)\\]\\)?\
 1608 {\\([^#\\.\n\r]+?\\)}"
 1609      (3 4 1) LaTeX-auto-style)
 1610     ;; \RequirePackageWithOptions{<package>}[<date>],
 1611     ("\\\\Require\\(Package\\)WithOptions\\(\\){\\([^#\\.\n\r]+?\\)}"
 1612      (2 3 1) LaTeX-auto-style)
 1613     ;; \LoadClass[<options>]{<package>}[<date>]
 1614     ("\\\\Load\\(Class\\)\\(\\[\\([^]]*\\)\\]\\)?{\\([^#\\.\n\r]+?\\)}"
 1615      (3 4 1) LaTeX-auto-style)
 1616     ;; \LoadClassWithOptions{<package>}[<date>]
 1617     ("\\\\Load\\(Class\\)WithOptions\\(\\){\\([^#\\.\n\r]+?\\)}"
 1618      (2 3 1) LaTeX-auto-style)
 1619     ;; \DeclareRobustCommand{<cmd>}[<num>][<default>]{<definition>},
 1620     ;; \DeclareRobustCommand*{<cmd>}[<num>][<default>]{<definition>}
 1621     ("\\\\DeclareRobustCommand\\*?{?\\\\\\([A-Za-z]+\\)}?\
 1622 \\[\\([0-9]+\\)\\]\\[\\([^\n\r]*?\\)\\]"
 1623      (1 2 3) LaTeX-auto-optional)
 1624     ("\\\\DeclareRobustCommand\\*?{?\\\\\\([A-Za-z]+\\)}?\\[\\([0-9]+\\)\\]"
 1625      (1 2) LaTeX-auto-arguments)
 1626     ("\\\\DeclareRobustCommand\\*?{?\\\\\\([A-Za-z]+\\)}?"
 1627      1 TeX-auto-symbol)
 1628     ;; Patterns for commands described in "LaTeX2e font selection" (fntguide)
 1629     ("\\\\DeclareMath\\(?:Symbol\\|Delimiter\\|Accent\\|Radical\\)\
 1630 {?\\\\\\([A-Za-z]+\\)}?"
 1631      1 TeX-auto-symbol)
 1632     ("\\\\\\(Declare\\|Provide\\)Text\
 1633 \\(?:Command\\|Symbol\\|Accent\\|Composite\\){?\\\\\\([A-Za-z]+\\)}?"
 1634      1 TeX-auto-symbol)
 1635     ("\\\\Declare\\(?:Text\\|Old\\)FontCommand{?\\\\\\([A-Za-z]+\\)}?"
 1636      1 TeX-auto-symbol))
 1637   "List of regular expressions matching macros in LaTeX classes and packages.")
 1638 
 1639 (defvar LaTeX-auto-pagestyle-regexp-list
 1640   '(("\\\\ps@\\([A-Za-z]+\\)" 1 LaTeX-auto-pagestyle))
 1641   "List of regular expressions matching LaTeX pagestyles only.")
 1642 
 1643 (defvar LaTeX-auto-counter-regexp-list
 1644   '(("\\\\newcounter *{\\([A-Za-z]+\\)}" 1 LaTeX-auto-counter)
 1645     ("\\\\@definecounter{\\([A-Za-z]+\\)}" 1 LaTeX-auto-counter))
 1646   "List of regular expressions matching LaTeX counters only.")
 1647 
 1648 (defvar LaTeX-auto-length-regexp-list
 1649   '(("\\\\newlength *{?\\\\\\([A-Za-z]+\\)}?" 1 LaTeX-auto-length))
 1650   "List of regular expressions matching LaTeX lengths only.")
 1651 
 1652 (defvar LaTeX-auto-savebox-regexp-list
 1653   '(("\\\\newsavebox *{?\\\\\\([A-Za-z]+\\)}?" 1 LaTeX-auto-savebox))
 1654   "List of regular expressions matching LaTeX saveboxes only.")
 1655 
 1656 (defvar LaTeX-auto-regexp-list
 1657   (append
 1658    (let ((token TeX-token-char))
 1659      `((,(concat "\\\\\\(?:new\\|provide\\)command\\*?{?\\\\\\(" token "+\\)}?\\[\\([0-9]+\\)\\]\\[\\([^\n\r]*\\)\\]")
 1660     (1 2 3) LaTeX-auto-optional)
 1661        (,(concat "\\\\\\(?:new\\|provide\\)command\\*?{?\\\\\\(" token "+\\)}?\\[\\([0-9]+\\)\\]")
 1662     (1 2) LaTeX-auto-arguments)
 1663        (,(concat "\\\\\\(?:new\\|provide\\)command\\*?{?\\\\\\(" token "+\\)}?")
 1664     1 TeX-auto-symbol)
 1665        (,(concat "\\\\newenvironment\\*?{?\\(" token "+\\)}?\\[\\([0-9]+\\)\\]\\[")
 1666     (1 2) LaTeX-auto-env-args-with-opt)
 1667        (,(concat "\\\\newenvironment\\*?{?\\(" token "+\\)}?\\[\\([0-9]+\\)\\]")
 1668     (1 2) LaTeX-auto-env-args)
 1669        (,(concat "\\\\newenvironment\\*?{?\\(" token "+\\)}?")
 1670     1 LaTeX-auto-environment)
 1671        (,(concat "\\\\newtheorem{\\(" token "+\\)}") 1 LaTeX-auto-environment)
 1672        ("\\\\input{\\(\\.*[^#}%\\\\\\.\n\r]+\\)\\(\\.[^#}%\\\\\\.\n\r]+\\)?}"
 1673     1 TeX-auto-file)
 1674        ("\\\\include{\\(\\.*[^#}%\\\\\\.\n\r]+\\)\\(\\.[^#}%\\\\\\.\n\r]+\\)?}"
 1675     1 TeX-auto-file)
 1676        (, (concat "\\\\bibitem{\\(" token "[^, \n\r\t%\"#'()={}]*\\)}")
 1677       1 LaTeX-auto-bibitem)
 1678        (, (concat "\\\\bibitem\\[[^][\n\r]+\\]{\\(" token "[^, \n\r\t%\"#'()={}]*\\)}")
 1679       1 LaTeX-auto-bibitem)
 1680        ("\\\\bibliography{\\([^#}\\\\\n\r]+\\)}" 1 LaTeX-auto-bibliography)
 1681        ("\\\\addbibresource\\(?:\\[[^]]+\\]\\)?{\\([^#}\\\\\n\r]+\\)\\..+}"
 1682     1 LaTeX-auto-bibliography)
 1683        ("\\\\add\\(?:global\\|section\\)bib\\(?:\\[[^]]+\\]\\)?{\\([^#}\\\\\n\r\.]+\\)\\(?:\\..+\\)?}" 1 LaTeX-auto-bibliography)
 1684        ("\\\\newrefsection\\[\\([^]]+\\)\\]" 1 LaTeX-split-bibs)
 1685        ("\\\\begin{refsection}\\[\\([^]]+\\)\\]" 1 LaTeX-split-bibs)))
 1686    LaTeX-auto-class-regexp-list
 1687    LaTeX-auto-label-regexp-list
 1688    LaTeX-auto-index-regexp-list
 1689    LaTeX-auto-minimal-regexp-list
 1690    LaTeX-auto-pagestyle-regexp-list
 1691    LaTeX-auto-counter-regexp-list
 1692    LaTeX-auto-length-regexp-list
 1693    LaTeX-auto-savebox-regexp-list)
 1694   "List of regular expression matching common LaTeX macro definitions.")
 1695 
 1696 (defun LaTeX-split-bibs (match)
 1697   "Extract bibliography resources from MATCH.
 1698 Split the string at commas and remove Biber file extensions."
 1699   (let ((bibs (TeX-split-string " *, *" (TeX-match-buffer match))))
 1700     (dolist (bib bibs)
 1701       (LaTeX-add-bibliographies (replace-regexp-in-string
 1702                  (concat "\\(?:\\."
 1703                      (mapconcat #'identity
 1704                             TeX-Biber-file-extensions
 1705                             "\\|\\.")
 1706                      "\\)")
 1707                  "" bib)))))
 1708 
 1709 (defun LaTeX-auto-prepare ()
 1710   "Prepare for LaTeX parsing."
 1711   (setq LaTeX-auto-arguments nil
 1712     LaTeX-auto-optional nil
 1713     LaTeX-auto-env-args nil
 1714     LaTeX-auto-style nil
 1715     LaTeX-auto-end-symbol nil))
 1716 
 1717 (add-hook 'TeX-auto-prepare-hook 'LaTeX-auto-prepare)
 1718 
 1719 (defun LaTeX-listify-package-options (options)
 1720   "Return a list from a comma-separated string of package OPTIONS.
 1721 The input string may include LaTeX comments and newlines."
 1722   ;; We jump through all those hoops and don't just use `split-string'
 1723   ;; or the like in order to be able to deal with key=value package
 1724   ;; options which can look like this: "pdftitle={A Perfect Day},
 1725   ;; colorlinks=false"
 1726   (let (opts match start)
 1727     (with-temp-buffer
 1728       (set-syntax-table LaTeX-mode-syntax-table)
 1729       (insert options)
 1730       (newline) ; So that the last entry can be found.
 1731       (goto-char (point-min))
 1732       (setq start (point))
 1733       (while (re-search-forward "[{ ,%\n\r]" nil t)
 1734     (setq match (match-string 0))
 1735     (cond
 1736      ;; Step over groups.  (Let's hope nobody uses escaped braces.)
 1737      ((string= match "{")
 1738       (up-list))
 1739      ;; Get rid of whitespace.
 1740      ((string= match " ")
 1741       (delete-region (1- (point))
 1742              (save-excursion
 1743                (skip-chars-forward " ")
 1744                (point))))
 1745      ;; Add entry to output.
 1746      ((or (string= match ",") (= (point) (point-max)))
 1747           (let ((entry (buffer-substring-no-properties
 1748                         start (1- (point)))))
 1749             (unless (member entry opts)
 1750               (setq opts (append opts (list entry)))))
 1751       (setq start (point)))
 1752      ;; Get rid of comments.
 1753      ((string= match "%")
 1754       (delete-region (1- (point))
 1755              (line-beginning-position 2)))
 1756      ;; Get rid of newlines.
 1757      ((or (string= match "\n") (string= match "\r"))
 1758       (delete-char -1)))))
 1759     opts))
 1760 
 1761 (defvar LaTeX-provided-class-options nil
 1762   "Alist of options provided to LaTeX classes.
 1763 For each element, the CAR is the name of the class, the CDR is
 1764 the list of options provided to it.
 1765 
 1766 E.g., its value will be
 1767   \(\(\"book\" \"a4paper\" \"11pt\" \"openany\" \"fleqn\"\)
 1768    ...\)
 1769 See also `LaTeX-provided-package-options'.")
 1770 (make-variable-buffer-local 'LaTeX-provided-class-options)
 1771 
 1772 (defun LaTeX-provided-class-options-member (class option)
 1773   "Return non-nil if OPTION has been given to CLASS at load time.
 1774 The value is actually the tail of the list of options given to CLASS."
 1775   (member option (cdr (assoc class LaTeX-provided-class-options))))
 1776 
 1777 (defun LaTeX-match-class-option (regexp)
 1778   "Check if a documentclass option matching REGEXP is active.
 1779 Return first found class option matching REGEXP, or nil if not found."
 1780   (TeX-member regexp (apply #'append
 1781                 (mapcar #'cdr LaTeX-provided-class-options))
 1782           'string-match))
 1783 
 1784 (defvar LaTeX-provided-package-options nil
 1785   "Alist of options provided to LaTeX packages.
 1786 For each element, the CAR is the name of the package, the CDR is
 1787 the list of options provided to it.
 1788 
 1789 E.g., its value will be
 1790   \(\(\"babel\" \"german\"\)
 1791    \(\"geometry\" \"a4paper\" \"top=2cm\" \"bottom=2cm\" \"left=2.5cm\" \"right=2.5cm\"\)
 1792    ...\)
 1793 See also `LaTeX-provided-class-options'.")
 1794 (make-variable-buffer-local 'LaTeX-provided-package-options)
 1795 
 1796 (defun LaTeX-provided-package-options-member (package option)
 1797   "Return non-nil if OPTION has been given to PACKAGE at load time.
 1798 The value is actually the tail of the list of options given to PACKAGE."
 1799   (member option (cdr (assoc package LaTeX-provided-package-options))))
 1800 
 1801 (defun LaTeX-auto-cleanup ()
 1802   "Cleanup after LaTeX parsing."
 1803 
 1804   ;; Cleanup BibTeX/Biber files
 1805   (setq LaTeX-auto-bibliography
 1806     (apply 'append (mapcar (lambda (arg)
 1807                  (TeX-split-string "," arg))
 1808                    LaTeX-auto-bibliography)))
 1809 
 1810   ;; Reset class and packages options for the current buffer
 1811   (setq LaTeX-provided-class-options nil)
 1812   (setq LaTeX-provided-package-options nil)
 1813 
 1814   ;; Cleanup document classes and packages
 1815   (unless (null LaTeX-auto-style)
 1816     (while LaTeX-auto-style
 1817       (let* ((entry (car LaTeX-auto-style))
 1818          (options (nth 0 entry))
 1819          (style (nth 1 entry))
 1820          (class (nth 2 entry)))
 1821 
 1822     ;; Next document style.
 1823     (setq LaTeX-auto-style (cdr LaTeX-auto-style))
 1824 
 1825     ;; Get the options.
 1826     (setq options (LaTeX-listify-package-options options))
 1827 
 1828         ;; Treat documentclass/documentstyle specially.
 1829         (if (or (string-equal "package" class)
 1830                 (string-equal "Package" class))
 1831             (dolist (elt (TeX-split-string
 1832                           "\\([ \t\r\n]\\|%[^\n\r]*[\n\r]\\|,\\)+" style))
 1833           ;; Append style to the style list.
 1834           (add-to-list 'TeX-auto-file elt t)
 1835               ;; Append to `LaTeX-provided-package-options' the name of the
 1836               ;; package and the options provided to it at load time.
 1837           (unless (equal options '(""))
 1838         (TeX-add-to-alist 'LaTeX-provided-package-options
 1839                   (list (cons elt options)))))
 1840       ;; And a special "art10" style file combining style and size.
 1841       (add-to-list 'TeX-auto-file style t)
 1842       (add-to-list 'TeX-auto-file
 1843                (concat
 1844             (cond ((string-equal "article" style)
 1845                    "art")
 1846                   ((string-equal "book" style)
 1847                    "bk")
 1848                   ((string-equal "report" style)
 1849                    "rep")
 1850                   ((string-equal "jarticle" style)
 1851                    "jart")
 1852                   ((string-equal "jbook" style)
 1853                    "jbk")
 1854                   ((string-equal "jreport" style)
 1855                    "jrep")
 1856                   ((string-equal "j-article" style)
 1857                    "j-art")
 1858                   ((string-equal "j-book" style)
 1859                    "j-bk")
 1860                   ((string-equal "j-report" style )
 1861                    "j-rep")
 1862                   (t style))
 1863             (cond ((member "11pt" options)
 1864                    "11")
 1865                   ((member "12pt" options)
 1866                    "12")
 1867                   (t
 1868                    "10"))) t)
 1869       (unless (equal options '(""))
 1870         (TeX-add-to-alist 'LaTeX-provided-class-options
 1871                   (list (cons style options)))))
 1872 
 1873     ;; The third argument if "class" indicates LaTeX2e features.
 1874     (cond ((or (string-equal class "class")
 1875            (string-equal class "Class"))
 1876            (add-to-list 'TeX-auto-file "latex2e"))
 1877           ((string-equal class "style")
 1878            (add-to-list 'TeX-auto-file "latex2"))))))
 1879 
 1880   ;; Cleanup optional arguments
 1881   (mapc (lambda (entry)
 1882       (add-to-list 'TeX-auto-symbol
 1883                (list (nth 0 entry)
 1884                  (string-to-number (nth 1 entry)))))
 1885     LaTeX-auto-arguments)
 1886 
 1887   ;; Cleanup default optional arguments
 1888   (mapc (lambda (entry)
 1889       (add-to-list 'TeX-auto-symbol
 1890                (list (nth 0 entry)
 1891                  (vector "argument")
 1892                  (1- (string-to-number (nth 1 entry))))))
 1893     LaTeX-auto-optional)
 1894 
 1895   ;; Cleanup environments arguments
 1896   (mapc (lambda (entry)
 1897       (add-to-list 'LaTeX-auto-environment
 1898                (list (nth 0 entry)
 1899                  (string-to-number (nth 1 entry)))))
 1900     LaTeX-auto-env-args)
 1901   ;; Ditto for environments with an optional arg
 1902   (mapc (lambda (entry)
 1903       (add-to-list 'LaTeX-auto-environment
 1904                (list (nth 0 entry) 'LaTeX-env-args (vector "argument")
 1905                  (1- (string-to-number (nth 1 entry))))))
 1906     LaTeX-auto-env-args-with-opt)
 1907 
 1908   ;; Cleanup use of def to add environments
 1909   ;; NOTE: This uses an O(N^2) algorithm, while an O(N log N)
 1910   ;; algorithm is possible.
 1911   (mapc (lambda (symbol)
 1912       (if (not (TeX-member symbol TeX-auto-symbol 'equal))
 1913           ;; No matching symbol, insert in list
 1914           (add-to-list 'TeX-auto-symbol (concat "end" symbol))
 1915         ;; Matching symbol found, remove from list
 1916         (if (equal (car TeX-auto-symbol) symbol)
 1917         ;; Is it the first symbol?
 1918         (setq TeX-auto-symbol (cdr TeX-auto-symbol))
 1919           ;; Nope!  Travel the list
 1920           (let ((list TeX-auto-symbol))
 1921         (while (consp (cdr list))
 1922           ;; Until we find it.
 1923           (if (equal (car (cdr list)) symbol)
 1924               ;; Then remove it.
 1925               (setcdr list (cdr (cdr list))))
 1926           (setq list (cdr list)))))
 1927         ;; and add the symbol as an environment.
 1928         (add-to-list 'LaTeX-auto-environment symbol)))
 1929     LaTeX-auto-end-symbol))
 1930 
 1931 (add-hook 'TeX-auto-cleanup-hook 'LaTeX-auto-cleanup)
 1932 
 1933 (defadvice LaTeX-add-bibliographies (after run-bib-style-hooks (&rest bibliographies) activate)
 1934   "Add BIBLIOGRAPHIES to the list of known bibliographies and style files."
 1935   (apply 'TeX-run-style-hooks bibliographies))
 1936 
 1937 ;;; Biber support
 1938 
 1939 (defvar LaTeX-using-Biber nil
 1940   "Used to track whether Biber is in use.")
 1941 (make-variable-buffer-local 'LaTeX-using-Biber)
 1942 
 1943 ;;; BibTeX
 1944 
 1945 ;;;###autoload
 1946 (defun BibTeX-auto-store ()
 1947   "This function should be called from `bibtex-mode-hook'.
 1948 It will setup BibTeX to store keys in an auto file."
 1949   ;; We want this to be early in the list, so we do not
 1950   ;; add it before we enter BibTeX mode the first time.
 1951   (add-hook 'write-file-functions #'TeX-safe-auto-write nil t)
 1952   (TeX-bibtex-set-BibTeX-dialect)
 1953   (set (make-local-variable 'TeX-auto-update) 'BibTeX)
 1954   (set (make-local-variable 'TeX-auto-untabify) nil)
 1955   (set (make-local-variable 'TeX-auto-parse-length) 999999)
 1956   (set (make-local-variable 'TeX-auto-regexp-list) BibTeX-auto-regexp-list)
 1957   (set (make-local-variable 'TeX-master) t))
 1958 
 1959 (defvar BibTeX-auto-regexp-list
 1960   '(("@[Ss][Tt][Rr][Ii][Nn][Gg]" 1 ignore)
 1961     ("@[a-zA-Z]+[{(][ \t]*\\([^, \n\r\t%\"#'()={}]*\\)" 1 LaTeX-auto-bibitem))
 1962   "List of regexp-list expressions matching BibTeX items.")
 1963 
 1964 ;;; Macro Argument Hooks
 1965 
 1966 (defun TeX-arg-conditional (optional expr then else)
 1967   "Implement if EXPR THEN ELSE.
 1968 
 1969 If OPTIONAL is non-nil, insert the resulting value as an optional
 1970 argument, otherwise as a mandatory one.
 1971 
 1972 If EXPR evaluate to true, parse THEN as an argument list, else parse
 1973 ELSE as an argument list."
 1974   (TeX-parse-arguments (if (eval expr) then else)))
 1975 
 1976 (defun TeX-arg-eval (optional &rest args)
 1977   "Evaluate ARGS and insert value in buffer.
 1978 If OPTIONAL is non-nil, insert the resulting value as an optional
 1979 argument, otherwise as a mandatory one."
 1980   (TeX-argument-insert (eval args) optional))
 1981 
 1982 (defvar TeX-read-label-prefix nil
 1983   "Initial input for the label in `TeX-read-label.'")
 1984 
 1985 (defun TeX-read-label (optional &optional prompt definition)
 1986   "Prompt for a label completing with known labels and return it.
 1987 This function always returns a string depending on user input:
 1988 the returned value can be an empty string \"\", the value of
 1989 `TeX-read-label-prefix' if present (e.g. \"fig:\") or a complete
 1990 label input (e.g. \"fig:foo\").  If OPTIONAL is non-nil, indicate
 1991 optional as part of prompt in minibuffer.  Use PROMPT as the
 1992 prompt string.  If DEFINITION is non-nil, add the chosen label to
 1993 the list of defined labels.  `TeX-read-label-prefix' is used as
 1994 initial input for the label.  Also check if label is already
 1995 defined and ask user for confirmation before proceeding."
 1996   (let (label valid)
 1997     (while (not valid)
 1998       (setq label
 1999         (completing-read
 2000          (TeX-argument-prompt optional prompt "Key")
 2001          (LaTeX-label-list) nil nil TeX-read-label-prefix))
 2002       ;; If we're defining a label, check if it's already defined and
 2003       ;; ask user for confirmation, otherwise ask again
 2004       (cond ((and definition
 2005           (assoc label (LaTeX-label-list)))
 2006          (ding)
 2007          (when (y-or-n-p
 2008             ;; Emacs 24 compatibility
 2009             (if (fboundp 'format-message)
 2010             (format-message "Label `%s' exists. Use anyway? " label)
 2011               (format "Label `%s' exists. Use anyway? " label)))
 2012            (setq valid t)))
 2013         (t
 2014          (setq valid t))))
 2015     ;; Only add a newly defined label to list of known one if it is
 2016     ;; not empty and not equal to `TeX-read-label-prefix', if given
 2017     (when (and definition
 2018            (not (string-equal "" label))
 2019            (if TeX-read-label-prefix
 2020            (not (string-equal TeX-read-label-prefix label))
 2021          t))
 2022       (LaTeX-add-labels label))
 2023     ;; Return label, can be empty string "", TeX-read-label-prefix
 2024     ;; only "fig:" or the real thing like "fig:foo"
 2025     label))
 2026 
 2027 (defun TeX-arg-label (optional &optional prompt definition)
 2028   "Prompt for a label completing with known labels.
 2029 If OPTIONAL is non-nil, insert the resulting value as an optional
 2030 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2031 string.  If DEFINITION is non-nil, add the chosen label to the
 2032 list of defined labels.  `TeX-read-label-prefix' is used as
 2033 initial input for the label."
 2034   (TeX-argument-insert
 2035    (TeX-read-label optional prompt definition) optional optional))
 2036 
 2037 (defvar reftex-ref-macro-prompt)
 2038 
 2039 (defun TeX-arg-ref (optional &optional prompt definition)
 2040   "Let-bind `reftex-ref-macro-prompt' to nil and pass arguments
 2041 to `TeX-arg-label'.
 2042 
 2043 See the documentation of `TeX-arg-label' for details on the
 2044 arguments: OPTIONAL, PROMPT, and DEFINITION."
 2045   (let ((reftex-ref-macro-prompt nil))
 2046     (TeX-arg-label optional prompt definition)))
 2047 
 2048 (defun TeX-arg-index-tag (optional &optional prompt &rest _args)
 2049   "Prompt for an index tag.
 2050 This is the name of an index, not the entry.
 2051 
 2052 If OPTIONAL is non-nil, insert the resulting value as an optional
 2053 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2054 string.  ARGS is unused."
 2055   (TeX-argument-insert
 2056    (TeX-read-string (TeX-argument-prompt optional prompt "Index tag")) optional))
 2057 
 2058 (defun TeX-arg-index (optional &optional prompt &rest args)
 2059   "Prompt for an index entry completing with known entries.
 2060 If OPTIONAL is non-nil, insert the resulting value as an optional
 2061 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2062 string.  ARGS is unused."
 2063   (let ((entry (completing-read (TeX-argument-prompt optional prompt "Key")
 2064                 (LaTeX-index-entry-list))))
 2065     (if (and (not (string-equal "" entry))
 2066          (not (member (list entry) (LaTeX-index-entry-list))))
 2067     (LaTeX-add-index-entries entry))
 2068     (TeX-argument-insert entry optional optional)))
 2069 
 2070 (defalias 'TeX-arg-define-index 'TeX-arg-index)
 2071 
 2072 (defun TeX-arg-macro (optional &optional prompt definition)
 2073   "Prompt for a TeX macro with completion.
 2074 If OPTIONAL is non-nil, insert the resulting value as an optional
 2075 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2076 string.  If DEFINITION is non-nil, add the chosen macro to the
 2077 list of defined macros."
 2078   (let ((macro (completing-read (TeX-argument-prompt optional prompt
 2079                              (concat "Macro: "
 2080                                  TeX-esc)
 2081                              t)
 2082                 (TeX-symbol-list))))
 2083     (if (and definition (not (string-equal "" macro)))
 2084     (TeX-add-symbols macro))
 2085     (TeX-argument-insert macro optional TeX-esc)))
 2086 
 2087 (defun TeX-arg-environment (optional &optional prompt definition)
 2088   "Prompt for a LaTeX environment with completion.
 2089 If OPTIONAL is non-nil, insert the resulting value as an optional
 2090 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2091 string.  If DEFINITION is non-nil, add the chosen environment to
 2092 the list of defined environments."
 2093   (let ((environment (completing-read (TeX-argument-prompt optional prompt
 2094                                "Environment")
 2095                       (LaTeX-environment-list))))
 2096     (if (and definition (not (string-equal "" environment)))
 2097     (LaTeX-add-environments environment))
 2098 
 2099     (TeX-argument-insert environment optional)))
 2100 
 2101 ;; Why is DEFINITION unused?
 2102 (defun TeX-arg-cite (optional &optional prompt definition)
 2103   "Prompt for a BibTeX citation with completion.
 2104 If OPTIONAL is non-nil, insert the resulting value as an optional
 2105 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2106 string.  DEFINITION is unused."
 2107   (let ((items (multi-prompt "," t (TeX-argument-prompt optional prompt "Key")
 2108                  (LaTeX-bibitem-list))))
 2109     (apply 'LaTeX-add-bibitems items)
 2110     (TeX-argument-insert (mapconcat 'identity items ",") optional optional)))
 2111 
 2112 (defun TeX-arg-counter (optional &optional prompt definition)
 2113   "Prompt for a LaTeX counter.
 2114 If OPTIONAL is non-nil, insert the resulting value as an optional
 2115 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2116 string.  If DEFINITION is non-nil, add the chosen counter to
 2117 the list of defined counters."
 2118   (let ((counter (completing-read (TeX-argument-prompt optional prompt
 2119                                "Counter")
 2120                   (LaTeX-counter-list))))
 2121     (if (and definition (not (string-equal "" counter)))
 2122     (LaTeX-add-counters counter))
 2123     (TeX-argument-insert counter optional)))
 2124 
 2125 (defun TeX-arg-savebox (optional &optional prompt definition)
 2126   "Prompt for a LaTeX savebox.
 2127 If OPTIONAL is non-nil, insert the resulting value as an optional
 2128 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2129 string.  If definition is non-nil, the savebox is added to the
 2130 list of defined saveboxes."
 2131   (let ((savebox (completing-read (TeX-argument-prompt optional prompt
 2132                                (concat "Savebox: "
 2133                                    TeX-esc) t)
 2134                                    (LaTeX-savebox-list))))
 2135     (if (and definition (not (zerop (length savebox))))
 2136         (LaTeX-add-saveboxes savebox))
 2137     (TeX-argument-insert savebox optional TeX-esc)))
 2138 
 2139 (defun TeX-arg-length (optional &optional prompt initial-input definition)
 2140   "Prompt for a LaTeX length.
 2141 If OPTIONAL is non-nil, insert the resulting value as an optional
 2142 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2143 string.  If INITIAL-INPUT is non-nil, insert it in the minibuffer
 2144 initially, with point positioned at the end.  If DEFINITION is
 2145 non-nil, the length is added to the list of defined length."
 2146   (let ((length (completing-read (TeX-argument-prompt optional prompt "Length")
 2147                  ;; A valid length can be a macro or a length of
 2148                  ;; the form <value><dimension>.  Input starting
 2149                  ;; with a `\' can be completed with length
 2150                  ;; macros.
 2151                  (mapcar (lambda(elt) (concat TeX-esc (car elt)))
 2152                      (LaTeX-length-list))
 2153                  ;; Some macros takes as argument only a length
 2154                  ;; macro (e.g., `\setlength' in its first
 2155                  ;; argument, and `\newlength'), in this case is
 2156                  ;; convenient to set `\\' as initial input.
 2157                  nil nil initial-input)))
 2158     (if (and definition (not (zerop (length length))))
 2159     ;; Strip leading TeX-esc from macro name
 2160         (LaTeX-add-lengths (substring length 1)))
 2161     (TeX-argument-insert length optional)))
 2162 
 2163 (defun TeX-arg-file (optional &optional prompt)
 2164   "Prompt for a filename in the current directory.
 2165 If OPTIONAL is non-nil, insert the resulting value as an optional
 2166 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2167 string."
 2168   (TeX-argument-insert (read-file-name (TeX-argument-prompt optional
 2169                                 prompt "File")
 2170                        "" "" nil)
 2171                optional))
 2172 
 2173 (defun TeX-arg-file-name (optional &optional prompt)
 2174   "Prompt for a file name.
 2175 Initial input is the name of the file being visited in the
 2176 current buffer, with extension.  If OPTIONAL is non-nil, insert
 2177 it as an optional argument.  Use PROMPT as the prompt string."
 2178   (TeX-argument-insert
 2179    (TeX-read-string
 2180     (TeX-argument-prompt optional prompt "Name")
 2181     (file-name-nondirectory buffer-file-name))
 2182    optional))
 2183 
 2184 (defun TeX-arg-file-name-sans-extension (optional &optional prompt)
 2185   "Prompt for a file name.
 2186 Initial input is the name of the file being visited in the
 2187 current buffer, without extension.  If OPTIONAL is non-nil,
 2188 insert it as an optional argument.  Use PROMPT as the prompt
 2189 string."
 2190   (TeX-argument-insert
 2191    (TeX-read-string
 2192     (TeX-argument-prompt optional prompt "Name")
 2193     (file-name-sans-extension (file-name-nondirectory buffer-file-name)))
 2194    optional))
 2195 
 2196 (defun TeX-arg-define-label (optional &optional prompt)
 2197   "Prompt for a label completing with known labels.
 2198 If OPTIONAL is non-nil, insert the resulting value as an optional
 2199 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2200 string.  `TeX-read-label-prefix' is used as initial input for the
 2201 label."
 2202   (TeX-arg-label optional prompt t))
 2203 
 2204 (defun TeX-arg-default-argument-value (optional &optional prompt)
 2205   "Prompt for the default value for the first argument of a LaTeX macro.
 2206 
 2207 If OPTIONAL is non-nil, insert the resulting value as an optional
 2208 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2209 string."
 2210   (TeX-argument-insert
 2211    (TeX-read-string
 2212     (TeX-argument-prompt optional prompt "Default value for first argument"))
 2213    optional))
 2214 
 2215 (defun TeX-arg-define-macro-arguments (optional &optional prompt)
 2216   "Prompt for the number of arguments for a LaTeX macro.  If this
 2217 is non-zero, also prompt for the default value for the first
 2218 argument.
 2219 
 2220 If OPTIONAL is non-nil, insert the resulting value as an optional
 2221 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2222 string."
 2223   (let ((arg-count (TeX-read-string
 2224                     (TeX-argument-prompt optional prompt
 2225                                          "Number of arguments"
 2226                                          nil))))
 2227     (unless (or (string= arg-count "0")
 2228                 (string= arg-count ""))
 2229       (TeX-argument-insert arg-count optional)
 2230       (unless (string-equal LaTeX-version "2")
 2231         (TeX-arg-default-argument-value optional)))))
 2232 
 2233 (defun TeX-arg-define-macro (optional &optional prompt)
 2234   "Prompt for a TeX macro with completion.
 2235 If OPTIONAL is non-nil, insert the resulting value as an optional
 2236 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2237 string."
 2238   (TeX-arg-macro optional prompt t))
 2239 
 2240 (defun TeX-arg-define-environment (optional &optional prompt)
 2241   "Prompt for a LaTeX environment with completion.
 2242 If OPTIONAL is non-nil, insert the resulting value as an optional
 2243 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2244 string."
 2245   (TeX-arg-environment optional prompt t))
 2246 
 2247 (defun TeX-arg-define-cite (optional &optional prompt)
 2248   "Prompt for a BibTeX citation.
 2249 If OPTIONAL is non-nil, insert the resulting value as an optional
 2250 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2251 string."
 2252   (TeX-arg-cite optional prompt t))
 2253 
 2254 (defun TeX-arg-define-counter (optional &optional prompt)
 2255   "Prompt for a LaTeX counter.
 2256 If OPTIONAL is non-nil, insert the resulting value as an optional
 2257 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2258 string."
 2259   (TeX-arg-counter optional prompt t))
 2260 
 2261 (defun TeX-arg-define-savebox (optional &optional prompt)
 2262   "Prompt for a LaTeX savebox.
 2263 If OPTIONAL is non-nil, insert the resulting value as an optional
 2264 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2265 string."
 2266   (TeX-arg-savebox optional prompt t))
 2267 
 2268 (defun TeX-arg-define-length (optional &optional prompt)
 2269   "Prompt for a LaTeX length.
 2270 If OPTIONAL is non-nil, insert the resulting value as an optional
 2271 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2272 string."
 2273   (TeX-arg-length optional prompt "\\" t))
 2274 
 2275 (defcustom LaTeX-style-list '(("amsart")
 2276                   ("amsbook")
 2277                   ("article")
 2278                   ("beamer")
 2279                   ("book")
 2280                   ("dinbrief")
 2281                   ("foils")
 2282                   ("letter")
 2283                   ("memoir")
 2284                   ("minimal")
 2285                   ("prosper")
 2286                   ("report")
 2287                   ("scrartcl")
 2288                   ("scrbook")
 2289                   ("scrlttr2")
 2290                   ("scrreprt")
 2291                   ("slides"))
 2292   "List of document classes offered when inserting a document environment.
 2293 
 2294 If `TeX-arg-input-file-search' is set to `t', you will get
 2295 completion with all LaTeX classes available in your distribution
 2296 and this variable will be ignored."
 2297   :group 'LaTeX-environment
 2298   :type '(repeat (group (string :format "%v"))))
 2299 
 2300 (defvar LaTeX-global-class-files nil
 2301   "List of the LaTeX class files.
 2302 Initialized once at the first time you prompt for a LaTeX class.
 2303 May be reset with `\\[universal-argument] \\[TeX-normal-mode]'.")
 2304 
 2305 (defvar TeX-after-document-hook nil
 2306   "List of functions to be run at the end of `TeX-arg-document'.
 2307 
 2308 To insert a hook here, you must insert it in the appropiate style file.")
 2309 
 2310 (defun TeX-arg-document (_optional &optional _ignore)
 2311   "Insert arguments to documentclass.
 2312 OPTIONAL and IGNORE are ignored."
 2313   (let* ((TeX-file-extensions '("cls"))
 2314      (crm-separator ",")
 2315      style var options defopt optprmpt)
 2316     (unless LaTeX-global-class-files
 2317       (setq LaTeX-global-class-files
 2318         (if (if (eq TeX-arg-input-file-search 'ask)
 2319             (not (y-or-n-p "Find class yourself? "))
 2320           TeX-arg-input-file-search)
 2321         (prog2
 2322             (message "Searching for LaTeX classes...")
 2323             (TeX-search-files-by-type 'texinputs 'global t t)
 2324           (message "Searching for LaTeX classes...done"))
 2325           LaTeX-style-list)))
 2326     (setq style (completing-read
 2327          (concat "Document class (default " LaTeX-default-style "): ")
 2328          LaTeX-global-class-files nil nil nil nil LaTeX-default-style))
 2329     ;; Clean up hook before use.
 2330     (setq TeX-after-document-hook nil)
 2331     (TeX-load-style style)
 2332     (setq var (intern (format "LaTeX-%s-class-options" style)))
 2333     (setq defopt (if (stringp LaTeX-default-options)
 2334              LaTeX-default-options
 2335            (mapconcat #'identity LaTeX-default-options ",")))
 2336     (setq optprmpt
 2337       (if (and defopt (not (string-equal defopt "")))
 2338           (format "Options (default %s): " defopt) "Options: "))
 2339     (if (or (and (boundp var)
 2340          (listp (symbol-value var)))
 2341         (fboundp var))
 2342     (if (functionp var)
 2343         (setq options (funcall var))
 2344       (when (symbol-value var)
 2345         (setq options
 2346           (mapconcat 'identity
 2347                  (TeX-completing-read-multiple
 2348                   optprmpt (mapcar 'list (symbol-value var)) nil nil
 2349                   nil nil defopt)
 2350                  ","))))
 2351       (setq options (TeX-read-string optprmpt nil nil defopt)))
 2352     (unless (zerop (length options))
 2353       (insert LaTeX-optop options LaTeX-optcl)
 2354       (let ((opts (LaTeX-listify-package-options options)))
 2355     (TeX-add-to-alist 'LaTeX-provided-class-options
 2356               (list (cons style opts)))))
 2357     (insert TeX-grop style TeX-grcl))
 2358 
 2359   (TeX-update-style t)
 2360   (run-hooks 'TeX-after-document-hook))
 2361 
 2362 (defvar LaTeX-after-usepackage-hook nil
 2363   "List of functions to be run at the end of `LaTeX-arg-usepackage'.
 2364 
 2365 To insert a hook here, you must insert it in the appropiate style file.")
 2366 
 2367 (defun LaTeX-arg-usepackage-read-packages-with-options ()
 2368   "Read the packages and the options for the usepackage macro.
 2369 
 2370 If at least one package is provided, this function returns a cons
 2371 cell, whose CAR is the list of packages and the CDR is the string
 2372 of the options, nil otherwise."
 2373   (let* ((TeX-file-extensions '("sty"))
 2374      (crm-separator ",")
 2375      packages var options)
 2376     (unless TeX-global-input-files
 2377       (if (if (eq TeX-arg-input-file-search 'ask)
 2378           (not (y-or-n-p "Find packages yourself? "))
 2379         TeX-arg-input-file-search)
 2380       (progn
 2381         (message "Searching for LaTeX packages...")
 2382         (setq TeX-global-input-files
 2383           (mapcar 'list (TeX-search-files-by-type
 2384                  'texinputs 'global t t)))
 2385         (message "Searching for LaTeX packages...done"))))
 2386     (setq packages (TeX-completing-read-multiple
 2387             "Packages: " TeX-global-input-files))
 2388     ;; Clean up hook before use in `LaTeX-arg-usepackage-insert'.
 2389     (setq LaTeX-after-usepackage-hook nil)
 2390     (mapc #'TeX-load-style packages)
 2391     ;; Prompt for options only if at least one package has been supplied, return
 2392     ;; nil otherwise.
 2393     (when packages
 2394       (setq var (if (= 1 (length packages))
 2395             (intern (format "LaTeX-%s-package-options" (car packages)))
 2396           ;; Something like `\usepackage[options]{pkg1,pkg2,pkg3,...}' is
 2397           ;; allowed (provided that pkg1, pkg2, pkg3, ... accept same
 2398           ;; options).  When there is more than one package, set `var' to
 2399           ;; a dummy value so next `if' enters else form.
 2400           t))
 2401       (if (or (and (boundp var)
 2402            (listp (symbol-value var)))
 2403           (fboundp var))
 2404       (if (functionp var)
 2405           (setq options (funcall var))
 2406         (when (symbol-value var)
 2407           (setq options
 2408             (mapconcat 'identity
 2409                    (TeX-completing-read-multiple
 2410                 "Options: " (mapcar 'list (symbol-value var)))
 2411                    ","))))
 2412     (setq options (TeX-read-string "Options: ")))
 2413       (cons packages options))))
 2414 
 2415 (defun LaTeX-arg-usepackage-insert (packages options)
 2416   "Actually insert arguments to usepackage."
 2417   (unless (zerop (length options))
 2418     (let ((opts (LaTeX-listify-package-options options)))
 2419       (mapc (lambda (elt)
 2420           (TeX-add-to-alist 'LaTeX-provided-package-options
 2421                 (list (cons elt opts))))
 2422         packages))
 2423     (insert LaTeX-optop options LaTeX-optcl))
 2424   (insert TeX-grop (mapconcat 'identity packages ",") TeX-grcl)
 2425   (run-hooks 'LaTeX-after-usepackage-hook)
 2426   (apply #'TeX-run-style-hooks packages))
 2427 
 2428 (defun LaTeX-arg-usepackage (_optional)
 2429   "Insert arguments to usepackage.
 2430 OPTIONAL is ignored."
 2431   (let* ((packages-options (LaTeX-arg-usepackage-read-packages-with-options))
 2432      (packages (car packages-options))
 2433      (options (cdr packages-options)))
 2434     (LaTeX-arg-usepackage-insert packages options)))
 2435 
 2436 (defun LaTeX-insert-usepackages ()
 2437   "Prompt for the insertion of usepackage macros until empty
 2438 input is reached.
 2439 
 2440 Return t if at least one \\usepackage has been inserted, nil
 2441 otherwise."
 2442   (let (packages-options packages options (inserted nil))
 2443     (while (setq packages-options
 2444          (LaTeX-arg-usepackage-read-packages-with-options))
 2445       (setq packages (car packages-options))
 2446       (setq options (cdr packages-options))
 2447       (insert TeX-esc "usepackage")
 2448       (LaTeX-arg-usepackage-insert packages options)
 2449       (LaTeX-newline)
 2450       (setq inserted t))
 2451     inserted))
 2452 
 2453 (defcustom LaTeX-search-files-type-alist
 2454   '((texinputs "${TEXINPUTS.latex}" ("tex/generic/" "tex/latex/")
 2455            TeX-file-extensions)
 2456     (docs "${TEXDOCS}" ("doc/") TeX-doc-extensions)
 2457     (graphics "${TEXINPUTS}" ("tex/") LaTeX-includegraphics-extensions)
 2458     (bibinputs "${BIBINPUTS}" ("bibtex/bib/") BibTeX-file-extensions)
 2459     (bstinputs "${BSTINPUTS}" ("bibtex/bst/") BibTeX-style-extensions)
 2460     (bbxinputs "" ("tex/latex/") BibLaTeX-style-extensions)
 2461     (biberinputs "${BIBINPUTS}" ("bibtex/bib/") TeX-Biber-file-extensions))
 2462   "Alist of filetypes with locations and file extensions.
 2463 Each element of the alist consists of a symbol expressing the
 2464 filetype, a variable which can be expanded on kpathsea-based
 2465 systems into the directories where files of the given type
 2466 reside, a list of absolute directories, relative directories
 2467 below the root of a TDS-compliant TeX tree or a list of variables
 2468 with either type of directories as an alternative for
 2469 non-kpathsea-based systems and a list of extensions to be matched
 2470 upon a file search.  Note that the directories have to end with a
 2471 directory separator.
 2472 
 2473 Reset the mode for a change of this variable to take effect."
 2474   :group 'TeX-file
 2475   :type '(alist :key-type symbol
 2476         :value-type
 2477         (group (string :tag "Kpathsea variable")
 2478                (choice :tag "Directories"
 2479                    (repeat :tag "TDS subdirectories" string)
 2480                    (repeat :tag "Absolute directories" directory)
 2481                    (repeat :tag "Variables" variable))
 2482                (choice :tag "Extensions"
 2483                    variable (repeat string)))))
 2484 
 2485 (defcustom TeX-arg-input-file-search t
 2486   "If `TeX-arg-input-file' should search for files.
 2487 If the value is t, files in TeX's search path are searched for
 2488 and provided for completion.  The file name is then inserted
 2489 without directory and extension.  If the value is nil, the file
 2490 name can be specified manually and is inserted with a path
 2491 relative to the directory of the current buffer's file and with
 2492 extension.  If the value is `ask', you are asked for the method
 2493 to use every time `TeX-arg-input-file' is called."
 2494   :group 'LaTeX-macro
 2495   :type '(choice (const t) (const nil) (const ask)))
 2496 
 2497 (defvar TeX-global-input-files nil
 2498   "List of the non-local TeX input files.
 2499 Initialized once at the first time you prompt for an input file.
 2500 May be reset with `\\[universal-argument] \\[TeX-normal-mode]'.")
 2501 
 2502 (defun TeX-arg-input-file (optional &optional prompt local)
 2503   "Prompt for a tex or sty file.
 2504 If OPTIONAL is non-nil, insert the resulting value as an optional
 2505 argument, otherwise as a mandatory one.  PROMPT is the prompt,
 2506 LOCAL is a flag.  If the flag is set, only complete with local
 2507 files."
 2508   (let ((search (if (eq TeX-arg-input-file-search 'ask)
 2509             (not (y-or-n-p "Find file yourself? "))
 2510           TeX-arg-input-file-search))
 2511     file style)
 2512     (if search
 2513     (progn
 2514       (unless (or TeX-global-input-files local)
 2515         (message "Searching for files...")
 2516         (setq TeX-global-input-files
 2517           (mapcar 'list (TeX-search-files-by-type
 2518                  'texinputs 'global t t)))
 2519         (message "Searching for files...done"))
 2520       (setq file (completing-read
 2521               (TeX-argument-prompt optional prompt "File")
 2522               (TeX-delete-dups-by-car
 2523                (append (mapcar 'list (TeX-search-files-by-type
 2524                           'texinputs 'local t t))
 2525                    (unless local
 2526                  TeX-global-input-files))))
 2527         style file))
 2528       (setq file (read-file-name
 2529           (TeX-argument-prompt optional prompt "File") nil ""))
 2530       (unless (string-equal file "")
 2531     (setq file (file-relative-name file)))
 2532       (setq style (file-name-sans-extension (file-name-nondirectory file))))
 2533     (unless (string-equal "" style)
 2534       (TeX-run-style-hooks style))
 2535     (TeX-argument-insert file optional)))
 2536 
 2537 (defvar BibTeX-global-style-files nil
 2538   "Association list of BibTeX style files.
 2539 
 2540 Initialized once at the first time you prompt for an input file.
 2541 May be reset with `\\[universal-argument] \\[TeX-normal-mode]'.")
 2542 
 2543 (defvar BibLaTeX-global-style-files nil
 2544   "Association list of BibLaTeX style files.
 2545 
 2546 Initialized once at the first time you prompt for a BibLaTeX
 2547 style.  May be reset with `\\[universal-argument] \\[TeX-normal-mode]'.")
 2548 
 2549 (defun TeX-arg-bibstyle (optional &optional prompt)
 2550   "Prompt for a BibTeX style file.
 2551 If OPTIONAL is non-nil, insert the resulting value as an optional
 2552 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2553 string."
 2554   (message "Searching for BibTeX styles...")
 2555   (or BibTeX-global-style-files
 2556       (setq BibTeX-global-style-files
 2557         (mapcar 'list (TeX-search-files-by-type 'bstinputs 'global t t))))
 2558   (message "Searching for BibTeX styles...done")
 2559   (TeX-argument-insert
 2560    (completing-read (TeX-argument-prompt optional prompt "BibTeX style")
 2561             (append (mapcar 'list (TeX-search-files-by-type
 2562                        'bstinputs 'local t t))
 2563                 BibTeX-global-style-files))
 2564    optional))
 2565 
 2566 (defvar BibTeX-global-files nil
 2567   "Association list of BibTeX files.
 2568 
 2569 Initialized once at the first time you prompt for a BibTeX file.
 2570 May be reset with `\\[universal-argument] \\[TeX-normal-mode]'.")
 2571 
 2572 (defvar TeX-Biber-global-files nil
 2573   "Association list of Biber files.
 2574 
 2575 Initialized once at the first time you prompt for an Biber file.
 2576 May be reset with `\\[universal-argument] \\[TeX-normal-mode]'.")
 2577 
 2578 (defun TeX-arg-bibliography (optional &optional prompt)
 2579   "Prompt for a BibTeX database file.
 2580 If OPTIONAL is non-nil, insert the resulting value as an optional
 2581 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2582 string."
 2583   (message "Searching for BibTeX files...")
 2584   (or BibTeX-global-files
 2585       (setq BibTeX-global-files
 2586         (mapcar 'list (TeX-search-files-by-type 'bibinputs 'global t t))))
 2587   (message "Searching for BibTeX files...done")
 2588   (let ((styles (multi-prompt
 2589          "," t
 2590          (TeX-argument-prompt optional prompt "BibTeX files")
 2591          (append (mapcar 'list (TeX-search-files-by-type
 2592                     'bibinputs 'local t t))
 2593              BibTeX-global-files))))
 2594     (apply 'LaTeX-add-bibliographies styles)
 2595     ;; Run style files associated to the bibliography database files in order to
 2596     ;; immediately fill `LaTeX-bibitem-list'.
 2597     (mapc 'TeX-run-style-hooks styles)
 2598     (TeX-argument-insert (mapconcat 'identity styles ",") optional)))
 2599 
 2600 (defun TeX-arg-corner (optional &optional prompt)
 2601   "Prompt for a LaTeX side or corner position with completion.
 2602 If OPTIONAL is non-nil, insert the resulting value as an optional
 2603 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2604 string."
 2605   (TeX-argument-insert
 2606    (completing-read (TeX-argument-prompt optional prompt "Position")
 2607             '(("") ("l") ("r") ("t") ("b") ("tl") ("tr") ("bl") ("br"))
 2608             nil t)
 2609    optional))
 2610 
 2611 (defun TeX-arg-lr (optional &optional prompt)
 2612   "Prompt for a LaTeX side with completion.
 2613 If OPTIONAL is non-nil, insert the resulting value as an optional
 2614 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2615 string."
 2616   (TeX-argument-insert
 2617    (completing-read (TeX-argument-prompt optional prompt "Position")
 2618             '(("") ("l") ("r"))
 2619             nil t)
 2620    optional))
 2621 
 2622 (defun TeX-arg-tb (optional &optional prompt)
 2623   "Prompt for a LaTeX side with completion.
 2624 If OPTIONAL is non-nil, insert the resulting value as an optional
 2625 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2626 string."
 2627   (TeX-argument-insert
 2628    (completing-read (TeX-argument-prompt optional prompt "Position")
 2629             '(("") ("t") ("b"))
 2630             nil t)
 2631    optional))
 2632 
 2633 (defcustom TeX-date-format "%Y/%m/%d"
 2634   "The default date format prompted by `TeX-arg-date'."
 2635   :group 'LaTeX-macro
 2636   :type 'string)
 2637 
 2638 (defun TeX-arg-date (optional &optional prompt)
 2639   "Prompt for a date, defaulting to the current date.
 2640 If OPTIONAL is non-nil, insert the resulting value as an optional
 2641 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2642 string."
 2643   (let ((default (format-time-string TeX-date-format (current-time))))
 2644     (TeX-argument-insert
 2645      (TeX-read-string (TeX-argument-prompt
 2646                optional prompt (format "Date (default %s)" default))
 2647               nil nil default)
 2648      optional)))
 2649 
 2650 (defun TeX-arg-version (optional &optional prompt)
 2651   "Prompt for the version of a file.
 2652 Use as initial input the current date.  If OPTIONAL is non-nil,
 2653 insert the resulting value as an optional argument, otherwise as
 2654 a mandatory one.  Use PROMPT as the prompt string."
 2655   (TeX-argument-insert
 2656    (TeX-read-string (TeX-argument-prompt optional prompt "Version")
 2657             (format-time-string "%Y/%m/%d" (current-time)))
 2658    optional))
 2659 
 2660 (defun TeX-arg-pagestyle (optional &optional prompt definition)
 2661   "Prompt for a LaTeX pagestyle with completion.
 2662 If OPTIONAL is non-nil, insert the resulting value as an optional
 2663 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2664 string.  If DEFINITION is non-nil, add the chosen pagestyle to
 2665 the list of defined pagestyles."
 2666   (let ((pagestyle (completing-read (TeX-argument-prompt optional prompt
 2667                              "Pagestyle")
 2668                     (LaTeX-pagestyle-list))))
 2669     (if (and definition (not (string-equal "" pagestyle)))
 2670     (LaTeX-add-pagestyles pagestyle))
 2671     (TeX-argument-insert pagestyle optional)))
 2672 
 2673 (defcustom LaTeX-default-verb-delimiter ?|
 2674   "Default delimiter for `\\verb' macros."
 2675   :group 'LaTeX-macro
 2676   :type 'character)
 2677 
 2678 (defun TeX-arg-verb (optional &optional _ignore)
 2679   "Prompt for delimiter and text.
 2680 If OPTIONAL is non-nil, insert the resulting value as an optional
 2681 argument, otherwise as a mandatory one.  IGNORE is ignored."
 2682   (let ((del (read-quoted-char
 2683           (concat "Delimiter (default "
 2684               (char-to-string LaTeX-default-verb-delimiter) "): "))))
 2685     (when (<= del ?\ ) (setq del LaTeX-default-verb-delimiter))
 2686     (if (TeX-active-mark)
 2687     (progn
 2688       (insert del)
 2689       (goto-char (mark))
 2690       (insert del))
 2691       (insert del (read-from-minibuffer "Text: ") del))
 2692     (setq LaTeX-default-verb-delimiter del)))
 2693 
 2694 (defun TeX-arg-verb-delim-or-brace (optional &optional prompt)
 2695   "Prompt for delimiter and text.
 2696 If OPTIONAL, indicate optional argument in minibuffer.  PROMPT is
 2697 a string replacing the default one when asking the user for text.
 2698 This function is intended for \\verb like macros which take their
 2699 argument in delimiters like \"\| \|\" or braces \"\{ \}\"."
 2700   (let ((del (read-quoted-char
 2701           (concat "Delimiter (default "
 2702               (char-to-string LaTeX-default-verb-delimiter) "): "))))
 2703     (when (<= del ?\ )
 2704       (setq del LaTeX-default-verb-delimiter))
 2705     (if (TeX-active-mark)
 2706     (progn
 2707       (insert del)
 2708       (goto-char (mark))
 2709       ;; If the delimiter was an opening brace, close it with a
 2710       ;; brace, otherwise use the delimiter again
 2711       (insert (if (= del ?\{)
 2712               ?\}
 2713             del)))
 2714       ;; Same thing again
 2715       (insert del (read-from-minibuffer
 2716            (TeX-argument-prompt optional prompt "Text"))
 2717           (if (= del ?\{)
 2718           ?\}
 2719         del)))
 2720     ;; Do not set `LaTeX-default-verb-delimiter' if the user input was
 2721     ;; an opening brace.  This would give funny results for the next
 2722     ;; "C-c C-m \verb RET"
 2723     (unless (= del ?\{)
 2724       (setq LaTeX-default-verb-delimiter del))))
 2725 
 2726 (defun TeX-arg-pair (optional first second)
 2727   "Insert a pair of number, prompted by FIRST and SECOND.
 2728 
 2729 The numbers are surounded by parenthesizes and separated with a
 2730 comma.
 2731 
 2732 If OPTIONAL is non-nil, insert the resulting value as an optional
 2733 argument, otherwise as a mandatory one."
 2734   (insert "(" (TeX-read-string (concat first  ": ")) ","
 2735           (TeX-read-string (concat second ": ")) ")"))
 2736 
 2737 (defun TeX-arg-size (optional)
 2738   "Insert width and height as a pair.
 2739 If OPTIONAL is non-nil, insert the resulting value as an optional
 2740 argument, otherwise as a mandatory one."
 2741   (TeX-arg-pair optional "Width" "Height"))
 2742 
 2743 (defun TeX-arg-coordinate (optional)
 2744   "Insert x and y coordinate as a pair.
 2745 If OPTIONAL is non-nil, insert the resulting value as an optional
 2746 argument, otherwise as a mandatory one."
 2747  (TeX-arg-pair optional "X position" "Y position"))
 2748 
 2749 (defconst TeX-braces-default-association
 2750   '(("[" . "]")
 2751     ("\\{" . "\\}")
 2752     ("(" . ")")
 2753     ("|" . "|")
 2754     ("\\|" . "\\|")
 2755     ("/" . "/")
 2756     ("\\backslash" . "\\backslash")
 2757     ("\\lfloor" . "\\rfloor")
 2758     ("\\lceil" . "\\rceil")
 2759     ("\\langle" . "\\rangle")))
 2760 
 2761 (defcustom TeX-braces-user-association nil
 2762   "A list of your personal association of brace symbols.
 2763 These are used for \\left and \\right.
 2764 
 2765 The car of each entry is the brace used with \\left,
 2766 the cdr is the brace used with \\right."
 2767   :group 'LaTeX-macro
 2768   :group 'LaTeX-math
 2769   :type '(repeat (cons :format "%v"
 2770                (string :tag "Left")
 2771                (string :tag "Right"))))
 2772 
 2773 (defvar TeX-braces-association
 2774   (append TeX-braces-user-association
 2775       TeX-braces-default-association)
 2776     "A list of association of brace symbols for \\left and \\right.
 2777 The car of each entry is the brace used with \\left,
 2778 the cdr is the brace used with \\right.")
 2779 
 2780 (defcustom LaTeX-electric-left-right-brace nil
 2781   "If non-nil, insert right brace with suitable macro after typing left brace."
 2782   :group 'LaTeX-macro
 2783   :type 'boolean)
 2784 
 2785 (defvar TeX-left-right-braces
 2786   '(("[") ("]") ("\\{") ("\\}") ("(") (")") ("|") ("\\|")
 2787     ("/") ("\\backslash") ("\\lfloor") ("\\rfloor")
 2788     ("\\lceil") ("\\rceil") ("\\langle") ("\\rangle")
 2789     ("\\uparrow") ("\\Uparrow") ("\\downarrow") ("\\Downarrow")
 2790     ("\\updownarrow") ("\\Updownarrow") ("."))
 2791   "List of symbols which can follow the \\left or \\right command.")
 2792 
 2793 (defvar LaTeX-left-right-macros-association
 2794   '(("left" . "right")
 2795     ("bigl" . "bigr") ("Bigl" . "Bigr")
 2796     ("biggl" . "biggr") ("Biggl" . "Biggr"))
 2797   "Alist of macros for adjusting size of left and right braces.
 2798 The car of each entry is for left brace and the cdr is for right brace.")
 2799 
 2800 (defun TeX-arg-insert-braces (optional &optional prompt)
 2801   "Prompt for a brace for \\left and insert the corresponding \\right.
 2802 If OPTIONAL is non-nil, insert the resulting value as an optional
 2803 argument, otherwise as a mandatory one.  Use PROMPT as the prompt
 2804 string."
 2805   (let (left-macro)
 2806     (save-excursion
 2807       ;; Obtain macro name such as "left", "bigl" etc.
 2808       (setq left-macro (buffer-substring-no-properties
 2809                         (point)
 2810                         (progn (backward-word 1) (point))))
 2811       (backward-char)
 2812       (LaTeX-newline)
 2813       (indent-according-to-mode)
 2814       ;; Delete possibly produced blank line.
 2815       (beginning-of-line 0)
 2816       (if (looking-at "^[ \t]*$")
 2817           (progn (delete-horizontal-space)
 2818                  (delete-char 1))))
 2819     (let ((left-brace (completing-read
 2820                        (TeX-argument-prompt optional prompt
 2821                         "Which brace")
 2822                        TeX-left-right-braces)))
 2823       (insert left-brace)
 2824       (LaTeX-newline)
 2825       (save-excursion
 2826     (if (TeX-active-mark)
 2827         (goto-char (mark)))
 2828         (LaTeX-newline)
 2829         (LaTeX-insert-corresponding-right-macro-and-brace
 2830          left-macro left-brace optional prompt)
 2831         (indent-according-to-mode))
 2832       (indent-according-to-mode))))
 2833 
 2834 (defun TeX-arg-insert-right-brace-maybe (optional)
 2835   "Insert the suitable right brace macro such as \\rangle.
 2836 Insertion is done when `TeX-arg-right-insert-p' is non-nil.
 2837 If the left brace macro is preceded by \\left, \\bigl etc.,
 2838 supply the corresponding macro such as \\right before the right brace macro."
 2839   ;; Nothing is done when TeX-arg-right-insert-p is nil.
 2840   (when TeX-arg-right-insert-p
 2841     (let (left-brace left-macro)
 2842       (save-excursion
 2843     ;; Obtain left brace macro name such as "\langle".
 2844     (setq left-brace (buffer-substring-no-properties
 2845               (point)
 2846               (progn (backward-word) (backward-char)
 2847                  (point)))
 2848           ;; Obtain the name of preceding left macro, if any,
 2849           ;; such as "left", "bigl" etc.
 2850           left-macro (LaTeX--find-preceding-left-macro-name)))
 2851       (save-excursion
 2852     (if (TeX-active-mark)
 2853         (goto-char (mark)))
 2854     (LaTeX-insert-corresponding-right-macro-and-brace
 2855      left-macro left-brace optional)))))
 2856 
 2857 (defvar TeX-arg-right-insert-p)
 2858 
 2859 (defun LaTeX-insert-left-brace (arg)
 2860   "Insert typed left brace ARG times and possibly a correspondig right brace.
 2861 Automatic right brace insertion is done only if no prefix ARG is given and
 2862 `LaTeX-electric-left-right-brace' is non-nil.
 2863 Normally bound to keys \(, { and [."
 2864   (interactive "*P")
 2865   ;; If you change the condition for `auto-p', adjust the condition in
 2866   ;; the `delete-selection' property, just below this defun, accordingly.
 2867   (let ((auto-p (and LaTeX-electric-left-right-brace (not arg))))
 2868     (if (and auto-p
 2869          (TeX-active-mark)
 2870          (> (point) (mark)))
 2871     (exchange-point-and-mark))
 2872     (self-insert-command (prefix-numeric-value arg))
 2873     (if auto-p
 2874       (let ((lbrace (char-to-string last-command-event)) lmacro skip-p)
 2875         (save-excursion
 2876           (backward-char)
 2877       ;; The brace "{" is exceptional in two aspects.
 2878       ;; 1. "\{" should be considered as a single brace
 2879       ;;    like "(" and "[".
 2880       ;; 2. "\left{" is nonsense while "\left\{" and
 2881       ;;    "\left(" are not.
 2882       (if (string= lbrace TeX-grop)
 2883           ;; If "{" follows "\", set lbrace to "\{".
 2884           (if (TeX-escaped-p)
 2885           (progn
 2886             (backward-char)
 2887             (setq lbrace (concat TeX-esc TeX-grop)))
 2888         ;; Otherwise, don't search for left macros.
 2889         (setq skip-p t)))
 2890       (unless skip-p
 2891         ;; Obtain the name of preceding left macro, if any,
 2892         ;; such as "left", "bigl" etc.
 2893         (setq lmacro (LaTeX--find-preceding-left-macro-name))))
 2894         (let ((TeX-arg-right-insert-p t)
 2895               ;; "{" and "}" are paired temporally so that typing
 2896           ;; a single "{" should insert a pair "{}".
 2897               (TeX-braces-association
 2898                (cons (cons TeX-grop TeX-grcl) TeX-braces-association)))
 2899       (save-excursion
 2900         (if (TeX-active-mark)
 2901         (goto-char (mark)))
 2902         (LaTeX-insert-corresponding-right-macro-and-brace
 2903          lmacro lbrace)))))))
 2904 ;; Cater for `delete-selection-mode' (bug#36385)
 2905 ;; See the header comment of delsel.el for detail.
 2906 (put #'LaTeX-insert-left-brace 'delete-selection
 2907      ;; COMPATIBILITY for Emacs < 24.3
 2908      (if (and (= emacs-major-version 24)
 2909           (< emacs-minor-version 3))
 2910      ;; Emacs < 24.3 doesn't support a function as value of
 2911      ;; `delete-selection' property.
 2912      nil
 2913        (lambda ()
 2914      ;; Consult `delete-selection' property when
 2915      ;; `LaTeX-insert-left-brace' works just the same as
 2916      ;; `self-insert-command'.
 2917      (and (or (not LaTeX-electric-left-right-brace)
 2918           current-prefix-arg)
 2919           (let ((f (get #'self-insert-command 'delete-selection)))
 2920         ;; If `delete-selection' property of
 2921         ;; `self-insert-command' is one of the predefined
 2922         ;; special symbols, just return itself.
 2923         (if (memq f '(yank supersede kill t nil))
 2924             ;; FIXME: if this list of special symbols is
 2925             ;; extended in future delsel.el, this discrimination
 2926             ;; will become wrong.
 2927             f
 2928           ;; Otherwise, call it as a function and return
 2929           ;; its value.
 2930           (funcall f)))))))
 2931 
 2932 (defun LaTeX-insert-corresponding-right-macro-and-brace
 2933   (lmacro lbrace &optional optional prompt)
 2934   "Insert right macro and brace correspoinding to LMACRO and LBRACE.
 2935 Left-right association is determined through
 2936 `LaTeX-left-right-macros-association' and `TeX-braces-association'.
 2937 
 2938 If brace association can't be determined or `TeX-arg-right-insert-p'
 2939 is nil, consult user which brace should be used."
 2940   ;; This function is called with LMACRO being one of the following
 2941   ;; possibilities.
 2942   ;;  (1) nil, which means LBRACE is isolated.
 2943   ;;  (2) null string, which means LBRACE follows right after "\" to
 2944   ;;      form "\(" or "\[".
 2945   ;;  (3) a string in CARs of `LaTeX-left-right-macros-association'.
 2946   (let ((rmacro (cdr (assoc lmacro LaTeX-left-right-macros-association)))
 2947     (rbrace (cdr (assoc lbrace TeX-braces-association))))
 2948     ;; Since braces like "\(" and "\)" should be paired, RMACRO
 2949     ;; should be considered as null string in the case (2).
 2950     (if (string= lmacro "")
 2951     (setq rmacro ""))
 2952     ;; Insert right macros such as "\right", "\bigr" etc., if necessary.
 2953     ;; Even single "\" will be inserted so that "\)" or "\]" is
 2954     ;; inserted after "\(", "\[".
 2955     (if rmacro
 2956     (insert TeX-esc rmacro))
 2957     (cond
 2958      ((and TeX-arg-right-insert-p rbrace)
 2959       (insert rbrace))
 2960      (rmacro
 2961       (insert (completing-read
 2962            (TeX-argument-prompt
 2963         optional prompt
 2964         (format "Which brace (default %s)"
 2965             (or rbrace "."))) TeX-left-right-braces
 2966             nil nil nil nil (or rbrace ".")))))))
 2967 
 2968 (defun LaTeX--find-preceding-left-macro-name ()
 2969   "Return the left macro name just before the point, if any.
 2970 If the preceding macro isn't left macros such as \\left, \\bigl etc.,
 2971 return nil.
 2972 If the point is just after unescaped `TeX-esc', return the null string."
 2973   ;; \left-!- => "left"
 2974   ;; \-!- => ""
 2975   ;; \infty-!- => nil
 2976   ;; \&-!- => nil
 2977   ;; \mathrm{abc}-!- => nil
 2978   ;; {blah blah blah}-!- => nil
 2979   ;; \\-!- => nil
 2980   (let ((name (buffer-substring-no-properties
 2981            (point)
 2982            ;; This is only a helper function, so we do not
 2983            ;; preserve point by save-excursion.
 2984            (progn
 2985          ;; Assume left macro names consist of only A-Z and a-z.
 2986          (skip-chars-backward "A-Za-z")
 2987          (point)))))
 2988     (if (and (TeX-escaped-p)
 2989          (or (string= name "")
 2990          (assoc name LaTeX-left-right-macros-association)))
 2991     name)))
 2992 (define-obsolete-function-alias
 2993   'LaTeX-find-preceeding-left-macro-name
 2994   #'LaTeX--find-preceding-left-macro-name "AUCTeX 12.2"
 2995   "Compatibility function for typo in its name.")
 2996 
 2997 (defcustom LaTeX-default-author 'user-full-name
 2998   "Initial input to `LaTeX-arg-author' prompt.
 2999 If nil, do not prompt at all."
 3000   :group 'LaTeX-macro
 3001   :type '(choice (const :tag "User name in Emacs" user-full-name)
 3002          (const :tag "Do not prompt" nil)
 3003          string))
 3004 
 3005 (defun LaTeX-arg-author (optional &optional prompt)
 3006   "Prompt for author name.
 3007 Insert the given value as a TeX macro argument.  If OPTIONAL is
 3008 non-nil, insert it as an optional argument.  Use PROMPT as the
 3009 prompt string.  `LaTeX-default-author' is the initial input."
 3010   (let ((author (if LaTeX-default-author
 3011             (TeX-read-string
 3012              (TeX-argument-prompt optional prompt "Author(s)")
 3013              (if (symbolp LaTeX-default-author)
 3014              (symbol-value LaTeX-default-author)
 3015                LaTeX-default-author))
 3016           "")))
 3017     (TeX-argument-insert author optional nil)))
 3018 
 3019 (defun TeX-read-key-val (optional key-val-alist &optional prompt)
 3020   "Prompt for keys and values in KEY-VAL-ALIST and return them.
 3021 If OPTIONAL is non-nil, indicate in the prompt that we are
 3022 reading an optional argument.  KEY-VAL-ALIST is an alist.  The
 3023 car of each element should be a string representing a key and the
 3024 optional cdr should be a list with strings to be used as values
 3025 for the key.  Use PROMPT as the prompt string."
 3026   (multi-prompt-key-value
 3027    (TeX-argument-prompt optional prompt "Options (k=v)")
 3028    (if (symbolp key-val-alist)
 3029        (eval key-val-alist)
 3030      key-val-alist)))
 3031 
 3032 (defun TeX-arg-key-val (optional key-val-alist &optional prompt)
 3033   "Prompt for keys and values in KEY-VAL-ALIST.
 3034 Insert the given value as a TeX macro argument.  If OPTIONAL is
 3035 non-nil, insert it as an optional argument.  KEY-VAL-ALIST is an
 3036 alist.  The car of each element should be a string representing a
 3037 key and the optional cdr should be a list with strings to be used
 3038 as values for the key.  Use PROMPT as the prompt string."
 3039   (let ((options (TeX-read-key-val optional key-val-alist prompt)))
 3040     (TeX-argument-insert options optional)))
 3041 
 3042 
 3043 ;;; Verbatim constructs
 3044 
 3045 (defcustom LaTeX-verbatim-macros-with-delims
 3046   '("verb" "verb*")
 3047   "Macros for inline verbatim with arguments in delimiters, like \\foo|...|.
 3048 
 3049 Programs should not use this variable directly but the function
 3050 `LaTeX-verbatim-macros-with-delims' which returns a value
 3051 including buffer-local keyword additions via
 3052 `LaTeX-verbatim-macros-with-delims-local' as well."
 3053   :group 'LaTeX-macro
 3054   :type '(repeat (string)))
 3055 
 3056 (defvar LaTeX-verbatim-macros-with-delims-local nil
 3057   "Buffer-local variable for inline verbatim with args in delimiters.
 3058 
 3059 Style files should add constructs to this variable and not to
 3060 `LaTeX-verbatim-macros-with-delims'.
 3061 
 3062 Programs should not use this variable directly but the function
 3063 `LaTeX-verbatim-macros-with-delims' which returns a value
 3064 including values of the variable
 3065 `LaTeX-verbatim-macros-with-delims' as well.")
 3066 (make-variable-buffer-local 'LaTeX-verbatim-macros-with-delims-local)
 3067 (put 'LaTeX-verbatim-macros-with-delims-local 'safe-local-variable
 3068      #'TeX--list-of-string-p)
 3069 
 3070 
 3071 (defcustom LaTeX-verbatim-macros-with-braces nil
 3072   "Macros for inline verbatim with arguments in braces, like \\foo{...}.
 3073 
 3074 Programs should not use this variable directly but the function
 3075 `LaTeX-verbatim-macros-with-braces' which returns a value
 3076 including buffer-local keyword additions via
 3077 `LaTeX-verbatim-macros-with-braces-local' as well."
 3078   :group 'LaTeX-macro
 3079   :type '(repeat (string)))
 3080 
 3081 (defvar LaTeX-verbatim-macros-with-braces-local nil
 3082   "Buffer-local variable for inline verbatim with args in braces.
 3083 
 3084 Style files should add constructs to this variable and not to
 3085 `LaTeX-verbatim-macros-with-braces'.
 3086 
 3087 Programs should not use this variable directly but the function
 3088 `LaTeX-verbatim-macros-with-braces' which returns a value
 3089 including values of the variable
 3090 `LaTeX-verbatim-macros-with-braces' as well.")
 3091 (make-variable-buffer-local 'LaTeX-verbatim-macros-with-braces-local)
 3092 (put 'LaTeX-verbatim-macros-with-braces-local 'safe-local-variable
 3093      #'TeX--list-of-string-p)
 3094 
 3095 (defcustom LaTeX-verbatim-environments
 3096   '("verbatim" "verbatim*" "filecontents" "filecontents*")
 3097   "Verbatim environments.
 3098 
 3099 Programs should not use this variable directly but the function
 3100 `LaTeX-verbatim-environments' which returns a value including
 3101 buffer-local keyword additions via
 3102 `LaTeX-verbatim-environments-local' as well."
 3103   :group 'LaTeX-environment
 3104   :type '(repeat (string)))
 3105 
 3106 (defvar LaTeX-verbatim-environments-local nil
 3107   "Buffer-local variable for inline verbatim environments.
 3108 
 3109 Style files should add constructs to this variable and not to
 3110 `LaTeX-verbatim-environments'.
 3111 
 3112 Programs should not use this variable directly but the function
 3113 `LaTeX-verbatim-environments' which returns a value including
 3114 values of the variable `LaTeX-verbatim-environments' as well.")
 3115 (make-variable-buffer-local 'LaTeX-verbatim-environments-local)
 3116 (put 'LaTeX-verbatim-environments-local 'safe-local-variable
 3117      #'TeX--list-of-string-p)
 3118 
 3119 (defun LaTeX-verbatim-macros-with-delims ()
 3120   "Return list of verbatim macros with delimiters."
 3121   (append LaTeX-verbatim-macros-with-delims
 3122       LaTeX-verbatim-macros-with-delims-local))
 3123 
 3124 (defun LaTeX-verbatim-macros-with-braces ()
 3125   "Return list of verbatim macros with braces."
 3126   (append LaTeX-verbatim-macros-with-braces
 3127       LaTeX-verbatim-macros-with-braces-local))
 3128 
 3129 (defun LaTeX-verbatim-environments ()
 3130   "Return list of verbatim environments."
 3131   (append LaTeX-verbatim-environments
 3132       LaTeX-verbatim-environments-local))
 3133 
 3134 (defun LaTeX-verbatim-macro-boundaries ()
 3135   "Return boundaries of verbatim macro.
 3136 Boundaries are returned as a cons cell where the car is the macro
 3137 start and the cdr the macro end.
 3138 
 3139 Only macros which enclose their arguments with special
 3140 non-parenthetical delimiters, like \\verb+foo+, are recognized."
 3141   (save-excursion
 3142     (let ((orig (point))
 3143       (verbatim-regexp (regexp-opt (LaTeX-verbatim-macros-with-delims) t)))
 3144       ;; Search backwards for the macro start, unless we are facing one
 3145       (unless (looking-at (concat (regexp-quote TeX-esc) verbatim-regexp))
 3146     (catch 'found
 3147       (while (progn
 3148            (skip-chars-backward (concat "^\n" (regexp-quote TeX-esc))
 3149                     (line-beginning-position))
 3150            (when (looking-at verbatim-regexp) (throw 'found nil))
 3151            (or (bobp) (forward-char -1))
 3152            (/= (point) (line-beginning-position))))))
 3153       ;; Search forward for the macro end, unless we failed to find a start
 3154       (unless (bolp)
 3155     (let* ((beg (1- (point)))
 3156            (macro-end (match-end 0))
 3157            ;; XXX: Here we assume we are dealing with \verb which
 3158            ;; expects the delimiter right behind the command.
 3159            ;; However, \lstinline can also cope with whitespace as
 3160            ;; well as an optional argument after the command.
 3161            (delimiter (buffer-substring-no-properties
 3162                macro-end (1+ macro-end))))
 3163       ;; Heuristic: If an opening brace is encountered, search for
 3164       ;; both the opening and the closing brace as an end marker.
 3165       ;; Like that the function should work for \verb|...| as well
 3166       ;; as for \url{...}.
 3167       (when (string= delimiter TeX-grop)
 3168         (setq delimiter (concat delimiter TeX-grcl)))
 3169       (goto-char (1+ macro-end))
 3170       (skip-chars-forward (concat "^" delimiter))
 3171       (when (<= orig (point))
 3172         (cons beg (1+ (point)))))))))
 3173 
 3174 (defun LaTeX-current-verbatim-macro ()
 3175   "Return name of verbatim macro containing point, nil if none is present."
 3176   (let ((macro-boundaries (LaTeX-verbatim-macro-boundaries)))
 3177     (when macro-boundaries
 3178       (save-excursion
 3179     (goto-char (car macro-boundaries))
 3180     (forward-char (length TeX-esc))
 3181     (buffer-substring-no-properties
 3182      (point) (progn (skip-chars-forward "@A-Za-z") (point)))))))
 3183 
 3184 (defun LaTeX-verbatim-p (&optional pos)
 3185   "Return non-nil if position POS is in a verbatim-like construct."
 3186   (when pos (goto-char pos))
 3187   (save-match-data
 3188     (or (when (fboundp 'font-latex-faces-present-p)
 3189       (font-latex-faces-present-p 'font-latex-verbatim-face))
 3190     (member (LaTeX-current-verbatim-macro)
 3191         (LaTeX-verbatim-macros-with-delims))
 3192     (member (TeX-current-macro) (LaTeX-verbatim-macros-with-braces))
 3193     (member (LaTeX-current-environment) (LaTeX-verbatim-environments)))))
 3194 
 3195 
 3196 ;;; Formatting
 3197 
 3198 (defcustom LaTeX-syntactic-comments t
 3199   "If non-nil comments will be handled according to LaTeX syntax.
 3200 This variable influences, among others, the behavior of
 3201 indentation and filling which will take LaTeX syntax into
 3202 consideration just as is in the non-commented source code."
 3203   :type 'boolean
 3204   :group 'LaTeX)
 3205 
 3206 
 3207 ;;; Indentation
 3208 
 3209 ;; We are distinguishing two different types of comments:
 3210 ;;
 3211 ;; 1) Comments starting in column one (line comments)
 3212 ;;
 3213 ;; 2) Comments starting after column one with only whitespace
 3214 ;;    preceding it.
 3215 ;;
 3216 ;; (There is actually a third type: Comments preceded not only by
 3217 ;; whitespace but by some code as well; so-called code comments.  But
 3218 ;; they are not relevant for the following explanations.)
 3219 ;;
 3220 ;; Additionally we are distinguishing two different types of
 3221 ;; indentation:
 3222 ;;
 3223 ;; a) Outer indentation: Indentation before the comment character(s).
 3224 ;;
 3225 ;; b) Inner indentation: Indentation after the comment character(s)
 3226 ;;    (taking into account possible comment padding).
 3227 ;;
 3228 ;; Comments can be filled syntax-aware or not.
 3229 ;;
 3230 ;; In `doctex-mode' line comments should always be indented
 3231 ;; syntax-aware and the comment character has to be anchored at the
 3232 ;; first column (unless the appear in a macrocode environment).  Other
 3233 ;; comments not in the documentation parts always start after the
 3234 ;; first column and can be indented syntax-aware or not.  If they are
 3235 ;; indented syntax-aware both the indentation before and after the
 3236 ;; comment character(s) have to be checked and adjusted.  Indentation
 3237 ;; should not move the comment character(s) to the first column.  With
 3238 ;; `LaTeX-syntactic-comments' disabled, line comments should still be
 3239 ;; indented syntax-aware.
 3240 ;;
 3241 ;; In `latex-mode' comments starting in different columns don't have
 3242 ;; to be handled differently.  They don't have to be anchored in
 3243 ;; column one.  That means that in any case indentation before and
 3244 ;; after the comment characters has to be checked and adjusted.
 3245 
 3246 (defgroup LaTeX-indentation nil
 3247   "Indentation of LaTeX code in AUCTeX"
 3248   :group 'LaTeX
 3249   :group 'TeX-indentation)
 3250 
 3251 (defcustom LaTeX-indent-level 2
 3252   "*Indentation of begin-end blocks in LaTeX."
 3253   :group 'LaTeX-indentation
 3254   :type 'integer)
 3255 
 3256 (defcustom LaTeX-item-indent (- LaTeX-indent-level)
 3257   "*Extra indentation for lines beginning with an item."
 3258   :group 'LaTeX-indentation
 3259   :type 'integer)
 3260 
 3261 (defcustom LaTeX-item-regexp "\\(bib\\)?item\\b"
 3262   "*Regular expression matching macros considered items."
 3263   :group 'LaTeX-indentation
 3264   :type 'regexp)
 3265 
 3266 (defcustom LaTeX-indent-environment-list
 3267   '(("verbatim" current-indentation)
 3268     ("verbatim*" current-indentation)
 3269     ("filecontents" current-indentation)
 3270     ("filecontents*" current-indentation)
 3271     ("tabular" LaTeX-indent-tabular)
 3272     ("tabular*" LaTeX-indent-tabular)
 3273     ("align" LaTeX-indent-tabular)
 3274     ("align*" LaTeX-indent-tabular)
 3275     ("array" LaTeX-indent-tabular)
 3276     ("eqnarray" LaTeX-indent-tabular)
 3277     ("eqnarray*" LaTeX-indent-tabular)
 3278     ;; The following should have their own, smart indentation function.
 3279     ;; Some other day.
 3280     ("displaymath")
 3281     ("equation")
 3282     ("equation*")
 3283     ("picture")
 3284     ("tabbing"))
 3285   "Alist of environments with special indentation.
 3286 The second element in each entry is the function to calculate the
 3287 indentation level in columns.
 3288 
 3289 Environments present in this list are not filled by filling
 3290 functions, see `LaTeX-fill-region-as-paragraph'."
 3291   :group 'LaTeX-indentation
 3292   :type '(repeat (list (string :tag "Environment")
 3293                (option function))))
 3294 
 3295 (defcustom LaTeX-indent-environment-check t
 3296   "*If non-nil, check for any special environments."
 3297   :group 'LaTeX-indentation
 3298   :type 'boolean)
 3299 
 3300 (defcustom LaTeX-document-regexp "document"
 3301   "Regexp matching environments in which the indentation starts at col 0."
 3302   :group 'LaTeX-indentation
 3303   :type 'regexp)
 3304 
 3305 (defcustom LaTeX-verbatim-regexp "verbatim\\*?"
 3306   "*Regexp matching environments with indentation at col 0 for begin/end."
 3307   :group 'LaTeX-indentation
 3308   :type 'regexp)
 3309 (make-obsolete-variable 'LaTeX-verbatim-regexp 'LaTeX-verbatim-environments-local
 3310             "2014-12-19")
 3311 
 3312 (defcustom LaTeX-begin-regexp "begin\\b\\|\\["
 3313   "*Regexp matching macros considered begins."
 3314   :group 'LaTeX-indentation
 3315   :type 'regexp)
 3316 
 3317 (defcustom LaTeX-end-regexp "end\\b\\|\\]"
 3318   "*Regexp matching macros considered ends."
 3319   :group 'LaTeX-indentation
 3320   :type 'regexp)
 3321 
 3322 (defcustom LaTeX-left-right-indent-level LaTeX-indent-level
 3323   "*The level of indentation produced by a \\left macro."
 3324   :group 'LaTeX-indentation
 3325   :type 'integer)
 3326 
 3327 (defcustom LaTeX-indent-comment-start-regexp "%"
 3328   "*Regexp matching comments ending the indent level count.
 3329 This means, we just count the LaTeX tokens \\left, \\right, \\begin,
 3330 and \\end up to the first occurence of text matching this regexp.
 3331 Thus, the default \"%\" stops counting the tokens at a comment.  A
 3332 value of \"%[^>]\" would allow you to alter the indentation with
 3333 comments, e.g. with comment `%> \\begin'.
 3334 Lines which start with `%' are not considered at all, regardless if this
 3335 value."
 3336   :group 'LaTeX-indentation
 3337   :type 'regexp)
 3338 
 3339 (defvar docTeX-indent-inner-fixed
 3340   `((,(concat (regexp-quote TeX-esc)
 3341          "\\(begin\\|end\\)[ \t]*{macrocode\\*?}") 4 t)
 3342     (,(concat (regexp-quote TeX-esc)
 3343          "\\(begin\\|end\\)[ \t]*{\\(macro\\|environment\\)\\*?}") 0 nil))
 3344   "List of items which should have a fixed inner indentation.
 3345 The items consist of three parts.  The first is a regular
 3346 expression which should match the respective string.  The second
 3347 is the amount of spaces to be used for indentation.  The third
 3348 toggles if comment padding is relevant or not.  If t padding is
 3349 part of the amount given, if nil the amount of spaces will be
 3350 inserted after potential padding.")
 3351 
 3352 (defun LaTeX-indent-line ()
 3353   "Indent the line containing point, as LaTeX source.
 3354 Add `LaTeX-indent-level' indentation in each \\begin{ - \\end{ block.
 3355 Lines starting with an item is given an extra indentation of
 3356 `LaTeX-item-indent'."
 3357   (interactive)
 3358   (let* ((case-fold-search nil)
 3359      ;; Compute a fill prefix.  Whitespace after the comment
 3360      ;; characters will be disregarded and replaced by
 3361      ;; `comment-padding'.
 3362      (fill-prefix
 3363       (and (TeX-in-commented-line)
 3364            (save-excursion
 3365          (beginning-of-line)
 3366          (looking-at
 3367           (concat "\\([ \t]*" TeX-comment-start-regexp "+\\)+"))
 3368          (concat (match-string 0) (TeX-comment-padding-string))))))
 3369     (save-excursion
 3370       (cond ((and fill-prefix
 3371           (TeX-in-line-comment)
 3372           (eq major-mode 'doctex-mode))
 3373          ;; If point is in a line comment in `doctex-mode' we only
 3374          ;; consider the inner indentation.
 3375          (let ((inner-indent (LaTeX-indent-calculate 'inner)))
 3376            (when (/= (LaTeX-current-indentation 'inner) inner-indent)
 3377          (LaTeX-indent-inner-do inner-indent))))
 3378         ((and fill-prefix
 3379           LaTeX-syntactic-comments)
 3380          ;; In any other case of a comment we have to consider
 3381          ;; outer and inner indentation if we do syntax-aware
 3382          ;; indentation.
 3383          (let ((inner-indent (LaTeX-indent-calculate 'inner))
 3384            (outer-indent (LaTeX-indent-calculate 'outer)))
 3385            (when (/= (LaTeX-current-indentation 'inner) inner-indent)
 3386            (LaTeX-indent-inner-do inner-indent))
 3387            (when (/= (LaTeX-current-indentation 'outer) outer-indent)
 3388            (LaTeX-indent-outer-do outer-indent))))
 3389         (t
 3390          ;; The default is to adapt whitespace before any
 3391          ;; non-whitespace character, i.e. to do outer
 3392          ;; indentation.
 3393          (let ((outer-indent (LaTeX-indent-calculate 'outer)))
 3394            (when (/= (LaTeX-current-indentation 'outer) outer-indent)
 3395            (LaTeX-indent-outer-do outer-indent))))))
 3396     (when (< (current-column) (save-excursion
 3397                 (LaTeX-back-to-indentation) (current-column)))
 3398       (LaTeX-back-to-indentation))))
 3399 
 3400 (defun LaTeX-indent-inner-do (inner-indent)
 3401   ;; Small helper function for `LaTeX-indent-line' to perform
 3402   ;; indentation after a comment character.  It requires that
 3403   ;; `LaTeX-indent-line' already set the appropriate variables and
 3404   ;; should not be used outside of `LaTeX-indent-line'.
 3405   (move-to-left-margin)
 3406   (TeX-re-search-forward-unescaped
 3407    (concat "\\(" TeX-comment-start-regexp "+[ \t]*\\)+") (line-end-position) t)
 3408   (delete-region (line-beginning-position) (point))
 3409   (insert fill-prefix)
 3410   (indent-to (+ inner-indent (length fill-prefix))))
 3411 
 3412 (defun LaTeX-indent-outer-do (outer-indent)
 3413   ;; Small helper function for `LaTeX-indent-line' to perform
 3414   ;; indentation of normal lines or before a comment character in a
 3415   ;; commented line.  It requires that `LaTeX-indent-line' already set
 3416   ;; the appropriate variables and should not be used outside of
 3417   ;; `LaTeX-indent-line'.
 3418   (back-to-indentation)
 3419   (delete-region (line-beginning-position) (point))
 3420   (indent-to outer-indent))
 3421 
 3422 (defun LaTeX-verbatim-regexp ()
 3423   "Calculate the verbatim env regex from `LaTeX-verbatim-environments'."
 3424   (regexp-opt (LaTeX-verbatim-environments)))
 3425 
 3426 (defun LaTeX-indent-calculate (&optional force-type)
 3427   "Return the indentation of a line of LaTeX source.
 3428 FORCE-TYPE can be used to force the calculation of an inner or
 3429 outer indentation in case of a commented line.  The symbols
 3430 'inner and 'outer are recognized."
 3431   (save-excursion
 3432     (LaTeX-back-to-indentation force-type)
 3433     (let ((i 0)
 3434       (list-length (safe-length docTeX-indent-inner-fixed))
 3435       (case-fold-search nil)
 3436       entry
 3437       found)
 3438       (cond ((save-excursion (beginning-of-line) (bobp)) 0)
 3439         ((and (eq major-mode 'doctex-mode)
 3440           fill-prefix
 3441           (TeX-in-line-comment)
 3442           (progn
 3443             (while (and (< i list-length)
 3444                 (not found))
 3445               (setq entry (nth i docTeX-indent-inner-fixed))
 3446               (when (looking-at (nth 0 entry))
 3447             (setq found t))
 3448               (setq i (1+ i)))
 3449             found))
 3450          (if (nth 2 entry)
 3451          (- (nth 1 entry) (if (integerp comment-padding)
 3452                       comment-padding
 3453                     (length comment-padding)))
 3454            (nth 1 entry)))
 3455         ((looking-at (concat (regexp-quote TeX-esc)
 3456                  "\\(begin\\|end\\){\\("
 3457                  (LaTeX-verbatim-regexp)
 3458                  "\\)}"))
 3459          ;; \end{verbatim} must be flush left, otherwise an unwanted
 3460          ;; empty line appears in LaTeX's output.
 3461          0)
 3462         ((and LaTeX-indent-environment-check
 3463           ;; Special environments.
 3464           (let ((entry (assoc (or LaTeX-current-environment
 3465                       (LaTeX-current-environment))
 3466                       LaTeX-indent-environment-list)))
 3467             (and entry
 3468              (nth 1 entry)
 3469              (funcall (nth 1 entry))))))
 3470         ((looking-at (concat (regexp-quote TeX-esc)
 3471                  "\\("
 3472                  LaTeX-end-regexp
 3473                  "\\)"))
 3474          ;; Backindent at \end.
 3475          (- (LaTeX-indent-calculate-last force-type) LaTeX-indent-level))
 3476         ((looking-at (concat (regexp-quote TeX-esc) "right\\b"))
 3477          ;; Backindent at \right.
 3478          (- (LaTeX-indent-calculate-last force-type)
 3479         LaTeX-left-right-indent-level))
 3480         ((looking-at (concat (regexp-quote TeX-esc)
 3481                  "\\("
 3482                  LaTeX-item-regexp
 3483                  "\\)"))
 3484          ;; Items.
 3485          (+ (LaTeX-indent-calculate-last force-type) LaTeX-item-indent))
 3486         ((looking-at "}")
 3487          ;; End brace in the start of the line.
 3488          (- (LaTeX-indent-calculate-last force-type)
 3489         TeX-brace-indent-level))
 3490         (t (LaTeX-indent-calculate-last force-type))))))
 3491 
 3492 (defun LaTeX-indent-level-count ()
 3493   "Count indentation change caused by all \\left, \\right, \\begin, and
 3494 \\end commands in the current line."
 3495   (save-excursion
 3496     (save-restriction
 3497       (let ((count 0))
 3498     (narrow-to-region (point)
 3499               (save-excursion
 3500                 (re-search-forward
 3501                  (concat "[^" TeX-esc "]"
 3502                      "\\(" LaTeX-indent-comment-start-regexp
 3503                      "\\)\\|\n\\|\\'"))
 3504                 (backward-char)
 3505                 (point)))
 3506     (while (search-forward TeX-esc nil t)
 3507       (cond
 3508        ((looking-at "left\\b")
 3509         (setq count (+ count LaTeX-left-right-indent-level)))
 3510        ((looking-at "right\\b")
 3511         (setq count (- count LaTeX-left-right-indent-level)))
 3512        ((looking-at LaTeX-begin-regexp)
 3513         (setq count (+ count LaTeX-indent-level)))
 3514        ((looking-at LaTeX-end-regexp)
 3515         (setq count (- count LaTeX-indent-level)))
 3516        ((looking-at (regexp-quote TeX-esc))
 3517         (forward-char 1))))
 3518     count))))
 3519 
 3520 (defun LaTeX-indent-calculate-last (&optional force-type)
 3521   "Return the correct indentation of a normal line of text.
 3522 The point is supposed to be at the beginning of the current line.
 3523 FORCE-TYPE can be used to force the calculation of an inner or
 3524 outer indentation in case of a commented line.  The symbols
 3525 'inner and 'outer are recognized."
 3526   (let (line-comment-current-flag
 3527     line-comment-last-flag
 3528     comment-current-flag
 3529     comment-last-flag)
 3530     (beginning-of-line)
 3531     (setq line-comment-current-flag (TeX-in-line-comment)
 3532       comment-current-flag (TeX-in-commented-line))
 3533     (if comment-current-flag
 3534     (skip-chars-backward "%\n\t ")
 3535       (skip-chars-backward "\n\t "))
 3536     (beginning-of-line)
 3537     ;; If we are called in a non-comment line, skip over comment
 3538     ;; lines.  The computation of indentation should in this case
 3539     ;; rather take the last non-comment line into account.
 3540     ;; Otherwise there might arise problems with e.g. multi-line
 3541     ;; code comments.  This behavior is not enabled in docTeX mode
 3542     ;; where large amounts of line comments may have to be skipped
 3543     ;; and indentation should not be influenced by unrelated code in
 3544     ;; other macrocode environments.
 3545     (while (and (not (eq major-mode 'doctex-mode))
 3546         (not comment-current-flag)
 3547         (TeX-in-commented-line)
 3548         (not (bobp)))
 3549       (skip-chars-backward "\n\t ")
 3550       (beginning-of-line))
 3551     (setq line-comment-last-flag (TeX-in-line-comment)
 3552       comment-last-flag (TeX-in-commented-line))
 3553     (LaTeX-back-to-indentation force-type)
 3554     ;; Separate line comments and other stuff (normal text/code and
 3555     ;; code comments).  Additionally we don't want to compute inner
 3556     ;; indentation when a commented and a non-commented line are
 3557     ;; compared.
 3558     (cond ((or (and (eq major-mode 'doctex-mode)
 3559             (or (and line-comment-current-flag
 3560                  (not line-comment-last-flag))
 3561             (and (not line-comment-current-flag)
 3562                  line-comment-last-flag)))
 3563            (and force-type
 3564             (eq force-type 'inner)
 3565             (or (and comment-current-flag
 3566                  (not comment-last-flag))
 3567             (and (not comment-current-flag)
 3568                  comment-last-flag))))
 3569        0)
 3570       ((looking-at (concat (regexp-quote TeX-esc)
 3571                    "begin *{\\("
 3572                    LaTeX-document-regexp
 3573                    "\\)}"))
 3574        ;; I dislike having all of the document indented...
 3575        (+ (LaTeX-current-indentation force-type)
 3576           ;; Some people have opening braces at the end of the
 3577           ;; line, e.g. in case of `\begin{letter}{%'.
 3578           (TeX-brace-count-line)))
 3579       ((and (eq major-mode 'doctex-mode)
 3580         (looking-at (concat (regexp-quote TeX-esc)
 3581                     "end[ \t]*{macrocode\\*?}"))
 3582         fill-prefix
 3583         (TeX-in-line-comment))
 3584        ;; Reset indentation to zero after a macrocode
 3585        ;; environment.
 3586        0)
 3587       ((looking-at (concat (regexp-quote TeX-esc)
 3588                    "begin *{\\("
 3589                    (LaTeX-verbatim-regexp)
 3590                    "\\)}"))
 3591        0)
 3592       ((looking-at (concat (regexp-quote TeX-esc)
 3593                    "end *{\\("
 3594                    (LaTeX-verbatim-regexp)
 3595                    "\\)}"))
 3596        ;; If I see an \end{verbatim} in the previous line I skip
 3597        ;; back to the preceding \begin{verbatim}.
 3598        (save-excursion
 3599          (if (re-search-backward (concat (regexp-quote TeX-esc)
 3600                          "begin *{\\("
 3601                          (LaTeX-verbatim-regexp)
 3602                          "\\)}") 0 t)
 3603          (LaTeX-indent-calculate-last force-type)
 3604            0)))
 3605       (t (+ (LaTeX-current-indentation force-type)
 3606         (if (not (and force-type
 3607                   (eq force-type 'outer)
 3608                   (TeX-in-commented-line)))
 3609             (+ (LaTeX-indent-level-count)
 3610                (TeX-brace-count-line))
 3611           0)
 3612         (cond ((looking-at (concat (regexp-quote TeX-esc)
 3613                        "\\("
 3614                        LaTeX-end-regexp
 3615                        "\\)"))
 3616                LaTeX-indent-level)
 3617               ((looking-at
 3618             (concat (regexp-quote TeX-esc) "right\\b"))
 3619                LaTeX-left-right-indent-level)
 3620               ((looking-at (concat (regexp-quote TeX-esc)
 3621                        "\\("
 3622                        LaTeX-item-regexp
 3623                        "\\)"))
 3624                (- LaTeX-item-indent))
 3625               ((looking-at "}")
 3626                TeX-brace-indent-level)
 3627               (t 0)))))))
 3628 
 3629 (defun LaTeX-current-indentation (&optional force-type)
 3630   "Return the indentation of a line.
 3631 FORCE-TYPE can be used to force the calculation of an inner or
 3632 outer indentation in case of a commented line.  The symbols
 3633 'inner and 'outer are recognized."
 3634   (if (and fill-prefix
 3635        (or (and force-type
 3636             (eq force-type 'inner))
 3637            (and (not force-type)
 3638             (or
 3639              ;; If `LaTeX-syntactic-comments' is not enabled,
 3640              ;; do conventional indentation
 3641              LaTeX-syntactic-comments
 3642              ;; Line comments in `doctex-mode' are always
 3643              ;; indented syntax-aware so we need their inner
 3644              ;; indentation.
 3645              (and (TeX-in-line-comment)
 3646               (eq major-mode 'doctex-mode))))))
 3647       ;; INNER indentation
 3648       (save-excursion
 3649     (beginning-of-line)
 3650     (looking-at (concat "\\(?:[ \t]*" TeX-comment-start-regexp "+\\)+"
 3651                 "\\([ \t]*\\)"))
 3652     (- (length (match-string 1)) (length (TeX-comment-padding-string))))
 3653     ;; OUTER indentation
 3654     (current-indentation)))
 3655 
 3656 (defun LaTeX-back-to-indentation (&optional force-type)
 3657   "Move point to the first non-whitespace character on this line.
 3658 If it is commented and comments are formatted syntax-aware move
 3659 point to the first non-whitespace character after the comment
 3660 character(s).  The optional argument FORCE-TYPE can be used to
 3661 force point being moved to the inner or outer indentation in case
 3662 of a commented line.  The symbols 'inner and 'outer are
 3663 recognized."
 3664   (if (or (and force-type
 3665            (eq force-type 'inner))
 3666       (and (not force-type)
 3667            (or (and (TeX-in-line-comment)
 3668             (eq major-mode 'doctex-mode))
 3669            (and (TeX-in-commented-line)
 3670             LaTeX-syntactic-comments))))
 3671       (progn
 3672     (beginning-of-line)
 3673     ;; Should this be anchored at the start of the line?
 3674     (TeX-re-search-forward-unescaped
 3675      (concat "\\(?:" TeX-comment-start-regexp "+[ \t]*\\)+")
 3676      (line-end-position) t))
 3677     (back-to-indentation)))
 3678 
 3679 
 3680 ;;; Filling
 3681 
 3682 ;; The default value should try not to break formulae across lines (this is
 3683 ;; useful for preview-latex) and give a meaningful filling.
 3684 (defcustom LaTeX-fill-break-at-separators '(\\\( \\\[)
 3685   "List of separators before or after which respectively a line
 3686 break will be inserted if they do not fit into one line."
 3687   :group 'LaTeX
 3688   :type '(set :tag "Contents"
 3689           (const :tag "Opening Brace" \{)
 3690           (const :tag "Closing Brace" \})
 3691           (const :tag "Opening Bracket" \[)
 3692           (const :tag "Opening Inline Math Switches" \\\()
 3693           (const :tag "Closing Inline Math Switches" \\\))
 3694           (const :tag "Opening Display Math Switch" \\\[)
 3695           (const :tag "Closing Display Math Switch" \\\])))
 3696 
 3697 (defcustom LaTeX-fill-break-before-code-comments t
 3698   "If non-nil, a line with some code followed by a comment will
 3699 be broken before the last non-comment word in case the comment
 3700 does not fit into the line."
 3701   :group 'LaTeX
 3702   :type 'boolean)
 3703 
 3704 (defcustom LaTeX-fill-excluded-macros nil
 3705   "List of macro names (without leading \\) whose arguments must
 3706 not be subject to filling."
 3707   :group 'LaTeX
 3708   :type '(repeat string))
 3709 
 3710 (defvar LaTeX-nospace-between-char-regexp "\\c|"
 3711   "Regexp matching a character where no interword space is necessary.
 3712 Words formed by such characters can be broken across newlines.")
 3713 
 3714 (defvar LaTeX-fill-newline-hook nil
 3715   "Hook run after `LaTeX-fill-newline' inserted and indented a new line.")
 3716 
 3717 (defun LaTeX-fill-region-as-paragraph (from to &optional justify-flag)
 3718   "Fill region as one paragraph.
 3719 Break lines to fit `fill-column', but leave all lines ending with
 3720 \\\\ \(plus its optional argument) alone.  Lines with code
 3721 comments and lines ending with `\par' are included in filling but
 3722 act as boundaries.  Prefix arg means justify too.  From program,
 3723 pass args FROM, TO and JUSTIFY-FLAG.
 3724 
 3725 You can disable filling inside a specific environment by adding
 3726 it to `LaTeX-indent-environment-list', only indentation is
 3727 performed in that case."
 3728   (interactive "*r\nP")
 3729   (let ((end-marker (save-excursion (goto-char to) (point-marker))))
 3730     (if (or (assoc (LaTeX-current-environment) LaTeX-indent-environment-list)
 3731         (member (TeX-current-macro) LaTeX-fill-excluded-macros)
 3732         ;; This could be generalized, if there are more cases where
 3733         ;; a special string at the start of a region to fill should
 3734         ;; inhibit filling.
 3735         (progn (save-excursion (goto-char from)
 3736                    (looking-at (concat TeX-comment-start-regexp
 3737                                "+[ \t]*"
 3738                                "Local Variables:")))))
 3739     ;; Filling disabled, only do indentation.
 3740     (indent-region from to nil)
 3741       (save-restriction
 3742     (goto-char from)
 3743     (while (< (point) end-marker)
 3744       (if (re-search-forward
 3745            (concat "\\("
 3746                ;; Code comments.
 3747                "[^\r\n%\\]\\([ \t]\\|\\\\\\\\\\)*"
 3748                TeX-comment-start-regexp
 3749                "\\|"
 3750                ;; Lines ending with `\par'.
 3751                "\\(\\=\\|[^" TeX-esc "\n]\\)\\("
 3752                (regexp-quote (concat TeX-esc TeX-esc))
 3753                "\\)*"
 3754                (regexp-quote TeX-esc) "par[ \t]*"
 3755                "\\({[ \t]*}\\)?[ \t]*$"
 3756                "\\)\\|\\("
 3757                ;; Lines ending with `\\'.
 3758                (regexp-quote TeX-esc)
 3759                (regexp-quote TeX-esc)
 3760                "\\(\\s-*\\*\\)?"
 3761                "\\(\\s-*\\[[^]]*\\]\\)?"
 3762                "\\s-*$\\)")
 3763            end-marker t)
 3764           (progn
 3765         (goto-char (line-end-position))
 3766         (delete-horizontal-space)
 3767         ;; I doubt very much if we want justify -
 3768         ;; this is a line with \\
 3769         ;; if you think otherwise - uncomment the next line
 3770         ;; (and justify-flag (justify-current-line))
 3771         (forward-char)
 3772         ;; keep our position in a buffer
 3773         (save-excursion
 3774           ;; Code comments and lines ending with `\par' are
 3775           ;; included in filling.  Lines ending with `\\' are
 3776           ;; skipped.
 3777           (if (match-string 1)
 3778               (LaTeX-fill-region-as-para-do from (point) justify-flag)
 3779             (LaTeX-fill-region-as-para-do
 3780              from (line-beginning-position 0) justify-flag)
 3781             ;; At least indent the line ending with `\\'.
 3782             (indent-according-to-mode)))
 3783         (setq from (point)))
 3784         ;; ELSE part follows - loop termination relies on a fact
 3785         ;; that (LaTeX-fill-region-as-para-do) moves point past
 3786         ;; the filled region
 3787         (LaTeX-fill-region-as-para-do from end-marker justify-flag)))))))
 3788 
 3789 ;; The content of `LaTeX-fill-region-as-para-do' was copied from the
 3790 ;; function `fill-region-as-paragraph' in `fill.el' (CVS Emacs,
 3791 ;; January 2004) and adapted to the needs of AUCTeX.
 3792 
 3793 (defun LaTeX-fill-region-as-para-do (from to &optional justify
 3794                       nosqueeze squeeze-after)
 3795   "Fill the region defined by FROM and TO as one paragraph.
 3796 It removes any paragraph breaks in the region and extra newlines at the end,
 3797 indents and fills lines between the margins given by the
 3798 `current-left-margin' and `current-fill-column' functions.
 3799 \(In most cases, the variable `fill-column' controls the width.)
 3800 It leaves point at the beginning of the line following the paragraph.
 3801 
 3802 Normally performs justification according to the `current-justification'
 3803 function, but with a prefix arg, does full justification instead.
 3804 
 3805 From a program, optional third arg JUSTIFY can specify any type of
 3806 justification.  Fourth arg NOSQUEEZE non-nil means not to make spaces
 3807 between words canonical before filling.  Fifth arg SQUEEZE-AFTER, if non-nil,
 3808 means don't canonicalize spaces before that position.
 3809 
 3810 Return the `fill-prefix' used for filling.
 3811 
 3812 If `sentence-end-double-space' is non-nil, then period followed by one
 3813 space does not end a sentence, so don't break a line there."
 3814   (interactive (progn
 3815          (barf-if-buffer-read-only)
 3816          (list (region-beginning) (region-end)
 3817                (if current-prefix-arg 'full))))
 3818   (unless (memq justify '(t nil none full center left right))
 3819     (setq justify 'full))
 3820 
 3821   ;; Make sure "to" is the endpoint.
 3822   (goto-char (min from to))
 3823   (setq to   (max from to))
 3824   ;; Ignore blank lines at beginning of region.
 3825   (skip-chars-forward " \t\n")
 3826 
 3827   (let ((from-plus-indent (point))
 3828     (oneleft nil))
 3829 
 3830     (beginning-of-line)
 3831     (setq from (point))
 3832 
 3833     ;; Delete all but one soft newline at end of region.
 3834     ;; And leave TO before that one.
 3835     (goto-char to)
 3836     (while (and (> (point) from) (eq ?\n (char-after (1- (point)))))
 3837       (if (and oneleft
 3838            (not (and use-hard-newlines
 3839              (get-text-property (1- (point)) 'hard))))
 3840       (delete-char -1)
 3841     (backward-char 1)
 3842     (setq oneleft t)))
 3843     (setq to (copy-marker (point) t))
 3844     (goto-char from-plus-indent))
 3845 
 3846   (if (not (> to (point)))
 3847       nil ;; There is no paragraph, only whitespace: exit now.
 3848 
 3849     (or justify (setq justify (current-justification)))
 3850 
 3851     ;; Don't let Adaptive Fill mode alter the fill prefix permanently.
 3852     (let ((fill-prefix fill-prefix))
 3853       ;; Figure out how this paragraph is indented, if desired.
 3854       (when (and adaptive-fill-mode
 3855          (or (null fill-prefix) (string= fill-prefix "")))
 3856     (setq fill-prefix (fill-context-prefix from to))
 3857     ;; Ignore a white-space only fill-prefix
 3858     ;; if we indent-according-to-mode.
 3859     (when (and fill-prefix fill-indent-according-to-mode
 3860            (string-match "\\`[ \t]*\\'" fill-prefix))
 3861       (setq fill-prefix nil)))
 3862 
 3863       (goto-char from)
 3864       (beginning-of-line)
 3865 
 3866       (if (not justify)   ; filling disabled: just check indentation
 3867       (progn
 3868         (goto-char from)
 3869         (while (< (point) to)
 3870           (if (and (not (eolp))
 3871                (< (LaTeX-current-indentation) (current-left-margin)))
 3872           (fill-indent-to-left-margin))
 3873           (forward-line 1)))
 3874 
 3875     (when use-hard-newlines
 3876       (remove-text-properties from to '(hard nil)))
 3877     ;; Make sure first line is indented (at least) to left margin...
 3878     (indent-according-to-mode)
 3879     ;; Delete the fill-prefix from every line.
 3880     (fill-delete-prefix from to fill-prefix)
 3881 
 3882     (setq from (point))
 3883 
 3884     ;; FROM, and point, are now before the text to fill,
 3885     ;; but after any fill prefix on the first line.
 3886 
 3887     (fill-delete-newlines from to justify nosqueeze squeeze-after)
 3888 
 3889     ;; This is the actual FILLING LOOP.
 3890     (goto-char from)
 3891     (let* (linebeg
 3892            (code-comment-start (save-excursion
 3893                      (LaTeX-back-to-indentation)
 3894                      (TeX-search-forward-comment-start
 3895                       (line-end-position))))
 3896            (end-marker (save-excursion
 3897                  (goto-char (or code-comment-start to))
 3898                  (point-marker)))
 3899            (LaTeX-current-environment (LaTeX-current-environment)))
 3900       ;; Fill until point is greater than the end point.  If there
 3901       ;; is a code comment, use the code comment's start as a
 3902       ;; limit.
 3903       (while (and (< (point) (marker-position end-marker))
 3904               (or (not code-comment-start)
 3905               (and code-comment-start
 3906                    (> (- (marker-position end-marker)
 3907                      (line-beginning-position))
 3908                   fill-column))))
 3909         (setq linebeg (point))
 3910         (move-to-column (current-fill-column))
 3911         (if (when (< (point) (marker-position end-marker))
 3912           ;; Find the position where we'll break the line.
 3913           (forward-char 1)  ; Use an immediately following
 3914                     ; space, if any.
 3915           (LaTeX-fill-move-to-break-point linebeg)
 3916 
 3917           ;; Check again to see if we got to the end of
 3918           ;; the paragraph.
 3919           (skip-chars-forward " \t")
 3920           (< (point) (marker-position end-marker)))
 3921         ;; Found a place to cut.
 3922         (progn
 3923           (LaTeX-fill-newline)
 3924           (when justify
 3925             ;; Justify the line just ended, if desired.
 3926             (save-excursion
 3927               (forward-line -1)
 3928               (justify-current-line justify nil t))))
 3929 
 3930           (goto-char end-marker)
 3931           ;; Justify this last line, if desired.
 3932           (if justify (justify-current-line justify t t))))
 3933 
 3934       ;; Fill a code comment if necessary.  (Enable this code if
 3935       ;; you want the comment part in lines with code comments to
 3936       ;; be filled.  Originally it was disabled because the
 3937       ;; indentation code indented the lines following the line
 3938       ;; with the code comment to the column of the comment
 3939       ;; starters.  That means, it would have looked like this:
 3940       ;; | code code code % comment
 3941       ;; |                % comment
 3942       ;; |                code code code
 3943       ;; This now (2005-07-29) is not the case anymore.  But as
 3944       ;; filling code comments like this would split a single
 3945       ;; paragraph into two separate ones, we still leave it
 3946       ;; disabled.  I leave the code here in case it is useful for
 3947       ;; somebody.
 3948       ;; (when (and code-comment-start
 3949       ;;            (> (- (line-end-position) (line-beginning-position))
 3950       ;;                  fill-column))
 3951       ;;   (LaTeX-fill-code-comment justify))
 3952 
 3953       ;; The following is an alternative strategy to minimize the
 3954       ;; occurence of overfull lines with code comments.  A line
 3955       ;; will be broken before the last non-comment word if the
 3956       ;; code comment does not fit into the line.
 3957       (when (and LaTeX-fill-break-before-code-comments
 3958              code-comment-start
 3959              (> (- (line-end-position) (line-beginning-position))
 3960             fill-column))
 3961         (beginning-of-line)
 3962         (goto-char end-marker)
 3963         (while (not (looking-at TeX-comment-start-regexp)) (forward-char))
 3964         (skip-chars-backward " \t")
 3965         (skip-chars-backward "^ \t\n")
 3966         (unless (or (bolp)
 3967             ;; Comment starters and whitespace.
 3968             (TeX-looking-at-backward
 3969              (concat "^\\([ \t]*" TeX-comment-start-regexp "+\\)*"
 3970                  "[ \t]*")
 3971              (line-beginning-position)))
 3972           (LaTeX-fill-newline)))))
 3973       ;; Leave point after final newline.
 3974       (goto-char to)
 3975       (unless (eobp) (forward-char 1))
 3976       ;; Return the fill-prefix we used
 3977       fill-prefix)))
 3978 
 3979 (defun LaTeX-fill-move-to-break-point (linebeg)
 3980   "Move to the position where the line should be broken."
 3981   (fill-move-to-break-point linebeg)
 3982   ;; Prevent line break between 2-byte char and 1-byte char.
 3983   (when (and (featurep 'mule)
 3984          enable-multibyte-characters
 3985          (or (and (not (looking-at LaTeX-nospace-between-char-regexp))
 3986               (TeX-looking-at-backward
 3987                LaTeX-nospace-between-char-regexp 1))
 3988          (and (not (TeX-looking-at-backward
 3989                 LaTeX-nospace-between-char-regexp 1))
 3990               (looking-at LaTeX-nospace-between-char-regexp)))
 3991          (re-search-backward
 3992           (concat LaTeX-nospace-between-char-regexp
 3993               LaTeX-nospace-between-char-regexp
 3994               LaTeX-nospace-between-char-regexp
 3995               "\\|"
 3996               ".\\ca\\s +\\ca") linebeg t))
 3997     (if (looking-at "..\\c>")
 3998     (forward-char 1)
 3999       (forward-char 2)))
 4000   ;; Cater for Japanese Macro
 4001   (when (and (boundp 'japanese-TeX-mode) japanese-TeX-mode
 4002          (aref (char-category-set (char-after)) ?j)
 4003          (TeX-looking-at-backward (concat (regexp-quote TeX-esc) TeX-token-char "*")
 4004                       (1- (- (point) linebeg)))
 4005          (not (TeX-escaped-p (match-beginning 0))))
 4006       (goto-char (match-beginning 0)))
 4007   ;; Cater for \verb|...| (and similar) contructs which should not be
 4008   ;; broken. (FIXME: Make it work with shortvrb.sty (also loaded by
 4009   ;; doc.sty) where |...| is allowed.  Arbitrary delimiters may be
 4010   ;; chosen with \MakeShortVerb{<char>}.)  This could probably be
 4011   ;; handled with `fill-nobreak-predicate', but this is not available
 4012   ;; in XEmacs.
 4013   (let ((final-breakpoint (point))
 4014     (verb-macros (regexp-opt (append (LaTeX-verbatim-macros-with-delims)
 4015                      (LaTeX-verbatim-macros-with-braces)))))
 4016     (save-excursion
 4017       ;; Look for the start of a verbatim macro in the current line.
 4018       (when (re-search-backward (concat (regexp-quote TeX-esc)
 4019                     "\\(?:" verb-macros "\\)\\([^a-z@*]\\)")
 4020                 (line-beginning-position) t)
 4021     ;; Determine start and end of verbatim macro.
 4022     (let ((beg (point))
 4023           (end (if (not (string-match "[ [{]" (match-string 1)))
 4024                (cdr (LaTeX-verbatim-macro-boundaries))
 4025              (TeX-find-macro-end))))
 4026       ;; Determine if macro end is behind fill column.
 4027       (when (and end
 4028              (> (- end (line-beginning-position))
 4029             (current-fill-column))
 4030              (> end final-breakpoint))
 4031         ;; Search backwards for place to break before the macro.
 4032         (goto-char beg)
 4033         (skip-chars-backward "^ \n")
 4034         ;; Determine if point ended up at the beginning of the line.
 4035         (when (save-excursion (skip-chars-backward " \t%") (bolp))
 4036           ;; Search forward for a place to break after the macro.
 4037           (goto-char end)
 4038           (skip-chars-forward "^ \n" (point-max)))
 4039         (setq final-breakpoint (point))))))
 4040     (goto-char final-breakpoint))
 4041   (when LaTeX-fill-break-at-separators
 4042     (let ((orig-breakpoint (point))
 4043       (final-breakpoint (point))
 4044       start-point)
 4045       (save-excursion
 4046     (beginning-of-line)
 4047     (LaTeX-back-to-indentation)
 4048     (setq start-point (point))
 4049     ;; Find occurences of [, $, {, }, \(, \), \[, \] or $$.
 4050     (while (and (= final-breakpoint orig-breakpoint)
 4051             (TeX-re-search-forward-unescaped
 4052              (concat "[[{}]\\|\\$\\$?\\|"
 4053                  (regexp-quote TeX-esc) "[][()]")
 4054              orig-breakpoint t))
 4055       (let ((match-string (match-string 0)))
 4056         (cond
 4057          ;; [ (opening bracket) (The closing bracket should
 4058          ;; already be handled implicitely by the code for the
 4059          ;; opening brace.)
 4060          ((save-excursion
 4061         (and (memq '\[ LaTeX-fill-break-at-separators)
 4062              (string= match-string "[")
 4063              (TeX-re-search-forward-unescaped (concat "\\][ \t]*{")
 4064                               (line-end-position) t)
 4065              (> (- (or (TeX-find-closing-brace)
 4066                    (line-end-position))
 4067                (line-beginning-position))
 4068             fill-column)))
 4069           (save-excursion
 4070         (skip-chars-backward "^ \n")
 4071         (when (> (point) start-point)
 4072           (setq final-breakpoint (point)))))
 4073          ;; { (opening brace)
 4074          ((save-excursion
 4075         (and (memq '\{ LaTeX-fill-break-at-separators)
 4076              (string= match-string "{")
 4077              (> (- (save-excursion
 4078                  ;; `TeX-find-closing-brace' is not enough
 4079                  ;; if there is no breakpoint in form of
 4080                  ;; whitespace after the brace.
 4081                  (goto-char (or (TeX-find-closing-brace)
 4082                         (line-end-position)))
 4083                  (skip-chars-forward "^ \t\n")
 4084                  (point))
 4085                (line-beginning-position))
 4086             fill-column)))
 4087           (save-excursion
 4088         (skip-chars-backward "^ \n")
 4089         ;; The following is a primitive and error-prone method
 4090         ;; to cope with point probably being inside square
 4091         ;; brackets.  A better way would be to use functions
 4092         ;; to determine if point is inside an optional
 4093         ;; argument and to jump to the start and end brackets.
 4094         (when (save-excursion
 4095             (TeX-re-search-forward-unescaped
 4096              (concat "\\][ \t]*{") orig-breakpoint t))
 4097           (TeX-search-backward-unescaped "["
 4098                          (line-beginning-position) t)
 4099           (skip-chars-backward "^ \n"))
 4100         (when (> (point) start-point)
 4101           (setq final-breakpoint (point)))))
 4102          ;; } (closing brace)
 4103          ((save-excursion
 4104         (and (memq '\} LaTeX-fill-break-at-separators)
 4105              (string= match-string "}")
 4106              (save-excursion
 4107                (backward-char 2)
 4108                (not (TeX-find-opening-brace
 4109                  nil (line-beginning-position))))))
 4110           (save-excursion
 4111         (skip-chars-forward "^ \n")
 4112         (when (> (point) start-point)
 4113           (setq final-breakpoint (point)))))
 4114          ;; $ or \( or \[ or $$ (opening math)
 4115          ((save-excursion
 4116         (and (or (and (memq '\\\( LaTeX-fill-break-at-separators)
 4117                   (or (and (string= match-string "$")
 4118                        (texmathp))
 4119                   (string= match-string "\\(")))
 4120              (and (memq '\\\[ LaTeX-fill-break-at-separators)
 4121                   (or (string= match-string "\\[")
 4122                   (and (string= match-string "$$")
 4123                        (texmathp)))))
 4124              (> (- (save-excursion
 4125                  (TeX-search-forward-unescaped
 4126                   (cond ((string= match-string "\\(")
 4127                      (concat TeX-esc ")"))
 4128                     ((string= match-string "$") "$")
 4129                     ((string= match-string "$$") "$$")
 4130                     (t (concat TeX-esc "]")))
 4131                   (point-max) t)
 4132                  (skip-chars-forward "^ \n")
 4133                  (point))
 4134                (line-beginning-position))
 4135             fill-column)))
 4136           (save-excursion
 4137         (skip-chars-backward "^ \n")
 4138         (when (> (point) start-point)
 4139           (setq final-breakpoint (point)))))
 4140          ;; $ or \) or \] or $$ (closing math)
 4141          ((save-excursion
 4142         (and (or (and (memq '\\\) LaTeX-fill-break-at-separators)
 4143                   (or (and (string= match-string "$")
 4144                        (not (texmathp)))
 4145                   (string= match-string "\\)")))
 4146              (and (memq '\\\] LaTeX-fill-break-at-separators)
 4147                   (or (string= match-string "\\]")
 4148                   (and (string= match-string "$$")
 4149                        (not (texmathp))))))
 4150              (if (member match-string '("$" "$$"))
 4151              (save-excursion
 4152                (skip-chars-backward "$")
 4153                (TeX-search-backward-unescaped
 4154                 match-string (line-beginning-position) t))
 4155                (texmathp-match-switch (line-beginning-position)))))
 4156           (save-excursion
 4157         (skip-chars-forward "^ \n")
 4158         (when (> (point) start-point)
 4159           (setq final-breakpoint (point)))))))))
 4160       (goto-char final-breakpoint))))
 4161 
 4162 ;; The content of `LaTeX-fill-newline' was copied from the function
 4163 ;; `fill-newline' in `fill.el' (CVS Emacs, January 2004) and adapted
 4164 ;; to the needs of AUCTeX.
 4165 (defun LaTeX-fill-newline ()
 4166   "Replace whitespace here with one newline and indent the line."
 4167   (skip-chars-backward " \t")
 4168   (newline 1)
 4169   ;; Give newline the properties of the space(s) it replaces
 4170   (set-text-properties (1- (point)) (point)
 4171                (text-properties-at (point)))
 4172   (and (looking-at "\\( [ \t]*\\)\\(\\c|\\)?")
 4173        (or (aref (char-category-set (or (char-before (1- (point))) ?\000)) ?|)
 4174        (match-end 2))
 4175        ;; When refilling later on, this newline would normally not
 4176        ;; be replaced by a space, so we need to mark it specially to
 4177        ;; re-install the space when we unfill.
 4178        (put-text-property (1- (point)) (point) 'fill-space (match-string 1)))
 4179   ;; If we don't want breaks in invisible text, don't insert
 4180   ;; an invisible newline.
 4181   (if fill-nobreak-invisible
 4182       (remove-text-properties (1- (point)) (point)
 4183                   '(invisible t)))
 4184   ;; Insert the fill prefix.
 4185   (and fill-prefix (not (equal fill-prefix ""))
 4186        ;; Markers that were after the whitespace are now at point: insert
 4187        ;; before them so they don't get stuck before the prefix.
 4188        (insert-before-markers-and-inherit fill-prefix))
 4189   (indent-according-to-mode)
 4190   (run-hooks 'LaTeX-fill-newline-hook))
 4191 
 4192 (defun LaTeX-fill-paragraph (&optional justify)
 4193   "Like `fill-paragraph', but handle LaTeX comments.
 4194 If any of the current line is a comment, fill the comment or the
 4195 paragraph of it that point is in.  Code comments, i.e. comments
 4196 with uncommented code preceding them in the same line, will not
 4197 be filled unless the cursor is placed on the line with the
 4198 code comment.
 4199 
 4200 If LaTeX syntax is taken into consideration during filling
 4201 depends on the value of `LaTeX-syntactic-comments'."
 4202   (interactive "P")
 4203   (if (save-excursion
 4204     (beginning-of-line)
 4205     (looking-at (concat TeX-comment-start-regexp "*[ \t]*$")))
 4206       ;; Don't do anything if we look at an empty line and let
 4207       ;; `fill-paragraph' think we successfully filled the paragraph.
 4208       t
 4209     (let (;; Non-nil if the current line contains a comment.
 4210       has-comment
 4211       ;; Non-nil if the current line contains code and a comment.
 4212       has-code-and-comment
 4213       code-comment-start
 4214       ;; If has-comment, the appropriate fill-prefix for the comment.
 4215       comment-fill-prefix)
 4216 
 4217       ;; Figure out what kind of comment we are looking at.
 4218       (cond
 4219        ;; A line only with potential whitespace followed by a
 4220        ;; comment on it?
 4221        ((save-excursion
 4222       (beginning-of-line)
 4223       (looking-at (concat "^[ \t]*" TeX-comment-start-regexp
 4224                   "\\(" TeX-comment-start-regexp "\\|[ \t]\\)*")))
 4225     (setq has-comment t
 4226           comment-fill-prefix (TeX-match-buffer 0)))
 4227        ;; A line with some code, followed by a comment?
 4228        ((and (setq code-comment-start (save-excursion
 4229                     (beginning-of-line)
 4230                     (TeX-search-forward-comment-start
 4231                      (line-end-position))))
 4232          (> (point) code-comment-start)
 4233          (not (TeX-in-commented-line))
 4234          (save-excursion
 4235            (goto-char code-comment-start)
 4236            ;; See if there is at least one non-whitespace character
 4237            ;; before the comment starts.
 4238            (re-search-backward "[^ \t\n]" (line-beginning-position) t)))
 4239     (setq has-comment t
 4240           has-code-and-comment t)))
 4241 
 4242       (cond
 4243        ;; Code comments.
 4244        (has-code-and-comment
 4245     (save-excursion
 4246       (when (>= (- code-comment-start (line-beginning-position))
 4247             fill-column)
 4248         ;; If start of code comment is beyond fill column, fill it as a
 4249         ;; regular paragraph before it is filled as a code comment.
 4250         (let ((end-marker (save-excursion (end-of-line) (point-marker))))
 4251           (LaTeX-fill-region-as-paragraph (line-beginning-position)
 4252                           (line-beginning-position 2)
 4253                           justify)
 4254           (goto-char end-marker)
 4255           (beginning-of-line)))
 4256       (LaTeX-fill-code-comment justify)))
 4257        ;; Syntax-aware filling:
 4258        ;; * `LaTeX-syntactic-comments' enabled: Everything.
 4259        ;; * `LaTeX-syntactic-comments' disabled: Uncommented code and
 4260        ;;   line comments in `doctex-mode'.
 4261        ((or (or LaTeX-syntactic-comments
 4262         (and (not LaTeX-syntactic-comments)
 4263              (not has-comment)))
 4264         (and (eq major-mode 'doctex-mode)
 4265          (TeX-in-line-comment)))
 4266     (let ((fill-prefix comment-fill-prefix))
 4267       (save-excursion
 4268         (let* ((end (progn (LaTeX-forward-paragraph)
 4269                    (or (bolp) (newline 1))
 4270                    (and (eobp) (not (bolp)) (open-line 1))
 4271                    (point)))
 4272            (start
 4273             (progn
 4274               (LaTeX-backward-paragraph)
 4275               (while (and (looking-at
 4276                    (concat "$\\|[ \t]+$\\|"
 4277                        "[ \t]*" TeX-comment-start-regexp
 4278                        "+[ \t]*$"))
 4279                   (< (point) end))
 4280             (forward-line))
 4281               (point))))
 4282           (LaTeX-fill-region-as-paragraph start end justify)))))
 4283     ;; Non-syntax-aware filling.
 4284        (t
 4285     (save-excursion
 4286       (save-restriction
 4287         (beginning-of-line)
 4288         (narrow-to-region
 4289          ;; Find the first line we should include in the region to fill.
 4290          (save-excursion
 4291            (while (and (zerop (forward-line -1))
 4292                (looking-at (concat "^[ \t]*"
 4293                            TeX-comment-start-regexp))))
 4294            ;; We may have gone too far.  Go forward again.
 4295            (or (looking-at (concat ".*" TeX-comment-start-regexp))
 4296            (forward-line 1))
 4297            (point))
 4298          ;; Find the beginning of the first line past the region to fill.
 4299          (save-excursion
 4300            (while (progn (forward-line 1)
 4301                  (looking-at (concat "^[ \t]*"
 4302                          TeX-comment-start-regexp))))
 4303            (point)))
 4304         ;; The definitions of `paragraph-start' and
 4305         ;; `paragraph-separate' will still make
 4306         ;; `forward-paragraph' and `backward-paragraph' stop at
 4307         ;; the respective (La)TeX commands.  If these should be
 4308         ;; disregarded, the definitions would have to be changed
 4309         ;; accordingly.  (Lines with only `%' characters on them
 4310         ;; can be paragraph boundaries.)
 4311         (let* ((paragraph-start
 4312             (concat paragraph-start "\\|"
 4313                 "\\(" TeX-comment-start-regexp "\\|[ \t]\\)*$"))
 4314            (paragraph-separate
 4315             (concat paragraph-separate "\\|"
 4316                 "\\(" TeX-comment-start-regexp "\\|[ \t]\\)*$"))
 4317            (fill-prefix comment-fill-prefix)
 4318            (end (progn (forward-paragraph)
 4319                    (or (bolp) (newline 1))
 4320                    (point)))
 4321            (beg (progn (backward-paragraph)
 4322                    (point))))
 4323           (fill-region-as-paragraph
 4324            beg end
 4325            justify nil
 4326            (save-excursion
 4327          (goto-char beg)
 4328          (if (looking-at fill-prefix)
 4329              nil
 4330            (re-search-forward comment-start-skip nil t)
 4331            (point)))))))))
 4332       t)))
 4333 
 4334 (defun LaTeX-fill-code-comment (&optional justify-flag)
 4335   "Fill a line including code followed by a comment."
 4336   (let ((beg (line-beginning-position))
 4337     fill-prefix code-comment-start)
 4338     (indent-according-to-mode)
 4339     (when (when (setq code-comment-start (save-excursion
 4340                        (goto-char beg)
 4341                        (TeX-search-forward-comment-start
 4342                         (line-end-position))))
 4343         (goto-char code-comment-start)
 4344         (while (not (looking-at TeX-comment-start-regexp)) (forward-char))
 4345         ;; See if there is at least one non-whitespace character
 4346         ;; before the comment starts.
 4347         (save-excursion
 4348           (re-search-backward "[^ \t\n]" (line-beginning-position) t)))
 4349       (setq fill-prefix
 4350         (concat
 4351          (if indent-tabs-mode
 4352          (concat (make-string (/ (current-column) tab-width) ?\t)
 4353              (make-string (% (current-column) tab-width) ?\ ))
 4354            (make-string (current-column) ?\ ))
 4355          (progn
 4356            (looking-at (concat TeX-comment-start-regexp "+[ \t]*"))
 4357            (TeX-match-buffer 0))))
 4358       (fill-region-as-paragraph beg (line-beginning-position 2)
 4359                 justify-flag  nil
 4360                 (save-excursion
 4361                   (goto-char beg)
 4362                   (if (looking-at fill-prefix)
 4363                       nil
 4364                     (re-search-forward comment-start-skip nil t)
 4365                     (point)))))))
 4366 
 4367 (defun LaTeX-fill-region (from to &optional justify what)
 4368   "Fill and indent the text in region from FROM to TO as LaTeX text.
 4369 Prefix arg (non-nil third arg JUSTIFY, if called from program)
 4370 means justify as well.  Fourth arg WHAT is a word to be displayed when
 4371 formatting."
 4372   (interactive "*r\nP")
 4373   (save-excursion
 4374     (let ((to (set-marker (make-marker) to))
 4375       (next-par (make-marker)))
 4376       (goto-char from)
 4377       (beginning-of-line)
 4378       (setq from (point))
 4379       (catch 'end-of-buffer
 4380     (while (and (< (point) to))
 4381       (message "Formatting%s...%d%%"
 4382            (or what "")
 4383            (/ (* 100 (- (point) from)) (- to from)))
 4384       (save-excursion (LaTeX-fill-paragraph justify))
 4385       (if (marker-position next-par)
 4386           (goto-char (marker-position next-par))
 4387         (LaTeX-forward-paragraph))
 4388       (when (eobp) (throw 'end-of-buffer t))
 4389       (LaTeX-forward-paragraph)
 4390       (set-marker next-par (point))
 4391       (LaTeX-backward-paragraph)
 4392       (while (and (not (eobp))
 4393               (looking-at
 4394                (concat "^\\($\\|[ \t]+$\\|[ \t]*"
 4395                    TeX-comment-start-regexp "+[ \t]*$\\)")))
 4396         (forward-line 1))))
 4397       (set-marker to nil)))
 4398   (message "Formatting%s...done" (or what "")))
 4399 
 4400 (defun LaTeX-find-matching-end ()
 4401   "Move point to the \\end of the current environment.
 4402 
 4403 If function is called inside a comment and
 4404 `LaTeX-syntactic-comments' is enabled, try to find the
 4405 environment in commented regions with the same comment prefix."
 4406   (interactive)
 4407   (let* ((regexp (concat (regexp-quote TeX-esc) "\\(begin\\|end\\)\\b"))
 4408      (level 1)
 4409      (in-comment (TeX-in-commented-line))
 4410      (comment-prefix (and in-comment (TeX-comment-prefix)))
 4411      (case-fold-search nil))
 4412     (let ((pt (point)))
 4413       (skip-chars-backward (concat "a-zA-Z \t" (regexp-quote TeX-grop)))
 4414       (unless (bolp)
 4415     (backward-char 1)
 4416     (if (and (looking-at regexp)
 4417          (char-equal (char-after (1+ (match-beginning 0))) ?e))
 4418         (setq level 0)
 4419       (goto-char pt))))
 4420     (while (and (> level 0) (re-search-forward regexp nil t))
 4421       (when (or (and LaTeX-syntactic-comments
 4422              (eq in-comment (TeX-in-commented-line))
 4423              ;; If we are in a commented line, check if the
 4424              ;; prefix matches the one we started out with.
 4425              (or (not in-comment)
 4426              (string= comment-prefix (TeX-comment-prefix))))
 4427         (and (not LaTeX-syntactic-comments)
 4428              (not (TeX-in-commented-line))))
 4429     (if (= (char-after (1+ (match-beginning 0))) ?b) ;;begin
 4430         (setq level (1+ level))
 4431       (setq level (1- level)))))
 4432     (if (= level 0)
 4433     (re-search-forward
 4434      (concat TeX-grop (LaTeX-environment-name-regexp) TeX-grcl))
 4435       (error "Can't locate end of current environment"))))
 4436 
 4437 (defun LaTeX-find-matching-begin ()
 4438   "Move point to the \\begin of the current environment.
 4439 
 4440 If function is called inside a comment and
 4441 `LaTeX-syntactic-comments' is enabled, try to find the
 4442 environment in commented regions with the same comment prefix."
 4443   (interactive)
 4444   (let* ((regexp (concat (regexp-quote TeX-esc) "\\(begin\\|end\\)\\b"))
 4445      (level 1)
 4446      (in-comment (TeX-in-commented-line))
 4447      (comment-prefix (and in-comment (TeX-comment-prefix)))
 4448      (case-fold-search nil))
 4449     (skip-chars-backward (concat "a-zA-Z \t" (regexp-quote TeX-grop)))
 4450     (unless (bolp)
 4451       (backward-char 1)
 4452       (and (looking-at regexp)
 4453        (char-equal (char-after (1+ (match-beginning 0))) ?b)
 4454        (setq level 0)))
 4455     (while (and (> level 0) (re-search-backward regexp nil t))
 4456       (when (or (and LaTeX-syntactic-comments
 4457              (eq in-comment (TeX-in-commented-line))
 4458              ;; If we are in a commented line, check if the
 4459              ;; prefix matches the one we started out with.
 4460              (or (not in-comment)
 4461              (string= comment-prefix (TeX-comment-prefix))))
 4462         (and (not LaTeX-syntactic-comments)
 4463              (not (TeX-in-commented-line))))
 4464     (if (= (char-after (1+ (match-beginning 0))) ?e) ;;end
 4465         (setq level (1+ level))
 4466       (setq level (1- level)))))
 4467     (or (= level 0)
 4468     (error "Can't locate beginning of current environment"))))
 4469 
 4470 (defun LaTeX-mark-environment (&optional count)
 4471   "Set mark to end of current environment and point to the matching begin.
 4472 If prefix argument COUNT is given, mark the respective number of
 4473 enclosing environments.  The command will not work properly if
 4474 there are unbalanced begin-end pairs in comments and verbatim
 4475 environments."
 4476   (interactive "p")
 4477   (setq count (if count (abs count) 1))
 4478   (let ((cur (point)) beg end)
 4479     ;; Only change point and mark after beginning and end were found.
 4480     ;; Point should not end up in the middle of nowhere if the search fails.
 4481     (save-excursion
 4482       (dotimes (c count) (LaTeX-find-matching-end))
 4483       (setq end (line-beginning-position 2))
 4484       (goto-char cur)
 4485       (dotimes (c count) (LaTeX-find-matching-begin))
 4486       (setq beg (point)))
 4487     (push-mark end)
 4488     (goto-char beg)
 4489     (TeX-activate-region)))
 4490 
 4491 (defun LaTeX-fill-environment (justify)
 4492   "Fill and indent current environment as LaTeX text."
 4493   (interactive "*P")
 4494   (save-excursion
 4495     (LaTeX-mark-environment)
 4496     (re-search-forward "{\\([^}]+\\)}")
 4497     (LaTeX-fill-region (region-beginning) (region-end) justify
 4498                (concat " environment " (TeX-match-buffer 1)))))
 4499 
 4500 (defun LaTeX-fill-section (justify)
 4501   "Fill and indent current logical section as LaTeX text."
 4502   (interactive "*P")
 4503   (save-excursion
 4504     (LaTeX-mark-section)
 4505     (re-search-forward "{\\([^}]+\\)}")
 4506     (LaTeX-fill-region (region-beginning) (region-end) justify
 4507                (concat " section " (TeX-match-buffer 1)))))
 4508 
 4509 (defun LaTeX-mark-section (&optional no-subsections)
 4510   "Set mark at end of current logical section, and point at top.
 4511 If optional argument NO-SUBSECTIONS is non-nil, mark only the
 4512 region from the current section start to the next sectioning
 4513 command.  Thereby subsections are not being marked.
 4514 
 4515 If the function `outline-mark-subtree' is not available,
 4516 `LaTeX-mark-section' always behaves like this regardless of the
 4517 value of NO-SUBSECTIONS."
 4518   (interactive "P")
 4519   (if (or no-subsections
 4520       (not (fboundp 'outline-mark-subtree)))
 4521       (progn
 4522     (re-search-forward (concat  "\\(" (LaTeX-outline-regexp)
 4523                     "\\|\\'\\)"))
 4524     (beginning-of-line)
 4525     (push-mark (point) nil t)
 4526     (re-search-backward (concat "\\(" (LaTeX-outline-regexp)
 4527                     "\\|\\`\\)")))
 4528     (outline-mark-subtree)
 4529     (when (and (boundp 'transient-mark-mode)
 4530            transient-mark-mode
 4531            (boundp 'mark-active)
 4532            (not mark-active))
 4533       (setq mark-active t)
 4534       (run-hooks 'activate-mark-hook)))
 4535   (TeX-activate-region))
 4536 
 4537 (defun LaTeX-fill-buffer (justify)
 4538   "Fill and indent current buffer as LaTeX text."
 4539   (interactive "*P")
 4540   (save-excursion
 4541     (LaTeX-fill-region
 4542      (point-min)
 4543      (point-max)
 4544      justify
 4545      (concat " buffer " (buffer-name)))))
 4546 
 4547 
 4548 ;;; Navigation
 4549 
 4550 (defvar LaTeX-paragraph-commands-internal
 4551   '("[" "]" ; display math
 4552     "appendix" "begin" "caption" "chapter" "end" "include" "includeonly"
 4553     "label" "maketitle" "newblock" "noindent" "par" "paragraph" "part"
 4554     "section" "subsection" "subsubsection" "tableofcontents"
 4555     "newpage" "clearpage")
 4556   "Internal list of LaTeX macros that should have their own line.")
 4557 
 4558 (defun LaTeX-paragraph-commands-regexp-make ()
 4559   "Return a regular expression matching defined paragraph commands.
 4560 Regexp part containing TeX control words is postfixed with `\\b'
 4561 to avoid ambiguities (e.g. \\par vs. \\parencite)."
 4562   (let (cmds symbs)
 4563     (dolist (mac (append LaTeX-paragraph-commands
 4564              LaTeX-paragraph-commands-internal))
 4565       (if (string-match "[^a-zA-Z]" mac)
 4566       (push mac symbs)
 4567     (push mac cmds)))
 4568     (concat (regexp-quote TeX-esc) "\\(?:"
 4569         (regexp-opt cmds "\\(?:")
 4570         "\\b"
 4571         "\\|"
 4572         (regexp-opt symbs)
 4573         "\\)")))
 4574 
 4575 (defcustom LaTeX-paragraph-commands nil
 4576   "List of LaTeX macros that should have their own line.
 4577 The list should contain macro names without the leading backslash."
 4578   :group 'LaTeX-macro
 4579   :type '(repeat (string))
 4580   :set (lambda (symbol value)
 4581          (set-default symbol value)
 4582      (setq LaTeX-paragraph-commands-regexp
 4583            (LaTeX-paragraph-commands-regexp-make))))
 4584 
 4585 (defvar LaTeX-paragraph-commands-regexp (LaTeX-paragraph-commands-regexp-make)
 4586     "Regular expression matching LaTeX macros that should have their own line.")
 4587 
 4588 (defun LaTeX-set-paragraph-start ()
 4589   "Set `paragraph-start'."
 4590   (setq paragraph-start
 4591     (concat
 4592      "[ \t]*%*[ \t]*\\("
 4593      LaTeX-paragraph-commands-regexp "\\|"
 4594      (regexp-quote TeX-esc) "\\(" LaTeX-item-regexp "\\)\\|"
 4595      "\\$\\$\\|" ; Plain TeX display math (Some people actually
 4596              ; use this with LaTeX.  Yuck.)
 4597      "$\\)")))
 4598 
 4599 (defun LaTeX-paragraph-commands-add-locally (commands)
 4600   "Make COMMANDS be recognized as paragraph commands.
 4601 COMMANDS can be a single string or a list of strings which will
 4602 be added to `LaTeX-paragraph-commands-internal'.  Additionally
 4603 `LaTeX-paragraph-commands-regexp' will be updated and both
 4604 variables will be made buffer-local.  This is mainly a
 4605 convenience function which can be used in style files."
 4606   (make-local-variable 'LaTeX-paragraph-commands-internal)
 4607   (make-local-variable 'LaTeX-paragraph-commands-regexp)
 4608   (unless (listp commands) (setq commands (list commands)))
 4609   (dolist (elt commands)
 4610     (add-to-list 'LaTeX-paragraph-commands-internal elt))
 4611   (setq LaTeX-paragraph-commands-regexp (LaTeX-paragraph-commands-regexp-make))
 4612   (LaTeX-set-paragraph-start))
 4613 
 4614 (defun LaTeX-forward-paragraph (&optional count)
 4615   "Move forward to end of paragraph.
 4616 If COUNT is non-nil, do it COUNT times."
 4617   (or count (setq count 1))
 4618   (dotimes (i count)
 4619     (let* ((macro-start (TeX-find-macro-start))
 4620        (paragraph-command-start
 4621         (cond
 4622          ;; Point is inside of a paragraph command.
 4623          ((and macro-start
 4624            (save-excursion
 4625              (goto-char macro-start)
 4626              (looking-at LaTeX-paragraph-commands-regexp)))
 4627           (match-beginning 0))
 4628          ;; Point is before a paragraph command in the same line.
 4629          ((looking-at
 4630            (concat "[ \t]*\\(?:" TeX-comment-start-regexp
 4631                "\\(?:" TeX-comment-start-regexp "\\|[ \t]\\)*\\)?"
 4632                "\\(" LaTeX-paragraph-commands-regexp "\\)"))
 4633           (match-beginning 1))))
 4634        macro-end)
 4635       ;; If a paragraph command is encountered there are two cases to be
 4636       ;; distinguished:
 4637       ;; 1) If the end of the paragraph command coincides (apart from
 4638       ;;    potential whitespace) with the end of the line, is only
 4639       ;;    followed by a comment or is directly followed by a macro,
 4640       ;;    it is assumed that it should be handled separately.
 4641       ;; 2) If the end of the paragraph command is followed by other
 4642       ;;    code, it is assumed that it should be included with the rest
 4643       ;;    of the paragraph.
 4644       (if (and paragraph-command-start
 4645            (save-excursion
 4646          (goto-char paragraph-command-start)
 4647          (setq macro-end (goto-char (TeX-find-macro-end)))
 4648          (looking-at (concat (regexp-quote TeX-esc) "[@A-Za-z]+\\|"
 4649                      "[ \t]*\\($\\|"
 4650                      TeX-comment-start-regexp "\\)"))))
 4651       (progn
 4652         (goto-char macro-end)
 4653         ;; If the paragraph command is followed directly by
 4654         ;; another macro, regard the latter as part of the
 4655         ;; paragraph command's paragraph.
 4656         (when (looking-at (concat (regexp-quote TeX-esc) "[@A-Za-z]+"))
 4657           (goto-char (TeX-find-macro-end)))
 4658         (forward-line))
 4659     (let (limit)
 4660       (goto-char (min (save-excursion
 4661                 (forward-paragraph)
 4662                 (setq limit (point)))
 4663               (save-excursion
 4664                 (TeX-forward-comment-skip 1 limit)
 4665                 (point)))))))))
 4666 
 4667 (defun LaTeX-backward-paragraph (&optional count)
 4668   "Move backward to beginning of paragraph.
 4669 If COUNT is non-nil, do it COUNT times."
 4670   (or count (setq count 1))
 4671   (dotimes (i count)
 4672     (let* ((macro-start (TeX-find-macro-start)))
 4673       (if (and macro-start
 4674            ;; Point really has to be inside of the macro, not before it.
 4675            (not (= macro-start (point)))
 4676            (save-excursion
 4677          (goto-char macro-start)
 4678          (looking-at LaTeX-paragraph-commands-regexp)))
 4679       ;; Point is inside of a paragraph command.
 4680       (progn
 4681         (goto-char macro-start)
 4682         (beginning-of-line))
 4683     (let (limit
 4684           (start (line-beginning-position)))
 4685       (goto-char
 4686        (max (save-excursion
 4687           (backward-paragraph)
 4688           (setq limit (point)))
 4689         ;; Search for possible transitions from commented to
 4690         ;; uncommented regions and vice versa.
 4691         (save-excursion
 4692           (TeX-backward-comment-skip 1 limit)
 4693           (point))
 4694         ;; Search for paragraph commands.
 4695         (save-excursion
 4696           (let ((end-point 0) macro-bol)
 4697             (when (setq macro-bol
 4698                 (re-search-backward
 4699                  (format "^[ \t]*%s*[ \t]*\\(%s\\)"
 4700                      TeX-comment-start-regexp
 4701                      LaTeX-paragraph-commands-regexp)
 4702                  limit t))
 4703               (if (and (string= (match-string 1) "\\begin")
 4704                    (progn
 4705                  (goto-char (match-end 1))
 4706                  (skip-chars-forward "{ \t")
 4707                  (member (buffer-substring-no-properties
 4708                       (point) (progn (skip-chars-forward
 4709                               "A-Za-z*") (point)))
 4710                      LaTeX-verbatim-environments)))
 4711               ;; If inside a verbatim environment, just
 4712               ;; use the next line.  In such environments
 4713               ;; `TeX-find-macro-end' could otherwise
 4714               ;; think brackets or braces belong to the
 4715               ;; \begin macro.
 4716               (setq end-point (line-beginning-position 2))
 4717             ;; Jump to the macro end otherwise.
 4718             (goto-char (match-beginning 1))
 4719             (goto-char (TeX-find-macro-end))
 4720             ;; For an explanation of this distinction see
 4721             ;; `LaTeX-forward-paragraph'.
 4722             (if (looking-at (concat (regexp-quote TeX-esc)
 4723                         "[@A-Za-z]+\\|[ \t]*\\($\\|"
 4724                         TeX-comment-start-regexp "\\)"))
 4725                 (progn
 4726                   (when (looking-at (regexp-quote TeX-esc))
 4727                 (goto-char (TeX-find-macro-end)))
 4728                   (forward-line 1)
 4729                   (when (< (point) start)
 4730                 (setq end-point (point))))
 4731               (setq end-point macro-bol))))
 4732             end-point)))))))))
 4733 
 4734 (defun LaTeX-search-forward-comment-start (&optional limit)
 4735   "Search forward for a comment start from current position till LIMIT.
 4736 If LIMIT is omitted, search till the end of the buffer.
 4737 
 4738 This function makes sure that any comment starters found inside
 4739 of verbatim constructs are not considered."
 4740   (setq limit (or limit (point-max)))
 4741   (save-excursion
 4742     (let (start)
 4743       (catch 'found
 4744     (while (progn
 4745          (when (and (TeX-re-search-forward-unescaped
 4746                  TeX-comment-start-regexp limit 'move)
 4747                 (not (LaTeX-verbatim-p)))
 4748            (setq start (match-beginning 0))
 4749            (throw 'found t))
 4750          (< (point) limit))))
 4751       start)))
 4752 
 4753 
 4754 ;;; Math Minor Mode
 4755 
 4756 (defgroup LaTeX-math nil
 4757   "Mathematics in AUCTeX."
 4758   :group 'LaTeX-macro)
 4759 
 4760 (defvar LaTeX-math-keymap (make-sparse-keymap)
 4761   "Keymap used for `LaTeX-math-mode' commands.")
 4762 
 4763 (defun LaTeX-math-abbrev-prefix ()
 4764   "Make a key definition from the variable `LaTeX-math-abbrev-prefix'."
 4765   (if (stringp LaTeX-math-abbrev-prefix)
 4766       (read-kbd-macro LaTeX-math-abbrev-prefix)
 4767     LaTeX-math-abbrev-prefix))
 4768 
 4769 (defvar LaTeX-math-menu
 4770   '("Math"
 4771     ("Greek Uppercase") ("Greek Lowercase") ("Binary Op") ("Relational")
 4772     ("Arrows") ("Punctuation") ("Misc Symbol") ("Var Symbol") ("Log-like")
 4773     ("Delimiters") ("Constructs") ("Accents") ("AMS"))
 4774   "Menu containing LaTeX math commands.
 4775 The menu entries will be generated dynamically, but you can specify
 4776 the sequence by initializing this variable.")
 4777 
 4778 (defcustom LaTeX-math-menu-unicode
 4779   (or (string-match "\\<GTK\\>" (emacs-version))
 4780       (eq window-system 'w32))
 4781   "Whether the LaTeX menu should try using Unicode for effect."
 4782   :type 'boolean
 4783   :group 'LaTeX-math)
 4784 
 4785 (defcustom LaTeX-math-abbrev-prefix "`"
 4786   "Prefix key for use in `LaTeX-math-mode'.
 4787 This has to be a string representing a key sequence in a format
 4788 understood by the `kbd' macro.  This corresponds to the syntax
 4789 usually used in the Emacs and Elisp manuals.
 4790 
 4791 Setting this variable directly does not take effect;
 4792 use \\[customize]."
 4793   :group 'LaTeX-math
 4794   :initialize 'custom-initialize-default
 4795   :set '(lambda (symbol value)
 4796       (define-key LaTeX-math-mode-map (LaTeX-math-abbrev-prefix) t)
 4797       (set-default symbol value)
 4798       (define-key LaTeX-math-mode-map
 4799         (LaTeX-math-abbrev-prefix) LaTeX-math-keymap))
 4800   :type '(string :tag "Key sequence"))
 4801 
 4802 (defun LaTeX-math-initialize ()
 4803   (let ((math (reverse (append LaTeX-math-list LaTeX-math-default)))
 4804     (map LaTeX-math-keymap)
 4805     (unicode (and LaTeX-math-menu-unicode (fboundp 'decode-char))))
 4806     (while math
 4807       (let* ((entry (car math))
 4808          (key (nth 0 entry))
 4809          (prefix
 4810           (and unicode
 4811            (nth 3 entry)))
 4812          value menu name)
 4813     (setq math (cdr math))
 4814     (if (and prefix
 4815          (setq prefix (decode-char 'ucs (nth 3 entry))))
 4816         (setq prefix (concat (string prefix) " \\"))
 4817       (setq prefix "\\"))
 4818     (if (listp (cdr entry))
 4819         (setq value (nth 1 entry)
 4820           menu (nth 2 entry))
 4821       (setq value (cdr entry)
 4822         menu nil))
 4823     (if (stringp value)
 4824         (progn
 4825           (setq name (intern (concat "LaTeX-math-" value)))
 4826           (fset name (list 'lambda (list 'arg) (list 'interactive "*P")
 4827                    (list 'LaTeX-math-insert value 'arg))))
 4828       (setq name value))
 4829     (if key
 4830         (progn
 4831           (setq key (cond ((numberp key) (char-to-string key))
 4832                   ((stringp key) (read-kbd-macro key))
 4833                   (t (vector key))))
 4834           (define-key map key name)))
 4835     (if menu
 4836         (let ((parent LaTeX-math-menu))
 4837           (if (listp menu)
 4838           (progn
 4839             (while (cdr menu)
 4840               (let ((sub (assoc (car menu) LaTeX-math-menu)))
 4841             (if sub
 4842                 (setq parent sub)
 4843               (setcdr parent (cons (list (car menu)) (cdr parent))))
 4844             (setq menu (cdr menu))))
 4845             (setq menu (car menu))))
 4846           (let ((sub (assoc menu parent)))
 4847         (if sub
 4848             (if (stringp value)
 4849             (setcdr sub (cons (vector (concat prefix value)
 4850                           name t)
 4851                       (cdr sub)))
 4852               (error "Cannot have multiple special math menu items"))
 4853           (setcdr parent
 4854               (cons (if (stringp value)
 4855                     (list menu (vector (concat prefix value)
 4856                                name t))
 4857                   (vector menu name t))
 4858                 (cdr parent)))))))))
 4859     ;; Make the math prefix char available if it has not been used as a prefix.
 4860     (unless (lookup-key map (LaTeX-math-abbrev-prefix))
 4861       (define-key map (LaTeX-math-abbrev-prefix) 'self-insert-command))))
 4862 
 4863 (defconst LaTeX-dialect :latex
 4864   "Default dialect for use with function `TeX-add-style-hook' for
 4865 argument DIALECT-EXPR when the hook is to be run only on LaTeX
 4866 file, or any mode derived thereof. See variable
 4867 `TeX-style-hook-dialect'." )
 4868 
 4869 (defconst LaTeX-math-default
 4870   '((?a "alpha" "Greek Lowercase" 945) ;; #X03B1
 4871     (?b "beta" "Greek Lowercase" 946) ;; #X03B2
 4872     (?g "gamma" "Greek Lowercase" 947) ;; #X03B3
 4873     (?d "delta" "Greek Lowercase" 948) ;; #X03B4
 4874     (?e "epsilon" "Greek Lowercase" 1013) ;; #X03F5
 4875     (?z "zeta" "Greek Lowercase" 950) ;; #X03B6
 4876     (?h "eta" "Greek Lowercase" 951) ;; #X03B7
 4877     (?j "theta" "Greek Lowercase" 952) ;; #X03B8
 4878     (nil "iota" "Greek Lowercase" 953) ;; #X03B9
 4879     (?k "kappa" "Greek Lowercase" 954) ;; #X03BA
 4880     (?l "lambda" "Greek Lowercase" 955) ;; #X03BB
 4881     (?m "mu" "Greek Lowercase" 956) ;; #X03BC
 4882     (?n "nu" "Greek Lowercase" 957) ;; #X03BD
 4883     (?x "xi" "Greek Lowercase" 958) ;; #X03BE
 4884     (?p "pi" "Greek Lowercase" 960) ;; #X03C0
 4885     (?r "rho" "Greek Lowercase" 961) ;; #X03C1
 4886     (?s "sigma" "Greek Lowercase" 963) ;; #X03C3
 4887     (?t "tau" "Greek Lowercase" 964) ;; #X03C4
 4888     (?u "upsilon" "Greek Lowercase" 965) ;; #X03C5
 4889     (?f "phi" "Greek Lowercase" 981) ;; #X03D5
 4890     (?q "chi" "Greek Lowercase" 967) ;; #X03C7
 4891     (?y "psi" "Greek Lowercase" 968) ;; #X03C8
 4892     (?w "omega" "Greek Lowercase" 969) ;; #X03C9
 4893     ("v e" "varepsilon" "Greek Lowercase" 949) ;; #X03B5
 4894     ("v j" "vartheta" "Greek Lowercase" 977) ;; #X03D1
 4895     ("v p" "varpi" "Greek Lowercase" 982) ;; #X03D6
 4896     ("v r" "varrho" "Greek Lowercase" 1009) ;; #X03F1
 4897     ("v s" "varsigma" "Greek Lowercase" 962) ;; #X03C2
 4898     ("v f" "varphi" "Greek Lowercase" 966) ;; #X03C6
 4899     (?G "Gamma" "Greek Uppercase" 915) ;; #X0393
 4900     (?D "Delta" "Greek Uppercase" 916) ;; #X0394
 4901     (?J "Theta" "Greek Uppercase" 920) ;; #X0398
 4902     (?L "Lambda" "Greek Uppercase" 923) ;; #X039B
 4903     (?X "Xi" "Greek Uppercase" 926) ;; #X039E
 4904     (?P "Pi" "Greek Uppercase" 928) ;; #X03A0
 4905     (?S "Sigma" "Greek Uppercase" 931) ;; #X03A3
 4906     (?U "Upsilon" "Greek Uppercase" 978) ;; #X03D2
 4907     (?F "Phi" "Greek Uppercase" 934) ;; #X03A6
 4908     (?Y "Psi" "Greek Uppercase" 936) ;; #X03A8
 4909     (?W "Omega" "Greek Uppercase" 937) ;; #X03A9
 4910     (?c LaTeX-math-cal "Cal-whatever")
 4911     (nil "pm" "Binary Op" 177) ;; #X00B1
 4912     (nil "mp" "Binary Op" 8723) ;; #X2213
 4913     (?* "times" "Binary Op" 215) ;; #X00D7
 4914     (nil "div" "Binary Op" 247) ;; #X00F7
 4915     (nil "ast" "Binary Op" 8727) ;; #X2217
 4916     (nil "star" "Binary Op" 8902) ;; #X22C6
 4917     (nil "circ" "Binary Op" 8728) ;; #X2218
 4918     (nil "bullet" "Binary Op" 8729) ;; #X2219
 4919     (?. "cdot" "Binary Op" 8901) ;; #X22C5
 4920     (?- "cap" "Binary Op" 8745) ;; #X2229
 4921     (?+ "cup" "Binary Op" 8746) ;; #X222A
 4922     (nil "uplus" "Binary Op" 8846) ;; #X228E
 4923     (nil "sqcap" "Binary Op" 8851) ;; #X2293
 4924     (?| "vee" "Binary Op" 8744) ;; #X2228
 4925     (?& "wedge" "Binary Op" 8743) ;; #X2227
 4926     (?\\ "setminus" "Binary Op" 8726) ;; #X2216
 4927     (nil "wr" "Binary Op" 8768) ;; #X2240
 4928     (nil "diamond" "Binary Op" 8900) ;; #X22C4
 4929     (nil "bigtriangleup" "Binary Op" 9651) ;; #X25B3
 4930     (nil "bigtriangledown" "Binary Op" 9661) ;; #X25BD
 4931     (nil "triangleleft" "Binary Op" 9665) ;; #X25C1
 4932     (nil "triangleright" "Binary Op" 9655) ;; #X25B7
 4933     (nil "lhd" "Binary Op" 8882) ;; #X22B2
 4934     (nil "rhd" "Binary Op" 8883) ;; #X22B3
 4935     (nil "unlhd" "Binary Op" 8884) ;; #X22B4
 4936     (nil "unrhd" "Binary Op" 8885) ;; #X22B5
 4937     (nil "oplus" "Binary Op" 8853) ;; #X2295
 4938     (nil "ominus" "Binary Op" 8854) ;; #X2296
 4939     (nil "otimes" "Binary Op" 8855) ;; #X2297
 4940     (nil "oslash" "Binary Op" 8709) ;; #X2205
 4941     (nil "odot" "Binary Op" 8857) ;; #X2299
 4942     (nil "bigcirc" "Binary Op" 9675) ;; #X25CB
 4943     (nil "dagger" "Binary Op" 8224) ;; #X2020
 4944     (nil "ddagger" "Binary Op" 8225) ;; #X2021
 4945     (nil "amalg" "Binary Op" 10815) ;; #X2A3F
 4946     (?< "leq" "Relational" 8804) ;; #X2264
 4947     (?> "geq" "Relational" 8805) ;; #X2265
 4948     (nil "qed" "Relational" 8718) ;; #X220E
 4949     (nil "equiv" "Relational" 8801) ;; #X2261
 4950     (nil "models" "Relational" 8871) ;; #X22A7
 4951     (nil "prec" "Relational" 8826) ;; #X227A
 4952     (nil "succ" "Relational" 8827) ;; #X227B
 4953     (nil "sim" "Relational" 8764) ;; #X223C
 4954     (nil "perp" "Relational" 10178) ;; #X27C2
 4955     (nil "preceq" "Relational" 10927) ;; #X2AAF
 4956     (nil "succeq" "Relational" 10928) ;; #X2AB0
 4957     (nil "simeq" "Relational" 8771) ;; #X2243
 4958     (nil "mid" "Relational" 8739) ;; #X2223
 4959     (nil "ll" "Relational" 8810) ;; #X226A
 4960     (nil "gg" "Relational" 8811) ;; #X226B
 4961     (nil "asymp" "Relational" 8781) ;; #X224D
 4962     (nil "parallel" "Relational" 8741) ;; #X2225
 4963     (?\{ "subset" "Relational" 8834) ;; #X2282
 4964     (?\} "supset" "Relational" 8835) ;; #X2283
 4965     (nil "approx" "Relational" 8776) ;; #X2248
 4966     (nil "bowtie" "Relational" 8904) ;; #X22C8
 4967     (?\[ "subseteq" "Relational" 8838) ;; #X2286
 4968     (?\] "supseteq" "Relational" 8839) ;; #X2287
 4969     (nil "cong" "Relational" 8773) ;; #X2245
 4970     (nil "Join" "Relational" 10781) ;; #X2A1D
 4971     (nil "sqsubset" "Relational" 8847) ;; #X228F
 4972     (nil "sqsupset" "Relational" 8848) ;; #X2290
 4973     (nil "neq" "Relational" 8800) ;; #X2260
 4974     (nil "smile" "Relational" 8995) ;; #X2323
 4975     (nil "sqsubseteq" "Relational" 8849) ;; #X2291
 4976     (nil "sqsupseteq" "Relational" 8850) ;; #X2292
 4977     (nil "doteq" "Relational" 8784) ;; #X2250
 4978     (nil "frown" "Relational" 8994) ;; #X2322
 4979     (?i "in" "Relational" 8712) ;; #X2208
 4980     (nil "ni" "Relational" 8715) ;; #X220B
 4981     (nil "propto" "Relational" 8733) ;; #X221D
 4982     (nil "vdash" "Relational" 8866) ;; #X22A2
 4983     (nil "dashv" "Relational" 8867) ;; #X22A3
 4984     (?\C-b "leftarrow" "Arrows" 8592) ;; #X2190
 4985     (nil "Leftarrow" "Arrows" 8656) ;; #X21D0
 4986     (?\C-f "rightarrow" "Arrows" 8594) ;; #X2192
 4987     (nil "Rightarrow" "Arrows" 8658) ;; #X21D2
 4988     (nil "leftrightarrow" "Arrows" 8596) ;; #X2194
 4989     (nil "Leftrightarrow" "Arrows" 8660) ;; #X21D4
 4990     (nil "mapsto" "Arrows" 8614) ;; #X21A6
 4991     (nil "hookleftarrow" "Arrows" 8617) ;; #X21A9
 4992     (nil "leftharpoonup" "Arrows" 8636) ;; #X21BC
 4993     (nil "leftharpoondown" "Arrows" 8637) ;; #X21BD
 4994     (nil "longleftarrow" "Arrows" 10229) ;; #X27F5
 4995     (nil "Longleftarrow" "Arrows" 10232) ;; #X27F8
 4996     (nil "longrightarrow" "Arrows" 10230) ;; #X27F6
 4997     (nil "Longrightarrow" "Arrows" 10233) ;; #X27F9
 4998     (nil "longleftrightarrow" "Arrows" 10231) ;; #X27F7
 4999     (nil "Longleftrightarrow" "Arrows" 10234) ;; #X27FA
 5000     (nil "iff" "Arrows" 10234) ;; #X27FA
 5001     (nil "longmapsto" "Arrows" 10236) ;; #X27FC
 5002     (nil "hookrightarrow" "Arrows" 8618) ;; #X21AA
 5003     (nil "rightharpoonup" "Arrows" 8640) ;; #X21C0
 5004     (nil "rightharpoondown" "Arrows" 8641) ;; #X21C1
 5005     (?\C-p "uparrow" "Arrows" 8593) ;; #X2191
 5006     (nil "Uparrow" "Arrows" 8657) ;; #X21D1
 5007     (?\C-n "downarrow" "Arrows" 8595) ;; #X2193
 5008     (nil "Downarrow" "Arrows" 8659) ;; #X21D3
 5009     (nil "updownarrow" "Arrows" 8597) ;; #X2195
 5010     (nil "Updownarrow" "Arrows" 8661) ;; #X21D5
 5011     (nil "nearrow" "Arrows" 8599) ;; #X2197
 5012     (nil "searrow" "Arrows" 8600) ;; #X2198
 5013     (nil "swarrow" "Arrows" 8601) ;; #X2199
 5014     (nil "nwarrow" "Arrows" 8598) ;; #X2196
 5015     (nil "ldots" "Punctuation" 8230) ;; #X2026
 5016     (nil "cdots" "Punctuation" 8943) ;; #X22EF
 5017     (nil "vdots" "Punctuation" 8942) ;; #X22EE
 5018     (nil "ddots" "Punctuation" 8945) ;; #X22F1
 5019     (?: "colon" "Punctuation" 58) ;; #X003A
 5020     (?N "nabla" "Misc Symbol" 8711) ;; #X2207
 5021     (nil "aleph" "Misc Symbol" 8501) ;; #X2135
 5022     (nil "prime" "Misc Symbol" 8242) ;; #X2032
 5023     (?A "forall" "Misc Symbol" 8704) ;; #X2200
 5024     (?I "infty" "Misc Symbol" 8734) ;; #X221E
 5025     (nil "hbar" "Misc Symbol" 8463) ;; #X210F
 5026     (?0 "emptyset" "Misc Symbol" 8709) ;; #X2205
 5027     (?E "exists" "Misc Symbol" 8707) ;; #X2203
 5028     (nil "surd" "Misc Symbol" 8730) ;; #X221A
 5029     (nil "Box" "Misc Symbol" 9633) ;; #X25A1
 5030     (nil "triangle" "Misc Symbol" 9651) ;; #X25B3
 5031     (nil "Diamond" "Misc Symbol" 9671) ;; #X25C7
 5032     (nil "imath" "Misc Symbol" 120484) ;; #X1D6A4
 5033     (nil "jmath" "Misc Symbol" 120485) ;; #X1D6A5
 5034     (nil "ell" "Misc Symbol" 8467) ;; #X2113
 5035     (nil "neg" "Misc Symbol" 172) ;; #X00AC
 5036     (?/ "not" "Misc Symbol" 824) ;; #X0338
 5037     (nil "top" "Misc Symbol" 8868) ;; #X22A4
 5038     (nil "flat" "Misc Symbol" 9837) ;; #X266D
 5039     (nil "natural" "Misc Symbol" 9838) ;; #X266E
 5040     (nil "sharp" "Misc Symbol" 9839) ;; #X266F
 5041     (nil "wp" "Misc Symbol" 8472) ;; #X2118
 5042     (nil "bot" "Misc Symbol" 8869) ;; #X22A5
 5043     (nil "clubsuit" "Misc Symbol" 9827) ;; #X2663
 5044     (nil "diamondsuit" "Misc Symbol" 9826) ;; #X2662
 5045     (nil "heartsuit" "Misc Symbol" 9825) ;; #X2661
 5046     (nil "spadesuit" "Misc Symbol" 9824) ;; #X2660
 5047     (nil "mho" "Misc Symbol" 8487) ;; #X2127
 5048     (nil "Re" "Misc Symbol" 8476) ;; #X211C
 5049     (nil "Im" "Misc Symbol" 8465) ;; #X2111
 5050     (nil "angle" "Misc Symbol" 8736) ;; #X2220
 5051     (nil "partial" "Misc Symbol" 8706) ;; #X2202
 5052     (nil "sum" "Var Symbol" 8721) ;; #X2211
 5053     (nil "prod" "Var Symbol" 8719) ;; #X220F
 5054     (nil "coprod" "Var Symbol" 8720) ;; #X2210
 5055     (nil "int" "Var Symbol" 8747) ;; #X222B
 5056     (nil "oint" "Var Symbol" 8750) ;; #X222E
 5057     (nil "bigcap" "Var Symbol" 8898) ;; #X22C2
 5058     (nil "bigcup" "Var Symbol" 8899) ;; #X22C3
 5059     (nil "bigsqcup" "Var Symbol" 10758) ;; #X2A06
 5060     (nil "bigvee" "Var Symbol" 8897) ;; #X22C1
 5061     (nil "bigwedge" "Var Symbol" 8896) ;; #X22C0
 5062     (nil "bigodot" "Var Symbol" 10752) ;; #X2A00
 5063     (nil "bigotimes" "Var Symbol" 10754) ;; #X2A02
 5064     (nil "bigoplus" "Var Symbol" 10753) ;; #X2A01
 5065     (nil "biguplus" "Var Symbol" 10756) ;; #X2A04
 5066     (nil "arccos" "Log-like")
 5067     (nil "arcsin" "Log-like")
 5068     (nil "arctan" "Log-like")
 5069     (nil "arg" "Log-like")
 5070     (?\C-c "cos" "Log-like")
 5071     (nil "cosh" "Log-like")
 5072     (nil "cot" "Log-like")
 5073     (nil "coth" "Log-like")
 5074     (nil "csc" "Log-like")
 5075     (nil "deg" "Log-like")
 5076     (?\C-d "det" "Log-like")
 5077     (nil "dim" "Log-like")
 5078     (?\C-e "exp" "Log-like")
 5079     (nil "gcd" "Log-like")
 5080     (nil "hom" "Log-like")
 5081     (?\C-_ "inf" "Log-like")
 5082     (nil "ker" "Log-like")
 5083     (nil "lg" "Log-like")
 5084     (?\C-l "lim" "Log-like")
 5085     (nil "liminf" "Log-like")
 5086     (nil "limsup" "Log-like")
 5087     (nil "ln" "Log-like")
 5088     (nil "log" "Log-like")
 5089     (nil "max" "Log-like")
 5090     (nil "min" "Log-like")
 5091     (nil "Pr" "Log-like")
 5092     (nil "sec" "Log-like")
 5093     (?\C-s "sin" "Log-like")
 5094     (nil "sinh" "Log-like")
 5095     (?\C-^ "sup" "Log-like")
 5096     (?\C-t "tan" "Log-like")
 5097     (nil "tanh" "Log-like")
 5098     (nil "{" "Delimiters" ?{)
 5099     (nil "}" "Delimiters" ?})
 5100     (nil "lfloor" "Delimiters" 8970) ;; #X230A
 5101     (nil "rfloor" "Delimiters" 8971) ;; #X230B
 5102     (nil "lceil" "Delimiters" 8968) ;; #X2308
 5103     (nil "rceil" "Delimiters" 8969) ;; #X2309
 5104     (?\( "langle" "Delimiters" 10216) ;; #X27E8
 5105     (?\) "rangle" "Delimiters" 10217) ;; #X27E9
 5106     (nil "rmoustache" "Delimiters" 9137) ;; #X23B1
 5107     (nil "lmoustache" "Delimiters" 9136) ;; #X23B0
 5108     (nil "rgroup" "Delimiters" 9133) ;; #X23AD
 5109     (nil "lgroup" "Delimiters" 9129) ;; #X23A9
 5110     (nil "backslash" "Delimiters" 92) ;; #X005C
 5111     (nil "|" "Delimiters" 8214) ;; #X2016)
 5112     (nil "arrowvert" "Delimiters")
 5113     (nil "Arrowvert" "Delimiters")
 5114     (nil "bracevert" "Delimiters")
 5115     (nil "widetilde" "Constructs" 771) ;; #X0303
 5116     (nil "widehat" "Constructs" 770) ;; #X0302
 5117     (nil "overleftarrow" "Constructs" 8406) ;; #X20D6
 5118     (nil "overrightarrow" "Constructs")
 5119     (nil "overline" "Constructs" 773) ;; #X0305
 5120     (nil "underline" "Constructs" 818) ;; #X0332
 5121     (nil "overbrace" "Constructs" 65079) ;; #XFE37
 5122     (nil "underbrace" "Constructs" 65080) ;; #XFE38
 5123     (nil "sqrt" "Constructs" 8730) ;; #X221A
 5124     (nil "frac" "Constructs")
 5125     (?^ "hat" "Accents" 770) ;; #X0302
 5126     (nil "acute" "Accents" 769) ;; #X0301
 5127     (nil "bar" "Accents" 772) ;; #X0304
 5128     (nil "dot" "Accents" 775) ;; #X0307
 5129     (nil "breve" "Accents" 774) ;; #X0306
 5130     (nil "check" "Accents" 780) ;; #X030C
 5131     (nil "grave" "Accents" 768) ;; #X0300
 5132     (nil "vec" "Accents" 8407) ;; #X20D7
 5133     (nil "ddot" "Accents" 776) ;; #X0308
 5134     (?~ "tilde" "Accents" 771) ;; #X0303
 5135     (nil "mathring" "Accents" 778) ;; #X030A
 5136     (nil "beth" ("AMS" "Hebrew") 8502) ;; #X2136
 5137     (nil "daleth" ("AMS" "Hebrew") 8504) ;; #X2138
 5138     (nil "gimel" ("AMS" "Hebrew") 8503) ;; #X2137
 5139     (nil "digamma" ("AMS" "Greek Lowercase") 989) ;; #X03DD
 5140     ("v k" "varkappa" ("AMS" "Greek Lowercase") 1008) ;; #X03F0
 5141     ("v G" "varGamma" ("AMS" "Greek Uppercase") 120548) ;; #X1D6E4
 5142     ("v D" "varDelta" ("AMS" "Greek Uppercase") 120549) ;; #X1D6E5
 5143     ("v J" "varTheta" ("AMS" "Greek Uppercase") 120553) ;; #X1D6E9
 5144     ("v L" "varLambda" ("AMS" "Greek Uppercase") 120556) ;; #X1D6EC
 5145     ("v X" "varXi" ("AMS" "Greek Uppercase") 120559) ;; #X1D6EF
 5146     ("v P" "varPi" ("AMS" "Greek Uppercase") 120561) ;; #X1D6F1
 5147     ("v S" "varSigma" ("AMS" "Greek Uppercase") 120564) ;; #X1D6F4
 5148     ("v U" "varUpsilon" ("AMS" "Greek Uppercase") 120566) ;; #X1D6F6
 5149     ("v F" "varPhi" ("AMS" "Greek Uppercase") 120567) ;; #X1D6F7
 5150     ("v Y" "varPsi" ("AMS" "Greek Uppercase") 120569) ;; #X1D6F9
 5151     ("v W" "varOmega" ("AMS" "Greek Uppercase") 120570) ;; #X1D6FA
 5152     (nil "dashrightarrow" ("AMS" "Arrows"))
 5153     (nil "dashleftarrow" ("AMS" "Arrows"))
 5154     (nil "impliedby" ("AMS" "Arrows") 10232) ;; #X27F8
 5155     (nil "implies" ("AMS" "Arrows") 10233) ;; #X27F9
 5156     (nil "leftleftarrows" ("AMS" "Arrows") 8647) ;; #X21C7
 5157     (nil "leftrightarrows" ("AMS" "Arrows") 8646) ;; #X21C6
 5158     (nil "Lleftarrow" ("AMS" "Arrows") 8666) ;; #X21DA
 5159     (nil "twoheadleftarrow" ("AMS" "Arrows") 8606) ;; #X219E
 5160     (nil "leftarrowtail" ("AMS" "Arrows") 8610) ;; #X21A2
 5161     (nil "looparrowleft" ("AMS" "Arrows") 8619) ;; #X21AB
 5162     (nil "leftrightharpoons" ("AMS" "Arrows") 8651) ;; #X21CB
 5163     (nil "curvearrowleft" ("AMS" "Arrows") 8630) ;; #X21B6
 5164     (nil "circlearrowleft" ("AMS" "Arrows") 8634) ;; #X21BA
 5165     (nil "Lsh" ("AMS" "Arrows") 8624) ;; #X21B0
 5166     (nil "upuparrows" ("AMS" "Arrows") 8648) ;; #X21C8
 5167     (nil "upharpoonleft" ("AMS" "Arrows") 8639) ;; #X21BF
 5168     (nil "downharpoonleft" ("AMS" "Arrows") 8643) ;; #X21C3
 5169     (nil "multimap" ("AMS" "Arrows") 8888) ;; #X22B8
 5170     (nil "leftrightsquigarrow" ("AMS" "Arrows") 8621) ;; #X21AD
 5171     (nil "looparrowright" ("AMS" "Arrows") 8620) ;; #X21AC
 5172     (nil "rightleftharpoons" ("AMS" "Arrows") 8652) ;; #X21CC
 5173     (nil "curvearrowright" ("AMS" "Arrows") 8631) ;; #X21B7
 5174     (nil "circlearrowright" ("AMS" "Arrows"))
 5175     (nil "Rsh" ("AMS" "Arrows") 8625) ;; #X21B1
 5176     (nil "downdownarrows" ("AMS" "Arrows") 8650) ;; #X21CA
 5177     (nil "upharpoonright" ("AMS" "Arrows") 8638) ;; #X21BE
 5178     (nil "downharpoonright" ("AMS" "Arrows") 8642) ;; #X21C2
 5179     (nil "rightsquigarrow" ("AMS" "Arrows") 8605) ;; #X219D
 5180     (nil "nleftarrow" ("AMS" "Neg Arrows") 8602) ;; #X219A
 5181     (nil "nrightarrow" ("AMS" "Neg Arrows") 8603) ;; #X219B
 5182     (nil "nLeftarrow" ("AMS" "Neg Arrows") 8653) ;; #X21CD
 5183     (nil "nRightarrow" ("AMS" "Neg Arrows") 8655) ;; #X21CF
 5184     (nil "nleftrightarrow" ("AMS" "Neg Arrows") 8622) ;; #X21AE
 5185     (nil "nLeftrightarrow" ("AMS" "Neg Arrows") 8654) ;; #X21CE
 5186     (nil "leqq" ("AMS" "Relational I") 8806) ;; #X2266
 5187     (nil "leqslant" ("AMS" "Relational I") 10877) ;; #X2A7D
 5188     (nil "eqslantless" ("AMS" "Relational I") 10901) ;; #X2A95
 5189     (nil "lesssim" ("AMS" "Relational I") 8818) ;; #X2272
 5190     (nil "lessapprox" ("AMS" "Relational I") 10885) ;; #X2A85
 5191     (nil "approxeq" ("AMS" "Relational I") 8778) ;; #X224A
 5192     (nil "lessdot" ("AMS" "Relational I") 8918) ;; #X22D6
 5193     (nil "lll" ("AMS" "Relational I") 8920) ;; #X22D8
 5194     (nil "lessgtr" ("AMS" "Relational I") 8822) ;; #X2276
 5195     (nil "lesseqgtr" ("AMS" "Relational I") 8922) ;; #X22DA
 5196     (nil "lesseqqgtr" ("AMS" "Relational I") 10891) ;; #X2A8B
 5197     (nil "doteqdot" ("AMS" "Relational I") 8785) ;; #X2251
 5198     (nil "risingdotseq" ("AMS" "Relational I") 8787) ;; #X2253
 5199     (nil "fallingdotseq" ("AMS" "Relational I") 8786) ;; #X2252
 5200     (nil "backsim" ("AMS" "Relational I") 8765) ;; #X223D
 5201     (nil "backsimeq" ("AMS" "Relational I") 8909) ;; #X22CD
 5202     (nil "subseteqq" ("AMS" "Relational I") 10949) ;; #X2AC5
 5203     (nil "Subset" ("AMS" "Relational I") 8912) ;; #X22D0
 5204     (nil "sqsubset" ("AMS" "Relational I") 8847) ;; #X228F
 5205     (nil "preccurlyeq" ("AMS" "Relational I") 8828) ;; #X227C
 5206     (nil "curlyeqprec" ("AMS" "Relational I") 8926) ;; #X22DE
 5207     (nil "precsim" ("AMS" "Relational I") 8830) ;; #X227E
 5208     (nil "precapprox" ("AMS" "Relational I") 10935) ;; #X2AB7
 5209     (nil "vartriangleleft" ("AMS" "Relational I") 8882) ;; #X22B2
 5210     (nil "trianglelefteq" ("AMS" "Relational I") 8884) ;; #X22B4
 5211     (nil "vDash" ("AMS" "Relational I") 8872) ;; #X22A8
 5212     (nil "Vvdash" ("AMS" "Relational I") 8874) ;; #X22AA
 5213     (nil "smallsmile" ("AMS" "Relational I") 8995) ;; #X2323
 5214     (nil "smallfrown" ("AMS" "Relational I") 8994) ;; #X2322
 5215     (nil "bumpeq" ("AMS" "Relational I") 8783) ;; #X224F
 5216     (nil "Bumpeq" ("AMS" "Relational I") 8782) ;; #X224E
 5217     (nil "geqq" ("AMS" "Relational II") 8807) ;; #X2267
 5218     (nil "geqslant" ("AMS" "Relational II") 10878) ;; #X2A7E
 5219     (nil "eqslantgtr" ("AMS" "Relational II") 10902) ;; #X2A96
 5220     (nil "gtrsim" ("AMS" "Relational II") 8819) ;; #X2273
 5221     (nil "gtrapprox" ("AMS" "Relational II") 10886) ;; #X2A86
 5222     (nil "gtrdot" ("AMS" "Relational II") 8919) ;; #X22D7
 5223     (nil "ggg" ("AMS" "Relational II") 8921) ;; #X22D9
 5224     (nil "gtrless" ("AMS" "Relational II") 8823) ;; #X2277
 5225     (nil "gtreqless" ("AMS" "Relational II") 8923) ;; #X22DB
 5226     (nil "gtreqqless" ("AMS" "Relational II") 10892) ;; #X2A8C
 5227     (nil "eqcirc" ("AMS" "Relational II") 8790) ;; #X2256
 5228     (nil "circeq" ("AMS" "Relational II") 8791) ;; #X2257
 5229     (nil "triangleq" ("AMS" "Relational II") 8796) ;; #X225C
 5230     (nil "thicksim" ("AMS" "Relational II") 8764) ;; #X223C
 5231     (nil "thickapprox" ("AMS" "Relational II") 8776) ;; #X2248
 5232     (nil "supseteqq" ("AMS" "Relational II") 10950) ;; #X2AC6
 5233     (nil "Supset" ("AMS" "Relational II") 8913) ;; #X22D1
 5234     (nil "sqsupset" ("AMS" "Relational II") 8848) ;; #X2290
 5235     (nil "succcurlyeq" ("AMS" "Relational II") 8829) ;; #X227D
 5236     (nil "curlyeqsucc" ("AMS" "Relational II") 8927) ;; #X22DF
 5237     (nil "succsim" ("AMS" "Relational II") 8831) ;; #X227F
 5238     (nil "succapprox" ("AMS" "Relational II") 10936) ;; #X2AB8
 5239     (nil "vartriangleright" ("AMS" "Relational II") 8883) ;; #X22B3
 5240     (nil "trianglerighteq" ("AMS" "Relational II") 8885) ;; #X22B5
 5241     (nil "Vdash" ("AMS" "Relational II") 8873) ;; #X22A9
 5242     (nil "shortmid" ("AMS" "Relational II") 8739) ;; #X2223
 5243     (nil "shortparallel" ("AMS" "Relational II") 8741) ;; #X2225
 5244     (nil "between" ("AMS" "Relational II") 8812) ;; #X226C
 5245     (nil "pitchfork" ("AMS" "Relational II") 8916) ;; #X22D4
 5246     (nil "varpropto" ("AMS" "Relational II") 8733) ;; #X221D
 5247     (nil "blacktriangleleft" ("AMS" "Relational II") 9664) ;; #X25C0
 5248     (nil "therefore" ("AMS" "Relational II") 8756) ;; #X2234
 5249     (nil "backepsilon" ("AMS" "Relational II") 1014) ;; #X03F6
 5250     (nil "blacktriangleright" ("AMS" "Relational II") 9654) ;; #X25B6
 5251     (nil "because" ("AMS" "Relational II") 8757) ;; #X2235
 5252     (nil "nless" ("AMS" "Neg Rel I") 8814) ;; #X226E
 5253     (nil "nleq" ("AMS" "Neg Rel I") 8816) ;; #X2270
 5254     (nil "nleqslant" ("AMS" "Neg Rel I"))
 5255     (nil "nleqq" ("AMS" "Neg Rel I"))
 5256     (nil "lneq" ("AMS" "Neg Rel I") 10887) ;; #X2A87
 5257     (nil "lneqq" ("AMS" "Neg Rel I") 8808) ;; #X2268
 5258     (nil "lvertneqq" ("AMS" "Neg Rel I"))
 5259     (nil "lnsim" ("AMS" "Neg Rel I") 8934) ;; #X22E6
 5260     (nil "lnapprox" ("AMS" "Neg Rel I") 10889) ;; #X2A89
 5261     (nil "nprec" ("AMS" "Neg Rel I") 8832) ;; #X2280
 5262     (nil "npreceq" ("AMS" "Neg Rel I"))
 5263     (nil "precnsim" ("AMS" "Neg Rel I") 8936) ;; #X22E8
 5264     (nil "precnapprox" ("AMS" "Neg Rel I") 10937) ;; #X2AB9
 5265     (nil "nsim" ("AMS" "Neg Rel I") 8769) ;; #X2241
 5266     (nil "nshortmid" ("AMS" "Neg Rel I") 8740) ;; #X2224
 5267     (nil "nmid" ("AMS" "Neg Rel I") 8740) ;; #X2224
 5268     (nil "nvdash" ("AMS" "Neg Rel I") 8876) ;; #X22AC
 5269     (nil "nvDash" ("AMS" "Neg Rel I") 8877) ;; #X22AD
 5270     (nil "ntriangleleft" ("AMS" "Neg Rel I") 8938) ;; #X22EA
 5271     (nil "ntrianglelefteq" ("AMS" "Neg Rel I") 8940) ;; #X22EC
 5272     (nil "nsubseteq" ("AMS" "Neg Rel I") 8840) ;; #X2288
 5273     (nil "subsetneq" ("AMS" "Neg Rel I") 8842) ;; #X228A
 5274     (nil "varsubsetneq" ("AMS" "Neg Rel I"))
 5275     (nil "subsetneqq" ("AMS" "Neg Rel I") 10955) ;; #X2ACB
 5276     (nil "varsubsetneqq" ("AMS" "Neg Rel I"))
 5277     (nil "ngtr" ("AMS" "Neg Rel II") 8815) ;; #X226F
 5278     (nil "ngeq" ("AMS" "Neg Rel II") 8817) ;; #X2271
 5279     (nil "ngeqslant" ("AMS" "Neg Rel II"))
 5280     (nil "ngeqq" ("AMS" "Neg Rel II"))
 5281     (nil "gneq" ("AMS" "Neg Rel II") 10888) ;; #X2A88
 5282     (nil "gneqq" ("AMS" "Neg Rel II") 8809) ;; #X2269
 5283     (nil "gvertneqq" ("AMS" "Neg Rel II"))
 5284     (nil "gnsim" ("AMS" "Neg Rel II") 8935) ;; #X22E7
 5285     (nil "gnapprox" ("AMS" "Neg Rel II") 10890) ;; #X2A8A
 5286     (nil "nsucc" ("AMS" "Neg Rel II") 8833) ;; #X2281
 5287     (nil "nsucceq" ("AMS" "Neg Rel II"))
 5288     (nil "succnsim" ("AMS" "Neg Rel II") 8937) ;; #X22E9
 5289     (nil "succnapprox" ("AMS" "Neg Rel II") 10938) ;; #X2ABA
 5290     (nil "ncong" ("AMS" "Neg Rel II") 8775) ;; #X2247
 5291     (nil "nshortparallel" ("AMS" "Neg Rel II") 8742) ;; #X2226
 5292     (nil "nparallel" ("AMS" "Neg Rel II") 8742) ;; #X2226
 5293     (nil "nvDash" ("AMS" "Neg Rel II") 8877) ;; #X22AD
 5294     (nil "nVDash" ("AMS" "Neg Rel II") 8879) ;; #X22AF
 5295     (nil "ntriangleright" ("AMS" "Neg Rel II") 8939) ;; #X22EB
 5296     (nil "ntrianglerighteq" ("AMS" "Neg Rel II") 8941) ;; #X22ED
 5297     (nil "nsupseteq" ("AMS" "Neg Rel II") 8841) ;; #X2289
 5298     (nil "nsupseteqq" ("AMS" "Neg Rel II"))
 5299     (nil "supsetneq" ("AMS" "Neg Rel II") 8843) ;; #X228B
 5300     (nil "varsupsetneq" ("AMS" "Neg Rel II"))
 5301     (nil "supsetneqq" ("AMS" "Neg Rel II") 10956) ;; #X2ACC
 5302     (nil "varsupsetneqq" ("AMS" "Neg Rel II"))
 5303     (nil "dotplus" ("AMS" "Binary Op") 8724) ;; #X2214
 5304     (nil "smallsetminus" ("AMS" "Binary Op") 8726) ;; #X2216
 5305     (nil "Cap" ("AMS" "Binary Op") 8914) ;; #X22D2
 5306     (nil "Cup" ("AMS" "Binary Op") 8915) ;; #X22D3
 5307     (nil "barwedge" ("AMS" "Binary Op") 8892) ;; #X22BC
 5308     (nil "veebar" ("AMS" "Binary Op") 8891) ;; #X22BB
 5309     (nil "doublebarwedge" ("AMS" "Binary Op") 8966) ;; #X2306
 5310     (nil "boxminus" ("AMS" "Binary Op") 8863) ;; #X229F
 5311     (nil "boxtimes" ("AMS" "Binary Op") 8864) ;; #X22A0
 5312     (nil "boxdot" ("AMS" "Binary Op") 8865) ;; #X22A1
 5313     (nil "boxplus" ("AMS" "Binary Op") 8862) ;; #X229E
 5314     (nil "divideontimes" ("AMS" "Binary Op") 8903) ;; #X22C7
 5315     (nil "ltimes" ("AMS" "Binary Op") 8905) ;; #X22C9
 5316     (nil "rtimes" ("AMS" "Binary Op") 8906) ;; #X22CA
 5317     (nil "leftthreetimes" ("AMS" "Binary Op") 8907) ;; #X22CB
 5318     (nil "rightthreetimes" ("AMS" "Binary Op") 8908) ;; #X22CC
 5319     (nil "curlywedge" ("AMS" "Binary Op") 8911) ;; #X22CF
 5320     (nil "curlyvee" ("AMS" "Binary Op") 8910) ;; #X22CE
 5321     (nil "circleddash" ("AMS" "Binary Op") 8861) ;; #X229D
 5322     (nil "circledast" ("AMS" "Binary Op") 8859) ;; #X229B
 5323     (nil "circledcirc" ("AMS" "Binary Op") 8858) ;; #X229A
 5324     (nil "centerdot" ("AMS" "Binary Op"))
 5325     (nil "intercal" ("AMS" "Binary Op") 8890) ;; #X22BA
 5326     (nil "hbar" ("AMS" "Misc") 8463) ;; #X210F
 5327     (nil "hslash" ("AMS" "Misc") 8463) ;; #X210F
 5328     (nil "vartriangle" ("AMS" "Misc") 9653) ;; #X25B5
 5329     (nil "triangledown" ("AMS" "Misc") 9663) ;; #X25BF
 5330     (nil "square" ("AMS" "Misc") 9633) ;; #X25A1
 5331     (nil "lozenge" ("AMS" "Misc") 9674) ;; #X25CA
 5332     (nil "circledS" ("AMS" "Misc") 9416) ;; #X24C8
 5333     (nil "angle" ("AMS" "Misc") 8736) ;; #X2220
 5334     (nil "measuredangle" ("AMS" "Misc") 8737) ;; #X2221
 5335     (nil "nexists" ("AMS" "Misc") 8708) ;; #X2204
 5336     (nil "mho" ("AMS" "Misc") 8487) ;; #X2127
 5337     (nil "Finv" ("AMS" "Misc") 8498) ;; #X2132
 5338     (nil "Game" ("AMS" "Misc") 8513) ;; #X2141
 5339     (nil "Bbbk" ("AMS" "Misc") 120156) ;; #X1D55C
 5340     (nil "backprime" ("AMS" "Misc") 8245) ;; #X2035
 5341     (nil "varnothing" ("AMS" "Misc") 8709) ;; #X2205
 5342     (nil "blacktriangle" ("AMS" "Misc") 9652) ;; #X25B4
 5343     (nil "blacktriangledown" ("AMS" "Misc") 9662) ;; #X25BE
 5344     (nil "blacksquare" ("AMS" "Misc") 9632) ;; #X25A0
 5345     (nil "blacklozenge" ("AMS" "Misc") 10731) ;; #X29EB
 5346     (nil "bigstar" ("AMS" "Misc") 9733) ;; #X2605
 5347     (nil "sphericalangle" ("AMS" "Misc") 8738) ;; #X2222
 5348     (nil "complement" ("AMS" "Misc") 8705) ;; #X2201
 5349     (nil "eth" ("AMS" "Misc") 240) ;; #X00F0
 5350     (nil "diagup" ("AMS" "Misc") 9585) ;; #X2571
 5351     (nil "diagdown" ("AMS" "Misc") 9586) ;; #X2572
 5352     (nil "dddot" ("AMS" "Accents") 8411) ;; #X20DB
 5353     (nil "ddddot" ("AMS" "Accents") 8412) ;; #X20DC
 5354     (nil "bigl" ("AMS" "Delimiters"))
 5355     (nil "bigr" ("AMS" "Delimiters"))
 5356     (nil "Bigl" ("AMS" "Delimiters"))
 5357     (nil "Bigr" ("AMS" "Delimiters"))
 5358     (nil "biggl" ("AMS" "Delimiters"))
 5359     (nil "biggr" ("AMS" "Delimiters"))
 5360     (nil "Biggl" ("AMS" "Delimiters"))
 5361     (nil "Biggr" ("AMS" "Delimiters"))
 5362     (nil "lvert" ("AMS" "Delimiters"))
 5363     (nil "rvert" ("AMS" "Delimiters"))
 5364     (nil "lVert" ("AMS" "Delimiters"))
 5365     (nil "rVert" ("AMS" "Delimiters"))
 5366     (nil "ulcorner" ("AMS" "Delimiters") 8988) ;; #X231C
 5367     (nil "urcorner" ("AMS" "Delimiters") 8989) ;; #X231D
 5368     (nil "llcorner" ("AMS" "Delimiters") 8990) ;; #X231E
 5369     (nil "lrcorner" ("AMS" "Delimiters") 8991) ;; #X231F
 5370     (nil "nobreakdash" ("AMS" "Special"))
 5371     (nil "leftroot" ("AMS" "Special"))
 5372     (nil "uproot" ("AMS" "Special"))
 5373     (nil "accentedsymbol" ("AMS" "Special"))
 5374     (nil "xleftarrow" ("AMS" "Special"))
 5375     (nil "xrightarrow" ("AMS" "Special"))
 5376     (nil "overset" ("AMS" "Special"))
 5377     (nil "underset" ("AMS" "Special"))
 5378     (nil "dfrac" ("AMS" "Special"))
 5379     (nil "genfrac" ("AMS" "Special"))
 5380     (nil "tfrac" ("AMS" "Special"))
 5381     (nil "binom" ("AMS" "Special"))
 5382     (nil "dbinom" ("AMS" "Special"))
 5383     (nil "tbinom" ("AMS" "Special"))
 5384     (nil "smash" ("AMS" "Special"))
 5385     (nil "eucal" ("AMS" "Special"))
 5386     (nil "boldsymbol" ("AMS" "Special"))
 5387     (nil "text" ("AMS" "Special"))
 5388     (nil "intertext" ("AMS" "Special"))
 5389     (nil "substack" ("AMS" "Special"))
 5390     (nil "subarray" ("AMS" "Special"))
 5391     (nil "sideset" ("AMS" "Special")))
 5392   "Alist of LaTeX math symbols.
 5393 
 5394 Each entry should be a list with upto four elements, KEY, VALUE,
 5395 MENU and CHARACTER, see `LaTeX-math-list' for details.")
 5396 
 5397 (defcustom LaTeX-math-list nil
 5398   "Alist of your personal LaTeX math symbols.
 5399 
 5400 Each entry should be a list with up to four elements, KEY, VALUE,
 5401 MENU and CHARACTER.
 5402 
 5403 KEY is the key (after `LaTeX-math-abbrev-prefix') to be redefined
 5404 in math minor mode.  If KEY is nil, the symbol has no associated
 5405 keystroke \(it is available in the menu, though\).
 5406 
 5407 VALUE can be a string with the name of the macro to be inserted,
 5408 or a function to be called.  The macro must be given without the
 5409 leading backslash.
 5410 
 5411 The third element MENU is the name of the submenu where the
 5412 command should be added.  MENU can be either a string
 5413 \(e.g. \"greek\"\), a list (e.g. \(\"AMS\" \"Delimiters\"\)\) or
 5414 nil.  If MENU is nil, no menu item will be created.
 5415 
 5416 The fourth element CHARACTER is a Unicode character position for
 5417 menu display.  When nil, no character is shown.
 5418 
 5419 See also `LaTeX-math-menu'."
 5420   :group 'LaTeX-math
 5421   :set (lambda (symbol value)
 5422      (set-default symbol value)
 5423      (LaTeX-math-initialize))
 5424   :type '(repeat (group (choice :tag "Key"
 5425                 (const :tag "none" nil)
 5426                 (choice (character)
 5427                     (string :tag "Key sequence")))
 5428             (choice :tag "Value"
 5429                 (string :tag "Macro")
 5430                 (function))
 5431             (choice :tag "Menu"
 5432                 (string :tag "Top level menu" )
 5433                 (repeat :tag "Submenu"
 5434                     (string :tag "Menu")))
 5435             (choice :tag "Unicode character"
 5436                 (const :tag "none" nil)
 5437                 (integer :tag "Number")))))
 5438 
 5439 (define-minor-mode LaTeX-math-mode
 5440   "A minor mode with easy access to TeX math macros.
 5441 
 5442 Easy insertion of LaTeX math symbols.  If you give a prefix argument,
 5443 the symbols will be surrounded by dollar signs.  The following
 5444 commands are defined:
 5445 
 5446 \\{LaTeX-math-mode-map}"
 5447   nil nil (list (cons (LaTeX-math-abbrev-prefix) LaTeX-math-keymap))
 5448   (if LaTeX-math-mode
 5449       (easy-menu-add LaTeX-math-mode-menu LaTeX-math-mode-map)
 5450     (easy-menu-remove LaTeX-math-mode-menu))
 5451   (TeX-set-mode-name))
 5452 (defalias 'latex-math-mode 'LaTeX-math-mode)
 5453 
 5454 (easy-menu-define LaTeX-math-mode-menu
 5455     LaTeX-math-mode-map
 5456     "Menu used in math minor mode."
 5457   LaTeX-math-menu)
 5458 
 5459 (defcustom LaTeX-math-insert-function 'TeX-insert-macro
 5460   "Function called with argument STRING to insert \\STRING."
 5461   :group 'LaTeX-math
 5462   :type 'function)
 5463 
 5464 (defun LaTeX-math-insert (string dollar)
 5465   "Insert \\STRING{}.  If DOLLAR is non-nil, put $'s around it.
 5466 If `TeX-electric-math' is non-nil wrap that symbols around the
 5467 string."
 5468   (let ((active (TeX-active-mark))
 5469     m closer)
 5470     (if (and active (> (point) (mark)))
 5471     (exchange-point-and-mark))
 5472     (when dollar
 5473       (insert (or (car TeX-electric-math) "$"))
 5474       (save-excursion
 5475     (if active (goto-char (mark)))
 5476     ;; Store closer string for later reference.
 5477     (setq closer (or (cdr TeX-electric-math) "$"))
 5478     (insert closer)
 5479     ;; Set temporal marker to decide whether to put the point
 5480     ;; after the math mode closer or not.
 5481     (setq m (point-marker))))
 5482     (funcall LaTeX-math-insert-function string)
 5483     (when dollar
 5484       ;; If the above `LaTeX-math-insert-function' resulted in
 5485       ;; inserting, e.g., a pair of "\langle" and "\rangle" by
 5486       ;; typing "`(", keep the point between them.  Otherwise
 5487       ;; move the point after the math mode closer.
 5488       (if (= m (+ (point) (length closer)))
 5489       (goto-char m))
 5490       ;; Make temporal marker point nowhere not to slow down the
 5491       ;; subsequent editing in the buffer.
 5492       (set-marker m nil))))
 5493 
 5494 (defun LaTeX-math-cal (char dollar)
 5495   "Insert a {\\cal CHAR}.  If DOLLAR is non-nil, put $'s around it.
 5496 If `TeX-electric-math' is non-nil wrap that symbols around the
 5497 char."
 5498   (interactive "*c\nP")
 5499   (if dollar (insert (or (car TeX-electric-math) "$")))
 5500   (if (member "latex2e" (TeX-style-list))
 5501       (insert "\\mathcal{" (char-to-string char) "}")
 5502     (insert "{\\cal " (char-to-string char) "}"))
 5503   (if dollar (insert (or (cdr TeX-electric-math) "$"))))
 5504 
 5505 
 5506 ;;; Folding
 5507 
 5508 (defcustom LaTeX-fold-macro-spec-list nil
 5509   "List of display strings and macros to fold in LaTeX mode."
 5510   :type '(repeat (group (choice (string :tag "Display String")
 5511                 (integer :tag "Number of argument" :value 1))
 5512             (repeat :tag "Macros" (string))))
 5513   :group 'TeX-fold)
 5514 
 5515 (defcustom LaTeX-fold-env-spec-list nil
 5516   "List of display strings and environments to fold in LaTeX mode."
 5517   :type '(repeat (group (choice (string :tag "Display String")
 5518                 (integer :tag "Number of argument" :value 1))
 5519             (repeat :tag "Environments" (string))))
 5520   :group 'TeX-fold)
 5521 
 5522 (defcustom LaTeX-fold-math-spec-list
 5523   (delete nil
 5524       (mapcar (lambda (elt)
 5525             (let ((tex-token (nth 1 elt))
 5526               (submenu   (nth 2 elt))
 5527               (unicode   (nth 3 elt))
 5528               uchar noargp)
 5529               (when (and (fboundp 'decode-char) (integerp unicode))
 5530             (setq uchar (decode-char 'ucs unicode)))
 5531               (when (listp submenu) (setq submenu (nth 1 submenu)))
 5532               (setq noargp
 5533                 (not (string-match
 5534                   (concat "^" (regexp-opt '("Constructs"
 5535                                 "Accents")))
 5536                   submenu)))
 5537               (when (and (stringp tex-token) (integerp uchar) noargp)
 5538             `(,(char-to-string uchar) (,tex-token)))))
 5539           `((nil "to" "" 8594)
 5540             (nil "gets" "" 8592)
 5541             ,@LaTeX-math-default)))
 5542   "List of display strings and math macros to fold in LaTeX mode."
 5543   :type '(repeat (group (choice (string :tag "Display String")
 5544                 (integer :tag "Number of argument" :value 1))
 5545             (repeat :tag "Math Macros" (string))))
 5546   :group 'TeX-fold)
 5547 
 5548 ;;; Narrowing
 5549 
 5550 (defun LaTeX-narrow-to-environment (&optional count)
 5551   "Make text outside current environment invisible.
 5552 With optional COUNT keep visible that number of enclosing
 5553 environments."
 5554   (interactive "p")
 5555   (setq count (if count (abs count) 1))
 5556   (save-excursion
 5557     (widen)
 5558     (let ((opoint (point))
 5559       beg end)
 5560       (dotimes (c count) (LaTeX-find-matching-end))
 5561       (setq end (point))
 5562       (goto-char opoint)
 5563       (dotimes (c count) (LaTeX-find-matching-begin))
 5564       (setq beg (point))
 5565       (narrow-to-region beg end))))
 5566 (put 'LaTeX-narrow-to-environment 'disabled t)
 5567 
 5568 ;;; Keymap
 5569 
 5570 (defvar LaTeX-mode-map
 5571   (let ((map (make-sparse-keymap)))
 5572     (set-keymap-parent map TeX-mode-map)
 5573 
 5574     ;; Standard
 5575     (define-key map "\n"      'reindent-then-newline-and-indent)
 5576 
 5577     ;; From latex.el
 5578     ;; We now set `fill-paragraph-function' instead.
 5579     ;; (define-key map "\eq"     'LaTeX-fill-paragraph) ;*** Alias
 5580     ;; This key is now used by Emacs for face settings.
 5581     ;; (define-key map "\eg"     'LaTeX-fill-region) ;*** Alias
 5582     (define-key map "\e\C-e"  'LaTeX-find-matching-end)
 5583     (define-key map "\e\C-a"  'LaTeX-find-matching-begin)
 5584 
 5585     (define-key map "\C-c\C-q\C-p" 'LaTeX-fill-paragraph)
 5586     (define-key map "\C-c\C-q\C-r" 'LaTeX-fill-region)
 5587     (define-key map "\C-c\C-q\C-s" 'LaTeX-fill-section)
 5588     (define-key map "\C-c\C-q\C-e" 'LaTeX-fill-environment)
 5589 
 5590     (define-key map "\C-c\C-z" 'LaTeX-command-section)
 5591     (define-key map "\C-c\M-z" 'LaTeX-command-section-change-level)
 5592 
 5593     (define-key map "\C-c."    'LaTeX-mark-environment) ;*** Dubious
 5594     (define-key map "\C-c*"    'LaTeX-mark-section) ;*** Dubious
 5595 
 5596     (define-key map "\C-c\C-e" 'LaTeX-environment)
 5597     (define-key map "\C-c\n"   'LaTeX-insert-item)
 5598     (or (key-binding "\e\r")
 5599     (define-key map "\e\r"    'LaTeX-insert-item)) ;*** Alias
 5600     (define-key map "\C-c]" 'LaTeX-close-environment)
 5601     (define-key map "\C-c\C-s" 'LaTeX-section)
 5602 
 5603     (define-key map "\C-c~"    'LaTeX-math-mode) ;*** Dubious
 5604 
 5605     (define-key map "-" 'LaTeX-babel-insert-hyphen)
 5606     (define-key map "(" 'LaTeX-insert-left-brace)
 5607     (define-key map "{" 'LaTeX-insert-left-brace)
 5608     (define-key map "[" 'LaTeX-insert-left-brace)
 5609     map)
 5610   "Keymap used in `LaTeX-mode'.")
 5611 
 5612 (defvar LaTeX-environment-menu-name "Insert Environment  (C-c C-e)")
 5613 
 5614 (defun LaTeX-environment-menu-entry (entry)
 5615   "Create an entry for the environment menu."
 5616   (vector (car entry) (list 'LaTeX-environment-menu (car entry)) t))
 5617 
 5618 (defvar LaTeX-environment-modify-menu-name "Change Environment  (C-u C-c C-e)")
 5619 
 5620 (defun LaTeX-environment-modify-menu-entry (entry)
 5621   "Create an entry for the change environment menu."
 5622   (vector (car entry) (list 'LaTeX-modify-environment (car entry)) t))
 5623 
 5624 (defun LaTeX-section-enable-symbol (level)
 5625   "Symbol used to enable section LEVEL in the menu bar."
 5626   (intern (concat "LaTeX-section-" (int-to-string level) "-enable")))
 5627 
 5628 (defun LaTeX-section-enable (entry)
 5629   "Enable or disable section ENTRY from `LaTeX-section-list'."
 5630   (let* ((level (nth 1 entry))
 5631      (symbol (LaTeX-section-enable-symbol level)))
 5632     (set symbol (or (= level 0) (>= level LaTeX-largest-level)))
 5633     (make-variable-buffer-local symbol)))
 5634 
 5635 (defun LaTeX-section-menu (level)
 5636   "Insert section from menu."
 5637   (let ((LaTeX-section-hook (delq 'LaTeX-section-heading
 5638                   (copy-sequence LaTeX-section-hook))))
 5639     (LaTeX-section level)))
 5640 
 5641 (defun LaTeX-section-menu-entry (entry)
 5642   "Create an ENTRY for the section menu."
 5643   (let ((enable (LaTeX-section-enable-symbol (nth 1 entry))))
 5644     (vector (car entry) (list 'LaTeX-section-menu (nth 1 entry)) enable)))
 5645 
 5646 (defcustom LaTeX-menu-max-items 25
 5647   "*Maximum number of items in the menu for LaTeX environments.
 5648 If number of entries in a menu is larger than this value, split menu
 5649 into submenus of nearly equal length.  If nil, never split menu into
 5650 submenus."
 5651   :group 'LaTeX-environment
 5652   :type '(choice (const :tag "no submenus" nil)
 5653          (integer)))
 5654 
 5655 (defcustom LaTeX-submenu-name-format "%-12.12s ... %.12s"
 5656   "*Format specification of the submenu name.
 5657 Used by `LaTeX-split-long-menu' if the number of entries in a menu is
 5658 larger than `LaTeX-menu-max-items'.
 5659 This string should contain one %s for the name of the first entry and
 5660 one %s for the name of the last entry in the submenu.
 5661 If the value is a function, it should return the submenu name.  The
 5662 function is called with two arguments, the names of the first and
 5663 the last entry in the menu."
 5664   :group 'LaTeX-environment
 5665   :type '(choice (string :tag "Format string")
 5666          (function)))
 5667 
 5668 (defun LaTeX-split-long-menu (menu)
 5669   "Split MENU according to `LaTeX-menu-max-items'."
 5670   (let ((len (length menu)))
 5671     (if (or (null LaTeX-menu-max-items)
 5672         (null (featurep 'lisp-float-type))
 5673         (<= len LaTeX-menu-max-items))
 5674     menu
 5675       ;; Submenu is max 2 entries longer than menu, never shorter, number of
 5676       ;; entries in submenus differ by at most one (with longer submenus first)
 5677       (let* ((outer (floor (sqrt len)))
 5678          (inner (/ len outer))
 5679          (rest (% len outer))
 5680          (result nil))
 5681     (setq menu (reverse menu))
 5682     (while menu
 5683       (let ((in inner)
 5684         (sub nil)
 5685         (to (car menu)))
 5686         (while (> in 0)
 5687           (setq in   (1- in)
 5688             sub  (cons (car menu) sub)
 5689             menu (cdr menu)))
 5690         (setq result
 5691           (cons (cons (if (stringp LaTeX-submenu-name-format)
 5692                   (format LaTeX-submenu-name-format
 5693                       (aref (car sub) 0) (aref to 0))
 5694                 (funcall LaTeX-submenu-name-format
 5695                      (aref (car sub) 0) (aref to 0)))
 5696                   sub)
 5697             result)
 5698           rest  (1+ rest))
 5699         (if (= rest outer) (setq inner (1+ inner)))))
 5700     result))))
 5701 
 5702 (defvar LaTeX-section-menu nil)
 5703 (make-variable-buffer-local 'LaTeX-section-menu)
 5704 (defun LaTeX-section-menu-filter (ignored)
 5705   "Filter function for the section submenu in the mode menu.
 5706 The argument IGNORED is not used in any way."
 5707   (TeX-update-style)
 5708   (or LaTeX-section-menu
 5709       (progn
 5710     (setq LaTeX-section-list-changed nil)
 5711     (mapc 'LaTeX-section-enable LaTeX-section-list)
 5712     (setq LaTeX-section-menu
 5713           (mapcar 'LaTeX-section-menu-entry LaTeX-section-list)))))
 5714 
 5715 (defvar LaTeX-environment-menu nil)
 5716 (make-variable-buffer-local 'LaTeX-environment-menu)
 5717 (defvar LaTeX-environment-modify-menu nil)
 5718 (make-variable-buffer-local 'LaTeX-environment-modify-menu)
 5719 (defun LaTeX-environment-menu-filter (menu)
 5720   "Filter function for the environment submenus in the mode menu.
 5721 The argument MENU is the name of the submenu in concern and
 5722 corresponds to the variables `LaTeX-environment-menu-name' and
 5723 `LaTeX-environment-modify-menu-name'."
 5724   (TeX-update-style)
 5725   (cond
 5726    ((string= menu LaTeX-environment-menu-name)
 5727     (or LaTeX-environment-menu
 5728     (setq LaTeX-environment-menu
 5729           (LaTeX-split-long-menu
 5730            (mapcar 'LaTeX-environment-menu-entry
 5731                (LaTeX-environment-list))))))
 5732    ((string= menu LaTeX-environment-modify-menu-name)
 5733     (or LaTeX-environment-modify-menu
 5734     (setq LaTeX-environment-modify-menu
 5735           (LaTeX-split-long-menu
 5736            (mapcar 'LaTeX-environment-modify-menu-entry
 5737                (LaTeX-environment-list))))))))
 5738 
 5739 (defadvice LaTeX-add-environments (after LaTeX-invalidate-environment-menu (&rest environments) activate)
 5740   "Add ENVIRONMENTS to the list of known environments.
 5741 Additionally invalidate the environment submenus to let them be
 5742 regenerated by the respective menu filter."
 5743   (setq LaTeX-environment-menu nil)
 5744   (setq LaTeX-environment-modify-menu nil))
 5745 
 5746 (easy-menu-define LaTeX-mode-command-menu
 5747     LaTeX-mode-map
 5748     "Command menu used in LaTeX mode."
 5749     (TeX-mode-specific-command-menu 'latex-mode))
 5750 
 5751 (easy-menu-define LaTeX-mode-menu
 5752   LaTeX-mode-map
 5753   "Menu used in LaTeX mode."
 5754   `("LaTeX"
 5755     ("Section  (C-c C-s)" :filter LaTeX-section-menu-filter)
 5756     ["Macro..." TeX-insert-macro
 5757      :help "Insert a macro and possibly arguments"]
 5758     ["Complete Macro" TeX-complete-symbol
 5759      :help "Complete the current macro or environment name"]
 5760     ,(list LaTeX-environment-menu-name
 5761        :filter (lambda (ignored) (LaTeX-environment-menu-filter
 5762                       LaTeX-environment-menu-name)))
 5763     ,(list LaTeX-environment-modify-menu-name
 5764        :filter (lambda (ignored) (LaTeX-environment-menu-filter
 5765                       LaTeX-environment-modify-menu-name)))
 5766     ["Close Environment" LaTeX-close-environment
 5767      :help "Insert the \\end part of the current environment"]
 5768     ["Item" LaTeX-insert-item
 5769      :help "Insert a new \\item into current environment"]
 5770     "-"
 5771     ("Insert Font"
 5772      ["Emphasize"    (TeX-font nil ?\C-e) :keys "C-c C-f C-e"]
 5773      "-"
 5774      ["Roman"        (TeX-font nil ?\C-r) :keys "C-c C-f C-r"]
 5775      ["Sans Serif"   (TeX-font nil ?\C-f) :keys "C-c C-f C-f"]
 5776      ["Typewriter"   (TeX-font nil ?\C-t) :keys "C-c C-f C-t"]
 5777      "-"
 5778      ["Medium"       (TeX-font nil ?\C-m) :keys "C-c C-f C-m"]
 5779      ["Bold"         (TeX-font nil ?\C-b) :keys "