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