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