1 ;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands -*- coding: utf-8 -*-
3 ;; Copyright (C) 1985-1986, 1989, 1992, 1994-1999, 2001-2012
4 ;; Free Software Foundation, Inc.
9 ;; Contributions over the years by William F. Schelter, Dick King,
10 ;; Stephen Gildea, Michael Prange, Jacob Gore, and Edward M. Reingold.
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 ;; Pacify the byte-compiler
37 (defvar font-lock-comment-face
)
38 (defvar font-lock-doc-face
)
43 (defgroup tex-file nil
44 "TeX files and directories."
49 "Running external commands from TeX mode."
53 (defgroup tex-view nil
54 "Viewing and printing TeX files."
59 (defcustom tex-shell-file-name nil
60 "If non-nil, the shell file name to run in the subshell used to run TeX."
61 :type
'(choice (const :tag
"None" nil
)
66 (defcustom tex-directory
(purecopy ".")
67 "Directory in which temporary files are written.
68 You can make this `/tmp' if your TEXINPUTS has no relative directories in it
69 and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
70 `\\input' commands with relative directories."
75 (defcustom tex-first-line-header-regexp nil
76 "Regexp for matching a first line which `tex-region' should include.
77 If this is non-nil, it should be a regular expression string;
78 if it matches the first line of the file,
79 `tex-region' always includes the first line in the TeX run."
80 :type
'(choice (const :tag
"None" nil
)
85 (defcustom tex-main-file nil
86 "The main TeX source file which includes this buffer's file.
87 The command `tex-file' runs TeX on the file specified by `tex-main-file'
88 if the variable is non-nil."
89 :type
'(choice (const :tag
"None" nil
)
94 (defcustom tex-offer-save t
95 "If non-nil, ask about saving modified buffers before \\[tex-file] is run."
100 (defcustom tex-run-command
(purecopy "tex")
101 "Command used to run TeX subjob.
102 TeX Mode sets `tex-command' to this string.
103 See the documentation of that variable."
108 (defcustom latex-run-command
(purecopy "latex")
109 "Command used to run LaTeX subjob.
110 LaTeX Mode sets `tex-command' to this string.
111 See the documentation of that variable."
116 (defcustom slitex-run-command
(purecopy "slitex")
117 "Command used to run SliTeX subjob.
118 SliTeX Mode sets `tex-command' to this string.
119 See the documentation of that variable."
124 (defcustom tex-start-options
(purecopy "")
125 "TeX options to use when starting TeX.
126 These immediately precede the commands in `tex-start-commands'
127 and the input file name, with no separating space and are not shell-quoted.
128 If nil, TeX runs with no options. See the documentation of `tex-command'."
134 (defcustom tex-start-commands
(purecopy "\\nonstopmode\\input")
135 "TeX commands to use when starting TeX.
136 They are shell-quoted and precede the input file name, with a separating space.
137 If nil, no commands are used. See the documentation of `tex-command'."
138 :type
'(radio (const :tag
"Interactive \(nil\)" nil
)
139 (const :tag
"Nonstop \(\"\\nonstopmode\\input\"\)"
140 "\\nonstopmode\\input")
141 (string :tag
"String at your choice"))
145 (defvar latex-standard-block-names
146 '("abstract" "array" "center" "description"
147 "displaymath" "document" "enumerate" "eqnarray"
148 "eqnarray*" "equation" "figure" "figure*"
149 "flushleft" "flushright" "itemize" "letter"
150 "list" "minipage" "picture" "quotation"
151 "quote" "slide" "sloppypar" "tabbing"
152 "table" "table*" "tabular" "tabular*"
153 "thebibliography" "theindex*" "titlepage" "trivlist"
154 "verbatim" "verbatim*" "verse" "math")
155 "Standard LaTeX block names.")
158 (defcustom latex-block-names nil
159 "User defined LaTeX block names.
160 Combined with `latex-standard-block-names' for minibuffer completion."
161 :type
'(repeat string
)
165 (defcustom tex-bibtex-command
(purecopy "bibtex")
166 "Command used by `tex-bibtex-file' to gather bibliographic data.
167 If this string contains an asterisk (`*'), that is replaced by the file name;
168 otherwise, the file name, preceded by blank, is added at the end."
173 (defcustom tex-dvi-print-command
(purecopy "lpr -d")
174 "Command used by \\[tex-print] to print a .dvi file.
175 If this string contains an asterisk (`*'), that is replaced by the file name;
176 otherwise, the file name, preceded by blank, is added at the end."
181 (defcustom tex-alt-dvi-print-command
(purecopy "lpr -d")
182 "Command used by \\[tex-print] with a prefix arg to print a .dvi file.
183 If this string contains an asterisk (`*'), that is replaced by the file name;
184 otherwise, the file name, preceded by blank, is added at the end.
186 If two printers are not enough of a choice, you can set the variable
187 `tex-alt-dvi-print-command' to an expression that asks what you want;
190 (setq tex-alt-dvi-print-command
191 '(format \"lpr -P%s\" (read-string \"Use printer: \")))
193 would tell \\[tex-print] with a prefix argument to ask you which printer to
195 :type
'(choice (string :tag
"Command")
196 (sexp :tag
"Expression"))
200 (defcustom tex-dvi-view-command
202 ((eq window-system
'x
) ,(purecopy "xdvi"))
203 ((eq window-system
'w32
) ,(purecopy "yap"))
204 (t ,(purecopy "dvi2tty * | cat -s")))
205 "Command used by \\[tex-view] to display a `.dvi' file.
206 If it is a string, that specifies the command directly.
207 If this string contains an asterisk (`*'), that is replaced by the file name;
208 otherwise, the file name, preceded by a space, is added at the end.
210 If the value is a form, it is evaluated to get the command to use."
211 :type
'(choice (const nil
) string sexp
)
215 (defcustom tex-show-queue-command
(purecopy "lpq")
216 "Command used by \\[tex-show-print-queue] to show the print queue.
217 Should show the queue(s) that \\[tex-print] puts jobs on."
222 (defcustom tex-default-mode
'latex-mode
223 "Mode to enter for a new file that might be either TeX or LaTeX.
224 This variable is used when it can't be determined whether the file
225 is plain TeX or LaTeX or what because the file contains no commands.
226 Normally set to either `plain-tex-mode' or `latex-mode'."
231 (defcustom tex-open-quote
(purecopy "``")
232 "String inserted by typing \\[tex-insert-quote] to open a quotation."
234 :options
'("``" "\"<" "\"`" "<<" "«")
238 (defcustom tex-close-quote
(purecopy "''")
239 "String inserted by typing \\[tex-insert-quote] to close a quotation."
241 :options
'("''" "\">" "\"'" ">>" "»")
244 (defcustom tex-fontify-script t
245 "If non-nil, fontify subscript and superscript strings."
249 (put 'tex-fontify-script
'safe-local-variable
'booleanp
)
251 (defcustom tex-font-script-display
'(-0.2
0.2)
252 "How much to lower and raise subscript and superscript content.
253 This is a list of two floats. The first is negative and
254 specifies how much subscript is lowered, the second is positive
255 and specifies how much superscript is raised. Heights are
256 measured relative to that of the normal text."
258 :type
'(list (float :tag
"Subscript")
259 (float :tag
"Superscript"))
262 (defvar tex-last-temp-file nil
263 "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
264 Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
265 tex shell terminates.")
267 (defvar tex-command
"tex"
269 If this string contains an asterisk \(`*'\), that is replaced by the file name;
270 otherwise the value of `tex-start-options', the \(shell-quoted\)
271 value of `tex-start-commands', and the file name are added at the end
272 with blanks as separators.
274 In TeX, LaTeX, and SliTeX Mode this variable becomes buffer local.
275 In these modes, use \\[set-variable] if you want to change it for the
278 (defvar tex-trailer nil
279 "String appended after the end of a region sent to TeX by \\[tex-region].")
281 (defvar tex-start-of-header nil
282 "Regular expression used by \\[tex-region] to find start of file's header.")
284 (defvar tex-end-of-header nil
285 "Regular expression used by \\[tex-region] to find end of file's header.")
287 (defvar tex-shell-cd-command
"cd"
288 "Command to give to shell running TeX to change directory.
289 The value of `tex-directory' is appended to this, separated by a space.")
291 (defvar tex-zap-file nil
292 "Temporary file name used for text being sent as input to TeX.
293 Should be a simple file name with no extension or directory specification.")
295 (defvar tex-last-buffer-texed nil
296 "Buffer which was last TeXed.")
298 (defvar tex-print-file nil
299 "File name that \\[tex-print] prints.
300 Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
302 (defvar tex-mode-syntax-table
303 (let ((st (make-syntax-table)))
304 (modify-syntax-entry ?%
"<" st
)
305 (modify-syntax-entry ?
\n ">" st
)
306 (modify-syntax-entry ?
\f ">" st
)
307 (modify-syntax-entry ?\C-
@ "w" st
)
308 (modify-syntax-entry ?
' "w" st
)
309 (modify-syntax-entry ?
@ "_" st
)
310 (modify-syntax-entry ?
* "_" st
)
311 (modify-syntax-entry ?
\t " " st
)
312 ;; ~ is printed by TeX as a space, but it's semantics in the syntax
313 ;; of TeX is not `whitespace' (i.e. it's just like \hspace{foo}).
314 (modify-syntax-entry ?~
"." st
)
315 (modify-syntax-entry ?$
"$$" st
)
316 (modify-syntax-entry ?
\\ "/" st
)
317 (modify-syntax-entry ?
\" "." st
)
318 (modify-syntax-entry ?
& "." st
)
319 (modify-syntax-entry ?_
"." st
)
320 (modify-syntax-entry ?^
"." st
)
322 "Syntax table used while in TeX mode.")
328 (defcustom latex-imenu-indent-string
". "
329 "String to add repeated in front of nested sectional units for Imenu.
330 An alternative value is \" . \", if you use a font with a narrow period."
334 (defvar latex-section-alist
335 '(("part" .
0) ("chapter" .
1)
336 ("section" .
2) ("subsection" .
3)
337 ("subsubsection" .
4)
338 ("paragraph" .
5) ("subparagraph" .
6)))
340 (defvar latex-metasection-list
341 '("documentstyle" "documentclass"
342 "begin{document}" "end{document}"
343 "appendix" "frontmatter" "mainmatter" "backmatter"))
345 (defun latex-imenu-create-index ()
346 "Generate an alist for imenu from a LaTeX buffer."
347 (let ((section-regexp
348 (concat "\\\\" (regexp-opt (mapcar 'car latex-section-alist
) t
)
351 (concat "\\\\" (regexp-opt latex-metasection-list t
)))
352 i0 menu case-fold-search
)
354 ;; Find the top-most level in this file but don't allow it to be
355 ;; any deeper than "section" (which is top-level in an article).
356 (goto-char (point-min))
357 (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t
)
359 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t
)
363 ;; Look for chapters and sections.
364 (goto-char (point-min))
365 (while (search-forward-regexp section-regexp nil t
)
366 (let ((start (match-beginning 0))
368 (i (cdr (assoc (buffer-substring-no-properties
371 latex-section-alist
))))
375 ;; Using sexps allows some use of matching {...} inside
378 (push (cons (concat (apply 'concat
381 latex-imenu-indent-string
))
382 (buffer-substring-no-properties
388 ;; Look for included material.
389 (goto-char (point-min))
390 (while (search-forward-regexp
391 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
392 \[ \t]*{\\([^}\n]+\\)}"
394 (push (cons (concat "<<" (buffer-substring-no-properties
397 (if (= (char-after (match-beginning 1)) ?b
)
403 ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
404 (goto-char (point-min))
405 (while (search-forward-regexp metasection-regexp nil t
)
406 (push (cons "--" (match-beginning 0)) menu
))
408 ;; Sort in increasing buffer position order.
409 (sort menu
(function (lambda (a b
) (< (cdr a
) (cdr b
))))))))
415 (defvar latex-outline-regexp
417 (regexp-opt (append latex-metasection-list
418 (mapcar 'car latex-section-alist
)) t
)))
420 (defun latex-outline-level ()
421 (if (looking-at latex-outline-regexp
)
422 (1+ (or (cdr (assoc (match-string 1) latex-section-alist
)) -
1))
426 ;;;; Font-Lock support
429 ;(defvar tex-font-lock-keywords
430 ; ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
431 ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
432 ; 2 font-lock-function-name-face)
433 ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
434 ; 2 font-lock-constant-face)
435 ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
436 ; ;; not be able to display those fonts.
437 ; ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
438 ; ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
439 ; ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
440 ; ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
441 ; ;; Rewritten and extended for LaTeX2e by Ulrik Dickow <dickow@nbi.dk>.
442 ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
443 ; 2 font-lock-function-name-face)
444 ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
445 ; 2 font-lock-constant-face)
446 ; ("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)" 1 font-lock-function-name-face)
447 ; "\\\\\\([a-zA-Z@]+\\|.\\)"
448 ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
449 ; ;; not be able to display those fonts.
450 ; ;; LaTeX2e: \emph{This is emphasized}.
451 ; ("\\\\emph{\\([^}]+\\)}" 1 'italic keep)
452 ; ;; LaTeX2e: \textbf{This is bold}, \textit{...}, \textsl{...}
453 ; ("\\\\text\\(\\(bf\\)\\|it\\|sl\\){\\([^}]+\\)}"
454 ; 3 (if (match-beginning 2) 'bold 'italic) keep)
455 ; ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
456 ; ("\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)"
457 ; 3 (if (match-beginning 2) 'bold 'italic) keep))
459 ;; Rewritten with the help of Alexandra Bac <abac@welcome.disi.unige.it>.
460 (defconst tex-font-lock-keywords-1
462 (let* (;; Names of commands whose arg should be fontified as heading, etc.
463 (headings (regexp-opt
464 '("title" "begin" "end" "chapter" "part"
465 "section" "subsection" "subsubsection"
466 "paragraph" "subparagraph" "subsubparagraph"
467 "newcommand" "renewcommand" "providecommand"
468 "newenvironment" "renewenvironment"
469 "newtheorem" "renewtheorem")
471 (variables (regexp-opt
472 '("newcounter" "newcounter*" "setcounter" "addtocounter"
473 "setlength" "addtolength" "settowidth")
475 (includes (regexp-opt
476 '("input" "include" "includeonly" "bibliography"
477 "epsfig" "psfig" "epsf" "nofiles" "usepackage"
478 "documentstyle" "documentclass" "verbatiminput"
479 "includegraphics" "includegraphics*")
481 (verbish (regexp-opt '("url" "nolinkurl" "path") t
))
484 (opt " *\\(\\[[^]]*\\] *\\)*")
485 ;; This would allow highlighting \newcommand\CMD but requires
486 ;; adapting subgroup numbers below.
487 ;; (arg "\\(?:{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)\\|\\\\[a-z*]+\\)"))
488 (inbraces-re (lambda (re)
489 (concat "\\(?:[^{}\\]\\|\\\\.\\|" re
"\\)")))
490 (arg (concat "{\\(" (funcall inbraces-re
"{[^}]*}") "+\\)")))
491 `( ;; Highlight $$math$$ and $math$.
492 ;; This is done at the very beginning so as to interact with the other
493 ;; keywords in the same way as comments and strings.
494 (,(concat "\\$\\$?\\(?:[^$\\{}]\\|\\\\.\\|{"
496 (concat "{" (funcall inbraces-re
"{[^}]*}") "*}"))
500 (,(concat slash headings
"\\*?" opt arg
)
501 ;; If ARG ends up matching too much (if the {} don't match, e.g.)
502 ;; jit-lock will do funny things: when updating the buffer
503 ;; the re-highlighting is only done locally so it will just
504 ;; match the local line, but defer-contextually will
505 ;; match more lines at a time, so ARG will end up matching
506 ;; a lot more, which might suddenly include a comment
507 ;; so you get things highlighted bold when you type them
508 ;; but they get turned back to normal a little while later
509 ;; because "there's already a face there".
510 ;; Using `keep' works around this un-intuitive behavior as well
511 ;; as improves the behavior in the very rare case where you do
512 ;; have a comment in ARG.
513 3 font-lock-function-name-face keep
)
514 (,(concat slash
"\\(?:provide\\|\\(?:re\\)?new\\)command\\** *\\(\\\\[A-Za-z@]+\\)")
515 1 font-lock-function-name-face keep
)
517 (,(concat slash variables
" *" arg
) 2 font-lock-variable-name-face
)
519 (,(concat slash includes opt arg
) 3 font-lock-builtin-face
)
520 ;; Verbatim-like args.
521 (,(concat slash verbish opt arg
) 3 'tex-verbatim
)
522 ;; Definitions. I think.
523 ("^[ \t]*\\\\def *\\\\\\(\\(\\w\\|@\\)+\\)"
524 1 font-lock-function-name-face
))))
525 "Subdued expressions to highlight in TeX modes.")
527 (defun tex-font-lock-append-prop (prop)
528 (unless (memq (get-text-property (match-end 1) 'face
)
529 '(font-lock-comment-face tex-verbatim
))
532 (defconst tex-font-lock-keywords-2
533 (append tex-font-lock-keywords-1
536 ;; Names of commands whose arg should be fontified with fonts.
537 (bold (regexp-opt '("textbf" "textsc" "textup"
538 "boldsymbol" "pmb") t
))
539 (italic (regexp-opt '("textit" "textsl" "emph") t
))
540 ;; FIXME: unimplemented yet.
541 ;; (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
543 ;; Names of commands whose arg should be fontified as a citation.
544 (citations (regexp-opt
545 '("label" "ref" "pageref" "vref" "eqref"
546 "cite" "nocite" "index" "glossary" "bibitem"
547 ;; natbib's two variants of \cite:
549 ;; These are text, rather than citations.
550 ;; "caption" "footnote" "footnotemark" "footnotetext"
554 ;; Names of commands that should be fontified.
555 (specials-1 (regexp-opt '("\\" "\\*") t
)) ;; "-"
556 (specials-2 (regexp-opt
557 '("linebreak" "nolinebreak" "pagebreak" "nopagebreak"
558 "newline" "newpage" "clearpage" "cleardoublepage"
559 "displaybreak" "allowdisplaybreaks"
560 "enlargethispage") t
))
561 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
565 (opt " *\\(\\[[^]]*\\] *\\)*")
566 (args "\\(\\(?:[^{}&\\]+\\|\\\\.\\|{[^}]*}\\)+\\)")
567 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
571 (list (concat slash citations opt arg
) 3 'font-lock-constant-face
)
573 ;; Text between `` quotes ''.
574 (cons (concat (regexp-opt `("``" "\"<" "\"`" "<<" "«") t
)
575 "[^'\">{]+" ;a bit pessimistic
576 (regexp-opt `("''" "\">" "\"'" ">>" "»") t
))
577 'font-lock-string-face
)
579 ;; Command names, special and general.
580 (cons (concat slash specials-1
) 'font-lock-warning-face
)
581 (list (concat "\\(" slash specials-2
"\\)\\([^a-zA-Z@]\\|\\'\\)")
582 1 'font-lock-warning-face
)
583 (concat slash general
)
585 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
586 ;; since we might not be able to display those fonts.
587 (list (concat slash bold
" *" arg
) 2
588 '(tex-font-lock-append-prop 'bold
) 'append
)
589 (list (concat slash italic
" *" arg
) 2
590 '(tex-font-lock-append-prop 'italic
) 'append
)
591 ;; (list (concat slash type arg) 2 '(quote bold-italic) 'append)
593 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
594 (list (concat "\\\\\\(em\\|it\\|sl\\)\\>" args
)
595 2 '(tex-font-lock-append-prop 'italic
) 'append
)
596 ;; This is separate from the previous one because of cases like
597 ;; {\em foo {\bf bar} bla} where both match.
598 (list (concat "\\\\\\(bf\\(series\\)?\\)\\>" args
)
599 3 '(tex-font-lock-append-prop 'bold
) 'append
)))))
600 "Gaudy expressions to highlight in TeX modes.")
602 (defun tex-font-lock-suscript (pos)
603 (unless (or (memq (get-text-property pos
'face
)
604 '(font-lock-constant-face font-lock-builtin-face
605 font-lock-comment-face tex-verbatim
))
606 ;; Check for backslash quoting
609 (while (eq (char-before pos
) ?
\\)
610 (setq pos
(1- pos
) odd
(not odd
)))
612 (if (eq (char-after pos
) ?_
)
613 `(face subscript display
(raise ,(car tex-font-script-display
)))
614 `(face superscript display
(raise ,(cadr tex-font-script-display
))))))
616 (defun tex-font-lock-match-suscript (limit)
617 "Match subscript and superscript patterns up to LIMIT."
618 (when (and tex-fontify-script
619 (re-search-forward "[_^] *\\([^\n\\{}]\\|\
620 \\\\\\([a-zA-Z@]+\\|[^ \t\n]\\)\\|\\({\\)\\)" limit t
))
622 (let ((beg (match-beginning 3))
623 (end (save-restriction
624 (narrow-to-region (point-min) limit
)
625 (condition-case nil
(scan-lists (point) 1 1) (error nil
)))))
626 (store-match-data (if end
627 (list (match-beginning 0) end beg end
)
628 (list beg beg beg beg
)))))
631 (defconst tex-font-lock-keywords-3
632 (append tex-font-lock-keywords-2
633 '((tex-font-lock-match-suscript
634 (1 (tex-font-lock-suscript (match-beginning 0)) append
))))
635 "Experimental expressions to highlight in TeX modes.")
637 (defconst tex-font-lock-keywords tex-font-lock-keywords-1
638 "Default expressions to highlight in TeX modes.")
640 (defvar tex-verbatim-environments
641 '("verbatim" "verbatim*"))
642 (put 'tex-verbatim-environments
'safe-local-variable
643 (lambda (x) (null (delq t
(mapcar 'stringp x
)))))
646 (defconst tex-syntax-propertize-rules
647 (syntax-propertize-precompile-rules
648 ("\\\\verb\\**\\([^a-z@*]\\)"
651 (match-beginning 0) (char-after (match-beginning 1))))))))
653 (defconst latex-syntax-propertize-rules
654 (syntax-propertize-precompile-rules
655 tex-syntax-propertize-rules
656 ("\\\\\\(?:end\\|begin\\) *\\({[^\n{}]*}\\)"
658 (tex-env-mark (match-beginning 0)
659 (match-beginning 1) (match-end 1))))))))
661 (defun tex-env-mark (cmd start end
)
662 (when (= cmd
(line-beginning-position))
663 (let ((arg (buffer-substring-no-properties (1+ start
) (1- end
))))
664 (when (member arg tex-verbatim-environments
)
665 (if (eq ?b
(char-after (1+ cmd
)))
667 (put-text-property (line-end-position)
668 (line-beginning-position 2)
669 'syntax-table
(string-to-syntax "< c"))
670 ;; In the case of an empty verbatim env, the \n after the \begin is
671 ;; the same as the \n before the \end. Lucky for us, the "> c"
672 ;; property associated to the \end will be placed afterwards, so it
673 ;; will override the "< c".
674 (put-text-property (1- cmd
) cmd
675 'syntax-table
(string-to-syntax "> c"))
676 ;; The text between \end{verbatim} and \n is ignored, so we'll treat
678 (put-text-property end
(min (1+ end
) (line-end-position))
679 'syntax-table
(string-to-syntax "<"))))))
680 ;; Mark env args for possible electric pairing.
681 (unless (get-char-property (1+ start
) 'text-clones
) ;Already paired-up.
682 (put-text-property start end
'latex-env-pair t
)))
684 (define-minor-mode latex-electric-env-pair-mode
685 "Toggle Latex Electric Env Pair mode.
686 With a prefix argument ARG, enable the mode if ARG is positive,
687 and disable it otherwise. If called from Lisp, enable it if ARG
690 Latex Electric Env Pair mode is a buffer-local minor mode for use
691 with `latex-mode'. When enabled, typing a \\begin or \\end tag
692 automatically inserts its partner."
694 (if latex-electric-env-pair-mode
695 (add-hook 'before-change-functions
696 #'latex-env-before-change nil
'local
)
697 (remove-hook 'before-change-functions
698 #'latex-env-before-change
'local
)))
700 (defun latex-env-before-change (start end
)
701 (when (get-text-property start
'latex-env-pair
)
703 (with-silent-modifications
704 ;; Remove properties even if don't find a pair.
705 (remove-text-properties
706 (previous-single-property-change (1+ start
) 'latex-env-pair
)
707 (next-single-property-change start
'latex-env-pair
)
709 (unless (or (get-char-property start
'text-clones
)
710 (get-char-property (1+ start
) 'text-clones
)
713 (not (re-search-backward
714 "\\\\\\(?:end\\|begi\\(n\\)\\) *{"
715 (line-beginning-position) t
))))
716 (let ((cmd-start (match-beginning 0))
717 (type (match-end 1)) ;nil for \end, else \begin.
718 (arg-start (1- (match-end 0))))
720 (goto-char (match-end 0))
721 (when (and (looking-at "[^\n{}]*}")
722 (> (match-end 0) end
))
723 (let ((arg-end (match-end 0)))
724 (if (null type
) ;\end
725 (progn (goto-char arg-end
)
726 (latex-forward-sexp -
1) (forward-word 1))
727 (goto-char cmd-start
)
728 (latex-forward-sexp 1)
729 (let (forward-sexp-function) (backward-sexp)))
731 (regexp-quote (buffer-substring arg-start arg-end
)))
732 (text-clone-create arg-start arg-end
))))))))
734 (error (message "Error in latex-env-before-change: %s" err
)))))
736 (defun tex-font-lock-unfontify-region (beg end
)
737 (font-lock-default-unfontify-region beg end
)
739 (let ((next (next-single-property-change beg
'display nil end
))
740 (prop (get-text-property beg
'display
)))
741 (if (and (eq (car-safe prop
) 'raise
)
742 (member (car-safe (cdr prop
)) tex-font-script-display
)
744 (put-text-property beg next
'display nil
))
747 (defcustom tex-suscript-height-ratio
0.8
748 "Ratio of subscript/superscript height to that of the preceding text.
749 In nested subscript/superscript, this factor is applied repeatedly,
750 subject to the limit set by `tex-suscript-height-minimum'."
755 (defcustom tex-suscript-height-minimum
0.0
756 "Integer or float limiting the minimum size of subscript/superscript text.
757 An integer is an absolute height in units of 1/10 point, a float
758 is a height relative to that of the default font. Zero means no minimum."
759 :type
'(choice (integer :tag
"Integer height in 1/10 point units")
760 (float :tag
"Fraction of default font height"))
764 (defun tex-suscript-height (height)
765 "Return the integer height of subscript/superscript font in 1/10 points.
766 Not smaller than the value set by `tex-suscript-height-minimum'."
767 (ceiling (max (if (integerp tex-suscript-height-minimum
)
768 tex-suscript-height-minimum
769 ;; For bootstrapping.
771 (* tex-suscript-height-minimum
772 (face-attribute 'default
:height
))
774 ;; NB assumes height is integer.
775 (* height tex-suscript-height-ratio
))))
778 '((t :height tex-suscript-height
)) ;; :raise 0.2
779 "Face used for superscripts."
782 '((t :height tex-suscript-height
)) ;; :raise -0.2
783 "Face used for subscripts."
787 '((t :inherit font-lock-string-face
))
788 "Face used to highlight TeX math expressions."
790 (define-obsolete-face-alias 'tex-math-face
'tex-math
"22.1")
791 (defvar tex-math-face
'tex-math
)
793 (defface tex-verbatim
794 ;; '((t :inherit font-lock-string-face))
795 '((t :family
"courier"))
796 "Face used to highlight TeX verbatim environments."
798 (define-obsolete-face-alias 'tex-verbatim-face
'tex-verbatim
"22.1")
799 (defvar tex-verbatim-face
'tex-verbatim
)
801 (defun tex-font-lock-verb (start delim
)
802 "Place syntax table properties on the \verb construct.
803 START is the position of the \\ and DELIM is the delimiter char."
804 ;; Do nothing if the \verb construct is itself inside a comment or
806 (unless (nth 8 (save-excursion (syntax-ppss start
)))
807 ;; Let's find the end and mark it.
808 (let ((afterdelim (point)))
809 (skip-chars-forward (string ?^ delim
) (line-end-position))
811 ;; "LaTeX Error: \verb ended by end of line."
812 ;; Remove the syntax-table property we've just put on the
813 ;; start-delimiter, so it doesn't spill over subsequent lines.
814 (put-text-property (1- afterdelim
) afterdelim
816 (when (eq (char-syntax (preceding-char)) ?
/)
817 (put-text-property (1- (point)) (point)
818 'syntax-table
(string-to-syntax ".")))
819 (put-text-property (point) (1+ (point))
820 'syntax-table
(string-to-syntax "\""))))))
822 ;; Use string syntax but math face for $...$.
823 (defun tex-font-lock-syntactic-face-function (state)
824 (let ((char (nth 3 state
)))
827 (if (eq 2 (nth 7 state
)) tex-verbatim-face font-lock-comment-face
))
828 ((eq char ?$
) tex-math-face
)
830 (t tex-verbatim-face
))))
833 (defun tex-define-common-keys (keymap)
834 "Define the keys that we want defined both in TeX mode and in the TeX shell."
835 (define-key keymap
"\C-c\C-k" 'tex-kill-job
)
836 (define-key keymap
"\C-c\C-l" 'tex-recenter-output-buffer
)
837 (define-key keymap
"\C-c\C-q" 'tex-show-print-queue
)
838 (define-key keymap
"\C-c\C-p" 'tex-print
)
839 (define-key keymap
"\C-c\C-v" 'tex-view
)
841 (define-key keymap
[menu-bar tex
] (cons "TeX" (make-sparse-keymap "TeX")))
843 (define-key keymap
[menu-bar tex tex-kill-job
]
844 '(menu-item "Tex Kill" tex-kill-job
:enable
(tex-shell-running)))
845 (define-key keymap
[menu-bar tex tex-recenter-output-buffer
]
846 '(menu-item "Tex Recenter" tex-recenter-output-buffer
847 :enable
(get-buffer "*tex-shell*")))
848 (define-key keymap
[menu-bar tex tex-show-print-queue
]
849 '("Show Print Queue" . tex-show-print-queue
))
850 (define-key keymap
[menu-bar tex tex-alt-print
]
851 '(menu-item "Tex Print (alt printer)" tex-alt-print
852 :enable
(stringp tex-print-file
)))
853 (define-key keymap
[menu-bar tex tex-print
]
854 '(menu-item "Tex Print" tex-print
:enable
(stringp tex-print-file
)))
855 (define-key keymap
[menu-bar tex tex-view
]
856 '(menu-item "Tex View" tex-view
:enable
(stringp tex-print-file
))))
859 (let ((map (make-sparse-keymap)))
860 (set-keymap-parent map text-mode-map
)
861 (tex-define-common-keys map
)
862 (define-key map
"\"" 'tex-insert-quote
)
863 (define-key map
"(" 'skeleton-pair-insert-maybe
)
864 (define-key map
"{" 'skeleton-pair-insert-maybe
)
865 (define-key map
"[" 'skeleton-pair-insert-maybe
)
866 (define-key map
"$" 'skeleton-pair-insert-maybe
)
867 (define-key map
"\n" 'tex-terminate-paragraph
)
868 (define-key map
"\M-\r" 'latex-insert-item
)
869 (define-key map
"\C-c}" 'up-list
)
870 (define-key map
"\C-c{" 'tex-insert-braces
)
871 (define-key map
"\C-c\C-r" 'tex-region
)
872 (define-key map
"\C-c\C-b" 'tex-buffer
)
873 (define-key map
"\C-c\C-f" 'tex-file
)
874 (define-key map
"\C-c\C-c" 'tex-compile
)
875 (define-key map
"\C-c\C-i" 'tex-bibtex-file
)
876 (define-key map
"\C-c\C-o" 'latex-insert-block
)
878 ;; Redundant keybindings, for consistency with SGML mode.
879 (define-key map
"\C-c\C-t" 'latex-insert-block
)
880 (define-key map
"\C-c]" 'latex-close-block
)
881 (define-key map
"\C-c/" 'latex-close-block
)
883 (define-key map
"\C-c\C-e" 'latex-close-block
)
884 (define-key map
"\C-c\C-u" 'tex-goto-last-unclosed-latex-block
)
885 (define-key map
"\C-c\C-m" 'tex-feed-input
)
886 (define-key map
[(control return
)] 'tex-feed-input
)
887 (define-key map
[menu-bar tex tex-bibtex-file
]
888 '("BibTeX File" . tex-bibtex-file
))
889 (define-key map
[menu-bar tex tex-validate-region
]
890 '(menu-item "Validate Region" tex-validate-region
:enable mark-active
))
891 (define-key map
[menu-bar tex tex-validate-buffer
]
892 '("Validate Buffer" . tex-validate-buffer
))
893 (define-key map
[menu-bar tex tex-region
]
894 '(menu-item "TeX Region" tex-region
:enable mark-active
))
895 (define-key map
[menu-bar tex tex-buffer
]
896 '("TeX Buffer" . tex-buffer
))
897 (define-key map
[menu-bar tex tex-file
] '("TeX File" . tex-file
))
899 "Keymap shared by TeX modes.")
901 (defvar latex-mode-map
902 (let ((map (make-sparse-keymap)))
903 (set-keymap-parent map tex-mode-map
)
904 (define-key map
"\C-c\C-s" 'latex-split-block
)
906 "Keymap for `latex-mode'. See also `tex-mode-map'.")
908 (defvar plain-tex-mode-map
909 (let ((map (make-sparse-keymap)))
910 (set-keymap-parent map tex-mode-map
)
912 "Keymap for `plain-tex-mode'. See also `tex-mode-map'.")
914 (defvar tex-shell-map
915 (let ((m (make-sparse-keymap)))
916 (set-keymap-parent m shell-mode-map
)
917 (tex-define-common-keys m
)
919 "Keymap for the TeX shell.
920 Inherits `shell-mode-map' with a few additions.")
922 (defvar tex-face-alist
925 (bold-italic .
"{\\bi ") ; hypothetical
926 (underline .
"\\underline{")
927 (default .
"{\\rm "))
928 "Alist of face and TeX font name for facemenu.")
930 (defvar tex-latex-face-alist
931 `((italic .
"{\\em ")
933 "Alist of face and LaTeX font name for facemenu.")
935 (defun tex-facemenu-add-face-function (face end
)
936 (or (cdr (assq face tex-face-alist
))
937 (or (and (consp face
)
940 (eq major-mode
'latex-mode
)
941 ;; This actually requires the `color' LaTeX package.
942 (cond ((eq (caar face
) :foreground
)
943 (format "{\\color{%s} " (cadr (car face
))))
944 ((eq (caar face
) :background
)
945 (format "\\colorbox{%s}{" (cadr (car face
))))))
946 (error "Face %s not configured for %s mode" face mode-name
))))
948 ;; This would be a lot simpler if we just used a regexp search,
949 ;; but then it would be too slow.
950 (defun tex-guess-mode ()
951 (let ((mode tex-default-mode
) slash comment
)
953 (goto-char (point-min))
954 (while (and (setq slash
(search-forward "\\" nil t
))
955 (setq comment
(let ((search-end (point)))
958 (search-forward "%" search-end t
))))))
959 (when (and slash
(not comment
))
964 (regexp-opt '("documentstyle" "documentclass"
965 "begin" "subsection" "section"
966 "part" "chapter" "newcommand"
967 "renewcommand" "RequirePackage") 'words
)
968 "\\|NeedsTeXFormat{LaTeX")))
970 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
971 ;; SliTeX is almost never used any more nowadays.
972 (tex-executable-exists-p slitex-run-command
))
978 ;; `tex-mode' plays two roles: it's the parent of several sub-modes
979 ;; but it's also the function that chooses between those submodes.
980 ;; To tell the difference between those two cases where the function
981 ;; might be called, we check `delay-mode-hooks'.
982 (define-derived-mode tex-mode text-mode
"generic-TeX"
983 (tex-common-initialization))
984 ;; We now move the function and define it again. This gives a warning
985 ;; in the byte-compiler :-( but it's difficult to avoid because
986 ;; `define-derived-mode' will necessarily define the function once
987 ;; and we need to define it a second time for `autoload' to get the
989 (defalias 'tex-mode-internal
(symbol-function 'tex-mode
))
991 ;; Suppress the byte-compiler warning about multiple definitions.
992 ;; This is a) ugly, and b) cheating, but this was the last
993 ;; remaining warning from byte-compiling all of Emacs...
995 (setq byte-compile-function-environment
996 (delq (assq 'tex-mode byte-compile-function-environment
)
997 byte-compile-function-environment
)))
1001 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
1002 Tries to determine (by looking at the beginning of the file) whether
1003 this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
1004 `latex-mode', or `slitex-mode', respectively. If it cannot be determined,
1005 such as if there are no commands in the file, the value of `tex-default-mode'
1006 says which mode to use."
1008 (if delay-mode-hooks
1009 ;; We're called from one of the children already.
1013 ;; The following three autoloaded aliases appear to conflict with
1014 ;; AUCTeX. However, even though AUCTeX uses the mixed case variants
1015 ;; for all mode relevant variables and hooks, the invocation function
1016 ;; and setting of `major-mode' themselves need to be lowercase for
1017 ;; AUCTeX to provide a fully functional user-level replacement. So
1018 ;; these aliases should remain as they are, in particular since AUCTeX
1019 ;; users are likely to use them.
1022 (defalias 'TeX-mode
'tex-mode
)
1024 (defalias 'plain-TeX-mode
'plain-tex-mode
)
1026 (defalias 'LaTeX-mode
'latex-mode
)
1029 (define-derived-mode plain-tex-mode tex-mode
"TeX"
1030 "Major mode for editing files of input for plain TeX.
1031 Makes $ and } display the characters they match.
1032 Makes \" insert `` when it seems to be the beginning of a quotation,
1033 and '' when it appears to be the end; it inserts \" only after a \\.
1035 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
1036 copied from the top of the file (containing macro definitions, etc.),
1037 running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
1038 \\[tex-file] saves the buffer and then processes the file.
1039 \\[tex-print] prints the .dvi file made by any of these.
1040 \\[tex-view] previews the .dvi file made by any of these.
1041 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1043 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1044 mismatched $'s or braces.
1047 \\{plain-tex-mode-map}
1051 Command string used by \\[tex-region] or \\[tex-buffer].
1053 Directory in which to create temporary files for TeX jobs
1054 run by \\[tex-region] or \\[tex-buffer].
1055 tex-dvi-print-command
1056 Command string used by \\[tex-print] to print a .dvi file.
1057 tex-alt-dvi-print-command
1058 Alternative command string used by \\[tex-print] (when given a prefix
1059 argument) to print a .dvi file.
1060 tex-dvi-view-command
1061 Command string used by \\[tex-view] to preview a .dvi file.
1062 tex-show-queue-command
1063 Command string used by \\[tex-show-print-queue] to show the print
1064 queue that \\[tex-print] put your job on.
1066 Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
1067 `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
1068 special subshell is initiated, the hook `tex-shell-hook' is run."
1069 (set (make-local-variable 'tex-command
) tex-run-command
)
1070 (set (make-local-variable 'tex-start-of-header
) "%\\*\\*start of header")
1071 (set (make-local-variable 'tex-end-of-header
) "%\\*\\*end of header")
1072 (set (make-local-variable 'tex-trailer
) "\\bye\n"))
1075 (define-derived-mode latex-mode tex-mode
"LaTeX"
1076 "Major mode for editing files of input for LaTeX.
1077 Makes $ and } display the characters they match.
1078 Makes \" insert `` when it seems to be the beginning of a quotation,
1079 and '' when it appears to be the end; it inserts \" only after a \\.
1081 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
1082 copied from the top of the file (containing \\documentstyle, etc.),
1083 running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
1084 \\[tex-file] saves the buffer and then processes the file.
1085 \\[tex-print] prints the .dvi file made by any of these.
1086 \\[tex-view] previews the .dvi file made by any of these.
1087 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1089 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1090 mismatched $'s or braces.
1097 Command string used by \\[tex-region] or \\[tex-buffer].
1099 Directory in which to create temporary files for LaTeX jobs
1100 run by \\[tex-region] or \\[tex-buffer].
1101 tex-dvi-print-command
1102 Command string used by \\[tex-print] to print a .dvi file.
1103 tex-alt-dvi-print-command
1104 Alternative command string used by \\[tex-print] (when given a prefix
1105 argument) to print a .dvi file.
1106 tex-dvi-view-command
1107 Command string used by \\[tex-view] to preview a .dvi file.
1108 tex-show-queue-command
1109 Command string used by \\[tex-show-print-queue] to show the print
1110 queue that \\[tex-print] put your job on.
1112 Entering Latex mode runs the hook `text-mode-hook', then
1113 `tex-mode-hook', and finally `latex-mode-hook'. When the special
1114 subshell is initiated, `tex-shell-hook' is run."
1115 (set (make-local-variable 'tex-command
) latex-run-command
)
1116 (set (make-local-variable 'tex-start-of-header
)
1117 "\\\\document\\(style\\|class\\)")
1118 (set (make-local-variable 'tex-end-of-header
) "\\\\begin\\s-*{document}")
1119 (set (make-local-variable 'tex-trailer
) "\\end{document}\n")
1120 ;; A line containing just $$ is treated as a paragraph separator.
1121 ;; A line starting with $$ starts a paragraph,
1122 ;; but does not separate paragraphs if it has more stuff on it.
1123 (setq paragraph-start
1124 (concat "[ \t]*\\(\\$\\$\\|"
1126 "\\\\" (regexp-opt (append
1127 (mapcar 'car latex-section-alist
)
1128 '("begin" "label" "end"
1129 "item" "bibitem" "newline" "noindent"
1130 "newpage" "footnote" "marginpar"
1131 "parbox" "caption")) t
)
1132 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t
)
1134 (setq paragraph-separate
1135 (concat "[\f%]\\|[ \t]*\\($\\|"
1137 "\\\\" (regexp-opt (append
1138 (mapcar 'car latex-section-alist
)
1139 '("begin" "label" "end" )) t
)
1140 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
1141 "noindent" "newpage" "footnote"
1142 "marginpar" "parbox" "caption"))
1143 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
1144 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
1145 (set (make-local-variable 'imenu-create-index-function
)
1146 'latex-imenu-create-index
)
1147 (set (make-local-variable 'tex-face-alist
) tex-latex-face-alist
)
1148 (add-hook 'fill-nobreak-predicate
'latex-fill-nobreak-predicate nil t
)
1149 (set (make-local-variable 'indent-line-function
) 'latex-indent
)
1150 (set (make-local-variable 'fill-indent-according-to-mode
) t
)
1151 (add-hook 'completion-at-point-functions
1152 'latex-complete-data nil
'local
)
1153 (set (make-local-variable 'outline-regexp
) latex-outline-regexp
)
1154 (set (make-local-variable 'outline-level
) 'latex-outline-level
)
1155 (set (make-local-variable 'forward-sexp-function
) 'latex-forward-sexp
)
1156 (set (make-local-variable 'skeleton-end-hook
) nil
))
1159 (define-derived-mode slitex-mode latex-mode
"SliTeX"
1160 "Major mode for editing files of input for SliTeX.
1161 Makes $ and } display the characters they match.
1162 Makes \" insert `` when it seems to be the beginning of a quotation,
1163 and '' when it appears to be the end; it inserts \" only after a \\.
1165 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
1166 copied from the top of the file (containing \\documentstyle, etc.),
1167 running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
1168 \\[tex-file] saves the buffer and then processes the file.
1169 \\[tex-print] prints the .dvi file made by any of these.
1170 \\[tex-view] previews the .dvi file made by any of these.
1171 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1173 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1174 mismatched $'s or braces.
1181 Command string used by \\[tex-region] or \\[tex-buffer].
1183 Directory in which to create temporary files for SliTeX jobs
1184 run by \\[tex-region] or \\[tex-buffer].
1185 tex-dvi-print-command
1186 Command string used by \\[tex-print] to print a .dvi file.
1187 tex-alt-dvi-print-command
1188 Alternative command string used by \\[tex-print] (when given a prefix
1189 argument) to print a .dvi file.
1190 tex-dvi-view-command
1191 Command string used by \\[tex-view] to preview a .dvi file.
1192 tex-show-queue-command
1193 Command string used by \\[tex-show-print-queue] to show the print
1194 queue that \\[tex-print] put your job on.
1196 Entering SliTeX mode runs the hook `text-mode-hook', then the hook
1197 `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
1198 `slitex-mode-hook'. When the special subshell is initiated, the hook
1199 `tex-shell-hook' is run."
1200 (setq tex-command slitex-run-command
)
1201 (setq tex-start-of-header
"\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
1203 (defun tex-common-initialization ()
1204 ;; Regexp isearch should accept newline and formfeed as whitespace.
1205 (set (make-local-variable 'search-whitespace-regexp
) "[ \t\r\n\f]+")
1206 ;; A line containing just $$ is treated as a paragraph separator.
1207 (set (make-local-variable 'paragraph-start
)
1208 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
1209 ;; A line starting with $$ starts a paragraph,
1210 ;; but does not separate paragraphs if it has more stuff on it.
1211 (set (make-local-variable 'paragraph-separate
)
1212 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
1213 (set (make-local-variable 'comment-start
) "%")
1214 (set (make-local-variable 'comment-add
) 1)
1215 (set (make-local-variable 'comment-start-skip
)
1216 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
1217 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
1218 (set (make-local-variable 'compare-windows-whitespace
)
1219 'tex-categorize-whitespace
)
1220 (set (make-local-variable 'facemenu-add-face-function
)
1221 'tex-facemenu-add-face-function
)
1222 (set (make-local-variable 'facemenu-end-add-face
) "}")
1223 (set (make-local-variable 'facemenu-remove-face-function
) t
)
1224 (set (make-local-variable 'font-lock-defaults
)
1225 '((tex-font-lock-keywords tex-font-lock-keywords-1
1226 tex-font-lock-keywords-2 tex-font-lock-keywords-3
)
1228 ;; Who ever uses that anyway ???
1229 (font-lock-mark-block-function . mark-paragraph
)
1230 (font-lock-syntactic-face-function
1231 . tex-font-lock-syntactic-face-function
)
1232 (font-lock-unfontify-region-function
1233 . tex-font-lock-unfontify-region
)))
1234 (set (make-local-variable 'syntax-propertize-function
)
1235 (syntax-propertize-rules latex-syntax-propertize-rules
))
1236 ;; TABs in verbatim environments don't do what you think.
1237 (set (make-local-variable 'indent-tabs-mode
) nil
)
1238 ;; Other vars that should be buffer-local.
1239 (make-local-variable 'tex-command
)
1240 (make-local-variable 'tex-start-of-header
)
1241 (make-local-variable 'tex-end-of-header
)
1242 (make-local-variable 'tex-trailer
))
1244 (defun tex-categorize-whitespace (backward-limit)
1245 ;; compare-windows-whitespace is set to this.
1246 ;; This is basically a finite-state machine.
1247 ;; Returns a symbol telling how TeX would treat
1248 ;; the whitespace we are looking at: null, space, or par.
1249 (let ((category 'null
)
1251 (skip-chars-backward " \t\n\f" backward-limit
)
1253 (cond ((looking-at "[ \t]+")
1254 (goto-char (match-end 0))
1255 (if (eq category
'null
)
1256 (setq category
'space
)))
1258 (cond ((eq category
'newline
)
1259 (setq category
'par
)
1260 (setq not-finished nil
))
1262 (setq category
'newline
) ;a strictly internal state
1263 (goto-char (match-end 0)))))
1265 (setq category
'par
)
1266 (setq not-finished nil
))
1268 (setq not-finished nil
))))
1269 (skip-chars-forward " \t\n\f")
1270 (if (eq category
'newline
)
1271 'space
;TeX doesn't distinguish
1274 (defun tex-insert-quote (arg)
1275 "Insert the appropriate quote marks for TeX.
1276 Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
1277 \(normally '') depending on the context. With prefix argument, always
1278 inserts \" characters."
1280 (if (or arg
(memq (char-syntax (preceding-char)) '(?
/ ?
\\))
1281 (eq (get-text-property (point) 'face
) 'tex-verbatim
)
1283 (backward-char (length tex-open-quote
))
1284 (when (or (looking-at (regexp-quote tex-open-quote
))
1285 (looking-at (regexp-quote tex-close-quote
)))
1286 (delete-char (length tex-open-quote
))
1288 (self-insert-command (prefix-numeric-value arg
))
1289 (insert (if (or (memq (char-syntax (preceding-char)) '(?\
( ?
> ?\s
))
1290 (memq (preceding-char) '(?~
)))
1291 tex-open-quote tex-close-quote
))))
1293 (defun tex-validate-buffer ()
1294 "Check current buffer for paragraphs containing mismatched braces or $s.
1295 Their positions are recorded in the buffer `*Occur*'.
1296 To find a particular invalidity from `*Occur*', switch to that buffer
1297 and type C-c C-c or click with mouse-2
1298 on the line for the invalidity you want to see."
1300 (let ((buffer (current-buffer))
1301 (prevpos (point-min))
1304 (with-output-to-temp-buffer "*Occur*"
1305 (princ "Mismatches:\n")
1306 (with-current-buffer standard-output
1308 ;; This won't actually work...Really, this whole thing should
1309 ;; be rewritten instead of being a hack on top of occur.
1310 (setq occur-revert-arguments
(list nil
0 (list buffer
))))
1312 (goto-char (point-max))
1313 ;; Do a little shimmy to place point at the end of the last
1314 ;; "real" paragraph. Need to avoid validating across an \end,
1315 ;; because that blows up latex-forward-sexp.
1316 (backward-paragraph)
1319 ;; Scan the previous paragraph for invalidities.
1320 (backward-paragraph)
1322 (or (tex-validate-region (point) (save-excursion
1325 (let ((end (line-beginning-position 2))
1328 (setq start
(point))
1329 ;; Keep track of line number as we scan,
1330 ;; in a cumulative fashion.
1332 (setq linenum
(- linenum
1333 (count-lines prevpos
(point))))
1334 (setq linenum
(1+ (count-lines 1 start
))))
1335 (setq prevpos
(point))
1336 ;; Mention this mismatch in *Occur*.
1337 ;; Since we scan from end of buffer to beginning,
1338 ;; add each mismatch at the beginning of *Occur*.
1340 (setq tem
(point-marker))
1341 (set-buffer standard-output
)
1342 (goto-char (point-min))
1343 ;; Skip "Mismatches:" header line.
1345 (setq num-matches
(1+ num-matches
))
1346 (insert-buffer-substring buffer start end
)
1347 (let (text-beg (text-end (point-marker)))
1348 (forward-char (- start end
))
1349 (setq text-beg
(point-marker))
1350 (insert (format "%3d: " linenum
))
1351 (add-text-properties
1352 text-beg
(- text-end
1)
1353 '(mouse-face highlight
1355 "mouse-2: go to this invalidity"))
1356 (put-text-property text-beg
(- text-end
1)
1357 'occur-target tem
))))))))
1358 (with-current-buffer standard-output
1359 (let ((no-matches (zerop num-matches
)))
1362 (if (called-interactively-p 'interactive
)
1363 (message (cond (no-matches "No mismatches found")
1364 ((= num-matches
1) "1 mismatch found")
1365 (t "%d mismatches found"))
1368 (defun tex-validate-region (start end
)
1369 "Check for mismatched braces or $'s in region.
1370 Returns t if no mismatches. Returns nil and moves point to suspect
1371 area if a mismatch is found."
1373 (let ((failure-point nil
) (max-possible-sexps (- end start
)))
1377 (narrow-to-region start end
)
1378 ;; First check that the open and close parens balance in numbers.
1380 (while (and (not (eobp))
1381 (<= 0 (setq max-possible-sexps
1382 (1- max-possible-sexps
))))
1384 ;; Now check that like matches like.
1386 (while (re-search-forward "\\s(" nil t
)
1388 (let ((pos (match-beginning 0)))
1390 (skip-chars-backward "\\\\") ; escaped parens
1392 (or (eq (preceding-char) (cdr (syntax-after pos
)))
1393 (eq (char-after pos
) (cdr (syntax-after (1- (point)))))
1394 (error "Mismatched parentheses"))))))
1396 (skip-syntax-forward " .>")
1397 (setq failure-point
(point)))))
1398 (if failure-point
(goto-char failure-point
))
1399 (not failure-point
)))
1401 (defun tex-terminate-paragraph (inhibit-validation)
1402 "Insert two newlines, breaking a paragraph for TeX.
1403 Check for mismatched braces or $s in paragraph being terminated.
1404 A prefix arg inhibits the checking."
1406 (or inhibit-validation
1408 ;; For the purposes of this, a "paragraph" is a block of text
1409 ;; wherein all the brackets etc are expected to be balanced. It
1410 ;; may start after a blank line (ie a "proper" paragraph), or
1411 ;; a begin{} or end{} block, etc.
1412 (tex-validate-region
1414 (backward-paragraph)
1417 (message "Paragraph being closed appears to contain a mismatch"))
1420 (define-skeleton tex-insert-braces
1421 "Make a pair of braces and be poised to type inside of them."
1425 ;; This function is used as the value of fill-nobreak-predicate
1426 ;; in LaTeX mode. Its job is to prevent line-breaking inside
1427 ;; of a \verb construct.
1428 (defun latex-fill-nobreak-predicate ()
1430 (skip-chars-backward " ")
1431 ;; Don't break after \ since `\ ' has special meaning.
1432 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?
\\ ?
/)))
1433 (let ((opoint (point))
1436 (while (re-search-forward "\\\\verb\\(.\\)" opoint t
)
1437 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t
)
1441 (defvar latex-block-default
"enumerate")
1443 (defvar latex-block-args-alist
1444 '(("array" nil ?\
{ (skeleton-read "Format: ") ?\
})
1445 ("tabular" nil ?\
{ (skeleton-read "Format: ") ?\
})
1446 ("minipage" nil ?\
{ (skeleton-read "Size: ") ?\
})
1447 ("picture" nil ?\
( (skeleton-read "SizeX,SizeY: ") ?\
))
1448 ;; FIXME: This is right for Prosper, but not for seminar.
1449 ;; ("slide" nil ?\{ (skeleton-read "Title: ") ?\})
1451 "Skeleton element to use for arguments to particular environments.
1452 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1453 the name of the environment and SKEL-ELEM is an element to use in
1454 a skeleton (see `skeleton-insert').")
1456 (defvar latex-block-body-alist
1457 '(("enumerate" nil
'(latex-insert-item) > _
)
1458 ("itemize" nil
'(latex-insert-item) > _
)
1459 ("table" nil
"\\caption{" > (skeleton-read "Caption: ") "}" > \n
1460 '(if (and (boundp 'reftex-mode
) reftex-mode
) (reftex-label "table"))
1462 ("figure" nil
> _
\n "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1463 '(if (and (boundp 'reftex-mode
) reftex-mode
) (reftex-label "table"))))
1464 "Skeleton element to use for the body of particular environments.
1465 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1466 the name of the environment and SKEL-ELEM is an element to use in
1467 a skeleton (see `skeleton-insert').")
1469 ;; Like tex-insert-braces, but for LaTeX.
1470 (defalias 'tex-latex-block
'latex-insert-block
)
1471 (define-skeleton latex-insert-block
1472 "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
1473 Puts point on a blank line between them."
1474 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1475 latex-block-default
)
1476 (append latex-block-names
1477 latex-standard-block-names
)
1478 nil nil nil nil latex-block-default
)))
1479 (setq latex-block-default choice
)
1480 (unless (or (member choice latex-standard-block-names
)
1481 (member choice latex-block-names
))
1482 ;; Remember new block names for later completion.
1483 (push choice latex-block-names
))
1485 \n "\\begin{" str
"}"
1486 (cdr (assoc str latex-block-args-alist
))
1487 > \n (or (cdr (assoc str latex-block-body-alist
)) '(nil > _
))
1489 "\\end{" str
"}" > \n)
1491 (define-skeleton latex-insert-item
1492 "Insert a \item macro."
1497 ;;;; LaTeX completion.
1499 (defvar latex-complete-bibtex-cache nil
)
1501 (define-obsolete-function-alias 'latex-string-prefix-p
1502 'string-prefix-p
"24.3")
1504 (defvar bibtex-reference-key
)
1505 (declare-function reftex-get-bibfile-list
"reftex-cite.el" ())
1507 (defun latex-complete-bibtex-keys ()
1508 (when (bound-and-true-p reftex-mode
)
1509 (lambda (key pred action
)
1510 (let ((re (concat "^[ \t]*@\\([a-zA-Z]+\\)[ \t\n]*\\([{(][ \t\n]*\\)"
1511 (regexp-quote key
)))
1512 (files (reftex-get-bibfile-list))
1514 (if (and (eq (car latex-complete-bibtex-cache
)
1515 (reftex-get-bibfile-list))
1516 (string-prefix-p (nth 1 latex-complete-bibtex-cache
)
1519 (setq keys
(nth 2 latex-complete-bibtex-cache
))
1520 (dolist (file files
)
1521 (with-current-buffer (find-file-noselect file
)
1522 (goto-char (point-min))
1523 (while (re-search-forward re nil t
)
1524 (goto-char (match-end 2))
1525 (when (and (not (member-ignore-case (match-string 1)
1526 '("c" "comment" "string")))
1527 (looking-at bibtex-reference-key
))
1528 (push (match-string-no-properties 0) keys
)))))
1530 (set (make-local-variable 'latex-complete-bibtex-cache
)
1531 (list files key keys
)))
1532 (complete-with-action action keys key pred
)))))
1534 (defun latex-complete-envnames ()
1535 (append latex-block-names latex-standard-block-names
))
1537 (defun latex-complete-refkeys ()
1538 (when (boundp 'reftex-docstruct-symbol
)
1539 (symbol-value reftex-docstruct-symbol
)))
1541 (defvar latex-complete-alist
1542 ;; TODO: Add \begin, \end, \ref, ...
1543 '(("\\`\\\\\\(short\\)?cite\\'" . latex-complete-bibtex-keys
)
1544 ("\\`\\\\\\(begin\\|end\\)\\'" . latex-complete-envnames
)
1545 ("\\`\\\\[vf]?ref\\'" . latex-complete-refkeys
)))
1547 (defun latex-complete-data ()
1548 "Get completion-data at point."
1551 (skip-chars-backward "^ {}\n\t\\\\")
1552 (pcase (char-before)
1553 ((or `nil ?\s ?
\n ?
\t ?\
}) nil
)
1555 ;; TODO: Complete commands.
1558 ;; Complete args to commands.
1562 (skip-chars-backward " \n")
1563 (buffer-substring (point)
1565 (skip-chars-backward "a-zA-Z@*")
1566 (let ((n (skip-chars-backward "\\\\")))
1567 (forward-char (* 2 (/ n
2))))
1570 (_ (progn (goto-char pt
) (skip-chars-backward "^," start
)))
1572 (_ (progn (goto-char pt
) (skip-chars-forward "^, {}\n\t\\\\")))
1576 (let ((f (lambda () t
)))
1577 (dolist (comp latex-complete-alist
)
1578 (if (string-match (car comp
) cmd
)
1579 (setq f
(cdr comp
))))
1584 (list comp-beg comp-end table
))))))))
1587 ;;;; LaTeX syntax navigation
1590 (defmacro tex-search-noncomment
(&rest body
)
1591 "Execute BODY as long as it return non-nil and point is in a comment.
1592 Return the value returned by the last execution of BODY."
1594 (let ((res-sym (make-symbol "result")))
1597 (and (setq ,res-sym
(progn ,@body
))
1598 (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
1601 (defun tex-last-unended-begin ()
1602 "Leave point at the beginning of the last `\\begin{...}' that is unended."
1604 (while (and (tex-search-noncomment
1605 (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
1606 (looking-at "\\\\end"))
1607 (tex-last-unended-begin))
1608 (search-failed (error "Couldn't find unended \\begin"))))
1610 (defun tex-next-unmatched-end ()
1611 "Leave point at the end of the next `\\end' that is unmatched."
1612 (while (and (tex-search-noncomment
1613 (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
1614 (save-excursion (goto-char (match-beginning 0))
1615 (looking-at "\\\\begin")))
1616 (tex-next-unmatched-end)))
1618 (defun tex-next-unmatched-eparen (otype)
1619 "Leave point after the next unmatched escaped closing parenthesis.
1620 The string OTYPE is an opening parenthesis type: `(', `{', or `['."
1622 (let ((ctype (char-to-string (cdr (aref (syntax-table)
1623 (string-to-char otype
))))))
1624 (while (and (tex-search-noncomment
1625 (re-search-forward (format "\\\\[%s%s]" ctype otype
)))
1627 (goto-char (match-beginning 0))
1628 (looking-at (format "\\\\%s" (regexp-quote otype
)))))
1629 (tex-next-unmatched-eparen otype
)))
1630 (wrong-type-argument (error "Unknown opening parenthesis type: %s" otype
))
1631 (search-failed (error "Couldn't find closing escaped paren"))))
1633 (defun tex-last-unended-eparen (ctype)
1634 "Leave point at the start of the last unended escaped opening parenthesis.
1635 The string CTYPE is a closing parenthesis type: `)', `}', or `]'."
1637 (let ((otype (char-to-string (cdr (aref (syntax-table)
1638 (string-to-char ctype
))))))
1639 (while (and (tex-search-noncomment
1640 (re-search-backward (format "\\\\[%s%s]" ctype otype
)))
1641 (looking-at (format "\\\\%s" (regexp-quote ctype
))))
1642 (tex-last-unended-eparen ctype
)))
1643 (wrong-type-argument (error "Unknown opening parenthesis type: %s" ctype
))
1644 (search-failed (error "Couldn't find unended escaped paren"))))
1646 (defun tex-goto-last-unclosed-latex-block ()
1647 "Move point to the last unclosed \\begin{...}.
1648 Mark is left at original location."
1652 (tex-last-unended-begin)
1653 (setq spot
(point)))
1657 (defvar latex-handle-escaped-parens t
)
1659 ;; Don't think this one actually _needs_ (for the purposes of
1660 ;; tex-mode) to handle escaped parens.
1661 ;; Does not handle escaped parens when latex-handle-escaped-parens is nil.
1662 (defun latex-backward-sexp-1 ()
1663 "Like (backward-sexp 1) but aware of multi-char elements and escaped parens."
1665 (forward-sexp-function))
1668 (if latex-handle-escaped-parens
1669 "\\\\\\(begin\\>\\|[[({]\\)"
1672 (list "Containing expression ends prematurely"
1673 (point) (prog1 (point) (goto-char pos
)))))
1674 ((and latex-handle-escaped-parens
1675 (looking-at "\\\\\\([])}]\\)"))
1676 (tex-last-unended-eparen (match-string 1)))
1677 ((eq (char-after) ?
{)
1678 (let ((newpos (point)))
1679 (when (ignore-errors (backward-sexp 1) t
)
1680 (if (or (looking-at "\\\\end\\>")
1681 ;; In case the \\ ends a verbatim section.
1682 (and (looking-at "end\\>") (eq (char-before) ?
\\)))
1683 (tex-last-unended-begin)
1684 (goto-char newpos
))))))))
1686 ;; Note this does not handle things like mismatched brackets inside
1687 ;; begin/end blocks.
1688 ;; Needs to handle escaped parens for tex-validate-*.
1689 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2007-09/msg00038.html
1690 ;; Does not handle escaped parens when latex-handle-escaped-parens is nil.
1691 (defun latex-forward-sexp-1 ()
1692 "Like (forward-sexp 1) but aware of multi-char elements and escaped parens."
1694 (forward-sexp-function))
1696 (let ((newpos (point)))
1697 (skip-syntax-backward "/w")
1699 ((looking-at "\\\\end\\>")
1701 (list "Containing expression ends prematurely"
1704 (progn (ignore-errors (forward-sexp 2)) (point))
1706 ((looking-at "\\\\begin\\>")
1707 (goto-char (match-end 0))
1708 (tex-next-unmatched-end))
1709 ;; A better way to handle this, \( .. \) etc, is probably to
1710 ;; temporarily change the syntax of the \ in \( to punctuation.
1711 ((and latex-handle-escaped-parens
1712 (looking-back "\\\\[])}]"))
1714 (list "Containing expression ends prematurely"
1715 (- (point) 2) (prog1 (point)
1717 ((and latex-handle-escaped-parens
1718 (looking-back "\\\\\\([({[]\\)"))
1719 (tex-next-unmatched-eparen (match-string 1)))
1720 (t (goto-char newpos
))))))
1722 (defun latex-forward-sexp (&optional arg
)
1723 "Like `forward-sexp' but aware of multi-char elements and escaped parens."
1725 (unless arg
(setq arg
1))
1729 (while (and (/= (point) opoint
)
1731 (setq opoint
(point))
1734 (progn (latex-forward-sexp-1) (1- arg
))
1735 (progn (latex-backward-sexp-1) (1+ arg
)))))
1738 (signal (car err
) (cdr err
))))))
1740 (defun latex-syntax-after ()
1741 "Like (char-syntax (char-after)) but aware of multi-char elements."
1742 (if (looking-at "\\\\end\\>") ?\
) (char-syntax (following-char))))
1744 (defun latex-skip-close-parens ()
1745 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1746 (let ((forward-sexp-function nil
))
1747 (while (progn (skip-syntax-forward " )")
1748 (looking-at "\\\\end\\>"))
1751 (defun latex-down-list ()
1752 "Like (down-list 1) but aware of multi-char elements."
1753 (forward-comment (point-max))
1754 (let ((forward-sexp-function nil
))
1755 (if (not (looking-at "\\\\begin\\>"))
1759 (while (looking-at "[ \t]*[[{(]")
1760 (with-syntax-table tex-mode-syntax-table
1763 (defalias 'tex-close-latex-block
'latex-close-block
)
1764 (define-skeleton latex-close-block
1765 "Create an \\end{...} to match the last unclosed \\begin{...}."
1767 (tex-last-unended-begin)
1768 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _
"}")
1770 \n "\\end" str
> \n)
1772 (define-skeleton latex-split-block
1773 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1775 (tex-last-unended-begin)
1776 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _
"}")
1777 (prog1 (match-string 1)
1778 (goto-char (match-end 1))
1779 (setq v1
(buffer-substring (point)
1781 (while (looking-at "[ \t]*[[{]")
1784 \n "\\end" str
> \n _
\n "\\begin" str v1
> \n)
1786 (defconst tex-discount-args-cmds
1787 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1788 "documentclass" "usepackage" "label")
1789 "TeX commands whose arguments should not be counted as text.")
1791 (defun tex-count-words (begin end
)
1792 "Count the number of words in the buffer."
1794 (if (and transient-mark-mode mark-active
)
1795 (list (region-beginning) (region-end))
1796 (list (point-min) (point-max))))
1797 ;; TODO: skip comments and math and maybe some environments.
1801 (while (and (< (point) end
) (re-search-forward "\\<" end t
))
1802 (if (not (eq (char-syntax (preceding-char)) ?
/))
1804 ;; Don't count single-char words.
1805 (unless (looking-at ".\\>") (cl-incf count
))
1808 (buffer-substring-no-properties
1809 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1812 (when (member cmd tex-discount-args-cmds
)
1813 (skip-chars-forward "*")
1814 (forward-comment (point-max))
1815 (when (looking-at "\\[")
1817 (forward-comment (point-max)))
1818 (if (not (looking-at "{"))
1820 (forward-sexp 1))))))
1821 (message "%s words" count
))))
1825 ;;; Invoking TeX in an inferior shell.
1827 ;; Why use a shell instead of running TeX directly? Because if TeX
1828 ;; gets stuck, the user can switch to the shell window and type at it.
1830 (defvar tex-error-parse-syntax-table
1831 (let ((st (make-syntax-table)))
1832 (modify-syntax-entry ?\
( "()" st
)
1833 (modify-syntax-entry ?\
) ")(" st
)
1834 (modify-syntax-entry ?
\\ "\\" st
)
1835 (modify-syntax-entry ?\
{ "_" st
)
1836 (modify-syntax-entry ?\
} "_" st
)
1837 (modify-syntax-entry ?\
[ "_" st
)
1838 (modify-syntax-entry ?\
] "_" st
)
1839 ;; Single quotations may appear in errors
1840 (modify-syntax-entry ?
\" "_" st
)
1842 "Syntax-table used while parsing TeX error messages.")
1844 (defun tex-old-error-file-name ()
1845 ;; This is unreliable, partly because we don't try very hard, and
1846 ;; partly because TeX's output format is eminently ambiguous and unfriendly
1850 (with-syntax-table tex-error-parse-syntax-table
1852 (backward-up-list 1)
1853 (skip-syntax-forward "(_")
1854 (while (not (let ((try-filename (thing-at-point 'filename
)))
1856 (not (string= "" try-filename
))
1857 (file-readable-p try-filename
))))
1858 (skip-syntax-backward "(_")
1859 (backward-up-list 1)
1860 (skip-syntax-forward "(_"))
1861 (thing-at-point 'filename
)))))
1863 (defconst tex-error-regexp-alist
1864 ;; First alternative handles the newer --file-line-error style:
1865 ;; ./test2.tex:14: Too many }'s.
1867 ;; Second handles the old-style, which spans two lines but doesn't include
1871 ("^l\\.\\([1-9][0-9]*\\) \\(?:\\.\\.\\.\\)?\\(.*\\)$"
1872 tex-old-error-file-name
1 nil nil nil
1873 ;; Since there's no filename to highlight, let's highlight the message.
1874 (2 compilation-error-face
))
1875 ;; A few common warning messages.
1876 ("^\\(?:Und\\|Ov\\)erfull \\\\[hv]box .* at lines? \\(\\([1-9][0-9]*\\)\\(?:--\\([1-9][0-9]*\\)\\)?\\)$"
1877 tex-old-error-file-name
(2 .
3) nil
1 nil
1878 (1 compilation-warning-face
))
1879 ("^(Font) *\\([^ \n].* on input line \\([1-9][0-9]*\\)\\)\\.$"
1880 tex-old-error-file-name
2 nil
1 1
1881 (2 compilation-warning-face
))
1882 ;; Included files get output as (<file> ...).
1883 ;; FIXME: there tend to be a boatload of them at the beginning of the
1884 ;; output which aren't that interesting. Maybe we should filter out
1885 ;; all the file name that start with /usr/share?
1886 ;; ("(\\.?/\\([^() \n]+\\)" 1 nil nil 0)
1889 ;; The utility functions:
1891 (define-derived-mode tex-shell shell-mode
"TeX-Shell"
1892 (set (make-local-variable 'compilation-error-regexp-alist
)
1893 tex-error-regexp-alist
)
1894 (compilation-shell-minor-mode t
))
1897 (defun tex-start-shell ()
1898 (with-current-buffer
1901 (or tex-shell-file-name
(getenv "ESHELL") shell-file-name
)
1903 ;; Specify an interactive shell, to make sure it prompts.
1905 (let ((proc (get-process "tex-shell")))
1906 (set-process-sentinel proc
'tex-shell-sentinel
)
1907 (set-process-query-on-exit-flag proc nil
)
1909 (while (zerop (buffer-size))
1912 (defun tex-feed-input ()
1913 "Send input to the tex shell process.
1914 In the tex buffer this can be used to continue an interactive tex run.
1915 In the tex shell buffer this command behaves like `comint-send-input'."
1917 (set-buffer (tex-shell-buf))
1919 (tex-recenter-output-buffer nil
))
1921 (defun tex-display-shell ()
1922 "Make the TeX shell buffer visible in a window."
1923 (display-buffer (tex-shell-buf))
1924 (tex-recenter-output-buffer nil
))
1926 (defun tex-shell-sentinel (proc msg
)
1927 (cond ((null (buffer-name (process-buffer proc
)))
1929 (set-process-buffer proc nil
)
1930 (tex-delete-last-temp-files))
1931 ((memq (process-status proc
) '(signal exit
))
1932 (tex-delete-last-temp-files))))
1934 (defun tex-set-buffer-directory (buffer directory
)
1935 "Set BUFFER's default directory to be DIRECTORY."
1936 (setq directory
(file-name-as-directory (expand-file-name directory
)))
1937 (if (not (file-directory-p directory
))
1938 (error "%s is not a directory" directory
)
1939 (with-current-buffer buffer
1940 (setq default-directory directory
))))
1942 (defvar tex-send-command-modified-tick
0)
1943 (make-variable-buffer-local 'tex-send-command-modified-tick
)
1945 (defun tex-shell-proc ()
1946 (or (tex-shell-running) (error "No TeX subprocess")))
1947 (defun tex-shell-buf ()
1948 (process-buffer (tex-shell-proc)))
1949 (defun tex-shell-buf-no-error ()
1950 (let ((proc (tex-shell-running)))
1951 (and proc
(process-buffer proc
))))
1953 (defun tex-send-command (command &optional file background
)
1954 "Send COMMAND to TeX shell process, substituting optional FILE for *.
1955 Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1956 FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1957 substitution will be made in COMMAND. COMMAND can be any expression that
1958 evaluates to a command string.
1960 Return the process in which TeX is running."
1962 (let* ((cmd (eval command
))
1963 (proc (tex-shell-proc))
1964 (buf (process-buffer proc
))
1965 (star (string-match "\\*" cmd
))
1970 (if (file-name-absolute-p file
)
1971 (setq file
(convert-standard-filename file
)))
1972 (if star
(concat (substring cmd
0 star
)
1973 (shell-quote-argument file
)
1974 (substring cmd
(1+ star
)))
1975 (concat cmd
" " (shell-quote-argument file
))))
1976 (if background
"&" ""))))
1977 ;; Switch to buffer before checking for subproc output in it.
1979 ;; If text is unchanged since previous tex-send-command,
1980 ;; we haven't got any output. So wait for output now.
1981 (if (= (buffer-modified-tick buf
) tex-send-command-modified-tick
)
1982 (accept-process-output proc
))
1983 (goto-char (process-mark proc
))
1986 (setq tex-send-command-modified-tick
(buffer-modified-tick buf
))
1989 (defun tex-delete-last-temp-files (&optional not-all
)
1990 "Delete any junk files from last temp file.
1991 If NOT-ALL is non-nil, save the `.dvi' file."
1992 (if tex-last-temp-file
1993 (let* ((dir (file-name-directory tex-last-temp-file
))
1994 (list (and (file-directory-p dir
)
1995 (file-name-all-completions
1996 (file-name-base tex-last-temp-file
)
2001 ;; If arg is non-nil, don't delete the .dvi file.
2002 (not (string-match "\\.dvi$" (car list
)))
2003 (delete-file (concat dir
(car list
))))
2004 (delete-file (concat dir
(car list
))))
2005 (setq list
(cdr list
))))))
2007 (add-hook 'kill-emacs-hook
'tex-delete-last-temp-files
)
2010 ;; Machinery to guess the command that the user wants to execute.
2013 (defvar tex-compile-history nil
)
2015 (defvar tex-input-files-re
2017 (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
2018 "bbl" "ind" "sty" "cls") t
)
2019 ;; Include files with no dots (for directories).
2020 "\\'\\|\\`[^.]+\\'")))
2022 (defcustom tex-use-reftex t
2023 "If non-nil, use RefTeX's list of files to determine what command to use."
2027 (defvar tex-compile-commands
2028 '(((concat "pdf" tex-command
2029 " " (if (< 0 (length tex-start-commands
))
2030 (shell-quote-argument tex-start-commands
)) " %f")
2032 ((concat tex-command
2033 " " (if (< 0 (length tex-start-commands
))
2034 (shell-quote-argument tex-start-commands
)) " %f")
2036 ("xdvi %r &" "%r.dvi")
2037 ("\\doc-view \"%r.pdf\"" "%r.pdf")
2038 ("xpdf %r.pdf &" "%r.pdf")
2039 ("gv %r.ps &" "%r.ps")
2040 ("yap %r &" "%r.dvi")
2041 ("advi %r &" "%r.dvi")
2042 ("gv %r.pdf &" "%r.pdf")
2043 ("bibtex %r" "%r.aux" "%r.bbl")
2044 ("makeindex %r" "%r.idx" "%r.ind")
2046 ("dvipdfm %r" "%r.dvi" "%r.pdf")
2047 ("dvipdf %r" "%r.dvi" "%r.pdf")
2048 ("dvips -o %r.ps %r" "%r.dvi" "%r.ps")
2049 ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
2050 ("lpr %r.ps" "%r.ps"))
2051 "List of commands for `tex-compile'.
2052 Each element should be of the form (FORMAT IN OUT) where
2053 FORMAT is an expression that evaluates to a string that can contain
2054 - `%r' the main file name without extension.
2055 - `%f' the main file name.
2056 IN can be either a string (with the same % escapes in it) indicating
2057 the name of the input file, or t to indicate that the input is all
2058 the TeX files of the document, or nil if we don't know.
2059 OUT describes the output file and is either a %-escaped string
2060 or nil to indicate that there is no output file.")
2062 (define-obsolete-function-alias 'tex-string-prefix-p
'string-prefix-p
"24.3")
2064 (defun tex-guess-main-file (&optional all
)
2065 "Find a likely `tex-main-file'.
2066 Looks for hints in other buffers in the same directory or in
2067 ALL other buffers. If ALL is `sub' only look at buffers in parent directories
2068 of the current buffer."
2069 (let ((dir default-directory
)
2070 (header-re tex-start-of-header
))
2072 ;; Look for a buffer with `tex-main-file' set.
2073 (dolist (buf (if (consp all
) all
(buffer-list)))
2074 (with-current-buffer buf
2076 ((null all
) (equal dir default-directory
))
2077 ((eq all
'sub
) (string-prefix-p default-directory dir
))
2079 (stringp tex-main-file
))
2080 (throw 'found
(expand-file-name tex-main-file
)))))
2081 ;; Look for a buffer containing the magic `tex-start-of-header'.
2082 (dolist (buf (if (consp all
) all
(buffer-list)))
2083 (with-current-buffer buf
2085 ((null all
) (equal dir default-directory
))
2086 ((eq all
'sub
) (string-prefix-p default-directory dir
))
2089 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
2090 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
2094 (goto-char (point-min))
2096 header-re
(+ (point) 10000) t
))))
2097 (throw 'found
(expand-file-name buffer-file-name
))))))))
2099 (defun tex-main-file ()
2100 "Return the relative name of the main file."
2101 (let* ((file (or tex-main-file
2102 ;; Compatibility with AUCTeX.
2104 (when (boundp 'TeX-master
)
2105 (cond ((stringp TeX-master
)
2106 (make-local-variable 'tex-main-file
)
2107 (setq tex-main-file TeX-master
))
2108 ((and (eq TeX-master t
) buffer-file-name
)
2109 (file-relative-name buffer-file-name
)))))
2110 ;; Try to guess the main file.
2111 (if (not buffer-file-name
)
2112 (error "Buffer is not associated with any file")
2115 (goto-char (point-min))
2116 (re-search-forward tex-start-of-header
2117 (+ (point) 10000) t
))
2118 ;; This is the main file.
2120 ;; This isn't the main file, let's try to find better,
2121 (or (tex-guess-main-file)
2122 (tex-guess-main-file 'sub
)
2123 ;; (tex-guess-main-file t)
2124 buffer-file-name
)))))))
2125 (if (or (file-exists-p file
) (string-match "\\.tex\\'" file
))
2126 file
(concat file
".tex"))))
2128 (defun tex-summarize-command (cmd)
2129 (if (not (stringp cmd
)) ""
2130 (mapconcat 'identity
2131 (mapcar (lambda (s) (car (split-string s
)))
2132 (split-string cmd
"\\s-*\\(?:;\\|&&\\)\\s-*"))
2135 (defun tex-uptodate-p (file)
2136 "Return non-nil if FILE is not uptodate w.r.t the document source files.
2137 FILE is typically the output DVI or PDF file."
2138 ;; We should check all the files included !!!
2140 ;; Clearly, the target must exist.
2141 (file-exists-p file
)
2142 ;; And the last run must not have asked for a rerun.
2143 ;; FIXME: this should check that the last run was done on the same file.
2144 (let ((buf (condition-case nil
(tex-shell-buf) (error nil
))))
2146 (with-current-buffer buf
2148 (goto-char (point-max))
2149 (and (re-search-backward
2150 (concat "(see the transcript file for additional information)"
2151 "\\|^Output written on .*"
2152 (regexp-quote (file-name-nondirectory file
))
2156 ;; Usually page numbers are output as [N], but
2157 ;; I've already seen things like
2158 ;; [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
2159 (or (re-search-backward "\\[[0-9]+\\({[^}]*}\\)?\\]"
2163 (or (re-search-backward "Rerun" nil t
)
2165 ;; And the input files must not have been changed in the meantime.
2166 (let ((files (if (and tex-use-reftex
2167 (fboundp 'reftex-scanning-info-available-p
)
2168 (reftex-scanning-info-available-p))
2169 (reftex-all-document-files)
2170 (list (file-name-directory (expand-file-name file
)))))
2174 (delq nil
(mapcar (lambda (s) (if (eq (aref s
(1- (length s
))) ?
/)
2175 (substring s
0 (1- (length s
)))))
2176 completion-ignored-extensions
))
2179 (while (and files uptodate
)
2180 (let ((f (pop files
)))
2181 (if (and (file-directory-p f
)
2182 ;; Avoid infinite loops.
2183 (not (file-symlink-p f
)))
2184 (unless (string-match ignored-dirs-re f
)
2186 (ignore-errors ;Not readable or something.
2187 (directory-files f t tex-input-files-re
))
2189 (when (file-newer-than-file-p f file
)
2190 (setq uptodate nil
)))))
2194 (autoload 'format-spec
"format-spec")
2196 (defvar tex-executable-cache nil
)
2197 (defun tex-executable-exists-p (name)
2198 "Like `executable-find' but with a cache."
2199 (let ((f (and (string-match "^\\\\\\([^ \t\n]+\\)" name
)
2200 (intern-soft (concat "tex-cmd-" (match-string 1 name
))))))
2203 (let ((cache (assoc name tex-executable-cache
)))
2204 (if cache
(cdr cache
)
2205 (let ((executable (executable-find name
)))
2206 (push (cons name executable
) tex-executable-cache
)
2209 (defun tex-command-executable (cmd)
2210 (let ((s (if (stringp cmd
) cmd
(eval (car cmd
)))))
2211 (substring s
0 (string-match "[ \t]\\|\\'" s
))))
2213 (defun tex-command-active-p (cmd fspec
)
2214 "Return non-nil if the CMD spec might need to be run."
2215 (let ((in (nth 1 cmd
))
2218 (let ((file (format-spec in fspec
)))
2219 (when (file-exists-p file
)
2221 (file-newer-than-file-p
2222 file
(format-spec out fspec
)))))
2223 (when (and (eq in t
) (stringp out
))
2224 (not (tex-uptodate-p (format-spec out fspec
)))))))
2226 (defcustom tex-cmd-bibtex-args
"--min-crossref=100"
2227 "Extra args to pass to `bibtex' by default."
2232 (defun tex-format-cmd (format fspec
)
2233 "Like `format-spec' but adds user-specified args to the command.
2234 Only applies the FSPEC to the args part of FORMAT."
2235 (if (not (string-match "\\([^ /\\]+\\) " format
))
2236 (format-spec format fspec
)
2237 (let* ((prefix (substring format
0 (match-beginning 0)))
2238 (cmd (match-string 1 format
))
2239 (args (substring format
(match-end 0)))
2240 (sym (intern-soft (format "tex-cmd-%s-args" cmd
)))
2241 (extra-args (and sym
(symbol-value sym
))))
2243 (if extra-args
(concat " " extra-args
))
2244 " " (format-spec args fspec
)))))
2246 (defun tex-compile-default (fspec)
2247 "Guess a default command given the `format-spec' FSPEC."
2248 ;; TODO: Learn to do latex+dvips!
2251 ;; Only consider active commands.
2252 (dolist (cmd tex-compile-commands
)
2253 (when (tex-executable-exists-p (tex-command-executable cmd
))
2254 (if (tex-command-active-p cmd fspec
)
2256 (push (nth 1 cmd
) unchanged-in
))))
2257 ;; If no command seems to be applicable, arbitrarily pick the first one.
2258 (setq cmds
(if cmds
(nreverse cmds
) (list (car tex-compile-commands
))))
2259 ;; Remove those commands whose input was considered stable for
2260 ;; some other command (typically if (t . "%.pdf") is inactive
2261 ;; then we're using pdflatex and the fact that the dvi file
2262 ;; is nonexistent doesn't matter).
2265 (unless (member (nth 1 cmd
) unchanged-in
)
2267 ;; Only remove if there's something left.
2268 (if tmp
(setq cmds
(nreverse tmp
))))
2269 ;; Remove commands whose input is not uptodate either.
2270 (let ((outs (delq nil
(mapcar (lambda (x) (nth 2 x
)) cmds
)))
2273 (unless (member (nth 1 cmd
) outs
)
2275 ;; Only remove if there's something left.
2276 (if tmp
(setq cmds
(nreverse tmp
))))
2277 ;; Select which file we're going to operate on (the latest).
2278 (let ((latest (nth 1 (car cmds
))))
2279 (dolist (cmd (prog1 (cdr cmds
) (setq cmds
(list (car cmds
)))))
2280 (if (equal latest
(nth 1 cmd
))
2282 (unless (eq latest t
) ;Can't beat that!
2283 (if (or (not (stringp latest
))
2285 (and (stringp (nth 1 cmd
))
2286 (file-newer-than-file-p
2287 (format-spec (nth 1 cmd
) fspec
)
2288 (format-spec latest fspec
))))
2289 (setq latest
(nth 1 cmd
) cmds
(list cmd
)))))))
2290 ;; Expand the command spec into the actual text.
2291 (dolist (cmd (prog1 cmds
(setq cmds nil
)))
2292 (push (cons (eval (car cmd
)) (cdr cmd
)) cmds
))
2293 ;; Select the favorite command from the history.
2294 (let ((hist tex-compile-history
)
2297 (setq hist-cmd
(pop hist
))
2298 (setq re
(concat "\\`"
2299 (regexp-quote (tex-command-executable hist-cmd
))
2300 "\\([ \t]\\|\\'\\)"))
2302 ;; If the hist entry uses the same command and applies to a file
2303 ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
2304 (and (string-match re
(car cmd
))
2305 (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd
)))
2306 (string-match (regexp-quote (match-string 1 (car cmd
)))
2308 (setq hist nil cmds
(list cmd
)))))
2309 ;; Substitute and return.
2311 (string-match (concat "[' \t\"]" (format-spec "%r" fspec
)
2312 "\\([;&' \t\"]\\|\\'\\)") hist-cmd
))
2313 ;; The history command was already applied to the same file,
2314 ;; so just reuse it.
2316 (if cmds
(tex-format-cmd (caar cmds
) fspec
))))))
2318 (defun tex-cmd-doc-view (file)
2319 (pop-to-buffer (find-file-noselect file
)))
2321 (defun tex-compile (dir cmd
)
2322 "Run a command CMD on current TeX buffer's file in DIR."
2323 ;; FIXME: Use time-stamps on files to decide the next op.
2325 (let* ((file (tex-main-file))
2327 (prog1 (file-name-directory (expand-file-name file
))
2328 (setq file
(file-name-nondirectory file
))))
2329 (root (file-name-sans-extension file
))
2330 (fspec (list (cons ?r
(shell-quote-argument root
))
2331 (cons ?f
(shell-quote-argument file
))))
2332 (default (tex-compile-default fspec
)))
2333 (list default-directory
2335 (format "Command [%s]: " (tex-summarize-command default
))
2337 (list (tex-format-cmd (eval (car x
)) fspec
)))
2338 tex-compile-commands
)
2339 nil nil nil
'tex-compile-history default
))))
2340 (save-some-buffers (not compilation-ask-about-save
) nil
)
2341 (let ((f (and (string-match "^\\\\\\([^ \t\n]+\\)" cmd
)
2342 (intern-soft (concat "tex-cmd-" (match-string 1 cmd
))))))
2345 (let ((default-directory dir
))
2346 (apply f
(split-string-and-unquote
2347 (substring cmd
(match-end 0)))))
2348 (wrong-number-of-arguments
2349 (error "Wrong number of arguments to %s"
2350 (substring (symbol-name f
) 8))))
2351 (if (tex-shell-running)
2354 (tex-send-tex-command cmd dir
))))
2356 (defun tex-start-tex (command file
&optional dir
)
2357 "Start a TeX run, using COMMAND on FILE."
2358 (let* ((star (string-match "\\*" command
))
2361 (concat (substring command
0 star
)
2362 (shell-quote-argument file
)
2363 (substring command
(1+ star
)))
2366 (if (< 0 (length tex-start-commands
))
2368 (shell-quote-argument tex-start-commands
) " "))
2369 (shell-quote-argument file
)))))
2370 (tex-send-tex-command compile-command dir
)))
2372 (defun tex-send-tex-command (cmd &optional dir
)
2373 (unless (or (equal dir
(let ((buf (tex-shell-buf-no-error)))
2374 (and buf
(with-current-buffer buf
2375 default-directory
))))
2377 (let (shell-dirtrack-verbose)
2378 (tex-send-command tex-shell-cd-command dir
)))
2379 (with-current-buffer (process-buffer (tex-send-command cmd
))
2380 (setq compilation-last-buffer
(current-buffer))
2381 (compilation-forget-errors)
2382 ;; Don't parse previous compilations.
2383 (set-marker compilation-parsing-end
(1- (point-max))))
2385 (setq tex-last-buffer-texed
(current-buffer)))
2389 (defun tex-region (beg end
)
2390 "Run TeX on the current region, via a temporary file.
2391 The file's name comes from the variable `tex-zap-file' and the
2392 variable `tex-directory' says where to put it.
2394 If the buffer has a header, the header is given to TeX before the
2395 region itself. The buffer's header is all lines between the strings
2396 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
2397 The header must start in the first 100 lines of the buffer.
2399 The value of `tex-trailer' is given to TeX as input after the region.
2401 The value of `tex-command' specifies the command to use to run TeX."
2403 (if (tex-shell-running)
2407 (setq tex-zap-file
(tex-generate-zap-file-name)))
2408 ;; Temp file will be written and TeX will be run in zap-directory.
2409 ;; If the TEXINPUTS file has relative directories or if the region has
2410 ;; \input of files, this must be the same directory as the file for
2411 ;; TeX to access the correct inputs. That's why it's safest if
2412 ;; tex-directory is ".".
2413 (let* ((zap-directory
2414 (file-name-as-directory (expand-file-name tex-directory
)))
2415 (tex-out-file (expand-file-name (concat tex-zap-file
".tex")
2417 (main-file (expand-file-name (tex-main-file)))
2418 (ismain (string-equal main-file
(buffer-file-name)))
2420 ;; Don't delete temp files if we do the same buffer twice in a row.
2421 (or (eq (current-buffer) tex-last-buffer-texed
)
2422 (tex-delete-last-temp-files t
))
2423 (let ((default-directory zap-directory
)) ; why?
2424 ;; We assume the header is fully contained in tex-main-file.
2425 ;; We use f-f-ns so we get prompted about any changes on disk.
2426 (with-current-buffer (find-file-noselect main-file
)
2427 (setq already-output
(tex-region-header tex-out-file
2429 ;; Write out the specified region (but don't repeat anything
2430 ;; already written in the header).
2431 (write-region (if ismain
2432 (max beg already-output
)
2434 end tex-out-file
(not (zerop already-output
)))
2435 ;; Write the trailer, if any.
2436 ;; Precede it with a newline to make sure it
2437 ;; is not hidden in a comment.
2439 (write-region (concat "\n" tex-trailer
) nil
2441 ;; Record the file name to be deleted afterward.
2442 (setq tex-last-temp-file tex-out-file
)
2443 ;; Use a relative file name here because (1) the proper dir
2444 ;; is already current, and (2) the abs file name is sometimes
2445 ;; too long and can make tex crash.
2446 (tex-start-tex tex-command
(concat tex-zap-file
".tex") zap-directory
)
2447 (setq tex-print-file tex-out-file
)))
2449 (defun tex-region-header (file &optional beg
)
2450 "If there is a TeX header in the current buffer, write it to FILE.
2451 Return point at the end of the region so written, or zero. If
2452 the optional buffer position BEG is specified, then the region
2453 written out starts at BEG, if this lies before the start of the header.
2455 If the first line matches `tex-first-line-header-regexp', it is
2456 also written out. The variables `tex-start-of-header' and
2457 `tex-end-of-header' are used to locate the header. Note that the
2458 start of the header is required to be within the first 100 lines."
2462 (goto-char (point-min))
2463 (let ((search-end (save-excursion
2468 ;; Maybe copy first line, such as `\input texinfo', to temp file.
2469 (and tex-first-line-header-regexp
2470 (looking-at tex-first-line-header-regexp
)
2471 (write-region (point)
2472 (progn (forward-line 1)
2473 (setq already-output
(point)))
2475 ;; Write out the header, if there is one, and any of the
2476 ;; specified region which extends before it. But don't repeat
2477 ;; anything already written.
2478 (and tex-start-of-header
2479 (re-search-forward tex-start-of-header search-end t
)
2482 (setq hbeg
(point)) ; mark beginning of header
2483 (when (re-search-forward tex-end-of-header nil t
)
2485 (setq hend
(point)) ; mark end of header
2491 hend file
(not (zerop already-output
)))
2492 (setq already-output hend
))))
2495 (defun tex-buffer ()
2496 "Run TeX on current buffer. See \\[tex-region] for more information.
2497 Does not save the buffer, so it's useful for trying experimental versions.
2498 See \\[tex-file] for an alternative."
2500 (tex-region (point-min) (point-max)))
2503 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
2504 This function is more useful than \\[tex-buffer] when you need the
2505 `.aux' file of LaTeX to have the correct name."
2507 (when tex-offer-save
2508 (save-some-buffers))
2509 (let* ((source-file (tex-main-file))
2510 (file-dir (file-name-directory (expand-file-name source-file
))))
2511 (if (tex-shell-running)
2514 (tex-start-tex tex-command source-file file-dir
)
2515 (setq tex-print-file
(expand-file-name source-file
))))
2517 (defun tex-generate-zap-file-name ()
2518 "Generate a unique name suitable for use as a file name."
2519 ;; Include the shell process number and host name
2520 ;; in case there are multiple shells (for same or different user).
2521 ;; Dec 1998: There is a report that some versions of xdvi
2522 ;; don't work with file names that start with #.
2524 (process-id (get-buffer-process "*tex-shell*"))
2525 (subst-char-in-string ?. ?-
(system-name))))
2527 ;; This will perhaps be useful for modifying TEXINPUTS.
2528 ;; Expand each file name, separated by colons, in the string S.
2529 (defun tex-expand-files (s)
2530 (let (elts (start 0))
2531 (while (string-match ":" s start
)
2532 (setq elts
(cons (substring s start
(match-beginning 0)) elts
))
2533 (setq start
(match-end 0)))
2535 (setq elts
(cons (substring s start
) elts
)))
2536 (mapconcat (lambda (elt)
2537 (if (= (length elt
) 0) elt
(expand-file-name elt
)))
2538 (nreverse elts
) ":")))
2540 (defun tex-shell-running ()
2541 (let ((proc (get-process "tex-shell")))
2543 (if (and (eq (process-status proc
) 'run
)
2544 (buffer-live-p (process-buffer proc
)))
2545 ;; return the TeX process on success
2547 ;; get rid of the process permanently
2548 ;; this should get rid of the annoying w32 problem with
2549 ;; dead tex-shell buffer and live process
2550 (delete-process proc
)))))
2552 (defun tex-kill-job ()
2553 "Kill the currently running TeX job."
2555 ;; `quit-process' leads to core dumps of the tex process (except if
2556 ;; coredumpsize has limit 0kb as on many environments). One would
2557 ;; like to use (kill-process proc 'lambda), however that construct
2558 ;; does not work on some systems and kills the shell itself.
2559 (let ((proc (get-process "tex-shell")))
2560 (when proc
(quit-process proc t
))))
2562 (defun tex-recenter-output-buffer (linenum)
2563 "Redisplay buffer of TeX job output so that most recent output can be seen.
2564 The last line of the buffer is displayed on
2565 line LINE of the window, or centered if LINE is nil."
2567 (let ((tex-shell (get-buffer "*tex-shell*"))
2569 (if (null tex-shell
)
2570 (message "No TeX output buffer")
2571 (setq window
(display-buffer tex-shell
))
2572 (save-selected-window
2573 (select-window window
)
2574 (bury-buffer tex-shell
)
2575 (goto-char (point-max))
2576 (recenter (if linenum
2577 (prefix-numeric-value linenum
)
2578 (/ (window-height) 2)))))))
2580 (defun tex-print (&optional alt
)
2581 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2582 Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
2583 is provided, use the alternative command, `tex-alt-dvi-print-command'."
2585 (let ((print-file-name-dvi (tex-append tex-print-file
".dvi"))
2587 (if (and (not (equal (current-buffer) tex-last-buffer-texed
))
2589 ;; Check that this buffer's printed file is up to date.
2590 (file-newer-than-file-p
2591 (setq test-name
(tex-append (buffer-file-name) ".dvi"))
2592 (buffer-file-name)))
2593 (setq print-file-name-dvi test-name
))
2594 (if (not (file-exists-p print-file-name-dvi
))
2595 (error "No appropriate `.dvi' file could be found")
2596 (if (tex-shell-running)
2600 (if alt tex-alt-dvi-print-command tex-dvi-print-command
)
2604 (defun tex-alt-print ()
2605 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2606 Runs the shell command defined by `tex-alt-dvi-print-command'."
2611 "Preview the last `.dvi' file made by running TeX under Emacs.
2612 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2613 The variable `tex-dvi-view-command' specifies the shell command for preview.
2614 You must set that variable yourself before using this command,
2615 because there is no standard value that would generally work."
2617 (or tex-dvi-view-command
2618 (error "You must set `tex-dvi-view-command'"))
2619 ;; Restart the TeX shell if necessary.
2620 (or (tex-shell-running)
2622 (let ((tex-dvi-print-command (eval tex-dvi-view-command
)))
2625 (defun tex-append (file-name suffix
)
2626 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
2627 Pascal-based TeX scans for the first period, C TeX uses the last.
2628 No period is retained immediately before SUFFIX,
2629 so normally SUFFIX starts with one."
2630 (if (stringp file-name
)
2631 (let ((file (file-name-nondirectory file-name
))
2633 ;; Try splitting on last period.
2634 ;; The first-period split can get fooled when two files
2635 ;; named a.tex and a.b.tex are both tex'd;
2636 ;; the last-period split must be right if it matches at all.
2638 (concat (file-name-directory file-name
)
2640 (string-match "\\.[^.]*$" file
))
2642 (if (or (file-exists-p trial-name
)
2643 (file-exists-p (concat trial-name
".aux"))) ;for BibTeX files
2645 ;; Not found, so split on first period.
2646 (concat (file-name-directory file-name
)
2648 (string-match "\\." file
))
2652 (defun tex-show-print-queue ()
2653 "Show the print queue that \\[tex-print] put your job on.
2654 Runs the shell command defined by `tex-show-queue-command'."
2656 (if (tex-shell-running)
2659 (tex-send-command tex-show-queue-command
)
2660 (tex-display-shell))
2662 (defun tex-bibtex-file ()
2663 "Run BibTeX on the current buffer's file."
2665 (if (tex-shell-running)
2668 (let* (shell-dirtrack-verbose
2669 (source-file (expand-file-name (tex-main-file)))
2671 (tex-append (file-name-nondirectory source-file
) ""))
2672 (file-dir (file-name-directory source-file
)))
2673 (tex-send-command tex-shell-cd-command file-dir
)
2674 (tex-send-command tex-bibtex-command tex-out-file
))
2675 (tex-display-shell))
2678 ;;;; LaTeX indentation
2681 (defvar tex-indent-allhanging t
)
2682 (defvar tex-indent-arg
4)
2683 (defvar tex-indent-basic
2)
2684 (defvar tex-indent-item tex-indent-basic
)
2685 (defvar tex-indent-item-re
"\\\\\\(bib\\)?item\\>")
2686 (defvar latex-noindent-environments
'("document"))
2688 (defvar tex-latex-indent-syntax-table
2689 (let ((st (make-syntax-table tex-mode-syntax-table
)))
2690 (modify-syntax-entry ?$
"." st
)
2691 (modify-syntax-entry ?\
( "." st
)
2692 (modify-syntax-entry ?\
) "." st
)
2694 "Syntax table used while computing indentation.")
2696 (defun latex-indent (&optional arg
)
2697 (if (and (eq (get-text-property (if (and (eobp) (bolp))
2698 (max (point-min) (1- (point)))
2699 (line-beginning-position)) 'face
)
2702 (with-syntax-table tex-latex-indent-syntax-table
2703 ;; TODO: Rather than ignore $, we should try to be more clever about it.
2707 (latex-find-indent))))
2708 (if (< indent
0) (setq indent
0))
2709 (if (<= (current-column) (current-indentation))
2710 (indent-line-to indent
)
2711 (save-excursion (indent-line-to indent
)))))))
2713 (defcustom latex-indent-within-escaped-parens nil
2714 "Non-nil means add extra indent to text within escaped parens.
2715 When this is non-nil, text within matching pairs of escaped
2716 parens is indented at the column following the open paren. The
2717 default value does not add any extra indent thus providing the
2718 behavior of Emacs 22 and earlier."
2723 (defun latex-find-indent (&optional virtual
)
2724 "Find the proper indentation of text after point.
2725 VIRTUAL if non-nil indicates that we're only trying to find the indentation
2726 in order to determine the indentation of something else.
2727 There might be text before point."
2728 (let ((latex-handle-escaped-parens latex-indent-within-escaped-parens
))
2730 (skip-chars-forward " \t")
2732 ;; Stick the first line at column 0.
2733 (and (= (point-min) (line-beginning-position)) 0)
2734 ;; Trust the current indentation, if such info is applicable.
2735 (and virtual
(save-excursion (skip-chars-backward " \t&") (bolp))
2737 ;; Stick verbatim environments to the left margin.
2738 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2739 (member (match-string 2) tex-verbatim-environments
)
2741 ;; Put leading close-paren where the matching open paren would be.
2743 (and (or (eq (latex-syntax-after) ?\
))
2744 ;; Try to handle escaped close parens but keep
2745 ;; original position if it doesn't work out.
2746 (and latex-handle-escaped-parens
2747 (setq escaped
(looking-at "\\\\\\([])}]\\)"))))
2751 (goto-char (match-beginning 1)))
2752 (latex-skip-close-parens)
2753 (latex-backward-sexp-1)
2754 (latex-find-indent 'virtual
)))))
2755 ;; Default (maybe an argument)
2757 ;; Outdent \item if necessary.
2758 (indent (if (looking-at tex-indent-item-re
) (- tex-indent-item
) 0))
2760 ;; Find the previous point which determines our current indentation.
2763 (latex-backward-sexp-1)
2764 (while (> (current-column) (current-indentation))
2765 (latex-backward-sexp-1)))
2767 (setq up-list-pos
(nth 2 err
))))
2769 ((= (point-min) pos
) 0) ; We're really just indenting the first line.
2770 ((integerp up-list-pos
)
2771 ;; Have to indent relative to the open-paren.
2772 (goto-char up-list-pos
)
2773 (if (and (not tex-indent-allhanging
)
2775 ;; Make sure we're an argument to a macro and
2776 ;; that the macro is at the beginning of a line.
2779 (while (eq (char-syntax (char-after)) ?\
()
2781 (and (eq (char-syntax (char-after)) ?
/)
2782 (progn (skip-chars-backward " \t&")
2785 (> pos
(progn (latex-down-list)
2786 (forward-comment (point-max))
2788 ;; Align with the first element after the open-paren.
2790 ;; We're the first element after a hanging brace.
2791 (goto-char up-list-pos
)
2792 (+ (if (and (looking-at "\\\\begin *{\\([^\n}]+\\)")
2793 (member (match-string 1)
2794 latex-noindent-environments
))
2796 indent
(latex-find-indent 'virtual
))))
2797 ;; We're now at the "beginning" of a line.
2798 ((not (and (not virtual
) (eq (char-after) ?
\\)))
2799 ;; Nothing particular here: just keep the same indentation.
2800 (+ indent
(current-column)))
2801 ;; We're now looking at a macro call.
2802 ((looking-at tex-indent-item-re
)
2803 ;; Indenting relative to an item, have to re-add the outdenting.
2804 (+ indent
(current-column) tex-indent-item
))
2806 (let ((col (current-column)))
2807 (if (or (not (eq (char-syntax (or (char-after pos
) ?\s
)) ?\
())
2808 ;; Can't be an arg if there's an empty line inbetween.
2809 (save-excursion (re-search-forward "^[ \t]*$" pos t
)))
2810 ;; If the first char was not an open-paren, there's
2811 ;; a risk that this is really not an argument to the
2815 (if (< (line-end-position)
2816 (save-excursion (forward-comment (point-max))
2818 ;; we're indenting the first argument.
2819 (min (current-column) (+ tex-indent-arg col
))
2820 (skip-syntax-forward " ")
2821 (current-column)))))))))))
2824 (defun doctex-font-lock-^^A
()
2825 (if (eq (char-after (line-beginning-position)) ?\%
)
2828 (1- (match-beginning 1)) (match-beginning 1)
2830 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2831 ;; The `%' is a single-char comment, which Emacs
2832 ;; syntax-table can't deal with. We could turn it
2833 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2834 ;; Instead, we include it in the ^^A comment.
2835 (string-to-syntax "< b")
2836 (string-to-syntax ">")))
2837 (let ((end (line-end-position)))
2838 (if (< end
(point-max))
2842 (string-to-syntax "> b"))))
2843 (string-to-syntax "< b"))))
2845 (defun doctex-font-lock-syntactic-face-function (state)
2846 ;; Mark DocTeX documentation, which is parsed as a style A comment
2847 ;; starting in column 0.
2848 (if (or (nth 3 state
) (nth 7 state
)
2849 (not (memq (char-before (nth 8 state
))
2851 ;; Anything else is just as for LaTeX.
2852 (tex-font-lock-syntactic-face-function state
)
2853 font-lock-doc-face
))
2856 (defconst doctex-syntax-propertize-rules
2857 (syntax-propertize-precompile-rules
2858 latex-syntax-propertize-rules
2859 ;; For DocTeX comment-in-doc.
2860 ("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A
))))))
2862 (defvar doctex-font-lock-keywords
2863 (append tex-font-lock-keywords
2864 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t
)))))
2867 (define-derived-mode doctex-mode latex-mode
"DocTeX"
2868 "Major mode to edit DocTeX files."
2869 (setq font-lock-defaults
2870 (cons (append (car font-lock-defaults
) '(doctex-font-lock-keywords))
2874 (`font-lock-syntactic-face-function
2875 (cons (car x
) 'doctex-font-lock-syntactic-face-function
))
2877 (cdr font-lock-defaults
))))
2878 (set (make-local-variable 'syntax-propertize-function
)
2879 (syntax-propertize-rules doctex-syntax-propertize-rules
)))
2881 (run-hooks 'tex-mode-load-hook
)
2885 ;;; tex-mode.el ends here