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