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