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