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