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