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