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