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