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, 2005 Free Software Foundation, Inc.
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)
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.
33 ;; Pacify the byte-compiler
42 (defgroup tex-file nil
43 "TeX files and directories"
48 "Running external commands from TeX mode"
52 (defgroup tex-view nil
53 "Viewing and printing TeX files"
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)
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."
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)
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)
93 (defcustom tex-offer-save t
94 "*If non-nil, ask about saving modified buffers before \\[tex-file] is run."
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."
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."
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."
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'."
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"))
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.")
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)
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."
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."
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;
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
194 :type '(choice (string :tag "Command")
195 (sexp :tag "Expression"))
199 (defcustom tex-dvi-view-command
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)
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."
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'."
230 (defcustom tex-open-quote "``"
231 "*String inserted by typing \\[tex-insert-quote] to open a quotation."
233 :options '("``" "\"<" "\"`" "<<" "«")
237 (defcustom tex-close-quote "''"
238 "*String inserted by typing \\[tex-insert-quote] to close a quotation."
240 :options '("''" "\">" "\"'" ">>" "»")
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
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.")
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."
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)
332 (concat "\\\\" (regexp-opt latex-metasection-list t)))
333 i0 menu case-fold-search)
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)
340 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
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))
349 (i (cdr (assoc (buffer-substring-no-properties
352 latex-section-alist))))
356 ;; Using sexps allows some use of matching {...} inside
359 (push (cons (concat (apply 'concat
362 latex-imenu-indent-string))
363 (buffer-substring-no-properties
369 ;; Look for included material.
370 (goto-char (point-min))
371 (while (search-forward-regexp
372 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
373 \[ \t]*{\\([^}\n]+\\)}"
375 (push (cons (concat "<<" (buffer-substring-no-properties
378 (if (= (char-after (match-beginning 1)) ?b)
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))))))))
396 (defvar latex-outline-regexp
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))
407 ;;;; Font-Lock support
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
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*"
465 (opt " *\\(\\[[^]]*\\] *\\)*")
466 ;; This would allow highlighting \newcommand\CMD but requires
467 ;; adapting subgroup numbers below.
468 ;; (arg "\\(?:{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)\\|\\\\[a-z*]+\\)"))
469 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
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)
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)
499 (list (concat slash variables " *" arg) 2 'font-lock-variable-name-face)
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))
512 (defconst tex-font-lock-keywords-2
513 (append tex-font-lock-keywords-1
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]\\)")
543 (opt " *\\(\\[[^]]*\\] *\\)*")
544 (args "\\(\\(?:[^{}&\\]+\\|\\\\.\\|{[^}]*}\\)+\\)")
545 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
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\\(series\\)?\\)\\>" 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
587 (while (eq (char-before pos) ?\\)
588 (setq pos (1- pos) odd (not 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
597 (let ((general "\\([a-zA-Z@]+\\|[^ \t\n]\\)")
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 "\\|#[0-9]\\|" arg "}\\)")
606 (1 (tex-font-lock-suscript (match-beginning 0))
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)
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))
641 (put-text-property beg next 'display nil))
645 '((t :height 0.8)) ;; :raise 0.3
646 "Face used for superscripts.")
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)))
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.
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)))
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))))
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))
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)
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)
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
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 ")
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)
780 (goto-char (point-min))
781 (while (and (setq slash (search-forward "\\" nil t))
782 (setq comment (let ((search-end (point)))
785 (search-forward "%" search-end t))))))
786 (when (and slash (not comment))
791 (regexp-opt '("documentstyle" "documentclass"
792 "begin" "subsection" "section"
793 "part" "chapter" "newcommand"
794 "renewcommand") 'words)
795 "\\|NeedsTeXFormat{LaTeX")))
797 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
798 ;; SliTeX is almost never used any more nowadays.
799 (tex-executable-exists-p slitex-run-command))
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
816 (defalias 'tex-mode-internal (symbol-function '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."
827 ;; We're called from one of the children already.
831 ;; The following three autoloaded aliases appear to conflict with
832 ;; AUCTeX. However, even though AUCTeX uses the mixed case variants
833 ;; for all mode relevant variables and hooks, the invocation function
834 ;; and setting of `major-mode' themselves need to be lowercase for
835 ;; AUCTeX to provide a fully functional user-level replacement. So
836 ;; these aliases should remain as they are, in particular since AUCTeX
837 ;; users are likely to use them.
840 (defalias 'TeX-mode 'tex-mode)
842 (defalias 'plain-TeX-mode 'plain-tex-mode)
844 (defalias 'LaTeX-mode 'latex-mode)
847 (define-derived-mode plain-tex-mode tex-mode "TeX"
848 "Major mode for editing files of input for plain TeX.
849 Makes $ and } display the characters they match.
850 Makes \" insert `` when it seems to be the beginning of a quotation,
851 and '' when it appears to be the end; it inserts \" only after a \\.
853 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
854 copied from the top of the file (containing macro definitions, etc.),
855 running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
856 \\[tex-file] saves the buffer and then processes the file.
857 \\[tex-print] prints the .dvi file made by any of these.
858 \\[tex-view] previews the .dvi file made by any of these.
859 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
861 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
862 mismatched $'s or braces.
865 \\{plain-tex-mode-map}
869 Command string used by \\[tex-region] or \\[tex-buffer].
871 Directory in which to create temporary files for TeX jobs
872 run by \\[tex-region] or \\[tex-buffer].
873 tex-dvi-print-command
874 Command string used by \\[tex-print] to print a .dvi file.
875 tex-alt-dvi-print-command
876 Alternative command string used by \\[tex-print] (when given a prefix
877 argument) to print a .dvi file.
879 Command string used by \\[tex-view] to preview a .dvi file.
880 tex-show-queue-command
881 Command string used by \\[tex-show-print-queue] to show the print
882 queue that \\[tex-print] put your job on.
884 Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
885 `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
886 special subshell is initiated, the hook `tex-shell-hook' is run."
887 (set (make-local-variable 'tex-command) tex-run-command)
888 (set (make-local-variable 'tex-start-of-header) "%\\*\\*start of header")
889 (set (make-local-variable 'tex-end-of-header) "%\\*\\*end of header")
890 (set (make-local-variable 'tex-trailer) "\\bye\n"))
893 (define-derived-mode latex-mode tex-mode "LaTeX"
894 "Major mode for editing files of input for LaTeX.
895 Makes $ and } display the characters they match.
896 Makes \" insert `` when it seems to be the beginning of a quotation,
897 and '' when it appears to be the end; it inserts \" only after a \\.
899 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
900 copied from the top of the file (containing \\documentstyle, etc.),
901 running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
902 \\[tex-file] saves the buffer and then processes the file.
903 \\[tex-print] prints the .dvi file made by any of these.
904 \\[tex-view] previews the .dvi file made by any of these.
905 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
907 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
908 mismatched $'s or braces.
915 Command string used by \\[tex-region] or \\[tex-buffer].
917 Directory in which to create temporary files for LaTeX jobs
918 run by \\[tex-region] or \\[tex-buffer].
919 tex-dvi-print-command
920 Command string used by \\[tex-print] to print a .dvi file.
921 tex-alt-dvi-print-command
922 Alternative command string used by \\[tex-print] (when given a prefix
923 argument) to print a .dvi file.
925 Command string used by \\[tex-view] to preview a .dvi file.
926 tex-show-queue-command
927 Command string used by \\[tex-show-print-queue] to show the print
928 queue that \\[tex-print] put your job on.
930 Entering Latex mode runs the hook `text-mode-hook', then
931 `tex-mode-hook', and finally `latex-mode-hook'. When the special
932 subshell is initiated, `tex-shell-hook' is run."
933 (set (make-local-variable 'tex-command) latex-run-command)
934 (set (make-local-variable 'tex-start-of-header)
935 "\\\\document\\(style\\|class\\)")
936 (set (make-local-variable 'tex-end-of-header) "\\\\begin\\s-*{document}")
937 (set (make-local-variable 'tex-trailer) "\\end{document}\n")
938 ;; A line containing just $$ is treated as a paragraph separator.
939 ;; A line starting with $$ starts a paragraph,
940 ;; but does not separate paragraphs if it has more stuff on it.
941 (setq paragraph-start
942 (concat "[ \t]*\\(\\$\\$\\|"
944 "\\\\" (regexp-opt (append
945 (mapcar 'car latex-section-alist)
946 '("begin" "label" "end"
947 "item" "bibitem" "newline" "noindent"
948 "newpage" "footnote" "marginpar"
949 "parbox" "caption")) t)
950 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
952 (setq paragraph-separate
953 (concat "[\f%]\\|[ \t]*\\($\\|"
955 "\\\\" (regexp-opt (append
956 (mapcar 'car latex-section-alist)
957 '("begin" "label" "end" )) t)
958 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
959 "noindent" "newpage" "footnote"
960 "marginpar" "parbox" "caption"))
961 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
962 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
963 (set (make-local-variable 'imenu-create-index-function)
964 'latex-imenu-create-index)
965 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
966 (add-hook 'fill-nobreak-predicate 'latex-fill-nobreak-predicate nil t)
967 (set (make-local-variable 'indent-line-function) 'latex-indent)
968 (set (make-local-variable 'fill-indent-according-to-mode) t)
969 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
970 (set (make-local-variable 'outline-level) 'latex-outline-level)
971 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
972 (set (make-local-variable 'skeleton-end-hook) nil))
975 (define-derived-mode slitex-mode latex-mode "SliTeX"
976 "Major mode for editing files of input for SliTeX.
977 Makes $ and } display the characters they match.
978 Makes \" insert `` when it seems to be the beginning of a quotation,
979 and '' when it appears to be the end; it inserts \" only after a \\.
981 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
982 copied from the top of the file (containing \\documentstyle, etc.),
983 running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
984 \\[tex-file] saves the buffer and then processes the file.
985 \\[tex-print] prints the .dvi file made by any of these.
986 \\[tex-view] previews the .dvi file made by any of these.
987 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
989 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
990 mismatched $'s or braces.
997 Command string used by \\[tex-region] or \\[tex-buffer].
999 Directory in which to create temporary files for SliTeX jobs
1000 run by \\[tex-region] or \\[tex-buffer].
1001 tex-dvi-print-command
1002 Command string used by \\[tex-print] to print a .dvi file.
1003 tex-alt-dvi-print-command
1004 Alternative command string used by \\[tex-print] (when given a prefix
1005 argument) to print a .dvi file.
1006 tex-dvi-view-command
1007 Command string used by \\[tex-view] to preview a .dvi file.
1008 tex-show-queue-command
1009 Command string used by \\[tex-show-print-queue] to show the print
1010 queue that \\[tex-print] put your job on.
1012 Entering SliTeX mode runs the hook `text-mode-hook', then the hook
1013 `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
1014 `slitex-mode-hook'. When the special subshell is initiated, the hook
1015 `tex-shell-hook' is run."
1016 (setq tex-command slitex-run-command)
1017 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
1019 (defun tex-common-initialization ()
1020 ;; Regexp isearch should accept newline and formfeed as whitespace.
1021 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
1022 ;; A line containing just $$ is treated as a paragraph separator.
1023 (set (make-local-variable 'paragraph-start)
1024 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
1025 ;; A line starting with $$ starts a paragraph,
1026 ;; but does not separate paragraphs if it has more stuff on it.
1027 (set (make-local-variable 'paragraph-separate)
1028 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
1029 (set (make-local-variable 'comment-start) "%")
1030 (set (make-local-variable 'comment-add) 1)
1031 (set (make-local-variable 'comment-start-skip)
1032 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
1033 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1034 (set (make-local-variable 'compare-windows-whitespace)
1035 'tex-categorize-whitespace)
1036 (set (make-local-variable 'facemenu-add-face-function)
1038 (or (cdr (assq face tex-face-alist))
1039 (error "Face %s not configured for %s mode" face mode-name))))
1040 (set (make-local-variable 'facemenu-end-add-face) "}")
1041 (set (make-local-variable 'facemenu-remove-face-function) t)
1042 (set (make-local-variable 'font-lock-defaults)
1043 '((tex-font-lock-keywords tex-font-lock-keywords-1
1044 tex-font-lock-keywords-2 tex-font-lock-keywords-3)
1045 nil nil ((?$ . "\"")) nil
1046 ;; Who ever uses that anyway ???
1047 (font-lock-mark-block-function . mark-paragraph)
1048 (font-lock-syntactic-face-function
1049 . tex-font-lock-syntactic-face-function)
1050 (font-lock-unfontify-region-function
1051 . tex-font-lock-unfontify-region)
1052 (font-lock-syntactic-keywords
1053 . tex-font-lock-syntactic-keywords)
1054 (parse-sexp-lookup-properties . t)))
1055 ;; TABs in verbatim environments don't do what you think.
1056 (set (make-local-variable 'indent-tabs-mode) nil)
1057 ;; Other vars that should be buffer-local.
1058 (make-local-variable 'tex-command)
1059 (make-local-variable 'tex-start-of-header)
1060 (make-local-variable 'tex-end-of-header)
1061 (make-local-variable 'tex-trailer))
1063 (defun tex-categorize-whitespace (backward-limit)
1064 ;; compare-windows-whitespace is set to this.
1065 ;; This is basically a finite-state machine.
1066 ;; Returns a symbol telling how TeX would treat
1067 ;; the whitespace we are looking at: null, space, or par.
1068 (let ((category 'null)
1070 (skip-chars-backward " \t\n\f" backward-limit)
1072 (cond ((looking-at "[ \t]+")
1073 (goto-char (match-end 0))
1074 (if (eq category 'null)
1075 (setq category 'space)))
1077 (cond ((eq category 'newline)
1078 (setq category 'par)
1079 (setq not-finished nil))
1081 (setq category 'newline) ;a strictly internal state
1082 (goto-char (match-end 0)))))
1084 (setq category 'par)
1085 (setq not-finished nil))
1087 (setq not-finished nil))))
1088 (skip-chars-forward " \t\n\f")
1089 (if (eq category 'newline)
1090 'space ;TeX doesn't distinguish
1093 (defun tex-insert-quote (arg)
1094 "Insert the appropriate quote marks for TeX.
1095 Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
1096 \(normally '') depending on the context. With prefix argument, always
1097 inserts \" characters."
1099 (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
1100 (eq (get-text-property (point) 'face) 'tex-verbatim-face)
1102 (backward-char (length tex-open-quote))
1103 (when (or (looking-at (regexp-quote tex-open-quote))
1104 (looking-at (regexp-quote tex-close-quote)))
1105 (delete-char (length tex-open-quote))
1107 (self-insert-command (prefix-numeric-value arg))
1108 (insert (if (memq (char-syntax (preceding-char)) '(?\( ?> ?\ ))
1109 tex-open-quote tex-close-quote))))
1111 (defun tex-validate-buffer ()
1112 "Check current buffer for paragraphs containing mismatched braces or $s.
1113 Their positions are recorded in the buffer `*Occur*'.
1114 To find a particular invalidity from `*Occur*', switch to that buffer
1115 and type C-c C-c or click with mouse-2
1116 on the line for the invalidity you want to see."
1118 (let ((buffer (current-buffer))
1119 (prevpos (point-min))
1122 (with-output-to-temp-buffer "*Occur*"
1123 (princ "Mismatches:\n")
1124 (with-current-buffer standard-output
1126 ;; This won't actually work...Really, this whole thing should
1127 ;; be rewritten instead of being a hack on top of occur.
1128 (setq occur-revert-arguments (list nil 0 (list buffer))))
1130 (goto-char (point-max))
1131 (while (and (not (bobp)))
1134 ;; Scan the previous paragraph for invalidities.
1135 (if (search-backward "\n\n" nil t)
1137 (setq prev-end (point))
1139 (goto-char (setq prev-end (point-min))))
1140 (or (tex-validate-region (point) end)
1141 (let* ((end (line-beginning-position 2))
1144 (setq start (point))
1145 ;; Keep track of line number as we scan,
1146 ;; in a cumulative fashion.
1148 (setq linenum (- linenum (count-lines prevpos (point))))
1149 (setq linenum (1+ (count-lines 1 start))))
1150 (setq prevpos (point))
1151 ;; Mention this mismatch in *Occur*.
1152 ;; Since we scan from end of buffer to beginning,
1153 ;; add each mismatch at the beginning of *Occur*.
1155 (setq tem (point-marker))
1156 (set-buffer standard-output)
1157 (goto-char (point-min))
1158 ;; Skip "Mismatches:" header line.
1160 (setq num-matches (1+ num-matches))
1161 (insert-buffer-substring buffer start end)
1162 (let (text-beg (text-end (point-marker)))
1163 (forward-char (- start end))
1164 (setq text-beg (point-marker))
1165 (insert (format "%3d: " linenum))
1166 (add-text-properties
1167 text-beg (- text-end 1)
1168 '(mouse-face highlight
1169 help-echo "mouse-2: go to this invalidity"))
1170 (put-text-property text-beg (- text-end 1)
1171 'occur-target tem)))))
1172 (goto-char prev-end))))
1173 (with-current-buffer standard-output
1174 (let ((no-matches (zerop num-matches)))
1178 (message (cond (no-matches "No mismatches found")
1179 ((= num-matches 1) "1 mismatch found")
1180 (t "%d mismatches found"))
1183 (defun tex-validate-region (start end)
1184 "Check for mismatched braces or $'s in region.
1185 Returns t if no mismatches. Returns nil and moves point to suspect
1186 area if a mismatch is found."
1188 (let ((failure-point nil) (max-possible-sexps (- end start)))
1192 (narrow-to-region start end)
1193 ;; First check that the open and close parens balance in numbers.
1195 (while (<= 0 (setq max-possible-sexps (1- max-possible-sexps)))
1197 ;; Now check that like matches like.
1199 (while (re-search-forward "\\s(" nil t)
1201 (let ((pos (match-beginning 0)))
1204 (or (eq (preceding-char) (cdr (syntax-after pos)))
1205 (eq (char-after pos) (cdr (syntax-after (1- (point)))))
1206 (error "Mismatched parentheses"))))))
1208 (skip-syntax-forward " .>")
1209 (setq failure-point (point)))))
1210 (if failure-point (goto-char failure-point))
1211 (not failure-point)))
1213 (defun tex-terminate-paragraph (inhibit-validation)
1214 "Insert two newlines, breaking a paragraph for TeX.
1215 Check for mismatched braces or $s in paragraph being terminated.
1216 A prefix arg inhibits the checking."
1218 (or inhibit-validation
1220 (tex-validate-region
1222 (search-backward "\n\n" nil 'move)
1225 (message "Paragraph being closed appears to contain a mismatch"))
1228 (define-skeleton tex-insert-braces
1229 "Make a pair of braces and be poised to type inside of them."
1233 ;; This function is used as the value of fill-nobreak-predicate
1234 ;; in LaTeX mode. Its job is to prevent line-breaking inside
1235 ;; of a \verb construct.
1236 (defun latex-fill-nobreak-predicate ()
1238 (skip-chars-backward " ")
1239 ;; Don't break after \ since `\ ' has special meaning.
1240 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
1241 (let ((opoint (point))
1244 (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
1245 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
1249 (defvar latex-block-default "enumerate")
1251 (defvar latex-block-args-alist
1252 '(("array" nil ?\{ (skeleton-read "Format: ") ?\})
1253 ("tabular" nil ?\{ (skeleton-read "Format: ") ?\})
1254 ("minipage" nil ?\{ (skeleton-read "Size: ") ?\})
1255 ("picture" nil ?\( (skeleton-read "SizeX,SizeY: ") ?\))
1256 ;; FIXME: This is right for Prosper, but not for seminar.
1257 ;; ("slide" nil ?\{ (skeleton-read "Title: ") ?\})
1259 "Skeleton element to use for arguments to particular environments.
1260 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1261 the name of the environment and SKEL-ELEM is an element to use in
1262 a skeleton (see `skeleton-insert').")
1264 (defvar latex-block-body-alist
1265 '(("enumerate" nil '(latex-insert-item) > _)
1266 ("itemize" nil '(latex-insert-item) > _)
1267 ("table" nil "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1268 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))
1270 ("figure" nil > _ \n "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1271 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))))
1272 "Skeleton element to use for the body of particular environments.
1273 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1274 the name of the environment and SKEL-ELEM is an element to use in
1275 a skeleton (see `skeleton-insert').")
1277 ;; Like tex-insert-braces, but for LaTeX.
1278 (defalias 'tex-latex-block 'latex-insert-block)
1279 (define-skeleton latex-insert-block
1280 "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
1281 Puts point on a blank line between them."
1282 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1283 latex-block-default)
1284 (append latex-block-names
1285 latex-standard-block-names)
1286 nil nil nil nil latex-block-default)))
1287 (setq latex-block-default choice)
1288 (unless (or (member choice latex-standard-block-names)
1289 (member choice latex-block-names))
1290 ;; Remember new block names for later completion.
1291 (push choice latex-block-names))
1293 \n "\\begin{" str "}"
1294 (cdr (assoc str latex-block-args-alist))
1295 > \n (or (cdr (assoc str latex-block-body-alist)) '(nil > _))
1297 "\\end{" str "}" > \n)
1299 (define-skeleton latex-insert-item
1300 "Insert a \item macro."
1306 ;;;; LaTeX syntax navigation
1309 (defmacro tex-search-noncomment (&rest body)
1310 "Execute BODY as long as it return non-nil and point is in a comment.
1311 Return the value returned by the last execution of BODY."
1313 (let ((res-sym (make-symbol "result")))
1316 (and (setq ,res-sym (progn ,@body))
1317 (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
1320 (defun tex-last-unended-begin ()
1321 "Leave point at the beginning of the last `\\begin{...}' that is unended."
1323 (while (and (tex-search-noncomment
1324 (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
1325 (looking-at "\\\\end"))
1326 (tex-last-unended-begin))
1327 (search-failed (error "Couldn't find unended \\begin"))))
1329 (defun tex-next-unmatched-end ()
1330 "Leave point at the end of the next `\\end' that is unended."
1331 (while (and (tex-search-noncomment
1332 (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
1333 (save-excursion (goto-char (match-beginning 0))
1334 (looking-at "\\\\begin")))
1335 (tex-next-unmatched-end)))
1337 (defun tex-goto-last-unclosed-latex-block ()
1338 "Move point to the last unclosed \\begin{...}.
1339 Mark is left at original location."
1343 (tex-last-unended-begin)
1344 (setq spot (point)))
1348 (defun latex-backward-sexp-1 ()
1349 "Like (backward-sexp 1) but aware of multi-char elements."
1351 (forward-sexp-function))
1353 (if (looking-at "\\\\begin\\>")
1355 (list "Containing expression ends prematurely"
1356 (point) (prog1 (point) (goto-char pos))))
1357 (when (eq (char-after) ?{)
1358 (let ((newpos (point)))
1359 (when (ignore-errors (backward-sexp 1) t)
1360 (if (or (looking-at "\\\\end\\>")
1361 ;; In case the \\ ends a verbatim section.
1362 (and (looking-at "end\\>") (eq (char-before) ?\\)))
1363 (tex-last-unended-begin)
1364 (goto-char newpos))))))))
1366 (defun latex-forward-sexp-1 ()
1367 "Like (forward-sexp 1) but aware of multi-char elements."
1369 (forward-sexp-function))
1371 (let ((newpos (point)))
1372 (skip-syntax-backward "/w")
1374 ((looking-at "\\\\end\\>")
1376 (list "Containing expression ends prematurely"
1379 (progn (ignore-errors (forward-sexp 2)) (point))
1381 ((looking-at "\\\\begin\\>")
1382 (goto-char (match-end 0))
1383 (tex-next-unmatched-end))
1384 (t (goto-char newpos))))))
1386 (defun latex-forward-sexp (&optional arg)
1387 "Like `forward-sexp' but aware of multi-char elements."
1389 (unless arg (setq arg 1))
1390 (let ((pos (point)))
1395 (progn (latex-forward-sexp-1) (1- arg))
1396 (progn (latex-backward-sexp-1) (1+ arg)))))
1399 (signal (car err) (cdr err))))))
1401 (defun latex-syntax-after ()
1402 "Like (char-syntax (char-after)) but aware of multi-char elements."
1403 (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
1405 (defun latex-skip-close-parens ()
1406 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1407 (let ((forward-sexp-function nil))
1408 (while (progn (skip-syntax-forward " )")
1409 (looking-at "\\\\end\\>"))
1412 (defun latex-down-list ()
1413 "Like (down-list 1) but aware of multi-char elements."
1414 (forward-comment (point-max))
1415 (let ((forward-sexp-function nil))
1416 (if (not (looking-at "\\\\begin\\>"))
1420 (while (looking-at "[ \t]*[[{(]")
1421 (with-syntax-table tex-mode-syntax-table
1424 (defalias 'tex-close-latex-block 'latex-close-block)
1425 (define-skeleton latex-close-block
1426 "Create an \\end{...} to match the last unclosed \\begin{...}."
1428 (tex-last-unended-begin)
1429 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1431 \n "\\end" str > \n)
1433 (define-skeleton latex-split-block
1434 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1436 (tex-last-unended-begin)
1437 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1438 (prog1 (match-string 1)
1439 (goto-char (match-end 1))
1440 (setq v1 (buffer-substring (point)
1442 (while (looking-at "[ \t]*[[{]")
1445 \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
1447 (defconst tex-discount-args-cmds
1448 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1449 "documentclass" "usepackage" "label")
1450 "TeX commands whose arguments should not be counted as text.")
1452 (defun tex-count-words (begin end)
1453 "Count the number of words in the buffer."
1455 (if (and transient-mark-mode mark-active)
1456 (list (region-beginning) (region-end))
1457 (list (point-min) (point-max))))
1458 ;; TODO: skip comments and math and maybe some environments.
1462 (while (and (< (point) end) (re-search-forward "\\<" end t))
1463 (if (not (eq (char-syntax (preceding-char)) ?/))
1465 ;; Don't count single-char words.
1466 (unless (looking-at ".\\>") (incf count))
1469 (buffer-substring-no-properties
1470 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1473 (when (member cmd tex-discount-args-cmds)
1474 (skip-chars-forward "*")
1475 (forward-comment (point-max))
1476 (when (looking-at "\\[")
1478 (forward-comment (point-max)))
1479 (if (not (looking-at "{"))
1481 (forward-sexp 1))))))
1482 (message "%s words" count))))
1486 ;;; Invoking TeX in an inferior shell.
1488 ;; Why use a shell instead of running TeX directly? Because if TeX
1489 ;; gets stuck, the user can switch to the shell window and type at it.
1491 ;; The utility functions:
1493 (define-derived-mode tex-shell shell-mode "TeX-Shell"
1494 (set (make-local-variable 'compilation-parse-errors-function)
1495 'tex-compilation-parse-errors)
1496 (compilation-shell-minor-mode t))
1499 (defun tex-start-shell ()
1500 (with-current-buffer
1503 (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
1505 ;; Specify an interactive shell, to make sure it prompts.
1507 (let ((proc (get-process "tex-shell")))
1508 (set-process-sentinel proc 'tex-shell-sentinel)
1509 (set-process-query-on-exit-flag proc nil)
1511 (while (zerop (buffer-size))
1514 (defun tex-feed-input ()
1515 "Send input to the tex shell process.
1516 In the tex buffer this can be used to continue an interactive tex run.
1517 In the tex shell buffer this command behaves like `comint-send-input'."
1519 (set-buffer (tex-shell-buf))
1521 (tex-recenter-output-buffer nil))
1523 (defun tex-display-shell ()
1524 "Make the TeX shell buffer visible in a window."
1525 (display-buffer (tex-shell-buf))
1526 (tex-recenter-output-buffer nil))
1528 (defun tex-shell-sentinel (proc msg)
1529 (cond ((null (buffer-name (process-buffer proc)))
1531 (set-process-buffer proc nil)
1532 (tex-delete-last-temp-files))
1533 ((memq (process-status proc) '(signal exit))
1534 (tex-delete-last-temp-files))))
1536 (defun tex-set-buffer-directory (buffer directory)
1537 "Set BUFFER's default directory to be DIRECTORY."
1538 (setq directory (file-name-as-directory (expand-file-name directory)))
1539 (if (not (file-directory-p directory))
1540 (error "%s is not a directory" directory)
1543 (setq default-directory directory))))
1545 (defvar tex-send-command-modified-tick 0)
1546 (make-variable-buffer-local 'tex-send-command-modified-tick)
1548 (defun tex-shell-proc ()
1549 (or (tex-shell-running) (error "No TeX subprocess")))
1550 (defun tex-shell-buf ()
1551 (process-buffer (tex-shell-proc)))
1552 (defun tex-shell-buf-no-error ()
1553 (let ((proc (tex-shell-running)))
1554 (and proc (process-buffer proc))))
1556 (defun tex-send-command (command &optional file background)
1557 "Send COMMAND to TeX shell process, substituting optional FILE for *.
1558 Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1559 FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1560 substitution will be made in COMMAND. COMMAND can be any expression that
1561 evaluates to a command string.
1563 Return the process in which TeX is running."
1565 (let* ((cmd (eval command))
1566 (proc (tex-shell-proc))
1567 (buf (process-buffer proc))
1568 (star (string-match "\\*" cmd))
1572 (if star (concat (substring cmd 0 star)
1573 (shell-quote-argument file)
1574 (substring cmd (1+ star)))
1575 (concat cmd " " (shell-quote-argument file)))
1577 (if background "&" ""))))
1578 ;; Switch to buffer before checking for subproc output in it.
1580 ;; If text is unchanged since previous tex-send-command,
1581 ;; we haven't got any output. So wait for output now.
1582 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
1583 (accept-process-output proc))
1584 (goto-char (process-mark proc))
1587 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1590 (defun tex-delete-last-temp-files (&optional not-all)
1591 "Delete any junk files from last temp file.
1592 If NOT-ALL is non-nil, save the `.dvi' file."
1593 (if tex-last-temp-file
1594 (let* ((dir (file-name-directory tex-last-temp-file))
1595 (list (and (file-directory-p dir)
1596 (file-name-all-completions
1597 (file-name-sans-extension
1598 (file-name-nondirectory tex-last-temp-file))
1603 ;; If arg is non-nil, don't delete the .dvi file.
1604 (not (string-match "\\.dvi$" (car list)))
1605 (delete-file (concat dir (car list))))
1606 (delete-file (concat dir (car list))))
1607 (setq list (cdr list))))))
1609 (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
1612 ;; Machinery to guess the command that the user wants to execute.
1615 (defvar tex-compile-history nil)
1617 (defvar tex-input-files-re
1619 (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
1620 "bbl" "ind" "sty" "cls") t)
1621 ;; Include files with no dots (for directories).
1622 "\\'\\|\\`[^.]+\\'")))
1624 (defcustom tex-use-reftex t
1625 "If non-nil, use RefTeX's list of files to determine what command to use."
1628 (defvar tex-compile-commands
1629 '(((concat "pdf" tex-command
1630 " " (if (< 0 (length tex-start-commands))
1631 (shell-quote-argument tex-start-commands)) " %f")
1633 ((concat tex-command
1634 " " (if (< 0 (length tex-start-commands))
1635 (shell-quote-argument tex-start-commands)) " %f")
1637 ("yap %r &" "%r.dvi")
1638 ("xdvi %r &" "%r.dvi")
1639 ("advi %r &" "%r.dvi")
1640 ("bibtex %r" "%r.aux" "%r.bbl")
1641 ("makeindex %r" "%r.idx" "%r.ind")
1643 ("dvipdfm %r" "%r.dvi" "%r.pdf")
1644 ("dvipdf %r" "%r.dvi" "%r.pdf")
1645 ("dvips -o %r.ps %r" "%r.dvi" "%r.ps")
1646 ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
1647 ("gv %r.ps &" "%r.ps")
1648 ("gv %r.pdf &" "%r.pdf")
1649 ("xpdf %r.pdf &" "%r.pdf")
1650 ("lpr %r.ps" "%r.ps"))
1651 "List of commands for `tex-compile'.
1652 Each element should be of the form (FORMAT IN OUT) where
1653 FORMAT is an expression that evaluates to a string that can contain
1654 - `%r' the main file name without extension.
1655 - `%f' the main file name.
1656 IN can be either a string (with the same % escapes in it) indicating
1657 the name of the input file, or t to indicate that the input is all
1658 the TeX files of the document, or nil if we don't know.
1659 OUT describes the output file and is either a %-escaped string
1660 or nil to indicate that there is no output file.")
1662 ;; defsubst* gives better byte-code than defsubst.
1663 (defsubst* tex-string-prefix-p (str1 str2)
1664 "Return non-nil if STR1 is a prefix of STR2"
1665 (eq t (compare-strings str2 nil (length str1) str1 nil nil)))
1667 (defun tex-guess-main-file (&optional all)
1668 "Find a likely `tex-main-file'.
1669 Looks for hints in other buffers in the same directory or in
1670 ALL other buffers. If ALL is `sub' only look at buffers in parent directories
1671 of the current buffer."
1672 (let ((dir default-directory)
1673 (header-re tex-start-of-header))
1675 ;; Look for a buffer with `tex-main-file' set.
1676 (dolist (buf (if (consp all) all (buffer-list)))
1677 (with-current-buffer buf
1679 ((null all) (equal dir default-directory))
1680 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1682 (stringp tex-main-file))
1683 (throw 'found (expand-file-name tex-main-file)))))
1684 ;; Look for a buffer containing the magic `tex-start-of-header'.
1685 (dolist (buf (if (consp all) all (buffer-list)))
1686 (with-current-buffer buf
1688 ((null all) (equal dir default-directory))
1689 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1692 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1693 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1697 (goto-char (point-min))
1699 header-re (+ (point) 10000) t))))
1700 (throw 'found (expand-file-name buffer-file-name))))))))
1702 (defun tex-main-file ()
1703 "Return the relative name of the main file."
1704 (let* ((file (or tex-main-file
1705 ;; Compatibility with AUCTeX.
1707 (when (boundp 'TeX-master)
1708 (cond ((stringp TeX-master)
1709 (make-local-variable 'tex-main-file)
1710 (setq tex-main-file TeX-master))
1711 ((and (eq TeX-master t) buffer-file-name)
1712 (file-relative-name buffer-file-name)))))
1713 ;; Try to guess the main file.
1714 (if (not buffer-file-name)
1715 (error "Buffer is not associated with any file")
1718 (goto-char (point-min))
1719 (re-search-forward tex-start-of-header
1720 (+ (point) 10000) t))
1721 ;; This is the main file.
1723 ;; This isn't the main file, let's try to find better,
1724 (or (tex-guess-main-file)
1725 (tex-guess-main-file 'sub)
1726 ;; (tex-guess-main-file t)
1727 buffer-file-name)))))))
1728 (if (or (file-exists-p file) (string-match "\\.tex\\'" file))
1729 file (concat file ".tex"))))
1731 (defun tex-summarize-command (cmd)
1732 (if (not (stringp cmd)) ""
1733 (mapconcat 'identity
1734 (mapcar (lambda (s) (car (split-string s)))
1735 (split-string cmd "\\s-*\\(?:;\\|&&\\)\\s-*"))
1738 (defun tex-uptodate-p (file)
1739 "Return non-nil if FILE is not uptodate w.r.t the document source files.
1740 FILE is typically the output DVI or PDF file."
1741 ;; We should check all the files included !!!
1743 ;; Clearly, the target must exist.
1744 (file-exists-p file)
1745 ;; And the last run must not have asked for a rerun.
1746 ;; FIXME: this should check that the last run was done on the same file.
1747 (let ((buf (condition-case nil (tex-shell-buf) (error nil))))
1749 (with-current-buffer buf
1751 (goto-char (point-max))
1752 (and (re-search-backward
1753 "(see the transcript file for additional information)" nil t)
1755 (or (re-search-backward "\\[[0-9]+\\]" nil t)
1758 (or (re-search-backward "Rerun" nil t)
1760 ;; And the input files must not have been changed in the meantime.
1761 (let ((files (if (and tex-use-reftex
1762 (fboundp 'reftex-scanning-info-available-p)
1763 (reftex-scanning-info-available-p))
1764 (reftex-all-document-files)
1765 (list (file-name-directory (expand-file-name file)))))
1769 (delq nil (mapcar (lambda (s) (if (eq (aref s (1- (length s))) ?/)
1770 (substring s 0 (1- (length s)))))
1771 completion-ignored-extensions))
1774 (while (and files uptodate)
1775 (let ((f (pop files)))
1776 (if (and (file-directory-p f)
1777 ;; Avoid infinite loops.
1778 (not (file-symlink-p f)))
1779 (unless (string-match ignored-dirs-re f)
1781 (directory-files f t tex-input-files-re)
1783 (when (file-newer-than-file-p f file)
1784 (setq uptodate nil)))))
1788 (autoload 'format-spec "format-spec")
1790 (defvar tex-executable-cache nil)
1791 (defun tex-executable-exists-p (name)
1792 "Like `executable-find' but with a cache."
1793 (let ((cache (assoc name tex-executable-cache)))
1794 (if cache (cdr cache)
1795 (let ((executable (executable-find name)))
1796 (push (cons name executable) tex-executable-cache)
1799 (defun tex-command-executable (cmd)
1800 (let ((s (if (stringp cmd) cmd (eval (car cmd)))))
1801 (substring s 0 (string-match "[ \t]\\|\\'" s))))
1803 (defun tex-command-active-p (cmd fspec)
1804 "Return non-nil if the CMD spec might need to be run."
1805 (let ((in (nth 1 cmd))
1808 (let ((file (format-spec in fspec)))
1809 (when (file-exists-p file)
1811 (file-newer-than-file-p
1812 file (format-spec out fspec)))))
1813 (when (and (eq in t) (stringp out))
1814 (not (tex-uptodate-p (format-spec out fspec)))))))
1816 (defun tex-compile-default (fspec)
1817 "Guess a default command given the `format-spec' FSPEC."
1818 ;; TODO: Learn to do latex+dvips!
1821 ;; Only consider active commands.
1822 (dolist (cmd tex-compile-commands)
1823 (when (tex-executable-exists-p (tex-command-executable cmd))
1824 (if (tex-command-active-p cmd fspec)
1826 (push (nth 1 cmd) unchanged-in))))
1827 ;; If no command seems to be applicable, arbitrarily pick the first one.
1829 (setq cmds (list (car tex-compile-commands))))
1830 ;; Remove those commands whose input was considered stable for
1831 ;; some other command (typically if (t . "%.pdf") is inactive
1832 ;; then we're using pdflatex and the fact that the dvi file
1833 ;; is inexistent doesn't matter).
1836 (unless (member (nth 1 cmd) unchanged-in)
1838 ;; Only remove if there's something left.
1839 (if tmp (setq cmds tmp)))
1840 ;; Remove commands whose input is not uptodate either.
1841 (let ((outs (delq nil (mapcar (lambda (x) (nth 2 x)) cmds)))
1844 (unless (member (nth 1 cmd) outs)
1846 ;; Only remove if there's something left.
1847 (if tmp (setq cmds tmp)))
1848 ;; Select which file we're going to operate on (the latest).
1849 (let ((latest (nth 1 (car cmds))))
1850 (dolist (cmd (prog1 (cdr cmds) (setq cmds (list (car cmds)))))
1851 (if (equal latest (nth 1 cmd))
1853 (unless (eq latest t) ;Can't beat that!
1854 (if (or (not (stringp latest))
1856 (and (stringp (nth 1 cmd))
1857 (file-newer-than-file-p
1858 (format-spec (nth 1 cmd) fspec)
1859 (format-spec latest fspec))))
1860 (setq latest (nth 1 cmd) cmds (list cmd)))))))
1861 ;; Expand the command spec into the actual text.
1862 (dolist (cmd (prog1 cmds (setq cmds nil)))
1863 (push (cons (eval (car cmd)) (cdr cmd)) cmds))
1864 ;; Select the favorite command from the history.
1865 (let ((hist tex-compile-history)
1868 (setq hist-cmd (pop hist))
1869 (setq re (concat "\\`"
1870 (regexp-quote (tex-command-executable hist-cmd))
1871 "\\([ \t]\\|\\'\\)"))
1873 ;; If the hist entry uses the same command and applies to a file
1874 ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
1875 (and (string-match re (car cmd))
1876 (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd)))
1877 (string-match (regexp-quote (match-string 1 (car cmd)))
1879 (setq hist nil cmds (list cmd)))))
1880 ;; Substitute and return.
1882 (string-match (concat "[' \t\"]" (format-spec "%r" fspec)
1883 "\\([;&' \t\"]\\|\\'\\)") hist-cmd))
1884 ;; The history command was already applied to the same file,
1885 ;; so just reuse it.
1887 (if cmds (format-spec (caar cmds) fspec))))))
1889 (defun tex-compile (dir cmd)
1890 "Run a command CMD on current TeX buffer's file in DIR."
1891 ;; FIXME: Use time-stamps on files to decide the next op.
1893 (let* ((file (tex-main-file))
1895 (prog1 (file-name-directory (expand-file-name file))
1896 (setq file (file-name-nondirectory file))))
1897 (root (file-name-sans-extension file))
1898 (fspec (list (cons ?r (shell-quote-argument root))
1899 (cons ?f (shell-quote-argument file))))
1900 (default (tex-compile-default fspec)))
1901 (list default-directory
1903 (format "Command [%s]: " (tex-summarize-command default))
1905 (list (format-spec (eval (car x)) fspec)))
1906 tex-compile-commands)
1907 nil nil nil 'tex-compile-history default))))
1908 (save-some-buffers (not compilation-ask-about-save) nil)
1909 (if (tex-shell-running)
1912 (tex-send-tex-command cmd dir))
1914 (defun tex-start-tex (command file &optional dir)
1915 "Start a TeX run, using COMMAND on FILE."
1916 (let* ((star (string-match "\\*" command))
1919 (concat (substring command 0 star)
1920 (shell-quote-argument file)
1921 (substring command (1+ star)))
1924 (if (< 0 (length tex-start-commands))
1926 (shell-quote-argument tex-start-commands) " "))
1927 (shell-quote-argument file)))))
1928 (tex-send-tex-command compile-command dir)))
1930 (defun tex-send-tex-command (cmd &optional dir)
1931 (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
1932 (and buf (with-current-buffer buf
1933 default-directory))))
1935 (let (shell-dirtrack-verbose)
1936 (tex-send-command tex-shell-cd-command dir)))
1937 (with-current-buffer (process-buffer (tex-send-command cmd))
1938 (setq compilation-last-buffer (current-buffer))
1939 (compilation-forget-errors)
1940 ;; Don't parse previous compilations.
1941 (set-marker compilation-parsing-end (1- (point-max))))
1943 (setq tex-last-buffer-texed (current-buffer)))
1945 (defvar tex-error-parse-syntax-table
1946 (let ((st (make-syntax-table)))
1947 (modify-syntax-entry ?\( "()" st)
1948 (modify-syntax-entry ?\) ")(" st)
1949 (modify-syntax-entry ?\\ "\\" st)
1950 (modify-syntax-entry ?\{ "_" st)
1951 (modify-syntax-entry ?\} "_" st)
1952 (modify-syntax-entry ?\[ "_" st)
1953 (modify-syntax-entry ?\] "_" st)
1954 ;; Single quotations may appear in errors
1955 (modify-syntax-entry ?\" "_" st)
1957 "Syntax-table used while parsing TeX error messages.")
1959 (defun tex-compilation-parse-errors (limit-search find-at-least)
1960 "Parse the current buffer as TeX error messages.
1961 See the variable `compilation-parse-errors-function' for the interface it uses.
1963 This function parses only the last TeX compilation.
1964 It works on TeX compilations only. It is necessary for that purpose,
1965 since TeX does not put file names and line numbers on the same line as
1966 for the error messages."
1967 (require 'thingatpt)
1968 (setq compilation-error-list nil)
1969 (let ((default-directory ; Perhaps dir has changed meanwhile.
1970 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
1971 found-desired (num-errors-found 0)
1972 last-filename last-linenum last-position
1973 begin-of-error end-of-error)
1974 ;; Don't reparse messages already seen at last parse.
1975 (goto-char compilation-parsing-end)
1977 (while (and (not (or found-desired (eobp)))
1978 (prog1 (re-search-forward "^! " nil 'move)
1979 (setq begin-of-error (match-beginning 0)
1980 end-of-error (match-end 0)))
1982 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
1983 (let* ((this-error (copy-marker begin-of-error))
1984 (linenum (string-to-number (match-string 1)))
1985 (error-text (regexp-quote (match-string 3)))
1988 (with-syntax-table tex-error-parse-syntax-table
1989 (backward-up-list 1)
1990 (skip-syntax-forward "(_")
1991 (while (not (file-readable-p (thing-at-point 'filename)))
1992 (skip-syntax-backward "(_")
1993 (backward-up-list 1)
1994 (skip-syntax-forward "(_"))
1995 (thing-at-point 'filename))))
1997 (or (null last-filename)
1998 (not (string-equal last-filename filename))))
2000 (with-current-buffer
2001 (if (equal filename (concat tex-zap-file ".tex"))
2002 tex-last-buffer-texed
2003 (find-file-noselect filename))
2006 (progn (goto-line linenum) (setq last-position nil))
2007 (goto-char last-position)
2008 (forward-line (- linenum last-linenum)))
2009 ;; first try a forward search for the error text,
2010 ;; then a backward search limited by the last error.
2011 (let ((starting-point (point)))
2012 (or (re-search-forward error-text nil t)
2013 (re-search-backward error-text last-position t)
2014 (goto-char starting-point)))
2016 (goto-char this-error)
2017 (if (and compilation-error-list
2018 (or (and find-at-least
2019 (>= num-errors-found
2022 (>= end-of-error limit-search)))
2024 (setq found-desired t)
2025 (setq num-errors-found (1+ num-errors-found)
2026 last-filename filename
2027 last-linenum linenum
2028 last-position error-location
2029 compilation-error-list ; Add the new error
2030 (cons (cons this-error error-location)
2031 compilation-error-list))
2032 (goto-char end-of-error)))))
2033 (set-marker compilation-parsing-end (point))
2034 (setq compilation-error-list (nreverse compilation-error-list)))
2038 (defun tex-region (beg end)
2039 "Run TeX on the current region, via a temporary file.
2040 The file's name comes from the variable `tex-zap-file' and the
2041 variable `tex-directory' says where to put it.
2043 If the buffer has a header, the header is given to TeX before the
2044 region itself. The buffer's header is all lines between the strings
2045 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
2046 The header must start in the first 100 lines of the buffer.
2048 The value of `tex-trailer' is given to TeX as input after the region.
2050 The value of `tex-command' specifies the command to use to run TeX."
2052 (if (tex-shell-running)
2056 (setq tex-zap-file (tex-generate-zap-file-name)))
2057 ;; Temp file will be written and TeX will be run in zap-directory.
2058 ;; If the TEXINPUTS file has relative directories or if the region has
2059 ;; \input of files, this must be the same directory as the file for
2060 ;; TeX to access the correct inputs. That's why it's safest if
2061 ;; tex-directory is ".".
2062 (let* ((zap-directory
2063 (file-name-as-directory (expand-file-name tex-directory)))
2064 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
2066 ;; Don't delete temp files if we do the same buffer twice in a row.
2067 (or (eq (current-buffer) tex-last-buffer-texed)
2068 (tex-delete-last-temp-files t))
2069 ;; Write the new temp file.
2073 (goto-char (point-min))
2075 (let ((search-end (point))
2076 (default-directory zap-directory)
2078 (goto-char (point-min))
2080 ;; Maybe copy first line, such as `\input texinfo', to temp file.
2081 (and tex-first-line-header-regexp
2082 (looking-at tex-first-line-header-regexp)
2083 (write-region (point)
2084 (progn (forward-line 1)
2085 (setq already-output (point)))
2086 tex-out-file nil nil))
2088 ;; Write out the header, if there is one,
2089 ;; and any of the specified region which extends before it.
2090 ;; But don't repeat anything already written.
2091 (if (re-search-forward tex-start-of-header search-end t)
2094 (setq hbeg (point)) ;mark beginning of header
2095 (if (re-search-forward tex-end-of-header nil t)
2098 (setq hend (point)) ;mark end of header
2099 (write-region (max (min hbeg beg) already-output)
2102 (not (zerop already-output)) nil)
2103 (setq already-output hend)))))
2105 ;; Write out the specified region
2106 ;; (but don't repeat anything already written).
2107 (write-region (max beg already-output) end
2109 (not (zerop already-output)) nil))
2110 ;; Write the trailer, if any.
2111 ;; Precede it with a newline to make sure it
2112 ;; is not hidden in a comment.
2114 (write-region (concat "\n" tex-trailer) nil
2115 tex-out-file t nil))))
2116 ;; Record the file name to be deleted afterward.
2117 (setq tex-last-temp-file tex-out-file)
2118 ;; Use a relative file name here because (1) the proper dir
2119 ;; is already current, and (2) the abs file name is sometimes
2120 ;; too long and can make tex crash.
2121 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
2122 (setq tex-print-file tex-out-file)))
2124 (defun tex-buffer ()
2125 "Run TeX on current buffer. See \\[tex-region] for more information.
2126 Does not save the buffer, so it's useful for trying experimental versions.
2127 See \\[tex-file] for an alternative."
2129 (tex-region (point-min) (point-max)))
2132 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
2133 This function is more useful than \\[tex-buffer] when you need the
2134 `.aux' file of LaTeX to have the correct name."
2136 (when tex-offer-save
2137 (save-some-buffers))
2138 (let* ((source-file (tex-main-file))
2139 (file-dir (file-name-directory (expand-file-name source-file))))
2140 (if (tex-shell-running)
2143 (tex-start-tex tex-command source-file file-dir)
2144 (setq tex-print-file (expand-file-name source-file))))
2146 (defun tex-generate-zap-file-name ()
2147 "Generate a unique name suitable for use as a file name."
2148 ;; Include the shell process number and host name
2149 ;; in case there are multiple shells (for same or different user).
2150 ;; Dec 1998: There is a report that some versions of xdvi
2151 ;; don't work with file names that start with #.
2153 (process-id (get-buffer-process "*tex-shell*"))
2154 (subst-char-in-string ?. ?- (system-name))))
2156 ;; This will perhaps be useful for modifying TEXINPUTS.
2157 ;; Expand each file name, separated by colons, in the string S.
2158 (defun tex-expand-files (s)
2159 (let (elts (start 0))
2160 (while (string-match ":" s start)
2161 (setq elts (cons (substring s start (match-beginning 0)) elts))
2162 (setq start (match-end 0)))
2164 (setq elts (cons (substring s start) elts)))
2165 (mapconcat (lambda (elt)
2166 (if (= (length elt) 0) elt (expand-file-name elt)))
2167 (nreverse elts) ":")))
2169 (defun tex-shell-running ()
2170 (let ((proc (get-process "tex-shell")))
2172 (if (and (eq (process-status proc) 'run)
2173 (buffer-live-p (process-buffer proc)))
2174 ;; return the TeX process on success
2176 ;; get rid of the process permanently
2177 ;; this should get rid of the annoying w32 problem with
2178 ;; dead tex-shell buffer and live process
2179 (delete-process proc)))))
2181 (defun tex-kill-job ()
2182 "Kill the currently running TeX job."
2184 ;; `quit-process' leads to core dumps of the tex process (except if
2185 ;; coredumpsize has limit 0kb as on many environments). One would
2186 ;; like to use (kill-process proc 'lambda), however that construct
2187 ;; does not work on some systems and kills the shell itself.
2188 (let ((proc (get-process "tex-shell")))
2189 (when proc (quit-process proc t))))
2191 (defun tex-recenter-output-buffer (linenum)
2192 "Redisplay buffer of TeX job output so that most recent output can be seen.
2193 The last line of the buffer is displayed on
2194 line LINE of the window, or centered if LINE is nil."
2196 (let ((tex-shell (get-buffer "*tex-shell*"))
2198 (if (null tex-shell)
2199 (message "No TeX output buffer")
2200 (setq window (display-buffer tex-shell))
2201 (save-selected-window
2202 (select-window window)
2203 (bury-buffer tex-shell)
2204 (goto-char (point-max))
2205 (recenter (if linenum
2206 (prefix-numeric-value linenum)
2207 (/ (window-height) 2)))))))
2209 (defun tex-print (&optional alt)
2210 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2211 Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
2212 is provided, use the alternative command, `tex-alt-dvi-print-command'."
2214 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
2216 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
2218 ;; Check that this buffer's printed file is up to date.
2219 (file-newer-than-file-p
2220 (setq test-name (tex-append (buffer-file-name) ".dvi"))
2221 (buffer-file-name)))
2222 (setq print-file-name-dvi test-name))
2223 (if (not (file-exists-p print-file-name-dvi))
2224 (error "No appropriate `.dvi' file could be found")
2225 (if (tex-shell-running)
2229 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
2230 (shell-quote-argument
2231 print-file-name-dvi)
2234 (defun tex-alt-print ()
2235 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2236 Runs the shell command defined by `tex-alt-dvi-print-command'."
2241 "Preview the last `.dvi' file made by running TeX under Emacs.
2242 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2243 The variable `tex-dvi-view-command' specifies the shell command for preview.
2244 You must set that variable yourself before using this command,
2245 because there is no standard value that would generally work."
2247 (or tex-dvi-view-command
2248 (error "You must set `tex-dvi-view-command'"))
2249 ;; Restart the TeX shell if necessary.
2250 (or (tex-shell-running)
2252 (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
2255 (defun tex-append (file-name suffix)
2256 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
2257 Pascal-based TeX scans for the first period, C TeX uses the last.
2258 No period is retained immediately before SUFFIX,
2259 so normally SUFFIX starts with one."
2260 (if (stringp file-name)
2261 (let ((file (file-name-nondirectory file-name))
2263 ;; Try splitting on last period.
2264 ;; The first-period split can get fooled when two files
2265 ;; named a.tex and a.b.tex are both tex'd;
2266 ;; the last-period split must be right if it matches at all.
2268 (concat (file-name-directory file-name)
2270 (string-match "\\.[^.]*$" file))
2272 (if (or (file-exists-p trial-name)
2273 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
2275 ;; Not found, so split on first period.
2276 (concat (file-name-directory file-name)
2278 (string-match "\\." file))
2282 (defun tex-show-print-queue ()
2283 "Show the print queue that \\[tex-print] put your job on.
2284 Runs the shell command defined by `tex-show-queue-command'."
2286 (if (tex-shell-running)
2289 (tex-send-command tex-show-queue-command)
2290 (tex-display-shell))
2292 (defun tex-bibtex-file ()
2293 "Run BibTeX on the current buffer's file."
2295 (if (tex-shell-running)
2298 (let (shell-dirtrack-verbose
2300 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
2301 (file-dir (file-name-directory (buffer-file-name))))
2302 (tex-send-command tex-shell-cd-command file-dir)
2303 (tex-send-command tex-bibtex-command tex-out-file))
2304 (tex-display-shell))
2307 ;;;; LaTeX indentation
2310 (defvar tex-indent-allhanging t)
2311 (defvar tex-indent-arg 4)
2312 (defvar tex-indent-basic 2)
2313 (defvar tex-indent-item tex-indent-basic)
2314 (defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
2315 (defvar latex-noindent-environments '("document"))
2317 (defvar tex-latex-indent-syntax-table
2318 (let ((st (make-syntax-table tex-mode-syntax-table)))
2319 (modify-syntax-entry ?$ "." st)
2320 (modify-syntax-entry ?\( "." st)
2321 (modify-syntax-entry ?\) "." st)
2323 "Syntax table used while computing indentation.")
2325 (defun latex-indent (&optional arg)
2326 (if (and (eq (get-text-property (line-beginning-position) 'face)
2329 (with-syntax-table tex-latex-indent-syntax-table
2330 ;; TODO: Rather than ignore $, we should try to be more clever about it.
2334 (latex-find-indent))))
2335 (if (< indent 0) (setq indent 0))
2336 (if (<= (current-column) (current-indentation))
2337 (indent-line-to indent)
2338 (save-excursion (indent-line-to indent)))))))
2340 (defun latex-find-indent (&optional virtual)
2341 "Find the proper indentation of text after point.
2342 VIRTUAL if non-nil indicates that we're only trying to find the indentation
2343 in order to determine the indentation of something else.
2344 There might be text before point."
2346 (skip-chars-forward " \t")
2348 ;; Stick the first line at column 0.
2349 (and (= (point-min) (line-beginning-position)) 0)
2350 ;; Trust the current indentation, if such info is applicable.
2351 (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
2353 ;; Stick verbatim environments to the left margin.
2354 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2355 (member (match-string 2) tex-verbatim-environments)
2357 ;; Put leading close-paren where the matching open brace would be.
2358 (and (eq (latex-syntax-after) ?\))
2361 (latex-skip-close-parens)
2362 (latex-backward-sexp-1)
2363 (latex-find-indent 'virtual))))
2364 ;; Default (maybe an argument)
2366 ;; Outdent \item if necessary.
2367 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
2369 ;; Find the previous point which determines our current indentation.
2372 (latex-backward-sexp-1)
2373 (while (> (current-column) (current-indentation))
2374 (latex-backward-sexp-1)))
2376 (setq up-list-pos (nth 2 err))))
2378 ((= (point-min) pos) 0) ; We're really just indenting the first line.
2379 ((integerp up-list-pos)
2380 ;; Have to indent relative to the open-paren.
2381 (goto-char up-list-pos)
2382 (if (and (not tex-indent-allhanging)
2384 ;; Make sure we're an argument to a macro and
2385 ;; that the macro is at the beginning of a line.
2388 (while (eq (char-syntax (char-after)) ?\()
2390 (and (eq (char-syntax (char-after)) ?/)
2391 (progn (skip-chars-backward " \t&")
2394 (> pos (progn (latex-down-list)
2395 (forward-comment (point-max))
2397 ;; Align with the first element after the open-paren.
2399 ;; We're the first element after a hanging brace.
2400 (goto-char up-list-pos)
2401 (+ (if (and (looking-at "\\\\begin *{\\([^\n}]+\\)")
2402 (member (match-string 1)
2403 latex-noindent-environments))
2405 indent (latex-find-indent 'virtual))))
2406 ;; We're now at the "beginning" of a line.
2407 ((not (and (not virtual) (eq (char-after) ?\\)))
2408 ;; Nothing particular here: just keep the same indentation.
2409 (+ indent (current-column)))
2410 ;; We're now looking at a macro call.
2411 ((looking-at tex-indent-item-re)
2412 ;; Indenting relative to an item, have to re-add the outdenting.
2413 (+ indent (current-column) tex-indent-item))
2415 (let ((col (current-column)))
2416 (if (or (not (eq (char-syntax (or (char-after pos) ?\ )) ?\())
2417 ;; Can't be an arg if there's an empty line inbetween.
2418 (save-excursion (re-search-forward "^[ \t]*$" pos t)))
2419 ;; If the first char was not an open-paren, there's
2420 ;; a risk that this is really not an argument to the
2424 (if (< (line-end-position)
2425 (save-excursion (forward-comment (point-max))
2427 ;; we're indenting the first argument.
2428 (min (current-column) (+ tex-indent-arg col))
2429 (skip-syntax-forward " ")
2430 (current-column))))))))))
2433 (defun doctex-font-lock-^^A ()
2434 (if (eq (char-after (line-beginning-position)) ?\%)
2437 (1- (match-beginning 1)) (match-beginning 1)
2439 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2440 ;; The `%' is a single-char comment, which Emacs
2441 ;; syntax-table can't deal with. We could turn it
2442 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2443 ;; Instead, we include it in the ^^A comment.
2444 (eval-when-compile (string-to-syntax "< b"))
2445 (eval-when-compile (string-to-syntax ">"))))
2446 (let ((end (line-end-position)))
2447 (if (< end (point-max))
2451 (eval-when-compile (string-to-syntax "> b")))))
2452 (eval-when-compile (string-to-syntax "< b")))))
2454 (defun doctex-font-lock-syntactic-face-function (state)
2455 ;; Mark DocTeX documentation, which is parsed as a style A comment
2456 ;; starting in column 0.
2457 (if (or (nth 3 state) (nth 7 state)
2458 (not (memq (char-before (nth 8 state))
2460 ;; Anything else is just as for LaTeX.
2461 (tex-font-lock-syntactic-face-function state)
2462 font-lock-doc-face))
2464 (defvar doctex-font-lock-syntactic-keywords
2466 tex-font-lock-syntactic-keywords
2467 ;; For DocTeX comment-in-doc.
2468 `(("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A))))))
2470 (defvar doctex-font-lock-keywords
2471 (append tex-font-lock-keywords
2472 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t)))))
2475 (define-derived-mode doctex-mode latex-mode "DocTeX"
2476 "Major mode to edit DocTeX files."
2477 (setq font-lock-defaults
2478 (cons (append (car font-lock-defaults) '(doctex-font-lock-keywords))
2482 (font-lock-syntactic-keywords
2483 (cons (car x) 'doctex-font-lock-syntactic-keywords))
2484 (font-lock-syntactic-face-function
2485 (cons (car x) 'doctex-font-lock-syntactic-face-function))
2487 (cdr font-lock-defaults)))))
2489 (run-hooks 'tex-mode-load-hook)
2493 ;; arch-tag: c0a680b1-63aa-4547-84b9-4193c29c0080
2494 ;;; tex-mode.el ends here