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