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