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