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