(Fmake_network_process): Doc fix.
[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 638(put 'tex-verbatim-environments 'safe-local-variable
299ea3d3 639 (lambda (x) (null (delq t (mapcar '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.
41c12ad8 1191 ;; FIXME this should be using something like backward-paragraph.
710a0f53
KH
1192 (if (search-backward "\n\n" nil t)
1193 (progn
1194 (setq prev-end (point))
1195 (forward-char 2))
1196 (goto-char (setq prev-end (point-min))))
869bff31 1197 (or (tex-validate-region (point) end)
a3d80d4a 1198 (let* ((end (line-beginning-position 2))
bbd93e41
RS
1199 start tem)
1200 (beginning-of-line)
1201 (setq start (point))
1202 ;; Keep track of line number as we scan,
1203 ;; in a cumulative fashion.
1204 (if linenum
1205 (setq linenum (- linenum (count-lines prevpos (point))))
1206 (setq linenum (1+ (count-lines 1 start))))
1207 (setq prevpos (point))
bed1b0c8 1208 ;; Mention this mismatch in *Occur*.
bbd93e41 1209 ;; Since we scan from end of buffer to beginning,
e6b0b773 1210 ;; add each mismatch at the beginning of *Occur*.
bbd93e41
RS
1211 (save-excursion
1212 (setq tem (point-marker))
1213 (set-buffer standard-output)
1214 (goto-char (point-min))
1215 ;; Skip "Mismatches:" header line.
1216 (forward-line 1)
e6b0b773 1217 (setq num-matches (1+ num-matches))
bbd93e41 1218 (insert-buffer-substring buffer start end)
e6b0b773
MR
1219 (let (text-beg (text-end (point-marker)))
1220 (forward-char (- start end))
1221 (setq text-beg (point-marker))
1222 (insert (format "%3d: " linenum))
a865de85
EZ
1223 (add-text-properties
1224 text-beg (- text-end 1)
1225 '(mouse-face highlight
1226 help-echo "mouse-2: go to this invalidity"))
1598a961 1227 (put-text-property text-beg (- text-end 1)
52ab062c 1228 'occur-target tem)))))
710a0f53 1229 (goto-char prev-end))))
bdbd9606 1230 (with-current-buffer standard-output
003274a0
JPW
1231 (let ((no-matches (zerop num-matches)))
1232 (if no-matches
1233 (insert "None!\n"))
1234 (if (interactive-p)
f04232c3
JPW
1235 (message (cond (no-matches "No mismatches found")
1236 ((= num-matches 1) "1 mismatch found")
1237 (t "%d mismatches found"))
1238 num-matches)))))))
869bff31 1239
1240(defun tex-validate-region (start end)
1241 "Check for mismatched braces or $'s in region.
1242Returns t if no mismatches. Returns nil and moves point to suspect
1243area if a mismatch is found."
1244 (interactive "r")
1245 (let ((failure-point nil) (max-possible-sexps (- end start)))
1246 (save-excursion
1247 (condition-case ()
1248 (save-restriction
1249 (narrow-to-region start end)
2ed2806c 1250 ;; First check that the open and close parens balance in numbers.
869bff31 1251 (goto-char start)
e6b0b773 1252 (while (<= 0 (setq max-possible-sexps (1- max-possible-sexps)))
2ed2806c
KH
1253 (forward-sexp 1))
1254 ;; Now check that like matches like.
1255 (goto-char start)
35dccc62
SM
1256 (while (re-search-forward "\\s(" nil t)
1257 (save-excursion
1258 (let ((pos (match-beginning 0)))
1259 (goto-char pos)
2ed2806c 1260 (forward-sexp 1)
35dccc62
SM
1261 (or (eq (preceding-char) (cdr (syntax-after pos)))
1262 (eq (char-after pos) (cdr (syntax-after (1- (point)))))
1263 (error "Mismatched parentheses"))))))
869bff31 1264 (error
bed1b0c8
RS
1265 (skip-syntax-forward " .>")
1266 (setq failure-point (point)))))
bdbd9606
SM
1267 (if failure-point (goto-char failure-point))
1268 (not failure-point)))
869bff31 1269
1270(defun tex-terminate-paragraph (inhibit-validation)
1271 "Insert two newlines, breaking a paragraph for TeX.
81c735c0 1272Check for mismatched braces or $s in paragraph being terminated.
869bff31 1273A prefix arg inhibits the checking."
528415e7 1274 (interactive "*P")
120d9fb5 1275 (insert "\n\n")
869bff31 1276 (or inhibit-validation
120d9fb5
GM
1277 ;; For the purposes of this, a "paragraph" is a block of text
1278 ;; wherein all the brackets etc are expected to be balanced. It
1279 ;; may start after a blank line (ie a "proper" paragraph), or
1280 ;; a begin{} or end{} block, etc.
1281 (tex-validate-region
1282 (save-excursion
1283 (backward-paragraph)
1284 (point))
1285 (point))
1286 (message "Paragraph being closed appears to contain a mismatch")))
869bff31 1287
7afecb99 1288(define-skeleton tex-insert-braces
869bff31 1289 "Make a pair of braces and be poised to type inside of them."
7afecb99
SM
1290 nil
1291 ?\{ _ ?})
869bff31 1292
9bd4f69c
RS
1293;; This function is used as the value of fill-nobreak-predicate
1294;; in LaTeX mode. Its job is to prevent line-breaking inside
1295;; of a \verb construct.
1296(defun latex-fill-nobreak-predicate ()
7afecb99
SM
1297 (save-excursion
1298 (skip-chars-backward " ")
1299 ;; Don't break after \ since `\ ' has special meaning.
1300 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
1301 (let ((opoint (point))
1302 inside)
1303 (beginning-of-line)
1304 (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
1305 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
1306 (setq inside t)))
1307 inside))))
9bd4f69c 1308
53c4fe47
SM
1309(defvar latex-block-default "enumerate")
1310
8084f5d8 1311(defvar latex-block-args-alist
dd166d5f
SM
1312 '(("array" nil ?\{ (skeleton-read "Format: ") ?\})
1313 ("tabular" nil ?\{ (skeleton-read "Format: ") ?\})
1314 ("minipage" nil ?\{ (skeleton-read "Size: ") ?\})
1315 ("picture" nil ?\( (skeleton-read "SizeX,SizeY: ") ?\))
1316 ;; FIXME: This is right for Prosper, but not for seminar.
1317 ;; ("slide" nil ?\{ (skeleton-read "Title: ") ?\})
1318 )
8084f5d8
SM
1319 "Skeleton element to use for arguments to particular environments.
1320Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1321the name of the environment and SKEL-ELEM is an element to use in
1322a skeleton (see `skeleton-insert').")
1323
1324(defvar latex-block-body-alist
1325 '(("enumerate" nil '(latex-insert-item) > _)
1326 ("itemize" nil '(latex-insert-item) > _)
dd166d5f
SM
1327 ("table" nil "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1328 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))
1329 \n _)
1330 ("figure" nil > _ \n "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1331 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))))
8084f5d8
SM
1332 "Skeleton element to use for the body of particular environments.
1333Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1334the name of the environment and SKEL-ELEM is an element to use in
1335a skeleton (see `skeleton-insert').")
1336
15ca8de7 1337;; Like tex-insert-braces, but for LaTeX.
7afecb99
SM
1338(defalias 'tex-latex-block 'latex-insert-block)
1339(define-skeleton latex-insert-block
8a591d52 1340 "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
869bff31 1341Puts point on a blank line between them."
53c4fe47
SM
1342 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1343 latex-block-default)
95a045bd 1344 (append latex-block-names
7afecb99 1345 latex-standard-block-names)
53c4fe47
SM
1346 nil nil nil nil latex-block-default)))
1347 (setq latex-block-default choice)
7afecb99 1348 (unless (or (member choice latex-standard-block-names)
53c4fe47
SM
1349 (member choice latex-block-names))
1350 ;; Remember new block names for later completion.
1351 (push choice latex-block-names))
1352 choice)
95a045bd 1353 \n "\\begin{" str "}"
8084f5d8 1354 (cdr (assoc str latex-block-args-alist))
dd166d5f
SM
1355 > \n (or (cdr (assoc str latex-block-body-alist)) '(nil > _))
1356 (unless (bolp) '\n)
95a045bd 1357 "\\end{" str "}" > \n)
53c4fe47 1358
ea590e1c
SM
1359(define-skeleton latex-insert-item
1360 "Insert a \item macro."
1361 nil
15ca8de7 1362 \n "\\item " >)
ea590e1c 1363
53c4fe47
SM
1364\f
1365;;;;
1366;;;; LaTeX syntax navigation
1367;;;;
869bff31 1368
5e56fb53
SM
1369(defmacro tex-search-noncomment (&rest body)
1370 "Execute BODY as long as it return non-nil and point is in a comment.
1371Return the value returned by the last execution of BODY."
1372 (declare (debug t))
1373 (let ((res-sym (make-symbol "result")))
1374 `(let (,res-sym)
1375 (while
1376 (and (setq ,res-sym (progn ,@body))
1377 (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
1378 ,res-sym)))
1379
869bff31 1380(defun tex-last-unended-begin ()
81c735c0 1381 "Leave point at the beginning of the last `\\begin{...}' that is unended."
95a045bd 1382 (condition-case nil
5e56fb53
SM
1383 (while (and (tex-search-noncomment
1384 (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
95a045bd
SM
1385 (looking-at "\\\\end"))
1386 (tex-last-unended-begin))
1387 (search-failed (error "Couldn't find unended \\begin"))))
869bff31 1388
53c4fe47
SM
1389(defun tex-next-unmatched-end ()
1390 "Leave point at the end of the next `\\end' that is unended."
5e56fb53
SM
1391 (while (and (tex-search-noncomment
1392 (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
ea590e1c
SM
1393 (save-excursion (goto-char (match-beginning 0))
1394 (looking-at "\\\\begin")))
53c4fe47
SM
1395 (tex-next-unmatched-end)))
1396
6a900cf1
ER
1397(defun tex-goto-last-unclosed-latex-block ()
1398 "Move point to the last unclosed \\begin{...}.
1399Mark is left at original location."
1400 (interactive)
1401 (let ((spot))
1402 (save-excursion
95a045bd 1403 (tex-last-unended-begin)
6a900cf1
ER
1404 (setq spot (point)))
1405 (push-mark)
1406 (goto-char spot)))
1407
53c4fe47
SM
1408(defun latex-backward-sexp-1 ()
1409 "Like (backward-sexp 1) but aware of multi-char elements."
1410 (let ((pos (point))
1411 (forward-sexp-function))
1412 (backward-sexp 1)
1413 (if (looking-at "\\\\begin\\>")
1414 (signal 'scan-error
1415 (list "Containing expression ends prematurely"
1416 (point) (prog1 (point) (goto-char pos))))
1417 (when (eq (char-after) ?{)
1418 (let ((newpos (point)))
1419 (when (ignore-errors (backward-sexp 1) t)
e67064e2
SM
1420 (if (or (looking-at "\\\\end\\>")
1421 ;; In case the \\ ends a verbatim section.
1422 (and (looking-at "end\\>") (eq (char-before) ?\\)))
53c4fe47
SM
1423 (tex-last-unended-begin)
1424 (goto-char newpos))))))))
1425
1426(defun latex-forward-sexp-1 ()
1427 "Like (forward-sexp 1) but aware of multi-char elements."
1428 (let ((pos (point))
1429 (forward-sexp-function))
1430 (forward-sexp 1)
1431 (let ((newpos (point)))
1432 (skip-syntax-backward "/w")
1433 (cond
1434 ((looking-at "\\\\end\\>")
1435 (signal 'scan-error
1436 (list "Containing expression ends prematurely"
1437 (point)
1438 (prog1
1439 (progn (ignore-errors (forward-sexp 2)) (point))
1440 (goto-char pos)))))
1441 ((looking-at "\\\\begin\\>")
1442 (goto-char (match-end 0))
1443 (tex-next-unmatched-end))
1444 (t (goto-char newpos))))))
1445
1446(defun latex-forward-sexp (&optional arg)
1447 "Like `forward-sexp' but aware of multi-char elements."
1448 (interactive "P")
1449 (unless arg (setq arg 1))
1450 (let ((pos (point)))
1451 (condition-case err
1452 (while (/= arg 0)
1453 (setq arg
1454 (if (> arg 0)
1455 (progn (latex-forward-sexp-1) (1- arg))
1456 (progn (latex-backward-sexp-1) (1+ arg)))))
1457 (scan-error
1458 (goto-char pos)
1459 (signal (car err) (cdr err))))))
1460
ea590e1c
SM
1461(defun latex-syntax-after ()
1462 "Like (char-syntax (char-after)) but aware of multi-char elements."
15ca8de7 1463 (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
ea590e1c
SM
1464
1465(defun latex-skip-close-parens ()
1466 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1467 (let ((forward-sexp-function nil))
1468 (while (progn (skip-syntax-forward " )")
1469 (looking-at "\\\\end\\>"))
1470 (forward-sexp 2))))
1471
1472(defun latex-down-list ()
1473 "Like (down-list 1) but aware of multi-char elements."
1474 (forward-comment (point-max))
1475 (let ((forward-sexp-function nil))
1476 (if (not (looking-at "\\\\begin\\>"))
1477 (down-list 1)
1478 (forward-sexp 1)
1479 ;; Skip arguments.
7afecb99
SM
1480 (while (looking-at "[ \t]*[[{(]")
1481 (with-syntax-table tex-mode-syntax-table
1482 (forward-sexp))))))
ea590e1c 1483
7afecb99
SM
1484(defalias 'tex-close-latex-block 'latex-close-block)
1485(define-skeleton latex-close-block
1486 "Create an \\end{...} to match the last unclosed \\begin{...}."
1487 (save-excursion
1488 (tex-last-unended-begin)
1489 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1490 (match-string 1)))
1491 \n "\\end" str > \n)
1492
1493(define-skeleton latex-split-block
1494 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1495 (save-excursion
1496 (tex-last-unended-begin)
1497 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1498 (prog1 (match-string 1)
1499 (goto-char (match-end 1))
1500 (setq v1 (buffer-substring (point)
1501 (progn
1502 (while (looking-at "[ \t]*[[{]")
1503 (forward-sexp 1))
1504 (point)))))))
1505 \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
15ca8de7
SM
1506
1507(defconst tex-discount-args-cmds
1508 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1509 "documentclass" "usepackage" "label")
1510 "TeX commands whose arguments should not be counted as text.")
1511
1512(defun tex-count-words (begin end)
1513 "Count the number of words in the buffer."
1514 (interactive
1515 (if (and transient-mark-mode mark-active)
1516 (list (region-beginning) (region-end))
1517 (list (point-min) (point-max))))
1518 ;; TODO: skip comments and math and maybe some environments.
1519 (save-excursion
1520 (goto-char begin)
1521 (let ((count 0))
1522 (while (and (< (point) end) (re-search-forward "\\<" end t))
1523 (if (not (eq (char-syntax (preceding-char)) ?/))
1524 (progn
1525 ;; Don't count single-char words.
1526 (unless (looking-at ".\\>") (incf count))
1527 (forward-char 1))
1528 (let ((cmd
1529 (buffer-substring-no-properties
1530 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1531 (forward-char 1))
1532 (point)))))
1533 (when (member cmd tex-discount-args-cmds)
1534 (skip-chars-forward "*")
1535 (forward-comment (point-max))
1536 (when (looking-at "\\[")
1537 (forward-sexp 1)
1538 (forward-comment (point-max)))
1539 (if (not (looking-at "{"))
1540 (forward-char 1)
1541 (forward-sexp 1))))))
1542 (message "%s words" count))))
b781e739
SS
1543
1544
869bff31 1545\f
1546;;; Invoking TeX in an inferior shell.
1547
15ca8de7
SM
1548;; Why use a shell instead of running TeX directly? Because if TeX
1549;; gets stuck, the user can switch to the shell window and type at it.
869bff31 1550
15ca8de7 1551;; The utility functions:
869bff31 1552
bdbd9606 1553(define-derived-mode tex-shell shell-mode "TeX-Shell"
3f2c97ea
SM
1554 (set (make-local-variable 'compilation-parse-errors-function)
1555 'tex-compilation-parse-errors)
bdbd9606
SM
1556 (compilation-shell-minor-mode t))
1557
d974af30 1558;;;###autoload
869bff31 1559(defun tex-start-shell ()
d6709b80
SM
1560 (with-current-buffer
1561 (make-comint
1562 "tex-shell"
07c16ec4 1563 (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
4042dc25 1564 nil
053be11a 1565 ;; Specify an interactive shell, to make sure it prompts.
4042dc25 1566 "-i")
528415e7
RS
1567 (let ((proc (get-process "tex-shell")))
1568 (set-process-sentinel proc 'tex-shell-sentinel)
003274a0 1569 (set-process-query-on-exit-flag proc nil)
bdbd9606 1570 (tex-shell)
528415e7 1571 (while (zerop (buffer-size))
51b2c841
RS
1572 (sleep-for 1)))))
1573
033306e3
RS
1574(defun tex-feed-input ()
1575 "Send input to the tex shell process.
1576In the tex buffer this can be used to continue an interactive tex run.
bed1b0c8 1577In the tex shell buffer this command behaves like `comint-send-input'."
033306e3 1578 (interactive)
b781e739 1579 (set-buffer (tex-shell-buf))
033306e3
RS
1580 (comint-send-input)
1581 (tex-recenter-output-buffer nil))
1582
51b2c841
RS
1583(defun tex-display-shell ()
1584 "Make the TeX shell buffer visible in a window."
b781e739 1585 (display-buffer (tex-shell-buf))
51b2c841 1586 (tex-recenter-output-buffer nil))
528415e7
RS
1587
1588(defun tex-shell-sentinel (proc msg)
1589 (cond ((null (buffer-name (process-buffer proc)))
1590 ;; buffer killed
1591 (set-process-buffer proc nil)
1592 (tex-delete-last-temp-files))
1593 ((memq (process-status proc) '(signal exit))
1594 (tex-delete-last-temp-files))))
1595
1596(defun tex-set-buffer-directory (buffer directory)
869bff31 1597 "Set BUFFER's default directory to be DIRECTORY."
1598 (setq directory (file-name-as-directory (expand-file-name directory)))
1599 (if (not (file-directory-p directory))
1600 (error "%s is not a directory" directory)
1601 (save-excursion
1602 (set-buffer buffer)
1603 (setq default-directory directory))))
1604
30803a05
RS
1605(defvar tex-send-command-modified-tick 0)
1606(make-variable-buffer-local 'tex-send-command-modified-tick)
1607
bdbd9606 1608(defun tex-shell-proc ()
b781e739 1609 (or (tex-shell-running) (error "No TeX subprocess")))
bdbd9606
SM
1610(defun tex-shell-buf ()
1611 (process-buffer (tex-shell-proc)))
b781e739
SS
1612(defun tex-shell-buf-no-error ()
1613 (let ((proc (tex-shell-running)))
1614 (and proc (process-buffer proc))))
bdbd9606 1615
528415e7 1616(defun tex-send-command (command &optional file background)
4cdc1d4b 1617 "Send COMMAND to TeX shell process, substituting optional FILE for *.
8241d7b9
ER
1618Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1619FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1620substitution will be made in COMMAND. COMMAND can be any expression that
460e1b7d
RS
1621evaluates to a command string.
1622
1623Return the process in which TeX is running."
528415e7
RS
1624 (save-excursion
1625 (let* ((cmd (eval command))
bdbd9606 1626 (proc (tex-shell-proc))
64db2461 1627 (buf (process-buffer proc))
4f45adda 1628 (star (string-match "\\*" cmd))
4cdc1d4b
RS
1629 (string
1630 (concat
8ca66348
SM
1631 (if (null file)
1632 cmd
1633 (if (file-name-absolute-p file)
1634 (setq file (convert-standard-filename file)))
1635 (if star (concat (substring cmd 0 star)
1636 (shell-quote-argument file)
1637 (substring cmd (1+ star)))
1638 (concat cmd " " (shell-quote-argument file))))
4cdc1d4b 1639 (if background "&" ""))))
64db2461
RS
1640 ;; Switch to buffer before checking for subproc output in it.
1641 (set-buffer buf)
30803a05
RS
1642 ;; If text is unchanged since previous tex-send-command,
1643 ;; we haven't got any output. So wait for output now.
64db2461 1644 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
30803a05 1645 (accept-process-output proc))
4cdc1d4b
RS
1646 (goto-char (process-mark proc))
1647 (insert string)
30803a05 1648 (comint-send-input)
460e1b7d
RS
1649 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1650 proc)))
528415e7 1651
a15849cb
RS
1652(defun tex-delete-last-temp-files (&optional not-all)
1653 "Delete any junk files from last temp file.
1654If NOT-ALL is non-nil, save the `.dvi' file."
528415e7
RS
1655 (if tex-last-temp-file
1656 (let* ((dir (file-name-directory tex-last-temp-file))
adf6b7f9
KH
1657 (list (and (file-directory-p dir)
1658 (file-name-all-completions
02fd229c
RS
1659 (file-name-sans-extension
1660 (file-name-nondirectory tex-last-temp-file))
1661 dir))))
adf6b7f9 1662 (while list
a15849cb
RS
1663 (if not-all
1664 (and
1665 ;; If arg is non-nil, don't delete the .dvi file.
1666 (not (string-match "\\.dvi$" (car list)))
1667 (delete-file (concat dir (car list))))
1668 (delete-file (concat dir (car list))))
528415e7
RS
1669 (setq list (cdr list))))))
1670
99621a14 1671(add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
869bff31 1672
75035a80
SM
1673;;
1674;; Machinery to guess the command that the user wants to execute.
1675;;
1676
1677(defvar tex-compile-history nil)
1678
1679(defvar tex-input-files-re
1680 (eval-when-compile
1681 (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
1682 "bbl" "ind" "sty" "cls") t)
1683 ;; Include files with no dots (for directories).
1684 "\\'\\|\\`[^.]+\\'")))
1685
1686(defcustom tex-use-reftex t
1687 "If non-nil, use RefTeX's list of files to determine what command to use."
18a8c773
LK
1688 :type 'boolean
1689 :group 'tex)
75035a80
SM
1690
1691(defvar tex-compile-commands
1692 '(((concat "pdf" tex-command
bf4ec222 1693 " " (if (< 0 (length tex-start-commands))
d18fc930 1694 (shell-quote-argument tex-start-commands)) " %f")
75035a80
SM
1695 t "%r.pdf")
1696 ((concat tex-command
bf4ec222 1697 " " (if (< 0 (length tex-start-commands))
d18fc930 1698 (shell-quote-argument tex-start-commands)) " %f")
75035a80
SM
1699 t "%r.dvi")
1700 ("xdvi %r &" "%r.dvi")
29a47b89
SM
1701 ("xpdf %r.pdf &" "%r.pdf")
1702 ("gv %r.ps &" "%r.ps")
1703 ("yap %r &" "%r.dvi")
75035a80 1704 ("advi %r &" "%r.dvi")
29a47b89 1705 ("gv %r.pdf &" "%r.pdf")
75035a80
SM
1706 ("bibtex %r" "%r.aux" "%r.bbl")
1707 ("makeindex %r" "%r.idx" "%r.ind")
1708 ("texindex %r.??")
1709 ("dvipdfm %r" "%r.dvi" "%r.pdf")
1710 ("dvipdf %r" "%r.dvi" "%r.pdf")
dd166d5f 1711 ("dvips -o %r.ps %r" "%r.dvi" "%r.ps")
e70ff1af 1712 ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
75035a80
SM
1713 ("lpr %r.ps" "%r.ps"))
1714 "List of commands for `tex-compile'.
1715Each element should be of the form (FORMAT IN OUT) where
1716FORMAT is an expression that evaluates to a string that can contain
1717 - `%r' the main file name without extension.
1718 - `%f' the main file name.
1719IN can be either a string (with the same % escapes in it) indicating
1720 the name of the input file, or t to indicate that the input is all
1721 the TeX files of the document, or nil if we don't know.
1722OUT describes the output file and is either a %-escaped string
1723 or nil to indicate that there is no output file.")
1724
8084f5d8
SM
1725;; defsubst* gives better byte-code than defsubst.
1726(defsubst* tex-string-prefix-p (str1 str2)
1727 "Return non-nil if STR1 is a prefix of STR2"
1728 (eq t (compare-strings str2 nil (length str1) str1 nil nil)))
1729
dd459839
SM
1730(defun tex-guess-main-file (&optional all)
1731 "Find a likely `tex-main-file'.
1732Looks for hints in other buffers in the same directory or in
8084f5d8
SM
1733ALL other buffers. If ALL is `sub' only look at buffers in parent directories
1734of the current buffer."
dd459839
SM
1735 (let ((dir default-directory)
1736 (header-re tex-start-of-header))
1737 (catch 'found
1738 ;; Look for a buffer with `tex-main-file' set.
1739 (dolist (buf (if (consp all) all (buffer-list)))
1740 (with-current-buffer buf
8084f5d8
SM
1741 (when (and (cond
1742 ((null all) (equal dir default-directory))
1743 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1744 (t))
dd459839
SM
1745 (stringp tex-main-file))
1746 (throw 'found (expand-file-name tex-main-file)))))
1747 ;; Look for a buffer containing the magic `tex-start-of-header'.
1748 (dolist (buf (if (consp all) all (buffer-list)))
1749 (with-current-buffer buf
8084f5d8
SM
1750 (when (and (cond
1751 ((null all) (equal dir default-directory))
1752 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1753 (t))
dd459839
SM
1754 buffer-file-name
1755 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1756 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1757 (save-excursion
cb30255a
SM
1758 (save-restriction
1759 (widen)
1760 (goto-char (point-min))
95a045bd
SM
1761 (re-search-forward
1762 header-re (+ (point) 10000) t))))
dd459839
SM
1763 (throw 'found (expand-file-name buffer-file-name))))))))
1764
07c16ec4
SM
1765(defun tex-main-file ()
1766 "Return the relative name of the main file."
bdbd9606
SM
1767 (let* ((file (or tex-main-file
1768 ;; Compatibility with AUCTeX.
96c0d9e9 1769 (with-no-warnings
034a48f4
MR
1770 (when (boundp 'TeX-master)
1771 (cond ((stringp TeX-master)
1772 (make-local-variable 'tex-main-file)
1773 (setq tex-main-file TeX-master))
1774 ((and (eq TeX-master t) buffer-file-name)
1775 (file-relative-name buffer-file-name)))))
bdbd9606
SM
1776 ;; Try to guess the main file.
1777 (if (not buffer-file-name)
1778 (error "Buffer is not associated with any file")
1779 (file-relative-name
1780 (if (save-excursion
1781 (goto-char (point-min))
95a045bd
SM
1782 (re-search-forward tex-start-of-header
1783 (+ (point) 10000) t))
bdbd9606
SM
1784 ;; This is the main file.
1785 buffer-file-name
1786 ;; This isn't the main file, let's try to find better,
1787 (or (tex-guess-main-file)
8084f5d8 1788 (tex-guess-main-file 'sub)
bdbd9606 1789 ;; (tex-guess-main-file t)
07c16ec4 1790 buffer-file-name)))))))
e70ff1af
SM
1791 (if (or (file-exists-p file) (string-match "\\.tex\\'" file))
1792 file (concat file ".tex"))))
dd459839 1793
75035a80
SM
1794(defun tex-summarize-command (cmd)
1795 (if (not (stringp cmd)) ""
1796 (mapconcat 'identity
1797 (mapcar (lambda (s) (car (split-string s)))
1798 (split-string cmd "\\s-*\\(?:;\\|&&\\)\\s-*"))
1799 "&")))
1800
1801(defun tex-uptodate-p (file)
1802 "Return non-nil if FILE is not uptodate w.r.t the document source files.
1803FILE is typically the output DVI or PDF file."
1804 ;; We should check all the files included !!!
1805 (and
1806 ;; Clearly, the target must exist.
1807 (file-exists-p file)
1808 ;; And the last run must not have asked for a rerun.
1809 ;; FIXME: this should check that the last run was done on the same file.
1810 (let ((buf (condition-case nil (tex-shell-buf) (error nil))))
1811 (when buf
1812 (with-current-buffer buf
1813 (save-excursion
1814 (goto-char (point-max))
1815 (and (re-search-backward
8ca66348
SM
1816 (concat
1817 "(see the transcript file for additional information)"
1818 "\\|^Output written on .*"
1819 (regexp-quote (file-name-nondirectory file))
1820 " (.*)\\.") nil t)
75035a80
SM
1821 (> (save-excursion
1822 (or (re-search-backward "\\[[0-9]+\\]" nil t)
1823 (point-min)))
1824 (save-excursion
1825 (or (re-search-backward "Rerun" nil t)
1826 (point-min)))))))))
1827 ;; And the input files must not have been changed in the meantime.
1828 (let ((files (if (and tex-use-reftex
1829 (fboundp 'reftex-scanning-info-available-p)
1830 (reftex-scanning-info-available-p))
1831 (reftex-all-document-files)
1832 (list (file-name-directory (expand-file-name file)))))
1833 (ignored-dirs-re
1834 (concat
1835 (regexp-opt
1836 (delq nil (mapcar (lambda (s) (if (eq (aref s (1- (length s))) ?/)
1837 (substring s 0 (1- (length s)))))
1838 completion-ignored-extensions))
1839 t) "\\'"))
1840 (uptodate t))
1841 (while (and files uptodate)
1842 (let ((f (pop files)))
e70ff1af
SM
1843 (if (and (file-directory-p f)
1844 ;; Avoid infinite loops.
1845 (not (file-symlink-p f)))
75035a80
SM
1846 (unless (string-match ignored-dirs-re f)
1847 (setq files (nconc
1848 (directory-files f t tex-input-files-re)
1849 files)))
1850 (when (file-newer-than-file-p f file)
1851 (setq uptodate nil)))))
1852 uptodate)))
bf247b6e 1853
75035a80
SM
1854
1855(autoload 'format-spec "format-spec")
1856
1857(defvar tex-executable-cache nil)
1858(defun tex-executable-exists-p (name)
1859 "Like `executable-find' but with a cache."
1860 (let ((cache (assoc name tex-executable-cache)))
1861 (if cache (cdr cache)
1862 (let ((executable (executable-find name)))
1863 (push (cons name executable) tex-executable-cache)
1864 executable))))
1865
1866(defun tex-command-executable (cmd)
1867 (let ((s (if (stringp cmd) cmd (eval (car cmd)))))
1868 (substring s 0 (string-match "[ \t]\\|\\'" s))))
1869
1870(defun tex-command-active-p (cmd fspec)
1871 "Return non-nil if the CMD spec might need to be run."
1872 (let ((in (nth 1 cmd))
1873 (out (nth 2 cmd)))
1874 (if (stringp in)
1875 (let ((file (format-spec in fspec)))
1876 (when (file-exists-p file)
1877 (or (not out)
1878 (file-newer-than-file-p
1879 file (format-spec out fspec)))))
1880 (when (and (eq in t) (stringp out))
1881 (not (tex-uptodate-p (format-spec out fspec)))))))
1882
8084f5d8 1883(defun tex-compile-default (fspec)
dd166d5f 1884 "Guess a default command given the `format-spec' FSPEC."
75035a80
SM
1885 ;; TODO: Learn to do latex+dvips!
1886 (let ((cmds nil)
1887 (unchanged-in nil))
1888 ;; Only consider active commands.
1889 (dolist (cmd tex-compile-commands)
1890 (when (tex-executable-exists-p (tex-command-executable cmd))
1891 (if (tex-command-active-p cmd fspec)
1892 (push cmd cmds)
1893 (push (nth 1 cmd) unchanged-in))))
dd166d5f 1894 ;; If no command seems to be applicable, arbitrarily pick the first one.
29a47b89 1895 (setq cmds (if cmds (nreverse cmds) (list (car tex-compile-commands))))
75035a80
SM
1896 ;; Remove those commands whose input was considered stable for
1897 ;; some other command (typically if (t . "%.pdf") is inactive
1898 ;; then we're using pdflatex and the fact that the dvi file
1899 ;; is inexistent doesn't matter).
1900 (let ((tmp nil))
1901 (dolist (cmd cmds)
1902 (unless (member (nth 1 cmd) unchanged-in)
1903 (push cmd tmp)))
8084f5d8 1904 ;; Only remove if there's something left.
29a47b89 1905 (if tmp (setq cmds (nreverse tmp))))
8084f5d8
SM
1906 ;; Remove commands whose input is not uptodate either.
1907 (let ((outs (delq nil (mapcar (lambda (x) (nth 2 x)) cmds)))
1908 (tmp nil))
1909 (dolist (cmd cmds)
75035a80 1910 (unless (member (nth 1 cmd) outs)
8084f5d8
SM
1911 (push cmd tmp)))
1912 ;; Only remove if there's something left.
29a47b89 1913 (if tmp (setq cmds (nreverse tmp))))
75035a80
SM
1914 ;; Select which file we're going to operate on (the latest).
1915 (let ((latest (nth 1 (car cmds))))
1916 (dolist (cmd (prog1 (cdr cmds) (setq cmds (list (car cmds)))))
1917 (if (equal latest (nth 1 cmd))
1918 (push cmd cmds)
1919 (unless (eq latest t) ;Can't beat that!
1920 (if (or (not (stringp latest))
1921 (eq (nth 1 cmd) t)
1922 (and (stringp (nth 1 cmd))
1923 (file-newer-than-file-p
1924 (format-spec (nth 1 cmd) fspec)
1925 (format-spec latest fspec))))
1926 (setq latest (nth 1 cmd) cmds (list cmd)))))))
1927 ;; Expand the command spec into the actual text.
1928 (dolist (cmd (prog1 cmds (setq cmds nil)))
1929 (push (cons (eval (car cmd)) (cdr cmd)) cmds))
1930 ;; Select the favorite command from the history.
1931 (let ((hist tex-compile-history)
8084f5d8 1932 re hist-cmd)
75035a80 1933 (while hist
8084f5d8 1934 (setq hist-cmd (pop hist))
75035a80 1935 (setq re (concat "\\`"
8084f5d8 1936 (regexp-quote (tex-command-executable hist-cmd))
75035a80
SM
1937 "\\([ \t]\\|\\'\\)"))
1938 (dolist (cmd cmds)
8084f5d8
SM
1939 ;; If the hist entry uses the same command and applies to a file
1940 ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
1941 (and (string-match re (car cmd))
1942 (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd)))
1943 (string-match (regexp-quote (match-string 1 (car cmd)))
1944 hist-cmd))
1945 (setq hist nil cmds (list cmd)))))
1946 ;; Substitute and return.
1947 (if (and hist-cmd
1948 (string-match (concat "[' \t\"]" (format-spec "%r" fspec)
1949 "\\([;&' \t\"]\\|\\'\\)") hist-cmd))
1950 ;; The history command was already applied to the same file,
1951 ;; so just reuse it.
1952 hist-cmd
1953 (if cmds (format-spec (caar cmds) fspec))))))
75035a80
SM
1954
1955(defun tex-compile (dir cmd)
1956 "Run a command CMD on current TeX buffer's file in DIR."
1957 ;; FIXME: Use time-stamps on files to decide the next op.
1958 (interactive
1959 (let* ((file (tex-main-file))
5e56fb53
SM
1960 (default-directory
1961 (prog1 (file-name-directory (expand-file-name file))
1962 (setq file (file-name-nondirectory file))))
75035a80 1963 (root (file-name-sans-extension file))
d18fc930
SM
1964 (fspec (list (cons ?r (shell-quote-argument root))
1965 (cons ?f (shell-quote-argument file))))
8084f5d8 1966 (default (tex-compile-default fspec)))
5e56fb53 1967 (list default-directory
75035a80
SM
1968 (completing-read
1969 (format "Command [%s]: " (tex-summarize-command default))
1970 (mapcar (lambda (x)
1971 (list (format-spec (eval (car x)) fspec)))
1972 tex-compile-commands)
1973 nil nil nil 'tex-compile-history default))))
1974 (save-some-buffers (not compilation-ask-about-save) nil)
1975 (if (tex-shell-running)
1976 (tex-kill-job)
1977 (tex-start-shell))
1978 (tex-send-tex-command cmd dir))
d6709b80
SM
1979
1980(defun tex-start-tex (command file &optional dir)
460e1b7d 1981 "Start a TeX run, using COMMAND on FILE."
6633b891 1982 (let* ((star (string-match "\\*" command))
460e1b7d 1983 (compile-command
6633b891
KH
1984 (if star
1985 (concat (substring command 0 star)
d18fc930 1986 (shell-quote-argument file)
6633b891
KH
1987 (substring command (1+ star)))
1988 (concat command " "
95a045bd 1989 tex-start-options
9e0ad27a 1990 (if (< 0 (length tex-start-commands))
d18fc930
SM
1991 (concat
1992 (shell-quote-argument tex-start-commands) " "))
1993 (shell-quote-argument file)))))
bdbd9606
SM
1994 (tex-send-tex-command compile-command dir)))
1995
1996(defun tex-send-tex-command (cmd &optional dir)
b781e739
SS
1997 (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
1998 (and buf (with-current-buffer buf
1999 default-directory))))
bdbd9606
SM
2000 (not dir))
2001 (let (shell-dirtrack-verbose)
8ca66348 2002 (tex-send-command tex-shell-cd-command dir)))
bdbd9606 2003 (with-current-buffer (process-buffer (tex-send-command cmd))
bdbd9606
SM
2004 (setq compilation-last-buffer (current-buffer))
2005 (compilation-forget-errors)
1598a961 2006 ;; Don't parse previous compilations.
bdbd9606
SM
2007 (set-marker compilation-parsing-end (1- (point-max))))
2008 (tex-display-shell)
2009 (setq tex-last-buffer-texed (current-buffer)))
460e1b7d 2010\f
1598a961
SM
2011(defvar tex-error-parse-syntax-table
2012 (let ((st (make-syntax-table)))
2013 (modify-syntax-entry ?\( "()" st)
2014 (modify-syntax-entry ?\) ")(" st)
2015 (modify-syntax-entry ?\\ "\\" st)
2016 (modify-syntax-entry ?\{ "_" st)
2017 (modify-syntax-entry ?\} "_" st)
2018 (modify-syntax-entry ?\[ "_" st)
2019 (modify-syntax-entry ?\] "_" st)
2020 ;; Single quotations may appear in errors
2021 (modify-syntax-entry ?\" "_" st)
2022 st)
2023 "Syntax-table used while parsing TeX error messages.")
2024
460e1b7d 2025(defun tex-compilation-parse-errors (limit-search find-at-least)
f05bd645
RS
2026 "Parse the current buffer as TeX error messages.
2027See the variable `compilation-parse-errors-function' for the interface it uses.
2028
2029This function parses only the last TeX compilation.
2030It works on TeX compilations only. It is necessary for that purpose,
2031since TeX does not put file names and line numbers on the same line as
2032for the error messages."
460e1b7d
RS
2033 (require 'thingatpt)
2034 (setq compilation-error-list nil)
f05bd645
RS
2035 (let ((default-directory ; Perhaps dir has changed meanwhile.
2036 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
f05bd645
RS
2037 found-desired (num-errors-found 0)
2038 last-filename last-linenum last-position
3d1634c6 2039 begin-of-error end-of-error errfilename)
f05bd645
RS
2040 ;; Don't reparse messages already seen at last parse.
2041 (goto-char compilation-parsing-end)
2042 ;; Parse messages.
2043 (while (and (not (or found-desired (eobp)))
3d1634c6
GM
2044 ;; First alternative handles the newer --file-line-error style:
2045 ;; ./test2.tex:14: Too many }'s.
2046 ;; Second handles the old-style:
2047 ;; ! Too many }'s.
e47a29ad 2048 (prog1 (re-search-forward
3d1634c6 2049 "^\\(?:\\([^:\n]+\\):[[:digit:]]+:\\|!\\) " nil 'move)
f05bd645 2050 (setq begin-of-error (match-beginning 0)
3d1634c6
GM
2051 end-of-error (match-end 0)
2052 errfilename (match-string 1)))
f05bd645
RS
2053 (re-search-forward
2054 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
3f2c97ea 2055 (let* ((this-error (copy-marker begin-of-error))
003274a0 2056 (linenum (string-to-number (match-string 1)))
f05bd645
RS
2057 (error-text (regexp-quote (match-string 3)))
2058 (filename
3d1634c6
GM
2059 ;; Prefer --file-liner-error filename if we have it.
2060 (or errfilename
2061 (save-excursion
2062 (with-syntax-table tex-error-parse-syntax-table
2063 (backward-up-list 1)
2064 (skip-syntax-forward "(_")
2065 (while (not (file-readable-p (thing-at-point 'filename)))
2066 (skip-syntax-backward "(_")
2067 (backward-up-list 1)
2068 (skip-syntax-forward "(_"))
2069 (thing-at-point 'filename)))))
f05bd645
RS
2070 (new-file
2071 (or (null last-filename)
2072 (not (string-equal last-filename filename))))
2073 (error-location
cc9f5376
SM
2074 (with-current-buffer
2075 (if (equal filename (concat tex-zap-file ".tex"))
2076 tex-last-buffer-texed
2077 (find-file-noselect filename))
2078 (save-excursion
2079 (if new-file
2080 (progn (goto-line linenum) (setq last-position nil))
2081 (goto-char last-position)
2082 (forward-line (- linenum last-linenum)))
2083 ;; first try a forward search for the error text,
2084 ;; then a backward search limited by the last error.
2085 (let ((starting-point (point)))
2086 (or (re-search-forward error-text nil t)
2087 (re-search-backward error-text last-position t)
2088 (goto-char starting-point)))
2089 (point-marker)))))
f05bd645
RS
2090 (goto-char this-error)
2091 (if (and compilation-error-list
2092 (or (and find-at-least
2093 (>= num-errors-found
2094 find-at-least))
2095 (and limit-search
2096 (>= end-of-error limit-search)))
2097 new-file)
2098 (setq found-desired t)
2099 (setq num-errors-found (1+ num-errors-found)
2100 last-filename filename
2101 last-linenum linenum
2102 last-position error-location
2103 compilation-error-list ; Add the new error
2104 (cons (cons this-error error-location)
2105 compilation-error-list))
2106 (goto-char end-of-error)))))
ee13a145 2107 (set-marker compilation-parsing-end (point))
13376c78 2108 (setq compilation-error-list (nreverse compilation-error-list)))
460e1b7d 2109\f
528415e7 2110;;; The commands:
869bff31 2111
2112(defun tex-region (beg end)
2113 "Run TeX on the current region, via a temporary file.
2114The file's name comes from the variable `tex-zap-file' and the
2115variable `tex-directory' says where to put it.
2116
2117If the buffer has a header, the header is given to TeX before the
2118region itself. The buffer's header is all lines between the strings
2119defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
2120The header must start in the first 100 lines of the buffer.
2121
2122The value of `tex-trailer' is given to TeX as input after the region.
2123
2124The value of `tex-command' specifies the command to use to run TeX."
2125 (interactive "r")
2126 (if (tex-shell-running)
2127 (tex-kill-job)
2128 (tex-start-shell))
2129 (or tex-zap-file
2130 (setq tex-zap-file (tex-generate-zap-file-name)))
6d34c59f
RS
2131 ;; Temp file will be written and TeX will be run in zap-directory.
2132 ;; If the TEXINPUTS file has relative directories or if the region has
2133 ;; \input of files, this must be the same directory as the file for
2134 ;; TeX to access the correct inputs. That's why it's safest if
2135 ;; tex-directory is ".".
2136 (let* ((zap-directory
528415e7 2137 (file-name-as-directory (expand-file-name tex-directory)))
d6709b80 2138 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
80c2ab0f
GM
2139 zap-directory))
2140 (main-file (expand-file-name (tex-main-file)))
595a68b4
GM
2141 (ismain (string-equal main-file (buffer-file-name)))
2142 already-output)
0d548e5d
RS
2143 ;; Don't delete temp files if we do the same buffer twice in a row.
2144 (or (eq (current-buffer) tex-last-buffer-texed)
2145 (tex-delete-last-temp-files t))
595a68b4
GM
2146 (let ((default-directory zap-directory)) ; why?
2147 ;; We assume the header is fully contained in tex-main-file.
2148 ;; We use f-f-ns so we get prompted about any changes on disk.
2149 (with-current-buffer (find-file-noselect main-file)
2150 (setq already-output (tex-region-header tex-out-file
2151 (and ismain beg))))
2152 ;; Write out the specified region (but don't repeat anything
2153 ;; already written in the header).
2154 (write-region (if ismain
2155 (max beg already-output)
2156 beg)
2157 end tex-out-file (not (zerop already-output)))
2158 ;; Write the trailer, if any.
2159 ;; Precede it with a newline to make sure it
2160 ;; is not hidden in a comment.
2161 (if tex-trailer
2162 (write-region (concat "\n" tex-trailer) nil
2163 tex-out-file t)))
80c2ab0f
GM
2164 ;; Record the file name to be deleted afterward.
2165 (setq tex-last-temp-file tex-out-file)
2166 ;; Use a relative file name here because (1) the proper dir
2167 ;; is already current, and (2) the abs file name is sometimes
2168 ;; too long and can make tex crash.
2169 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
2170 (setq tex-print-file tex-out-file)))
2171
595a68b4
GM
2172(defun tex-region-header (file &optional beg)
2173 "If there is a TeX header in the current buffer, write it to FILE.
2174Return point at the end of the region so written, or zero. If
2175the optional buffer position BEG is specified, then the region
2176written out starts at BEG, if this lies before the start of the header.
2177
2178If the first line matches `tex-first-line-header-regexp', it is
2179also written out. The variables `tex-start-of-header' and
2180`tex-end-of-header' are used to locate the header. Note that the
2181start of the header is required to be within the first 100 lines."
2182 (save-excursion
2183 (save-restriction
2184 (widen)
2185 (goto-char (point-min))
2186 (let ((search-end (save-excursion
2187 (forward-line 100)
2188 (point)))
2189 (already-output 0)
2190 hbeg hend)
2191 ;; Maybe copy first line, such as `\input texinfo', to temp file.
2192 (and tex-first-line-header-regexp
2193 (looking-at tex-first-line-header-regexp)
2194 (write-region (point)
2195 (progn (forward-line 1)
2196 (setq already-output (point)))
2197 file))
2198 ;; Write out the header, if there is one, and any of the
2199 ;; specified region which extends before it. But don't repeat
2200 ;; anything already written.
2201 (and tex-start-of-header
2202 (re-search-forward tex-start-of-header search-end t)
2203 (progn
2204 (beginning-of-line)
2205 (setq hbeg (point)) ; mark beginning of header
2206 (when (re-search-forward tex-end-of-header nil t)
2207 (forward-line 1)
2208 (setq hend (point)) ; mark end of header
2209 (write-region
2210 (max (if beg
2211 (min hbeg beg)
2212 hbeg)
2213 already-output)
2214 hend file (not (zerop already-output)))
2215 (setq already-output hend))))
2216 already-output))))
869bff31 2217
2218(defun tex-buffer ()
2219 "Run TeX on current buffer. See \\[tex-region] for more information.
528415e7
RS
2220Does not save the buffer, so it's useful for trying experimental versions.
2221See \\[tex-file] for an alternative."
869bff31 2222 (interactive)
2223 (tex-region (point-min) (point-max)))
2224
2225(defun tex-file ()
2226 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
2227This function is more useful than \\[tex-buffer] when you need the
2228`.aux' file of LaTeX to have the correct name."
2229 (interactive)
7abc9add
SS
2230 (when tex-offer-save
2231 (save-some-buffers))
d6709b80 2232 (let* ((source-file (tex-main-file))
07c16ec4 2233 (file-dir (file-name-directory (expand-file-name source-file))))
869bff31 2234 (if (tex-shell-running)
2235 (tex-kill-job)
2236 (tex-start-shell))
d6709b80 2237 (tex-start-tex tex-command source-file file-dir)
f05bd645 2238 (setq tex-print-file (expand-file-name source-file))))
869bff31 2239
2240(defun tex-generate-zap-file-name ()
2241 "Generate a unique name suitable for use as a file name."
2242 ;; Include the shell process number and host name
2243 ;; in case there are multiple shells (for same or different user).
f5cdb851
KH
2244 ;; Dec 1998: There is a report that some versions of xdvi
2245 ;; don't work with file names that start with #.
5616ee46 2246 (format "_TZ_%d-%s"
869bff31 2247 (process-id (get-buffer-process "*tex-shell*"))
07c16ec4 2248 (subst-char-in-string ?. ?- (system-name))))
869bff31 2249
2250;; This will perhaps be useful for modifying TEXINPUTS.
2251;; Expand each file name, separated by colons, in the string S.
2252(defun tex-expand-files (s)
2253 (let (elts (start 0))
2254 (while (string-match ":" s start)
2255 (setq elts (cons (substring s start (match-beginning 0)) elts))
2256 (setq start (match-end 0)))
2257 (or (= start 0)
2258 (setq elts (cons (substring s start) elts)))
c0df1972
SM
2259 (mapconcat (lambda (elt)
2260 (if (= (length elt) 0) elt (expand-file-name elt)))
5616ee46 2261 (nreverse elts) ":")))
869bff31 2262
2263(defun tex-shell-running ()
713f7b15 2264 (let ((proc (get-process "tex-shell")))
b781e739
SS
2265 (when proc
2266 (if (and (eq (process-status proc) 'run)
2267 (buffer-live-p (process-buffer proc)))
2268 ;; return the TeX process on success
2269 proc
2270 ;; get rid of the process permanently
2271 ;; this should get rid of the annoying w32 problem with
2272 ;; dead tex-shell buffer and live process
2273 (delete-process proc)))))
869bff31 2274
2275(defun tex-kill-job ()
2276 "Kill the currently running TeX job."
2277 (interactive)
b781e739 2278 ;; `quit-process' leads to core dumps of the tex process (except if
bed1b0c8
RS
2279 ;; coredumpsize has limit 0kb as on many environments). One would
2280 ;; like to use (kill-process proc 'lambda), however that construct
2281 ;; does not work on some systems and kills the shell itself.
b781e739
SS
2282 (let ((proc (get-process "tex-shell")))
2283 (when proc (quit-process proc t))))
869bff31 2284
2285(defun tex-recenter-output-buffer (linenum)
2286 "Redisplay buffer of TeX job output so that most recent output can be seen.
2287The last line of the buffer is displayed on
2288line LINE of the window, or centered if LINE is nil."
2289 (interactive "P")
2290 (let ((tex-shell (get-buffer "*tex-shell*"))
23b64225 2291 (window))
869bff31 2292 (if (null tex-shell)
2293 (message "No TeX output buffer")
23b64225
RS
2294 (setq window (display-buffer tex-shell))
2295 (save-selected-window
2296 (select-window window)
2297 (bury-buffer tex-shell)
2298 (goto-char (point-max))
2299 (recenter (if linenum
2300 (prefix-numeric-value linenum)
2301 (/ (window-height) 2)))))))
869bff31 2302
528415e7 2303(defun tex-print (&optional alt)
869bff31 2304 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1433a222
CZ
2305Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
2306is provided, use the alternative command, `tex-alt-dvi-print-command'."
528415e7 2307 (interactive "P")
869bff31 2308 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
2309 test-name)
2310 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
45c3304d
RS
2311 (buffer-file-name)
2312 ;; Check that this buffer's printed file is up to date.
869bff31 2313 (file-newer-than-file-p
2314 (setq test-name (tex-append (buffer-file-name) ".dvi"))
45c3304d 2315 (buffer-file-name)))
869bff31 2316 (setq print-file-name-dvi test-name))
528415e7
RS
2317 (if (not (file-exists-p print-file-name-dvi))
2318 (error "No appropriate `.dvi' file could be found")
460e1b7d
RS
2319 (if (tex-shell-running)
2320 (tex-kill-job)
2321 (tex-start-shell))
528415e7 2322 (tex-send-command
bed1b0c8 2323 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
b5352ff5 2324 print-file-name-dvi
602503c5 2325 t))))
869bff31 2326
cf6d6e8a
RS
2327(defun tex-alt-print ()
2328 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
002b0d00 2329Runs the shell command defined by `tex-alt-dvi-print-command'."
cf6d6e8a
RS
2330 (interactive)
2331 (tex-print t))
2332
869bff31 2333(defun tex-view ()
2334 "Preview the last `.dvi' file made by running TeX under Emacs.
2335This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2b7971c9
RS
2336The variable `tex-dvi-view-command' specifies the shell command for preview.
2337You must set that variable yourself before using this command,
2338because there is no standard value that would generally work."
869bff31 2339 (interactive)
2b7971c9
RS
2340 (or tex-dvi-view-command
2341 (error "You must set `tex-dvi-view-command'"))
3356ce3b
EZ
2342 ;; Restart the TeX shell if necessary.
2343 (or (tex-shell-running)
2344 (tex-start-shell))
746c30e2 2345 (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
869bff31 2346 (tex-print)))
2347
2348(defun tex-append (file-name suffix)
2349 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
cf6d6e8a 2350Pascal-based TeX scans for the first period, C TeX uses the last.
869bff31 2351No period is retained immediately before SUFFIX,
2352so normally SUFFIX starts with one."
2353 (if (stringp file-name)
cf6d6e8a
RS
2354 (let ((file (file-name-nondirectory file-name))
2355 trial-name)
6da9bbd6 2356 ;; Try splitting on last period.
7d0ca249
RS
2357 ;; The first-period split can get fooled when two files
2358 ;; named a.tex and a.b.tex are both tex'd;
2359 ;; the last-period split must be right if it matches at all.
cf6d6e8a
RS
2360 (setq trial-name
2361 (concat (file-name-directory file-name)
2362 (substring file 0
7d0ca249 2363 (string-match "\\.[^.]*$" file))
cf6d6e8a
RS
2364 suffix))
2365 (if (or (file-exists-p trial-name)
2366 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
2367 trial-name
7d0ca249 2368 ;; Not found, so split on first period.
cf6d6e8a
RS
2369 (concat (file-name-directory file-name)
2370 (substring file 0
7d0ca249 2371 (string-match "\\." file))
cf6d6e8a 2372 suffix)))
869bff31 2373 " "))
2374
2375(defun tex-show-print-queue ()
2376 "Show the print queue that \\[tex-print] put your job on.
1433a222 2377Runs the shell command defined by `tex-show-queue-command'."
869bff31 2378 (interactive)
2379 (if (tex-shell-running)
2380 (tex-kill-job)
2381 (tex-start-shell))
51b2c841
RS
2382 (tex-send-command tex-show-queue-command)
2383 (tex-display-shell))
869bff31 2384
2385(defun tex-bibtex-file ()
2386 "Run BibTeX on the current buffer's file."
2387 (interactive)
2388 (if (tex-shell-running)
2389 (tex-kill-job)
2390 (tex-start-shell))
e6b0b773
MR
2391 (let (shell-dirtrack-verbose
2392 (tex-out-file
869bff31 2393 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
2394 (file-dir (file-name-directory (buffer-file-name))))
8ca66348 2395 (tex-send-command tex-shell-cd-command file-dir)
51b2c841
RS
2396 (tex-send-command tex-bibtex-command tex-out-file))
2397 (tex-display-shell))
ea590e1c
SM
2398\f
2399;;;;
2400;;;; LaTeX indentation
2401;;;;
2402
2403(defvar tex-indent-allhanging t)
2404(defvar tex-indent-arg 4)
2405(defvar tex-indent-basic 2)
2406(defvar tex-indent-item tex-indent-basic)
2407(defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
dd166d5f 2408(defvar latex-noindent-environments '("document"))
ea590e1c 2409
8a591d52
SM
2410(defvar tex-latex-indent-syntax-table
2411 (let ((st (make-syntax-table tex-mode-syntax-table)))
2412 (modify-syntax-entry ?$ "." st)
2413 (modify-syntax-entry ?\( "." st)
2414 (modify-syntax-entry ?\) "." st)
2415 st)
2416 "Syntax table used while computing indentation.")
ea590e1c
SM
2417
2418(defun latex-indent (&optional arg)
7afecb99 2419 (if (and (eq (get-text-property (line-beginning-position) 'face)
014e29b9 2420 'tex-verbatim))
a3d80d4a 2421 'noindent
7afecb99
SM
2422 (with-syntax-table tex-latex-indent-syntax-table
2423 ;; TODO: Rather than ignore $, we should try to be more clever about it.
2424 (let ((indent
2425 (save-excursion
2426 (beginning-of-line)
2427 (latex-find-indent))))
2428 (if (< indent 0) (setq indent 0))
2429 (if (<= (current-column) (current-indentation))
2430 (indent-line-to indent)
2431 (save-excursion (indent-line-to indent)))))))
ea590e1c
SM
2432
2433(defun latex-find-indent (&optional virtual)
2434 "Find the proper indentation of text after point.
2435VIRTUAL if non-nil indicates that we're only trying to find the indentation
2436 in order to determine the indentation of something else.
2437There might be text before point."
2438 (save-excursion
2439 (skip-chars-forward " \t")
2440 (or
7afecb99
SM
2441 ;; Stick the first line at column 0.
2442 (and (= (point-min) (line-beginning-position)) 0)
ea590e1c 2443 ;; Trust the current indentation, if such info is applicable.
7afecb99
SM
2444 (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
2445 (current-column))
2446 ;; Stick verbatim environments to the left margin.
2447 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2448 (member (match-string 2) tex-verbatim-environments)
2449 0)
ea590e1c
SM
2450 ;; Put leading close-paren where the matching open brace would be.
2451 (and (eq (latex-syntax-after) ?\))
2452 (ignore-errors
2453 (save-excursion
2454 (latex-skip-close-parens)
2455 (latex-backward-sexp-1)
2456 (latex-find-indent 'virtual))))
2457 ;; Default (maybe an argument)
2458 (let ((pos (point))
ea590e1c
SM
2459 ;; Outdent \item if necessary.
2460 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
2461 up-list-pos)
2462 ;; Find the previous point which determines our current indentation.
2463 (condition-case err
2464 (progn
2465 (latex-backward-sexp-1)
2466 (while (> (current-column) (current-indentation))
2467 (latex-backward-sexp-1)))
2468 (scan-error
2469 (setq up-list-pos (nth 2 err))))
8908cf40
SM
2470 (cond
2471 ((= (point-min) pos) 0) ; We're really just indenting the first line.
2472 ((integerp up-list-pos)
2473 ;; Have to indent relative to the open-paren.
2474 (goto-char up-list-pos)
2475 (if (and (not tex-indent-allhanging)
dd166d5f
SM
2476 (save-excursion
2477 ;; Make sure we're an argument to a macro and
2478 ;; that the macro is at the beginning of a line.
2479 (condition-case nil
2480 (progn
2481 (while (eq (char-syntax (char-after)) ?\()
2482 (forward-sexp -1))
2483 (and (eq (char-syntax (char-after)) ?/)
2484 (progn (skip-chars-backward " \t&")
2485 (bolp))))
2486 (scan-error nil)))
8908cf40
SM
2487 (> pos (progn (latex-down-list)
2488 (forward-comment (point-max))
2489 (point))))
7afecb99 2490 ;; Align with the first element after the open-paren.
8908cf40
SM
2491 (current-column)
2492 ;; We're the first element after a hanging brace.
2493 (goto-char up-list-pos)
dd166d5f
SM
2494 (+ (if (and (looking-at "\\\\begin *{\\([^\n}]+\\)")
2495 (member (match-string 1)
2496 latex-noindent-environments))
2497 0 tex-indent-basic)
2498 indent (latex-find-indent 'virtual))))
8908cf40
SM
2499 ;; We're now at the "beginning" of a line.
2500 ((not (and (not virtual) (eq (char-after) ?\\)))
2501 ;; Nothing particular here: just keep the same indentation.
2502 (+ indent (current-column)))
2503 ;; We're now looking at a macro call.
dd166d5f
SM
2504 ((looking-at tex-indent-item-re)
2505 ;; Indenting relative to an item, have to re-add the outdenting.
8908cf40
SM
2506 (+ indent (current-column) tex-indent-item))
2507 (t
2508 (let ((col (current-column)))
d1218e3e 2509 (if (or (not (eq (char-syntax (or (char-after pos) ?\s)) ?\())
dd166d5f
SM
2510 ;; Can't be an arg if there's an empty line inbetween.
2511 (save-excursion (re-search-forward "^[ \t]*$" pos t)))
8908cf40
SM
2512 ;; If the first char was not an open-paren, there's
2513 ;; a risk that this is really not an argument to the
2514 ;; macro at all.
21749f14
RS
2515 (+ indent col)
2516 (forward-sexp 1)
2517 (if (< (line-end-position)
2518 (save-excursion (forward-comment (point-max))
2519 (point)))
8908cf40
SM
2520 ;; we're indenting the first argument.
2521 (min (current-column) (+ tex-indent-arg col))
2522 (skip-syntax-forward " ")
2523 (current-column))))))))))
a3d80d4a
SM
2524;;; DocTeX support
2525
2526(defun doctex-font-lock-^^A ()
2527 (if (eq (char-after (line-beginning-position)) ?\%)
2528 (progn
2529 (put-text-property
2530 (1- (match-beginning 1)) (match-beginning 1)
2531 'syntax-table
2532 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2533 ;; The `%' is a single-char comment, which Emacs
2534 ;; syntax-table can't deal with. We could turn it
2535 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2536 ;; Instead, we include it in the ^^A comment.
2537 (eval-when-compile (string-to-syntax "< b"))
2538 (eval-when-compile (string-to-syntax ">"))))
2539 (let ((end (line-end-position)))
2540 (if (< end (point-max))
2541 (put-text-property
2542 end (1+ end)
2543 'syntax-table
2544 (eval-when-compile (string-to-syntax "> b")))))
2545 (eval-when-compile (string-to-syntax "< b")))))
2546
2547(defun doctex-font-lock-syntactic-face-function (state)
2548 ;; Mark DocTeX documentation, which is parsed as a style A comment
2549 ;; starting in column 0.
2550 (if (or (nth 3 state) (nth 7 state)
2551 (not (memq (char-before (nth 8 state))
2552 '(?\n nil))))
2553 ;; Anything else is just as for LaTeX.
2554 (tex-font-lock-syntactic-face-function state)
2555 font-lock-doc-face))
2556
2557(defvar doctex-font-lock-syntactic-keywords
2558 (append
2559 tex-font-lock-syntactic-keywords
2560 ;; For DocTeX comment-in-doc.
2561 `(("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A))))))
2562
2563(defvar doctex-font-lock-keywords
2564 (append tex-font-lock-keywords
2565 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t)))))
2566
2567;;;###autoload
2568(define-derived-mode doctex-mode latex-mode "DocTeX"
2569 "Major mode to edit DocTeX files."
2570 (setq font-lock-defaults
2571 (cons (append (car font-lock-defaults) '(doctex-font-lock-keywords))
2572 (mapcar
2573 (lambda (x)
2574 (case (car-safe x)
2575 (font-lock-syntactic-keywords
2576 (cons (car x) 'doctex-font-lock-syntactic-keywords))
2577 (font-lock-syntactic-face-function
2578 (cons (car x) 'doctex-font-lock-syntactic-face-function))
2579 (t x)))
2580 (cdr font-lock-defaults)))))
528415e7
RS
2581
2582(run-hooks 'tex-mode-load-hook)
869bff31 2583
49116ac0
JB
2584(provide 'tex-mode)
2585
dd166d5f 2586;; arch-tag: c0a680b1-63aa-4547-84b9-4193c29c0080
d501f516 2587;;; tex-mode.el ends here