(uniquify-rationalize-file-buffer-names):
[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
1b741d9e 3;; Copyright (C) 1985, 86, 89, 92, 94, 95, 96, 97, 98, 1999, 2002
d61140e8 4;; 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
RS
25;; along with GNU Emacs; see the file COPYING. If not, write to the
26;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27;; Boston, MA 02111-1307, 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
a0e9c22a 39(require 'shell)
2f3067de 40(require 'compile)
528415e7 41
d61140e8
RS
42(defgroup tex-file nil
43 "TeX files and directories"
44 :prefix "tex-"
45 :group 'tex)
46
47(defgroup tex-run nil
48 "Running external commands from TeX mode"
49 :prefix "tex-"
50 :group 'tex)
51
52(defgroup tex-view nil
53 "Viewing and printing TeX files"
54 :prefix "tex-"
55 :group 'tex)
56
7e1dae73 57;;;###autoload
d61140e8
RS
58(defcustom tex-shell-file-name nil
59 "*If non-nil, the shell file name to run in the subshell used to run TeX."
60 :type '(choice (const :tag "None" nil)
61 string)
62 :group 'tex-run)
528415e7 63
7e1dae73 64;;;###autoload
d61140e8 65(defcustom tex-directory "."
f73741fc 66 "*Directory in which temporary files are written.
81c735c0 67You can make this `/tmp' if your TEXINPUTS has no relative directories in it
528415e7 68and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
d61140e8
RS
69`\\input' commands with relative directories."
70 :type 'directory
71 :group 'tex-file)
869bff31 72
725b7428 73;;;###autoload
d61140e8 74(defcustom tex-first-line-header-regexp nil
725b7428
RS
75 "Regexp for matching a first line which `tex-region' should include.
76If this is non-nil, it should be a regular expression string;
77if it matches the first line of the file,
d61140e8
RS
78`tex-region' always includes the first line in the TeX run."
79 :type '(choice (const :tag "None" nil)
80 regexp)
81 :group 'tex-file)
725b7428 82
f73741fc 83;;;###autoload
d61140e8 84(defcustom tex-main-file nil
f73741fc 85 "*The main TeX source file which includes this buffer's file.
be4a962d
RS
86The command `tex-file' runs TeX on the file specified by `tex-main-file'
87if the variable is non-nil."
d61140e8
RS
88 :type '(choice (const :tag "None" nil)
89 file)
90 :group 'tex-file)
f73741fc 91
7e1dae73 92;;;###autoload
d61140e8
RS
93(defcustom tex-offer-save t
94 "*If non-nil, ask about saving modified buffers before \\[tex-file] is run."
95 :type 'boolean
96 :group 'tex-file)
869bff31 97
7e1dae73 98;;;###autoload
d61140e8 99(defcustom tex-run-command "tex"
869bff31 100 "*Command used to run TeX subjob.
c3ce7bf4
RS
101TeX Mode sets `tex-command' to this string.
102See the documentation of that variable."
d61140e8
RS
103 :type 'string
104 :group 'tex-run)
869bff31 105
7e1dae73 106;;;###autoload
d61140e8 107(defcustom latex-run-command "latex"
869bff31 108 "*Command used to run LaTeX subjob.
c3ce7bf4
RS
109LaTeX Mode sets `tex-command' to this string.
110See the documentation of that variable."
d61140e8
RS
111 :type 'string
112 :group 'tex-run)
528415e7 113
bed1b0c8
RS
114;;;###autoload
115(defcustom slitex-run-command "slitex"
116 "*Command used to run SliTeX subjob.
c3ce7bf4
RS
117SliTeX Mode sets `tex-command' to this string.
118See the documentation of that variable."
bed1b0c8
RS
119 :type 'string
120 :group 'tex-run)
121
c3ce7bf4 122;;;###autoload
95a045bd 123(defcustom tex-start-options ""
9e0ad27a 124 "*TeX options to use when starting TeX.
95a045bd
SM
125These immediately precede the commands in `tex-start-commands'
126and the input file name, with no separating space and are not shell-quoted.
127If nil, TeX runs with no options. See the documentation of `tex-command'."
128 :type 'string
bed1b0c8 129 :group 'tex-run
9e0ad27a
RS
130 :version "21.4")
131
132;;;###autoload
133(defcustom tex-start-commands "\\nonstopmode\\input"
134 "*TeX commands to use when starting TeX.
95a045bd
SM
135They are shell-quoted and precede the input file name, with a separating space.
136If nil, no commands are used. See the documentation of `tex-command'."
9e0ad27a
RS
137 :type '(radio (const :tag "Interactive \(nil\)" nil)
138 (const :tag "Nonstop \(\"\\nonstopmode\\input\"\)"
139 "\\nonstopmode\\input")
140 (string :tag "String at your choice"))
141 :group 'tex-run
142 :version "21.4")
bed1b0c8 143
7afecb99 144(defvar latex-standard-block-names
dd459839
SM
145 '("abstract" "array" "center" "description"
146 "displaymath" "document" "enumerate" "eqnarray"
147 "eqnarray*" "equation" "figure" "figure*"
148 "flushleft" "flushright" "itemize" "letter"
149 "list" "minipage" "picture" "quotation"
150 "quote" "slide" "sloppypar" "tabbing"
151 "table" "table*" "tabular" "tabular*"
152 "thebibliography" "theindex*" "titlepage" "trivlist"
153 "verbatim" "verbatim*" "verse" "math")
528415e7
RS
154 "Standard LaTeX block names.")
155
7e1dae73 156;;;###autoload
d61140e8 157(defcustom latex-block-names nil
528415e7 158 "*User defined LaTeX block names.
7afecb99 159Combined with `latex-standard-block-names' for minibuffer completion."
d61140e8
RS
160 :type '(repeat string)
161 :group 'tex-run)
869bff31 162
7e1dae73 163;;;###autoload
d61140e8 164(defcustom tex-bibtex-command "bibtex"
528415e7 165 "*Command used by `tex-bibtex-file' to gather bibliographic data.
81c735c0 166If this string contains an asterisk (`*'), that is replaced by the file name;
d61140e8
RS
167otherwise, the file name, preceded by blank, is added at the end."
168 :type 'string
169 :group 'tex-run)
869bff31 170
7e1dae73 171;;;###autoload
d61140e8 172(defcustom tex-dvi-print-command "lpr -d"
528415e7 173 "*Command used by \\[tex-print] to print a .dvi file.
81c735c0 174If this string contains an asterisk (`*'), that is replaced by the file name;
d61140e8
RS
175otherwise, the file name, preceded by blank, is added at the end."
176 :type 'string
177 :group 'tex-view)
528415e7 178
7e1dae73 179;;;###autoload
d61140e8 180(defcustom tex-alt-dvi-print-command "lpr -d"
528415e7 181 "*Command used by \\[tex-print] with a prefix arg to print a .dvi file.
81c735c0
RS
182If this string contains an asterisk (`*'), that is replaced by the file name;
183otherwise, the file name, preceded by blank, is added at the end.
528415e7 184
81c735c0
RS
185If two printers are not enough of a choice, you can set the variable
186`tex-alt-dvi-print-command' to an expression that asks what you want;
528415e7
RS
187for example,
188
189 (setq tex-alt-dvi-print-command
190 '(format \"lpr -P%s\" (read-string \"Use printer: \")))
191
192would tell \\[tex-print] with a prefix argument to ask you which printer to
d61140e8
RS
193use."
194 :type '(choice (string :tag "Command")
195 (sexp :tag "Expression"))
196 :group 'tex-view)
869bff31 197
7e1dae73 198;;;###autoload
746c30e2 199(defcustom tex-dvi-view-command '(if (eq window-system 'x) \"xdvi\" \"dvi2tty * | cat -s\")
81c735c0 200 "*Command used by \\[tex-view] to display a `.dvi' file.
746c30e2 201If it is a string, that specifies the command directly.
81c735c0 202If this string contains an asterisk (`*'), that is replaced by the file name;
746c30e2 203otherwise, the file name, preceded by a space, is added at the end.
528415e7 204
746c30e2
RS
205If the value is a form, it is evaluated to get the command to use."
206 :type '(choice (const nil) string sexp)
d61140e8 207 :group 'tex-view)
869bff31 208
7e1dae73 209;;;###autoload
d61140e8 210(defcustom tex-show-queue-command "lpq"
528415e7 211 "*Command used by \\[tex-show-print-queue] to show the print queue.
d61140e8
RS
212Should show the queue(s) that \\[tex-print] puts jobs on."
213 :type 'string
214 :group 'tex-view)
869bff31 215
7e1dae73 216;;;###autoload
9920303f 217(defcustom tex-default-mode 'latex-mode
869bff31 218 "*Mode to enter for a new file that might be either TeX or LaTeX.
219This variable is used when it can't be determined whether the file
220is plain TeX or LaTeX or what because the file contains no commands.
d61140e8
RS
221Normally set to either `plain-tex-mode' or `latex-mode'."
222 :type 'function
223 :group 'tex)
869bff31 224
7e1dae73 225;;;###autoload
d61140e8
RS
226(defcustom tex-open-quote "``"
227 "*String inserted by typing \\[tex-insert-quote] to open a quotation."
228 :type 'string
95a045bd 229 :options '("``" "\"<" "\"`" "<<" "«")
d61140e8 230 :group 'tex)
869bff31 231
7e1dae73 232;;;###autoload
d61140e8
RS
233(defcustom tex-close-quote "''"
234 "*String inserted by typing \\[tex-insert-quote] to close a quotation."
235 :type 'string
95a045bd 236 :options '("''" "\">" "\"'" ">>" "»")
d61140e8 237 :group 'tex)
869bff31 238
528415e7
RS
239(defvar tex-last-temp-file nil
240 "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
241Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
81c735c0 242tex shell terminates.")
528415e7 243
95a045bd 244(defvar tex-command "tex"
c3ce7bf4 245 "*Command to run TeX.
95a045bd 246If this string contains an asterisk \(`*'\), that is replaced by the file name;
9e0ad27a
RS
247otherwise the value of `tex-start-options', the \(shell-quoted\)
248value of `tex-start-commands', and the file name are added at the end
249with blanks as separators.
c3ce7bf4
RS
250
251In TeX, LaTeX, and SliTeX Mode this variable becomes buffer local.
252In these modes, use \\[set-variable] if you want to change it for the
253current buffer.")
869bff31 254
255(defvar tex-trailer nil
256 "String appended after the end of a region sent to TeX by \\[tex-region].")
257
258(defvar tex-start-of-header nil
898b9ac1 259 "Regular expression used by \\[tex-region] to find start of file's header.")
869bff31 260
261(defvar tex-end-of-header nil
898b9ac1 262 "Regular expression used by \\[tex-region] to find end of file's header.")
869bff31 263
264(defvar tex-shell-cd-command "cd"
265 "Command to give to shell running TeX to change directory.
81c735c0 266The value of `tex-directory' is appended to this, separated by a space.")
869bff31 267
268(defvar tex-zap-file nil
269 "Temporary file name used for text being sent as input to TeX.
270Should be a simple file name with no extension or directory specification.")
271
272(defvar tex-last-buffer-texed nil
273 "Buffer which was last TeXed.")
274
275(defvar tex-print-file nil
276 "File name that \\[tex-print] prints.
277Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
278
ea590e1c
SM
279(easy-mmode-defsyntax tex-mode-syntax-table
280 '((?% . "<")
281 (?\n . ">")
282 (?\f . ">")
283 (?\C-@ . "w")
284 (?' . "w")
285 (?@ . "_")
286 (?* . "_")
287 (?\t . " ")
288 (?~ . " ")
289 (?$ . "$$")
290 (?\\ . "/")
291 (?\" . ".")
292 (?& . ".")
15ca8de7
SM
293 (?_ . ".")
294 (?^ . "."))
869bff31 295 "Syntax table used while in TeX mode.")
53c4fe47
SM
296\f
297;;;;
298;;;; Imenu support
299;;;;
869bff31 300
d6709b80 301(defcustom latex-imenu-indent-string ". "
a53c647b
RS
302 "*String to add repeated in front of nested sectional units for Imenu.
303An alternative value is \" . \", if you use a font with a narrow period."
304 :type 'string
305 :group 'tex)
306
d6709b80
SM
307(defvar latex-section-alist
308 '(("part" . 0) ("chapter" . 1)
309 ("section" . 2) ("subsection" . 3)
310 ("subsubsection" . 4)
311 ("paragraph" . 5) ("subparagraph" . 6)))
312
53c4fe47
SM
313(defvar latex-metasection-list
314 '("documentstyle" "documentclass"
315 "begin{document}" "end{document}"
316 "appendix" "frontmatter" "mainmatter" "backmatter"))
317
a5e2ae01 318(defun latex-imenu-create-index ()
53c4fe47
SM
319 "Generate an alist for imenu from a LaTeX buffer."
320 (let ((section-regexp
321 (concat "\\\\" (regexp-opt (mapcar 'car latex-section-alist) t)
322 "\\*?[ \t]*{"))
323 (metasection-regexp
324 (concat "\\\\" (regexp-opt latex-metasection-list t)))
325 i0 menu case-fold-search)
a53c647b
RS
326 (save-excursion
327 ;; Find the top-most level in this file but don't allow it to be
328 ;; any deeper than "section" (which is top-level in an article).
329 (goto-char (point-min))
330 (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t)
331 (setq i0 0)
332 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
333 (setq i0 1)
334 (setq i0 2)))
335
336 ;; Look for chapters and sections.
337 (goto-char (point-min))
53c4fe47 338 (while (search-forward-regexp section-regexp nil t)
a53c647b
RS
339 (let ((start (match-beginning 0))
340 (here (point))
341 (i (cdr (assoc (buffer-substring-no-properties
342 (match-beginning 1)
343 (match-end 1))
d6709b80 344 latex-section-alist))))
a53c647b
RS
345 (backward-char 1)
346 (condition-case err
347 (progn
348 ;; Using sexps allows some use of matching {...} inside
349 ;; titles.
350 (forward-sexp 1)
d6709b80
SM
351 (push (cons (concat (apply 'concat
352 (make-list
353 (max 0 (- i i0))
354 latex-imenu-indent-string))
355 (buffer-substring-no-properties
356 here (1- (point))))
357 start)
358 menu))
a53c647b
RS
359 (error nil))))
360
361 ;; Look for included material.
362 (goto-char (point-min))
363 (while (search-forward-regexp
364 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
53c4fe47 365\[ \t]*{\\([^}\n]+\\)}"
a53c647b 366 nil t)
53c4fe47
SM
367 (push (cons (concat "<<" (buffer-substring-no-properties
368 (match-beginning 2)
369 (match-end 2))
370 (if (= (char-after (match-beginning 1)) ?b)
371 ".bbl"
372 ".tex"))
373 (match-beginning 0))
374 menu))
a53c647b
RS
375
376 ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
377 (goto-char (point-min))
53c4fe47
SM
378 (while (search-forward-regexp metasection-regexp nil t)
379 (push (cons "--" (match-beginning 0)) menu))
a53c647b
RS
380
381 ;; Sort in increasing buffer position order.
382 (sort menu (function (lambda (a b) (< (cdr a) (cdr b))))))))
53c4fe47
SM
383\f
384;;;;
385;;;; Outline support
386;;;;
387
388(defvar latex-outline-regexp
389 (concat "\\\\"
390 (regexp-opt (append latex-metasection-list
391 (mapcar 'car latex-section-alist)) t)))
392
393(defun latex-outline-level ()
394 (if (looking-at latex-outline-regexp)
395 (1+ (or (cdr (assoc (match-string 1) latex-section-alist)) -1))
396 1000))
397\f
398;;;;
399;;;; Font-Lock support
400;;;;
401
402;(defvar tex-font-lock-keywords
403; ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
404; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
405; 2 font-lock-function-name-face)
406; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
407; 2 font-lock-constant-face)
408; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
409; ;; not be able to display those fonts.
410; ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
411; ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
412; ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
413; ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
414; ;; Rewritten and extended for LaTeX2e by 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; ("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)" 1 font-lock-function-name-face)
420; "\\\\\\([a-zA-Z@]+\\|.\\)"
421; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
422; ;; not be able to display those fonts.
423; ;; LaTeX2e: \emph{This is emphasized}.
424; ("\\\\emph{\\([^}]+\\)}" 1 'italic keep)
425; ;; LaTeX2e: \textbf{This is bold}, \textit{...}, \textsl{...}
426; ("\\\\text\\(\\(bf\\)\\|it\\|sl\\){\\([^}]+\\)}"
427; 3 (if (match-beginning 2) 'bold 'italic) keep)
428; ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
429; ("\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)"
430; 3 (if (match-beginning 2) 'bold 'italic) keep))
431
432;; Rewritten with the help of Alexandra Bac <abac@welcome.disi.unige.it>.
433(defconst tex-font-lock-keywords-1
434 (eval-when-compile
435 (let* (;; Names of commands whose arg should be fontified as heading, etc.
436 (headings (regexp-opt
437 '("title" "begin" "end" "chapter" "part"
438 "section" "subsection" "subsubsection"
439 "paragraph" "subparagraph" "subsubparagraph"
7afecb99
SM
440 "newcommand" "renewcommand" "providecommand"
441 "newenvironment" "renewenvironment"
442 "newtheorem" "renewtheorem")
53c4fe47
SM
443 t))
444 (variables (regexp-opt
445 '("newcounter" "newcounter*" "setcounter" "addtocounter"
446 "setlength" "addtolength" "settowidth")
447 t))
448 (includes (regexp-opt
449 '("input" "include" "includeonly" "bibliography"
450 "epsfig" "psfig" "epsf" "nofiles" "usepackage"
15ca8de7 451 "documentstyle" "documentclass" "verbatiminput"
53c4fe47
SM
452 "includegraphics" "includegraphics*")
453 t))
454 ;; Miscellany.
455 (slash "\\\\")
15ca8de7
SM
456 (opt " *\\(\\[[^]]*\\] *\\)*")
457 ;; This would allow highlighting \newcommand\CMD but requires
458 ;; adapting subgroup numbers below.
459 ;; (arg "\\(?:{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)\\|\\\\[a-z*]+\\)"))
1598a961 460 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
53c4fe47 461 (list
95a045bd
SM
462 ;; display $$ math $$
463 ;; We only mark the match between $$ and $$ because the $$ delimiters
464 ;; themselves have already been marked (along with $..$) by syntactic
465 ;; fontification. Also this is done at the very beginning so as to
466 ;; interact with the other keywords in the same way as $...$ does.
467 (list "\\$\\$\\([^$]+\\)\\$\\$" 1 'tex-math-face)
53c4fe47
SM
468 ;; Heading args.
469 (list (concat slash headings "\\*?" opt arg)
bdbd9606
SM
470 ;; If ARG ends up matching too much (if the {} don't match, f.ex)
471 ;; jit-lock will do funny things: when updating the buffer
472 ;; the re-highlighting is only done locally so it will just
473 ;; match the local line, but defer-contextually will
474 ;; match more lines at a time, so ARG will end up matching
475 ;; a lot more, which might suddenly include a comment
476 ;; so you get things highlighted bold when you type them
477 ;; but they get turned back to normal a little while later
478 ;; because "there's already a face there".
479 ;; Using `keep' works around this un-intuitive behavior as well
15ca8de7
SM
480 ;; as improves the behavior in the very rare case where you do
481 ;; have a comment in ARG.
bdbd9606 482 3 'font-lock-function-name-face 'keep)
7afecb99
SM
483 (list (concat slash "\\(?:provide\\|\\(?:re\\)?new\\)command\\** *\\(\\\\[A-Za-z@]+\\)")
484 1 'font-lock-function-name-face 'keep)
53c4fe47 485 ;; Variable args.
15ca8de7 486 (list (concat slash variables " *" arg) 2 'font-lock-variable-name-face)
53c4fe47
SM
487 ;; Include args.
488 (list (concat slash includes opt arg) 3 'font-lock-builtin-face)
489 ;; Definitions. I think.
15ca8de7 490 '("^[ \t]*\\\\def *\\\\\\(\\(\\w\\|@\\)+\\)"
bdbd9606 491 1 font-lock-function-name-face))))
53c4fe47
SM
492 "Subdued expressions to highlight in TeX modes.")
493
494(defconst tex-font-lock-keywords-2
495 (append tex-font-lock-keywords-1
496 (eval-when-compile
497 (let* (;;
498 ;; Names of commands whose arg should be fontified with fonts.
1598a961 499 (bold (regexp-opt '("textbf" "textsc" "textup"
53c4fe47 500 "boldsymbol" "pmb") t))
1598a961 501 (italic (regexp-opt '("textit" "textsl" "emph") t))
a3d80d4a
SM
502 ;; FIXME: unimplemented yet.
503 ;; (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
53c4fe47
SM
504 ;;
505 ;; Names of commands whose arg should be fontified as a citation.
506 (citations (regexp-opt
507 '("label" "ref" "pageref" "vref" "eqref"
15ca8de7 508 "cite" "nocite" "index" "glossary" "bibitem"
1598a961
SM
509 ;; These are text, rather than citations.
510 ;; "caption" "footnote" "footnotemark" "footnotetext"
511 )
53c4fe47
SM
512 t))
513 ;;
514 ;; Names of commands that should be fontified.
1b741d9e
AS
515 (specials-1 (regexp-opt '("\\" "\\*") t)) ;; "-"
516 (specials-2 (regexp-opt
517 '("linebreak" "nolinebreak" "pagebreak" "nopagebreak"
518 "newline" "newpage" "clearpage" "cleardoublepage"
519 "displaybreak" "allowdisplaybreaks"
520 "enlargethispage") t))
53c4fe47
SM
521 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
522 ;;
523 ;; Miscellany.
524 (slash "\\\\")
15ca8de7 525 (opt " *\\(\\[[^]]*\\] *\\)*")
7afecb99 526 (args "\\(\\(?:[^{}&\\]+\\|\\\\.\\|{[^}]*}\\)+\\)")
1598a961 527 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
53c4fe47
SM
528 (list
529 ;;
530 ;; Citation args.
531 (list (concat slash citations opt arg) 3 'font-lock-constant-face)
532 ;;
15ca8de7 533 ;; Text between `` quotes ''.
95a045bd 534 (cons (concat (regexp-opt `("``" "\"<" "\"`" "<<" "«") t)
7abc9add 535 "[^'\">{]+" ;a bit pessimistic
95a045bd 536 (regexp-opt `("''" "\">" "\"'" ">>" "»") t))
15ca8de7
SM
537 'font-lock-string-face)
538 ;;
53c4fe47 539 ;; Command names, special and general.
1b741d9e
AS
540 (cons (concat slash specials-1) 'font-lock-warning-face)
541 (list (concat "\\(" slash specials-2 "\\)\\([^a-zA-Z@]\\|\\'\\)")
542 1 'font-lock-warning-face)
53c4fe47
SM
543 (concat slash general)
544 ;;
545 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
546 ;; since we might not be able to display those fonts.
15ca8de7
SM
547 (list (concat slash bold " *" arg) 2 '(quote bold) 'append)
548 (list (concat slash italic " *" arg) 2 '(quote italic) 'append)
1598a961 549 ;; (list (concat slash type arg) 2 '(quote bold-italic) 'append)
53c4fe47
SM
550 ;;
551 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
7afecb99
SM
552 (list (concat "\\\\\\(em\\|it\\|sl\\)\\>" args)
553 2 '(quote italic) 'append)
554 ;; This is separate from the previous one because of cases like
555 ;; {\em foo {\bf bar} bla} where both match.
556 (list (concat "\\\\bf\\>" args) 1 '(quote bold) 'append)))))
53c4fe47
SM
557 "Gaudy expressions to highlight in TeX modes.")
558
7afecb99
SM
559(defun tex-font-lock-suscript (pos)
560 (unless (or (memq (get-text-property pos 'face)
561 '(font-lock-constant-face font-lock-builtin-face
562 font-lock-comment-face tex-verbatim-face))
563 ;; Check for backslash quoting
564 (let ((odd nil)
565 (pos pos))
566 (while (eq (char-before pos) ?\\)
567 (setq pos (1- pos) odd (not odd)))
568 odd))
569 (if (eq (char-after pos) ?_)
570 '(face subscript display (raise -0.3))
571 '(face superscript display (raise +0.3)))))
572
573(defconst tex-font-lock-keywords-3
574 (append tex-font-lock-keywords-2
575 (eval-when-compile
576 (let ((general "\\([a-zA-Z@]+\\|[^ \t\n]\\)")
577 (slash "\\\\")
578 ;; This is not the same regexp as before: it has a `+' removed.
579 ;; The + makes the matching faster in the above cases (where we can
580 ;; exit as soon as the match fails) but would make this matching
581 ;; degenerate to nasty complexity (because we try to match the
582 ;; closing brace, which forces trying all matching combinations).
583 (arg "{\\(?:[^{}\\]\\|\\\\.\\|{[^}]*}\\)*"))
584 `((,(concat "[_^] *\\([^\n\\{}]\\|" slash general "\\|" arg "}\\)")
585 (1 (tex-font-lock-suscript (match-beginning 0))
586 append))))))
587 "Experimental expressions to highlight in TeX modes.")
588
53c4fe47
SM
589(defvar tex-font-lock-keywords tex-font-lock-keywords-1
590 "Default expressions to highlight in TeX modes.")
0fb4f245 591
7afecb99
SM
592(defvar tex-verbatim-environments
593 '("verbatim" "verbatim*"))
594
595(defvar tex-font-lock-syntactic-keywords
596 (let ((verbs (regexp-opt tex-verbatim-environments t)))
597 `((,(concat "^\\\\begin *{" verbs "}.*\\(\n\\)") 2 "|")
598 (,(concat "^\\\\end *{" verbs "}\\(.?\\)") 2
599 (unless (<= (match-beginning 0) (point-min))
600 (put-text-property (1- (match-beginning 0)) (match-beginning 0)
601 'syntax-table (string-to-syntax "|"))
602 "<"))
603 ;; ("^\\(\\\\\\)begin *{comment}" 1 "< b")
604 ;; ("^\\\\end *{comment}.*\\(\n\\)" 1 "> b")
605 ("\\\\verb\\**\\([^a-z@*]\\)" 1 "\""))))
606
607(defun tex-font-lock-unfontify-region (beg end)
608 (font-lock-default-unfontify-region beg end)
609 (while (< beg end)
610 (let ((next (next-single-property-change beg 'display nil end))
611 (prop (get-text-property beg 'display)))
612 (if (and (eq (car-safe prop) 'raise)
613 (member (car-safe (cdr prop)) '(-0.3 +0.3))
614 (null (cddr prop)))
615 (put-text-property beg next 'display nil))
616 (setq beg next))))
617
618(defface superscript
619 '((t :height 0.8)) ;; :raise 0.3
620 "Face used for superscripts.")
621(defface subscript
622 '((t :height 0.8)) ;; :raise -0.3
623 "Face used for subscripts.")
bdbd9606
SM
624
625(defface tex-math-face
626 '((t :inherit font-lock-string-face))
627 "Face used to highlight TeX math expressions.")
628(defvar tex-math-face 'tex-math-face)
7afecb99
SM
629(defface tex-verbatim-face
630 ;; '((t :inherit font-lock-string-face))
631 '((t :family "courier"))
632 "Face used to highlight TeX verbatim environments.")
633(defvar tex-verbatim-face 'tex-verbatim-face)
bdbd9606
SM
634
635;; Use string syntax but math face for $...$.
636(defun tex-font-lock-syntactic-face-function (state)
7afecb99
SM
637 (let ((char (nth 3 state)))
638 (cond
639 ((not char) font-lock-comment-face)
640 ((eq char ?$) tex-math-face)
641 (t
642 (when (char-valid-p char)
643 ;; This is a \verb?...? construct. Let's find the end and mark it.
644 (save-excursion
645 (skip-chars-forward (string ?^ char)) ;; Use `end' ?
646 (when (eq (char-syntax (preceding-char)) ?/)
647 (put-text-property (1- (point)) (point) 'syntax-table '(1)))
648 (unless (eobp)
649 (put-text-property (point) (1+ (point)) 'syntax-table '(7)))))
650 tex-verbatim-face))))
bdbd9606 651
53c4fe47 652\f
869bff31 653(defun tex-define-common-keys (keymap)
81c735c0 654 "Define the keys that we want defined both in TeX mode and in the TeX shell."
869bff31 655 (define-key keymap "\C-c\C-k" 'tex-kill-job)
656 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
657 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
658 (define-key keymap "\C-c\C-p" 'tex-print)
659 (define-key keymap "\C-c\C-v" 'tex-view)
62a24cb5
RS
660
661 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
662
bdbd9606
SM
663 (define-key keymap [menu-bar tex tex-kill-job]
664 '(menu-item "Tex Kill" tex-kill-job :enable (tex-shell-running)))
cf6d6e8a 665 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
bdbd9606
SM
666 '(menu-item "Tex Recenter" tex-recenter-output-buffer
667 :enable (get-buffer "*tex-shell*")))
62a24cb5
RS
668 (define-key keymap [menu-bar tex tex-show-print-queue]
669 '("Show Print Queue" . tex-show-print-queue))
cf6d6e8a 670 (define-key keymap [menu-bar tex tex-alt-print]
bdbd9606
SM
671 '(menu-item "Tex Print (alt printer)" tex-alt-print
672 :enable (stringp tex-print-file)))
673 (define-key keymap [menu-bar tex tex-print]
674 '(menu-item "Tex Print" tex-print :enable (stringp tex-print-file)))
675 (define-key keymap [menu-bar tex tex-view]
676 '(menu-item "Tex View" tex-view :enable (stringp tex-print-file))))
677
678(defvar tex-mode-map
679 (let ((map (make-sparse-keymap)))
15ca8de7 680 (set-keymap-parent map text-mode-map)
bdbd9606
SM
681 (tex-define-common-keys map)
682 (define-key map "\"" 'tex-insert-quote)
683 (define-key map "(" 'skeleton-pair-insert-maybe)
684 (define-key map "{" 'skeleton-pair-insert-maybe)
685 (define-key map "[" 'skeleton-pair-insert-maybe)
686 (define-key map "$" 'skeleton-pair-insert-maybe)
687 (define-key map "\n" 'tex-terminate-paragraph)
688 (define-key map "\M-\r" 'latex-insert-item)
689 (define-key map "\C-c}" 'up-list)
690 (define-key map "\C-c{" 'tex-insert-braces)
691 (define-key map "\C-c\C-r" 'tex-region)
692 (define-key map "\C-c\C-b" 'tex-buffer)
693 (define-key map "\C-c\C-f" 'tex-file)
bdbd9606 694 (define-key map "\C-c\C-i" 'tex-bibtex-file)
7afecb99
SM
695 (define-key map "\C-c\C-o" 'latex-insert-block)
696 (define-key map "\C-c\C-e" 'latex-close-block)
bdbd9606
SM
697 (define-key map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
698 (define-key map "\C-c\C-m" 'tex-feed-input)
699 (define-key map [(control return)] 'tex-feed-input)
700 (define-key map [menu-bar tex tex-bibtex-file]
701 '("BibTeX File" . tex-bibtex-file))
702 (define-key map [menu-bar tex tex-validate-region]
703 '(menu-item "Validate Region" tex-validate-region :enable mark-active))
704 (define-key map [menu-bar tex tex-validate-buffer]
705 '("Validate Buffer" . tex-validate-buffer))
706 (define-key map [menu-bar tex tex-region]
707 '(menu-item "TeX Region" tex-region :enable mark-active))
708 (define-key map [menu-bar tex tex-buffer]
709 '("TeX Buffer" . tex-buffer))
710 (define-key map [menu-bar tex tex-file] '("TeX File" . tex-file))
711 map)
15ca8de7
SM
712 "Keymap shared by TeX modes.")
713
714(defvar latex-mode-map
715 (let ((map (make-sparse-keymap)))
716 (set-keymap-parent map tex-mode-map)
a3d80d4a 717 (define-key map "\C-c\C-s" 'latex-split-block)
15ca8de7
SM
718 map)
719 "Keymap for `latex-mode'. See also `tex-mode-map'.")
720
721(defvar plain-tex-mode-map
722 (let ((map (make-sparse-keymap)))
723 (set-keymap-parent map tex-mode-map)
724 map)
725 "Keymap for `plain-tex-mode'. See also `tex-mode-map'.")
cf6d6e8a 726
d6709b80
SM
727(defvar tex-shell-map
728 (let ((m (make-sparse-keymap)))
729 (set-keymap-parent m shell-mode-map)
730 (tex-define-common-keys m)
731 m)
81c735c0 732 "Keymap for the TeX shell.
dca5ea48 733Inherits `shell-mode-map' with a few additions.")
869bff31 734
6da9bbd6
RS
735(defvar tex-face-alist
736 '((bold . "{\\bf ")
737 (italic . "{\\it ")
738 (bold-italic . "{\\bi ") ; hypothetical
739 (underline . "\\underline{")
740 (default . "{\\rm "))
741 "Alist of face and TeX font name for facemenu.")
742
743(defvar tex-latex-face-alist
744 `((italic . "{\\em ")
745 ,@tex-face-alist)
746 "Alist of face and LaTeX font name for facemenu.")
747
15ca8de7
SM
748;; This would be a lot simpler if we just used a regexp search,
749;; but then it would be too slow.
a3d80d4a 750(defun tex-guess-mode ()
d6709b80 751 (let ((mode tex-default-mode) slash comment)
869bff31 752 (save-excursion
753 (goto-char (point-min))
754 (while (and (setq slash (search-forward "\\" nil t))
755 (setq comment (let ((search-end (point)))
756 (save-excursion
757 (beginning-of-line)
758 (search-forward "%" search-end t))))))
bdbd9606
SM
759 (when (and slash (not comment))
760 (setq mode
761 (if (looking-at
762 (eval-when-compile
763 (concat
764 (regexp-opt '("documentstyle" "documentclass"
95a045bd
SM
765 "begin" "subsection" "section"
766 "part" "chapter" "newcommand") 'words)
bdbd9606
SM
767 "\\|NeedsTeXFormat{LaTeX")))
768 (if (looking-at
769 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
770 'slitex-mode
771 'latex-mode)
772 'plain-tex-mode))))
d6709b80 773 (funcall mode)))
e4c8c838 774
a3d80d4a
SM
775;; `tex-mode' plays two roles: it's the parent of several sub-modes
776;; but it's also the function that chooses between those submodes.
777;; To tell the difference between those two cases where the function
778;; might be called, we check `delay-mode-hooks'.
779;;;###autoload
780(define-derived-mode tex-mode text-mode "generic-TeX"
781 (tex-common-initialization))
782(fset 'tex-mode
783 `(lambda ()
784 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
785Tries to determine (by looking at the beginning of the file) whether
786this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
787`latex-mode', or `slitex-mode', respectively. If it cannot be determined,
788such as if there are no commands in the file, the value of `tex-default-mode'
789says which mode to use."
790 (interactive)
791 (if delay-mode-hooks
792 ;; We're called from one of the children already.
793 (funcall ,(symbol-function 'tex-mode))
794 (tex-guess-mode))))
795
6503cec3 796;;;###autoload
31e1d920 797(defalias 'TeX-mode 'tex-mode)
6503cec3 798;;;###autoload
c3ce7bf4
RS
799(defalias 'plain-TeX-mode 'plain-tex-mode)
800;;;###autoload
31e1d920 801(defalias 'LaTeX-mode 'latex-mode)
869bff31 802
7229064d 803;;;###autoload
a3d80d4a 804(define-derived-mode plain-tex-mode tex-mode "TeX"
869bff31 805 "Major mode for editing files of input for plain TeX.
806Makes $ and } display the characters they match.
807Makes \" insert `` when it seems to be the beginning of a quotation,
808and '' when it appears to be the end; it inserts \" only after a \\.
809
810Use \\[tex-region] to run TeX on the current region, plus a \"header\"
811copied from the top of the file (containing macro definitions, etc.),
812running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
813\\[tex-file] saves the buffer and then processes the file.
814\\[tex-print] prints the .dvi file made by any of these.
815\\[tex-view] previews the .dvi file made by any of these.
816\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
817
e6b0b773 818Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 819mismatched $'s or braces.
820
821Special commands:
15ca8de7 822\\{plain-tex-mode-map}
869bff31 823
824Mode variables:
825tex-run-command
826 Command string used by \\[tex-region] or \\[tex-buffer].
827tex-directory
828 Directory in which to create temporary files for TeX jobs
829 run by \\[tex-region] or \\[tex-buffer].
830tex-dvi-print-command
831 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
832tex-alt-dvi-print-command
833 Alternative command string used by \\[tex-print] (when given a prefix
834 argument) to print a .dvi file.
869bff31 835tex-dvi-view-command
836 Command string used by \\[tex-view] to preview a .dvi file.
837tex-show-queue-command
838 Command string used by \\[tex-show-print-queue] to show the print
839 queue that \\[tex-print] put your job on.
840
81c735c0
RS
841Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
842`tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
843special subshell is initiated, the hook `tex-shell-hook' is run."
a3d80d4a
SM
844 (set (make-local-variable 'tex-command) tex-run-command)
845 (set (make-local-variable 'tex-start-of-header) "%\\*\\*start of header")
846 (set (make-local-variable 'tex-end-of-header) "%\\*\\*end of header")
847 (set (make-local-variable 'tex-trailer) "\\bye\n"))
869bff31 848
7229064d 849;;;###autoload
a3d80d4a 850(define-derived-mode latex-mode tex-mode "LaTeX"
869bff31 851 "Major mode for editing files of input for LaTeX.
852Makes $ and } display the characters they match.
853Makes \" insert `` when it seems to be the beginning of a quotation,
854and '' when it appears to be the end; it inserts \" only after a \\.
855
856Use \\[tex-region] to run LaTeX on the current region, plus the preamble
857copied from the top of the file (containing \\documentstyle, etc.),
858running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
859\\[tex-file] saves the buffer and then processes the file.
860\\[tex-print] prints the .dvi file made by any of these.
861\\[tex-view] previews the .dvi file made by any of these.
862\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
863
e6b0b773 864Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 865mismatched $'s or braces.
866
867Special commands:
15ca8de7 868\\{latex-mode-map}
869bff31 869
870Mode variables:
871latex-run-command
872 Command string used by \\[tex-region] or \\[tex-buffer].
873tex-directory
874 Directory in which to create temporary files for LaTeX jobs
875 run by \\[tex-region] or \\[tex-buffer].
876tex-dvi-print-command
877 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
878tex-alt-dvi-print-command
879 Alternative command string used by \\[tex-print] (when given a prefix
880 argument) to print a .dvi file.
869bff31 881tex-dvi-view-command
882 Command string used by \\[tex-view] to preview a .dvi file.
883tex-show-queue-command
884 Command string used by \\[tex-show-print-queue] to show the print
885 queue that \\[tex-print] put your job on.
886
bed1b0c8 887Entering Latex mode runs the hook `text-mode-hook', then
81c735c0
RS
888`tex-mode-hook', and finally `latex-mode-hook'. When the special
889subshell is initiated, `tex-shell-hook' is run."
a3d80d4a
SM
890 (set (make-local-variable 'tex-command) latex-run-command)
891 (set (make-local-variable 'tex-start-of-header)
892 "\\\\document\\(style\\|class\\)")
893 (set (make-local-variable 'tex-end-of-header) "\\\\begin\\s-*{document}")
894 (set (make-local-variable 'tex-trailer) "\\end\\s-*{document}\n")
ab2c9f54
RS
895 ;; A line containing just $$ is treated as a paragraph separator.
896 ;; A line starting with $$ starts a paragraph,
897 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80 898 (setq paragraph-start
a3d80d4a 899 (concat "[ \t]*\\(\\$\\$\\|"
d6709b80
SM
900 "\\\\[][]\\|"
901 "\\\\" (regexp-opt (append
902 (mapcar 'car latex-section-alist)
903 '("begin" "label" "end"
904 "item" "bibitem" "newline" "noindent"
905 "newpage" "footnote" "marginpar"
906 "parbox" "caption")) t)
907 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
dd459839 908 "\\>\\)"))
d6709b80 909 (setq paragraph-separate
dd459839 910 (concat "[\f%]\\|[ \t]*\\($\\|"
d6709b80
SM
911 "\\\\[][]\\|"
912 "\\\\" (regexp-opt (append
913 (mapcar 'car latex-section-alist)
914 '("begin" "label" "end" )) t)
915 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
916 "noindent" "newpage" "footnote"
917 "marginpar" "parbox" "caption"))
dd459839
SM
918 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
919 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
d6709b80
SM
920 (set (make-local-variable 'imenu-create-index-function)
921 'latex-imenu-create-index)
922 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
95a045bd 923 (add-hook 'fill-nobreak-predicate 'latex-fill-nobreak-predicate nil t)
ea590e1c 924 (set (make-local-variable 'indent-line-function) 'latex-indent)
dd459839 925 (set (make-local-variable 'fill-indent-according-to-mode) t)
d6709b80
SM
926 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
927 (set (make-local-variable 'outline-level) 'latex-outline-level)
53c4fe47 928 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
a3d80d4a 929 (set (make-local-variable 'skeleton-end-hook) nil))
869bff31 930
bd2f2323 931;;;###autoload
d6709b80 932(define-derived-mode slitex-mode latex-mode "SliTeX"
869bff31 933 "Major mode for editing files of input for SliTeX.
934Makes $ and } display the characters they match.
935Makes \" insert `` when it seems to be the beginning of a quotation,
936and '' when it appears to be the end; it inserts \" only after a \\.
937
938Use \\[tex-region] to run SliTeX on the current region, plus the preamble
939copied from the top of the file (containing \\documentstyle, etc.),
940running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
941\\[tex-file] saves the buffer and then processes the file.
942\\[tex-print] prints the .dvi file made by any of these.
943\\[tex-view] previews the .dvi file made by any of these.
944\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
945
e6b0b773 946Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 947mismatched $'s or braces.
948
949Special commands:
15ca8de7 950\\{slitex-mode-map}
869bff31 951
952Mode variables:
953slitex-run-command
954 Command string used by \\[tex-region] or \\[tex-buffer].
955tex-directory
956 Directory in which to create temporary files for SliTeX jobs
957 run by \\[tex-region] or \\[tex-buffer].
958tex-dvi-print-command
959 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
960tex-alt-dvi-print-command
961 Alternative command string used by \\[tex-print] (when given a prefix
962 argument) to print a .dvi file.
869bff31 963tex-dvi-view-command
964 Command string used by \\[tex-view] to preview a .dvi file.
965tex-show-queue-command
966 Command string used by \\[tex-show-print-queue] to show the print
967 queue that \\[tex-print] put your job on.
968
81c735c0
RS
969Entering SliTeX mode runs the hook `text-mode-hook', then the hook
970`tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
971`slitex-mode-hook'. When the special subshell is initiated, the hook
972`tex-shell-hook' is run."
869bff31 973 (setq tex-command slitex-run-command)
d6709b80 974 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
869bff31 975
976(defun tex-common-initialization ()
822eddf4 977 ;; Regexp isearch should accept newline and formfeed as whitespace.
d6709b80 978 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
64db2461 979 ;; A line containing just $$ is treated as a paragraph separator.
d6709b80
SM
980 (set (make-local-variable 'paragraph-start)
981 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
ab2c9f54
RS
982 ;; A line starting with $$ starts a paragraph,
983 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80
SM
984 (set (make-local-variable 'paragraph-separate)
985 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
986 (set (make-local-variable 'comment-start) "%")
987 (set (make-local-variable 'comment-add) 1)
988 (set (make-local-variable 'comment-start-skip)
5ae0d697 989 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
d6709b80
SM
990 (set (make-local-variable 'parse-sexp-ignore-comments) t)
991 (set (make-local-variable 'compare-windows-whitespace)
992 'tex-categorize-whitespace)
993 (set (make-local-variable 'facemenu-add-face-function)
994 (lambda (face end)
995 (let ((face-text (cdr (assq face tex-face-alist))))
996 (if face-text
997 face-text
998 (error "Face %s not configured for %s mode" face mode-name)))))
999 (set (make-local-variable 'facemenu-end-add-face) "}")
1000 (set (make-local-variable 'facemenu-remove-face-function) t)
1001 (set (make-local-variable 'font-lock-defaults)
7afecb99
SM
1002 '((tex-font-lock-keywords tex-font-lock-keywords-1
1003 tex-font-lock-keywords-2 tex-font-lock-keywords-3)
d6709b80
SM
1004 nil nil ((?$ . "\"")) nil
1005 ;; Who ever uses that anyway ???
bdbd9606
SM
1006 (font-lock-mark-block-function . mark-paragraph)
1007 (font-lock-syntactic-face-function
7afecb99
SM
1008 . tex-font-lock-syntactic-face-function)
1009 (font-lock-unfontify-region-function
1010 . tex-font-lock-unfontify-region)
1011 (font-lock-syntactic-keywords
1012 . tex-font-lock-syntactic-keywords)
1013 (parse-sexp-lookup-properties . t)))
95a045bd
SM
1014 ;; TABs in verbatim environments don't do what you think.
1015 (set (make-local-variable 'indent-tabs-mode) nil)
7afecb99 1016 ;; Other vars that should be buffer-local.
869bff31 1017 (make-local-variable 'tex-command)
1018 (make-local-variable 'tex-start-of-header)
1019 (make-local-variable 'tex-end-of-header)
1020 (make-local-variable 'tex-trailer))
1021
869bff31 1022(defun tex-categorize-whitespace (backward-limit)
1023 ;; compare-windows-whitespace is set to this.
1024 ;; This is basically a finite-state machine.
1025 ;; Returns a symbol telling how TeX would treat
1026 ;; the whitespace we are looking at: null, space, or par.
1027 (let ((category 'null)
1028 (not-finished t))
1029 (skip-chars-backward " \t\n\f" backward-limit)
1030 (while not-finished
1031 (cond ((looking-at "[ \t]+")
1032 (goto-char (match-end 0))
2be5fefb 1033 (if (eq category 'null)
869bff31 1034 (setq category 'space)))
1035 ((looking-at "\n")
2be5fefb 1036 (cond ((eq category 'newline)
869bff31 1037 (setq category 'par)
1038 (setq not-finished nil))
1039 (t
1040 (setq category 'newline) ;a strictly internal state
1041 (goto-char (match-end 0)))))
1042 ((looking-at "\f+")
1043 (setq category 'par)
1044 (setq not-finished nil))
1045 (t
1046 (setq not-finished nil))))
1047 (skip-chars-forward " \t\n\f")
2be5fefb 1048 (if (eq category 'newline)
869bff31 1049 'space ;TeX doesn't distinguish
1050 category)))
1051
1052(defun tex-insert-quote (arg)
1053 "Insert the appropriate quote marks for TeX.
08348502
RS
1054Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
1055\(normally '') depending on the context. With prefix argument, always
869bff31 1056inserts \" characters."
528415e7 1057 (interactive "*P")
95a045bd
SM
1058 (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
1059 (eq (get-text-property (point) 'face) 'tex-verbatim-face)
1060 (save-excursion
1061 (backward-char (length tex-open-quote))
1062 (when (or (looking-at (regexp-quote tex-open-quote))
1063 (looking-at (regexp-quote tex-close-quote)))
1064 (delete-char (length tex-open-quote))
1065 t)))
869bff31 1066 (self-insert-command (prefix-numeric-value arg))
95a045bd
SM
1067 (insert (if (memq (char-syntax (preceding-char)) '(?\( ?> ?\ ))
1068 tex-open-quote tex-close-quote))))
869bff31 1069
e6b0b773
MR
1070(defun tex-validate-buffer ()
1071 "Check current buffer for paragraphs containing mismatched braces or $s.
bbd93e41 1072Their positions are recorded in the buffer `*Occur*'.
e6b0b773
MR
1073To find a particular invalidity from `*Occur*', switch to that buffer
1074and type C-c C-c or click with mouse-2
1075on the line for the invalidity you want to see."
869bff31 1076 (interactive)
bbd93e41
RS
1077 (let ((buffer (current-buffer))
1078 (prevpos (point-min))
e6b0b773
MR
1079 (linenum nil)
1080 (num-matches 0))
bbd93e41
RS
1081 (with-output-to-temp-buffer "*Occur*"
1082 (princ "Mismatches:\n")
a3d80d4a 1083 (with-current-buffer standard-output
bbd93e41 1084 (occur-mode)
52ab062c
CW
1085 ;; This won't actually work...Really, this whole thing should
1086 ;; be rewritten instead of being a hack on top of occur.
1087 (setq occur-revert-arguments (list nil 0 (list buffer))))
bbd93e41
RS
1088 (save-excursion
1089 (goto-char (point-max))
52ab062c 1090 (while (and (not (bobp)))
710a0f53
KH
1091 (let ((end (point))
1092 prev-end)
bbd93e41 1093 ;; Scan the previous paragraph for invalidities.
710a0f53
KH
1094 (if (search-backward "\n\n" nil t)
1095 (progn
1096 (setq prev-end (point))
1097 (forward-char 2))
1098 (goto-char (setq prev-end (point-min))))
869bff31 1099 (or (tex-validate-region (point) end)
a3d80d4a 1100 (let* ((end (line-beginning-position 2))
bbd93e41
RS
1101 start tem)
1102 (beginning-of-line)
1103 (setq start (point))
1104 ;; Keep track of line number as we scan,
1105 ;; in a cumulative fashion.
1106 (if linenum
1107 (setq linenum (- linenum (count-lines prevpos (point))))
1108 (setq linenum (1+ (count-lines 1 start))))
1109 (setq prevpos (point))
bed1b0c8 1110 ;; Mention this mismatch in *Occur*.
bbd93e41 1111 ;; Since we scan from end of buffer to beginning,
e6b0b773 1112 ;; add each mismatch at the beginning of *Occur*.
bbd93e41
RS
1113 (save-excursion
1114 (setq tem (point-marker))
1115 (set-buffer standard-output)
1116 (goto-char (point-min))
1117 ;; Skip "Mismatches:" header line.
1118 (forward-line 1)
e6b0b773 1119 (setq num-matches (1+ num-matches))
bbd93e41 1120 (insert-buffer-substring buffer start end)
e6b0b773
MR
1121 (let (text-beg (text-end (point-marker)))
1122 (forward-char (- start end))
1123 (setq text-beg (point-marker))
1124 (insert (format "%3d: " linenum))
a865de85
EZ
1125 (add-text-properties
1126 text-beg (- text-end 1)
1127 '(mouse-face highlight
1128 help-echo "mouse-2: go to this invalidity"))
1598a961 1129 (put-text-property text-beg (- text-end 1)
52ab062c 1130 'occur-target tem)))))
710a0f53 1131 (goto-char prev-end))))
bdbd9606 1132 (with-current-buffer standard-output
e6b0b773 1133 (if (eq num-matches 0)
bbd93e41
RS
1134 (insert "None!\n"))
1135 (if (interactive-p)
e6b0b773 1136 (message "%d mismatches found" num-matches))))))
869bff31 1137
1138(defun tex-validate-region (start end)
1139 "Check for mismatched braces or $'s in region.
1140Returns t if no mismatches. Returns nil and moves point to suspect
1141area if a mismatch is found."
1142 (interactive "r")
1143 (let ((failure-point nil) (max-possible-sexps (- end start)))
1144 (save-excursion
1145 (condition-case ()
1146 (save-restriction
1147 (narrow-to-region start end)
2ed2806c 1148 ;; First check that the open and close parens balance in numbers.
869bff31 1149 (goto-char start)
e6b0b773 1150 (while (<= 0 (setq max-possible-sexps (1- max-possible-sexps)))
2ed2806c
KH
1151 (forward-sexp 1))
1152 ;; Now check that like matches like.
1153 (goto-char start)
1154 (while (progn (skip-syntax-forward "^(")
1155 (not (eobp)))
1156 (let ((match (matching-paren (following-char))))
1157 (save-excursion
1158 (forward-sexp 1)
1159 (or (= (preceding-char) match)
1160 (error "Mismatched parentheses"))))
1161 (forward-char 1)))
869bff31 1162 (error
bed1b0c8
RS
1163 (skip-syntax-forward " .>")
1164 (setq failure-point (point)))))
bdbd9606
SM
1165 (if failure-point (goto-char failure-point))
1166 (not failure-point)))
869bff31 1167
1168(defun tex-terminate-paragraph (inhibit-validation)
1169 "Insert two newlines, breaking a paragraph for TeX.
81c735c0 1170Check for mismatched braces or $s in paragraph being terminated.
869bff31 1171A prefix arg inhibits the checking."
528415e7 1172 (interactive "*P")
869bff31 1173 (or inhibit-validation
1174 (save-excursion
1175 (tex-validate-region
bed1b0c8
RS
1176 (save-excursion
1177 (search-backward "\n\n" nil 'move)
1178 (point))
1179 (point)))
869bff31 1180 (message "Paragraph being closed appears to contain a mismatch"))
1181 (insert "\n\n"))
1182
7afecb99 1183(define-skeleton tex-insert-braces
869bff31 1184 "Make a pair of braces and be poised to type inside of them."
7afecb99
SM
1185 nil
1186 ?\{ _ ?})
869bff31 1187
9bd4f69c
RS
1188;; This function is used as the value of fill-nobreak-predicate
1189;; in LaTeX mode. Its job is to prevent line-breaking inside
1190;; of a \verb construct.
1191(defun latex-fill-nobreak-predicate ()
7afecb99
SM
1192 (save-excursion
1193 (skip-chars-backward " ")
1194 ;; Don't break after \ since `\ ' has special meaning.
1195 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
1196 (let ((opoint (point))
1197 inside)
1198 (beginning-of-line)
1199 (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
1200 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
1201 (setq inside t)))
1202 inside))))
9bd4f69c 1203
53c4fe47
SM
1204(defvar latex-block-default "enumerate")
1205
15ca8de7 1206;; Like tex-insert-braces, but for LaTeX.
7afecb99
SM
1207(defalias 'tex-latex-block 'latex-insert-block)
1208(define-skeleton latex-insert-block
cf149bdf 1209 "Create a matching pair of lines \\begin[OPT]{NAME} and \\end{NAME} at point.
869bff31 1210Puts point on a blank line between them."
53c4fe47
SM
1211 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1212 latex-block-default)
95a045bd 1213 (append latex-block-names
7afecb99 1214 latex-standard-block-names)
53c4fe47
SM
1215 nil nil nil nil latex-block-default)))
1216 (setq latex-block-default choice)
7afecb99 1217 (unless (or (member choice latex-standard-block-names)
53c4fe47
SM
1218 (member choice latex-block-names))
1219 ;; Remember new block names for later completion.
1220 (push choice latex-block-names))
1221 choice)
95a045bd 1222 \n "\\begin{" str "}"
53c4fe47 1223 ?\[ (skeleton-read "[options]: ") & ?\] | -1
dd459839 1224 > \n _ \n
95a045bd 1225 "\\end{" str "}" > \n)
53c4fe47 1226
ea590e1c
SM
1227(define-skeleton latex-insert-item
1228 "Insert a \item macro."
1229 nil
15ca8de7 1230 \n "\\item " >)
ea590e1c 1231
53c4fe47
SM
1232\f
1233;;;;
1234;;;; LaTeX syntax navigation
1235;;;;
869bff31 1236
1237(defun tex-last-unended-begin ()
81c735c0 1238 "Leave point at the beginning of the last `\\begin{...}' that is unended."
95a045bd
SM
1239 (condition-case nil
1240 (while (and (re-search-backward "\\\\\\(begin\\|end\\)\\s *{")
1241 (looking-at "\\\\end"))
1242 (tex-last-unended-begin))
1243 (search-failed (error "Couldn't find unended \\begin"))))
869bff31 1244
53c4fe47
SM
1245(defun tex-next-unmatched-end ()
1246 "Leave point at the end of the next `\\end' that is unended."
1247 (while (and (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}")
ea590e1c
SM
1248 (save-excursion (goto-char (match-beginning 0))
1249 (looking-at "\\\\begin")))
53c4fe47
SM
1250 (tex-next-unmatched-end)))
1251
6a900cf1
ER
1252(defun tex-goto-last-unclosed-latex-block ()
1253 "Move point to the last unclosed \\begin{...}.
1254Mark is left at original location."
1255 (interactive)
1256 (let ((spot))
1257 (save-excursion
95a045bd 1258 (tex-last-unended-begin)
6a900cf1
ER
1259 (setq spot (point)))
1260 (push-mark)
1261 (goto-char spot)))
1262
53c4fe47
SM
1263(defun latex-backward-sexp-1 ()
1264 "Like (backward-sexp 1) but aware of multi-char elements."
1265 (let ((pos (point))
1266 (forward-sexp-function))
1267 (backward-sexp 1)
1268 (if (looking-at "\\\\begin\\>")
1269 (signal 'scan-error
1270 (list "Containing expression ends prematurely"
1271 (point) (prog1 (point) (goto-char pos))))
1272 (when (eq (char-after) ?{)
1273 (let ((newpos (point)))
1274 (when (ignore-errors (backward-sexp 1) t)
1275 (if (looking-at "\\\\end\\>")
1276 (tex-last-unended-begin)
1277 (goto-char newpos))))))))
1278
1279(defun latex-forward-sexp-1 ()
1280 "Like (forward-sexp 1) but aware of multi-char elements."
1281 (let ((pos (point))
1282 (forward-sexp-function))
1283 (forward-sexp 1)
1284 (let ((newpos (point)))
1285 (skip-syntax-backward "/w")
1286 (cond
1287 ((looking-at "\\\\end\\>")
1288 (signal 'scan-error
1289 (list "Containing expression ends prematurely"
1290 (point)
1291 (prog1
1292 (progn (ignore-errors (forward-sexp 2)) (point))
1293 (goto-char pos)))))
1294 ((looking-at "\\\\begin\\>")
1295 (goto-char (match-end 0))
1296 (tex-next-unmatched-end))
1297 (t (goto-char newpos))))))
1298
1299(defun latex-forward-sexp (&optional arg)
1300 "Like `forward-sexp' but aware of multi-char elements."
1301 (interactive "P")
1302 (unless arg (setq arg 1))
1303 (let ((pos (point)))
1304 (condition-case err
1305 (while (/= arg 0)
1306 (setq arg
1307 (if (> arg 0)
1308 (progn (latex-forward-sexp-1) (1- arg))
1309 (progn (latex-backward-sexp-1) (1+ arg)))))
1310 (scan-error
1311 (goto-char pos)
1312 (signal (car err) (cdr err))))))
1313
ea590e1c
SM
1314(defun latex-syntax-after ()
1315 "Like (char-syntax (char-after)) but aware of multi-char elements."
15ca8de7 1316 (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
ea590e1c
SM
1317
1318(defun latex-skip-close-parens ()
1319 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1320 (let ((forward-sexp-function nil))
1321 (while (progn (skip-syntax-forward " )")
1322 (looking-at "\\\\end\\>"))
1323 (forward-sexp 2))))
1324
1325(defun latex-down-list ()
1326 "Like (down-list 1) but aware of multi-char elements."
1327 (forward-comment (point-max))
1328 (let ((forward-sexp-function nil))
1329 (if (not (looking-at "\\\\begin\\>"))
1330 (down-list 1)
1331 (forward-sexp 1)
1332 ;; Skip arguments.
7afecb99
SM
1333 (while (looking-at "[ \t]*[[{(]")
1334 (with-syntax-table tex-mode-syntax-table
1335 (forward-sexp))))))
ea590e1c 1336
7afecb99
SM
1337(defalias 'tex-close-latex-block 'latex-close-block)
1338(define-skeleton latex-close-block
1339 "Create an \\end{...} to match the last unclosed \\begin{...}."
1340 (save-excursion
1341 (tex-last-unended-begin)
1342 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1343 (match-string 1)))
1344 \n "\\end" str > \n)
1345
1346(define-skeleton latex-split-block
1347 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1348 (save-excursion
1349 (tex-last-unended-begin)
1350 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1351 (prog1 (match-string 1)
1352 (goto-char (match-end 1))
1353 (setq v1 (buffer-substring (point)
1354 (progn
1355 (while (looking-at "[ \t]*[[{]")
1356 (forward-sexp 1))
1357 (point)))))))
1358 \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
15ca8de7
SM
1359
1360(defconst tex-discount-args-cmds
1361 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1362 "documentclass" "usepackage" "label")
1363 "TeX commands whose arguments should not be counted as text.")
1364
1365(defun tex-count-words (begin end)
1366 "Count the number of words in the buffer."
1367 (interactive
1368 (if (and transient-mark-mode mark-active)
1369 (list (region-beginning) (region-end))
1370 (list (point-min) (point-max))))
1371 ;; TODO: skip comments and math and maybe some environments.
1372 (save-excursion
1373 (goto-char begin)
1374 (let ((count 0))
1375 (while (and (< (point) end) (re-search-forward "\\<" end t))
1376 (if (not (eq (char-syntax (preceding-char)) ?/))
1377 (progn
1378 ;; Don't count single-char words.
1379 (unless (looking-at ".\\>") (incf count))
1380 (forward-char 1))
1381 (let ((cmd
1382 (buffer-substring-no-properties
1383 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1384 (forward-char 1))
1385 (point)))))
1386 (when (member cmd tex-discount-args-cmds)
1387 (skip-chars-forward "*")
1388 (forward-comment (point-max))
1389 (when (looking-at "\\[")
1390 (forward-sexp 1)
1391 (forward-comment (point-max)))
1392 (if (not (looking-at "{"))
1393 (forward-char 1)
1394 (forward-sexp 1))))))
1395 (message "%s words" count))))
b781e739
SS
1396
1397
869bff31 1398\f
1399;;; Invoking TeX in an inferior shell.
1400
15ca8de7
SM
1401;; Why use a shell instead of running TeX directly? Because if TeX
1402;; gets stuck, the user can switch to the shell window and type at it.
869bff31 1403
15ca8de7 1404;; The utility functions:
869bff31 1405
bdbd9606
SM
1406(define-derived-mode tex-shell shell-mode "TeX-Shell"
1407 (compilation-shell-minor-mode t))
1408
d974af30 1409;;;###autoload
869bff31 1410(defun tex-start-shell ()
d6709b80
SM
1411 (with-current-buffer
1412 (make-comint
1413 "tex-shell"
07c16ec4 1414 (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
d6709b80 1415 nil)
528415e7
RS
1416 (let ((proc (get-process "tex-shell")))
1417 (set-process-sentinel proc 'tex-shell-sentinel)
1418 (process-kill-without-query proc)
bdbd9606 1419 (tex-shell)
528415e7 1420 (while (zerop (buffer-size))
51b2c841
RS
1421 (sleep-for 1)))))
1422
033306e3
RS
1423(defun tex-feed-input ()
1424 "Send input to the tex shell process.
1425In the tex buffer this can be used to continue an interactive tex run.
bed1b0c8 1426In the tex shell buffer this command behaves like `comint-send-input'."
033306e3 1427 (interactive)
b781e739 1428 (set-buffer (tex-shell-buf))
033306e3
RS
1429 (comint-send-input)
1430 (tex-recenter-output-buffer nil))
1431
51b2c841
RS
1432(defun tex-display-shell ()
1433 "Make the TeX shell buffer visible in a window."
b781e739 1434 (display-buffer (tex-shell-buf))
51b2c841 1435 (tex-recenter-output-buffer nil))
528415e7
RS
1436
1437(defun tex-shell-sentinel (proc msg)
1438 (cond ((null (buffer-name (process-buffer proc)))
1439 ;; buffer killed
1440 (set-process-buffer proc nil)
1441 (tex-delete-last-temp-files))
1442 ((memq (process-status proc) '(signal exit))
1443 (tex-delete-last-temp-files))))
1444
1445(defun tex-set-buffer-directory (buffer directory)
869bff31 1446 "Set BUFFER's default directory to be DIRECTORY."
1447 (setq directory (file-name-as-directory (expand-file-name directory)))
1448 (if (not (file-directory-p directory))
1449 (error "%s is not a directory" directory)
1450 (save-excursion
1451 (set-buffer buffer)
1452 (setq default-directory directory))))
1453
30803a05
RS
1454(defvar tex-send-command-modified-tick 0)
1455(make-variable-buffer-local 'tex-send-command-modified-tick)
1456
bdbd9606 1457(defun tex-shell-proc ()
b781e739 1458 (or (tex-shell-running) (error "No TeX subprocess")))
bdbd9606
SM
1459(defun tex-shell-buf ()
1460 (process-buffer (tex-shell-proc)))
b781e739
SS
1461(defun tex-shell-buf-no-error ()
1462 (let ((proc (tex-shell-running)))
1463 (and proc (process-buffer proc))))
bdbd9606 1464
528415e7 1465(defun tex-send-command (command &optional file background)
4cdc1d4b 1466 "Send COMMAND to TeX shell process, substituting optional FILE for *.
8241d7b9
ER
1467Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1468FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1469substitution will be made in COMMAND. COMMAND can be any expression that
460e1b7d
RS
1470evaluates to a command string.
1471
1472Return the process in which TeX is running."
528415e7
RS
1473 (save-excursion
1474 (let* ((cmd (eval command))
bdbd9606 1475 (proc (tex-shell-proc))
64db2461 1476 (buf (process-buffer proc))
4f45adda 1477 (star (string-match "\\*" cmd))
4cdc1d4b
RS
1478 (string
1479 (concat
1480 (if file
1481 (if star (concat (substring cmd 0 star)
1482 file (substring cmd (1+ star)))
1483 (concat cmd " " file))
1484 cmd)
1485 (if background "&" ""))))
64db2461
RS
1486 ;; Switch to buffer before checking for subproc output in it.
1487 (set-buffer buf)
30803a05
RS
1488 ;; If text is unchanged since previous tex-send-command,
1489 ;; we haven't got any output. So wait for output now.
64db2461 1490 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
30803a05 1491 (accept-process-output proc))
4cdc1d4b
RS
1492 (goto-char (process-mark proc))
1493 (insert string)
30803a05 1494 (comint-send-input)
460e1b7d
RS
1495 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1496 proc)))
528415e7 1497
a15849cb
RS
1498(defun tex-delete-last-temp-files (&optional not-all)
1499 "Delete any junk files from last temp file.
1500If NOT-ALL is non-nil, save the `.dvi' file."
528415e7
RS
1501 (if tex-last-temp-file
1502 (let* ((dir (file-name-directory tex-last-temp-file))
adf6b7f9
KH
1503 (list (and (file-directory-p dir)
1504 (file-name-all-completions
02fd229c
RS
1505 (file-name-sans-extension
1506 (file-name-nondirectory tex-last-temp-file))
1507 dir))))
adf6b7f9 1508 (while list
a15849cb
RS
1509 (if not-all
1510 (and
1511 ;; If arg is non-nil, don't delete the .dvi file.
1512 (not (string-match "\\.dvi$" (car list)))
1513 (delete-file (concat dir (car list))))
1514 (delete-file (concat dir (car list))))
528415e7
RS
1515 (setq list (cdr list))))))
1516
99621a14 1517(add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
869bff31 1518
dd459839
SM
1519(defun tex-guess-main-file (&optional all)
1520 "Find a likely `tex-main-file'.
1521Looks for hints in other buffers in the same directory or in
1522ALL other buffers."
1523 (let ((dir default-directory)
1524 (header-re tex-start-of-header))
1525 (catch 'found
1526 ;; Look for a buffer with `tex-main-file' set.
1527 (dolist (buf (if (consp all) all (buffer-list)))
1528 (with-current-buffer buf
1529 (when (and (or all (equal dir default-directory))
1530 (stringp tex-main-file))
1531 (throw 'found (expand-file-name tex-main-file)))))
1532 ;; Look for a buffer containing the magic `tex-start-of-header'.
1533 (dolist (buf (if (consp all) all (buffer-list)))
1534 (with-current-buffer buf
1535 (when (and (or all (equal dir default-directory))
1536 buffer-file-name
1537 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1538 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1539 (save-excursion
cb30255a
SM
1540 (save-restriction
1541 (widen)
1542 (goto-char (point-min))
95a045bd
SM
1543 (re-search-forward
1544 header-re (+ (point) 10000) t))))
dd459839
SM
1545 (throw 'found (expand-file-name buffer-file-name))))))))
1546
07c16ec4
SM
1547(defun tex-main-file ()
1548 "Return the relative name of the main file."
bdbd9606
SM
1549 (let* ((file (or tex-main-file
1550 ;; Compatibility with AUCTeX.
1551 (and (boundp 'TeX-master) (stringp TeX-master)
1552 (set (make-local-variable 'tex-main-file) TeX-master))
1553 ;; Try to guess the main file.
1554 (if (not buffer-file-name)
1555 (error "Buffer is not associated with any file")
1556 (file-relative-name
1557 (if (save-excursion
1558 (goto-char (point-min))
95a045bd
SM
1559 (re-search-forward tex-start-of-header
1560 (+ (point) 10000) t))
bdbd9606
SM
1561 ;; This is the main file.
1562 buffer-file-name
1563 ;; This isn't the main file, let's try to find better,
1564 (or (tex-guess-main-file)
1565 ;; (tex-guess-main-file t)
07c16ec4
SM
1566 buffer-file-name)))))))
1567 (if (file-exists-p file) file (concat file ".tex"))))
dd459839 1568
d6709b80
SM
1569
1570(defun tex-start-tex (command file &optional dir)
460e1b7d 1571 "Start a TeX run, using COMMAND on FILE."
6633b891 1572 (let* ((star (string-match "\\*" command))
460e1b7d 1573 (compile-command
6633b891
KH
1574 (if star
1575 (concat (substring command 0 star)
1576 (comint-quote-filename file)
1577 (substring command (1+ star)))
1578 (concat command " "
95a045bd 1579 tex-start-options
9e0ad27a 1580 (if (< 0 (length tex-start-commands))
c3ce7bf4 1581 (concat
9e0ad27a 1582 (shell-quote-argument tex-start-commands) " "))
6633b891 1583 (comint-quote-filename file)))))
bdbd9606
SM
1584 (tex-send-tex-command compile-command dir)))
1585
1586(defun tex-send-tex-command (cmd &optional dir)
b781e739
SS
1587 (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
1588 (and buf (with-current-buffer buf
1589 default-directory))))
bdbd9606
SM
1590 (not dir))
1591 (let (shell-dirtrack-verbose)
1592 (tex-send-command tex-shell-cd-command dir)))
1593 (with-current-buffer (process-buffer (tex-send-command cmd))
bdbd9606
SM
1594 (make-local-variable 'compilation-parse-errors-function)
1595 (setq compilation-parse-errors-function 'tex-compilation-parse-errors)
1596 (setq compilation-last-buffer (current-buffer))
1597 (compilation-forget-errors)
1598a961 1598 ;; Don't parse previous compilations.
bdbd9606
SM
1599 (set-marker compilation-parsing-end (1- (point-max))))
1600 (tex-display-shell)
1601 (setq tex-last-buffer-texed (current-buffer)))
460e1b7d 1602\f
1598a961
SM
1603(defvar tex-error-parse-syntax-table
1604 (let ((st (make-syntax-table)))
1605 (modify-syntax-entry ?\( "()" st)
1606 (modify-syntax-entry ?\) ")(" st)
1607 (modify-syntax-entry ?\\ "\\" st)
1608 (modify-syntax-entry ?\{ "_" st)
1609 (modify-syntax-entry ?\} "_" st)
1610 (modify-syntax-entry ?\[ "_" st)
1611 (modify-syntax-entry ?\] "_" st)
1612 ;; Single quotations may appear in errors
1613 (modify-syntax-entry ?\" "_" st)
1614 st)
1615 "Syntax-table used while parsing TeX error messages.")
1616
460e1b7d 1617(defun tex-compilation-parse-errors (limit-search find-at-least)
f05bd645
RS
1618 "Parse the current buffer as TeX error messages.
1619See the variable `compilation-parse-errors-function' for the interface it uses.
1620
1621This function parses only the last TeX compilation.
1622It works on TeX compilations only. It is necessary for that purpose,
1623since TeX does not put file names and line numbers on the same line as
1624for the error messages."
460e1b7d
RS
1625 (require 'thingatpt)
1626 (setq compilation-error-list nil)
1627 (message "Parsing error messages...")
f05bd645
RS
1628 (let ((default-directory ; Perhaps dir has changed meanwhile.
1629 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
f05bd645
RS
1630 found-desired (num-errors-found 0)
1631 last-filename last-linenum last-position
1632 begin-of-error end-of-error)
f05bd645
RS
1633 ;; Don't reparse messages already seen at last parse.
1634 (goto-char compilation-parsing-end)
1635 ;; Parse messages.
1636 (while (and (not (or found-desired (eobp)))
1637 (prog1 (re-search-forward "^! " nil 'move)
1638 (setq begin-of-error (match-beginning 0)
1639 end-of-error (match-end 0)))
1640 (re-search-forward
1641 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
1642 (let* ((this-error (set-marker (make-marker) begin-of-error))
1643 (linenum (string-to-int (match-string 1)))
1644 (error-text (regexp-quote (match-string 3)))
1645 (filename
1646 (save-excursion
ea590e1c
SM
1647 (with-syntax-table tex-error-parse-syntax-table
1648 (backward-up-list 1)
1649 (skip-syntax-forward "(_")
1650 (while (not (file-readable-p (thing-at-point 'filename)))
1651 (skip-syntax-backward "(_")
1652 (backward-up-list 1)
1653 (skip-syntax-forward "(_"))
1654 (thing-at-point 'filename))))
f05bd645
RS
1655 (new-file
1656 (or (null last-filename)
1657 (not (string-equal last-filename filename))))
1658 (error-location
1659 (save-excursion
1660 (if (equal filename (concat tex-zap-file ".tex"))
1661 (set-buffer tex-last-buffer-texed)
1662 (set-buffer (find-file-noselect filename)))
1663 (if new-file
1598a961 1664 (progn (goto-line linenum) (setq last-position nil))
f05bd645
RS
1665 (goto-char last-position)
1666 (forward-line (- linenum last-linenum)))
1667 ;; first try a forward search for the error text,
1668 ;; then a backward search limited by the last error.
1669 (let ((starting-point (point)))
1670 (or (re-search-forward error-text nil t)
1598a961 1671 (re-search-backward error-text last-position t)
f05bd645
RS
1672 (goto-char starting-point)))
1673 (point-marker))))
1674 (goto-char this-error)
1675 (if (and compilation-error-list
1676 (or (and find-at-least
1677 (>= num-errors-found
1678 find-at-least))
1679 (and limit-search
1680 (>= end-of-error limit-search)))
1681 new-file)
1682 (setq found-desired t)
1683 (setq num-errors-found (1+ num-errors-found)
1684 last-filename filename
1685 last-linenum linenum
1686 last-position error-location
1687 compilation-error-list ; Add the new error
1688 (cons (cons this-error error-location)
1689 compilation-error-list))
1690 (goto-char end-of-error)))))
ee13a145 1691 (set-marker compilation-parsing-end (point))
f05bd645 1692 (setq compilation-error-list (nreverse compilation-error-list))
460e1b7d
RS
1693 (message "Parsing error messages...done"))
1694\f
528415e7 1695;;; The commands:
869bff31 1696
1697(defun tex-region (beg end)
1698 "Run TeX on the current region, via a temporary file.
1699The file's name comes from the variable `tex-zap-file' and the
1700variable `tex-directory' says where to put it.
1701
1702If the buffer has a header, the header is given to TeX before the
1703region itself. The buffer's header is all lines between the strings
1704defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
1705The header must start in the first 100 lines of the buffer.
1706
1707The value of `tex-trailer' is given to TeX as input after the region.
1708
1709The value of `tex-command' specifies the command to use to run TeX."
1710 (interactive "r")
1711 (if (tex-shell-running)
1712 (tex-kill-job)
1713 (tex-start-shell))
1714 (or tex-zap-file
1715 (setq tex-zap-file (tex-generate-zap-file-name)))
6d34c59f
RS
1716 ;; Temp file will be written and TeX will be run in zap-directory.
1717 ;; If the TEXINPUTS file has relative directories or if the region has
1718 ;; \input of files, this must be the same directory as the file for
1719 ;; TeX to access the correct inputs. That's why it's safest if
1720 ;; tex-directory is ".".
1721 (let* ((zap-directory
528415e7 1722 (file-name-as-directory (expand-file-name tex-directory)))
d6709b80
SM
1723 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
1724 zap-directory)))
0d548e5d
RS
1725 ;; Don't delete temp files if we do the same buffer twice in a row.
1726 (or (eq (current-buffer) tex-last-buffer-texed)
1727 (tex-delete-last-temp-files t))
869bff31 1728 ;; Write the new temp file.
1729 (save-excursion
1730 (save-restriction
1731 (widen)
1732 (goto-char (point-min))
1733 (forward-line 100)
1734 (let ((search-end (point))
6d34c59f
RS
1735 (default-directory zap-directory)
1736 (already-output 0))
869bff31 1737 (goto-char (point-min))
6d34c59f 1738
725b7428
RS
1739 ;; Maybe copy first line, such as `\input texinfo', to temp file.
1740 (and tex-first-line-header-regexp
1741 (looking-at tex-first-line-header-regexp)
bed1b0c8 1742 (write-region (point)
6d34c59f
RS
1743 (progn (forward-line 1)
1744 (setq already-output (point)))
725b7428
RS
1745 tex-out-file nil nil))
1746
6d34c59f
RS
1747 ;; Write out the header, if there is one,
1748 ;; and any of the specified region which extends before it.
1749 ;; But don't repeat anything already written.
898b9ac1 1750 (if (re-search-forward tex-start-of-header search-end t)
6d34c59f 1751 (let (hbeg)
869bff31 1752 (beginning-of-line)
1753 (setq hbeg (point)) ;mark beginning of header
898b9ac1 1754 (if (re-search-forward tex-end-of-header nil t)
6d34c59f
RS
1755 (let (hend)
1756 (forward-line 1)
bed1b0c8 1757 (setq hend (point)) ;mark end of header
6d34c59f
RS
1758 (write-region (max (min hbeg beg) already-output)
1759 hend
1760 tex-out-file
1761 (not (zerop already-output)) nil)
1762 (setq already-output hend)))))
1763
1764 ;; Write out the specified region
1765 ;; (but don't repeat anything already written).
1766 (write-region (max beg already-output) end
1767 tex-out-file
1768 (not (zerop already-output)) nil))
1769 ;; Write the trailer, if any.
1770 ;; Precede it with a newline to make sure it
1771 ;; is not hidden in a comment.
1772 (if tex-trailer
1773 (write-region (concat "\n" tex-trailer) nil
1774 tex-out-file t nil))))
528415e7
RS
1775 ;; Record the file name to be deleted afterward.
1776 (setq tex-last-temp-file tex-out-file)
f05bd645
RS
1777 ;; Use a relative file name here because (1) the proper dir
1778 ;; is already current, and (2) the abs file name is sometimes
1779 ;; too long and can make tex crash.
d6709b80
SM
1780 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
1781 (setq tex-print-file tex-out-file)))
869bff31 1782
1783(defun tex-buffer ()
1784 "Run TeX on current buffer. See \\[tex-region] for more information.
528415e7
RS
1785Does not save the buffer, so it's useful for trying experimental versions.
1786See \\[tex-file] for an alternative."
869bff31 1787 (interactive)
1788 (tex-region (point-min) (point-max)))
1789
1790(defun tex-file ()
1791 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
1792This function is more useful than \\[tex-buffer] when you need the
1793`.aux' file of LaTeX to have the correct name."
1794 (interactive)
7abc9add
SS
1795 (when tex-offer-save
1796 (save-some-buffers))
d6709b80 1797 (let* ((source-file (tex-main-file))
07c16ec4 1798 (file-dir (file-name-directory (expand-file-name source-file))))
869bff31 1799 (if (tex-shell-running)
1800 (tex-kill-job)
1801 (tex-start-shell))
d6709b80 1802 (tex-start-tex tex-command source-file file-dir)
f05bd645 1803 (setq tex-print-file (expand-file-name source-file))))
869bff31 1804
1805(defun tex-generate-zap-file-name ()
1806 "Generate a unique name suitable for use as a file name."
1807 ;; Include the shell process number and host name
1808 ;; in case there are multiple shells (for same or different user).
f5cdb851
KH
1809 ;; Dec 1998: There is a report that some versions of xdvi
1810 ;; don't work with file names that start with #.
5616ee46 1811 (format "_TZ_%d-%s"
869bff31 1812 (process-id (get-buffer-process "*tex-shell*"))
07c16ec4 1813 (subst-char-in-string ?. ?- (system-name))))
869bff31 1814
1815;; This will perhaps be useful for modifying TEXINPUTS.
1816;; Expand each file name, separated by colons, in the string S.
1817(defun tex-expand-files (s)
1818 (let (elts (start 0))
1819 (while (string-match ":" s start)
1820 (setq elts (cons (substring s start (match-beginning 0)) elts))
1821 (setq start (match-end 0)))
1822 (or (= start 0)
1823 (setq elts (cons (substring s start) elts)))
c0df1972
SM
1824 (mapconcat (lambda (elt)
1825 (if (= (length elt) 0) elt (expand-file-name elt)))
5616ee46 1826 (nreverse elts) ":")))
869bff31 1827
1828(defun tex-shell-running ()
713f7b15 1829 (let ((proc (get-process "tex-shell")))
b781e739
SS
1830 (when proc
1831 (if (and (eq (process-status proc) 'run)
1832 (buffer-live-p (process-buffer proc)))
1833 ;; return the TeX process on success
1834 proc
1835 ;; get rid of the process permanently
1836 ;; this should get rid of the annoying w32 problem with
1837 ;; dead tex-shell buffer and live process
1838 (delete-process proc)))))
869bff31 1839
1840(defun tex-kill-job ()
1841 "Kill the currently running TeX job."
1842 (interactive)
b781e739 1843 ;; `quit-process' leads to core dumps of the tex process (except if
bed1b0c8
RS
1844 ;; coredumpsize has limit 0kb as on many environments). One would
1845 ;; like to use (kill-process proc 'lambda), however that construct
1846 ;; does not work on some systems and kills the shell itself.
b781e739
SS
1847 (let ((proc (get-process "tex-shell")))
1848 (when proc (quit-process proc t))))
869bff31 1849
1850(defun tex-recenter-output-buffer (linenum)
1851 "Redisplay buffer of TeX job output so that most recent output can be seen.
1852The last line of the buffer is displayed on
1853line LINE of the window, or centered if LINE is nil."
1854 (interactive "P")
1855 (let ((tex-shell (get-buffer "*tex-shell*"))
23b64225 1856 (window))
869bff31 1857 (if (null tex-shell)
1858 (message "No TeX output buffer")
23b64225
RS
1859 (setq window (display-buffer tex-shell))
1860 (save-selected-window
1861 (select-window window)
1862 (bury-buffer tex-shell)
1863 (goto-char (point-max))
1864 (recenter (if linenum
1865 (prefix-numeric-value linenum)
1866 (/ (window-height) 2)))))))
869bff31 1867
528415e7 1868(defun tex-print (&optional alt)
869bff31 1869 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1433a222
CZ
1870Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
1871is provided, use the alternative command, `tex-alt-dvi-print-command'."
528415e7 1872 (interactive "P")
869bff31 1873 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
1874 test-name)
1875 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
45c3304d
RS
1876 (buffer-file-name)
1877 ;; Check that this buffer's printed file is up to date.
869bff31 1878 (file-newer-than-file-p
1879 (setq test-name (tex-append (buffer-file-name) ".dvi"))
45c3304d 1880 (buffer-file-name)))
869bff31 1881 (setq print-file-name-dvi test-name))
528415e7
RS
1882 (if (not (file-exists-p print-file-name-dvi))
1883 (error "No appropriate `.dvi' file could be found")
460e1b7d
RS
1884 (if (tex-shell-running)
1885 (tex-kill-job)
1886 (tex-start-shell))
528415e7 1887 (tex-send-command
bed1b0c8 1888 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
602503c5
RS
1889 (shell-quote-argument
1890 print-file-name-dvi)
1891 t))))
869bff31 1892
cf6d6e8a
RS
1893(defun tex-alt-print ()
1894 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
002b0d00 1895Runs the shell command defined by `tex-alt-dvi-print-command'."
cf6d6e8a
RS
1896 (interactive)
1897 (tex-print t))
1898
869bff31 1899(defun tex-view ()
1900 "Preview the last `.dvi' file made by running TeX under Emacs.
1901This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2b7971c9
RS
1902The variable `tex-dvi-view-command' specifies the shell command for preview.
1903You must set that variable yourself before using this command,
1904because there is no standard value that would generally work."
869bff31 1905 (interactive)
2b7971c9
RS
1906 (or tex-dvi-view-command
1907 (error "You must set `tex-dvi-view-command'"))
746c30e2 1908 (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
869bff31 1909 (tex-print)))
1910
1911(defun tex-append (file-name suffix)
1912 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
cf6d6e8a 1913Pascal-based TeX scans for the first period, C TeX uses the last.
869bff31 1914No period is retained immediately before SUFFIX,
1915so normally SUFFIX starts with one."
1916 (if (stringp file-name)
cf6d6e8a
RS
1917 (let ((file (file-name-nondirectory file-name))
1918 trial-name)
6da9bbd6 1919 ;; Try splitting on last period.
7d0ca249
RS
1920 ;; The first-period split can get fooled when two files
1921 ;; named a.tex and a.b.tex are both tex'd;
1922 ;; the last-period split must be right if it matches at all.
cf6d6e8a
RS
1923 (setq trial-name
1924 (concat (file-name-directory file-name)
1925 (substring file 0
7d0ca249 1926 (string-match "\\.[^.]*$" file))
cf6d6e8a
RS
1927 suffix))
1928 (if (or (file-exists-p trial-name)
1929 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
1930 trial-name
7d0ca249 1931 ;; Not found, so split on first period.
cf6d6e8a
RS
1932 (concat (file-name-directory file-name)
1933 (substring file 0
7d0ca249 1934 (string-match "\\." file))
cf6d6e8a 1935 suffix)))
869bff31 1936 " "))
1937
1938(defun tex-show-print-queue ()
1939 "Show the print queue that \\[tex-print] put your job on.
1433a222 1940Runs the shell command defined by `tex-show-queue-command'."
869bff31 1941 (interactive)
1942 (if (tex-shell-running)
1943 (tex-kill-job)
1944 (tex-start-shell))
51b2c841
RS
1945 (tex-send-command tex-show-queue-command)
1946 (tex-display-shell))
869bff31 1947
1948(defun tex-bibtex-file ()
1949 "Run BibTeX on the current buffer's file."
1950 (interactive)
1951 (if (tex-shell-running)
1952 (tex-kill-job)
1953 (tex-start-shell))
e6b0b773
MR
1954 (let (shell-dirtrack-verbose
1955 (tex-out-file
869bff31 1956 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
1957 (file-dir (file-name-directory (buffer-file-name))))
528415e7 1958 (tex-send-command tex-shell-cd-command file-dir)
51b2c841
RS
1959 (tex-send-command tex-bibtex-command tex-out-file))
1960 (tex-display-shell))
ea590e1c
SM
1961\f
1962;;;;
1963;;;; LaTeX indentation
1964;;;;
1965
1966(defvar tex-indent-allhanging t)
1967(defvar tex-indent-arg 4)
1968(defvar tex-indent-basic 2)
1969(defvar tex-indent-item tex-indent-basic)
1970(defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
1971
1972(easy-mmode-defsyntax tex-latex-indent-syntax-table
dd459839
SM
1973 '((?$ . ".")
1974 (?\( . ".")
1975 (?\) . "."))
ea590e1c
SM
1976 "Syntax table used while computing indentation."
1977 :copy tex-mode-syntax-table)
1978
1979(defun latex-indent (&optional arg)
7afecb99
SM
1980 (if (and (eq (get-text-property (line-beginning-position) 'face)
1981 tex-verbatim-face))
a3d80d4a 1982 'noindent
7afecb99
SM
1983 (with-syntax-table tex-latex-indent-syntax-table
1984 ;; TODO: Rather than ignore $, we should try to be more clever about it.
1985 (let ((indent
1986 (save-excursion
1987 (beginning-of-line)
1988 (latex-find-indent))))
1989 (if (< indent 0) (setq indent 0))
1990 (if (<= (current-column) (current-indentation))
1991 (indent-line-to indent)
1992 (save-excursion (indent-line-to indent)))))))
ea590e1c
SM
1993
1994(defun latex-find-indent (&optional virtual)
1995 "Find the proper indentation of text after point.
1996VIRTUAL if non-nil indicates that we're only trying to find the indentation
1997 in order to determine the indentation of something else.
1998There might be text before point."
1999 (save-excursion
2000 (skip-chars-forward " \t")
2001 (or
7afecb99
SM
2002 ;; Stick the first line at column 0.
2003 (and (= (point-min) (line-beginning-position)) 0)
ea590e1c 2004 ;; Trust the current indentation, if such info is applicable.
7afecb99
SM
2005 (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
2006 (current-column))
2007 ;; Stick verbatim environments to the left margin.
2008 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2009 (member (match-string 2) tex-verbatim-environments)
2010 0)
ea590e1c
SM
2011 ;; Put leading close-paren where the matching open brace would be.
2012 (and (eq (latex-syntax-after) ?\))
2013 (ignore-errors
2014 (save-excursion
2015 (latex-skip-close-parens)
2016 (latex-backward-sexp-1)
2017 (latex-find-indent 'virtual))))
2018 ;; Default (maybe an argument)
2019 (let ((pos (point))
2020 (char (char-after))
2021 ;; Outdent \item if necessary.
2022 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
2023 up-list-pos)
2024 ;; Find the previous point which determines our current indentation.
2025 (condition-case err
2026 (progn
2027 (latex-backward-sexp-1)
2028 (while (> (current-column) (current-indentation))
2029 (latex-backward-sexp-1)))
2030 (scan-error
2031 (setq up-list-pos (nth 2 err))))
8908cf40
SM
2032 (cond
2033 ((= (point-min) pos) 0) ; We're really just indenting the first line.
2034 ((integerp up-list-pos)
2035 ;; Have to indent relative to the open-paren.
2036 (goto-char up-list-pos)
2037 (if (and (not tex-indent-allhanging)
2038 (> pos (progn (latex-down-list)
2039 (forward-comment (point-max))
2040 (point))))
7afecb99 2041 ;; Align with the first element after the open-paren.
8908cf40
SM
2042 (current-column)
2043 ;; We're the first element after a hanging brace.
2044 (goto-char up-list-pos)
2045 (+ indent tex-indent-basic (latex-find-indent 'virtual))))
2046 ;; We're now at the "beginning" of a line.
2047 ((not (and (not virtual) (eq (char-after) ?\\)))
2048 ;; Nothing particular here: just keep the same indentation.
2049 (+ indent (current-column)))
2050 ;; We're now looking at a macro call.
7afecb99
SM
2051 ((looking-at tex-indent-item-re)
2052 ;; Indenting relative to an item, have to re-add the outdenting.
8908cf40
SM
2053 (+ indent (current-column) tex-indent-item))
2054 (t
2055 (let ((col (current-column)))
2056 (if (not (eq (char-syntax char) ?\())
2057 ;; If the first char was not an open-paren, there's
2058 ;; a risk that this is really not an argument to the
2059 ;; macro at all.
7afecb99
SM
2060 (+ indent col)
2061 (forward-sexp 1)
2062 (if (< (line-end-position)
2063 (save-excursion (forward-comment (point-max))
2064 (point)))
8908cf40
SM
2065 ;; we're indenting the first argument.
2066 (min (current-column) (+ tex-indent-arg col))
2067 (skip-syntax-forward " ")
2068 (current-column))))))))))
a3d80d4a
SM
2069;;; DocTeX support
2070
2071(defun doctex-font-lock-^^A ()
2072 (if (eq (char-after (line-beginning-position)) ?\%)
2073 (progn
2074 (put-text-property
2075 (1- (match-beginning 1)) (match-beginning 1)
2076 'syntax-table
2077 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2078 ;; The `%' is a single-char comment, which Emacs
2079 ;; syntax-table can't deal with. We could turn it
2080 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2081 ;; Instead, we include it in the ^^A comment.
2082 (eval-when-compile (string-to-syntax "< b"))
2083 (eval-when-compile (string-to-syntax ">"))))
2084 (let ((end (line-end-position)))
2085 (if (< end (point-max))
2086 (put-text-property
2087 end (1+ end)
2088 'syntax-table
2089 (eval-when-compile (string-to-syntax "> b")))))
2090 (eval-when-compile (string-to-syntax "< b")))))
2091
2092(defun doctex-font-lock-syntactic-face-function (state)
2093 ;; Mark DocTeX documentation, which is parsed as a style A comment
2094 ;; starting in column 0.
2095 (if (or (nth 3 state) (nth 7 state)
2096 (not (memq (char-before (nth 8 state))
2097 '(?\n nil))))
2098 ;; Anything else is just as for LaTeX.
2099 (tex-font-lock-syntactic-face-function state)
2100 font-lock-doc-face))
2101
2102(defvar doctex-font-lock-syntactic-keywords
2103 (append
2104 tex-font-lock-syntactic-keywords
2105 ;; For DocTeX comment-in-doc.
2106 `(("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A))))))
2107
2108(defvar doctex-font-lock-keywords
2109 (append tex-font-lock-keywords
2110 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t)))))
2111
2112;;;###autoload
2113(define-derived-mode doctex-mode latex-mode "DocTeX"
2114 "Major mode to edit DocTeX files."
2115 (setq font-lock-defaults
2116 (cons (append (car font-lock-defaults) '(doctex-font-lock-keywords))
2117 (mapcar
2118 (lambda (x)
2119 (case (car-safe x)
2120 (font-lock-syntactic-keywords
2121 (cons (car x) 'doctex-font-lock-syntactic-keywords))
2122 (font-lock-syntactic-face-function
2123 (cons (car x) 'doctex-font-lock-syntactic-face-function))
2124 (t x)))
2125 (cdr font-lock-defaults)))))
528415e7
RS
2126
2127(run-hooks 'tex-mode-load-hook)
869bff31 2128
49116ac0
JB
2129(provide 'tex-mode)
2130
d501f516 2131;;; tex-mode.el ends here