(outline-next-visible-heading):
[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))
53c4fe47
SM
502 (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
503 ;;
504 ;; Names of commands whose arg should be fontified as a citation.
505 (citations (regexp-opt
506 '("label" "ref" "pageref" "vref" "eqref"
15ca8de7 507 "cite" "nocite" "index" "glossary" "bibitem"
1598a961
SM
508 ;; These are text, rather than citations.
509 ;; "caption" "footnote" "footnotemark" "footnotetext"
510 )
53c4fe47
SM
511 t))
512 ;;
513 ;; Names of commands that should be fontified.
1b741d9e
AS
514 (specials-1 (regexp-opt '("\\" "\\*") t)) ;; "-"
515 (specials-2 (regexp-opt
516 '("linebreak" "nolinebreak" "pagebreak" "nopagebreak"
517 "newline" "newpage" "clearpage" "cleardoublepage"
518 "displaybreak" "allowdisplaybreaks"
519 "enlargethispage") t))
53c4fe47
SM
520 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
521 ;;
522 ;; Miscellany.
523 (slash "\\\\")
15ca8de7 524 (opt " *\\(\\[[^]]*\\] *\\)*")
7afecb99 525 (args "\\(\\(?:[^{}&\\]+\\|\\\\.\\|{[^}]*}\\)+\\)")
1598a961 526 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
53c4fe47
SM
527 (list
528 ;;
529 ;; Citation args.
530 (list (concat slash citations opt arg) 3 'font-lock-constant-face)
531 ;;
15ca8de7 532 ;; Text between `` quotes ''.
95a045bd 533 (cons (concat (regexp-opt `("``" "\"<" "\"`" "<<" "«") t)
7abc9add 534 "[^'\">{]+" ;a bit pessimistic
95a045bd 535 (regexp-opt `("''" "\">" "\"'" ">>" "»") t))
15ca8de7
SM
536 'font-lock-string-face)
537 ;;
53c4fe47 538 ;; Command names, special and general.
1b741d9e
AS
539 (cons (concat slash specials-1) 'font-lock-warning-face)
540 (list (concat "\\(" slash specials-2 "\\)\\([^a-zA-Z@]\\|\\'\\)")
541 1 'font-lock-warning-face)
53c4fe47
SM
542 (concat slash general)
543 ;;
544 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
545 ;; since we might not be able to display those fonts.
15ca8de7
SM
546 (list (concat slash bold " *" arg) 2 '(quote bold) 'append)
547 (list (concat slash italic " *" arg) 2 '(quote italic) 'append)
1598a961 548 ;; (list (concat slash type arg) 2 '(quote bold-italic) 'append)
53c4fe47
SM
549 ;;
550 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
7afecb99
SM
551 (list (concat "\\\\\\(em\\|it\\|sl\\)\\>" args)
552 2 '(quote italic) 'append)
553 ;; This is separate from the previous one because of cases like
554 ;; {\em foo {\bf bar} bla} where both match.
555 (list (concat "\\\\bf\\>" args) 1 '(quote bold) 'append)))))
53c4fe47
SM
556 "Gaudy expressions to highlight in TeX modes.")
557
7afecb99
SM
558(defun tex-font-lock-suscript (pos)
559 (unless (or (memq (get-text-property pos 'face)
560 '(font-lock-constant-face font-lock-builtin-face
561 font-lock-comment-face tex-verbatim-face))
562 ;; Check for backslash quoting
563 (let ((odd nil)
564 (pos pos))
565 (while (eq (char-before pos) ?\\)
566 (setq pos (1- pos) odd (not odd)))
567 odd))
568 (if (eq (char-after pos) ?_)
569 '(face subscript display (raise -0.3))
570 '(face superscript display (raise +0.3)))))
571
572(defconst tex-font-lock-keywords-3
573 (append tex-font-lock-keywords-2
574 (eval-when-compile
575 (let ((general "\\([a-zA-Z@]+\\|[^ \t\n]\\)")
576 (slash "\\\\")
577 ;; This is not the same regexp as before: it has a `+' removed.
578 ;; The + makes the matching faster in the above cases (where we can
579 ;; exit as soon as the match fails) but would make this matching
580 ;; degenerate to nasty complexity (because we try to match the
581 ;; closing brace, which forces trying all matching combinations).
582 (arg "{\\(?:[^{}\\]\\|\\\\.\\|{[^}]*}\\)*"))
583 `((,(concat "[_^] *\\([^\n\\{}]\\|" slash general "\\|" arg "}\\)")
584 (1 (tex-font-lock-suscript (match-beginning 0))
585 append))))))
586 "Experimental expressions to highlight in TeX modes.")
587
53c4fe47
SM
588(defvar tex-font-lock-keywords tex-font-lock-keywords-1
589 "Default expressions to highlight in TeX modes.")
0fb4f245 590
7afecb99
SM
591(defvar tex-verbatim-environments
592 '("verbatim" "verbatim*"))
593
594(defvar tex-font-lock-syntactic-keywords
595 (let ((verbs (regexp-opt tex-verbatim-environments t)))
596 `((,(concat "^\\\\begin *{" verbs "}.*\\(\n\\)") 2 "|")
597 (,(concat "^\\\\end *{" verbs "}\\(.?\\)") 2
598 (unless (<= (match-beginning 0) (point-min))
599 (put-text-property (1- (match-beginning 0)) (match-beginning 0)
600 'syntax-table (string-to-syntax "|"))
601 "<"))
602 ;; ("^\\(\\\\\\)begin *{comment}" 1 "< b")
603 ;; ("^\\\\end *{comment}.*\\(\n\\)" 1 "> b")
604 ("\\\\verb\\**\\([^a-z@*]\\)" 1 "\""))))
605
606(defun tex-font-lock-unfontify-region (beg end)
607 (font-lock-default-unfontify-region beg end)
608 (while (< beg end)
609 (let ((next (next-single-property-change beg 'display nil end))
610 (prop (get-text-property beg 'display)))
611 (if (and (eq (car-safe prop) 'raise)
612 (member (car-safe (cdr prop)) '(-0.3 +0.3))
613 (null (cddr prop)))
614 (put-text-property beg next 'display nil))
615 (setq beg next))))
616
617(defface superscript
618 '((t :height 0.8)) ;; :raise 0.3
619 "Face used for superscripts.")
620(defface subscript
621 '((t :height 0.8)) ;; :raise -0.3
622 "Face used for subscripts.")
bdbd9606
SM
623
624(defface tex-math-face
625 '((t :inherit font-lock-string-face))
626 "Face used to highlight TeX math expressions.")
627(defvar tex-math-face 'tex-math-face)
7afecb99
SM
628(defface tex-verbatim-face
629 ;; '((t :inherit font-lock-string-face))
630 '((t :family "courier"))
631 "Face used to highlight TeX verbatim environments.")
632(defvar tex-verbatim-face 'tex-verbatim-face)
bdbd9606
SM
633
634;; Use string syntax but math face for $...$.
635(defun tex-font-lock-syntactic-face-function (state)
7afecb99
SM
636 (let ((char (nth 3 state)))
637 (cond
638 ((not char) font-lock-comment-face)
639 ((eq char ?$) tex-math-face)
640 (t
641 (when (char-valid-p char)
642 ;; This is a \verb?...? construct. Let's find the end and mark it.
643 (save-excursion
644 (skip-chars-forward (string ?^ char)) ;; Use `end' ?
645 (when (eq (char-syntax (preceding-char)) ?/)
646 (put-text-property (1- (point)) (point) 'syntax-table '(1)))
647 (unless (eobp)
648 (put-text-property (point) (1+ (point)) 'syntax-table '(7)))))
649 tex-verbatim-face))))
bdbd9606 650
53c4fe47 651\f
869bff31 652(defun tex-define-common-keys (keymap)
81c735c0 653 "Define the keys that we want defined both in TeX mode and in the TeX shell."
869bff31 654 (define-key keymap "\C-c\C-k" 'tex-kill-job)
655 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
656 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
657 (define-key keymap "\C-c\C-p" 'tex-print)
658 (define-key keymap "\C-c\C-v" 'tex-view)
62a24cb5
RS
659
660 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
661
bdbd9606
SM
662 (define-key keymap [menu-bar tex tex-kill-job]
663 '(menu-item "Tex Kill" tex-kill-job :enable (tex-shell-running)))
cf6d6e8a 664 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
bdbd9606
SM
665 '(menu-item "Tex Recenter" tex-recenter-output-buffer
666 :enable (get-buffer "*tex-shell*")))
62a24cb5
RS
667 (define-key keymap [menu-bar tex tex-show-print-queue]
668 '("Show Print Queue" . tex-show-print-queue))
cf6d6e8a 669 (define-key keymap [menu-bar tex tex-alt-print]
bdbd9606
SM
670 '(menu-item "Tex Print (alt printer)" tex-alt-print
671 :enable (stringp tex-print-file)))
672 (define-key keymap [menu-bar tex tex-print]
673 '(menu-item "Tex Print" tex-print :enable (stringp tex-print-file)))
674 (define-key keymap [menu-bar tex tex-view]
675 '(menu-item "Tex View" tex-view :enable (stringp tex-print-file))))
676
677(defvar tex-mode-map
678 (let ((map (make-sparse-keymap)))
15ca8de7 679 (set-keymap-parent map text-mode-map)
bdbd9606
SM
680 (tex-define-common-keys map)
681 (define-key map "\"" 'tex-insert-quote)
682 (define-key map "(" 'skeleton-pair-insert-maybe)
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 "\n" 'tex-terminate-paragraph)
687 (define-key map "\M-\r" 'latex-insert-item)
688 (define-key map "\C-c}" 'up-list)
689 (define-key map "\C-c{" 'tex-insert-braces)
690 (define-key map "\C-c\C-r" 'tex-region)
691 (define-key map "\C-c\C-b" 'tex-buffer)
692 (define-key map "\C-c\C-f" 'tex-file)
bdbd9606 693 (define-key map "\C-c\C-i" 'tex-bibtex-file)
7afecb99
SM
694 (define-key map "\C-c\C-o" 'latex-insert-block)
695 (define-key map "\C-c\C-e" 'latex-close-block)
bdbd9606
SM
696 (define-key map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
697 (define-key map "\C-c\C-m" 'tex-feed-input)
698 (define-key map [(control return)] 'tex-feed-input)
699 (define-key map [menu-bar tex tex-bibtex-file]
700 '("BibTeX File" . tex-bibtex-file))
701 (define-key map [menu-bar tex tex-validate-region]
702 '(menu-item "Validate Region" tex-validate-region :enable mark-active))
703 (define-key map [menu-bar tex tex-validate-buffer]
704 '("Validate Buffer" . tex-validate-buffer))
705 (define-key map [menu-bar tex tex-region]
706 '(menu-item "TeX Region" tex-region :enable mark-active))
707 (define-key map [menu-bar tex tex-buffer]
708 '("TeX Buffer" . tex-buffer))
709 (define-key map [menu-bar tex tex-file] '("TeX File" . tex-file))
710 map)
15ca8de7
SM
711 "Keymap shared by TeX modes.")
712
713(defvar latex-mode-map
714 (let ((map (make-sparse-keymap)))
715 (set-keymap-parent map tex-mode-map)
716 map)
717 "Keymap for `latex-mode'. See also `tex-mode-map'.")
718
719(defvar plain-tex-mode-map
720 (let ((map (make-sparse-keymap)))
721 (set-keymap-parent map tex-mode-map)
722 map)
723 "Keymap for `plain-tex-mode'. See also `tex-mode-map'.")
cf6d6e8a 724
d6709b80
SM
725(defvar tex-shell-map
726 (let ((m (make-sparse-keymap)))
727 (set-keymap-parent m shell-mode-map)
728 (tex-define-common-keys m)
729 m)
81c735c0 730 "Keymap for the TeX shell.
dca5ea48 731Inherits `shell-mode-map' with a few additions.")
869bff31 732
6da9bbd6
RS
733(defvar tex-face-alist
734 '((bold . "{\\bf ")
735 (italic . "{\\it ")
736 (bold-italic . "{\\bi ") ; hypothetical
737 (underline . "\\underline{")
738 (default . "{\\rm "))
739 "Alist of face and TeX font name for facemenu.")
740
741(defvar tex-latex-face-alist
742 `((italic . "{\\em ")
743 ,@tex-face-alist)
744 "Alist of face and LaTeX font name for facemenu.")
745
15ca8de7
SM
746;; This would be a lot simpler if we just used a regexp search,
747;; but then it would be too slow.
7229064d 748;;;###autoload
869bff31 749(defun tex-mode ()
750 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
751Tries to determine (by looking at the beginning of the file) whether
81c735c0
RS
752this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
753`latex-mode', or `slitex-mode', respectively. If it cannot be determined,
754such as if there are no commands in the file, the value of `tex-default-mode'
755says which mode to use."
869bff31 756 (interactive)
d6709b80 757 (let ((mode tex-default-mode) slash comment)
869bff31 758 (save-excursion
759 (goto-char (point-min))
760 (while (and (setq slash (search-forward "\\" nil t))
761 (setq comment (let ((search-end (point)))
762 (save-excursion
763 (beginning-of-line)
764 (search-forward "%" search-end t))))))
bdbd9606
SM
765 (when (and slash (not comment))
766 (setq mode
767 (if (looking-at
768 (eval-when-compile
769 (concat
770 (regexp-opt '("documentstyle" "documentclass"
95a045bd
SM
771 "begin" "subsection" "section"
772 "part" "chapter" "newcommand") 'words)
bdbd9606
SM
773 "\\|NeedsTeXFormat{LaTeX")))
774 (if (looking-at
775 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
776 'slitex-mode
777 'latex-mode)
778 'plain-tex-mode))))
d6709b80 779 (funcall mode)))
e4c8c838 780
6503cec3 781;;;###autoload
31e1d920 782(defalias 'TeX-mode 'tex-mode)
6503cec3 783;;;###autoload
c3ce7bf4
RS
784(defalias 'plain-TeX-mode 'plain-tex-mode)
785;;;###autoload
31e1d920 786(defalias 'LaTeX-mode 'latex-mode)
869bff31 787
7229064d 788;;;###autoload
d6709b80 789(define-derived-mode plain-tex-mode text-mode "TeX"
869bff31 790 "Major mode for editing files of input for plain TeX.
791Makes $ and } display the characters they match.
792Makes \" insert `` when it seems to be the beginning of a quotation,
793and '' when it appears to be the end; it inserts \" only after a \\.
794
795Use \\[tex-region] to run TeX on the current region, plus a \"header\"
796copied from the top of the file (containing macro definitions, etc.),
797running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
798\\[tex-file] saves the buffer and then processes the file.
799\\[tex-print] prints the .dvi file made by any of these.
800\\[tex-view] previews the .dvi file made by any of these.
801\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
802
e6b0b773 803Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 804mismatched $'s or braces.
805
806Special commands:
15ca8de7 807\\{plain-tex-mode-map}
869bff31 808
809Mode variables:
810tex-run-command
811 Command string used by \\[tex-region] or \\[tex-buffer].
812tex-directory
813 Directory in which to create temporary files for TeX jobs
814 run by \\[tex-region] or \\[tex-buffer].
815tex-dvi-print-command
816 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
817tex-alt-dvi-print-command
818 Alternative command string used by \\[tex-print] (when given a prefix
819 argument) to print a .dvi file.
869bff31 820tex-dvi-view-command
821 Command string used by \\[tex-view] to preview a .dvi file.
822tex-show-queue-command
823 Command string used by \\[tex-show-print-queue] to show the print
824 queue that \\[tex-print] put your job on.
825
81c735c0
RS
826Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
827`tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
828special subshell is initiated, the hook `tex-shell-hook' is run."
869bff31 829 (tex-common-initialization)
869bff31 830 (setq tex-command tex-run-command)
898b9ac1
RS
831 (setq tex-start-of-header "%\\*\\*start of header")
832 (setq tex-end-of-header "%\\*\\*end of header")
869bff31 833 (setq tex-trailer "\\bye\n")
d6709b80 834 (run-hooks 'tex-mode-hook))
869bff31 835
7229064d 836;;;###autoload
d6709b80 837(define-derived-mode latex-mode text-mode "LaTeX"
869bff31 838 "Major mode for editing files of input for LaTeX.
839Makes $ and } display the characters they match.
840Makes \" insert `` when it seems to be the beginning of a quotation,
841and '' when it appears to be the end; it inserts \" only after a \\.
842
843Use \\[tex-region] to run LaTeX on the current region, plus the preamble
844copied from the top of the file (containing \\documentstyle, etc.),
845running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
846\\[tex-file] saves the buffer and then processes the file.
847\\[tex-print] prints the .dvi file made by any of these.
848\\[tex-view] previews the .dvi file made by any of these.
849\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
850
e6b0b773 851Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 852mismatched $'s or braces.
853
854Special commands:
15ca8de7 855\\{latex-mode-map}
869bff31 856
857Mode variables:
858latex-run-command
859 Command string used by \\[tex-region] or \\[tex-buffer].
860tex-directory
861 Directory in which to create temporary files for LaTeX jobs
862 run by \\[tex-region] or \\[tex-buffer].
863tex-dvi-print-command
864 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
865tex-alt-dvi-print-command
866 Alternative command string used by \\[tex-print] (when given a prefix
867 argument) to print a .dvi file.
869bff31 868tex-dvi-view-command
869 Command string used by \\[tex-view] to preview a .dvi file.
870tex-show-queue-command
871 Command string used by \\[tex-show-print-queue] to show the print
872 queue that \\[tex-print] put your job on.
873
bed1b0c8 874Entering Latex mode runs the hook `text-mode-hook', then
81c735c0
RS
875`tex-mode-hook', and finally `latex-mode-hook'. When the special
876subshell is initiated, `tex-shell-hook' is run."
869bff31 877 (tex-common-initialization)
869bff31 878 (setq tex-command latex-run-command)
dd459839
SM
879 (setq tex-start-of-header "\\\\document\\(style\\|class\\)")
880 (setq tex-end-of-header "\\\\begin\\s-*{document}")
881 (setq tex-trailer "\\end\\s-*{document}\n")
ab2c9f54
RS
882 ;; A line containing just $$ is treated as a paragraph separator.
883 ;; A line starting with $$ starts a paragraph,
884 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80 885 (setq paragraph-start
dd459839 886 (concat "[\f%]\\|[ \t]*\\($\\|\\$\\$\\|"
d6709b80
SM
887 "\\\\[][]\\|"
888 "\\\\" (regexp-opt (append
889 (mapcar 'car latex-section-alist)
890 '("begin" "label" "end"
891 "item" "bibitem" "newline" "noindent"
892 "newpage" "footnote" "marginpar"
893 "parbox" "caption")) t)
894 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
dd459839 895 "\\>\\)"))
d6709b80 896 (setq paragraph-separate
dd459839 897 (concat "[\f%]\\|[ \t]*\\($\\|"
d6709b80
SM
898 "\\\\[][]\\|"
899 "\\\\" (regexp-opt (append
900 (mapcar 'car latex-section-alist)
901 '("begin" "label" "end" )) t)
902 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
903 "noindent" "newpage" "footnote"
904 "marginpar" "parbox" "caption"))
dd459839
SM
905 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
906 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
d6709b80
SM
907 (set (make-local-variable 'imenu-create-index-function)
908 'latex-imenu-create-index)
909 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
95a045bd 910 (add-hook 'fill-nobreak-predicate 'latex-fill-nobreak-predicate nil t)
ea590e1c 911 (set (make-local-variable 'indent-line-function) 'latex-indent)
dd459839 912 (set (make-local-variable 'fill-indent-according-to-mode) t)
d6709b80
SM
913 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
914 (set (make-local-variable 'outline-level) 'latex-outline-level)
53c4fe47 915 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
15ca8de7 916 (set (make-local-variable 'skeleton-end-hook) nil)
d6709b80 917 (run-hooks 'tex-mode-hook))
869bff31 918
bd2f2323 919;;;###autoload
d6709b80 920(define-derived-mode slitex-mode latex-mode "SliTeX"
869bff31 921 "Major mode for editing files of input for SliTeX.
922Makes $ and } display the characters they match.
923Makes \" insert `` when it seems to be the beginning of a quotation,
924and '' when it appears to be the end; it inserts \" only after a \\.
925
926Use \\[tex-region] to run SliTeX on the current region, plus the preamble
927copied from the top of the file (containing \\documentstyle, etc.),
928running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
929\\[tex-file] saves the buffer and then processes the file.
930\\[tex-print] prints the .dvi file made by any of these.
931\\[tex-view] previews the .dvi file made by any of these.
932\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
933
e6b0b773 934Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 935mismatched $'s or braces.
936
937Special commands:
15ca8de7 938\\{slitex-mode-map}
869bff31 939
940Mode variables:
941slitex-run-command
942 Command string used by \\[tex-region] or \\[tex-buffer].
943tex-directory
944 Directory in which to create temporary files for SliTeX jobs
945 run by \\[tex-region] or \\[tex-buffer].
946tex-dvi-print-command
947 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
948tex-alt-dvi-print-command
949 Alternative command string used by \\[tex-print] (when given a prefix
950 argument) to print a .dvi file.
869bff31 951tex-dvi-view-command
952 Command string used by \\[tex-view] to preview a .dvi file.
953tex-show-queue-command
954 Command string used by \\[tex-show-print-queue] to show the print
955 queue that \\[tex-print] put your job on.
956
81c735c0
RS
957Entering SliTeX mode runs the hook `text-mode-hook', then the hook
958`tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
959`slitex-mode-hook'. When the special subshell is initiated, the hook
960`tex-shell-hook' is run."
869bff31 961 (setq tex-command slitex-run-command)
d6709b80 962 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
869bff31 963
964(defun tex-common-initialization ()
ea590e1c 965 (set-syntax-table tex-mode-syntax-table)
822eddf4 966 ;; Regexp isearch should accept newline and formfeed as whitespace.
d6709b80 967 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
64db2461 968 ;; A line containing just $$ is treated as a paragraph separator.
d6709b80
SM
969 (set (make-local-variable 'paragraph-start)
970 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
ab2c9f54
RS
971 ;; A line starting with $$ starts a paragraph,
972 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80
SM
973 (set (make-local-variable 'paragraph-separate)
974 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
975 (set (make-local-variable 'comment-start) "%")
976 (set (make-local-variable 'comment-add) 1)
977 (set (make-local-variable 'comment-start-skip)
5ae0d697 978 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
d6709b80
SM
979 (set (make-local-variable 'parse-sexp-ignore-comments) t)
980 (set (make-local-variable 'compare-windows-whitespace)
981 'tex-categorize-whitespace)
982 (set (make-local-variable 'facemenu-add-face-function)
983 (lambda (face end)
984 (let ((face-text (cdr (assq face tex-face-alist))))
985 (if face-text
986 face-text
987 (error "Face %s not configured for %s mode" face mode-name)))))
988 (set (make-local-variable 'facemenu-end-add-face) "}")
989 (set (make-local-variable 'facemenu-remove-face-function) t)
990 (set (make-local-variable 'font-lock-defaults)
7afecb99
SM
991 '((tex-font-lock-keywords tex-font-lock-keywords-1
992 tex-font-lock-keywords-2 tex-font-lock-keywords-3)
d6709b80
SM
993 nil nil ((?$ . "\"")) nil
994 ;; Who ever uses that anyway ???
bdbd9606
SM
995 (font-lock-mark-block-function . mark-paragraph)
996 (font-lock-syntactic-face-function
7afecb99
SM
997 . tex-font-lock-syntactic-face-function)
998 (font-lock-unfontify-region-function
999 . tex-font-lock-unfontify-region)
1000 (font-lock-syntactic-keywords
1001 . tex-font-lock-syntactic-keywords)
1002 (parse-sexp-lookup-properties . t)))
95a045bd
SM
1003 ;; TABs in verbatim environments don't do what you think.
1004 (set (make-local-variable 'indent-tabs-mode) nil)
7afecb99 1005 ;; Other vars that should be buffer-local.
869bff31 1006 (make-local-variable 'tex-command)
1007 (make-local-variable 'tex-start-of-header)
1008 (make-local-variable 'tex-end-of-header)
1009 (make-local-variable 'tex-trailer))
1010
869bff31 1011(defun tex-categorize-whitespace (backward-limit)
1012 ;; compare-windows-whitespace is set to this.
1013 ;; This is basically a finite-state machine.
1014 ;; Returns a symbol telling how TeX would treat
1015 ;; the whitespace we are looking at: null, space, or par.
1016 (let ((category 'null)
1017 (not-finished t))
1018 (skip-chars-backward " \t\n\f" backward-limit)
1019 (while not-finished
1020 (cond ((looking-at "[ \t]+")
1021 (goto-char (match-end 0))
2be5fefb 1022 (if (eq category 'null)
869bff31 1023 (setq category 'space)))
1024 ((looking-at "\n")
2be5fefb 1025 (cond ((eq category 'newline)
869bff31 1026 (setq category 'par)
1027 (setq not-finished nil))
1028 (t
1029 (setq category 'newline) ;a strictly internal state
1030 (goto-char (match-end 0)))))
1031 ((looking-at "\f+")
1032 (setq category 'par)
1033 (setq not-finished nil))
1034 (t
1035 (setq not-finished nil))))
1036 (skip-chars-forward " \t\n\f")
2be5fefb 1037 (if (eq category 'newline)
869bff31 1038 'space ;TeX doesn't distinguish
1039 category)))
1040
1041(defun tex-insert-quote (arg)
1042 "Insert the appropriate quote marks for TeX.
08348502
RS
1043Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
1044\(normally '') depending on the context. With prefix argument, always
869bff31 1045inserts \" characters."
528415e7 1046 (interactive "*P")
95a045bd
SM
1047 (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
1048 (eq (get-text-property (point) 'face) 'tex-verbatim-face)
1049 (save-excursion
1050 (backward-char (length tex-open-quote))
1051 (when (or (looking-at (regexp-quote tex-open-quote))
1052 (looking-at (regexp-quote tex-close-quote)))
1053 (delete-char (length tex-open-quote))
1054 t)))
869bff31 1055 (self-insert-command (prefix-numeric-value arg))
95a045bd
SM
1056 (insert (if (memq (char-syntax (preceding-char)) '(?\( ?> ?\ ))
1057 tex-open-quote tex-close-quote))))
869bff31 1058
e6b0b773
MR
1059(defun tex-validate-buffer ()
1060 "Check current buffer for paragraphs containing mismatched braces or $s.
bbd93e41 1061Their positions are recorded in the buffer `*Occur*'.
e6b0b773
MR
1062To find a particular invalidity from `*Occur*', switch to that buffer
1063and type C-c C-c or click with mouse-2
1064on the line for the invalidity you want to see."
869bff31 1065 (interactive)
bbd93e41
RS
1066 (let ((buffer (current-buffer))
1067 (prevpos (point-min))
e6b0b773
MR
1068 (linenum nil)
1069 (num-matches 0))
bbd93e41
RS
1070 (with-output-to-temp-buffer "*Occur*"
1071 (princ "Mismatches:\n")
1072 (save-excursion
1073 (set-buffer standard-output)
1074 (occur-mode)
52ab062c
CW
1075 ;; This won't actually work...Really, this whole thing should
1076 ;; be rewritten instead of being a hack on top of occur.
1077 (setq occur-revert-arguments (list nil 0 (list buffer))))
bbd93e41
RS
1078 (save-excursion
1079 (goto-char (point-max))
52ab062c 1080 (while (and (not (bobp)))
710a0f53
KH
1081 (let ((end (point))
1082 prev-end)
bbd93e41 1083 ;; Scan the previous paragraph for invalidities.
710a0f53
KH
1084 (if (search-backward "\n\n" nil t)
1085 (progn
1086 (setq prev-end (point))
1087 (forward-char 2))
1088 (goto-char (setq prev-end (point-min))))
869bff31 1089 (or (tex-validate-region (point) end)
710a0f53
KH
1090 (let* ((oend end)
1091 (end (save-excursion (forward-line 1) (point)))
bbd93e41
RS
1092 start tem)
1093 (beginning-of-line)
1094 (setq start (point))
1095 ;; Keep track of line number as we scan,
1096 ;; in a cumulative fashion.
1097 (if linenum
1098 (setq linenum (- linenum (count-lines prevpos (point))))
1099 (setq linenum (1+ (count-lines 1 start))))
1100 (setq prevpos (point))
bed1b0c8 1101 ;; Mention this mismatch in *Occur*.
bbd93e41 1102 ;; Since we scan from end of buffer to beginning,
e6b0b773 1103 ;; add each mismatch at the beginning of *Occur*.
bbd93e41
RS
1104 (save-excursion
1105 (setq tem (point-marker))
1106 (set-buffer standard-output)
1107 (goto-char (point-min))
1108 ;; Skip "Mismatches:" header line.
1109 (forward-line 1)
e6b0b773 1110 (setq num-matches (1+ num-matches))
bbd93e41 1111 (insert-buffer-substring buffer start end)
e6b0b773
MR
1112 (let (text-beg (text-end (point-marker)))
1113 (forward-char (- start end))
1114 (setq text-beg (point-marker))
1115 (insert (format "%3d: " linenum))
a865de85
EZ
1116 (add-text-properties
1117 text-beg (- text-end 1)
1118 '(mouse-face highlight
1119 help-echo "mouse-2: go to this invalidity"))
1598a961 1120 (put-text-property text-beg (- text-end 1)
52ab062c 1121 'occur-target tem)))))
710a0f53 1122 (goto-char prev-end))))
bdbd9606 1123 (with-current-buffer standard-output
e6b0b773 1124 (if (eq num-matches 0)
bbd93e41
RS
1125 (insert "None!\n"))
1126 (if (interactive-p)
e6b0b773 1127 (message "%d mismatches found" num-matches))))))
869bff31 1128
1129(defun tex-validate-region (start end)
1130 "Check for mismatched braces or $'s in region.
1131Returns t if no mismatches. Returns nil and moves point to suspect
1132area if a mismatch is found."
1133 (interactive "r")
1134 (let ((failure-point nil) (max-possible-sexps (- end start)))
1135 (save-excursion
1136 (condition-case ()
1137 (save-restriction
1138 (narrow-to-region start end)
2ed2806c 1139 ;; First check that the open and close parens balance in numbers.
869bff31 1140 (goto-char start)
e6b0b773 1141 (while (<= 0 (setq max-possible-sexps (1- max-possible-sexps)))
2ed2806c
KH
1142 (forward-sexp 1))
1143 ;; Now check that like matches like.
1144 (goto-char start)
1145 (while (progn (skip-syntax-forward "^(")
1146 (not (eobp)))
1147 (let ((match (matching-paren (following-char))))
1148 (save-excursion
1149 (forward-sexp 1)
1150 (or (= (preceding-char) match)
1151 (error "Mismatched parentheses"))))
1152 (forward-char 1)))
869bff31 1153 (error
bed1b0c8
RS
1154 (skip-syntax-forward " .>")
1155 (setq failure-point (point)))))
bdbd9606
SM
1156 (if failure-point (goto-char failure-point))
1157 (not failure-point)))
869bff31 1158
1159(defun tex-terminate-paragraph (inhibit-validation)
1160 "Insert two newlines, breaking a paragraph for TeX.
81c735c0 1161Check for mismatched braces or $s in paragraph being terminated.
869bff31 1162A prefix arg inhibits the checking."
528415e7 1163 (interactive "*P")
869bff31 1164 (or inhibit-validation
1165 (save-excursion
1166 (tex-validate-region
bed1b0c8
RS
1167 (save-excursion
1168 (search-backward "\n\n" nil 'move)
1169 (point))
1170 (point)))
869bff31 1171 (message "Paragraph being closed appears to contain a mismatch"))
1172 (insert "\n\n"))
1173
7afecb99 1174(define-skeleton tex-insert-braces
869bff31 1175 "Make a pair of braces and be poised to type inside of them."
7afecb99
SM
1176 nil
1177 ?\{ _ ?})
869bff31 1178
9bd4f69c
RS
1179;; This function is used as the value of fill-nobreak-predicate
1180;; in LaTeX mode. Its job is to prevent line-breaking inside
1181;; of a \verb construct.
1182(defun latex-fill-nobreak-predicate ()
7afecb99
SM
1183 (save-excursion
1184 (skip-chars-backward " ")
1185 ;; Don't break after \ since `\ ' has special meaning.
1186 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
1187 (let ((opoint (point))
1188 inside)
1189 (beginning-of-line)
1190 (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
1191 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
1192 (setq inside t)))
1193 inside))))
9bd4f69c 1194
53c4fe47
SM
1195(defvar latex-block-default "enumerate")
1196
15ca8de7 1197;; Like tex-insert-braces, but for LaTeX.
7afecb99
SM
1198(defalias 'tex-latex-block 'latex-insert-block)
1199(define-skeleton latex-insert-block
cf149bdf 1200 "Create a matching pair of lines \\begin[OPT]{NAME} and \\end{NAME} at point.
869bff31 1201Puts point on a blank line between them."
53c4fe47
SM
1202 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1203 latex-block-default)
95a045bd 1204 (append latex-block-names
7afecb99 1205 latex-standard-block-names)
53c4fe47
SM
1206 nil nil nil nil latex-block-default)))
1207 (setq latex-block-default choice)
7afecb99 1208 (unless (or (member choice latex-standard-block-names)
53c4fe47
SM
1209 (member choice latex-block-names))
1210 ;; Remember new block names for later completion.
1211 (push choice latex-block-names))
1212 choice)
95a045bd 1213 \n "\\begin{" str "}"
53c4fe47 1214 ?\[ (skeleton-read "[options]: ") & ?\] | -1
dd459839 1215 > \n _ \n
95a045bd 1216 "\\end{" str "}" > \n)
53c4fe47 1217
ea590e1c
SM
1218(define-skeleton latex-insert-item
1219 "Insert a \item macro."
1220 nil
15ca8de7 1221 \n "\\item " >)
ea590e1c 1222
53c4fe47
SM
1223\f
1224;;;;
1225;;;; LaTeX syntax navigation
1226;;;;
869bff31 1227
1228(defun tex-last-unended-begin ()
81c735c0 1229 "Leave point at the beginning of the last `\\begin{...}' that is unended."
95a045bd
SM
1230 (condition-case nil
1231 (while (and (re-search-backward "\\\\\\(begin\\|end\\)\\s *{")
1232 (looking-at "\\\\end"))
1233 (tex-last-unended-begin))
1234 (search-failed (error "Couldn't find unended \\begin"))))
869bff31 1235
53c4fe47
SM
1236(defun tex-next-unmatched-end ()
1237 "Leave point at the end of the next `\\end' that is unended."
1238 (while (and (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}")
ea590e1c
SM
1239 (save-excursion (goto-char (match-beginning 0))
1240 (looking-at "\\\\begin")))
53c4fe47
SM
1241 (tex-next-unmatched-end)))
1242
6a900cf1
ER
1243(defun tex-goto-last-unclosed-latex-block ()
1244 "Move point to the last unclosed \\begin{...}.
1245Mark is left at original location."
1246 (interactive)
1247 (let ((spot))
1248 (save-excursion
95a045bd 1249 (tex-last-unended-begin)
6a900cf1
ER
1250 (setq spot (point)))
1251 (push-mark)
1252 (goto-char spot)))
1253
53c4fe47
SM
1254(defun latex-backward-sexp-1 ()
1255 "Like (backward-sexp 1) but aware of multi-char elements."
1256 (let ((pos (point))
1257 (forward-sexp-function))
1258 (backward-sexp 1)
1259 (if (looking-at "\\\\begin\\>")
1260 (signal 'scan-error
1261 (list "Containing expression ends prematurely"
1262 (point) (prog1 (point) (goto-char pos))))
1263 (when (eq (char-after) ?{)
1264 (let ((newpos (point)))
1265 (when (ignore-errors (backward-sexp 1) t)
1266 (if (looking-at "\\\\end\\>")
1267 (tex-last-unended-begin)
1268 (goto-char newpos))))))))
1269
1270(defun latex-forward-sexp-1 ()
1271 "Like (forward-sexp 1) but aware of multi-char elements."
1272 (let ((pos (point))
1273 (forward-sexp-function))
1274 (forward-sexp 1)
1275 (let ((newpos (point)))
1276 (skip-syntax-backward "/w")
1277 (cond
1278 ((looking-at "\\\\end\\>")
1279 (signal 'scan-error
1280 (list "Containing expression ends prematurely"
1281 (point)
1282 (prog1
1283 (progn (ignore-errors (forward-sexp 2)) (point))
1284 (goto-char pos)))))
1285 ((looking-at "\\\\begin\\>")
1286 (goto-char (match-end 0))
1287 (tex-next-unmatched-end))
1288 (t (goto-char newpos))))))
1289
1290(defun latex-forward-sexp (&optional arg)
1291 "Like `forward-sexp' but aware of multi-char elements."
1292 (interactive "P")
1293 (unless arg (setq arg 1))
1294 (let ((pos (point)))
1295 (condition-case err
1296 (while (/= arg 0)
1297 (setq arg
1298 (if (> arg 0)
1299 (progn (latex-forward-sexp-1) (1- arg))
1300 (progn (latex-backward-sexp-1) (1+ arg)))))
1301 (scan-error
1302 (goto-char pos)
1303 (signal (car err) (cdr err))))))
1304
ea590e1c
SM
1305(defun latex-syntax-after ()
1306 "Like (char-syntax (char-after)) but aware of multi-char elements."
15ca8de7 1307 (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
ea590e1c
SM
1308
1309(defun latex-skip-close-parens ()
1310 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1311 (let ((forward-sexp-function nil))
1312 (while (progn (skip-syntax-forward " )")
1313 (looking-at "\\\\end\\>"))
1314 (forward-sexp 2))))
1315
1316(defun latex-down-list ()
1317 "Like (down-list 1) but aware of multi-char elements."
1318 (forward-comment (point-max))
1319 (let ((forward-sexp-function nil))
1320 (if (not (looking-at "\\\\begin\\>"))
1321 (down-list 1)
1322 (forward-sexp 1)
1323 ;; Skip arguments.
7afecb99
SM
1324 (while (looking-at "[ \t]*[[{(]")
1325 (with-syntax-table tex-mode-syntax-table
1326 (forward-sexp))))))
ea590e1c 1327
7afecb99
SM
1328(defalias 'tex-close-latex-block 'latex-close-block)
1329(define-skeleton latex-close-block
1330 "Create an \\end{...} to match the last unclosed \\begin{...}."
1331 (save-excursion
1332 (tex-last-unended-begin)
1333 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1334 (match-string 1)))
1335 \n "\\end" str > \n)
1336
1337(define-skeleton latex-split-block
1338 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1339 (save-excursion
1340 (tex-last-unended-begin)
1341 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1342 (prog1 (match-string 1)
1343 (goto-char (match-end 1))
1344 (setq v1 (buffer-substring (point)
1345 (progn
1346 (while (looking-at "[ \t]*[[{]")
1347 (forward-sexp 1))
1348 (point)))))))
1349 \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
15ca8de7
SM
1350
1351(defconst tex-discount-args-cmds
1352 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1353 "documentclass" "usepackage" "label")
1354 "TeX commands whose arguments should not be counted as text.")
1355
1356(defun tex-count-words (begin end)
1357 "Count the number of words in the buffer."
1358 (interactive
1359 (if (and transient-mark-mode mark-active)
1360 (list (region-beginning) (region-end))
1361 (list (point-min) (point-max))))
1362 ;; TODO: skip comments and math and maybe some environments.
1363 (save-excursion
1364 (goto-char begin)
1365 (let ((count 0))
1366 (while (and (< (point) end) (re-search-forward "\\<" end t))
1367 (if (not (eq (char-syntax (preceding-char)) ?/))
1368 (progn
1369 ;; Don't count single-char words.
1370 (unless (looking-at ".\\>") (incf count))
1371 (forward-char 1))
1372 (let ((cmd
1373 (buffer-substring-no-properties
1374 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1375 (forward-char 1))
1376 (point)))))
1377 (when (member cmd tex-discount-args-cmds)
1378 (skip-chars-forward "*")
1379 (forward-comment (point-max))
1380 (when (looking-at "\\[")
1381 (forward-sexp 1)
1382 (forward-comment (point-max)))
1383 (if (not (looking-at "{"))
1384 (forward-char 1)
1385 (forward-sexp 1))))))
1386 (message "%s words" count))))
b781e739
SS
1387
1388
869bff31 1389\f
1390;;; Invoking TeX in an inferior shell.
1391
15ca8de7
SM
1392;; Why use a shell instead of running TeX directly? Because if TeX
1393;; gets stuck, the user can switch to the shell window and type at it.
869bff31 1394
15ca8de7 1395;; The utility functions:
869bff31 1396
bdbd9606
SM
1397(define-derived-mode tex-shell shell-mode "TeX-Shell"
1398 (compilation-shell-minor-mode t))
1399
d974af30 1400;;;###autoload
869bff31 1401(defun tex-start-shell ()
d6709b80
SM
1402 (with-current-buffer
1403 (make-comint
1404 "tex-shell"
07c16ec4 1405 (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
d6709b80 1406 nil)
528415e7
RS
1407 (let ((proc (get-process "tex-shell")))
1408 (set-process-sentinel proc 'tex-shell-sentinel)
1409 (process-kill-without-query proc)
bdbd9606 1410 (tex-shell)
528415e7 1411 (while (zerop (buffer-size))
51b2c841
RS
1412 (sleep-for 1)))))
1413
033306e3
RS
1414(defun tex-feed-input ()
1415 "Send input to the tex shell process.
1416In the tex buffer this can be used to continue an interactive tex run.
bed1b0c8 1417In the tex shell buffer this command behaves like `comint-send-input'."
033306e3 1418 (interactive)
b781e739 1419 (set-buffer (tex-shell-buf))
033306e3
RS
1420 (comint-send-input)
1421 (tex-recenter-output-buffer nil))
1422
51b2c841
RS
1423(defun tex-display-shell ()
1424 "Make the TeX shell buffer visible in a window."
b781e739 1425 (display-buffer (tex-shell-buf))
51b2c841 1426 (tex-recenter-output-buffer nil))
528415e7
RS
1427
1428(defun tex-shell-sentinel (proc msg)
1429 (cond ((null (buffer-name (process-buffer proc)))
1430 ;; buffer killed
1431 (set-process-buffer proc nil)
1432 (tex-delete-last-temp-files))
1433 ((memq (process-status proc) '(signal exit))
1434 (tex-delete-last-temp-files))))
1435
1436(defun tex-set-buffer-directory (buffer directory)
869bff31 1437 "Set BUFFER's default directory to be DIRECTORY."
1438 (setq directory (file-name-as-directory (expand-file-name directory)))
1439 (if (not (file-directory-p directory))
1440 (error "%s is not a directory" directory)
1441 (save-excursion
1442 (set-buffer buffer)
1443 (setq default-directory directory))))
1444
30803a05
RS
1445(defvar tex-send-command-modified-tick 0)
1446(make-variable-buffer-local 'tex-send-command-modified-tick)
1447
bdbd9606 1448(defun tex-shell-proc ()
b781e739 1449 (or (tex-shell-running) (error "No TeX subprocess")))
bdbd9606
SM
1450(defun tex-shell-buf ()
1451 (process-buffer (tex-shell-proc)))
b781e739
SS
1452(defun tex-shell-buf-no-error ()
1453 (let ((proc (tex-shell-running)))
1454 (and proc (process-buffer proc))))
bdbd9606 1455
528415e7 1456(defun tex-send-command (command &optional file background)
4cdc1d4b 1457 "Send COMMAND to TeX shell process, substituting optional FILE for *.
8241d7b9
ER
1458Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1459FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1460substitution will be made in COMMAND. COMMAND can be any expression that
460e1b7d
RS
1461evaluates to a command string.
1462
1463Return the process in which TeX is running."
528415e7
RS
1464 (save-excursion
1465 (let* ((cmd (eval command))
bdbd9606 1466 (proc (tex-shell-proc))
64db2461 1467 (buf (process-buffer proc))
4f45adda 1468 (star (string-match "\\*" cmd))
4cdc1d4b
RS
1469 (string
1470 (concat
1471 (if file
1472 (if star (concat (substring cmd 0 star)
1473 file (substring cmd (1+ star)))
1474 (concat cmd " " file))
1475 cmd)
1476 (if background "&" ""))))
64db2461
RS
1477 ;; Switch to buffer before checking for subproc output in it.
1478 (set-buffer buf)
30803a05
RS
1479 ;; If text is unchanged since previous tex-send-command,
1480 ;; we haven't got any output. So wait for output now.
64db2461 1481 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
30803a05 1482 (accept-process-output proc))
4cdc1d4b
RS
1483 (goto-char (process-mark proc))
1484 (insert string)
30803a05 1485 (comint-send-input)
460e1b7d
RS
1486 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1487 proc)))
528415e7 1488
a15849cb
RS
1489(defun tex-delete-last-temp-files (&optional not-all)
1490 "Delete any junk files from last temp file.
1491If NOT-ALL is non-nil, save the `.dvi' file."
528415e7
RS
1492 (if tex-last-temp-file
1493 (let* ((dir (file-name-directory tex-last-temp-file))
adf6b7f9
KH
1494 (list (and (file-directory-p dir)
1495 (file-name-all-completions
02fd229c
RS
1496 (file-name-sans-extension
1497 (file-name-nondirectory tex-last-temp-file))
1498 dir))))
adf6b7f9 1499 (while list
a15849cb
RS
1500 (if not-all
1501 (and
1502 ;; If arg is non-nil, don't delete the .dvi file.
1503 (not (string-match "\\.dvi$" (car list)))
1504 (delete-file (concat dir (car list))))
1505 (delete-file (concat dir (car list))))
528415e7
RS
1506 (setq list (cdr list))))))
1507
99621a14 1508(add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
869bff31 1509
dd459839
SM
1510(defun tex-guess-main-file (&optional all)
1511 "Find a likely `tex-main-file'.
1512Looks for hints in other buffers in the same directory or in
1513ALL other buffers."
1514 (let ((dir default-directory)
1515 (header-re tex-start-of-header))
1516 (catch 'found
1517 ;; Look for a buffer with `tex-main-file' set.
1518 (dolist (buf (if (consp all) all (buffer-list)))
1519 (with-current-buffer buf
1520 (when (and (or all (equal dir default-directory))
1521 (stringp tex-main-file))
1522 (throw 'found (expand-file-name tex-main-file)))))
1523 ;; Look for a buffer containing the magic `tex-start-of-header'.
1524 (dolist (buf (if (consp all) all (buffer-list)))
1525 (with-current-buffer buf
1526 (when (and (or all (equal dir default-directory))
1527 buffer-file-name
1528 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1529 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1530 (save-excursion
cb30255a
SM
1531 (save-restriction
1532 (widen)
1533 (goto-char (point-min))
95a045bd
SM
1534 (re-search-forward
1535 header-re (+ (point) 10000) t))))
dd459839
SM
1536 (throw 'found (expand-file-name buffer-file-name))))))))
1537
07c16ec4
SM
1538(defun tex-main-file ()
1539 "Return the relative name of the main file."
bdbd9606
SM
1540 (let* ((file (or tex-main-file
1541 ;; Compatibility with AUCTeX.
1542 (and (boundp 'TeX-master) (stringp TeX-master)
1543 (set (make-local-variable 'tex-main-file) TeX-master))
1544 ;; Try to guess the main file.
1545 (if (not buffer-file-name)
1546 (error "Buffer is not associated with any file")
1547 (file-relative-name
1548 (if (save-excursion
1549 (goto-char (point-min))
95a045bd
SM
1550 (re-search-forward tex-start-of-header
1551 (+ (point) 10000) t))
bdbd9606
SM
1552 ;; This is the main file.
1553 buffer-file-name
1554 ;; This isn't the main file, let's try to find better,
1555 (or (tex-guess-main-file)
1556 ;; (tex-guess-main-file t)
07c16ec4
SM
1557 buffer-file-name)))))))
1558 (if (file-exists-p file) file (concat file ".tex"))))
dd459839 1559
d6709b80
SM
1560
1561(defun tex-start-tex (command file &optional dir)
460e1b7d 1562 "Start a TeX run, using COMMAND on FILE."
6633b891 1563 (let* ((star (string-match "\\*" command))
460e1b7d 1564 (compile-command
6633b891
KH
1565 (if star
1566 (concat (substring command 0 star)
1567 (comint-quote-filename file)
1568 (substring command (1+ star)))
1569 (concat command " "
95a045bd 1570 tex-start-options
9e0ad27a 1571 (if (< 0 (length tex-start-commands))
c3ce7bf4 1572 (concat
9e0ad27a 1573 (shell-quote-argument tex-start-commands) " "))
6633b891 1574 (comint-quote-filename file)))))
bdbd9606
SM
1575 (tex-send-tex-command compile-command dir)))
1576
1577(defun tex-send-tex-command (cmd &optional dir)
b781e739
SS
1578 (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
1579 (and buf (with-current-buffer buf
1580 default-directory))))
bdbd9606
SM
1581 (not dir))
1582 (let (shell-dirtrack-verbose)
1583 (tex-send-command tex-shell-cd-command dir)))
1584 (with-current-buffer (process-buffer (tex-send-command cmd))
bdbd9606
SM
1585 (make-local-variable 'compilation-parse-errors-function)
1586 (setq compilation-parse-errors-function 'tex-compilation-parse-errors)
1587 (setq compilation-last-buffer (current-buffer))
1588 (compilation-forget-errors)
1598a961 1589 ;; Don't parse previous compilations.
bdbd9606
SM
1590 (set-marker compilation-parsing-end (1- (point-max))))
1591 (tex-display-shell)
1592 (setq tex-last-buffer-texed (current-buffer)))
460e1b7d 1593\f
1598a961
SM
1594(defvar tex-error-parse-syntax-table
1595 (let ((st (make-syntax-table)))
1596 (modify-syntax-entry ?\( "()" st)
1597 (modify-syntax-entry ?\) ")(" st)
1598 (modify-syntax-entry ?\\ "\\" st)
1599 (modify-syntax-entry ?\{ "_" st)
1600 (modify-syntax-entry ?\} "_" st)
1601 (modify-syntax-entry ?\[ "_" st)
1602 (modify-syntax-entry ?\] "_" st)
1603 ;; Single quotations may appear in errors
1604 (modify-syntax-entry ?\" "_" st)
1605 st)
1606 "Syntax-table used while parsing TeX error messages.")
1607
460e1b7d 1608(defun tex-compilation-parse-errors (limit-search find-at-least)
f05bd645
RS
1609 "Parse the current buffer as TeX error messages.
1610See the variable `compilation-parse-errors-function' for the interface it uses.
1611
1612This function parses only the last TeX compilation.
1613It works on TeX compilations only. It is necessary for that purpose,
1614since TeX does not put file names and line numbers on the same line as
1615for the error messages."
460e1b7d
RS
1616 (require 'thingatpt)
1617 (setq compilation-error-list nil)
1618 (message "Parsing error messages...")
f05bd645
RS
1619 (let ((default-directory ; Perhaps dir has changed meanwhile.
1620 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
f05bd645
RS
1621 found-desired (num-errors-found 0)
1622 last-filename last-linenum last-position
1623 begin-of-error end-of-error)
f05bd645
RS
1624 ;; Don't reparse messages already seen at last parse.
1625 (goto-char compilation-parsing-end)
1626 ;; Parse messages.
1627 (while (and (not (or found-desired (eobp)))
1628 (prog1 (re-search-forward "^! " nil 'move)
1629 (setq begin-of-error (match-beginning 0)
1630 end-of-error (match-end 0)))
1631 (re-search-forward
1632 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
1633 (let* ((this-error (set-marker (make-marker) begin-of-error))
1634 (linenum (string-to-int (match-string 1)))
1635 (error-text (regexp-quote (match-string 3)))
1636 (filename
1637 (save-excursion
ea590e1c
SM
1638 (with-syntax-table tex-error-parse-syntax-table
1639 (backward-up-list 1)
1640 (skip-syntax-forward "(_")
1641 (while (not (file-readable-p (thing-at-point 'filename)))
1642 (skip-syntax-backward "(_")
1643 (backward-up-list 1)
1644 (skip-syntax-forward "(_"))
1645 (thing-at-point 'filename))))
f05bd645
RS
1646 (new-file
1647 (or (null last-filename)
1648 (not (string-equal last-filename filename))))
1649 (error-location
1650 (save-excursion
1651 (if (equal filename (concat tex-zap-file ".tex"))
1652 (set-buffer tex-last-buffer-texed)
1653 (set-buffer (find-file-noselect filename)))
1654 (if new-file
1598a961 1655 (progn (goto-line linenum) (setq last-position nil))
f05bd645
RS
1656 (goto-char last-position)
1657 (forward-line (- linenum last-linenum)))
1658 ;; first try a forward search for the error text,
1659 ;; then a backward search limited by the last error.
1660 (let ((starting-point (point)))
1661 (or (re-search-forward error-text nil t)
1598a961 1662 (re-search-backward error-text last-position t)
f05bd645
RS
1663 (goto-char starting-point)))
1664 (point-marker))))
1665 (goto-char this-error)
1666 (if (and compilation-error-list
1667 (or (and find-at-least
1668 (>= num-errors-found
1669 find-at-least))
1670 (and limit-search
1671 (>= end-of-error limit-search)))
1672 new-file)
1673 (setq found-desired t)
1674 (setq num-errors-found (1+ num-errors-found)
1675 last-filename filename
1676 last-linenum linenum
1677 last-position error-location
1678 compilation-error-list ; Add the new error
1679 (cons (cons this-error error-location)
1680 compilation-error-list))
1681 (goto-char end-of-error)))))
ee13a145 1682 (set-marker compilation-parsing-end (point))
f05bd645 1683 (setq compilation-error-list (nreverse compilation-error-list))
460e1b7d
RS
1684 (message "Parsing error messages...done"))
1685\f
528415e7 1686;;; The commands:
869bff31 1687
1688(defun tex-region (beg end)
1689 "Run TeX on the current region, via a temporary file.
1690The file's name comes from the variable `tex-zap-file' and the
1691variable `tex-directory' says where to put it.
1692
1693If the buffer has a header, the header is given to TeX before the
1694region itself. The buffer's header is all lines between the strings
1695defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
1696The header must start in the first 100 lines of the buffer.
1697
1698The value of `tex-trailer' is given to TeX as input after the region.
1699
1700The value of `tex-command' specifies the command to use to run TeX."
1701 (interactive "r")
1702 (if (tex-shell-running)
1703 (tex-kill-job)
1704 (tex-start-shell))
1705 (or tex-zap-file
1706 (setq tex-zap-file (tex-generate-zap-file-name)))
6d34c59f
RS
1707 ;; Temp file will be written and TeX will be run in zap-directory.
1708 ;; If the TEXINPUTS file has relative directories or if the region has
1709 ;; \input of files, this must be the same directory as the file for
1710 ;; TeX to access the correct inputs. That's why it's safest if
1711 ;; tex-directory is ".".
1712 (let* ((zap-directory
528415e7 1713 (file-name-as-directory (expand-file-name tex-directory)))
d6709b80
SM
1714 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
1715 zap-directory)))
0d548e5d
RS
1716 ;; Don't delete temp files if we do the same buffer twice in a row.
1717 (or (eq (current-buffer) tex-last-buffer-texed)
1718 (tex-delete-last-temp-files t))
869bff31 1719 ;; Write the new temp file.
1720 (save-excursion
1721 (save-restriction
1722 (widen)
1723 (goto-char (point-min))
1724 (forward-line 100)
1725 (let ((search-end (point))
6d34c59f
RS
1726 (default-directory zap-directory)
1727 (already-output 0))
869bff31 1728 (goto-char (point-min))
6d34c59f 1729
725b7428
RS
1730 ;; Maybe copy first line, such as `\input texinfo', to temp file.
1731 (and tex-first-line-header-regexp
1732 (looking-at tex-first-line-header-regexp)
bed1b0c8 1733 (write-region (point)
6d34c59f
RS
1734 (progn (forward-line 1)
1735 (setq already-output (point)))
725b7428
RS
1736 tex-out-file nil nil))
1737
6d34c59f
RS
1738 ;; Write out the header, if there is one,
1739 ;; and any of the specified region which extends before it.
1740 ;; But don't repeat anything already written.
898b9ac1 1741 (if (re-search-forward tex-start-of-header search-end t)
6d34c59f 1742 (let (hbeg)
869bff31 1743 (beginning-of-line)
1744 (setq hbeg (point)) ;mark beginning of header
898b9ac1 1745 (if (re-search-forward tex-end-of-header nil t)
6d34c59f
RS
1746 (let (hend)
1747 (forward-line 1)
bed1b0c8 1748 (setq hend (point)) ;mark end of header
6d34c59f
RS
1749 (write-region (max (min hbeg beg) already-output)
1750 hend
1751 tex-out-file
1752 (not (zerop already-output)) nil)
1753 (setq already-output hend)))))
1754
1755 ;; Write out the specified region
1756 ;; (but don't repeat anything already written).
1757 (write-region (max beg already-output) end
1758 tex-out-file
1759 (not (zerop already-output)) nil))
1760 ;; Write the trailer, if any.
1761 ;; Precede it with a newline to make sure it
1762 ;; is not hidden in a comment.
1763 (if tex-trailer
1764 (write-region (concat "\n" tex-trailer) nil
1765 tex-out-file t nil))))
528415e7
RS
1766 ;; Record the file name to be deleted afterward.
1767 (setq tex-last-temp-file tex-out-file)
f05bd645
RS
1768 ;; Use a relative file name here because (1) the proper dir
1769 ;; is already current, and (2) the abs file name is sometimes
1770 ;; too long and can make tex crash.
d6709b80
SM
1771 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
1772 (setq tex-print-file tex-out-file)))
869bff31 1773
1774(defun tex-buffer ()
1775 "Run TeX on current buffer. See \\[tex-region] for more information.
528415e7
RS
1776Does not save the buffer, so it's useful for trying experimental versions.
1777See \\[tex-file] for an alternative."
869bff31 1778 (interactive)
1779 (tex-region (point-min) (point-max)))
1780
1781(defun tex-file ()
1782 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
1783This function is more useful than \\[tex-buffer] when you need the
1784`.aux' file of LaTeX to have the correct name."
1785 (interactive)
7abc9add
SS
1786 (when tex-offer-save
1787 (save-some-buffers))
d6709b80 1788 (let* ((source-file (tex-main-file))
07c16ec4 1789 (file-dir (file-name-directory (expand-file-name source-file))))
869bff31 1790 (if (tex-shell-running)
1791 (tex-kill-job)
1792 (tex-start-shell))
d6709b80 1793 (tex-start-tex tex-command source-file file-dir)
f05bd645 1794 (setq tex-print-file (expand-file-name source-file))))
869bff31 1795
1796(defun tex-generate-zap-file-name ()
1797 "Generate a unique name suitable for use as a file name."
1798 ;; Include the shell process number and host name
1799 ;; in case there are multiple shells (for same or different user).
f5cdb851
KH
1800 ;; Dec 1998: There is a report that some versions of xdvi
1801 ;; don't work with file names that start with #.
5616ee46 1802 (format "_TZ_%d-%s"
869bff31 1803 (process-id (get-buffer-process "*tex-shell*"))
07c16ec4 1804 (subst-char-in-string ?. ?- (system-name))))
869bff31 1805
1806;; This will perhaps be useful for modifying TEXINPUTS.
1807;; Expand each file name, separated by colons, in the string S.
1808(defun tex-expand-files (s)
1809 (let (elts (start 0))
1810 (while (string-match ":" s start)
1811 (setq elts (cons (substring s start (match-beginning 0)) elts))
1812 (setq start (match-end 0)))
1813 (or (= start 0)
1814 (setq elts (cons (substring s start) elts)))
c0df1972
SM
1815 (mapconcat (lambda (elt)
1816 (if (= (length elt) 0) elt (expand-file-name elt)))
5616ee46 1817 (nreverse elts) ":")))
869bff31 1818
1819(defun tex-shell-running ()
713f7b15 1820 (let ((proc (get-process "tex-shell")))
b781e739
SS
1821 (when proc
1822 (if (and (eq (process-status proc) 'run)
1823 (buffer-live-p (process-buffer proc)))
1824 ;; return the TeX process on success
1825 proc
1826 ;; get rid of the process permanently
1827 ;; this should get rid of the annoying w32 problem with
1828 ;; dead tex-shell buffer and live process
1829 (delete-process proc)))))
869bff31 1830
1831(defun tex-kill-job ()
1832 "Kill the currently running TeX job."
1833 (interactive)
b781e739 1834 ;; `quit-process' leads to core dumps of the tex process (except if
bed1b0c8
RS
1835 ;; coredumpsize has limit 0kb as on many environments). One would
1836 ;; like to use (kill-process proc 'lambda), however that construct
1837 ;; does not work on some systems and kills the shell itself.
b781e739
SS
1838 (let ((proc (get-process "tex-shell")))
1839 (when proc (quit-process proc t))))
869bff31 1840
1841(defun tex-recenter-output-buffer (linenum)
1842 "Redisplay buffer of TeX job output so that most recent output can be seen.
1843The last line of the buffer is displayed on
1844line LINE of the window, or centered if LINE is nil."
1845 (interactive "P")
1846 (let ((tex-shell (get-buffer "*tex-shell*"))
23b64225
RS
1847 (old-buffer (current-buffer))
1848 (window))
869bff31 1849 (if (null tex-shell)
1850 (message "No TeX output buffer")
23b64225
RS
1851 (setq window (display-buffer tex-shell))
1852 (save-selected-window
1853 (select-window window)
1854 (bury-buffer tex-shell)
1855 (goto-char (point-max))
1856 (recenter (if linenum
1857 (prefix-numeric-value linenum)
1858 (/ (window-height) 2)))))))
869bff31 1859
528415e7 1860(defun tex-print (&optional alt)
869bff31 1861 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1433a222
CZ
1862Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
1863is provided, use the alternative command, `tex-alt-dvi-print-command'."
528415e7 1864 (interactive "P")
869bff31 1865 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
1866 test-name)
1867 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
45c3304d
RS
1868 (buffer-file-name)
1869 ;; Check that this buffer's printed file is up to date.
869bff31 1870 (file-newer-than-file-p
1871 (setq test-name (tex-append (buffer-file-name) ".dvi"))
45c3304d 1872 (buffer-file-name)))
869bff31 1873 (setq print-file-name-dvi test-name))
528415e7
RS
1874 (if (not (file-exists-p print-file-name-dvi))
1875 (error "No appropriate `.dvi' file could be found")
460e1b7d
RS
1876 (if (tex-shell-running)
1877 (tex-kill-job)
1878 (tex-start-shell))
528415e7 1879 (tex-send-command
bed1b0c8
RS
1880 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
1881 print-file-name-dvi t))))
869bff31 1882
cf6d6e8a
RS
1883(defun tex-alt-print ()
1884 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
002b0d00 1885Runs the shell command defined by `tex-alt-dvi-print-command'."
cf6d6e8a
RS
1886 (interactive)
1887 (tex-print t))
1888
869bff31 1889(defun tex-view ()
1890 "Preview the last `.dvi' file made by running TeX under Emacs.
1891This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2b7971c9
RS
1892The variable `tex-dvi-view-command' specifies the shell command for preview.
1893You must set that variable yourself before using this command,
1894because there is no standard value that would generally work."
869bff31 1895 (interactive)
2b7971c9
RS
1896 (or tex-dvi-view-command
1897 (error "You must set `tex-dvi-view-command'"))
746c30e2 1898 (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
869bff31 1899 (tex-print)))
1900
1901(defun tex-append (file-name suffix)
1902 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
cf6d6e8a 1903Pascal-based TeX scans for the first period, C TeX uses the last.
869bff31 1904No period is retained immediately before SUFFIX,
1905so normally SUFFIX starts with one."
1906 (if (stringp file-name)
cf6d6e8a
RS
1907 (let ((file (file-name-nondirectory file-name))
1908 trial-name)
6da9bbd6 1909 ;; Try splitting on last period.
7d0ca249
RS
1910 ;; The first-period split can get fooled when two files
1911 ;; named a.tex and a.b.tex are both tex'd;
1912 ;; the last-period split must be right if it matches at all.
cf6d6e8a
RS
1913 (setq trial-name
1914 (concat (file-name-directory file-name)
1915 (substring file 0
7d0ca249 1916 (string-match "\\.[^.]*$" file))
cf6d6e8a
RS
1917 suffix))
1918 (if (or (file-exists-p trial-name)
1919 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
1920 trial-name
7d0ca249 1921 ;; Not found, so split on first period.
cf6d6e8a
RS
1922 (concat (file-name-directory file-name)
1923 (substring file 0
7d0ca249 1924 (string-match "\\." file))
cf6d6e8a 1925 suffix)))
869bff31 1926 " "))
1927
1928(defun tex-show-print-queue ()
1929 "Show the print queue that \\[tex-print] put your job on.
1433a222 1930Runs the shell command defined by `tex-show-queue-command'."
869bff31 1931 (interactive)
1932 (if (tex-shell-running)
1933 (tex-kill-job)
1934 (tex-start-shell))
51b2c841
RS
1935 (tex-send-command tex-show-queue-command)
1936 (tex-display-shell))
869bff31 1937
1938(defun tex-bibtex-file ()
1939 "Run BibTeX on the current buffer's file."
1940 (interactive)
1941 (if (tex-shell-running)
1942 (tex-kill-job)
1943 (tex-start-shell))
e6b0b773
MR
1944 (let (shell-dirtrack-verbose
1945 (tex-out-file
869bff31 1946 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
1947 (file-dir (file-name-directory (buffer-file-name))))
528415e7 1948 (tex-send-command tex-shell-cd-command file-dir)
51b2c841
RS
1949 (tex-send-command tex-bibtex-command tex-out-file))
1950 (tex-display-shell))
ea590e1c
SM
1951\f
1952;;;;
1953;;;; LaTeX indentation
1954;;;;
1955
1956(defvar tex-indent-allhanging t)
1957(defvar tex-indent-arg 4)
1958(defvar tex-indent-basic 2)
1959(defvar tex-indent-item tex-indent-basic)
1960(defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
1961
1962(easy-mmode-defsyntax tex-latex-indent-syntax-table
dd459839
SM
1963 '((?$ . ".")
1964 (?\( . ".")
1965 (?\) . "."))
ea590e1c
SM
1966 "Syntax table used while computing indentation."
1967 :copy tex-mode-syntax-table)
1968
1969(defun latex-indent (&optional arg)
7afecb99
SM
1970 (if (and (eq (get-text-property (line-beginning-position) 'face)
1971 tex-verbatim-face))
1972 (indent-relative)
1973 (with-syntax-table tex-latex-indent-syntax-table
1974 ;; TODO: Rather than ignore $, we should try to be more clever about it.
1975 (let ((indent
1976 (save-excursion
1977 (beginning-of-line)
1978 (latex-find-indent))))
1979 (if (< indent 0) (setq indent 0))
1980 (if (<= (current-column) (current-indentation))
1981 (indent-line-to indent)
1982 (save-excursion (indent-line-to indent)))))))
ea590e1c
SM
1983
1984(defun latex-find-indent (&optional virtual)
1985 "Find the proper indentation of text after point.
1986VIRTUAL if non-nil indicates that we're only trying to find the indentation
1987 in order to determine the indentation of something else.
1988There might be text before point."
1989 (save-excursion
1990 (skip-chars-forward " \t")
1991 (or
7afecb99
SM
1992 ;; Stick the first line at column 0.
1993 (and (= (point-min) (line-beginning-position)) 0)
ea590e1c 1994 ;; Trust the current indentation, if such info is applicable.
7afecb99
SM
1995 (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
1996 (current-column))
1997 ;; Stick verbatim environments to the left margin.
1998 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
1999 (member (match-string 2) tex-verbatim-environments)
2000 0)
ea590e1c
SM
2001 ;; Put leading close-paren where the matching open brace would be.
2002 (and (eq (latex-syntax-after) ?\))
2003 (ignore-errors
2004 (save-excursion
2005 (latex-skip-close-parens)
2006 (latex-backward-sexp-1)
2007 (latex-find-indent 'virtual))))
2008 ;; Default (maybe an argument)
2009 (let ((pos (point))
2010 (char (char-after))
2011 ;; Outdent \item if necessary.
2012 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
2013 up-list-pos)
2014 ;; Find the previous point which determines our current indentation.
2015 (condition-case err
2016 (progn
2017 (latex-backward-sexp-1)
2018 (while (> (current-column) (current-indentation))
2019 (latex-backward-sexp-1)))
2020 (scan-error
2021 (setq up-list-pos (nth 2 err))))
8908cf40
SM
2022 (cond
2023 ((= (point-min) pos) 0) ; We're really just indenting the first line.
2024 ((integerp up-list-pos)
2025 ;; Have to indent relative to the open-paren.
2026 (goto-char up-list-pos)
2027 (if (and (not tex-indent-allhanging)
2028 (> pos (progn (latex-down-list)
2029 (forward-comment (point-max))
2030 (point))))
7afecb99 2031 ;; Align with the first element after the open-paren.
8908cf40
SM
2032 (current-column)
2033 ;; We're the first element after a hanging brace.
2034 (goto-char up-list-pos)
2035 (+ indent tex-indent-basic (latex-find-indent 'virtual))))
2036 ;; We're now at the "beginning" of a line.
2037 ((not (and (not virtual) (eq (char-after) ?\\)))
2038 ;; Nothing particular here: just keep the same indentation.
2039 (+ indent (current-column)))
2040 ;; We're now looking at a macro call.
7afecb99
SM
2041 ((looking-at tex-indent-item-re)
2042 ;; Indenting relative to an item, have to re-add the outdenting.
8908cf40
SM
2043 (+ indent (current-column) tex-indent-item))
2044 (t
2045 (let ((col (current-column)))
2046 (if (not (eq (char-syntax char) ?\())
2047 ;; If the first char was not an open-paren, there's
2048 ;; a risk that this is really not an argument to the
2049 ;; macro at all.
7afecb99
SM
2050 (+ indent col)
2051 (forward-sexp 1)
2052 (if (< (line-end-position)
2053 (save-excursion (forward-comment (point-max))
2054 (point)))
8908cf40
SM
2055 ;; we're indenting the first argument.
2056 (min (current-column) (+ tex-indent-arg col))
2057 (skip-syntax-forward " ")
2058 (current-column))))))))))
528415e7
RS
2059
2060(run-hooks 'tex-mode-load-hook)
869bff31 2061
49116ac0
JB
2062(provide 'tex-mode)
2063
d501f516 2064;;; tex-mode.el ends here