1 ;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands -*- coding: utf-8 -*-
3 ;; Copyright (C) 1985, 1986, 1989, 1992, 1994, 1995, 1996, 1997, 1998
4 ;; 1999, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 ;; Free Software Foundation, Inc.
10 ;; Contributions over the years by William F. Schelter, Dick King,
11 ;; Stephen Gildea, Michael Prange, Jacob Gore, and Edward M. Reingold.
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation, either version 3 of the License, or
18 ;; (at your option) any later version.
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
32 ;; Pacify the byte-compiler
38 (defvar font-lock-comment-face
)
39 (defvar font-lock-doc-face
)
44 (defgroup tex-file nil
45 "TeX files and directories."
50 "Running external commands from TeX mode."
54 (defgroup tex-view nil
55 "Viewing and printing TeX files."
60 (defcustom tex-shell-file-name nil
61 "If non-nil, the shell file name to run in the subshell used to run TeX."
62 :type
'(choice (const :tag
"None" nil
)
67 (defcustom tex-directory
(purecopy ".")
68 "Directory in which temporary files are written.
69 You can make this `/tmp' if your TEXINPUTS has no relative directories in it
70 and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
71 `\\input' commands with relative directories."
76 (defcustom tex-first-line-header-regexp nil
77 "Regexp for matching a first line which `tex-region' should include.
78 If this is non-nil, it should be a regular expression string;
79 if it matches the first line of the file,
80 `tex-region' always includes the first line in the TeX run."
81 :type
'(choice (const :tag
"None" nil
)
86 (defcustom tex-main-file nil
87 "The main TeX source file which includes this buffer's file.
88 The command `tex-file' runs TeX on the file specified by `tex-main-file'
89 if the variable is non-nil."
90 :type
'(choice (const :tag
"None" nil
)
95 (defcustom tex-offer-save t
96 "If non-nil, ask about saving modified buffers before \\[tex-file] is run."
101 (defcustom tex-run-command
(purecopy "tex")
102 "Command used to run TeX subjob.
103 TeX Mode sets `tex-command' to this string.
104 See the documentation of that variable."
109 (defcustom latex-run-command
(purecopy "latex")
110 "Command used to run LaTeX subjob.
111 LaTeX Mode sets `tex-command' to this string.
112 See the documentation of that variable."
117 (defcustom slitex-run-command
(purecopy "slitex")
118 "Command used to run SliTeX subjob.
119 SliTeX Mode sets `tex-command' to this string.
120 See the documentation of that variable."
125 (defcustom tex-start-options
(purecopy "")
126 "TeX options to use when starting TeX.
127 These immediately precede the commands in `tex-start-commands'
128 and the input file name, with no separating space and are not shell-quoted.
129 If nil, TeX runs with no options. See the documentation of `tex-command'."
135 (defcustom tex-start-commands
(purecopy "\\nonstopmode\\input")
136 "TeX commands to use when starting TeX.
137 They are shell-quoted and precede the input file name, with a separating space.
138 If nil, no commands are used. See the documentation of `tex-command'."
139 :type
'(radio (const :tag
"Interactive \(nil\)" nil
)
140 (const :tag
"Nonstop \(\"\\nonstopmode\\input\"\)"
141 "\\nonstopmode\\input")
142 (string :tag
"String at your choice"))
146 (defvar latex-standard-block-names
147 '("abstract" "array" "center" "description"
148 "displaymath" "document" "enumerate" "eqnarray"
149 "eqnarray*" "equation" "figure" "figure*"
150 "flushleft" "flushright" "itemize" "letter"
151 "list" "minipage" "picture" "quotation"
152 "quote" "slide" "sloppypar" "tabbing"
153 "table" "table*" "tabular" "tabular*"
154 "thebibliography" "theindex*" "titlepage" "trivlist"
155 "verbatim" "verbatim*" "verse" "math")
156 "Standard LaTeX block names.")
159 (defcustom latex-block-names nil
160 "User defined LaTeX block names.
161 Combined with `latex-standard-block-names' for minibuffer completion."
162 :type
'(repeat string
)
166 (defcustom tex-bibtex-command
(purecopy "bibtex")
167 "Command used by `tex-bibtex-file' to gather bibliographic data.
168 If this string contains an asterisk (`*'), that is replaced by the file name;
169 otherwise, the file name, preceded by blank, is added at the end."
174 (defcustom tex-dvi-print-command
(purecopy "lpr -d")
175 "Command used by \\[tex-print] to print a .dvi file.
176 If this string contains an asterisk (`*'), that is replaced by the file name;
177 otherwise, the file name, preceded by blank, is added at the end."
182 (defcustom tex-alt-dvi-print-command
(purecopy "lpr -d")
183 "Command used by \\[tex-print] with a prefix arg to print a .dvi file.
184 If this string contains an asterisk (`*'), that is replaced by the file name;
185 otherwise, the file name, preceded by blank, is added at the end.
187 If two printers are not enough of a choice, you can set the variable
188 `tex-alt-dvi-print-command' to an expression that asks what you want;
191 (setq tex-alt-dvi-print-command
192 '(format \"lpr -P%s\" (read-string \"Use printer: \")))
194 would tell \\[tex-print] with a prefix argument to ask you which printer to
196 :type
'(choice (string :tag
"Command")
197 (sexp :tag
"Expression"))
201 (defcustom tex-dvi-view-command
203 ((eq window-system
'x
) ,(purecopy "xdvi"))
204 ((eq window-system
'w32
) ,(purecopy "yap"))
205 (t ,(purecopy "dvi2tty * | cat -s")))
206 "Command used by \\[tex-view] to display a `.dvi' file.
207 If it is a string, that specifies the command directly.
208 If this string contains an asterisk (`*'), that is replaced by the file name;
209 otherwise, the file name, preceded by a space, is added at the end.
211 If the value is a form, it is evaluated to get the command to use."
212 :type
'(choice (const nil
) string sexp
)
216 (defcustom tex-show-queue-command
(purecopy "lpq")
217 "Command used by \\[tex-show-print-queue] to show the print queue.
218 Should show the queue(s) that \\[tex-print] puts jobs on."
223 (defcustom tex-default-mode
'latex-mode
224 "Mode to enter for a new file that might be either TeX or LaTeX.
225 This variable is used when it can't be determined whether the file
226 is plain TeX or LaTeX or what because the file contains no commands.
227 Normally set to either `plain-tex-mode' or `latex-mode'."
232 (defcustom tex-open-quote
(purecopy "``")
233 "String inserted by typing \\[tex-insert-quote] to open a quotation."
235 :options
'("``" "\"<" "\"`" "<<" "«")
239 (defcustom tex-close-quote
(purecopy "''")
240 "String inserted by typing \\[tex-insert-quote] to close a quotation."
242 :options
'("''" "\">" "\"'" ">>" "»")
245 (defcustom tex-fontify-script t
246 "If non-nil, fontify subscript and superscript strings."
250 (put 'tex-fontify-script
'safe-local-variable
'booleanp
)
252 (defcustom tex-font-script-display
'(-0.2
0.2)
253 "How much to lower and raise subscript and superscript content.
254 This is a list of two floats. The first is negative and
255 specifies how much subscript is lowered, the second is positive
256 and specifies how much superscript is raised. Heights are
257 measured relative to that of the normal text."
259 :type
'(list (float :tag
"Subscript")
260 (float :tag
"Superscript"))
263 (defvar tex-last-temp-file nil
264 "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
265 Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
266 tex shell terminates.")
268 (defvar tex-command
"tex"
269 "*Command to run TeX.
270 If this string contains an asterisk \(`*'\), that is replaced by the file name;
271 otherwise the value of `tex-start-options', the \(shell-quoted\)
272 value of `tex-start-commands', and the file name are added at the end
273 with blanks as separators.
275 In TeX, LaTeX, and SliTeX Mode this variable becomes buffer local.
276 In these modes, use \\[set-variable] if you want to change it for the
279 (defvar tex-trailer nil
280 "String appended after the end of a region sent to TeX by \\[tex-region].")
282 (defvar tex-start-of-header nil
283 "Regular expression used by \\[tex-region] to find start of file's header.")
285 (defvar tex-end-of-header nil
286 "Regular expression used by \\[tex-region] to find end of file's header.")
288 (defvar tex-shell-cd-command
"cd"
289 "Command to give to shell running TeX to change directory.
290 The value of `tex-directory' is appended to this, separated by a space.")
292 (defvar tex-zap-file nil
293 "Temporary file name used for text being sent as input to TeX.
294 Should be a simple file name with no extension or directory specification.")
296 (defvar tex-last-buffer-texed nil
297 "Buffer which was last TeXed.")
299 (defvar tex-print-file nil
300 "File name that \\[tex-print] prints.
301 Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
303 (defvar tex-mode-syntax-table
304 (let ((st (make-syntax-table)))
305 (modify-syntax-entry ?%
"<" st
)
306 (modify-syntax-entry ?
\n ">" st
)
307 (modify-syntax-entry ?
\f ">" st
)
308 (modify-syntax-entry ?\C-
@ "w" st
)
309 (modify-syntax-entry ?
' "w" st
)
310 (modify-syntax-entry ?
@ "_" st
)
311 (modify-syntax-entry ?
* "_" st
)
312 (modify-syntax-entry ?
\t " " st
)
313 ;; ~ is printed by TeX as a space, but it's semantics in the syntax
314 ;; of TeX is not `whitespace' (i.e. it's just like \hspace{foo}).
315 (modify-syntax-entry ?~
"." st
)
316 (modify-syntax-entry ?$
"$$" st
)
317 (modify-syntax-entry ?
\\ "/" st
)
318 (modify-syntax-entry ?
\" "." st
)
319 (modify-syntax-entry ?
& "." st
)
320 (modify-syntax-entry ?_
"." st
)
321 (modify-syntax-entry ?^
"." st
)
323 "Syntax table used while in TeX mode.")
329 (defcustom latex-imenu-indent-string
". "
330 "String to add repeated in front of nested sectional units for Imenu.
331 An alternative value is \" . \", if you use a font with a narrow period."
335 (defvar latex-section-alist
336 '(("part" .
0) ("chapter" .
1)
337 ("section" .
2) ("subsection" .
3)
338 ("subsubsection" .
4)
339 ("paragraph" .
5) ("subparagraph" .
6)))
341 (defvar latex-metasection-list
342 '("documentstyle" "documentclass"
343 "begin{document}" "end{document}"
344 "appendix" "frontmatter" "mainmatter" "backmatter"))
346 (defun latex-imenu-create-index ()
347 "Generate an alist for imenu from a LaTeX buffer."
348 (let ((section-regexp
349 (concat "\\\\" (regexp-opt (mapcar 'car latex-section-alist
) t
)
352 (concat "\\\\" (regexp-opt latex-metasection-list t
)))
353 i0 menu case-fold-search
)
355 ;; Find the top-most level in this file but don't allow it to be
356 ;; any deeper than "section" (which is top-level in an article).
357 (goto-char (point-min))
358 (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t
)
360 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t
)
364 ;; Look for chapters and sections.
365 (goto-char (point-min))
366 (while (search-forward-regexp section-regexp nil t
)
367 (let ((start (match-beginning 0))
369 (i (cdr (assoc (buffer-substring-no-properties
372 latex-section-alist
))))
376 ;; Using sexps allows some use of matching {...} inside
379 (push (cons (concat (apply 'concat
382 latex-imenu-indent-string
))
383 (buffer-substring-no-properties
389 ;; Look for included material.
390 (goto-char (point-min))
391 (while (search-forward-regexp
392 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
393 \[ \t]*{\\([^}\n]+\\)}"
395 (push (cons (concat "<<" (buffer-substring-no-properties
398 (if (= (char-after (match-beginning 1)) ?b
)
404 ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
405 (goto-char (point-min))
406 (while (search-forward-regexp metasection-regexp nil t
)
407 (push (cons "--" (match-beginning 0)) menu
))
409 ;; Sort in increasing buffer position order.
410 (sort menu
(function (lambda (a b
) (< (cdr a
) (cdr b
))))))))
416 (defvar latex-outline-regexp
418 (regexp-opt (append latex-metasection-list
419 (mapcar 'car latex-section-alist
)) t
)))
421 (defun latex-outline-level ()
422 (if (looking-at latex-outline-regexp
)
423 (1+ (or (cdr (assoc (match-string 1) latex-section-alist
)) -
1))
427 ;;;; Font-Lock support
430 ;(defvar tex-font-lock-keywords
431 ; ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
432 ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
433 ; 2 font-lock-function-name-face)
434 ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
435 ; 2 font-lock-constant-face)
436 ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
437 ; ;; not be able to display those fonts.
438 ; ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
439 ; ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
440 ; ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
441 ; ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
442 ; ;; Rewritten and extended for LaTeX2e by Ulrik Dickow <dickow@nbi.dk>.
443 ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
444 ; 2 font-lock-function-name-face)
445 ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
446 ; 2 font-lock-constant-face)
447 ; ("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)" 1 font-lock-function-name-face)
448 ; "\\\\\\([a-zA-Z@]+\\|.\\)"
449 ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
450 ; ;; not be able to display those fonts.
451 ; ;; LaTeX2e: \emph{This is emphasized}.
452 ; ("\\\\emph{\\([^}]+\\)}" 1 'italic keep)
453 ; ;; LaTeX2e: \textbf{This is bold}, \textit{...}, \textsl{...}
454 ; ("\\\\text\\(\\(bf\\)\\|it\\|sl\\){\\([^}]+\\)}"
455 ; 3 (if (match-beginning 2) 'bold 'italic) keep)
456 ; ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
457 ; ("\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)"
458 ; 3 (if (match-beginning 2) 'bold 'italic) keep))
460 ;; Rewritten with the help of Alexandra Bac <abac@welcome.disi.unige.it>.
461 (defconst tex-font-lock-keywords-1
463 (let* (;; Names of commands whose arg should be fontified as heading, etc.
464 (headings (regexp-opt
465 '("title" "begin" "end" "chapter" "part"
466 "section" "subsection" "subsubsection"
467 "paragraph" "subparagraph" "subsubparagraph"
468 "newcommand" "renewcommand" "providecommand"
469 "newenvironment" "renewenvironment"
470 "newtheorem" "renewtheorem")
472 (variables (regexp-opt
473 '("newcounter" "newcounter*" "setcounter" "addtocounter"
474 "setlength" "addtolength" "settowidth")
476 (includes (regexp-opt
477 '("input" "include" "includeonly" "bibliography"
478 "epsfig" "psfig" "epsf" "nofiles" "usepackage"
479 "documentstyle" "documentclass" "verbatiminput"
480 "includegraphics" "includegraphics*"
485 (opt " *\\(\\[[^]]*\\] *\\)*")
486 ;; This would allow highlighting \newcommand\CMD but requires
487 ;; adapting subgroup numbers below.
488 ;; (arg "\\(?:{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)\\|\\\\[a-z*]+\\)"))
489 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
491 ;; display $$ math $$
492 ;; We only mark the match between $$ and $$ because the $$ delimiters
493 ;; themselves have already been marked (along with $..$) by syntactic
494 ;; fontification. Also this is done at the very beginning so as to
495 ;; interact with the other keywords in the same way as $...$ does.
496 (list "\\$\\$\\([^$]+\\)\\$\\$" 1 'tex-math-face
)
498 (list (concat slash headings
"\\*?" opt arg
)
499 ;; If ARG ends up matching too much (if the {} don't match, e.g.)
500 ;; jit-lock will do funny things: when updating the buffer
501 ;; the re-highlighting is only done locally so it will just
502 ;; match the local line, but defer-contextually will
503 ;; match more lines at a time, so ARG will end up matching
504 ;; a lot more, which might suddenly include a comment
505 ;; so you get things highlighted bold when you type them
506 ;; but they get turned back to normal a little while later
507 ;; because "there's already a face there".
508 ;; Using `keep' works around this un-intuitive behavior as well
509 ;; as improves the behavior in the very rare case where you do
510 ;; have a comment in ARG.
511 3 'font-lock-function-name-face
'keep
)
512 (list (concat slash
"\\(?:provide\\|\\(?:re\\)?new\\)command\\** *\\(\\\\[A-Za-z@]+\\)")
513 1 'font-lock-function-name-face
'keep
)
515 (list (concat slash variables
" *" arg
) 2 'font-lock-variable-name-face
)
517 (list (concat slash includes opt arg
) 3 'font-lock-builtin-face
)
518 ;; Definitions. I think.
519 '("^[ \t]*\\\\def *\\\\\\(\\(\\w\\|@\\)+\\)"
520 1 font-lock-function-name-face
))))
521 "Subdued expressions to highlight in TeX modes.")
523 (defun tex-font-lock-append-prop (prop)
524 (unless (memq (get-text-property (match-end 1) 'face
)
525 '(font-lock-comment-face tex-verbatim
))
528 (defconst tex-font-lock-keywords-2
529 (append tex-font-lock-keywords-1
532 ;; Names of commands whose arg should be fontified with fonts.
533 (bold (regexp-opt '("textbf" "textsc" "textup"
534 "boldsymbol" "pmb") t
))
535 (italic (regexp-opt '("textit" "textsl" "emph") t
))
536 ;; FIXME: unimplemented yet.
537 ;; (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
539 ;; Names of commands whose arg should be fontified as a citation.
540 (citations (regexp-opt
541 '("label" "ref" "pageref" "vref" "eqref"
542 "cite" "nocite" "index" "glossary" "bibitem"
543 ;; natbib's two variants of \cite:
545 ;; These are text, rather than citations.
546 ;; "caption" "footnote" "footnotemark" "footnotetext"
550 ;; Names of commands that should be fontified.
551 (specials-1 (regexp-opt '("\\" "\\*") t
)) ;; "-"
552 (specials-2 (regexp-opt
553 '("linebreak" "nolinebreak" "pagebreak" "nopagebreak"
554 "newline" "newpage" "clearpage" "cleardoublepage"
555 "displaybreak" "allowdisplaybreaks"
556 "enlargethispage") t
))
557 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
561 (opt " *\\(\\[[^]]*\\] *\\)*")
562 (args "\\(\\(?:[^{}&\\]+\\|\\\\.\\|{[^}]*}\\)+\\)")
563 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
567 (list (concat slash citations opt arg
) 3 'font-lock-constant-face
)
569 ;; Text between `` quotes ''.
570 (cons (concat (regexp-opt `("``" "\"<" "\"`" "<<" "«") t
)
571 "[^'\">{]+" ;a bit pessimistic
572 (regexp-opt `("''" "\">" "\"'" ">>" "»") t
))
573 'font-lock-string-face
)
575 ;; Command names, special and general.
576 (cons (concat slash specials-1
) 'font-lock-warning-face
)
577 (list (concat "\\(" slash specials-2
"\\)\\([^a-zA-Z@]\\|\\'\\)")
578 1 'font-lock-warning-face
)
579 (concat slash general
)
581 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
582 ;; since we might not be able to display those fonts.
583 (list (concat slash bold
" *" arg
) 2
584 '(tex-font-lock-append-prop 'bold
) 'append
)
585 (list (concat slash italic
" *" arg
) 2
586 '(tex-font-lock-append-prop 'italic
) 'append
)
587 ;; (list (concat slash type arg) 2 '(quote bold-italic) 'append)
589 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
590 (list (concat "\\\\\\(em\\|it\\|sl\\)\\>" args
)
591 2 '(tex-font-lock-append-prop 'italic
) 'append
)
592 ;; This is separate from the previous one because of cases like
593 ;; {\em foo {\bf bar} bla} where both match.
594 (list (concat "\\\\\\(bf\\(series\\)?\\)\\>" args
)
595 3 '(tex-font-lock-append-prop 'bold
) 'append
)))))
596 "Gaudy expressions to highlight in TeX modes.")
598 (defun tex-font-lock-suscript (pos)
599 (unless (or (memq (get-text-property pos
'face
)
600 '(font-lock-constant-face font-lock-builtin-face
601 font-lock-comment-face tex-verbatim
))
602 ;; Check for backslash quoting
605 (while (eq (char-before pos
) ?
\\)
606 (setq pos
(1- pos
) odd
(not odd
)))
608 (if (eq (char-after pos
) ?_
)
609 `(face subscript display
(raise ,(car tex-font-script-display
)))
610 `(face superscript display
(raise ,(cadr tex-font-script-display
))))))
612 (defun tex-font-lock-match-suscript (limit)
613 "Match subscript and superscript patterns up to LIMIT."
614 (when (and tex-fontify-script
615 (re-search-forward "[_^] *\\([^\n\\{}]\\|\
616 \\\\\\([a-zA-Z@]+\\|[^ \t\n]\\)\\|\\({\\)\\)" limit t
))
618 (let ((beg (match-beginning 3))
619 (end (save-restriction
620 (narrow-to-region (point-min) limit
)
621 (condition-case nil
(scan-lists (point) 1 1) (error nil
)))))
622 (store-match-data (if end
623 (list (match-beginning 0) end beg end
)
624 (list beg beg beg beg
)))))
627 (defconst tex-font-lock-keywords-3
628 (append tex-font-lock-keywords-2
629 '((tex-font-lock-match-suscript
630 (1 (tex-font-lock-suscript (match-beginning 0)) append
))))
631 "Experimental expressions to highlight in TeX modes.")
633 (defvar tex-font-lock-keywords tex-font-lock-keywords-1
634 "Default expressions to highlight in TeX modes.")
636 (defvar tex-verbatim-environments
637 '("verbatim" "verbatim*"))
638 (put 'tex-verbatim-environments
'safe-local-variable
639 (lambda (x) (null (delq t
(mapcar 'stringp x
)))))
642 (defconst tex-syntax-propertize-rules
643 (syntax-propertize-precompile-rules
644 ("\\\\verb\\**\\([^a-z@*]\\)"
647 (match-beginning 0) (char-after (match-beginning 1))))))))
649 (defconst latex-syntax-propertize-rules
650 (syntax-propertize-precompile-rules
651 tex-syntax-propertize-rules
652 ("\\\\\\(?:end\\|begin\\) *\\({[^\n{}]*}\\)"
654 (tex-env-mark (match-beginning 0)
655 (match-beginning 1) (match-end 1))))))))
657 (defun tex-env-mark (cmd start end
)
658 (when (= cmd
(line-beginning-position))
659 (let ((arg (buffer-substring-no-properties (1+ start
) (1- end
))))
660 (when (member arg tex-verbatim-environments
)
661 (if (eq ?b
(char-after (1+ cmd
)))
663 (put-text-property (line-end-position)
664 (line-beginning-position 2)
665 'syntax-table
(string-to-syntax "< c"))
666 ;; In the case of an empty verbatim env, the \n after the \begin is
667 ;; the same as the \n before the \end. Lucky for us, the "> c"
668 ;; property associated to the \end will be placed afterwards, so it
669 ;; will override the "< c".
670 (put-text-property (1- cmd
) cmd
671 'syntax-table
(string-to-syntax "> c"))
672 ;; The text between \end{verbatim} and \n is ignored, so we'll treat
674 (put-text-property end
(min (1+ end
) (line-end-position))
675 'syntax-table
(string-to-syntax "<"))))))
676 ;; Mark env args for possible electric pairing.
677 (unless (get-char-property (1+ start
) 'text-clones
) ;Already paired-up.
678 (put-text-property start end
'latex-env-pair t
)))
680 (define-minor-mode latex-electric-env-pair-mode
681 "Automatically update the \\end arg when editing the \\begin one.
684 (if latex-electric-env-pair-mode
685 (add-hook 'before-change-functions
686 #'latex-env-before-change nil
'local
)
687 (remove-hook 'before-change-functions
688 #'latex-env-before-change
'local
)))
690 (defun latex-env-before-change (start end
)
691 (when (get-text-property start
'latex-env-pair
)
693 (with-silent-modifications
694 ;; Remove properties even if don't find a pair.
695 (remove-text-properties
696 (previous-single-property-change (1+ start
) 'latex-env-pair
)
697 (next-single-property-change start
'latex-env-pair
)
699 (unless (or (get-char-property start
'text-clones
)
700 (get-char-property (1+ start
) 'text-clones
)
703 (not (re-search-backward
704 "\\\\\\(?:end\\|begi\\(n\\)\\) *{"
705 (line-beginning-position) t
))))
706 (let ((cmd-start (match-beginning 0))
707 (type (match-end 1)) ;nil for \end, else \begin.
708 (arg-start (1- (match-end 0))))
710 (goto-char (match-end 0))
711 (when (and (looking-at "[^\n{}]*}")
712 (> (match-end 0) end
))
713 (let ((arg-end (match-end 0)))
714 (if (null type
) ;\end
715 (progn (goto-char arg-end
)
716 (latex-forward-sexp -
1) (forward-word 1))
717 (goto-char cmd-start
)
718 (latex-forward-sexp 1)
719 (let (forward-sexp-function) (backward-sexp)))
721 (regexp-quote (buffer-substring arg-start arg-end
)))
722 (text-clone-create arg-start arg-end
))))))))
724 (error (message "Error in latex-env-before-change: %s" err
)))))
726 (defun tex-font-lock-unfontify-region (beg end
)
727 (font-lock-default-unfontify-region beg end
)
729 (let ((next (next-single-property-change beg
'display nil end
))
730 (prop (get-text-property beg
'display
)))
731 (if (and (eq (car-safe prop
) 'raise
)
732 (member (car-safe (cdr prop
)) tex-font-script-display
)
734 (put-text-property beg next
'display nil
))
737 (defcustom tex-suscript-height-ratio
0.8
738 "Ratio of subscript/superscript height to that of the preceding text.
739 In nested subscript/superscript, this factor is applied repeatedly,
740 subject to the limit set by `tex-suscript-height-minimum'."
745 (defcustom tex-suscript-height-minimum
0.0
746 "Integer or float limiting the minimum size of subscript/superscript text.
747 An integer is an absolute height in units of 1/10 point, a float
748 is a height relative to that of the default font. Zero means no minimum."
749 :type
'(choice (integer :tag
"Integer height in 1/10 point units")
750 (float :tag
"Fraction of default font height"))
754 (defun tex-suscript-height (height)
755 "Return the integer height of subscript/superscript font in 1/10 points.
756 Not smaller than the value set by `tex-suscript-height-minimum'."
757 (ceiling (max (if (integerp tex-suscript-height-minimum
)
758 tex-suscript-height-minimum
759 ;; For bootstrapping.
761 (* tex-suscript-height-minimum
762 (face-attribute 'default
:height
))
764 ;; NB assumes height is integer.
765 (* height tex-suscript-height-ratio
))))
768 '((t :height tex-suscript-height
)) ;; :raise 0.2
769 "Face used for superscripts."
772 '((t :height tex-suscript-height
)) ;; :raise -0.2
773 "Face used for subscripts."
777 '((t :inherit font-lock-string-face
))
778 "Face used to highlight TeX math expressions."
780 (define-obsolete-face-alias 'tex-math-face
'tex-math
"22.1")
781 (defvar tex-math-face
'tex-math
)
783 (defface tex-verbatim
784 ;; '((t :inherit font-lock-string-face))
785 '((t :family
"courier"))
786 "Face used to highlight TeX verbatim environments."
788 (define-obsolete-face-alias 'tex-verbatim-face
'tex-verbatim
"22.1")
789 (defvar tex-verbatim-face
'tex-verbatim
)
791 (defun tex-font-lock-verb (start delim
)
792 "Place syntax table properties on the \verb construct.
793 START is the position of the \\ and DELIM is the delimiter char."
794 ;; Do nothing if the \verb construct is itself inside a comment or
796 (unless (nth 8 (save-excursion (syntax-ppss start
)))
797 ;; Let's find the end and mark it.
798 ;; This may span more than a single line, but we don't bother
799 ;; placing a syntax-multiline property since such multiline verbs aren't
801 (skip-chars-forward (string ?^ delim
))
803 (when (eq (char-syntax (preceding-char)) ?
/)
804 (put-text-property (1- (point)) (point)
805 'syntax-table
(string-to-syntax ".")))
806 (put-text-property (point) (1+ (point))
807 'syntax-table
(string-to-syntax "\"")))))
809 ;; Use string syntax but math face for $...$.
810 (defun tex-font-lock-syntactic-face-function (state)
811 (let ((char (nth 3 state
)))
814 (if (eq 2 (nth 7 state
)) tex-verbatim-face font-lock-comment-face
))
815 ((eq char ?$
) tex-math-face
)
817 (t tex-verbatim-face
))))
820 (defun tex-define-common-keys (keymap)
821 "Define the keys that we want defined both in TeX mode and in the TeX shell."
822 (define-key keymap
"\C-c\C-k" 'tex-kill-job
)
823 (define-key keymap
"\C-c\C-l" 'tex-recenter-output-buffer
)
824 (define-key keymap
"\C-c\C-q" 'tex-show-print-queue
)
825 (define-key keymap
"\C-c\C-p" 'tex-print
)
826 (define-key keymap
"\C-c\C-v" 'tex-view
)
828 (define-key keymap
[menu-bar tex
] (cons "TeX" (make-sparse-keymap "TeX")))
830 (define-key keymap
[menu-bar tex tex-kill-job
]
831 '(menu-item "Tex Kill" tex-kill-job
:enable
(tex-shell-running)))
832 (define-key keymap
[menu-bar tex tex-recenter-output-buffer
]
833 '(menu-item "Tex Recenter" tex-recenter-output-buffer
834 :enable
(get-buffer "*tex-shell*")))
835 (define-key keymap
[menu-bar tex tex-show-print-queue
]
836 '("Show Print Queue" . tex-show-print-queue
))
837 (define-key keymap
[menu-bar tex tex-alt-print
]
838 '(menu-item "Tex Print (alt printer)" tex-alt-print
839 :enable
(stringp tex-print-file
)))
840 (define-key keymap
[menu-bar tex tex-print
]
841 '(menu-item "Tex Print" tex-print
:enable
(stringp tex-print-file
)))
842 (define-key keymap
[menu-bar tex tex-view
]
843 '(menu-item "Tex View" tex-view
:enable
(stringp tex-print-file
))))
846 (let ((map (make-sparse-keymap)))
847 (set-keymap-parent map text-mode-map
)
848 (tex-define-common-keys map
)
849 (define-key map
"\"" 'tex-insert-quote
)
850 (define-key map
"(" 'skeleton-pair-insert-maybe
)
851 (define-key map
"{" 'skeleton-pair-insert-maybe
)
852 (define-key map
"[" 'skeleton-pair-insert-maybe
)
853 (define-key map
"$" 'skeleton-pair-insert-maybe
)
854 (define-key map
"\n" 'tex-terminate-paragraph
)
855 (define-key map
"\M-\r" 'latex-insert-item
)
856 (define-key map
"\C-c}" 'up-list
)
857 (define-key map
"\C-c{" 'tex-insert-braces
)
858 (define-key map
"\C-c\C-r" 'tex-region
)
859 (define-key map
"\C-c\C-b" 'tex-buffer
)
860 (define-key map
"\C-c\C-f" 'tex-file
)
861 (define-key map
"\C-c\C-c" 'tex-compile
)
862 (define-key map
"\C-c\C-i" 'tex-bibtex-file
)
863 (define-key map
"\C-c\C-o" 'latex-insert-block
)
865 ;; Redundant keybindings, for consistency with SGML mode.
866 (define-key map
"\C-c\C-t" 'latex-insert-block
)
867 (define-key map
"\C-c]" 'latex-close-block
)
868 (define-key map
"\C-c/" 'latex-close-block
)
870 (define-key map
"\C-c\C-e" 'latex-close-block
)
871 (define-key map
"\C-c\C-u" 'tex-goto-last-unclosed-latex-block
)
872 (define-key map
"\C-c\C-m" 'tex-feed-input
)
873 (define-key map
[(control return
)] 'tex-feed-input
)
874 (define-key map
[menu-bar tex tex-bibtex-file
]
875 '("BibTeX File" . tex-bibtex-file
))
876 (define-key map
[menu-bar tex tex-validate-region
]
877 '(menu-item "Validate Region" tex-validate-region
:enable mark-active
))
878 (define-key map
[menu-bar tex tex-validate-buffer
]
879 '("Validate Buffer" . tex-validate-buffer
))
880 (define-key map
[menu-bar tex tex-region
]
881 '(menu-item "TeX Region" tex-region
:enable mark-active
))
882 (define-key map
[menu-bar tex tex-buffer
]
883 '("TeX Buffer" . tex-buffer
))
884 (define-key map
[menu-bar tex tex-file
] '("TeX File" . tex-file
))
886 "Keymap shared by TeX modes.")
888 (defvar latex-mode-map
889 (let ((map (make-sparse-keymap)))
890 (set-keymap-parent map tex-mode-map
)
891 (define-key map
"\C-c\C-s" 'latex-split-block
)
893 "Keymap for `latex-mode'. See also `tex-mode-map'.")
895 (defvar plain-tex-mode-map
896 (let ((map (make-sparse-keymap)))
897 (set-keymap-parent map tex-mode-map
)
899 "Keymap for `plain-tex-mode'. See also `tex-mode-map'.")
901 (defvar tex-shell-map
902 (let ((m (make-sparse-keymap)))
903 (set-keymap-parent m shell-mode-map
)
904 (tex-define-common-keys m
)
906 "Keymap for the TeX shell.
907 Inherits `shell-mode-map' with a few additions.")
909 (defvar tex-face-alist
912 (bold-italic .
"{\\bi ") ; hypothetical
913 (underline .
"\\underline{")
914 (default .
"{\\rm "))
915 "Alist of face and TeX font name for facemenu.")
917 (defvar tex-latex-face-alist
918 `((italic .
"{\\em ")
920 "Alist of face and LaTeX font name for facemenu.")
922 (defun tex-facemenu-add-face-function (face end
)
923 (or (cdr (assq face tex-face-alist
))
924 (or (and (consp face
)
927 (eq major-mode
'latex-mode
)
928 ;; This actually requires the `color' LaTeX package.
929 (cond ((eq (caar face
) :foreground
)
930 (format "{\\color{%s} " (cadr (car face
))))
931 ((eq (caar face
) :background
)
932 (format "\\colorbox{%s}{" (cadr (car face
))))))
933 (error "Face %s not configured for %s mode" face mode-name
))))
935 ;; This would be a lot simpler if we just used a regexp search,
936 ;; but then it would be too slow.
937 (defun tex-guess-mode ()
938 (let ((mode tex-default-mode
) slash comment
)
940 (goto-char (point-min))
941 (while (and (setq slash
(search-forward "\\" nil t
))
942 (setq comment
(let ((search-end (point)))
945 (search-forward "%" search-end t
))))))
946 (when (and slash
(not comment
))
951 (regexp-opt '("documentstyle" "documentclass"
952 "begin" "subsection" "section"
953 "part" "chapter" "newcommand"
954 "renewcommand" "RequirePackage") 'words
)
955 "\\|NeedsTeXFormat{LaTeX")))
957 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
958 ;; SliTeX is almost never used any more nowadays.
959 (tex-executable-exists-p slitex-run-command
))
965 ;; `tex-mode' plays two roles: it's the parent of several sub-modes
966 ;; but it's also the function that chooses between those submodes.
967 ;; To tell the difference between those two cases where the function
968 ;; might be called, we check `delay-mode-hooks'.
969 (define-derived-mode tex-mode text-mode
"generic-TeX"
970 (tex-common-initialization))
971 ;; We now move the function and define it again. This gives a warning
972 ;; in the byte-compiler :-( but it's difficult to avoid because
973 ;; `define-derived-mode' will necessarily define the function once
974 ;; and we need to define it a second time for `autoload' to get the
976 (defalias 'tex-mode-internal
(symbol-function 'tex-mode
))
978 ;; Suppress the byte-compiler warning about multiple definitions.
979 ;; This is a) ugly, and b) cheating, but this was the last
980 ;; remaining warning from byte-compiling all of Emacs...
982 (setq byte-compile-function-environment
983 (delq (assq 'tex-mode byte-compile-function-environment
)
984 byte-compile-function-environment
)))
988 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
989 Tries to determine (by looking at the beginning of the file) whether
990 this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
991 `latex-mode', or `slitex-mode', respectively. If it cannot be determined,
992 such as if there are no commands in the file, the value of `tex-default-mode'
993 says which mode to use."
996 ;; We're called from one of the children already.
1000 ;; The following three autoloaded aliases appear to conflict with
1001 ;; AUCTeX. However, even though AUCTeX uses the mixed case variants
1002 ;; for all mode relevant variables and hooks, the invocation function
1003 ;; and setting of `major-mode' themselves need to be lowercase for
1004 ;; AUCTeX to provide a fully functional user-level replacement. So
1005 ;; these aliases should remain as they are, in particular since AUCTeX
1006 ;; users are likely to use them.
1009 (defalias 'TeX-mode
'tex-mode
)
1011 (defalias 'plain-TeX-mode
'plain-tex-mode
)
1013 (defalias 'LaTeX-mode
'latex-mode
)
1016 (define-derived-mode plain-tex-mode tex-mode
"TeX"
1017 "Major mode for editing files of input for plain TeX.
1018 Makes $ and } display the characters they match.
1019 Makes \" insert `` when it seems to be the beginning of a quotation,
1020 and '' when it appears to be the end; it inserts \" only after a \\.
1022 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
1023 copied from the top of the file (containing macro definitions, etc.),
1024 running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
1025 \\[tex-file] saves the buffer and then processes the file.
1026 \\[tex-print] prints the .dvi file made by any of these.
1027 \\[tex-view] previews the .dvi file made by any of these.
1028 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1030 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1031 mismatched $'s or braces.
1034 \\{plain-tex-mode-map}
1038 Command string used by \\[tex-region] or \\[tex-buffer].
1040 Directory in which to create temporary files for TeX jobs
1041 run by \\[tex-region] or \\[tex-buffer].
1042 tex-dvi-print-command
1043 Command string used by \\[tex-print] to print a .dvi file.
1044 tex-alt-dvi-print-command
1045 Alternative command string used by \\[tex-print] (when given a prefix
1046 argument) to print a .dvi file.
1047 tex-dvi-view-command
1048 Command string used by \\[tex-view] to preview a .dvi file.
1049 tex-show-queue-command
1050 Command string used by \\[tex-show-print-queue] to show the print
1051 queue that \\[tex-print] put your job on.
1053 Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
1054 `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
1055 special subshell is initiated, the hook `tex-shell-hook' is run."
1056 (set (make-local-variable 'tex-command
) tex-run-command
)
1057 (set (make-local-variable 'tex-start-of-header
) "%\\*\\*start of header")
1058 (set (make-local-variable 'tex-end-of-header
) "%\\*\\*end of header")
1059 (set (make-local-variable 'tex-trailer
) "\\bye\n"))
1062 (define-derived-mode latex-mode tex-mode
"LaTeX"
1063 "Major mode for editing files of input for LaTeX.
1064 Makes $ and } display the characters they match.
1065 Makes \" insert `` when it seems to be the beginning of a quotation,
1066 and '' when it appears to be the end; it inserts \" only after a \\.
1068 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
1069 copied from the top of the file (containing \\documentstyle, etc.),
1070 running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
1071 \\[tex-file] saves the buffer and then processes the file.
1072 \\[tex-print] prints the .dvi file made by any of these.
1073 \\[tex-view] previews the .dvi file made by any of these.
1074 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1076 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1077 mismatched $'s or braces.
1084 Command string used by \\[tex-region] or \\[tex-buffer].
1086 Directory in which to create temporary files for LaTeX jobs
1087 run by \\[tex-region] or \\[tex-buffer].
1088 tex-dvi-print-command
1089 Command string used by \\[tex-print] to print a .dvi file.
1090 tex-alt-dvi-print-command
1091 Alternative command string used by \\[tex-print] (when given a prefix
1092 argument) to print a .dvi file.
1093 tex-dvi-view-command
1094 Command string used by \\[tex-view] to preview a .dvi file.
1095 tex-show-queue-command
1096 Command string used by \\[tex-show-print-queue] to show the print
1097 queue that \\[tex-print] put your job on.
1099 Entering Latex mode runs the hook `text-mode-hook', then
1100 `tex-mode-hook', and finally `latex-mode-hook'. When the special
1101 subshell is initiated, `tex-shell-hook' is run."
1102 (set (make-local-variable 'tex-command
) latex-run-command
)
1103 (set (make-local-variable 'tex-start-of-header
)
1104 "\\\\document\\(style\\|class\\)")
1105 (set (make-local-variable 'tex-end-of-header
) "\\\\begin\\s-*{document}")
1106 (set (make-local-variable 'tex-trailer
) "\\end{document}\n")
1107 ;; A line containing just $$ is treated as a paragraph separator.
1108 ;; A line starting with $$ starts a paragraph,
1109 ;; but does not separate paragraphs if it has more stuff on it.
1110 (setq paragraph-start
1111 (concat "[ \t]*\\(\\$\\$\\|"
1113 "\\\\" (regexp-opt (append
1114 (mapcar 'car latex-section-alist
)
1115 '("begin" "label" "end"
1116 "item" "bibitem" "newline" "noindent"
1117 "newpage" "footnote" "marginpar"
1118 "parbox" "caption")) t
)
1119 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t
)
1121 (setq paragraph-separate
1122 (concat "[\f%]\\|[ \t]*\\($\\|"
1124 "\\\\" (regexp-opt (append
1125 (mapcar 'car latex-section-alist
)
1126 '("begin" "label" "end" )) t
)
1127 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
1128 "noindent" "newpage" "footnote"
1129 "marginpar" "parbox" "caption"))
1130 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
1131 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
1132 (set (make-local-variable 'imenu-create-index-function
)
1133 'latex-imenu-create-index
)
1134 (set (make-local-variable 'tex-face-alist
) tex-latex-face-alist
)
1135 (add-hook 'fill-nobreak-predicate
'latex-fill-nobreak-predicate nil t
)
1136 (set (make-local-variable 'indent-line-function
) 'latex-indent
)
1137 (set (make-local-variable 'fill-indent-according-to-mode
) t
)
1138 (add-hook 'completion-at-point-functions
1139 'latex-complete-data nil
'local
)
1140 (set (make-local-variable 'outline-regexp
) latex-outline-regexp
)
1141 (set (make-local-variable 'outline-level
) 'latex-outline-level
)
1142 (set (make-local-variable 'forward-sexp-function
) 'latex-forward-sexp
)
1143 (set (make-local-variable 'skeleton-end-hook
) nil
))
1146 (define-derived-mode slitex-mode latex-mode
"SliTeX"
1147 "Major mode for editing files of input for SliTeX.
1148 Makes $ and } display the characters they match.
1149 Makes \" insert `` when it seems to be the beginning of a quotation,
1150 and '' when it appears to be the end; it inserts \" only after a \\.
1152 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
1153 copied from the top of the file (containing \\documentstyle, etc.),
1154 running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
1155 \\[tex-file] saves the buffer and then processes the file.
1156 \\[tex-print] prints the .dvi file made by any of these.
1157 \\[tex-view] previews the .dvi file made by any of these.
1158 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1160 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1161 mismatched $'s or braces.
1168 Command string used by \\[tex-region] or \\[tex-buffer].
1170 Directory in which to create temporary files for SliTeX jobs
1171 run by \\[tex-region] or \\[tex-buffer].
1172 tex-dvi-print-command
1173 Command string used by \\[tex-print] to print a .dvi file.
1174 tex-alt-dvi-print-command
1175 Alternative command string used by \\[tex-print] (when given a prefix
1176 argument) to print a .dvi file.
1177 tex-dvi-view-command
1178 Command string used by \\[tex-view] to preview a .dvi file.
1179 tex-show-queue-command
1180 Command string used by \\[tex-show-print-queue] to show the print
1181 queue that \\[tex-print] put your job on.
1183 Entering SliTeX mode runs the hook `text-mode-hook', then the hook
1184 `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
1185 `slitex-mode-hook'. When the special subshell is initiated, the hook
1186 `tex-shell-hook' is run."
1187 (setq tex-command slitex-run-command
)
1188 (setq tex-start-of-header
"\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
1190 (defun tex-common-initialization ()
1191 ;; Regexp isearch should accept newline and formfeed as whitespace.
1192 (set (make-local-variable 'search-whitespace-regexp
) "[ \t\r\n\f]+")
1193 ;; A line containing just $$ is treated as a paragraph separator.
1194 (set (make-local-variable 'paragraph-start
)
1195 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
1196 ;; A line starting with $$ starts a paragraph,
1197 ;; but does not separate paragraphs if it has more stuff on it.
1198 (set (make-local-variable 'paragraph-separate
)
1199 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
1200 (set (make-local-variable 'comment-start
) "%")
1201 (set (make-local-variable 'comment-add
) 1)
1202 (set (make-local-variable 'comment-start-skip
)
1203 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
1204 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
1205 (set (make-local-variable 'compare-windows-whitespace
)
1206 'tex-categorize-whitespace
)
1207 (set (make-local-variable 'facemenu-add-face-function
)
1208 'tex-facemenu-add-face-function
)
1209 (set (make-local-variable 'facemenu-end-add-face
) "}")
1210 (set (make-local-variable 'facemenu-remove-face-function
) t
)
1211 (set (make-local-variable 'font-lock-defaults
)
1212 '((tex-font-lock-keywords tex-font-lock-keywords-1
1213 tex-font-lock-keywords-2 tex-font-lock-keywords-3
)
1214 nil nil
((?$ .
"\"")) nil
1215 ;; Who ever uses that anyway ???
1216 (font-lock-mark-block-function . mark-paragraph
)
1217 (font-lock-syntactic-face-function
1218 . tex-font-lock-syntactic-face-function
)
1219 (font-lock-unfontify-region-function
1220 . tex-font-lock-unfontify-region
)))
1221 (set (make-local-variable 'syntax-propertize-function
)
1222 (syntax-propertize-rules latex-syntax-propertize-rules
))
1223 ;; TABs in verbatim environments don't do what you think.
1224 (set (make-local-variable 'indent-tabs-mode
) nil
)
1225 ;; Other vars that should be buffer-local.
1226 (make-local-variable 'tex-command
)
1227 (make-local-variable 'tex-start-of-header
)
1228 (make-local-variable 'tex-end-of-header
)
1229 (make-local-variable 'tex-trailer
))
1231 (defun tex-categorize-whitespace (backward-limit)
1232 ;; compare-windows-whitespace is set to this.
1233 ;; This is basically a finite-state machine.
1234 ;; Returns a symbol telling how TeX would treat
1235 ;; the whitespace we are looking at: null, space, or par.
1236 (let ((category 'null
)
1238 (skip-chars-backward " \t\n\f" backward-limit
)
1240 (cond ((looking-at "[ \t]+")
1241 (goto-char (match-end 0))
1242 (if (eq category
'null
)
1243 (setq category
'space
)))
1245 (cond ((eq category
'newline
)
1246 (setq category
'par
)
1247 (setq not-finished nil
))
1249 (setq category
'newline
) ;a strictly internal state
1250 (goto-char (match-end 0)))))
1252 (setq category
'par
)
1253 (setq not-finished nil
))
1255 (setq not-finished nil
))))
1256 (skip-chars-forward " \t\n\f")
1257 (if (eq category
'newline
)
1258 'space
;TeX doesn't distinguish
1261 (defun tex-insert-quote (arg)
1262 "Insert the appropriate quote marks for TeX.
1263 Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
1264 \(normally '') depending on the context. With prefix argument, always
1265 inserts \" characters."
1267 (if (or arg
(memq (char-syntax (preceding-char)) '(?
/ ?
\\))
1268 (eq (get-text-property (point) 'face
) 'tex-verbatim
)
1270 (backward-char (length tex-open-quote
))
1271 (when (or (looking-at (regexp-quote tex-open-quote
))
1272 (looking-at (regexp-quote tex-close-quote
)))
1273 (delete-char (length tex-open-quote
))
1275 (self-insert-command (prefix-numeric-value arg
))
1276 (insert (if (memq (char-syntax (preceding-char)) '(?\
( ?
> ?\s
))
1277 tex-open-quote tex-close-quote
))))
1279 (defun tex-validate-buffer ()
1280 "Check current buffer for paragraphs containing mismatched braces or $s.
1281 Their positions are recorded in the buffer `*Occur*'.
1282 To find a particular invalidity from `*Occur*', switch to that buffer
1283 and type C-c C-c or click with mouse-2
1284 on the line for the invalidity you want to see."
1286 (let ((buffer (current-buffer))
1287 (prevpos (point-min))
1290 (with-output-to-temp-buffer "*Occur*"
1291 (princ "Mismatches:\n")
1292 (with-current-buffer standard-output
1294 ;; This won't actually work...Really, this whole thing should
1295 ;; be rewritten instead of being a hack on top of occur.
1296 (setq occur-revert-arguments
(list nil
0 (list buffer
))))
1298 (goto-char (point-max))
1299 ;; Do a little shimmy to place point at the end of the last
1300 ;; "real" paragraph. Need to avoid validating across an \end,
1301 ;; because that blows up latex-forward-sexp.
1302 (backward-paragraph)
1305 ;; Scan the previous paragraph for invalidities.
1306 (backward-paragraph)
1308 (or (tex-validate-region (point) (save-excursion
1311 (let ((end (line-beginning-position 2))
1314 (setq start
(point))
1315 ;; Keep track of line number as we scan,
1316 ;; in a cumulative fashion.
1318 (setq linenum
(- linenum
1319 (count-lines prevpos
(point))))
1320 (setq linenum
(1+ (count-lines 1 start
))))
1321 (setq prevpos
(point))
1322 ;; Mention this mismatch in *Occur*.
1323 ;; Since we scan from end of buffer to beginning,
1324 ;; add each mismatch at the beginning of *Occur*.
1326 (setq tem
(point-marker))
1327 (set-buffer standard-output
)
1328 (goto-char (point-min))
1329 ;; Skip "Mismatches:" header line.
1331 (setq num-matches
(1+ num-matches
))
1332 (insert-buffer-substring buffer start end
)
1333 (let (text-beg (text-end (point-marker)))
1334 (forward-char (- start end
))
1335 (setq text-beg
(point-marker))
1336 (insert (format "%3d: " linenum
))
1337 (add-text-properties
1338 text-beg
(- text-end
1)
1339 '(mouse-face highlight
1341 "mouse-2: go to this invalidity"))
1342 (put-text-property text-beg
(- text-end
1)
1343 'occur-target tem
))))))))
1344 (with-current-buffer standard-output
1345 (let ((no-matches (zerop num-matches
)))
1348 (if (called-interactively-p 'interactive
)
1349 (message (cond (no-matches "No mismatches found")
1350 ((= num-matches
1) "1 mismatch found")
1351 (t "%d mismatches found"))
1354 (defun tex-validate-region (start end
)
1355 "Check for mismatched braces or $'s in region.
1356 Returns t if no mismatches. Returns nil and moves point to suspect
1357 area if a mismatch is found."
1359 (let ((failure-point nil
) (max-possible-sexps (- end start
)))
1363 (narrow-to-region start end
)
1364 ;; First check that the open and close parens balance in numbers.
1366 (while (and (not (eobp))
1367 (<= 0 (setq max-possible-sexps
1368 (1- max-possible-sexps
))))
1370 ;; Now check that like matches like.
1372 (while (re-search-forward "\\s(" nil t
)
1374 (let ((pos (match-beginning 0)))
1376 (skip-chars-backward "\\\\") ; escaped parens
1378 (or (eq (preceding-char) (cdr (syntax-after pos
)))
1379 (eq (char-after pos
) (cdr (syntax-after (1- (point)))))
1380 (error "Mismatched parentheses"))))))
1382 (skip-syntax-forward " .>")
1383 (setq failure-point
(point)))))
1384 (if failure-point
(goto-char failure-point
))
1385 (not failure-point
)))
1387 (defun tex-terminate-paragraph (inhibit-validation)
1388 "Insert two newlines, breaking a paragraph for TeX.
1389 Check for mismatched braces or $s in paragraph being terminated.
1390 A prefix arg inhibits the checking."
1392 (or inhibit-validation
1394 ;; For the purposes of this, a "paragraph" is a block of text
1395 ;; wherein all the brackets etc are expected to be balanced. It
1396 ;; may start after a blank line (ie a "proper" paragraph), or
1397 ;; a begin{} or end{} block, etc.
1398 (tex-validate-region
1400 (backward-paragraph)
1403 (message "Paragraph being closed appears to contain a mismatch"))
1406 (define-skeleton tex-insert-braces
1407 "Make a pair of braces and be poised to type inside of them."
1411 ;; This function is used as the value of fill-nobreak-predicate
1412 ;; in LaTeX mode. Its job is to prevent line-breaking inside
1413 ;; of a \verb construct.
1414 (defun latex-fill-nobreak-predicate ()
1416 (skip-chars-backward " ")
1417 ;; Don't break after \ since `\ ' has special meaning.
1418 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?
\\ ?
/)))
1419 (let ((opoint (point))
1422 (while (re-search-forward "\\\\verb\\(.\\)" opoint t
)
1423 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t
)
1427 (defvar latex-block-default
"enumerate")
1429 (defvar latex-block-args-alist
1430 '(("array" nil ?\
{ (skeleton-read "Format: ") ?\
})
1431 ("tabular" nil ?\
{ (skeleton-read "Format: ") ?\
})
1432 ("minipage" nil ?\
{ (skeleton-read "Size: ") ?\
})
1433 ("picture" nil ?\
( (skeleton-read "SizeX,SizeY: ") ?\
))
1434 ;; FIXME: This is right for Prosper, but not for seminar.
1435 ;; ("slide" nil ?\{ (skeleton-read "Title: ") ?\})
1437 "Skeleton element to use for arguments to particular environments.
1438 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1439 the name of the environment and SKEL-ELEM is an element to use in
1440 a skeleton (see `skeleton-insert').")
1442 (defvar latex-block-body-alist
1443 '(("enumerate" nil
'(latex-insert-item) > _
)
1444 ("itemize" nil
'(latex-insert-item) > _
)
1445 ("table" nil
"\\caption{" > (skeleton-read "Caption: ") "}" > \n
1446 '(if (and (boundp 'reftex-mode
) reftex-mode
) (reftex-label "table"))
1448 ("figure" nil
> _
\n "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1449 '(if (and (boundp 'reftex-mode
) reftex-mode
) (reftex-label "table"))))
1450 "Skeleton element to use for the body of particular environments.
1451 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1452 the name of the environment and SKEL-ELEM is an element to use in
1453 a skeleton (see `skeleton-insert').")
1455 ;; Like tex-insert-braces, but for LaTeX.
1456 (defalias 'tex-latex-block
'latex-insert-block
)
1457 (define-skeleton latex-insert-block
1458 "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
1459 Puts point on a blank line between them."
1460 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1461 latex-block-default
)
1462 (append latex-block-names
1463 latex-standard-block-names
)
1464 nil nil nil nil latex-block-default
)))
1465 (setq latex-block-default choice
)
1466 (unless (or (member choice latex-standard-block-names
)
1467 (member choice latex-block-names
))
1468 ;; Remember new block names for later completion.
1469 (push choice latex-block-names
))
1471 \n "\\begin{" str
"}"
1472 (cdr (assoc str latex-block-args-alist
))
1473 > \n (or (cdr (assoc str latex-block-body-alist
)) '(nil > _
))
1475 "\\end{" str
"}" > \n)
1477 (define-skeleton latex-insert-item
1478 "Insert a \item macro."
1483 ;;;; LaTeX completion.
1485 (defvar latex-complete-bibtex-cache nil
)
1487 (defun latex-string-prefix-p (str1 str2
)
1488 (eq t
(compare-strings str1 nil nil str2
0 (length str1
))))
1490 (defvar bibtex-reference-key
)
1491 (declare-function reftex-get-bibfile-list
"reftex-cite.el" ())
1493 (defun latex-complete-bibtex-keys ()
1494 (when (bound-and-true-p reftex-mode
)
1495 (lambda (key pred action
)
1496 (let ((re (concat "^[ \t]*@\\([a-zA-Z]+\\)[ \t\n]*\\([{(][ \t\n]*\\)"
1497 (regexp-quote key
)))
1498 (files (reftex-get-bibfile-list))
1500 (if (and (eq (car latex-complete-bibtex-cache
)
1501 (reftex-get-bibfile-list))
1502 (latex-string-prefix-p (nth 1 latex-complete-bibtex-cache
)
1505 (setq keys
(nth 2 latex-complete-bibtex-cache
))
1506 (dolist (file files
)
1507 (with-current-buffer (find-file-noselect file
)
1508 (goto-char (point-min))
1509 (while (re-search-forward re nil t
)
1510 (goto-char (match-end 2))
1511 (when (and (not (member-ignore-case (match-string 1)
1512 '("c" "comment" "string")))
1513 (looking-at bibtex-reference-key
))
1514 (push (match-string-no-properties 0) keys
)))))
1516 (set (make-local-variable 'latex-complete-bibtex-cache
)
1517 (list files key keys
)))
1518 (complete-with-action action keys key pred
)))))
1520 (defun latex-complete-envnames ()
1521 (append latex-block-names latex-standard-block-names
))
1523 (defun latex-complete-refkeys ()
1524 (when (boundp 'reftex-docstruct-symbol
)
1525 (symbol-value reftex-docstruct-symbol
)))
1527 (defvar latex-complete-alist
1528 ;; TODO: Add \begin, \end, \ref, ...
1529 '(("\\`\\\\\\(short\\)?cite\\'" . latex-complete-bibtex-keys
)
1530 ("\\`\\\\\\(begin\\|end\\)\\'" . latex-complete-envnames
)
1531 ("\\`\\\\[vf]?ref\\'" . latex-complete-refkeys
)))
1533 (defun latex-complete-data ()
1534 "Get completion-data at point."
1537 (skip-chars-backward "^ {}\n\t\\\\")
1539 ((nil ?\s ?
\n ?
\t ?\
}) nil
)
1541 ;; TODO: Complete commands.
1544 ;; Complete args to commands.
1548 (skip-chars-backward " \n")
1549 (buffer-substring (point)
1551 (skip-chars-backward "a-zA-Z@*")
1552 (let ((n (skip-chars-backward "\\\\")))
1553 (forward-char (* 2 (/ n
2))))
1556 (_ (progn (goto-char pt
) (skip-chars-backward "^," start
)))
1558 (_ (progn (goto-char pt
) (skip-chars-forward "^, {}\n\t\\\\")))
1562 (let ((f (lambda () t
)))
1563 (dolist (comp latex-complete-alist
)
1564 (if (string-match (car comp
) cmd
)
1565 (setq f
(cdr comp
))))
1570 (list comp-beg comp-end table
))))))))
1573 ;;;; LaTeX syntax navigation
1576 (defmacro tex-search-noncomment
(&rest body
)
1577 "Execute BODY as long as it return non-nil and point is in a comment.
1578 Return the value returned by the last execution of BODY."
1580 (let ((res-sym (make-symbol "result")))
1583 (and (setq ,res-sym
(progn ,@body
))
1584 (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
1587 (defun tex-last-unended-begin ()
1588 "Leave point at the beginning of the last `\\begin{...}' that is unended."
1590 (while (and (tex-search-noncomment
1591 (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
1592 (looking-at "\\\\end"))
1593 (tex-last-unended-begin))
1594 (search-failed (error "Couldn't find unended \\begin"))))
1596 (defun tex-next-unmatched-end ()
1597 "Leave point at the end of the next `\\end' that is unmatched."
1598 (while (and (tex-search-noncomment
1599 (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
1600 (save-excursion (goto-char (match-beginning 0))
1601 (looking-at "\\\\begin")))
1602 (tex-next-unmatched-end)))
1604 (defun tex-next-unmatched-eparen (otype)
1605 "Leave point after the next unmatched escaped closing parenthesis.
1606 The string OTYPE is an opening parenthesis type: `(', `{', or `['."
1608 (let ((ctype (char-to-string (cdr (aref (syntax-table)
1609 (string-to-char otype
))))))
1610 (while (and (tex-search-noncomment
1611 (re-search-forward (format "\\\\[%s%s]" ctype otype
)))
1613 (goto-char (match-beginning 0))
1614 (looking-at (format "\\\\%s" (regexp-quote otype
)))))
1615 (tex-next-unmatched-eparen otype
)))
1616 (wrong-type-argument (error "Unknown opening parenthesis type: %s" otype
))
1617 (search-failed (error "Couldn't find closing escaped paren"))))
1619 (defun tex-last-unended-eparen (ctype)
1620 "Leave point at the start of the last unended escaped opening parenthesis.
1621 The string CTYPE is a closing parenthesis type: `)', `}', or `]'."
1623 (let ((otype (char-to-string (cdr (aref (syntax-table)
1624 (string-to-char ctype
))))))
1625 (while (and (tex-search-noncomment
1626 (re-search-backward (format "\\\\[%s%s]" ctype otype
)))
1627 (looking-at (format "\\\\%s" (regexp-quote ctype
))))
1628 (tex-last-unended-eparen ctype
)))
1629 (wrong-type-argument (error "Unknown opening parenthesis type: %s" ctype
))
1630 (search-failed (error "Couldn't find unended escaped paren"))))
1632 (defun tex-goto-last-unclosed-latex-block ()
1633 "Move point to the last unclosed \\begin{...}.
1634 Mark is left at original location."
1638 (tex-last-unended-begin)
1639 (setq spot
(point)))
1643 (defvar latex-handle-escaped-parens t
)
1645 ;; Don't think this one actually _needs_ (for the purposes of
1646 ;; tex-mode) to handle escaped parens.
1647 ;; Does not handle escaped parens when latex-handle-escaped-parens is nil.
1648 (defun latex-backward-sexp-1 ()
1649 "Like (backward-sexp 1) but aware of multi-char elements and escaped parens."
1651 (forward-sexp-function))
1654 (if latex-handle-escaped-parens
1655 "\\\\\\(begin\\>\\|[[({]\\)"
1658 (list "Containing expression ends prematurely"
1659 (point) (prog1 (point) (goto-char pos
)))))
1660 ((and latex-handle-escaped-parens
1661 (looking-at "\\\\\\([])}]\\)"))
1662 (tex-last-unended-eparen (match-string 1)))
1663 ((eq (char-after) ?
{)
1664 (let ((newpos (point)))
1665 (when (ignore-errors (backward-sexp 1) t
)
1666 (if (or (looking-at "\\\\end\\>")
1667 ;; In case the \\ ends a verbatim section.
1668 (and (looking-at "end\\>") (eq (char-before) ?
\\)))
1669 (tex-last-unended-begin)
1670 (goto-char newpos
))))))))
1672 ;; Note this does not handle things like mismatched brackets inside
1673 ;; begin/end blocks.
1674 ;; Needs to handle escaped parens for tex-validate-*.
1675 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2007-09/msg00038.html
1676 ;; Does not handle escaped parens when latex-handle-escaped-parens is nil.
1677 (defun latex-forward-sexp-1 ()
1678 "Like (forward-sexp 1) but aware of multi-char elements and escaped parens."
1680 (forward-sexp-function))
1682 (let ((newpos (point)))
1683 (skip-syntax-backward "/w")
1685 ((looking-at "\\\\end\\>")
1687 (list "Containing expression ends prematurely"
1690 (progn (ignore-errors (forward-sexp 2)) (point))
1692 ((looking-at "\\\\begin\\>")
1693 (goto-char (match-end 0))
1694 (tex-next-unmatched-end))
1695 ;; A better way to handle this, \( .. \) etc, is probably to
1696 ;; temporarily change the syntax of the \ in \( to punctuation.
1697 ((and latex-handle-escaped-parens
1698 (looking-back "\\\\[])}]"))
1700 (list "Containing expression ends prematurely"
1701 (- (point) 2) (prog1 (point)
1703 ((and latex-handle-escaped-parens
1704 (looking-back "\\\\\\([({[]\\)"))
1705 (tex-next-unmatched-eparen (match-string 1)))
1706 (t (goto-char newpos
))))))
1708 (defun latex-forward-sexp (&optional arg
)
1709 "Like `forward-sexp' but aware of multi-char elements and escaped parens."
1711 (unless arg
(setq arg
1))
1712 (let ((pos (point)))
1717 (progn (latex-forward-sexp-1) (1- arg
))
1718 (progn (latex-backward-sexp-1) (1+ arg
)))))
1721 (signal (car err
) (cdr err
))))))
1723 (defun latex-syntax-after ()
1724 "Like (char-syntax (char-after)) but aware of multi-char elements."
1725 (if (looking-at "\\\\end\\>") ?\
) (char-syntax (following-char))))
1727 (defun latex-skip-close-parens ()
1728 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1729 (let ((forward-sexp-function nil
))
1730 (while (progn (skip-syntax-forward " )")
1731 (looking-at "\\\\end\\>"))
1734 (defun latex-down-list ()
1735 "Like (down-list 1) but aware of multi-char elements."
1736 (forward-comment (point-max))
1737 (let ((forward-sexp-function nil
))
1738 (if (not (looking-at "\\\\begin\\>"))
1742 (while (looking-at "[ \t]*[[{(]")
1743 (with-syntax-table tex-mode-syntax-table
1746 (defalias 'tex-close-latex-block
'latex-close-block
)
1747 (define-skeleton latex-close-block
1748 "Create an \\end{...} to match the last unclosed \\begin{...}."
1750 (tex-last-unended-begin)
1751 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _
"}")
1753 \n "\\end" str
> \n)
1755 (define-skeleton latex-split-block
1756 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1758 (tex-last-unended-begin)
1759 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _
"}")
1760 (prog1 (match-string 1)
1761 (goto-char (match-end 1))
1762 (setq v1
(buffer-substring (point)
1764 (while (looking-at "[ \t]*[[{]")
1767 \n "\\end" str
> \n _
\n "\\begin" str v1
> \n)
1769 (defconst tex-discount-args-cmds
1770 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1771 "documentclass" "usepackage" "label")
1772 "TeX commands whose arguments should not be counted as text.")
1774 (defun tex-count-words (begin end
)
1775 "Count the number of words in the buffer."
1777 (if (and transient-mark-mode mark-active
)
1778 (list (region-beginning) (region-end))
1779 (list (point-min) (point-max))))
1780 ;; TODO: skip comments and math and maybe some environments.
1784 (while (and (< (point) end
) (re-search-forward "\\<" end t
))
1785 (if (not (eq (char-syntax (preceding-char)) ?
/))
1787 ;; Don't count single-char words.
1788 (unless (looking-at ".\\>") (incf count
))
1791 (buffer-substring-no-properties
1792 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1795 (when (member cmd tex-discount-args-cmds
)
1796 (skip-chars-forward "*")
1797 (forward-comment (point-max))
1798 (when (looking-at "\\[")
1800 (forward-comment (point-max)))
1801 (if (not (looking-at "{"))
1803 (forward-sexp 1))))))
1804 (message "%s words" count
))))
1808 ;;; Invoking TeX in an inferior shell.
1810 ;; Why use a shell instead of running TeX directly? Because if TeX
1811 ;; gets stuck, the user can switch to the shell window and type at it.
1813 ;; The utility functions:
1815 (define-derived-mode tex-shell shell-mode
"TeX-Shell"
1816 (set (make-local-variable 'compilation-parse-errors-function
)
1817 'tex-compilation-parse-errors
)
1818 (compilation-shell-minor-mode t
))
1821 (defun tex-start-shell ()
1822 (with-current-buffer
1825 (or tex-shell-file-name
(getenv "ESHELL") shell-file-name
)
1827 ;; Specify an interactive shell, to make sure it prompts.
1829 (let ((proc (get-process "tex-shell")))
1830 (set-process-sentinel proc
'tex-shell-sentinel
)
1831 (set-process-query-on-exit-flag proc nil
)
1833 (while (zerop (buffer-size))
1836 (defun tex-feed-input ()
1837 "Send input to the tex shell process.
1838 In the tex buffer this can be used to continue an interactive tex run.
1839 In the tex shell buffer this command behaves like `comint-send-input'."
1841 (set-buffer (tex-shell-buf))
1843 (tex-recenter-output-buffer nil
))
1845 (defun tex-display-shell ()
1846 "Make the TeX shell buffer visible in a window."
1847 (display-buffer (tex-shell-buf))
1848 (tex-recenter-output-buffer nil
))
1850 (defun tex-shell-sentinel (proc msg
)
1851 (cond ((null (buffer-name (process-buffer proc
)))
1853 (set-process-buffer proc nil
)
1854 (tex-delete-last-temp-files))
1855 ((memq (process-status proc
) '(signal exit
))
1856 (tex-delete-last-temp-files))))
1858 (defun tex-set-buffer-directory (buffer directory
)
1859 "Set BUFFER's default directory to be DIRECTORY."
1860 (setq directory
(file-name-as-directory (expand-file-name directory
)))
1861 (if (not (file-directory-p directory
))
1862 (error "%s is not a directory" directory
)
1863 (with-current-buffer buffer
1864 (setq default-directory directory
))))
1866 (defvar tex-send-command-modified-tick
0)
1867 (make-variable-buffer-local 'tex-send-command-modified-tick
)
1869 (defun tex-shell-proc ()
1870 (or (tex-shell-running) (error "No TeX subprocess")))
1871 (defun tex-shell-buf ()
1872 (process-buffer (tex-shell-proc)))
1873 (defun tex-shell-buf-no-error ()
1874 (let ((proc (tex-shell-running)))
1875 (and proc
(process-buffer proc
))))
1877 (defun tex-send-command (command &optional file background
)
1878 "Send COMMAND to TeX shell process, substituting optional FILE for *.
1879 Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1880 FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1881 substitution will be made in COMMAND. COMMAND can be any expression that
1882 evaluates to a command string.
1884 Return the process in which TeX is running."
1886 (let* ((cmd (eval command
))
1887 (proc (tex-shell-proc))
1888 (buf (process-buffer proc
))
1889 (star (string-match "\\*" cmd
))
1894 (if (file-name-absolute-p file
)
1895 (setq file
(convert-standard-filename file
)))
1896 (if star
(concat (substring cmd
0 star
)
1897 (shell-quote-argument file
)
1898 (substring cmd
(1+ star
)))
1899 (concat cmd
" " (shell-quote-argument file
))))
1900 (if background
"&" ""))))
1901 ;; Switch to buffer before checking for subproc output in it.
1903 ;; If text is unchanged since previous tex-send-command,
1904 ;; we haven't got any output. So wait for output now.
1905 (if (= (buffer-modified-tick buf
) tex-send-command-modified-tick
)
1906 (accept-process-output proc
))
1907 (goto-char (process-mark proc
))
1910 (setq tex-send-command-modified-tick
(buffer-modified-tick buf
))
1913 (defun tex-delete-last-temp-files (&optional not-all
)
1914 "Delete any junk files from last temp file.
1915 If NOT-ALL is non-nil, save the `.dvi' file."
1916 (if tex-last-temp-file
1917 (let* ((dir (file-name-directory tex-last-temp-file
))
1918 (list (and (file-directory-p dir
)
1919 (file-name-all-completions
1920 (file-name-sans-extension
1921 (file-name-nondirectory tex-last-temp-file
))
1926 ;; If arg is non-nil, don't delete the .dvi file.
1927 (not (string-match "\\.dvi$" (car list
)))
1928 (delete-file (concat dir
(car list
))))
1929 (delete-file (concat dir
(car list
))))
1930 (setq list
(cdr list
))))))
1932 (add-hook 'kill-emacs-hook
'tex-delete-last-temp-files
)
1935 ;; Machinery to guess the command that the user wants to execute.
1938 (defvar tex-compile-history nil
)
1940 (defvar tex-input-files-re
1942 (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
1943 "bbl" "ind" "sty" "cls") t
)
1944 ;; Include files with no dots (for directories).
1945 "\\'\\|\\`[^.]+\\'")))
1947 (defcustom tex-use-reftex t
1948 "If non-nil, use RefTeX's list of files to determine what command to use."
1952 (defvar tex-compile-commands
1953 '(((concat "pdf" tex-command
1954 " " (if (< 0 (length tex-start-commands
))
1955 (shell-quote-argument tex-start-commands
)) " %f")
1957 ((concat tex-command
1958 " " (if (< 0 (length tex-start-commands
))
1959 (shell-quote-argument tex-start-commands
)) " %f")
1961 ("xdvi %r &" "%r.dvi")
1962 ("\\doc-view \"%r.pdf\"" "%r.pdf")
1963 ("xpdf %r.pdf &" "%r.pdf")
1964 ("gv %r.ps &" "%r.ps")
1965 ("yap %r &" "%r.dvi")
1966 ("advi %r &" "%r.dvi")
1967 ("gv %r.pdf &" "%r.pdf")
1968 ("bibtex %r" "%r.aux" "%r.bbl")
1969 ("makeindex %r" "%r.idx" "%r.ind")
1971 ("dvipdfm %r" "%r.dvi" "%r.pdf")
1972 ("dvipdf %r" "%r.dvi" "%r.pdf")
1973 ("dvips -o %r.ps %r" "%r.dvi" "%r.ps")
1974 ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
1975 ("lpr %r.ps" "%r.ps"))
1976 "List of commands for `tex-compile'.
1977 Each element should be of the form (FORMAT IN OUT) where
1978 FORMAT is an expression that evaluates to a string that can contain
1979 - `%r' the main file name without extension.
1980 - `%f' the main file name.
1981 IN can be either a string (with the same % escapes in it) indicating
1982 the name of the input file, or t to indicate that the input is all
1983 the TeX files of the document, or nil if we don't know.
1984 OUT describes the output file and is either a %-escaped string
1985 or nil to indicate that there is no output file.")
1987 ;; defsubst* gives better byte-code than defsubst.
1988 (defsubst* tex-string-prefix-p
(str1 str2
)
1989 "Return non-nil if STR1 is a prefix of STR2"
1990 (eq t
(compare-strings str2 nil
(length str1
) str1 nil nil
)))
1992 (defun tex-guess-main-file (&optional all
)
1993 "Find a likely `tex-main-file'.
1994 Looks for hints in other buffers in the same directory or in
1995 ALL other buffers. If ALL is `sub' only look at buffers in parent directories
1996 of the current buffer."
1997 (let ((dir default-directory
)
1998 (header-re tex-start-of-header
))
2000 ;; Look for a buffer with `tex-main-file' set.
2001 (dolist (buf (if (consp all
) all
(buffer-list)))
2002 (with-current-buffer buf
2004 ((null all
) (equal dir default-directory
))
2005 ((eq all
'sub
) (tex-string-prefix-p default-directory dir
))
2007 (stringp tex-main-file
))
2008 (throw 'found
(expand-file-name tex-main-file
)))))
2009 ;; Look for a buffer containing the magic `tex-start-of-header'.
2010 (dolist (buf (if (consp all
) all
(buffer-list)))
2011 (with-current-buffer buf
2013 ((null all
) (equal dir default-directory
))
2014 ((eq all
'sub
) (tex-string-prefix-p default-directory dir
))
2017 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
2018 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
2022 (goto-char (point-min))
2024 header-re
(+ (point) 10000) t
))))
2025 (throw 'found
(expand-file-name buffer-file-name
))))))))
2027 (defun tex-main-file ()
2028 "Return the relative name of the main file."
2029 (let* ((file (or tex-main-file
2030 ;; Compatibility with AUCTeX.
2032 (when (boundp 'TeX-master
)
2033 (cond ((stringp TeX-master
)
2034 (make-local-variable 'tex-main-file
)
2035 (setq tex-main-file TeX-master
))
2036 ((and (eq TeX-master t
) buffer-file-name
)
2037 (file-relative-name buffer-file-name
)))))
2038 ;; Try to guess the main file.
2039 (if (not buffer-file-name
)
2040 (error "Buffer is not associated with any file")
2043 (goto-char (point-min))
2044 (re-search-forward tex-start-of-header
2045 (+ (point) 10000) t
))
2046 ;; This is the main file.
2048 ;; This isn't the main file, let's try to find better,
2049 (or (tex-guess-main-file)
2050 (tex-guess-main-file 'sub
)
2051 ;; (tex-guess-main-file t)
2052 buffer-file-name
)))))))
2053 (if (or (file-exists-p file
) (string-match "\\.tex\\'" file
))
2054 file
(concat file
".tex"))))
2056 (defun tex-summarize-command (cmd)
2057 (if (not (stringp cmd
)) ""
2058 (mapconcat 'identity
2059 (mapcar (lambda (s) (car (split-string s
)))
2060 (split-string cmd
"\\s-*\\(?:;\\|&&\\)\\s-*"))
2063 (defun tex-uptodate-p (file)
2064 "Return non-nil if FILE is not uptodate w.r.t the document source files.
2065 FILE is typically the output DVI or PDF file."
2066 ;; We should check all the files included !!!
2068 ;; Clearly, the target must exist.
2069 (file-exists-p file
)
2070 ;; And the last run must not have asked for a rerun.
2071 ;; FIXME: this should check that the last run was done on the same file.
2072 (let ((buf (condition-case nil
(tex-shell-buf) (error nil
))))
2074 (with-current-buffer buf
2076 (goto-char (point-max))
2077 (and (re-search-backward
2078 (concat "(see the transcript file for additional information)"
2079 "\\|^Output written on .*"
2080 (regexp-quote (file-name-nondirectory file
))
2084 ;; Usually page numbers are output as [N], but
2085 ;; I've already seen things like
2086 ;; [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
2087 (or (re-search-backward "\\[[0-9]+\\({[^}]*}\\)?\\]"
2091 (or (re-search-backward "Rerun" nil t
)
2093 ;; And the input files must not have been changed in the meantime.
2094 (let ((files (if (and tex-use-reftex
2095 (fboundp 'reftex-scanning-info-available-p
)
2096 (reftex-scanning-info-available-p))
2097 (reftex-all-document-files)
2098 (list (file-name-directory (expand-file-name file
)))))
2102 (delq nil
(mapcar (lambda (s) (if (eq (aref s
(1- (length s
))) ?
/)
2103 (substring s
0 (1- (length s
)))))
2104 completion-ignored-extensions
))
2107 (while (and files uptodate
)
2108 (let ((f (pop files
)))
2109 (if (and (file-directory-p f
)
2110 ;; Avoid infinite loops.
2111 (not (file-symlink-p f
)))
2112 (unless (string-match ignored-dirs-re f
)
2114 (ignore-errors ;Not readable or something.
2115 (directory-files f t tex-input-files-re
))
2117 (when (file-newer-than-file-p f file
)
2118 (setq uptodate nil
)))))
2122 (autoload 'format-spec
"format-spec")
2124 (defvar tex-executable-cache nil
)
2125 (defun tex-executable-exists-p (name)
2126 "Like `executable-find' but with a cache."
2127 (let ((f (and (string-match "^\\\\\\([^ \t\n]+\\)" name
)
2128 (intern-soft (concat "tex-cmd-" (match-string 1 name
))))))
2131 (let ((cache (assoc name tex-executable-cache
)))
2132 (if cache
(cdr cache
)
2133 (let ((executable (executable-find name
)))
2134 (push (cons name executable
) tex-executable-cache
)
2137 (defun tex-command-executable (cmd)
2138 (let ((s (if (stringp cmd
) cmd
(eval (car cmd
)))))
2139 (substring s
0 (string-match "[ \t]\\|\\'" s
))))
2141 (defun tex-command-active-p (cmd fspec
)
2142 "Return non-nil if the CMD spec might need to be run."
2143 (let ((in (nth 1 cmd
))
2146 (let ((file (format-spec in fspec
)))
2147 (when (file-exists-p file
)
2149 (file-newer-than-file-p
2150 file
(format-spec out fspec
)))))
2151 (when (and (eq in t
) (stringp out
))
2152 (not (tex-uptodate-p (format-spec out fspec
)))))))
2154 (defcustom tex-cmd-bibtex-args
"--min-crossref=100"
2155 "Extra args to pass to `bibtex' by default."
2160 (defun tex-format-cmd (format fspec
)
2161 "Like `format-spec' but adds user-specified args to the command.
2162 Only applies the FSPEC to the args part of FORMAT."
2163 (if (not (string-match "\\([^ /\\]+\\) " format
))
2164 (format-spec format fspec
)
2165 (let* ((prefix (substring format
0 (match-beginning 0)))
2166 (cmd (match-string 1 format
))
2167 (args (substring format
(match-end 0)))
2168 (sym (intern-soft (format "tex-cmd-%s-args" cmd
)))
2169 (extra-args (and sym
(symbol-value sym
))))
2171 (if extra-args
(concat " " extra-args
))
2172 " " (format-spec args fspec
)))))
2174 (defun tex-compile-default (fspec)
2175 "Guess a default command given the `format-spec' FSPEC."
2176 ;; TODO: Learn to do latex+dvips!
2179 ;; Only consider active commands.
2180 (dolist (cmd tex-compile-commands
)
2181 (when (tex-executable-exists-p (tex-command-executable cmd
))
2182 (if (tex-command-active-p cmd fspec
)
2184 (push (nth 1 cmd
) unchanged-in
))))
2185 ;; If no command seems to be applicable, arbitrarily pick the first one.
2186 (setq cmds
(if cmds
(nreverse cmds
) (list (car tex-compile-commands
))))
2187 ;; Remove those commands whose input was considered stable for
2188 ;; some other command (typically if (t . "%.pdf") is inactive
2189 ;; then we're using pdflatex and the fact that the dvi file
2190 ;; is inexistent doesn't matter).
2193 (unless (member (nth 1 cmd
) unchanged-in
)
2195 ;; Only remove if there's something left.
2196 (if tmp
(setq cmds
(nreverse tmp
))))
2197 ;; Remove commands whose input is not uptodate either.
2198 (let ((outs (delq nil
(mapcar (lambda (x) (nth 2 x
)) cmds
)))
2201 (unless (member (nth 1 cmd
) outs
)
2203 ;; Only remove if there's something left.
2204 (if tmp
(setq cmds
(nreverse tmp
))))
2205 ;; Select which file we're going to operate on (the latest).
2206 (let ((latest (nth 1 (car cmds
))))
2207 (dolist (cmd (prog1 (cdr cmds
) (setq cmds
(list (car cmds
)))))
2208 (if (equal latest
(nth 1 cmd
))
2210 (unless (eq latest t
) ;Can't beat that!
2211 (if (or (not (stringp latest
))
2213 (and (stringp (nth 1 cmd
))
2214 (file-newer-than-file-p
2215 (format-spec (nth 1 cmd
) fspec
)
2216 (format-spec latest fspec
))))
2217 (setq latest
(nth 1 cmd
) cmds
(list cmd
)))))))
2218 ;; Expand the command spec into the actual text.
2219 (dolist (cmd (prog1 cmds
(setq cmds nil
)))
2220 (push (cons (eval (car cmd
)) (cdr cmd
)) cmds
))
2221 ;; Select the favorite command from the history.
2222 (let ((hist tex-compile-history
)
2225 (setq hist-cmd
(pop hist
))
2226 (setq re
(concat "\\`"
2227 (regexp-quote (tex-command-executable hist-cmd
))
2228 "\\([ \t]\\|\\'\\)"))
2230 ;; If the hist entry uses the same command and applies to a file
2231 ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
2232 (and (string-match re
(car cmd
))
2233 (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd
)))
2234 (string-match (regexp-quote (match-string 1 (car cmd
)))
2236 (setq hist nil cmds
(list cmd
)))))
2237 ;; Substitute and return.
2239 (string-match (concat "[' \t\"]" (format-spec "%r" fspec
)
2240 "\\([;&' \t\"]\\|\\'\\)") hist-cmd
))
2241 ;; The history command was already applied to the same file,
2242 ;; so just reuse it.
2244 (if cmds
(tex-format-cmd (caar cmds
) fspec
))))))
2246 (defun tex-cmd-doc-view (file)
2247 (pop-to-buffer (find-file-noselect file
)))
2249 (defun tex-compile (dir cmd
)
2250 "Run a command CMD on current TeX buffer's file in DIR."
2251 ;; FIXME: Use time-stamps on files to decide the next op.
2253 (let* ((file (tex-main-file))
2255 (prog1 (file-name-directory (expand-file-name file
))
2256 (setq file
(file-name-nondirectory file
))))
2257 (root (file-name-sans-extension file
))
2258 (fspec (list (cons ?r
(shell-quote-argument root
))
2259 (cons ?f
(shell-quote-argument file
))))
2260 (default (tex-compile-default fspec
)))
2261 (list default-directory
2263 (format "Command [%s]: " (tex-summarize-command default
))
2265 (list (tex-format-cmd (eval (car x
)) fspec
)))
2266 tex-compile-commands
)
2267 nil nil nil
'tex-compile-history default
))))
2268 (save-some-buffers (not compilation-ask-about-save
) nil
)
2269 (let ((f (and (string-match "^\\\\\\([^ \t\n]+\\)" cmd
)
2270 (intern-soft (concat "tex-cmd-" (match-string 1 cmd
))))))
2273 (let ((default-directory dir
))
2274 (apply f
(split-string-and-unquote
2275 (substring cmd
(match-end 0)))))
2276 (wrong-number-of-arguments
2277 (error "Wrong number of arguments to %s"
2278 (substring (symbol-name f
) 8))))
2279 (if (tex-shell-running)
2282 (tex-send-tex-command cmd dir
))))
2284 (defun tex-start-tex (command file
&optional dir
)
2285 "Start a TeX run, using COMMAND on FILE."
2286 (let* ((star (string-match "\\*" command
))
2289 (concat (substring command
0 star
)
2290 (shell-quote-argument file
)
2291 (substring command
(1+ star
)))
2294 (if (< 0 (length tex-start-commands
))
2296 (shell-quote-argument tex-start-commands
) " "))
2297 (shell-quote-argument file
)))))
2298 (tex-send-tex-command compile-command dir
)))
2300 (defun tex-send-tex-command (cmd &optional dir
)
2301 (unless (or (equal dir
(let ((buf (tex-shell-buf-no-error)))
2302 (and buf
(with-current-buffer buf
2303 default-directory
))))
2305 (let (shell-dirtrack-verbose)
2306 (tex-send-command tex-shell-cd-command dir
)))
2307 (with-current-buffer (process-buffer (tex-send-command cmd
))
2308 (setq compilation-last-buffer
(current-buffer))
2309 (compilation-forget-errors)
2310 ;; Don't parse previous compilations.
2311 (set-marker compilation-parsing-end
(1- (point-max))))
2313 (setq tex-last-buffer-texed
(current-buffer)))
2315 (defvar tex-error-parse-syntax-table
2316 (let ((st (make-syntax-table)))
2317 (modify-syntax-entry ?\
( "()" st
)
2318 (modify-syntax-entry ?\
) ")(" st
)
2319 (modify-syntax-entry ?
\\ "\\" st
)
2320 (modify-syntax-entry ?\
{ "_" st
)
2321 (modify-syntax-entry ?\
} "_" st
)
2322 (modify-syntax-entry ?\
[ "_" st
)
2323 (modify-syntax-entry ?\
] "_" st
)
2324 ;; Single quotations may appear in errors
2325 (modify-syntax-entry ?
\" "_" st
)
2327 "Syntax-table used while parsing TeX error messages.")
2329 (defun tex-compilation-parse-errors (limit-search find-at-least
)
2330 "Parse the current buffer as TeX error messages.
2331 See the variable `compilation-parse-errors-function' for the interface it uses.
2333 This function parses only the last TeX compilation.
2334 It works on TeX compilations only. It is necessary for that purpose,
2335 since TeX does not put file names and line numbers on the same line as
2336 for the error messages."
2337 (require 'thingatpt
)
2338 (setq compilation-error-list nil
)
2339 (let ((default-directory ; Perhaps dir has changed meanwhile.
2340 (file-name-directory (buffer-file-name tex-last-buffer-texed
)))
2341 found-desired
(num-errors-found 0)
2342 last-filename last-linenum last-position
2343 begin-of-error end-of-error errfilename
)
2344 ;; Don't reparse messages already seen at last parse.
2345 (goto-char compilation-parsing-end
)
2347 (while (and (not (or found-desired
(eobp)))
2348 ;; First alternative handles the newer --file-line-error style:
2349 ;; ./test2.tex:14: Too many }'s.
2350 ;; Second handles the old-style:
2352 (prog1 (re-search-forward
2353 "^\\(?:\\([^:\n]+\\):[[:digit:]]+:\\|!\\) " nil
'move
)
2354 (setq begin-of-error
(match-beginning 0)
2355 end-of-error
(match-end 0)
2356 errfilename
(match-string 1)))
2358 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil
'move
))
2359 (let* ((this-error (copy-marker begin-of-error
))
2360 (linenum (string-to-number (match-string 1)))
2361 (error-text (regexp-quote (match-string 3)))
2364 ;; Prefer --file-liner-error filename if we have it.
2367 (with-syntax-table tex-error-parse-syntax-table
2368 (backward-up-list 1)
2369 (skip-syntax-forward "(_")
2371 (and (setq try-filename
(thing-at-point
2373 (not (string= "" try-filename
))
2374 (file-readable-p try-filename
)))
2375 (skip-syntax-backward "(_")
2376 (backward-up-list 1)
2377 (skip-syntax-forward "(_"))
2378 (thing-at-point 'filename
)))))
2380 (or (null last-filename
)
2381 (not (string-equal last-filename filename
))))
2383 (with-current-buffer
2384 (if (equal filename
(concat tex-zap-file
".tex"))
2385 tex-last-buffer-texed
2386 (find-file-noselect filename
))
2390 (goto-char (point-min))
2391 (forward-line (1- linenum
))
2392 (setq last-position nil
))
2393 (goto-char last-position
)
2394 (forward-line (- linenum last-linenum
)))
2395 ;; first try a forward search for the error text,
2396 ;; then a backward search limited by the last error.
2397 (let ((starting-point (point)))
2398 (or (re-search-forward error-text nil t
)
2399 (re-search-backward error-text last-position t
)
2400 (goto-char starting-point
)))
2402 (goto-char this-error
)
2403 (if (and compilation-error-list
2404 (or (and find-at-least
2405 (>= num-errors-found
2408 (>= end-of-error limit-search
)))
2410 (setq found-desired t
)
2411 (setq num-errors-found
(1+ num-errors-found
)
2412 last-filename filename
2413 last-linenum linenum
2414 last-position error-location
2415 compilation-error-list
; Add the new error
2416 (cons (cons this-error error-location
)
2417 compilation-error-list
))
2418 (goto-char end-of-error
)))))
2419 (set-marker compilation-parsing-end
(point))
2420 (setq compilation-error-list
(nreverse compilation-error-list
)))
2424 (defun tex-region (beg end
)
2425 "Run TeX on the current region, via a temporary file.
2426 The file's name comes from the variable `tex-zap-file' and the
2427 variable `tex-directory' says where to put it.
2429 If the buffer has a header, the header is given to TeX before the
2430 region itself. The buffer's header is all lines between the strings
2431 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
2432 The header must start in the first 100 lines of the buffer.
2434 The value of `tex-trailer' is given to TeX as input after the region.
2436 The value of `tex-command' specifies the command to use to run TeX."
2438 (if (tex-shell-running)
2442 (setq tex-zap-file
(tex-generate-zap-file-name)))
2443 ;; Temp file will be written and TeX will be run in zap-directory.
2444 ;; If the TEXINPUTS file has relative directories or if the region has
2445 ;; \input of files, this must be the same directory as the file for
2446 ;; TeX to access the correct inputs. That's why it's safest if
2447 ;; tex-directory is ".".
2448 (let* ((zap-directory
2449 (file-name-as-directory (expand-file-name tex-directory
)))
2450 (tex-out-file (expand-file-name (concat tex-zap-file
".tex")
2452 (main-file (expand-file-name (tex-main-file)))
2453 (ismain (string-equal main-file
(buffer-file-name)))
2455 ;; Don't delete temp files if we do the same buffer twice in a row.
2456 (or (eq (current-buffer) tex-last-buffer-texed
)
2457 (tex-delete-last-temp-files t
))
2458 (let ((default-directory zap-directory
)) ; why?
2459 ;; We assume the header is fully contained in tex-main-file.
2460 ;; We use f-f-ns so we get prompted about any changes on disk.
2461 (with-current-buffer (find-file-noselect main-file
)
2462 (setq already-output
(tex-region-header tex-out-file
2464 ;; Write out the specified region (but don't repeat anything
2465 ;; already written in the header).
2466 (write-region (if ismain
2467 (max beg already-output
)
2469 end tex-out-file
(not (zerop already-output
)))
2470 ;; Write the trailer, if any.
2471 ;; Precede it with a newline to make sure it
2472 ;; is not hidden in a comment.
2474 (write-region (concat "\n" tex-trailer
) nil
2476 ;; Record the file name to be deleted afterward.
2477 (setq tex-last-temp-file tex-out-file
)
2478 ;; Use a relative file name here because (1) the proper dir
2479 ;; is already current, and (2) the abs file name is sometimes
2480 ;; too long and can make tex crash.
2481 (tex-start-tex tex-command
(concat tex-zap-file
".tex") zap-directory
)
2482 (setq tex-print-file tex-out-file
)))
2484 (defun tex-region-header (file &optional beg
)
2485 "If there is a TeX header in the current buffer, write it to FILE.
2486 Return point at the end of the region so written, or zero. If
2487 the optional buffer position BEG is specified, then the region
2488 written out starts at BEG, if this lies before the start of the header.
2490 If the first line matches `tex-first-line-header-regexp', it is
2491 also written out. The variables `tex-start-of-header' and
2492 `tex-end-of-header' are used to locate the header. Note that the
2493 start of the header is required to be within the first 100 lines."
2497 (goto-char (point-min))
2498 (let ((search-end (save-excursion
2503 ;; Maybe copy first line, such as `\input texinfo', to temp file.
2504 (and tex-first-line-header-regexp
2505 (looking-at tex-first-line-header-regexp
)
2506 (write-region (point)
2507 (progn (forward-line 1)
2508 (setq already-output
(point)))
2510 ;; Write out the header, if there is one, and any of the
2511 ;; specified region which extends before it. But don't repeat
2512 ;; anything already written.
2513 (and tex-start-of-header
2514 (re-search-forward tex-start-of-header search-end t
)
2517 (setq hbeg
(point)) ; mark beginning of header
2518 (when (re-search-forward tex-end-of-header nil t
)
2520 (setq hend
(point)) ; mark end of header
2526 hend file
(not (zerop already-output
)))
2527 (setq already-output hend
))))
2530 (defun tex-buffer ()
2531 "Run TeX on current buffer. See \\[tex-region] for more information.
2532 Does not save the buffer, so it's useful for trying experimental versions.
2533 See \\[tex-file] for an alternative."
2535 (tex-region (point-min) (point-max)))
2538 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
2539 This function is more useful than \\[tex-buffer] when you need the
2540 `.aux' file of LaTeX to have the correct name."
2542 (when tex-offer-save
2543 (save-some-buffers))
2544 (let* ((source-file (tex-main-file))
2545 (file-dir (file-name-directory (expand-file-name source-file
))))
2546 (if (tex-shell-running)
2549 (tex-start-tex tex-command source-file file-dir
)
2550 (setq tex-print-file
(expand-file-name source-file
))))
2552 (defun tex-generate-zap-file-name ()
2553 "Generate a unique name suitable for use as a file name."
2554 ;; Include the shell process number and host name
2555 ;; in case there are multiple shells (for same or different user).
2556 ;; Dec 1998: There is a report that some versions of xdvi
2557 ;; don't work with file names that start with #.
2559 (process-id (get-buffer-process "*tex-shell*"))
2560 (subst-char-in-string ?. ?-
(system-name))))
2562 ;; This will perhaps be useful for modifying TEXINPUTS.
2563 ;; Expand each file name, separated by colons, in the string S.
2564 (defun tex-expand-files (s)
2565 (let (elts (start 0))
2566 (while (string-match ":" s start
)
2567 (setq elts
(cons (substring s start
(match-beginning 0)) elts
))
2568 (setq start
(match-end 0)))
2570 (setq elts
(cons (substring s start
) elts
)))
2571 (mapconcat (lambda (elt)
2572 (if (= (length elt
) 0) elt
(expand-file-name elt
)))
2573 (nreverse elts
) ":")))
2575 (defun tex-shell-running ()
2576 (let ((proc (get-process "tex-shell")))
2578 (if (and (eq (process-status proc
) 'run
)
2579 (buffer-live-p (process-buffer proc
)))
2580 ;; return the TeX process on success
2582 ;; get rid of the process permanently
2583 ;; this should get rid of the annoying w32 problem with
2584 ;; dead tex-shell buffer and live process
2585 (delete-process proc
)))))
2587 (defun tex-kill-job ()
2588 "Kill the currently running TeX job."
2590 ;; `quit-process' leads to core dumps of the tex process (except if
2591 ;; coredumpsize has limit 0kb as on many environments). One would
2592 ;; like to use (kill-process proc 'lambda), however that construct
2593 ;; does not work on some systems and kills the shell itself.
2594 (let ((proc (get-process "tex-shell")))
2595 (when proc
(quit-process proc t
))))
2597 (defun tex-recenter-output-buffer (linenum)
2598 "Redisplay buffer of TeX job output so that most recent output can be seen.
2599 The last line of the buffer is displayed on
2600 line LINE of the window, or centered if LINE is nil."
2602 (let ((tex-shell (get-buffer "*tex-shell*"))
2604 (if (null tex-shell
)
2605 (message "No TeX output buffer")
2606 (setq window
(display-buffer tex-shell
))
2607 (save-selected-window
2608 (select-window window
)
2609 (bury-buffer tex-shell
)
2610 (goto-char (point-max))
2611 (recenter (if linenum
2612 (prefix-numeric-value linenum
)
2613 (/ (window-height) 2)))))))
2615 (defun tex-print (&optional alt
)
2616 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2617 Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
2618 is provided, use the alternative command, `tex-alt-dvi-print-command'."
2620 (let ((print-file-name-dvi (tex-append tex-print-file
".dvi"))
2622 (if (and (not (equal (current-buffer) tex-last-buffer-texed
))
2624 ;; Check that this buffer's printed file is up to date.
2625 (file-newer-than-file-p
2626 (setq test-name
(tex-append (buffer-file-name) ".dvi"))
2627 (buffer-file-name)))
2628 (setq print-file-name-dvi test-name
))
2629 (if (not (file-exists-p print-file-name-dvi
))
2630 (error "No appropriate `.dvi' file could be found")
2631 (if (tex-shell-running)
2635 (if alt tex-alt-dvi-print-command tex-dvi-print-command
)
2639 (defun tex-alt-print ()
2640 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2641 Runs the shell command defined by `tex-alt-dvi-print-command'."
2646 "Preview the last `.dvi' file made by running TeX under Emacs.
2647 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2648 The variable `tex-dvi-view-command' specifies the shell command for preview.
2649 You must set that variable yourself before using this command,
2650 because there is no standard value that would generally work."
2652 (or tex-dvi-view-command
2653 (error "You must set `tex-dvi-view-command'"))
2654 ;; Restart the TeX shell if necessary.
2655 (or (tex-shell-running)
2657 (let ((tex-dvi-print-command (eval tex-dvi-view-command
)))
2660 (defun tex-append (file-name suffix
)
2661 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
2662 Pascal-based TeX scans for the first period, C TeX uses the last.
2663 No period is retained immediately before SUFFIX,
2664 so normally SUFFIX starts with one."
2665 (if (stringp file-name
)
2666 (let ((file (file-name-nondirectory file-name
))
2668 ;; Try splitting on last period.
2669 ;; The first-period split can get fooled when two files
2670 ;; named a.tex and a.b.tex are both tex'd;
2671 ;; the last-period split must be right if it matches at all.
2673 (concat (file-name-directory file-name
)
2675 (string-match "\\.[^.]*$" file
))
2677 (if (or (file-exists-p trial-name
)
2678 (file-exists-p (concat trial-name
".aux"))) ;for BibTeX files
2680 ;; Not found, so split on first period.
2681 (concat (file-name-directory file-name
)
2683 (string-match "\\." file
))
2687 (defun tex-show-print-queue ()
2688 "Show the print queue that \\[tex-print] put your job on.
2689 Runs the shell command defined by `tex-show-queue-command'."
2691 (if (tex-shell-running)
2694 (tex-send-command tex-show-queue-command
)
2695 (tex-display-shell))
2697 (defun tex-bibtex-file ()
2698 "Run BibTeX on the current buffer's file."
2700 (if (tex-shell-running)
2703 (let* (shell-dirtrack-verbose
2704 (source-file (expand-file-name (tex-main-file)))
2706 (tex-append (file-name-nondirectory source-file
) ""))
2707 (file-dir (file-name-directory source-file
)))
2708 (tex-send-command tex-shell-cd-command file-dir
)
2709 (tex-send-command tex-bibtex-command tex-out-file
))
2710 (tex-display-shell))
2713 ;;;; LaTeX indentation
2716 (defvar tex-indent-allhanging t
)
2717 (defvar tex-indent-arg
4)
2718 (defvar tex-indent-basic
2)
2719 (defvar tex-indent-item tex-indent-basic
)
2720 (defvar tex-indent-item-re
"\\\\\\(bib\\)?item\\>")
2721 (defvar latex-noindent-environments
'("document"))
2723 (defvar tex-latex-indent-syntax-table
2724 (let ((st (make-syntax-table tex-mode-syntax-table
)))
2725 (modify-syntax-entry ?$
"." st
)
2726 (modify-syntax-entry ?\
( "." st
)
2727 (modify-syntax-entry ?\
) "." st
)
2729 "Syntax table used while computing indentation.")
2731 (defun latex-indent (&optional arg
)
2732 (if (and (eq (get-text-property (line-beginning-position) 'face
)
2735 (with-syntax-table tex-latex-indent-syntax-table
2736 ;; TODO: Rather than ignore $, we should try to be more clever about it.
2740 (latex-find-indent))))
2741 (if (< indent
0) (setq indent
0))
2742 (if (<= (current-column) (current-indentation))
2743 (indent-line-to indent
)
2744 (save-excursion (indent-line-to indent
)))))))
2746 (defcustom latex-indent-within-escaped-parens nil
2747 "Non-nil means add extra indent to text within escaped parens.
2748 When this is non-nil, text within matching pairs of escaped
2749 parens is indented at the column following the open paren. The
2750 default value does not add any extra indent thus providing the
2751 behavior of Emacs 22 and earlier."
2756 (defun latex-find-indent (&optional virtual
)
2757 "Find the proper indentation of text after point.
2758 VIRTUAL if non-nil indicates that we're only trying to find the indentation
2759 in order to determine the indentation of something else.
2760 There might be text before point."
2761 (let ((latex-handle-escaped-parens latex-indent-within-escaped-parens
))
2763 (skip-chars-forward " \t")
2765 ;; Stick the first line at column 0.
2766 (and (= (point-min) (line-beginning-position)) 0)
2767 ;; Trust the current indentation, if such info is applicable.
2768 (and virtual
(save-excursion (skip-chars-backward " \t&") (bolp))
2770 ;; Stick verbatim environments to the left margin.
2771 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2772 (member (match-string 2) tex-verbatim-environments
)
2774 ;; Put leading close-paren where the matching open paren would be.
2776 (and (or (eq (latex-syntax-after) ?\
))
2777 ;; Try to handle escaped close parens but keep
2778 ;; original position if it doesn't work out.
2779 (and latex-handle-escaped-parens
2780 (setq escaped
(looking-at "\\\\\\([])}]\\)"))))
2784 (goto-char (match-beginning 1)))
2785 (latex-skip-close-parens)
2786 (latex-backward-sexp-1)
2787 (latex-find-indent 'virtual
)))))
2788 ;; Default (maybe an argument)
2790 ;; Outdent \item if necessary.
2791 (indent (if (looking-at tex-indent-item-re
) (- tex-indent-item
) 0))
2793 ;; Find the previous point which determines our current indentation.
2796 (latex-backward-sexp-1)
2797 (while (> (current-column) (current-indentation))
2798 (latex-backward-sexp-1)))
2800 (setq up-list-pos
(nth 2 err
))))
2802 ((= (point-min) pos
) 0) ; We're really just indenting the first line.
2803 ((integerp up-list-pos
)
2804 ;; Have to indent relative to the open-paren.
2805 (goto-char up-list-pos
)
2806 (if (and (not tex-indent-allhanging
)
2808 ;; Make sure we're an argument to a macro and
2809 ;; that the macro is at the beginning of a line.
2812 (while (eq (char-syntax (char-after)) ?\
()
2814 (and (eq (char-syntax (char-after)) ?
/)
2815 (progn (skip-chars-backward " \t&")
2818 (> pos
(progn (latex-down-list)
2819 (forward-comment (point-max))
2821 ;; Align with the first element after the open-paren.
2823 ;; We're the first element after a hanging brace.
2824 (goto-char up-list-pos
)
2825 (+ (if (and (looking-at "\\\\begin *{\\([^\n}]+\\)")
2826 (member (match-string 1)
2827 latex-noindent-environments
))
2829 indent
(latex-find-indent 'virtual
))))
2830 ;; We're now at the "beginning" of a line.
2831 ((not (and (not virtual
) (eq (char-after) ?
\\)))
2832 ;; Nothing particular here: just keep the same indentation.
2833 (+ indent
(current-column)))
2834 ;; We're now looking at a macro call.
2835 ((looking-at tex-indent-item-re
)
2836 ;; Indenting relative to an item, have to re-add the outdenting.
2837 (+ indent
(current-column) tex-indent-item
))
2839 (let ((col (current-column)))
2840 (if (or (not (eq (char-syntax (or (char-after pos
) ?\s
)) ?\
())
2841 ;; Can't be an arg if there's an empty line inbetween.
2842 (save-excursion (re-search-forward "^[ \t]*$" pos t
)))
2843 ;; If the first char was not an open-paren, there's
2844 ;; a risk that this is really not an argument to the
2848 (if (< (line-end-position)
2849 (save-excursion (forward-comment (point-max))
2851 ;; we're indenting the first argument.
2852 (min (current-column) (+ tex-indent-arg col
))
2853 (skip-syntax-forward " ")
2854 (current-column)))))))))))
2857 (defun doctex-font-lock-^^A
()
2858 (if (eq (char-after (line-beginning-position)) ?\%
)
2861 (1- (match-beginning 1)) (match-beginning 1)
2863 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2864 ;; The `%' is a single-char comment, which Emacs
2865 ;; syntax-table can't deal with. We could turn it
2866 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2867 ;; Instead, we include it in the ^^A comment.
2868 (string-to-syntax "< b")
2869 (string-to-syntax ">")))
2870 (let ((end (line-end-position)))
2871 (if (< end
(point-max))
2875 (string-to-syntax "> b"))))
2876 (string-to-syntax "< b"))))
2878 (defun doctex-font-lock-syntactic-face-function (state)
2879 ;; Mark DocTeX documentation, which is parsed as a style A comment
2880 ;; starting in column 0.
2881 (if (or (nth 3 state
) (nth 7 state
)
2882 (not (memq (char-before (nth 8 state
))
2884 ;; Anything else is just as for LaTeX.
2885 (tex-font-lock-syntactic-face-function state
)
2886 font-lock-doc-face
))
2889 (defconst doctex-syntax-propertize-rules
2890 (syntax-propertize-precompile-rules
2891 latex-syntax-propertize-rules
2892 ;; For DocTeX comment-in-doc.
2893 ("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A
))))))
2895 (defvar doctex-font-lock-keywords
2896 (append tex-font-lock-keywords
2897 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t
)))))
2900 (define-derived-mode doctex-mode latex-mode
"DocTeX"
2901 "Major mode to edit DocTeX files."
2902 (setq font-lock-defaults
2903 (cons (append (car font-lock-defaults
) '(doctex-font-lock-keywords))
2907 (font-lock-syntactic-face-function
2908 (cons (car x
) 'doctex-font-lock-syntactic-face-function
))
2910 (cdr font-lock-defaults
))))
2911 (set (make-local-variable 'syntax-propertize-function
)
2912 (syntax-propertize-rules doctex-syntax-propertize-rules
)))
2914 (run-hooks 'tex-mode-load-hook
)
2918 ;; arch-tag: c0a680b1-63aa-4547-84b9-4193c29c0080
2919 ;;; tex-mode.el ends here