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