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