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