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