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