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