]> 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 ;;;###autoload
910 (defun tex-mode ()
911 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
912 Tries to determine (by looking at the beginning of the file) whether
913 this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
914 `latex-mode', or `slitex-mode', respectively. If it cannot be determined,
915 such as if there are no commands in the file, the value of `tex-default-mode'
916 says which mode to use."
917 (interactive)
918 (if delay-mode-hooks
919 ;; We're called from one of the children already.
920 (tex-mode-internal)
921 (tex-guess-mode)))
922
923 ;; The following three autoloaded aliases appear to conflict with
924 ;; AUCTeX. However, even though AUCTeX uses the mixed case variants
925 ;; for all mode relevant variables and hooks, the invocation function
926 ;; and setting of `major-mode' themselves need to be lowercase for
927 ;; AUCTeX to provide a fully functional user-level replacement. So
928 ;; these aliases should remain as they are, in particular since AUCTeX
929 ;; users are likely to use them.
930
931 ;;;###autoload
932 (defalias 'TeX-mode 'tex-mode)
933 ;;;###autoload
934 (defalias 'plain-TeX-mode 'plain-tex-mode)
935 ;;;###autoload
936 (defalias 'LaTeX-mode 'latex-mode)
937
938 ;;;###autoload
939 (define-derived-mode plain-tex-mode tex-mode "TeX"
940 "Major mode for editing files of input for plain TeX.
941 Makes $ and } display the characters they match.
942 Makes \" insert `` when it seems to be the beginning of a quotation,
943 and '' when it appears to be the end; it inserts \" only after a \\.
944
945 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
946 copied from the top of the file (containing macro definitions, etc.),
947 running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
948 \\[tex-file] saves the buffer and then processes the file.
949 \\[tex-print] prints the .dvi file made by any of these.
950 \\[tex-view] previews the .dvi file made by any of these.
951 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
952
953 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
954 mismatched $'s or braces.
955
956 Special commands:
957 \\{plain-tex-mode-map}
958
959 Mode variables:
960 tex-run-command
961 Command string used by \\[tex-region] or \\[tex-buffer].
962 tex-directory
963 Directory in which to create temporary files for TeX jobs
964 run by \\[tex-region] or \\[tex-buffer].
965 tex-dvi-print-command
966 Command string used by \\[tex-print] to print a .dvi file.
967 tex-alt-dvi-print-command
968 Alternative command string used by \\[tex-print] (when given a prefix
969 argument) to print a .dvi file.
970 tex-dvi-view-command
971 Command string used by \\[tex-view] to preview a .dvi file.
972 tex-show-queue-command
973 Command string used by \\[tex-show-print-queue] to show the print
974 queue that \\[tex-print] put your job on.
975
976 Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
977 `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
978 special subshell is initiated, the hook `tex-shell-hook' is run."
979 (set (make-local-variable 'tex-command) tex-run-command)
980 (set (make-local-variable 'tex-start-of-header) "%\\*\\*start of header")
981 (set (make-local-variable 'tex-end-of-header) "%\\*\\*end of header")
982 (set (make-local-variable 'tex-trailer) "\\bye\n"))
983
984 ;;;###autoload
985 (define-derived-mode latex-mode tex-mode "LaTeX"
986 "Major mode for editing files of input for LaTeX.
987 Makes $ and } display the characters they match.
988 Makes \" insert `` when it seems to be the beginning of a quotation,
989 and '' when it appears to be the end; it inserts \" only after a \\.
990
991 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
992 copied from the top of the file (containing \\documentstyle, etc.),
993 running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
994 \\[tex-file] saves the buffer and then processes the file.
995 \\[tex-print] prints the .dvi file made by any of these.
996 \\[tex-view] previews the .dvi file made by any of these.
997 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
998
999 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1000 mismatched $'s or braces.
1001
1002 Special commands:
1003 \\{latex-mode-map}
1004
1005 Mode variables:
1006 latex-run-command
1007 Command string used by \\[tex-region] or \\[tex-buffer].
1008 tex-directory
1009 Directory in which to create temporary files for LaTeX jobs
1010 run by \\[tex-region] or \\[tex-buffer].
1011 tex-dvi-print-command
1012 Command string used by \\[tex-print] to print a .dvi file.
1013 tex-alt-dvi-print-command
1014 Alternative command string used by \\[tex-print] (when given a prefix
1015 argument) to print a .dvi file.
1016 tex-dvi-view-command
1017 Command string used by \\[tex-view] to preview a .dvi file.
1018 tex-show-queue-command
1019 Command string used by \\[tex-show-print-queue] to show the print
1020 queue that \\[tex-print] put your job on.
1021
1022 Entering Latex mode runs the hook `text-mode-hook', then
1023 `tex-mode-hook', and finally `latex-mode-hook'. When the special
1024 subshell is initiated, `tex-shell-hook' is run."
1025 (set (make-local-variable 'tex-command) latex-run-command)
1026 (set (make-local-variable 'tex-start-of-header)
1027 "\\\\document\\(style\\|class\\)")
1028 (set (make-local-variable 'tex-end-of-header) "\\\\begin\\s-*{document}")
1029 (set (make-local-variable 'tex-trailer) "\\end{document}\n")
1030 ;; A line containing just $$ is treated as a paragraph separator.
1031 ;; A line starting with $$ starts a paragraph,
1032 ;; but does not separate paragraphs if it has more stuff on it.
1033 (setq paragraph-start
1034 (concat "[ \t]*\\(\\$\\$\\|"
1035 "\\\\[][]\\|"
1036 "\\\\" (regexp-opt (append
1037 (mapcar 'car latex-section-alist)
1038 '("begin" "label" "end"
1039 "item" "bibitem" "newline" "noindent"
1040 "newpage" "footnote" "marginpar"
1041 "parbox" "caption")) t)
1042 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
1043 "\\>\\)"))
1044 (setq paragraph-separate
1045 (concat "[\f%]\\|[ \t]*\\($\\|"
1046 "\\\\[][]\\|"
1047 "\\\\" (regexp-opt (append
1048 (mapcar 'car latex-section-alist)
1049 '("begin" "label" "end" )) t)
1050 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
1051 "noindent" "newpage" "footnote"
1052 "marginpar" "parbox" "caption"))
1053 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
1054 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
1055 (set (make-local-variable 'imenu-create-index-function)
1056 'latex-imenu-create-index)
1057 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
1058 (add-hook 'fill-nobreak-predicate 'latex-fill-nobreak-predicate nil t)
1059 (set (make-local-variable 'indent-line-function) 'latex-indent)
1060 (set (make-local-variable 'fill-indent-according-to-mode) t)
1061 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
1062 (set (make-local-variable 'outline-level) 'latex-outline-level)
1063 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
1064 (set (make-local-variable 'skeleton-end-hook) nil))
1065
1066 ;;;###autoload
1067 (define-derived-mode slitex-mode latex-mode "SliTeX"
1068 "Major mode for editing files of input for SliTeX.
1069 Makes $ and } display the characters they match.
1070 Makes \" insert `` when it seems to be the beginning of a quotation,
1071 and '' when it appears to be the end; it inserts \" only after a \\.
1072
1073 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
1074 copied from the top of the file (containing \\documentstyle, etc.),
1075 running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
1076 \\[tex-file] saves the buffer and then processes the file.
1077 \\[tex-print] prints the .dvi file made by any of these.
1078 \\[tex-view] previews the .dvi file made by any of these.
1079 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1080
1081 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1082 mismatched $'s or braces.
1083
1084 Special commands:
1085 \\{slitex-mode-map}
1086
1087 Mode variables:
1088 slitex-run-command
1089 Command string used by \\[tex-region] or \\[tex-buffer].
1090 tex-directory
1091 Directory in which to create temporary files for SliTeX jobs
1092 run by \\[tex-region] or \\[tex-buffer].
1093 tex-dvi-print-command
1094 Command string used by \\[tex-print] to print a .dvi file.
1095 tex-alt-dvi-print-command
1096 Alternative command string used by \\[tex-print] (when given a prefix
1097 argument) to print a .dvi file.
1098 tex-dvi-view-command
1099 Command string used by \\[tex-view] to preview a .dvi file.
1100 tex-show-queue-command
1101 Command string used by \\[tex-show-print-queue] to show the print
1102 queue that \\[tex-print] put your job on.
1103
1104 Entering SliTeX mode runs the hook `text-mode-hook', then the hook
1105 `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
1106 `slitex-mode-hook'. When the special subshell is initiated, the hook
1107 `tex-shell-hook' is run."
1108 (setq tex-command slitex-run-command)
1109 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
1110
1111 (defun tex-common-initialization ()
1112 ;; Regexp isearch should accept newline and formfeed as whitespace.
1113 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
1114 ;; A line containing just $$ is treated as a paragraph separator.
1115 (set (make-local-variable 'paragraph-start)
1116 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
1117 ;; A line starting with $$ starts a paragraph,
1118 ;; but does not separate paragraphs if it has more stuff on it.
1119 (set (make-local-variable 'paragraph-separate)
1120 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
1121 (set (make-local-variable 'comment-start) "%")
1122 (set (make-local-variable 'comment-add) 1)
1123 (set (make-local-variable 'comment-start-skip)
1124 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
1125 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1126 (set (make-local-variable 'compare-windows-whitespace)
1127 'tex-categorize-whitespace)
1128 (set (make-local-variable 'facemenu-add-face-function)
1129 (lambda (face end)
1130 (or (cdr (assq face tex-face-alist))
1131 (error "Face %s not configured for %s mode" face mode-name))))
1132 (set (make-local-variable 'facemenu-end-add-face) "}")
1133 (set (make-local-variable 'facemenu-remove-face-function) t)
1134 (set (make-local-variable 'font-lock-defaults)
1135 '((tex-font-lock-keywords tex-font-lock-keywords-1
1136 tex-font-lock-keywords-2 tex-font-lock-keywords-3)
1137 nil nil ((?$ . "\"")) nil
1138 ;; Who ever uses that anyway ???
1139 (font-lock-mark-block-function . mark-paragraph)
1140 (font-lock-syntactic-face-function
1141 . tex-font-lock-syntactic-face-function)
1142 (font-lock-unfontify-region-function
1143 . tex-font-lock-unfontify-region)
1144 (font-lock-syntactic-keywords
1145 . tex-font-lock-syntactic-keywords)
1146 (parse-sexp-lookup-properties . t)))
1147 ;; TABs in verbatim environments don't do what you think.
1148 (set (make-local-variable 'indent-tabs-mode) nil)
1149 ;; Other vars that should be buffer-local.
1150 (make-local-variable 'tex-command)
1151 (make-local-variable 'tex-start-of-header)
1152 (make-local-variable 'tex-end-of-header)
1153 (make-local-variable 'tex-trailer))
1154
1155 (defun tex-categorize-whitespace (backward-limit)
1156 ;; compare-windows-whitespace is set to this.
1157 ;; This is basically a finite-state machine.
1158 ;; Returns a symbol telling how TeX would treat
1159 ;; the whitespace we are looking at: null, space, or par.
1160 (let ((category 'null)
1161 (not-finished t))
1162 (skip-chars-backward " \t\n\f" backward-limit)
1163 (while not-finished
1164 (cond ((looking-at "[ \t]+")
1165 (goto-char (match-end 0))
1166 (if (eq category 'null)
1167 (setq category 'space)))
1168 ((looking-at "\n")
1169 (cond ((eq category 'newline)
1170 (setq category 'par)
1171 (setq not-finished nil))
1172 (t
1173 (setq category 'newline) ;a strictly internal state
1174 (goto-char (match-end 0)))))
1175 ((looking-at "\f+")
1176 (setq category 'par)
1177 (setq not-finished nil))
1178 (t
1179 (setq not-finished nil))))
1180 (skip-chars-forward " \t\n\f")
1181 (if (eq category 'newline)
1182 'space ;TeX doesn't distinguish
1183 category)))
1184
1185 (defun tex-insert-quote (arg)
1186 "Insert the appropriate quote marks for TeX.
1187 Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
1188 \(normally '') depending on the context. With prefix argument, always
1189 inserts \" characters."
1190 (interactive "*P")
1191 (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
1192 (eq (get-text-property (point) 'face) 'tex-verbatim)
1193 (save-excursion
1194 (backward-char (length tex-open-quote))
1195 (when (or (looking-at (regexp-quote tex-open-quote))
1196 (looking-at (regexp-quote tex-close-quote)))
1197 (delete-char (length tex-open-quote))
1198 t)))
1199 (self-insert-command (prefix-numeric-value arg))
1200 (insert (if (memq (char-syntax (preceding-char)) '(?\( ?> ?\s))
1201 tex-open-quote tex-close-quote))))
1202
1203 (defun tex-validate-buffer ()
1204 "Check current buffer for paragraphs containing mismatched braces or $s.
1205 Their positions are recorded in the buffer `*Occur*'.
1206 To find a particular invalidity from `*Occur*', switch to that buffer
1207 and type C-c C-c or click with mouse-2
1208 on the line for the invalidity you want to see."
1209 (interactive)
1210 (let ((buffer (current-buffer))
1211 (prevpos (point-min))
1212 (linenum nil)
1213 (num-matches 0))
1214 (with-output-to-temp-buffer "*Occur*"
1215 (princ "Mismatches:\n")
1216 (with-current-buffer standard-output
1217 (occur-mode)
1218 ;; This won't actually work...Really, this whole thing should
1219 ;; be rewritten instead of being a hack on top of occur.
1220 (setq occur-revert-arguments (list nil 0 (list buffer))))
1221 (save-excursion
1222 (goto-char (point-max))
1223 ;; Do a little shimmy to place point at the end of the last
1224 ;; "real" paragraph. Need to avoid validating across an \end,
1225 ;; because that blows up latex-forward-sexp.
1226 (backward-paragraph)
1227 (forward-paragraph)
1228 (while (not (bobp))
1229 ;; Scan the previous paragraph for invalidities.
1230 (backward-paragraph)
1231 (save-excursion
1232 (or (tex-validate-region (point) (save-excursion
1233 (forward-paragraph)
1234 (point)))
1235 (let ((end (line-beginning-position 2))
1236 start tem)
1237 (beginning-of-line)
1238 (setq start (point))
1239 ;; Keep track of line number as we scan,
1240 ;; in a cumulative fashion.
1241 (if linenum
1242 (setq linenum (- linenum
1243 (count-lines prevpos (point))))
1244 (setq linenum (1+ (count-lines 1 start))))
1245 (setq prevpos (point))
1246 ;; Mention this mismatch in *Occur*.
1247 ;; Since we scan from end of buffer to beginning,
1248 ;; add each mismatch at the beginning of *Occur*.
1249 (save-excursion
1250 (setq tem (point-marker))
1251 (set-buffer standard-output)
1252 (goto-char (point-min))
1253 ;; Skip "Mismatches:" header line.
1254 (forward-line 1)
1255 (setq num-matches (1+ num-matches))
1256 (insert-buffer-substring buffer start end)
1257 (let (text-beg (text-end (point-marker)))
1258 (forward-char (- start end))
1259 (setq text-beg (point-marker))
1260 (insert (format "%3d: " linenum))
1261 (add-text-properties
1262 text-beg (- text-end 1)
1263 '(mouse-face highlight
1264 help-echo
1265 "mouse-2: go to this invalidity"))
1266 (put-text-property text-beg (- text-end 1)
1267 'occur-target tem))))))))
1268 (with-current-buffer standard-output
1269 (let ((no-matches (zerop num-matches)))
1270 (if no-matches
1271 (insert "None!\n"))
1272 (if (interactive-p)
1273 (message (cond (no-matches "No mismatches found")
1274 ((= num-matches 1) "1 mismatch found")
1275 (t "%d mismatches found"))
1276 num-matches)))))))
1277
1278 (defun tex-validate-region (start end)
1279 "Check for mismatched braces or $'s in region.
1280 Returns t if no mismatches. Returns nil and moves point to suspect
1281 area if a mismatch is found."
1282 (interactive "r")
1283 (let ((failure-point nil) (max-possible-sexps (- end start)))
1284 (save-excursion
1285 (condition-case ()
1286 (save-restriction
1287 (narrow-to-region start end)
1288 ;; First check that the open and close parens balance in numbers.
1289 (goto-char start)
1290 (while (and (not (eobp))
1291 (<= 0 (setq max-possible-sexps
1292 (1- max-possible-sexps))))
1293 (forward-sexp 1))
1294 ;; Now check that like matches like.
1295 (goto-char start)
1296 (while (re-search-forward "\\s(" nil t)
1297 (save-excursion
1298 (let ((pos (match-beginning 0)))
1299 (goto-char pos)
1300 (skip-chars-backward "\\\\") ; escaped parens
1301 (forward-sexp 1)
1302 (or (eq (preceding-char) (cdr (syntax-after pos)))
1303 (eq (char-after pos) (cdr (syntax-after (1- (point)))))
1304 (error "Mismatched parentheses"))))))
1305 (error
1306 (skip-syntax-forward " .>")
1307 (setq failure-point (point)))))
1308 (if failure-point (goto-char failure-point))
1309 (not failure-point)))
1310
1311 (defun tex-terminate-paragraph (inhibit-validation)
1312 "Insert two newlines, breaking a paragraph for TeX.
1313 Check for mismatched braces or $s in paragraph being terminated.
1314 A prefix arg inhibits the checking."
1315 (interactive "*P")
1316 (or inhibit-validation
1317 (save-excursion
1318 ;; For the purposes of this, a "paragraph" is a block of text
1319 ;; wherein all the brackets etc are expected to be balanced. It
1320 ;; may start after a blank line (ie a "proper" paragraph), or
1321 ;; a begin{} or end{} block, etc.
1322 (tex-validate-region
1323 (save-excursion
1324 (backward-paragraph)
1325 (point))
1326 (point)))
1327 (message "Paragraph being closed appears to contain a mismatch"))
1328 (insert "\n\n"))
1329
1330 (define-skeleton tex-insert-braces
1331 "Make a pair of braces and be poised to type inside of them."
1332 nil
1333 ?\{ _ ?})
1334
1335 ;; This function is used as the value of fill-nobreak-predicate
1336 ;; in LaTeX mode. Its job is to prevent line-breaking inside
1337 ;; of a \verb construct.
1338 (defun latex-fill-nobreak-predicate ()
1339 (save-excursion
1340 (skip-chars-backward " ")
1341 ;; Don't break after \ since `\ ' has special meaning.
1342 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
1343 (let ((opoint (point))
1344 inside)
1345 (beginning-of-line)
1346 (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
1347 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
1348 (setq inside t)))
1349 inside))))
1350
1351 (defvar latex-block-default "enumerate")
1352
1353 (defvar latex-block-args-alist
1354 '(("array" nil ?\{ (skeleton-read "Format: ") ?\})
1355 ("tabular" nil ?\{ (skeleton-read "Format: ") ?\})
1356 ("minipage" nil ?\{ (skeleton-read "Size: ") ?\})
1357 ("picture" nil ?\( (skeleton-read "SizeX,SizeY: ") ?\))
1358 ;; FIXME: This is right for Prosper, but not for seminar.
1359 ;; ("slide" nil ?\{ (skeleton-read "Title: ") ?\})
1360 )
1361 "Skeleton element to use for arguments to particular environments.
1362 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1363 the name of the environment and SKEL-ELEM is an element to use in
1364 a skeleton (see `skeleton-insert').")
1365
1366 (defvar latex-block-body-alist
1367 '(("enumerate" nil '(latex-insert-item) > _)
1368 ("itemize" nil '(latex-insert-item) > _)
1369 ("table" nil "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1370 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))
1371 \n _)
1372 ("figure" nil > _ \n "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1373 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))))
1374 "Skeleton element to use for the body of particular environments.
1375 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1376 the name of the environment and SKEL-ELEM is an element to use in
1377 a skeleton (see `skeleton-insert').")
1378
1379 ;; Like tex-insert-braces, but for LaTeX.
1380 (defalias 'tex-latex-block 'latex-insert-block)
1381 (define-skeleton latex-insert-block
1382 "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
1383 Puts point on a blank line between them."
1384 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1385 latex-block-default)
1386 (append latex-block-names
1387 latex-standard-block-names)
1388 nil nil nil nil latex-block-default)))
1389 (setq latex-block-default choice)
1390 (unless (or (member choice latex-standard-block-names)
1391 (member choice latex-block-names))
1392 ;; Remember new block names for later completion.
1393 (push choice latex-block-names))
1394 choice)
1395 \n "\\begin{" str "}"
1396 (cdr (assoc str latex-block-args-alist))
1397 > \n (or (cdr (assoc str latex-block-body-alist)) '(nil > _))
1398 (unless (bolp) '\n)
1399 "\\end{" str "}" > \n)
1400
1401 (define-skeleton latex-insert-item
1402 "Insert a \item macro."
1403 nil
1404 \n "\\item " >)
1405
1406 \f
1407 ;;;;
1408 ;;;; LaTeX syntax navigation
1409 ;;;;
1410
1411 (defmacro tex-search-noncomment (&rest body)
1412 "Execute BODY as long as it return non-nil and point is in a comment.
1413 Return the value returned by the last execution of BODY."
1414 (declare (debug t))
1415 (let ((res-sym (make-symbol "result")))
1416 `(let (,res-sym)
1417 (while
1418 (and (setq ,res-sym (progn ,@body))
1419 (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
1420 ,res-sym)))
1421
1422 (defun tex-last-unended-begin ()
1423 "Leave point at the beginning of the last `\\begin{...}' that is unended."
1424 (condition-case nil
1425 (while (and (tex-search-noncomment
1426 (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
1427 (looking-at "\\\\end"))
1428 (tex-last-unended-begin))
1429 (search-failed (error "Couldn't find unended \\begin"))))
1430
1431 (defun tex-next-unmatched-end ()
1432 "Leave point at the end of the next `\\end' that is unmatched."
1433 (while (and (tex-search-noncomment
1434 (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
1435 (save-excursion (goto-char (match-beginning 0))
1436 (looking-at "\\\\begin")))
1437 (tex-next-unmatched-end)))
1438
1439 (defun tex-next-unmatched-eparen (otype)
1440 "Leave point after the next unmatched escaped closing parenthesis.
1441 The string OTYPE is an opening parenthesis type: `(', `{', or `['."
1442 (condition-case nil
1443 (let ((ctype (char-to-string (cdr (aref (syntax-table)
1444 (string-to-char otype))))))
1445 (while (and (tex-search-noncomment
1446 (re-search-forward (format "\\\\[%s%s]" ctype otype)))
1447 (save-excursion
1448 (goto-char (match-beginning 0))
1449 (looking-at (format "\\\\%s" (regexp-quote otype)))))
1450 (tex-next-unmatched-eparen otype)))
1451 (wrong-type-argument (error "Unknown opening parenthesis type: %s" otype))
1452 (search-failed (error "Couldn't find closing escaped paren"))))
1453
1454 (defun tex-last-unended-eparen (ctype)
1455 "Leave point at the start of the last unended escaped opening parenthesis.
1456 The string CTYPE is a closing parenthesis type: `)', `}', or `]'."
1457 (condition-case nil
1458 (let ((otype (char-to-string (cdr (aref (syntax-table)
1459 (string-to-char ctype))))))
1460 (while (and (tex-search-noncomment
1461 (re-search-backward (format "\\\\[%s%s]" ctype otype)))
1462 (looking-at (format "\\\\%s" (regexp-quote ctype))))
1463 (tex-last-unended-eparen ctype)))
1464 (wrong-type-argument (error "Unknown opening parenthesis type: %s" ctype))
1465 (search-failed (error "Couldn't find unended escaped paren"))))
1466
1467 (defun tex-goto-last-unclosed-latex-block ()
1468 "Move point to the last unclosed \\begin{...}.
1469 Mark is left at original location."
1470 (interactive)
1471 (let ((spot))
1472 (save-excursion
1473 (tex-last-unended-begin)
1474 (setq spot (point)))
1475 (push-mark)
1476 (goto-char spot)))
1477
1478 ;; Don't think this one actually _needs_ (for the purposes of
1479 ;; tex-mode) to handle escaped parens.
1480 (defun latex-backward-sexp-1 ()
1481 "Like (backward-sexp 1) but aware of multi-char elements and escaped parens."
1482 (let ((pos (point))
1483 (forward-sexp-function))
1484 (backward-sexp 1)
1485 (cond ((looking-at "\\\\\\(begin\\>\\|[[({]\\)")
1486 (signal 'scan-error
1487 (list "Containing expression ends prematurely"
1488 (point) (prog1 (point) (goto-char pos)))))
1489 ((looking-at "\\\\\\([])}]\\)")
1490 (tex-last-unended-eparen (match-string 1)))
1491 ((eq (char-after) ?{)
1492 (let ((newpos (point)))
1493 (when (ignore-errors (backward-sexp 1) t)
1494 (if (or (looking-at "\\\\end\\>")
1495 ;; In case the \\ ends a verbatim section.
1496 (and (looking-at "end\\>") (eq (char-before) ?\\)))
1497 (tex-last-unended-begin)
1498 (goto-char newpos))))))))
1499
1500 ;; Note this does not handle things like mismatched brackets inside
1501 ;; begin/end blocks.
1502 ;; Needs to handle escaped parens for tex-validate-*.
1503 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2007-09/msg00038.html
1504 (defun latex-forward-sexp-1 ()
1505 "Like (forward-sexp 1) but aware of multi-char elements and escaped parens."
1506 (let ((pos (point))
1507 (forward-sexp-function))
1508 (forward-sexp 1)
1509 (let ((newpos (point)))
1510 (skip-syntax-backward "/w")
1511 (cond
1512 ((looking-at "\\\\end\\>")
1513 (signal 'scan-error
1514 (list "Containing expression ends prematurely"
1515 (point)
1516 (prog1
1517 (progn (ignore-errors (forward-sexp 2)) (point))
1518 (goto-char pos)))))
1519 ((looking-at "\\\\begin\\>")
1520 (goto-char (match-end 0))
1521 (tex-next-unmatched-end))
1522 ;; A better way to handle this, \( .. \) etc, is probably to
1523 ;; temporarily change the syntax of the \ in \( to punctuation.
1524 ((looking-back "\\\\[])}]")
1525 (signal 'scan-error
1526 (list "Containing expression ends prematurely"
1527 (- (point) 2) (prog1 (point)
1528 (goto-char pos)))))
1529 ((looking-back "\\\\\\([({[]\\)")
1530 (tex-next-unmatched-eparen (match-string 1)))
1531 (t (goto-char newpos))))))
1532
1533 (defun latex-forward-sexp (&optional arg)
1534 "Like `forward-sexp' but aware of multi-char elements and escaped parens."
1535 (interactive "P")
1536 (unless arg (setq arg 1))
1537 (let ((pos (point)))
1538 (condition-case err
1539 (while (/= arg 0)
1540 (setq arg
1541 (if (> arg 0)
1542 (progn (latex-forward-sexp-1) (1- arg))
1543 (progn (latex-backward-sexp-1) (1+ arg)))))
1544 (scan-error
1545 (goto-char pos)
1546 (signal (car err) (cdr err))))))
1547
1548 (defun latex-syntax-after ()
1549 "Like (char-syntax (char-after)) but aware of multi-char elements."
1550 (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
1551
1552 (defun latex-skip-close-parens ()
1553 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1554 (let ((forward-sexp-function nil))
1555 (while (progn (skip-syntax-forward " )")
1556 (looking-at "\\\\end\\>"))
1557 (forward-sexp 2))))
1558
1559 (defun latex-down-list ()
1560 "Like (down-list 1) but aware of multi-char elements."
1561 (forward-comment (point-max))
1562 (let ((forward-sexp-function nil))
1563 (if (not (looking-at "\\\\begin\\>"))
1564 (down-list 1)
1565 (forward-sexp 1)
1566 ;; Skip arguments.
1567 (while (looking-at "[ \t]*[[{(]")
1568 (with-syntax-table tex-mode-syntax-table
1569 (forward-sexp))))))
1570
1571 (defalias 'tex-close-latex-block 'latex-close-block)
1572 (define-skeleton latex-close-block
1573 "Create an \\end{...} to match the last unclosed \\begin{...}."
1574 (save-excursion
1575 (tex-last-unended-begin)
1576 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1577 (match-string 1)))
1578 \n "\\end" str > \n)
1579
1580 (define-skeleton latex-split-block
1581 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1582 (save-excursion
1583 (tex-last-unended-begin)
1584 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1585 (prog1 (match-string 1)
1586 (goto-char (match-end 1))
1587 (setq v1 (buffer-substring (point)
1588 (progn
1589 (while (looking-at "[ \t]*[[{]")
1590 (forward-sexp 1))
1591 (point)))))))
1592 \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
1593
1594 (defconst tex-discount-args-cmds
1595 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1596 "documentclass" "usepackage" "label")
1597 "TeX commands whose arguments should not be counted as text.")
1598
1599 (defun tex-count-words (begin end)
1600 "Count the number of words in the buffer."
1601 (interactive
1602 (if (and transient-mark-mode mark-active)
1603 (list (region-beginning) (region-end))
1604 (list (point-min) (point-max))))
1605 ;; TODO: skip comments and math and maybe some environments.
1606 (save-excursion
1607 (goto-char begin)
1608 (let ((count 0))
1609 (while (and (< (point) end) (re-search-forward "\\<" end t))
1610 (if (not (eq (char-syntax (preceding-char)) ?/))
1611 (progn
1612 ;; Don't count single-char words.
1613 (unless (looking-at ".\\>") (incf count))
1614 (forward-char 1))
1615 (let ((cmd
1616 (buffer-substring-no-properties
1617 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1618 (forward-char 1))
1619 (point)))))
1620 (when (member cmd tex-discount-args-cmds)
1621 (skip-chars-forward "*")
1622 (forward-comment (point-max))
1623 (when (looking-at "\\[")
1624 (forward-sexp 1)
1625 (forward-comment (point-max)))
1626 (if (not (looking-at "{"))
1627 (forward-char 1)
1628 (forward-sexp 1))))))
1629 (message "%s words" count))))
1630
1631
1632 \f
1633 ;;; Invoking TeX in an inferior shell.
1634
1635 ;; Why use a shell instead of running TeX directly? Because if TeX
1636 ;; gets stuck, the user can switch to the shell window and type at it.
1637
1638 ;; The utility functions:
1639
1640 (define-derived-mode tex-shell shell-mode "TeX-Shell"
1641 (set (make-local-variable 'compilation-parse-errors-function)
1642 'tex-compilation-parse-errors)
1643 (compilation-shell-minor-mode t))
1644
1645 ;;;###autoload
1646 (defun tex-start-shell ()
1647 (with-current-buffer
1648 (make-comint
1649 "tex-shell"
1650 (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
1651 nil
1652 ;; Specify an interactive shell, to make sure it prompts.
1653 "-i")
1654 (let ((proc (get-process "tex-shell")))
1655 (set-process-sentinel proc 'tex-shell-sentinel)
1656 (set-process-query-on-exit-flag proc nil)
1657 (tex-shell)
1658 (while (zerop (buffer-size))
1659 (sleep-for 1)))))
1660
1661 (defun tex-feed-input ()
1662 "Send input to the tex shell process.
1663 In the tex buffer this can be used to continue an interactive tex run.
1664 In the tex shell buffer this command behaves like `comint-send-input'."
1665 (interactive)
1666 (set-buffer (tex-shell-buf))
1667 (comint-send-input)
1668 (tex-recenter-output-buffer nil))
1669
1670 (defun tex-display-shell ()
1671 "Make the TeX shell buffer visible in a window."
1672 (display-buffer (tex-shell-buf))
1673 (tex-recenter-output-buffer nil))
1674
1675 (defun tex-shell-sentinel (proc msg)
1676 (cond ((null (buffer-name (process-buffer proc)))
1677 ;; buffer killed
1678 (set-process-buffer proc nil)
1679 (tex-delete-last-temp-files))
1680 ((memq (process-status proc) '(signal exit))
1681 (tex-delete-last-temp-files))))
1682
1683 (defun tex-set-buffer-directory (buffer directory)
1684 "Set BUFFER's default directory to be DIRECTORY."
1685 (setq directory (file-name-as-directory (expand-file-name directory)))
1686 (if (not (file-directory-p directory))
1687 (error "%s is not a directory" directory)
1688 (save-excursion
1689 (set-buffer buffer)
1690 (setq default-directory directory))))
1691
1692 (defvar tex-send-command-modified-tick 0)
1693 (make-variable-buffer-local 'tex-send-command-modified-tick)
1694
1695 (defun tex-shell-proc ()
1696 (or (tex-shell-running) (error "No TeX subprocess")))
1697 (defun tex-shell-buf ()
1698 (process-buffer (tex-shell-proc)))
1699 (defun tex-shell-buf-no-error ()
1700 (let ((proc (tex-shell-running)))
1701 (and proc (process-buffer proc))))
1702
1703 (defun tex-send-command (command &optional file background)
1704 "Send COMMAND to TeX shell process, substituting optional FILE for *.
1705 Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1706 FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1707 substitution will be made in COMMAND. COMMAND can be any expression that
1708 evaluates to a command string.
1709
1710 Return the process in which TeX is running."
1711 (save-excursion
1712 (let* ((cmd (eval command))
1713 (proc (tex-shell-proc))
1714 (buf (process-buffer proc))
1715 (star (string-match "\\*" cmd))
1716 (string
1717 (concat
1718 (if (null file)
1719 cmd
1720 (if (file-name-absolute-p file)
1721 (setq file (convert-standard-filename file)))
1722 (if star (concat (substring cmd 0 star)
1723 (shell-quote-argument file)
1724 (substring cmd (1+ star)))
1725 (concat cmd " " (shell-quote-argument file))))
1726 (if background "&" ""))))
1727 ;; Switch to buffer before checking for subproc output in it.
1728 (set-buffer buf)
1729 ;; If text is unchanged since previous tex-send-command,
1730 ;; we haven't got any output. So wait for output now.
1731 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
1732 (accept-process-output proc))
1733 (goto-char (process-mark proc))
1734 (insert string)
1735 (comint-send-input)
1736 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1737 proc)))
1738
1739 (defun tex-delete-last-temp-files (&optional not-all)
1740 "Delete any junk files from last temp file.
1741 If NOT-ALL is non-nil, save the `.dvi' file."
1742 (if tex-last-temp-file
1743 (let* ((dir (file-name-directory tex-last-temp-file))
1744 (list (and (file-directory-p dir)
1745 (file-name-all-completions
1746 (file-name-sans-extension
1747 (file-name-nondirectory tex-last-temp-file))
1748 dir))))
1749 (while list
1750 (if not-all
1751 (and
1752 ;; If arg is non-nil, don't delete the .dvi file.
1753 (not (string-match "\\.dvi$" (car list)))
1754 (delete-file (concat dir (car list))))
1755 (delete-file (concat dir (car list))))
1756 (setq list (cdr list))))))
1757
1758 (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
1759
1760 ;;
1761 ;; Machinery to guess the command that the user wants to execute.
1762 ;;
1763
1764 (defvar tex-compile-history nil)
1765
1766 (defvar tex-input-files-re
1767 (eval-when-compile
1768 (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
1769 "bbl" "ind" "sty" "cls") t)
1770 ;; Include files with no dots (for directories).
1771 "\\'\\|\\`[^.]+\\'")))
1772
1773 (defcustom tex-use-reftex t
1774 "If non-nil, use RefTeX's list of files to determine what command to use."
1775 :type 'boolean
1776 :group 'tex)
1777
1778 (defvar tex-compile-commands
1779 '(((concat "pdf" tex-command
1780 " " (if (< 0 (length tex-start-commands))
1781 (shell-quote-argument tex-start-commands)) " %f")
1782 t "%r.pdf")
1783 ((concat tex-command
1784 " " (if (< 0 (length tex-start-commands))
1785 (shell-quote-argument tex-start-commands)) " %f")
1786 t "%r.dvi")
1787 ("xdvi %r &" "%r.dvi")
1788 ("xpdf %r.pdf &" "%r.pdf")
1789 ("gv %r.ps &" "%r.ps")
1790 ("yap %r &" "%r.dvi")
1791 ("advi %r &" "%r.dvi")
1792 ("gv %r.pdf &" "%r.pdf")
1793 ("bibtex %r" "%r.aux" "%r.bbl")
1794 ("makeindex %r" "%r.idx" "%r.ind")
1795 ("texindex %r.??")
1796 ("dvipdfm %r" "%r.dvi" "%r.pdf")
1797 ("dvipdf %r" "%r.dvi" "%r.pdf")
1798 ("dvips -o %r.ps %r" "%r.dvi" "%r.ps")
1799 ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
1800 ("lpr %r.ps" "%r.ps"))
1801 "List of commands for `tex-compile'.
1802 Each element should be of the form (FORMAT IN OUT) where
1803 FORMAT is an expression that evaluates to a string that can contain
1804 - `%r' the main file name without extension.
1805 - `%f' the main file name.
1806 IN can be either a string (with the same % escapes in it) indicating
1807 the name of the input file, or t to indicate that the input is all
1808 the TeX files of the document, or nil if we don't know.
1809 OUT describes the output file and is either a %-escaped string
1810 or nil to indicate that there is no output file.")
1811
1812 ;; defsubst* gives better byte-code than defsubst.
1813 (defsubst* tex-string-prefix-p (str1 str2)
1814 "Return non-nil if STR1 is a prefix of STR2"
1815 (eq t (compare-strings str2 nil (length str1) str1 nil nil)))
1816
1817 (defun tex-guess-main-file (&optional all)
1818 "Find a likely `tex-main-file'.
1819 Looks for hints in other buffers in the same directory or in
1820 ALL other buffers. If ALL is `sub' only look at buffers in parent directories
1821 of the current buffer."
1822 (let ((dir default-directory)
1823 (header-re tex-start-of-header))
1824 (catch 'found
1825 ;; Look for a buffer with `tex-main-file' set.
1826 (dolist (buf (if (consp all) all (buffer-list)))
1827 (with-current-buffer buf
1828 (when (and (cond
1829 ((null all) (equal dir default-directory))
1830 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1831 (t))
1832 (stringp tex-main-file))
1833 (throw 'found (expand-file-name tex-main-file)))))
1834 ;; Look for a buffer containing the magic `tex-start-of-header'.
1835 (dolist (buf (if (consp all) all (buffer-list)))
1836 (with-current-buffer buf
1837 (when (and (cond
1838 ((null all) (equal dir default-directory))
1839 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1840 (t))
1841 buffer-file-name
1842 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1843 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1844 (save-excursion
1845 (save-restriction
1846 (widen)
1847 (goto-char (point-min))
1848 (re-search-forward
1849 header-re (+ (point) 10000) t))))
1850 (throw 'found (expand-file-name buffer-file-name))))))))
1851
1852 (defun tex-main-file ()
1853 "Return the relative name of the main file."
1854 (let* ((file (or tex-main-file
1855 ;; Compatibility with AUCTeX.
1856 (with-no-warnings
1857 (when (boundp 'TeX-master)
1858 (cond ((stringp TeX-master)
1859 (make-local-variable 'tex-main-file)
1860 (setq tex-main-file TeX-master))
1861 ((and (eq TeX-master t) buffer-file-name)
1862 (file-relative-name buffer-file-name)))))
1863 ;; Try to guess the main file.
1864 (if (not buffer-file-name)
1865 (error "Buffer is not associated with any file")
1866 (file-relative-name
1867 (if (save-excursion
1868 (goto-char (point-min))
1869 (re-search-forward tex-start-of-header
1870 (+ (point) 10000) t))
1871 ;; This is the main file.
1872 buffer-file-name
1873 ;; This isn't the main file, let's try to find better,
1874 (or (tex-guess-main-file)
1875 (tex-guess-main-file 'sub)
1876 ;; (tex-guess-main-file t)
1877 buffer-file-name)))))))
1878 (if (or (file-exists-p file) (string-match "\\.tex\\'" file))
1879 file (concat file ".tex"))))
1880
1881 (defun tex-summarize-command (cmd)
1882 (if (not (stringp cmd)) ""
1883 (mapconcat 'identity
1884 (mapcar (lambda (s) (car (split-string s)))
1885 (split-string cmd "\\s-*\\(?:;\\|&&\\)\\s-*"))
1886 "&")))
1887
1888 (defun tex-uptodate-p (file)
1889 "Return non-nil if FILE is not uptodate w.r.t the document source files.
1890 FILE is typically the output DVI or PDF file."
1891 ;; We should check all the files included !!!
1892 (and
1893 ;; Clearly, the target must exist.
1894 (file-exists-p file)
1895 ;; And the last run must not have asked for a rerun.
1896 ;; FIXME: this should check that the last run was done on the same file.
1897 (let ((buf (condition-case nil (tex-shell-buf) (error nil))))
1898 (when buf
1899 (with-current-buffer buf
1900 (save-excursion
1901 (goto-char (point-max))
1902 (and (re-search-backward
1903 (concat
1904 "(see the transcript file for additional information)"
1905 "\\|^Output written on .*"
1906 (regexp-quote (file-name-nondirectory file))
1907 " (.*)\\.") nil t)
1908 (> (save-excursion
1909 (or (re-search-backward "\\[[0-9]+\\]" nil t)
1910 (point-min)))
1911 (save-excursion
1912 (or (re-search-backward "Rerun" nil t)
1913 (point-min)))))))))
1914 ;; And the input files must not have been changed in the meantime.
1915 (let ((files (if (and tex-use-reftex
1916 (fboundp 'reftex-scanning-info-available-p)
1917 (reftex-scanning-info-available-p))
1918 (reftex-all-document-files)
1919 (list (file-name-directory (expand-file-name file)))))
1920 (ignored-dirs-re
1921 (concat
1922 (regexp-opt
1923 (delq nil (mapcar (lambda (s) (if (eq (aref s (1- (length s))) ?/)
1924 (substring s 0 (1- (length s)))))
1925 completion-ignored-extensions))
1926 t) "\\'"))
1927 (uptodate t))
1928 (while (and files uptodate)
1929 (let ((f (pop files)))
1930 (if (and (file-directory-p f)
1931 ;; Avoid infinite loops.
1932 (not (file-symlink-p f)))
1933 (unless (string-match ignored-dirs-re f)
1934 (setq files (nconc
1935 (ignore-errors ;Not readable or something.
1936 (directory-files f t tex-input-files-re))
1937 files)))
1938 (when (file-newer-than-file-p f file)
1939 (setq uptodate nil)))))
1940 uptodate)))
1941
1942
1943 (autoload 'format-spec "format-spec")
1944
1945 (defvar tex-executable-cache nil)
1946 (defun tex-executable-exists-p (name)
1947 "Like `executable-find' but with a cache."
1948 (let ((cache (assoc name tex-executable-cache)))
1949 (if cache (cdr cache)
1950 (let ((executable (executable-find name)))
1951 (push (cons name executable) tex-executable-cache)
1952 executable))))
1953
1954 (defun tex-command-executable (cmd)
1955 (let ((s (if (stringp cmd) cmd (eval (car cmd)))))
1956 (substring s 0 (string-match "[ \t]\\|\\'" s))))
1957
1958 (defun tex-command-active-p (cmd fspec)
1959 "Return non-nil if the CMD spec might need to be run."
1960 (let ((in (nth 1 cmd))
1961 (out (nth 2 cmd)))
1962 (if (stringp in)
1963 (let ((file (format-spec in fspec)))
1964 (when (file-exists-p file)
1965 (or (not out)
1966 (file-newer-than-file-p
1967 file (format-spec out fspec)))))
1968 (when (and (eq in t) (stringp out))
1969 (not (tex-uptodate-p (format-spec out fspec)))))))
1970
1971 (defun tex-compile-default (fspec)
1972 "Guess a default command given the `format-spec' FSPEC."
1973 ;; TODO: Learn to do latex+dvips!
1974 (let ((cmds nil)
1975 (unchanged-in nil))
1976 ;; Only consider active commands.
1977 (dolist (cmd tex-compile-commands)
1978 (when (tex-executable-exists-p (tex-command-executable cmd))
1979 (if (tex-command-active-p cmd fspec)
1980 (push cmd cmds)
1981 (push (nth 1 cmd) unchanged-in))))
1982 ;; If no command seems to be applicable, arbitrarily pick the first one.
1983 (setq cmds (if cmds (nreverse cmds) (list (car tex-compile-commands))))
1984 ;; Remove those commands whose input was considered stable for
1985 ;; some other command (typically if (t . "%.pdf") is inactive
1986 ;; then we're using pdflatex and the fact that the dvi file
1987 ;; is inexistent doesn't matter).
1988 (let ((tmp nil))
1989 (dolist (cmd cmds)
1990 (unless (member (nth 1 cmd) unchanged-in)
1991 (push cmd tmp)))
1992 ;; Only remove if there's something left.
1993 (if tmp (setq cmds (nreverse tmp))))
1994 ;; Remove commands whose input is not uptodate either.
1995 (let ((outs (delq nil (mapcar (lambda (x) (nth 2 x)) cmds)))
1996 (tmp nil))
1997 (dolist (cmd cmds)
1998 (unless (member (nth 1 cmd) outs)
1999 (push cmd tmp)))
2000 ;; Only remove if there's something left.
2001 (if tmp (setq cmds (nreverse tmp))))
2002 ;; Select which file we're going to operate on (the latest).
2003 (let ((latest (nth 1 (car cmds))))
2004 (dolist (cmd (prog1 (cdr cmds) (setq cmds (list (car cmds)))))
2005 (if (equal latest (nth 1 cmd))
2006 (push cmd cmds)
2007 (unless (eq latest t) ;Can't beat that!
2008 (if (or (not (stringp latest))
2009 (eq (nth 1 cmd) t)
2010 (and (stringp (nth 1 cmd))
2011 (file-newer-than-file-p
2012 (format-spec (nth 1 cmd) fspec)
2013 (format-spec latest fspec))))
2014 (setq latest (nth 1 cmd) cmds (list cmd)))))))
2015 ;; Expand the command spec into the actual text.
2016 (dolist (cmd (prog1 cmds (setq cmds nil)))
2017 (push (cons (eval (car cmd)) (cdr cmd)) cmds))
2018 ;; Select the favorite command from the history.
2019 (let ((hist tex-compile-history)
2020 re hist-cmd)
2021 (while hist
2022 (setq hist-cmd (pop hist))
2023 (setq re (concat "\\`"
2024 (regexp-quote (tex-command-executable hist-cmd))
2025 "\\([ \t]\\|\\'\\)"))
2026 (dolist (cmd cmds)
2027 ;; If the hist entry uses the same command and applies to a file
2028 ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
2029 (and (string-match re (car cmd))
2030 (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd)))
2031 (string-match (regexp-quote (match-string 1 (car cmd)))
2032 hist-cmd))
2033 (setq hist nil cmds (list cmd)))))
2034 ;; Substitute and return.
2035 (if (and hist-cmd
2036 (string-match (concat "[' \t\"]" (format-spec "%r" fspec)
2037 "\\([;&' \t\"]\\|\\'\\)") hist-cmd))
2038 ;; The history command was already applied to the same file,
2039 ;; so just reuse it.
2040 hist-cmd
2041 (if cmds (format-spec (caar cmds) fspec))))))
2042
2043 (defun tex-compile (dir cmd)
2044 "Run a command CMD on current TeX buffer's file in DIR."
2045 ;; FIXME: Use time-stamps on files to decide the next op.
2046 (interactive
2047 (let* ((file (tex-main-file))
2048 (default-directory
2049 (prog1 (file-name-directory (expand-file-name file))
2050 (setq file (file-name-nondirectory file))))
2051 (root (file-name-sans-extension file))
2052 (fspec (list (cons ?r (shell-quote-argument root))
2053 (cons ?f (shell-quote-argument file))))
2054 (default (tex-compile-default fspec)))
2055 (list default-directory
2056 (completing-read
2057 (format "Command [%s]: " (tex-summarize-command default))
2058 (mapcar (lambda (x)
2059 (list (format-spec (eval (car x)) fspec)))
2060 tex-compile-commands)
2061 nil nil nil 'tex-compile-history default))))
2062 (save-some-buffers (not compilation-ask-about-save) nil)
2063 (if (tex-shell-running)
2064 (tex-kill-job)
2065 (tex-start-shell))
2066 (tex-send-tex-command cmd dir))
2067
2068 (defun tex-start-tex (command file &optional dir)
2069 "Start a TeX run, using COMMAND on FILE."
2070 (let* ((star (string-match "\\*" command))
2071 (compile-command
2072 (if star
2073 (concat (substring command 0 star)
2074 (shell-quote-argument file)
2075 (substring command (1+ star)))
2076 (concat command " "
2077 tex-start-options
2078 (if (< 0 (length tex-start-commands))
2079 (concat
2080 (shell-quote-argument tex-start-commands) " "))
2081 (shell-quote-argument file)))))
2082 (tex-send-tex-command compile-command dir)))
2083
2084 (defun tex-send-tex-command (cmd &optional dir)
2085 (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
2086 (and buf (with-current-buffer buf
2087 default-directory))))
2088 (not dir))
2089 (let (shell-dirtrack-verbose)
2090 (tex-send-command tex-shell-cd-command dir)))
2091 (with-current-buffer (process-buffer (tex-send-command cmd))
2092 (setq compilation-last-buffer (current-buffer))
2093 (compilation-forget-errors)
2094 ;; Don't parse previous compilations.
2095 (set-marker compilation-parsing-end (1- (point-max))))
2096 (tex-display-shell)
2097 (setq tex-last-buffer-texed (current-buffer)))
2098 \f
2099 (defvar tex-error-parse-syntax-table
2100 (let ((st (make-syntax-table)))
2101 (modify-syntax-entry ?\( "()" st)
2102 (modify-syntax-entry ?\) ")(" st)
2103 (modify-syntax-entry ?\\ "\\" st)
2104 (modify-syntax-entry ?\{ "_" st)
2105 (modify-syntax-entry ?\} "_" st)
2106 (modify-syntax-entry ?\[ "_" st)
2107 (modify-syntax-entry ?\] "_" st)
2108 ;; Single quotations may appear in errors
2109 (modify-syntax-entry ?\" "_" st)
2110 st)
2111 "Syntax-table used while parsing TeX error messages.")
2112
2113 (defun tex-compilation-parse-errors (limit-search find-at-least)
2114 "Parse the current buffer as TeX error messages.
2115 See the variable `compilation-parse-errors-function' for the interface it uses.
2116
2117 This function parses only the last TeX compilation.
2118 It works on TeX compilations only. It is necessary for that purpose,
2119 since TeX does not put file names and line numbers on the same line as
2120 for the error messages."
2121 (require 'thingatpt)
2122 (setq compilation-error-list nil)
2123 (let ((default-directory ; Perhaps dir has changed meanwhile.
2124 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
2125 found-desired (num-errors-found 0)
2126 last-filename last-linenum last-position
2127 begin-of-error end-of-error errfilename)
2128 ;; Don't reparse messages already seen at last parse.
2129 (goto-char compilation-parsing-end)
2130 ;; Parse messages.
2131 (while (and (not (or found-desired (eobp)))
2132 ;; First alternative handles the newer --file-line-error style:
2133 ;; ./test2.tex:14: Too many }'s.
2134 ;; Second handles the old-style:
2135 ;; ! Too many }'s.
2136 (prog1 (re-search-forward
2137 "^\\(?:\\([^:\n]+\\):[[:digit:]]+:\\|!\\) " nil 'move)
2138 (setq begin-of-error (match-beginning 0)
2139 end-of-error (match-end 0)
2140 errfilename (match-string 1)))
2141 (re-search-forward
2142 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
2143 (let* ((this-error (copy-marker begin-of-error))
2144 (linenum (string-to-number (match-string 1)))
2145 (error-text (regexp-quote (match-string 3)))
2146 (filename
2147 ;; Prefer --file-liner-error filename if we have it.
2148 (or errfilename
2149 (save-excursion
2150 (with-syntax-table tex-error-parse-syntax-table
2151 (backward-up-list 1)
2152 (skip-syntax-forward "(_")
2153 (while (not (file-readable-p (thing-at-point 'filename)))
2154 (skip-syntax-backward "(_")
2155 (backward-up-list 1)
2156 (skip-syntax-forward "(_"))
2157 (thing-at-point 'filename)))))
2158 (new-file
2159 (or (null last-filename)
2160 (not (string-equal last-filename filename))))
2161 (error-location
2162 (with-current-buffer
2163 (if (equal filename (concat tex-zap-file ".tex"))
2164 tex-last-buffer-texed
2165 (find-file-noselect filename))
2166 (save-excursion
2167 (if new-file
2168 (progn (goto-line linenum) (setq last-position nil))
2169 (goto-char last-position)
2170 (forward-line (- linenum last-linenum)))
2171 ;; first try a forward search for the error text,
2172 ;; then a backward search limited by the last error.
2173 (let ((starting-point (point)))
2174 (or (re-search-forward error-text nil t)
2175 (re-search-backward error-text last-position t)
2176 (goto-char starting-point)))
2177 (point-marker)))))
2178 (goto-char this-error)
2179 (if (and compilation-error-list
2180 (or (and find-at-least
2181 (>= num-errors-found
2182 find-at-least))
2183 (and limit-search
2184 (>= end-of-error limit-search)))
2185 new-file)
2186 (setq found-desired t)
2187 (setq num-errors-found (1+ num-errors-found)
2188 last-filename filename
2189 last-linenum linenum
2190 last-position error-location
2191 compilation-error-list ; Add the new error
2192 (cons (cons this-error error-location)
2193 compilation-error-list))
2194 (goto-char end-of-error)))))
2195 (set-marker compilation-parsing-end (point))
2196 (setq compilation-error-list (nreverse compilation-error-list)))
2197 \f
2198 ;;; The commands:
2199
2200 (defun tex-region (beg end)
2201 "Run TeX on the current region, via a temporary file.
2202 The file's name comes from the variable `tex-zap-file' and the
2203 variable `tex-directory' says where to put it.
2204
2205 If the buffer has a header, the header is given to TeX before the
2206 region itself. The buffer's header is all lines between the strings
2207 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
2208 The header must start in the first 100 lines of the buffer.
2209
2210 The value of `tex-trailer' is given to TeX as input after the region.
2211
2212 The value of `tex-command' specifies the command to use to run TeX."
2213 (interactive "r")
2214 (if (tex-shell-running)
2215 (tex-kill-job)
2216 (tex-start-shell))
2217 (or tex-zap-file
2218 (setq tex-zap-file (tex-generate-zap-file-name)))
2219 ;; Temp file will be written and TeX will be run in zap-directory.
2220 ;; If the TEXINPUTS file has relative directories or if the region has
2221 ;; \input of files, this must be the same directory as the file for
2222 ;; TeX to access the correct inputs. That's why it's safest if
2223 ;; tex-directory is ".".
2224 (let* ((zap-directory
2225 (file-name-as-directory (expand-file-name tex-directory)))
2226 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
2227 zap-directory))
2228 (main-file (expand-file-name (tex-main-file)))
2229 (ismain (string-equal main-file (buffer-file-name)))
2230 already-output)
2231 ;; Don't delete temp files if we do the same buffer twice in a row.
2232 (or (eq (current-buffer) tex-last-buffer-texed)
2233 (tex-delete-last-temp-files t))
2234 (let ((default-directory zap-directory)) ; why?
2235 ;; We assume the header is fully contained in tex-main-file.
2236 ;; We use f-f-ns so we get prompted about any changes on disk.
2237 (with-current-buffer (find-file-noselect main-file)
2238 (setq already-output (tex-region-header tex-out-file
2239 (and ismain beg))))
2240 ;; Write out the specified region (but don't repeat anything
2241 ;; already written in the header).
2242 (write-region (if ismain
2243 (max beg already-output)
2244 beg)
2245 end tex-out-file (not (zerop already-output)))
2246 ;; Write the trailer, if any.
2247 ;; Precede it with a newline to make sure it
2248 ;; is not hidden in a comment.
2249 (if tex-trailer
2250 (write-region (concat "\n" tex-trailer) nil
2251 tex-out-file t)))
2252 ;; Record the file name to be deleted afterward.
2253 (setq tex-last-temp-file tex-out-file)
2254 ;; Use a relative file name here because (1) the proper dir
2255 ;; is already current, and (2) the abs file name is sometimes
2256 ;; too long and can make tex crash.
2257 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
2258 (setq tex-print-file tex-out-file)))
2259
2260 (defun tex-region-header (file &optional beg)
2261 "If there is a TeX header in the current buffer, write it to FILE.
2262 Return point at the end of the region so written, or zero. If
2263 the optional buffer position BEG is specified, then the region
2264 written out starts at BEG, if this lies before the start of the header.
2265
2266 If the first line matches `tex-first-line-header-regexp', it is
2267 also written out. The variables `tex-start-of-header' and
2268 `tex-end-of-header' are used to locate the header. Note that the
2269 start of the header is required to be within the first 100 lines."
2270 (save-excursion
2271 (save-restriction
2272 (widen)
2273 (goto-char (point-min))
2274 (let ((search-end (save-excursion
2275 (forward-line 100)
2276 (point)))
2277 (already-output 0)
2278 hbeg hend)
2279 ;; Maybe copy first line, such as `\input texinfo', to temp file.
2280 (and tex-first-line-header-regexp
2281 (looking-at tex-first-line-header-regexp)
2282 (write-region (point)
2283 (progn (forward-line 1)
2284 (setq already-output (point)))
2285 file))
2286 ;; Write out the header, if there is one, and any of the
2287 ;; specified region which extends before it. But don't repeat
2288 ;; anything already written.
2289 (and tex-start-of-header
2290 (re-search-forward tex-start-of-header search-end t)
2291 (progn
2292 (beginning-of-line)
2293 (setq hbeg (point)) ; mark beginning of header
2294 (when (re-search-forward tex-end-of-header nil t)
2295 (forward-line 1)
2296 (setq hend (point)) ; mark end of header
2297 (write-region
2298 (max (if beg
2299 (min hbeg beg)
2300 hbeg)
2301 already-output)
2302 hend file (not (zerop already-output)))
2303 (setq already-output hend))))
2304 already-output))))
2305
2306 (defun tex-buffer ()
2307 "Run TeX on current buffer. See \\[tex-region] for more information.
2308 Does not save the buffer, so it's useful for trying experimental versions.
2309 See \\[tex-file] for an alternative."
2310 (interactive)
2311 (tex-region (point-min) (point-max)))
2312
2313 (defun tex-file ()
2314 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
2315 This function is more useful than \\[tex-buffer] when you need the
2316 `.aux' file of LaTeX to have the correct name."
2317 (interactive)
2318 (when tex-offer-save
2319 (save-some-buffers))
2320 (let* ((source-file (tex-main-file))
2321 (file-dir (file-name-directory (expand-file-name source-file))))
2322 (if (tex-shell-running)
2323 (tex-kill-job)
2324 (tex-start-shell))
2325 (tex-start-tex tex-command source-file file-dir)
2326 (setq tex-print-file (expand-file-name source-file))))
2327
2328 (defun tex-generate-zap-file-name ()
2329 "Generate a unique name suitable for use as a file name."
2330 ;; Include the shell process number and host name
2331 ;; in case there are multiple shells (for same or different user).
2332 ;; Dec 1998: There is a report that some versions of xdvi
2333 ;; don't work with file names that start with #.
2334 (format "_TZ_%d-%s"
2335 (process-id (get-buffer-process "*tex-shell*"))
2336 (subst-char-in-string ?. ?- (system-name))))
2337
2338 ;; This will perhaps be useful for modifying TEXINPUTS.
2339 ;; Expand each file name, separated by colons, in the string S.
2340 (defun tex-expand-files (s)
2341 (let (elts (start 0))
2342 (while (string-match ":" s start)
2343 (setq elts (cons (substring s start (match-beginning 0)) elts))
2344 (setq start (match-end 0)))
2345 (or (= start 0)
2346 (setq elts (cons (substring s start) elts)))
2347 (mapconcat (lambda (elt)
2348 (if (= (length elt) 0) elt (expand-file-name elt)))
2349 (nreverse elts) ":")))
2350
2351 (defun tex-shell-running ()
2352 (let ((proc (get-process "tex-shell")))
2353 (when proc
2354 (if (and (eq (process-status proc) 'run)
2355 (buffer-live-p (process-buffer proc)))
2356 ;; return the TeX process on success
2357 proc
2358 ;; get rid of the process permanently
2359 ;; this should get rid of the annoying w32 problem with
2360 ;; dead tex-shell buffer and live process
2361 (delete-process proc)))))
2362
2363 (defun tex-kill-job ()
2364 "Kill the currently running TeX job."
2365 (interactive)
2366 ;; `quit-process' leads to core dumps of the tex process (except if
2367 ;; coredumpsize has limit 0kb as on many environments). One would
2368 ;; like to use (kill-process proc 'lambda), however that construct
2369 ;; does not work on some systems and kills the shell itself.
2370 (let ((proc (get-process "tex-shell")))
2371 (when proc (quit-process proc t))))
2372
2373 (defun tex-recenter-output-buffer (linenum)
2374 "Redisplay buffer of TeX job output so that most recent output can be seen.
2375 The last line of the buffer is displayed on
2376 line LINE of the window, or centered if LINE is nil."
2377 (interactive "P")
2378 (let ((tex-shell (get-buffer "*tex-shell*"))
2379 (window))
2380 (if (null tex-shell)
2381 (message "No TeX output buffer")
2382 (setq window (display-buffer tex-shell))
2383 (save-selected-window
2384 (select-window window)
2385 (bury-buffer tex-shell)
2386 (goto-char (point-max))
2387 (recenter (if linenum
2388 (prefix-numeric-value linenum)
2389 (/ (window-height) 2)))))))
2390
2391 (defun tex-print (&optional alt)
2392 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2393 Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
2394 is provided, use the alternative command, `tex-alt-dvi-print-command'."
2395 (interactive "P")
2396 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
2397 test-name)
2398 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
2399 (buffer-file-name)
2400 ;; Check that this buffer's printed file is up to date.
2401 (file-newer-than-file-p
2402 (setq test-name (tex-append (buffer-file-name) ".dvi"))
2403 (buffer-file-name)))
2404 (setq print-file-name-dvi test-name))
2405 (if (not (file-exists-p print-file-name-dvi))
2406 (error "No appropriate `.dvi' file could be found")
2407 (if (tex-shell-running)
2408 (tex-kill-job)
2409 (tex-start-shell))
2410 (tex-send-command
2411 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
2412 print-file-name-dvi
2413 t))))
2414
2415 (defun tex-alt-print ()
2416 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2417 Runs the shell command defined by `tex-alt-dvi-print-command'."
2418 (interactive)
2419 (tex-print t))
2420
2421 (defun tex-view ()
2422 "Preview the last `.dvi' file made by running TeX under Emacs.
2423 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2424 The variable `tex-dvi-view-command' specifies the shell command for preview.
2425 You must set that variable yourself before using this command,
2426 because there is no standard value that would generally work."
2427 (interactive)
2428 (or tex-dvi-view-command
2429 (error "You must set `tex-dvi-view-command'"))
2430 ;; Restart the TeX shell if necessary.
2431 (or (tex-shell-running)
2432 (tex-start-shell))
2433 (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
2434 (tex-print)))
2435
2436 (defun tex-append (file-name suffix)
2437 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
2438 Pascal-based TeX scans for the first period, C TeX uses the last.
2439 No period is retained immediately before SUFFIX,
2440 so normally SUFFIX starts with one."
2441 (if (stringp file-name)
2442 (let ((file (file-name-nondirectory file-name))
2443 trial-name)
2444 ;; Try splitting on last period.
2445 ;; The first-period split can get fooled when two files
2446 ;; named a.tex and a.b.tex are both tex'd;
2447 ;; the last-period split must be right if it matches at all.
2448 (setq trial-name
2449 (concat (file-name-directory file-name)
2450 (substring file 0
2451 (string-match "\\.[^.]*$" file))
2452 suffix))
2453 (if (or (file-exists-p trial-name)
2454 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
2455 trial-name
2456 ;; Not found, so split on first period.
2457 (concat (file-name-directory file-name)
2458 (substring file 0
2459 (string-match "\\." file))
2460 suffix)))
2461 " "))
2462
2463 (defun tex-show-print-queue ()
2464 "Show the print queue that \\[tex-print] put your job on.
2465 Runs the shell command defined by `tex-show-queue-command'."
2466 (interactive)
2467 (if (tex-shell-running)
2468 (tex-kill-job)
2469 (tex-start-shell))
2470 (tex-send-command tex-show-queue-command)
2471 (tex-display-shell))
2472
2473 (defun tex-bibtex-file ()
2474 "Run BibTeX on the current buffer's file."
2475 (interactive)
2476 (if (tex-shell-running)
2477 (tex-kill-job)
2478 (tex-start-shell))
2479 (let (shell-dirtrack-verbose
2480 (tex-out-file
2481 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
2482 (file-dir (file-name-directory (buffer-file-name))))
2483 (tex-send-command tex-shell-cd-command file-dir)
2484 (tex-send-command tex-bibtex-command tex-out-file))
2485 (tex-display-shell))
2486 \f
2487 ;;;;
2488 ;;;; LaTeX indentation
2489 ;;;;
2490
2491 (defvar tex-indent-allhanging t)
2492 (defvar tex-indent-arg 4)
2493 (defvar tex-indent-basic 2)
2494 (defvar tex-indent-item tex-indent-basic)
2495 (defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
2496 (defvar latex-noindent-environments '("document"))
2497
2498 (defvar tex-latex-indent-syntax-table
2499 (let ((st (make-syntax-table tex-mode-syntax-table)))
2500 (modify-syntax-entry ?$ "." st)
2501 (modify-syntax-entry ?\( "." st)
2502 (modify-syntax-entry ?\) "." st)
2503 st)
2504 "Syntax table used while computing indentation.")
2505
2506 (defun latex-indent (&optional arg)
2507 (if (and (eq (get-text-property (line-beginning-position) 'face)
2508 'tex-verbatim))
2509 'noindent
2510 (with-syntax-table tex-latex-indent-syntax-table
2511 ;; TODO: Rather than ignore $, we should try to be more clever about it.
2512 (let ((indent
2513 (save-excursion
2514 (beginning-of-line)
2515 (latex-find-indent))))
2516 (if (< indent 0) (setq indent 0))
2517 (if (<= (current-column) (current-indentation))
2518 (indent-line-to indent)
2519 (save-excursion (indent-line-to indent)))))))
2520
2521 (defun latex-find-indent (&optional virtual)
2522 "Find the proper indentation of text after point.
2523 VIRTUAL if non-nil indicates that we're only trying to find the indentation
2524 in order to determine the indentation of something else.
2525 There might be text before point."
2526 (save-excursion
2527 (skip-chars-forward " \t")
2528 (or
2529 ;; Stick the first line at column 0.
2530 (and (= (point-min) (line-beginning-position)) 0)
2531 ;; Trust the current indentation, if such info is applicable.
2532 (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
2533 (current-column))
2534 ;; Stick verbatim environments to the left margin.
2535 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2536 (member (match-string 2) tex-verbatim-environments)
2537 0)
2538 ;; Put leading close-paren where the matching open brace would be.
2539 (and (eq (latex-syntax-after) ?\))
2540 (ignore-errors
2541 (save-excursion
2542 (latex-skip-close-parens)
2543 (latex-backward-sexp-1)
2544 (latex-find-indent 'virtual))))
2545 ;; Default (maybe an argument)
2546 (let ((pos (point))
2547 ;; Outdent \item if necessary.
2548 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
2549 up-list-pos)
2550 ;; Find the previous point which determines our current indentation.
2551 (condition-case err
2552 (progn
2553 (latex-backward-sexp-1)
2554 (while (> (current-column) (current-indentation))
2555 (latex-backward-sexp-1)))
2556 (scan-error
2557 (setq up-list-pos (nth 2 err))))
2558 (cond
2559 ((= (point-min) pos) 0) ; We're really just indenting the first line.
2560 ((integerp up-list-pos)
2561 ;; Have to indent relative to the open-paren.
2562 (goto-char up-list-pos)
2563 (if (and (not tex-indent-allhanging)
2564 (save-excursion
2565 ;; Make sure we're an argument to a macro and
2566 ;; that the macro is at the beginning of a line.
2567 (condition-case nil
2568 (progn
2569 (while (eq (char-syntax (char-after)) ?\()
2570 (forward-sexp -1))
2571 (and (eq (char-syntax (char-after)) ?/)
2572 (progn (skip-chars-backward " \t&")
2573 (bolp))))
2574 (scan-error nil)))
2575 (> pos (progn (latex-down-list)
2576 (forward-comment (point-max))
2577 (point))))
2578 ;; Align with the first element after the open-paren.
2579 (current-column)
2580 ;; We're the first element after a hanging brace.
2581 (goto-char up-list-pos)
2582 (+ (if (and (looking-at "\\\\begin *{\\([^\n}]+\\)")
2583 (member (match-string 1)
2584 latex-noindent-environments))
2585 0 tex-indent-basic)
2586 indent (latex-find-indent 'virtual))))
2587 ;; We're now at the "beginning" of a line.
2588 ((not (and (not virtual) (eq (char-after) ?\\)))
2589 ;; Nothing particular here: just keep the same indentation.
2590 (+ indent (current-column)))
2591 ;; We're now looking at a macro call.
2592 ((looking-at tex-indent-item-re)
2593 ;; Indenting relative to an item, have to re-add the outdenting.
2594 (+ indent (current-column) tex-indent-item))
2595 (t
2596 (let ((col (current-column)))
2597 (if (or (not (eq (char-syntax (or (char-after pos) ?\s)) ?\())
2598 ;; Can't be an arg if there's an empty line inbetween.
2599 (save-excursion (re-search-forward "^[ \t]*$" pos t)))
2600 ;; If the first char was not an open-paren, there's
2601 ;; a risk that this is really not an argument to the
2602 ;; macro at all.
2603 (+ indent col)
2604 (forward-sexp 1)
2605 (if (< (line-end-position)
2606 (save-excursion (forward-comment (point-max))
2607 (point)))
2608 ;; we're indenting the first argument.
2609 (min (current-column) (+ tex-indent-arg col))
2610 (skip-syntax-forward " ")
2611 (current-column))))))))))
2612 ;;; DocTeX support
2613
2614 (defun doctex-font-lock-^^A ()
2615 (if (eq (char-after (line-beginning-position)) ?\%)
2616 (progn
2617 (put-text-property
2618 (1- (match-beginning 1)) (match-beginning 1)
2619 'syntax-table
2620 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2621 ;; The `%' is a single-char comment, which Emacs
2622 ;; syntax-table can't deal with. We could turn it
2623 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2624 ;; Instead, we include it in the ^^A comment.
2625 (eval-when-compile (string-to-syntax "< b"))
2626 (eval-when-compile (string-to-syntax ">"))))
2627 (let ((end (line-end-position)))
2628 (if (< end (point-max))
2629 (put-text-property
2630 end (1+ end)
2631 'syntax-table
2632 (eval-when-compile (string-to-syntax "> b")))))
2633 (eval-when-compile (string-to-syntax "< b")))))
2634
2635 (defun doctex-font-lock-syntactic-face-function (state)
2636 ;; Mark DocTeX documentation, which is parsed as a style A comment
2637 ;; starting in column 0.
2638 (if (or (nth 3 state) (nth 7 state)
2639 (not (memq (char-before (nth 8 state))
2640 '(?\n nil))))
2641 ;; Anything else is just as for LaTeX.
2642 (tex-font-lock-syntactic-face-function state)
2643 font-lock-doc-face))
2644
2645 (defvar doctex-font-lock-syntactic-keywords
2646 (append
2647 tex-font-lock-syntactic-keywords
2648 ;; For DocTeX comment-in-doc.
2649 `(("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A))))))
2650
2651 (defvar doctex-font-lock-keywords
2652 (append tex-font-lock-keywords
2653 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t)))))
2654
2655 ;;;###autoload
2656 (define-derived-mode doctex-mode latex-mode "DocTeX"
2657 "Major mode to edit DocTeX files."
2658 (setq font-lock-defaults
2659 (cons (append (car font-lock-defaults) '(doctex-font-lock-keywords))
2660 (mapcar
2661 (lambda (x)
2662 (case (car-safe x)
2663 (font-lock-syntactic-keywords
2664 (cons (car x) 'doctex-font-lock-syntactic-keywords))
2665 (font-lock-syntactic-face-function
2666 (cons (car x) 'doctex-font-lock-syntactic-face-function))
2667 (t x)))
2668 (cdr font-lock-defaults)))))
2669
2670 (run-hooks 'tex-mode-load-hook)
2671
2672 (provide 'tex-mode)
2673
2674 ;; arch-tag: c0a680b1-63aa-4547-84b9-4193c29c0080
2675 ;;; tex-mode.el ends here