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