]> code.delx.au - gnu-emacs/blob - lisp/textmodes/tex-mode.el
Require CL when compiling.
[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")
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 3 'font-lock-function-name-face 'prepend)
450 ;; Variable args.
451 (list (concat slash variables arg) 2 'font-lock-variable-name-face)
452 ;; Include args.
453 (list (concat slash includes opt arg) 3 'font-lock-builtin-face)
454 ;; Definitions. I think.
455 '("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)"
456 1 font-lock-function-name-face)
457 )))
458 "Subdued expressions to highlight in TeX modes.")
459
460 (defconst tex-font-lock-keywords-2
461 (append tex-font-lock-keywords-1
462 (eval-when-compile
463 (let* (;;
464 ;; Names of commands whose arg should be fontified with fonts.
465 (bold (regexp-opt '("bf" "textbf" "textsc" "textup"
466 "boldsymbol" "pmb") t))
467 (italic (regexp-opt '("it" "textit" "textsl" "emph") t))
468 (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
469 ;;
470 ;; Names of commands whose arg should be fontified as a citation.
471 (citations (regexp-opt
472 '("label" "ref" "pageref" "vref" "eqref"
473 "cite" "nocite" "caption" "index" "glossary"
474 "footnote" "footnotemark" "footnotetext")
475 t))
476 ;;
477 ;; Names of commands that should be fontified.
478 (specials (regexp-opt
479 '("\\"
480 "linebreak" "nolinebreak" "pagebreak" "nopagebreak"
481 "newline" "newpage" "clearpage" "cleardoublepage"
482 "displaybreak" "allowdisplaybreaks" "enlargethispage")
483 t))
484 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
485 ;;
486 ;; Miscellany.
487 (slash "\\\\")
488 (opt "\\(\\[[^]]*\\]\\)?")
489 (arg "{\\(\\(?:[^{}]+\\(?:{[^}]*}\\)?\\)+\\)"))
490 (list
491 ;;
492 ;; Citation args.
493 (list (concat slash citations opt arg) 3 'font-lock-constant-face)
494 ;;
495 ;; Command names, special and general.
496 (cons (concat slash specials) 'font-lock-warning-face)
497 (concat slash general)
498 ;;
499 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
500 ;; since we might not be able to display those fonts.
501 (list (concat slash bold arg) 2 '(quote bold) 'append)
502 (list (concat slash italic arg) 2 '(quote italic) 'append)
503 (list (concat slash type arg) 2 '(quote bold-italic) 'append)
504 ;;
505 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
506 (list (concat "\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>"
507 "\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)")
508 3 '(if (match-beginning 2) 'bold 'italic) 'append)
509 ))))
510 "Gaudy expressions to highlight in TeX modes.")
511
512 (defvar tex-font-lock-keywords tex-font-lock-keywords-1
513 "Default expressions to highlight in TeX modes.")
514
515 \f
516 (defun tex-define-common-keys (keymap)
517 "Define the keys that we want defined both in TeX mode and in the TeX shell."
518 (define-key keymap "\C-c\C-k" 'tex-kill-job)
519 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
520 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
521 (define-key keymap "\C-c\C-p" 'tex-print)
522 (define-key keymap "\C-c\C-v" 'tex-view)
523
524 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
525
526 (define-key keymap [menu-bar tex tex-kill-job] '("Tex Kill" . tex-kill-job))
527 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
528 '("Tex Recenter" . tex-recenter-output-buffer))
529 (define-key keymap [menu-bar tex tex-show-print-queue]
530 '("Show Print Queue" . tex-show-print-queue))
531 (define-key keymap [menu-bar tex tex-alt-print]
532 '("Tex Print (alt printer)" . tex-alt-print))
533 (define-key keymap [menu-bar tex tex-print] '("Tex Print" . tex-print))
534 (define-key keymap [menu-bar tex tex-view] '("Tex View" . tex-view))
535 )
536
537 (defvar tex-mode-map nil "Keymap for TeX mode.")
538
539 (if tex-mode-map
540 nil
541 (setq tex-mode-map (make-sparse-keymap))
542 (tex-define-common-keys tex-mode-map)
543 (define-key tex-mode-map "\"" 'tex-insert-quote)
544 (define-key tex-mode-map "\n" 'tex-terminate-paragraph)
545 (define-key tex-mode-map "\M-\r" 'latex-insert-item)
546 (define-key tex-mode-map "\C-c}" 'up-list)
547 (define-key tex-mode-map "\C-c{" 'tex-insert-braces)
548 (define-key tex-mode-map "\C-c\C-r" 'tex-region)
549 (define-key tex-mode-map "\C-c\C-b" 'tex-buffer)
550 (define-key tex-mode-map "\C-c\C-f" 'tex-file)
551 (define-key tex-mode-map "\C-c\C-i" 'tex-bibtex-file)
552 (define-key tex-mode-map "\C-c\C-o" 'tex-latex-block)
553 (define-key tex-mode-map "\C-c\C-e" 'tex-close-latex-block)
554 (define-key tex-mode-map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
555 (define-key tex-mode-map "\C-c\C-m" 'tex-feed-input)
556 (define-key tex-mode-map [(control return)] 'tex-feed-input)
557 (define-key tex-mode-map [menu-bar tex tex-bibtex-file]
558 '("BibTeX File" . tex-bibtex-file))
559 (define-key tex-mode-map [menu-bar tex tex-validate-region]
560 '("Validate Region" . tex-validate-region))
561 (define-key tex-mode-map [menu-bar tex tex-validate-buffer]
562 '("Validate Buffer" . tex-validate-buffer))
563 (define-key tex-mode-map [menu-bar tex tex-region]
564 '("TeX Region" . tex-region))
565 (define-key tex-mode-map [menu-bar tex tex-buffer]
566 '("TeX Buffer" . tex-buffer))
567 (define-key tex-mode-map [menu-bar tex tex-file] '("TeX File" . tex-file)))
568
569 (put 'tex-region 'menu-enable 'mark-active)
570 (put 'tex-validate-region 'menu-enable 'mark-active)
571 (put 'tex-print 'menu-enable '(stringp tex-print-file))
572 (put 'tex-alt-print 'menu-enable '(stringp tex-print-file))
573 (put 'tex-view 'menu-enable '(stringp tex-print-file))
574 (put 'tex-recenter-output-buffer 'menu-enable '(get-buffer "*tex-shell*"))
575 (put 'tex-kill-job 'menu-enable '(tex-shell-running))
576
577 (defvar tex-shell-map
578 (let ((m (make-sparse-keymap)))
579 (set-keymap-parent m shell-mode-map)
580 (tex-define-common-keys m)
581 m)
582 "Keymap for the TeX shell.
583 Inherits `shell-mode-map' with a few additions.")
584
585 (defvar tex-face-alist
586 '((bold . "{\\bf ")
587 (italic . "{\\it ")
588 (bold-italic . "{\\bi ") ; hypothetical
589 (underline . "\\underline{")
590 (default . "{\\rm "))
591 "Alist of face and TeX font name for facemenu.")
592
593 (defvar tex-latex-face-alist
594 `((italic . "{\\em ")
595 ,@tex-face-alist)
596 "Alist of face and LaTeX font name for facemenu.")
597
598 ;;; This would be a lot simpler if we just used a regexp search,
599 ;;; but then it would be too slow.
600 ;;;###autoload
601 (defun tex-mode ()
602 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
603 Tries to determine (by looking at the beginning of the file) whether
604 this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
605 `latex-mode', or `slitex-mode', respectively. If it cannot be determined,
606 such as if there are no commands in the file, the value of `tex-default-mode'
607 says which mode to use."
608 (interactive)
609 (let ((mode tex-default-mode) slash comment)
610 (save-excursion
611 (goto-char (point-min))
612 (while (and (setq slash (search-forward "\\" nil t))
613 (setq comment (let ((search-end (point)))
614 (save-excursion
615 (beginning-of-line)
616 (search-forward "%" search-end t))))))
617 (if (and slash (not comment))
618 (setq mode (if (looking-at "documentstyle\\|documentclass\\|begin\\b\\|NeedsTeXFormat{LaTeX")
619 (if (looking-at
620 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
621 'slitex-mode
622 'latex-mode)
623 'plain-tex-mode))))
624 (funcall mode)))
625
626 ;;;###autoload
627 (defalias 'TeX-mode 'tex-mode)
628 ;;;###autoload
629 (defalias 'plain-TeX-mode 'plain-tex-mode)
630 ;;;###autoload
631 (defalias 'LaTeX-mode 'latex-mode)
632
633 ;;;###autoload
634 (define-derived-mode plain-tex-mode text-mode "TeX"
635 "Major mode for editing files of input for plain TeX.
636 Makes $ and } display the characters they match.
637 Makes \" insert `` when it seems to be the beginning of a quotation,
638 and '' when it appears to be the end; it inserts \" only after a \\.
639
640 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
641 copied from the top of the file (containing macro definitions, etc.),
642 running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
643 \\[tex-file] saves the buffer and then processes the file.
644 \\[tex-print] prints the .dvi file made by any of these.
645 \\[tex-view] previews the .dvi file made by any of these.
646 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
647
648 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
649 mismatched $'s or braces.
650
651 Special commands:
652 \\{tex-mode-map}
653
654 Mode variables:
655 tex-run-command
656 Command string used by \\[tex-region] or \\[tex-buffer].
657 tex-directory
658 Directory in which to create temporary files for TeX jobs
659 run by \\[tex-region] or \\[tex-buffer].
660 tex-dvi-print-command
661 Command string used by \\[tex-print] to print a .dvi file.
662 tex-alt-dvi-print-command
663 Alternative command string used by \\[tex-print] (when given a prefix
664 argument) to print a .dvi file.
665 tex-dvi-view-command
666 Command string used by \\[tex-view] to preview a .dvi file.
667 tex-show-queue-command
668 Command string used by \\[tex-show-print-queue] to show the print
669 queue that \\[tex-print] put your job on.
670
671 Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
672 `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
673 special subshell is initiated, the hook `tex-shell-hook' is run."
674 (tex-common-initialization)
675 (setq tex-command tex-run-command)
676 (setq tex-start-of-header "%\\*\\*start of header")
677 (setq tex-end-of-header "%\\*\\*end of header")
678 (setq tex-trailer "\\bye\n")
679 (run-hooks 'tex-mode-hook))
680
681 ;;;###autoload
682 (define-derived-mode latex-mode text-mode "LaTeX"
683 "Major mode for editing files of input for LaTeX.
684 Makes $ and } display the characters they match.
685 Makes \" insert `` when it seems to be the beginning of a quotation,
686 and '' when it appears to be the end; it inserts \" only after a \\.
687
688 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
689 copied from the top of the file (containing \\documentstyle, etc.),
690 running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
691 \\[tex-file] saves the buffer and then processes the file.
692 \\[tex-print] prints the .dvi file made by any of these.
693 \\[tex-view] previews the .dvi file made by any of these.
694 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
695
696 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
697 mismatched $'s or braces.
698
699 Special commands:
700 \\{tex-mode-map}
701
702 Mode variables:
703 latex-run-command
704 Command string used by \\[tex-region] or \\[tex-buffer].
705 tex-directory
706 Directory in which to create temporary files for LaTeX jobs
707 run by \\[tex-region] or \\[tex-buffer].
708 tex-dvi-print-command
709 Command string used by \\[tex-print] to print a .dvi file.
710 tex-alt-dvi-print-command
711 Alternative command string used by \\[tex-print] (when given a prefix
712 argument) to print a .dvi file.
713 tex-dvi-view-command
714 Command string used by \\[tex-view] to preview a .dvi file.
715 tex-show-queue-command
716 Command string used by \\[tex-show-print-queue] to show the print
717 queue that \\[tex-print] put your job on.
718
719 Entering Latex mode runs the hook `text-mode-hook', then
720 `tex-mode-hook', and finally `latex-mode-hook'. When the special
721 subshell is initiated, `tex-shell-hook' is run."
722 (tex-common-initialization)
723 (setq tex-command latex-run-command)
724 (setq tex-start-of-header "\\\\documentstyle\\|\\\\documentclass")
725 (setq tex-end-of-header "\\\\begin{document}")
726 (setq tex-trailer "\\end{document}\n")
727 ;; A line containing just $$ is treated as a paragraph separator.
728 ;; A line starting with $$ starts a paragraph,
729 ;; but does not separate paragraphs if it has more stuff on it.
730 (setq paragraph-start
731 (concat "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$\\|"
732 "\\\\[][]\\|"
733 "\\\\" (regexp-opt (append
734 (mapcar 'car latex-section-alist)
735 '("begin" "label" "end"
736 "item" "bibitem" "newline" "noindent"
737 "newpage" "footnote" "marginpar"
738 "parbox" "caption")) t)
739 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
740 "\\>"))
741 (setq paragraph-separate
742 (concat "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$[ \t]*$\\|"
743 "\\\\[][]\\|"
744 "\\\\" (regexp-opt (append
745 (mapcar 'car latex-section-alist)
746 '("begin" "label" "end" )) t)
747 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
748 "noindent" "newpage" "footnote"
749 "marginpar" "parbox" "caption"))
750 "\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
751 "\\)[ \t]*\\($\\|%\\)"))
752 (set (make-local-variable 'imenu-create-index-function)
753 'latex-imenu-create-index)
754 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
755 (set (make-local-variable 'fill-nobreak-predicate)
756 'latex-fill-nobreak-predicate)
757 (set (make-local-variable 'indent-line-function) 'latex-indent)
758 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
759 (set (make-local-variable 'outline-level) 'latex-outline-level)
760 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
761 (run-hooks 'tex-mode-hook))
762
763 ;;;###autoload
764 (define-derived-mode slitex-mode latex-mode "SliTeX"
765 "Major mode for editing files of input for SliTeX.
766 Makes $ and } display the characters they match.
767 Makes \" insert `` when it seems to be the beginning of a quotation,
768 and '' when it appears to be the end; it inserts \" only after a \\.
769
770 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
771 copied from the top of the file (containing \\documentstyle, etc.),
772 running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
773 \\[tex-file] saves the buffer and then processes the file.
774 \\[tex-print] prints the .dvi file made by any of these.
775 \\[tex-view] previews the .dvi file made by any of these.
776 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
777
778 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
779 mismatched $'s or braces.
780
781 Special commands:
782 \\{tex-mode-map}
783
784 Mode variables:
785 slitex-run-command
786 Command string used by \\[tex-region] or \\[tex-buffer].
787 tex-directory
788 Directory in which to create temporary files for SliTeX jobs
789 run by \\[tex-region] or \\[tex-buffer].
790 tex-dvi-print-command
791 Command string used by \\[tex-print] to print a .dvi file.
792 tex-alt-dvi-print-command
793 Alternative command string used by \\[tex-print] (when given a prefix
794 argument) to print a .dvi file.
795 tex-dvi-view-command
796 Command string used by \\[tex-view] to preview a .dvi file.
797 tex-show-queue-command
798 Command string used by \\[tex-show-print-queue] to show the print
799 queue that \\[tex-print] put your job on.
800
801 Entering SliTeX mode runs the hook `text-mode-hook', then the hook
802 `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
803 `slitex-mode-hook'. When the special subshell is initiated, the hook
804 `tex-shell-hook' is run."
805 (setq tex-command slitex-run-command)
806 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
807
808 (defun tex-common-initialization ()
809 (use-local-map tex-mode-map)
810 (set-syntax-table tex-mode-syntax-table)
811 ;; Regexp isearch should accept newline and formfeed as whitespace.
812 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
813 ;; A line containing just $$ is treated as a paragraph separator.
814 (set (make-local-variable 'paragraph-start)
815 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
816 ;; A line starting with $$ starts a paragraph,
817 ;; but does not separate paragraphs if it has more stuff on it.
818 (set (make-local-variable 'paragraph-separate)
819 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
820 (set (make-local-variable 'comment-start) "%")
821 (set (make-local-variable 'comment-add) 1)
822 (set (make-local-variable 'comment-start-skip)
823 "\\(\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
824 (set (make-local-variable 'parse-sexp-ignore-comments) t)
825 (set (make-local-variable 'compare-windows-whitespace)
826 'tex-categorize-whitespace)
827 (set (make-local-variable 'facemenu-add-face-function)
828 (lambda (face end)
829 (let ((face-text (cdr (assq face tex-face-alist))))
830 (if face-text
831 face-text
832 (error "Face %s not configured for %s mode" face mode-name)))))
833 (set (make-local-variable 'facemenu-end-add-face) "}")
834 (set (make-local-variable 'facemenu-remove-face-function) t)
835 (set (make-local-variable 'font-lock-defaults)
836 '((tex-font-lock-keywords
837 tex-font-lock-keywords-1 tex-font-lock-keywords-2)
838 nil nil ((?$ . "\"")) nil
839 ;; Who ever uses that anyway ???
840 (font-lock-mark-block-function . mark-paragraph)))
841 (make-local-variable 'tex-command)
842 (make-local-variable 'tex-start-of-header)
843 (make-local-variable 'tex-end-of-header)
844 (make-local-variable 'tex-trailer))
845
846 (defun tex-categorize-whitespace (backward-limit)
847 ;; compare-windows-whitespace is set to this.
848 ;; This is basically a finite-state machine.
849 ;; Returns a symbol telling how TeX would treat
850 ;; the whitespace we are looking at: null, space, or par.
851 (let ((category 'null)
852 (not-finished t))
853 (skip-chars-backward " \t\n\f" backward-limit)
854 (while not-finished
855 (cond ((looking-at "[ \t]+")
856 (goto-char (match-end 0))
857 (if (eq category 'null)
858 (setq category 'space)))
859 ((looking-at "\n")
860 (cond ((eq category 'newline)
861 (setq category 'par)
862 (setq not-finished nil))
863 (t
864 (setq category 'newline) ;a strictly internal state
865 (goto-char (match-end 0)))))
866 ((looking-at "\f+")
867 (setq category 'par)
868 (setq not-finished nil))
869 (t
870 (setq not-finished nil))))
871 (skip-chars-forward " \t\n\f")
872 (if (eq category 'newline)
873 'space ;TeX doesn't distinguish
874 category)))
875
876 (defun tex-insert-quote (arg)
877 "Insert the appropriate quote marks for TeX.
878 Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
879 \(normally '') depending on the context. With prefix argument, always
880 inserts \" characters."
881 (interactive "*P")
882 (if arg
883 (self-insert-command (prefix-numeric-value arg))
884 (insert
885 (cond ((or (bobp)
886 (save-excursion
887 (forward-char -1)
888 (looking-at "\\s(\\|\\s \\|\\s>")))
889 tex-open-quote)
890 ((= (preceding-char) ?\\)
891 ?\")
892 (t
893 tex-close-quote)))))
894
895 (defun tex-validate-buffer ()
896 "Check current buffer for paragraphs containing mismatched braces or $s.
897 Their positions are recorded in the buffer `*Occur*'.
898 To find a particular invalidity from `*Occur*', switch to that buffer
899 and type C-c C-c or click with mouse-2
900 on the line for the invalidity you want to see."
901 (interactive)
902 (let ((buffer (current-buffer))
903 (prevpos (point-min))
904 (linenum nil)
905 (num-matches 0))
906 (with-output-to-temp-buffer "*Occur*"
907 (princ "Mismatches:\n")
908 (save-excursion
909 (set-buffer standard-output)
910 (occur-mode)
911 (setq occur-buffer buffer)
912 (setq occur-nlines 0))
913 (save-excursion
914 (goto-char (point-max))
915 (while (and (not (input-pending-p)) (not (bobp)))
916 (let ((end (point))
917 prev-end)
918 ;; Scan the previous paragraph for invalidities.
919 (if (search-backward "\n\n" nil t)
920 (progn
921 (setq prev-end (point))
922 (forward-char 2))
923 (goto-char (setq prev-end (point-min))))
924 (or (tex-validate-region (point) end)
925 (let* ((oend end)
926 (end (save-excursion (forward-line 1) (point)))
927 start tem)
928 (beginning-of-line)
929 (setq start (point))
930 ;; Keep track of line number as we scan,
931 ;; in a cumulative fashion.
932 (if linenum
933 (setq linenum (- linenum (count-lines prevpos (point))))
934 (setq linenum (1+ (count-lines 1 start))))
935 (setq prevpos (point))
936 ;; Mention this mismatch in *Occur*.
937 ;; Since we scan from end of buffer to beginning,
938 ;; add each mismatch at the beginning of *Occur*.
939 (save-excursion
940 (setq tem (point-marker))
941 (set-buffer standard-output)
942 (goto-char (point-min))
943 ;; Skip "Mismatches:" header line.
944 (forward-line 1)
945 (setq num-matches (1+ num-matches))
946 (insert-buffer-substring buffer start end)
947 (let (text-beg (text-end (point-marker)))
948 (forward-char (- start end))
949 (setq text-beg (point-marker))
950 (insert (format "%3d: " linenum))
951 (put-text-property (marker-position text-beg)
952 (- (marker-position text-end) 1)
953 'mouse-face 'highlight)
954 (put-text-property (marker-position text-beg)
955 (- (marker-position text-end) 1)
956 'occur tem)))))
957 (goto-char prev-end))))
958 (save-excursion
959 (set-buffer standard-output)
960 (if (eq num-matches 0)
961 (insert "None!\n"))
962 (if (interactive-p)
963 (message "%d mismatches found" num-matches))))))
964
965 (defun tex-validate-region (start end)
966 "Check for mismatched braces or $'s in region.
967 Returns t if no mismatches. Returns nil and moves point to suspect
968 area if a mismatch is found."
969 (interactive "r")
970 (let ((failure-point nil) (max-possible-sexps (- end start)))
971 (save-excursion
972 (condition-case ()
973 (save-restriction
974 (narrow-to-region start end)
975 ;; First check that the open and close parens balance in numbers.
976 (goto-char start)
977 (while (<= 0 (setq max-possible-sexps (1- max-possible-sexps)))
978 (forward-sexp 1))
979 ;; Now check that like matches like.
980 (goto-char start)
981 (while (progn (skip-syntax-forward "^(")
982 (not (eobp)))
983 (let ((match (matching-paren (following-char))))
984 (save-excursion
985 (forward-sexp 1)
986 (or (= (preceding-char) match)
987 (error "Mismatched parentheses"))))
988 (forward-char 1)))
989 (error
990 (skip-syntax-forward " .>")
991 (setq failure-point (point)))))
992 (if failure-point
993 (progn
994 (goto-char failure-point)
995 nil)
996 t)))
997
998 (defun tex-terminate-paragraph (inhibit-validation)
999 "Insert two newlines, breaking a paragraph for TeX.
1000 Check for mismatched braces or $s in paragraph being terminated.
1001 A prefix arg inhibits the checking."
1002 (interactive "*P")
1003 (or inhibit-validation
1004 (save-excursion
1005 (tex-validate-region
1006 (save-excursion
1007 (search-backward "\n\n" nil 'move)
1008 (point))
1009 (point)))
1010 (message "Paragraph being closed appears to contain a mismatch"))
1011 (insert "\n\n"))
1012
1013 (defun tex-insert-braces ()
1014 "Make a pair of braces and be poised to type inside of them."
1015 (interactive "*")
1016 (insert ?\{)
1017 (save-excursion
1018 (insert ?})))
1019
1020 ;; This function is used as the value of fill-nobreak-predicate
1021 ;; in LaTeX mode. Its job is to prevent line-breaking inside
1022 ;; of a \verb construct.
1023 (defun latex-fill-nobreak-predicate ()
1024 (let ((opoint (point))
1025 inside)
1026 (save-excursion
1027 (save-restriction
1028 (beginning-of-line)
1029 (narrow-to-region (point) opoint)
1030 (while (re-search-forward "\\\\verb\\(.\\)" nil t)
1031 (unless (re-search-forward (regexp-quote (match-string 1)) nil t)
1032 (setq inside t)))))
1033 inside))
1034
1035 (defvar latex-block-default "enumerate")
1036
1037 ;;; Like tex-insert-braces, but for LaTeX.
1038 (define-skeleton tex-latex-block
1039 "Create a matching pair of lines \\begin[OPT]{NAME} and \\end{NAME} at point.
1040 Puts point on a blank line between them."
1041 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1042 latex-block-default)
1043 (mapcar 'list
1044 (append standard-latex-block-names
1045 latex-block-names))
1046 nil nil nil nil latex-block-default)))
1047 (setq latex-block-default choice)
1048 (unless (or (member choice standard-latex-block-names)
1049 (member choice latex-block-names))
1050 ;; Remember new block names for later completion.
1051 (push choice latex-block-names))
1052 choice)
1053 "\\begin{" str ?\}
1054 ?\[ (skeleton-read "[options]: ") & ?\] | -1
1055 \n _ \n
1056 "\\end{" str ?\} >)
1057
1058 (define-skeleton latex-insert-item
1059 "Insert a \item macro."
1060 nil
1061 \n "\\item " >)
1062
1063 \f
1064 ;;;;
1065 ;;;; LaTeX syntax navigation
1066 ;;;;
1067
1068 (defun tex-last-unended-begin ()
1069 "Leave point at the beginning of the last `\\begin{...}' that is unended."
1070 (while (and (re-search-backward "\\\\\\(begin\\|end\\)\\s *{")
1071 (looking-at "\\\\end"))
1072 (tex-last-unended-begin)))
1073
1074 (defun tex-next-unmatched-end ()
1075 "Leave point at the end of the next `\\end' that is unended."
1076 (while (and (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}")
1077 (save-excursion (goto-char (match-beginning 0))
1078 (looking-at "\\\\begin")))
1079 (tex-next-unmatched-end)))
1080
1081 (defun tex-goto-last-unclosed-latex-block ()
1082 "Move point to the last unclosed \\begin{...}.
1083 Mark is left at original location."
1084 (interactive)
1085 (let ((spot))
1086 (save-excursion
1087 (condition-case nil
1088 (tex-last-unended-begin)
1089 (error (error "Couldn't find unended \\begin")))
1090 (setq spot (point)))
1091 (push-mark)
1092 (goto-char spot)))
1093
1094 (defun latex-backward-sexp-1 ()
1095 "Like (backward-sexp 1) but aware of multi-char elements."
1096 (let ((pos (point))
1097 (forward-sexp-function))
1098 (backward-sexp 1)
1099 (if (looking-at "\\\\begin\\>")
1100 (signal 'scan-error
1101 (list "Containing expression ends prematurely"
1102 (point) (prog1 (point) (goto-char pos))))
1103 (when (eq (char-after) ?{)
1104 (let ((newpos (point)))
1105 (when (ignore-errors (backward-sexp 1) t)
1106 (if (looking-at "\\\\end\\>")
1107 (tex-last-unended-begin)
1108 (goto-char newpos))))))))
1109
1110 (defun latex-forward-sexp-1 ()
1111 "Like (forward-sexp 1) but aware of multi-char elements."
1112 (let ((pos (point))
1113 (forward-sexp-function))
1114 (forward-sexp 1)
1115 (let ((newpos (point)))
1116 (skip-syntax-backward "/w")
1117 (cond
1118 ((looking-at "\\\\end\\>")
1119 (signal 'scan-error
1120 (list "Containing expression ends prematurely"
1121 (point)
1122 (prog1
1123 (progn (ignore-errors (forward-sexp 2)) (point))
1124 (goto-char pos)))))
1125 ((looking-at "\\\\begin\\>")
1126 (goto-char (match-end 0))
1127 (tex-next-unmatched-end))
1128 (t (goto-char newpos))))))
1129
1130 (defun latex-forward-sexp (&optional arg)
1131 "Like `forward-sexp' but aware of multi-char elements."
1132 (interactive "P")
1133 (unless arg (setq arg 1))
1134 (let ((pos (point)))
1135 (condition-case err
1136 (while (/= arg 0)
1137 (setq arg
1138 (if (> arg 0)
1139 (progn (latex-forward-sexp-1) (1- arg))
1140 (progn (latex-backward-sexp-1) (1+ arg)))))
1141 (scan-error
1142 (goto-char pos)
1143 (signal (car err) (cdr err))))))
1144
1145 (defun latex-syntax-after ()
1146 "Like (char-syntax (char-after)) but aware of multi-char elements."
1147 (if (looking-at "\\\\end\\>") ?\) (char-syntax (char-after))))
1148
1149 (defun latex-skip-close-parens ()
1150 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1151 (let ((forward-sexp-function nil))
1152 (while (progn (skip-syntax-forward " )")
1153 (looking-at "\\\\end\\>"))
1154 (forward-sexp 2))))
1155
1156 (defun latex-down-list ()
1157 "Like (down-list 1) but aware of multi-char elements."
1158 (forward-comment (point-max))
1159 (let ((forward-sexp-function nil))
1160 (if (not (looking-at "\\\\begin\\>"))
1161 (down-list 1)
1162 (forward-sexp 1)
1163 ;; Skip arguments.
1164 (while (looking-at "[ \t]*\\s(") (forward-sexp)))))
1165
1166 (defun tex-close-latex-block ()
1167 "Creates an \\end{...} to match the last unclosed \\begin{...}."
1168 (interactive "*")
1169 (let ((new-line-needed (bolp))
1170 text indentation)
1171 (save-excursion
1172 (condition-case nil
1173 (tex-last-unended-begin)
1174 (error (error "Couldn't find unended \\begin")))
1175 (setq indentation (current-column))
1176 (re-search-forward "\\\\begin\\(\\s *{[^}\n]*}\\)")
1177 (setq text (buffer-substring (match-beginning 1) (match-end 1))))
1178 (indent-to indentation)
1179 (insert "\\end" text)
1180 (if new-line-needed (insert ?\n))))
1181 \f
1182 ;;; Invoking TeX in an inferior shell.
1183
1184 ;;; Why use a shell instead of running TeX directly? Because if TeX
1185 ;;; gets stuck, the user can switch to the shell window and type at it.
1186
1187 ;;; The utility functions:
1188
1189 ;;;###autoload
1190 (defun tex-start-shell ()
1191 (with-current-buffer
1192 (make-comint
1193 "tex-shell"
1194 (or tex-shell-file-name (getenv "ESHELL") (getenv "SHELL") "/bin/sh")
1195 nil)
1196 (let ((proc (get-process "tex-shell")))
1197 (set-process-sentinel proc 'tex-shell-sentinel)
1198 (process-kill-without-query proc)
1199 (setq comint-prompt-regexp shell-prompt-pattern)
1200 (use-local-map tex-shell-map)
1201 (compilation-shell-minor-mode t)
1202 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
1203 (make-local-variable 'list-buffers-directory)
1204 (make-local-variable 'shell-dirstack)
1205 (make-local-variable 'shell-last-dir)
1206 (make-local-variable 'shell-dirtrackp)
1207 (run-hooks 'tex-shell-hook)
1208 (while (zerop (buffer-size))
1209 (sleep-for 1)))))
1210
1211 (defun tex-feed-input ()
1212 "Send input to the tex shell process.
1213 In the tex buffer this can be used to continue an interactive tex run.
1214 In the tex shell buffer this command behaves like `comint-send-input'."
1215 (interactive)
1216 (set-buffer (process-buffer (get-process "tex-shell")))
1217 (comint-send-input)
1218 (tex-recenter-output-buffer nil))
1219
1220 (defun tex-display-shell ()
1221 "Make the TeX shell buffer visible in a window."
1222 (display-buffer (process-buffer (get-process "tex-shell")))
1223 (tex-recenter-output-buffer nil))
1224
1225 (defun tex-shell-sentinel (proc msg)
1226 (cond ((null (buffer-name (process-buffer proc)))
1227 ;; buffer killed
1228 (set-process-buffer proc nil)
1229 (tex-delete-last-temp-files))
1230 ((memq (process-status proc) '(signal exit))
1231 (tex-delete-last-temp-files))))
1232
1233 (defun tex-set-buffer-directory (buffer directory)
1234 "Set BUFFER's default directory to be DIRECTORY."
1235 (setq directory (file-name-as-directory (expand-file-name directory)))
1236 (if (not (file-directory-p directory))
1237 (error "%s is not a directory" directory)
1238 (save-excursion
1239 (set-buffer buffer)
1240 (setq default-directory directory))))
1241
1242 (defvar tex-send-command-modified-tick 0)
1243 (make-variable-buffer-local 'tex-send-command-modified-tick)
1244
1245 (defun tex-send-command (command &optional file background)
1246 "Send COMMAND to TeX shell process, substituting optional FILE for *.
1247 Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1248 FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1249 substitution will be made in COMMAND. COMMAND can be any expression that
1250 evaluates to a command string.
1251
1252 Return the process in which TeX is running."
1253 (save-excursion
1254 (let* ((cmd (eval command))
1255 (proc (or (get-process "tex-shell") (error "No TeX subprocess")))
1256 (buf (process-buffer proc))
1257 (star (string-match "\\*" cmd))
1258 (string
1259 (concat
1260 (if file
1261 (if star (concat (substring cmd 0 star)
1262 file (substring cmd (1+ star)))
1263 (concat cmd " " file))
1264 cmd)
1265 (if background "&" ""))))
1266 ;; Switch to buffer before checking for subproc output in it.
1267 (set-buffer buf)
1268 ;; If text is unchanged since previous tex-send-command,
1269 ;; we haven't got any output. So wait for output now.
1270 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
1271 (accept-process-output proc))
1272 (goto-char (process-mark proc))
1273 (insert string)
1274 (comint-send-input)
1275 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1276 proc)))
1277
1278 (defun tex-delete-last-temp-files (&optional not-all)
1279 "Delete any junk files from last temp file.
1280 If NOT-ALL is non-nil, save the `.dvi' file."
1281 (if tex-last-temp-file
1282 (let* ((dir (file-name-directory tex-last-temp-file))
1283 (list (and (file-directory-p dir)
1284 (file-name-all-completions
1285 (file-name-sans-extension
1286 (file-name-nondirectory tex-last-temp-file))
1287 dir))))
1288 (while list
1289 (if not-all
1290 (and
1291 ;; If arg is non-nil, don't delete the .dvi file.
1292 (not (string-match "\\.dvi$" (car list)))
1293 (delete-file (concat dir (car list))))
1294 (delete-file (concat dir (car list))))
1295 (setq list (cdr list))))))
1296
1297 (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
1298
1299 (defvar tex-start-tex-marker nil
1300 "Marker pointing after last TeX-running command in the TeX shell buffer.")
1301
1302 (defun tex-main-file ()
1303 (let ((file (or tex-main-file
1304 ;; Compatibility with AUCTeX
1305 (and (boundp 'TeX-master) (stringp TeX-master) TeX-master)
1306 (if (buffer-file-name)
1307 (file-relative-name (buffer-file-name))
1308 (error "Buffer is not associated with any file")))))
1309 (if (string-match "\\.tex\\'" file)
1310 (substring file 0 (match-beginning 0))
1311 file)))
1312
1313 (defun tex-start-tex (command file &optional dir)
1314 "Start a TeX run, using COMMAND on FILE."
1315 (let* ((star (string-match "\\*" command))
1316 (compile-command
1317 (if star
1318 (concat (substring command 0 star)
1319 (comint-quote-filename file)
1320 (substring command (1+ star)))
1321 (concat command " "
1322 (if (< 0 (length tex-start-options-string))
1323 (concat
1324 (shell-quote-argument tex-start-options-string) " "))
1325 (comint-quote-filename file)))))
1326 (when dir
1327 (let (shell-dirtrack-verbose)
1328 (tex-send-command tex-shell-cd-command dir)))
1329 (with-current-buffer (process-buffer (tex-send-command compile-command))
1330 (save-excursion
1331 (forward-line -1)
1332 (setq tex-start-tex-marker (point-marker)))
1333 (make-local-variable 'compilation-parse-errors-function)
1334 (setq compilation-parse-errors-function 'tex-compilation-parse-errors)
1335 (compilation-forget-errors))
1336 (tex-display-shell)
1337 (setq tex-last-buffer-texed (current-buffer))))
1338 \f
1339 (defun tex-compilation-parse-errors (limit-search find-at-least)
1340 "Parse the current buffer as TeX error messages.
1341 See the variable `compilation-parse-errors-function' for the interface it uses.
1342
1343 This function parses only the last TeX compilation.
1344 It works on TeX compilations only. It is necessary for that purpose,
1345 since TeX does not put file names and line numbers on the same line as
1346 for the error messages."
1347 (require 'thingatpt)
1348 (setq compilation-error-list nil)
1349 (message "Parsing error messages...")
1350 (let ((default-directory ; Perhaps dir has changed meanwhile.
1351 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
1352 (old-syntax-table (syntax-table))
1353 (tex-error-parse-syntax-table (copy-syntax-table (syntax-table)))
1354 found-desired (num-errors-found 0)
1355 last-filename last-linenum last-position
1356 begin-of-error end-of-error)
1357 (modify-syntax-entry ?\{ "_" tex-error-parse-syntax-table)
1358 (modify-syntax-entry ?\} "_" tex-error-parse-syntax-table)
1359 (modify-syntax-entry ?\[ "_" tex-error-parse-syntax-table)
1360 (modify-syntax-entry ?\] "_" tex-error-parse-syntax-table)
1361 ;; Single quotations may appear in errors
1362 (modify-syntax-entry ?\" "_" tex-error-parse-syntax-table)
1363 ;; Don't parse previous compilations.
1364 (set-marker compilation-parsing-end
1365 (max compilation-parsing-end tex-start-tex-marker))
1366 ;; Don't reparse messages already seen at last parse.
1367 (goto-char compilation-parsing-end)
1368 ;; Parse messages.
1369 (while (and (not (or found-desired (eobp)))
1370 (prog1 (re-search-forward "^! " nil 'move)
1371 (setq begin-of-error (match-beginning 0)
1372 end-of-error (match-end 0)))
1373 (re-search-forward
1374 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
1375 (let* ((this-error (set-marker (make-marker) begin-of-error))
1376 (linenum (string-to-int (match-string 1)))
1377 (error-text (regexp-quote (match-string 3)))
1378 (filename
1379 (save-excursion
1380 (with-syntax-table tex-error-parse-syntax-table
1381 (backward-up-list 1)
1382 (skip-syntax-forward "(_")
1383 (while (not (file-readable-p (thing-at-point 'filename)))
1384 (skip-syntax-backward "(_")
1385 (backward-up-list 1)
1386 (skip-syntax-forward "(_"))
1387 (thing-at-point 'filename))))
1388 (new-file
1389 (or (null last-filename)
1390 (not (string-equal last-filename filename))))
1391 (error-location
1392 (save-excursion
1393 (if (equal filename (concat tex-zap-file ".tex"))
1394 (set-buffer tex-last-buffer-texed)
1395 (set-buffer (find-file-noselect filename)))
1396 (if new-file
1397 (goto-line linenum)
1398 (goto-char last-position)
1399 (forward-line (- linenum last-linenum)))
1400 ;; first try a forward search for the error text,
1401 ;; then a backward search limited by the last error.
1402 (let ((starting-point (point)))
1403 (or (re-search-forward error-text nil t)
1404 (re-search-backward
1405 error-text
1406 (marker-position last-position) t)
1407 (goto-char starting-point)))
1408 (point-marker))))
1409 (goto-char this-error)
1410 (if (and compilation-error-list
1411 (or (and find-at-least
1412 (>= num-errors-found
1413 find-at-least))
1414 (and limit-search
1415 (>= end-of-error limit-search)))
1416 new-file)
1417 (setq found-desired t)
1418 (setq num-errors-found (1+ num-errors-found)
1419 last-filename filename
1420 last-linenum linenum
1421 last-position error-location
1422 compilation-error-list ; Add the new error
1423 (cons (cons this-error error-location)
1424 compilation-error-list))
1425 (goto-char end-of-error)))))
1426 (set-marker compilation-parsing-end (point))
1427 (setq compilation-error-list (nreverse compilation-error-list))
1428 (message "Parsing error messages...done"))
1429 \f
1430 ;;; The commands:
1431
1432 (defun tex-region (beg end)
1433 "Run TeX on the current region, via a temporary file.
1434 The file's name comes from the variable `tex-zap-file' and the
1435 variable `tex-directory' says where to put it.
1436
1437 If the buffer has a header, the header is given to TeX before the
1438 region itself. The buffer's header is all lines between the strings
1439 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
1440 The header must start in the first 100 lines of the buffer.
1441
1442 The value of `tex-trailer' is given to TeX as input after the region.
1443
1444 The value of `tex-command' specifies the command to use to run TeX."
1445 (interactive "r")
1446 (if (tex-shell-running)
1447 (tex-kill-job)
1448 (tex-start-shell))
1449 (or tex-zap-file
1450 (setq tex-zap-file (tex-generate-zap-file-name)))
1451 ;; Temp file will be written and TeX will be run in zap-directory.
1452 ;; If the TEXINPUTS file has relative directories or if the region has
1453 ;; \input of files, this must be the same directory as the file for
1454 ;; TeX to access the correct inputs. That's why it's safest if
1455 ;; tex-directory is ".".
1456 (let* ((zap-directory
1457 (file-name-as-directory (expand-file-name tex-directory)))
1458 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
1459 zap-directory)))
1460 ;; Don't delete temp files if we do the same buffer twice in a row.
1461 (or (eq (current-buffer) tex-last-buffer-texed)
1462 (tex-delete-last-temp-files t))
1463 ;; Write the new temp file.
1464 (save-excursion
1465 (save-restriction
1466 (widen)
1467 (goto-char (point-min))
1468 (forward-line 100)
1469 (let ((search-end (point))
1470 (default-directory zap-directory)
1471 (already-output 0))
1472 (goto-char (point-min))
1473
1474 ;; Maybe copy first line, such as `\input texinfo', to temp file.
1475 (and tex-first-line-header-regexp
1476 (looking-at tex-first-line-header-regexp)
1477 (write-region (point)
1478 (progn (forward-line 1)
1479 (setq already-output (point)))
1480 tex-out-file nil nil))
1481
1482 ;; Write out the header, if there is one,
1483 ;; and any of the specified region which extends before it.
1484 ;; But don't repeat anything already written.
1485 (if (re-search-forward tex-start-of-header search-end t)
1486 (let (hbeg)
1487 (beginning-of-line)
1488 (setq hbeg (point)) ;mark beginning of header
1489 (if (re-search-forward tex-end-of-header nil t)
1490 (let (hend)
1491 (forward-line 1)
1492 (setq hend (point)) ;mark end of header
1493 (write-region (max (min hbeg beg) already-output)
1494 hend
1495 tex-out-file
1496 (not (zerop already-output)) nil)
1497 (setq already-output hend)))))
1498
1499 ;; Write out the specified region
1500 ;; (but don't repeat anything already written).
1501 (write-region (max beg already-output) end
1502 tex-out-file
1503 (not (zerop already-output)) nil))
1504 ;; Write the trailer, if any.
1505 ;; Precede it with a newline to make sure it
1506 ;; is not hidden in a comment.
1507 (if tex-trailer
1508 (write-region (concat "\n" tex-trailer) nil
1509 tex-out-file t nil))))
1510 ;; Record the file name to be deleted afterward.
1511 (setq tex-last-temp-file tex-out-file)
1512 ;; Use a relative file name here because (1) the proper dir
1513 ;; is already current, and (2) the abs file name is sometimes
1514 ;; too long and can make tex crash.
1515 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
1516 (setq tex-print-file tex-out-file)))
1517
1518 (defun tex-buffer ()
1519 "Run TeX on current buffer. See \\[tex-region] for more information.
1520 Does not save the buffer, so it's useful for trying experimental versions.
1521 See \\[tex-file] for an alternative."
1522 (interactive)
1523 (tex-region (point-min) (point-max)))
1524
1525 (defun tex-file ()
1526 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
1527 This function is more useful than \\[tex-buffer] when you need the
1528 `.aux' file of LaTeX to have the correct name."
1529 (interactive)
1530 (let* ((source-file (tex-main-file))
1531 (file-dir (expand-file-name (file-name-directory source-file))))
1532 (if tex-offer-save
1533 (save-some-buffers))
1534 (if (tex-shell-running)
1535 (tex-kill-job)
1536 (tex-start-shell))
1537 (tex-start-tex tex-command source-file file-dir)
1538 (setq tex-print-file (expand-file-name source-file))))
1539
1540 (defun tex-generate-zap-file-name ()
1541 "Generate a unique name suitable for use as a file name."
1542 ;; Include the shell process number and host name
1543 ;; in case there are multiple shells (for same or different user).
1544 ;; Dec 1998: There is a report that some versions of xdvi
1545 ;; don't work with file names that start with #.
1546 (format "_TZ_%d-%s"
1547 (process-id (get-buffer-process "*tex-shell*"))
1548 (tex-strip-dots (system-name))))
1549
1550 (defun tex-strip-dots (s)
1551 (setq s (copy-sequence s))
1552 (while (string-match "\\." s)
1553 (aset s (match-beginning 0) ?-))
1554 s)
1555
1556 ;; This will perhaps be useful for modifying TEXINPUTS.
1557 ;; Expand each file name, separated by colons, in the string S.
1558 (defun tex-expand-files (s)
1559 (let (elts (start 0))
1560 (while (string-match ":" s start)
1561 (setq elts (cons (substring s start (match-beginning 0)) elts))
1562 (setq start (match-end 0)))
1563 (or (= start 0)
1564 (setq elts (cons (substring s start) elts)))
1565 (mapconcat (lambda (elt)
1566 (if (= (length elt) 0) elt (expand-file-name elt)))
1567 (nreverse elts) ":")))
1568
1569 (defun tex-shell-running ()
1570 (and (get-process "tex-shell")
1571 (eq (process-status (get-process "tex-shell")) 'run)))
1572
1573 (defun tex-kill-job ()
1574 "Kill the currently running TeX job."
1575 (interactive)
1576 ;; quit-process leads to core dumps of the tex process (except if
1577 ;; coredumpsize has limit 0kb as on many environments). One would
1578 ;; like to use (kill-process proc 'lambda), however that construct
1579 ;; does not work on some systems and kills the shell itself.
1580 (quit-process (get-process "tex-shell") t))
1581
1582 (defun tex-recenter-output-buffer (linenum)
1583 "Redisplay buffer of TeX job output so that most recent output can be seen.
1584 The last line of the buffer is displayed on
1585 line LINE of the window, or centered if LINE is nil."
1586 (interactive "P")
1587 (let ((tex-shell (get-buffer "*tex-shell*"))
1588 (old-buffer (current-buffer))
1589 (window))
1590 (if (null tex-shell)
1591 (message "No TeX output buffer")
1592 (setq window (display-buffer tex-shell))
1593 (save-selected-window
1594 (select-window window)
1595 (bury-buffer tex-shell)
1596 (goto-char (point-max))
1597 (recenter (if linenum
1598 (prefix-numeric-value linenum)
1599 (/ (window-height) 2)))))))
1600
1601 (defun tex-print (&optional alt)
1602 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1603 Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
1604 is provided, use the alternative command, `tex-alt-dvi-print-command'."
1605 (interactive "P")
1606 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
1607 test-name)
1608 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
1609 (buffer-file-name)
1610 ;; Check that this buffer's printed file is up to date.
1611 (file-newer-than-file-p
1612 (setq test-name (tex-append (buffer-file-name) ".dvi"))
1613 (buffer-file-name)))
1614 (setq print-file-name-dvi test-name))
1615 (if (not (file-exists-p print-file-name-dvi))
1616 (error "No appropriate `.dvi' file could be found")
1617 (if (tex-shell-running)
1618 (tex-kill-job)
1619 (tex-start-shell))
1620 (tex-send-command
1621 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
1622 print-file-name-dvi t))))
1623
1624 (defun tex-alt-print ()
1625 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1626 Runs the shell command defined by `tex-alt-dvi-print-command'."
1627 (interactive)
1628 (tex-print t))
1629
1630 (defun tex-view ()
1631 "Preview the last `.dvi' file made by running TeX under Emacs.
1632 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
1633 The variable `tex-dvi-view-command' specifies the shell command for preview.
1634 You must set that variable yourself before using this command,
1635 because there is no standard value that would generally work."
1636 (interactive)
1637 (or tex-dvi-view-command
1638 (error "You must set `tex-dvi-view-command'"))
1639 (let ((tex-dvi-print-command tex-dvi-view-command))
1640 (tex-print)))
1641
1642 (defun tex-append (file-name suffix)
1643 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
1644 Pascal-based TeX scans for the first period, C TeX uses the last.
1645 No period is retained immediately before SUFFIX,
1646 so normally SUFFIX starts with one."
1647 (if (stringp file-name)
1648 (let ((file (file-name-nondirectory file-name))
1649 trial-name)
1650 ;; Try splitting on last period.
1651 ;; The first-period split can get fooled when two files
1652 ;; named a.tex and a.b.tex are both tex'd;
1653 ;; the last-period split must be right if it matches at all.
1654 (setq trial-name
1655 (concat (file-name-directory file-name)
1656 (substring file 0
1657 (string-match "\\.[^.]*$" file))
1658 suffix))
1659 (if (or (file-exists-p trial-name)
1660 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
1661 trial-name
1662 ;; Not found, so split on first period.
1663 (concat (file-name-directory file-name)
1664 (substring file 0
1665 (string-match "\\." file))
1666 suffix)))
1667 " "))
1668
1669 (defun tex-show-print-queue ()
1670 "Show the print queue that \\[tex-print] put your job on.
1671 Runs the shell command defined by `tex-show-queue-command'."
1672 (interactive)
1673 (if (tex-shell-running)
1674 (tex-kill-job)
1675 (tex-start-shell))
1676 (tex-send-command tex-show-queue-command)
1677 (tex-display-shell))
1678
1679 (defun tex-bibtex-file ()
1680 "Run BibTeX on the current buffer's file."
1681 (interactive)
1682 (if (tex-shell-running)
1683 (tex-kill-job)
1684 (tex-start-shell))
1685 (let (shell-dirtrack-verbose
1686 (tex-out-file
1687 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
1688 (file-dir (file-name-directory (buffer-file-name))))
1689 (tex-send-command tex-shell-cd-command file-dir)
1690 (tex-send-command tex-bibtex-command tex-out-file))
1691 (tex-display-shell))
1692 \f
1693 ;;;;
1694 ;;;; LaTeX indentation
1695 ;;;;
1696
1697 (defvar tex-indent-allhanging t)
1698 (defvar tex-indent-arg 4)
1699 (defvar tex-indent-basic 2)
1700 (defvar tex-indent-item tex-indent-basic)
1701 (defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
1702
1703 (easy-mmode-defsyntax tex-latex-indent-syntax-table
1704 '((?$ . "."))
1705 "Syntax table used while computing indentation."
1706 :copy tex-mode-syntax-table)
1707
1708 (defun latex-indent (&optional arg)
1709 (with-syntax-table tex-latex-indent-syntax-table
1710 ;; TODO: Rather than ignore $, we should try to be more clever about it.
1711 (let ((indent
1712 (save-excursion
1713 (beginning-of-line)
1714 (latex-find-indent))))
1715 (if (< indent 0) (setq indent 0))
1716 (if (<= (current-column) (current-indentation))
1717 (indent-line-to indent)
1718 (save-excursion (indent-line-to indent))))))
1719
1720 (defun latex-find-indent (&optional virtual)
1721 "Find the proper indentation of text after point.
1722 VIRTUAL if non-nil indicates that we're only trying to find the indentation
1723 in order to determine the indentation of something else.
1724 There might be text before point."
1725 (save-excursion
1726 (skip-chars-forward " \t")
1727 (or
1728 ;; Trust the current indentation, if such info is applicable.
1729 (and virtual (>= (current-indentation) (current-column))
1730 (current-indentation))
1731 ;; Put leading close-paren where the matching open brace would be.
1732 (and (eq (latex-syntax-after) ?\))
1733 (ignore-errors
1734 (save-excursion
1735 (latex-skip-close-parens)
1736 (latex-backward-sexp-1)
1737 (latex-find-indent 'virtual))))
1738 ;; Default (maybe an argument)
1739 (let ((pos (point))
1740 (char (char-after))
1741 ;; Outdent \item if necessary.
1742 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
1743 up-list-pos)
1744 ;; Find the previous point which determines our current indentation.
1745 (condition-case err
1746 (progn
1747 (latex-backward-sexp-1)
1748 (while (> (current-column) (current-indentation))
1749 (latex-backward-sexp-1)))
1750 (scan-error
1751 (setq up-list-pos (nth 2 err))))
1752 (if (integerp up-list-pos)
1753 ;; Have to indent relative to the open-paren.
1754 (progn
1755 (goto-char up-list-pos)
1756 (if (and (not tex-indent-allhanging)
1757 (> pos (progn (latex-down-list)
1758 (forward-comment (point-max))
1759 (point))))
1760 ;; Align with the first element after the open-paren.
1761 (current-column)
1762 ;; We're the first element after a hanging brace.
1763 (goto-char up-list-pos)
1764 (+ indent tex-indent-basic (latex-find-indent 'virtual))))
1765 ;; We're now at the beginning of a line.
1766 (if (not (and (not virtual) (eq (char-after) ?\\)))
1767 ;; Nothing particular here: just keep the same indentation.
1768 (+ indent (current-column))
1769 ;; We're now looking at a macro call.
1770 (if (looking-at tex-indent-item-re)
1771 ;; Indenting relative to an item, have to re-add the outdenting.
1772 (+ indent (current-column) tex-indent-item)
1773 (let ((col (current-column)))
1774 (if (not (eq (char-syntax char) ?\())
1775 ;; If the first char was not an open-paren, there's
1776 ;; a risk that this is really not an argument to the
1777 ;; macro at all.
1778 (+ indent col)
1779 (forward-sexp 1)
1780 (if (< (line-end-position)
1781 (save-excursion (forward-comment (point-max))
1782 (point)))
1783 ;; we're indenting the first argument.
1784 (min (current-column) (+ tex-indent-arg col))
1785 (skip-syntax-forward " ")
1786 (current-column)))))))))))
1787
1788 (run-hooks 'tex-mode-load-hook)
1789
1790 (provide 'tex-mode)
1791
1792 ;;; tex-mode.el ends here