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