]> code.delx.au - gnu-emacs/blob - lisp/textmodes/tex-mode.el
(bibtex-search-reference): store-match-data => set-match-data.
[gnu-emacs] / lisp / textmodes / tex-mode.el
1 ;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands.
2
3 ;; Copyright (C) 1985, 86, 89, 92, 94, 95, 96, 1997
4 ;; Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7 ;; Keywords: tex
8
9 ;; Contributions over the years by William F. Schelter, Dick King,
10 ;; Stephen Gildea, Michael Prange, Jacob Gore, and Edward M. Reingold.
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28
29 ;;; Code:
30
31 (require 'shell)
32 (require 'compile)
33
34 (defgroup tex-file nil
35 "TeX files and directories"
36 :prefix "tex-"
37 :group 'tex)
38
39 (defgroup tex-run nil
40 "Running external commands from TeX mode"
41 :prefix "tex-"
42 :group 'tex)
43
44 (defgroup tex-view nil
45 "Viewing and printing TeX files"
46 :prefix "tex-"
47 :group 'tex)
48
49 ;;;###autoload
50 (defcustom tex-shell-file-name nil
51 "*If non-nil, the shell file name to run in the subshell used to run TeX."
52 :type '(choice (const :tag "None" nil)
53 string)
54 :group 'tex-run)
55
56 ;;;###autoload
57 (defcustom tex-directory "."
58 "*Directory in which temporary files are written.
59 You can make this `/tmp' if your TEXINPUTS has no relative directories in it
60 and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
61 `\\input' commands with relative directories."
62 :type 'directory
63 :group 'tex-file)
64
65 ;;;###autoload
66 (defcustom tex-first-line-header-regexp nil
67 "Regexp for matching a first line which `tex-region' should include.
68 If this is non-nil, it should be a regular expression string;
69 if it matches the first line of the file,
70 `tex-region' always includes the first line in the TeX run."
71 :type '(choice (const :tag "None" nil)
72 regexp)
73 :group 'tex-file)
74
75 ;;;###autoload
76 (defcustom tex-main-file nil
77 "*The main TeX source file which includes this buffer's file.
78 The command `tex-buffer' runs TeX on `tex-main-file'if that is non-nil."
79 :type '(choice (const :tag "None" nil)
80 file)
81 :group 'tex-file)
82
83 ;;;###autoload
84 (defcustom tex-offer-save t
85 "*If non-nil, ask about saving modified buffers before \\[tex-file] is run."
86 :type 'boolean
87 :group 'tex-file)
88
89 ;;;###autoload
90 (defcustom tex-run-command "tex"
91 "*Command used to run TeX subjob.
92 If this string contains an asterisk (`*'), that is replaced by the file name;
93 otherwise, the file name, preceded by blank, is added at the end."
94 :type 'string
95 :group 'tex-run)
96
97 ;;;###autoload
98 (defcustom latex-run-command "latex"
99 "*Command used to run LaTeX subjob.
100 If this string contains an asterisk (`*'), that is replaced by the file name;
101 otherwise, the file name, preceded by blank, is added at the end."
102 :type 'string
103 :group 'tex-run)
104
105 (defvar standard-latex-block-names
106 '("abstract" "array" "center" "description"
107 "displaymath" "document" "enumerate" "eqnarray"
108 "eqnarray*" "equation" "figure" "figure*"
109 "flushleft" "flushright" "itemize" "letter"
110 "list" "minipage" "picture" "quotation"
111 "quote" "slide" "sloppypar" "tabbing"
112 "table" "table*" "tabular" "tabular*"
113 "thebibliography" "theindex*" "titlepage" "trivlist"
114 "verbatim" "verbatim*" "verse")
115 "Standard LaTeX block names.")
116
117 ;;;###autoload
118 (defcustom latex-block-names nil
119 "*User defined LaTeX block names.
120 Combined with `standard-latex-block-names' for minibuffer completion."
121 :type '(repeat string)
122 :group 'tex-run)
123
124 ;;;###autoload
125 (defcustom slitex-run-command "slitex"
126 "*Command used to run SliTeX subjob.
127 If this string contains an asterisk (`*'), that is replaced by the file name;
128 otherwise, the file name, preceded by blank, is added at the end."
129 :type 'string
130 :group 'tex-run)
131
132 ;;;###autoload
133 (defcustom tex-bibtex-command "bibtex"
134 "*Command used by `tex-bibtex-file' to gather bibliographic data.
135 If this string contains an asterisk (`*'), that is replaced by the file name;
136 otherwise, the file name, preceded by blank, is added at the end."
137 :type 'string
138 :group 'tex-run)
139
140 ;;;###autoload
141 (defcustom tex-dvi-print-command "lpr -d"
142 "*Command used by \\[tex-print] to print a .dvi file.
143 If this string contains an asterisk (`*'), that is replaced by the file name;
144 otherwise, the file name, preceded by blank, is added at the end."
145 :type 'string
146 :group 'tex-view)
147
148 ;;;###autoload
149 (defcustom tex-alt-dvi-print-command "lpr -d"
150 "*Command used by \\[tex-print] with a prefix arg to print a .dvi file.
151 If this string contains an asterisk (`*'), that is replaced by the file name;
152 otherwise, the file name, preceded by blank, is added at the end.
153
154 If two printers are not enough of a choice, you can set the variable
155 `tex-alt-dvi-print-command' to an expression that asks what you want;
156 for example,
157
158 (setq tex-alt-dvi-print-command
159 '(format \"lpr -P%s\" (read-string \"Use printer: \")))
160
161 would tell \\[tex-print] with a prefix argument to ask you which printer to
162 use."
163 :type '(choice (string :tag "Command")
164 (sexp :tag "Expression"))
165 :group 'tex-view)
166
167 ;;;###autoload
168 (defcustom tex-dvi-view-command nil
169 "*Command used by \\[tex-view] to display a `.dvi' file.
170 If this string contains an asterisk (`*'), that is replaced by the file name;
171 otherwise, the file name, preceded by blank, is added at the end.
172
173 This can be set conditionally so that the previewer used is suitable for the
174 window system being used. For example,
175
176 (setq tex-dvi-view-command
177 (if (eq window-system 'x) \"xdvi\" \"dvi2tty * | cat -s\"))
178
179 would tell \\[tex-view] to use xdvi under X windows and to use dvi2tty
180 otherwise."
181 :type '(choice (const nil) string)
182 :group 'tex-view)
183
184 ;;;###autoload
185 (defcustom tex-show-queue-command "lpq"
186 "*Command used by \\[tex-show-print-queue] to show the print queue.
187 Should show the queue(s) that \\[tex-print] puts jobs on."
188 :type 'string
189 :group 'tex-view)
190
191 ;;;###autoload
192 (defcustom tex-default-mode 'plain-tex-mode
193 "*Mode to enter for a new file that might be either TeX or LaTeX.
194 This variable is used when it can't be determined whether the file
195 is plain TeX or LaTeX or what because the file contains no commands.
196 Normally set to either `plain-tex-mode' or `latex-mode'."
197 :type 'function
198 :group 'tex)
199
200 ;;;###autoload
201 (defcustom tex-open-quote "``"
202 "*String inserted by typing \\[tex-insert-quote] to open a quotation."
203 :type 'string
204 :group 'tex)
205
206 ;;;###autoload
207 (defcustom tex-close-quote "''"
208 "*String inserted by typing \\[tex-insert-quote] to close a quotation."
209 :type 'string
210 :group 'tex)
211
212 (defvar tex-last-temp-file nil
213 "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
214 Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
215 tex shell terminates.")
216
217 (defvar tex-command nil
218 "Command to run TeX.
219 The name of the file, preceded by a blank, will be added to this string.")
220
221 (defvar tex-trailer nil
222 "String appended after the end of a region sent to TeX by \\[tex-region].")
223
224 (defvar tex-start-of-header nil
225 "Regular expression used by \\[tex-region] to find start of file's header.")
226
227 (defvar tex-end-of-header nil
228 "Regular expression used by \\[tex-region] to find end of file's header.")
229
230 (defvar tex-shell-cd-command "cd"
231 "Command to give to shell running TeX to change directory.
232 The value of `tex-directory' is appended to this, separated by a space.")
233
234 (defvar tex-zap-file nil
235 "Temporary file name used for text being sent as input to TeX.
236 Should be a simple file name with no extension or directory specification.")
237
238 (defvar tex-last-buffer-texed nil
239 "Buffer which was last TeXed.")
240
241 (defvar tex-print-file nil
242 "File name that \\[tex-print] prints.
243 Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
244
245 (defvar tex-mode-syntax-table nil
246 "Syntax table used while in TeX mode.")
247
248 (defcustom latex-imenu-indent-string "."
249 "*String to add repeated in front of nested sectional units for Imenu.
250 An alternative value is \" . \", if you use a font with a narrow period."
251 :type 'string
252 :group 'tex)
253
254 (defun latex-imenu-create-index ()
255 "Generates an alist for imenu from a LaTeX buffer."
256 (let (i0 menu case-fold-search)
257 (save-excursion
258 ;; Find the top-most level in this file but don't allow it to be
259 ;; any deeper than "section" (which is top-level in an article).
260 (goto-char (point-min))
261 (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t)
262 (setq i0 0)
263 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
264 (setq i0 1)
265 (setq i0 2)))
266
267 ;; Look for chapters and sections.
268 (goto-char (point-min))
269 (while (search-forward-regexp
270 "\\\\\\(part\\|chapter\\|section\\|subsection\\|\
271 subsubsection\\|paragraph\\|subparagraph\\)\\*?[ \t]*{" nil t)
272 (let ((start (match-beginning 0))
273 (here (point))
274 (i (cdr (assoc (buffer-substring-no-properties
275 (match-beginning 1)
276 (match-end 1))
277 '(("part" . 0) ("chapter" . 1)
278 ("section" . 2) ("subsection" . 3)
279 ("subsubsection" . 4)
280 ("paragraph" . 5) ("subparagraph" . 6))))))
281 (backward-char 1)
282 (condition-case err
283 (progn
284 ;; Using sexps allows some use of matching {...} inside
285 ;; titles.
286 (forward-sexp 1)
287 (setq menu
288 (cons (cons (concat (apply 'concat
289 (make-list
290 (max 0 (- i i0))
291 latex-imenu-indent-string))
292 (buffer-substring-no-properties
293 here (1- (point))))
294 start)
295 menu))
296 )
297 (error nil))))
298
299 ;; Look for included material.
300 (goto-char (point-min))
301 (while (search-forward-regexp
302 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
303 [ \t]*{\\([^}\n]+\\)}"
304 nil t)
305 (setq menu
306 (cons (cons (concat "<<" (buffer-substring-no-properties
307 (match-beginning 2)
308 (match-end 2))
309 (if (= (char-after (match-beginning 1)) ?b)
310 ".bbl"
311 ".tex"))
312 (match-beginning 0))
313 menu)))
314
315 ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
316 (goto-char (point-min))
317 (while (search-forward-regexp
318 "\\\\\\(frontmatter\\|mainmatter\\|backmatter\\|appendix\\)\\b"
319 nil t)
320 (setq menu
321 (cons (cons "--" (match-beginning 0))
322 menu)))
323
324 ;; Sort in increasing buffer position order.
325 (sort menu (function (lambda (a b) (< (cdr a) (cdr b))))))))
326
327 (defun tex-define-common-keys (keymap)
328 "Define the keys that we want defined both in TeX mode and in the TeX shell."
329 (define-key keymap "\C-c\C-k" 'tex-kill-job)
330 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
331 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
332 (define-key keymap "\C-c\C-p" 'tex-print)
333 (define-key keymap "\C-c\C-v" 'tex-view)
334
335 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
336
337 (define-key keymap [menu-bar tex tex-kill-job] '("Tex Kill" . tex-kill-job))
338 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
339 '("Tex Recenter" . tex-recenter-output-buffer))
340 (define-key keymap [menu-bar tex tex-show-print-queue]
341 '("Show Print Queue" . tex-show-print-queue))
342 (define-key keymap [menu-bar tex tex-alt-print]
343 '("Tex Print (alt printer)" . tex-alt-print))
344 (define-key keymap [menu-bar tex tex-print] '("Tex Print" . tex-print))
345 (define-key keymap [menu-bar tex tex-view] '("Tex View" . tex-view))
346 )
347
348 (defvar tex-mode-map nil "Keymap for TeX mode.")
349
350 (if tex-mode-map
351 nil
352 (setq tex-mode-map (make-sparse-keymap))
353 (tex-define-common-keys tex-mode-map)
354 (define-key tex-mode-map "\"" 'tex-insert-quote)
355 (define-key tex-mode-map "\n" 'tex-terminate-paragraph)
356 (define-key tex-mode-map "\C-c}" 'up-list)
357 (define-key tex-mode-map "\C-c{" 'tex-insert-braces)
358 (define-key tex-mode-map "\C-c\C-r" 'tex-region)
359 (define-key tex-mode-map "\C-c\C-b" 'tex-buffer)
360 (define-key tex-mode-map "\C-c\C-f" 'tex-file)
361 (define-key tex-mode-map "\C-c\C-i" 'tex-bibtex-file)
362 (define-key tex-mode-map "\C-c\C-o" 'tex-latex-block)
363 (define-key tex-mode-map "\C-c\C-e" 'tex-close-latex-block)
364 (define-key tex-mode-map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
365 (define-key tex-mode-map [menu-bar tex tex-bibtex-file]
366 '("BibTeX File" . tex-bibtex-file))
367 (define-key tex-mode-map [menu-bar tex tex-validate-region]
368 '("Validate Region" . tex-validate-region))
369 (define-key tex-mode-map [menu-bar tex validate-tex-buffer]
370 '("Validate Buffer" . validate-tex-buffer))
371 (define-key tex-mode-map [menu-bar tex tex-region]
372 '("TeX Region" . tex-region))
373 (define-key tex-mode-map [menu-bar tex tex-buffer]
374 '("TeX Buffer" . tex-buffer))
375 (define-key tex-mode-map [menu-bar tex tex-file] '("TeX File" . tex-file)))
376
377 (put 'tex-region 'menu-enable 'mark-active)
378 (put 'tex-validate-region 'menu-enable 'mark-active)
379 (put 'tex-print 'menu-enable '(stringp tex-print-file))
380 (put 'tex-alt-print 'menu-enable '(stringp tex-print-file))
381 (put 'tex-view 'menu-enable '(stringp tex-print-file))
382 (put 'tex-recenter-output-buffer 'menu-enable '(get-buffer "*tex-shell*"))
383 (put 'tex-kill-job 'menu-enable '(tex-shell-running))
384
385
386 (defvar tex-shell-map nil
387 "Keymap for the TeX shell.
388 Inherits `shell-mode-map' with a few additions.")
389
390 (defvar tex-face-alist
391 '((bold . "{\\bf ")
392 (italic . "{\\it ")
393 (bold-italic . "{\\bi ") ; hypothetical
394 (underline . "\\underline{")
395 (default . "{\\rm "))
396 "Alist of face and TeX font name for facemenu.")
397
398 (defvar tex-latex-face-alist
399 `((italic . "{\\em ")
400 ,@tex-face-alist)
401 "Alist of face and LaTeX font name for facemenu.")
402
403
404 (defvar compare-windows-whitespace) ; Pacify the byte-compiler
405
406 ;;; This would be a lot simpler if we just used a regexp search,
407 ;;; but then it would be too slow.
408 ;;;###autoload
409 (defun tex-mode ()
410 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
411 Tries to determine (by looking at the beginning of the file) whether
412 this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
413 `latex-mode', or `slitex-mode', respectively. If it cannot be determined,
414 such as if there are no commands in the file, the value of `tex-default-mode'
415 says which mode to use."
416 (interactive)
417 (let (mode slash comment)
418 (save-excursion
419 (goto-char (point-min))
420 (while (and (setq slash (search-forward "\\" nil t))
421 (setq comment (let ((search-end (point)))
422 (save-excursion
423 (beginning-of-line)
424 (search-forward "%" search-end t))))))
425 (if (and slash (not comment))
426 (setq mode (if (looking-at "documentstyle\\|documentclass\\|begin\\b\\|NeedsTeXFormat{LaTeX")
427 (if (looking-at
428 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
429 'slitex-mode
430 'latex-mode)
431 'plain-tex-mode))))
432 (if mode (funcall mode)
433 (funcall tex-default-mode))))
434
435 ;;;###autoload
436 (defalias 'TeX-mode 'tex-mode)
437 ;;;###autoload
438 (defalias 'LaTeX-mode 'latex-mode)
439
440 ;;;###autoload
441 (defun plain-tex-mode ()
442 "Major mode for editing files of input for plain TeX.
443 Makes $ and } display the characters they match.
444 Makes \" insert `` when it seems to be the beginning of a quotation,
445 and '' when it appears to be the end; it inserts \" only after a \\.
446
447 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
448 copied from the top of the file (containing macro definitions, etc.),
449 running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
450 \\[tex-file] saves the buffer and then processes the file.
451 \\[tex-print] prints the .dvi file made by any of these.
452 \\[tex-view] previews the .dvi file made by any of these.
453 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
454
455 Use \\[validate-tex-buffer] to check buffer for paragraphs containing
456 mismatched $'s or braces.
457
458 Special commands:
459 \\{tex-mode-map}
460
461 Mode variables:
462 tex-run-command
463 Command string used by \\[tex-region] or \\[tex-buffer].
464 tex-directory
465 Directory in which to create temporary files for TeX jobs
466 run by \\[tex-region] or \\[tex-buffer].
467 tex-dvi-print-command
468 Command string used by \\[tex-print] to print a .dvi file.
469 tex-alt-dvi-print-command
470 Alternative command string used by \\[tex-print] (when given a prefix
471 argument) to print a .dvi file.
472 tex-dvi-view-command
473 Command string used by \\[tex-view] to preview a .dvi file.
474 tex-show-queue-command
475 Command string used by \\[tex-show-print-queue] to show the print
476 queue that \\[tex-print] put your job on.
477
478 Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
479 `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
480 special subshell is initiated, the hook `tex-shell-hook' is run."
481
482 (interactive)
483 (tex-common-initialization)
484 (setq mode-name "TeX")
485 (setq major-mode 'plain-tex-mode)
486 (setq tex-command tex-run-command)
487 (setq tex-start-of-header "%\\*\\*start of header")
488 (setq tex-end-of-header "%\\*\\*end of header")
489 (setq tex-trailer "\\bye\n")
490 (run-hooks 'text-mode-hook 'tex-mode-hook 'plain-tex-mode-hook))
491 ;;;###autoload
492 (defalias 'plain-TeX-mode 'plain-tex-mode)
493
494 ;;;###autoload
495 (defun latex-mode ()
496 "Major mode for editing files of input for LaTeX.
497 Makes $ and } display the characters they match.
498 Makes \" insert `` when it seems to be the beginning of a quotation,
499 and '' when it appears to be the end; it inserts \" only after a \\.
500
501 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
502 copied from the top of the file (containing \\documentstyle, etc.),
503 running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
504 \\[tex-file] saves the buffer and then processes the file.
505 \\[tex-print] prints the .dvi file made by any of these.
506 \\[tex-view] previews the .dvi file made by any of these.
507 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
508
509 Use \\[validate-tex-buffer] to check buffer for paragraphs containing
510 mismatched $'s or braces.
511
512 Special commands:
513 \\{tex-mode-map}
514
515 Mode variables:
516 latex-run-command
517 Command string used by \\[tex-region] or \\[tex-buffer].
518 tex-directory
519 Directory in which to create temporary files for LaTeX jobs
520 run by \\[tex-region] or \\[tex-buffer].
521 tex-dvi-print-command
522 Command string used by \\[tex-print] to print a .dvi file.
523 tex-alt-dvi-print-command
524 Alternative command string used by \\[tex-print] (when given a prefix
525 argument) to print a .dvi file.
526 tex-dvi-view-command
527 Command string used by \\[tex-view] to preview a .dvi file.
528 tex-show-queue-command
529 Command string used by \\[tex-show-print-queue] to show the print
530 queue that \\[tex-print] put your job on.
531
532 Entering Latex mode runs the hook `text-mode-hook', then
533 `tex-mode-hook', and finally `latex-mode-hook'. When the special
534 subshell is initiated, `tex-shell-hook' is run."
535 (interactive)
536 (tex-common-initialization)
537 (setq mode-name "LaTeX")
538 (setq major-mode 'latex-mode)
539 (setq tex-command latex-run-command)
540 (setq tex-start-of-header "\\\\documentstyle\\|\\\\documentclass")
541 (setq tex-end-of-header "\\\\begin{document}")
542 (setq tex-trailer "\\end{document}\n")
543 ;; A line containing just $$ is treated as a paragraph separator.
544 ;; A line starting with $$ starts a paragraph,
545 ;; but does not separate paragraphs if it has more stuff on it.
546 (setq paragraph-start "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$\\|\
547 \\\\begin\\>\\|\\\\label\\>\\|\\\\end\\>\\|\\\\\\[\\|\\\\\\]\\|\
548 \\\\chapter\\>\\|\\\\section\\>\\|\
549 \\\\subsection\\>\\|\\\\subsubsection\\>\\|\
550 \\\\paragraph\\>\\|\\\\subparagraph\\>\\|\
551 \\\\item\\>\\|\\\\bibitem\\>\\|\\\\newline\\>\\|\\\\noindent\\>\\|\
552 \\\\[a-z]*space\\>\\|\\\\[a-z]*skip\\>\\|\
553 \\\\newpage\\>\\|\\\\[a-z]*page\\|\\\\footnote\\>\\|\
554 \\\\marginpar\\>\\|\\\\parbox\\>\\|\\\\caption\\>")
555 (setq paragraph-separate "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$[ \t]*$\\|\
556 \\\\begin\\>\\|\\\\label\\>\\|\\\\end\\>\\|\\\\\\[\\|\\\\\\]\\|\
557 \\\\chapter\\>\\|\\\\section\\>\\|\
558 \\\\subsection\\>\\|\\\\subsubsection\\>\\|\
559 \\\\paragraph\\>\\|\\\\subparagraph\\>\\|\
560 \\(\\\\item\\|\\\\bibitem\\|\\\\newline\\|\\\\noindent\\|\
561 \\\\[a-z]*space\\|\\\\[a-z]*skip\\|\
562 \\\\newpage\\|\\\\[a-z]*page[a-z]*\\|\\\\footnote\\|\
563 \\\\marginpar\\|\\\\parbox\\|\\\\caption\\)[ \t]*\\($\\|%\\)")
564 (make-local-variable 'imenu-create-index-function)
565 (setq imenu-create-index-function 'latex-imenu-create-index)
566 (make-local-variable 'tex-face-alist)
567 (setq tex-face-alist tex-latex-face-alist)
568 (make-local-variable 'fill-nobreak-predicate)
569 (setq fill-nobreak-predicate 'latex-fill-nobreak-predicate)
570 (run-hooks 'text-mode-hook 'tex-mode-hook 'latex-mode-hook))
571
572 ;;;###autoload
573 (defun slitex-mode ()
574 "Major mode for editing files of input for SliTeX.
575 Makes $ and } display the characters they match.
576 Makes \" insert `` when it seems to be the beginning of a quotation,
577 and '' when it appears to be the end; it inserts \" only after a \\.
578
579 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
580 copied from the top of the file (containing \\documentstyle, etc.),
581 running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
582 \\[tex-file] saves the buffer and then processes the file.
583 \\[tex-print] prints the .dvi file made by any of these.
584 \\[tex-view] previews the .dvi file made by any of these.
585 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
586
587 Use \\[validate-tex-buffer] to check buffer for paragraphs containing
588 mismatched $'s or braces.
589
590 Special commands:
591 \\{tex-mode-map}
592
593 Mode variables:
594 slitex-run-command
595 Command string used by \\[tex-region] or \\[tex-buffer].
596 tex-directory
597 Directory in which to create temporary files for SliTeX jobs
598 run by \\[tex-region] or \\[tex-buffer].
599 tex-dvi-print-command
600 Command string used by \\[tex-print] to print a .dvi file.
601 tex-alt-dvi-print-command
602 Alternative command string used by \\[tex-print] (when given a prefix
603 argument) to print a .dvi file.
604 tex-dvi-view-command
605 Command string used by \\[tex-view] to preview a .dvi file.
606 tex-show-queue-command
607 Command string used by \\[tex-show-print-queue] to show the print
608 queue that \\[tex-print] put your job on.
609
610 Entering SliTeX mode runs the hook `text-mode-hook', then the hook
611 `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
612 `slitex-mode-hook'. When the special subshell is initiated, the hook
613 `tex-shell-hook' is run."
614 (interactive)
615 (tex-common-initialization)
616 (setq mode-name "SliTeX")
617 (setq major-mode 'slitex-mode)
618 (setq tex-command slitex-run-command)
619 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}")
620 (setq tex-end-of-header "\\\\begin{document}")
621 (setq tex-trailer "\\end{document}\n")
622 ;; A line containing just $$ is treated as a paragraph separator.
623 ;; A line starting with $$ starts a paragraph,
624 ;; but does not separate paragraphs if it has more stuff on it.
625 (setq paragraph-start "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$\\|\
626 \\\\begin\\>\\|\\\\label\\>\\|\\\\end\\>\\|\\\\\\[\\|\\\\\\]\\|\
627 \\\\chapter\\>\\|\\\\section\\>\\|\
628 \\\\subsection\\>\\|\\\\subsubsection\\>\\|\
629 \\\\paragraph\\>\\|\\\\subparagraph\\>\\|\
630 \\\\item\\>\\|\\\\bibitem\\>\\|\\\\newline\\>\\|\\\\noindent\\>\\|\
631 \\\\[a-z]*space\\>\\|\\\\[a-z]*skip\\>\\|\
632 \\\\newpage\\>\\|\\\\[a-z]*page\\|\\\\footnote\\>\\|\
633 \\\\marginpar\\>\\|\\\\parbox\\>\\|\\\\caption\\>")
634 (setq paragraph-separate "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$[ \t]*$\\|\
635 \\\\begin\\>\\|\\\\label\\>\\|\\\\end\\>\\|\\\\\\[\\|\\\\\\]\\|\
636 \\\\chapter\\>\\|\\\\section\\>\\|\
637 \\\\subsection\\>\\|\\\\subsubsection\\>\\|\
638 \\\\paragraph\\>\\|\\\\subparagraph\\>\\|\
639 \\\\item[ \t]*$\\|\\\\bibitem[ \t]*$\\|\\\\newline[ \t]*$\\|\\\\noindent[ \t]*$\\|\
640 \\\\[a-z]*space[ \t]*$\\|\\\\[a-z]*skip[ \t]*$\\|\
641 \\\\newpage[ \t]*$\\|\\\\[a-z]*page[a-z]*[ \t]*$\\|\\\\footnote[ \t]*$\\|\
642 \\\\marginpar[ \t]*$\\|\\\\parbox[ \t]*$\\|\\\\caption[ \t]*$")
643 (make-local-variable 'imenu-create-index-function)
644 (setq imenu-create-index-function 'latex-imenu-create-index)
645 (make-local-variable 'tex-face-alist)
646 (setq tex-face-alist tex-latex-face-alist)
647 (make-local-variable 'fill-nobreak-predicate)
648 (setq fill-nobreak-predicate 'latex-fill-nobreak-predicate)
649 (run-hooks
650 'text-mode-hook 'tex-mode-hook 'latex-mode-hook 'slitex-mode-hook))
651
652 (defun tex-common-initialization ()
653 (kill-all-local-variables)
654 (use-local-map tex-mode-map)
655 (setq local-abbrev-table text-mode-abbrev-table)
656 (if (null tex-mode-syntax-table)
657 (let ((char 0))
658 (setq tex-mode-syntax-table (make-syntax-table))
659 (set-syntax-table tex-mode-syntax-table)
660 (while (< char ? )
661 (modify-syntax-entry char ".")
662 (setq char (1+ char)))
663 (modify-syntax-entry ?\C-@ "w")
664 (modify-syntax-entry ?\t " ")
665 (modify-syntax-entry ?\n ">")
666 (modify-syntax-entry ?\f ">")
667 (modify-syntax-entry ?$ "$$")
668 (modify-syntax-entry ?% "<")
669 (modify-syntax-entry ?\\ "/")
670 (modify-syntax-entry ?\" ".")
671 (modify-syntax-entry ?& ".")
672 (modify-syntax-entry ?_ ".")
673 (modify-syntax-entry ?@ "_")
674 (modify-syntax-entry ?~ " ")
675 (modify-syntax-entry ?' "w"))
676 (set-syntax-table tex-mode-syntax-table))
677 ;; Regexp isearch should accept newline and formfeed as whitespace.
678 (make-local-variable 'search-whitespace-regexp)
679 (setq search-whitespace-regexp "[ \t\r\n\f]+")
680 (make-local-variable 'paragraph-start)
681 ;; A line containing just $$ is treated as a paragraph separator.
682 (setq paragraph-start "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
683 (make-local-variable 'paragraph-separate)
684 ;; A line starting with $$ starts a paragraph,
685 ;; but does not separate paragraphs if it has more stuff on it.
686 (setq paragraph-separate "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
687 (make-local-variable 'comment-start)
688 (setq comment-start "%")
689 (make-local-variable 'comment-start-skip)
690 (setq comment-start-skip "\\(\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
691 (make-local-variable 'comment-indent-function)
692 (setq comment-indent-function 'tex-comment-indent)
693 (make-local-variable 'parse-sexp-ignore-comments)
694 (setq parse-sexp-ignore-comments t)
695 (make-local-variable 'compare-windows-whitespace)
696 (setq compare-windows-whitespace 'tex-categorize-whitespace)
697 (make-local-variable 'skeleton-further-elements)
698 (setq skeleton-further-elements
699 '((indent-line-function 'indent-relative-maybe)))
700 (make-local-variable 'facemenu-add-face-function)
701 (make-local-variable 'facemenu-end-add-face)
702 (make-local-variable 'facemenu-remove-face-function)
703 (setq facemenu-add-face-function
704 (lambda (face end)
705 (let ((face-text (cdr (assq face tex-face-alist))))
706 (if face-text
707 face-text
708 (error "Face %s not configured for %s mode" face mode-name))))
709 facemenu-end-add-face "}"
710 facemenu-remove-face-function t)
711 (make-local-variable 'tex-command)
712 (make-local-variable 'tex-start-of-header)
713 (make-local-variable 'tex-end-of-header)
714 (make-local-variable 'tex-trailer))
715
716 (defun tex-comment-indent ()
717 (if (looking-at "%%%")
718 (current-column)
719 (skip-chars-backward " \t")
720 (max (if (bolp) 0 (1+ (current-column)))
721 comment-column)))
722
723 (defun tex-categorize-whitespace (backward-limit)
724 ;; compare-windows-whitespace is set to this.
725 ;; This is basically a finite-state machine.
726 ;; Returns a symbol telling how TeX would treat
727 ;; the whitespace we are looking at: null, space, or par.
728 (let ((category 'null)
729 (not-finished t))
730 (skip-chars-backward " \t\n\f" backward-limit)
731 (while not-finished
732 (cond ((looking-at "[ \t]+")
733 (goto-char (match-end 0))
734 (if (eq category 'null)
735 (setq category 'space)))
736 ((looking-at "\n")
737 (cond ((eq category 'newline)
738 (setq category 'par)
739 (setq not-finished nil))
740 (t
741 (setq category 'newline) ;a strictly internal state
742 (goto-char (match-end 0)))))
743 ((looking-at "\f+")
744 (setq category 'par)
745 (setq not-finished nil))
746 (t
747 (setq not-finished nil))))
748 (skip-chars-forward " \t\n\f")
749 (if (eq category 'newline)
750 'space ;TeX doesn't distinguish
751 category)))
752
753 (defun tex-insert-quote (arg)
754 "Insert the appropriate quote marks for TeX.
755 Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
756 \(normally '') depending on the context. With prefix argument, always
757 inserts \" characters."
758 (interactive "*P")
759 (if arg
760 (self-insert-command (prefix-numeric-value arg))
761 (insert
762 (cond ((or (bobp)
763 (save-excursion
764 (forward-char -1)
765 (looking-at "\\s(\\|\\s \\|\\s>")))
766 tex-open-quote)
767 ((= (preceding-char) ?\\)
768 ?\")
769 (t
770 tex-close-quote)))))
771
772 (defun validate-tex-buffer ()
773 "Check current buffer for paragraphs containing mismatched $s.
774 Their positions are recorded in the buffer `*Occur*'.
775 To find a particular invalidity from `*Occur*',
776 switch to to that buffer and type C-c C-c on the line
777 for the invalidity you want to see."
778 (interactive)
779 (let ((buffer (current-buffer))
780 (prevpos (point-min))
781 (linenum nil))
782 (with-output-to-temp-buffer "*Occur*"
783 (princ "Mismatches:\n")
784 (save-excursion
785 (set-buffer standard-output)
786 (occur-mode)
787 (setq occur-buffer buffer)
788 (setq occur-nlines 0)
789 (setq occur-pos-list nil))
790 (save-excursion
791 (goto-char (point-max))
792 (while (and (not (input-pending-p)) (not (bobp)))
793 (let ((end (point))
794 prev-end)
795 ;; Scan the previous paragraph for invalidities.
796 (if (search-backward "\n\n" nil t)
797 (progn
798 (setq prev-end (point))
799 (forward-char 2))
800 (goto-char (setq prev-end (point-min))))
801 (or (tex-validate-region (point) end)
802 (let* ((oend end)
803 (end (save-excursion (forward-line 1) (point)))
804 start tem)
805 (beginning-of-line)
806 (setq start (point))
807 ;; Keep track of line number as we scan,
808 ;; in a cumulative fashion.
809 (if linenum
810 (setq linenum (- linenum (count-lines prevpos (point))))
811 (setq linenum (1+ (count-lines 1 start))))
812 (setq prevpos (point))
813 ;; Mention this mismatch in *Occur*.
814 ;; Since we scan from end of buffer to beginning,
815 ;; add each mismatch at the beginning of *Occur*
816 ;; and at the beginning of occur-pos-list.
817 (save-excursion
818 (setq tem (point-marker))
819 (set-buffer standard-output)
820 (goto-char (point-min))
821 ;; Skip "Mismatches:" header line.
822 (forward-line 1)
823 (setq occur-pos-list (cons tem occur-pos-list))
824 (insert-buffer-substring buffer start end)
825 (forward-char (- start end))
826 (insert (format "%3d: " linenum)))))
827 (goto-char prev-end))))
828 (save-excursion
829 (set-buffer standard-output)
830 (if (null occur-pos-list)
831 (insert "None!\n"))
832 (if (interactive-p)
833 (message "%d mismatches found" (length occur-pos-list)))))))
834
835 (defun tex-validate-region (start end)
836 "Check for mismatched braces or $'s in region.
837 Returns t if no mismatches. Returns nil and moves point to suspect
838 area if a mismatch is found."
839 (interactive "r")
840 (let ((failure-point nil) (max-possible-sexps (- end start)))
841 (save-excursion
842 (condition-case ()
843 (save-restriction
844 (narrow-to-region start end)
845 ;; First check that the open and close parens balance in numbers.
846 (goto-char start)
847 (while (< 0 (setq max-possible-sexps (1- max-possible-sexps)))
848 (forward-sexp 1))
849 ;; Now check that like matches like.
850 (goto-char start)
851 (while (progn (skip-syntax-forward "^(")
852 (not (eobp)))
853 (let ((match (matching-paren (following-char))))
854 (save-excursion
855 (forward-sexp 1)
856 (or (= (preceding-char) match)
857 (error "Mismatched parentheses"))))
858 (forward-char 1)))
859 (error
860 (skip-syntax-forward " .>")
861 (setq failure-point (point)))))
862 (if failure-point
863 (progn
864 (goto-char failure-point)
865 nil)
866 t)))
867
868 (defun tex-terminate-paragraph (inhibit-validation)
869 "Insert two newlines, breaking a paragraph for TeX.
870 Check for mismatched braces or $s in paragraph being terminated.
871 A prefix arg inhibits the checking."
872 (interactive "*P")
873 (or inhibit-validation
874 (save-excursion
875 (tex-validate-region
876 (save-excursion
877 (search-backward "\n\n" nil 'move)
878 (point))
879 (point)))
880 (message "Paragraph being closed appears to contain a mismatch"))
881 (insert "\n\n"))
882
883 (defun tex-insert-braces ()
884 "Make a pair of braces and be poised to type inside of them."
885 (interactive "*")
886 (insert ?\{)
887 (save-excursion
888 (insert ?})))
889
890 ;; This function is used as the value of fill-nobreak-predicate
891 ;; in LaTeX mode. Its job is to prevent line-breaking inside
892 ;; of a \verb construct.
893 (defun latex-fill-nobreak-predicate ()
894 (let ((opoint (point))
895 inside)
896 (save-excursion
897 (save-restriction
898 (beginning-of-line)
899 (narrow-to-region (point) opoint)
900 (while (re-search-forward "\\\\verb\\(.\\)" nil t)
901 (unless (re-search-forward (regexp-quote (match-string 1)) nil t)
902 (setq inside t)))))
903 inside))
904
905 ;;; Like tex-insert-braces, but for LaTeX.
906 (define-skeleton tex-latex-block
907 "Create a matching pair of lines \\begin[OPT]{NAME} and \\end{NAME} at point.
908 Puts point on a blank line between them."
909 (completing-read "LaTeX block name: "
910 (mapcar 'list
911 (append standard-latex-block-names
912 latex-block-names)))
913 "\\begin["
914 (skeleton-read "[options]: ") & ?\] | -1
915 ?\{
916 str
917 ?\} \n
918 _ \n
919 "\\end{" str ?\})
920
921 (defun tex-last-unended-begin ()
922 "Leave point at the beginning of the last `\\begin{...}' that is unended."
923 (while (and (re-search-backward "\\(\\\\begin\\s *{\\)\\|\\(\\\\end\\s *{\\)")
924 (looking-at "\\\\end{"))
925 (tex-last-unended-begin)))
926
927 (defun tex-goto-last-unclosed-latex-block ()
928 "Move point to the last unclosed \\begin{...}.
929 Mark is left at original location."
930 (interactive)
931 (let ((spot))
932 (save-excursion
933 (condition-case nil
934 (tex-last-unended-begin)
935 (error (error "Couldn't find unended \\begin")))
936 (setq spot (point)))
937 (push-mark)
938 (goto-char spot)))
939
940 (defun tex-close-latex-block ()
941 "Creates an \\end{...} to match the last unclosed \\begin{...}."
942 (interactive "*")
943 (let ((new-line-needed (bolp))
944 text indentation)
945 (save-excursion
946 (condition-case nil
947 (tex-last-unended-begin)
948 (error (error "Couldn't find unended \\begin")))
949 (setq indentation (current-column))
950 (re-search-forward "\\\\begin\\(\\s *{[^}\n]*}\\)")
951 (setq text (buffer-substring (match-beginning 1) (match-end 1))))
952 (indent-to indentation)
953 (insert "\\end" text)
954 (if new-line-needed (insert ?\n))))
955 \f
956 (defun tex-compilation-parse-errors ()
957 "Parse the current buffer as error messages.
958 This makes a list of error descriptors, compilation-error-list.
959 For each source-file, line-number pair in the buffer,
960 the source file is read in, and the text location is saved in
961 compilation-error-list. The function `next-error', assigned to
962 \\[next-error], takes the next error off the list and visits its location.
963
964 This function works on TeX compilations only. It is necessary for
965 that purpose, since TeX does not put file names on the same line as
966 line numbers for the errors."
967 (setq compilation-error-list nil)
968 (message "Parsing error messages...")
969 (modify-syntax-entry ?\{ "_")
970 (modify-syntax-entry ?\} "_")
971 (modify-syntax-entry ?\[ "_")
972 (modify-syntax-entry ?\] "_")
973 (let (text-buffer
974 last-filename last-linenum)
975 ;; Don't reparse messages already seen at last parse.
976 (goto-char compilation-parsing-end)
977 ;; Don't parse the first two lines as error messages.
978 ;; This matters for grep.
979 (if (bobp)
980 (forward-line 2))
981 (while (re-search-forward "^l\.[0-9]+ " nil t)
982 (let (linenum filename
983 error-marker text-marker)
984 ;; Extract file name and line number from error message.
985 ;; Line number is 2 away from beginning of line: "l.23"
986 (beginning-of-line)
987 (goto-char (+ (point) 2))
988 (setq linenum (read (current-buffer)))
989 ;; The file is the one that was opened last and is still open.
990 ;; We need to find the last open parenthesis.
991 (insert ?\))
992 (backward-sexp)
993 (forward-char)
994 (setq filename (current-word))
995 ;; Locate the erring file and line.
996 (if (and (equal filename last-filename)
997 (= linenum last-linenum))
998 nil
999 (skip-chars-backward "^(")
1000 (backward-char)
1001 (forward-sexp)
1002 (backward-delete-char 1)
1003 (setq error-marker (point-marker))
1004 ;; text-buffer gets the buffer containing this error's file.
1005 (if (not (equal filename last-filename))
1006 (setq text-buffer
1007 (and (file-exists-p (setq last-filename filename))
1008 (find-file-noselect filename))
1009 last-linenum 0))
1010 (if text-buffer
1011 ;; Go to that buffer and find the erring line.
1012 (save-excursion
1013 (set-buffer text-buffer)
1014 (if (zerop last-linenum)
1015 (progn
1016 (goto-char 1)
1017 (setq last-linenum 1)))
1018 (forward-line (- linenum last-linenum))
1019 (setq last-linenum linenum)
1020 (setq text-marker (point-marker))
1021 (setq compilation-error-list
1022 (cons (list error-marker text-marker)
1023 compilation-error-list)))))
1024 (forward-line 1)))
1025 (setq compilation-parsing-end (point-max)))
1026 (message "Parsing error messages...done")
1027 (setq compilation-error-list (nreverse compilation-error-list)))
1028 \f
1029 ;;; Invoking TeX in an inferior shell.
1030
1031 ;;; Why use a shell instead of running TeX directly? Because if TeX
1032 ;;; gets stuck, the user can switch to the shell window and type at it.
1033
1034 ;;; The utility functions:
1035
1036 ;;;###autoload
1037 (defun tex-start-shell ()
1038 (save-excursion
1039 (set-buffer
1040 (make-comint
1041 "tex-shell"
1042 (or tex-shell-file-name (getenv "ESHELL") (getenv "SHELL") "/bin/sh")
1043 nil))
1044 (let ((proc (get-process "tex-shell")))
1045 (set-process-sentinel proc 'tex-shell-sentinel)
1046 (process-kill-without-query proc)
1047 (setq comint-prompt-regexp shell-prompt-pattern)
1048 (setq tex-shell-map (nconc (make-sparse-keymap) shell-mode-map))
1049 (tex-define-common-keys tex-shell-map)
1050 (use-local-map tex-shell-map)
1051 (run-hooks 'tex-shell-hook)
1052 (while (zerop (buffer-size))
1053 (sleep-for 1)))))
1054
1055 (defun tex-display-shell ()
1056 "Make the TeX shell buffer visible in a window."
1057 (display-buffer (process-buffer (get-process "tex-shell")))
1058 (tex-recenter-output-buffer nil))
1059
1060 (defun tex-shell-sentinel (proc msg)
1061 (cond ((null (buffer-name (process-buffer proc)))
1062 ;; buffer killed
1063 (set-process-buffer proc nil)
1064 (tex-delete-last-temp-files))
1065 ((memq (process-status proc) '(signal exit))
1066 (tex-delete-last-temp-files))))
1067
1068 (defun tex-set-buffer-directory (buffer directory)
1069 "Set BUFFER's default directory to be DIRECTORY."
1070 (setq directory (file-name-as-directory (expand-file-name directory)))
1071 (if (not (file-directory-p directory))
1072 (error "%s is not a directory" directory)
1073 (save-excursion
1074 (set-buffer buffer)
1075 (setq default-directory directory))))
1076
1077 (defvar tex-send-command-modified-tick 0)
1078 (make-variable-buffer-local 'tex-send-command-modified-tick)
1079
1080 (defun tex-send-command (command &optional file background)
1081 "Send COMMAND to TeX shell process, substituting optional FILE for *.
1082 Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1083 FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1084 substitution will be made in COMMAND. COMMAND can be any expression that
1085 evaluates to a command string."
1086 (save-excursion
1087 (let* ((cmd (eval command))
1088 (proc (or (get-process "tex-shell") (error "No TeX subprocess")))
1089 (buf (process-buffer proc))
1090 (star (string-match "\\*" cmd))
1091 (string
1092 (concat
1093 (if file
1094 (if star (concat (substring cmd 0 star)
1095 file (substring cmd (1+ star)))
1096 (concat cmd " " file))
1097 cmd)
1098 (if background "&" ""))))
1099 ;; Switch to buffer before checking for subproc output in it.
1100 (set-buffer buf)
1101 ;; If text is unchanged since previous tex-send-command,
1102 ;; we haven't got any output. So wait for output now.
1103 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
1104 (accept-process-output proc))
1105 (goto-char (process-mark proc))
1106 (insert string)
1107 (comint-send-input)
1108 (setq tex-send-command-modified-tick (buffer-modified-tick buf)))))
1109
1110 (defun tex-delete-last-temp-files (&optional not-all)
1111 "Delete any junk files from last temp file.
1112 If NOT-ALL is non-nil, save the `.dvi' file."
1113 (if tex-last-temp-file
1114 (let* ((dir (file-name-directory tex-last-temp-file))
1115 (list (and (file-directory-p dir)
1116 (file-name-all-completions
1117 (file-name-nondirectory tex-last-temp-file) dir))))
1118 (while list
1119 (if not-all
1120 (and
1121 ;; If arg is non-nil, don't delete the .dvi file.
1122 (not (string-match "\\.dvi$" (car list)))
1123 (delete-file (concat dir (car list))))
1124 (delete-file (concat dir (car list))))
1125 (setq list (cdr list))))))
1126
1127 (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
1128
1129 ;;; The commands:
1130
1131 (defun tex-region (beg end)
1132 "Run TeX on the current region, via a temporary file.
1133 The file's name comes from the variable `tex-zap-file' and the
1134 variable `tex-directory' says where to put it.
1135
1136 If the buffer has a header, the header is given to TeX before the
1137 region itself. The buffer's header is all lines between the strings
1138 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
1139 The header must start in the first 100 lines of the buffer.
1140
1141 The value of `tex-trailer' is given to TeX as input after the region.
1142
1143 The value of `tex-command' specifies the command to use to run TeX."
1144 (interactive "r")
1145 (if (tex-shell-running)
1146 (tex-kill-job)
1147 (tex-start-shell))
1148 (or tex-zap-file
1149 (setq tex-zap-file (tex-generate-zap-file-name)))
1150 ;; Temp file will be written and TeX will be run in zap-directory.
1151 ;; If the TEXINPUTS file has relative directories or if the region has
1152 ;; \input of files, this must be the same directory as the file for
1153 ;; TeX to access the correct inputs. That's why it's safest if
1154 ;; tex-directory is ".".
1155 (let* ((zap-directory
1156 (file-name-as-directory (expand-file-name tex-directory)))
1157 (tex-out-file (concat zap-directory tex-zap-file ".tex")))
1158 ;; Don't delete temp files if we do the same buffer twice in a row.
1159 (or (eq (current-buffer) tex-last-buffer-texed)
1160 (tex-delete-last-temp-files t))
1161 ;; Write the new temp file.
1162 (save-excursion
1163 (save-restriction
1164 (widen)
1165 (goto-char (point-min))
1166 (forward-line 100)
1167 (let ((search-end (point))
1168 (default-directory zap-directory)
1169 (already-output 0))
1170 (goto-char (point-min))
1171
1172 ;; Maybe copy first line, such as `\input texinfo', to temp file.
1173 (and tex-first-line-header-regexp
1174 (looking-at tex-first-line-header-regexp)
1175 (write-region (point)
1176 (progn (forward-line 1)
1177 (setq already-output (point)))
1178 tex-out-file nil nil))
1179
1180 ;; Write out the header, if there is one,
1181 ;; and any of the specified region which extends before it.
1182 ;; But don't repeat anything already written.
1183 (if (re-search-forward tex-start-of-header search-end t)
1184 (let (hbeg)
1185 (beginning-of-line)
1186 (setq hbeg (point)) ;mark beginning of header
1187 (if (re-search-forward tex-end-of-header nil t)
1188 (let (hend)
1189 (forward-line 1)
1190 (setq hend (point)) ;mark end of header
1191 (write-region (max (min hbeg beg) already-output)
1192 hend
1193 tex-out-file
1194 (not (zerop already-output)) nil)
1195 (setq already-output hend)))))
1196
1197 ;; Write out the specified region
1198 ;; (but don't repeat anything already written).
1199 (write-region (max beg already-output) end
1200 tex-out-file
1201 (not (zerop already-output)) nil))
1202 ;; Write the trailer, if any.
1203 ;; Precede it with a newline to make sure it
1204 ;; is not hidden in a comment.
1205 (if tex-trailer
1206 (write-region (concat "\n" tex-trailer) nil
1207 tex-out-file t nil))))
1208 ;; Record the file name to be deleted afterward.
1209 (setq tex-last-temp-file tex-out-file)
1210 (tex-send-command tex-shell-cd-command zap-directory)
1211 (tex-send-command tex-command tex-out-file)
1212 (tex-display-shell)
1213 (setq tex-print-file tex-out-file)
1214 (setq tex-last-buffer-texed (current-buffer))))
1215
1216 (defun tex-buffer ()
1217 "Run TeX on current buffer. See \\[tex-region] for more information.
1218 Does not save the buffer, so it's useful for trying experimental versions.
1219 See \\[tex-file] for an alternative."
1220 (interactive)
1221 (tex-region (point-min) (point-max)))
1222
1223 (defun tex-file ()
1224 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
1225 This function is more useful than \\[tex-buffer] when you need the
1226 `.aux' file of LaTeX to have the correct name."
1227 (interactive)
1228 (let ((source-file
1229 (or tex-main-file
1230 (if (buffer-file-name)
1231 (file-name-nondirectory (buffer-file-name))
1232 (error "Buffer does not seem to be associated with any file"))))
1233 (file-dir (file-name-directory (buffer-file-name))))
1234 (if tex-offer-save
1235 (save-some-buffers))
1236 (if (tex-shell-running)
1237 (tex-kill-job)
1238 (tex-start-shell))
1239 (tex-send-command tex-shell-cd-command file-dir)
1240 (tex-send-command tex-command source-file)
1241 (tex-display-shell)
1242 (setq tex-last-buffer-texed (current-buffer))
1243 (setq tex-print-file source-file)))
1244
1245 (defun tex-generate-zap-file-name ()
1246 "Generate a unique name suitable for use as a file name."
1247 ;; Include the shell process number and host name
1248 ;; in case there are multiple shells (for same or different user).
1249 (format "#tz%d%s"
1250 (process-id (get-buffer-process "*tex-shell*"))
1251 (tex-strip-dots (system-name))))
1252
1253 (defun tex-strip-dots (s)
1254 (setq s (copy-sequence s))
1255 (while (string-match "\\." s)
1256 (aset s (match-beginning 0) ?-))
1257 s)
1258
1259 ;; This will perhaps be useful for modifying TEXINPUTS.
1260 ;; Expand each file name, separated by colons, in the string S.
1261 (defun tex-expand-files (s)
1262 (let (elts (start 0))
1263 (while (string-match ":" s start)
1264 (setq elts (cons (substring s start (match-beginning 0)) elts))
1265 (setq start (match-end 0)))
1266 (or (= start 0)
1267 (setq elts (cons (substring s start) elts)))
1268 (mapconcat 'expand-file-name (nreverse elts) ":")))
1269
1270 (defun tex-shell-running ()
1271 (and (get-process "tex-shell")
1272 (eq (process-status (get-process "tex-shell")) 'run)))
1273
1274 (defun tex-kill-job ()
1275 "Kill the currently running TeX job."
1276 (interactive)
1277 (quit-process (get-process "tex-shell") t))
1278
1279 (defun tex-recenter-output-buffer (linenum)
1280 "Redisplay buffer of TeX job output so that most recent output can be seen.
1281 The last line of the buffer is displayed on
1282 line LINE of the window, or centered if LINE is nil."
1283 (interactive "P")
1284 (let ((tex-shell (get-buffer "*tex-shell*"))
1285 (old-buffer (current-buffer))
1286 (window))
1287 (if (null tex-shell)
1288 (message "No TeX output buffer")
1289 (setq window (display-buffer tex-shell))
1290 (save-selected-window
1291 (select-window window)
1292 (bury-buffer tex-shell)
1293 (goto-char (point-max))
1294 (recenter (if linenum
1295 (prefix-numeric-value linenum)
1296 (/ (window-height) 2)))))))
1297
1298 (defun tex-print (&optional alt)
1299 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1300 Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
1301 is provided, use the alternative command, `tex-alt-dvi-print-command'."
1302 (interactive "P")
1303 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
1304 test-name)
1305 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
1306 (buffer-file-name)
1307 ;; Check that this buffer's printed file is up to date.
1308 (file-newer-than-file-p
1309 (setq test-name (tex-append (buffer-file-name) ".dvi"))
1310 (buffer-file-name)))
1311 (setq print-file-name-dvi test-name))
1312 (if (not (file-exists-p print-file-name-dvi))
1313 (error "No appropriate `.dvi' file could be found")
1314 (tex-send-command
1315 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
1316 print-file-name-dvi t))))
1317
1318 (defun tex-alt-print ()
1319 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1320 Runs the shell command defined by `tex-alt-dvi-print-command'."
1321 (interactive)
1322 (tex-print t))
1323
1324 (defun tex-view ()
1325 "Preview the last `.dvi' file made by running TeX under Emacs.
1326 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
1327 The variable `tex-dvi-view-command' specifies the shell command for preview.
1328 You must set that variable yourself before using this command,
1329 because there is no standard value that would generally work."
1330 (interactive)
1331 (or tex-dvi-view-command
1332 (error "You must set `tex-dvi-view-command'"))
1333 (let ((tex-dvi-print-command tex-dvi-view-command))
1334 (tex-print)))
1335
1336 (defun tex-append (file-name suffix)
1337 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
1338 Pascal-based TeX scans for the first period, C TeX uses the last.
1339 No period is retained immediately before SUFFIX,
1340 so normally SUFFIX starts with one."
1341 (if (stringp file-name)
1342 (let ((file (file-name-nondirectory file-name))
1343 trial-name)
1344 ;; Try splitting on last period.
1345 ;; The first-period split can get fooled when two files
1346 ;; named a.tex and a.b.tex are both tex'd;
1347 ;; the last-period split must be right if it matches at all.
1348 (setq trial-name
1349 (concat (file-name-directory file-name)
1350 (substring file 0
1351 (string-match "\\.[^.]*$" file))
1352 suffix))
1353 (if (or (file-exists-p trial-name)
1354 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
1355 trial-name
1356 ;; Not found, so split on first period.
1357 (concat (file-name-directory file-name)
1358 (substring file 0
1359 (string-match "\\." file))
1360 suffix)))
1361 " "))
1362
1363 (defun tex-show-print-queue ()
1364 "Show the print queue that \\[tex-print] put your job on.
1365 Runs the shell command defined by `tex-show-queue-command'."
1366 (interactive)
1367 (if (tex-shell-running)
1368 (tex-kill-job)
1369 (tex-start-shell))
1370 (tex-send-command tex-show-queue-command)
1371 (tex-display-shell))
1372
1373 (defun tex-bibtex-file ()
1374 "Run BibTeX on the current buffer's file."
1375 (interactive)
1376 (if (tex-shell-running)
1377 (tex-kill-job)
1378 (tex-start-shell))
1379 (let ((tex-out-file
1380 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
1381 (file-dir (file-name-directory (buffer-file-name))))
1382 (tex-send-command tex-shell-cd-command file-dir)
1383 (tex-send-command tex-bibtex-command tex-out-file))
1384 (tex-display-shell))
1385
1386 (run-hooks 'tex-mode-load-hook)
1387
1388 (provide 'tex-mode)
1389
1390 ;;; tex-mode.el ends here
1391