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