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