Initial Commit
[packages] / xemacs-packages / texinfo / tex-mode.el
1 ;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands.
2
3 ;; Copyright (C) 1985-1992 Free Software Foundation, Inc.
4 ;; Contributions over the years by William F. Schelter, Dick King,
5 ;; Stephen Gildea, Michael Prange, and Edward M. Reingold.
6
7 ;; Latest revision (1992) by Edward M. Reingold <reingold@cs.uiuc.edu>.
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the 
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 (require 'comint)
27
28 (defvar tex-shell-file-name nil
29   "*If non-nil, is file name to use for the subshell in which TeX is run.")
30
31 (defvar tex-directory "."
32   "*Directory in which temporary files are left.
33 You can make this /tmp if your TEXINPUTS has no relative directories in it
34 and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
35 \\input commands with relative directories.")
36
37 (defvar tex-offer-save t
38   "*If non-nil, ask about saving modified buffers before \\[tex-file] is run.")
39
40 (defvar tex-run-command "tex"
41   "*Command used to run TeX subjob.
42 If this string contains an asterisk (*), it will be replaced by the
43 filename; if not, the name of the file, preceded by blank, will be added to
44 this string.")
45
46 (defvar latex-run-command "latex"
47   "*Command used to run LaTeX subjob.
48 If this string contains an asterisk (*), it will be replaced by the
49 filename; if not, the name of the file, preceded by blank, will be added to
50 this string.")
51
52 (defvar standard-latex-block-names
53       '("abstract"         "array"            "center"       "description"
54         "displaymath"      "document"         "enumerate"    "eqnarray"
55         "eqnarray*"        "equation"         "figure"       "figure*"
56         "flushleft"        "flushright"       "itemize"      "letter"
57         "list"             "minipage"         "picture"      "quotation"
58         "quote"            "slide"            "sloppypar"     "tabbing"
59         "table"            "table*"           "tabular"       "tabular*"
60         "thebibliography"  "theindex*"        "titlepage"     "trivlist"
61         "verbatim"         "verbatim*"        "verse")
62   "Standard LaTeX block names.")
63
64 (defvar latex-block-names nil
65   "*User defined LaTeX block names.
66 Combined with `standard-latex-block-names' for minibuffer completion.")
67
68 (defvar tex-latex-document-regex "documentstyle\\|documentclass"
69   "matches the first command of a LaTeX document")
70
71 (defvar slitex-run-command "slitex"
72   "*Command used to run SliTeX subjob.
73 If this string contains an asterisk (*), it will be replaced by the
74 filename; if not, the name of the file, preceded by blank, will be added to
75 this string.")
76
77 (defvar tex-slitex-document-regex "documentstyle{slides}"
78   "Matches the first command of a slitex document")
79   
80 (defvar tex-bibtex-command "bibtex"
81   "*Command used by `tex-bibtex-file' to gather bibliographic data.
82 If this string contains an asterisk (*), it will be replaced by the
83 filename; if not, the name of the file, preceded by blank, will be added to
84 this string.")
85
86 (defvar tex-dvi-print-command "lpr -d"
87   "*Command used by \\[tex-print] to print a .dvi file.
88 If this string contains an asterisk (*), it will be replaced by the
89 filename; if not, the name of the file, preceded by blank, will be added to
90 this string.")
91
92 (defvar tex-alt-dvi-print-command "lpr -d"
93   "*Command used by \\[tex-print] with a prefix arg to print a .dvi file.
94 If this string contains an asterisk (*), it will be replaced by the
95 filename; if not, the name of the file, preceded by blank, will be added to
96 this string.
97
98 If two printers are not enough of a choice, you can define the value
99 of tex-alt-dvi-print-command to be an expression that asks what you want;
100 for example,
101
102     (setq tex-alt-dvi-print-command
103          '(format \"lpr -P%s\" (read-string \"Use printer: \")))
104
105 would tell \\[tex-print] with a prefix argument to ask you which printer to
106 use.")
107
108 (defvar tex-dvi-view-command nil
109   "*Command used by \\[tex-view] to display a .dvi file.
110 If this string contains an asterisk (*), it will be replaced by the
111 filename; if not, the name of the file, preceded by blank, will be added to
112 this string.
113
114 This can be set conditionally so that the previewer used is suitable for the
115 window system being used.  For example,
116
117     (setq tex-dvi-view-command
118           (if (eq window-system 'x) \"xdvi\" \"dvi2tty * | cat -s\"))
119
120 would tell \\[tex-view] use xdvi under X windows and to use dvi2tty
121 otherwise.")
122
123 (defvar tex-show-queue-command "lpq"
124   "*Command used by \\[tex-show-print-queue] to show the print queue.
125 Should show the queue(s) that \\[tex-print] puts jobs on.")
126
127 (defvar tex-default-mode 'plain-tex-mode
128   "*Mode to enter for a new file that might be either TeX or LaTeX.
129 This variable is used when it can't be determined whether the file
130 is plain TeX or LaTeX or what because the file contains no commands.
131 Normally set to either 'plain-tex-mode or 'latex-mode.")
132
133 (defvar tex-open-quote "``"
134   "*String inserted by typing \\[tex-insert-quote] to open a quotation.")
135
136 (defvar tex-close-quote "''"
137   "*String inserted by typing \\[tex-insert-quote] to close a quotation.")
138
139 (defvar tex-last-temp-file nil
140   "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
141 Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
142 tex-shell goes away.")
143
144 (defvar tex-command nil
145   "Command to run TeX.
146 The name of the file, preceded by a blank, will be added to this string.")
147
148 (defvar tex-trailer nil
149   "String appended after the end of a region sent to TeX by \\[tex-region].")
150
151 (defvar tex-start-of-header nil
152   "String used by \\[tex-region] to delimit the start of the file's header.")
153
154 (defvar tex-end-of-header nil
155   "String used by \\[tex-region] to delimit the end of the file's header.")
156
157 (defvar tex-shell-cd-command "cd"
158   "Command to give to shell running TeX to change directory.
159 The value of tex-directory will be appended to this, separated by a space.")
160
161 (defvar tex-zap-file nil
162   "Temporary file name used for text being sent as input to TeX.
163 Should be a simple file name with no extension or directory specification.")
164
165 (defvar tex-last-buffer-texed nil
166   "Buffer which was last TeXed.")
167
168 (defvar tex-print-file nil
169   "File name that \\[tex-print] prints.
170 Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
171
172 (defvar tex-mode-syntax-table nil
173   "Syntax table used while in TeX mode.")
174
175 (defvar tex-mode-hook nil
176   "Hook to run in TeX modes (plain-tex-mode, latex-mode, slitex-mode).")
177
178 (defvar tex-shell-hook nil
179   "Hook to run in TeX modes (plain-tex-mode, latex-mode, slitex-mode),
180 when the special subshell is initiated.")
181
182 (defvar plain-tex-mode-hook nil
183   "Hook to run when entering plain-tex-mode.")
184
185 (defvar latex-mode-hook nil
186   "Hook to run when entering latex-mode.")
187
188 (defvar slitex-mode-hook nil
189   "Hook to run when entering slitex-mode.")
190
191 (defun tex-define-common-keys (keymap)
192   "Define the keys that we want defined both in TeX mode and in the tex-shell."
193   (define-key keymap "\C-c\C-k" 'tex-kill-job)
194   (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
195   (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
196   (define-key keymap "\C-c\C-p" 'tex-print)
197   (define-key keymap "\C-c\C-v" 'tex-view)
198   )
199
200 (defvar tex-mode-map nil "Keymap for TeX mode.")
201
202 (if tex-mode-map 
203     nil
204   (setq tex-mode-map (make-sparse-keymap))
205   (tex-define-common-keys tex-mode-map)
206   (define-key tex-mode-map "\"" 'tex-insert-quote)
207   (define-key tex-mode-map "\n" 'tex-terminate-paragraph)
208   (define-key tex-mode-map "\C-c}" 'up-list)
209   (define-key tex-mode-map "\C-c{" 'tex-insert-braces)
210   (define-key tex-mode-map "\C-c\C-r" 'tex-region)
211   (define-key tex-mode-map "\C-c\C-b" 'tex-buffer)
212   (define-key tex-mode-map "\C-c\C-f" 'tex-file)
213   (define-key tex-mode-map "\C-c\C-i" 'tex-bibtex-file)
214   (define-key tex-mode-map "\C-c\C-o" 'tex-latex-block)
215   (define-key tex-mode-map "\C-c\C-e" 'tex-close-latex-block))
216
217 (defvar tex-shell-map nil
218   "Keymap for the tex-shell.  A comint-mode-map with a few additions.")
219
220 ;;; This would be a lot simpler if we just used a regexp search,
221 ;;; but then it would be too slow.
222 ;;;###autoload
223 (defun tex-mode ()
224   "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
225 Tries to determine (by looking at the beginning of the file) whether
226 this file is for plain TeX, LaTeX, or SliTeX and calls plain-tex-mode,
227 latex-mode, or slitex-mode, respectively.  If it cannot be determined,
228 such as if there are no commands in the file, the value of tex-default-mode
229 is used."
230   (interactive)
231   (let (mode slash comment)
232     (save-excursion
233       (goto-char (point-min))
234       (while (and (setq slash (search-forward "\\" nil t))
235                   (setq comment (let ((search-end (point)))
236                                   (save-excursion
237                                     (beginning-of-line)
238                                     (search-forward "%" search-end t))))))
239       (if (and slash (not comment))
240           (setq mode (if (looking-at tex-latex-document-regex)
241                          (if (looking-at tex-slitex-document-regex)
242                              'slitex-mode
243                            'latex-mode)
244                        'plain-tex-mode))))
245     (if mode (funcall mode)
246       (funcall tex-default-mode))))
247 ;;;###autoload
248 (fset 'TeX-mode 'tex-mode)
249 ;;;###autoload
250 (fset 'LaTeX-mode 'latex-mode)
251
252 ;;;###autoload
253 (defun plain-tex-mode ()
254   "Major mode for editing files of input for plain TeX.
255 Makes $ and } display the characters they match.
256 Makes \" insert `` when it seems to be the beginning of a quotation,
257 and '' when it appears to be the end; it inserts \" only after a \\.
258
259 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
260 copied from the top of the file (containing macro definitions, etc.),
261 running TeX under a special subshell.  \\[tex-buffer] does the whole buffer.
262 \\[tex-file] saves the buffer and then processes the file.
263 \\[tex-print] prints the .dvi file made by any of these.
264 \\[tex-view] previews the .dvi file made by any of these.
265 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
266
267 Use \\[validate-tex-buffer] to check buffer for paragraphs containing
268 mismatched $'s or braces.
269
270 Special commands:
271 \\{tex-mode-map}
272
273 Mode variables:
274 tex-run-command
275         Command string used by \\[tex-region] or \\[tex-buffer].
276 tex-directory
277         Directory in which to create temporary files for TeX jobs
278         run by \\[tex-region] or \\[tex-buffer].
279 tex-dvi-print-command
280         Command string used by \\[tex-print] to print a .dvi file.
281 tex-alt-dvi-print-command
282         Alternative command string used by \\[tex-print] (when given a prefix
283         argument) to print a .dvi file.
284 tex-dvi-view-command
285         Command string used by \\[tex-view] to preview a .dvi file.
286 tex-show-queue-command
287         Command string used by \\[tex-show-print-queue] to show the print
288         queue that \\[tex-print] put your job on.
289
290 Entering Plain-tex mode calls the value of text-mode-hook, then the value of
291 tex-mode-hook, and then the value of plain-tex-mode-hook.  When the special
292 subshell is initiated, the value of tex-shell-hook is called."
293   (interactive)
294   (tex-common-initialization)
295   (setq mode-name "TeX")
296   (setq major-mode 'plain-tex-mode)
297   (setq tex-command tex-run-command)
298   (setq tex-start-of-header "%**start of header")
299   (setq tex-end-of-header "%**end of header")
300   (setq tex-trailer "\\bye\n")
301   (run-hooks 'text-mode-hook 'tex-mode-hook 'plain-tex-mode-hook))
302 ;;;###autoload
303 (fset 'plain-TeX-mode 'plain-tex-mode)
304
305 ;;;###autoload
306 (defun latex-mode ()
307   "Major mode for editing files of input for LaTeX.
308 Makes $ and } display the characters they match.
309 Makes \" insert `` when it seems to be the beginning of a quotation,
310 and '' when it appears to be the end; it inserts \" only after a \\.
311
312 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
313 copied from the top of the file (containing \\documentstyle, etc.),
314 running LaTeX under a special subshell.  \\[tex-buffer] does the whole buffer.
315 \\[tex-file] saves the buffer and then processes the file.
316 \\[tex-print] prints the .dvi file made by any of these.
317 \\[tex-view] previews the .dvi file made by any of these.
318 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
319
320 Use \\[validate-tex-buffer] to check buffer for paragraphs containing
321 mismatched $'s or braces.
322
323 Special commands:
324 \\{tex-mode-map}
325
326 Mode variables:
327 latex-run-command
328         Command string used by \\[tex-region] or \\[tex-buffer].
329 tex-directory
330         Directory in which to create temporary files for LaTeX jobs
331         run by \\[tex-region] or \\[tex-buffer].
332 tex-dvi-print-command
333         Command string used by \\[tex-print] to print a .dvi file.
334 tex-alt-dvi-print-command
335         Alternative command string used by \\[tex-print] (when given a prefix
336         argument) to print a .dvi file.
337 tex-dvi-view-command
338         Command string used by \\[tex-view] to preview a .dvi file.
339 tex-show-queue-command
340         Command string used by \\[tex-show-print-queue] to show the print
341         queue that \\[tex-print] put your job on.
342
343 Entering Latex mode calls the value of text-mode-hook, then the value of
344 tex-mode-hook, and then the value of latex-mode-hook.  When the special
345 subshell is initiated, the value of tex-shell-hook is called."
346   (interactive)
347   (tex-common-initialization)
348   (setq mode-name "LaTeX")
349   (setq major-mode 'latex-mode)
350   (setq tex-command latex-run-command)
351   (setq tex-start-of-header "\\documentstyle")
352   (setq tex-end-of-header "\\begin{document}")
353   (setq tex-trailer "\\end{document}\n")
354   (run-hooks 'text-mode-hook 'tex-mode-hook 'latex-mode-hook))
355
356 (defun slitex-mode ()
357   "Major mode for editing files of input for SliTeX.
358 Makes $ and } display the characters they match.
359 Makes \" insert `` when it seems to be the beginning of a quotation,
360 and '' when it appears to be the end; it inserts \" only after a \\.
361
362 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
363 copied from the top of the file (containing \\documentstyle, etc.),
364 running SliTeX under a special subshell.  \\[tex-buffer] does the whole buffer.
365 \\[tex-file] saves the buffer and then processes the file.
366 \\[tex-print] prints the .dvi file made by any of these.
367 \\[tex-view] previews the .dvi file made by any of these.
368 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
369
370 Use \\[validate-tex-buffer] to check buffer for paragraphs containing
371 mismatched $'s or braces.
372
373 Special commands:
374 \\{tex-mode-map}
375
376 Mode variables:
377 slitex-run-command
378         Command string used by \\[tex-region] or \\[tex-buffer].
379 tex-directory
380         Directory in which to create temporary files for SliTeX jobs
381         run by \\[tex-region] or \\[tex-buffer].
382 tex-dvi-print-command
383         Command string used by \\[tex-print] to print a .dvi file.
384 tex-alt-dvi-print-command
385         Alternative command string used by \\[tex-print] (when given a prefix
386         argument) to print a .dvi file.
387 tex-dvi-view-command
388         Command string used by \\[tex-view] to preview a .dvi file.
389 tex-show-queue-command
390         Command string used by \\[tex-show-print-queue] to show the print
391         queue that \\[tex-print] put your job on.
392
393 Entering SliTeX mode calls the value of text-mode-hook, then the value of
394 tex-mode-hook, then the value of latex-mode-hook, and then the value of
395 slitex-mode-hook.  When the special subshell is initiated, the value of
396 tex-shell-hook is called."
397   (interactive)
398   (tex-common-initialization)
399   (setq mode-name "SliTeX")
400   (setq major-mode 'slitex-mode)
401   (setq tex-command slitex-run-command)
402   (setq tex-start-of-header "\\documentstyle{slides}")
403   (setq tex-end-of-header "\\begin{document}")
404   (setq tex-trailer "\\end{document}\n")
405   (run-hooks
406    'text-mode-hook 'tex-mode-hook 'latex-mode-hook 'slitex-mode-hook))
407
408 (defun tex-common-initialization ()
409   (kill-all-local-variables)
410   (use-local-map tex-mode-map)
411   (setq local-abbrev-table text-mode-abbrev-table)
412   (if (null tex-mode-syntax-table)
413       (let ((char 0))
414         (setq tex-mode-syntax-table (make-syntax-table))
415         (set-syntax-table tex-mode-syntax-table)
416         (while (< char ? )
417           (modify-syntax-entry char ".")
418           (setq char (1+ char)))
419         (modify-syntax-entry ?\C-@ "w")
420         (modify-syntax-entry ?\t " ")
421         (modify-syntax-entry ?\n ">")
422         (modify-syntax-entry ?\f ">")
423         (modify-syntax-entry ?$ "$$")
424         (modify-syntax-entry ?% "<")
425         (modify-syntax-entry ?\\ "\\")
426         (modify-syntax-entry ?\" ".")
427         (modify-syntax-entry ?& ".")
428         (modify-syntax-entry ?_ ".")
429         (modify-syntax-entry ?@ "_")
430         (modify-syntax-entry ?~ " ")
431         (modify-syntax-entry ?' "w"))
432     (set-syntax-table tex-mode-syntax-table))
433   (make-local-variable 'paragraph-start)
434   (setq paragraph-start "^[ \t]*$\\|^[\f\\\\%]")
435   (make-local-variable 'paragraph-separate)
436   (setq paragraph-separate paragraph-start)
437   (make-local-variable 'comment-start)
438   (setq comment-start "%")
439   (make-local-variable 'comment-start-skip)
440   (setq comment-start-skip "\\(\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
441   (make-local-variable 'comment-indent-function)
442   (setq comment-indent-function 'tex-comment-indent)
443   (make-local-variable 'compare-windows-whitespace)
444   (setq compare-windows-whitespace 'tex-categorize-whitespace)
445   (make-local-variable 'tex-command)
446   (make-local-variable 'tex-start-of-header)
447   (make-local-variable 'tex-end-of-header)
448   (make-local-variable 'tex-trailer))
449
450 (defun tex-comment-indent ()
451   (if (looking-at "%%%")
452       (current-column)
453     (skip-chars-backward " \t")
454     (max (if (bolp) 0 (1+ (current-column)))
455          comment-column)))
456
457 (defun tex-categorize-whitespace (backward-limit)
458   ;; compare-windows-whitespace is set to this.
459   ;; This is basically a finite-state machine.
460   ;; Returns a symbol telling how TeX would treat
461   ;; the whitespace we are looking at: null, space, or par.
462   (let ((category 'null)
463         (not-finished t))
464     (skip-chars-backward " \t\n\f" backward-limit)
465     (while not-finished
466       (cond ((looking-at "[ \t]+")
467              (goto-char (match-end 0))
468              (if (eql category 'null)
469                  (setq category 'space)))
470             ((looking-at "\n")
471              (cond ((eql category 'newline)
472                     (setq category 'par)
473                     (setq not-finished nil))
474                    (t
475                     (setq category 'newline) ;a strictly internal state
476                     (goto-char (match-end 0)))))
477             ((looking-at "\f+")
478              (setq category 'par)
479              (setq not-finished nil))
480             (t
481              (setq not-finished nil))))
482     (skip-chars-forward " \t\n\f")
483     (if (eql category 'newline)
484         'space                          ;TeX doesn't distinguish
485       category)))
486
487 (defun tex-insert-quote (arg)
488   "Insert the appropriate quote marks for TeX.
489 Inserts the value of tex-open-quote (normally ``) or tex-close-quote
490 (normally '') depending on the context.  With prefix argument, always
491 inserts \" characters."
492   (interactive "*P")
493   (if arg
494       (self-insert-command (prefix-numeric-value arg))
495     (insert
496      (cond ((or (bobp)
497                 (save-excursion
498                   (forward-char -1)
499                   (looking-at "\\s(\\|\\s \\|\\s>")))
500             tex-open-quote)
501            ((= (preceding-char) ?\\)
502             ?\")
503            (t
504             tex-close-quote)))))
505
506 (defun validate-tex-buffer ()
507   "Check current buffer for paragraphs containing mismatched $'s.
508 As each such paragraph is found, a mark is pushed at its beginning,
509 and the location is displayed for a few seconds."
510   (interactive)
511   (let ((opoint (point)))
512     (goto-char (point-max))
513     ;; Does not use save-excursion
514     ;; because we do not want to save the mark.
515     (unwind-protect
516         (while (and (not (input-pending-p)) (not (bobp)))
517           (let ((end (point)))
518             (search-backward "\n\n" nil 'move)
519             (or (tex-validate-region (point) end)
520                 (progn
521                   (push-mark (point))
522                   (message "Mismatch found in pararaph starting here")
523                   (sit-for 4)))))
524       (goto-char opoint))))
525
526 (defun tex-validate-region (start end)
527   "Check for mismatched braces or $'s in region.
528 Returns t if no mismatches.  Returns nil and moves point to suspect
529 area if a mismatch is found."
530   (interactive "r")
531   (let ((failure-point nil) (max-possible-sexps (- end start)))
532     (save-excursion
533       (condition-case ()
534           (save-restriction
535             (narrow-to-region start end)
536             (goto-char start)
537             (while (< 0 (setq max-possible-sexps (1- max-possible-sexps)))
538               (forward-sexp 1)))
539         (error
540           (setq failure-point (point)))))
541     (if failure-point
542         (progn
543           (goto-char failure-point)
544           nil)
545       t)))
546
547 (defun tex-terminate-paragraph (inhibit-validation)
548   "Insert two newlines, breaking a paragraph for TeX.
549 Check for mismatched braces/$'s in paragraph being terminated.
550 A prefix arg inhibits the checking."
551   (interactive "*P")
552   (or inhibit-validation
553       (save-excursion
554         (tex-validate-region
555           (save-excursion
556             (search-backward "\n\n" nil 'move)
557             (point))
558           (point)))
559       (message "Paragraph being closed appears to contain a mismatch"))
560   (insert "\n\n"))
561
562 (defun tex-insert-braces ()
563   "Make a pair of braces and be poised to type inside of them."
564   (interactive "*")
565   (insert ?\{)
566   (save-excursion
567     (insert ?})))
568
569 ;;; Like tex-insert-braces, but for LaTeX.
570 (defun tex-latex-block (name)
571   "Creates a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
572 Puts point on a blank line between them."
573   (interactive
574    (prog2
575       (barf-if-buffer-read-only)
576       (list
577        (completing-read "LaTeX block name: "
578                         (mapcar 'list
579                                 (append standard-latex-block-names
580                                         latex-block-names))))))
581   (let ((col (current-column)))
582     (insert (format "\\begin{%s}\n" name))
583     (indent-to col)
584     (save-excursion
585       (insert ?\n)
586       (indent-to col)
587       (insert (format "\\end{%s}" name))
588       (if (eobp) (insert ?\n)))))
589
590 (defun tex-last-unended-begin ()
591   "Leave point at the beginning of the last \\begin{...} that is unended."
592   (while (and (re-search-backward "\\(\\\\begin\\s *{\\)\\|\\(\\\\end\\s *{\\)")
593               (looking-at "\\\\end{"))
594     (tex-last-unended-begin)))
595
596 (defun tex-close-latex-block ()
597   "Creates an \\end{...} to match the last unclosed \\begin{...}."
598   (interactive "*")
599   (let ((new-line-needed (bolp))
600         text indentation)
601     (save-excursion
602       (condition-case nil
603           (tex-last-unended-begin)
604         (error (error "Couldn't find unended \\begin")))
605       (setq indentation (current-column))
606       (re-search-forward "\\\\begin\\(\\s *{[^}\n]*}\\)")
607       (setq text (buffer-substring (match-beginning 1) (match-end 1))))
608     (indent-to indentation)
609     (insert "\\end" text)
610     (if new-line-needed (insert ?\n))))
611 \f
612 ;;; Invoking TeX in an inferior shell.
613
614 ;;; Why use a shell instead of running TeX directly?  Because if TeX
615 ;;; gets stuck, the user can switch to the shell window and type at it.
616
617 ;;; The utility functions:
618
619 (defun tex-start-shell ()
620   (save-excursion
621     (set-buffer
622      (make-comint
623       "tex-shell"
624       (or tex-shell-file-name (getenv "ESHELL") (getenv "SHELL") "/bin/sh")
625       nil "-v"))
626     (let ((proc (get-process "tex-shell")))
627       (set-process-sentinel proc 'tex-shell-sentinel)
628       (process-kill-without-query proc)
629       (setq tex-shell-map (copy-keymap comint-mode-map))
630       (tex-define-common-keys tex-shell-map)
631       (use-local-map tex-shell-map)
632       (run-hooks 'tex-shell-hook)
633       (while (zerop (buffer-size))
634           (sleep-for 1)))))
635
636 (defun tex-shell-sentinel (proc msg)
637   (cond ((null (buffer-name (process-buffer proc)))
638          ;; buffer killed
639          (set-process-buffer proc nil)
640          (tex-delete-last-temp-files))
641         ((memq (process-status proc) '(signal exit))
642          (tex-delete-last-temp-files))))
643
644 (defun tex-set-buffer-directory (buffer directory)
645   "Set BUFFER's default directory to be DIRECTORY."
646   (setq directory (file-name-as-directory (expand-file-name directory)))
647   (if (not (file-directory-p directory))
648       (error "%s is not a directory" directory)
649     (save-excursion
650       (set-buffer buffer)
651       (setq default-directory directory))))
652
653 (defun tex-send-command (command &optional file background)
654   "Send COMMAND to tex-shell, substituting optional FILE for *; in background
655 if optional BACKGROUND is t.   If COMMAND has no *, FILE will be appended,
656 preceded by a blank, to COMMAND.  If FILE is nil, no substitution will be made
657 in COMMAND.  COMMAND can be any expression that evaluates to a command string."
658   (save-excursion
659     (let* ((cmd (eval command))
660            (star (string-match "\\*" cmd)))
661       (comint-proc-query (get-process "tex-shell")
662                          (concat (substring cmd 0 star)
663                                  (if file (concat " " file) "")
664                                  (if star (substring cmd (1+ star) nil) "")
665                                  (if background "&\n" "\n"))))))
666
667 (defun tex-delete-last-temp-files ()
668   "Delete any junk files from last temp file."
669   (if tex-last-temp-file
670       (let* ((dir (file-name-directory tex-last-temp-file))
671              (list (file-name-all-completions
672                     (file-name-nondirectory tex-last-temp-file) dir)))
673         (while list
674           (delete-file (concat dir (car list)))
675           (setq list (cdr list))))))
676
677 (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
678
679 ;;; The commands:
680
681 (defun tex-region (beg end)
682   "Run TeX on the current region, via a temporary file.
683 The file's name comes from the variable `tex-zap-file' and the
684 variable `tex-directory' says where to put it.
685
686 If the buffer has a header, the header is given to TeX before the
687 region itself.  The buffer's header is all lines between the strings
688 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
689 The header must start in the first 100 lines of the buffer.
690
691 The value of `tex-trailer' is given to TeX as input after the region.
692
693 The value of `tex-command' specifies the command to use to run TeX."
694   (interactive "r")
695   (if (tex-shell-running)
696       (tex-kill-job)
697     (tex-start-shell))
698   (or tex-zap-file
699       (setq tex-zap-file (tex-generate-zap-file-name)))
700   (let* ((temp-buffer (get-buffer-create " TeX-Output-Buffer"))
701          ; Temp file will be written and TeX will be run in zap-directory.
702          ; If the TEXINPUTS file has relative directories or if the region has
703          ; \input of files, this must be the same directory as the file for
704          ; TeX to access the correct inputs.  That's why it's safest if
705          ; tex-directory is ".".
706          (zap-directory
707           (file-name-as-directory (expand-file-name tex-directory)))
708          (tex-out-file (concat zap-directory tex-zap-file)))
709     (tex-delete-last-temp-files)
710     ;; Write the new temp file.
711     (save-excursion
712       (save-restriction
713         (widen)
714         (goto-char (point-min))
715         (forward-line 100)
716         (let ((search-end (point))
717               (hbeg (point-min)) (hend (point-min))
718               (default-directory zap-directory))
719           (goto-char (point-min))
720           ;; Initialize the temp file with either the header or nothing
721           (if (search-forward tex-start-of-header search-end t)
722               (progn
723                 (beginning-of-line)
724                 (setq hbeg (point))     ;mark beginning of header
725                 (if (search-forward tex-end-of-header nil t)
726                     (progn (forward-line 1)
727                            (setq hend (point))) ;mark end of header
728                   (setq hbeg (point-min))))) ;no header
729           (write-region (min hbeg beg) hend
730                         (concat tex-out-file ".tex") nil nil)
731           (write-region (max beg hend) end (concat tex-out-file ".tex") t nil))
732         (let ((local-tex-trailer tex-trailer))
733           (set-buffer temp-buffer)
734           (erase-buffer)
735           ;; make sure trailer isn't hidden by a comment
736           (insert ?\n)
737           (if local-tex-trailer (insert local-tex-trailer))
738           (tex-set-buffer-directory temp-buffer zap-directory)
739           (write-region (point-min) (point-max)
740                         (concat tex-out-file ".tex") t nil))))
741     ;; Record the file name to be deleted afterward.
742     (setq tex-last-temp-file tex-out-file)
743     (tex-send-command tex-shell-cd-command zap-directory)
744     (tex-send-command tex-command tex-out-file)
745     (setq tex-print-file tex-out-file)
746     (setq tex-last-buffer-texed (current-buffer))))
747
748 (defun tex-buffer ()
749   "Run TeX on current buffer.  See \\[tex-region] for more information.
750 Does not save the buffer, so it's useful for trying experimental versions.
751 See \\[tex-file] for an alternative."
752   (interactive)
753   (tex-region (point-min) (point-max)))
754
755 (defun tex-file ()
756   "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
757 This function is more useful than \\[tex-buffer] when you need the
758 `.aux' file of LaTeX to have the correct name."
759   (interactive)
760   (let ((tex-out-file
761          (if (buffer-file-name)
762              (file-name-nondirectory (buffer-file-name))
763            (error "Buffer does not seem to be associated with any file")))
764         (file-dir (file-name-directory (buffer-file-name))))
765     (save-some-buffers)
766     (if (tex-shell-running)
767         (tex-kill-job)
768       (tex-start-shell))
769     (tex-send-command tex-shell-cd-command file-dir)
770     (tex-send-command tex-command tex-out-file))
771   (setq tex-last-buffer-texed (current-buffer))
772   (setq tex-print-file (buffer-file-name)))
773
774 (defun tex-generate-zap-file-name ()
775   "Generate a unique name suitable for use as a file name."
776   ;; Include the shell process number and host name
777   ;; in case there are multiple shells (for same or different user).
778   (format "#tz%d%s"
779           (process-id (get-buffer-process "*tex-shell*"))
780           (tex-strip-dots (system-name))))
781
782 (defun tex-strip-dots (s)
783   (setq s (copy-sequence s))
784   (while (string-match "\\." s)
785     (aset s (match-beginning 0) ?-))
786   s)
787
788 ;; This will perhaps be useful for modifying TEXINPUTS.
789 ;; Expand each file name, separated by colons, in the string S.
790 (defun tex-expand-files (s)
791   (let (elts (start 0))
792     (while (string-match ":" s start)
793       (setq elts (cons (substring s start (match-beginning 0)) elts))
794       (setq start (match-end 0)))
795     (or (= start 0)
796         (setq elts (cons (substring s start) elts)))
797     (mapconcat 'expand-file-name (nreverse elts) ":")))
798
799 (defun tex-shell-running ()
800   (and (get-process "tex-shell")
801        (eq (process-status (get-process "tex-shell")) 'run)))
802
803 (defun tex-kill-job ()
804   "Kill the currently running TeX job."
805   (interactive)
806   (quit-process (get-process "tex-shell") t))
807
808 (defun tex-recenter-output-buffer (linenum)
809   "Redisplay buffer of TeX job output so that most recent output can be seen.
810 The last line of the buffer is displayed on
811 line LINE of the window, or centered if LINE is nil."
812   (interactive "P")
813   (let ((tex-shell (get-buffer "*tex-shell*"))
814         (old-buffer (current-buffer)))
815     (if (null tex-shell)
816         (message "No TeX output buffer")
817       (pop-to-buffer tex-shell)
818       (bury-buffer tex-shell)
819       (goto-char (point-max))
820       (recenter (if linenum
821                     (prefix-numeric-value linenum)
822                   (/ (window-height) 2)))
823       (pop-to-buffer old-buffer))))
824
825 (defun tex-print (&optional alt)
826   "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
827 Runs the shell command defined by tex-dvi-print-command.  If prefix argument
828 is provided, use the alternative command, tex-alt-dvi-print-command."
829   (interactive "P")
830   (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
831         test-name)
832     (if (and (not (equal (current-buffer) tex-last-buffer-texed))
833              (file-newer-than-file-p
834               (setq test-name (tex-append (buffer-file-name) ".dvi"))
835               print-file-name-dvi))
836         (setq print-file-name-dvi test-name))
837     (if (not (file-exists-p print-file-name-dvi))
838         (error "No appropriate `.dvi' file could be found")
839       (tex-send-command
840         (if alt tex-alt-dvi-print-command tex-dvi-print-command)
841         print-file-name-dvi t))))
842
843 (defun tex-view ()
844   "Preview the last `.dvi' file made by running TeX under Emacs.
845 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
846 The variable `tex-dvi-view-command' specifies the shell command for preview."
847   (interactive)
848   (let ((tex-dvi-print-command tex-dvi-view-command))
849     (tex-print)))
850
851 (defun tex-append (file-name suffix)
852   "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
853 Scans for the first (not last) period.
854 No period is retained immediately before SUFFIX,
855 so normally SUFFIX starts with one."
856   (if (stringp file-name)
857       (let ((file (file-name-nondirectory file-name)))
858         (concat (file-name-directory file-name)
859                 (substring file 0
860                            (string-match "\\." file))
861                 suffix))
862     " "))
863
864 (defun tex-show-print-queue ()
865   "Show the print queue that \\[tex-print] put your job on.
866 Runs the shell command defined by tex-show-queue-command."
867   (interactive)
868   (if (tex-shell-running)
869       (tex-kill-job)
870     (tex-start-shell))
871   (tex-send-command tex-show-queue-command))
872
873 (defun tex-bibtex-file ()
874   "Run BibTeX on the current buffer's file."
875   (interactive)
876   (if (tex-shell-running)
877       (tex-kill-job)
878     (tex-start-shell))
879   (let ((tex-out-file
880          (tex-append (file-name-nondirectory (buffer-file-name)) ""))
881         (file-dir (file-name-directory (buffer-file-name))))
882     (tex-send-command tex-shell-cd-command file-dir)
883     (tex-send-command bibtex-command tex-out-file)))
884
885 (run-hooks 'tex-mode-load-hook)
886
887 ;; XEmacs additions
888 ;;;###autoload(add-to-list 'auto-mode-alist '("\\.ltx\\'" . latex-mode))
889 ;;;###autoload(add-to-list 'auto-mode-alist '("\\.[tT]e[xX]\\'" . tex-mode))
890 ;;;###autoload(add-to-list 'auto-mode-alist '("\\.\\(?:sty\\|cls\\|bbl\\)\\'" . latex-mode))
891
892 (provide 'tex-mode)