* fileio.c (auto_save_1) Call Ffile_modes for remote files.
[bpt/emacs.git] / lisp / textmodes / tex-mode.el
CommitLineData
95a045bd 1;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands -*- coding: utf-8 -*-
d501f516 2
3f2c97ea 3;; Copyright (C) 1985,86,89,92,94,95,96,97,98,1999,2002,03,2004
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
55535639
PJ
29;;; Commentary:
30
e5167999
ER
31;;; Code:
32
bed1b0c8
RS
33;; Pacify the byte-compiler
34(eval-when-compile
35 (require 'compare-w)
ea590e1c 36 (require 'cl)
bed1b0c8
RS
37 (require 'skeleton))
38
a0e9c22a 39(require 'shell)
2f3067de 40(require 'compile)
528415e7 41
d61140e8
RS
42(defgroup tex-file nil
43 "TeX files and directories"
44 :prefix "tex-"
45 :group 'tex)
46
47(defgroup tex-run nil
48 "Running external commands from TeX mode"
49 :prefix "tex-"
50 :group 'tex)
51
52(defgroup tex-view nil
53 "Viewing and printing TeX files"
54 :prefix "tex-"
55 :group 'tex)
56
7e1dae73 57;;;###autoload
d61140e8
RS
58(defcustom tex-shell-file-name nil
59 "*If non-nil, the shell file name to run in the subshell used to run TeX."
60 :type '(choice (const :tag "None" nil)
61 string)
62 :group 'tex-run)
528415e7 63
7e1dae73 64;;;###autoload
d61140e8 65(defcustom tex-directory "."
f73741fc 66 "*Directory in which temporary files are written.
81c735c0 67You can make this `/tmp' if your TEXINPUTS has no relative directories in it
528415e7 68and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
d61140e8
RS
69`\\input' commands with relative directories."
70 :type 'directory
71 :group 'tex-file)
869bff31 72
725b7428 73;;;###autoload
d61140e8 74(defcustom tex-first-line-header-regexp nil
725b7428
RS
75 "Regexp for matching a first line which `tex-region' should include.
76If this is non-nil, it should be a regular expression string;
77if it matches the first line of the file,
d61140e8
RS
78`tex-region' always includes the first line in the TeX run."
79 :type '(choice (const :tag "None" nil)
80 regexp)
81 :group 'tex-file)
725b7428 82
f73741fc 83;;;###autoload
d61140e8 84(defcustom tex-main-file nil
f73741fc 85 "*The main TeX source file which includes this buffer's file.
be4a962d
RS
86The command `tex-file' runs TeX on the file specified by `tex-main-file'
87if the variable is non-nil."
d61140e8
RS
88 :type '(choice (const :tag "None" nil)
89 file)
90 :group 'tex-file)
f73741fc 91
7e1dae73 92;;;###autoload
d61140e8
RS
93(defcustom tex-offer-save t
94 "*If non-nil, ask about saving modified buffers before \\[tex-file] is run."
95 :type 'boolean
96 :group 'tex-file)
869bff31 97
7e1dae73 98;;;###autoload
d61140e8 99(defcustom tex-run-command "tex"
869bff31 100 "*Command used to run TeX subjob.
c3ce7bf4
RS
101TeX Mode sets `tex-command' to this string.
102See the documentation of that variable."
d61140e8
RS
103 :type 'string
104 :group 'tex-run)
869bff31 105
7e1dae73 106;;;###autoload
d61140e8 107(defcustom latex-run-command "latex"
869bff31 108 "*Command used to run LaTeX subjob.
c3ce7bf4
RS
109LaTeX Mode sets `tex-command' to this string.
110See the documentation of that variable."
d61140e8
RS
111 :type 'string
112 :group 'tex-run)
528415e7 113
bed1b0c8
RS
114;;;###autoload
115(defcustom slitex-run-command "slitex"
116 "*Command used to run SliTeX subjob.
c3ce7bf4
RS
117SliTeX Mode sets `tex-command' to this string.
118See the documentation of that variable."
bed1b0c8
RS
119 :type 'string
120 :group 'tex-run)
121
c3ce7bf4 122;;;###autoload
95a045bd 123(defcustom tex-start-options ""
9e0ad27a 124 "*TeX options to use when starting TeX.
95a045bd
SM
125These immediately precede the commands in `tex-start-commands'
126and the input file name, with no separating space and are not shell-quoted.
127If nil, TeX runs with no options. See the documentation of `tex-command'."
128 :type 'string
bed1b0c8 129 :group 'tex-run
9e0ad27a
RS
130 :version "21.4")
131
132;;;###autoload
133(defcustom tex-start-commands "\\nonstopmode\\input"
134 "*TeX commands to use when starting TeX.
95a045bd
SM
135They are shell-quoted and precede the input file name, with a separating space.
136If nil, no commands are used. See the documentation of `tex-command'."
9e0ad27a
RS
137 :type '(radio (const :tag "Interactive \(nil\)" nil)
138 (const :tag "Nonstop \(\"\\nonstopmode\\input\"\)"
139 "\\nonstopmode\\input")
140 (string :tag "String at your choice"))
141 :group 'tex-run
142 :version "21.4")
bed1b0c8 143
7afecb99 144(defvar latex-standard-block-names
dd459839
SM
145 '("abstract" "array" "center" "description"
146 "displaymath" "document" "enumerate" "eqnarray"
147 "eqnarray*" "equation" "figure" "figure*"
148 "flushleft" "flushright" "itemize" "letter"
149 "list" "minipage" "picture" "quotation"
150 "quote" "slide" "sloppypar" "tabbing"
151 "table" "table*" "tabular" "tabular*"
152 "thebibliography" "theindex*" "titlepage" "trivlist"
153 "verbatim" "verbatim*" "verse" "math")
528415e7
RS
154 "Standard LaTeX block names.")
155
7e1dae73 156;;;###autoload
d61140e8 157(defcustom latex-block-names nil
528415e7 158 "*User defined LaTeX block names.
7afecb99 159Combined with `latex-standard-block-names' for minibuffer completion."
d61140e8
RS
160 :type '(repeat string)
161 :group 'tex-run)
869bff31 162
7e1dae73 163;;;###autoload
d61140e8 164(defcustom tex-bibtex-command "bibtex"
528415e7 165 "*Command used by `tex-bibtex-file' to gather bibliographic data.
81c735c0 166If this string contains an asterisk (`*'), that is replaced by the file name;
d61140e8
RS
167otherwise, the file name, preceded by blank, is added at the end."
168 :type 'string
169 :group 'tex-run)
869bff31 170
7e1dae73 171;;;###autoload
d61140e8 172(defcustom tex-dvi-print-command "lpr -d"
528415e7 173 "*Command used by \\[tex-print] to print a .dvi file.
81c735c0 174If this string contains an asterisk (`*'), that is replaced by the file name;
d61140e8
RS
175otherwise, the file name, preceded by blank, is added at the end."
176 :type 'string
177 :group 'tex-view)
528415e7 178
7e1dae73 179;;;###autoload
d61140e8 180(defcustom tex-alt-dvi-print-command "lpr -d"
528415e7 181 "*Command used by \\[tex-print] with a prefix arg to print a .dvi file.
81c735c0
RS
182If this string contains an asterisk (`*'), that is replaced by the file name;
183otherwise, the file name, preceded by blank, is added at the end.
528415e7 184
81c735c0
RS
185If two printers are not enough of a choice, you can set the variable
186`tex-alt-dvi-print-command' to an expression that asks what you want;
528415e7
RS
187for example,
188
189 (setq tex-alt-dvi-print-command
190 '(format \"lpr -P%s\" (read-string \"Use printer: \")))
191
192would tell \\[tex-print] with a prefix argument to ask you which printer to
d61140e8
RS
193use."
194 :type '(choice (string :tag "Command")
195 (sexp :tag "Expression"))
196 :group 'tex-view)
869bff31 197
7e1dae73 198;;;###autoload
4372483c 199(defcustom tex-dvi-view-command '(if (eq window-system 'x) "xdvi" "dvi2tty * | cat -s")
81c735c0 200 "*Command used by \\[tex-view] to display a `.dvi' file.
746c30e2 201If it is a string, that specifies the command directly.
81c735c0 202If this string contains an asterisk (`*'), that is replaced by the file name;
746c30e2 203otherwise, the file name, preceded by a space, is added at the end.
528415e7 204
746c30e2
RS
205If the value is a form, it is evaluated to get the command to use."
206 :type '(choice (const nil) string sexp)
d61140e8 207 :group 'tex-view)
869bff31 208
7e1dae73 209;;;###autoload
d61140e8 210(defcustom tex-show-queue-command "lpq"
528415e7 211 "*Command used by \\[tex-show-print-queue] to show the print queue.
d61140e8
RS
212Should show the queue(s) that \\[tex-print] puts jobs on."
213 :type 'string
214 :group 'tex-view)
869bff31 215
7e1dae73 216;;;###autoload
9920303f 217(defcustom tex-default-mode 'latex-mode
869bff31 218 "*Mode to enter for a new file that might be either TeX or LaTeX.
219This variable is used when it can't be determined whether the file
220is plain TeX or LaTeX or what because the file contains no commands.
d61140e8
RS
221Normally set to either `plain-tex-mode' or `latex-mode'."
222 :type 'function
223 :group 'tex)
869bff31 224
7e1dae73 225;;;###autoload
d61140e8
RS
226(defcustom tex-open-quote "``"
227 "*String inserted by typing \\[tex-insert-quote] to open a quotation."
228 :type 'string
95a045bd 229 :options '("``" "\"<" "\"`" "<<" "«")
d61140e8 230 :group 'tex)
869bff31 231
7e1dae73 232;;;###autoload
d61140e8
RS
233(defcustom tex-close-quote "''"
234 "*String inserted by typing \\[tex-insert-quote] to close a quotation."
235 :type 'string
95a045bd 236 :options '("''" "\">" "\"'" ">>" "»")
d61140e8 237 :group 'tex)
869bff31 238
528415e7
RS
239(defvar tex-last-temp-file nil
240 "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
241Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
81c735c0 242tex shell terminates.")
528415e7 243
95a045bd 244(defvar tex-command "tex"
c3ce7bf4 245 "*Command to run TeX.
95a045bd 246If this string contains an asterisk \(`*'\), that is replaced by the file name;
9e0ad27a
RS
247otherwise the value of `tex-start-options', the \(shell-quoted\)
248value of `tex-start-commands', and the file name are added at the end
249with blanks as separators.
c3ce7bf4
RS
250
251In TeX, LaTeX, and SliTeX Mode this variable becomes buffer local.
252In these modes, use \\[set-variable] if you want to change it for the
253current buffer.")
869bff31 254
255(defvar tex-trailer nil
256 "String appended after the end of a region sent to TeX by \\[tex-region].")
257
258(defvar tex-start-of-header nil
898b9ac1 259 "Regular expression used by \\[tex-region] to find start of file's header.")
869bff31 260
261(defvar tex-end-of-header nil
898b9ac1 262 "Regular expression used by \\[tex-region] to find end of file's header.")
869bff31 263
264(defvar tex-shell-cd-command "cd"
265 "Command to give to shell running TeX to change directory.
81c735c0 266The value of `tex-directory' is appended to this, separated by a space.")
869bff31 267
268(defvar tex-zap-file nil
269 "Temporary file name used for text being sent as input to TeX.
270Should be a simple file name with no extension or directory specification.")
271
272(defvar tex-last-buffer-texed nil
273 "Buffer which was last TeXed.")
274
275(defvar tex-print-file nil
276 "File name that \\[tex-print] prints.
277Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
278
8a591d52
SM
279(defvar tex-mode-syntax-table
280 (let ((st (make-syntax-table)))
281 (modify-syntax-entry ?% "<" st)
282 (modify-syntax-entry ?\n ">" st)
283 (modify-syntax-entry ?\f ">" st)
284 (modify-syntax-entry ?\C-@ "w" st)
285 (modify-syntax-entry ?' "w" st)
286 (modify-syntax-entry ?@ "_" st)
287 (modify-syntax-entry ?* "_" st)
288 (modify-syntax-entry ?\t " " st)
bca7a08b
SM
289 ;; ~ is printed by TeX as a space, but it's semantics in the syntax
290 ;; of TeX is not `whitespace' (i.e. it's just like \hspace{foo}).
8a591d52
SM
291 (modify-syntax-entry ?~ "." st)
292 (modify-syntax-entry ?$ "$$" st)
293 (modify-syntax-entry ?\\ "/" st)
294 (modify-syntax-entry ?\" "." st)
295 (modify-syntax-entry ?& "." st)
296 (modify-syntax-entry ?_ "." st)
297 (modify-syntax-entry ?^ "." st)
298 st)
869bff31 299 "Syntax table used while in TeX mode.")
53c4fe47
SM
300\f
301;;;;
302;;;; Imenu support
303;;;;
869bff31 304
d6709b80 305(defcustom latex-imenu-indent-string ". "
a53c647b
RS
306 "*String to add repeated in front of nested sectional units for Imenu.
307An alternative value is \" . \", if you use a font with a narrow period."
308 :type 'string
309 :group 'tex)
310
d6709b80
SM
311(defvar latex-section-alist
312 '(("part" . 0) ("chapter" . 1)
313 ("section" . 2) ("subsection" . 3)
314 ("subsubsection" . 4)
315 ("paragraph" . 5) ("subparagraph" . 6)))
316
53c4fe47
SM
317(defvar latex-metasection-list
318 '("documentstyle" "documentclass"
319 "begin{document}" "end{document}"
320 "appendix" "frontmatter" "mainmatter" "backmatter"))
321
a5e2ae01 322(defun latex-imenu-create-index ()
53c4fe47
SM
323 "Generate an alist for imenu from a LaTeX buffer."
324 (let ((section-regexp
325 (concat "\\\\" (regexp-opt (mapcar 'car latex-section-alist) t)
326 "\\*?[ \t]*{"))
327 (metasection-regexp
328 (concat "\\\\" (regexp-opt latex-metasection-list t)))
329 i0 menu case-fold-search)
a53c647b
RS
330 (save-excursion
331 ;; Find the top-most level in this file but don't allow it to be
332 ;; any deeper than "section" (which is top-level in an article).
333 (goto-char (point-min))
334 (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t)
335 (setq i0 0)
336 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
337 (setq i0 1)
338 (setq i0 2)))
339
340 ;; Look for chapters and sections.
341 (goto-char (point-min))
53c4fe47 342 (while (search-forward-regexp section-regexp nil t)
a53c647b
RS
343 (let ((start (match-beginning 0))
344 (here (point))
345 (i (cdr (assoc (buffer-substring-no-properties
346 (match-beginning 1)
347 (match-end 1))
d6709b80 348 latex-section-alist))))
a53c647b
RS
349 (backward-char 1)
350 (condition-case err
351 (progn
352 ;; Using sexps allows some use of matching {...} inside
353 ;; titles.
354 (forward-sexp 1)
d6709b80
SM
355 (push (cons (concat (apply 'concat
356 (make-list
357 (max 0 (- i i0))
358 latex-imenu-indent-string))
359 (buffer-substring-no-properties
360 here (1- (point))))
361 start)
362 menu))
a53c647b
RS
363 (error nil))))
364
365 ;; Look for included material.
366 (goto-char (point-min))
367 (while (search-forward-regexp
368 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
53c4fe47 369\[ \t]*{\\([^}\n]+\\)}"
a53c647b 370 nil t)
53c4fe47
SM
371 (push (cons (concat "<<" (buffer-substring-no-properties
372 (match-beginning 2)
373 (match-end 2))
374 (if (= (char-after (match-beginning 1)) ?b)
375 ".bbl"
376 ".tex"))
377 (match-beginning 0))
378 menu))
a53c647b
RS
379
380 ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
381 (goto-char (point-min))
53c4fe47
SM
382 (while (search-forward-regexp metasection-regexp nil t)
383 (push (cons "--" (match-beginning 0)) menu))
a53c647b
RS
384
385 ;; Sort in increasing buffer position order.
386 (sort menu (function (lambda (a b) (< (cdr a) (cdr b))))))))
53c4fe47
SM
387\f
388;;;;
389;;;; Outline support
390;;;;
391
392(defvar latex-outline-regexp
393 (concat "\\\\"
394 (regexp-opt (append latex-metasection-list
395 (mapcar 'car latex-section-alist)) t)))
396
397(defun latex-outline-level ()
398 (if (looking-at latex-outline-regexp)
399 (1+ (or (cdr (assoc (match-string 1) latex-section-alist)) -1))
400 1000))
401\f
402;;;;
403;;;; Font-Lock support
404;;;;
405
406;(defvar tex-font-lock-keywords
407; ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
408; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
409; 2 font-lock-function-name-face)
410; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
411; 2 font-lock-constant-face)
412; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
413; ;; not be able to display those fonts.
414; ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
415; ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
416; ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
417; ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
418; ;; Rewritten and extended for LaTeX2e by Ulrik Dickow <dickow@nbi.dk>.
419; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
420; 2 font-lock-function-name-face)
421; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
422; 2 font-lock-constant-face)
423; ("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)" 1 font-lock-function-name-face)
424; "\\\\\\([a-zA-Z@]+\\|.\\)"
425; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
426; ;; not be able to display those fonts.
427; ;; LaTeX2e: \emph{This is emphasized}.
428; ("\\\\emph{\\([^}]+\\)}" 1 'italic keep)
429; ;; LaTeX2e: \textbf{This is bold}, \textit{...}, \textsl{...}
430; ("\\\\text\\(\\(bf\\)\\|it\\|sl\\){\\([^}]+\\)}"
431; 3 (if (match-beginning 2) 'bold 'italic) keep)
432; ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
433; ("\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)"
434; 3 (if (match-beginning 2) 'bold 'italic) keep))
435
436;; Rewritten with the help of Alexandra Bac <abac@welcome.disi.unige.it>.
437(defconst tex-font-lock-keywords-1
438 (eval-when-compile
439 (let* (;; Names of commands whose arg should be fontified as heading, etc.
440 (headings (regexp-opt
441 '("title" "begin" "end" "chapter" "part"
442 "section" "subsection" "subsubsection"
443 "paragraph" "subparagraph" "subsubparagraph"
7afecb99
SM
444 "newcommand" "renewcommand" "providecommand"
445 "newenvironment" "renewenvironment"
446 "newtheorem" "renewtheorem")
53c4fe47
SM
447 t))
448 (variables (regexp-opt
449 '("newcounter" "newcounter*" "setcounter" "addtocounter"
450 "setlength" "addtolength" "settowidth")
451 t))
452 (includes (regexp-opt
453 '("input" "include" "includeonly" "bibliography"
454 "epsfig" "psfig" "epsf" "nofiles" "usepackage"
15ca8de7 455 "documentstyle" "documentclass" "verbatiminput"
53c4fe47
SM
456 "includegraphics" "includegraphics*")
457 t))
458 ;; Miscellany.
459 (slash "\\\\")
15ca8de7
SM
460 (opt " *\\(\\[[^]]*\\] *\\)*")
461 ;; This would allow highlighting \newcommand\CMD but requires
462 ;; adapting subgroup numbers below.
463 ;; (arg "\\(?:{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)\\|\\\\[a-z*]+\\)"))
1598a961 464 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
53c4fe47 465 (list
95a045bd
SM
466 ;; display $$ math $$
467 ;; We only mark the match between $$ and $$ because the $$ delimiters
468 ;; themselves have already been marked (along with $..$) by syntactic
469 ;; fontification. Also this is done at the very beginning so as to
470 ;; interact with the other keywords in the same way as $...$ does.
471 (list "\\$\\$\\([^$]+\\)\\$\\$" 1 'tex-math-face)
53c4fe47
SM
472 ;; Heading args.
473 (list (concat slash headings "\\*?" opt arg)
bdbd9606
SM
474 ;; If ARG ends up matching too much (if the {} don't match, f.ex)
475 ;; jit-lock will do funny things: when updating the buffer
476 ;; the re-highlighting is only done locally so it will just
477 ;; match the local line, but defer-contextually will
478 ;; match more lines at a time, so ARG will end up matching
479 ;; a lot more, which might suddenly include a comment
480 ;; so you get things highlighted bold when you type them
481 ;; but they get turned back to normal a little while later
482 ;; because "there's already a face there".
483 ;; Using `keep' works around this un-intuitive behavior as well
15ca8de7
SM
484 ;; as improves the behavior in the very rare case where you do
485 ;; have a comment in ARG.
bdbd9606 486 3 'font-lock-function-name-face 'keep)
7afecb99
SM
487 (list (concat slash "\\(?:provide\\|\\(?:re\\)?new\\)command\\** *\\(\\\\[A-Za-z@]+\\)")
488 1 'font-lock-function-name-face 'keep)
53c4fe47 489 ;; Variable args.
15ca8de7 490 (list (concat slash variables " *" arg) 2 'font-lock-variable-name-face)
53c4fe47
SM
491 ;; Include args.
492 (list (concat slash includes opt arg) 3 'font-lock-builtin-face)
493 ;; Definitions. I think.
15ca8de7 494 '("^[ \t]*\\\\def *\\\\\\(\\(\\w\\|@\\)+\\)"
bdbd9606 495 1 font-lock-function-name-face))))
53c4fe47
SM
496 "Subdued expressions to highlight in TeX modes.")
497
498(defconst tex-font-lock-keywords-2
499 (append tex-font-lock-keywords-1
500 (eval-when-compile
501 (let* (;;
502 ;; Names of commands whose arg should be fontified with fonts.
1598a961 503 (bold (regexp-opt '("textbf" "textsc" "textup"
53c4fe47 504 "boldsymbol" "pmb") t))
1598a961 505 (italic (regexp-opt '("textit" "textsl" "emph") t))
a3d80d4a
SM
506 ;; FIXME: unimplemented yet.
507 ;; (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
53c4fe47
SM
508 ;;
509 ;; Names of commands whose arg should be fontified as a citation.
510 (citations (regexp-opt
511 '("label" "ref" "pageref" "vref" "eqref"
15ca8de7 512 "cite" "nocite" "index" "glossary" "bibitem"
1598a961
SM
513 ;; These are text, rather than citations.
514 ;; "caption" "footnote" "footnotemark" "footnotetext"
515 )
53c4fe47
SM
516 t))
517 ;;
518 ;; Names of commands that should be fontified.
1b741d9e
AS
519 (specials-1 (regexp-opt '("\\" "\\*") t)) ;; "-"
520 (specials-2 (regexp-opt
521 '("linebreak" "nolinebreak" "pagebreak" "nopagebreak"
522 "newline" "newpage" "clearpage" "cleardoublepage"
523 "displaybreak" "allowdisplaybreaks"
524 "enlargethispage") t))
53c4fe47
SM
525 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
526 ;;
527 ;; Miscellany.
528 (slash "\\\\")
15ca8de7 529 (opt " *\\(\\[[^]]*\\] *\\)*")
7afecb99 530 (args "\\(\\(?:[^{}&\\]+\\|\\\\.\\|{[^}]*}\\)+\\)")
1598a961 531 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
53c4fe47
SM
532 (list
533 ;;
534 ;; Citation args.
535 (list (concat slash citations opt arg) 3 'font-lock-constant-face)
536 ;;
15ca8de7 537 ;; Text between `` quotes ''.
95a045bd 538 (cons (concat (regexp-opt `("``" "\"<" "\"`" "<<" "«") t)
7abc9add 539 "[^'\">{]+" ;a bit pessimistic
95a045bd 540 (regexp-opt `("''" "\">" "\"'" ">>" "»") t))
15ca8de7
SM
541 'font-lock-string-face)
542 ;;
53c4fe47 543 ;; Command names, special and general.
1b741d9e
AS
544 (cons (concat slash specials-1) 'font-lock-warning-face)
545 (list (concat "\\(" slash specials-2 "\\)\\([^a-zA-Z@]\\|\\'\\)")
546 1 'font-lock-warning-face)
53c4fe47
SM
547 (concat slash general)
548 ;;
549 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
550 ;; since we might not be able to display those fonts.
15ca8de7
SM
551 (list (concat slash bold " *" arg) 2 '(quote bold) 'append)
552 (list (concat slash italic " *" arg) 2 '(quote italic) 'append)
1598a961 553 ;; (list (concat slash type arg) 2 '(quote bold-italic) 'append)
53c4fe47
SM
554 ;;
555 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
7afecb99
SM
556 (list (concat "\\\\\\(em\\|it\\|sl\\)\\>" args)
557 2 '(quote italic) 'append)
558 ;; This is separate from the previous one because of cases like
559 ;; {\em foo {\bf bar} bla} where both match.
560 (list (concat "\\\\bf\\>" args) 1 '(quote bold) 'append)))))
53c4fe47
SM
561 "Gaudy expressions to highlight in TeX modes.")
562
7afecb99
SM
563(defun tex-font-lock-suscript (pos)
564 (unless (or (memq (get-text-property pos 'face)
565 '(font-lock-constant-face font-lock-builtin-face
566 font-lock-comment-face tex-verbatim-face))
567 ;; Check for backslash quoting
568 (let ((odd nil)
569 (pos pos))
570 (while (eq (char-before pos) ?\\)
571 (setq pos (1- pos) odd (not odd)))
572 odd))
573 (if (eq (char-after pos) ?_)
574 '(face subscript display (raise -0.3))
575 '(face superscript display (raise +0.3)))))
576
577(defconst tex-font-lock-keywords-3
578 (append tex-font-lock-keywords-2
579 (eval-when-compile
580 (let ((general "\\([a-zA-Z@]+\\|[^ \t\n]\\)")
581 (slash "\\\\")
582 ;; This is not the same regexp as before: it has a `+' removed.
583 ;; The + makes the matching faster in the above cases (where we can
584 ;; exit as soon as the match fails) but would make this matching
585 ;; degenerate to nasty complexity (because we try to match the
586 ;; closing brace, which forces trying all matching combinations).
587 (arg "{\\(?:[^{}\\]\\|\\\\.\\|{[^}]*}\\)*"))
588 `((,(concat "[_^] *\\([^\n\\{}]\\|" slash general "\\|" arg "}\\)")
589 (1 (tex-font-lock-suscript (match-beginning 0))
590 append))))))
591 "Experimental expressions to highlight in TeX modes.")
592
53c4fe47
SM
593(defvar tex-font-lock-keywords tex-font-lock-keywords-1
594 "Default expressions to highlight in TeX modes.")
0fb4f245 595
7afecb99
SM
596(defvar tex-verbatim-environments
597 '("verbatim" "verbatim*"))
598
599(defvar tex-font-lock-syntactic-keywords
600 (let ((verbs (regexp-opt tex-verbatim-environments t)))
601 `((,(concat "^\\\\begin *{" verbs "}.*\\(\n\\)") 2 "|")
602 (,(concat "^\\\\end *{" verbs "}\\(.?\\)") 2
603 (unless (<= (match-beginning 0) (point-min))
604 (put-text-property (1- (match-beginning 0)) (match-beginning 0)
605 'syntax-table (string-to-syntax "|"))
606 "<"))
607 ;; ("^\\(\\\\\\)begin *{comment}" 1 "< b")
608 ;; ("^\\\\end *{comment}.*\\(\n\\)" 1 "> b")
609 ("\\\\verb\\**\\([^a-z@*]\\)" 1 "\""))))
610
611(defun tex-font-lock-unfontify-region (beg end)
612 (font-lock-default-unfontify-region beg end)
613 (while (< beg end)
614 (let ((next (next-single-property-change beg 'display nil end))
615 (prop (get-text-property beg 'display)))
616 (if (and (eq (car-safe prop) 'raise)
617 (member (car-safe (cdr prop)) '(-0.3 +0.3))
618 (null (cddr prop)))
619 (put-text-property beg next 'display nil))
620 (setq beg next))))
621
622(defface superscript
623 '((t :height 0.8)) ;; :raise 0.3
624 "Face used for superscripts.")
625(defface subscript
626 '((t :height 0.8)) ;; :raise -0.3
627 "Face used for subscripts.")
bdbd9606
SM
628
629(defface tex-math-face
630 '((t :inherit font-lock-string-face))
631 "Face used to highlight TeX math expressions.")
632(defvar tex-math-face 'tex-math-face)
7afecb99
SM
633(defface tex-verbatim-face
634 ;; '((t :inherit font-lock-string-face))
635 '((t :family "courier"))
636 "Face used to highlight TeX verbatim environments.")
637(defvar tex-verbatim-face 'tex-verbatim-face)
bdbd9606
SM
638
639;; Use string syntax but math face for $...$.
640(defun tex-font-lock-syntactic-face-function (state)
7afecb99
SM
641 (let ((char (nth 3 state)))
642 (cond
643 ((not char) font-lock-comment-face)
644 ((eq char ?$) tex-math-face)
645 (t
646 (when (char-valid-p char)
647 ;; This is a \verb?...? construct. Let's find the end and mark it.
648 (save-excursion
649 (skip-chars-forward (string ?^ char)) ;; Use `end' ?
650 (when (eq (char-syntax (preceding-char)) ?/)
651 (put-text-property (1- (point)) (point) 'syntax-table '(1)))
652 (unless (eobp)
653 (put-text-property (point) (1+ (point)) 'syntax-table '(7)))))
654 tex-verbatim-face))))
bdbd9606 655
53c4fe47 656\f
869bff31 657(defun tex-define-common-keys (keymap)
81c735c0 658 "Define the keys that we want defined both in TeX mode and in the TeX shell."
869bff31 659 (define-key keymap "\C-c\C-k" 'tex-kill-job)
660 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
661 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
662 (define-key keymap "\C-c\C-p" 'tex-print)
663 (define-key keymap "\C-c\C-v" 'tex-view)
62a24cb5
RS
664
665 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
666
bdbd9606
SM
667 (define-key keymap [menu-bar tex tex-kill-job]
668 '(menu-item "Tex Kill" tex-kill-job :enable (tex-shell-running)))
cf6d6e8a 669 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
bdbd9606
SM
670 '(menu-item "Tex Recenter" tex-recenter-output-buffer
671 :enable (get-buffer "*tex-shell*")))
62a24cb5
RS
672 (define-key keymap [menu-bar tex tex-show-print-queue]
673 '("Show Print Queue" . tex-show-print-queue))
cf6d6e8a 674 (define-key keymap [menu-bar tex tex-alt-print]
bdbd9606
SM
675 '(menu-item "Tex Print (alt printer)" tex-alt-print
676 :enable (stringp tex-print-file)))
677 (define-key keymap [menu-bar tex tex-print]
678 '(menu-item "Tex Print" tex-print :enable (stringp tex-print-file)))
679 (define-key keymap [menu-bar tex tex-view]
680 '(menu-item "Tex View" tex-view :enable (stringp tex-print-file))))
681
682(defvar tex-mode-map
683 (let ((map (make-sparse-keymap)))
15ca8de7 684 (set-keymap-parent map text-mode-map)
bdbd9606
SM
685 (tex-define-common-keys map)
686 (define-key map "\"" 'tex-insert-quote)
687 (define-key map "(" 'skeleton-pair-insert-maybe)
688 (define-key map "{" 'skeleton-pair-insert-maybe)
689 (define-key map "[" 'skeleton-pair-insert-maybe)
690 (define-key map "$" 'skeleton-pair-insert-maybe)
691 (define-key map "\n" 'tex-terminate-paragraph)
692 (define-key map "\M-\r" 'latex-insert-item)
693 (define-key map "\C-c}" 'up-list)
694 (define-key map "\C-c{" 'tex-insert-braces)
695 (define-key map "\C-c\C-r" 'tex-region)
696 (define-key map "\C-c\C-b" 'tex-buffer)
697 (define-key map "\C-c\C-f" 'tex-file)
75035a80 698 (define-key map "\C-c\C-c" 'tex-compile)
bdbd9606 699 (define-key map "\C-c\C-i" 'tex-bibtex-file)
7afecb99
SM
700 (define-key map "\C-c\C-o" 'latex-insert-block)
701 (define-key map "\C-c\C-e" 'latex-close-block)
bdbd9606
SM
702 (define-key map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
703 (define-key map "\C-c\C-m" 'tex-feed-input)
704 (define-key map [(control return)] 'tex-feed-input)
705 (define-key map [menu-bar tex tex-bibtex-file]
706 '("BibTeX File" . tex-bibtex-file))
707 (define-key map [menu-bar tex tex-validate-region]
708 '(menu-item "Validate Region" tex-validate-region :enable mark-active))
709 (define-key map [menu-bar tex tex-validate-buffer]
710 '("Validate Buffer" . tex-validate-buffer))
711 (define-key map [menu-bar tex tex-region]
712 '(menu-item "TeX Region" tex-region :enable mark-active))
713 (define-key map [menu-bar tex tex-buffer]
714 '("TeX Buffer" . tex-buffer))
715 (define-key map [menu-bar tex tex-file] '("TeX File" . tex-file))
716 map)
15ca8de7
SM
717 "Keymap shared by TeX modes.")
718
719(defvar latex-mode-map
720 (let ((map (make-sparse-keymap)))
721 (set-keymap-parent map tex-mode-map)
a3d80d4a 722 (define-key map "\C-c\C-s" 'latex-split-block)
15ca8de7
SM
723 map)
724 "Keymap for `latex-mode'. See also `tex-mode-map'.")
725
726(defvar plain-tex-mode-map
727 (let ((map (make-sparse-keymap)))
728 (set-keymap-parent map tex-mode-map)
729 map)
730 "Keymap for `plain-tex-mode'. See also `tex-mode-map'.")
cf6d6e8a 731
d6709b80
SM
732(defvar tex-shell-map
733 (let ((m (make-sparse-keymap)))
734 (set-keymap-parent m shell-mode-map)
735 (tex-define-common-keys m)
736 m)
81c735c0 737 "Keymap for the TeX shell.
dca5ea48 738Inherits `shell-mode-map' with a few additions.")
869bff31 739
6da9bbd6
RS
740(defvar tex-face-alist
741 '((bold . "{\\bf ")
742 (italic . "{\\it ")
743 (bold-italic . "{\\bi ") ; hypothetical
744 (underline . "\\underline{")
745 (default . "{\\rm "))
746 "Alist of face and TeX font name for facemenu.")
747
748(defvar tex-latex-face-alist
749 `((italic . "{\\em ")
750 ,@tex-face-alist)
751 "Alist of face and LaTeX font name for facemenu.")
752
15ca8de7
SM
753;; This would be a lot simpler if we just used a regexp search,
754;; but then it would be too slow.
a3d80d4a 755(defun tex-guess-mode ()
d6709b80 756 (let ((mode tex-default-mode) slash comment)
869bff31 757 (save-excursion
758 (goto-char (point-min))
759 (while (and (setq slash (search-forward "\\" nil t))
760 (setq comment (let ((search-end (point)))
761 (save-excursion
762 (beginning-of-line)
763 (search-forward "%" search-end t))))))
bdbd9606
SM
764 (when (and slash (not comment))
765 (setq mode
766 (if (looking-at
767 (eval-when-compile
768 (concat
769 (regexp-opt '("documentstyle" "documentclass"
95a045bd 770 "begin" "subsection" "section"
bca7a08b
SM
771 "part" "chapter" "newcommand"
772 "renewcommand") 'words)
bdbd9606
SM
773 "\\|NeedsTeXFormat{LaTeX")))
774 (if (looking-at
775 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
776 'slitex-mode
777 'latex-mode)
778 'plain-tex-mode))))
d6709b80 779 (funcall mode)))
e4c8c838 780
a3d80d4a
SM
781;; `tex-mode' plays two roles: it's the parent of several sub-modes
782;; but it's also the function that chooses between those submodes.
783;; To tell the difference between those two cases where the function
784;; might be called, we check `delay-mode-hooks'.
a3d80d4a
SM
785(define-derived-mode tex-mode text-mode "generic-TeX"
786 (tex-common-initialization))
bca7a08b
SM
787;; We now move the function and define it again. This gives a warning
788;; in the byte-compiler :-( but it's difficult to avoid because
789;; `define-derived-mode' will necessarily define the function once
790;; and we need to define it a second time for `autoload' to get the
791;; proper docstring.
792(defalias 'tex-mode-internal (symbol-function 'tex-mode))
793;;;###autoload
794(defun tex-mode ()
795 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
a3d80d4a
SM
796Tries to determine (by looking at the beginning of the file) whether
797this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
798`latex-mode', or `slitex-mode', respectively. If it cannot be determined,
799such as if there are no commands in the file, the value of `tex-default-mode'
800says which mode to use."
bca7a08b
SM
801 (interactive)
802 (if delay-mode-hooks
803 ;; We're called from one of the children already.
804 (tex-mode-internal)
805 (tex-guess-mode)))
a3d80d4a 806
6503cec3 807;;;###autoload
31e1d920 808(defalias 'TeX-mode 'tex-mode)
6503cec3 809;;;###autoload
c3ce7bf4
RS
810(defalias 'plain-TeX-mode 'plain-tex-mode)
811;;;###autoload
31e1d920 812(defalias 'LaTeX-mode 'latex-mode)
869bff31 813
7229064d 814;;;###autoload
a3d80d4a 815(define-derived-mode plain-tex-mode tex-mode "TeX"
869bff31 816 "Major mode for editing files of input for plain TeX.
817Makes $ and } display the characters they match.
818Makes \" insert `` when it seems to be the beginning of a quotation,
819and '' when it appears to be the end; it inserts \" only after a \\.
820
821Use \\[tex-region] to run TeX on the current region, plus a \"header\"
822copied from the top of the file (containing macro definitions, etc.),
823running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
824\\[tex-file] saves the buffer and then processes the file.
825\\[tex-print] prints the .dvi file made by any of these.
826\\[tex-view] previews the .dvi file made by any of these.
827\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
828
e6b0b773 829Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 830mismatched $'s or braces.
831
832Special commands:
15ca8de7 833\\{plain-tex-mode-map}
869bff31 834
835Mode variables:
836tex-run-command
837 Command string used by \\[tex-region] or \\[tex-buffer].
838tex-directory
839 Directory in which to create temporary files for TeX jobs
840 run by \\[tex-region] or \\[tex-buffer].
841tex-dvi-print-command
842 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
843tex-alt-dvi-print-command
844 Alternative command string used by \\[tex-print] (when given a prefix
845 argument) to print a .dvi file.
869bff31 846tex-dvi-view-command
847 Command string used by \\[tex-view] to preview a .dvi file.
848tex-show-queue-command
849 Command string used by \\[tex-show-print-queue] to show the print
850 queue that \\[tex-print] put your job on.
851
81c735c0
RS
852Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
853`tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
854special subshell is initiated, the hook `tex-shell-hook' is run."
a3d80d4a
SM
855 (set (make-local-variable 'tex-command) tex-run-command)
856 (set (make-local-variable 'tex-start-of-header) "%\\*\\*start of header")
857 (set (make-local-variable 'tex-end-of-header) "%\\*\\*end of header")
858 (set (make-local-variable 'tex-trailer) "\\bye\n"))
869bff31 859
7229064d 860;;;###autoload
a3d80d4a 861(define-derived-mode latex-mode tex-mode "LaTeX"
869bff31 862 "Major mode for editing files of input for LaTeX.
863Makes $ and } display the characters they match.
864Makes \" insert `` when it seems to be the beginning of a quotation,
865and '' when it appears to be the end; it inserts \" only after a \\.
866
867Use \\[tex-region] to run LaTeX on the current region, plus the preamble
868copied from the top of the file (containing \\documentstyle, etc.),
869running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
870\\[tex-file] saves the buffer and then processes the file.
871\\[tex-print] prints the .dvi file made by any of these.
872\\[tex-view] previews the .dvi file made by any of these.
873\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
874
e6b0b773 875Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 876mismatched $'s or braces.
877
878Special commands:
15ca8de7 879\\{latex-mode-map}
869bff31 880
881Mode variables:
882latex-run-command
883 Command string used by \\[tex-region] or \\[tex-buffer].
884tex-directory
885 Directory in which to create temporary files for LaTeX jobs
886 run by \\[tex-region] or \\[tex-buffer].
887tex-dvi-print-command
888 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
889tex-alt-dvi-print-command
890 Alternative command string used by \\[tex-print] (when given a prefix
891 argument) to print a .dvi file.
869bff31 892tex-dvi-view-command
893 Command string used by \\[tex-view] to preview a .dvi file.
894tex-show-queue-command
895 Command string used by \\[tex-show-print-queue] to show the print
896 queue that \\[tex-print] put your job on.
897
bed1b0c8 898Entering Latex mode runs the hook `text-mode-hook', then
81c735c0
RS
899`tex-mode-hook', and finally `latex-mode-hook'. When the special
900subshell is initiated, `tex-shell-hook' is run."
a3d80d4a
SM
901 (set (make-local-variable 'tex-command) latex-run-command)
902 (set (make-local-variable 'tex-start-of-header)
903 "\\\\document\\(style\\|class\\)")
904 (set (make-local-variable 'tex-end-of-header) "\\\\begin\\s-*{document}")
d9cbee57 905 (set (make-local-variable 'tex-trailer) "\\end{document}\n")
ab2c9f54
RS
906 ;; A line containing just $$ is treated as a paragraph separator.
907 ;; A line starting with $$ starts a paragraph,
908 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80 909 (setq paragraph-start
a3d80d4a 910 (concat "[ \t]*\\(\\$\\$\\|"
d6709b80
SM
911 "\\\\[][]\\|"
912 "\\\\" (regexp-opt (append
913 (mapcar 'car latex-section-alist)
914 '("begin" "label" "end"
915 "item" "bibitem" "newline" "noindent"
916 "newpage" "footnote" "marginpar"
917 "parbox" "caption")) t)
918 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
dd459839 919 "\\>\\)"))
d6709b80 920 (setq paragraph-separate
dd459839 921 (concat "[\f%]\\|[ \t]*\\($\\|"
d6709b80
SM
922 "\\\\[][]\\|"
923 "\\\\" (regexp-opt (append
924 (mapcar 'car latex-section-alist)
925 '("begin" "label" "end" )) t)
926 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
927 "noindent" "newpage" "footnote"
928 "marginpar" "parbox" "caption"))
dd459839
SM
929 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
930 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
d6709b80
SM
931 (set (make-local-variable 'imenu-create-index-function)
932 'latex-imenu-create-index)
933 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
95a045bd 934 (add-hook 'fill-nobreak-predicate 'latex-fill-nobreak-predicate nil t)
ea590e1c 935 (set (make-local-variable 'indent-line-function) 'latex-indent)
dd459839 936 (set (make-local-variable 'fill-indent-according-to-mode) t)
d6709b80
SM
937 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
938 (set (make-local-variable 'outline-level) 'latex-outline-level)
53c4fe47 939 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
a3d80d4a 940 (set (make-local-variable 'skeleton-end-hook) nil))
869bff31 941
bd2f2323 942;;;###autoload
d6709b80 943(define-derived-mode slitex-mode latex-mode "SliTeX"
869bff31 944 "Major mode for editing files of input for SliTeX.
945Makes $ and } display the characters they match.
946Makes \" insert `` when it seems to be the beginning of a quotation,
947and '' when it appears to be the end; it inserts \" only after a \\.
948
949Use \\[tex-region] to run SliTeX on the current region, plus the preamble
950copied from the top of the file (containing \\documentstyle, etc.),
951running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
952\\[tex-file] saves the buffer and then processes the file.
953\\[tex-print] prints the .dvi file made by any of these.
954\\[tex-view] previews the .dvi file made by any of these.
955\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
956
e6b0b773 957Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 958mismatched $'s or braces.
959
960Special commands:
15ca8de7 961\\{slitex-mode-map}
869bff31 962
963Mode variables:
964slitex-run-command
965 Command string used by \\[tex-region] or \\[tex-buffer].
966tex-directory
967 Directory in which to create temporary files for SliTeX jobs
968 run by \\[tex-region] or \\[tex-buffer].
969tex-dvi-print-command
970 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
971tex-alt-dvi-print-command
972 Alternative command string used by \\[tex-print] (when given a prefix
973 argument) to print a .dvi file.
869bff31 974tex-dvi-view-command
975 Command string used by \\[tex-view] to preview a .dvi file.
976tex-show-queue-command
977 Command string used by \\[tex-show-print-queue] to show the print
978 queue that \\[tex-print] put your job on.
979
81c735c0
RS
980Entering SliTeX mode runs the hook `text-mode-hook', then the hook
981`tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
982`slitex-mode-hook'. When the special subshell is initiated, the hook
983`tex-shell-hook' is run."
869bff31 984 (setq tex-command slitex-run-command)
d6709b80 985 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
869bff31 986
987(defun tex-common-initialization ()
822eddf4 988 ;; Regexp isearch should accept newline and formfeed as whitespace.
d6709b80 989 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
64db2461 990 ;; A line containing just $$ is treated as a paragraph separator.
d6709b80
SM
991 (set (make-local-variable 'paragraph-start)
992 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
ab2c9f54
RS
993 ;; A line starting with $$ starts a paragraph,
994 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80
SM
995 (set (make-local-variable 'paragraph-separate)
996 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
997 (set (make-local-variable 'comment-start) "%")
998 (set (make-local-variable 'comment-add) 1)
999 (set (make-local-variable 'comment-start-skip)
5ae0d697 1000 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
d6709b80
SM
1001 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1002 (set (make-local-variable 'compare-windows-whitespace)
1003 'tex-categorize-whitespace)
1004 (set (make-local-variable 'facemenu-add-face-function)
1005 (lambda (face end)
1006 (let ((face-text (cdr (assq face tex-face-alist))))
1007 (if face-text
1008 face-text
1009 (error "Face %s not configured for %s mode" face mode-name)))))
1010 (set (make-local-variable 'facemenu-end-add-face) "}")
1011 (set (make-local-variable 'facemenu-remove-face-function) t)
1012 (set (make-local-variable 'font-lock-defaults)
7afecb99
SM
1013 '((tex-font-lock-keywords tex-font-lock-keywords-1
1014 tex-font-lock-keywords-2 tex-font-lock-keywords-3)
d6709b80
SM
1015 nil nil ((?$ . "\"")) nil
1016 ;; Who ever uses that anyway ???
bdbd9606
SM
1017 (font-lock-mark-block-function . mark-paragraph)
1018 (font-lock-syntactic-face-function
7afecb99
SM
1019 . tex-font-lock-syntactic-face-function)
1020 (font-lock-unfontify-region-function
1021 . tex-font-lock-unfontify-region)
1022 (font-lock-syntactic-keywords
1023 . tex-font-lock-syntactic-keywords)
1024 (parse-sexp-lookup-properties . t)))
95a045bd
SM
1025 ;; TABs in verbatim environments don't do what you think.
1026 (set (make-local-variable 'indent-tabs-mode) nil)
7afecb99 1027 ;; Other vars that should be buffer-local.
869bff31 1028 (make-local-variable 'tex-command)
1029 (make-local-variable 'tex-start-of-header)
1030 (make-local-variable 'tex-end-of-header)
1031 (make-local-variable 'tex-trailer))
1032
869bff31 1033(defun tex-categorize-whitespace (backward-limit)
1034 ;; compare-windows-whitespace is set to this.
1035 ;; This is basically a finite-state machine.
1036 ;; Returns a symbol telling how TeX would treat
1037 ;; the whitespace we are looking at: null, space, or par.
1038 (let ((category 'null)
1039 (not-finished t))
1040 (skip-chars-backward " \t\n\f" backward-limit)
1041 (while not-finished
1042 (cond ((looking-at "[ \t]+")
1043 (goto-char (match-end 0))
2be5fefb 1044 (if (eq category 'null)
869bff31 1045 (setq category 'space)))
1046 ((looking-at "\n")
2be5fefb 1047 (cond ((eq category 'newline)
869bff31 1048 (setq category 'par)
1049 (setq not-finished nil))
1050 (t
1051 (setq category 'newline) ;a strictly internal state
1052 (goto-char (match-end 0)))))
1053 ((looking-at "\f+")
1054 (setq category 'par)
1055 (setq not-finished nil))
1056 (t
1057 (setq not-finished nil))))
1058 (skip-chars-forward " \t\n\f")
2be5fefb 1059 (if (eq category 'newline)
869bff31 1060 'space ;TeX doesn't distinguish
1061 category)))
1062
1063(defun tex-insert-quote (arg)
1064 "Insert the appropriate quote marks for TeX.
08348502
RS
1065Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
1066\(normally '') depending on the context. With prefix argument, always
869bff31 1067inserts \" characters."
528415e7 1068 (interactive "*P")
95a045bd
SM
1069 (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
1070 (eq (get-text-property (point) 'face) 'tex-verbatim-face)
1071 (save-excursion
1072 (backward-char (length tex-open-quote))
1073 (when (or (looking-at (regexp-quote tex-open-quote))
1074 (looking-at (regexp-quote tex-close-quote)))
1075 (delete-char (length tex-open-quote))
1076 t)))
869bff31 1077 (self-insert-command (prefix-numeric-value arg))
95a045bd
SM
1078 (insert (if (memq (char-syntax (preceding-char)) '(?\( ?> ?\ ))
1079 tex-open-quote tex-close-quote))))
869bff31 1080
e6b0b773
MR
1081(defun tex-validate-buffer ()
1082 "Check current buffer for paragraphs containing mismatched braces or $s.
bbd93e41 1083Their positions are recorded in the buffer `*Occur*'.
e6b0b773
MR
1084To find a particular invalidity from `*Occur*', switch to that buffer
1085and type C-c C-c or click with mouse-2
1086on the line for the invalidity you want to see."
869bff31 1087 (interactive)
bbd93e41
RS
1088 (let ((buffer (current-buffer))
1089 (prevpos (point-min))
e6b0b773
MR
1090 (linenum nil)
1091 (num-matches 0))
bbd93e41
RS
1092 (with-output-to-temp-buffer "*Occur*"
1093 (princ "Mismatches:\n")
a3d80d4a 1094 (with-current-buffer standard-output
bbd93e41 1095 (occur-mode)
52ab062c
CW
1096 ;; This won't actually work...Really, this whole thing should
1097 ;; be rewritten instead of being a hack on top of occur.
1098 (setq occur-revert-arguments (list nil 0 (list buffer))))
bbd93e41
RS
1099 (save-excursion
1100 (goto-char (point-max))
52ab062c 1101 (while (and (not (bobp)))
710a0f53
KH
1102 (let ((end (point))
1103 prev-end)
bbd93e41 1104 ;; Scan the previous paragraph for invalidities.
710a0f53
KH
1105 (if (search-backward "\n\n" nil t)
1106 (progn
1107 (setq prev-end (point))
1108 (forward-char 2))
1109 (goto-char (setq prev-end (point-min))))
869bff31 1110 (or (tex-validate-region (point) end)
a3d80d4a 1111 (let* ((end (line-beginning-position 2))
bbd93e41
RS
1112 start tem)
1113 (beginning-of-line)
1114 (setq start (point))
1115 ;; Keep track of line number as we scan,
1116 ;; in a cumulative fashion.
1117 (if linenum
1118 (setq linenum (- linenum (count-lines prevpos (point))))
1119 (setq linenum (1+ (count-lines 1 start))))
1120 (setq prevpos (point))
bed1b0c8 1121 ;; Mention this mismatch in *Occur*.
bbd93e41 1122 ;; Since we scan from end of buffer to beginning,
e6b0b773 1123 ;; add each mismatch at the beginning of *Occur*.
bbd93e41
RS
1124 (save-excursion
1125 (setq tem (point-marker))
1126 (set-buffer standard-output)
1127 (goto-char (point-min))
1128 ;; Skip "Mismatches:" header line.
1129 (forward-line 1)
e6b0b773 1130 (setq num-matches (1+ num-matches))
bbd93e41 1131 (insert-buffer-substring buffer start end)
e6b0b773
MR
1132 (let (text-beg (text-end (point-marker)))
1133 (forward-char (- start end))
1134 (setq text-beg (point-marker))
1135 (insert (format "%3d: " linenum))
a865de85
EZ
1136 (add-text-properties
1137 text-beg (- text-end 1)
1138 '(mouse-face highlight
1139 help-echo "mouse-2: go to this invalidity"))
1598a961 1140 (put-text-property text-beg (- text-end 1)
52ab062c 1141 'occur-target tem)))))
710a0f53 1142 (goto-char prev-end))))
bdbd9606 1143 (with-current-buffer standard-output
003274a0
JPW
1144 (let ((no-matches (zerop num-matches)))
1145 (if no-matches
1146 (insert "None!\n"))
1147 (if (interactive-p)
f04232c3
JPW
1148 (message (cond (no-matches "No mismatches found")
1149 ((= num-matches 1) "1 mismatch found")
1150 (t "%d mismatches found"))
1151 num-matches)))))))
869bff31 1152
1153(defun tex-validate-region (start end)
1154 "Check for mismatched braces or $'s in region.
1155Returns t if no mismatches. Returns nil and moves point to suspect
1156area if a mismatch is found."
1157 (interactive "r")
1158 (let ((failure-point nil) (max-possible-sexps (- end start)))
1159 (save-excursion
1160 (condition-case ()
1161 (save-restriction
1162 (narrow-to-region start end)
2ed2806c 1163 ;; First check that the open and close parens balance in numbers.
869bff31 1164 (goto-char start)
e6b0b773 1165 (while (<= 0 (setq max-possible-sexps (1- max-possible-sexps)))
2ed2806c
KH
1166 (forward-sexp 1))
1167 ;; Now check that like matches like.
1168 (goto-char start)
1169 (while (progn (skip-syntax-forward "^(")
1170 (not (eobp)))
1171 (let ((match (matching-paren (following-char))))
1172 (save-excursion
1173 (forward-sexp 1)
1174 (or (= (preceding-char) match)
1175 (error "Mismatched parentheses"))))
1176 (forward-char 1)))
869bff31 1177 (error
bed1b0c8
RS
1178 (skip-syntax-forward " .>")
1179 (setq failure-point (point)))))
bdbd9606
SM
1180 (if failure-point (goto-char failure-point))
1181 (not failure-point)))
869bff31 1182
1183(defun tex-terminate-paragraph (inhibit-validation)
1184 "Insert two newlines, breaking a paragraph for TeX.
81c735c0 1185Check for mismatched braces or $s in paragraph being terminated.
869bff31 1186A prefix arg inhibits the checking."
528415e7 1187 (interactive "*P")
869bff31 1188 (or inhibit-validation
1189 (save-excursion
1190 (tex-validate-region
bed1b0c8
RS
1191 (save-excursion
1192 (search-backward "\n\n" nil 'move)
1193 (point))
1194 (point)))
869bff31 1195 (message "Paragraph being closed appears to contain a mismatch"))
1196 (insert "\n\n"))
1197
7afecb99 1198(define-skeleton tex-insert-braces
869bff31 1199 "Make a pair of braces and be poised to type inside of them."
7afecb99
SM
1200 nil
1201 ?\{ _ ?})
869bff31 1202
9bd4f69c
RS
1203;; This function is used as the value of fill-nobreak-predicate
1204;; in LaTeX mode. Its job is to prevent line-breaking inside
1205;; of a \verb construct.
1206(defun latex-fill-nobreak-predicate ()
7afecb99
SM
1207 (save-excursion
1208 (skip-chars-backward " ")
1209 ;; Don't break after \ since `\ ' has special meaning.
1210 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
1211 (let ((opoint (point))
1212 inside)
1213 (beginning-of-line)
1214 (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
1215 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
1216 (setq inside t)))
1217 inside))))
9bd4f69c 1218
53c4fe47
SM
1219(defvar latex-block-default "enumerate")
1220
8084f5d8
SM
1221(defvar latex-block-args-alist
1222 '(("array" nil ?\{ (skeleton-read "[options]: ") ?\})
1223 ("tabular" nil ?\{ (skeleton-read "[options]: ") ?\}))
1224 "Skeleton element to use for arguments to particular environments.
1225Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1226the name of the environment and SKEL-ELEM is an element to use in
1227a skeleton (see `skeleton-insert').")
1228
1229(defvar latex-block-body-alist
1230 '(("enumerate" nil '(latex-insert-item) > _)
1231 ("itemize" nil '(latex-insert-item) > _)
1232 ("table" nil "\\caption{" > - "}" > \n _)
1233 ("figure" nil > _ \n "\\caption{" > _ "}" >))
1234 "Skeleton element to use for the body of particular environments.
1235Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1236the name of the environment and SKEL-ELEM is an element to use in
1237a skeleton (see `skeleton-insert').")
1238
15ca8de7 1239;; Like tex-insert-braces, but for LaTeX.
7afecb99
SM
1240(defalias 'tex-latex-block 'latex-insert-block)
1241(define-skeleton latex-insert-block
8a591d52 1242 "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
869bff31 1243Puts point on a blank line between them."
53c4fe47
SM
1244 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1245 latex-block-default)
95a045bd 1246 (append latex-block-names
7afecb99 1247 latex-standard-block-names)
53c4fe47
SM
1248 nil nil nil nil latex-block-default)))
1249 (setq latex-block-default choice)
7afecb99 1250 (unless (or (member choice latex-standard-block-names)
53c4fe47
SM
1251 (member choice latex-block-names))
1252 ;; Remember new block names for later completion.
1253 (push choice latex-block-names))
1254 choice)
95a045bd 1255 \n "\\begin{" str "}"
8084f5d8
SM
1256 (cdr (assoc str latex-block-args-alist))
1257 > \n (or (cdr (assoc str latex-block-body-alist)) '(nil > _)) \n
95a045bd 1258 "\\end{" str "}" > \n)
53c4fe47 1259
ea590e1c
SM
1260(define-skeleton latex-insert-item
1261 "Insert a \item macro."
1262 nil
15ca8de7 1263 \n "\\item " >)
ea590e1c 1264
53c4fe47
SM
1265\f
1266;;;;
1267;;;; LaTeX syntax navigation
1268;;;;
869bff31 1269
5e56fb53
SM
1270(defmacro tex-search-noncomment (&rest body)
1271 "Execute BODY as long as it return non-nil and point is in a comment.
1272Return the value returned by the last execution of BODY."
1273 (declare (debug t))
1274 (let ((res-sym (make-symbol "result")))
1275 `(let (,res-sym)
1276 (while
1277 (and (setq ,res-sym (progn ,@body))
1278 (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
1279 ,res-sym)))
1280
869bff31 1281(defun tex-last-unended-begin ()
81c735c0 1282 "Leave point at the beginning of the last `\\begin{...}' that is unended."
95a045bd 1283 (condition-case nil
5e56fb53
SM
1284 (while (and (tex-search-noncomment
1285 (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
95a045bd
SM
1286 (looking-at "\\\\end"))
1287 (tex-last-unended-begin))
1288 (search-failed (error "Couldn't find unended \\begin"))))
869bff31 1289
53c4fe47
SM
1290(defun tex-next-unmatched-end ()
1291 "Leave point at the end of the next `\\end' that is unended."
5e56fb53
SM
1292 (while (and (tex-search-noncomment
1293 (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
ea590e1c
SM
1294 (save-excursion (goto-char (match-beginning 0))
1295 (looking-at "\\\\begin")))
53c4fe47
SM
1296 (tex-next-unmatched-end)))
1297
6a900cf1
ER
1298(defun tex-goto-last-unclosed-latex-block ()
1299 "Move point to the last unclosed \\begin{...}.
1300Mark is left at original location."
1301 (interactive)
1302 (let ((spot))
1303 (save-excursion
95a045bd 1304 (tex-last-unended-begin)
6a900cf1
ER
1305 (setq spot (point)))
1306 (push-mark)
1307 (goto-char spot)))
1308
53c4fe47
SM
1309(defun latex-backward-sexp-1 ()
1310 "Like (backward-sexp 1) but aware of multi-char elements."
1311 (let ((pos (point))
1312 (forward-sexp-function))
1313 (backward-sexp 1)
1314 (if (looking-at "\\\\begin\\>")
1315 (signal 'scan-error
1316 (list "Containing expression ends prematurely"
1317 (point) (prog1 (point) (goto-char pos))))
1318 (when (eq (char-after) ?{)
1319 (let ((newpos (point)))
1320 (when (ignore-errors (backward-sexp 1) t)
1321 (if (looking-at "\\\\end\\>")
1322 (tex-last-unended-begin)
1323 (goto-char newpos))))))))
1324
1325(defun latex-forward-sexp-1 ()
1326 "Like (forward-sexp 1) but aware of multi-char elements."
1327 (let ((pos (point))
1328 (forward-sexp-function))
1329 (forward-sexp 1)
1330 (let ((newpos (point)))
1331 (skip-syntax-backward "/w")
1332 (cond
1333 ((looking-at "\\\\end\\>")
1334 (signal 'scan-error
1335 (list "Containing expression ends prematurely"
1336 (point)
1337 (prog1
1338 (progn (ignore-errors (forward-sexp 2)) (point))
1339 (goto-char pos)))))
1340 ((looking-at "\\\\begin\\>")
1341 (goto-char (match-end 0))
1342 (tex-next-unmatched-end))
1343 (t (goto-char newpos))))))
1344
1345(defun latex-forward-sexp (&optional arg)
1346 "Like `forward-sexp' but aware of multi-char elements."
1347 (interactive "P")
1348 (unless arg (setq arg 1))
1349 (let ((pos (point)))
1350 (condition-case err
1351 (while (/= arg 0)
1352 (setq arg
1353 (if (> arg 0)
1354 (progn (latex-forward-sexp-1) (1- arg))
1355 (progn (latex-backward-sexp-1) (1+ arg)))))
1356 (scan-error
1357 (goto-char pos)
1358 (signal (car err) (cdr err))))))
1359
ea590e1c
SM
1360(defun latex-syntax-after ()
1361 "Like (char-syntax (char-after)) but aware of multi-char elements."
15ca8de7 1362 (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
ea590e1c
SM
1363
1364(defun latex-skip-close-parens ()
1365 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1366 (let ((forward-sexp-function nil))
1367 (while (progn (skip-syntax-forward " )")
1368 (looking-at "\\\\end\\>"))
1369 (forward-sexp 2))))
1370
1371(defun latex-down-list ()
1372 "Like (down-list 1) but aware of multi-char elements."
1373 (forward-comment (point-max))
1374 (let ((forward-sexp-function nil))
1375 (if (not (looking-at "\\\\begin\\>"))
1376 (down-list 1)
1377 (forward-sexp 1)
1378 ;; Skip arguments.
7afecb99
SM
1379 (while (looking-at "[ \t]*[[{(]")
1380 (with-syntax-table tex-mode-syntax-table
1381 (forward-sexp))))))
ea590e1c 1382
7afecb99
SM
1383(defalias 'tex-close-latex-block 'latex-close-block)
1384(define-skeleton latex-close-block
1385 "Create an \\end{...} to match the last unclosed \\begin{...}."
1386 (save-excursion
1387 (tex-last-unended-begin)
1388 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1389 (match-string 1)))
1390 \n "\\end" str > \n)
1391
1392(define-skeleton latex-split-block
1393 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1394 (save-excursion
1395 (tex-last-unended-begin)
1396 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1397 (prog1 (match-string 1)
1398 (goto-char (match-end 1))
1399 (setq v1 (buffer-substring (point)
1400 (progn
1401 (while (looking-at "[ \t]*[[{]")
1402 (forward-sexp 1))
1403 (point)))))))
1404 \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
15ca8de7
SM
1405
1406(defconst tex-discount-args-cmds
1407 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1408 "documentclass" "usepackage" "label")
1409 "TeX commands whose arguments should not be counted as text.")
1410
1411(defun tex-count-words (begin end)
1412 "Count the number of words in the buffer."
1413 (interactive
1414 (if (and transient-mark-mode mark-active)
1415 (list (region-beginning) (region-end))
1416 (list (point-min) (point-max))))
1417 ;; TODO: skip comments and math and maybe some environments.
1418 (save-excursion
1419 (goto-char begin)
1420 (let ((count 0))
1421 (while (and (< (point) end) (re-search-forward "\\<" end t))
1422 (if (not (eq (char-syntax (preceding-char)) ?/))
1423 (progn
1424 ;; Don't count single-char words.
1425 (unless (looking-at ".\\>") (incf count))
1426 (forward-char 1))
1427 (let ((cmd
1428 (buffer-substring-no-properties
1429 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1430 (forward-char 1))
1431 (point)))))
1432 (when (member cmd tex-discount-args-cmds)
1433 (skip-chars-forward "*")
1434 (forward-comment (point-max))
1435 (when (looking-at "\\[")
1436 (forward-sexp 1)
1437 (forward-comment (point-max)))
1438 (if (not (looking-at "{"))
1439 (forward-char 1)
1440 (forward-sexp 1))))))
1441 (message "%s words" count))))
b781e739
SS
1442
1443
869bff31 1444\f
1445;;; Invoking TeX in an inferior shell.
1446
15ca8de7
SM
1447;; Why use a shell instead of running TeX directly? Because if TeX
1448;; gets stuck, the user can switch to the shell window and type at it.
869bff31 1449
15ca8de7 1450;; The utility functions:
869bff31 1451
bdbd9606 1452(define-derived-mode tex-shell shell-mode "TeX-Shell"
3f2c97ea
SM
1453 (set (make-local-variable 'compilation-parse-errors-function)
1454 'tex-compilation-parse-errors)
bdbd9606
SM
1455 (compilation-shell-minor-mode t))
1456
d974af30 1457;;;###autoload
869bff31 1458(defun tex-start-shell ()
d6709b80
SM
1459 (with-current-buffer
1460 (make-comint
1461 "tex-shell"
07c16ec4 1462 (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
d6709b80 1463 nil)
528415e7
RS
1464 (let ((proc (get-process "tex-shell")))
1465 (set-process-sentinel proc 'tex-shell-sentinel)
003274a0 1466 (set-process-query-on-exit-flag proc nil)
bdbd9606 1467 (tex-shell)
528415e7 1468 (while (zerop (buffer-size))
51b2c841
RS
1469 (sleep-for 1)))))
1470
033306e3
RS
1471(defun tex-feed-input ()
1472 "Send input to the tex shell process.
1473In the tex buffer this can be used to continue an interactive tex run.
bed1b0c8 1474In the tex shell buffer this command behaves like `comint-send-input'."
033306e3 1475 (interactive)
b781e739 1476 (set-buffer (tex-shell-buf))
033306e3
RS
1477 (comint-send-input)
1478 (tex-recenter-output-buffer nil))
1479
51b2c841
RS
1480(defun tex-display-shell ()
1481 "Make the TeX shell buffer visible in a window."
b781e739 1482 (display-buffer (tex-shell-buf))
51b2c841 1483 (tex-recenter-output-buffer nil))
528415e7
RS
1484
1485(defun tex-shell-sentinel (proc msg)
1486 (cond ((null (buffer-name (process-buffer proc)))
1487 ;; buffer killed
1488 (set-process-buffer proc nil)
1489 (tex-delete-last-temp-files))
1490 ((memq (process-status proc) '(signal exit))
1491 (tex-delete-last-temp-files))))
1492
1493(defun tex-set-buffer-directory (buffer directory)
869bff31 1494 "Set BUFFER's default directory to be DIRECTORY."
1495 (setq directory (file-name-as-directory (expand-file-name directory)))
1496 (if (not (file-directory-p directory))
1497 (error "%s is not a directory" directory)
1498 (save-excursion
1499 (set-buffer buffer)
1500 (setq default-directory directory))))
1501
30803a05
RS
1502(defvar tex-send-command-modified-tick 0)
1503(make-variable-buffer-local 'tex-send-command-modified-tick)
1504
bdbd9606 1505(defun tex-shell-proc ()
b781e739 1506 (or (tex-shell-running) (error "No TeX subprocess")))
bdbd9606
SM
1507(defun tex-shell-buf ()
1508 (process-buffer (tex-shell-proc)))
b781e739
SS
1509(defun tex-shell-buf-no-error ()
1510 (let ((proc (tex-shell-running)))
1511 (and proc (process-buffer proc))))
bdbd9606 1512
528415e7 1513(defun tex-send-command (command &optional file background)
4cdc1d4b 1514 "Send COMMAND to TeX shell process, substituting optional FILE for *.
8241d7b9
ER
1515Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1516FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1517substitution will be made in COMMAND. COMMAND can be any expression that
460e1b7d
RS
1518evaluates to a command string.
1519
1520Return the process in which TeX is running."
528415e7
RS
1521 (save-excursion
1522 (let* ((cmd (eval command))
bdbd9606 1523 (proc (tex-shell-proc))
64db2461 1524 (buf (process-buffer proc))
4f45adda 1525 (star (string-match "\\*" cmd))
4cdc1d4b
RS
1526 (string
1527 (concat
1528 (if file
1529 (if star (concat (substring cmd 0 star)
1530 file (substring cmd (1+ star)))
1531 (concat cmd " " file))
1532 cmd)
1533 (if background "&" ""))))
64db2461
RS
1534 ;; Switch to buffer before checking for subproc output in it.
1535 (set-buffer buf)
30803a05
RS
1536 ;; If text is unchanged since previous tex-send-command,
1537 ;; we haven't got any output. So wait for output now.
64db2461 1538 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
30803a05 1539 (accept-process-output proc))
4cdc1d4b
RS
1540 (goto-char (process-mark proc))
1541 (insert string)
30803a05 1542 (comint-send-input)
460e1b7d
RS
1543 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1544 proc)))
528415e7 1545
a15849cb
RS
1546(defun tex-delete-last-temp-files (&optional not-all)
1547 "Delete any junk files from last temp file.
1548If NOT-ALL is non-nil, save the `.dvi' file."
528415e7
RS
1549 (if tex-last-temp-file
1550 (let* ((dir (file-name-directory tex-last-temp-file))
adf6b7f9
KH
1551 (list (and (file-directory-p dir)
1552 (file-name-all-completions
02fd229c
RS
1553 (file-name-sans-extension
1554 (file-name-nondirectory tex-last-temp-file))
1555 dir))))
adf6b7f9 1556 (while list
a15849cb
RS
1557 (if not-all
1558 (and
1559 ;; If arg is non-nil, don't delete the .dvi file.
1560 (not (string-match "\\.dvi$" (car list)))
1561 (delete-file (concat dir (car list))))
1562 (delete-file (concat dir (car list))))
528415e7
RS
1563 (setq list (cdr list))))))
1564
99621a14 1565(add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
869bff31 1566
75035a80
SM
1567;;
1568;; Machinery to guess the command that the user wants to execute.
1569;;
1570
1571(defvar tex-compile-history nil)
1572
1573(defvar tex-input-files-re
1574 (eval-when-compile
1575 (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
1576 "bbl" "ind" "sty" "cls") t)
1577 ;; Include files with no dots (for directories).
1578 "\\'\\|\\`[^.]+\\'")))
1579
1580(defcustom tex-use-reftex t
1581 "If non-nil, use RefTeX's list of files to determine what command to use."
1582 :type 'boolean)
1583
1584(defvar tex-compile-commands
1585 '(((concat "pdf" tex-command
bf4ec222
SM
1586 " " (if (< 0 (length tex-start-commands))
1587 (shell-quote-argument tex-start-commands)) " %f")
75035a80
SM
1588 t "%r.pdf")
1589 ((concat tex-command
bf4ec222
SM
1590 " " (if (< 0 (length tex-start-commands))
1591 (shell-quote-argument tex-start-commands)) " %f")
75035a80 1592 t "%r.dvi")
e70ff1af 1593 ("yap %r &" "%r.dvi")
75035a80
SM
1594 ("xdvi %r &" "%r.dvi")
1595 ("advi %r &" "%r.dvi")
1596 ("bibtex %r" "%r.aux" "%r.bbl")
1597 ("makeindex %r" "%r.idx" "%r.ind")
1598 ("texindex %r.??")
1599 ("dvipdfm %r" "%r.dvi" "%r.pdf")
1600 ("dvipdf %r" "%r.dvi" "%r.pdf")
1601 ("dvips %r" "%r.dvi" "%r.ps")
e70ff1af 1602 ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
75035a80
SM
1603 ("gv %r.ps &" "%r.ps")
1604 ("gv %r.pdf &" "%r.pdf")
1605 ("xpdf %r.pdf &" "%r.pdf")
1606 ("lpr %r.ps" "%r.ps"))
1607 "List of commands for `tex-compile'.
1608Each element should be of the form (FORMAT IN OUT) where
1609FORMAT is an expression that evaluates to a string that can contain
1610 - `%r' the main file name without extension.
1611 - `%f' the main file name.
1612IN can be either a string (with the same % escapes in it) indicating
1613 the name of the input file, or t to indicate that the input is all
1614 the TeX files of the document, or nil if we don't know.
1615OUT describes the output file and is either a %-escaped string
1616 or nil to indicate that there is no output file.")
1617
8084f5d8
SM
1618;; defsubst* gives better byte-code than defsubst.
1619(defsubst* tex-string-prefix-p (str1 str2)
1620 "Return non-nil if STR1 is a prefix of STR2"
1621 (eq t (compare-strings str2 nil (length str1) str1 nil nil)))
1622
dd459839
SM
1623(defun tex-guess-main-file (&optional all)
1624 "Find a likely `tex-main-file'.
1625Looks for hints in other buffers in the same directory or in
8084f5d8
SM
1626ALL other buffers. If ALL is `sub' only look at buffers in parent directories
1627of the current buffer."
dd459839
SM
1628 (let ((dir default-directory)
1629 (header-re tex-start-of-header))
1630 (catch 'found
1631 ;; Look for a buffer with `tex-main-file' set.
1632 (dolist (buf (if (consp all) all (buffer-list)))
1633 (with-current-buffer buf
8084f5d8
SM
1634 (when (and (cond
1635 ((null all) (equal dir default-directory))
1636 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1637 (t))
dd459839
SM
1638 (stringp tex-main-file))
1639 (throw 'found (expand-file-name tex-main-file)))))
1640 ;; Look for a buffer containing the magic `tex-start-of-header'.
1641 (dolist (buf (if (consp all) all (buffer-list)))
1642 (with-current-buffer buf
8084f5d8
SM
1643 (when (and (cond
1644 ((null all) (equal dir default-directory))
1645 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1646 (t))
dd459839
SM
1647 buffer-file-name
1648 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1649 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1650 (save-excursion
cb30255a
SM
1651 (save-restriction
1652 (widen)
1653 (goto-char (point-min))
95a045bd
SM
1654 (re-search-forward
1655 header-re (+ (point) 10000) t))))
dd459839
SM
1656 (throw 'found (expand-file-name buffer-file-name))))))))
1657
07c16ec4
SM
1658(defun tex-main-file ()
1659 "Return the relative name of the main file."
bdbd9606
SM
1660 (let* ((file (or tex-main-file
1661 ;; Compatibility with AUCTeX.
96c0d9e9
RS
1662 (with-no-warnings
1663 (when (and (boundp 'TeX-master) (stringp TeX-master))
1664 (make-local-variable 'tex-main-file)
1665 (setq tex-main-file TeX-master)))
bdbd9606
SM
1666 ;; Try to guess the main file.
1667 (if (not buffer-file-name)
1668 (error "Buffer is not associated with any file")
1669 (file-relative-name
1670 (if (save-excursion
1671 (goto-char (point-min))
95a045bd
SM
1672 (re-search-forward tex-start-of-header
1673 (+ (point) 10000) t))
bdbd9606
SM
1674 ;; This is the main file.
1675 buffer-file-name
1676 ;; This isn't the main file, let's try to find better,
1677 (or (tex-guess-main-file)
8084f5d8 1678 (tex-guess-main-file 'sub)
bdbd9606 1679 ;; (tex-guess-main-file t)
07c16ec4 1680 buffer-file-name)))))))
e70ff1af
SM
1681 (if (or (file-exists-p file) (string-match "\\.tex\\'" file))
1682 file (concat file ".tex"))))
dd459839 1683
75035a80
SM
1684(defun tex-summarize-command (cmd)
1685 (if (not (stringp cmd)) ""
1686 (mapconcat 'identity
1687 (mapcar (lambda (s) (car (split-string s)))
1688 (split-string cmd "\\s-*\\(?:;\\|&&\\)\\s-*"))
1689 "&")))
1690
1691(defun tex-uptodate-p (file)
1692 "Return non-nil if FILE is not uptodate w.r.t the document source files.
1693FILE is typically the output DVI or PDF file."
1694 ;; We should check all the files included !!!
1695 (and
1696 ;; Clearly, the target must exist.
1697 (file-exists-p file)
1698 ;; And the last run must not have asked for a rerun.
1699 ;; FIXME: this should check that the last run was done on the same file.
1700 (let ((buf (condition-case nil (tex-shell-buf) (error nil))))
1701 (when buf
1702 (with-current-buffer buf
1703 (save-excursion
1704 (goto-char (point-max))
1705 (and (re-search-backward
1706 "(see the transcript file for additional information)" nil t)
1707 (> (save-excursion
1708 (or (re-search-backward "\\[[0-9]+\\]" nil t)
1709 (point-min)))
1710 (save-excursion
1711 (or (re-search-backward "Rerun" nil t)
1712 (point-min)))))))))
1713 ;; And the input files must not have been changed in the meantime.
1714 (let ((files (if (and tex-use-reftex
1715 (fboundp 'reftex-scanning-info-available-p)
1716 (reftex-scanning-info-available-p))
1717 (reftex-all-document-files)
1718 (list (file-name-directory (expand-file-name file)))))
1719 (ignored-dirs-re
1720 (concat
1721 (regexp-opt
1722 (delq nil (mapcar (lambda (s) (if (eq (aref s (1- (length s))) ?/)
1723 (substring s 0 (1- (length s)))))
1724 completion-ignored-extensions))
1725 t) "\\'"))
1726 (uptodate t))
1727 (while (and files uptodate)
1728 (let ((f (pop files)))
e70ff1af
SM
1729 (if (and (file-directory-p f)
1730 ;; Avoid infinite loops.
1731 (not (file-symlink-p f)))
75035a80
SM
1732 (unless (string-match ignored-dirs-re f)
1733 (setq files (nconc
1734 (directory-files f t tex-input-files-re)
1735 files)))
1736 (when (file-newer-than-file-p f file)
1737 (setq uptodate nil)))))
1738 uptodate)))
1739
1740
1741(autoload 'format-spec "format-spec")
1742
1743(defvar tex-executable-cache nil)
1744(defun tex-executable-exists-p (name)
1745 "Like `executable-find' but with a cache."
1746 (let ((cache (assoc name tex-executable-cache)))
1747 (if cache (cdr cache)
1748 (let ((executable (executable-find name)))
1749 (push (cons name executable) tex-executable-cache)
1750 executable))))
1751
1752(defun tex-command-executable (cmd)
1753 (let ((s (if (stringp cmd) cmd (eval (car cmd)))))
1754 (substring s 0 (string-match "[ \t]\\|\\'" s))))
1755
1756(defun tex-command-active-p (cmd fspec)
1757 "Return non-nil if the CMD spec might need to be run."
1758 (let ((in (nth 1 cmd))
1759 (out (nth 2 cmd)))
1760 (if (stringp in)
1761 (let ((file (format-spec in fspec)))
1762 (when (file-exists-p file)
1763 (or (not out)
1764 (file-newer-than-file-p
1765 file (format-spec out fspec)))))
1766 (when (and (eq in t) (stringp out))
1767 (not (tex-uptodate-p (format-spec out fspec)))))))
1768
8084f5d8
SM
1769(defun tex-compile-default (fspec)
1770 "Guess a default command given the format-spec FSPEC."
75035a80
SM
1771 ;; TODO: Learn to do latex+dvips!
1772 (let ((cmds nil)
1773 (unchanged-in nil))
1774 ;; Only consider active commands.
1775 (dolist (cmd tex-compile-commands)
1776 (when (tex-executable-exists-p (tex-command-executable cmd))
1777 (if (tex-command-active-p cmd fspec)
1778 (push cmd cmds)
1779 (push (nth 1 cmd) unchanged-in))))
1780 ;; Remove those commands whose input was considered stable for
1781 ;; some other command (typically if (t . "%.pdf") is inactive
1782 ;; then we're using pdflatex and the fact that the dvi file
1783 ;; is inexistent doesn't matter).
1784 (let ((tmp nil))
1785 (dolist (cmd cmds)
1786 (unless (member (nth 1 cmd) unchanged-in)
1787 (push cmd tmp)))
8084f5d8 1788 ;; Only remove if there's something left.
75035a80 1789 (if tmp (setq cmds tmp)))
8084f5d8
SM
1790 ;; Remove commands whose input is not uptodate either.
1791 (let ((outs (delq nil (mapcar (lambda (x) (nth 2 x)) cmds)))
1792 (tmp nil))
1793 (dolist (cmd cmds)
75035a80 1794 (unless (member (nth 1 cmd) outs)
8084f5d8
SM
1795 (push cmd tmp)))
1796 ;; Only remove if there's something left.
1797 (if tmp (setq cmds tmp)))
75035a80
SM
1798 ;; Select which file we're going to operate on (the latest).
1799 (let ((latest (nth 1 (car cmds))))
1800 (dolist (cmd (prog1 (cdr cmds) (setq cmds (list (car cmds)))))
1801 (if (equal latest (nth 1 cmd))
1802 (push cmd cmds)
1803 (unless (eq latest t) ;Can't beat that!
1804 (if (or (not (stringp latest))
1805 (eq (nth 1 cmd) t)
1806 (and (stringp (nth 1 cmd))
1807 (file-newer-than-file-p
1808 (format-spec (nth 1 cmd) fspec)
1809 (format-spec latest fspec))))
1810 (setq latest (nth 1 cmd) cmds (list cmd)))))))
1811 ;; Expand the command spec into the actual text.
1812 (dolist (cmd (prog1 cmds (setq cmds nil)))
1813 (push (cons (eval (car cmd)) (cdr cmd)) cmds))
1814 ;; Select the favorite command from the history.
1815 (let ((hist tex-compile-history)
8084f5d8 1816 re hist-cmd)
75035a80 1817 (while hist
8084f5d8 1818 (setq hist-cmd (pop hist))
75035a80 1819 (setq re (concat "\\`"
8084f5d8 1820 (regexp-quote (tex-command-executable hist-cmd))
75035a80
SM
1821 "\\([ \t]\\|\\'\\)"))
1822 (dolist (cmd cmds)
8084f5d8
SM
1823 ;; If the hist entry uses the same command and applies to a file
1824 ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
1825 (and (string-match re (car cmd))
1826 (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd)))
1827 (string-match (regexp-quote (match-string 1 (car cmd)))
1828 hist-cmd))
1829 (setq hist nil cmds (list cmd)))))
1830 ;; Substitute and return.
1831 (if (and hist-cmd
1832 (string-match (concat "[' \t\"]" (format-spec "%r" fspec)
1833 "\\([;&' \t\"]\\|\\'\\)") hist-cmd))
1834 ;; The history command was already applied to the same file,
1835 ;; so just reuse it.
1836 hist-cmd
1837 (if cmds (format-spec (caar cmds) fspec))))))
75035a80
SM
1838
1839(defun tex-compile (dir cmd)
1840 "Run a command CMD on current TeX buffer's file in DIR."
1841 ;; FIXME: Use time-stamps on files to decide the next op.
1842 (interactive
1843 (let* ((file (tex-main-file))
5e56fb53
SM
1844 (default-directory
1845 (prog1 (file-name-directory (expand-file-name file))
1846 (setq file (file-name-nondirectory file))))
75035a80 1847 (root (file-name-sans-extension file))
75035a80
SM
1848 (fspec (list (cons ?r (comint-quote-filename root))
1849 (cons ?f (comint-quote-filename file))))
8084f5d8 1850 (default (tex-compile-default fspec)))
5e56fb53 1851 (list default-directory
75035a80
SM
1852 (completing-read
1853 (format "Command [%s]: " (tex-summarize-command default))
1854 (mapcar (lambda (x)
1855 (list (format-spec (eval (car x)) fspec)))
1856 tex-compile-commands)
1857 nil nil nil 'tex-compile-history default))))
1858 (save-some-buffers (not compilation-ask-about-save) nil)
1859 (if (tex-shell-running)
1860 (tex-kill-job)
1861 (tex-start-shell))
1862 (tex-send-tex-command cmd dir))
d6709b80
SM
1863
1864(defun tex-start-tex (command file &optional dir)
460e1b7d 1865 "Start a TeX run, using COMMAND on FILE."
6633b891 1866 (let* ((star (string-match "\\*" command))
460e1b7d 1867 (compile-command
6633b891
KH
1868 (if star
1869 (concat (substring command 0 star)
1870 (comint-quote-filename file)
1871 (substring command (1+ star)))
1872 (concat command " "
95a045bd 1873 tex-start-options
9e0ad27a 1874 (if (< 0 (length tex-start-commands))
c3ce7bf4 1875 (concat
9e0ad27a 1876 (shell-quote-argument tex-start-commands) " "))
6633b891 1877 (comint-quote-filename file)))))
bdbd9606
SM
1878 (tex-send-tex-command compile-command dir)))
1879
1880(defun tex-send-tex-command (cmd &optional dir)
b781e739
SS
1881 (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
1882 (and buf (with-current-buffer buf
1883 default-directory))))
bdbd9606
SM
1884 (not dir))
1885 (let (shell-dirtrack-verbose)
1886 (tex-send-command tex-shell-cd-command dir)))
1887 (with-current-buffer (process-buffer (tex-send-command cmd))
bdbd9606
SM
1888 (setq compilation-last-buffer (current-buffer))
1889 (compilation-forget-errors)
1598a961 1890 ;; Don't parse previous compilations.
bdbd9606
SM
1891 (set-marker compilation-parsing-end (1- (point-max))))
1892 (tex-display-shell)
1893 (setq tex-last-buffer-texed (current-buffer)))
460e1b7d 1894\f
1598a961
SM
1895(defvar tex-error-parse-syntax-table
1896 (let ((st (make-syntax-table)))
1897 (modify-syntax-entry ?\( "()" st)
1898 (modify-syntax-entry ?\) ")(" st)
1899 (modify-syntax-entry ?\\ "\\" st)
1900 (modify-syntax-entry ?\{ "_" st)
1901 (modify-syntax-entry ?\} "_" st)
1902 (modify-syntax-entry ?\[ "_" st)
1903 (modify-syntax-entry ?\] "_" st)
1904 ;; Single quotations may appear in errors
1905 (modify-syntax-entry ?\" "_" st)
1906 st)
1907 "Syntax-table used while parsing TeX error messages.")
1908
460e1b7d 1909(defun tex-compilation-parse-errors (limit-search find-at-least)
f05bd645
RS
1910 "Parse the current buffer as TeX error messages.
1911See the variable `compilation-parse-errors-function' for the interface it uses.
1912
1913This function parses only the last TeX compilation.
1914It works on TeX compilations only. It is necessary for that purpose,
1915since TeX does not put file names and line numbers on the same line as
1916for the error messages."
460e1b7d
RS
1917 (require 'thingatpt)
1918 (setq compilation-error-list nil)
1919 (message "Parsing error messages...")
f05bd645
RS
1920 (let ((default-directory ; Perhaps dir has changed meanwhile.
1921 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
f05bd645
RS
1922 found-desired (num-errors-found 0)
1923 last-filename last-linenum last-position
1924 begin-of-error end-of-error)
f05bd645
RS
1925 ;; Don't reparse messages already seen at last parse.
1926 (goto-char compilation-parsing-end)
1927 ;; Parse messages.
1928 (while (and (not (or found-desired (eobp)))
1929 (prog1 (re-search-forward "^! " nil 'move)
1930 (setq begin-of-error (match-beginning 0)
1931 end-of-error (match-end 0)))
1932 (re-search-forward
1933 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
3f2c97ea 1934 (let* ((this-error (copy-marker begin-of-error))
003274a0 1935 (linenum (string-to-number (match-string 1)))
f05bd645
RS
1936 (error-text (regexp-quote (match-string 3)))
1937 (filename
1938 (save-excursion
ea590e1c
SM
1939 (with-syntax-table tex-error-parse-syntax-table
1940 (backward-up-list 1)
1941 (skip-syntax-forward "(_")
1942 (while (not (file-readable-p (thing-at-point 'filename)))
1943 (skip-syntax-backward "(_")
1944 (backward-up-list 1)
1945 (skip-syntax-forward "(_"))
1946 (thing-at-point 'filename))))
f05bd645
RS
1947 (new-file
1948 (or (null last-filename)
1949 (not (string-equal last-filename filename))))
1950 (error-location
cc9f5376
SM
1951 (with-current-buffer
1952 (if (equal filename (concat tex-zap-file ".tex"))
1953 tex-last-buffer-texed
1954 (find-file-noselect filename))
1955 (save-excursion
1956 (if new-file
1957 (progn (goto-line linenum) (setq last-position nil))
1958 (goto-char last-position)
1959 (forward-line (- linenum last-linenum)))
1960 ;; first try a forward search for the error text,
1961 ;; then a backward search limited by the last error.
1962 (let ((starting-point (point)))
1963 (or (re-search-forward error-text nil t)
1964 (re-search-backward error-text last-position t)
1965 (goto-char starting-point)))
1966 (point-marker)))))
f05bd645
RS
1967 (goto-char this-error)
1968 (if (and compilation-error-list
1969 (or (and find-at-least
1970 (>= num-errors-found
1971 find-at-least))
1972 (and limit-search
1973 (>= end-of-error limit-search)))
1974 new-file)
1975 (setq found-desired t)
1976 (setq num-errors-found (1+ num-errors-found)
1977 last-filename filename
1978 last-linenum linenum
1979 last-position error-location
1980 compilation-error-list ; Add the new error
1981 (cons (cons this-error error-location)
1982 compilation-error-list))
1983 (goto-char end-of-error)))))
ee13a145 1984 (set-marker compilation-parsing-end (point))
f05bd645 1985 (setq compilation-error-list (nreverse compilation-error-list))
460e1b7d
RS
1986 (message "Parsing error messages...done"))
1987\f
528415e7 1988;;; The commands:
869bff31 1989
1990(defun tex-region (beg end)
1991 "Run TeX on the current region, via a temporary file.
1992The file's name comes from the variable `tex-zap-file' and the
1993variable `tex-directory' says where to put it.
1994
1995If the buffer has a header, the header is given to TeX before the
1996region itself. The buffer's header is all lines between the strings
1997defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
1998The header must start in the first 100 lines of the buffer.
1999
2000The value of `tex-trailer' is given to TeX as input after the region.
2001
2002The value of `tex-command' specifies the command to use to run TeX."
2003 (interactive "r")
2004 (if (tex-shell-running)
2005 (tex-kill-job)
2006 (tex-start-shell))
2007 (or tex-zap-file
2008 (setq tex-zap-file (tex-generate-zap-file-name)))
6d34c59f
RS
2009 ;; Temp file will be written and TeX will be run in zap-directory.
2010 ;; If the TEXINPUTS file has relative directories or if the region has
2011 ;; \input of files, this must be the same directory as the file for
2012 ;; TeX to access the correct inputs. That's why it's safest if
2013 ;; tex-directory is ".".
2014 (let* ((zap-directory
528415e7 2015 (file-name-as-directory (expand-file-name tex-directory)))
d6709b80
SM
2016 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
2017 zap-directory)))
0d548e5d
RS
2018 ;; Don't delete temp files if we do the same buffer twice in a row.
2019 (or (eq (current-buffer) tex-last-buffer-texed)
2020 (tex-delete-last-temp-files t))
869bff31 2021 ;; Write the new temp file.
2022 (save-excursion
2023 (save-restriction
2024 (widen)
2025 (goto-char (point-min))
2026 (forward-line 100)
2027 (let ((search-end (point))
6d34c59f
RS
2028 (default-directory zap-directory)
2029 (already-output 0))
869bff31 2030 (goto-char (point-min))
6d34c59f 2031
725b7428
RS
2032 ;; Maybe copy first line, such as `\input texinfo', to temp file.
2033 (and tex-first-line-header-regexp
2034 (looking-at tex-first-line-header-regexp)
bed1b0c8 2035 (write-region (point)
6d34c59f
RS
2036 (progn (forward-line 1)
2037 (setq already-output (point)))
725b7428
RS
2038 tex-out-file nil nil))
2039
6d34c59f
RS
2040 ;; Write out the header, if there is one,
2041 ;; and any of the specified region which extends before it.
2042 ;; But don't repeat anything already written.
898b9ac1 2043 (if (re-search-forward tex-start-of-header search-end t)
6d34c59f 2044 (let (hbeg)
869bff31 2045 (beginning-of-line)
2046 (setq hbeg (point)) ;mark beginning of header
898b9ac1 2047 (if (re-search-forward tex-end-of-header nil t)
6d34c59f
RS
2048 (let (hend)
2049 (forward-line 1)
bed1b0c8 2050 (setq hend (point)) ;mark end of header
6d34c59f
RS
2051 (write-region (max (min hbeg beg) already-output)
2052 hend
2053 tex-out-file
2054 (not (zerop already-output)) nil)
2055 (setq already-output hend)))))
2056
2057 ;; Write out the specified region
2058 ;; (but don't repeat anything already written).
2059 (write-region (max beg already-output) end
2060 tex-out-file
2061 (not (zerop already-output)) nil))
2062 ;; Write the trailer, if any.
2063 ;; Precede it with a newline to make sure it
2064 ;; is not hidden in a comment.
2065 (if tex-trailer
2066 (write-region (concat "\n" tex-trailer) nil
2067 tex-out-file t nil))))
528415e7
RS
2068 ;; Record the file name to be deleted afterward.
2069 (setq tex-last-temp-file tex-out-file)
f05bd645
RS
2070 ;; Use a relative file name here because (1) the proper dir
2071 ;; is already current, and (2) the abs file name is sometimes
2072 ;; too long and can make tex crash.
d6709b80
SM
2073 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
2074 (setq tex-print-file tex-out-file)))
869bff31 2075
2076(defun tex-buffer ()
2077 "Run TeX on current buffer. See \\[tex-region] for more information.
528415e7
RS
2078Does not save the buffer, so it's useful for trying experimental versions.
2079See \\[tex-file] for an alternative."
869bff31 2080 (interactive)
2081 (tex-region (point-min) (point-max)))
2082
2083(defun tex-file ()
2084 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
2085This function is more useful than \\[tex-buffer] when you need the
2086`.aux' file of LaTeX to have the correct name."
2087 (interactive)
7abc9add
SS
2088 (when tex-offer-save
2089 (save-some-buffers))
d6709b80 2090 (let* ((source-file (tex-main-file))
07c16ec4 2091 (file-dir (file-name-directory (expand-file-name source-file))))
869bff31 2092 (if (tex-shell-running)
2093 (tex-kill-job)
2094 (tex-start-shell))
d6709b80 2095 (tex-start-tex tex-command source-file file-dir)
f05bd645 2096 (setq tex-print-file (expand-file-name source-file))))
869bff31 2097
2098(defun tex-generate-zap-file-name ()
2099 "Generate a unique name suitable for use as a file name."
2100 ;; Include the shell process number and host name
2101 ;; in case there are multiple shells (for same or different user).
f5cdb851
KH
2102 ;; Dec 1998: There is a report that some versions of xdvi
2103 ;; don't work with file names that start with #.
5616ee46 2104 (format "_TZ_%d-%s"
869bff31 2105 (process-id (get-buffer-process "*tex-shell*"))
07c16ec4 2106 (subst-char-in-string ?. ?- (system-name))))
869bff31 2107
2108;; This will perhaps be useful for modifying TEXINPUTS.
2109;; Expand each file name, separated by colons, in the string S.
2110(defun tex-expand-files (s)
2111 (let (elts (start 0))
2112 (while (string-match ":" s start)
2113 (setq elts (cons (substring s start (match-beginning 0)) elts))
2114 (setq start (match-end 0)))
2115 (or (= start 0)
2116 (setq elts (cons (substring s start) elts)))
c0df1972
SM
2117 (mapconcat (lambda (elt)
2118 (if (= (length elt) 0) elt (expand-file-name elt)))
5616ee46 2119 (nreverse elts) ":")))
869bff31 2120
2121(defun tex-shell-running ()
713f7b15 2122 (let ((proc (get-process "tex-shell")))
b781e739
SS
2123 (when proc
2124 (if (and (eq (process-status proc) 'run)
2125 (buffer-live-p (process-buffer proc)))
2126 ;; return the TeX process on success
2127 proc
2128 ;; get rid of the process permanently
2129 ;; this should get rid of the annoying w32 problem with
2130 ;; dead tex-shell buffer and live process
2131 (delete-process proc)))))
869bff31 2132
2133(defun tex-kill-job ()
2134 "Kill the currently running TeX job."
2135 (interactive)
b781e739 2136 ;; `quit-process' leads to core dumps of the tex process (except if
bed1b0c8
RS
2137 ;; coredumpsize has limit 0kb as on many environments). One would
2138 ;; like to use (kill-process proc 'lambda), however that construct
2139 ;; does not work on some systems and kills the shell itself.
b781e739
SS
2140 (let ((proc (get-process "tex-shell")))
2141 (when proc (quit-process proc t))))
869bff31 2142
2143(defun tex-recenter-output-buffer (linenum)
2144 "Redisplay buffer of TeX job output so that most recent output can be seen.
2145The last line of the buffer is displayed on
2146line LINE of the window, or centered if LINE is nil."
2147 (interactive "P")
2148 (let ((tex-shell (get-buffer "*tex-shell*"))
23b64225 2149 (window))
869bff31 2150 (if (null tex-shell)
2151 (message "No TeX output buffer")
23b64225
RS
2152 (setq window (display-buffer tex-shell))
2153 (save-selected-window
2154 (select-window window)
2155 (bury-buffer tex-shell)
2156 (goto-char (point-max))
2157 (recenter (if linenum
2158 (prefix-numeric-value linenum)
2159 (/ (window-height) 2)))))))
869bff31 2160
528415e7 2161(defun tex-print (&optional alt)
869bff31 2162 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1433a222
CZ
2163Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
2164is provided, use the alternative command, `tex-alt-dvi-print-command'."
528415e7 2165 (interactive "P")
869bff31 2166 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
2167 test-name)
2168 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
45c3304d
RS
2169 (buffer-file-name)
2170 ;; Check that this buffer's printed file is up to date.
869bff31 2171 (file-newer-than-file-p
2172 (setq test-name (tex-append (buffer-file-name) ".dvi"))
45c3304d 2173 (buffer-file-name)))
869bff31 2174 (setq print-file-name-dvi test-name))
528415e7
RS
2175 (if (not (file-exists-p print-file-name-dvi))
2176 (error "No appropriate `.dvi' file could be found")
460e1b7d
RS
2177 (if (tex-shell-running)
2178 (tex-kill-job)
2179 (tex-start-shell))
528415e7 2180 (tex-send-command
bed1b0c8 2181 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
602503c5
RS
2182 (shell-quote-argument
2183 print-file-name-dvi)
2184 t))))
869bff31 2185
cf6d6e8a
RS
2186(defun tex-alt-print ()
2187 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
002b0d00 2188Runs the shell command defined by `tex-alt-dvi-print-command'."
cf6d6e8a
RS
2189 (interactive)
2190 (tex-print t))
2191
869bff31 2192(defun tex-view ()
2193 "Preview the last `.dvi' file made by running TeX under Emacs.
2194This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2b7971c9
RS
2195The variable `tex-dvi-view-command' specifies the shell command for preview.
2196You must set that variable yourself before using this command,
2197because there is no standard value that would generally work."
869bff31 2198 (interactive)
2b7971c9
RS
2199 (or tex-dvi-view-command
2200 (error "You must set `tex-dvi-view-command'"))
746c30e2 2201 (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
869bff31 2202 (tex-print)))
2203
2204(defun tex-append (file-name suffix)
2205 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
cf6d6e8a 2206Pascal-based TeX scans for the first period, C TeX uses the last.
869bff31 2207No period is retained immediately before SUFFIX,
2208so normally SUFFIX starts with one."
2209 (if (stringp file-name)
cf6d6e8a
RS
2210 (let ((file (file-name-nondirectory file-name))
2211 trial-name)
6da9bbd6 2212 ;; Try splitting on last period.
7d0ca249
RS
2213 ;; The first-period split can get fooled when two files
2214 ;; named a.tex and a.b.tex are both tex'd;
2215 ;; the last-period split must be right if it matches at all.
cf6d6e8a
RS
2216 (setq trial-name
2217 (concat (file-name-directory file-name)
2218 (substring file 0
7d0ca249 2219 (string-match "\\.[^.]*$" file))
cf6d6e8a
RS
2220 suffix))
2221 (if (or (file-exists-p trial-name)
2222 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
2223 trial-name
7d0ca249 2224 ;; Not found, so split on first period.
cf6d6e8a
RS
2225 (concat (file-name-directory file-name)
2226 (substring file 0
7d0ca249 2227 (string-match "\\." file))
cf6d6e8a 2228 suffix)))
869bff31 2229 " "))
2230
2231(defun tex-show-print-queue ()
2232 "Show the print queue that \\[tex-print] put your job on.
1433a222 2233Runs the shell command defined by `tex-show-queue-command'."
869bff31 2234 (interactive)
2235 (if (tex-shell-running)
2236 (tex-kill-job)
2237 (tex-start-shell))
51b2c841
RS
2238 (tex-send-command tex-show-queue-command)
2239 (tex-display-shell))
869bff31 2240
2241(defun tex-bibtex-file ()
2242 "Run BibTeX on the current buffer's file."
2243 (interactive)
2244 (if (tex-shell-running)
2245 (tex-kill-job)
2246 (tex-start-shell))
e6b0b773
MR
2247 (let (shell-dirtrack-verbose
2248 (tex-out-file
869bff31 2249 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
2250 (file-dir (file-name-directory (buffer-file-name))))
528415e7 2251 (tex-send-command tex-shell-cd-command file-dir)
51b2c841
RS
2252 (tex-send-command tex-bibtex-command tex-out-file))
2253 (tex-display-shell))
ea590e1c
SM
2254\f
2255;;;;
2256;;;; LaTeX indentation
2257;;;;
2258
2259(defvar tex-indent-allhanging t)
2260(defvar tex-indent-arg 4)
2261(defvar tex-indent-basic 2)
2262(defvar tex-indent-item tex-indent-basic)
2263(defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
2264
8a591d52
SM
2265(defvar tex-latex-indent-syntax-table
2266 (let ((st (make-syntax-table tex-mode-syntax-table)))
2267 (modify-syntax-entry ?$ "." st)
2268 (modify-syntax-entry ?\( "." st)
2269 (modify-syntax-entry ?\) "." st)
2270 st)
2271 "Syntax table used while computing indentation.")
ea590e1c
SM
2272
2273(defun latex-indent (&optional arg)
7afecb99
SM
2274 (if (and (eq (get-text-property (line-beginning-position) 'face)
2275 tex-verbatim-face))
a3d80d4a 2276 'noindent
7afecb99
SM
2277 (with-syntax-table tex-latex-indent-syntax-table
2278 ;; TODO: Rather than ignore $, we should try to be more clever about it.
2279 (let ((indent
2280 (save-excursion
2281 (beginning-of-line)
2282 (latex-find-indent))))
2283 (if (< indent 0) (setq indent 0))
2284 (if (<= (current-column) (current-indentation))
2285 (indent-line-to indent)
2286 (save-excursion (indent-line-to indent)))))))
ea590e1c
SM
2287
2288(defun latex-find-indent (&optional virtual)
2289 "Find the proper indentation of text after point.
2290VIRTUAL if non-nil indicates that we're only trying to find the indentation
2291 in order to determine the indentation of something else.
2292There might be text before point."
2293 (save-excursion
2294 (skip-chars-forward " \t")
2295 (or
7afecb99
SM
2296 ;; Stick the first line at column 0.
2297 (and (= (point-min) (line-beginning-position)) 0)
ea590e1c 2298 ;; Trust the current indentation, if such info is applicable.
7afecb99
SM
2299 (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
2300 (current-column))
2301 ;; Stick verbatim environments to the left margin.
2302 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2303 (member (match-string 2) tex-verbatim-environments)
2304 0)
ea590e1c
SM
2305 ;; Put leading close-paren where the matching open brace would be.
2306 (and (eq (latex-syntax-after) ?\))
2307 (ignore-errors
2308 (save-excursion
2309 (latex-skip-close-parens)
2310 (latex-backward-sexp-1)
2311 (latex-find-indent 'virtual))))
2312 ;; Default (maybe an argument)
2313 (let ((pos (point))
2314 (char (char-after))
2315 ;; Outdent \item if necessary.
2316 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
2317 up-list-pos)
2318 ;; Find the previous point which determines our current indentation.
2319 (condition-case err
2320 (progn
2321 (latex-backward-sexp-1)
2322 (while (> (current-column) (current-indentation))
2323 (latex-backward-sexp-1)))
2324 (scan-error
2325 (setq up-list-pos (nth 2 err))))
8908cf40
SM
2326 (cond
2327 ((= (point-min) pos) 0) ; We're really just indenting the first line.
2328 ((integerp up-list-pos)
2329 ;; Have to indent relative to the open-paren.
2330 (goto-char up-list-pos)
2331 (if (and (not tex-indent-allhanging)
2332 (> pos (progn (latex-down-list)
2333 (forward-comment (point-max))
2334 (point))))
7afecb99 2335 ;; Align with the first element after the open-paren.
8908cf40
SM
2336 (current-column)
2337 ;; We're the first element after a hanging brace.
2338 (goto-char up-list-pos)
2339 (+ indent tex-indent-basic (latex-find-indent 'virtual))))
2340 ;; We're now at the "beginning" of a line.
2341 ((not (and (not virtual) (eq (char-after) ?\\)))
2342 ;; Nothing particular here: just keep the same indentation.
2343 (+ indent (current-column)))
2344 ;; We're now looking at a macro call.
7afecb99
SM
2345 ((looking-at tex-indent-item-re)
2346 ;; Indenting relative to an item, have to re-add the outdenting.
8908cf40
SM
2347 (+ indent (current-column) tex-indent-item))
2348 (t
2349 (let ((col (current-column)))
21749f14 2350 (if (or (null char) (not (eq (char-syntax char) ?\()))
8908cf40
SM
2351 ;; If the first char was not an open-paren, there's
2352 ;; a risk that this is really not an argument to the
2353 ;; macro at all.
21749f14
RS
2354 (+ indent col)
2355 (forward-sexp 1)
2356 (if (< (line-end-position)
2357 (save-excursion (forward-comment (point-max))
2358 (point)))
8908cf40
SM
2359 ;; we're indenting the first argument.
2360 (min (current-column) (+ tex-indent-arg col))
2361 (skip-syntax-forward " ")
2362 (current-column))))))))))
a3d80d4a
SM
2363;;; DocTeX support
2364
2365(defun doctex-font-lock-^^A ()
2366 (if (eq (char-after (line-beginning-position)) ?\%)
2367 (progn
2368 (put-text-property
2369 (1- (match-beginning 1)) (match-beginning 1)
2370 'syntax-table
2371 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2372 ;; The `%' is a single-char comment, which Emacs
2373 ;; syntax-table can't deal with. We could turn it
2374 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2375 ;; Instead, we include it in the ^^A comment.
2376 (eval-when-compile (string-to-syntax "< b"))
2377 (eval-when-compile (string-to-syntax ">"))))
2378 (let ((end (line-end-position)))
2379 (if (< end (point-max))
2380 (put-text-property
2381 end (1+ end)
2382 'syntax-table
2383 (eval-when-compile (string-to-syntax "> b")))))
2384 (eval-when-compile (string-to-syntax "< b")))))
2385
2386(defun doctex-font-lock-syntactic-face-function (state)
2387 ;; Mark DocTeX documentation, which is parsed as a style A comment
2388 ;; starting in column 0.
2389 (if (or (nth 3 state) (nth 7 state)
2390 (not (memq (char-before (nth 8 state))
2391 '(?\n nil))))
2392 ;; Anything else is just as for LaTeX.
2393 (tex-font-lock-syntactic-face-function state)
2394 font-lock-doc-face))
2395
2396(defvar doctex-font-lock-syntactic-keywords
2397 (append
2398 tex-font-lock-syntactic-keywords
2399 ;; For DocTeX comment-in-doc.
2400 `(("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A))))))
2401
2402(defvar doctex-font-lock-keywords
2403 (append tex-font-lock-keywords
2404 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t)))))
2405
2406;;;###autoload
2407(define-derived-mode doctex-mode latex-mode "DocTeX"
2408 "Major mode to edit DocTeX files."
2409 (setq font-lock-defaults
2410 (cons (append (car font-lock-defaults) '(doctex-font-lock-keywords))
2411 (mapcar
2412 (lambda (x)
2413 (case (car-safe x)
2414 (font-lock-syntactic-keywords
2415 (cons (car x) 'doctex-font-lock-syntactic-keywords))
2416 (font-lock-syntactic-face-function
2417 (cons (car x) 'doctex-font-lock-syntactic-face-function))
2418 (t x)))
2419 (cdr font-lock-defaults)))))
528415e7
RS
2420
2421(run-hooks 'tex-mode-load-hook)
869bff31 2422
49116ac0
JB
2423(provide 'tex-mode)
2424
ab5796a9 2425;;; arch-tag: c0a680b1-63aa-4547-84b9-4193c29c0080
d501f516 2426;;; tex-mode.el ends here