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