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