Initial Commit
[packages] / xemacs-packages / auctex / tex.el
1 ;;; tex.el --- Support for TeX documents.
2
3 ;; Copyright (C) 1985-1987, 1991, 1993-2014 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 basic functions used by the AUCTeX modes.
28
29 ;;; Code:
30
31 (when (< emacs-major-version 21)
32   (error "AUCTeX requires Emacs 21 or later"))
33
34 (require 'custom)
35 (require 'tex-site)
36 (eval-when-compile
37   (require 'cl))
38
39 (defgroup TeX-file nil
40   "Files used by AUCTeX."
41   :group 'AUCTeX)
42
43 (defgroup TeX-command nil
44   "Calling external commands from AUCTeX."
45   :group 'AUCTeX)
46
47 (defgroup LaTeX nil
48   "LaTeX support in AUCTeX."
49   :tag "LaTeX"
50   :group 'AUCTeX
51   :prefix "LaTeX-")
52
53 (defgroup TeX-misc nil
54   "Various AUCTeX settings."
55   :group 'AUCTeX)
56
57 ;;; Site Customization
58 ;;
59 ;; The following variables are likely to need to be changed for your
60 ;; site.  You should do this with customize.
61
62 (defcustom TeX-command "tex"
63   "Command to run plain TeX."
64   :group 'TeX-command
65   :type 'string)
66
67 (defcustom TeX-Omega-command "omega"
68   "Command to run plain TeX on Omega."
69   :group 'TeX-command
70   :type 'string)
71
72 (defcustom LaTeX-command "latex"
73   "Command to run LaTeX."
74   :group 'TeX-command
75   :type 'string)
76
77 (defcustom LaTeX-Omega-command "lambda"
78   "Command to run LaTeX on Omega."
79   :group 'TeX-command
80   :type 'string)
81
82 (defcustom ConTeXt-engine nil
83   "Engine to use for --engine in the texexec command.
84 If nil, none is specified."
85   :group 'TeX-command
86   :type '(choice (const :tag "Unspecified" nil)
87                  string))
88
89 (defcustom ConTeXt-Omega-engine TeX-Omega-command
90   "Engine to use for --engine in the texexec command in Omega mode.
91 If nil, none is specified."
92   :group 'TeX-command
93   :type '(choice (const :tag "Unspecified" nil)
94                  string))
95 ;; At least in TeXLive 2009 ConTeXt does not support an omega option anymore.
96 (make-obsolete-variable 'ConTeXt-Omega-engine 'TeX-engine-alist "11.86")
97
98 (defcustom TeX-mode-hook nil
99   "A hook run in TeX mode buffers."
100   :type 'hook
101   :group 'TeX-misc)
102
103 (defcustom AmS-TeX-mode-hook nil
104   "A hook run in AmS-TeX mode buffers."
105   :type 'hook
106   :group 'TeX-misc)
107
108 ;; This is the major configuration variable.  Most sites will only
109 ;; need to change the second string in each entry, which is the name
110 ;; of a command to send to the shell.  If you use other formatters
111 ;; like AMSLaTeX or AMSTeX, you can add those to the list.  See
112 ;; TeX-expand-list for a description of the % escapes
113
114 (defcustom TeX-command-list
115   `(("TeX" "%(PDF)%(tex) %(extraopts) %`%S%(PDFout)%(mode)%' %t"
116      TeX-run-TeX nil
117      (plain-tex-mode ams-tex-mode texinfo-mode) :help "Run plain TeX")
118     ("LaTeX" "%`%l%(mode)%' %t"
119      TeX-run-TeX nil
120      (latex-mode doctex-mode) :help "Run LaTeX")
121         ;; Not part of standard TeX.
122     ("Makeinfo" "makeinfo %(extraopts) %t" TeX-run-compile nil
123      (texinfo-mode) :help "Run Makeinfo with Info output")
124     ("Makeinfo HTML" "makeinfo %(extraopts) --html %t" TeX-run-compile nil
125      (texinfo-mode) :help "Run Makeinfo with HTML output")
126     ("AmSTeX" "%(PDF)amstex %(extraopts) %`%S%(PDFout)%(mode)%' %t"
127      TeX-run-TeX nil (ams-tex-mode) :help "Run AMSTeX")
128     ;; support for ConTeXt  --pg
129     ;; first version of ConTeXt to support nonstopmode: 2003.2.10
130     ("ConTeXt" "texexec --once --texutil %(extraopts) %(execopts)%t"
131      TeX-run-TeX nil (context-mode) :help "Run ConTeXt once")
132     ("ConTeXt Full" "texexec %(extraopts) %(execopts)%t"
133      TeX-run-TeX nil
134      (context-mode) :help "Run ConTeXt until completion")
135     ("BibTeX" "bibtex %s" TeX-run-BibTeX nil t :help "Run BibTeX")
136     ("Biber" "biber %s" TeX-run-Biber nil t :help "Run Biber")
137     ,(if (or window-system (getenv "DISPLAY"))
138         '("View" "%V" TeX-run-discard-or-function t t :help "Run Viewer")
139        '("View" "dvi2tty -q -w 132 %s" TeX-run-command t t
140          :help "Run Text viewer"))
141     ("Print" "%p" TeX-run-command t t :help "Print the file")
142     ("Queue" "%q" TeX-run-background nil t :help "View the printer queue"
143      :visible TeX-queue-command)
144     ("File" "%(o?)dvips %d -o %f " TeX-run-command t t
145      :help "Generate PostScript file")
146     ("Index" "makeindex %s" TeX-run-command nil t :help "Create index file")
147     ("Xindy" "texindy %s" TeX-run-command nil t
148      :help "Run xindy to create index file")
149     ("Check" "lacheck %s" TeX-run-compile nil (latex-mode)
150      :help "Check LaTeX file for correctness")
151     ("ChkTeX" "chktex -v6 %s" TeX-run-compile nil (latex-mode)
152      :help "Check LaTeX file for common mistakes")
153     ("Spell" "(TeX-ispell-document \"\")" TeX-run-function nil t
154      :help "Spell-check the document")
155     ("Clean" "TeX-clean" TeX-run-function nil t
156      :help "Delete generated intermediate files")
157     ("Clean All" "(TeX-clean t)" TeX-run-function nil t
158      :help "Delete generated intermediate and output files")
159     ("Other" "" TeX-run-command t t :help "Run an arbitrary command"))
160   "List of commands to execute on the current document.
161
162 Each element is a list, whose first element is the name of the command
163 as it will be presented to the user.
164
165 The second element is the string handed to the shell after being
166 expanded.  The expansion is done using the information found in
167 `TeX-expand-list'.
168
169 The third element is the function which actually start the process.
170 Several such hooks has been defined:
171
172 TeX-run-command: Start up the process and show the output in a
173 separate buffer.  Check that there is not two commands running for the
174 same file.  Return the process object.
175
176 TeX-run-format: As `TeX-run-command', but assume the output is created
177 by a TeX macro package.  Return the process object.
178
179 TeX-run-TeX: For TeX output.
180
181 TeX-run-interactive: Run TeX or LaTeX interactively.
182
183 TeX-run-BibTeX: For BibTeX output.
184
185 TeX-run-Biber: For Biber output.
186
187 TeX-run-compile: Use `compile' to run the process.
188
189 TeX-run-shell: Use `shell-command' to run the process.
190
191 TeX-run-discard: Start the process in the background, discarding its
192 output.
193
194 TeX-run-background: Start the process in the background, show output
195 in other window.
196
197 TeX-run-silent: Start the process in the background.
198
199 TeX-run-discard-foreground: Start the process in the foreground,
200 discarding its output.
201
202 TeX-run-function: Execute the Lisp function or function call
203 specified by the string in the second element.  Consequently,
204 this hook does not start a process.
205
206 TeX-run-discard-or-function: If the command is a Lisp function,
207 execute it as such, otherwise start the command as a process,
208 discarding its output.
209
210 To create your own hook, define a function taking three arguments: The
211 name of the command, the command string, and the name of the file to
212 process.  It might be useful to use `TeX-run-command' in order to
213 create an asynchronous process.
214
215 If the fourth element is non-nil, the user will get a chance to
216 modify the expanded string.
217
218 The fifth element indicates in which mode(s) the command should be
219 present in the Command menu.  Use t if it should be active in any
220 mode.  If it should only be present in some modes, specify a list with
221 the respective mode names.
222
223 Any additional elements get just transferred to the respective menu entries."
224   :group 'TeX-command
225   :type '(repeat (group :value ("" "" TeX-run-command nil t)
226                         (string :tag "Name")
227                         (string :tag "Command")
228                         (choice :tag "How"
229                                 :value TeX-run-command
230                                 (function-item TeX-run-command)
231                                 (function-item TeX-run-format)
232                                 (function-item TeX-run-TeX)
233                                 (function-item TeX-run-interactive)
234                                 (function-item TeX-run-BibTeX)
235                                 (function-item TeX-run-Biber)
236                                 (function-item TeX-run-compile)
237                                 (function-item TeX-run-shell)
238                                 (function-item TeX-run-discard)
239                                 (function-item TeX-run-background)
240                                 (function-item TeX-run-silent)
241                                 (function-item TeX-run-discard-foreground)
242                                 (function-item TeX-run-function)
243                                 (function-item TeX-run-discard-or-function)
244                                 (function :tag "Other"))
245                         (boolean :tag "Prompt")
246                         (choice :tag "Modes"
247                                 (const :tag "All" t)
248                                 (set (const :tag "Plain TeX" plain-tex-mode)
249                                      (const :tag "LaTeX" latex-mode)
250                                      (const :tag "DocTeX" doctex-mode)
251                                      (const :tag "ConTeXt" context-mode)
252                                      (const :tag "Texinfo" texinfo-mode)
253                                      (const :tag "AmSTeX" ams-tex-mode)))
254                         (repeat :tag "Menu elements" :inline t sexp))))
255
256 (defcustom TeX-command-output-list
257   '(
258 ; Add the following line if you want to use htlatex (tex4ht)
259 ;    ("\\`htlatex" ("html"))
260     )
261   "List of regexps and file extensions.
262
263 Each element is a list, whose first element is a regular expression to
264 match against the name of the command that will be used to process the TeX
265 file.
266
267 The second element is either a string or a list with a string as element.
268 If it is a string this is the default file extension that will be expected
269 for output files that are produced by commands that match the first
270 element.  The real file extension will be obtained from the logging output
271 if possible, defaulting to the given string.
272 If it is a list, the element of the list will be the fixed extension used
273 without looking at the logging output.
274
275 If this list does not yield an extension, the default is either \"dvi\"
276 or \"pdf\", depending on the setting of `TeX-PDF-mode'.
277 Extensions must be given without the \".\"."
278
279   :group 'TeX-command
280   :type '(repeat (group (regexp :tag "Command Regexp")
281                         (choice (string :tag "Default Extension")
282                                 (group (string :tag "Fixed Extension"))))))
283
284 ;; You may want to change the default LaTeX version for your site.
285 (defcustom LaTeX-version "2e"
286   "Default LaTeX version.  Currently recognized is \"2\" and \"2e\"."
287   :group 'LaTeX
288   :type '(radio (const :format "%v\n%h"
289                        :doc "\
290 The executable `latex' is LaTeX version 2."
291                        "2")
292                 (const :format "%v\n%h"
293                        :doc "\
294 The executable `latex' is LaTeX version 2e."
295                        "2e")
296                 (string :tag "Other")))
297
298
299 ;; Use different compilation commands depending on style.
300 ;; Only works if parsing is enabled.
301
302 (defcustom LaTeX-command-style
303   ;; They have all been combined in LaTeX 2e.
304   '(("" "%(PDF)%(latex) %(extraopts) %S%(PDFout)"))
305 "List of style options and LaTeX commands.
306
307 If the first element (a regular expression) matches the name of one of
308 the style files, any occurrence of the string `%l' in a command in
309 `TeX-command-list' will be replaced with the second element.  The first
310 match is used, if no match is found the `%l' is replaced with the empty
311 string."
312   :group 'TeX-command
313   :type '(repeat (group :value ("" "")
314                         regexp (string :tag "Style"))))
315
316 ;; Printing: If you want to print, TeX-print-command must be non-nil
317 ;; (if it is nil, you'll get a complaint when using the print menu).
318 ;; If you want to view the queue, TeX-queue-command needs to be
319 ;; non-nil (if it is nil, it won't get mentioned in the menu).  If
320 ;; TeX-printer-list is nil, nothing else gets asked: the menu entries
321 ;; lead directly to the respective commands.  If those commands
322 ;; contain %p, the value of TeX-printer-default gets inserted there,
323 ;; no questions asked.  Now if TeX-printer-list is non-nil, you'll
324 ;; always get asked which printer you want to use.  You can enter a
325 ;; configured printer from TeX-printer-list, or an unknown one.  The
326 ;; respective menus will show all configured printers.  Since you can
327 ;; enter unknown printers, the printer name _must_ be set with %p in
328 ;; TeX-print-command.
329
330 (defcustom TeX-print-command
331   "{ test -e %s.dvi && %(o?)dvips -P%p %r %s; } || lpr -P%p %o"
332   "Command used to print a file.
333
334 First `%p' is expanded to the printer name, then ordinary expansion is
335 performed as specified in `TeX-expand-list'.  If it is nil,
336 then customization is requested."
337   :group 'TeX-command
338   :type '(choice (string :tag "Print command")
339                  (const :tag "No print command customized" nil)))
340
341 (defcustom TeX-queue-command "lpq -P%p"
342   "Command used to show the status of a printer queue.
343
344 First `%p' is expanded to the printer name, then ordinary expansion is
345 performed as specified in `TeX-expand-list'.  If this is nil,
346 the printer has no corresponding command."
347   :group 'TeX-command
348   :type '(choice (string :tag "Queue check command")
349                  (const :tag "No such command" nil)))
350
351 ;; Enter the names of the printers available at your site, or nil if
352 ;; you only have one printer.
353
354 (defcustom TeX-printer-list
355   '(("Default"
356      ;; Print to the (unnamed) default printer.  If there is a DVI
357      ;; file print via Dvips.  If not, pass the output file (which
358      ;; should then be a Postscript or PDF file) directly to lpr.
359      "{ test -e %s.dvi && %(o?)dvips -f %r %s | lpr; } || lpr %o"
360      ;; Show the queue for the (unnamed) default printer.
361      "lpq"))
362   "List of available printers.
363
364 The first element of each entry is the printer name.
365
366 The second element is the command used to print to this
367 printer.  It defaults to the value of `TeX-print-command' when nil.
368
369 The third element is the command used to examine the print queue for
370 this printer.  It defaults to the value of `TeX-queue-command' similarly.
371
372 Any occurrence of `%p' in the second or third element is expanded to
373 the printer name given in the first element, then ordinary expansion
374 is performed as specified in `TeX-expand-list'.
375
376 If this list is empty, only `TeX-print-command' and `TeX-queue-command'
377 get consulted."
378   :group 'TeX-command
379   :type '(repeat (group (string :tag "Name")
380                         (option (group :inline t
381                                        :extra-offset -4
382                                        (choice :tag "Print"
383                                                (const :tag "default")
384                                                (string :format "%v"))
385                                        (option (choice :tag "Queue"
386                                                        (const :tag "default")
387                                                        (string
388                                                         :format "%v"))))))))
389
390 ;; The name of the most used printer.
391
392 (defcustom TeX-printer-default (or (getenv "PRINTER")
393                                    (and TeX-printer-list
394                                         (car (car TeX-printer-list)))
395                                    "lp")
396   "Default printer to use with `TeX-command'."
397   :group 'TeX-command
398   :type 'string)
399
400 (defcustom TeX-print-style '(("^landscape$" "-t landscape"))
401   "List of style options and print options.
402
403 If the first element (a regular expression) matches the name of one of
404 the style files, any occurrence of the string `%r' in a command in
405 `TeX-command-list' will be replaced with the second element.  The first
406 match is used, if no match is found the `%r' is replaced with the empty
407 string."
408   :group 'TeX-command
409   :type '(repeat (group regexp (string :tag "Command"))))
410
411 (defcustom TeX-command-extra-options ""
412   "String with the extra options to be given to the TeX processor."
413   :type 'string)
414 (make-variable-buffer-local 'TeX-command-extra-options)
415
416 ;; This is the list of expansion for the commands in
417 ;; TeX-command-list.  Not likely to be changed, but you may e.g. want
418 ;; to handle .ps files.
419
420 (defcustom TeX-expand-list
421   '(("%p" TeX-printer-query)            ;%p must be the first entry
422     ("%q" (lambda ()
423             (TeX-printer-query t)))
424     ("%V" (lambda ()
425             (TeX-source-correlate-start-server-maybe)
426             (TeX-view-command-raw)))
427     ("%vv" (lambda ()
428              (TeX-source-correlate-start-server-maybe)
429              (TeX-output-style-check TeX-output-view-style)))
430     ("%v" (lambda ()
431             (TeX-source-correlate-start-server-maybe)
432             (TeX-style-check TeX-view-style)))
433     ("%r" (lambda ()
434             (TeX-style-check TeX-print-style)))
435     ("%l" (lambda ()
436             (TeX-style-check LaTeX-command-style)))
437     ("%(PDF)" (lambda ()
438                 (if (and (eq TeX-engine 'default)
439                          (or TeX-PDF-mode
440                              TeX-DVI-via-PDFTeX))
441                     "pdf"
442                   "")))
443     ("%(PDFout)" (lambda ()
444                    (cond ((and (eq TeX-engine 'xetex)
445                                (not TeX-PDF-mode))
446                           " -no-pdf")
447                          ((and (eq TeX-engine 'luatex)
448                                (not TeX-PDF-mode))
449                           " --output-format=dvi")
450                          ((and (eq TeX-engine 'default)
451                                (not TeX-PDF-mode)
452                                TeX-DVI-via-PDFTeX)
453                           " \"\\pdfoutput=0 \"")
454                          (t ""))))
455     ("%(mode)" (lambda ()
456                  (if TeX-interactive-mode
457                      ""
458                    " -interaction=nonstopmode")))
459     ("%(o?)" (lambda () (if (eq TeX-engine 'omega) "o" "")))
460     ("%(tex)" (lambda () (eval (nth 2 (assq TeX-engine (TeX-engine-alist))))))
461     ("%(latex)" (lambda () (eval (nth 3 (assq TeX-engine (TeX-engine-alist))))))
462     ("%(execopts)" ConTeXt-expand-options)
463     ("%(extraopts)" (lambda () TeX-command-extra-options))
464     ("%S" TeX-source-correlate-expand-options)
465     ("%dS" TeX-source-specials-view-expand-options)
466     ("%cS" TeX-source-specials-view-expand-client)
467     ("%(outpage)" (lambda ()
468                     ;; When `TeX-source-correlate-output-page-function' is nil
469                     ;; and we are using synctex, fallback on
470                     ;; `TeX-synctex-output-page'.
471                     (and TeX-source-correlate-mode
472                          (null TeX-source-correlate-output-page-function)
473                          (eq (TeX-source-correlate-method-active) 'synctex)
474                          (setq TeX-source-correlate-output-page-function
475                                'TeX-synctex-output-page))
476                     (or (if TeX-source-correlate-output-page-function
477                             (funcall TeX-source-correlate-output-page-function))
478                         "1")))
479     ;; `file' means to call `TeX-master-file' or `TeX-region-file'
480     ("%s" file nil t)
481     ("%t" file t t)
482     ("%`" (lambda nil
483             (setq TeX-command-pos t TeX-command-text "")))
484     (" \"\\" (lambda nil
485                (if (eq TeX-command-pos t)
486                    (setq TeX-command-pos pos
487                          pos (+ 3 pos))
488                  (setq pos (1+ pos)))))
489     ("\"" (lambda nil (if (numberp TeX-command-pos)
490                           (setq TeX-command-text
491                                 (concat
492                                  TeX-command-text
493                                  (substring command
494                                             TeX-command-pos
495                                             (1+ pos)))
496                                 command
497                                 (concat
498                                  (substring command
499                                             0
500                                             TeX-command-pos)
501                                  (substring command
502                                             (1+ pos)))
503                                 pos TeX-command-pos
504                                 TeX-command-pos t)
505                         (setq pos (1+ pos)))))
506     ("%'" (lambda nil
507             (prog1
508                 (if (stringp TeX-command-text)
509                     (progn
510                       (setq pos (+ pos (length TeX-command-text) 9)
511                             TeX-command-pos
512                             (and (string-match " "
513                                                (funcall file t t))
514                                  "\""))
515                       (concat TeX-command-text " \"\\input\""))
516                   (setq TeX-command-pos nil)
517                   "")
518               (setq TeX-command-text nil))))
519     ("%n" TeX-current-line)
520     ("%d" file "dvi" t)
521     ("%f" file "ps" t)
522     ("%o" (lambda nil (funcall file (TeX-output-extension) t)))
523     ;; for source specials the file name generated for the xdvi
524     ;; command needs to be relative to the master file, just in
525     ;; case the file is in a different subdirectory
526     ("%b" TeX-current-file-name-master-relative)
527     ;; Okular forward PDF search requires absolute path.
528     ("%a" (lambda nil (prin1-to-string (expand-file-name (buffer-file-name)))))
529     ;; the following is for preview-latex.
530     ("%m" preview-create-subdirectory))
531   "List of expansion strings for TeX command names.
532
533 Each entry is a list with two or more elements.  The first element is
534 the string to be expanded.  The second element is the name of a
535 function returning the expanded string when called with the remaining
536 elements as arguments.  The special value `file' will be expanded to
537 the name of the file being processed, with an optional extension."
538   :group 'TeX-command
539   :type '(repeat (group (string :tag "Key")
540                         (sexp :tag "Expander")
541                         (repeat :inline t
542                                 :tag "Arguments"
543                                 (sexp :format "%v")))))
544
545
546 ;; The following dependencies are not done with autoload cookies since
547 ;; they are only useful when tex.el is loaded, anyway.  tex-buf.el
548 ;; should remain unloaded as long as one is only editing files, so
549 ;; requiring it here would be wrong.
550
551 (autoload 'TeX-region-create "tex-buf" nil nil)
552 (autoload 'TeX-save-document "tex-buf" nil t)
553 (autoload 'TeX-home-buffer "tex-buf" nil t)
554 (autoload 'TeX-pin-region "tex-buf" nil t)
555 (autoload 'TeX-command-region "tex-buf" nil t)
556 (autoload 'TeX-command-buffer "tex-buf" nil t)
557 (autoload 'TeX-command-master "tex-buf" nil t)
558 (autoload 'TeX-command "tex-buf" nil nil)
559 (autoload 'TeX-kill-job "tex-buf" nil t)
560 (autoload 'TeX-recenter-output-buffer "tex-buf" nil t)
561 (autoload 'TeX-next-error "tex-buf" nil t)
562 (autoload 'TeX-error-overview "tex-buf" nil t)
563 (autoload 'TeX-region-file "tex-buf" nil nil)
564 (autoload 'TeX-current-offset "tex-buf" nil nil)
565 (autoload 'TeX-process-set-variable "tex-buf" nil nil)
566 (autoload 'TeX-view "tex-buf" nil t)
567
568 ;;; Portability.
569
570 (require 'easymenu)
571
572 (eval-and-compile
573   (if (featurep 'xemacs)
574       (defun TeX-maybe-remove-help (menu)
575       "Removes :help entries from menus, since XEmacs does not like them.
576 Also does other stuff."
577       (cond ((consp menu)
578              (cond ((eq (car menu) :help)
579                     (TeX-maybe-remove-help (cddr menu)))
580                    ((eq (car menu) :visible)
581                     (cons :included
582                           (cons (cadr menu)
583                                 (TeX-maybe-remove-help (cddr menu)))))
584                    (t (cons (TeX-maybe-remove-help (car menu))
585                             (TeX-maybe-remove-help (cdr menu))))))
586             ((vectorp menu)
587              (vconcat (TeX-maybe-remove-help (append menu nil))))
588             (t menu)))
589     (defun TeX-maybe-remove-help (menu)
590       "Compatibility function that would remove :help entries if on XEmacs,
591 but does nothing in Emacs."
592       menu))
593   (defmacro TeX-menu-with-help (menu)
594     "Compatibility macro that removes :help entries if on XEmacs.
595 Also does other stuff."
596     (TeX-maybe-remove-help menu)))
597
598 ;;;###autoload
599 (defalias 'TeX-assoc-string
600   (symbol-function  (if (featurep 'xemacs) 'assoc 'assoc-string)))
601
602 ;;; Documentation for Info-goto-emacs-command-node and similar
603
604 (eval-after-load 'info '(dolist (elt '("TeX" "LaTeX" "ConTeXt" "Texinfo"
605                                        "docTeX"))
606                           (add-to-list 'Info-file-list-for-emacs
607                                        (cons elt "AUCTeX"))))
608
609 (defadvice hack-one-local-variable (after TeX-hack-one-local-variable-after
610                                           activate)
611   "Call minor mode function if minor mode variable is found."
612   (let ((var (ad-get-arg 0))
613         (val (ad-get-arg 1)))
614     ;; Instead of checking for each mode explicitely `minor-mode-list'
615     ;; could be used.  But this may make the byte compiler pop up.
616     (when (memq var '(TeX-PDF-mode
617                       TeX-source-correlate-mode TeX-interactive-mode
618                       TeX-fold-mode LaTeX-math-mode))
619       (if (symbol-value val) (funcall var 1) (funcall var 0)))))
620
621 (defvar TeX-overlay-priority-step 16
622   "Numerical difference of priorities between nested overlays.
623 The step should be big enough to allow setting a priority for new
624 overlays between two existing ones.")
625
626
627 ;;; Special support for XEmacs
628
629 (when (featurep 'xemacs)
630
631   (defun TeX-read-string
632     (prompt &optional initial-input history default-value)
633     (condition-case nil
634         (read-string prompt initial-input history default-value t)
635       (wrong-number-of-arguments
636        (read-string prompt initial-input history default-value))))
637
638   (defun TeX-mark-active ()
639     ;; In Lucid (mark) returns nil when not active.
640     (if zmacs-regions
641         (mark)
642       (mark t)))
643
644   (defun TeX-active-mark ()
645     (and zmacs-regions (mark)))
646
647   (fset 'TeX-activate-region (symbol-function 'zmacs-activate-region))
648
649   ;; I am aware that this counteracts coding conventions but I am sick
650   ;; of it.
651   (unless (fboundp 'line-beginning-position)
652     (defalias 'line-beginning-position 'point-at-bol))
653   (unless (fboundp 'line-end-position)
654     (defalias 'line-end-position 'point-at-eol))
655
656   (defun TeX-overlay-prioritize (start end)
657     "Calculate a priority for an overlay extending from START to END.
658 The calculated priority is lower than the minimum of priorities
659 of surrounding overlays and higher than the maximum of enclosed
660 overlays."
661     (let (inner-priority outer-priority
662                          (prios (cons nil nil)))
663       (map-extents
664        #'(lambda (ov prios)
665            (and
666             (or (eq (extent-property ov 'category) 'TeX-fold)
667                 (extent-property ov 'preview-state))
668             (setcar prios
669                     (max (or (car prios) 0)
670                          (extent-property ov 'priority))))
671            nil)
672        nil start end prios 'start-and-end-in-region 'priority)
673       (map-extents
674        #'(lambda (ov prios)
675            (and
676             (or (eq (extent-property ov 'category) 'TeX-fold)
677                 (extent-property ov 'preview-state))
678             (setcdr prios
679                     (min (or (cdr prios) most-positive-fixnum)
680                          (extent-property ov 'priority))))
681            nil)
682        nil start end prios
683        '(start-and-end-in-region negate-in-region) 'priority)
684       (setq inner-priority (car prios) outer-priority (cdr prios))
685       (cond ((and inner-priority (not outer-priority))
686              (+ inner-priority TeX-overlay-priority-step))
687             ((and (not inner-priority) outer-priority)
688              (/ outer-priority 2))
689             ((and inner-priority outer-priority)
690              (+ (/ (- outer-priority inner-priority) 2) inner-priority))
691             (t TeX-overlay-priority-step)))) )
692
693 ;; require crm here, because we often do
694 ;;
695 ;; (let ((crm-separator ","))
696 ;;   (TeX-completing-read-multiple ...))
697 ;;
698 ;; which results in a void-variable error if crm hasn't been loaded before.
699 ;; XEmacs 21.4 `require' doesn't have the third NOERROR argument, thus we handle
700 ;; the file-error signal with a `condition-case' also in GNU Emacs.
701 (condition-case nil
702     (require 'crm)
703   (file-error
704    (error "AUCTeX requires crm.el which is included in Emacs and
705 edit-utils >= 2.32 for XEmacs.")))
706
707 (if (fboundp 'completing-read-multiple)
708     (defun TeX-completing-read-multiple
709         (prompt table &optional predicate require-match initial-input
710                 hist def inherit-input-method)
711       "Like `completing-read-multiple' which see.
712 Ensures that empty input results in nil across different emacs versions."
713       (let ((result (completing-read-multiple prompt table predicate
714                                               require-match initial-input
715                                               hist def inherit-input-method)))
716         (if (equal result '("")) nil result)))
717   (defun TeX-completing-read-multiple
718     (prompt table &optional predicate require-match initial-input
719             hist def inherit-input-method)
720     "Poor mans implementation of Emacs' `completing-read-multiple' for XEmacs.
721 The XEmacs package edit-utils-2.32 includes `crm.el'."
722     (multi-prompt (if (boundp 'crm-separator) crm-separator ",") nil prompt
723                   table predicate require-match initial-input hist)))
724
725 (if (fboundp 'line-number-at-pos)
726     (defalias 'TeX-line-number-at-pos 'line-number-at-pos)
727   ;; `line-number-at-pos' from `simple.el' in Emacs CVS (2006-06-07)
728   (defun TeX-line-number-at-pos (&optional pos)
729     "Return (narrowed) buffer line number at position POS.
730 If POS is nil, use current buffer location."
731     (let ((opoint (or pos (point))) start)
732       (save-excursion
733         (goto-char (point-min))
734         (setq start (point))
735         (goto-char opoint)
736         (forward-line 0)
737         (1+ (count-lines start (point)))))))
738
739 ;;; Special support for GNU Emacs
740
741 (unless (featurep 'xemacs)
742
743   (defun TeX-read-string (prompt &optional initial-input history default-value)
744     (read-string prompt initial-input history default-value t))
745
746   (defun TeX-mark-active ()
747     ;; In FSF 19 mark-active indicates if mark is active.
748     mark-active)
749
750   (defun TeX-active-mark ()
751     (and transient-mark-mode mark-active))
752
753   (defun TeX-activate-region ()
754     (setq deactivate-mark nil)
755     (activate-mark))
756
757   (defun TeX-overlay-prioritize (start end)
758     "Calculate a priority for an overlay extending from START to END.
759 The calculated priority is lower than the minimum of priorities
760 of surrounding overlays and higher than the maximum of enclosed
761 overlays."
762     (let (outer-priority inner-priority ov-priority)
763       (dolist (ov (overlays-in start end))
764         (when (or (eq (overlay-get ov 'category) 'TeX-fold)
765                   (overlay-get ov 'preview-state))
766           (setq ov-priority (overlay-get ov 'priority))
767           (if (>= (overlay-start ov) start)
768               (setq inner-priority (max ov-priority (or inner-priority
769                                                         ov-priority)))
770             (setq outer-priority (min ov-priority (or outer-priority
771                                                       ov-priority))))))
772       (cond ((and inner-priority (not outer-priority))
773              (+ inner-priority TeX-overlay-priority-step))
774             ((and (not inner-priority) outer-priority)
775              (/ outer-priority 2))
776             ((and inner-priority outer-priority)
777              (+ (/ (- outer-priority inner-priority) 2) inner-priority))
778             (t TeX-overlay-priority-step)))) )
779
780 (defun TeX-delete-dups-by-car (alist &optional keep-list)
781   "Return a list of all elements in ALIST, but each car only once.
782 Elements of KEEP-LIST are not removed even if duplicate."
783   ;; Copy of `reftex-uniquify-by-car' (written by David Kastrup).
784   (setq keep-list (sort (copy-sequence keep-list) #'string<))
785   (setq alist (sort (copy-sequence alist)
786                     (lambda (a b)
787                       (string< (car a) (car b)))))
788   (let ((new alist) elt)
789     (while new
790       (setq elt (caar new))
791       (while (and keep-list (string< (car keep-list) elt))
792         (setq keep-list (cdr keep-list)))
793       (unless (and keep-list (string= elt (car keep-list)))
794         (while (string= elt (car (cadr new)))
795           (setcdr new (cddr new))))
796       (setq new (cdr new))))
797   alist)
798
799 (defun TeX-delete-duplicate-strings (list)
800   "Return a list of all strings in LIST, but each only once."
801   (setq list (TeX-sort-strings list))
802   (let ((new list) elt)
803     (while new
804       (setq elt (car new))
805       (while (string= elt (cadr new))
806         (setcdr new (cddr new)))
807       (setq new (cdr new))))
808   list)
809
810 (defun TeX-sort-strings (list)
811   "Return sorted list of all strings in LIST."
812   (sort (copy-sequence list) #'string<))
813
814 ;;; Buffer
815
816 (defgroup TeX-output nil
817   "Parsing TeX output."
818   :prefix "TeX-"
819   :group 'AUCTeX)
820
821 (defcustom TeX-display-help t
822   "Control type of help display when stepping through errors with \\[TeX-next-error].
823 If t display help buffer.  If nil display message about error in
824 echo area.  If `expert' display output buffer with raw processor output."
825   :group 'TeX-output
826   :type '(choice (const :tag "Help buffer" t)
827                  (const :tag "Echo area" nil)
828                  (const :tag "Output buffer" expert)))
829
830 (defcustom TeX-debug-bad-boxes nil
831   "Non-nil means also find overfull/underfull box warnings with \\[TeX-next-error]."
832   :group 'TeX-output
833   :type 'boolean)
834
835 (defcustom TeX-debug-warnings nil
836   "Non-nil means also find LaTeX or package warnings with \\[TeX-next-error]."
837   :group 'TeX-output
838   :type 'boolean)
839
840 (defun TeX-toggle-debug-bad-boxes ()
841   "Toggle if the debugger should display \"bad boxes\" too."
842   (interactive)
843   (setq TeX-debug-bad-boxes (not TeX-debug-bad-boxes))
844   (message (concat "TeX-debug-bad-boxes: "
845                    (if TeX-debug-bad-boxes "on" "off"))))
846
847 (defun TeX-toggle-debug-warnings ()
848   "Toggle if the debugger should display warnings too."
849   (interactive)
850   (setq TeX-debug-warnings (not TeX-debug-warnings))
851   (message (concat "TeX-debug-warnings: "
852                    (if TeX-debug-warnings "on" "off"))))
853
854 ;;; Mode names.
855
856 (defvar TeX-base-mode-name nil
857   "Base name of mode.")
858 (make-variable-buffer-local 'TeX-base-mode-name)
859
860 (defun TeX-set-mode-name (&optional changed local reset)
861   "Build and set the mode name.
862 The base mode name will be concatenated with indicators for
863 helper modes where appropriate.
864
865 If CHANGED is non-nil, it indicates which global mode
866 may have changed so that all corresponding buffers
867 without a local value might get their name updated.
868 A value of t will thus update all buffer names.
869
870 If LOCAL is non-nil and CHANGED is buffer-local, only
871 a local change has been performed and only the local
872 name is to be updated.
873
874 If RESET is non-nil, `TeX-command-next' is reset to
875 `TeX-command-default' in updated buffers."
876   (if (and changed
877            (not (and local (local-variable-p changed (current-buffer)))))
878       (dolist (buffer (buffer-list))
879         (and (local-variable-p 'TeX-mode-p buffer)
880              (not (local-variable-p changed buffer))
881              (with-current-buffer buffer (TeX-set-mode-name nil nil reset))))
882     (if TeX-mode-p
883         (let ((trailing-flags
884                (concat
885                 (and (boundp 'TeX-fold-mode) TeX-fold-mode "F")
886                 (and (boundp 'LaTeX-math-mode) LaTeX-math-mode "M")
887                 (and TeX-PDF-mode "P")
888                 (and TeX-interactive-mode "I")
889                 (and TeX-source-correlate-mode "S"))))
890           (setq mode-name (concat TeX-base-mode-name
891                                   (when (> (length trailing-flags) 0)
892                                     (concat "/" trailing-flags))))
893           (when reset
894             (TeX-process-set-variable (TeX-master-file)
895                                       'TeX-command-next TeX-command-default)
896             (TeX-process-set-variable (TeX-region-file)
897                                       'TeX-command-next TeX-command-default))
898           (set-buffer-modified-p (buffer-modified-p))))))
899
900 (defun TeX-mode-prefix (&optional mode)
901   "Return the prefix for the symbol MODE as string.
902 If no mode is given the current major mode is used."
903   (cdr (assoc (or mode major-mode) '((plain-tex-mode . "plain-TeX")
904                                      (latex-mode . "LaTeX")
905                                      (doctex-mode . "docTeX")
906                                      (texinfo-mode . "Texinfo")
907                                      (context-mode . "ConTeXt")))))
908
909 ;;; Viewing
910
911 (defgroup TeX-view nil
912   "Calling viewers from AUCTeX."
913   :group 'TeX-command)
914
915 (defcustom TeX-view-style
916   `((,(concat
917       "^" (regexp-opt '("a4paper" "a4dutch" "a4wide" "sem-a4")) "$")
918      "%(o?)xdvi %dS -paper a4 %d")
919     (,(concat "^" (regexp-opt '("a5paper" "a5comb")) "$")
920      "%(o?)xdvi %dS -paper a5 %d")
921     ("^b5paper$" "%(o?)xdvi %dS -paper b5 %d")
922     ("^letterpaper$" "%(o?)xdvi %dS -paper us %d")
923     ("^legalpaper$" "%(o?)xdvi %dS -paper legal %d")
924     ("^executivepaper$" "%(o?)xdvi %dS -paper 7.25x10.5in %d")
925     ("^landscape$" "%(o?)xdvi %dS -paper a4r -s 0 %d")
926     ;; The latest xdvi can show embedded postscript.  If you don't
927     ;; have that, uncomment next line.
928     ;; ("^epsf$" "ghostview %f")
929     ("." "%(o?)xdvi %dS %d"))
930   "List of style options and view options.
931
932 If the first element (a regular expression) matches the name of
933 one of the style files, any occurrence of the string `%v' in a
934 command in `TeX-command-list' will be replaced with the second
935 element.  The first match is used, if no match is found the `%v'
936 is replaced with the empty string.
937
938 As a default, the \"View\" command in `TeX-command-list' is set
939 to `%V'.  This means that `TeX-output-view-style' will be
940 consulted before `TeX-view-style'.  Only if no match is found in
941 `TeX-output-view-style' the settings in `TeX-view-style' will be
942 considered.  If you want to bypass `TeX-output-view-style', which
943 is not recommended because it is more powerful than
944 `TeX-view-style', use `%v' in the \"View\" command."
945   :group 'TeX-view
946   :type '(repeat (group regexp (string :tag "Command"))))
947
948 (defcustom TeX-output-view-style
949   `(("^dvi$" ("^landscape$" "^pstricks$\\|^pst-\\|^psfrag$")
950      "%(o?)dvips -t landscape %d -o && gv %f")
951     ("^dvi$" "^pstricks$\\|^pst-\\|^psfrag$" "%(o?)dvips %d -o && gv %f")
952     ("^dvi$" (,(concat
953                 "^" (regexp-opt '("a4paper" "a4dutch" "a4wide" "sem-a4")) "$")
954               "^landscape$")
955      "%(o?)xdvi %dS -paper a4r -s 0 %d")
956     ("^dvi$" ,(concat
957                "^" (regexp-opt '("a4paper" "a4dutch" "a4wide" "sem-a4")) "$")
958      "%(o?)xdvi %dS -paper a4 %d")
959     ("^dvi$" (,(concat "^" (regexp-opt '("a5paper" "a5comb")) "$")
960               "^landscape$")
961      "%(o?)xdvi %dS -paper a5r -s 0 %d")
962     ("^dvi$" ,(concat "^" (regexp-opt '("a5paper" "a5comb")) "$")
963      "%(o?)xdvi %dS -paper a5 %d")
964     ("^dvi$" "^b5paper$" "%(o?)xdvi %dS -paper b5 %d")
965     ("^dvi$" "^letterpaper$" "%(o?)xdvi %dS -paper us %d")
966     ("^dvi$" "^legalpaper$" "%(o?)xdvi %dS -paper legal %d")
967     ("^dvi$" "^executivepaper$" "%(o?)xdvi %dS -paper 7.25x10.5in %d")
968     ("^dvi$" "." "%(o?)xdvi %dS %d")
969     ("^pdf$" "." "xpdf -remote %s -raise %o %(outpage)")
970     ("^html?$" "." "netscape %o"))
971   "List of output file extensions and view options.
972
973 If the first element (a regular expression) matches the output
974 file extension, and the second element (a regular expression)
975 matches the name of one of the style options, any occurrence of
976 the string `%V' in a command in `TeX-command-list' will be
977 replaced with the third element.  The first match is used; if no
978 match is found the `%V' is replaced with `%v'.  The outcome of `%v'
979 is determined by the settings in `TeX-view-style' which therefore
980 serves as a fallback for `TeX-output-view-style'.  The second
981 element may also be a list of regular expressions, in which case
982 all the regular expressions must match for the element to apply."
983   :group 'TeX-view
984   :type '(repeat (group
985                   (regexp :tag "Extension")
986                   (choice regexp (repeat :tag "List" regexp))
987                   (string :tag "Command"))))
988
989 ;;; Viewing (new implementation)
990
991 (defvar TeX-view-predicate-list-builtin
992   '((output-dvi
993      (string-match "dvi" (TeX-output-extension)))
994     (output-pdf
995      (string-match "pdf" (TeX-output-extension)))
996     (output-html
997      (string-match "html" (TeX-output-extension)))
998     (style-pstricks
999      (TeX-match-style "^pstricks$\\|^pst-\\|^psfrag$"))
1000     (engine-omega
1001      (eq TeX-engine 'omega))
1002     (engine-xetex
1003      (eq TeX-engine 'xetex))
1004     (mode-io-correlate
1005      TeX-source-correlate-mode)
1006     (paper-landscape
1007      (TeX-match-style "\\`landscape\\'"))
1008     (paper-portrait
1009      (not (TeX-match-style "\\`landscape\\'")))
1010     (paper-a4
1011      (TeX-match-style "\\`a4paper\\|a4dutch\\|a4wide\\|sem-a4\\'"))
1012     (paper-a5
1013      (TeX-match-style "\\`a5paper\\|a5comb\\'"))
1014     (paper-b5
1015      (TeX-match-style "\\`b5paper\\'"))
1016     (paper-letter
1017      (TeX-match-style "\\`letterpaper\\'"))
1018     (paper-legal
1019      (TeX-match-style "\\`legalpaper\\'"))
1020     (paper-executive
1021      (TeX-match-style "\\`executivepaper\\'")))
1022   "Alist of built-in predicates for viewer selection and invocation.
1023 See the doc string of `TeX-view-predicate-list' for a short
1024 description of each predicate.")
1025
1026 (defcustom TeX-view-predicate-list nil
1027   "Alist of predicates for viewer selection and invocation.
1028 The key of each list item is a symbol and the value a Lisp form
1029 to be evaluated.  The form should return nil if the predicate is
1030 not fulfilled.
1031
1032 Built-in predicates provided in `TeX-view-predicate-list-builtin'
1033 can be overwritten by defining predicates with the same symbol.
1034
1035 The following built-in predicates are available:
1036   `output-dvi': The output is a DVI file.
1037   `output-pdf': The output is a PDF file.
1038   `output-html': The output is an HTML file.
1039   `style-pstricks': The document loads a PSTricks package.
1040   `engine-omega': The Omega engine is used for typesetting.
1041   `engine-xetex': The XeTeX engine is used for typesetting.
1042   `mode-io-correlate': TeX Source Correlate mode is active.
1043   `paper-landscape': The document is typeset in landscape orientation.
1044   `paper-portrait': The document is not typeset in landscape orientation.
1045   `paper-a4': The paper format is A4.
1046   `paper-a5': The paper format is A5.
1047   `paper-b5': The paper format is B5.
1048   `paper-letter': The paper format is letter.
1049   `paper-legal': The paper format is legal.
1050   `paper-executive': The paper format is executive."
1051   :group 'TeX-view
1052   :type '(alist :key-type symbol :value-type (group sexp)))
1053
1054 ;; Require dbus at compile time to prevent errors due to `dbus-ignore-errors'
1055 ;; not being defined.
1056 (eval-when-compile (and (featurep 'dbusbind)
1057                         (require 'dbus nil :no-error)))
1058 (defun TeX-evince-dbus-p (&rest options)
1059   "Return non-nil, if evince is installed and accessible via DBUS.
1060 Additional OPTIONS may be given to extend the check.  If none are
1061 given, only the minimal requirements needed by backward search
1062 are checked.  If OPTIONS include `:forward', which is currently
1063 the only option, then additional requirements needed by forward
1064 search are checked, too."
1065   (and (featurep 'dbusbind)
1066        (require 'dbus nil :no-error)
1067        (dbus-ignore-errors (dbus-get-unique-name :session))
1068        (dbus-ping :session "org.gnome.evince.Daemon")
1069        (executable-find "evince")
1070        (or (not (memq :forward options))
1071            (let ((spec (dbus-introspect-get-method
1072                         :session "org.gnome.evince.Daemon"
1073                         "/org/gnome/evince/Daemon"
1074                         "org.gnome.evince.Daemon"
1075                         "FindDocument")))
1076              ;; FindDocument must exist, and its signature must be (String,
1077              ;; Boolean, String).  Evince versions between 2.30 and 2.91.x
1078              ;; didn't have the Boolean spawn argument we need to start evince
1079              ;; initially.
1080              (and spec
1081                   (equal '("s" "b" "s")
1082                          (delq nil (mapcar (lambda (elem)
1083                                              (when (and (listp elem)
1084                                                         (eq (car elem) 'arg))
1085                                                (cdr (caar (cdr elem)))))
1086                                            spec))))))))
1087
1088 (defun TeX-evince-sync-view ()
1089   "Focus the focused page/paragraph in Evince with the position
1090 of point in emacs by using Evince's DBUS API.  Used by default
1091 for the Evince viewer entry in `TeX-view-program-list-builtin' if
1092 the requirements are met."
1093   (require 'url-util)
1094   (let* ((uri (concat "file://" (let ((url-unreserved-chars (cons ?/ url-unreserved-chars)))
1095                                   (url-hexify-string
1096                                    (expand-file-name
1097                                     (concat file "." (TeX-output-extension)))))))
1098          (owner (dbus-call-method
1099                  :session "org.gnome.evince.Daemon"
1100                  "/org/gnome/evince/Daemon"
1101                  "org.gnome.evince.Daemon"
1102                  "FindDocument"
1103                  uri
1104                  t)))
1105     (if owner
1106         (dbus-call-method
1107          :session owner
1108          "/org/gnome/evince/Window/0"
1109          "org.gnome.evince.Window"
1110          "SyncView"
1111          (buffer-file-name)
1112          (list :struct :int32 (line-number-at-pos) :int32 (1+ (current-column)))
1113          :uint32 0)
1114       (error "Couldn't find the Evince instance for %s" uri))))
1115
1116 (defvar TeX-view-program-list-builtin
1117   (cond
1118    ((eq system-type 'windows-nt)
1119     '(("Yap" ("yap -1" (mode-io-correlate " -s %n%b") " %o"))
1120       ("dvips and start" "dvips %d -o && start \"\" %f")
1121       ("start" "start \"\" %o")))
1122    ((eq system-type 'darwin)
1123     '(("Preview.app" "open -a Preview.app %o")
1124       ("Skim" "open -a Skim.app %o")
1125       ("displayline" "displayline %n %o %b")
1126       ("open" "open %o")))
1127    (t
1128     `(("xdvi" ("%(o?)xdvi"
1129                (mode-io-correlate " -sourceposition \"%n %b\" -editor \"%cS\"")
1130                ((paper-a4 paper-portrait) " -paper a4")
1131                ((paper-a4 paper-landscape) " -paper a4r")
1132                ((paper-a5 paper-portrait) " -paper a5")
1133                ((paper-a5 paper-landscape) " -paper a5r")
1134                (paper-b5 " -paper b5")
1135                (paper-letter " -paper us")
1136                (paper-legal " -paper legal")
1137                (paper-executive " -paper 7.25x10.5in")
1138                " %d"))
1139       ("dvips and gv" "%(o?)dvips %d -o && gv %f")
1140       ("gv" "gv %o")
1141       ("xpdf" ("xpdf -remote %s -raise %o" (mode-io-correlate " %(outpage)")))
1142       ("Evince" ,(if (TeX-evince-dbus-p :forward)
1143                      'TeX-evince-sync-view
1144                    `("evince" (mode-io-correlate
1145                                ;; With evince 3, -p N opens the page *labeled* N,
1146                                ;; and -i,--page-index the physical page N.
1147                                ,(if (string-match "--page-index"
1148                                                   (shell-command-to-string "evince --help"))
1149                                     " -i %(outpage)"
1150                                   " -p %(outpage)")) " %o")))
1151       ("Okular" ("okular --unique %o" (mode-io-correlate "#src:%n%a")))
1152       ("xdg-open" "xdg-open %o"))))
1153   "Alist of built-in viewer specifications.
1154 This variable should not be changed by the user who can use
1155 `TeX-view-program-list' to add new viewers or overwrite the
1156 definition of built-in ones.  The latter variable also contains a
1157 description of the data format.")
1158
1159 (defcustom TeX-view-program-list nil
1160   "Alist of viewer specifications.
1161 This variable can be used to specify how a viewer is to be
1162 invoked and thereby add new viewers on top of the built-in list
1163 of viewers defined in `TeX-view-program-list-builtin' or override
1164 entries in the latter.
1165
1166 The car of each item is a string with a user-readable name.  The
1167 second element can be a command line to be run as a process or a
1168 Lisp function to be executed.  The command line can either be
1169 specified as a single string or a list of strings and two-part
1170 lists.  The first element of the two-part lists is a symbol or a
1171 list of symbols referring to one or more of the predicates in
1172 `TeX-view-predicate-list' or `TeX-view-predicate-list-builtin'.
1173 The second part of the two-part lists is a command line part.
1174 The command line for the viewer is constructed by concatenating
1175 the command line parts.  Parts with a predicate are only
1176 considered if the predicate was evaluated with a positive result.
1177 Note that the command line can contain placeholders as defined in
1178 `TeX-expand-list' which are expanded before the viewer is called.
1179
1180 The use of a function as the second element only works if the
1181 View command in `TeX-command-list' makes use of the hook
1182 `TeX-run-discard-or-function'.
1183
1184 Note: Predicates defined in the current Emacs session will only
1185 show up in the customization interface for this variable after
1186 restarting Emacs."
1187   :group 'TeX-view
1188   :type
1189   `(alist
1190     :key-type (string :tag "Name")
1191     :value-type
1192     (choice
1193      (group :tag "Command" (string :tag "Command"))
1194      (group :tag "Command parts"
1195             (repeat
1196              :tag "Command parts"
1197              (choice
1198               (string :tag "Command part")
1199               (list :tag "Predicate and command part"
1200                     ,(let (list)
1201                        ;; Build the list of available predicates.
1202                        (mapc (lambda (spec)
1203                                (add-to-list 'list `(const ,(car spec))))
1204                              (append TeX-view-predicate-list
1205                                      TeX-view-predicate-list-builtin))
1206                        ;; Sort the list alphabetically.
1207                        (setq list (sort list
1208                                         (lambda (a b)
1209                                           (string<
1210                                            (downcase (symbol-name (cadr a)))
1211                                            (downcase (symbol-name (cadr b)))))))
1212                        `(choice
1213                          (choice :tag "Predicate" ,@list)
1214                          (repeat :tag "List of predicates"
1215                                  (choice :tag "Predicate" ,@list))))
1216                     (string :tag "Command part")))))
1217      (group :tag "Function" function))))
1218
1219 ;; XXX: Regarding a possibility to (manually) run an update command,
1220 ;; one could support this through `TeX-view' by letting it temporarily
1221 ;; set a variable which is checked with a predicate in the viewer
1222 ;; selection.  If the check is positive, the update command is run
1223 ;; instead of the normal viewer command.  Direct support through the
1224 ;; View command would require a predicate which knows when an update
1225 ;; has to be done.
1226 (defcustom TeX-view-program-selection
1227   (cond
1228    ((eq system-type 'windows-nt)
1229     '(((output-dvi style-pstricks) "dvips and start")
1230       (output-dvi "Yap")
1231       (output-pdf "start")
1232       (output-html "start")))
1233    ((eq system-type 'darwin)
1234     '((output-dvi "open")
1235       (output-pdf "open")
1236       (output-html "open")))
1237    (t
1238     '(((output-dvi style-pstricks) "dvips and gv")
1239       (output-dvi "xdvi")
1240       (output-pdf "Evince")
1241       (output-html "xdg-open"))))
1242   "Alist of predicates and viewers.
1243 Each entry consists of a list with two elements.  The first
1244 element is a symbol or list of symbols referring to predicates as
1245 defined in `TeX-view-predicate-list' or
1246 `TeX-view-predicate-list-builtin'.  The second element is a
1247 string referring to the name of a viewer as defined in
1248 `TeX-view-program-list' or `TeX-view-program-list-builtin'.
1249 \(Note: Viewers added to `TeX-view-program-list' in the current
1250 Emacs session will not show up in the customization interface of
1251 `TeX-view-program-selection' until you restart Emacs.)
1252
1253 When a viewer is called for, the entries are evaluated in turn
1254 and the viewer related to the first entry all predicates of which
1255 are evaluated positively is chosen."
1256   :group 'TeX-view
1257   :type `(alist :key-type
1258                 ;; Offer list of defined predicates.
1259                 ,(let (list)
1260                    (mapc (lambda (spec)
1261                            (add-to-list 'list `(const ,(car spec))))
1262                          (append TeX-view-predicate-list
1263                                  TeX-view-predicate-list-builtin))
1264                    (setq list (sort list
1265                                     (lambda (a b)
1266                                       (string<
1267                                        (downcase (symbol-name (cadr a)))
1268                                        (downcase (symbol-name (cadr b)))))))
1269                    `(choice (choice :tag "Single predicate" ,@list)
1270                             (repeat :tag "Multiple predicates"
1271                                     (choice ,@list))))
1272                 :value-type
1273                 ;; Offer list of defined viewers.
1274                 (group (choice :tag "Viewer"
1275                                ,@(let (list)
1276                                    (mapc (lambda (spec)
1277                                            (add-to-list 'list
1278                                                         `(const ,(car spec))))
1279                                      (append TeX-view-program-list
1280                                              TeX-view-program-list-builtin))
1281                                    (sort list
1282                                          (lambda (a b)
1283                                            (string< (downcase (cadr a))
1284                                                     (downcase (cadr b))))))))))
1285
1286 (defun TeX-match-style (regexp)
1287   "Check if a style matching REGEXP is active."
1288   (TeX-member regexp (TeX-style-list) 'string-match))
1289
1290 (defun TeX-view-match-predicate (predicate)
1291   "Check if PREDICATE is true.
1292 PREDICATE can be a symbol or a list of symbols defined in
1293 `TeX-view-predicate-list-builtin' or `TeX-view-predicate-list'.
1294 In case of a single symbol, return t if the predicate is true,
1295 nil otherwise.  In case of a list of symbols, return t if all
1296 predicates are true, nil otherwise."
1297   (let ((pred-symbols (if (listp predicate) predicate (list predicate)))
1298         (pred-defs (append TeX-view-predicate-list
1299                            TeX-view-predicate-list-builtin))
1300         (result t)
1301         elt)
1302     (while (and (setq elt (pop pred-symbols)) result)
1303       (unless (eval (cadr (assq elt pred-defs)))
1304         (setq result nil)))
1305     result))
1306
1307 (defun TeX-view-command-raw ()
1308   "Choose a viewer and return its unexpanded command string."
1309   (let ((selection TeX-view-program-selection)
1310         entry viewer spec command)
1311     ;; Find the appropriate viewer.
1312     (while (and (setq entry (pop selection)) (not viewer))
1313       (when (TeX-view-match-predicate (car entry))
1314         (setq viewer (cadr entry))))
1315     (unless viewer
1316       (error "No matching viewer found"))
1317     ;; Get the command line or function spec.
1318     (setq spec (cadr (assoc viewer (append TeX-view-program-list
1319                                            TeX-view-program-list-builtin))))
1320     (cond ((functionp spec)
1321            ;; Converting the function call to a string is ugly, but
1322            ;; the backend currently only supports strings.
1323            (prin1-to-string spec))
1324           ((stringp spec)
1325            spec)
1326           ((null spec)
1327            (error
1328             (format "Unknown %S viewer. \
1329 Check the `TeX-view-program-selection' variable." viewer)))
1330           (t
1331            ;; Build the unexpanded command line.  Pieces with predicates are
1332            ;; only added if the predicate is evaluated positively.
1333            (dolist (elt spec)
1334              (cond ((stringp elt)
1335                     (setq command (concat command elt)))
1336                    ((listp elt)
1337                     (when (TeX-view-match-predicate (car elt))
1338                       (setq command (concat command (cadr elt)))))))
1339            command))))
1340
1341 ;;; Engine
1342
1343 (defvar TeX-engine-alist-builtin
1344   '((default "Default" TeX-command LaTeX-command ConTeXt-engine)
1345     (xetex "XeTeX" "xetex" "xelatex" "xetex")
1346     ;; Some lualatex versions before 0.71 would use "texput" as file
1347     ;; name if --jobname were not supplied
1348     (luatex "LuaTeX" "luatex" "lualatex --jobname=%s" "luatex")
1349     (omega "Omega" TeX-Omega-command LaTeX-Omega-command ConTeXt-Omega-engine))
1350   "Alist of built-in TeX engines and associated commands.
1351 For a description of the format see `TeX-engine-alist'.")
1352
1353 (defcustom TeX-engine-alist nil
1354   "Alist of TeX engines and associated commands.
1355 Each entry is a list with a maximum of five elements.  The first
1356 element is a symbol used to identify the engine.  The second is a
1357 string describing the engine.  The third is the command to be
1358 used for plain TeX.  The fourth is the command to be used for
1359 LaTeX.  The fifth is the command to be used for the --engine
1360 parameter of ConTeXt's texexec program.  Each command can either
1361 be a variable or a string.  An empty string or nil means there is
1362 no command available.
1363
1364 You can override a built-in engine defined in the variable
1365 `TeX-engine-alist-builtin' by adding an entry beginning with the
1366 same symbol as the built-in entry to `TeX-engine-alist'."
1367   :group 'TeX-command
1368   :type '(repeat (group symbol
1369                         (string :tag "Name")
1370                         (choice :tag "Plain TeX command" string variable)
1371                         (choice :tag "LaTeX command" string variable)
1372                         (choice :tag "ConTeXt command" string variable))))
1373
1374 (defun TeX-engine-alist ()
1375   "Return an alist of TeX engines.
1376 The function appends the built-in engine specs from
1377 `TeX-engine-alist-builtin' and the user-defined engines from
1378 `TeX-engine-alist' and deletes any entries from the built-in part
1379 where an entry with the same car exists in the user-defined part."
1380   (TeX-delete-dups-by-car (append TeX-engine-alist TeX-engine-alist-builtin)))
1381
1382 (defcustom TeX-engine 'default
1383   (concat "Type of TeX engine to use.
1384 It should be one of the following symbols:\n\n"
1385           (mapconcat (lambda (x) (format "* `%s'" (car x)))
1386                      (TeX-engine-alist) "\n"))
1387   :group 'TeX-command
1388   :type `(choice ,@(mapcar (lambda (x)
1389                              `(const :tag ,(nth 1 x) ,(car x)))
1390                            (TeX-engine-alist))))
1391 (make-variable-buffer-local 'TeX-engine)
1392 (put 'TeX-engine 'safe-local-variable
1393      (lambda (arg) (memq arg (mapcar 'car TeX-engine-alist-builtin))))
1394
1395 (defun TeX-engine-set (type)
1396   "Set TeX engine to TYPE.
1397 For available TYPEs, see variable `TeX-engine'."
1398   (interactive (list (completing-read "Engine: "
1399                                       (mapcar (lambda (x)
1400                                                 (symbol-name (car x)))
1401                                               (TeX-engine-alist))
1402                                       nil t)))
1403   (when (stringp type)
1404     (setq type (intern type)))
1405   (setq TeX-engine type)
1406   ;; Automatically enable or disable TeX PDF mode as a convenience
1407   (cond ((eq type 'xetex) (TeX-PDF-mode 1))
1408         ((eq type 'omega) (TeX-PDF-mode 0))))
1409
1410 (define-minor-mode TeX-Omega-mode
1411   "Minor mode for using the Omega engine."
1412   nil nil nil
1413   :group 'TeX-command
1414   (TeX-engine-set (if TeX-Omega-mode 'omega 'default)))
1415 (defalias 'tex-omega-mode 'TeX-Omega-mode)
1416 (make-obsolete 'TeX-Omega-mode 'TeX-engine-set "11.86")
1417 (make-obsolete-variable 'TeX-Omega-mode 'TeX-engine "11.86")
1418
1419 ;;; Forward and inverse search
1420
1421 (defcustom TeX-source-correlate-method
1422   '((dvi . source-specials) (pdf . synctex))
1423   "Method to use for enabling forward and inverse search.
1424 This can be `source-specials' if source specials should be used,
1425 `synctex' if SyncTeX should be used, or `auto' if AUCTeX should
1426 decide.
1427
1428 The previous values determine the variable for both DVI and PDF
1429 mode.  This variable can also be an alist of the kind
1430
1431   ((dvi . <source-specials or synctex>)
1432    (pdf . <source-specials or synctex>))
1433
1434 in which the CDR of each entry is a symbol specifying the method
1435 to be used in the corresponding mode.
1436
1437 Programs should not use this variable directly but the function
1438 `TeX-source-correlate-method-active' which returns the method
1439 actually used for forward and inverse search."
1440   :type '(choice (const auto)
1441                  (const synctex)
1442                  (const source-specials)
1443                  (list :tag "Different method for DVI and PDF"
1444                        (cons (const dvi)
1445                              (choice :tag "Method for DVI mode"
1446                                      (const synctex)
1447                                      (const source-specials)))
1448                        (cons (const pdf)
1449                              (choice :tag "Method for PDF mode"
1450                                      (const synctex)
1451                                      (const source-specials)))))
1452   :group 'TeX-view)
1453
1454 (defvar TeX-source-correlate-output-page-function nil
1455   "Symbol of function returning an output page relating to buffer position.
1456 The function should take no arguments and return the page numer
1457 as a string.")
1458 (make-variable-buffer-local 'TeX-source-correlate-output-page-function)
1459
1460 (defcustom TeX-source-correlate-start-server 'ask
1461   "Control if server should be started for inverse search."
1462   :type '(choice (const :tag "Always" t)
1463                  (const :tag "Never" nil)
1464                  (const :tag "Ask" ask))
1465   :group 'TeX-view)
1466 (when (fboundp 'defvaralias)
1467   (defvaralias 'TeX-source-specials-view-start-server
1468     'TeX-source-correlate-start-server))
1469
1470 (defvar TeX-source-correlate-start-server-asked nil
1471   "Keep track if question about server start search was asked.")
1472
1473 (defvar TeX-source-correlate-start-server-flag nil
1474   "If non-nil, `TeX-source-correlate-start-server-maybe' will start a server.
1475 Code related to features requiring a server, e.g. for inverse
1476 search, can set the variable.")
1477
1478 (defun TeX-source-correlate-gnuserv-p ()
1479   "Guess whether to use gnuserv when a server is requested."
1480   (cond ((and (boundp 'gnuserv-process)
1481               (processp gnuserv-process)))
1482         ((and (boundp 'server-process)
1483               (processp server-process))
1484          nil)
1485         ((featurep 'xemacs))))
1486
1487 (defun TeX-source-correlate-server-enabled-p ()
1488   "Return non-nil if Emacs server or gnuserv is enabled."
1489   (let* ((gnuserv-p (TeX-source-correlate-gnuserv-p))
1490          (process (if gnuserv-p 'gnuserv-process 'server-process)))
1491     (and (boundp process) (processp (symbol-value process)))))
1492
1493 (defun TeX-source-correlate-start-server-maybe ()
1494   "Start Emacs server or gnuserv if a feature using it is enabled.
1495 This is the case if `TeX-source-correlate-start-server-flag' is non-nil."
1496   (when (and TeX-source-correlate-start-server-flag
1497              (not (TeX-source-correlate-server-enabled-p)))
1498     (let* ((gnuserv-p (TeX-source-correlate-gnuserv-p))
1499            (start (if gnuserv-p 'gnuserv-start 'server-start)))
1500       (cond
1501        ;; Server should be started unconditionally
1502        ((eq TeX-source-correlate-start-server t)
1503         (funcall start))
1504        ;; Ask user if server is to be started
1505        ((and (eq TeX-source-correlate-start-server 'ask)
1506              (not TeX-source-correlate-start-server-asked)
1507              (prog1
1508                  (y-or-n-p (format "Start %s for inverse search in viewer? "
1509                                    (if gnuserv-p
1510                                        "gnuserv"
1511                                      "Emacs server")))
1512                (setq TeX-source-correlate-start-server-asked t)))
1513         (funcall start))))))
1514
1515 (defun TeX-source-correlate-determine-method ()
1516   "Determine which method is available for forward and inverse search."
1517   (let ((help (condition-case nil
1518                   (with-output-to-string
1519                     (call-process LaTeX-command
1520                                   nil (list standard-output nil) nil "--help"))
1521                 (error ""))))
1522     (if (string-match "^[ ]*-?-synctex" help)
1523         'synctex
1524       'source-specials)))
1525
1526 (defun TeX-source-correlate-method-active ()
1527   "Return the method actually used for forward and inverse search."
1528   (cond
1529    ((eq TeX-source-correlate-method 'auto)
1530     (TeX-source-correlate-determine-method))
1531    ((listp TeX-source-correlate-method)
1532     (if TeX-PDF-mode
1533         (cdr (assoc 'pdf TeX-source-correlate-method))
1534       (cdr (assoc 'dvi TeX-source-correlate-method))))
1535    (t
1536     TeX-source-correlate-method)))
1537
1538 (defun TeX-source-correlate-expand-options ()
1539   "Return TeX engine command line option for forward search facilities.
1540 The return value depends on the value of `TeX-source-correlate-mode'.
1541 If this is nil, an empty string will be returned."
1542   (if TeX-source-correlate-mode
1543       (if (eq (TeX-source-correlate-method-active) 'source-specials)
1544           (concat TeX-source-specials-tex-flags
1545                   (if TeX-source-specials-places
1546                       ;; -src-specials=WHERE: insert source specials
1547                       ;; in certain places of the DVI file. WHERE is a
1548                       ;; comma-separated value list: cr display hbox
1549                       ;; math par parend vbox
1550                       (concat "=" (mapconcat 'identity
1551                                              TeX-source-specials-places ","))))
1552         TeX-synctex-tex-flags)
1553     ""))
1554
1555 (defvar TeX-source-correlate-map
1556   (let ((map (make-sparse-keymap)))
1557     ;; (if (featurep 'xemacs)
1558     ;;     (define-key map [(control button1)] #'TeX-view-mouse)
1559     ;;   (define-key map [C-down-mouse-1] #'TeX-view-mouse))
1560     map)
1561   "Keymap for `TeX-source-correlate-mode'.
1562 You could use this for unusual mouse bindings.")
1563
1564 (defun TeX-source-correlate-sync-source (file linecol &rest ignored)
1565   "Show TeX FILE with point at LINECOL.
1566 This function is called when emacs receives a SyncSource signal
1567 emitted from the Evince document viewer.  IGNORED absorbs an
1568 unused id field accompanying the DBUS signal sent by Evince-3.0.0
1569 or newer."
1570   ;; FILE may be given as relative path to the TeX-master root document or as
1571   ;; absolute file:// URL.  In the former case, the tex file has to be already
1572   ;; opened.
1573   (let ((buf (let ((f (condition-case nil
1574                           (progn
1575                             (require 'url-parse)
1576                             (require 'url-util)
1577                             (url-unhex-string (aref (url-generic-parse-url file) 6)))
1578                         ;; For Emacs 21 compatibility, which doesn't have the
1579                         ;; url package.
1580                         (file-error (replace-regexp-in-string "^file://" "" file)))))
1581                (if (file-name-absolute-p f)
1582                    (find-file f)
1583                  (get-buffer (file-name-nondirectory file)))))
1584         (line (car linecol))
1585         (col (cadr linecol)))
1586     (if (null buf)
1587         (message "No buffer for %s." file)
1588       (switch-to-buffer buf)
1589       (push-mark (point) 'nomsg)
1590       (goto-char (point-min))
1591       (forward-line (1- line))
1592       (unless (= col -1)
1593         (move-to-column col))
1594       (raise-frame))))
1595
1596 (define-minor-mode TeX-source-correlate-mode
1597   "Minor mode for forward and inverse search.
1598
1599 If enabled, the viewer can be advised to show the output page
1600 corresponding to the point in the source and vice versa.
1601
1602 The method to be used can be controlled with the variable
1603 `TeX-source-correlate-method'.  Currently source specials or
1604 SyncTeX are recognized."
1605   :group 'TeX-view
1606   ;; Since this is a global minor mode and we don't want to require
1607   ;; tex.el when the mode variable is set, the mode function is called
1608   ;; explicitely (if necessary) in `VirTeX-common-initialization'.  We
1609   ;; do it there because otherwise `kill-all-local-variables' would
1610   ;; reset `TeX-source-correlate-output-page-function' which is
1611   ;; buffer-local.
1612   :global t
1613   (set-keymap-parent TeX-mode-map (and TeX-source-correlate-mode
1614                                        TeX-source-correlate-map))
1615   (TeX-set-mode-name 'TeX-source-correlate-mode t t)
1616   (setq TeX-source-correlate-start-server-flag TeX-source-correlate-mode)
1617   ;; Register Emacs for the SyncSource DBUS signal emitted by Evince.
1618   (when (TeX-evince-dbus-p)
1619     (dbus-register-signal
1620      :session nil "/org/gnome/evince/Window/0"
1621      "org.gnome.evince.Window" "SyncSource"
1622      'TeX-source-correlate-sync-source)))
1623
1624 (defalias 'TeX-source-specials-mode 'TeX-source-correlate-mode)
1625 (make-obsolete 'TeX-source-specials-mode 'TeX-source-correlate-mode "11.86")
1626 (defalias 'tex-source-correlate-mode 'TeX-source-correlate-mode)
1627 (put 'TeX-source-correlate-mode 'safe-local-variable 'TeX-booleanp)
1628 ;; We do not want the custom variable to require tex.el.  This is only
1629 ;; necessary if AUCTeX was compiled with Emacs 21.
1630 (put 'TeX-source-correlate-mode 'custom-requests nil)
1631 (setq minor-mode-map-alist
1632       (delq (assq 'TeX-source-correlate-mode minor-mode-map-alist)
1633             minor-mode-map-alist))
1634
1635
1636 ;;; Source Specials
1637
1638 (defcustom TeX-source-specials-tex-flags "-src-specials"
1639   "Extra flags to pass to TeX commands to generate source specials."
1640   :group 'TeX-view
1641   :type 'string)
1642
1643 (defcustom TeX-source-specials-places nil
1644   "List of places where to insert source specials into the DVI file.
1645 If nil, use (La)TeX's defaults."
1646   :group 'TeX-view
1647   :type '(list (set :inline t
1648                     ;; :tag "Options known to work"
1649                     ;; cr display hbox math par parend vbox
1650                     (const "cr")
1651                     (const "display")
1652                     (const "hbox")
1653                     (const "math")
1654                     (const "par")
1655                     (const "parend")
1656                     (const "vbox"))
1657                (repeat :inline t
1658                        :tag "Other options"
1659                        (string))))
1660
1661 (defcustom TeX-source-specials-view-position-flags
1662   "-sourceposition \"%n %b\""
1663   "Flags to pass to the DVI viewer commands for the position in the source."
1664   :group 'TeX-view
1665   :type 'string)
1666
1667 (defcustom TeX-source-specials-view-editor-flags
1668   "-editor \"%cS\""
1669   "Flags to pass to DVI viewer commands for inverse search."
1670   :group 'TeX-view
1671   :type 'string)
1672
1673 (defcustom TeX-source-specials-view-gnuclient-flags
1674   "-q +%%l %%f"
1675   "Flags to pass to gnuclient for inverse search."
1676   :group 'TeX-view
1677   :type 'string)
1678
1679 (defcustom TeX-source-specials-view-emacsclient-flags
1680   "--no-wait +%%l %%f"
1681   "Flags to emacsclient for inverse search."
1682   :group 'TeX-view
1683   :type 'string)
1684
1685 ;; FIXME: Make client binaries configurable.
1686 (defun TeX-source-specials-view-expand-client ()
1687   "Return gnuclient or emacslient executable with options.
1688 Return the full path to the executable if possible."
1689   (let* ((gnuserv-p (TeX-source-correlate-gnuserv-p))
1690          (client-base (if gnuserv-p
1691                           "gnuclient"
1692                         "emacsclient"))
1693          (client-full (and invocation-directory
1694                            (expand-file-name client-base
1695                                              invocation-directory)))
1696          (options (if gnuserv-p
1697                       TeX-source-specials-view-gnuclient-flags
1698                     TeX-source-specials-view-emacsclient-flags)))
1699     (if (and client-full (file-executable-p client-full))
1700         (concat client-full " " options)
1701       (concat client-base " " options))))
1702
1703 (defun TeX-source-specials-view-expand-options (&optional viewer)
1704   "Return source specials command line option for viewer command.
1705 The return value depends on the values of
1706 `TeX-source-correlate-mode' and
1707 `TeX-source-correlate-method-active'.  If those are nil or not
1708 `source-specials' respectively, an empty string will be
1709 returned."
1710   (if (and TeX-source-correlate-mode
1711            (eq (TeX-source-correlate-method-active) 'source-specials))
1712       (concat TeX-source-specials-view-position-flags
1713               (when (TeX-source-correlate-server-enabled-p)
1714                 (concat " " TeX-source-specials-view-editor-flags)))
1715     ""))
1716
1717 ;;; SyncTeX
1718
1719 (defvar TeX-synctex-tex-flags "--synctex=1"
1720   "Extra flags to pass to TeX commands to enable SyncTeX.")
1721
1722 (defun TeX-synctex-output-page-1 (file)
1723   "Return the page corresponding to the current position in FILE.
1724 This method assumes that the document was compiled with SyncTeX
1725 enabled and the `synctex' binary is available."
1726   (let ((synctex-output
1727          (with-output-to-string
1728            (call-process "synctex" nil (list standard-output nil) nil "view"
1729                          "-i" (format "%s:%s:%s" (line-number-at-pos)
1730                                       (current-column)
1731                                       file)
1732                          "-o" (TeX-active-master (TeX-output-extension))))))
1733     (when (string-match "Page:\\([0-9]+\\)" synctex-output)
1734       (match-string 1 synctex-output))))
1735
1736 (defun TeX-synctex-output-page ()
1737   "Return the page corresponding to the position in the current buffer.
1738 This method assumes that the document was compiled with SyncTeX
1739 enabled and the `synctex' binary is available."
1740   (let* ((file (file-relative-name (buffer-file-name)
1741                                    (file-name-directory
1742                                     (TeX-active-master))))
1743          (abs-file (concat (expand-file-name (or (file-name-directory (TeX-active-master))
1744                                                  (file-name-directory (buffer-file-name))))
1745                            "./" file)))
1746     ;; It's known that depending on synctex version one of
1747     ;; /absolute/path/./foo/bar.tex, foo/bar.tex, or ./foo/bar.tex (relative to
1748     ;; TeX-master, and the "." in the absolute path is important) are needed.
1749     ;; So try all variants before falling back to page 1.
1750     (or (TeX-synctex-output-page-1 abs-file)
1751         (TeX-synctex-output-page-1 file)
1752         (TeX-synctex-output-page-1 (concat "./" file))
1753         "1")))
1754
1755 ;;; Miscellaneous minor modes
1756
1757 (defvar TeX-mode-p nil
1758   "This indicates a TeX mode being active.")
1759 (make-variable-buffer-local 'TeX-mode-p)
1760
1761 (defun TeX-mode-set (var value)
1762   (set-default var value)
1763   (TeX-set-mode-name var nil t))
1764
1765 (defcustom TeX-PDF-mode t nil
1766   :group 'TeX-command
1767   :set 'TeX-mode-set
1768   :type 'boolean)
1769 (put 'TeX-PDF-mode 'safe-local-variable 'TeX-booleanp)
1770
1771 (define-minor-mode TeX-PDF-mode
1772   "Minor mode for using PDFTeX.
1773
1774 If enabled, PDFTeX will be used as an executable by default.
1775 You can customize an initial value, and you can use the
1776 function `TeX-global-PDF-mode' for toggling this value."
1777   :group 'TeX-command
1778   (when (eq TeX-engine 'omega)
1779     (setq TeX-PDF-mode nil))
1780   (setq TeX-PDF-mode-parsed nil)
1781   (TeX-set-mode-name nil nil t)
1782   (setq TeX-output-extension
1783         (if TeX-PDF-mode "pdf" "dvi")))
1784 (add-to-list 'minor-mode-alist '(TeX-PDF-mode ""))
1785
1786 (defun TeX-global-PDF-mode (&optional arg)
1787   "Toggle default for `TeX-PDF-mode'."
1788   (interactive "P")
1789   (prog1
1790       (setq-default TeX-PDF-mode
1791                     (if arg (> (prefix-numeric-value arg) 0)
1792                       (not (default-value 'TeX-PDF-mode))))
1793     (TeX-set-mode-name 'TeX-PDF-mode nil t)))
1794
1795 (defalias 'tex-pdf-mode 'TeX-PDF-mode)
1796
1797 (defvar TeX-PDF-mode-parsed nil
1798   "Set if `TeX-PDF-mode' has come about by parsing.")
1799
1800 (make-variable-buffer-local 'TeX-PDF-mode-parsed)
1801
1802 (defun TeX-PDF-mode-parsed (arg)
1803   "Change `TeX-PDF-mode' to ARG based on parsing.
1804 If this conflicts with previous parsed settings,
1805 just use the default.  If an explicit setting is
1806 already established, don't do anything."
1807
1808 ;; Basically we have the following situations:
1809 ;; TeX-PDF-mode-parsed (local-variable-p 'TeX-PDF-mode):
1810 ;; nil nil : virgin state
1811 ;; nil t   : stably set state (possibly because of conflicting parse info)
1812 ;; t   t   : non-conflicting parsed info
1813
1814   (if TeX-PDF-mode-parsed
1815       (unless (eq TeX-PDF-mode arg)
1816         (TeX-PDF-mode (if (default-value 'TeX-PDF-mode) 1 0)))
1817     (unless (local-variable-p 'TeX-PDF-mode (current-buffer))
1818       (TeX-PDF-mode (if arg 1 0))
1819       (setq TeX-PDF-mode-parsed t))))
1820
1821 (defun TeX-PDF-mode-on ()
1822   "Use only from parsing routines."
1823   (TeX-PDF-mode-parsed t))
1824
1825 (defun TeX-PDF-mode-off ()
1826   "Use only from parsing routines."
1827   (TeX-PDF-mode-parsed nil))
1828
1829 (defcustom TeX-DVI-via-PDFTeX nil
1830   "Whether to use PDFTeX also for producing DVI files."
1831   :group 'TeX-command
1832   :type 'boolean)
1833
1834 (define-minor-mode TeX-interactive-mode
1835   "Minor mode for interactive runs of TeX."
1836   nil nil nil
1837   :group 'TeX-command
1838   (TeX-set-mode-name 'TeX-interactive-mode t t))
1839 (defalias 'tex-interactive-mode 'TeX-interactive-mode)
1840 (add-to-list 'minor-mode-alist '(TeX-interactive-mode ""))
1841
1842 ;;; Commands
1843
1844 (defgroup TeX-command-name nil
1845   "Names for external commands in AUCTeX."
1846   :group 'TeX-command)
1847
1848 (defcustom TeX-command-BibTeX "BibTeX"
1849   "*The name of the BibTeX entry in `TeX-command-list'."
1850   :group 'TeX-command-name
1851   :type 'string)
1852   (make-variable-buffer-local 'TeX-command-BibTeX)
1853
1854 (defcustom TeX-command-Biber "Biber"
1855   "*The name of the Biber entry in `TeX-command-list'."
1856   :group 'TeX-command-name
1857   :type 'string)
1858   (make-variable-buffer-local 'TeX-command-Biber)
1859
1860 (defcustom TeX-command-Show "View"
1861   "*The default command to show (view or print) a TeX file.
1862 Must be the car of an entry in `TeX-command-list'."
1863   :group 'TeX-command-name
1864   :type 'string)
1865   (make-variable-buffer-local 'TeX-command-Show)
1866
1867 (defcustom TeX-command-Print "Print"
1868   "The name of the Print entry in `TeX-command-Print'."
1869   :group 'TeX-command-name
1870   :type 'string)
1871
1872 (defcustom TeX-command-Queue "Queue"
1873   "The name of the Queue entry in `TeX-command-Queue'."
1874   :group 'TeX-command-name
1875   :type 'string)
1876
1877 (defvar TeX-trailer-start nil
1878   "Regular expression delimiting start of trailer in a TeX file.")
1879
1880  (make-variable-buffer-local 'TeX-trailer-start)
1881
1882 (defvar TeX-header-end nil
1883   "Regular expression delimiting end of header in a TeX file.")
1884
1885  (make-variable-buffer-local 'TeX-header-end)
1886
1887 (defvar TeX-command-default nil
1888   "The default command for `TeX-command' in the current major mode.")
1889
1890  (make-variable-buffer-local 'TeX-command-default)
1891
1892 (put 'TeX-command-default 'safe-local-variable 'stringp)
1893
1894 (defvar TeX-clean-default-intermediate-suffixes
1895   '("\\.aux" "\\.bbl" "\\.blg" "\\.brf" "\\.fot"
1896     "\\.glo" "\\.gls" "\\.idx" "\\.ilg" "\\.ind"
1897     "\\.lof" "\\.log" "\\.lot" "\\.nav" "\\.out"
1898     "\\.snm" "\\.toc" "\\.url" "\\.synctex\\.gz"
1899     "\\.bcf" "\\.run\\.xml" "\\.fls" "-blx\\.bib")
1900   "List of regexps matching suffixes of files to be cleaned.
1901 Used as a default in TeX, LaTeX and docTeX mode.")
1902
1903 (defvar TeX-clean-default-output-suffixes
1904   '("\\.dvi" "\\.pdf" "\\.ps" "\\.xdv")
1905   "List of regexps matching suffixes of files to be cleaned.
1906 Used as a default in TeX, LaTeX and docTeX mode.")
1907
1908 (defcustom TeX-clean-confirm t
1909   "If non-nil, ask before deleting files."
1910   :type 'boolean
1911   :group 'TeX-command)
1912
1913 (autoload 'dired-mark-pop-up "dired")
1914
1915 (defun TeX-clean (&optional arg)
1916   "Delete generated files associated with current master and region files.
1917 If prefix ARG is non-nil, not only remove intermediate but also
1918 output files."
1919   (interactive "P")
1920   (let* ((mode-prefix (TeX-mode-prefix))
1921          (suffixes (append (symbol-value
1922                             (intern (concat mode-prefix
1923                                             "-clean-intermediate-suffixes")))
1924                            (when arg
1925                              (symbol-value
1926                               (intern (concat mode-prefix
1927                                               "-clean-output-suffixes"))))))
1928          (master (TeX-active-master))
1929          (master-dir (file-name-directory master))
1930          (regexp (concat "\\("
1931                          (regexp-quote (file-name-nondirectory master)) "\\|"
1932                          (TeX-region-file nil t)
1933                          "\\)"
1934                          "\\("
1935                          (mapconcat 'identity suffixes "\\|")
1936                          "\\)\\'"
1937                          "\\|" (TeX-region-file t t)))
1938          (files (when regexp
1939                   (directory-files (or master-dir ".") nil regexp))))
1940     (if files
1941         (when (or (not TeX-clean-confirm)
1942                   (condition-case nil
1943                       (dired-mark-pop-up " *Deletions*" 'delete
1944                                          (if (> (length files) 1)
1945                                              files
1946                                            (cons t files))
1947                                          'y-or-n-p "Delete files? ")
1948                     (wrong-type-argument ; e.g. with Emacs 21
1949                      (y-or-n-p (format "Delete %S? " (car files))))))
1950           (dolist (file files)
1951             (delete-file (concat master-dir file))))
1952       (message "No files to be deleted"))))
1953
1954
1955 ;;; Master File
1956
1957 (defcustom TeX-master t
1958   "*The master file associated with the current buffer.
1959 If the file being edited is actually included from another file, you
1960 can tell AUCTeX the name of the master file by setting this variable.
1961 If there are multiple levels of nesting, specify the top level file.
1962
1963 If this variable is nil, AUCTeX will query you for the name.
1964
1965 If the variable is t, AUCTeX will assume the file is a master file
1966 itself.
1967
1968 If the variable is 'shared, AUCTeX will query for the name, but not
1969 change the file.
1970
1971 If the variable is 'dwim, AUCTeX will try to avoid querying by
1972 attempting to `do what I mean'; and then change the file.
1973
1974 It is suggested that you use the File Variables (see the info node in
1975 the Emacs manual) to set this variable permanently for each file."
1976   :group 'TeX-command
1977   :group 'TeX-parse
1978   :type '(choice (const :tag "Query" nil)
1979                  (const :tag "This file" t)
1980                  (const :tag "Shared" shared)
1981                  (const :tag "Dwim" dwim)
1982                  (string :format "%v")))
1983 (make-variable-buffer-local 'TeX-master)
1984 (put 'TeX-master 'safe-local-variable
1985      '(lambda (x)
1986         (or (stringp x)
1987             (member x (quote (t nil shared dwim))))))
1988
1989 (defcustom TeX-one-master "\\.\\(texi?\\|dtx\\)$"
1990   "*Regular expression matching ordinary TeX files.
1991
1992 You should set this variable to match the name of all files, where
1993 automatically adding a file variable with the name of the master file
1994 is a good idea.  When AUCTeX adds the name of the master file as a
1995 file variable, it does not need to ask next time you edit the file.
1996
1997 If you dislike AUCTeX automatically modifying your files, you can set
1998 this variable to \"<none>\"."
1999   :group 'TeX-command
2000   :type 'regexp)
2001
2002 (defvar TeX-convert-master t
2003   "*If not nil, automatically convert ``Master:'' lines to file variables.
2004 This will be done when AUCTeX first try to use the master file.")
2005
2006 ;; Can be let-bound temporarily in order to inhibit the master file question
2007 ;; by using its value instead in case `TeX-master' is nil or 'shared.
2008 (defvar TeX-transient-master nil)
2009
2010 (defun TeX-dwim-master ()
2011   "Find a likely `TeX-master'."
2012   (let ((dir default-directory))
2013     (dolist (buf (buffer-list))
2014       (when (with-current-buffer buf
2015               (and (equal dir default-directory)
2016                    (stringp TeX-master)))
2017         (return (with-current-buffer buf TeX-master))))))
2018
2019 (defun TeX-master-file-ask ()
2020   "Ask for master file, set `TeX-master' and add local variables."
2021   (interactive)
2022   (if (TeX-local-master-p)
2023       (error "Master file already set")
2024     (let* ((default (TeX-dwim-master))
2025            (name (or (and (eq 'dwim TeX-master) default)
2026                      (condition-case nil
2027                          (read-file-name (format "Master file: (default %s) "
2028                                                  (or default "this file"))
2029                                          nil default)
2030                        (quit "<quit>")))))
2031       (cond ((string= name "<quit>")
2032              (setq TeX-master t))
2033             ((string= name default)
2034              (setq TeX-master default)
2035              (TeX-add-local-master))
2036             ((or
2037               ;; Default `read-file-name' proposes and buffer visits a file.
2038               (string= (expand-file-name name) (buffer-file-name))
2039               ;; Default of `read-file-name' and buffer does not visit a file.
2040               (string= name default-directory)
2041               ;; User typed <RET> in an empty minibuffer.
2042               (string= name ""))
2043              (setq TeX-master t)
2044              (TeX-add-local-master))
2045             (t
2046              (setq TeX-master (TeX-strip-extension (file-relative-name name)
2047                                                    (list TeX-default-extension)
2048                                                    'path))
2049              (TeX-add-local-master))))))
2050
2051 (defun TeX-master-file (&optional extension nondirectory ask)
2052   "Set and return the name of the master file for the current document.
2053
2054 If optional argument EXTENSION is non-nil, add that file extension to
2055 the name.  Special value t means use `TeX-default-extension'.
2056
2057 If optional second argument NONDIRECTORY is non-nil, do not include
2058 the directory.
2059
2060 If optional third argument ASK is non-nil, ask the user for the
2061 name of master file if it cannot be determined otherwise.
2062
2063 Currently it will check for the presence of a ``Master:'' line in
2064 the beginning of the file, but that feature will be phased out."
2065   (interactive)
2066   (if (eq extension t)
2067       (setq extension TeX-default-extension))
2068   (let ((my-name (if (buffer-file-name)
2069                      (TeX-strip-extension nil (list TeX-default-extension) t)
2070                    "<none>")))
2071     (save-excursion
2072       (save-restriction
2073         (widen)
2074         (goto-char (point-min))
2075         (cond
2076          ((and TeX-transient-master
2077                (or (not TeX-master) (eq TeX-master 'shared)))
2078           (setq TeX-master TeX-transient-master))
2079          ;; Special value 't means it is own master (a free file).
2080          ((equal TeX-master my-name)
2081           (setq TeX-master t))
2082
2083          ;; For files shared between many documents.
2084          ((and (eq 'shared TeX-master) ask)
2085           (setq TeX-master
2086                 (let* ((default (TeX-dwim-master))
2087                        (name (read-file-name
2088                               (format "Master file: (default %s) "
2089                                       (or default "this file"))
2090                               nil default)))
2091                   (cond ((string= name default)
2092                          default)
2093                         ((or
2094                           ;; Default `read-file-name' proposes and
2095                           ;; buffer visits a file.
2096                           (string= (expand-file-name name)
2097                                    (buffer-file-name))
2098                           ;; Default of `read-file-name' and
2099                           ;; buffer does not visit a file.
2100                           (string= name default-directory)
2101                           ;; User typed <RET> in an empty minibuffer.
2102                           (string= name ""))
2103                          t)
2104                         (t
2105                          (TeX-strip-extension
2106                           name (list TeX-default-extension) 'path))))))
2107
2108          ;; We might already know the name.
2109          ((or (eq TeX-master t) (stringp TeX-master)) TeX-master)
2110
2111          ;; Support the ``Master:'' line (under protest!)
2112          ((re-search-forward
2113            "^%% *[Mm]aster:?[ \t]*\\([^ \t\n]+\\)" 500 t)
2114           (setq TeX-master
2115                 (TeX-strip-extension (TeX-match-buffer 1)
2116                                      (list TeX-default-extension)))
2117           (if TeX-convert-master
2118               (progn
2119                 (beginning-of-line)
2120                 (kill-line 1)
2121                 (TeX-add-local-master))))
2122
2123          ;; Ask the user (but add it as a local variable).
2124          (ask (TeX-master-file-ask)))))
2125
2126     (let ((name (if (stringp TeX-master)
2127                     TeX-master
2128                   my-name)))
2129
2130       (if (TeX-match-extension name)
2131           ;; If it already has an extension...
2132           (if (equal extension TeX-default-extension)
2133               ;; Use instead of the default extension
2134               (setq extension nil)
2135             ;; Otherwise drop it.
2136             (setq name (TeX-strip-extension name))))
2137
2138       ;; Remove directory if needed.
2139       (if nondirectory
2140           (setq name (file-name-nondirectory name)))
2141
2142       (if extension
2143           (concat name "." extension)
2144         name))))
2145
2146 (defun TeX-master-directory ()
2147   "Directory of master file."
2148   (file-name-as-directory
2149    (abbreviate-file-name
2150     (substitute-in-file-name
2151      (expand-file-name
2152       (let ((dir (file-name-directory (TeX-master-file))))
2153         (if dir (directory-file-name dir) "."))
2154       (and buffer-file-name
2155            (file-name-directory buffer-file-name)))))))
2156
2157 (defun TeX-add-local-master ()
2158   "Add local variable for `TeX-master'."
2159   (when (and (buffer-file-name)
2160              (string-match TeX-one-master
2161                            (file-name-nondirectory (buffer-file-name)))
2162              (not buffer-read-only))
2163     (goto-char (point-max))
2164     (if (re-search-backward "^\\([^\n]+\\)Local Variables:"
2165                             (- (point-max) 3000) t)
2166         (let ((prefix (TeX-match-buffer 1)))
2167           (re-search-forward (regexp-quote (concat prefix
2168                                                    "End:")))
2169           (beginning-of-line 1)
2170           (insert prefix "TeX-master: " (prin1-to-string TeX-master) "\n"))
2171       (let ((comment-prefix (cond ((eq major-mode 'texinfo-mode) "@c ")
2172                                   ((eq major-mode 'doctex-mode) "% ")
2173                                   (t "%%% ")))
2174             (mode (concat (and (boundp 'japanese-TeX-mode) japanese-TeX-mode
2175                                "japanese-")
2176                           (substring (symbol-name major-mode) 0 -5))))
2177         (newline)
2178         (when (eq major-mode 'doctex-mode)
2179           (insert comment-prefix TeX-esc "endinput\n"))
2180         (insert
2181          comment-prefix "Local Variables:\n"
2182          comment-prefix "mode: " mode "\n"
2183          comment-prefix "TeX-master: " (prin1-to-string TeX-master) "\n"
2184          comment-prefix "End:\n")))))
2185
2186 (defun TeX-local-master-p ()
2187   "Return non-nil if there is a `TeX-master' entry in local variables spec.
2188 Return nil otherwise."
2189   (save-excursion
2190     ;; XXX: Checking -*- line necessary as well?
2191     (goto-char (point-max))
2192     (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
2193     (re-search-forward "^%+ *TeX-master:" nil t)))
2194
2195 ;;; Style Paths
2196
2197 (defcustom TeX-style-global (expand-file-name "style" TeX-data-directory)
2198   "*Directory containing hand generated TeX information.
2199
2200 These correspond to TeX macros shared by all users of a site."
2201   :group 'TeX-file
2202   :type 'directory)
2203
2204 (defcustom TeX-auto-local "auto"
2205   "*Directory containing automatically generated TeX information.
2206
2207 This correspond to TeX macros found in the current directory, and must
2208 be relative to that."
2209   :group 'TeX-file
2210   :type 'string)
2211
2212 (defcustom TeX-style-local "style"
2213   "*Directory containing hand generated TeX information.
2214
2215 These correspond to TeX macros found in the current directory, and must
2216 be relative to that."
2217   :group 'TeX-file
2218   :type 'string)
2219
2220 (defun TeX-split-string (regexp string)
2221   "Return a list of strings.
2222 Given REGEXP the STRING is split into sections which in string was
2223 seperated by REGEXP.
2224
2225 Examples:
2226
2227       (TeX-split-string \"\:\" \"abc:def:ghi\")
2228           -> (\"abc\" \"def\" \"ghi\")
2229
2230       (TeX-split-string \" +\" \"dvips  -Plw -p3 -c4 testfile.dvi\")
2231
2232           -> (\"dvips\" \"-Plw\" \"-p3\" \"-c4\" \"testfile.dvi\")
2233
2234 If REGEXP is nil, or \"\", an error will occur."
2235
2236   (let ((start 0) result match)
2237     (while (setq match (string-match regexp string start))
2238       (push (substring string start match) result)
2239       (setq start (match-end 0)))
2240     (push (substring string start) result)
2241     (nreverse result)))
2242
2243 (defun TeX-parse-path (env)
2244   "Return a list if private TeX directories found in environment variable ENV."
2245   (let* ((value (getenv env))
2246          (entries (and value
2247                        (TeX-split-string
2248                         (if (string-match ";" value) ";" ":")
2249                         value)))
2250          entry
2251          answers)
2252     (while entries
2253       (setq entry (car entries))
2254       (setq entries (cdr entries))
2255       (setq entry (file-name-as-directory
2256                    (if (string-match "/?/?\\'" entry)
2257                        (substring entry 0 (match-beginning 0))
2258                      entry)))
2259       (or (not (file-name-absolute-p entry))
2260           (member entry (append '("/" "\\") TeX-macro-global))
2261           (setq answers (cons entry answers))))
2262     answers))
2263
2264 (defun TeX-tree-expand (vars program &optional subdirs)
2265   "Return directories corresponding to the kpathsea variables VARS.
2266 This is done calling `kpsewhich --expand-path' for each variable.
2267 PROGRAM is passed as the parameter for --progname.  SUBDIRS are
2268 subdirectories which are appended to the directories of the TeX
2269 trees.  Only existing directories are returned."
2270   (let (path-list path exit-status input-dir-list)
2271     (condition-case nil
2272         (dolist (var vars)
2273           (setq path (with-output-to-string
2274                        (setq exit-status (call-process
2275                                           "kpsewhich"  nil
2276                                           (list standard-output nil) nil
2277                                           "--progname" program
2278                                           "--expand-path" var))))
2279           (when (zerop exit-status)
2280             (add-to-list 'path-list path t)))
2281       (error nil))
2282     (dolist (elt path-list)
2283       (let ((separators (if (string-match "^[A-Za-z]:" elt)
2284                             "[\n\r;]"
2285                           "[\n\r:]")))
2286         (dolist (item (condition-case nil
2287                           (split-string elt separators t)
2288                         ;; COMPATIBILITY for XEmacs <= 21.4.15
2289                         (error (delete "" (split-string elt separators)))))
2290           (if subdirs
2291               (dolist (subdir subdirs)
2292                 (setq path (file-name-as-directory (concat item subdir)))
2293                 (when (file-exists-p path)
2294                   (add-to-list 'input-dir-list path t)))
2295             (setq path (file-name-as-directory item))
2296             (when (file-exists-p path)
2297               (add-to-list 'input-dir-list path t))))))
2298     input-dir-list))
2299
2300 (defun TeX-macro-global ()
2301   "Return directories containing the site's TeX macro and style files."
2302   (or (TeX-tree-expand '("$SYSTEXMF" "$TEXMFLOCAL" "$TEXMFMAIN" "$TEXMFDIST")
2303                        "latex" '("/tex/" "/bibtex/bst/"))
2304       '("/usr/share/texmf/tex/" "/usr/share/texmf/bibtex/bst/")))
2305
2306 (defun TeX-macro-private ()
2307   "Return directories containing the user's TeX macro and style files."
2308   (TeX-tree-expand '("$TEXMFHOME") "latex" '("/tex/" "/bibtex/bst/")))
2309
2310 (defcustom TeX-macro-global (TeX-macro-global)
2311   "Directories containing the site's TeX macro and style files."
2312   :group 'TeX-file
2313   :type '(repeat (directory :format "%v")))
2314
2315 (defcustom TeX-macro-private (or (append (TeX-parse-path "TEXINPUTS")
2316                                          (TeX-parse-path "BIBINPUTS"))
2317                                  (TeX-macro-private))
2318   "Directories where you store your personal TeX macros."
2319   :group 'TeX-file
2320   :type '(repeat (file :format "%v")))
2321
2322 (defcustom TeX-auto-private
2323   (list (expand-file-name TeX-auto-local
2324                           (or (and (boundp 'user-emacs-directory)
2325                                    (concat user-emacs-directory "auctex/"))
2326                               "~/.emacs.d/auctex/")))
2327   "List of directories containing automatically generated AUCTeX style files.
2328
2329 These correspond to the personal TeX macros."
2330   :group 'TeX-file
2331   :type '(repeat (file :format "%v")))
2332
2333 (if (stringp TeX-auto-private)          ;Backward compatibility
2334     (setq TeX-auto-private (list TeX-auto-private)))
2335
2336 (defcustom TeX-style-private
2337   (list (expand-file-name TeX-style-local
2338                           (or (and (boundp 'user-emacs-directory)
2339                                    (concat user-emacs-directory "auctex/"))
2340                               "~/.emacs.d/auctex/")))
2341   "List of directories containing hand-generated AUCTeX style files.
2342
2343 These correspond to the personal TeX macros."
2344   :group 'TeX-file
2345   :type '(repeat (file :format "%v")))
2346
2347 (if (stringp TeX-style-private)         ;Backward compatibility
2348     (setq TeX-style-private (list TeX-style-private)))
2349
2350 (defcustom TeX-style-path
2351   (let ((path))
2352     ;; Put directories in an order where the more local files can
2353     ;; override the more global ones.
2354     (mapcar (lambda (file) (when file (add-to-list 'path file t)))
2355             (append (list TeX-auto-global TeX-style-global)
2356                     TeX-auto-private TeX-style-private
2357                     (list TeX-auto-local TeX-style-local)))
2358     path)
2359   "List of directories to search for AUCTeX style files.
2360 Per default the list is built from the values of the variables
2361 `TeX-auto-global', `TeX-style-global', `TeX-auto-private',
2362 `TeX-style-private', `TeX-auto-local', and `TeX-style-local'."
2363   :group 'TeX-file
2364   :type '(repeat (file :format "%v")))
2365
2366 (defcustom TeX-check-path
2367   (append (list ".") TeX-macro-private TeX-macro-global)
2368   "Directory path to search for dependencies.
2369
2370 If nil, just check the current file.
2371 Used when checking if any files have changed."
2372   :group 'TeX-file
2373   :type '(repeat (file :format "%v")))
2374
2375 ;;; Style Files
2376
2377 (defvar TeX-style-hook-list nil
2378   "List of TeX style hooks currently loaded.
2379
2380 Each entry is a list:
2381
2382  (STYLE HOOK1 HOOK2 ...)
2383
2384 where the first element STYLE is the name of the style, and the
2385 remaining elements HOOKN, if any, are hooks to be run when that
2386 style is active.
2387
2388 A hook HOOKN may be a hook function HOOK-FUN to be run in
2389 all TeX dialects (LaTeX, Texinfo, etc.), or a vector like:
2390
2391      [TeX-style-hook HOOK-FUN DIALECT-SET]
2392
2393 where HOOK-FUN is the hook function to be run, and DIALECT-SET is
2394 a non-empty set of dialects in which the hook function may be
2395 run.
2396
2397 This set is instantiated by function `TeX-add-style-hook' through
2398 functions manipulating style hook dialect expression named with a
2399 `TeX-shdex-' prefix.
2400
2401 For supported dialects, see variables `TeX-style-hook-dialect'.")
2402
2403 (defvar TeX-style-hook-dialect :latex
2404   "Dialect for running hooks locally to the considered file.
2405 Supported values are described below:
2406
2407 * `:bibtex'  for files in BibTeX mode.
2408 * `:latex'   for files in LaTeX mode, or any mode derived
2409              thereof.
2410 * `:texinfo' for Texinfo files.
2411
2412 Purpose is notably to prevent non-Texinfo hooks to be run in
2413 Texinfo files, due to ambiguous style name, as this may cause bad
2414 side effect e.g. on variable `TeX-font-list'.")
2415
2416 (defcustom TeX-byte-compile nil
2417   "*Not nil means try to byte compile auto files before loading."
2418   :group 'TeX-parse
2419   :type 'boolean)
2420
2421 (defun TeX-bibtex-set-BibTeX-dialect ()
2422   "Set `TeX-style-hook-dialect' to `:bibtex' locally to BibTeX buffers."
2423   (set (make-local-variable 'TeX-style-hook-dialect) :bibtex))
2424
2425 (defun TeX-load-style (style)
2426   "Search for and load each definition for STYLE in `TeX-style-path'."
2427   (cond ((assoc style TeX-style-hook-list)) ; We already found it
2428         ((string-match "\\`\\(.+[/\\]\\)\\([^/\\]*\\)\\'" style) ;Complex path
2429          (let* ((dir (substring style (match-beginning 1) (match-end 1)))
2430                 (style (substring style (match-beginning 2) (match-end 2)))
2431                 (master-dir (if (stringp TeX-master)
2432                                 (file-name-directory
2433                                  (file-relative-name TeX-master))
2434                               "./"))
2435                 (TeX-style-path (append (list (expand-file-name
2436                                                TeX-auto-local dir)
2437                                               (expand-file-name
2438                                                TeX-auto-local master-dir)
2439                                               (expand-file-name
2440                                                TeX-style-local dir)
2441                                               (expand-file-name
2442                                                TeX-style-local master-dir))
2443                                         TeX-style-path)))
2444            (TeX-load-style style)))
2445         (t                              ;Relative path
2446          ;; Insert empty list to mark the fact that we have searched.
2447          (setq TeX-style-hook-list (cons (list style) TeX-style-hook-list))
2448          ;; Now check each element of the path
2449          (dolist (name TeX-style-path)
2450            (TeX-load-style-file (expand-file-name style name))))))
2451
2452 (defun TeX-load-style-file (file)
2453   "Load FILE checking for a Lisp extensions."
2454   (let ((el (concat file ".el"))
2455         (elc (concat file ".elc")))
2456     (cond ((file-newer-than-file-p el elc)
2457            (if (file-readable-p el)
2458                (if (and TeX-byte-compile
2459                         (file-writable-p elc)
2460                         (save-excursion
2461                           ;; `byte-compile-file' switches buffer in Emacs 20.3.
2462                           (byte-compile-file el))
2463                         (file-readable-p elc))
2464                    (load-file elc)
2465                  (load-file el))))
2466           ((file-readable-p elc)
2467            (load-file elc))
2468           ((file-readable-p el)
2469            (load-file el)))))
2470
2471 (defconst TeX-style-hook-dialect-weight-alist
2472   '((:latex . 1) (:texinfo . 2) (:bibtex . 4))
2473   "Association list to map dialects to binary weight, in order to
2474   implement dialect sets as bitmaps."  )
2475
2476 (defun TeX-shdex-eval (dialect-expr)
2477   "Evaluate a style hook dialect expression DIALECT-EXPR."
2478   (cond
2479    ((symbolp dialect-expr)
2480     (let ((cell (assq dialect-expr TeX-style-hook-dialect-weight-alist)))
2481       (if cell (cdr cell)
2482         (error "Invalid dialect expression : %S." dialect-expr))))
2483    ((and (consp dialect-expr)
2484          (memq (car dialect-expr) '(or not and nor)))
2485     (apply (intern
2486             (concat "TeX-shdex-" (symbol-name  (car dialect-expr))))
2487            (cdr dialect-expr)))
2488    (t
2489     (error "Invalid dialect expression : %S." dialect-expr))))
2490
2491 (defsubst TeX-shdex-or (&rest args)
2492   "OR operator for style hook dialect expressions."
2493   (apply 'logior (mapcar 'TeX-shdex-eval args)))
2494
2495 (defsubst TeX-shdex-and (&rest args)
2496   "AND operator for style hook dialect expressions."
2497   (apply 'logand (mapcar 'TeX-shdex-eval args)))
2498
2499 (defsubst TeX-shdex-nor (&rest args)
2500   "NOR operator for style hook dialect expressions."
2501   (lognot (apply 'TeX-shdex-or args)))
2502
2503 (defsubst TeX-shdex-not (arg)
2504   "NOT operator for style hook dialect expressions."
2505    (lognot (TeX-shdex-eval arg)))
2506
2507 (defsubst TeX-shdex-in-p (dialect dialect-set)
2508   "Test whether dialect DIALECT is in dialect set DIALECT-SET."
2509   (let ((cell (assq dialect TeX-style-hook-dialect-weight-alist)))
2510     (if cell
2511         (/= 0 (logand (cdr cell) dialect-set))
2512       (error "Invalid dialect %S" dialect))))
2513
2514 (defsubst TeX-shdex-listify (dialect-set)
2515   "Converts a dialect set DIALECT-SET to a list of all dialect
2516 comprised in this set, where dialects are symbols"
2517   (let (ret)
2518     (dolist (c dialect-set)
2519       (when (/= 0 (logand (cdr c) dialect-set))
2520         (push (car c) ret)))
2521     ret))
2522
2523 (defun TeX-add-style-hook (style hook &optional dialect-expr)
2524   "Give STYLE yet another HOOK to run.
2525
2526 DIALECT-EXPR serves the purpose of marking the hook to be run only in
2527 that dicontext.
2528
2529 DIALECT-EXPR may be a single symbol defining the dialect, see
2530 variable `TeX-style-hook-dialect' for supported dialects.
2531
2532 DIALECT-EXPR can also be an expression like one of the following:
2533
2534 * (or  DIALECT1 DIALECT2 ...)
2535 * (nor DIALECT1 DIALECT2 ...)
2536 * (and DIALECT1 DIALECT2 ...)
2537 * (not DIALECT )
2538
2539 When omitted DIALECT-EXPR is equivalent to `(nor )', ie all
2540 dialected are allowed."
2541   (let ((entry (TeX-assoc-string style TeX-style-hook-list)))
2542     (and dialect-expr (setq hook (vector 'TeX-style-hook hook
2543                                          (TeX-shdex-eval dialect-expr))))
2544     (cond ((null entry)
2545            ;; New style, add entry.
2546            (setq TeX-style-hook-list (cons (list style hook)
2547                                            TeX-style-hook-list)))
2548           ((member hook entry)
2549            ;; Old style, hook already there, do nothing.
2550            nil)
2551           (t
2552            ;; Old style, new hook.
2553            (setcdr entry (cons hook (cdr entry)))))))
2554
2555 (defun TeX-keep-hooks-in-dialect (hooks dialect-list)
2556   "Scan HOOKS for all hooks the associated dialect of which is
2557 found in DIALECT-LIST and return the list thereof."
2558   (let (ret dialect-list-1)
2559     (dolist (hook hooks)
2560       (setq dialect-list-1 (and (vectorp hook) (eq (aref hook 0) 'TeX-style-hook)
2561                                 (TeX-shdex-listify (aref hook 2))))
2562       (while dialect-list-1
2563         (when (memq (pop dialect-list-1) dialect-list)
2564           (push hook ret)
2565           (setq dialect-list-1 nil)))
2566     ret)))
2567
2568 (defun TeX-unload-style (style &optional dialect-list)
2569   "Forget that we once loaded STYLE. If DIALECT-LIST is provided
2570 the STYLE is only removed for those dialects in DIALECT-LIST.
2571
2572 See variable `TeX-style-hook-dialect' for supported dialects."
2573   (let ((style-data (TeX-assoc-string style TeX-style-hook-list)))
2574     (if style-data
2575         (let ((hooks (and dialect-list (TeX-keep-hooks-in-dialect (cdr style-data) dialect-list))))
2576           (if hooks
2577               (setcdr style-data hooks)
2578             (setq TeX-style-hook-list (delq style-data TeX-style-hook-list)))))))
2579
2580 (defcustom TeX-virgin-style (if (and TeX-auto-global
2581                                      (file-directory-p TeX-auto-global))
2582                                 "virtex"
2583                               "NoVirtexSymbols")
2584   "Style all documents use."
2585   :group 'TeX-parse
2586   :type 'string)
2587
2588 (defvar TeX-active-styles nil
2589   "List of styles currently active in the document.")
2590  (make-variable-buffer-local 'TeX-active-styles)
2591
2592 (defun TeX-run-style-hooks (&rest styles)
2593   "Run the TeX style hooks STYLES."
2594   (mapcar (lambda (style)
2595             ;; Avoid recursion.
2596             (unless (TeX-member style TeX-active-styles 'string-equal)
2597               (setq TeX-active-styles
2598                     (cons style TeX-active-styles))
2599               (TeX-load-style style)
2600               (let ((default-directory default-directory))
2601                 ;; Complex path.
2602                 (when (string-match "\\`\\(.+[/\\]\\)\\([^/\\]*\\)\\'" style)
2603                   ;; Set `default-directory' to directory of master
2604                   ;; file since style files not stored in the fixed
2605                   ;; style directories are usually located there.
2606                   (setq default-directory (save-match-data
2607                                             (TeX-master-directory))
2608                         style (substring style
2609                                          (match-beginning 2) (match-end 2))))
2610                 (condition-case err
2611                     (mapcar (lambda (hook)
2612                               (cond
2613                                ((functionp hook)
2614                                 (funcall hook))
2615                                ((and (vectorp hook)
2616                                      (eq (aref hook 0) 'TeX-style-hook))
2617                                 (and (TeX-shdex-in-p TeX-style-hook-dialect (aref hook 2))
2618                                      (funcall (aref hook 1))))
2619                                (t (error "Invalid style hook %S" hook))))
2620                             (cdr-safe (TeX-assoc-string style TeX-style-hook-list)))
2621                   ;; This happens in case some style added a new parser, and
2622                   ;; now the style isn't used anymore (user deleted
2623                   ;; \usepackage{style}).  Then we're left over with, e.g.,
2624                   ;; (LaTeX-add-siunitx-units "\\parsec"), but the function is
2625                   ;; defined in a style siunitx.el that's not loaded anymore.
2626                   (void-function nil)))))
2627           styles))
2628
2629 (defcustom TeX-parse-self nil
2630   "Parse file after loading it if no style hook is found for it."
2631   :group 'TeX-parse
2632   :type 'boolean)
2633
2634 (defvar TeX-style-hook-applied-p nil
2635   "Nil, unless the style specific hooks have been applied.")
2636  (make-variable-buffer-local 'TeX-style-hook-applied-p)
2637
2638 (defvar TeX-update-style-hook nil
2639   "Hook run as soon as style specific hooks were applied.")
2640
2641 (defun TeX-update-style (&optional force)
2642   "Run style specific hooks for the current document.
2643
2644 Only do this if it has not been done before, or if optional argument
2645 FORCE is not nil."
2646   (unless (or (and (boundp 'TeX-auto-update)
2647                    (eq TeX-auto-update 'BibTeX)) ; Not a real TeX buffer
2648               (and (not force)
2649                    TeX-style-hook-applied-p))
2650     (setq TeX-style-hook-applied-p t)
2651     (message "Applying style hooks...")
2652     (TeX-run-style-hooks (TeX-strip-extension nil nil t))
2653     ;; Run parent style hooks if it has a single parent that isn't itself.
2654     (if (or (not (memq TeX-master '(nil t)))
2655             (and (buffer-file-name)
2656                  (string-match TeX-one-master
2657                                (file-name-nondirectory (buffer-file-name)))))
2658         (TeX-run-style-hooks (TeX-master-file)))
2659     (if (and TeX-parse-self
2660              (null (cdr-safe (assoc (TeX-strip-extension nil nil t)
2661                                     TeX-style-hook-list))))
2662         (TeX-auto-apply))
2663     (run-hooks 'TeX-update-style-hook)
2664     (message "Applying style hooks... done")))
2665
2666 (defvar TeX-remove-style-hook nil
2667   "List of hooks to call when we remove the style specific information.")
2668  (make-variable-buffer-local 'TeX-remove-style-hook)
2669
2670 (defun TeX-remove-style ()
2671   "Remove all style specific information."
2672   (setq TeX-style-hook-applied-p nil)
2673   (run-hooks 'TeX-remove-style-hook)
2674   (setq TeX-active-styles (list TeX-virgin-style)))
2675
2676 (defun TeX-style-list ()
2677   "Return a list of all styles (subfiles) used by the current document."
2678   (TeX-update-style)
2679   TeX-active-styles)
2680
2681 ;;; Special Characters
2682
2683 (defvar TeX-esc "\\" "The TeX escape character.")
2684  (make-variable-buffer-local 'TeX-esc)
2685
2686 (defvar TeX-grop "{" "The TeX group opening character.")
2687  (make-variable-buffer-local 'TeX-grop)
2688
2689 (defvar TeX-grcl "}" "The TeX group closing character.")
2690  (make-variable-buffer-local 'TeX-grcl)
2691
2692 ;;; Symbols
2693
2694 ;; Must be before keymaps.
2695
2696 (defgroup TeX-macro nil
2697   "Support for TeX macros in AUCTeX."
2698   :prefix "TeX-"
2699   :group 'AUCTeX)
2700
2701 (defcustom TeX-complete-word 'ispell-complete-word
2702   "*Function to call for completing non-macros in `tex-mode'."
2703   :group 'TeX-macro)
2704
2705 (defcustom TeX-complete-expert-commands nil
2706   "Complete macros and environments marked as expert commands.
2707
2708 Possible values are nil, t, or a list of style names.
2709
2710   - nil           Don't complete expert commands (default).
2711   - t             Always complete expert commands.
2712   - (STYLES ...)  Only complete expert commands of STYLES."
2713   :group 'TeX-macro
2714   :type '(choice (const  :tag "Don't complete expert commands" nil)
2715                  (const  :tag "Always complete expert commands" t)
2716                  (repeat :tag "Complete expert commands of certain styles" string)))
2717
2718 (defmacro TeX-complete-make-expert-command-functions (thing list-var prefix)
2719   (let* ((plural (concat thing "s"))
2720          (upcase (upcase thing))
2721          (upcase-plural (upcase plural)))
2722     `(progn
2723        (defvar ,(intern (format "%s-expert-%s-table" prefix thing))
2724          (make-hash-table :test 'equal)
2725          ,(format "A hash-table mapping %s names to the style name providing it.
2726
2727 A %s occuring in this table is considered an expert %s and
2728 treated specially in the completion." thing thing thing))
2729
2730        (defun ,(intern (format "%s-declare-expert-%s" prefix plural)) (style &rest ,(intern plural))
2731          ,(format "Declare %s as expert %s of STYLE.
2732
2733 Expert %s are completed depending on `TeX-complete-expert-commands'."
2734                   upcase-plural plural plural)
2735          (dolist (x ,(intern plural))
2736            (if (null style)
2737                (remhash x TeX-expert-macro-table)
2738              (puthash x style TeX-expert-macro-table))))
2739
2740        (defun ,(intern (format "%s-filtered" list-var)) ()
2741          ,(format "Return (%s) filtered depending on `TeX-complete-expert-commands'."
2742                   list-var)
2743          (delq nil
2744                (mapcar
2745                 (lambda (entry)
2746                   (if (eq t TeX-complete-expert-commands)
2747                       entry
2748                     (let* ((cmd (car entry))
2749                            (style (gethash cmd TeX-expert-macro-table)))
2750                       (when (or (null style)
2751                                 (member style TeX-complete-expert-commands))
2752                         entry))))
2753                 (,list-var)))))))
2754
2755 (TeX-complete-make-expert-command-functions "macro" TeX-symbol-list "TeX")
2756 (TeX-complete-make-expert-command-functions "environment" LaTeX-environment-list "LaTeX")
2757
2758 (defvar TeX-complete-list nil
2759   "List of ways to complete the preceding text.
2760
2761 Each entry is a list with the following elements:
2762
2763 0. Regexp matching the preceding text.
2764 1. A number indicating the subgroup in the regexp containing the text.
2765 2. A function returning an alist of possible completions.
2766 3. Text to append after a succesful completion.
2767
2768 Or alternatively:
2769
2770 0. Regexp matching the preceding text.
2771 1. Function to do the actual completion.")
2772
2773 (defun TeX-complete-symbol ()
2774   "Perform completion on TeX/LaTeX symbol preceding point."
2775   (interactive "*")
2776   (let ((list TeX-complete-list)
2777         entry)
2778     (while list
2779       (setq entry (car list)
2780             list (cdr list))
2781       (if (TeX-looking-at-backward (car entry) 250)
2782           (setq list nil)))
2783     (if (numberp (nth 1 entry))
2784         (let* ((sub (nth 1 entry))
2785                (close (nth 3 entry))
2786                (begin (match-beginning sub))
2787                (end (match-end sub))
2788                (pattern (TeX-match-buffer 0))
2789                (symbol (buffer-substring begin end))
2790                (list (funcall (nth 2 entry)))
2791                (completion (try-completion symbol list))
2792                (buf-name "*Completions*"))
2793           (cond ((eq completion t)
2794                  (and close
2795                       (not (looking-at (regexp-quote close)))
2796                       (insert close))
2797                  (let ((window (get-buffer-window buf-name)))
2798                    (when window (delete-window window))))
2799                 ((null completion)
2800                  (error "Can't find completion for \"%s\"" pattern))
2801                 ((not (string-equal symbol completion))
2802                  (delete-region begin end)
2803                  (insert completion)
2804                  (and close
2805                       (eq (try-completion completion list) t)
2806                       (not (looking-at (regexp-quote close)))
2807                       (insert close))
2808                  (let ((window (get-buffer-window buf-name)))
2809                    (when window (delete-window window))))
2810                 (t
2811                  (if (fboundp 'completion-in-region)
2812                      (completion-in-region begin end
2813                                            (all-completions symbol list nil))
2814                    (message "Making completion list...")
2815                    (let ((list (all-completions symbol list nil)))
2816                      (with-output-to-temp-buffer buf-name
2817                        (display-completion-list list)))
2818                    (set-window-dedicated-p (get-buffer-window buf-name) 'soft)
2819                    (message "Making completion list...done")))))
2820       (funcall (nth 1 entry)))))
2821
2822 (defcustom TeX-default-macro "ref"
2823   "*The default macro when creating new ones with `TeX-insert-macro'."
2824   :group 'TeX-macro
2825   :type 'string)
2826
2827 (make-variable-buffer-local 'TeX-default-macro)
2828
2829 (defcustom TeX-insert-braces t
2830   "*If non-nil, append a empty pair of braces after inserting a macro.
2831
2832 See also `TeX-insert-braces-alist'."
2833   :group 'TeX-macro
2834   :type 'boolean)
2835
2836 (defcustom TeX-insert-braces-alist nil
2837   "Alist of macros to which braces should or should not be appended.
2838
2839 Each element is a cons cell, whose CAR is the macro name, and the
2840 CDR is non-nil or nil, depending on whether a pair of braces
2841 should be, respectively, appended or not to the macro.
2842
2843 If a macro has an element in this variable, `TeX-parse-macro'
2844 will use its value to decided what to do, whatever the value of
2845 the variable `TeX-insert-braces'."
2846   :group 'TeX-macro
2847   :type '(repeat (cons (string :tag "Macro name")
2848                        (boolean :tag "Append braces?"))))
2849 (make-variable-buffer-local 'TeX-insert-braces-alist)
2850
2851 (defcustom TeX-insert-macro-default-style 'show-optional-args
2852   "Specifies whether `TeX-insert-macro' will ask for all optional arguments.
2853
2854 If set to the symbol `show-optional-args', `TeX-insert-macro'
2855 asks for optional arguments of TeX marcos, unless the previous
2856 optional argument has been rejected.  If set to
2857 `show-all-optional-args', `TeX-insert-macro' asks for all
2858 optional arguments.  If set to `mandatory-args-only',
2859 `TeX-insert-macro' asks only for mandatory argument.
2860
2861 When `TeX-insert-macro' is called with \\[universal-argument], it's the other
2862 way round.
2863
2864 Note that for some macros, there are special mechanisms, see e.g.
2865 `LaTeX-includegraphics-options-alist' and `TeX-arg-cite-note-p'."
2866   :group 'TeX-macro
2867   :type '(choice (const mandatory-args-only)
2868                  (const show-optional-args)
2869                  (const show-all-optional-args)))
2870
2871 (defvar TeX-arg-opening-brace nil
2872   "String used as an opening brace for argument insertion.
2873 The variable will be temporarily let-bound with the necessary value.")
2874
2875 (defvar TeX-arg-closing-brace nil
2876   "String used as a closing brace for argument insertion.
2877 The variable will be temporarily let-bound with the necessary value.")
2878
2879 (defvar TeX-after-insert-macro-hook nil
2880   "A hook run after `TeX-insert-macro'.")
2881
2882 (defvar TeX-macro-history nil)
2883
2884 (defun TeX-insert-macro (symbol)
2885   "Insert TeX macro SYMBOL with completion.
2886
2887 AUCTeX knows of some macros and may query for extra arguments, depending on
2888 the value of `TeX-insert-macro-default-style' and whether `TeX-insert-macro'
2889 is called with \\[universal-argument]."
2890   ;; When called with a prefix (C-u), only ask for mandatory arguments,
2891   ;; i.e. all optional arguments are skipped.  See `TeX-parse-arguments' for
2892   ;; details.  Note that this behavior may be changed in favor of a more
2893   ;; flexible solution in the future, therefore we don't document it at the
2894   ;; moment.
2895   (interactive (list (completing-read (concat "Macro (default "
2896                                               TeX-default-macro
2897                                               "): "
2898                                               TeX-esc)
2899                                       (TeX-symbol-list-filtered) nil nil nil
2900                                       'TeX-macro-history TeX-default-macro)))
2901   (when (interactive-p)
2902     (setq TeX-default-macro symbol))
2903   (TeX-parse-macro symbol (cdr-safe (assoc symbol (TeX-symbol-list))))
2904   (run-hooks 'TeX-after-insert-macro-hook))
2905
2906 (defvar TeX-electric-macro-map
2907   (let ((map (make-sparse-keymap)))
2908     (set-keymap-parent map minibuffer-local-completion-map)
2909     (define-key map " " 'minibuffer-complete-and-exit)
2910     map))
2911
2912 (defun TeX-electric-macro ()
2913   "Insert TeX macro with completion.
2914
2915 AUCTeX knows of some macros, and may query for extra arguments.
2916 Space will complete and exit."
2917   (interactive)
2918   (cond ((eq (preceding-char) ?\\)
2919          (call-interactively 'self-insert-command))
2920         ((eq (preceding-char) ?.)
2921          (let ((TeX-default-macro " ")
2922                (minibuffer-local-completion-map TeX-electric-macro-map))
2923            (call-interactively 'TeX-insert-macro)))
2924         (t
2925          (let ((minibuffer-local-completion-map TeX-electric-macro-map))
2926            (call-interactively 'TeX-insert-macro)))))
2927
2928 (defun TeX-parse-macro (symbol args)
2929   "How to parse TeX macros which takes one or more arguments.
2930
2931 First argument SYMBOL is the name of the macro.
2932
2933 If called with no additional arguments, insert macro with point
2934 inside braces.  Otherwise, each argument of this function should
2935 match an argument to the TeX macro.  What is done depend on the
2936 type of ARGS:
2937
2938   string: Use the string as a prompt to prompt for the argument.
2939
2940   number: Insert that many braces, leave point inside the first.
2941
2942   nil: Insert empty braces.
2943
2944   t: Insert empty braces, leave point between the braces.
2945
2946   other symbols: Call the symbol as a function.  You can define
2947   your own hook, or use one of the predefined argument hooks.  If
2948   you add new hooks, you can assume that point is placed directly
2949   after the previous argument, or after the macro name if this is
2950   the first argument.  Please leave point located after the
2951   argument you are inserting.  If you want point to be located
2952   somewhere else after all hooks have been processed, set the value
2953   of `exit-mark'.  It will point nowhere, until the argument hook
2954   set it.  By convention, these hooks all start with `TeX-arg-'.
2955
2956   list: If the car is a string, insert it as a prompt and the next
2957   element as initial input.  Otherwise, call the car of the list
2958   with the remaining elements as arguments.
2959
2960   vector: Optional argument.  If it has more than one element,
2961   parse it as a list, otherwise parse the only element as above.
2962   Use square brackets instead of curly braces, and is not inserted
2963   on empty user input."
2964
2965   (if (and (TeX-active-mark)
2966            (> (point) (mark)))
2967       (exchange-point-and-mark))
2968   (insert TeX-esc symbol)
2969   (let ((exit-mark (make-marker))
2970         (position (point)))
2971     (TeX-parse-arguments args)
2972     (cond ((marker-position exit-mark)
2973            (goto-char (marker-position exit-mark))
2974            (set-marker exit-mark nil))
2975           ((let ((element (assoc symbol TeX-insert-braces-alist)))
2976              ;; If in `TeX-insert-braces-alist' there is an element associated
2977              ;; to the current macro, use its value to decide whether inserting
2978              ;; a pair of braces, otherwise use the standard criterion.
2979              (if element
2980                  (cdr element)
2981                (and TeX-insert-braces
2982                     ;; Do not add braces if the argument is 0 or -1.
2983                     (not (and (= (safe-length args) 1)
2984                               (numberp (car args))
2985                               (<= (car args) 0)))
2986                     (equal position (point))
2987                     (string-match "[a-zA-Z]+" symbol))))
2988            (if (texmathp)
2989                (when (TeX-active-mark)
2990                  (insert TeX-grop)
2991                  (exchange-point-and-mark)
2992                  (insert TeX-grcl))
2993              (insert TeX-grop)
2994              (if (TeX-active-mark)
2995                  (progn
2996                    (exchange-point-and-mark)
2997                    (insert TeX-grcl))
2998                (insert TeX-grcl)
2999                (backward-char)))))))
3000
3001 (defun TeX-arg-string (optional &optional prompt initial-input)
3002   "Prompt for a string.
3003
3004 If OPTIONAL is not nil then the PROMPT will start with ``(Optional) ''.
3005 INITIAL-INPUT is a string to insert before reading input."
3006   (TeX-argument-insert
3007    (if (and (not optional) (TeX-active-mark))
3008        (let ((TeX-argument (buffer-substring (point) (mark))))
3009          (delete-region (point) (mark))
3010          TeX-argument)
3011      (read-string (TeX-argument-prompt optional prompt "Text") initial-input))
3012    optional))
3013
3014 (defun TeX-parse-arguments (args)
3015   "Parse TeX macro arguments ARGS.
3016
3017 See `TeX-parse-macro' for details."
3018   (let ((last-optional-rejected nil))
3019     (while args
3020       (if (vectorp (car args))
3021           ;; Maybe get rid of all optional arguments.  See `TeX-insert-macro'
3022           ;; for more comments.  See `TeX-insert-macro-default-style'.
3023           (unless (if (eq TeX-insert-macro-default-style 'show-all-optional-args)
3024                       (equal current-prefix-arg '(4))
3025                     (or
3026                      (and (eq TeX-insert-macro-default-style 'show-optional-args)
3027                           (equal current-prefix-arg '(4)))
3028                      (and (eq TeX-insert-macro-default-style 'mandatory-args-only)
3029                           (null (equal current-prefix-arg '(4))))
3030                      last-optional-rejected))
3031             (let ((TeX-arg-opening-brace LaTeX-optop)
3032                   (TeX-arg-closing-brace LaTeX-optcl))
3033               (TeX-parse-argument t (if (equal (length (car args)) 1)
3034                                         (aref (car args) 0)
3035                                       (append (car args) nil)))))
3036         (let ((TeX-arg-opening-brace TeX-grop)
3037               (TeX-arg-closing-brace TeX-grcl))
3038           (setq last-optional-rejected nil)
3039           (TeX-parse-argument nil (car args))))
3040       (setq args (cdr args)))))
3041
3042 (defun TeX-parse-argument (optional arg)
3043   "Depending on OPTIONAL, insert TeX macro argument ARG.
3044 If OPTIONAL is set, only insert if there is anything to insert, and
3045 then use square brackets instead of curly braces.
3046
3047 See `TeX-parse-macro' for details."
3048   (let (insert-flag)
3049     (cond ((stringp arg)
3050            (TeX-arg-string optional arg)
3051            (setq insert-flag t))
3052           ((numberp arg)
3053            (cond ((< arg 0)
3054                   (when (TeX-active-mark)
3055                     ;; Put both the macro and the marked region in a TeX group.
3056                     (let ((beg (min (point) (mark)))
3057                           (end (set-marker (make-marker) (max (point) (mark)))))
3058                       (insert " ")
3059                       (goto-char beg)
3060                       (skip-chars-backward "^\\\\")
3061                       (backward-char)
3062                       (insert TeX-arg-opening-brace)
3063                       (goto-char (marker-position end))
3064                       (insert TeX-arg-closing-brace)
3065                       (setq insert-flag t))))
3066                  ((= arg 0)) ; nop for clarity
3067                  ((> arg 0)
3068                   (TeX-parse-argument optional t)
3069                   (while (> arg 1)
3070                     (TeX-parse-argument optional nil)
3071                     (setq arg (- arg 1))))))
3072           ((null arg)
3073            (insert TeX-arg-opening-brace)
3074            (when (and (not optional) (TeX-active-mark))
3075              (exchange-point-and-mark))
3076            (insert TeX-arg-closing-brace)
3077            (setq insert-flag t))
3078           ((eq arg t)
3079            (insert TeX-arg-opening-brace)
3080            (if (and (not optional) (TeX-active-mark))
3081                (progn
3082                  (exchange-point-and-mark))
3083              (set-marker exit-mark (point)))
3084            (insert TeX-arg-closing-brace)
3085            (setq insert-flag t))
3086           ((symbolp arg)
3087            (funcall arg optional))
3088           ((listp arg)
3089            (let ((head (car arg))
3090                  (tail (cdr arg)))
3091              (cond ((stringp head)
3092                     (apply 'TeX-arg-string optional arg))
3093                    ((symbolp head)
3094                     (apply head optional tail))
3095                    (t (error "Unknown list argument type %s"
3096                              (prin1-to-string head))))))
3097           (t (error "Unknown argument type %s" (prin1-to-string arg))))
3098     (when (and insert-flag (not optional) (TeX-active-mark))
3099       (TeX-deactivate-mark))))
3100
3101 (defun TeX-argument-insert (name optional &optional prefix)
3102   "Insert NAME surrounded by curly braces.
3103
3104 If OPTIONAL, only insert it if not empty, and then use square brackets.
3105 If PREFIX is given, insert it before NAME."
3106   (if (and optional (string-equal name ""))
3107       (setq last-optional-rejected t)
3108     (insert TeX-arg-opening-brace)
3109     (if prefix
3110         (insert prefix))
3111     (if (and (string-equal name "")
3112              (null (marker-position exit-mark)))
3113         (set-marker exit-mark (point))
3114       (insert name))
3115     (insert TeX-arg-closing-brace)))
3116
3117 (defun TeX-argument-prompt (optional prompt default &optional complete)
3118   "Return a argument prompt.
3119
3120 If OPTIONAL is not nil then the prompt will start with ``(Optional) ''.
3121
3122 PROMPT will be used if not nil, otherwise use DEFAULT.
3123
3124 Unless optional argument COMPLETE is non-nil, ``: '' will be appended."
3125   (concat (if optional "(Optional) " "")
3126           (if prompt prompt default)
3127           (if complete "" ": ")))
3128
3129 (defun TeX-string-divide-number-unit (string)
3130   "Divide number and unit in STRING.
3131 Return the number as car and unit as cdr."
3132   (if (string-match "[0-9]*\\.?[0-9]+" string)
3133       (list (substring string 0 (string-match "[^.0-9]" string))
3134             (substring string (if (string-match "[^.0-9]" string)
3135                                   (string-match "[^.0-9]" string)
3136                                 (length string))))
3137     (list "" string)))
3138
3139 (defcustom TeX-default-unit-for-image "cm"
3140   "Default unit when prompting for an image size."
3141   :group 'TeX-macro
3142   :type '(choice (const "cm")
3143                  (const "in")
3144                  (const "\\linewidth")
3145                  (string :tag "Other")))
3146
3147 (defun TeX-arg-maybe (symbol list form)
3148   "Evaluates FORM, if SYMBOL is an element of LIST."
3149   (when (memq symbol list)
3150     (eval form)))
3151
3152 (defun TeX-arg-free (optional &rest args)
3153   "Parse its arguments but use no braces when they are inserted."
3154   (let ((TeX-arg-opening-brace "")
3155         (TeX-arg-closing-brace ""))
3156     (if (equal (length args) 1)
3157         (TeX-parse-argument optional (car args))
3158       (TeX-parse-argument optional args))))
3159
3160 (defun TeX-arg-literal (optional &rest args)
3161   "Insert its arguments ARGS into the buffer.
3162 Used for specifying extra syntax for a macro.  The compatibility
3163 argument OPTION is ignored."
3164   (apply 'insert args))
3165
3166
3167 ;;; Font Locking
3168
3169 (defcustom TeX-install-font-lock 'font-latex-setup
3170   "Function to call to install font lock support.
3171 Choose `ignore' if you don't want AUCTeX to install support for font locking."
3172   :group 'TeX-misc
3173   :type '(radio (function-item font-latex-setup)
3174                 (function-item tex-font-setup)
3175                 (function-item ignore)
3176                 (function :tag "Other")))
3177
3178 ;;; The Mode
3179
3180 (defvar TeX-format-list
3181   '(("JLATEX" japanese-latex-mode
3182      "\\\\\\(documentstyle\\|documentclass\\)[^%\n]*{\\(j[s-]?\\|t\\)\
3183 \\(article\\|report\\|book\\|slides\\)")
3184     ("JTEX" japanese-plain-tex-mode
3185      "-- string likely in Japanese TeX --")
3186     ("AMSTEX" ams-tex-mode
3187      "\\\\document\\b")
3188     ("CONTEXT" context-mode
3189      "\\\\\\(start\\(text\\|tekst\\|proje[ck]t\\|proiect\\|\
3190 produ[ck]t\\|produs\\|environment\\|omgeving\\|umgebung\\|prostredi\\|mediu\\|\
3191 component\\|onderdeel\\|komponent[ea]\\|componenta\\)\
3192 \\|inizia\\(testo\\|progetto\\|prodotto\\|ambiente\\|componente\\)\
3193 \\)\\|%.*?interface=")
3194     ("LATEX" latex-mode
3195      "\\\\\\(begin\\|\\(?:sub\\)\\{0,2\\}section\\|chapter\\|documentstyle\\|\
3196 documentclass\\)\\b")
3197     ("TEX" plain-tex-mode "."))
3198   "*List of format packages to consider when choosing a TeX mode.
3199
3200 A list with an entry for each format package available at the site.
3201
3202 Each entry is a list with three elements.
3203
3204 1. The name of the format package.
3205 2. The name of the major mode.
3206 3. A regexp typically matched in the beginning of the file.
3207
3208 When entering `tex-mode', each regexp is tried in turn in order to find
3209 the major mode to be used.")
3210
3211 (defcustom TeX-default-mode 'latex-mode
3212   "*Mode to enter for a new file when it can't be determined otherwise."
3213   :group 'TeX-misc
3214   :type '(radio (function-item latex-mode)
3215                 (function-item plain-tex-mode)
3216                 (function :tag "Other")))
3217
3218 (defcustom TeX-force-default-mode nil
3219   "*If set to nil, try to infer the mode of the file from its content."
3220   :group 'TeX-misc
3221   :type 'boolean)
3222
3223 ;;;###autoload
3224 (defun TeX-tex-mode ()
3225   "Major mode in AUCTeX for editing TeX or LaTeX files.
3226 Tries to guess whether this file is for plain TeX or LaTeX.
3227
3228 The algorithm is as follows:
3229
3230    1) if the file is empty or `TeX-force-default-mode' is not set to nil,
3231       `TeX-default-mode' is chosen
3232    2) If \\documentstyle or \\begin{, \\section{, \\part{ or \\chapter{ is
3233       found, `latex-mode' is selected.
3234    3) Otherwise, use `plain-tex-mode'"
3235   (interactive)
3236
3237   (funcall (if (or (equal (buffer-size) 0)
3238                    TeX-force-default-mode)
3239                TeX-default-mode
3240              (save-excursion
3241                (goto-char (point-min))
3242                (let ((comment-start-skip ;Used by TeX-in-comment
3243                       (concat
3244                        "\\(\\(^\\|[^\\\n]\\)\\("
3245                        (regexp-quote TeX-esc)
3246                        (regexp-quote TeX-esc)
3247                        "\\)*\\)\\(%+ *\\)"))
3248                      (entry TeX-format-list)
3249                      answer)
3250                  (while (and entry (not answer))
3251                    (if (re-search-forward (nth 2 (car entry))
3252                                           10000 t)
3253                        (if (not (TeX-in-comment))
3254                            (setq answer (nth 1 (car entry))))
3255                      (setq entry (cdr entry))))
3256                  (if answer
3257                      answer
3258                    TeX-default-mode))))))
3259
3260 (defun VirTeX-common-initialization ()
3261   "Perform basic initialization."
3262   (kill-all-local-variables)
3263   (setq TeX-mode-p t)
3264   (setq TeX-output-extension (if TeX-PDF-mode "pdf" "dvi"))
3265   (setq indent-tabs-mode nil)
3266
3267   ;; Ispell support
3268   (set (make-local-variable 'ispell-parser) 'tex)
3269   (set (make-local-variable 'ispell-tex-p) t)
3270
3271   ;; Redefine some standard variables
3272   (make-local-variable 'paragraph-start)
3273   (make-local-variable 'paragraph-separate)
3274   (set (make-local-variable 'comment-start) "%")
3275   (set (make-local-variable 'comment-start-skip)
3276         (concat
3277          "\\(\\(^\\|[^\\\n]\\)\\("
3278          (regexp-quote TeX-esc)
3279          (regexp-quote TeX-esc)
3280          "\\)*\\)\\(%+[ \t]*\\)"))
3281   (set (make-local-variable 'comment-end-skip) "[ \t]*\\(\\s>\\|\n\\)")
3282   (set (make-local-variable 'comment-use-syntax) t)
3283   ;; `comment-padding' is defined here as an integer for compatibility
3284   ;; reasons because older Emacsen could not cope with a string.
3285   (set (make-local-variable 'comment-padding) 1)
3286   ;; Removed as commenting in (La)TeX is done with one `%' not two
3287   ;; (make-local-variable 'comment-add)
3288   ;; (setq comment-add 1) ;default to `%%' in comment-region
3289   (set (make-local-variable 'comment-indent-function) 'TeX-comment-indent)
3290   (set (make-local-variable 'comment-multi-line) nil)
3291   (make-local-variable 'compile-command)
3292   (unless (boundp 'compile-command)
3293     (setq compile-command "make"))
3294   (set (make-local-variable 'words-include-escapes) nil)
3295
3296   ;; Make TAB stand out
3297   ;;  (make-local-variable 'buffer-display-table)
3298   ;;  (setq buffer-display-table (if standard-display-table
3299   ;;                             (copy-sequence standard-display-table)
3300   ;;                           (make-display-table)))
3301   ;;  (aset buffer-display-table ?\t (apply 'vector (append "<TAB>" nil)))
3302
3303   ;; Symbol completion.
3304   (set (make-local-variable 'TeX-complete-list)
3305         (list (list "\\\\\\([a-zA-Z]*\\)"
3306                     1 'TeX-symbol-list-filtered
3307                     (if TeX-insert-braces "{}"))
3308               (list "" TeX-complete-word)))
3309
3310   (funcall TeX-install-font-lock)
3311
3312   ;; We want this to be early in the list, so we do not add it before
3313   ;; we enter TeX mode  the first time.
3314   (if (boundp 'local-write-file-hooks)
3315       (add-hook 'local-write-file-hooks 'TeX-safe-auto-write)
3316     (add-hook 'write-file-hooks 'TeX-safe-auto-write))
3317   (set (make-local-variable 'TeX-auto-update) t)
3318
3319   (define-key TeX-mode-map "\C-xng" 'TeX-narrow-to-group)
3320
3321   ;; Minor modes
3322   (when TeX-source-correlate-mode
3323     (TeX-source-correlate-mode 1))
3324
3325   ;; Let `TeX-master-file' be called after a new file was opened and
3326   ;; call `TeX-update-style' on any file opened.  (The addition to the
3327   ;; hook has to be made here because its local value will be deleted
3328   ;; by `kill-all-local-variables' if it is added e.g. in `tex-mode'.)
3329   ;;
3330   ;; `TeX-update-style' has to be called before
3331   ;; `global-font-lock-mode', which may also be specified in
3332   ;; `find-file-hooks', gets called.  Otherwise style-based
3333   ;; fontification will break (in XEmacs).  That means, `add-hook'
3334   ;; cannot be called with a non-nil value of the APPEND argument.
3335   ;;
3336   ;; `(TeX-master-file nil nil t)' has to be called *before*
3337   ;; `TeX-update-style' as the latter will call `TeX-master-file'
3338   ;; without the `ask' bit set.
3339   (when (and (featurep 'xemacs) (not (emacs-version>= 21 5)))
3340     (make-local-hook 'find-file-hooks))
3341   (add-hook 'find-file-hooks
3342             (lambda ()
3343               ;; Check if we are looking at a new or shared file.
3344               (when (or (not (file-exists-p (buffer-file-name)))
3345                         (eq TeX-master 'shared))
3346                 (TeX-master-file nil nil t))
3347               (TeX-update-style t)) nil t))
3348
3349
3350 ;;; Hilighting
3351
3352 (if (boundp 'hilit-patterns-alist)
3353     (let ((latex-patterns (cdr-safe (assq 'latex-mode hilit-patterns-alist)))
3354           (plain-tex-patterns (cdr-safe (assq 'plain-tex-mode
3355                                               hilit-patterns-alist))))
3356       (if (and latex-patterns plain-tex-patterns)
3357           (setq hilit-patterns-alist
3358                 (append (list (cons 'ams-tex-mode plain-tex-patterns))
3359                         hilit-patterns-alist)))))
3360
3361 ;;; Parsing
3362
3363 (defgroup TeX-parse nil
3364   "Parsing TeX files from AUCTeX."
3365   :group 'AUCTeX)
3366
3367 (defvar TeX-auto-parser '((styles TeX-auto-file TeX-run-style-hooks)))
3368 ;; Alist of parsed information.
3369 ;; Each entry is a list with the following elements:
3370 ;;
3371 ;; 0. Name of information type.
3372 ;; 1. Name of temporary variable used when parsing.
3373 ;; 2. Name of function to add information to add to #3.
3374 ;; 3. Name of variable holding buffer local information.
3375 ;; 4. Name of variable indicating that #3 has changed.
3376
3377
3378 (defconst TeX-auto-parser-temporary 1)
3379 (defconst TeX-auto-parser-add 2)
3380 (defconst TeX-auto-parser-local 3)
3381 (defconst TeX-auto-parser-change 4)
3382
3383 (defun TeX-auto-add-information (name entries)
3384   "For NAME in `TeX-auto-parser' add ENTRIES."
3385   (let* ((entry (assoc name TeX-auto-parser))
3386          (change (nth TeX-auto-parser-change entry))
3387          (change-value (symbol-value change))
3388          (local (nth TeX-auto-parser-local entry))
3389          (local-value (symbol-value local)))
3390     (if change-value
3391         (set local (cons entries local-value))
3392       (set change t)
3393       (set local (list entries local-value)))))
3394
3395 (defun TeX-auto-list-information (name)
3396   "Return information in `TeX-auto-parser' about NAME."
3397   (TeX-update-style)
3398   (let* ((entry (assoc name TeX-auto-parser))
3399          (change (nth TeX-auto-parser-change entry))
3400          (change-value (symbol-value change))
3401          (local (nth TeX-auto-parser-local entry)))
3402     (if (not change-value)
3403         ()
3404       (set change nil)
3405       ;; Sort it
3406       (message "Sorting %s..." name)
3407       (set local
3408            (sort (mapcar 'TeX-listify (apply 'append (symbol-value local)))
3409                  'TeX-car-string-lessp))
3410       ;; Make it unique
3411       (message "Removing duplicates...")
3412       (let ((entry (symbol-value local)))
3413         (while (and entry (cdr entry))
3414           (let ((this (car entry))
3415                 (next (car (cdr entry))))
3416             (if (not (string-equal (car this) (car next)))
3417                 (setq entry (cdr entry))
3418               ;; We have two equal symbols.  Use the one with
3419               ;; most arguments.
3420               (if (> (length next) (length this))
3421                   (setcdr this (cdr next)))
3422               (setcdr entry (cdr (cdr entry)))))))
3423       (message "Removing duplicates... done"))
3424     (symbol-value local)))
3425
3426 (defmacro TeX-auto-add-type (name prefix &optional plural)
3427   "Add information about NAME to the parser using PREFIX.
3428
3429 Optional third argument PLURAL is the plural form of TYPE.
3430 By default just add an `s'.
3431
3432 This function create a set of variables and functions to maintain a
3433 separate type of information in the parser."
3434   (let* ((names (or plural (concat name "s")))
3435          (tmp (intern (concat prefix "-auto-" name)))
3436          (add (intern (concat prefix "-add-" names)))
3437          (local (intern (concat prefix "-" name "-list")))
3438          (change (intern (concat prefix "-" name "-changed")))
3439          (vardoc (concat "Information about " names
3440                           " in the current buffer.
3441 Generated by `TeX-auto-add-type'.")))
3442     `(progn
3443        (defvar ,tmp nil ,vardoc)
3444        (defvar ,local nil ,vardoc)
3445        (make-variable-buffer-local ',local)
3446        (defvar ,change nil ,vardoc)
3447        (make-variable-buffer-local ',change)
3448        (defun ,add (&rest ,(intern names))
3449          ,(concat "Add information about " (upcase names)
3450                   " to the current buffer.
3451 Generated by `TeX-auto-add-type'.")
3452          (TeX-auto-add-information ,name ,(intern names)))
3453        (defun ,local ()
3454          ,(concat "List of " names
3455                   " active in the current buffer.
3456 Generated by `TeX-auto-add-type'.")
3457          (TeX-auto-list-information ,name))
3458        ;; Append new type to `TeX-auto-parser' in order to make `style' type
3459        ;; always the first.
3460        (add-to-list 'TeX-auto-parser ',(list name tmp add local change) t)
3461        (add-hook 'TeX-remove-style-hook
3462                  (lambda ()
3463                    (setq ,local nil))))))
3464
3465 (TeX-auto-add-type "symbol" "TeX")
3466
3467 (defvar TeX-auto-apply-hook nil
3468   "Hook run when a buffer is parsed and the information is applied.")
3469
3470 (defun TeX-auto-apply ()
3471   "Parse and apply TeX information in the current buffer."
3472   (TeX-auto-parse)
3473   (run-hooks 'TeX-auto-apply-hook)
3474   (mapcar 'TeX-auto-apply-entry TeX-auto-parser))
3475
3476 (defun TeX-auto-apply-entry (entry)
3477   "Apply the information in ENTRY in `TeX-auto-parser'."
3478   (let ((value (symbol-value (nth TeX-auto-parser-temporary entry)))
3479         (add (nth TeX-auto-parser-add entry)))
3480     (if value (apply add value))))
3481
3482 (defun TeX-safe-auto-write ()
3483   "Call `TeX-auto-write' safely."
3484   (condition-case name
3485       (and (boundp 'TeX-auto-update)
3486            TeX-auto-update
3487            (TeX-auto-write))
3488     (error nil))
3489   ;; Continue with the other write file hooks.
3490   nil)
3491
3492 (defcustom TeX-auto-save nil
3493   "*Automatically save style information when saving the buffer."
3494   :group 'TeX-parse
3495   :type 'boolean)
3496
3497 (defcustom TeX-auto-untabify nil
3498   "*Automatically untabify when saving the buffer."
3499   :group 'TeX-parse
3500   :type 'boolean)
3501
3502 (defun TeX-auto-write ()
3503   "Save all relevant TeX information from the current buffer."
3504   (if TeX-auto-untabify
3505       (untabify (point-min) (point-max)))
3506   (if (and TeX-auto-save TeX-auto-local)
3507       (let* ((file (expand-file-name
3508                     (concat
3509                      (file-name-as-directory TeX-auto-local)
3510                      (TeX-strip-extension nil TeX-all-extensions t)
3511                      ".el")
3512                     (TeX-master-directory)))
3513              (dir (file-name-directory file)))
3514         ;; Create auto directory if possible.
3515         (if (not (file-exists-p dir))
3516             (condition-case name
3517                 (make-directory dir)
3518               (error nil)))
3519         (if (file-writable-p file)
3520             (save-excursion
3521               (TeX-update-style)
3522               (TeX-auto-store file))
3523           (message "Can't write style information.")))))
3524
3525 (defcustom TeX-macro-default (car-safe TeX-macro-private)
3526   "*Default directory to search for TeX macros."
3527   :group 'TeX-file
3528   :type 'directory)
3529
3530 (defcustom TeX-auto-default (car-safe TeX-auto-private)
3531   "*Default directory to place automatically generated TeX information."
3532   :group 'TeX-file
3533   :type 'directory)
3534
3535 (defcustom TeX-ignore-file
3536   "\\(^\\|[/\\]\\)\\(\\.\\|\\.\\.\\|RCS\\|SCCS\\|CVS\\|babel\\..*\\)$"
3537   "Regular expression matching file names to ignore.
3538
3539 These files or directories will not be considered when searching for
3540 TeX files in a directory."
3541   :group 'TeX-parse
3542   :type 'regexp)
3543
3544 (defcustom TeX-file-recurse t
3545   "Whether to search TeX directories recursively.
3546 nil means do not recurse, a positive integer means go that far deep in the
3547 directory hierarchy, t means recurse indefinitely."
3548   :group 'TeX-parse
3549   :type '(choice (const :tag "On" t)
3550                  (const :tag "Off" nil)
3551                  (integer :tag "Depth" :value 1)))
3552
3553 ;;;###autoload
3554 (defun TeX-auto-generate (tex auto)
3555   "Generate style file for TEX and store it in AUTO.
3556 If TEX is a directory, generate style files for all files in the directory."
3557   (interactive (list (setq TeX-macro-default
3558                            (expand-file-name (read-file-name
3559                                               "TeX file or directory: "
3560                                               TeX-macro-default
3561                                               TeX-macro-default 'confirm)))
3562                      (setq TeX-auto-default
3563                            (expand-file-name (read-file-name
3564                                               "AUTO lisp directory: "
3565                                               TeX-auto-default
3566                                               TeX-auto-default 'confirm)))))
3567   (cond ((not (file-readable-p tex)))
3568         ((string-match TeX-ignore-file tex))
3569         ((file-directory-p tex)
3570          (let ((files (directory-files (expand-file-name tex)))
3571                (default-directory (file-name-as-directory
3572                                    (expand-file-name tex)))
3573                (TeX-file-recurse (cond ((symbolp TeX-file-recurse)
3574                                         TeX-file-recurse)
3575                                        ((zerop TeX-file-recurse)
3576                                         nil)
3577                                        ((1- TeX-file-recurse)))))
3578            (mapcar (lambda (file)
3579                      (if (or TeX-file-recurse
3580                              (not (file-directory-p file)))
3581                          (TeX-auto-generate file auto)))
3582                    files)))
3583         ((not (file-newer-than-file-p
3584                tex
3585                (concat (file-name-as-directory auto)
3586                        (TeX-strip-extension tex TeX-all-extensions t)
3587                        ".el"))))
3588         ((TeX-match-extension tex (TeX-delete-duplicate-strings
3589                                    (append TeX-file-extensions
3590                                            BibTeX-file-extensions
3591                                            TeX-Biber-file-extensions)))
3592          (with-current-buffer (let (enable-local-eval)
3593                                 (find-file-noselect tex))
3594            (message "Parsing %s..." tex)
3595            (TeX-auto-store (concat (file-name-as-directory auto)
3596                                    (TeX-strip-extension tex
3597                                                         TeX-all-extensions
3598                                                         t)
3599                                    ".el"))
3600            (kill-buffer (current-buffer))
3601            (message "Parsing %s... done" tex)))))
3602
3603 ;;;###autoload
3604 (defun TeX-auto-generate-global ()
3605   "Create global auto directory for global TeX macro definitions."
3606   (interactive)
3607   (unless (file-directory-p TeX-auto-global)
3608     (make-directory TeX-auto-global))
3609   (let ((TeX-file-extensions '("cls" "sty"))
3610         (BibTeX-file-extensions nil)
3611         (TeX-Biber-file-extensions nil))
3612     (mapc (lambda (macro) (TeX-auto-generate macro TeX-auto-global))
3613           TeX-macro-global))
3614   (byte-recompile-directory TeX-auto-global 0))
3615
3616 (defun TeX-auto-store (file)
3617   "Extract information for AUCTeX from current buffer and store it in FILE."
3618   (TeX-auto-parse)
3619
3620   (if (member nil (mapcar 'TeX-auto-entry-clear-p TeX-auto-parser))
3621       (let ((style (TeX-strip-extension nil TeX-all-extensions t))
3622             (class-opts (if (boundp 'LaTeX-provided-class-options)
3623                             LaTeX-provided-class-options))
3624             (pkg-opts (if (boundp 'LaTeX-provided-package-options)
3625                           LaTeX-provided-package-options)))
3626         (TeX-unload-style style)
3627         (with-current-buffer (generate-new-buffer file)
3628           (erase-buffer)
3629           (insert "(TeX-add-style-hook\n \""
3630                   style "\"\n (lambda ()")
3631           (when class-opts
3632             (insert "\n   (TeX-add-to-alist 'LaTeX-provided-class-options\n"
3633                     "                     '" (prin1-to-string class-opts) ")"))
3634           (when pkg-opts
3635             (insert "\n   (TeX-add-to-alist 'LaTeX-provided-package-options\n"
3636                     "                     '" (prin1-to-string pkg-opts) ")"))
3637           (mapc (lambda (el) (TeX-auto-insert el style))
3638                 TeX-auto-parser)
3639           (insert "))\n\n")
3640           (write-region (point-min) (point-max) file nil 'silent)
3641           (kill-buffer (current-buffer))))
3642     (if (file-exists-p (concat file "c"))
3643         (delete-file (concat file "c")))
3644     (if (file-exists-p file)
3645         (delete-file file))))
3646
3647 (defun TeX-auto-entry-clear-p (entry)
3648   "Check if the temporary for `TeX-auto-parser' entry ENTRY is clear."
3649   ;; FIXME: This doc-string isn't clear to me.  -- rs
3650   (null (symbol-value (nth TeX-auto-parser-temporary entry))))
3651
3652 (defun TeX-auto-insert (entry &optional skip)
3653   "Insert code to initialize ENTRY from `TeX-auto-parser'.
3654
3655 If SKIP is not-nil, don't insert code for SKIP."
3656   (let ((name (symbol-name (nth TeX-auto-parser-add entry)))
3657         (list (symbol-value (nth TeX-auto-parser-temporary entry))))
3658     (unless (null list)
3659       (insert "\n   (" name)
3660       (dolist (el list)
3661         (cond ((and (stringp el) (not (string= el skip)))
3662                (insert "\n    ")
3663                (insert (prin1-to-string el)))
3664               ((not (stringp el))
3665                (insert "\n    ")
3666                (insert "'" (prin1-to-string el)))))
3667       (insert ")"))))
3668
3669 (defvar TeX-auto-ignore
3670   '("csname" "filedate" "fileversion" "docdate" "next" "labelitemi"
3671     "labelitemii" "labelitemiii" "labelitemiv" "labelitemv"
3672     "labelenumi" "labelenumii" "labelenumiii" "labelenumiv"
3673     "labelenumv" "theenumi" "theenumii" "theenumiii" "theenumiv"
3674     "theenumv" "document" "par" "do" "expandafter")
3675   "List of symbols to ignore when scanning a TeX style file.")
3676
3677 (defcustom TeX-auto-regexp-list 'TeX-auto-full-regexp-list
3678   "List of regular expressions used for parsing the current file."
3679   :type '(radio (variable-item TeX-auto-empty-regexp-list)
3680                 (variable-item TeX-auto-full-regexp-list)
3681                 (variable-item plain-TeX-auto-regexp-list)
3682                 (variable-item LaTeX-auto-minimal-regexp-list)
3683                 (variable-item LaTeX-auto-label-regexp-list)
3684                 (variable-item LaTeX-auto-regexp-list)
3685                 (symbol :tag "Other")
3686                 (repeat :tag "Specify"
3687                         (group (regexp :tag "Match")
3688                                (sexp :tag "Groups")
3689                                symbol)))
3690   :group 'TeX-parse)
3691   (make-variable-buffer-local 'TeX-auto-regexp-list)
3692
3693 (defun TeX-auto-add-regexp (regexp)
3694   "Add REGEXP to `TeX-auto-regexp-list' if not already a member."
3695   (if (symbolp TeX-auto-regexp-list)
3696       (setq TeX-auto-regexp-list (symbol-value TeX-auto-regexp-list)))
3697   (or (memq regexp TeX-auto-regexp-list)
3698       (setq TeX-auto-regexp-list (cons regexp TeX-auto-regexp-list))))
3699
3700 (defvar TeX-auto-empty-regexp-list
3701   '(("<IMPOSSIBLE>\\(\\'\\`\\)" 1 ignore))
3702   "List of regular expressions guaranteed to match nothing.")
3703
3704 (defvar TeX-token-char
3705   (if (featurep 'mule)
3706       "\\(?:[a-zA-Z]\\|\\cj\\)"
3707     "[a-zA-Z]")
3708   "Regexp matching a character in a TeX macro.
3709
3710 Please use a shy group if you use a grouping construct, because
3711 the functions/variables which use `TeX-token-char' expect not to
3712 alter the numbering of any ordinary, non-shy groups.")
3713
3714 (defvar plain-TeX-auto-regexp-list
3715   (let ((token TeX-token-char))
3716     `((,(concat "\\\\def\\\\\\(" token "+\\)[^a-zA-Z@]")
3717        1 TeX-auto-symbol-check)
3718       (,(concat "\\\\let\\\\\\(" token "+\\)[^a-zA-Z@]")
3719        1 TeX-auto-symbol-check)
3720       (,(concat "\\\\font\\\\\\(" token "+\\)[^a-zA-Z@]") 1 TeX-auto-symbol)
3721       (,(concat "\\\\chardef\\\\\\(" token "+\\)[^a-zA-Z@]") 1 TeX-auto-symbol)
3722       (,(concat "\\\\new\\(?:count\\|dimen\\|muskip\\|skip\\)\\\\\\(" token
3723                 "+\\)[^a-zA-Z@]")
3724        1 TeX-auto-symbol)
3725       (,(concat "\\\\newfont{?\\\\\\(" token "+\\)}?") 1 TeX-auto-symbol)
3726       (,(concat "\\\\typein\\[\\\\\\(" token "+\\)\\]") 1 TeX-auto-symbol)
3727       ("\\\\input +\\(\\.*[^#%\\\\\\.\n\r]+\\)\\(\\.[^#%\\\\\\.\n\r]+\\)?"
3728        1 TeX-auto-file)
3729       (,(concat "\\\\mathchardef\\\\\\(" token "+\\)[^a-zA-Z@]")
3730        1 TeX-auto-symbol)))
3731   "List of regular expression matching common LaTeX macro definitions.")
3732
3733 (defvar TeX-auto-full-regexp-list plain-TeX-auto-regexp-list
3734   "Full list of regular expression matching TeX macro definitions.")
3735
3736 (defvar TeX-auto-prepare-hook nil
3737   "List of hooks to be called before parsing a TeX file.")
3738
3739 (defvar TeX-auto-cleanup-hook nil
3740   "List of hooks to be called after parsing a TeX file.")
3741
3742 (defcustom TeX-auto-parse-length 999999
3743   "Maximal length of TeX file (in characters) that will be parsed."
3744   :group 'TeX-parse
3745   :type 'integer)
3746   (make-variable-buffer-local 'TeX-auto-parse-length)
3747
3748 (defcustom TeX-auto-x-parse-length 0
3749   "Maximum length of TeX file that will be parsed additionally.
3750 Use `TeX-auto-x-regexp-list' for parsing the region between
3751 `TeX-auto-parse-length' and this value."
3752   :group 'TeX-parse
3753   :type 'integer)
3754   (make-variable-buffer-local 'TeX-auto-x-parse-length)
3755
3756 (defcustom TeX-auto-x-regexp-list 'LaTeX-auto-label-regexp-list
3757   "List of regular expressions used for additional parsing.
3758 See `TeX-auto-x-parse-length'."
3759   :type '(radio (variable-item TeX-auto-empty-regexp-list)
3760                 (variable-item TeX-auto-full-regexp-list)
3761                 (variable-item plain-TeX-auto-regexp-list)
3762                 (variable-item LaTeX-auto-minimal-regexp-list)
3763                 (variable-item LaTeX-auto-label-regexp-list)
3764                 (variable-item LaTeX-auto-regexp-list)
3765                 (symbol :tag "Other")
3766                 (repeat :tag "Specify"
3767                         (group (regexp :tag "Match")
3768                                (sexp :tag "Groups")
3769                                symbol)))
3770   :group 'TeX-parse)
3771   (make-variable-buffer-local 'TeX-auto-x-regexp-list)
3772
3773 (defun TeX-regexp-group-count (regexp)
3774   "Return number of groups in a REGEXP.  This is not foolproof:
3775 you should not use something like `[\\(]' for a character range."
3776   (let (start (n 0))
3777     (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\([^?]"
3778                          regexp start)
3779       (setq start (- (match-end 0) 2)
3780             n (1+ n)))
3781     n))
3782
3783 (defun TeX-auto-parse-region (regexp-list beg end)
3784   "Parse TeX information according to REGEXP-LIST between BEG and END."
3785   (if (symbolp regexp-list)
3786       (setq regexp-list (and (boundp regexp-list) (symbol-value regexp-list))))
3787    (if regexp-list
3788        ;; Extract the information.
3789        (let* (groups
3790               (count 1)
3791               (regexp (concat "\\("
3792                               (mapconcat
3793                                (lambda(x)
3794                                  (push (cons count x) groups)
3795                                  (setq count
3796                                        (+ 1 count
3797                                           (TeX-regexp-group-count (car x))))
3798                                  (car x))
3799                                regexp-list "\\)\\|\\(")
3800                               "\\)"))
3801               syms
3802               lst)
3803          (setq count 0)
3804          (goto-char (if end (min end (point-max)) (point-max)))
3805          (while (re-search-backward regexp beg t)
3806            (let* ((entry (cdr (TeX-member nil groups
3807                                           (lambda (a b)
3808                                             (match-beginning (car b))))))
3809                   (symbol (nth 2 entry))
3810                   (match (nth 1 entry)))
3811              (unless (TeX-in-comment)
3812                (looking-at (nth 0 entry))
3813                (if (fboundp symbol)
3814                    (funcall symbol match)
3815                  (puthash (if (listp match)
3816                               (mapcar #'TeX-match-buffer match)
3817                             (TeX-match-buffer match))
3818                           (setq count (1- count))
3819                           (cdr (or (assq symbol syms)
3820                                    (car (push
3821                                          (cons symbol
3822                                                (make-hash-table :test 'equal))
3823                                          syms)))))))))
3824          (setq count 0)
3825          (dolist (symbol syms)
3826            (setq lst (symbol-value (car symbol)))
3827            (while lst
3828              (puthash (pop lst)
3829                       (setq count (1+ count))
3830                       (cdr symbol)))
3831            (maphash (lambda (key value)
3832                       (push (cons value key) lst))
3833                     (cdr symbol))
3834            (clrhash (cdr symbol))
3835            (set (car symbol) (mapcar #'cdr (sort lst #'car-less-than-car)))))))
3836
3837
3838 (defun TeX-auto-parse ()
3839   "Parse TeX information in current buffer.
3840
3841 Call the functions in `TeX-auto-prepare-hook' before parsing, and the
3842 functions in `TeX-auto-cleanup-hook' after parsing."
3843
3844   (let ((case-fold-search nil))
3845
3846     (mapc 'TeX-auto-clear-entry TeX-auto-parser)
3847     (run-hooks 'TeX-auto-prepare-hook)
3848
3849     (save-excursion
3850       (and (> TeX-auto-x-parse-length TeX-auto-parse-length)
3851            (> (point-max) TeX-auto-parse-length)
3852            (TeX-auto-parse-region TeX-auto-x-regexp-list
3853                                   TeX-auto-parse-length
3854                                   TeX-auto-x-parse-length))
3855       (TeX-auto-parse-region TeX-auto-regexp-list
3856                              nil TeX-auto-parse-length))
3857
3858     ;; Cleanup ignored symbols.
3859
3860     ;; NOTE: This is O(N M) where it could be O(N log N + M log M) if we
3861     ;; sorted the lists first.
3862     (while (member (car TeX-auto-symbol) TeX-auto-ignore)
3863       (setq TeX-auto-symbol (cdr TeX-auto-symbol)))
3864     (let ((list TeX-auto-symbol))
3865       (while (and list (cdr list))
3866         (if (member (car (cdr list)) TeX-auto-ignore)
3867             (setcdr list (cdr (cdr list)))
3868           (setq list (cdr list)))))
3869
3870     (run-hooks 'TeX-auto-cleanup-hook)))
3871
3872 (defun TeX-auto-clear-entry (entry)
3873   "Set the temporary variable in ENTRY to nil."
3874   (set (nth TeX-auto-parser-temporary entry) nil))
3875
3876 (defvar LaTeX-auto-end-symbol nil)
3877
3878 (defun TeX-auto-symbol-check (match)
3879   "Add MATCH to TeX-auto-symbols.
3880 Check for potential LaTeX environments."
3881   (let ((symbol (if (listp match)
3882                     (mapcar 'TeX-match-buffer match)
3883                   (TeX-match-buffer match))))
3884     (if (and (stringp symbol)
3885              (string-match "^end\\(.+\\)$" symbol))
3886         (add-to-list 'LaTeX-auto-end-symbol
3887                      (substring symbol (match-beginning 1) (match-end 1)))
3888       (if (listp symbol)
3889           (dolist (elt symbol)
3890             (add-to-list 'TeX-auto-symbol elt))
3891         (add-to-list 'TeX-auto-symbol symbol)))))
3892
3893
3894 ;;; File Extensions
3895
3896 (defgroup TeX-file-extension nil
3897   "File extensions recognized by AUCTeX."
3898   :group 'TeX-file)
3899
3900 (defcustom TeX-file-extensions '("tex" "sty" "cls" "ltx" "texi" "txi" "texinfo" "dtx")
3901   "*File extensions used by manually generated TeX files."
3902   :group 'TeX-file-extension
3903   :type '(repeat (string :format "%v")))
3904
3905 (defcustom TeX-all-extensions '("[^.\n]+")
3906   "All possible file extensions."
3907   :group 'TeX-file-extension
3908   :type '(repeat (regexp :format "%v")))
3909
3910 (defcustom TeX-default-extension "tex"
3911   "*Default extension for TeX files."
3912   :group 'TeX-file-extension
3913   :type 'string)
3914
3915   (make-variable-buffer-local 'TeX-default-extension)
3916
3917 (defvar TeX-doc-extensions
3918   '("dvi" "pdf" "ps" "txt" "html" "dvi.gz" "pdf.gz" "ps.gz" "txt.gz" "html.gz"
3919     "dvi.bz2" "pdf.bz2" "ps.bz2" "txt.bz2" "html.bz2")
3920   "File extensions of documentation files.")
3921
3922 (defcustom docTeX-default-extension "dtx"
3923   "*Default extension for docTeX files."
3924   :group 'TeX-file-extension
3925   :type 'string)
3926
3927 (defvar TeX-output-extension nil
3928   "Extension of TeX output file.
3929 This is either a string or a list with
3930 a string as element.  Its value is obtained from `TeX-command-output-list'.
3931 Access to the value should be through the function `TeX-output-extension'.")
3932
3933   (make-variable-buffer-local 'TeX-output-extension)
3934
3935 (defcustom TeX-Biber-file-extensions '("bib" "ris" "xml")
3936   "Valid file extensions for Biber files."
3937   :group 'TeX-file-extension
3938   :type '(repeat (string :format "%v")))
3939
3940 (defcustom BibTeX-file-extensions '("bib")
3941   "Valid file extensions for BibTeX files."
3942   :group 'TeX-file-extension
3943   :type '(repeat (string :format "%v")))
3944
3945 (defcustom BibLaTeX-style-extensions '("bbx")
3946   "Valid file extensions for BibLaTeX styles."
3947   :group 'TeX-file-extension
3948   :type '(repeat (string :format "%v")))
3949
3950 (defcustom BibTeX-style-extensions '("bst")
3951   "Valid file extensions for BibTeX styles."
3952   :group 'TeX-file-extension
3953   :type '(repeat (string :format "%v")))
3954
3955 (defun TeX-match-extension (file &optional extensions)
3956   "Return non-nil if FILE has one of EXTENSIONS.
3957
3958 If EXTENSIONS is not specified or nil, the value of
3959 `TeX-file-extensions' is used instead."
3960
3961   (if (null extensions)
3962       (setq extensions TeX-file-extensions))
3963
3964   (let ((regexp (concat "\\.\\("
3965                         (mapconcat 'identity extensions "\\|")
3966                         "\\)$"))
3967         (case-fold-search t))
3968     (string-match regexp file)))
3969
3970 (defun TeX-strip-extension (&optional string extensions nodir nostrip)
3971   "Return STRING without any trailing extension in EXTENSIONS.
3972 If NODIR is t, also remove directory part of STRING.
3973 If NODIR is `path', remove directory part of STRING if it is equal to
3974 the current directory, `TeX-macro-private' or `TeX-macro-global'.
3975 If NOSTRIP is set, do not remove extension after all.
3976 STRING defaults to the name of the current buffer.
3977 EXTENSIONS defaults to `TeX-file-extensions'."
3978
3979   (if (null string)
3980       (setq string (or (buffer-file-name) "<none>")))
3981
3982   (if (null extensions)
3983       (setq extensions TeX-file-extensions))
3984
3985   (let* ((strip (if (and (not nostrip)
3986                          (TeX-match-extension string extensions))
3987                     (substring string 0 (match-beginning 0))
3988                   string))
3989          (dir (expand-file-name (or (file-name-directory strip) "./"))))
3990     (if (or (eq nodir t)
3991             (string-equal dir (expand-file-name "./"))
3992             (member dir TeX-macro-global)
3993             (member dir TeX-macro-private))
3994         (file-name-nondirectory strip)
3995       strip)))
3996
3997
3998 ;;; File Searching
3999
4000 (defun TeX-tree-roots ()
4001   "Return a list of available TeX tree roots."
4002   (let (list)
4003     (dolist (dir (TeX-tree-expand '("$TEXMFHOME" "$TEXMFMAIN" "$TEXMFLOCAL"
4004                                     "$TEXMFDIST") "latex"))
4005       (when (file-readable-p dir)
4006         (add-to-list 'list dir t)))
4007     list))
4008
4009 (defcustom TeX-tree-roots (TeX-tree-roots)
4010   "List of all available TeX tree root directories."
4011   :group 'TeX-file
4012   :type '(repeat directory))
4013
4014 (defcustom TeX-kpathsea-path-delimiter t
4015   "Path delimiter for kpathsea output.
4016 t means autodetect, nil means kpathsea is disabled."
4017   :group 'TeX-file
4018   :type '(choice (const ":")
4019                  (const ";")
4020                  (const :tag "Autodetect" t)
4021                  (const :tag "Off" nil)))
4022
4023 ;; We keep this function in addition to `TeX-search-files' because it
4024 ;; is faster.  Since it does not look further into subdirectories,
4025 ;; this comes at the price of finding a smaller number of files.
4026 (defun TeX-search-files-kpathsea (var extensions scope nodir strip)
4027   "Return a list of files in directories determined by expanding VAR.
4028 Only files which match EXTENSIONS are returned.  SCOPE defines
4029 the scope for the search and can be `local' or `global' besides
4030 nil.  If NODIR is non-nil, remove directory part.  If STRIP is
4031 non-nil, remove file extension."
4032   (and TeX-kpathsea-path-delimiter
4033        (catch 'no-kpathsea
4034          (let* ((dirs (if (eq scope 'local)
4035                           "."
4036                         (with-output-to-string
4037                           (unless (zerop (call-process
4038                                           "kpsewhich" nil
4039                                           (list standard-output nil) nil
4040                                           (concat "-expand-path=" var)))
4041                             (if (eq TeX-kpathsea-path-delimiter t)
4042                                 (throw 'no-kpathsea
4043                                        (setq TeX-kpathsea-path-delimiter nil))
4044                               (error "kpsewhich error"))))))
4045                 result)
4046            (when (eq TeX-kpathsea-path-delimiter t)
4047              (setq TeX-kpathsea-path-delimiter
4048                    (if (string-match ";" dirs) ";" ":")))
4049            (unless TeX-kpathsea-path-delimiter
4050              (throw 'no-kpathsea nil))
4051            (setq dirs (delete "" (split-string
4052                                   dirs (concat "[\n\r"
4053                                                TeX-kpathsea-path-delimiter
4054                                                "]+"))))
4055            (if (eq scope 'global)
4056                (delete "." dirs))
4057            (setq extensions (concat "\\." (regexp-opt extensions t) "\\'")
4058                  result (apply #'append (mapcar (lambda (x)
4059                                                   (when (file-readable-p x)
4060                                                     (directory-files
4061                                                      x (not nodir) extensions)))
4062                                                 dirs)))
4063            (if strip
4064                (mapcar (lambda(x)
4065                          (if (string-match extensions x)
4066                              (substring x 0 (match-beginning 0))
4067                            x))
4068                        result)
4069              result)))))
4070
4071 (defun TeX-search-files (&optional directories extensions nodir strip)
4072   "Return a list of all reachable files in DIRECTORIES ending with EXTENSIONS.
4073 If optional argument NODIR is set, remove directory part.
4074 If optional argument STRIP is set, remove file extension.
4075 If optional argument DIRECTORIES is set, search in those directories.
4076 Otherwise, search in all TeX macro directories.
4077 If optional argument EXTENSIONS is not set, use `TeX-file-extensions'"
4078   (when (null extensions)
4079     (setq extensions TeX-file-extensions))
4080   (when (null directories)
4081     (setq directories (cons "./" (append TeX-macro-private TeX-macro-global))))
4082   (let (match
4083         (TeX-file-recurse (cond ((symbolp TeX-file-recurse)
4084                                  TeX-file-recurse)
4085                                 ((zerop TeX-file-recurse)
4086                                  nil)
4087                                 ((1- TeX-file-recurse)))))
4088     (while directories
4089       (let* ((directory (car directories))
4090              (content (and directory
4091                            (file-readable-p directory)
4092                            (file-directory-p directory)
4093                            (directory-files directory))))
4094         (setq directories (cdr directories))
4095         (while content
4096           (let ((file (concat directory (car content))))
4097             (setq content (cdr content))
4098             (cond ((string-match TeX-ignore-file file))
4099                   ((not (file-readable-p file)))
4100                   ((file-directory-p file)
4101                    (if TeX-file-recurse
4102                        (setq match
4103                              (append match
4104                                      (TeX-search-files
4105                                       (list (file-name-as-directory file))
4106                                       extensions nodir strip)))))
4107                   ((TeX-match-extension file extensions)
4108                    (setq match (cons (TeX-strip-extension
4109                                       file extensions nodir (not strip))
4110                                      match))))))))
4111     match))
4112
4113 ;; The variables `TeX-macro-private' and `TeX-macro-global' are not
4114 ;; used for specifying the directories because the number of
4115 ;; directories to be searched should be limited as much as possible
4116 ;; and the TeX-macro-* variables are just too broad for this.
4117 (defvar TeX-search-files-type-alist
4118   '((texinputs "${TEXINPUTS}" ("tex/") TeX-file-extensions)
4119     (docs "${TEXDOCS}" ("doc/") TeX-doc-extensions)
4120     (graphics "${TEXINPUTS}" ("tex/") LaTeX-includegraphics-extensions)
4121     (bibinputs "${BIBINPUTS}" ("bibtex/bib/") BibTeX-file-extensions)
4122     (bstinputs "${BSTINPUTS}" ("bibtex/bst/") BibTeX-style-extensions))
4123   "Alist of filetypes with locations and file extensions.
4124 Each element of the alist consists of a symbol expressing the
4125 filetype, a variable which can be expanded on kpathsea-based
4126 systems into the directories where files of the given type
4127 reside, a list of absolute directories, relative directories
4128 below the root of a TDS-compliant TeX tree or a list of variables
4129 with either type of directories as an alternative for
4130 non-kpathsea-based systems and a list of extensions to be matched
4131 upon a file search.  Note that the directories have to end with a
4132 directory separator.
4133
4134 Each AUCTeX mode should set the variable buffer-locally with a
4135 more specific value.  See `LateX-search-files-type-alist' for an
4136 example.")
4137
4138 (defun TeX-search-files-by-type (filetype &optional scope nodir strip)
4139   "Return a list of files in TeX's search path with type FILETYPE.
4140 FILETYPE is a symbol used to choose the search paths and
4141 extensions.  See `TeX-search-files-type-alist' for supported
4142 symbols.
4143
4144 The optional argument SCOPE sets the scope for the search.
4145 Besides nil the symbols `local' and `global' are accepted.
4146 `local' means to search in the current directory only, `global'
4147 in the global directories only and nil in both.
4148
4149 If optional argument NODIR is non-nil, remove directory part.
4150
4151 If optional argument STRIP is non-nil, remove file extension."
4152   (let* ((spec (assq filetype TeX-search-files-type-alist))
4153          (kpse-var (nth 1 spec))
4154          (rawdirs (nth 2 spec))
4155          (exts (nth 3 spec))
4156          expdirs dirs local-files)
4157     (setq exts (if (symbolp exts) (eval exts) exts))
4158     (or (TeX-search-files-kpathsea kpse-var exts scope nodir strip)
4159         (progn
4160           (unless (eq scope 'global)
4161             (setq local-files
4162                   (let ((TeX-file-recurse nil))
4163                     (TeX-search-files '("./") exts nodir strip))))
4164           (if (eq scope 'local)
4165               local-files
4166             (if (null TeX-tree-roots)
4167                 (error "No TeX trees available; configure `TeX-tree-roots'")
4168               ;; Expand variables.
4169               (dolist (rawdir rawdirs)
4170                 (if (symbolp rawdir)
4171                     (setq expdirs (append expdirs (eval rawdir)))
4172                   (add-to-list 'expdirs rawdir t)))
4173               (delete-dups expdirs)
4174               ;; Assumption: Either all paths are absolute or all are relative.
4175               (if (file-name-absolute-p (car expdirs))
4176                   (setq dirs expdirs)
4177                 ;; Append relative TDS subdirs to all TeX tree roots.
4178                 (dolist (root TeX-tree-roots)
4179                   (dolist (dir expdirs)
4180                     (add-to-list 'dirs (concat (file-name-as-directory root)
4181                                                dir) t)))))
4182             (append local-files (TeX-search-files dirs exts nodir strip)))))))
4183
4184 ;;; Narrowing
4185
4186 (defun TeX-narrow-to-group ()
4187   "Make text outside current group invisible."
4188   (interactive)
4189   (save-excursion
4190     (widen)
4191     (let ((opoint (point))
4192           beg end)
4193       (if (null (search-backward "{" nil t))
4194           (message "Nothing to be narrowed here.")
4195         (setq beg (point))
4196         (forward-sexp)
4197         (setq end (point))
4198         (if (< end opoint)
4199             (message "Nothing to be narrowed here.")
4200           (narrow-to-region beg end))))))
4201 (put 'TeX-narrow-to-group 'disabled t)
4202
4203 ;;; Utilities
4204 ;;
4205 ;; Some of these functions has little to do with TeX, but nonetheless we
4206 ;; should use the "TeX-" prefix to avoid name clashes.
4207
4208 (defun TeX-car-string-lessp (s1 s2)
4209   "Compare the cars of S1 and S2 in lexicographic order.
4210 Return t if first is less than second in lexicographic order."
4211   (string-lessp (car s1) (car s2)))
4212
4213 (defun TeX-listify (elt)
4214   "Return a newly created list with element ELT.
4215 If ELT already is a list, return ELT."
4216   (if (listp elt) elt (list elt)))
4217
4218 (defun TeX-member (elt list how)
4219   "Return the member ELT in LIST.  Comparison done with HOW.
4220 Return nil if ELT is not a member of LIST."
4221   (while (and list (not (funcall how elt (car list))))
4222     (setq list (cdr list)))
4223   (car-safe list))
4224
4225 (defun TeX-elt-of-list-member (elts list)
4226   "Return non-nil if an element of ELTS is a member of LIST."
4227   (catch 'found
4228     (dolist (elt elts)
4229       (when (member elt list)
4230         (throw 'found t)))))
4231
4232 (defun TeX-assoc (key list)
4233   "Return non-nil if KEY is `equal' to the car of an element of LIST.
4234 Like assoc, except case insensitive."
4235   (let ((case-fold-search t))
4236     (TeX-member key list
4237                 (lambda (a b)
4238                   (string-match (concat "^" (regexp-quote a) "$")
4239                                 (car b))))))
4240
4241 (defun TeX-match-buffer (n)
4242   "Return the substring corresponding to the N'th match.
4243 See `match-data' for details."
4244   (if (match-beginning n)
4245       (buffer-substring-no-properties (match-beginning n) (match-end n))
4246     ""))
4247
4248 (defun TeX-function-p (arg)
4249   "Return non-nil if ARG is callable as a function."
4250   (or (and (fboundp 'byte-code-function-p)
4251            (byte-code-function-p arg))
4252       (and (listp arg)
4253            (eq (car arg) 'lambda))
4254       (and (symbolp arg)
4255            (fboundp arg))))
4256
4257 (defun TeX-booleanp (arg)
4258   "Return non-nil if ARG is t or nil."
4259   (memq arg '(t nil)))
4260
4261 (defun TeX-looking-at-backward (regexp &optional limit)
4262   "Return non-nil if the text before point matches REGEXP.
4263 Optional second argument LIMIT gives a max number of characters
4264 to look backward for."
4265   (let ((pos (point)))
4266     (save-excursion
4267       (and (re-search-backward regexp
4268                                (if limit (max (point-min) (- (point) limit)))
4269                                t)
4270            (eq (match-end 0) pos)))))
4271
4272 (defun TeX-current-line ()
4273   "The current line number."
4274   (format "%d" (1+ (TeX-current-offset))))
4275
4276 (defun TeX-current-file-name-master-relative ()
4277   "Return current filename, relative to master directory."
4278   (file-relative-name
4279    (buffer-file-name)
4280    (TeX-master-directory)))
4281
4282 (defun TeX-near-bobp ()
4283   "Return t iff there's nothing but whitespace between (bob) and (point)."
4284   (save-excursion
4285     (skip-chars-backward " \t\n")
4286     (bobp)))
4287
4288 (defun TeX-deactivate-mark ()
4289   "Deactivate the mark.
4290 This is a compatibility function which works both in Emacs and
4291 XEmacs.  In XEmacs the region is deactivated instead of the
4292 mark which is sort of equivalent."
4293   (if (featurep 'xemacs)
4294       (zmacs-deactivate-region)
4295     (deactivate-mark)))
4296
4297 (defalias 'TeX-run-mode-hooks
4298   (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks))
4299
4300 (defun TeX-add-to-alist (alist-var new-alist)
4301   "Add NEW-ALIST to the ALIST-VAR.
4302 If an element with the same key as the key of an element of
4303 NEW-ALIST is already present in ALIST-VAR, add the new values to
4304 it; if a matching element is not already present, append the new
4305 element to ALIST-VAR."
4306   ;; Loop over all elements of NEW-ALIST.
4307   (while new-alist
4308     (let* ((new-element (car new-alist))
4309            ;; Get the element of ALIST-VAR with the same key of the current
4310            ;; element of NEW-ALIST, if any.
4311            (old-element (assoc (car new-element) (symbol-value alist-var))))
4312       (if old-element
4313           (progn
4314             (set alist-var (delete old-element (symbol-value alist-var)))
4315             ;; Append to `old-element' the values of the current element of
4316             ;; NEW-ALIST.
4317             (mapc (lambda (elt) (add-to-list 'old-element elt t))
4318                   (cdr new-element))
4319             (set alist-var (add-to-list alist-var old-element t)))
4320         (add-to-list alist-var new-element t)))
4321     ;; Next element of NEW-ALIST.
4322     (setq new-alist (cdr new-alist))))
4323
4324 ;;; Syntax Table
4325
4326 (defvar TeX-mode-syntax-table (make-syntax-table)
4327   "Syntax table used while in TeX mode.")
4328
4329  (make-variable-buffer-local 'TeX-mode-syntax-table)
4330
4331 (progn ; Define TeX-mode-syntax-table.
4332   (modify-syntax-entry (string-to-char TeX-esc)
4333                            "\\" TeX-mode-syntax-table)
4334   (modify-syntax-entry ?\f ">"  TeX-mode-syntax-table)
4335   (modify-syntax-entry ?\n ">"  TeX-mode-syntax-table)
4336   (modify-syntax-entry (string-to-char TeX-grop)
4337                            (concat "(" TeX-grcl)
4338                                 TeX-mode-syntax-table)
4339   (modify-syntax-entry (string-to-char TeX-grcl)
4340                            (concat ")" TeX-grop)
4341                                 TeX-mode-syntax-table)
4342   (modify-syntax-entry ?%  "<"  TeX-mode-syntax-table)
4343   (modify-syntax-entry ?\" "."  TeX-mode-syntax-table)
4344   (modify-syntax-entry ?&  "."  TeX-mode-syntax-table)
4345   (modify-syntax-entry ?_  "."  TeX-mode-syntax-table)
4346   (modify-syntax-entry ?@  "_"  TeX-mode-syntax-table)
4347   (modify-syntax-entry ?~  "."  TeX-mode-syntax-table)
4348   (modify-syntax-entry ?$  "$"  TeX-mode-syntax-table)
4349   (modify-syntax-entry ?'  "w"  TeX-mode-syntax-table)
4350   (modify-syntax-entry ?«  "."  TeX-mode-syntax-table)
4351   (modify-syntax-entry ?»  "."  TeX-mode-syntax-table))
4352
4353 ;;; Menu Support
4354
4355 (defvar TeX-command-current 'TeX-command-master
4356   "Specify whether to run command on master, buffer or region.")
4357 ;; Function used to run external command.
4358
4359 (defun TeX-command-select-master ()
4360   "Determine that the next command will be on the master file."
4361   (interactive)
4362   (message "Next command will be on the master file.")
4363   (setq TeX-command-current 'TeX-command-master))
4364
4365 (defun TeX-command-select-buffer ()
4366   "Determine that the next command will be on the buffer."
4367   (interactive)
4368   (message "Next command will be on the buffer")
4369   (setq TeX-command-current 'TeX-command-buffer))
4370
4371 (defun TeX-command-select-region ()
4372   "Determine that the next command will be on the region."
4373   (interactive)
4374   (message "Next command will be on the region")
4375   (setq TeX-command-current 'TeX-command-region))
4376
4377 (defvar TeX-command-force nil)
4378 ;; If non-nil, TeX-command-query will return the value of this
4379 ;; variable instead of quering the user.
4380
4381 (defun TeX-command-menu (name)
4382   "Execute `TeX-command-list' NAME from a menu."
4383   (let ((TeX-command-force name))
4384     (funcall TeX-command-current)))
4385
4386 (defun TeX-command-menu-print (printer command name)
4387   "Print on PRINTER using method COMMAND to run NAME."
4388   (let ((TeX-printer-default (unless (string= printer "Other") printer))
4389         (TeX-printer-list (and (string= printer "Other") TeX-printer-list))
4390         (TeX-print-command command)
4391         (TeX-queue-command command))
4392     (TeX-command-menu name)))
4393
4394 (defun TeX-command-menu-printer-entry (entry lookup command name)
4395   "Return `TeX-printer-list' ENTRY as a menu item."
4396   (vector (nth 0 entry)
4397           (list 'TeX-command-menu-print
4398                 (nth 0 entry)
4399                 (or (nth lookup entry) command)
4400                 name)))
4401
4402 (defun TeX-command-menu-entry (entry)
4403   "Return `TeX-command-list' ENTRY as a menu item."
4404   (let ((name (car entry)))
4405     (cond ((and (string-equal name TeX-command-Print)
4406                 TeX-printer-list)
4407            (cons TeX-command-Print
4408                  (mapcar (lambda (entry)
4409                            (TeX-command-menu-printer-entry
4410                             entry 1 TeX-print-command name))
4411                          (append TeX-printer-list '(("Other"))))))
4412           ((and (string-equal name TeX-command-Queue)
4413                 TeX-printer-list)
4414            (cons TeX-command-Queue
4415                  (mapcar (lambda (entry)
4416                            (TeX-command-menu-printer-entry
4417                             entry 2 TeX-queue-command name))
4418                          (append TeX-printer-list '(("Other"))))))
4419           (t
4420            (vconcat `(,name (TeX-command-menu ,name))
4421                     (nthcdr 5 entry))))))
4422
4423 (defconst TeX-command-menu-name "Command"
4424   "Name to be displayed for the command menu in all modes defined by AUCTeX.")
4425
4426 ;;; Keymap
4427
4428 (defcustom TeX-electric-escape nil
4429   "If non-nil, ``\\'' will be bound to `TeX-electric-macro'."
4430   :group 'TeX-macro
4431   :type 'boolean)
4432
4433 (defcustom TeX-electric-sub-and-superscript nil
4434   "If non-nil, insert braces after typing `^' and `_' in math mode."
4435   :group 'TeX-macro
4436   :type 'boolean)
4437
4438 (defcustom TeX-newline-function 'newline
4439   "Function to be called upon pressing `RET'."
4440   :group 'TeX-indentation
4441   :type '(choice (const newline)
4442                  (const newline-and-indent)
4443                  (const reindent-then-newline-and-indent)
4444                  (sexp :tag "Other")))
4445
4446 (defun TeX-insert-backslash (arg)
4447   "Either insert typed key ARG times or call `TeX-electric-macro'.
4448 `TeX-electric-macro' will be called if `TeX-electric-escape' is non-nil."
4449   (interactive "*p")
4450   (if TeX-electric-escape
4451       (TeX-electric-macro)
4452     (self-insert-command arg)))
4453
4454 (defun TeX-insert-sub-or-superscript (arg)
4455   "Insert typed key ARG times and possibly a pair of braces.
4456 Brace insertion is only done if point is in a math construct and
4457 `TeX-electric-sub-and-superscript' has a non-nil value."
4458   (interactive "*p")
4459   (self-insert-command arg)
4460   (when (and TeX-electric-sub-and-superscript (texmathp))
4461     (insert (concat TeX-grop TeX-grcl))
4462     (backward-char)))
4463
4464 (defun TeX-newline ()
4465   "Call the function specified by the variable `TeX-newline-function'."
4466   (interactive) (funcall TeX-newline-function))
4467
4468 (defvar TeX-mode-map
4469   (let ((map (make-sparse-keymap)))
4470     ;; Standard
4471     ;; (define-key map "\177"     'backward-delete-char-untabify)
4472     (define-key map "\C-c}"    'up-list)
4473     (define-key map "\C-c#"    'TeX-normal-mode)
4474     (define-key map "\C-c\C-n" 'TeX-normal-mode)
4475     (define-key map "\C-c?"    'TeX-doc)
4476     (define-key map "\C-c\C-i" 'TeX-goto-info-page)
4477     (define-key map "\r"       'TeX-newline)
4478
4479     ;; From tex.el
4480     (define-key map "\""       'TeX-insert-quote)
4481     (define-key map "$"        'TeX-insert-dollar)
4482     ;; Removed because LaTeX 2e have a better solution to italic correction.
4483     ;; (define-key map "."        'TeX-insert-punctuation)
4484     ;; (define-key map ","        'TeX-insert-punctuation)
4485     (define-key map "\C-c{"    'TeX-insert-braces)
4486     (define-key map "\C-c\C-f" 'TeX-font)
4487     (define-key map "\C-c\C-m" 'TeX-insert-macro)
4488     (define-key map "\\"       'TeX-insert-backslash)
4489     (define-key map "^"        'TeX-insert-sub-or-superscript)
4490     (define-key map "_"        'TeX-insert-sub-or-superscript)
4491     (define-key map "\e\t"     'TeX-complete-symbol) ;*** Emacs 19 way
4492
4493     (define-key map "\C-c'"    'TeX-comment-or-uncomment-paragraph) ;*** Old way
4494     (define-key map "\C-c:"    'TeX-comment-or-uncomment-region) ;*** Old way
4495     (define-key map "\C-c\""   'TeX-uncomment) ;*** Old way
4496
4497     (define-key map "\C-c;"    'TeX-comment-or-uncomment-region)
4498     (define-key map "\C-c%"    'TeX-comment-or-uncomment-paragraph)
4499
4500     (define-key map "\C-c\C-t\C-p"   'TeX-PDF-mode)
4501     (define-key map "\C-c\C-t\C-i"   'TeX-interactive-mode)
4502     (define-key map "\C-c\C-t\C-s"   'TeX-source-correlate-mode)
4503     (define-key map "\C-c\C-t\C-r"   'TeX-pin-region)
4504     (define-key map "\C-c\C-w"       'TeX-toggle-debug-bad-boxes); to be removed
4505     (define-key map "\C-c\C-t\C-b"   'TeX-toggle-debug-bad-boxes)
4506     (define-key map "\C-c\C-t\C-w"   'TeX-toggle-debug-warnings)
4507     (define-key map "\C-c\C-v" 'TeX-view)
4508     ;; From tex-buf.el
4509     (define-key map "\C-c\C-d" 'TeX-save-document)
4510     (define-key map "\C-c\C-r" 'TeX-command-region)
4511     (define-key map "\C-c\C-b" 'TeX-command-buffer)
4512     (define-key map "\C-c\C-c" 'TeX-command-master)
4513     (define-key map "\C-c\C-k" 'TeX-kill-job)
4514     (define-key map "\C-c\C-l" 'TeX-recenter-output-buffer)
4515     (define-key map "\C-c^" 'TeX-home-buffer)
4516     (define-key map "\C-c`"    'TeX-next-error)
4517     ;; Remap bindings of `next-error'
4518     (if (featurep 'xemacs)
4519         (substitute-key-definition 'next-error 'TeX-next-error map global-map)
4520       (define-key map [remap next-error] 'TeX-next-error))
4521     ;; Remap bindings of `previous-error'
4522     (if (featurep 'xemacs)
4523         (substitute-key-definition 'previous-error 'TeX-previous-error
4524                                    map global-map)
4525       (define-key map [remap previous-error] 'TeX-previous-error))
4526     ;; From tex-fold.el
4527     (define-key map "\C-c\C-o\C-f" 'TeX-fold-mode)
4528
4529     ;; Multifile
4530     (define-key map "\C-c_" 'TeX-master-file-ask)  ;*** temporary
4531     map)
4532   "Keymap for common TeX and LaTeX commands.")
4533
4534 (defun TeX-mode-specific-command-menu (mode)
4535   "Return a Command menu specific to the major MODE."
4536   ;; COMPATIBILITY for Emacs < 21
4537   (if (and (not (featurep 'xemacs))
4538            (= emacs-major-version 20))
4539       (cons TeX-command-menu-name
4540             (TeX-mode-specific-command-menu-entries mode))
4541     (list TeX-command-menu-name
4542           :filter `(lambda (&rest ignored)
4543                      (TeX-mode-specific-command-menu-entries ',mode))
4544           "Bug.")))
4545
4546 (defun TeX-mode-specific-command-menu-entries (mode)
4547   "Return the entries for a Command menu specific to the major MODE."
4548   (append
4549    (TeX-menu-with-help
4550     `("Command on"
4551       [ "Master File" TeX-command-select-master
4552         :keys "C-c C-c" :style radio
4553         :selected (eq TeX-command-current 'TeX-command-master)
4554         :help "Commands in this menu work on the Master File"]
4555       [ "Buffer" TeX-command-select-buffer
4556         :keys "C-c C-b" :style radio
4557         :selected (eq TeX-command-current 'TeX-command-buffer)
4558         :help "Commands in this menu work on the current buffer"]
4559       [ "Region" TeX-command-select-region
4560         :keys "C-c C-r" :style radio
4561         :selected (eq TeX-command-current 'TeX-command-region)
4562         :help "Commands in this menu work on the region"]
4563       [ "Fix the Region" TeX-pin-region
4564         :active (or (if prefix-arg
4565                         (<= (prefix-numeric-value prefix-arg) 0)
4566                       (and (boundp 'TeX-command-region-begin)
4567                            (markerp TeX-command-region-begin)))
4568                     (TeX-mark-active))
4569         ;;:visible (eq TeX-command-current 'TeX-command-region)
4570         :style toggle
4571         :selected (and (boundp 'TeX-command-region-begin)
4572                        (markerp TeX-command-region-begin))
4573         :help "Fix the region for \"Command on Region\""]
4574       "-"
4575       ["Recenter Output Buffer" TeX-recenter-output-buffer
4576        :help "Show the output of current TeX process"]
4577       ["Kill Job" TeX-kill-job
4578        :help "Kill the current TeX process"]
4579       ["Next Error" TeX-next-error
4580        :help "Jump to the next error of the last TeX run"]
4581       ["Previous Error" TeX-previous-error
4582        :help "Jump to the previous error of the last TeX run"
4583        :visible TeX-parse-all-errors]
4584       ["Error Overview" TeX-error-overview
4585        :help "Open an overview of errors occured in the last TeX run"
4586        :visible (and TeX-parse-all-errors (fboundp 'tabulated-list-mode))]
4587       ["Quick View" TeX-view
4588        :help "Start a viewer without prompting"]
4589       "-"
4590       ("TeXing Options"
4591        ,@(mapcar (lambda (x)
4592                    (let ((symbol (car x)) (name (nth 1 x)))
4593                      `[ ,(format "Use %s engine" name) (TeX-engine-set ',symbol)
4594                         :style radio :selected (eq TeX-engine ',symbol)
4595                         :help ,(format "Use %s engine for compiling" name) ]))
4596                  (TeX-engine-alist))
4597        "-"
4598        [ "Generate PDF" TeX-PDF-mode
4599          :style toggle :selected TeX-PDF-mode
4600          :active (not (eq TeX-engine 'omega))
4601          :help "Use PDFTeX to generate PDF instead of DVI"]
4602        [ "Run Interactively" TeX-interactive-mode
4603          :style toggle :selected TeX-interactive-mode :keys "C-c C-t C-i"
4604          :help "Stop on errors in a TeX run"]
4605        [ "Correlate I/O" TeX-source-correlate-mode
4606          :style toggle :selected TeX-source-correlate-mode
4607          :help "Enable forward and inverse search in the previewer"]
4608        ["Debug Bad Boxes" TeX-toggle-debug-bad-boxes
4609         :style toggle :selected TeX-debug-bad-boxes :keys "C-c C-t C-b"
4610         :help "Make \"Next Error\" show overfull and underfull boxes"]
4611        ["Debug Warnings" TeX-toggle-debug-warnings
4612         :style toggle :selected TeX-debug-warnings
4613         :help "Make \"Next Error\" show warnings"])))
4614    (let ((file 'TeX-command-on-current)) ;; is this actually needed?
4615      (TeX-maybe-remove-help
4616       (delq nil
4617             (mapcar 'TeX-command-menu-entry
4618                     (TeX-mode-specific-command-list mode)))))))
4619
4620 (defun TeX-mode-specific-command-list (mode)
4621   "Return the list of commands available in the given MODE."
4622   (let ((full-list TeX-command-list)
4623         out-list
4624         entry)
4625     (while (setq entry (pop full-list))
4626       ;; `(nth 4 entry)' may be either an atom in case of which the
4627       ;; entry should be present in any mode or a list of major modes.
4628       (if (or (atom (nth 4 entry))
4629               (memq mode (nth 4 entry)))
4630           (push entry out-list)))
4631     (nreverse out-list)))
4632
4633 (defvar TeX-fold-menu
4634   (TeX-menu-with-help
4635    '("Show/Hide"
4636      ["Fold Mode" TeX-fold-mode
4637       :style toggle
4638       :selected (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4639       :help "Toggle folding mode"]
4640      "-"
4641      ["Hide All in Current Buffer" TeX-fold-buffer
4642       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4643       :help "Hide all configured TeX constructs in the current buffer"]
4644      ["Hide All in Current Region" TeX-fold-region
4645       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4646       :help "Hide all configured TeX constructs in the marked region"]
4647      ["Hide All in Current Paragraph" TeX-fold-paragraph
4648       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4649       :help "Hide all configured TeX constructs in the paragraph containing point"]
4650      ["Hide Current Macro" TeX-fold-macro
4651       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4652       :help "Hide the macro containing point"]
4653      ["Hide Current Environment" TeX-fold-env
4654       :visible (not (eq major-mode 'plain-tex-mode))
4655       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4656       :help "Hide the environment containing point"]
4657      ["Hide Current Comment" TeX-fold-comment
4658       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4659       :help "Hide the comment containing point"]
4660      "-"
4661      ["Show All in Current Buffer" TeX-fold-clearout-buffer
4662       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4663       :help "Permanently show all folded content again"]
4664      ["Show All in Current Region" TeX-fold-clearout-region
4665       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4666       :help "Permanently show all folded content in marked region"]
4667      ["Show All in Current Paragraph" TeX-fold-clearout-paragraph
4668       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4669       :help "Permanently show all folded content in paragraph containing point"]
4670      ["Show Current Item" TeX-fold-clearout-item
4671       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4672       :help "Permanently show the item containing point"]
4673      "-"
4674      ["Hide or Show Current Item" TeX-fold-dwim
4675       :active (and (boundp 'TeX-fold-mode) TeX-fold-mode)
4676       :help "Hide or show the item containing point"]))
4677    "Menu definition for commands from tex-fold.el.")
4678
4679 (defvar TeX-customization-menu nil)
4680
4681 (defvar TeX-common-menu-entries
4682   (TeX-menu-with-help
4683    `(("Multifile/Parsing"
4684       ["Switch to Master File" TeX-home-buffer
4685        :help "Switch to buffer of Master File, or buffer of last TeX command"]
4686       ["Save Document" TeX-save-document
4687        :help "Save all buffers associated with the current Master File"]
4688       ["Set Master File" TeX-master-file-ask
4689        :active (not (TeX-local-master-p))
4690        :help "Set the main file to run TeX commands on"]
4691       ["Reset Buffer" TeX-normal-mode
4692        :help "Save and reparse the current buffer for style information"]
4693       ["Reset AUCTeX" (TeX-normal-mode t) :keys "C-u C-c C-n"
4694        :help "Reset buffer and reload AUCTeX style files"])
4695      ["Find Documentation..." TeX-doc
4696       :help "Get help on commands, packages, or TeX-related topics in general"]
4697      ["Read the AUCTeX Manual" TeX-goto-info-page
4698       :help "Everything worth reading"]
4699      ("Customize AUCTeX"
4700       ["Browse Options"
4701        (customize-group 'AUCTeX)
4702        :help "Open the customization buffer for AUCTeX"]
4703       ["Extend this Menu"
4704        (progn
4705          (easy-menu-add-item
4706           nil
4707           ;; Ugly hack because docTeX mode uses the LaTeX menu.
4708           (list (if (eq major-mode 'doctex-mode) "LaTeX" TeX-base-mode-name))
4709           (or TeX-customization-menu
4710               (setq TeX-customization-menu
4711                     (customize-menu-create 'AUCTeX "Customize AUCTeX")))))
4712        :help "Make this menu a full-blown customization menu"])
4713      ["Report AUCTeX Bug" TeX-submit-bug-report
4714       :help ,(format "Problems with AUCTeX %s? Mail us!"
4715                      AUCTeX-version)])))
4716
4717
4718 ;;; Verbatim constructs
4719
4720 (defvar TeX-verbatim-p-function nil
4721   "Mode-specific function to be called by `TeX-verbatim-p'.")
4722 (make-variable-buffer-local 'TeX-verbatim-p-function)
4723
4724 ;; XXX: We only have an implementation for LaTeX mode at the moment (Oct 2009).
4725 (defun TeX-verbatim-p (&optional pos)
4726   "Return non-nil if position POS is in a verbatim-like construct.
4727 A mode-specific implementation is required.  If it is not
4728 available, the function always returns nil."
4729   (when TeX-verbatim-p-function
4730     (funcall TeX-verbatim-p-function)))
4731
4732
4733 ;;; Comments
4734
4735 (defvar TeX-comment-start-regexp "%"
4736   "Regular expression matching a comment starter.
4737 Unlike the variable `comment-start-skip' it should not match any
4738 whitespace after the comment starter or any character before it.")
4739 (make-variable-buffer-local 'TeX-comment-start-regexp)
4740
4741 (defun TeX-comment-region (beg end &optional arg)
4742   "Comment each line in the region from BEG to END.
4743 Numeric prefix arg ARG means use ARG comment characters.
4744 If ARG is negative, delete that many comment characters instead."
4745   (interactive "*r\nP")
4746   ;; `comment-padding' will not be recognized in XEmacs' (21.4)
4747   ;; `comment-region', so we temporarily modify `comment-start' to get
4748   ;; proper spacing.  Unfortunately we have to check for the XEmacs
4749   ;; version and cannot test if `comment-padding' is bound as this
4750   ;; gets initialized in `VirTeX-common-initialization'.
4751   (let ((comment-start (if (and (featurep 'xemacs)
4752                                 (= emacs-major-version 21)
4753                                 (<= emacs-minor-version 4))
4754                            (concat comment-start (TeX-comment-padding-string))
4755                          comment-start)))
4756     (comment-region beg end arg)))
4757
4758 (eval-and-compile
4759   ;; COMPATIBILITY for Emacs <= 21.3
4760   (if (fboundp 'comment-or-uncomment-region)
4761       (defalias 'TeX-comment-or-uncomment-region 'comment-or-uncomment-region)
4762     ;; The following function was copied from `newcomment.el' on
4763     ;; 2004-01-30 and adapted accordingly
4764     (defun TeX-comment-or-uncomment-region (beg end &optional arg)
4765       "Comment or uncomment a the region from BEG to END.
4766 Call `TeX-comment-region', unless the region only consists of
4767 comments, in which case call `TeX-uncomment-region'.  If a prefix
4768 arg ARG is given, it is passed on to the respective function."
4769       (interactive "*r\nP")
4770       (funcall (if (save-excursion ;; check for already commented region
4771                      (goto-char beg)
4772                      (TeX-comment-forward (point-max))
4773                      (<= end (point)))
4774                    'TeX-uncomment-region 'TeX-comment-region)
4775                beg end arg)))
4776
4777   ;; COMPATIBILITY for Emacs <= 20.  (Introduced in 21.1?)
4778   (if (fboundp 'uncomment-region)
4779       (defalias 'TeX-uncomment-region 'uncomment-region)
4780     (defun TeX-uncomment-region (beg end &optional arg)
4781       "Remove comment characters from the beginning of each line
4782 in the region from BEG to END.  Numeric prefix arg ARG means use
4783 ARG comment characters.  If ARG is negative, delete that many
4784 comment characters instead."
4785       (interactive "*r\nP")
4786       (or arg
4787           ;; Determine the number of comment characters at the
4788           ;; beginning of the first commented line.
4789           (setq arg
4790                 (save-excursion
4791                   (goto-char beg)
4792                   (re-search-forward
4793                    (concat "^" TeX-comment-start-regexp "+") end t)
4794                   (length (match-string 0)))))
4795       (comment-region beg end (- arg)))))
4796
4797 (defun TeX-uncomment ()
4798   "Delete comment characters from the beginning of each line in a comment."
4799   (interactive)
4800   (save-excursion
4801     ;; Find first comment line
4802     (beginning-of-line)
4803     (while (and (looking-at (concat "^[ \t]*" TeX-comment-start-regexp))
4804                 (not (bobp)))
4805       (forward-line -1))
4806     (let ((beg (point)))
4807       (forward-line 1)
4808       ;; Find last comment line
4809       (while (and (looking-at (concat "^[ \t]*" TeX-comment-start-regexp))
4810                   (not (eobp)))
4811         (forward-line 1))
4812       ;; Uncomment region
4813       (TeX-uncomment-region beg (point)))))
4814
4815 (defun TeX-comment-or-uncomment-paragraph ()
4816   "Comment or uncomment current paragraph."
4817   (interactive)
4818   (if (TeX-in-commented-line)
4819       (TeX-uncomment)
4820     (save-excursion
4821       (beginning-of-line)
4822       ;; Don't do anything if we are in an empty line.  If this line
4823       ;; is followed by a lot of commented lines, this shall prevent
4824       ;; that mark-paragraph skips over these lines and marks a
4825       ;; paragraph outside the visible window which might get
4826       ;; commented without the user noticing.
4827       (unless (looking-at "^[ \t]*$")
4828         (mark-paragraph)
4829         (TeX-comment-region (point) (mark))))))
4830
4831 (defun TeX-in-comment ()
4832   "Return non-nil if point is in a comment."
4833   (if (or (bolp)
4834           (null comment-start-skip)
4835           (eq (preceding-char) ?\r))
4836       nil
4837     (save-excursion
4838       (save-match-data
4839         (let ((pos (point)))
4840           (beginning-of-line)
4841           (and (or (looking-at comment-start-skip)
4842                    (re-search-forward comment-start-skip pos t))
4843                (not (TeX-verbatim-p))))))))
4844
4845 (defun TeX-in-commented-line ()
4846   "Return non-nil if point is in a line consisting only of a comment.
4847 The comment can be preceded by whitespace.  This means that
4848 `TeX-in-commented-line' is more general than `TeX-in-line-comment'
4849 which will not match commented lines with leading whitespace.  But
4850 `TeX-in-commented-line' will match commented lines without leading
4851 whitespace as well."
4852   (save-excursion
4853     (forward-line 0)
4854     (skip-chars-forward " \t")
4855     (string= (buffer-substring-no-properties
4856               (point) (min (point-max) (+ (point) (length comment-start))))
4857              comment-start)))
4858
4859 (defun TeX-in-line-comment ()
4860   "Return non-nil if point is in a line comment.
4861 A line comment is a comment starting in column one, i.e. there is
4862 no whitespace before the comment sign."
4863   (save-excursion
4864     (forward-line 0)
4865     (string= (buffer-substring-no-properties
4866               (point) (min (point-max) (+ (point) (length comment-start))))
4867              comment-start)))
4868
4869 (defun TeX-comment-prefix ()
4870   "Return the comment prefix of the current line.
4871 If there are no comment starters after potential whitespace at
4872 the beginning of the line, return nil."
4873   (save-excursion
4874     (beginning-of-line)
4875     (save-match-data
4876       (when (looking-at (concat "\\([ \t]*" TeX-comment-start-regexp "+\\)+"))
4877         (match-string 0)))))
4878
4879 (defun TeX-forward-comment-skip (&optional count limit)
4880   "Move forward to the next comment skip.
4881 This may be a switch between commented and not commented adjacent
4882 lines or between lines with different comment prefixes.  With
4883 argument COUNT do it COUNT times.  If argument LIMIT is given, do
4884 not move point further than this value."
4885   (unless count (setq count 1))
4886   ;; A value of 0 is nonsense.
4887   (when (= count 0) (setq count 1))
4888   (unless limit (setq limit (point-max)))
4889   (dotimes (i (abs count))
4890     (if (< count 0)
4891         (forward-line -1)
4892       (beginning-of-line))
4893     (let ((prefix (when (looking-at (concat "\\([ \t]*"
4894                                             TeX-comment-start-regexp "+\\)+"))
4895                     (buffer-substring (+ (line-beginning-position)
4896                                          (current-indentation))
4897                                       (match-end 0)))))
4898       (while (save-excursion
4899                (and (if (> count 0)
4900                         (<= (point) limit)
4901                       (>= (point) limit))
4902                     (zerop (if (> count 0)
4903                                (forward-line 1)
4904                              (forward-line -1)))
4905                     (if prefix
4906                         (if (looking-at (concat "\\([ \t]*"
4907                                                 TeX-comment-start-regexp
4908                                                 "+\\)+"))
4909                             ;; If the preceding line is a commented line
4910                             ;; as well, check if the prefixes are
4911                             ;; identical.
4912                             (string= prefix
4913                                      (buffer-substring
4914                                       (+ (line-beginning-position)
4915                                          (current-indentation))
4916                                       (match-end 0)))
4917                           nil)
4918                       (not (looking-at (concat "[ \t]*"
4919                                                TeX-comment-start-regexp))))))
4920         (if (> count 0)
4921             (forward-line 1)
4922           (forward-line -1)))
4923       (if (> count 0)
4924           (forward-line 1)))))
4925
4926 (defun TeX-backward-comment-skip (&optional count limit)
4927   "Move backward to the next comment skip.
4928 This may be a switch between commented and not commented adjacent
4929 lines or between lines with different comment prefixes.  With
4930 argument COUNT do it COUNT times.  If argument LIMIT is given, do
4931 not move point to a position less than this value."
4932   (unless count (setq count 1))
4933   (when (= count 0) (setq count 1))
4934   (unless limit (setq limit (point-min)))
4935   (TeX-forward-comment-skip (- count) limit))
4936
4937 ;; Taken from `comment-forward' in Emacs' CVS on 2006-12-26.  Used as
4938 ;; a compatibility function for XEmacs 21.4.
4939 (defun TeX-comment-forward (&optional n)
4940   "Skip forward over N comments.
4941 Just like `forward-comment' but only for positive N
4942 and can use regexps instead of syntax."
4943   (when (fboundp 'comment-normalize-vars)
4944     (comment-normalize-vars))
4945   (if (fboundp 'comment-forward)
4946       (comment-forward n)
4947     (setq n (or n 1))
4948     (if (< n 0) (error "No comment-backward")
4949       (if comment-use-syntax (forward-comment n)
4950         (while (> n 0)
4951           (setq n
4952                 (if (or (forward-comment 1)
4953                         (and (looking-at comment-start-skip)
4954                              (goto-char (match-end 0))
4955                              (re-search-forward comment-end-skip nil 'move)))
4956                     (1- n) -1)))
4957         (= n 0)))))
4958
4959 (defun TeX-comment-padding-string ()
4960   "Return  comment padding as a string.
4961 The variable `comment-padding' can hold an integer or a string.
4962 This function will return the appropriate string representation
4963 regardless of its data type."
4964   (if (integerp comment-padding)
4965       (make-string comment-padding ? )
4966     comment-padding))
4967
4968
4969 ;;; Indentation
4970
4971 (defgroup TeX-indentation nil
4972   "Indentation of TeX buffers in AUCTeX."
4973   :group 'AUCTeX)
4974
4975 (defcustom TeX-brace-indent-level 2
4976   "*The level of indentation produced by an open brace."
4977   :group 'TeX-indentation
4978   :type 'integer)
4979
4980 (defun TeX-comment-indent ()
4981   "Determine the indentation of a comment."
4982   (if (looking-at "%%%")
4983       (current-column)
4984     (skip-chars-backward " \t")
4985     (max (if (bolp) 0 (1+ (current-column)))
4986          comment-column)))
4987
4988 (defun TeX-brace-count-line ()
4989   "Count number of open/closed braces."
4990   (save-excursion
4991     (let ((count 0) (limit (line-end-position)) char)
4992       (while (progn
4993                (skip-chars-forward "^{}\\\\" limit)
4994                (when (and (< (point) limit) (not (TeX-in-comment)))
4995                  (setq char (char-after))
4996                  (forward-char)
4997                  (cond ((eq char ?\{)
4998                         (setq count (+ count TeX-brace-indent-level)))
4999                        ((eq char ?\})
5000                         (setq count (- count TeX-brace-indent-level)))
5001                        ((eq char ?\\)
5002                         (when (< (point) limit)
5003                           (forward-char)
5004                           t))))))
5005       count)))
5006
5007 ;;; Navigation
5008
5009 (defvar TeX-search-syntax-table
5010   (let ((table (make-syntax-table (make-char-table (if (featurep 'xemacs)
5011                                                        'syntax
5012                                                      'syntax-table)))))
5013     ;; Preset mode-independent syntax entries.  (Mode-dependent
5014     ;; entries are set in the function `TeX-search-syntax-table'.)
5015     ;; ?\", ?\( and ?\) explicitely get whitespace syntax because
5016     ;; Emacs 21.3 and XEmacs don't generate a completely empty syntax
5017     ;; table.
5018     (dolist (elt '((?\f . ">") (?\n . ">") (?\" . " ") (?\( . " ") (?\) . " ")))
5019       (modify-syntax-entry (car elt) (cdr elt) table))
5020     table)
5021   "Syntax table used for searching purposes.
5022 It should be accessed through the function `TeX-search-syntax-table'.")
5023
5024 (defun TeX-search-syntax-table (&rest args)
5025   "Return a syntax table for searching purposes.
5026 ARGS may be a list of characters.  For each of them the
5027 respective predefined syntax is set.  Currently the parenthetical
5028 characters ?{, ?}, ?[, ?], ?\(, ?\), ?<, and ?> are supported.
5029 The syntax of each of these characters not specified will be
5030 reset to \" \"."
5031   (let ((char-syntax-alist '((?\{ . "(}") (?\} . "){")
5032                              (?\[ . "(]") (?\] . ")[")
5033                              (?\( . "()") (?\) . ")(")
5034                              (?\< . "(>") (?\> . ")<"))))
5035     ;; Clean entries possibly set before.
5036     (modify-syntax-entry ?\\ " " TeX-search-syntax-table)
5037     (modify-syntax-entry ?@ " " TeX-search-syntax-table)
5038     (modify-syntax-entry ?\% " " TeX-search-syntax-table)
5039     ;; Preset mode-dependent syntax entries.  (Mode-independent entries
5040     ;; are set when the variable `TeX-search-syntax-table' is created.)
5041     (modify-syntax-entry (string-to-char TeX-esc) "\\" TeX-search-syntax-table)
5042     (unless (eq major-mode 'texinfo-mode)
5043       (modify-syntax-entry ?\% "<" TeX-search-syntax-table))
5044     ;; Clean up the entries which can be specified as arguments.
5045     (dolist (elt char-syntax-alist)
5046       (modify-syntax-entry (car elt) " " TeX-search-syntax-table))
5047     ;; Now set what we got.
5048     (dolist (elt args)
5049       (unless (assoc elt char-syntax-alist) (error "Char not supported"))
5050       (modify-syntax-entry elt (cdr (assoc elt char-syntax-alist))
5051                            TeX-search-syntax-table))
5052     ;; Return the syntax table.
5053     TeX-search-syntax-table))
5054
5055 (defun TeX-find-balanced-brace (&optional count depth limit)
5056   "Return the position of a balanced brace in a TeX group.
5057 The function scans forward COUNT parenthetical groupings.
5058 Default is 1.  If COUNT is negative, it searches backwards.  With
5059 optional DEPTH>=1, find that outer level.  If LIMIT is non-nil,
5060 do not search further than this position in the buffer."
5061   (let ((count (if count
5062                    (if (= count 0) (error "COUNT has to be <> 0") count)
5063                  1))
5064         (depth (if depth
5065                    (if (< depth 1) (error "DEPTH has to be > 0") depth)
5066                  1)))
5067     (save-restriction
5068       (when limit
5069         (if (> count 0)
5070             (narrow-to-region (point-min) limit)
5071           (narrow-to-region limit (point-max))))
5072       (with-syntax-table (TeX-search-syntax-table ?\{ ?\})
5073         (condition-case nil
5074             (scan-lists (point) count depth)
5075           (error nil))))))
5076
5077 (defun TeX-find-closing-brace (&optional depth limit)
5078   "Return the position of the closing brace in a TeX group.
5079 The function assumes that point is inside the group, i.e. after
5080 an opening brace.  With optional DEPTH>=1, find that outer level.
5081 If LIMIT is non-nil, do not search further down than this
5082 position in the buffer."
5083   (TeX-find-balanced-brace 1 depth limit))
5084
5085 (defun TeX-find-opening-brace (&optional depth limit)
5086   "Return the position of the opening brace in a TeX group.
5087 The function assumes that point is inside the group, i.e. before
5088 a closing brace.  With optional DEPTH>=1, find that outer level.
5089 If LIMIT is non-nil, do not search further up than this position
5090 in the buffer."
5091   (TeX-find-balanced-brace -1 depth limit))
5092
5093 (defun TeX-find-macro-boundaries (&optional lower-bound)
5094   "Return a list containing the start and end of a macro.
5095 If LOWER-BOUND is given, do not search backward further than this
5096 point in buffer.  Arguments enclosed in brackets or braces are
5097 considered part of the macro."
5098   (save-restriction
5099     (when lower-bound
5100       (narrow-to-region lower-bound (point-max)))
5101     (let ((orig-point (point))
5102           start-point)
5103       ;; Point is located directly at the start of a macro. (-!-\foo{bar})
5104       (when (and (eq (char-after) (aref TeX-esc 0))
5105                  (not (TeX-escaped-p)))
5106         (setq start-point (point)))
5107       ;; Point is located on a macro. (\fo-!-o{bar})
5108       (unless start-point
5109         (save-excursion
5110           (skip-chars-backward "A-Za-z@*")
5111           (when (and (eq (char-before) (aref TeX-esc 0))
5112                      (not (TeX-escaped-p (1- (point)))))
5113             (setq start-point (1- (point))))))
5114       ;; Point is located in the argument of a macro. (\foo{ba-!-r})
5115       (unless start-point
5116         (save-excursion
5117           (catch 'abort
5118             (let ((parse-sexp-ignore-comments t))
5119               (when (condition-case nil (progn (up-list) t) (error nil))
5120                 (while (progn
5121                          (condition-case nil (backward-sexp)
5122                            (error (throw 'abort nil)))
5123                          (forward-comment -1)
5124                          (and (memq (char-before) '(?\] ?\}))
5125                               (not (TeX-escaped-p (1- (point)))))))
5126                 (skip-chars-backward "A-Za-z@*")
5127                 (when (and (eq (char-before) (aref TeX-esc 0))
5128                            (not (TeX-escaped-p (1- (point)))))
5129                   (setq start-point (1- (point)))))))))
5130       ;; Search forward for the end of the macro.
5131       (when start-point
5132         (save-excursion
5133           (goto-char (TeX-find-macro-end-helper start-point))
5134           (if (< orig-point (point))
5135               (cons start-point (point))
5136             nil))))))
5137
5138 (defun TeX-find-macro-end-helper (start)
5139   "Find the end of a macro given its START.
5140 START is the position just before the starting token of the macro.
5141 If the macro is followed by square brackets or curly braces,
5142 those will be considered part of it."
5143   (save-excursion
5144     (save-match-data
5145       (catch 'found
5146         (goto-char (1+ start))
5147         (if (zerop (skip-chars-forward "A-Za-z@"))
5148             (forward-char)
5149           (skip-chars-forward "*"))
5150         (while (not (eobp))
5151           (cond
5152            ;; Skip over pairs of square brackets
5153            ((or (looking-at "[ \t]*\n?\\(\\[\\)") ; Be conservative: Consider
5154                                         ; only consecutive lines.
5155                 (and (looking-at (concat "[ \t]*" TeX-comment-start-regexp))
5156                      (save-excursion
5157                        (forward-line 1)
5158                        (looking-at "[ \t]*\\(\\[\\)"))))
5159             (goto-char (match-beginning 1))
5160             (condition-case nil
5161                 (forward-sexp)
5162               (scan-error (throw 'found (point)))))
5163            ;; Skip over pairs of curly braces
5164            ((or (looking-at "[ \t]*\n?{") ; Be conservative: Consider
5165                                         ; only consecutive lines.
5166                 (and (looking-at (concat "[ \t]*" TeX-comment-start-regexp))
5167                      (save-excursion
5168                        (forward-line 1)
5169                        (looking-at "[ \t]*{"))))
5170             (goto-char (match-end 0))
5171             (goto-char (or (TeX-find-closing-brace)
5172                            ;; If we cannot find a regular end, use the
5173                            ;; next whitespace.
5174                            (save-excursion (skip-chars-forward "^ \t\n")
5175                                            (point))))
5176             (when (eobp) (throw 'found (point))))
5177            (t
5178             (throw 'found (point)))))))))
5179
5180 (defun TeX-find-macro-start (&optional limit)
5181   "Return the start of a macro.
5182 If LIMIT is given, do not search backward further than this point
5183 in buffer.  Arguments enclosed in brackets or braces are
5184 considered part of the macro."
5185   (car (TeX-find-macro-boundaries limit)))
5186
5187 (defun TeX-find-macro-end ()
5188   "Return the end of a macro.
5189 Arguments enclosed in brackets or braces are considered part of
5190 the macro."
5191   (cdr (TeX-find-macro-boundaries)))
5192
5193 (defun TeX-search-forward-unescaped (string &optional bound noerror)
5194   "Search forward from point for unescaped STRING.
5195 The optional argument BOUND limits the search to the respective
5196 buffer position.
5197 If NOERROR is non-nil, return nil if the search failed instead of
5198 throwing an error.
5199 A pattern is escaped, if it is preceded by an odd number of escape
5200 characters."
5201   (TeX-search-unescaped string 'forward nil bound noerror))
5202
5203 (defun TeX-search-backward-unescaped (string &optional bound noerror)
5204   "Search backward from point for unescaped STRING.
5205 The optional argument BOUND limits the search to the respective
5206 buffer position.
5207 If NOERROR is non-nil, return nil if the search failed instead of
5208 throwing an error.
5209 A pattern is escaped, if it is preceded by an odd number of escape
5210 characters."
5211   (TeX-search-unescaped string 'backward nil bound noerror))
5212
5213 (defun TeX-re-search-forward-unescaped (regexp &optional bound noerror)
5214   "Search forward from point for unescaped regular expression REGEXP.
5215 The optional argument BOUND limits the search to the respective
5216 buffer position.
5217 If NOERROR is non-nil, return nil if the search failed instead of
5218 throwing an error.
5219 A pattern is escaped, if it is preceded by an odd number of escape
5220 characters."
5221   (TeX-search-unescaped regexp 'forward t bound noerror))
5222
5223 (defun TeX-search-unescaped (pattern
5224                              &optional direction regexp-flag bound noerror)
5225   "Search for unescaped PATTERN in a certain DIRECTION.
5226 DIRECTION can be indicated by the symbols 'forward and 'backward.
5227 If DIRECTION is omitted, a forward search is carried out.
5228 If REGEXP-FLAG is non-nil, PATTERN may be a regular expression,
5229 otherwise a string.
5230 The optional argument BOUND limits the search to the respective
5231 buffer position.
5232 If NOERROR is non-nil, return nil if the search failed instead of
5233 throwing an error.
5234 A pattern is escaped, if it is preceded by an odd number of escape
5235 characters."
5236   (let ((search-fun (if (eq direction 'backward)
5237                         (if regexp-flag 're-search-backward 'search-backward)
5238                       (if regexp-flag 're-search-forward 'search-forward))))
5239     (catch 'found
5240       (while (funcall search-fun pattern bound noerror)
5241         (when (not (TeX-escaped-p (match-beginning 0)))
5242           (throw 'found (point)))))))
5243
5244 (defun TeX-escaped-p (&optional pos)
5245   "Return t if the character at position POS is escaped.
5246 If POS is omitted, examine the character at point.
5247 A character is escaped if it is preceded by an odd number of
5248 escape characters, such as \"\\\" in LaTeX."
5249   (save-excursion
5250     (when pos (goto-char pos))
5251     (not (zerop (mod (skip-chars-backward (regexp-quote TeX-esc)) 2)))))
5252
5253 (defun TeX-current-macro ()
5254   "Return the name of the macro containing point, nil if there is none."
5255   (let ((macro-start (TeX-find-macro-start)))
5256     (when macro-start
5257       (save-excursion
5258         (goto-char macro-start)
5259         (forward-char (length TeX-esc))
5260         (buffer-substring-no-properties
5261          (point) (progn (skip-chars-forward "@A-Za-z") (point)))))))
5262
5263 (defvar TeX-search-forward-comment-start-function nil
5264   "Function to find the start of a comment.
5265 The function should accept an optional argument for specifying
5266 the limit of the search.  It should return the position just
5267 before the comment if one is found and nil otherwise.  Point
5268 should not be moved.")
5269 (make-variable-buffer-local 'TeX-search-forward-comment-start-function)
5270
5271 (defun TeX-search-forward-comment-start (&optional limit)
5272   "Search forward for a comment start from current position till LIMIT.
5273 If LIMIT is omitted, search till the end of the buffer.
5274
5275 The search relies on `TeX-comment-start-regexp' being set
5276 correctly for the current mode.
5277
5278 Set `TeX-search-forward-comment-start-defun' in order to override
5279 the default implementation."
5280   (if TeX-search-forward-comment-start-function
5281       (funcall TeX-search-forward-comment-start-function limit)
5282     (setq limit (or limit (point-max)))
5283     (when (TeX-re-search-forward-unescaped TeX-comment-start-regexp limit t)
5284       (match-beginning 0))))
5285
5286 ;;; Fonts
5287
5288 (defcustom TeX-font-list '((?\C-b "{\\bf " "}")
5289                            (?\C-c "{\\sc " "}")
5290                            (?\C-e "{\\em " "\\/}")
5291                            (?\C-i "{\\it " "\\/}")
5292                            (?\C-r "{\\rm " "}")
5293                            (?\C-s "{\\sl " "\\/}")
5294                            (?\C-t "{\\tt " "}")
5295                            (?\C-d "" "" t))
5296   "List of fonts used by `TeX-font'.
5297
5298 Each entry is a list.
5299 The first element is the key to activate the font.
5300 The second element is the string to insert before point, and the third
5301 element is the string to insert after point.
5302 If the fourth and fifth element are strings, they specify the prefix and
5303 suffix to be used in math mode.
5304 An optional fourth (or sixth) element means always replace if t."
5305   :group 'TeX-macro
5306   :type '(repeat
5307            (group
5308             :value (?\C-a "" "")
5309             (character :tag "Key")
5310             (string :tag "Prefix")
5311             (string :tag "Suffix")
5312             (option (group
5313                      :inline t
5314                      (string :tag "Math Prefix")
5315                      (string :tag "Math Suffix")))
5316             (option (sexp :format "Replace\n" :value t)))))
5317
5318 (defvar TeX-font-replace-function 'TeX-font-replace
5319   "Determines the function which is called when a font should be replaced.")
5320
5321 (defun TeX-describe-font-entry (entry)
5322   "A textual description of an ENTRY in `TeX-font-list'."
5323   (concat (format "%16s  " (key-description (char-to-string (nth 0 entry))))
5324           (if (or (eq t (nth 3 entry)) (eq t (nth 5 entry)))
5325               "-- delete font"
5326             (format "%14s %-3s %14s %-3s"
5327                     (nth 1 entry) (nth 2 entry)
5328                     (if (stringp (nth 3 entry)) (nth 3 entry) "")
5329                     (if (stringp (nth 4 entry)) (nth 4 entry) "")))))
5330
5331 (defun TeX-font (replace what)
5332   "Insert template for font change command.
5333 If REPLACE is not nil, replace current font.  WHAT determines the font
5334 to use, as specified by `TeX-font-list'."
5335   (interactive "*P\nc")
5336   (TeX-update-style)
5337   (let* ((entry (assoc what TeX-font-list))
5338          (in-math (texmathp))
5339          (before (nth 1 entry))
5340          (after (nth 2 entry)))
5341     (setq replace (or replace (eq t (nth 3 entry)) (eq t (nth 5 entry))))
5342     (if (and in-math (stringp (nth 3 entry)))
5343         (setq before (nth 3 entry)
5344               after (nth 4 entry)))
5345     (cond ((null entry)
5346            (let ((help (concat
5347                         "Font list:   "
5348                         "KEY        TEXTFONT           MATHFONT\n\n"
5349                         (mapconcat 'TeX-describe-font-entry
5350                                    TeX-font-list "\n"))))
5351              (with-output-to-temp-buffer "*Help*"
5352                (set-buffer "*Help*")
5353                (insert help))))
5354           (replace
5355            (funcall TeX-font-replace-function before after))
5356           ((TeX-active-mark)
5357            (save-excursion
5358              (cond ((> (mark) (point))
5359                     (insert before)
5360                     (goto-char (mark))
5361                     (insert after))
5362                    (t
5363                     (insert after)
5364                     (goto-char (mark))
5365                     (insert before)))))
5366           (t
5367            (insert before)
5368            (save-excursion
5369              (insert after))))))
5370
5371 (defun TeX-font-replace (start end)
5372   "Replace font specification around point with START and END.
5373 For modes with font specifications like `{\\font text}'.
5374 See also `TeX-font-replace-macro' and `TeX-font-replace-function'."
5375   (save-excursion
5376     (while (not (looking-at "{\\\\[a-zA-Z]+ "))
5377       (up-list -1))
5378     (forward-sexp)
5379     (save-excursion
5380       (replace-match start t t))
5381     (if (save-excursion
5382           (backward-char 3)
5383           (if (looking-at (regexp-quote "\\/}"))
5384               (progn
5385                 (delete-char 3)
5386                 nil)
5387             t))
5388         (delete-char -1))
5389     (insert end)))
5390
5391 (defun TeX-font-replace-macro (start end)
5392   "Replace font specification around point with START and END.
5393 For modes with font specifications like `\\font{text}'.
5394 See also `TeX-font-replace' and `TeX-font-replace-function'."
5395   (let ((font-list TeX-font-list)
5396         cmds strings regexp)
5397     (while font-list
5398       (setq strings (cdr (car font-list))
5399             font-list (cdr font-list))
5400       (and (stringp (car strings)) (null (string= (car strings) ""))
5401            (setq cmds (cons (car strings) cmds)))
5402       (setq strings (cdr (cdr strings)))
5403       (and (stringp (car strings)) (null (string= (car strings) ""))
5404            (setq cmds (cons (car strings) cmds))))
5405     (setq regexp (mapconcat 'regexp-quote cmds "\\|"))
5406     (save-excursion
5407       (catch 'done
5408         (while t
5409           (if (/= ?\\ (following-char))
5410               (skip-chars-backward "a-zA-Z "))
5411           (skip-chars-backward (regexp-quote TeX-esc))
5412           (if (looking-at regexp)
5413               (throw 'done t)
5414             (up-list -1))))
5415       ;; Use stripped syntax table in order to get stuff like "\emph{(}" right.
5416       (with-syntax-table (TeX-search-syntax-table ?\{ ?\})
5417         (forward-sexp 2))
5418       (save-excursion
5419         (replace-match start t t))
5420       (delete-char -1)
5421       (insert end))))
5422
5423 ;;; Dollars
5424 ;;
5425 ;; Rewritten from scratch with use of `texmathp' by
5426 ;; Carsten Dominik <dominik@strw.leidenuniv.nl>
5427
5428 (defvar TeX-symbol-marker nil)
5429
5430 (defvar TeX-symbol-marker-pos 0)
5431
5432 ;; The following constants are no longer used, but kept in case some
5433 ;; foreign code uses any of them.
5434 (defvar TeX-dollar-sign ?$
5435   "*Character used to enter and leave math mode in TeX.")
5436 (defconst TeX-dollar-string (char-to-string TeX-dollar-sign))
5437 (defconst TeX-dollar-regexp
5438   (concat "^" (regexp-quote TeX-dollar-string) "\\|[^" TeX-esc "]"
5439           (regexp-quote TeX-dollar-string)))
5440
5441 (defcustom TeX-math-toggle-off-input-method t
5442   "*If non-nil, auto toggle off CJK input methods when entering math mode."
5443   :group 'TeX-macro
5444   :type 'boolean)
5445
5446 (defcustom TeX-electric-math nil
5447   "If non-nil, when outside math mode `TeX-insert-dollar' will
5448 insert symbols for opening and closing inline equation and put
5449 the point between them.  If there is an active region,
5450 `TeX-insert-dollar' will put around it symbols for opening and
5451 closing inline equation and keep the region active, with point
5452 after closing symbol.  If you press `$' again, you can toggle
5453 between inline equation, display equation, and no equation.
5454
5455 If non-nil and point is inside math mode right between a couple
5456 of single dollars, pressing `$' will insert another pair of
5457 dollar signs and leave the point between them.
5458
5459 If nil, `TeX-insert-dollar' will simply insert \"$\" at point,
5460 this is the default.
5461
5462 If non-nil, this variable is a cons cell whose CAR is the string
5463 to insert before point, the CDR is the string to insert after
5464 point.  You can choose between \"$...$\" and \"\\(...\\)\"."
5465   :group 'TeX-macro
5466   :type '(choice (const :tag "No electricity" nil)
5467                  (const :tag "$...$" ("$" . "$"))
5468                  (const :tag "\\(...\\)" ("\\(" . "\\)"))
5469                  (cons :tag "Other"
5470                        (string :tag "Insert before point")
5471                        (string :tag "Insert after point"))))
5472
5473 (defun TeX-insert-dollar (&optional arg)
5474   "Insert dollar sign.
5475
5476 If current math mode was not entered with a dollar, refuse to
5477 insert one.  Show matching dollar sign if this dollar sign ends
5478 the TeX math mode and `blink-matching-paren' is non-nil.
5479
5480 When outside math mode, the behavior is controlled by the variable
5481 `TeX-electric-math'.
5482
5483 With raw \\[universal-argument] prefix, insert exactly one dollar
5484 sign.  With optional ARG, insert that many dollar signs."
5485   (interactive "P")
5486   (cond
5487    ((and arg (listp arg))
5488     ;; C-u always inserts one
5489     (insert "$"))
5490    (arg
5491     ;; Numerical arg inserts that many
5492     (insert (make-string (prefix-numeric-value arg) ?\$)))
5493    ((or (TeX-escaped-p) (TeX-verbatim-p))
5494     ;; Point is escaped with `\' or is in a verbatim-like construct, so just
5495     ;; insert one $.
5496     (insert "$"))
5497    ((texmathp)
5498     ;; We are inside math mode
5499     (cond
5500      ((and TeX-electric-math
5501            (eq (preceding-char) ?\$)
5502            (eq (following-char) ?\$))
5503       ;; Point is between "$$" and `TeX-electric-math' is non-nil - insert
5504       ;; another pair of dollar signs and leave point between them.
5505       (insert "$$")
5506       (backward-char))
5507      ((and (stringp (car texmathp-why))
5508            (string-equal (substring (car texmathp-why) 0 1) "\$"))
5509       ;; Math mode was turned on with $ or $$ - insert a single $.
5510       (insert "$")
5511       ;; Compatibility, `TeX-math-close-double-dollar' has been removed
5512       ;; after AUCTeX 11.87.
5513       (if (boundp 'TeX-math-close-double-dollar)
5514           (message
5515            (concat "`TeX-math-close-double-dollar' has been removed,"
5516                    "\nplease use `TeX-electric-math' instead.")))
5517       (when (and blink-matching-paren
5518                  (or (string= (car texmathp-why) "$")
5519                      (zerop (mod (save-excursion
5520                                    (skip-chars-backward "$")) 2))))
5521         (save-excursion
5522           (goto-char (cdr texmathp-why))
5523           (if (pos-visible-in-window-p)
5524               (sit-for blink-matching-delay)
5525             (message "Matches %s"
5526                      (buffer-substring
5527                       (point) (progn (end-of-line) (point))))))))
5528      (t
5529       ;; Math mode was not entered with dollar - we cannot finish it with one.
5530       (message "Math mode started with `%s' cannot be closed with dollar"
5531                (car texmathp-why))
5532       (insert "$"))))
5533    (t
5534     ;; Just somewhere in the text.
5535     (cond
5536      ((and TeX-electric-math (TeX-active-mark))
5537       (if (> (point) (mark))
5538           (exchange-point-and-mark))
5539       (cond
5540        ;; $...$ to $$...$$
5541        ((and (eq last-command 'TeX-insert-dollar)
5542              (re-search-forward "\\=\\$\\([^$][^z-a]*[^$]\\)\\$" (mark) t))
5543         (replace-match "$$\\1$$")
5544         (set-mark (match-beginning 0)))
5545        ;; \(...\) to \[...\]
5546        ((and (eq last-command 'TeX-insert-dollar)
5547              (re-search-forward "\\=\\\\(\\([^z-a]*\\)\\\\)" (mark) t))
5548         (replace-match "\\\\[\\1\\\\]")
5549         (set-mark (match-beginning 0)))
5550        ;; Strip \[...\] or $$...$$
5551        ((and (eq last-command 'TeX-insert-dollar)
5552              (or (re-search-forward "\\=\\\\\\[\\([^z-a]*\\)\\\\\\]" (mark) t)
5553                  (re-search-forward "\\=\\$\\$\\([^z-a]*\\)\\$\\$" (mark) t)))
5554         (replace-match "\\1")
5555         (set-mark (match-beginning 0)))
5556        (t
5557         ;; We use `save-excursion' because point must be situated before opening
5558         ;; symbol.
5559         (save-excursion (insert (car TeX-electric-math)))
5560         (exchange-point-and-mark)
5561         (insert (cdr TeX-electric-math))))
5562       ;; Keep the region active.
5563       (TeX-activate-region))
5564      (TeX-electric-math
5565       (insert (car TeX-electric-math))
5566       (save-excursion (insert (cdr TeX-electric-math)))
5567       (if blink-matching-paren
5568           (progn
5569             (backward-char)
5570             (sit-for blink-matching-delay)
5571             (forward-char))))
5572      ;; In any other case just insert a single $.
5573      ((insert "$")))))
5574   (TeX-math-input-method-off))
5575
5576 (defvar TeX-math-input-method-off-regexp
5577   (concat "^" (regexp-opt '("chinese" "japanese" "korean" "bulgarian" "russian") t))
5578   "Regexp matching input methods to be deactivated when entering math mode.")
5579
5580 (defun TeX-math-input-method-off ()
5581   "Toggle off input method when entering math mode."
5582   (and TeX-math-toggle-off-input-method
5583        (texmathp)
5584        (boundp 'current-input-method) current-input-method
5585        (string-match TeX-math-input-method-off-regexp current-input-method)
5586        (inactivate-input-method)))
5587
5588 ;;; Simple Commands
5589
5590 (defun TeX-normal-mode (&optional arg)
5591   "Remove all information about this buffer, and apply the style hooks again.
5592 Save buffer first including style information.
5593 With optional argument ARG, also reload the style hooks."
5594   (interactive "*P")
5595   (if arg
5596       (setq TeX-style-hook-list nil
5597             BibTeX-global-style-files nil
5598             BibTeX-global-files nil
5599             BibLaTeX-global-style-files nil
5600             TeX-Biber-global-files nil
5601             TeX-global-input-files nil
5602             LaTeX-global-class-files nil))
5603   (let ((TeX-auto-save t))
5604     (if (buffer-modified-p)
5605         (save-buffer)
5606       (TeX-auto-write)))
5607   (normal-mode)
5608   ;; See also addition to `find-file-hooks' in `VirTeX-common-initialization'.
5609   (when (eq TeX-master 'shared) (TeX-master-file nil nil t))
5610   (TeX-update-style t))
5611
5612 (defgroup TeX-quote nil
5613   "Quoting in AUCTeX."
5614   :group 'AUCTeX)
5615
5616 (defcustom TeX-open-quote "``"
5617   "String inserted by typing \\[TeX-insert-quote] to open a quotation."
5618   :group 'TeX-quote
5619   :type 'string)
5620
5621 (defcustom TeX-close-quote "''"
5622   "String inserted by typing \\[TeX-insert-quote] to close a quotation."
5623   :group 'TeX-quote
5624   :type 'string)
5625
5626 (defcustom TeX-quote-after-quote nil
5627   "Behaviour of \\[TeX-insert-quote].
5628 Nil means standard behaviour; when non-nil, opening and closing
5629 quotes are inserted only after \"."
5630   :group 'TeX-quote
5631   :type 'boolean)
5632
5633 (defcustom TeX-quote-language-alist nil
5634   "Alist for overriding the default language-specific quote insertion.
5635 First element in each item is the name of the language as set by
5636 the language style file as a string.  Second element is the
5637 opening quotation mark.  Third element is the closing quotation
5638 mark.  Opening and closing quotation marks can be specified
5639 directly as strings or as functions returning a string.  Fourth
5640 element is a boolean specifying insertion behavior, overriding
5641 `TeX-quote-after-quote'.  See Info node `(auctex)European' for
5642 valid languages."
5643   :group 'TeX-quote
5644   :link '(custom-manual "(auctex)European")
5645   :type '(repeat (group (choice
5646                          (const "czech")
5647                          (const "danish")
5648                          (const "dutch")
5649                          (const "german")
5650                          (const "ngerman")
5651                          (const "french") ;; not frenchb or francais
5652                          (const "italian")
5653                          (const "polish")
5654                          (const "slovak")
5655                          (const "swedish")
5656                          (string :tag "Other Language"))
5657                         (choice :tag "Opening quotation mark" string function)
5658                         (choice :tag "Closing quotation mark" string function)
5659                         (boolean :tag "Insert plain quote first" :value t))))
5660
5661 (defvar TeX-quote-language nil
5662   "If non-nil determines behavior of quote insertion.
5663 It is usually set by language-related style files.  Its value has
5664 the same structure as the elements of `TeX-quote-language-alist'.
5665 The symbol 'override can be used as its car in order to override
5666 the settings of style files.  Style files should therefore check
5667 if this symbol is present and not alter `TeX-quote-language' if
5668 it is.")
5669 (make-variable-buffer-local 'TeX-quote-language)
5670
5671 (defun TeX-insert-quote (force)
5672   "Insert the appropriate quotation marks for TeX.
5673 Inserts the value of `TeX-open-quote' (normally ``) or `TeX-close-quote'
5674 \(normally '') depending on the context.  If `TeX-quote-after-quote'
5675 is non-nil, this insertion works only after \".
5676 With prefix argument FORCE, always inserts \" characters."
5677   (interactive "*P")
5678   (if (or force
5679           ;; Do not insert TeX quotes in verbatim, math or comment constructs.
5680           (and (fboundp 'font-latex-faces-present-p)
5681                (font-latex-faces-present-p '(font-latex-verbatim-face
5682                                              font-latex-math-face
5683                                              font-lock-comment-face))
5684                (font-latex-faces-present-p '(font-latex-verbatim-face
5685                                              font-latex-math-face
5686                                              font-lock-comment-face)
5687                                            (1- (point))))
5688           (texmathp)
5689           (and (TeX-in-comment) (not (eq major-mode 'doctex-mode))))
5690       (self-insert-command (prefix-numeric-value force))
5691     (TeX-update-style)
5692     (let* ((lang-override (if (eq (car TeX-quote-language) 'override)
5693                               TeX-quote-language
5694                             (assoc (car TeX-quote-language)
5695                                    TeX-quote-language-alist)))
5696            (lang (or lang-override TeX-quote-language))
5697            (open-quote (if lang (nth 1 lang) TeX-open-quote))
5698            (close-quote (if lang (nth 2 lang) TeX-close-quote))
5699            (q-after-q (if lang (nth 3 lang) TeX-quote-after-quote)))
5700       (when (functionp open-quote)
5701         (setq open-quote (funcall open-quote)))
5702       (when (functionp close-quote)
5703         (setq close-quote (funcall close-quote)))
5704       (if q-after-q
5705           (insert (cond ((bobp)
5706                          ?\")
5707                         ((save-excursion
5708                            (TeX-looking-at-backward
5709                             (concat (regexp-quote open-quote) "\\|"
5710                                     (regexp-quote close-quote))
5711                             (max (length open-quote) (length close-quote))))
5712                          (delete-char (- (length (match-string 0))))
5713                          "\"\"")
5714                         ((< (save-excursion (skip-chars-backward "\"")) -1)
5715                          ?\")
5716                         ((not (= (preceding-char) ?\"))
5717                          ?\")
5718                         ((save-excursion
5719                            (forward-char -1)
5720                            (bobp))
5721                          (delete-char -1)
5722                          open-quote)
5723                         ((save-excursion
5724                            (forward-char -2) ;;; at -1 there is double quote
5725                            (looking-at "[ \t\n]\\|\\s("))
5726                          (delete-char -1)
5727                          open-quote)
5728                         (t
5729                          (delete-char -1)
5730                          close-quote)))
5731         (insert (cond ((bobp)
5732                        open-quote)
5733                       ((= (preceding-char) (string-to-char TeX-esc))
5734                        ?\")
5735                       ((= (preceding-char) ?\")
5736                        ?\")
5737                       ((save-excursion
5738                          (forward-char (- (length open-quote)))
5739                          (looking-at (regexp-quote open-quote)))
5740                        (delete-char (- (length open-quote)))
5741                        ?\")
5742                       ((save-excursion
5743                          (forward-char (- (length close-quote)))
5744                          (looking-at (regexp-quote close-quote)))
5745                        (delete-char (- (length close-quote)))
5746                        ?\")
5747                       ((save-excursion
5748                          (forward-char -1)
5749                          (looking-at "[ \t\n]\\|\\s("))
5750                        open-quote)
5751                       (t
5752                        close-quote)))))))
5753
5754 (defun TeX-insert-punctuation ()
5755   "Insert point or comma, cleaning up preceding space."
5756   (interactive)
5757   (expand-abbrev)
5758   (if (TeX-looking-at-backward "\\\\/\\(}+\\)" 50)
5759       (replace-match "\\1" t))
5760   (call-interactively 'self-insert-command))
5761
5762 (defun TeX-insert-braces (arg)
5763   "Make a pair of braces around next ARG sexps and leave point inside.
5764 No argument is equivalent to zero: just insert braces and leave point
5765 between.
5766
5767 If there is an active region, ARG will be ignored, braces will be
5768 inserted around the region, and point will be left after the
5769 closing brace."
5770   (interactive "P")
5771   (if (TeX-active-mark)
5772       (progn
5773         (if (< (point) (mark))
5774             (exchange-point-and-mark))
5775         (insert TeX-grcl)
5776         (save-excursion
5777           (goto-char (mark))
5778           (insert TeX-grop)))
5779     (insert TeX-grop)
5780     (save-excursion
5781       (if arg (forward-sexp (prefix-numeric-value arg)))
5782       (insert TeX-grcl))))
5783
5784 ;;;###autoload
5785 (defun TeX-submit-bug-report ()
5786   "Submit a bug report on AUCTeX via mail.
5787
5788 Don't hesitate to report any problems or inaccurate documentation.
5789
5790 If you don't have setup sending mail from (X)Emacs, please copy the
5791 output buffer into your mail program, as it gives us important
5792 information about your AUCTeX version and AUCTeX configuration."
5793   (interactive)
5794   (require 'reporter)
5795   (let ((reporter-prompt-for-summary-p "Bug report subject: "))
5796     (reporter-submit-bug-report
5797      "bug-auctex@gnu.org"
5798      AUCTeX-version
5799      (list 'AUCTeX-date
5800            'window-system
5801            'LaTeX-version
5802            'TeX-style-path
5803            'TeX-auto-save
5804            'TeX-parse-self
5805            'TeX-master
5806            'TeX-command-list)
5807      nil nil
5808      "Remember to cover the basics, that is, what you expected to happen and
5809 what in fact did happen.
5810
5811 Be sure to consult the FAQ section in the manual before submitting
5812 a bug report.  In addition check if the bug is reproducable with an
5813 up-to-date version of AUCTeX.  So please upgrade to the version
5814 available from http://www.gnu.org/software/auctex/ if your
5815 installation is older than the one available from the web site.
5816
5817 If the bug is triggered by a specific \(La\)TeX file, you should try
5818 to produce a minimal sample file showing the problem and include it
5819 in your report.
5820
5821 Your bug report will be posted to the AUCTeX bug reporting list.
5822 ------------------------------------------------------------------------")))
5823
5824
5825 ;;; Documentation
5826
5827 (defun TeX-goto-info-page ()
5828   "Read documentation for AUCTeX in the info system."
5829   (interactive)
5830   (info "auctex"))
5831
5832 (autoload 'info-lookup->completions "info-look")
5833
5834 (defvar TeX-doc-backend-alist
5835   '((texdoc (plain-tex-mode latex-mode doctex-mode ams-tex-mode context-mode)
5836             (lambda ()
5837               (when (executable-find "texdoc")
5838                 (TeX-search-files
5839                  ;; Explicitely supply doc directory for
5840                  ;; non-kpathsea-based TeX systems.
5841                  (unless (stringp TeX-kpathsea-path-delimiter)
5842                    (or (TeX-tree-expand
5843                         '("$SYSTEXMF" "$TEXMFLOCAL" "$TEXMFMAIN" "$TEXMFDIST")
5844                         "latex" '("/doc/"))
5845                        `(,@TeX-macro-global ,@TeX-macro-private)))
5846                  '("dvi" "pdf" "ps" "txt" "html") t t)))
5847             (lambda (doc)
5848               ;; texdoc in MiKTeX requires --view in order to start
5849               ;; the viewer instead of an intermediate web page.
5850               (call-process "texdoc" nil 0 nil "--view" doc)))
5851     (latex-info (latex-mode)
5852                 (lambda ()
5853                   (mapcar (lambda (x)
5854                             (let ((x (car x)))
5855                               (if (string-match "\\`\\\\" x)
5856                                   (substring x 1) x)))
5857                           (info-lookup->completions 'symbol 'latex-mode)))
5858                 (lambda (doc)
5859                   (info-lookup-symbol (concat "\\" doc) 'latex-mode)))
5860     (texinfo-info (texinfo-mode)
5861                   (lambda ()
5862                     (mapcar (lambda (x)
5863                               (let ((x (car x)))
5864                                 (if (string-match "\\`@" x)
5865                                     (substring x 1) x)))
5866                             (info-lookup->completions 'symbol
5867                                                       'texinfo-mode)))
5868                   (lambda (doc)
5869                     (info-lookup-symbol (concat "@" doc) 'texinfo-mode))))
5870   "Alist of backends used for looking up documentation.
5871 Each item consists of four elements.
5872
5873 The first is a symbol describing the backend's name.
5874
5875 The second is a list of modes the backend should be activated in.
5876
5877 The third is a function returning a list of documents available
5878 to the backend.  It should return nil if the backend is not
5879 available, e.g. if a required executable is not present on the
5880 system in question.
5881
5882 The fourth is a function for displaying the documentation.  The
5883 function should accept a single argument, the chosen package,
5884 command, or document name.")
5885
5886 (defun TeX-doc (&optional name)
5887   "Display documentation for string NAME.
5888 NAME may be a package, a command, or a document."
5889   (interactive)
5890   (let (docs)
5891     ;; Build the lists of available documentation used for completion.
5892     (dolist (elt TeX-doc-backend-alist)
5893       (when (memq major-mode (nth 1 elt))
5894         (let ((completions (funcall (nth 2 elt))))
5895           (unless (null completions)
5896             (add-to-list 'docs (cons completions (nth 0 elt)))))))
5897     (if (null docs)
5898         (progn
5899           (if (executable-find "texdoc")
5900               ;; Fallback if we did not find anything via the backend list.
5901               (let ((doc (read-from-minibuffer "Input for `texdoc': ")))
5902                 (when doc (call-process "texdoc" nil 0 nil "--view" doc)))
5903             ;; Give up.
5904             (message "No documentation found")))
5905       ;; Ask the user about the package, command, or document.
5906       (when (and (interactive-p)
5907                  (or (not name) (string= name "")))
5908         (let ((symbol (thing-at-point 'symbol))
5909               contained completions doc)
5910           ;; Is the symbol at point contained in the lists of available
5911           ;; documentation?
5912           (setq contained (catch 'found
5913                             (dolist (elt docs)
5914                               (when (member symbol (car elt))
5915                                 (throw 'found t)))))
5916           ;; Setup completion list in a format suitable for `completing-read'.
5917           (dolist (elt docs)
5918             (setq completions (nconc (mapcar 'list (car elt)) completions)))
5919           ;; Query user.
5920           (setq doc (completing-read
5921                      (if contained
5922                          (format "Package, command, or document (default %s): "
5923                                  symbol)
5924                        "Package, command, or document: ")
5925                      completions))
5926           (setq name (if (string= doc "") symbol doc))))
5927       (if (not name)
5928           (message "No documentation specified")
5929         ;; XXX: Provide way to choose in case a symbol can be found in
5930         ;; more than one backend.
5931         (let* ((backend (catch 'found
5932                           (dolist (elt docs)
5933                             (when (member name (car elt))
5934                               (throw 'found (cdr elt)))))))
5935           (if backend
5936               (funcall (nth 3 (assoc backend TeX-doc-backend-alist)) name)
5937             (message "Documentation not found")))))))
5938
5939
5940 ;;; Ispell Support
5941
5942 ;; FIXME: Document those functions and variables.  -- rs
5943
5944 ;; The FSF ispell.el use this.
5945 (defun ispell-tex-buffer-p ()
5946   (and (boundp 'ispell-tex-p) ispell-tex-p))
5947
5948 ;; The FSF ispell.el might one day use this.
5949 (setq ispell-enable-tex-parser t)
5950
5951 (defun TeX-run-ispell (command string file)
5952   "Run ispell on current TeX buffer."
5953   (cond ((and (string-equal file (TeX-region-file))
5954               (fboundp 'ispell-region))
5955          (call-interactively 'ispell-region))
5956         ((string-equal file (TeX-region-file))
5957          (call-interactively 'spell-region))
5958         ((fboundp 'ispell-buffer)
5959          (ispell-buffer))
5960         ((fboundp 'ispell)
5961          (ispell))
5962         (t
5963          (spell-buffer))))
5964
5965 (defun TeX-ispell-document (name)
5966   "Run ispell on all open files belonging to the current document."
5967   (interactive (list (TeX-master-file)))
5968   (if (string-equal name "")
5969       (setq name (TeX-master-file)))
5970
5971   (let ((found nil)
5972         (regexp (concat "\\`\\("
5973                         (mapconcat (lambda (dir)
5974                                      (regexp-quote
5975                                       (expand-file-name
5976                                        (file-name-as-directory dir))))
5977                                    (append (when (file-name-directory name)
5978                                              (list (file-name-directory name)))
5979                                            TeX-check-path)
5980                                    "\\|")
5981                         "\\).*\\("
5982                         (mapconcat 'regexp-quote
5983                                    (cons (file-name-nondirectory name)
5984                                          (TeX-style-list)) "\\|")
5985                         "\\)\\.\\("
5986                         (mapconcat 'regexp-quote TeX-file-extensions "\\|")
5987                         "\\)\\'"))
5988         (buffers (buffer-list)))
5989     (while buffers
5990       (let* ((buffer (car buffers))
5991              (name (buffer-file-name buffer)))
5992         (setq buffers (cdr buffers))
5993         (if (and name (string-match regexp name))
5994             (progn
5995               (save-excursion (switch-to-buffer buffer) (ispell-buffer))
5996               (setq found t)))))))
5997
5998 ;; Some versions of ispell 3 use this.
5999 (defvar ispell-tex-major-modes nil)
6000 (setq ispell-tex-major-modes
6001       (append '(plain-tex-mode ams-tex-mode latex-mode doctex-mode)
6002               ispell-tex-major-modes))
6003
6004
6005 ;;; Abbrev mode
6006
6007 (defmacro TeX-abbrev-mode-setup (mode)
6008   "Set up the abbrev table and variable for MODE."
6009   (let ((symbol (intern (concat (symbol-name mode) "-abbrev-table")))
6010         (name (TeX-mode-prefix mode)))
6011     `(progn
6012        (defvar ,symbol nil
6013          ,(format "Abbrev table for %s mode." name))
6014        (define-abbrev-table ',symbol nil)
6015        (when (fboundp 'abbrev-table-put)
6016          (abbrev-table-put ,symbol :parents (list text-mode-abbrev-table))))))
6017
6018
6019 ;;; Special provisions for other modes and libraries
6020
6021 ;; desktop-locals-to-save is broken by design.  Don't have
6022 ;; buffer-local values of it.
6023 (eval-after-load "desktop"
6024   '(progn
6025      (dolist (elt '(TeX-master))
6026        (unless (member elt (default-value 'desktop-locals-to-save))
6027          (setq-default desktop-locals-to-save
6028                        (cons elt (default-value 'desktop-locals-to-save)))))
6029      (add-hook 'desktop-after-read-hook '(lambda ()
6030                                            (TeX-set-mode-name t)))))
6031
6032 ;; delsel.el, `delete-selection-mode'
6033 (put 'TeX-newline 'delete-selection t)
6034 (put 'TeX-insert-quote 'delete-selection t)
6035 (put 'TeX-insert-backslash 'delete-selection t)
6036
6037 (defun TeX-how-many (regexp &optional rstart rend)
6038   "Compatibily function for `how-many'.
6039 Supports restriction to a region where the XEmacs version doesn't
6040 and always returns the number of matches, also in XEmacs and GNU
6041 Emacs 21."
6042   ;; Emacs >= 22 does what we want.
6043   (if (>= emacs-major-version 22)
6044       (how-many regexp rstart rend)
6045     ;; XEmacs and GNU Emacs 21 don't return the number of matches but only print
6046     ;; it.
6047     (let ((string
6048            (if (featurep 'xemacs)
6049                ;; XEmacs doesn't even support restriction to a region.
6050                (save-excursion
6051                  (save-restriction
6052                    (when (and (integer-or-marker-p rstart)
6053                               (integer-or-marker-p rend))
6054                      (narrow-to-region rstart rend)
6055                      (goto-char (point-min)))
6056                    (how-many regexp)))
6057              (how-many regexp rstart rend))))
6058       ;; Hide the message printed by `how-many'.
6059       (message "")
6060       ;; Select the number of occurrences and convert it to a number.
6061       (if (string-match "\\([0-9]+\\).*" string)
6062           (string-to-number (replace-match "\\1" nil nil string))
6063         0))))
6064
6065 (provide 'tex)
6066
6067 ;; Local Variables:
6068 ;; coding: iso-8859-1
6069 ;; End:
6070
6071 ;;; tex.el ends here