]> code.delx.au - gnu-emacs/blob - lisp/textmodes/tex-mode.el
(tex-font-lock-keywords-1): Use `keep'
[gnu-emacs] / lisp / textmodes / tex-mode.el
1 ;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands.
2
3 ;; Copyright (C) 1985, 86, 89, 92, 94, 95, 96, 97, 98, 1999
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 ;;; Code:
30
31 ;; Pacify the byte-compiler
32 (eval-when-compile
33 (require 'compare-w)
34 (require 'cl)
35 (require 'skeleton))
36
37 (require 'shell)
38 (require 'compile)
39
40 (defgroup tex-file nil
41 "TeX files and directories"
42 :prefix "tex-"
43 :group 'tex)
44
45 (defgroup tex-run nil
46 "Running external commands from TeX mode"
47 :prefix "tex-"
48 :group 'tex)
49
50 (defgroup tex-view nil
51 "Viewing and printing TeX files"
52 :prefix "tex-"
53 :group 'tex)
54
55 ;;;###autoload
56 (defcustom tex-shell-file-name nil
57 "*If non-nil, the shell file name to run in the subshell used to run TeX."
58 :type '(choice (const :tag "None" nil)
59 string)
60 :group 'tex-run)
61
62 ;;;###autoload
63 (defcustom tex-directory "."
64 "*Directory in which temporary files are written.
65 You can make this `/tmp' if your TEXINPUTS has no relative directories in it
66 and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
67 `\\input' commands with relative directories."
68 :type 'directory
69 :group 'tex-file)
70
71 ;;;###autoload
72 (defcustom tex-first-line-header-regexp nil
73 "Regexp for matching a first line which `tex-region' should include.
74 If this is non-nil, it should be a regular expression string;
75 if it matches the first line of the file,
76 `tex-region' always includes the first line in the TeX run."
77 :type '(choice (const :tag "None" nil)
78 regexp)
79 :group 'tex-file)
80
81 ;;;###autoload
82 (defcustom tex-main-file nil
83 "*The main TeX source file which includes this buffer's file.
84 The command `tex-file' runs TeX on the file specified by `tex-main-file'
85 if the variable is non-nil."
86 :type '(choice (const :tag "None" nil)
87 file)
88 :group 'tex-file)
89
90 ;;;###autoload
91 (defcustom tex-offer-save t
92 "*If non-nil, ask about saving modified buffers before \\[tex-file] is run."
93 :type 'boolean
94 :group 'tex-file)
95
96 ;;;###autoload
97 (defcustom tex-run-command "tex"
98 "*Command used to run TeX subjob.
99 TeX Mode sets `tex-command' to this string.
100 See the documentation of that variable."
101 :type 'string
102 :group 'tex-run)
103
104 ;;;###autoload
105 (defcustom latex-run-command "latex"
106 "*Command used to run LaTeX subjob.
107 LaTeX Mode sets `tex-command' to this string.
108 See the documentation of that variable."
109 :type 'string
110 :group 'tex-run)
111
112 ;;;###autoload
113 (defcustom slitex-run-command "slitex"
114 "*Command used to run SliTeX subjob.
115 SliTeX Mode sets `tex-command' to this string.
116 See the documentation of that variable."
117 :type 'string
118 :group 'tex-run)
119
120 ;;;###autoload
121 (defcustom tex-start-options-string "\\nonstopmode\\input"
122 "*TeX options to use when running TeX.
123 These precede the input file name. If nil, TeX runs without option.
124 See the documentation of `tex-command'."
125 :type '(radio (const :tag "Interactive \(nil\)" nil)
126 (const :tag "Nonstop \(\"\\nonstopmode\\input\"\)"
127 "\\nonstopmode\\input")
128 (string :tag "String at your choice"))
129 :group 'tex-run
130 :version "20.4")
131
132 (defvar standard-latex-block-names
133 '("abstract" "array" "center" "description"
134 "displaymath" "document" "enumerate" "eqnarray"
135 "eqnarray*" "equation" "figure" "figure*"
136 "flushleft" "flushright" "itemize" "letter"
137 "list" "minipage" "picture" "quotation"
138 "quote" "slide" "sloppypar" "tabbing"
139 "table" "table*" "tabular" "tabular*"
140 "thebibliography" "theindex*" "titlepage" "trivlist"
141 "verbatim" "verbatim*" "verse" "math")
142 "Standard LaTeX block names.")
143
144 ;;;###autoload
145 (defcustom latex-block-names nil
146 "*User defined LaTeX block names.
147 Combined with `standard-latex-block-names' for minibuffer completion."
148 :type '(repeat string)
149 :group 'tex-run)
150
151 ;;;###autoload
152 (defcustom tex-bibtex-command "bibtex"
153 "*Command used by `tex-bibtex-file' to gather bibliographic data.
154 If this string contains an asterisk (`*'), that is replaced by the file name;
155 otherwise, the file name, preceded by blank, is added at the end."
156 :type 'string
157 :group 'tex-run)
158
159 ;;;###autoload
160 (defcustom tex-dvi-print-command "lpr -d"
161 "*Command used by \\[tex-print] to print a .dvi file.
162 If this string contains an asterisk (`*'), that is replaced by the file name;
163 otherwise, the file name, preceded by blank, is added at the end."
164 :type 'string
165 :group 'tex-view)
166
167 ;;;###autoload
168 (defcustom tex-alt-dvi-print-command "lpr -d"
169 "*Command used by \\[tex-print] with a prefix arg to print a .dvi file.
170 If this string contains an asterisk (`*'), that is replaced by the file name;
171 otherwise, the file name, preceded by blank, is added at the end.
172
173 If two printers are not enough of a choice, you can set the variable
174 `tex-alt-dvi-print-command' to an expression that asks what you want;
175 for example,
176
177 (setq tex-alt-dvi-print-command
178 '(format \"lpr -P%s\" (read-string \"Use printer: \")))
179
180 would tell \\[tex-print] with a prefix argument to ask you which printer to
181 use."
182 :type '(choice (string :tag "Command")
183 (sexp :tag "Expression"))
184 :group 'tex-view)
185
186 ;;;###autoload
187 (defcustom tex-dvi-view-command nil
188 "*Command used by \\[tex-view] to display a `.dvi' file.
189 If this string contains an asterisk (`*'), that is replaced by the file name;
190 otherwise, the file name, preceded by blank, is added at the end.
191
192 This can be set conditionally so that the previewer used is suitable for the
193 window system being used. For example,
194
195 (setq tex-dvi-view-command
196 (if (eq window-system 'x) \"xdvi\" \"dvi2tty * | cat -s\"))
197
198 would tell \\[tex-view] to use xdvi under X windows and to use dvi2tty
199 otherwise."
200 :type '(choice (const nil) string)
201 :group 'tex-view)
202
203 ;;;###autoload
204 (defcustom tex-show-queue-command "lpq"
205 "*Command used by \\[tex-show-print-queue] to show the print queue.
206 Should show the queue(s) that \\[tex-print] puts jobs on."
207 :type 'string
208 :group 'tex-view)
209
210 ;;;###autoload
211 (defcustom tex-default-mode 'latex-mode
212 "*Mode to enter for a new file that might be either TeX or LaTeX.
213 This variable is used when it can't be determined whether the file
214 is plain TeX or LaTeX or what because the file contains no commands.
215 Normally set to either `plain-tex-mode' or `latex-mode'."
216 :type 'function
217 :group 'tex)
218
219 ;;;###autoload
220 (defcustom tex-open-quote "``"
221 "*String inserted by typing \\[tex-insert-quote] to open a quotation."
222 :type 'string
223 :group 'tex)
224
225 ;;;###autoload
226 (defcustom tex-close-quote "''"
227 "*String inserted by typing \\[tex-insert-quote] to close a quotation."
228 :type 'string
229 :group 'tex)
230
231 (defvar tex-last-temp-file nil
232 "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
233 Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
234 tex shell terminates.")
235
236 (defvar tex-command nil
237 "*Command to run TeX.
238 If this string contains an asterisk \(`*'\), that is replaced by the file name\;
239 otherwise the \(shell-quoted\) value of `tex-start-options-string' and
240 the file name are added at the end, with blanks as separators.
241
242 In TeX, LaTeX, and SliTeX Mode this variable becomes buffer local.
243 In these modes, use \\[set-variable] if you want to change it for the
244 current buffer.")
245
246 (defvar tex-trailer nil
247 "String appended after the end of a region sent to TeX by \\[tex-region].")
248
249 (defvar tex-start-of-header nil
250 "Regular expression used by \\[tex-region] to find start of file's header.")
251
252 (defvar tex-end-of-header nil
253 "Regular expression used by \\[tex-region] to find end of file's header.")
254
255 (defvar tex-shell-cd-command "cd"
256 "Command to give to shell running TeX to change directory.
257 The value of `tex-directory' is appended to this, separated by a space.")
258
259 (defvar tex-zap-file nil
260 "Temporary file name used for text being sent as input to TeX.
261 Should be a simple file name with no extension or directory specification.")
262
263 (defvar tex-last-buffer-texed nil
264 "Buffer which was last TeXed.")
265
266 (defvar tex-print-file nil
267 "File name that \\[tex-print] prints.
268 Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
269
270 (easy-mmode-defsyntax tex-mode-syntax-table
271 '((?% . "<")
272 (?\n . ">")
273 (?\f . ">")
274 (?\C-@ . "w")
275 (?' . "w")
276 (?@ . "_")
277 (?* . "_")
278 (?\t . " ")
279 (?~ . " ")
280 (?$ . "$$")
281 (?\\ . "/")
282 (?\" . ".")
283 (?& . ".")
284 (?_ . "."))
285 "Syntax table used while in TeX mode.")
286 \f
287 ;;;;
288 ;;;; Imenu support
289 ;;;;
290
291 (defcustom latex-imenu-indent-string ". "
292 "*String to add repeated in front of nested sectional units for Imenu.
293 An alternative value is \" . \", if you use a font with a narrow period."
294 :type 'string
295 :group 'tex)
296
297 (defvar latex-section-alist
298 '(("part" . 0) ("chapter" . 1)
299 ("section" . 2) ("subsection" . 3)
300 ("subsubsection" . 4)
301 ("paragraph" . 5) ("subparagraph" . 6)))
302
303 (defvar latex-metasection-list
304 '("documentstyle" "documentclass"
305 "begin{document}" "end{document}"
306 "appendix" "frontmatter" "mainmatter" "backmatter"))
307
308 (defun latex-imenu-create-index ()
309 "Generate an alist for imenu from a LaTeX buffer."
310 (let ((section-regexp
311 (concat "\\\\" (regexp-opt (mapcar 'car latex-section-alist) t)
312 "\\*?[ \t]*{"))
313 (metasection-regexp
314 (concat "\\\\" (regexp-opt latex-metasection-list t)))
315 i0 menu case-fold-search)
316 (save-excursion
317 ;; Find the top-most level in this file but don't allow it to be
318 ;; any deeper than "section" (which is top-level in an article).
319 (goto-char (point-min))
320 (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t)
321 (setq i0 0)
322 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
323 (setq i0 1)
324 (setq i0 2)))
325
326 ;; Look for chapters and sections.
327 (goto-char (point-min))
328 (while (search-forward-regexp section-regexp nil t)
329 (let ((start (match-beginning 0))
330 (here (point))
331 (i (cdr (assoc (buffer-substring-no-properties
332 (match-beginning 1)
333 (match-end 1))
334 latex-section-alist))))
335 (backward-char 1)
336 (condition-case err
337 (progn
338 ;; Using sexps allows some use of matching {...} inside
339 ;; titles.
340 (forward-sexp 1)
341 (push (cons (concat (apply 'concat
342 (make-list
343 (max 0 (- i i0))
344 latex-imenu-indent-string))
345 (buffer-substring-no-properties
346 here (1- (point))))
347 start)
348 menu))
349 (error nil))))
350
351 ;; Look for included material.
352 (goto-char (point-min))
353 (while (search-forward-regexp
354 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
355 \[ \t]*{\\([^}\n]+\\)}"
356 nil t)
357 (push (cons (concat "<<" (buffer-substring-no-properties
358 (match-beginning 2)
359 (match-end 2))
360 (if (= (char-after (match-beginning 1)) ?b)
361 ".bbl"
362 ".tex"))
363 (match-beginning 0))
364 menu))
365
366 ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
367 (goto-char (point-min))
368 (while (search-forward-regexp metasection-regexp nil t)
369 (push (cons "--" (match-beginning 0)) menu))
370
371 ;; Sort in increasing buffer position order.
372 (sort menu (function (lambda (a b) (< (cdr a) (cdr b))))))))
373 \f
374 ;;;;
375 ;;;; Outline support
376 ;;;;
377
378 (defvar latex-outline-regexp
379 (concat "\\\\"
380 (regexp-opt (append latex-metasection-list
381 (mapcar 'car latex-section-alist)) t)))
382
383 (defun latex-outline-level ()
384 (if (looking-at latex-outline-regexp)
385 (1+ (or (cdr (assoc (match-string 1) latex-section-alist)) -1))
386 1000))
387 \f
388 ;;;;
389 ;;;; Font-Lock support
390 ;;;;
391
392 ;(defvar tex-font-lock-keywords
393 ; ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
394 ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
395 ; 2 font-lock-function-name-face)
396 ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
397 ; 2 font-lock-constant-face)
398 ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
399 ; ;; not be able to display those fonts.
400 ; ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
401 ; ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
402 ; ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
403 ; ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
404 ; ;; Rewritten and extended for LaTeX2e by Ulrik Dickow <dickow@nbi.dk>.
405 ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
406 ; 2 font-lock-function-name-face)
407 ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
408 ; 2 font-lock-constant-face)
409 ; ("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)" 1 font-lock-function-name-face)
410 ; "\\\\\\([a-zA-Z@]+\\|.\\)"
411 ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
412 ; ;; not be able to display those fonts.
413 ; ;; LaTeX2e: \emph{This is emphasized}.
414 ; ("\\\\emph{\\([^}]+\\)}" 1 'italic keep)
415 ; ;; LaTeX2e: \textbf{This is bold}, \textit{...}, \textsl{...}
416 ; ("\\\\text\\(\\(bf\\)\\|it\\|sl\\){\\([^}]+\\)}"
417 ; 3 (if (match-beginning 2) 'bold 'italic) keep)
418 ; ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
419 ; ("\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)"
420 ; 3 (if (match-beginning 2) 'bold 'italic) keep))
421
422 ;; Rewritten with the help of Alexandra Bac <abac@welcome.disi.unige.it>.
423 (defconst tex-font-lock-keywords-1
424 (eval-when-compile
425 (let* (;; Names of commands whose arg should be fontified as heading, etc.
426 (headings (regexp-opt
427 '("title" "begin" "end" "chapter" "part"
428 "section" "subsection" "subsubsection"
429 "paragraph" "subparagraph" "subsubparagraph"
430 "newcommand" "renewcommand" "newenvironment"
431 "newtheorem")
432 t))
433 (variables (regexp-opt
434 '("newcounter" "newcounter*" "setcounter" "addtocounter"
435 "setlength" "addtolength" "settowidth")
436 t))
437 (includes (regexp-opt
438 '("input" "include" "includeonly" "bibliography"
439 "epsfig" "psfig" "epsf" "nofiles" "usepackage"
440 "includegraphics" "includegraphics*")
441 t))
442 ;; Miscellany.
443 (slash "\\\\")
444 (opt "\\(\\[[^]]*\\]\\)?")
445 (arg "{\\(\\(?:[^{}]+\\(?:{[^}]*}\\)?\\)+\\)"))
446 (list
447 ;; Heading args.
448 (list (concat slash headings "\\*?" opt arg)
449 ;; If ARG ends up matching too much (if the {} don't match, f.ex)
450 ;; jit-lock will do funny things: when updating the buffer
451 ;; the re-highlighting is only done locally so it will just
452 ;; match the local line, but defer-contextually will
453 ;; match more lines at a time, so ARG will end up matching
454 ;; a lot more, which might suddenly include a comment
455 ;; so you get things highlighted bold when you type them
456 ;; but they get turned back to normal a little while later
457 ;; because "there's already a face there".
458 ;; Using `keep' works around this un-intuitive behavior as well
459 ;; as improves the behavior in the very rare case where you do have
460 ;; a comment in ARG.
461 3 'font-lock-function-name-face 'keep)
462 ;; Variable args.
463 (list (concat slash variables arg) 2 'font-lock-variable-name-face)
464 ;; Include args.
465 (list (concat slash includes opt arg) 3 'font-lock-builtin-face)
466 ;; Definitions. I think.
467 '("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)"
468 1 font-lock-function-name-face))))
469 "Subdued expressions to highlight in TeX modes.")
470
471 (defconst tex-font-lock-keywords-2
472 (append tex-font-lock-keywords-1
473 (eval-when-compile
474 (let* (;;
475 ;; Names of commands whose arg should be fontified with fonts.
476 (bold (regexp-opt '("bf" "textbf" "textsc" "textup"
477 "boldsymbol" "pmb") t))
478 (italic (regexp-opt '("it" "textit" "textsl" "emph") t))
479 (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
480 ;;
481 ;; Names of commands whose arg should be fontified as a citation.
482 (citations (regexp-opt
483 '("label" "ref" "pageref" "vref" "eqref"
484 "cite" "nocite" "caption" "index" "glossary"
485 "footnote" "footnotemark" "footnotetext")
486 t))
487 ;;
488 ;; Names of commands that should be fontified.
489 (specials (regexp-opt
490 '("\\"
491 "linebreak" "nolinebreak" "pagebreak" "nopagebreak"
492 "newline" "newpage" "clearpage" "cleardoublepage"
493 "displaybreak" "allowdisplaybreaks" "enlargethispage")
494 t))
495 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
496 ;;
497 ;; Miscellany.
498 (slash "\\\\")
499 (opt "\\(\\[[^]]*\\]\\)?")
500 (arg "{\\(\\(?:[^{}]+\\(?:{[^}]*}\\)?\\)+\\)"))
501 (list
502 ;;
503 ;; Citation args.
504 (list (concat slash citations opt arg) 3 'font-lock-constant-face)
505 ;;
506 ;; Command names, special and general.
507 (cons (concat slash specials) 'font-lock-warning-face)
508 (concat slash general)
509 ;;
510 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
511 ;; since we might not be able to display those fonts.
512 (list (concat slash bold arg) 2 '(quote bold) 'append)
513 (list (concat slash italic arg) 2 '(quote italic) 'append)
514 (list (concat slash type arg) 2 '(quote bold-italic) 'append)
515 ;;
516 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
517 (list (concat "\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>"
518 "\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)")
519 3 '(if (match-beginning 2) 'bold 'italic) 'append)))))
520 "Gaudy expressions to highlight in TeX modes.")
521
522 (defvar tex-font-lock-keywords tex-font-lock-keywords-1
523 "Default expressions to highlight in TeX modes.")
524
525
526 (defface tex-math-face
527 '((t :inherit font-lock-string-face))
528 "Face used to highlight TeX math expressions.")
529 (defvar tex-math-face 'tex-math-face)
530
531 ;; Use string syntax but math face for $...$.
532 (defun tex-font-lock-syntactic-face-function (state)
533 (if (nth 3 state) tex-math-face font-lock-comment-face))
534
535 \f
536 (defun tex-define-common-keys (keymap)
537 "Define the keys that we want defined both in TeX mode and in the TeX shell."
538 (define-key keymap "\C-c\C-k" 'tex-kill-job)
539 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
540 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
541 (define-key keymap "\C-c\C-p" 'tex-print)
542 (define-key keymap "\C-c\C-v" 'tex-view)
543
544 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
545
546 (define-key keymap [menu-bar tex tex-kill-job]
547 '(menu-item "Tex Kill" tex-kill-job :enable (tex-shell-running)))
548 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
549 '(menu-item "Tex Recenter" tex-recenter-output-buffer
550 :enable (get-buffer "*tex-shell*")))
551 (define-key keymap [menu-bar tex tex-show-print-queue]
552 '("Show Print Queue" . tex-show-print-queue))
553 (define-key keymap [menu-bar tex tex-alt-print]
554 '(menu-item "Tex Print (alt printer)" tex-alt-print
555 :enable (stringp tex-print-file)))
556 (define-key keymap [menu-bar tex tex-print]
557 '(menu-item "Tex Print" tex-print :enable (stringp tex-print-file)))
558 (define-key keymap [menu-bar tex tex-view]
559 '(menu-item "Tex View" tex-view :enable (stringp tex-print-file))))
560
561 (defvar tex-mode-map
562 (let ((map (make-sparse-keymap)))
563 (tex-define-common-keys map)
564 (define-key map "\"" 'tex-insert-quote)
565 (define-key map "(" 'skeleton-pair-insert-maybe)
566 (define-key map "{" 'skeleton-pair-insert-maybe)
567 (define-key map "[" 'skeleton-pair-insert-maybe)
568 (define-key map "$" 'skeleton-pair-insert-maybe)
569 (define-key map "\n" 'tex-terminate-paragraph)
570 (define-key map "\M-\r" 'latex-insert-item)
571 (define-key map "\C-c}" 'up-list)
572 (define-key map "\C-c{" 'tex-insert-braces)
573 (define-key map "\C-c\C-r" 'tex-region)
574 (define-key map "\C-c\C-b" 'tex-buffer)
575 (define-key map "\C-c\C-f" 'tex-file)
576 (define-key map "\C-c\C-c" 'tex-compile)
577 (define-key map "\C-c\C-i" 'tex-bibtex-file)
578 (define-key map "\C-c\C-o" 'tex-latex-block)
579 (define-key map "\C-c\C-e" 'tex-close-latex-block)
580 (define-key map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
581 (define-key map "\C-c\C-m" 'tex-feed-input)
582 (define-key map [(control return)] 'tex-feed-input)
583 (define-key map [menu-bar tex tex-bibtex-file]
584 '("BibTeX File" . tex-bibtex-file))
585 (define-key map [menu-bar tex tex-validate-region]
586 '(menu-item "Validate Region" tex-validate-region :enable mark-active))
587 (define-key map [menu-bar tex tex-validate-buffer]
588 '("Validate Buffer" . tex-validate-buffer))
589 (define-key map [menu-bar tex tex-region]
590 '(menu-item "TeX Region" tex-region :enable mark-active))
591 (define-key map [menu-bar tex tex-buffer]
592 '("TeX Buffer" . tex-buffer))
593 (define-key map [menu-bar tex tex-file] '("TeX File" . tex-file))
594 map)
595 "Keymap for TeX modes.")
596
597 (defvar tex-shell-map
598 (let ((m (make-sparse-keymap)))
599 (set-keymap-parent m shell-mode-map)
600 (tex-define-common-keys m)
601 m)
602 "Keymap for the TeX shell.
603 Inherits `shell-mode-map' with a few additions.")
604
605 (defvar tex-face-alist
606 '((bold . "{\\bf ")
607 (italic . "{\\it ")
608 (bold-italic . "{\\bi ") ; hypothetical
609 (underline . "\\underline{")
610 (default . "{\\rm "))
611 "Alist of face and TeX font name for facemenu.")
612
613 (defvar tex-latex-face-alist
614 `((italic . "{\\em ")
615 ,@tex-face-alist)
616 "Alist of face and LaTeX font name for facemenu.")
617
618 ;;; This would be a lot simpler if we just used a regexp search,
619 ;;; but then it would be too slow.
620 ;;;###autoload
621 (defun tex-mode ()
622 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
623 Tries to determine (by looking at the beginning of the file) whether
624 this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
625 `latex-mode', or `slitex-mode', respectively. If it cannot be determined,
626 such as if there are no commands in the file, the value of `tex-default-mode'
627 says which mode to use."
628 (interactive)
629 (let ((mode tex-default-mode) slash comment)
630 (save-excursion
631 (goto-char (point-min))
632 (while (and (setq slash (search-forward "\\" nil t))
633 (setq comment (let ((search-end (point)))
634 (save-excursion
635 (beginning-of-line)
636 (search-forward "%" search-end t))))))
637 (when (and slash (not comment))
638 (setq mode
639 (if (looking-at
640 (eval-when-compile
641 (concat
642 (regexp-opt '("documentstyle" "documentclass"
643 "begin" "section" "part" "chapter") 'words)
644 "\\|NeedsTeXFormat{LaTeX")))
645 (if (looking-at
646 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
647 'slitex-mode
648 'latex-mode)
649 'plain-tex-mode))))
650 (funcall mode)))
651
652 ;;;###autoload
653 (defalias 'TeX-mode 'tex-mode)
654 ;;;###autoload
655 (defalias 'plain-TeX-mode 'plain-tex-mode)
656 ;;;###autoload
657 (defalias 'LaTeX-mode 'latex-mode)
658
659 ;;;###autoload
660 (define-derived-mode plain-tex-mode text-mode "TeX"
661 "Major mode for editing files of input for plain TeX.
662 Makes $ and } display the characters they match.
663 Makes \" insert `` when it seems to be the beginning of a quotation,
664 and '' when it appears to be the end; it inserts \" only after a \\.
665
666 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
667 copied from the top of the file (containing macro definitions, etc.),
668 running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
669 \\[tex-file] saves the buffer and then processes the file.
670 \\[tex-print] prints the .dvi file made by any of these.
671 \\[tex-view] previews the .dvi file made by any of these.
672 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
673
674 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
675 mismatched $'s or braces.
676
677 Special commands:
678 \\{tex-mode-map}
679
680 Mode variables:
681 tex-run-command
682 Command string used by \\[tex-region] or \\[tex-buffer].
683 tex-directory
684 Directory in which to create temporary files for TeX jobs
685 run by \\[tex-region] or \\[tex-buffer].
686 tex-dvi-print-command
687 Command string used by \\[tex-print] to print a .dvi file.
688 tex-alt-dvi-print-command
689 Alternative command string used by \\[tex-print] (when given a prefix
690 argument) to print a .dvi file.
691 tex-dvi-view-command
692 Command string used by \\[tex-view] to preview a .dvi file.
693 tex-show-queue-command
694 Command string used by \\[tex-show-print-queue] to show the print
695 queue that \\[tex-print] put your job on.
696
697 Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
698 `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
699 special subshell is initiated, the hook `tex-shell-hook' is run."
700 (tex-common-initialization)
701 (setq tex-command tex-run-command)
702 (setq tex-start-of-header "%\\*\\*start of header")
703 (setq tex-end-of-header "%\\*\\*end of header")
704 (setq tex-trailer "\\bye\n")
705 (run-hooks 'tex-mode-hook))
706
707 ;;;###autoload
708 (define-derived-mode latex-mode text-mode "LaTeX"
709 "Major mode for editing files of input for LaTeX.
710 Makes $ and } display the characters they match.
711 Makes \" insert `` when it seems to be the beginning of a quotation,
712 and '' when it appears to be the end; it inserts \" only after a \\.
713
714 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
715 copied from the top of the file (containing \\documentstyle, etc.),
716 running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
717 \\[tex-file] saves the buffer and then processes the file.
718 \\[tex-print] prints the .dvi file made by any of these.
719 \\[tex-view] previews the .dvi file made by any of these.
720 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
721
722 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
723 mismatched $'s or braces.
724
725 Special commands:
726 \\{tex-mode-map}
727
728 Mode variables:
729 latex-run-command
730 Command string used by \\[tex-region] or \\[tex-buffer].
731 tex-directory
732 Directory in which to create temporary files for LaTeX jobs
733 run by \\[tex-region] or \\[tex-buffer].
734 tex-dvi-print-command
735 Command string used by \\[tex-print] to print a .dvi file.
736 tex-alt-dvi-print-command
737 Alternative command string used by \\[tex-print] (when given a prefix
738 argument) to print a .dvi file.
739 tex-dvi-view-command
740 Command string used by \\[tex-view] to preview a .dvi file.
741 tex-show-queue-command
742 Command string used by \\[tex-show-print-queue] to show the print
743 queue that \\[tex-print] put your job on.
744
745 Entering Latex mode runs the hook `text-mode-hook', then
746 `tex-mode-hook', and finally `latex-mode-hook'. When the special
747 subshell is initiated, `tex-shell-hook' is run."
748 (tex-common-initialization)
749 (setq tex-command latex-run-command)
750 (setq tex-start-of-header "\\\\document\\(style\\|class\\)")
751 (setq tex-end-of-header "\\\\begin\\s-*{document}")
752 (setq tex-trailer "\\end\\s-*{document}\n")
753 ;; A line containing just $$ is treated as a paragraph separator.
754 ;; A line starting with $$ starts a paragraph,
755 ;; but does not separate paragraphs if it has more stuff on it.
756 (setq paragraph-start
757 (concat "[\f%]\\|[ \t]*\\($\\|\\$\\$\\|"
758 "\\\\[][]\\|"
759 "\\\\" (regexp-opt (append
760 (mapcar 'car latex-section-alist)
761 '("begin" "label" "end"
762 "item" "bibitem" "newline" "noindent"
763 "newpage" "footnote" "marginpar"
764 "parbox" "caption")) t)
765 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
766 "\\>\\)"))
767 (setq paragraph-separate
768 (concat "[\f%]\\|[ \t]*\\($\\|"
769 "\\\\[][]\\|"
770 "\\\\" (regexp-opt (append
771 (mapcar 'car latex-section-alist)
772 '("begin" "label" "end" )) t)
773 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
774 "noindent" "newpage" "footnote"
775 "marginpar" "parbox" "caption"))
776 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
777 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
778 (set (make-local-variable 'imenu-create-index-function)
779 'latex-imenu-create-index)
780 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
781 (set (make-local-variable 'fill-nobreak-predicate)
782 'latex-fill-nobreak-predicate)
783 (set (make-local-variable 'indent-line-function) 'latex-indent)
784 (set (make-local-variable 'fill-indent-according-to-mode) t)
785 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
786 (set (make-local-variable 'outline-level) 'latex-outline-level)
787 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
788 (run-hooks 'tex-mode-hook))
789
790 ;;;###autoload
791 (define-derived-mode slitex-mode latex-mode "SliTeX"
792 "Major mode for editing files of input for SliTeX.
793 Makes $ and } display the characters they match.
794 Makes \" insert `` when it seems to be the beginning of a quotation,
795 and '' when it appears to be the end; it inserts \" only after a \\.
796
797 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
798 copied from the top of the file (containing \\documentstyle, etc.),
799 running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
800 \\[tex-file] saves the buffer and then processes the file.
801 \\[tex-print] prints the .dvi file made by any of these.
802 \\[tex-view] previews the .dvi file made by any of these.
803 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
804
805 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
806 mismatched $'s or braces.
807
808 Special commands:
809 \\{tex-mode-map}
810
811 Mode variables:
812 slitex-run-command
813 Command string used by \\[tex-region] or \\[tex-buffer].
814 tex-directory
815 Directory in which to create temporary files for SliTeX jobs
816 run by \\[tex-region] or \\[tex-buffer].
817 tex-dvi-print-command
818 Command string used by \\[tex-print] to print a .dvi file.
819 tex-alt-dvi-print-command
820 Alternative command string used by \\[tex-print] (when given a prefix
821 argument) to print a .dvi file.
822 tex-dvi-view-command
823 Command string used by \\[tex-view] to preview a .dvi file.
824 tex-show-queue-command
825 Command string used by \\[tex-show-print-queue] to show the print
826 queue that \\[tex-print] put your job on.
827
828 Entering SliTeX mode runs the hook `text-mode-hook', then the hook
829 `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
830 `slitex-mode-hook'. When the special subshell is initiated, the hook
831 `tex-shell-hook' is run."
832 (setq tex-command slitex-run-command)
833 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
834
835 (defun tex-common-initialization ()
836 (use-local-map tex-mode-map)
837 (set-syntax-table tex-mode-syntax-table)
838 ;; Regexp isearch should accept newline and formfeed as whitespace.
839 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
840 ;; A line containing just $$ is treated as a paragraph separator.
841 (set (make-local-variable 'paragraph-start)
842 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
843 ;; A line starting with $$ starts a paragraph,
844 ;; but does not separate paragraphs if it has more stuff on it.
845 (set (make-local-variable 'paragraph-separate)
846 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
847 (set (make-local-variable 'comment-start) "%")
848 (set (make-local-variable 'comment-add) 1)
849 (set (make-local-variable 'comment-start-skip)
850 "\\(\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
851 (set (make-local-variable 'parse-sexp-ignore-comments) t)
852 (set (make-local-variable 'compare-windows-whitespace)
853 'tex-categorize-whitespace)
854 (set (make-local-variable 'facemenu-add-face-function)
855 (lambda (face end)
856 (let ((face-text (cdr (assq face tex-face-alist))))
857 (if face-text
858 face-text
859 (error "Face %s not configured for %s mode" face mode-name)))))
860 (set (make-local-variable 'facemenu-end-add-face) "}")
861 (set (make-local-variable 'facemenu-remove-face-function) t)
862 (set (make-local-variable 'font-lock-defaults)
863 '((tex-font-lock-keywords
864 tex-font-lock-keywords-1 tex-font-lock-keywords-2)
865 nil nil ((?$ . "\"")) nil
866 ;; Who ever uses that anyway ???
867 (font-lock-mark-block-function . mark-paragraph)
868 (font-lock-syntactic-face-function
869 . tex-font-lock-syntactic-face-function)))
870 (make-local-variable 'tex-command)
871 (make-local-variable 'tex-start-of-header)
872 (make-local-variable 'tex-end-of-header)
873 (make-local-variable 'tex-trailer))
874
875 (defun tex-categorize-whitespace (backward-limit)
876 ;; compare-windows-whitespace is set to this.
877 ;; This is basically a finite-state machine.
878 ;; Returns a symbol telling how TeX would treat
879 ;; the whitespace we are looking at: null, space, or par.
880 (let ((category 'null)
881 (not-finished t))
882 (skip-chars-backward " \t\n\f" backward-limit)
883 (while not-finished
884 (cond ((looking-at "[ \t]+")
885 (goto-char (match-end 0))
886 (if (eq category 'null)
887 (setq category 'space)))
888 ((looking-at "\n")
889 (cond ((eq category 'newline)
890 (setq category 'par)
891 (setq not-finished nil))
892 (t
893 (setq category 'newline) ;a strictly internal state
894 (goto-char (match-end 0)))))
895 ((looking-at "\f+")
896 (setq category 'par)
897 (setq not-finished nil))
898 (t
899 (setq not-finished nil))))
900 (skip-chars-forward " \t\n\f")
901 (if (eq category 'newline)
902 'space ;TeX doesn't distinguish
903 category)))
904
905 (defun tex-insert-quote (arg)
906 "Insert the appropriate quote marks for TeX.
907 Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
908 \(normally '') depending on the context. With prefix argument, always
909 inserts \" characters."
910 (interactive "*P")
911 (if arg
912 (self-insert-command (prefix-numeric-value arg))
913 (insert
914 (cond ((= (preceding-char) ?\\) ?\")
915 ((memq (char-syntax (preceding-char)) '(?\( ?> ?\ )) tex-open-quote)
916 (t tex-close-quote)))))
917
918 (defun tex-validate-buffer ()
919 "Check current buffer for paragraphs containing mismatched braces or $s.
920 Their positions are recorded in the buffer `*Occur*'.
921 To find a particular invalidity from `*Occur*', switch to that buffer
922 and type C-c C-c or click with mouse-2
923 on the line for the invalidity you want to see."
924 (interactive)
925 (let ((buffer (current-buffer))
926 (prevpos (point-min))
927 (linenum nil)
928 (num-matches 0))
929 (with-output-to-temp-buffer "*Occur*"
930 (princ "Mismatches:\n")
931 (save-excursion
932 (set-buffer standard-output)
933 (occur-mode)
934 (setq occur-buffer buffer)
935 (setq occur-nlines 0))
936 (save-excursion
937 (goto-char (point-max))
938 (while (and (not (input-pending-p)) (not (bobp)))
939 (let ((end (point))
940 prev-end)
941 ;; Scan the previous paragraph for invalidities.
942 (if (search-backward "\n\n" nil t)
943 (progn
944 (setq prev-end (point))
945 (forward-char 2))
946 (goto-char (setq prev-end (point-min))))
947 (or (tex-validate-region (point) end)
948 (let* ((oend end)
949 (end (save-excursion (forward-line 1) (point)))
950 start tem)
951 (beginning-of-line)
952 (setq start (point))
953 ;; Keep track of line number as we scan,
954 ;; in a cumulative fashion.
955 (if linenum
956 (setq linenum (- linenum (count-lines prevpos (point))))
957 (setq linenum (1+ (count-lines 1 start))))
958 (setq prevpos (point))
959 ;; Mention this mismatch in *Occur*.
960 ;; Since we scan from end of buffer to beginning,
961 ;; add each mismatch at the beginning of *Occur*.
962 (save-excursion
963 (setq tem (point-marker))
964 (set-buffer standard-output)
965 (goto-char (point-min))
966 ;; Skip "Mismatches:" header line.
967 (forward-line 1)
968 (setq num-matches (1+ num-matches))
969 (insert-buffer-substring buffer start end)
970 (let (text-beg (text-end (point-marker)))
971 (forward-char (- start end))
972 (setq text-beg (point-marker))
973 (insert (format "%3d: " linenum))
974 (put-text-property (marker-position text-beg)
975 (- (marker-position text-end) 1)
976 'mouse-face 'highlight)
977 (put-text-property (marker-position text-beg)
978 (- (marker-position text-end) 1)
979 'occur tem)))))
980 (goto-char prev-end))))
981 (with-current-buffer standard-output
982 (if (eq num-matches 0)
983 (insert "None!\n"))
984 (if (interactive-p)
985 (message "%d mismatches found" num-matches))))))
986
987 (defun tex-validate-region (start end)
988 "Check for mismatched braces or $'s in region.
989 Returns t if no mismatches. Returns nil and moves point to suspect
990 area if a mismatch is found."
991 (interactive "r")
992 (let ((failure-point nil) (max-possible-sexps (- end start)))
993 (save-excursion
994 (condition-case ()
995 (save-restriction
996 (narrow-to-region start end)
997 ;; First check that the open and close parens balance in numbers.
998 (goto-char start)
999 (while (<= 0 (setq max-possible-sexps (1- max-possible-sexps)))
1000 (forward-sexp 1))
1001 ;; Now check that like matches like.
1002 (goto-char start)
1003 (while (progn (skip-syntax-forward "^(")
1004 (not (eobp)))
1005 (let ((match (matching-paren (following-char))))
1006 (save-excursion
1007 (forward-sexp 1)
1008 (or (= (preceding-char) match)
1009 (error "Mismatched parentheses"))))
1010 (forward-char 1)))
1011 (error
1012 (skip-syntax-forward " .>")
1013 (setq failure-point (point)))))
1014 (if failure-point (goto-char failure-point))
1015 (not failure-point)))
1016
1017 (defun tex-terminate-paragraph (inhibit-validation)
1018 "Insert two newlines, breaking a paragraph for TeX.
1019 Check for mismatched braces or $s in paragraph being terminated.
1020 A prefix arg inhibits the checking."
1021 (interactive "*P")
1022 (or inhibit-validation
1023 (save-excursion
1024 (tex-validate-region
1025 (save-excursion
1026 (search-backward "\n\n" nil 'move)
1027 (point))
1028 (point)))
1029 (message "Paragraph being closed appears to contain a mismatch"))
1030 (insert "\n\n"))
1031
1032 (defun tex-insert-braces ()
1033 "Make a pair of braces and be poised to type inside of them."
1034 (interactive "*")
1035 (insert ?\{)
1036 (save-excursion
1037 (insert ?})))
1038
1039 ;; This function is used as the value of fill-nobreak-predicate
1040 ;; in LaTeX mode. Its job is to prevent line-breaking inside
1041 ;; of a \verb construct.
1042 (defun latex-fill-nobreak-predicate ()
1043 (let ((opoint (point))
1044 inside)
1045 (save-excursion
1046 (save-restriction
1047 (beginning-of-line)
1048 (narrow-to-region (point) opoint)
1049 (while (re-search-forward "\\\\verb\\(.\\)" nil t)
1050 (unless (re-search-forward (regexp-quote (match-string 1)) nil t)
1051 (setq inside t)))))
1052 inside))
1053
1054 (defvar latex-block-default "enumerate")
1055
1056 ;;; Like tex-insert-braces, but for LaTeX.
1057 (define-skeleton tex-latex-block
1058 "Create a matching pair of lines \\begin[OPT]{NAME} and \\end{NAME} at point.
1059 Puts point on a blank line between them."
1060 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1061 latex-block-default)
1062 (mapcar 'list
1063 (append standard-latex-block-names
1064 latex-block-names))
1065 nil nil nil nil latex-block-default)))
1066 (setq latex-block-default choice)
1067 (unless (or (member choice standard-latex-block-names)
1068 (member choice latex-block-names))
1069 ;; Remember new block names for later completion.
1070 (push choice latex-block-names))
1071 choice)
1072 (unless (save-excursion (beginning-of-line) (looking-at "[ \t]*$")) '\n)
1073 "\\begin{" str ?\}
1074 ?\[ (skeleton-read "[options]: ") & ?\] | -1
1075 > \n _ \n
1076 "\\end{" str ?\} >)
1077
1078 (define-skeleton latex-insert-item
1079 "Insert a \item macro."
1080 nil
1081 (unless (save-excursion (beginning-of-line) (looking-at "[ \t]*$")) '\n)
1082 "\\item " >)
1083
1084 \f
1085 ;;;;
1086 ;;;; LaTeX syntax navigation
1087 ;;;;
1088
1089 (defun tex-last-unended-begin ()
1090 "Leave point at the beginning of the last `\\begin{...}' that is unended."
1091 (while (and (re-search-backward "\\\\\\(begin\\|end\\)\\s *{")
1092 (looking-at "\\\\end"))
1093 (tex-last-unended-begin)))
1094
1095 (defun tex-next-unmatched-end ()
1096 "Leave point at the end of the next `\\end' that is unended."
1097 (while (and (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}")
1098 (save-excursion (goto-char (match-beginning 0))
1099 (looking-at "\\\\begin")))
1100 (tex-next-unmatched-end)))
1101
1102 (defun tex-goto-last-unclosed-latex-block ()
1103 "Move point to the last unclosed \\begin{...}.
1104 Mark is left at original location."
1105 (interactive)
1106 (let ((spot))
1107 (save-excursion
1108 (condition-case nil
1109 (tex-last-unended-begin)
1110 (error (error "Couldn't find unended \\begin")))
1111 (setq spot (point)))
1112 (push-mark)
1113 (goto-char spot)))
1114
1115 (defun latex-backward-sexp-1 ()
1116 "Like (backward-sexp 1) but aware of multi-char elements."
1117 (let ((pos (point))
1118 (forward-sexp-function))
1119 (backward-sexp 1)
1120 (if (looking-at "\\\\begin\\>")
1121 (signal 'scan-error
1122 (list "Containing expression ends prematurely"
1123 (point) (prog1 (point) (goto-char pos))))
1124 (when (eq (char-after) ?{)
1125 (let ((newpos (point)))
1126 (when (ignore-errors (backward-sexp 1) t)
1127 (if (looking-at "\\\\end\\>")
1128 (tex-last-unended-begin)
1129 (goto-char newpos))))))))
1130
1131 (defun latex-forward-sexp-1 ()
1132 "Like (forward-sexp 1) but aware of multi-char elements."
1133 (let ((pos (point))
1134 (forward-sexp-function))
1135 (forward-sexp 1)
1136 (let ((newpos (point)))
1137 (skip-syntax-backward "/w")
1138 (cond
1139 ((looking-at "\\\\end\\>")
1140 (signal 'scan-error
1141 (list "Containing expression ends prematurely"
1142 (point)
1143 (prog1
1144 (progn (ignore-errors (forward-sexp 2)) (point))
1145 (goto-char pos)))))
1146 ((looking-at "\\\\begin\\>")
1147 (goto-char (match-end 0))
1148 (tex-next-unmatched-end))
1149 (t (goto-char newpos))))))
1150
1151 (defun latex-forward-sexp (&optional arg)
1152 "Like `forward-sexp' but aware of multi-char elements."
1153 (interactive "P")
1154 (unless arg (setq arg 1))
1155 (let ((pos (point)))
1156 (condition-case err
1157 (while (/= arg 0)
1158 (setq arg
1159 (if (> arg 0)
1160 (progn (latex-forward-sexp-1) (1- arg))
1161 (progn (latex-backward-sexp-1) (1+ arg)))))
1162 (scan-error
1163 (goto-char pos)
1164 (signal (car err) (cdr err))))))
1165
1166 (defun latex-syntax-after ()
1167 "Like (char-syntax (char-after)) but aware of multi-char elements."
1168 (if (looking-at "\\\\end\\>") ?\) (char-syntax (char-after))))
1169
1170 (defun latex-skip-close-parens ()
1171 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1172 (let ((forward-sexp-function nil))
1173 (while (progn (skip-syntax-forward " )")
1174 (looking-at "\\\\end\\>"))
1175 (forward-sexp 2))))
1176
1177 (defun latex-down-list ()
1178 "Like (down-list 1) but aware of multi-char elements."
1179 (forward-comment (point-max))
1180 (let ((forward-sexp-function nil))
1181 (if (not (looking-at "\\\\begin\\>"))
1182 (down-list 1)
1183 (forward-sexp 1)
1184 ;; Skip arguments.
1185 (while (looking-at "[ \t]*\\s(") (forward-sexp)))))
1186
1187 (defun tex-close-latex-block ()
1188 "Creates an \\end{...} to match the last unclosed \\begin{...}."
1189 (interactive "*")
1190 (let ((new-line-needed (bolp))
1191 text indentation)
1192 (save-excursion
1193 (condition-case nil
1194 (tex-last-unended-begin)
1195 (error (error "Couldn't find unended \\begin")))
1196 (setq indentation (current-column))
1197 (re-search-forward "\\\\begin\\(\\s *{[^}\n]*}\\)")
1198 (setq text (buffer-substring (match-beginning 1) (match-end 1))))
1199 (indent-to indentation)
1200 (insert "\\end" text)
1201 (if new-line-needed (insert ?\n))))
1202 \f
1203 ;;; Invoking TeX in an inferior shell.
1204
1205 ;;; Why use a shell instead of running TeX directly? Because if TeX
1206 ;;; gets stuck, the user can switch to the shell window and type at it.
1207
1208 ;;; The utility functions:
1209
1210 (define-derived-mode tex-shell shell-mode "TeX-Shell"
1211 (compilation-shell-minor-mode t))
1212
1213 ;;;###autoload
1214 (defun tex-start-shell ()
1215 (with-current-buffer
1216 (make-comint
1217 "tex-shell"
1218 (or tex-shell-file-name (getenv "ESHELL") (getenv "SHELL") "/bin/sh")
1219 nil)
1220 (let ((proc (get-process "tex-shell")))
1221 (set-process-sentinel proc 'tex-shell-sentinel)
1222 (process-kill-without-query proc)
1223 (tex-shell)
1224 (while (zerop (buffer-size))
1225 (sleep-for 1)))))
1226
1227 (defun tex-feed-input ()
1228 "Send input to the tex shell process.
1229 In the tex buffer this can be used to continue an interactive tex run.
1230 In the tex shell buffer this command behaves like `comint-send-input'."
1231 (interactive)
1232 (set-buffer (process-buffer (get-process "tex-shell")))
1233 (comint-send-input)
1234 (tex-recenter-output-buffer nil))
1235
1236 (defun tex-display-shell ()
1237 "Make the TeX shell buffer visible in a window."
1238 (display-buffer (process-buffer (get-process "tex-shell")))
1239 (tex-recenter-output-buffer nil))
1240
1241 (defun tex-shell-sentinel (proc msg)
1242 (cond ((null (buffer-name (process-buffer proc)))
1243 ;; buffer killed
1244 (set-process-buffer proc nil)
1245 (tex-delete-last-temp-files))
1246 ((memq (process-status proc) '(signal exit))
1247 (tex-delete-last-temp-files))))
1248
1249 (defun tex-set-buffer-directory (buffer directory)
1250 "Set BUFFER's default directory to be DIRECTORY."
1251 (setq directory (file-name-as-directory (expand-file-name directory)))
1252 (if (not (file-directory-p directory))
1253 (error "%s is not a directory" directory)
1254 (save-excursion
1255 (set-buffer buffer)
1256 (setq default-directory directory))))
1257
1258 (defvar tex-send-command-modified-tick 0)
1259 (make-variable-buffer-local 'tex-send-command-modified-tick)
1260
1261 (defun tex-shell-proc ()
1262 (or (get-process "tex-shell") (error "No TeX subprocess")))
1263 (defun tex-shell-buf ()
1264 (process-buffer (tex-shell-proc)))
1265
1266 (defun tex-send-command (command &optional file background)
1267 "Send COMMAND to TeX shell process, substituting optional FILE for *.
1268 Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1269 FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1270 substitution will be made in COMMAND. COMMAND can be any expression that
1271 evaluates to a command string.
1272
1273 Return the process in which TeX is running."
1274 (save-excursion
1275 (let* ((cmd (eval command))
1276 (proc (tex-shell-proc))
1277 (buf (process-buffer proc))
1278 (star (string-match "\\*" cmd))
1279 (string
1280 (concat
1281 (if file
1282 (if star (concat (substring cmd 0 star)
1283 file (substring cmd (1+ star)))
1284 (concat cmd " " file))
1285 cmd)
1286 (if background "&" ""))))
1287 ;; Switch to buffer before checking for subproc output in it.
1288 (set-buffer buf)
1289 ;; If text is unchanged since previous tex-send-command,
1290 ;; we haven't got any output. So wait for output now.
1291 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
1292 (accept-process-output proc))
1293 (goto-char (process-mark proc))
1294 (insert string)
1295 (comint-send-input)
1296 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1297 proc)))
1298
1299 (defun tex-delete-last-temp-files (&optional not-all)
1300 "Delete any junk files from last temp file.
1301 If NOT-ALL is non-nil, save the `.dvi' file."
1302 (if tex-last-temp-file
1303 (let* ((dir (file-name-directory tex-last-temp-file))
1304 (list (and (file-directory-p dir)
1305 (file-name-all-completions
1306 (file-name-sans-extension
1307 (file-name-nondirectory tex-last-temp-file))
1308 dir))))
1309 (while list
1310 (if not-all
1311 (and
1312 ;; If arg is non-nil, don't delete the .dvi file.
1313 (not (string-match "\\.dvi$" (car list)))
1314 (delete-file (concat dir (car list))))
1315 (delete-file (concat dir (car list))))
1316 (setq list (cdr list))))))
1317
1318 (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
1319
1320 (defvar tex-start-tex-marker nil
1321 "Marker pointing after last TeX-running command in the TeX shell buffer.")
1322
1323 (defun tex-guess-main-file (&optional all)
1324 "Find a likely `tex-main-file'.
1325 Looks for hints in other buffers in the same directory or in
1326 ALL other buffers."
1327 (let ((dir default-directory)
1328 (header-re tex-start-of-header))
1329 (catch 'found
1330 ;; Look for a buffer with `tex-main-file' set.
1331 (dolist (buf (if (consp all) all (buffer-list)))
1332 (with-current-buffer buf
1333 (when (and (or all (equal dir default-directory))
1334 (stringp tex-main-file))
1335 (throw 'found (expand-file-name tex-main-file)))))
1336 ;; Look for a buffer containing the magic `tex-start-of-header'.
1337 (dolist (buf (if (consp all) all (buffer-list)))
1338 (with-current-buffer buf
1339 (when (and (or all (equal dir default-directory))
1340 buffer-file-name
1341 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1342 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1343 (save-excursion
1344 (goto-char (point-min))
1345 (re-search-forward header-re 10000 t)))
1346 (throw 'found (expand-file-name buffer-file-name))))))))
1347
1348 (defun tex-main-file (&optional realfile)
1349 "Return the name of the main file with the `.tex' extension stripped.
1350 If REALFILE is non-nil, return the pair (FILE . REALFILE) where FILE
1351 is the filename without the extension while REALFILE is the filename
1352 with extension."
1353 (let* ((file (or tex-main-file
1354 ;; Compatibility with AUCTeX.
1355 (and (boundp 'TeX-master) (stringp TeX-master)
1356 (set (make-local-variable 'tex-main-file) TeX-master))
1357 ;; Try to guess the main file.
1358 (if (not buffer-file-name)
1359 (error "Buffer is not associated with any file")
1360 (file-relative-name
1361 (if (save-excursion
1362 (goto-char (point-min))
1363 (re-search-forward tex-start-of-header 10000 t))
1364 ;; This is the main file.
1365 buffer-file-name
1366 ;; This isn't the main file, let's try to find better,
1367 (or (tex-guess-main-file)
1368 ;; (tex-guess-main-file t)
1369 buffer-file-name))))))
1370 (real (if (file-exists-p file) file (concat file ".tex"))))
1371 (when (string-match "\\.tex\\'" file)
1372 (setq file (substring file 0 (match-beginning 0))))
1373 (if realfile (cons file real) file)))
1374
1375
1376 (defun tex-start-tex (command file &optional dir)
1377 "Start a TeX run, using COMMAND on FILE."
1378 (let* ((star (string-match "\\*" command))
1379 (compile-command
1380 (if star
1381 (concat (substring command 0 star)
1382 (comint-quote-filename file)
1383 (substring command (1+ star)))
1384 (concat command " "
1385 (if (< 0 (length tex-start-options-string))
1386 (concat
1387 (shell-quote-argument tex-start-options-string) " "))
1388 (comint-quote-filename file)))))
1389 (tex-send-tex-command compile-command dir)))
1390
1391 (defun tex-send-tex-command (cmd &optional dir)
1392 (unless (or (equal dir (with-current-buffer (tex-shell-buf)
1393 default-directory))
1394 (not dir))
1395 (let (shell-dirtrack-verbose)
1396 (tex-send-command tex-shell-cd-command dir)))
1397 (with-current-buffer (process-buffer (tex-send-command cmd))
1398 (save-excursion
1399 (forward-line -1)
1400 (setq tex-start-tex-marker (point-marker)))
1401 (make-local-variable 'compilation-parse-errors-function)
1402 (setq compilation-parse-errors-function 'tex-compilation-parse-errors)
1403 (setq compilation-last-buffer (current-buffer))
1404 (compilation-forget-errors)
1405 (set-marker compilation-parsing-end (1- (point-max))))
1406 (tex-display-shell)
1407 (setq tex-last-buffer-texed (current-buffer)))
1408 \f
1409 (defun tex-compilation-parse-errors (limit-search find-at-least)
1410 "Parse the current buffer as TeX error messages.
1411 See the variable `compilation-parse-errors-function' for the interface it uses.
1412
1413 This function parses only the last TeX compilation.
1414 It works on TeX compilations only. It is necessary for that purpose,
1415 since TeX does not put file names and line numbers on the same line as
1416 for the error messages."
1417 (require 'thingatpt)
1418 (setq compilation-error-list nil)
1419 (message "Parsing error messages...")
1420 (let ((default-directory ; Perhaps dir has changed meanwhile.
1421 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
1422 (old-syntax-table (syntax-table))
1423 (tex-error-parse-syntax-table (copy-syntax-table (syntax-table)))
1424 found-desired (num-errors-found 0)
1425 last-filename last-linenum last-position
1426 begin-of-error end-of-error)
1427 (modify-syntax-entry ?\{ "_" tex-error-parse-syntax-table)
1428 (modify-syntax-entry ?\} "_" tex-error-parse-syntax-table)
1429 (modify-syntax-entry ?\[ "_" tex-error-parse-syntax-table)
1430 (modify-syntax-entry ?\] "_" tex-error-parse-syntax-table)
1431 ;; Single quotations may appear in errors
1432 (modify-syntax-entry ?\" "_" tex-error-parse-syntax-table)
1433 ;; Don't parse previous compilations.
1434 (set-marker compilation-parsing-end
1435 (max compilation-parsing-end tex-start-tex-marker))
1436 ;; Don't reparse messages already seen at last parse.
1437 (goto-char compilation-parsing-end)
1438 ;; Parse messages.
1439 (while (and (not (or found-desired (eobp)))
1440 (prog1 (re-search-forward "^! " nil 'move)
1441 (setq begin-of-error (match-beginning 0)
1442 end-of-error (match-end 0)))
1443 (re-search-forward
1444 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
1445 (let* ((this-error (set-marker (make-marker) begin-of-error))
1446 (linenum (string-to-int (match-string 1)))
1447 (error-text (regexp-quote (match-string 3)))
1448 (filename
1449 (save-excursion
1450 (with-syntax-table tex-error-parse-syntax-table
1451 (backward-up-list 1)
1452 (skip-syntax-forward "(_")
1453 (while (not (file-readable-p (thing-at-point 'filename)))
1454 (skip-syntax-backward "(_")
1455 (backward-up-list 1)
1456 (skip-syntax-forward "(_"))
1457 (thing-at-point 'filename))))
1458 (new-file
1459 (or (null last-filename)
1460 (not (string-equal last-filename filename))))
1461 (error-location
1462 (save-excursion
1463 (if (equal filename (concat tex-zap-file ".tex"))
1464 (set-buffer tex-last-buffer-texed)
1465 (set-buffer (find-file-noselect filename)))
1466 (if new-file
1467 (goto-line linenum)
1468 (goto-char last-position)
1469 (forward-line (- linenum last-linenum)))
1470 ;; first try a forward search for the error text,
1471 ;; then a backward search limited by the last error.
1472 (let ((starting-point (point)))
1473 (or (re-search-forward error-text nil t)
1474 (re-search-backward
1475 error-text
1476 (marker-position last-position) t)
1477 (goto-char starting-point)))
1478 (point-marker))))
1479 (goto-char this-error)
1480 (if (and compilation-error-list
1481 (or (and find-at-least
1482 (>= num-errors-found
1483 find-at-least))
1484 (and limit-search
1485 (>= end-of-error limit-search)))
1486 new-file)
1487 (setq found-desired t)
1488 (setq num-errors-found (1+ num-errors-found)
1489 last-filename filename
1490 last-linenum linenum
1491 last-position error-location
1492 compilation-error-list ; Add the new error
1493 (cons (cons this-error error-location)
1494 compilation-error-list))
1495 (goto-char end-of-error)))))
1496 (set-marker compilation-parsing-end (point))
1497 (setq compilation-error-list (nreverse compilation-error-list))
1498 (message "Parsing error messages...done"))
1499 \f
1500 ;;; The commands:
1501
1502 (defun tex-region (beg end)
1503 "Run TeX on the current region, via a temporary file.
1504 The file's name comes from the variable `tex-zap-file' and the
1505 variable `tex-directory' says where to put it.
1506
1507 If the buffer has a header, the header is given to TeX before the
1508 region itself. The buffer's header is all lines between the strings
1509 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
1510 The header must start in the first 100 lines of the buffer.
1511
1512 The value of `tex-trailer' is given to TeX as input after the region.
1513
1514 The value of `tex-command' specifies the command to use to run TeX."
1515 (interactive "r")
1516 (if (tex-shell-running)
1517 (tex-kill-job)
1518 (tex-start-shell))
1519 (or tex-zap-file
1520 (setq tex-zap-file (tex-generate-zap-file-name)))
1521 ;; Temp file will be written and TeX will be run in zap-directory.
1522 ;; If the TEXINPUTS file has relative directories or if the region has
1523 ;; \input of files, this must be the same directory as the file for
1524 ;; TeX to access the correct inputs. That's why it's safest if
1525 ;; tex-directory is ".".
1526 (let* ((zap-directory
1527 (file-name-as-directory (expand-file-name tex-directory)))
1528 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
1529 zap-directory)))
1530 ;; Don't delete temp files if we do the same buffer twice in a row.
1531 (or (eq (current-buffer) tex-last-buffer-texed)
1532 (tex-delete-last-temp-files t))
1533 ;; Write the new temp file.
1534 (save-excursion
1535 (save-restriction
1536 (widen)
1537 (goto-char (point-min))
1538 (forward-line 100)
1539 (let ((search-end (point))
1540 (default-directory zap-directory)
1541 (already-output 0))
1542 (goto-char (point-min))
1543
1544 ;; Maybe copy first line, such as `\input texinfo', to temp file.
1545 (and tex-first-line-header-regexp
1546 (looking-at tex-first-line-header-regexp)
1547 (write-region (point)
1548 (progn (forward-line 1)
1549 (setq already-output (point)))
1550 tex-out-file nil nil))
1551
1552 ;; Write out the header, if there is one,
1553 ;; and any of the specified region which extends before it.
1554 ;; But don't repeat anything already written.
1555 (if (re-search-forward tex-start-of-header search-end t)
1556 (let (hbeg)
1557 (beginning-of-line)
1558 (setq hbeg (point)) ;mark beginning of header
1559 (if (re-search-forward tex-end-of-header nil t)
1560 (let (hend)
1561 (forward-line 1)
1562 (setq hend (point)) ;mark end of header
1563 (write-region (max (min hbeg beg) already-output)
1564 hend
1565 tex-out-file
1566 (not (zerop already-output)) nil)
1567 (setq already-output hend)))))
1568
1569 ;; Write out the specified region
1570 ;; (but don't repeat anything already written).
1571 (write-region (max beg already-output) end
1572 tex-out-file
1573 (not (zerop already-output)) nil))
1574 ;; Write the trailer, if any.
1575 ;; Precede it with a newline to make sure it
1576 ;; is not hidden in a comment.
1577 (if tex-trailer
1578 (write-region (concat "\n" tex-trailer) nil
1579 tex-out-file t nil))))
1580 ;; Record the file name to be deleted afterward.
1581 (setq tex-last-temp-file tex-out-file)
1582 ;; Use a relative file name here because (1) the proper dir
1583 ;; is already current, and (2) the abs file name is sometimes
1584 ;; too long and can make tex crash.
1585 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
1586 (setq tex-print-file tex-out-file)))
1587
1588 (defun tex-buffer ()
1589 "Run TeX on current buffer. See \\[tex-region] for more information.
1590 Does not save the buffer, so it's useful for trying experimental versions.
1591 See \\[tex-file] for an alternative."
1592 (interactive)
1593 (tex-region (point-min) (point-max)))
1594
1595 (defun tex-file ()
1596 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
1597 This function is more useful than \\[tex-buffer] when you need the
1598 `.aux' file of LaTeX to have the correct name."
1599 (interactive)
1600 (let* ((source-file (tex-main-file))
1601 (file-dir (expand-file-name (or (file-name-directory source-file)
1602 default-directory))))
1603 (if tex-offer-save
1604 (save-some-buffers))
1605 (if (tex-shell-running)
1606 (tex-kill-job)
1607 (tex-start-shell))
1608 (tex-start-tex tex-command source-file file-dir)
1609 (setq tex-print-file (expand-file-name source-file))))
1610
1611 (defun tex-generate-zap-file-name ()
1612 "Generate a unique name suitable for use as a file name."
1613 ;; Include the shell process number and host name
1614 ;; in case there are multiple shells (for same or different user).
1615 ;; Dec 1998: There is a report that some versions of xdvi
1616 ;; don't work with file names that start with #.
1617 (format "_TZ_%d-%s"
1618 (process-id (get-buffer-process "*tex-shell*"))
1619 (tex-strip-dots (system-name))))
1620
1621 (defun tex-strip-dots (s)
1622 (setq s (copy-sequence s))
1623 (while (string-match "\\." s)
1624 (aset s (match-beginning 0) ?-))
1625 s)
1626
1627 ;; This will perhaps be useful for modifying TEXINPUTS.
1628 ;; Expand each file name, separated by colons, in the string S.
1629 (defun tex-expand-files (s)
1630 (let (elts (start 0))
1631 (while (string-match ":" s start)
1632 (setq elts (cons (substring s start (match-beginning 0)) elts))
1633 (setq start (match-end 0)))
1634 (or (= start 0)
1635 (setq elts (cons (substring s start) elts)))
1636 (mapconcat (lambda (elt)
1637 (if (= (length elt) 0) elt (expand-file-name elt)))
1638 (nreverse elts) ":")))
1639
1640 (defun tex-shell-running ()
1641 (and (get-process "tex-shell")
1642 (eq (process-status (get-process "tex-shell")) 'run)))
1643
1644 (defun tex-kill-job ()
1645 "Kill the currently running TeX job."
1646 (interactive)
1647 ;; quit-process leads to core dumps of the tex process (except if
1648 ;; coredumpsize has limit 0kb as on many environments). One would
1649 ;; like to use (kill-process proc 'lambda), however that construct
1650 ;; does not work on some systems and kills the shell itself.
1651 (quit-process (get-process "tex-shell") t))
1652
1653 (defun tex-recenter-output-buffer (linenum)
1654 "Redisplay buffer of TeX job output so that most recent output can be seen.
1655 The last line of the buffer is displayed on
1656 line LINE of the window, or centered if LINE is nil."
1657 (interactive "P")
1658 (let ((tex-shell (get-buffer "*tex-shell*"))
1659 (old-buffer (current-buffer))
1660 (window))
1661 (if (null tex-shell)
1662 (message "No TeX output buffer")
1663 (setq window (display-buffer tex-shell))
1664 (save-selected-window
1665 (select-window window)
1666 (bury-buffer tex-shell)
1667 (goto-char (point-max))
1668 (recenter (if linenum
1669 (prefix-numeric-value linenum)
1670 (/ (window-height) 2)))))))
1671
1672 (defun tex-print (&optional alt)
1673 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1674 Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
1675 is provided, use the alternative command, `tex-alt-dvi-print-command'."
1676 (interactive "P")
1677 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
1678 test-name)
1679 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
1680 (buffer-file-name)
1681 ;; Check that this buffer's printed file is up to date.
1682 (file-newer-than-file-p
1683 (setq test-name (tex-append (buffer-file-name) ".dvi"))
1684 (buffer-file-name)))
1685 (setq print-file-name-dvi test-name))
1686 (if (not (file-exists-p print-file-name-dvi))
1687 (error "No appropriate `.dvi' file could be found")
1688 (if (tex-shell-running)
1689 (tex-kill-job)
1690 (tex-start-shell))
1691 (tex-send-command
1692 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
1693 print-file-name-dvi t))))
1694
1695 (defun tex-alt-print ()
1696 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1697 Runs the shell command defined by `tex-alt-dvi-print-command'."
1698 (interactive)
1699 (tex-print t))
1700
1701 (defun tex-view ()
1702 "Preview the last `.dvi' file made by running TeX under Emacs.
1703 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
1704 The variable `tex-dvi-view-command' specifies the shell command for preview.
1705 You must set that variable yourself before using this command,
1706 because there is no standard value that would generally work."
1707 (interactive)
1708 (or tex-dvi-view-command
1709 (error "You must set `tex-dvi-view-command'"))
1710 (let ((tex-dvi-print-command tex-dvi-view-command))
1711 (tex-print)))
1712
1713 (defun tex-append (file-name suffix)
1714 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
1715 Pascal-based TeX scans for the first period, C TeX uses the last.
1716 No period is retained immediately before SUFFIX,
1717 so normally SUFFIX starts with one."
1718 (if (stringp file-name)
1719 (let ((file (file-name-nondirectory file-name))
1720 trial-name)
1721 ;; Try splitting on last period.
1722 ;; The first-period split can get fooled when two files
1723 ;; named a.tex and a.b.tex are both tex'd;
1724 ;; the last-period split must be right if it matches at all.
1725 (setq trial-name
1726 (concat (file-name-directory file-name)
1727 (substring file 0
1728 (string-match "\\.[^.]*$" file))
1729 suffix))
1730 (if (or (file-exists-p trial-name)
1731 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
1732 trial-name
1733 ;; Not found, so split on first period.
1734 (concat (file-name-directory file-name)
1735 (substring file 0
1736 (string-match "\\." file))
1737 suffix)))
1738 " "))
1739
1740 (defun tex-show-print-queue ()
1741 "Show the print queue that \\[tex-print] put your job on.
1742 Runs the shell command defined by `tex-show-queue-command'."
1743 (interactive)
1744 (if (tex-shell-running)
1745 (tex-kill-job)
1746 (tex-start-shell))
1747 (tex-send-command tex-show-queue-command)
1748 (tex-display-shell))
1749
1750 (defun tex-bibtex-file ()
1751 "Run BibTeX on the current buffer's file."
1752 (interactive)
1753 (if (tex-shell-running)
1754 (tex-kill-job)
1755 (tex-start-shell))
1756 (let (shell-dirtrack-verbose
1757 (tex-out-file
1758 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
1759 (file-dir (file-name-directory (buffer-file-name))))
1760 (tex-send-command tex-shell-cd-command file-dir)
1761 (tex-send-command tex-bibtex-command tex-out-file))
1762 (tex-display-shell))
1763 \f
1764 ;;;;
1765 ;;;; LaTeX indentation
1766 ;;;;
1767
1768 (defvar tex-indent-allhanging t)
1769 (defvar tex-indent-arg 4)
1770 (defvar tex-indent-basic 2)
1771 (defvar tex-indent-item tex-indent-basic)
1772 (defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
1773
1774 (easy-mmode-defsyntax tex-latex-indent-syntax-table
1775 '((?$ . ".")
1776 (?\( . ".")
1777 (?\) . "."))
1778 "Syntax table used while computing indentation."
1779 :copy tex-mode-syntax-table)
1780
1781 (defun latex-indent (&optional arg)
1782 (with-syntax-table tex-latex-indent-syntax-table
1783 ;; TODO: Rather than ignore $, we should try to be more clever about it.
1784 (let ((indent
1785 (save-excursion
1786 (beginning-of-line)
1787 (latex-find-indent))))
1788 (if (< indent 0) (setq indent 0))
1789 (if (<= (current-column) (current-indentation))
1790 (indent-line-to indent)
1791 (save-excursion (indent-line-to indent))))))
1792
1793 (defun latex-find-indent (&optional virtual)
1794 "Find the proper indentation of text after point.
1795 VIRTUAL if non-nil indicates that we're only trying to find the indentation
1796 in order to determine the indentation of something else.
1797 There might be text before point."
1798 (save-excursion
1799 (skip-chars-forward " \t")
1800 (or
1801 ;; Trust the current indentation, if such info is applicable.
1802 (and virtual (>= (current-indentation) (current-column))
1803 (current-indentation))
1804 ;; Put leading close-paren where the matching open brace would be.
1805 (and (eq (latex-syntax-after) ?\))
1806 (ignore-errors
1807 (save-excursion
1808 (latex-skip-close-parens)
1809 (latex-backward-sexp-1)
1810 (latex-find-indent 'virtual))))
1811 ;; Default (maybe an argument)
1812 (let ((pos (point))
1813 (char (char-after))
1814 ;; Outdent \item if necessary.
1815 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
1816 up-list-pos)
1817 ;; Find the previous point which determines our current indentation.
1818 (condition-case err
1819 (progn
1820 (latex-backward-sexp-1)
1821 (while (> (current-column) (current-indentation))
1822 (latex-backward-sexp-1)))
1823 (scan-error
1824 (setq up-list-pos (nth 2 err))))
1825 (if (integerp up-list-pos)
1826 ;; Have to indent relative to the open-paren.
1827 (progn
1828 (goto-char up-list-pos)
1829 (if (and (not tex-indent-allhanging)
1830 (> pos (progn (latex-down-list)
1831 (forward-comment (point-max))
1832 (point))))
1833 ;; Align with the first element after the open-paren.
1834 (current-column)
1835 ;; We're the first element after a hanging brace.
1836 (goto-char up-list-pos)
1837 (+ indent tex-indent-basic (latex-find-indent 'virtual))))
1838 ;; We're now at the beginning of a line.
1839 (if (not (and (not virtual) (eq (char-after) ?\\)))
1840 ;; Nothing particular here: just keep the same indentation.
1841 (+ indent (current-column))
1842 ;; We're now looking at a macro call.
1843 (if (looking-at tex-indent-item-re)
1844 ;; Indenting relative to an item, have to re-add the outdenting.
1845 (+ indent (current-column) tex-indent-item)
1846 (let ((col (current-column)))
1847 (if (not (eq (char-syntax char) ?\())
1848 ;; If the first char was not an open-paren, there's
1849 ;; a risk that this is really not an argument to the
1850 ;; macro at all.
1851 (+ indent col)
1852 (forward-sexp 1)
1853 (if (< (line-end-position)
1854 (save-excursion (forward-comment (point-max))
1855 (point)))
1856 ;; we're indenting the first argument.
1857 (min (current-column) (+ tex-indent-arg col))
1858 (skip-syntax-forward " ")
1859 (current-column)))))))))))
1860
1861 (run-hooks 'tex-mode-load-hook)
1862
1863 (provide 'tex-mode)
1864
1865 ;;; tex-mode.el ends here