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