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