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