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