*** empty log message ***
[bpt/emacs.git] / lisp / textmodes / tex-mode.el
CommitLineData
d501f516
ER
1;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands.
2
c3ce7bf4 3;; Copyright (C) 1985, 86, 89, 92, 94, 95, 96, 97, 98, 1999
d61140e8 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
bed1b0c8
RS
31;; Pacify the byte-compiler
32(eval-when-compile
33 (require 'compare-w)
ea590e1c 34 (require 'cl)
bed1b0c8
RS
35 (require 'skeleton))
36
a0e9c22a 37(require 'shell)
2f3067de 38(require 'compile)
528415e7 39
d61140e8
RS
40(defgroup tex-file nil
41 "TeX files and directories"
42 :prefix "tex-"
43 :group 'tex)
44
45(defgroup tex-run nil
46 "Running external commands from TeX mode"
47 :prefix "tex-"
48 :group 'tex)
49
50(defgroup tex-view nil
51 "Viewing and printing TeX files"
52 :prefix "tex-"
53 :group 'tex)
54
7e1dae73 55;;;###autoload
d61140e8
RS
56(defcustom tex-shell-file-name nil
57 "*If non-nil, the shell file name to run in the subshell used to run TeX."
58 :type '(choice (const :tag "None" nil)
59 string)
60 :group 'tex-run)
528415e7 61
7e1dae73 62;;;###autoload
d61140e8 63(defcustom tex-directory "."
f73741fc 64 "*Directory in which temporary files are written.
81c735c0 65You can make this `/tmp' if your TEXINPUTS has no relative directories in it
528415e7 66and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
d61140e8
RS
67`\\input' commands with relative directories."
68 :type 'directory
69 :group 'tex-file)
869bff31 70
725b7428 71;;;###autoload
d61140e8 72(defcustom tex-first-line-header-regexp nil
725b7428
RS
73 "Regexp for matching a first line which `tex-region' should include.
74If this is non-nil, it should be a regular expression string;
75if it matches the first line of the file,
d61140e8
RS
76`tex-region' always includes the first line in the TeX run."
77 :type '(choice (const :tag "None" nil)
78 regexp)
79 :group 'tex-file)
725b7428 80
f73741fc 81;;;###autoload
d61140e8 82(defcustom tex-main-file nil
f73741fc 83 "*The main TeX source file which includes this buffer's file.
be4a962d
RS
84The command `tex-file' runs TeX on the file specified by `tex-main-file'
85if the variable is non-nil."
d61140e8
RS
86 :type '(choice (const :tag "None" nil)
87 file)
88 :group 'tex-file)
f73741fc 89
7e1dae73 90;;;###autoload
d61140e8
RS
91(defcustom tex-offer-save t
92 "*If non-nil, ask about saving modified buffers before \\[tex-file] is run."
93 :type 'boolean
94 :group 'tex-file)
869bff31 95
7e1dae73 96;;;###autoload
d61140e8 97(defcustom tex-run-command "tex"
869bff31 98 "*Command used to run TeX subjob.
c3ce7bf4
RS
99TeX Mode sets `tex-command' to this string.
100See the documentation of that variable."
d61140e8
RS
101 :type 'string
102 :group 'tex-run)
869bff31 103
7e1dae73 104;;;###autoload
d61140e8 105(defcustom latex-run-command "latex"
869bff31 106 "*Command used to run LaTeX subjob.
c3ce7bf4
RS
107LaTeX Mode sets `tex-command' to this string.
108See the documentation of that variable."
d61140e8
RS
109 :type 'string
110 :group 'tex-run)
528415e7 111
bed1b0c8
RS
112;;;###autoload
113(defcustom slitex-run-command "slitex"
114 "*Command used to run SliTeX subjob.
c3ce7bf4
RS
115SliTeX Mode sets `tex-command' to this string.
116See the documentation of that variable."
bed1b0c8
RS
117 :type 'string
118 :group 'tex-run)
119
c3ce7bf4
RS
120;;;###autoload
121(defcustom tex-start-options-string "\\nonstopmode\\input"
bed1b0c8 122 "*TeX options to use when running TeX.
c3ce7bf4
RS
123These precede the input file name. If nil, TeX runs without option.
124See the documentation of `tex-command'."
125 :type '(radio (const :tag "Interactive \(nil\)" nil)
126 (const :tag "Nonstop \(\"\\nonstopmode\\input\"\)"
127 "\\nonstopmode\\input")
128 (string :tag "String at your choice"))
bed1b0c8
RS
129 :group 'tex-run
130 :version "20.4")
131
528415e7 132(defvar standard-latex-block-names
dd459839
SM
133 '("abstract" "array" "center" "description"
134 "displaymath" "document" "enumerate" "eqnarray"
135 "eqnarray*" "equation" "figure" "figure*"
136 "flushleft" "flushright" "itemize" "letter"
137 "list" "minipage" "picture" "quotation"
138 "quote" "slide" "sloppypar" "tabbing"
139 "table" "table*" "tabular" "tabular*"
140 "thebibliography" "theindex*" "titlepage" "trivlist"
141 "verbatim" "verbatim*" "verse" "math")
528415e7
RS
142 "Standard LaTeX block names.")
143
7e1dae73 144;;;###autoload
d61140e8 145(defcustom latex-block-names nil
528415e7 146 "*User defined LaTeX block names.
d61140e8
RS
147Combined with `standard-latex-block-names' for minibuffer completion."
148 :type '(repeat string)
149 :group 'tex-run)
869bff31 150
7e1dae73 151;;;###autoload
d61140e8 152(defcustom tex-bibtex-command "bibtex"
528415e7 153 "*Command used by `tex-bibtex-file' to gather bibliographic data.
81c735c0 154If this string contains an asterisk (`*'), that is replaced by the file name;
d61140e8
RS
155otherwise, the file name, preceded by blank, is added at the end."
156 :type 'string
157 :group 'tex-run)
869bff31 158
7e1dae73 159;;;###autoload
d61140e8 160(defcustom tex-dvi-print-command "lpr -d"
528415e7 161 "*Command used by \\[tex-print] to print a .dvi file.
81c735c0 162If this string contains an asterisk (`*'), that is replaced by the file name;
d61140e8
RS
163otherwise, the file name, preceded by blank, is added at the end."
164 :type 'string
165 :group 'tex-view)
528415e7 166
7e1dae73 167;;;###autoload
d61140e8 168(defcustom tex-alt-dvi-print-command "lpr -d"
528415e7 169 "*Command used by \\[tex-print] with a prefix arg to print a .dvi file.
81c735c0
RS
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 172
81c735c0
RS
173If two printers are not enough of a choice, you can set the variable
174`tex-alt-dvi-print-command' to an expression that asks what you want;
528415e7
RS
175for example,
176
177 (setq tex-alt-dvi-print-command
178 '(format \"lpr -P%s\" (read-string \"Use printer: \")))
179
180would tell \\[tex-print] with a prefix argument to ask you which printer to
d61140e8
RS
181use."
182 :type '(choice (string :tag "Command")
183 (sexp :tag "Expression"))
184 :group 'tex-view)
869bff31 185
7e1dae73 186;;;###autoload
d61140e8 187(defcustom tex-dvi-view-command nil
81c735c0
RS
188 "*Command used by \\[tex-view] to display a `.dvi' file.
189If this string contains an asterisk (`*'), that is replaced by the file name;
190otherwise, the file name, preceded by blank, is added at the end.
528415e7
RS
191
192This can be set conditionally so that the previewer used is suitable for the
193window system being used. For example,
194
195 (setq tex-dvi-view-command
196 (if (eq window-system 'x) \"xdvi\" \"dvi2tty * | cat -s\"))
197
81c735c0 198would tell \\[tex-view] to use xdvi under X windows and to use dvi2tty
d61140e8
RS
199otherwise."
200 :type '(choice (const nil) string)
201 :group 'tex-view)
869bff31 202
7e1dae73 203;;;###autoload
d61140e8 204(defcustom tex-show-queue-command "lpq"
528415e7 205 "*Command used by \\[tex-show-print-queue] to show the print queue.
d61140e8
RS
206Should show the queue(s) that \\[tex-print] puts jobs on."
207 :type 'string
208 :group 'tex-view)
869bff31 209
7e1dae73 210;;;###autoload
9920303f 211(defcustom tex-default-mode 'latex-mode
869bff31 212 "*Mode to enter for a new file that might be either TeX or LaTeX.
213This variable is used when it can't be determined whether the file
214is plain TeX or LaTeX or what because the file contains no commands.
d61140e8
RS
215Normally set to either `plain-tex-mode' or `latex-mode'."
216 :type 'function
217 :group 'tex)
869bff31 218
7e1dae73 219;;;###autoload
d61140e8
RS
220(defcustom tex-open-quote "``"
221 "*String inserted by typing \\[tex-insert-quote] to open a quotation."
222 :type 'string
223 :group 'tex)
869bff31 224
7e1dae73 225;;;###autoload
d61140e8
RS
226(defcustom tex-close-quote "''"
227 "*String inserted by typing \\[tex-insert-quote] to close a quotation."
228 :type 'string
229 :group 'tex)
869bff31 230
528415e7
RS
231(defvar tex-last-temp-file nil
232 "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
233Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
81c735c0 234tex shell terminates.")
528415e7 235
869bff31 236(defvar tex-command nil
c3ce7bf4
RS
237 "*Command to run TeX.
238If this string contains an asterisk \(`*'\), that is replaced by the file name\;
239otherwise the \(shell-quoted\) value of `tex-start-options-string' and
240the file name are added at the end, with blanks as separators.
241
242In TeX, LaTeX, and SliTeX Mode this variable becomes buffer local.
243In these modes, use \\[set-variable] if you want to change it for the
244current buffer.")
869bff31 245
246(defvar tex-trailer nil
247 "String appended after the end of a region sent to TeX by \\[tex-region].")
248
249(defvar tex-start-of-header nil
898b9ac1 250 "Regular expression used by \\[tex-region] to find start of file's header.")
869bff31 251
252(defvar tex-end-of-header nil
898b9ac1 253 "Regular expression used by \\[tex-region] to find end of file's header.")
869bff31 254
255(defvar tex-shell-cd-command "cd"
256 "Command to give to shell running TeX to change directory.
81c735c0 257The value of `tex-directory' is appended to this, separated by a space.")
869bff31 258
259(defvar tex-zap-file nil
260 "Temporary file name used for text being sent as input to TeX.
261Should be a simple file name with no extension or directory specification.")
262
263(defvar tex-last-buffer-texed nil
264 "Buffer which was last TeXed.")
265
266(defvar tex-print-file nil
267 "File name that \\[tex-print] prints.
268Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
269
ea590e1c
SM
270(easy-mmode-defsyntax tex-mode-syntax-table
271 '((?% . "<")
272 (?\n . ">")
273 (?\f . ">")
274 (?\C-@ . "w")
275 (?' . "w")
276 (?@ . "_")
277 (?* . "_")
278 (?\t . " ")
279 (?~ . " ")
280 (?$ . "$$")
281 (?\\ . "/")
282 (?\" . ".")
283 (?& . ".")
284 (?_ . "."))
869bff31 285 "Syntax table used while in TeX mode.")
53c4fe47
SM
286\f
287;;;;
288;;;; Imenu support
289;;;;
869bff31 290
d6709b80 291(defcustom latex-imenu-indent-string ". "
a53c647b
RS
292 "*String to add repeated in front of nested sectional units for Imenu.
293An alternative value is \" . \", if you use a font with a narrow period."
294 :type 'string
295 :group 'tex)
296
d6709b80
SM
297(defvar latex-section-alist
298 '(("part" . 0) ("chapter" . 1)
299 ("section" . 2) ("subsection" . 3)
300 ("subsubsection" . 4)
301 ("paragraph" . 5) ("subparagraph" . 6)))
302
53c4fe47
SM
303(defvar latex-metasection-list
304 '("documentstyle" "documentclass"
305 "begin{document}" "end{document}"
306 "appendix" "frontmatter" "mainmatter" "backmatter"))
307
a5e2ae01 308(defun latex-imenu-create-index ()
53c4fe47
SM
309 "Generate an alist for imenu from a LaTeX buffer."
310 (let ((section-regexp
311 (concat "\\\\" (regexp-opt (mapcar 'car latex-section-alist) t)
312 "\\*?[ \t]*{"))
313 (metasection-regexp
314 (concat "\\\\" (regexp-opt latex-metasection-list t)))
315 i0 menu case-fold-search)
a53c647b
RS
316 (save-excursion
317 ;; Find the top-most level in this file but don't allow it to be
318 ;; any deeper than "section" (which is top-level in an article).
319 (goto-char (point-min))
320 (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t)
321 (setq i0 0)
322 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
323 (setq i0 1)
324 (setq i0 2)))
325
326 ;; Look for chapters and sections.
327 (goto-char (point-min))
53c4fe47 328 (while (search-forward-regexp section-regexp nil t)
a53c647b
RS
329 (let ((start (match-beginning 0))
330 (here (point))
331 (i (cdr (assoc (buffer-substring-no-properties
332 (match-beginning 1)
333 (match-end 1))
d6709b80 334 latex-section-alist))))
a53c647b
RS
335 (backward-char 1)
336 (condition-case err
337 (progn
338 ;; Using sexps allows some use of matching {...} inside
339 ;; titles.
340 (forward-sexp 1)
d6709b80
SM
341 (push (cons (concat (apply 'concat
342 (make-list
343 (max 0 (- i i0))
344 latex-imenu-indent-string))
345 (buffer-substring-no-properties
346 here (1- (point))))
347 start)
348 menu))
a53c647b
RS
349 (error nil))))
350
351 ;; Look for included material.
352 (goto-char (point-min))
353 (while (search-forward-regexp
354 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
53c4fe47 355\[ \t]*{\\([^}\n]+\\)}"
a53c647b 356 nil t)
53c4fe47
SM
357 (push (cons (concat "<<" (buffer-substring-no-properties
358 (match-beginning 2)
359 (match-end 2))
360 (if (= (char-after (match-beginning 1)) ?b)
361 ".bbl"
362 ".tex"))
363 (match-beginning 0))
364 menu))
a53c647b
RS
365
366 ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
367 (goto-char (point-min))
53c4fe47
SM
368 (while (search-forward-regexp metasection-regexp nil t)
369 (push (cons "--" (match-beginning 0)) menu))
a53c647b
RS
370
371 ;; Sort in increasing buffer position order.
372 (sort menu (function (lambda (a b) (< (cdr a) (cdr b))))))))
53c4fe47
SM
373\f
374;;;;
375;;;; Outline support
376;;;;
377
378(defvar latex-outline-regexp
379 (concat "\\\\"
380 (regexp-opt (append latex-metasection-list
381 (mapcar 'car latex-section-alist)) t)))
382
383(defun latex-outline-level ()
384 (if (looking-at latex-outline-regexp)
385 (1+ (or (cdr (assoc (match-string 1) latex-section-alist)) -1))
386 1000))
387\f
388;;;;
389;;;; Font-Lock support
390;;;;
391
392;(defvar tex-font-lock-keywords
393; ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
394; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
395; 2 font-lock-function-name-face)
396; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
397; 2 font-lock-constant-face)
398; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
399; ;; not be able to display those fonts.
400; ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
401; ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
402; ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
403; ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
404; ;; Rewritten and extended for LaTeX2e by Ulrik Dickow <dickow@nbi.dk>.
405; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
406; 2 font-lock-function-name-face)
407; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
408; 2 font-lock-constant-face)
409; ("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)" 1 font-lock-function-name-face)
410; "\\\\\\([a-zA-Z@]+\\|.\\)"
411; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
412; ;; not be able to display those fonts.
413; ;; LaTeX2e: \emph{This is emphasized}.
414; ("\\\\emph{\\([^}]+\\)}" 1 'italic keep)
415; ;; LaTeX2e: \textbf{This is bold}, \textit{...}, \textsl{...}
416; ("\\\\text\\(\\(bf\\)\\|it\\|sl\\){\\([^}]+\\)}"
417; 3 (if (match-beginning 2) 'bold 'italic) keep)
418; ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
419; ("\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)"
420; 3 (if (match-beginning 2) 'bold 'italic) keep))
421
422;; Rewritten with the help of Alexandra Bac <abac@welcome.disi.unige.it>.
423(defconst tex-font-lock-keywords-1
424 (eval-when-compile
425 (let* (;; Names of commands whose arg should be fontified as heading, etc.
426 (headings (regexp-opt
427 '("title" "begin" "end" "chapter" "part"
428 "section" "subsection" "subsubsection"
429 "paragraph" "subparagraph" "subsubparagraph"
430 "newcommand" "renewcommand" "newenvironment"
431 "newtheorem")
432 t))
433 (variables (regexp-opt
434 '("newcounter" "newcounter*" "setcounter" "addtocounter"
435 "setlength" "addtolength" "settowidth")
436 t))
437 (includes (regexp-opt
438 '("input" "include" "includeonly" "bibliography"
439 "epsfig" "psfig" "epsf" "nofiles" "usepackage"
440 "includegraphics" "includegraphics*")
441 t))
442 ;; Miscellany.
443 (slash "\\\\")
444 (opt "\\(\\[[^]]*\\]\\)?")
445 (arg "{\\(\\(?:[^{}]+\\(?:{[^}]*}\\)?\\)+\\)"))
446 (list
447 ;; Heading args.
448 (list (concat slash headings "\\*?" opt arg)
449 3 'font-lock-function-name-face 'prepend)
450 ;; Variable args.
451 (list (concat slash variables arg) 2 'font-lock-variable-name-face)
452 ;; Include args.
453 (list (concat slash includes opt arg) 3 'font-lock-builtin-face)
454 ;; Definitions. I think.
455 '("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)"
456 1 font-lock-function-name-face)
457 )))
458 "Subdued expressions to highlight in TeX modes.")
459
460(defconst tex-font-lock-keywords-2
461 (append tex-font-lock-keywords-1
462 (eval-when-compile
463 (let* (;;
464 ;; Names of commands whose arg should be fontified with fonts.
465 (bold (regexp-opt '("bf" "textbf" "textsc" "textup"
466 "boldsymbol" "pmb") t))
467 (italic (regexp-opt '("it" "textit" "textsl" "emph") t))
468 (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
469 ;;
470 ;; Names of commands whose arg should be fontified as a citation.
471 (citations (regexp-opt
472 '("label" "ref" "pageref" "vref" "eqref"
473 "cite" "nocite" "caption" "index" "glossary"
474 "footnote" "footnotemark" "footnotetext")
475 t))
476 ;;
477 ;; Names of commands that should be fontified.
478 (specials (regexp-opt
479 '("\\"
480 "linebreak" "nolinebreak" "pagebreak" "nopagebreak"
481 "newline" "newpage" "clearpage" "cleardoublepage"
482 "displaybreak" "allowdisplaybreaks" "enlargethispage")
483 t))
484 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
485 ;;
486 ;; Miscellany.
487 (slash "\\\\")
488 (opt "\\(\\[[^]]*\\]\\)?")
489 (arg "{\\(\\(?:[^{}]+\\(?:{[^}]*}\\)?\\)+\\)"))
490 (list
491 ;;
492 ;; Citation args.
493 (list (concat slash citations opt arg) 3 'font-lock-constant-face)
494 ;;
495 ;; Command names, special and general.
496 (cons (concat slash specials) 'font-lock-warning-face)
497 (concat slash general)
498 ;;
499 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
500 ;; since we might not be able to display those fonts.
501 (list (concat slash bold arg) 2 '(quote bold) 'append)
502 (list (concat slash italic arg) 2 '(quote italic) 'append)
503 (list (concat slash type arg) 2 '(quote bold-italic) 'append)
504 ;;
505 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
506 (list (concat "\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>"
507 "\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)")
508 3 '(if (match-beginning 2) 'bold 'italic) 'append)
509 ))))
510 "Gaudy expressions to highlight in TeX modes.")
511
512(defvar tex-font-lock-keywords tex-font-lock-keywords-1
513 "Default expressions to highlight in TeX modes.")
0fb4f245 514
53c4fe47 515\f
869bff31 516(defun tex-define-common-keys (keymap)
81c735c0 517 "Define the keys that we want defined both in TeX mode and in the TeX shell."
869bff31 518 (define-key keymap "\C-c\C-k" 'tex-kill-job)
519 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
520 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
521 (define-key keymap "\C-c\C-p" 'tex-print)
522 (define-key keymap "\C-c\C-v" 'tex-view)
62a24cb5
RS
523
524 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
525
526 (define-key keymap [menu-bar tex tex-kill-job] '("Tex Kill" . tex-kill-job))
cf6d6e8a
RS
527 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
528 '("Tex Recenter" . tex-recenter-output-buffer))
62a24cb5
RS
529 (define-key keymap [menu-bar tex tex-show-print-queue]
530 '("Show Print Queue" . tex-show-print-queue))
cf6d6e8a
RS
531 (define-key keymap [menu-bar tex tex-alt-print]
532 '("Tex Print (alt printer)" . tex-alt-print))
62a24cb5 533 (define-key keymap [menu-bar tex tex-print] '("Tex Print" . tex-print))
cf6d6e8a 534 (define-key keymap [menu-bar tex tex-view] '("Tex View" . tex-view))
869bff31 535 )
536
537(defvar tex-mode-map nil "Keymap for TeX mode.")
538
bed1b0c8 539(if tex-mode-map
869bff31 540 nil
541 (setq tex-mode-map (make-sparse-keymap))
542 (tex-define-common-keys tex-mode-map)
543 (define-key tex-mode-map "\"" 'tex-insert-quote)
544 (define-key tex-mode-map "\n" 'tex-terminate-paragraph)
ea590e1c 545 (define-key tex-mode-map "\M-\r" 'latex-insert-item)
869bff31 546 (define-key tex-mode-map "\C-c}" 'up-list)
547 (define-key tex-mode-map "\C-c{" 'tex-insert-braces)
548 (define-key tex-mode-map "\C-c\C-r" 'tex-region)
549 (define-key tex-mode-map "\C-c\C-b" 'tex-buffer)
550 (define-key tex-mode-map "\C-c\C-f" 'tex-file)
551 (define-key tex-mode-map "\C-c\C-i" 'tex-bibtex-file)
552 (define-key tex-mode-map "\C-c\C-o" 'tex-latex-block)
cf6d6e8a 553 (define-key tex-mode-map "\C-c\C-e" 'tex-close-latex-block)
6a900cf1 554 (define-key tex-mode-map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
f05bd645
RS
555 (define-key tex-mode-map "\C-c\C-m" 'tex-feed-input)
556 (define-key tex-mode-map [(control return)] 'tex-feed-input)
002b0d00
RS
557 (define-key tex-mode-map [menu-bar tex tex-bibtex-file]
558 '("BibTeX File" . tex-bibtex-file))
cf6d6e8a
RS
559 (define-key tex-mode-map [menu-bar tex tex-validate-region]
560 '("Validate Region" . tex-validate-region))
e6b0b773
MR
561 (define-key tex-mode-map [menu-bar tex tex-validate-buffer]
562 '("Validate Buffer" . tex-validate-buffer))
cf6d6e8a 563 (define-key tex-mode-map [menu-bar tex tex-region]
002b0d00 564 '("TeX Region" . tex-region))
cf6d6e8a 565 (define-key tex-mode-map [menu-bar tex tex-buffer]
002b0d00
RS
566 '("TeX Buffer" . tex-buffer))
567 (define-key tex-mode-map [menu-bar tex tex-file] '("TeX File" . tex-file)))
cf6d6e8a
RS
568
569(put 'tex-region 'menu-enable 'mark-active)
570(put 'tex-validate-region 'menu-enable 'mark-active)
571(put 'tex-print 'menu-enable '(stringp tex-print-file))
572(put 'tex-alt-print 'menu-enable '(stringp tex-print-file))
573(put 'tex-view 'menu-enable '(stringp tex-print-file))
574(put 'tex-recenter-output-buffer 'menu-enable '(get-buffer "*tex-shell*"))
575(put 'tex-kill-job 'menu-enable '(tex-shell-running))
576
d6709b80
SM
577(defvar tex-shell-map
578 (let ((m (make-sparse-keymap)))
579 (set-keymap-parent m shell-mode-map)
580 (tex-define-common-keys m)
581 m)
81c735c0 582 "Keymap for the TeX shell.
dca5ea48 583Inherits `shell-mode-map' with a few additions.")
869bff31 584
6da9bbd6
RS
585(defvar tex-face-alist
586 '((bold . "{\\bf ")
587 (italic . "{\\it ")
588 (bold-italic . "{\\bi ") ; hypothetical
589 (underline . "\\underline{")
590 (default . "{\\rm "))
591 "Alist of face and TeX font name for facemenu.")
592
593(defvar tex-latex-face-alist
594 `((italic . "{\\em ")
595 ,@tex-face-alist)
596 "Alist of face and LaTeX font name for facemenu.")
597
869bff31 598;;; This would be a lot simpler if we just used a regexp search,
599;;; but then it would be too slow.
7229064d 600;;;###autoload
869bff31 601(defun tex-mode ()
602 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
603Tries to determine (by looking at the beginning of the file) whether
81c735c0
RS
604this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
605`latex-mode', or `slitex-mode', respectively. If it cannot be determined,
606such as if there are no commands in the file, the value of `tex-default-mode'
607says which mode to use."
869bff31 608 (interactive)
d6709b80 609 (let ((mode tex-default-mode) slash comment)
869bff31 610 (save-excursion
611 (goto-char (point-min))
612 (while (and (setq slash (search-forward "\\" nil t))
613 (setq comment (let ((search-end (point)))
614 (save-excursion
615 (beginning-of-line)
616 (search-forward "%" search-end t))))))
617 (if (and slash (not comment))
c0bcb239 618 (setq mode (if (looking-at "documentstyle\\|documentclass\\|begin\\b\\|NeedsTeXFormat{LaTeX")
0edb9815
RS
619 (if (looking-at
620 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
869bff31 621 'slitex-mode
622 'latex-mode)
623 'plain-tex-mode))))
d6709b80 624 (funcall mode)))
e4c8c838 625
6503cec3 626;;;###autoload
31e1d920 627(defalias 'TeX-mode 'tex-mode)
6503cec3 628;;;###autoload
c3ce7bf4
RS
629(defalias 'plain-TeX-mode 'plain-tex-mode)
630;;;###autoload
31e1d920 631(defalias 'LaTeX-mode 'latex-mode)
869bff31 632
7229064d 633;;;###autoload
d6709b80 634(define-derived-mode plain-tex-mode text-mode "TeX"
869bff31 635 "Major mode for editing files of input for plain TeX.
636Makes $ and } display the characters they match.
637Makes \" insert `` when it seems to be the beginning of a quotation,
638and '' when it appears to be the end; it inserts \" only after a \\.
639
640Use \\[tex-region] to run TeX on the current region, plus a \"header\"
641copied from the top of the file (containing macro definitions, etc.),
642running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
643\\[tex-file] saves the buffer and then processes the file.
644\\[tex-print] prints the .dvi file made by any of these.
645\\[tex-view] previews the .dvi file made by any of these.
646\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
647
e6b0b773 648Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 649mismatched $'s or braces.
650
651Special commands:
652\\{tex-mode-map}
653
654Mode variables:
655tex-run-command
656 Command string used by \\[tex-region] or \\[tex-buffer].
657tex-directory
658 Directory in which to create temporary files for TeX jobs
659 run by \\[tex-region] or \\[tex-buffer].
660tex-dvi-print-command
661 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
662tex-alt-dvi-print-command
663 Alternative command string used by \\[tex-print] (when given a prefix
664 argument) to print a .dvi file.
869bff31 665tex-dvi-view-command
666 Command string used by \\[tex-view] to preview a .dvi file.
667tex-show-queue-command
668 Command string used by \\[tex-show-print-queue] to show the print
669 queue that \\[tex-print] put your job on.
670
81c735c0
RS
671Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
672`tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
673special subshell is initiated, the hook `tex-shell-hook' is run."
869bff31 674 (tex-common-initialization)
869bff31 675 (setq tex-command tex-run-command)
898b9ac1
RS
676 (setq tex-start-of-header "%\\*\\*start of header")
677 (setq tex-end-of-header "%\\*\\*end of header")
869bff31 678 (setq tex-trailer "\\bye\n")
d6709b80 679 (run-hooks 'tex-mode-hook))
869bff31 680
7229064d 681;;;###autoload
d6709b80 682(define-derived-mode latex-mode text-mode "LaTeX"
869bff31 683 "Major mode for editing files of input for LaTeX.
684Makes $ and } display the characters they match.
685Makes \" insert `` when it seems to be the beginning of a quotation,
686and '' when it appears to be the end; it inserts \" only after a \\.
687
688Use \\[tex-region] to run LaTeX on the current region, plus the preamble
689copied from the top of the file (containing \\documentstyle, etc.),
690running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
691\\[tex-file] saves the buffer and then processes the file.
692\\[tex-print] prints the .dvi file made by any of these.
693\\[tex-view] previews the .dvi file made by any of these.
694\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
695
e6b0b773 696Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 697mismatched $'s or braces.
698
699Special commands:
700\\{tex-mode-map}
701
702Mode variables:
703latex-run-command
704 Command string used by \\[tex-region] or \\[tex-buffer].
705tex-directory
706 Directory in which to create temporary files for LaTeX jobs
707 run by \\[tex-region] or \\[tex-buffer].
708tex-dvi-print-command
709 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
710tex-alt-dvi-print-command
711 Alternative command string used by \\[tex-print] (when given a prefix
712 argument) to print a .dvi file.
869bff31 713tex-dvi-view-command
714 Command string used by \\[tex-view] to preview a .dvi file.
715tex-show-queue-command
716 Command string used by \\[tex-show-print-queue] to show the print
717 queue that \\[tex-print] put your job on.
718
bed1b0c8 719Entering Latex mode runs the hook `text-mode-hook', then
81c735c0
RS
720`tex-mode-hook', and finally `latex-mode-hook'. When the special
721subshell is initiated, `tex-shell-hook' is run."
869bff31 722 (tex-common-initialization)
869bff31 723 (setq tex-command latex-run-command)
dd459839
SM
724 (setq tex-start-of-header "\\\\document\\(style\\|class\\)")
725 (setq tex-end-of-header "\\\\begin\\s-*{document}")
726 (setq tex-trailer "\\end\\s-*{document}\n")
ab2c9f54
RS
727 ;; A line containing just $$ is treated as a paragraph separator.
728 ;; A line starting with $$ starts a paragraph,
729 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80 730 (setq paragraph-start
dd459839 731 (concat "[\f%]\\|[ \t]*\\($\\|\\$\\$\\|"
d6709b80
SM
732 "\\\\[][]\\|"
733 "\\\\" (regexp-opt (append
734 (mapcar 'car latex-section-alist)
735 '("begin" "label" "end"
736 "item" "bibitem" "newline" "noindent"
737 "newpage" "footnote" "marginpar"
738 "parbox" "caption")) t)
739 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
dd459839 740 "\\>\\)"))
d6709b80 741 (setq paragraph-separate
dd459839 742 (concat "[\f%]\\|[ \t]*\\($\\|"
d6709b80
SM
743 "\\\\[][]\\|"
744 "\\\\" (regexp-opt (append
745 (mapcar 'car latex-section-alist)
746 '("begin" "label" "end" )) t)
747 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
748 "noindent" "newpage" "footnote"
749 "marginpar" "parbox" "caption"))
dd459839
SM
750 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
751 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
d6709b80
SM
752 (set (make-local-variable 'imenu-create-index-function)
753 'latex-imenu-create-index)
754 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
755 (set (make-local-variable 'fill-nobreak-predicate)
756 'latex-fill-nobreak-predicate)
ea590e1c 757 (set (make-local-variable 'indent-line-function) 'latex-indent)
dd459839 758 (set (make-local-variable 'fill-indent-according-to-mode) t)
d6709b80
SM
759 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
760 (set (make-local-variable 'outline-level) 'latex-outline-level)
53c4fe47 761 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
d6709b80 762 (run-hooks 'tex-mode-hook))
869bff31 763
bd2f2323 764;;;###autoload
d6709b80 765(define-derived-mode slitex-mode latex-mode "SliTeX"
869bff31 766 "Major mode for editing files of input for SliTeX.
767Makes $ and } display the characters they match.
768Makes \" insert `` when it seems to be the beginning of a quotation,
769and '' when it appears to be the end; it inserts \" only after a \\.
770
771Use \\[tex-region] to run SliTeX on the current region, plus the preamble
772copied from the top of the file (containing \\documentstyle, etc.),
773running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
774\\[tex-file] saves the buffer and then processes the file.
775\\[tex-print] prints the .dvi file made by any of these.
776\\[tex-view] previews the .dvi file made by any of these.
777\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
778
e6b0b773 779Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 780mismatched $'s or braces.
781
782Special commands:
783\\{tex-mode-map}
784
785Mode variables:
786slitex-run-command
787 Command string used by \\[tex-region] or \\[tex-buffer].
788tex-directory
789 Directory in which to create temporary files for SliTeX jobs
790 run by \\[tex-region] or \\[tex-buffer].
791tex-dvi-print-command
792 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
793tex-alt-dvi-print-command
794 Alternative command string used by \\[tex-print] (when given a prefix
795 argument) to print a .dvi file.
869bff31 796tex-dvi-view-command
797 Command string used by \\[tex-view] to preview a .dvi file.
798tex-show-queue-command
799 Command string used by \\[tex-show-print-queue] to show the print
800 queue that \\[tex-print] put your job on.
801
81c735c0
RS
802Entering SliTeX mode runs the hook `text-mode-hook', then the hook
803`tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
804`slitex-mode-hook'. When the special subshell is initiated, the hook
805`tex-shell-hook' is run."
869bff31 806 (setq tex-command slitex-run-command)
d6709b80 807 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
869bff31 808
809(defun tex-common-initialization ()
869bff31 810 (use-local-map tex-mode-map)
ea590e1c 811 (set-syntax-table tex-mode-syntax-table)
822eddf4 812 ;; Regexp isearch should accept newline and formfeed as whitespace.
d6709b80 813 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
64db2461 814 ;; A line containing just $$ is treated as a paragraph separator.
d6709b80
SM
815 (set (make-local-variable 'paragraph-start)
816 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
ab2c9f54
RS
817 ;; A line starting with $$ starts a paragraph,
818 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80
SM
819 (set (make-local-variable 'paragraph-separate)
820 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
821 (set (make-local-variable 'comment-start) "%")
822 (set (make-local-variable 'comment-add) 1)
823 (set (make-local-variable 'comment-start-skip)
824 "\\(\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
d6709b80
SM
825 (set (make-local-variable 'parse-sexp-ignore-comments) t)
826 (set (make-local-variable 'compare-windows-whitespace)
827 'tex-categorize-whitespace)
828 (set (make-local-variable 'facemenu-add-face-function)
829 (lambda (face end)
830 (let ((face-text (cdr (assq face tex-face-alist))))
831 (if face-text
832 face-text
833 (error "Face %s not configured for %s mode" face mode-name)))))
834 (set (make-local-variable 'facemenu-end-add-face) "}")
835 (set (make-local-variable 'facemenu-remove-face-function) t)
836 (set (make-local-variable 'font-lock-defaults)
837 '((tex-font-lock-keywords
838 tex-font-lock-keywords-1 tex-font-lock-keywords-2)
839 nil nil ((?$ . "\"")) nil
840 ;; Who ever uses that anyway ???
841 (font-lock-mark-block-function . mark-paragraph)))
869bff31 842 (make-local-variable 'tex-command)
843 (make-local-variable 'tex-start-of-header)
844 (make-local-variable 'tex-end-of-header)
845 (make-local-variable 'tex-trailer))
846
869bff31 847(defun tex-categorize-whitespace (backward-limit)
848 ;; compare-windows-whitespace is set to this.
849 ;; This is basically a finite-state machine.
850 ;; Returns a symbol telling how TeX would treat
851 ;; the whitespace we are looking at: null, space, or par.
852 (let ((category 'null)
853 (not-finished t))
854 (skip-chars-backward " \t\n\f" backward-limit)
855 (while not-finished
856 (cond ((looking-at "[ \t]+")
857 (goto-char (match-end 0))
2be5fefb 858 (if (eq category 'null)
869bff31 859 (setq category 'space)))
860 ((looking-at "\n")
2be5fefb 861 (cond ((eq category 'newline)
869bff31 862 (setq category 'par)
863 (setq not-finished nil))
864 (t
865 (setq category 'newline) ;a strictly internal state
866 (goto-char (match-end 0)))))
867 ((looking-at "\f+")
868 (setq category 'par)
869 (setq not-finished nil))
870 (t
871 (setq not-finished nil))))
872 (skip-chars-forward " \t\n\f")
2be5fefb 873 (if (eq category 'newline)
869bff31 874 'space ;TeX doesn't distinguish
875 category)))
876
877(defun tex-insert-quote (arg)
878 "Insert the appropriate quote marks for TeX.
08348502
RS
879Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
880\(normally '') depending on the context. With prefix argument, always
869bff31 881inserts \" characters."
528415e7 882 (interactive "*P")
869bff31 883 (if arg
884 (self-insert-command (prefix-numeric-value arg))
885 (insert
886 (cond ((or (bobp)
887 (save-excursion
888 (forward-char -1)
889 (looking-at "\\s(\\|\\s \\|\\s>")))
890 tex-open-quote)
891 ((= (preceding-char) ?\\)
892 ?\")
893 (t
894 tex-close-quote)))))
895
e6b0b773
MR
896(defun tex-validate-buffer ()
897 "Check current buffer for paragraphs containing mismatched braces or $s.
bbd93e41 898Their positions are recorded in the buffer `*Occur*'.
e6b0b773
MR
899To find a particular invalidity from `*Occur*', switch to that buffer
900and type C-c C-c or click with mouse-2
901on the line for the invalidity you want to see."
869bff31 902 (interactive)
bbd93e41
RS
903 (let ((buffer (current-buffer))
904 (prevpos (point-min))
e6b0b773
MR
905 (linenum nil)
906 (num-matches 0))
bbd93e41
RS
907 (with-output-to-temp-buffer "*Occur*"
908 (princ "Mismatches:\n")
909 (save-excursion
910 (set-buffer standard-output)
911 (occur-mode)
912 (setq occur-buffer buffer)
e6b0b773 913 (setq occur-nlines 0))
bbd93e41
RS
914 (save-excursion
915 (goto-char (point-max))
869bff31 916 (while (and (not (input-pending-p)) (not (bobp)))
710a0f53
KH
917 (let ((end (point))
918 prev-end)
bbd93e41 919 ;; Scan the previous paragraph for invalidities.
710a0f53
KH
920 (if (search-backward "\n\n" nil t)
921 (progn
922 (setq prev-end (point))
923 (forward-char 2))
924 (goto-char (setq prev-end (point-min))))
869bff31 925 (or (tex-validate-region (point) end)
710a0f53
KH
926 (let* ((oend end)
927 (end (save-excursion (forward-line 1) (point)))
bbd93e41
RS
928 start tem)
929 (beginning-of-line)
930 (setq start (point))
931 ;; Keep track of line number as we scan,
932 ;; in a cumulative fashion.
933 (if linenum
934 (setq linenum (- linenum (count-lines prevpos (point))))
935 (setq linenum (1+ (count-lines 1 start))))
936 (setq prevpos (point))
bed1b0c8 937 ;; Mention this mismatch in *Occur*.
bbd93e41 938 ;; Since we scan from end of buffer to beginning,
e6b0b773 939 ;; add each mismatch at the beginning of *Occur*.
bbd93e41
RS
940 (save-excursion
941 (setq tem (point-marker))
942 (set-buffer standard-output)
943 (goto-char (point-min))
944 ;; Skip "Mismatches:" header line.
945 (forward-line 1)
e6b0b773 946 (setq num-matches (1+ num-matches))
bbd93e41 947 (insert-buffer-substring buffer start end)
e6b0b773
MR
948 (let (text-beg (text-end (point-marker)))
949 (forward-char (- start end))
950 (setq text-beg (point-marker))
951 (insert (format "%3d: " linenum))
952 (put-text-property (marker-position text-beg)
953 (- (marker-position text-end) 1)
954 'mouse-face 'highlight)
955 (put-text-property (marker-position text-beg)
956 (- (marker-position text-end) 1)
957 'occur tem)))))
710a0f53 958 (goto-char prev-end))))
bbd93e41
RS
959 (save-excursion
960 (set-buffer standard-output)
e6b0b773 961 (if (eq num-matches 0)
bbd93e41
RS
962 (insert "None!\n"))
963 (if (interactive-p)
e6b0b773 964 (message "%d mismatches found" num-matches))))))
869bff31 965
966(defun tex-validate-region (start end)
967 "Check for mismatched braces or $'s in region.
968Returns t if no mismatches. Returns nil and moves point to suspect
969area if a mismatch is found."
970 (interactive "r")
971 (let ((failure-point nil) (max-possible-sexps (- end start)))
972 (save-excursion
973 (condition-case ()
974 (save-restriction
975 (narrow-to-region start end)
2ed2806c 976 ;; First check that the open and close parens balance in numbers.
869bff31 977 (goto-char start)
e6b0b773 978 (while (<= 0 (setq max-possible-sexps (1- max-possible-sexps)))
2ed2806c
KH
979 (forward-sexp 1))
980 ;; Now check that like matches like.
981 (goto-char start)
982 (while (progn (skip-syntax-forward "^(")
983 (not (eobp)))
984 (let ((match (matching-paren (following-char))))
985 (save-excursion
986 (forward-sexp 1)
987 (or (= (preceding-char) match)
988 (error "Mismatched parentheses"))))
989 (forward-char 1)))
869bff31 990 (error
bed1b0c8
RS
991 (skip-syntax-forward " .>")
992 (setq failure-point (point)))))
869bff31 993 (if failure-point
994 (progn
995 (goto-char failure-point)
996 nil)
997 t)))
998
999(defun tex-terminate-paragraph (inhibit-validation)
1000 "Insert two newlines, breaking a paragraph for TeX.
81c735c0 1001Check for mismatched braces or $s in paragraph being terminated.
869bff31 1002A prefix arg inhibits the checking."
528415e7 1003 (interactive "*P")
869bff31 1004 (or inhibit-validation
1005 (save-excursion
1006 (tex-validate-region
bed1b0c8
RS
1007 (save-excursion
1008 (search-backward "\n\n" nil 'move)
1009 (point))
1010 (point)))
869bff31 1011 (message "Paragraph being closed appears to contain a mismatch"))
1012 (insert "\n\n"))
1013
1014(defun tex-insert-braces ()
1015 "Make a pair of braces and be poised to type inside of them."
528415e7 1016 (interactive "*")
869bff31 1017 (insert ?\{)
1018 (save-excursion
1019 (insert ?})))
1020
9bd4f69c
RS
1021;; This function is used as the value of fill-nobreak-predicate
1022;; in LaTeX mode. Its job is to prevent line-breaking inside
1023;; of a \verb construct.
1024(defun latex-fill-nobreak-predicate ()
1025 (let ((opoint (point))
1026 inside)
bed1b0c8 1027 (save-excursion
9bd4f69c
RS
1028 (save-restriction
1029 (beginning-of-line)
1030 (narrow-to-region (point) opoint)
1031 (while (re-search-forward "\\\\verb\\(.\\)" nil t)
1032 (unless (re-search-forward (regexp-quote (match-string 1)) nil t)
1033 (setq inside t)))))
1034 inside))
1035
53c4fe47
SM
1036(defvar latex-block-default "enumerate")
1037
869bff31 1038;;; Like tex-insert-braces, but for LaTeX.
cf149bdf
RS
1039(define-skeleton tex-latex-block
1040 "Create a matching pair of lines \\begin[OPT]{NAME} and \\end{NAME} at point.
869bff31 1041Puts point on a blank line between them."
53c4fe47
SM
1042 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1043 latex-block-default)
1044 (mapcar 'list
1045 (append standard-latex-block-names
1046 latex-block-names))
1047 nil nil nil nil latex-block-default)))
1048 (setq latex-block-default choice)
1049 (unless (or (member choice standard-latex-block-names)
1050 (member choice latex-block-names))
1051 ;; Remember new block names for later completion.
1052 (push choice latex-block-names))
1053 choice)
dd459839 1054 (unless (save-excursion (beginning-of-line) (looking-at "[ \t]*$")) '\n)
53c4fe47
SM
1055 "\\begin{" str ?\}
1056 ?\[ (skeleton-read "[options]: ") & ?\] | -1
dd459839 1057 > \n _ \n
53c4fe47
SM
1058 "\\end{" str ?\} >)
1059
ea590e1c
SM
1060(define-skeleton latex-insert-item
1061 "Insert a \item macro."
1062 nil
dd459839
SM
1063 (unless (save-excursion (beginning-of-line) (looking-at "[ \t]*$")) '\n)
1064 "\\item " >)
ea590e1c 1065
53c4fe47
SM
1066\f
1067;;;;
1068;;;; LaTeX syntax navigation
1069;;;;
869bff31 1070
1071(defun tex-last-unended-begin ()
81c735c0 1072 "Leave point at the beginning of the last `\\begin{...}' that is unended."
53c4fe47
SM
1073 (while (and (re-search-backward "\\\\\\(begin\\|end\\)\\s *{")
1074 (looking-at "\\\\end"))
869bff31 1075 (tex-last-unended-begin)))
1076
53c4fe47
SM
1077(defun tex-next-unmatched-end ()
1078 "Leave point at the end of the next `\\end' that is unended."
1079 (while (and (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}")
ea590e1c
SM
1080 (save-excursion (goto-char (match-beginning 0))
1081 (looking-at "\\\\begin")))
53c4fe47
SM
1082 (tex-next-unmatched-end)))
1083
6a900cf1
ER
1084(defun tex-goto-last-unclosed-latex-block ()
1085 "Move point to the last unclosed \\begin{...}.
1086Mark is left at original location."
1087 (interactive)
1088 (let ((spot))
1089 (save-excursion
1090 (condition-case nil
1091 (tex-last-unended-begin)
1092 (error (error "Couldn't find unended \\begin")))
1093 (setq spot (point)))
1094 (push-mark)
1095 (goto-char spot)))
1096
53c4fe47
SM
1097(defun latex-backward-sexp-1 ()
1098 "Like (backward-sexp 1) but aware of multi-char elements."
1099 (let ((pos (point))
1100 (forward-sexp-function))
1101 (backward-sexp 1)
1102 (if (looking-at "\\\\begin\\>")
1103 (signal 'scan-error
1104 (list "Containing expression ends prematurely"
1105 (point) (prog1 (point) (goto-char pos))))
1106 (when (eq (char-after) ?{)
1107 (let ((newpos (point)))
1108 (when (ignore-errors (backward-sexp 1) t)
1109 (if (looking-at "\\\\end\\>")
1110 (tex-last-unended-begin)
1111 (goto-char newpos))))))))
1112
1113(defun latex-forward-sexp-1 ()
1114 "Like (forward-sexp 1) but aware of multi-char elements."
1115 (let ((pos (point))
1116 (forward-sexp-function))
1117 (forward-sexp 1)
1118 (let ((newpos (point)))
1119 (skip-syntax-backward "/w")
1120 (cond
1121 ((looking-at "\\\\end\\>")
1122 (signal 'scan-error
1123 (list "Containing expression ends prematurely"
1124 (point)
1125 (prog1
1126 (progn (ignore-errors (forward-sexp 2)) (point))
1127 (goto-char pos)))))
1128 ((looking-at "\\\\begin\\>")
1129 (goto-char (match-end 0))
1130 (tex-next-unmatched-end))
1131 (t (goto-char newpos))))))
1132
1133(defun latex-forward-sexp (&optional arg)
1134 "Like `forward-sexp' but aware of multi-char elements."
1135 (interactive "P")
1136 (unless arg (setq arg 1))
1137 (let ((pos (point)))
1138 (condition-case err
1139 (while (/= arg 0)
1140 (setq arg
1141 (if (> arg 0)
1142 (progn (latex-forward-sexp-1) (1- arg))
1143 (progn (latex-backward-sexp-1) (1+ arg)))))
1144 (scan-error
1145 (goto-char pos)
1146 (signal (car err) (cdr err))))))
1147
ea590e1c
SM
1148(defun latex-syntax-after ()
1149 "Like (char-syntax (char-after)) but aware of multi-char elements."
1150 (if (looking-at "\\\\end\\>") ?\) (char-syntax (char-after))))
1151
1152(defun latex-skip-close-parens ()
1153 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1154 (let ((forward-sexp-function nil))
1155 (while (progn (skip-syntax-forward " )")
1156 (looking-at "\\\\end\\>"))
1157 (forward-sexp 2))))
1158
1159(defun latex-down-list ()
1160 "Like (down-list 1) but aware of multi-char elements."
1161 (forward-comment (point-max))
1162 (let ((forward-sexp-function nil))
1163 (if (not (looking-at "\\\\begin\\>"))
1164 (down-list 1)
1165 (forward-sexp 1)
1166 ;; Skip arguments.
1167 (while (looking-at "[ \t]*\\s(") (forward-sexp)))))
1168
869bff31 1169(defun tex-close-latex-block ()
1170 "Creates an \\end{...} to match the last unclosed \\begin{...}."
1171 (interactive "*")
1172 (let ((new-line-needed (bolp))
1173 text indentation)
1174 (save-excursion
528415e7 1175 (condition-case nil
869bff31 1176 (tex-last-unended-begin)
1177 (error (error "Couldn't find unended \\begin")))
1178 (setq indentation (current-column))
1179 (re-search-forward "\\\\begin\\(\\s *{[^}\n]*}\\)")
1180 (setq text (buffer-substring (match-beginning 1) (match-end 1))))
1181 (indent-to indentation)
1182 (insert "\\end" text)
1183 (if new-line-needed (insert ?\n))))
1184\f
1185;;; Invoking TeX in an inferior shell.
1186
1187;;; Why use a shell instead of running TeX directly? Because if TeX
1188;;; gets stuck, the user can switch to the shell window and type at it.
1189
1190;;; The utility functions:
1191
d974af30 1192;;;###autoload
869bff31 1193(defun tex-start-shell ()
d6709b80
SM
1194 (with-current-buffer
1195 (make-comint
1196 "tex-shell"
1197 (or tex-shell-file-name (getenv "ESHELL") (getenv "SHELL") "/bin/sh")
1198 nil)
528415e7
RS
1199 (let ((proc (get-process "tex-shell")))
1200 (set-process-sentinel proc 'tex-shell-sentinel)
1201 (process-kill-without-query proc)
e8c04c88 1202 (setq comint-prompt-regexp shell-prompt-pattern)
528415e7 1203 (use-local-map tex-shell-map)
f05bd645 1204 (compilation-shell-minor-mode t)
09592182
AS
1205 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
1206 (make-local-variable 'list-buffers-directory)
1207 (make-local-variable 'shell-dirstack)
1208 (make-local-variable 'shell-last-dir)
1209 (make-local-variable 'shell-dirtrackp)
f05bd645 1210 (run-hooks 'tex-shell-hook)
528415e7 1211 (while (zerop (buffer-size))
51b2c841
RS
1212 (sleep-for 1)))))
1213
033306e3
RS
1214(defun tex-feed-input ()
1215 "Send input to the tex shell process.
1216In the tex buffer this can be used to continue an interactive tex run.
bed1b0c8 1217In the tex shell buffer this command behaves like `comint-send-input'."
033306e3
RS
1218 (interactive)
1219 (set-buffer (process-buffer (get-process "tex-shell")))
1220 (comint-send-input)
1221 (tex-recenter-output-buffer nil))
1222
51b2c841
RS
1223(defun tex-display-shell ()
1224 "Make the TeX shell buffer visible in a window."
1225 (display-buffer (process-buffer (get-process "tex-shell")))
1226 (tex-recenter-output-buffer nil))
528415e7
RS
1227
1228(defun tex-shell-sentinel (proc msg)
1229 (cond ((null (buffer-name (process-buffer proc)))
1230 ;; buffer killed
1231 (set-process-buffer proc nil)
1232 (tex-delete-last-temp-files))
1233 ((memq (process-status proc) '(signal exit))
1234 (tex-delete-last-temp-files))))
1235
1236(defun tex-set-buffer-directory (buffer directory)
869bff31 1237 "Set BUFFER's default directory to be DIRECTORY."
1238 (setq directory (file-name-as-directory (expand-file-name directory)))
1239 (if (not (file-directory-p directory))
1240 (error "%s is not a directory" directory)
1241 (save-excursion
1242 (set-buffer buffer)
1243 (setq default-directory directory))))
1244
30803a05
RS
1245(defvar tex-send-command-modified-tick 0)
1246(make-variable-buffer-local 'tex-send-command-modified-tick)
1247
528415e7 1248(defun tex-send-command (command &optional file background)
4cdc1d4b 1249 "Send COMMAND to TeX shell process, substituting optional FILE for *.
8241d7b9
ER
1250Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1251FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1252substitution will be made in COMMAND. COMMAND can be any expression that
460e1b7d
RS
1253evaluates to a command string.
1254
1255Return the process in which TeX is running."
528415e7
RS
1256 (save-excursion
1257 (let* ((cmd (eval command))
c93931c3 1258 (proc (or (get-process "tex-shell") (error "No TeX subprocess")))
64db2461 1259 (buf (process-buffer proc))
4f45adda 1260 (star (string-match "\\*" cmd))
4cdc1d4b
RS
1261 (string
1262 (concat
1263 (if file
1264 (if star (concat (substring cmd 0 star)
1265 file (substring cmd (1+ star)))
1266 (concat cmd " " file))
1267 cmd)
1268 (if background "&" ""))))
64db2461
RS
1269 ;; Switch to buffer before checking for subproc output in it.
1270 (set-buffer buf)
30803a05
RS
1271 ;; If text is unchanged since previous tex-send-command,
1272 ;; we haven't got any output. So wait for output now.
64db2461 1273 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
30803a05 1274 (accept-process-output proc))
4cdc1d4b
RS
1275 (goto-char (process-mark proc))
1276 (insert string)
30803a05 1277 (comint-send-input)
460e1b7d
RS
1278 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1279 proc)))
528415e7 1280
a15849cb
RS
1281(defun tex-delete-last-temp-files (&optional not-all)
1282 "Delete any junk files from last temp file.
1283If NOT-ALL is non-nil, save the `.dvi' file."
528415e7
RS
1284 (if tex-last-temp-file
1285 (let* ((dir (file-name-directory tex-last-temp-file))
adf6b7f9
KH
1286 (list (and (file-directory-p dir)
1287 (file-name-all-completions
02fd229c
RS
1288 (file-name-sans-extension
1289 (file-name-nondirectory tex-last-temp-file))
1290 dir))))
adf6b7f9 1291 (while list
a15849cb
RS
1292 (if not-all
1293 (and
1294 ;; If arg is non-nil, don't delete the .dvi file.
1295 (not (string-match "\\.dvi$" (car list)))
1296 (delete-file (concat dir (car list))))
1297 (delete-file (concat dir (car list))))
528415e7
RS
1298 (setq list (cdr list))))))
1299
99621a14 1300(add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
869bff31 1301
460e1b7d
RS
1302(defvar tex-start-tex-marker nil
1303 "Marker pointing after last TeX-running command in the TeX shell buffer.")
1304
dd459839
SM
1305(defun tex-guess-main-file (&optional all)
1306 "Find a likely `tex-main-file'.
1307Looks for hints in other buffers in the same directory or in
1308ALL other buffers."
1309 (let ((dir default-directory)
1310 (header-re tex-start-of-header))
1311 (catch 'found
1312 ;; Look for a buffer with `tex-main-file' set.
1313 (dolist (buf (if (consp all) all (buffer-list)))
1314 (with-current-buffer buf
1315 (when (and (or all (equal dir default-directory))
1316 (stringp tex-main-file))
1317 (throw 'found (expand-file-name tex-main-file)))))
1318 ;; Look for a buffer containing the magic `tex-start-of-header'.
1319 (dolist (buf (if (consp all) all (buffer-list)))
1320 (with-current-buffer buf
1321 (when (and (or all (equal dir default-directory))
1322 buffer-file-name
1323 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1324 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1325 (save-excursion
1326 (goto-char (point-min))
1327 (re-search-forward header-re 10000 t)))
1328 (throw 'found (expand-file-name buffer-file-name))))))))
1329
1330(defun tex-main-file (&optional realfile)
1331 "Return the name of the main file with the `.tex' extension stripped.
1332If REALFILE is non-nil, don't strip the extension."
d6709b80 1333 (let ((file (or tex-main-file
dd459839
SM
1334 ;; Compatibility with AUCTeX.
1335 (and (boundp 'TeX-master) (stringp TeX-master)
1336 (set (make-local-variable 'tex-main-file) TeX-master))
1337 ;; Try to guess the main file.
1338 (if (not buffer-file-name)
1339 (error "Buffer is not associated with any file")
1340 (file-relative-name
1341 (if (save-excursion
1342 (goto-char (point-min))
1343 (re-search-forward tex-start-of-header 10000 t))
1344 ;; This is the main file.
1345 buffer-file-name
1346 ;; This isn't the main file, let's try to find better,
1347 (or (tex-guess-main-file)
1348 ;; (tex-guess-main-file t)
1349 buffer-file-name)))))))
1350 (cond
1351 (realfile (if (file-exists-p file) file (concat file ".tex")))
1352 ((string-match "\\.tex\\'" file) (substring file 0 (match-beginning 0)))
1353 (t file))))
1354
d6709b80
SM
1355
1356(defun tex-start-tex (command file &optional dir)
460e1b7d 1357 "Start a TeX run, using COMMAND on FILE."
6633b891 1358 (let* ((star (string-match "\\*" command))
460e1b7d 1359 (compile-command
6633b891
KH
1360 (if star
1361 (concat (substring command 0 star)
1362 (comint-quote-filename file)
1363 (substring command (1+ star)))
1364 (concat command " "
c3ce7bf4
RS
1365 (if (< 0 (length tex-start-options-string))
1366 (concat
1367 (shell-quote-argument tex-start-options-string) " "))
6633b891 1368 (comint-quote-filename file)))))
d6709b80
SM
1369 (when dir
1370 (let (shell-dirtrack-verbose)
1371 (tex-send-command tex-shell-cd-command dir)))
460e1b7d
RS
1372 (with-current-buffer (process-buffer (tex-send-command compile-command))
1373 (save-excursion
1374 (forward-line -1)
1375 (setq tex-start-tex-marker (point-marker)))
1376 (make-local-variable 'compilation-parse-errors-function)
f05bd645 1377 (setq compilation-parse-errors-function 'tex-compilation-parse-errors)
d6709b80
SM
1378 (compilation-forget-errors))
1379 (tex-display-shell)
1380 (setq tex-last-buffer-texed (current-buffer))))
460e1b7d
RS
1381\f
1382(defun tex-compilation-parse-errors (limit-search find-at-least)
f05bd645
RS
1383 "Parse the current buffer as TeX error messages.
1384See the variable `compilation-parse-errors-function' for the interface it uses.
1385
1386This function parses only the last TeX compilation.
1387It works on TeX compilations only. It is necessary for that purpose,
1388since TeX does not put file names and line numbers on the same line as
1389for the error messages."
460e1b7d
RS
1390 (require 'thingatpt)
1391 (setq compilation-error-list nil)
1392 (message "Parsing error messages...")
f05bd645
RS
1393 (let ((default-directory ; Perhaps dir has changed meanwhile.
1394 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
1395 (old-syntax-table (syntax-table))
1396 (tex-error-parse-syntax-table (copy-syntax-table (syntax-table)))
1397 found-desired (num-errors-found 0)
1398 last-filename last-linenum last-position
1399 begin-of-error end-of-error)
1400 (modify-syntax-entry ?\{ "_" tex-error-parse-syntax-table)
1401 (modify-syntax-entry ?\} "_" tex-error-parse-syntax-table)
1402 (modify-syntax-entry ?\[ "_" tex-error-parse-syntax-table)
1403 (modify-syntax-entry ?\] "_" tex-error-parse-syntax-table)
1404 ;; Single quotations may appear in errors
1405 (modify-syntax-entry ?\" "_" tex-error-parse-syntax-table)
1406 ;; Don't parse previous compilations.
ee13a145
RS
1407 (set-marker compilation-parsing-end
1408 (max compilation-parsing-end tex-start-tex-marker))
f05bd645
RS
1409 ;; Don't reparse messages already seen at last parse.
1410 (goto-char compilation-parsing-end)
1411 ;; Parse messages.
1412 (while (and (not (or found-desired (eobp)))
1413 (prog1 (re-search-forward "^! " nil 'move)
1414 (setq begin-of-error (match-beginning 0)
1415 end-of-error (match-end 0)))
1416 (re-search-forward
1417 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
1418 (let* ((this-error (set-marker (make-marker) begin-of-error))
1419 (linenum (string-to-int (match-string 1)))
1420 (error-text (regexp-quote (match-string 3)))
1421 (filename
1422 (save-excursion
ea590e1c
SM
1423 (with-syntax-table tex-error-parse-syntax-table
1424 (backward-up-list 1)
1425 (skip-syntax-forward "(_")
1426 (while (not (file-readable-p (thing-at-point 'filename)))
1427 (skip-syntax-backward "(_")
1428 (backward-up-list 1)
1429 (skip-syntax-forward "(_"))
1430 (thing-at-point 'filename))))
f05bd645
RS
1431 (new-file
1432 (or (null last-filename)
1433 (not (string-equal last-filename filename))))
1434 (error-location
1435 (save-excursion
1436 (if (equal filename (concat tex-zap-file ".tex"))
1437 (set-buffer tex-last-buffer-texed)
1438 (set-buffer (find-file-noselect filename)))
1439 (if new-file
1440 (goto-line linenum)
1441 (goto-char last-position)
1442 (forward-line (- linenum last-linenum)))
1443 ;; first try a forward search for the error text,
1444 ;; then a backward search limited by the last error.
1445 (let ((starting-point (point)))
1446 (or (re-search-forward error-text nil t)
1447 (re-search-backward
1448 error-text
1449 (marker-position last-position) t)
1450 (goto-char starting-point)))
1451 (point-marker))))
1452 (goto-char this-error)
1453 (if (and compilation-error-list
1454 (or (and find-at-least
1455 (>= num-errors-found
1456 find-at-least))
1457 (and limit-search
1458 (>= end-of-error limit-search)))
1459 new-file)
1460 (setq found-desired t)
1461 (setq num-errors-found (1+ num-errors-found)
1462 last-filename filename
1463 last-linenum linenum
1464 last-position error-location
1465 compilation-error-list ; Add the new error
1466 (cons (cons this-error error-location)
1467 compilation-error-list))
1468 (goto-char end-of-error)))))
ee13a145 1469 (set-marker compilation-parsing-end (point))
f05bd645 1470 (setq compilation-error-list (nreverse compilation-error-list))
460e1b7d
RS
1471 (message "Parsing error messages...done"))
1472\f
528415e7 1473;;; The commands:
869bff31 1474
1475(defun tex-region (beg end)
1476 "Run TeX on the current region, via a temporary file.
1477The file's name comes from the variable `tex-zap-file' and the
1478variable `tex-directory' says where to put it.
1479
1480If the buffer has a header, the header is given to TeX before the
1481region itself. The buffer's header is all lines between the strings
1482defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
1483The header must start in the first 100 lines of the buffer.
1484
1485The value of `tex-trailer' is given to TeX as input after the region.
1486
1487The value of `tex-command' specifies the command to use to run TeX."
1488 (interactive "r")
1489 (if (tex-shell-running)
1490 (tex-kill-job)
1491 (tex-start-shell))
1492 (or tex-zap-file
1493 (setq tex-zap-file (tex-generate-zap-file-name)))
6d34c59f
RS
1494 ;; Temp file will be written and TeX will be run in zap-directory.
1495 ;; If the TEXINPUTS file has relative directories or if the region has
1496 ;; \input of files, this must be the same directory as the file for
1497 ;; TeX to access the correct inputs. That's why it's safest if
1498 ;; tex-directory is ".".
1499 (let* ((zap-directory
528415e7 1500 (file-name-as-directory (expand-file-name tex-directory)))
d6709b80
SM
1501 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
1502 zap-directory)))
0d548e5d
RS
1503 ;; Don't delete temp files if we do the same buffer twice in a row.
1504 (or (eq (current-buffer) tex-last-buffer-texed)
1505 (tex-delete-last-temp-files t))
869bff31 1506 ;; Write the new temp file.
1507 (save-excursion
1508 (save-restriction
1509 (widen)
1510 (goto-char (point-min))
1511 (forward-line 100)
1512 (let ((search-end (point))
6d34c59f
RS
1513 (default-directory zap-directory)
1514 (already-output 0))
869bff31 1515 (goto-char (point-min))
6d34c59f 1516
725b7428
RS
1517 ;; Maybe copy first line, such as `\input texinfo', to temp file.
1518 (and tex-first-line-header-regexp
1519 (looking-at tex-first-line-header-regexp)
bed1b0c8 1520 (write-region (point)
6d34c59f
RS
1521 (progn (forward-line 1)
1522 (setq already-output (point)))
725b7428
RS
1523 tex-out-file nil nil))
1524
6d34c59f
RS
1525 ;; Write out the header, if there is one,
1526 ;; and any of the specified region which extends before it.
1527 ;; But don't repeat anything already written.
898b9ac1 1528 (if (re-search-forward tex-start-of-header search-end t)
6d34c59f 1529 (let (hbeg)
869bff31 1530 (beginning-of-line)
1531 (setq hbeg (point)) ;mark beginning of header
898b9ac1 1532 (if (re-search-forward tex-end-of-header nil t)
6d34c59f
RS
1533 (let (hend)
1534 (forward-line 1)
bed1b0c8 1535 (setq hend (point)) ;mark end of header
6d34c59f
RS
1536 (write-region (max (min hbeg beg) already-output)
1537 hend
1538 tex-out-file
1539 (not (zerop already-output)) nil)
1540 (setq already-output hend)))))
1541
1542 ;; Write out the specified region
1543 ;; (but don't repeat anything already written).
1544 (write-region (max beg already-output) end
1545 tex-out-file
1546 (not (zerop already-output)) nil))
1547 ;; Write the trailer, if any.
1548 ;; Precede it with a newline to make sure it
1549 ;; is not hidden in a comment.
1550 (if tex-trailer
1551 (write-region (concat "\n" tex-trailer) nil
1552 tex-out-file t nil))))
528415e7
RS
1553 ;; Record the file name to be deleted afterward.
1554 (setq tex-last-temp-file tex-out-file)
f05bd645
RS
1555 ;; Use a relative file name here because (1) the proper dir
1556 ;; is already current, and (2) the abs file name is sometimes
1557 ;; too long and can make tex crash.
d6709b80
SM
1558 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
1559 (setq tex-print-file tex-out-file)))
869bff31 1560
1561(defun tex-buffer ()
1562 "Run TeX on current buffer. See \\[tex-region] for more information.
528415e7
RS
1563Does not save the buffer, so it's useful for trying experimental versions.
1564See \\[tex-file] for an alternative."
869bff31 1565 (interactive)
1566 (tex-region (point-min) (point-max)))
1567
1568(defun tex-file ()
1569 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
1570This function is more useful than \\[tex-buffer] when you need the
1571`.aux' file of LaTeX to have the correct name."
1572 (interactive)
d6709b80 1573 (let* ((source-file (tex-main-file))
a4032611
SS
1574 (file-dir (expand-file-name (or (file-name-directory source-file)
1575 default-directory))))
7047ec77 1576 (if tex-offer-save
99621a14 1577 (save-some-buffers))
869bff31 1578 (if (tex-shell-running)
1579 (tex-kill-job)
1580 (tex-start-shell))
d6709b80 1581 (tex-start-tex tex-command source-file file-dir)
f05bd645 1582 (setq tex-print-file (expand-file-name source-file))))
869bff31 1583
1584(defun tex-generate-zap-file-name ()
1585 "Generate a unique name suitable for use as a file name."
1586 ;; Include the shell process number and host name
1587 ;; in case there are multiple shells (for same or different user).
f5cdb851
KH
1588 ;; Dec 1998: There is a report that some versions of xdvi
1589 ;; don't work with file names that start with #.
5616ee46 1590 (format "_TZ_%d-%s"
869bff31 1591 (process-id (get-buffer-process "*tex-shell*"))
1592 (tex-strip-dots (system-name))))
1593
1594(defun tex-strip-dots (s)
1595 (setq s (copy-sequence s))
1596 (while (string-match "\\." s)
1597 (aset s (match-beginning 0) ?-))
1598 s)
1599
1600;; This will perhaps be useful for modifying TEXINPUTS.
1601;; Expand each file name, separated by colons, in the string S.
1602(defun tex-expand-files (s)
1603 (let (elts (start 0))
1604 (while (string-match ":" s start)
1605 (setq elts (cons (substring s start (match-beginning 0)) elts))
1606 (setq start (match-end 0)))
1607 (or (= start 0)
1608 (setq elts (cons (substring s start) elts)))
c0df1972
SM
1609 (mapconcat (lambda (elt)
1610 (if (= (length elt) 0) elt (expand-file-name elt)))
5616ee46 1611 (nreverse elts) ":")))
869bff31 1612
1613(defun tex-shell-running ()
1614 (and (get-process "tex-shell")
1615 (eq (process-status (get-process "tex-shell")) 'run)))
1616
1617(defun tex-kill-job ()
1618 "Kill the currently running TeX job."
1619 (interactive)
bed1b0c8
RS
1620 ;; quit-process leads to core dumps of the tex process (except if
1621 ;; coredumpsize has limit 0kb as on many environments). One would
1622 ;; like to use (kill-process proc 'lambda), however that construct
1623 ;; does not work on some systems and kills the shell itself.
528415e7 1624 (quit-process (get-process "tex-shell") t))
869bff31 1625
1626(defun tex-recenter-output-buffer (linenum)
1627 "Redisplay buffer of TeX job output so that most recent output can be seen.
1628The last line of the buffer is displayed on
1629line LINE of the window, or centered if LINE is nil."
1630 (interactive "P")
1631 (let ((tex-shell (get-buffer "*tex-shell*"))
23b64225
RS
1632 (old-buffer (current-buffer))
1633 (window))
869bff31 1634 (if (null tex-shell)
1635 (message "No TeX output buffer")
23b64225
RS
1636 (setq window (display-buffer tex-shell))
1637 (save-selected-window
1638 (select-window window)
1639 (bury-buffer tex-shell)
1640 (goto-char (point-max))
1641 (recenter (if linenum
1642 (prefix-numeric-value linenum)
1643 (/ (window-height) 2)))))))
869bff31 1644
528415e7 1645(defun tex-print (&optional alt)
869bff31 1646 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1433a222
CZ
1647Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
1648is provided, use the alternative command, `tex-alt-dvi-print-command'."
528415e7 1649 (interactive "P")
869bff31 1650 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
1651 test-name)
1652 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
45c3304d
RS
1653 (buffer-file-name)
1654 ;; Check that this buffer's printed file is up to date.
869bff31 1655 (file-newer-than-file-p
1656 (setq test-name (tex-append (buffer-file-name) ".dvi"))
45c3304d 1657 (buffer-file-name)))
869bff31 1658 (setq print-file-name-dvi test-name))
528415e7
RS
1659 (if (not (file-exists-p print-file-name-dvi))
1660 (error "No appropriate `.dvi' file could be found")
460e1b7d
RS
1661 (if (tex-shell-running)
1662 (tex-kill-job)
1663 (tex-start-shell))
528415e7 1664 (tex-send-command
bed1b0c8
RS
1665 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
1666 print-file-name-dvi t))))
869bff31 1667
cf6d6e8a
RS
1668(defun tex-alt-print ()
1669 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
002b0d00 1670Runs the shell command defined by `tex-alt-dvi-print-command'."
cf6d6e8a
RS
1671 (interactive)
1672 (tex-print t))
1673
869bff31 1674(defun tex-view ()
1675 "Preview the last `.dvi' file made by running TeX under Emacs.
1676This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2b7971c9
RS
1677The variable `tex-dvi-view-command' specifies the shell command for preview.
1678You must set that variable yourself before using this command,
1679because there is no standard value that would generally work."
869bff31 1680 (interactive)
2b7971c9
RS
1681 (or tex-dvi-view-command
1682 (error "You must set `tex-dvi-view-command'"))
869bff31 1683 (let ((tex-dvi-print-command tex-dvi-view-command))
1684 (tex-print)))
1685
1686(defun tex-append (file-name suffix)
1687 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
cf6d6e8a 1688Pascal-based TeX scans for the first period, C TeX uses the last.
869bff31 1689No period is retained immediately before SUFFIX,
1690so normally SUFFIX starts with one."
1691 (if (stringp file-name)
cf6d6e8a
RS
1692 (let ((file (file-name-nondirectory file-name))
1693 trial-name)
6da9bbd6 1694 ;; Try splitting on last period.
7d0ca249
RS
1695 ;; The first-period split can get fooled when two files
1696 ;; named a.tex and a.b.tex are both tex'd;
1697 ;; the last-period split must be right if it matches at all.
cf6d6e8a
RS
1698 (setq trial-name
1699 (concat (file-name-directory file-name)
1700 (substring file 0
7d0ca249 1701 (string-match "\\.[^.]*$" file))
cf6d6e8a
RS
1702 suffix))
1703 (if (or (file-exists-p trial-name)
1704 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
1705 trial-name
7d0ca249 1706 ;; Not found, so split on first period.
cf6d6e8a
RS
1707 (concat (file-name-directory file-name)
1708 (substring file 0
7d0ca249 1709 (string-match "\\." file))
cf6d6e8a 1710 suffix)))
869bff31 1711 " "))
1712
1713(defun tex-show-print-queue ()
1714 "Show the print queue that \\[tex-print] put your job on.
1433a222 1715Runs the shell command defined by `tex-show-queue-command'."
869bff31 1716 (interactive)
1717 (if (tex-shell-running)
1718 (tex-kill-job)
1719 (tex-start-shell))
51b2c841
RS
1720 (tex-send-command tex-show-queue-command)
1721 (tex-display-shell))
869bff31 1722
1723(defun tex-bibtex-file ()
1724 "Run BibTeX on the current buffer's file."
1725 (interactive)
1726 (if (tex-shell-running)
1727 (tex-kill-job)
1728 (tex-start-shell))
e6b0b773
MR
1729 (let (shell-dirtrack-verbose
1730 (tex-out-file
869bff31 1731 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
1732 (file-dir (file-name-directory (buffer-file-name))))
528415e7 1733 (tex-send-command tex-shell-cd-command file-dir)
51b2c841
RS
1734 (tex-send-command tex-bibtex-command tex-out-file))
1735 (tex-display-shell))
ea590e1c
SM
1736\f
1737;;;;
1738;;;; LaTeX indentation
1739;;;;
1740
1741(defvar tex-indent-allhanging t)
1742(defvar tex-indent-arg 4)
1743(defvar tex-indent-basic 2)
1744(defvar tex-indent-item tex-indent-basic)
1745(defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
1746
1747(easy-mmode-defsyntax tex-latex-indent-syntax-table
dd459839
SM
1748 '((?$ . ".")
1749 (?\( . ".")
1750 (?\) . "."))
ea590e1c
SM
1751 "Syntax table used while computing indentation."
1752 :copy tex-mode-syntax-table)
1753
1754(defun latex-indent (&optional arg)
1755 (with-syntax-table tex-latex-indent-syntax-table
1756 ;; TODO: Rather than ignore $, we should try to be more clever about it.
1757 (let ((indent
1758 (save-excursion
1759 (beginning-of-line)
1760 (latex-find-indent))))
1761 (if (< indent 0) (setq indent 0))
1762 (if (<= (current-column) (current-indentation))
1763 (indent-line-to indent)
1764 (save-excursion (indent-line-to indent))))))
1765
1766(defun latex-find-indent (&optional virtual)
1767 "Find the proper indentation of text after point.
1768VIRTUAL if non-nil indicates that we're only trying to find the indentation
1769 in order to determine the indentation of something else.
1770There might be text before point."
1771 (save-excursion
1772 (skip-chars-forward " \t")
1773 (or
1774 ;; Trust the current indentation, if such info is applicable.
1775 (and virtual (>= (current-indentation) (current-column))
1776 (current-indentation))
1777 ;; Put leading close-paren where the matching open brace would be.
1778 (and (eq (latex-syntax-after) ?\))
1779 (ignore-errors
1780 (save-excursion
1781 (latex-skip-close-parens)
1782 (latex-backward-sexp-1)
1783 (latex-find-indent 'virtual))))
1784 ;; Default (maybe an argument)
1785 (let ((pos (point))
1786 (char (char-after))
1787 ;; Outdent \item if necessary.
1788 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
1789 up-list-pos)
1790 ;; Find the previous point which determines our current indentation.
1791 (condition-case err
1792 (progn
1793 (latex-backward-sexp-1)
1794 (while (> (current-column) (current-indentation))
1795 (latex-backward-sexp-1)))
1796 (scan-error
1797 (setq up-list-pos (nth 2 err))))
1798 (if (integerp up-list-pos)
1799 ;; Have to indent relative to the open-paren.
1800 (progn
1801 (goto-char up-list-pos)
1802 (if (and (not tex-indent-allhanging)
1803 (> pos (progn (latex-down-list)
1804 (forward-comment (point-max))
1805 (point))))
1806 ;; Align with the first element after the open-paren.
1807 (current-column)
1808 ;; We're the first element after a hanging brace.
1809 (goto-char up-list-pos)
1810 (+ indent tex-indent-basic (latex-find-indent 'virtual))))
1811 ;; We're now at the beginning of a line.
1812 (if (not (and (not virtual) (eq (char-after) ?\\)))
1813 ;; Nothing particular here: just keep the same indentation.
1814 (+ indent (current-column))
1815 ;; We're now looking at a macro call.
1816 (if (looking-at tex-indent-item-re)
1817 ;; Indenting relative to an item, have to re-add the outdenting.
1818 (+ indent (current-column) tex-indent-item)
1819 (let ((col (current-column)))
1820 (if (not (eq (char-syntax char) ?\())
1821 ;; If the first char was not an open-paren, there's
1822 ;; a risk that this is really not an argument to the
1823 ;; macro at all.
1824 (+ indent col)
1825 (forward-sexp 1)
1826 (if (< (line-end-position)
1827 (save-excursion (forward-comment (point-max))
1828 (point)))
1829 ;; we're indenting the first argument.
1830 (min (current-column) (+ tex-indent-arg col))
1831 (skip-syntax-forward " ")
1832 (current-column)))))))))))
528415e7
RS
1833
1834(run-hooks 'tex-mode-load-hook)
869bff31 1835
49116ac0
JB
1836(provide 'tex-mode)
1837
d501f516 1838;;; tex-mode.el ends here