Add TeX super/sub script.
[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
GM
3;; Copyright (C) 1985, 1986, 1989, 1992, 1994, 1995, 1996, 1997, 1998
4;; 1999, 2001, 2002, 2003, 2004, 2005, 2006, 2007
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
15;; GNU Emacs is free software; you can redistribute it and/or modify
16;; it under the terms of the GNU General Public License as published by
5a9dffec 17;; the Free Software Foundation; either version 3, or (at your option)
869bff31 18;; any later version.
19
20;; GNU Emacs is distributed in the hope that it will be useful,
21;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23;; GNU General Public License for more details.
24
25;; You should have received a copy of the GNU General Public License
6da9bbd6 26;; along with GNU Emacs; see the file COPYING. If not, write to the
4fc5845f
LK
27;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
28;; Boston, MA 02110-1301, USA.
869bff31 29
55535639
PJ
30;;; Commentary:
31
e5167999
ER
32;;; Code:
33
bed1b0c8
RS
34;; Pacify the byte-compiler
35(eval-when-compile
36 (require 'compare-w)
ea590e1c 37 (require 'cl)
bed1b0c8
RS
38 (require 'skeleton))
39
2e261f76
JB
40(defvar font-lock-comment-face)
41(defvar font-lock-doc-face)
42
a0e9c22a 43(require 'shell)
2f3067de 44(require 'compile)
528415e7 45
d61140e8 46(defgroup tex-file nil
d1218e3e 47 "TeX files and directories."
d61140e8
RS
48 :prefix "tex-"
49 :group 'tex)
50
51(defgroup tex-run nil
d1218e3e 52 "Running external commands from TeX mode."
d61140e8
RS
53 :prefix "tex-"
54 :group 'tex)
55
56(defgroup tex-view nil
d1218e3e 57 "Viewing and printing TeX files."
d61140e8
RS
58 :prefix "tex-"
59 :group 'tex)
60
7e1dae73 61;;;###autoload
d61140e8
RS
62(defcustom tex-shell-file-name nil
63 "*If non-nil, the shell file name to run in the subshell used to run TeX."
64 :type '(choice (const :tag "None" nil)
65 string)
66 :group 'tex-run)
528415e7 67
7e1dae73 68;;;###autoload
d61140e8 69(defcustom tex-directory "."
f73741fc 70 "*Directory in which temporary files are written.
81c735c0 71You can make this `/tmp' if your TEXINPUTS has no relative directories in it
528415e7 72and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
d61140e8
RS
73`\\input' commands with relative directories."
74 :type 'directory
75 :group 'tex-file)
869bff31 76
725b7428 77;;;###autoload
d61140e8 78(defcustom tex-first-line-header-regexp nil
725b7428
RS
79 "Regexp for matching a first line which `tex-region' should include.
80If this is non-nil, it should be a regular expression string;
81if it matches the first line of the file,
d61140e8
RS
82`tex-region' always includes the first line in the TeX run."
83 :type '(choice (const :tag "None" nil)
84 regexp)
85 :group 'tex-file)
725b7428 86
f73741fc 87;;;###autoload
d61140e8 88(defcustom tex-main-file nil
f73741fc 89 "*The main TeX source file which includes this buffer's file.
be4a962d
RS
90The command `tex-file' runs TeX on the file specified by `tex-main-file'
91if the variable is non-nil."
d61140e8
RS
92 :type '(choice (const :tag "None" nil)
93 file)
94 :group 'tex-file)
f73741fc 95
7e1dae73 96;;;###autoload
d61140e8
RS
97(defcustom tex-offer-save t
98 "*If non-nil, ask about saving modified buffers before \\[tex-file] is run."
99 :type 'boolean
100 :group 'tex-file)
869bff31 101
7e1dae73 102;;;###autoload
d61140e8 103(defcustom tex-run-command "tex"
869bff31 104 "*Command used to run TeX subjob.
c3ce7bf4
RS
105TeX Mode sets `tex-command' to this string.
106See the documentation of that variable."
d61140e8
RS
107 :type 'string
108 :group 'tex-run)
869bff31 109
7e1dae73 110;;;###autoload
d61140e8 111(defcustom latex-run-command "latex"
869bff31 112 "*Command used to run LaTeX subjob.
c3ce7bf4
RS
113LaTeX Mode sets `tex-command' to this string.
114See the documentation of that variable."
d61140e8
RS
115 :type 'string
116 :group 'tex-run)
528415e7 117
bed1b0c8
RS
118;;;###autoload
119(defcustom slitex-run-command "slitex"
120 "*Command used to run SliTeX subjob.
c3ce7bf4
RS
121SliTeX Mode sets `tex-command' to this string.
122See the documentation of that variable."
bed1b0c8
RS
123 :type 'string
124 :group 'tex-run)
125
c3ce7bf4 126;;;###autoload
95a045bd 127(defcustom tex-start-options ""
9e0ad27a 128 "*TeX options to use when starting TeX.
95a045bd
SM
129These immediately precede the commands in `tex-start-commands'
130and the input file name, with no separating space and are not shell-quoted.
131If nil, TeX runs with no options. See the documentation of `tex-command'."
132 :type 'string
bed1b0c8 133 :group 'tex-run
bf247b6e 134 :version "22.1")
9e0ad27a
RS
135
136;;;###autoload
137(defcustom tex-start-commands "\\nonstopmode\\input"
138 "*TeX commands to use when starting TeX.
95a045bd
SM
139They are shell-quoted and precede the input file name, with a separating space.
140If nil, no commands are used. See the documentation of `tex-command'."
9e0ad27a
RS
141 :type '(radio (const :tag "Interactive \(nil\)" nil)
142 (const :tag "Nonstop \(\"\\nonstopmode\\input\"\)"
143 "\\nonstopmode\\input")
144 (string :tag "String at your choice"))
145 :group 'tex-run
bf247b6e 146 :version "22.1")
bed1b0c8 147
7afecb99 148(defvar latex-standard-block-names
dd459839
SM
149 '("abstract" "array" "center" "description"
150 "displaymath" "document" "enumerate" "eqnarray"
151 "eqnarray*" "equation" "figure" "figure*"
152 "flushleft" "flushright" "itemize" "letter"
153 "list" "minipage" "picture" "quotation"
154 "quote" "slide" "sloppypar" "tabbing"
155 "table" "table*" "tabular" "tabular*"
156 "thebibliography" "theindex*" "titlepage" "trivlist"
157 "verbatim" "verbatim*" "verse" "math")
528415e7
RS
158 "Standard LaTeX block names.")
159
7e1dae73 160;;;###autoload
d61140e8 161(defcustom latex-block-names nil
528415e7 162 "*User defined LaTeX block names.
7afecb99 163Combined with `latex-standard-block-names' for minibuffer completion."
d61140e8
RS
164 :type '(repeat string)
165 :group 'tex-run)
869bff31 166
7e1dae73 167;;;###autoload
d61140e8 168(defcustom tex-bibtex-command "bibtex"
528415e7 169 "*Command used by `tex-bibtex-file' to gather bibliographic data.
81c735c0 170If this string contains an asterisk (`*'), that is replaced by the file name;
d61140e8
RS
171otherwise, the file name, preceded by blank, is added at the end."
172 :type 'string
173 :group 'tex-run)
869bff31 174
7e1dae73 175;;;###autoload
d61140e8 176(defcustom tex-dvi-print-command "lpr -d"
528415e7 177 "*Command used by \\[tex-print] to print a .dvi file.
81c735c0 178If this string contains an asterisk (`*'), that is replaced by the file name;
d61140e8
RS
179otherwise, the file name, preceded by blank, is added at the end."
180 :type 'string
181 :group 'tex-view)
528415e7 182
7e1dae73 183;;;###autoload
d61140e8 184(defcustom tex-alt-dvi-print-command "lpr -d"
528415e7 185 "*Command used by \\[tex-print] with a prefix arg to print a .dvi file.
81c735c0
RS
186If this string contains an asterisk (`*'), that is replaced by the file name;
187otherwise, the file name, preceded by blank, is added at the end.
528415e7 188
81c735c0
RS
189If two printers are not enough of a choice, you can set the variable
190`tex-alt-dvi-print-command' to an expression that asks what you want;
528415e7
RS
191for example,
192
193 (setq tex-alt-dvi-print-command
194 '(format \"lpr -P%s\" (read-string \"Use printer: \")))
195
196would tell \\[tex-print] with a prefix argument to ask you which printer to
d61140e8
RS
197use."
198 :type '(choice (string :tag "Command")
199 (sexp :tag "Expression"))
200 :group 'tex-view)
869bff31 201
7e1dae73 202;;;###autoload
dd166d5f
SM
203(defcustom tex-dvi-view-command
204 '(cond
205 ((eq window-system 'x) "xdvi")
bf247b6e 206 ((eq window-system 'w32) "yap")
dd166d5f 207 (t "dvi2tty * | cat -s"))
81c735c0 208 "*Command used by \\[tex-view] to display a `.dvi' file.
746c30e2 209If it is a string, that specifies the command directly.
81c735c0 210If this string contains an asterisk (`*'), that is replaced by the file name;
746c30e2 211otherwise, the file name, preceded by a space, is added at the end.
528415e7 212
746c30e2
RS
213If the value is a form, it is evaluated to get the command to use."
214 :type '(choice (const nil) string sexp)
d61140e8 215 :group 'tex-view)
869bff31 216
7e1dae73 217;;;###autoload
d61140e8 218(defcustom tex-show-queue-command "lpq"
528415e7 219 "*Command used by \\[tex-show-print-queue] to show the print queue.
d61140e8
RS
220Should show the queue(s) that \\[tex-print] puts jobs on."
221 :type 'string
222 :group 'tex-view)
869bff31 223
7e1dae73 224;;;###autoload
9920303f 225(defcustom tex-default-mode 'latex-mode
869bff31 226 "*Mode to enter for a new file that might be either TeX or LaTeX.
227This variable is used when it can't be determined whether the file
228is plain TeX or LaTeX or what because the file contains no commands.
d61140e8
RS
229Normally set to either `plain-tex-mode' or `latex-mode'."
230 :type 'function
231 :group 'tex)
869bff31 232
7e1dae73 233;;;###autoload
d61140e8
RS
234(defcustom tex-open-quote "``"
235 "*String inserted by typing \\[tex-insert-quote] to open a quotation."
236 :type 'string
95a045bd 237 :options '("``" "\"<" "\"`" "<<" "«")
d61140e8 238 :group 'tex)
869bff31 239
7e1dae73 240;;;###autoload
d61140e8
RS
241(defcustom tex-close-quote "''"
242 "*String inserted by typing \\[tex-insert-quote] to close a quotation."
243 :type 'string
95a045bd 244 :options '("''" "\">" "\"'" ">>" "»")
d61140e8 245 :group 'tex)
869bff31 246
2b1567a5
RS
247(defcustom tex-fontify-script t
248 "If non-nil, fontify subscript and superscript strings."
249 :type 'boolean
250 :group 'tex)
251(put 'tex-fontify-script 'safe-local-variable 'booleanp)
252
0e1627a7 253(defcustom tex-font-script-display '(-0.2 0.2)
acdc4e59
GM
254 "How much to lower and raise subscript and superscript content.
255This is a list of two floats. The first is negative and
256specifies how much subscript is lowered, the second is positive
257and specifies how much superscript is raised. Heights are
258measured relative to that of the normal text."
2b1567a5 259 :group 'tex
0e1627a7
SM
260 :type '(list (float :tag "Subscript")
261 (float :tag "Superscript")))
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)
bdbd9606
SM
503 ;; If ARG ends up matching too much (if the {} don't match, f.ex)
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)
ad49d9d6
MB
722;; backward-compatibility alias
723(put 'tex-math-face 'face-alias 'tex-math)
724(defvar tex-math-face 'tex-math)
725
726(defface tex-verbatim
7afecb99
SM
727 ;; '((t :inherit font-lock-string-face))
728 '((t :family "courier"))
18a8c773
LK
729 "Face used to highlight TeX verbatim environments."
730 :group 'tex)
ad49d9d6
MB
731;; backward-compatibility alias
732(put 'tex-verbatim-face 'face-alias 'tex-verbatim)
733(defvar tex-verbatim-face 'tex-verbatim)
bdbd9606 734
3307a4fa
SM
735(defun tex-font-lock-verb (end)
736 "Place syntax-table properties on the \verb construct.
737END is the position of the first delimiter after \verb."
738 (unless (nth 8 (syntax-ppss end))
739 ;; Do nothing if the \verb construct is itself inside a comment or
740 ;; verbatim env.
741 (save-excursion
742 ;; Let's find the end and mark it.
743 ;; We used to do it inside tex-font-lock-syntactic-face-function, but
744 ;; this leads to funny effects when jumping to the end of the buffer,
745 ;; because font-lock applies font-lock-syntactic-keywords to the whole
746 ;; preceding text but font-lock-syntactic-face-function only to the
747 ;; actually displayed text.
748 (goto-char end)
749 (let ((char (char-before)))
750 (skip-chars-forward (string ?^ char)) ;; Use `end' ?
751 (when (eq (char-syntax (preceding-char)) ?/)
752 (put-text-property (1- (point)) (point) 'syntax-table '(1)))
753 (unless (eobp)
754 (put-text-property (point) (1+ (point)) 'syntax-table '(7))
755 ;; Cause the rest of the buffer to be re-fontified.
756 ;; (remove-text-properties (1+ (point)) (point-max) '(fontified))
757 )))
758 "\""))
759
bdbd9606
SM
760;; Use string syntax but math face for $...$.
761(defun tex-font-lock-syntactic-face-function (state)
7afecb99
SM
762 (let ((char (nth 3 state)))
763 (cond
764 ((not char) font-lock-comment-face)
765 ((eq char ?$) tex-math-face)
3307a4fa 766 (t tex-verbatim-face))))
bdbd9606 767
53c4fe47 768\f
869bff31 769(defun tex-define-common-keys (keymap)
81c735c0 770 "Define the keys that we want defined both in TeX mode and in the TeX shell."
869bff31 771 (define-key keymap "\C-c\C-k" 'tex-kill-job)
772 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
773 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
774 (define-key keymap "\C-c\C-p" 'tex-print)
775 (define-key keymap "\C-c\C-v" 'tex-view)
62a24cb5
RS
776
777 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
778
bdbd9606
SM
779 (define-key keymap [menu-bar tex tex-kill-job]
780 '(menu-item "Tex Kill" tex-kill-job :enable (tex-shell-running)))
cf6d6e8a 781 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
bdbd9606
SM
782 '(menu-item "Tex Recenter" tex-recenter-output-buffer
783 :enable (get-buffer "*tex-shell*")))
62a24cb5
RS
784 (define-key keymap [menu-bar tex tex-show-print-queue]
785 '("Show Print Queue" . tex-show-print-queue))
cf6d6e8a 786 (define-key keymap [menu-bar tex tex-alt-print]
bdbd9606
SM
787 '(menu-item "Tex Print (alt printer)" tex-alt-print
788 :enable (stringp tex-print-file)))
789 (define-key keymap [menu-bar tex tex-print]
790 '(menu-item "Tex Print" tex-print :enable (stringp tex-print-file)))
791 (define-key keymap [menu-bar tex tex-view]
792 '(menu-item "Tex View" tex-view :enable (stringp tex-print-file))))
793
794(defvar tex-mode-map
795 (let ((map (make-sparse-keymap)))
15ca8de7 796 (set-keymap-parent map text-mode-map)
bdbd9606
SM
797 (tex-define-common-keys map)
798 (define-key map "\"" 'tex-insert-quote)
799 (define-key map "(" 'skeleton-pair-insert-maybe)
800 (define-key map "{" 'skeleton-pair-insert-maybe)
801 (define-key map "[" 'skeleton-pair-insert-maybe)
802 (define-key map "$" 'skeleton-pair-insert-maybe)
803 (define-key map "\n" 'tex-terminate-paragraph)
804 (define-key map "\M-\r" 'latex-insert-item)
805 (define-key map "\C-c}" 'up-list)
806 (define-key map "\C-c{" 'tex-insert-braces)
807 (define-key map "\C-c\C-r" 'tex-region)
808 (define-key map "\C-c\C-b" 'tex-buffer)
809 (define-key map "\C-c\C-f" 'tex-file)
75035a80 810 (define-key map "\C-c\C-c" 'tex-compile)
bdbd9606 811 (define-key map "\C-c\C-i" 'tex-bibtex-file)
7afecb99
SM
812 (define-key map "\C-c\C-o" 'latex-insert-block)
813 (define-key map "\C-c\C-e" 'latex-close-block)
bdbd9606
SM
814 (define-key map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
815 (define-key map "\C-c\C-m" 'tex-feed-input)
816 (define-key map [(control return)] 'tex-feed-input)
817 (define-key map [menu-bar tex tex-bibtex-file]
818 '("BibTeX File" . tex-bibtex-file))
819 (define-key map [menu-bar tex tex-validate-region]
820 '(menu-item "Validate Region" tex-validate-region :enable mark-active))
821 (define-key map [menu-bar tex tex-validate-buffer]
822 '("Validate Buffer" . tex-validate-buffer))
823 (define-key map [menu-bar tex tex-region]
824 '(menu-item "TeX Region" tex-region :enable mark-active))
825 (define-key map [menu-bar tex tex-buffer]
826 '("TeX Buffer" . tex-buffer))
827 (define-key map [menu-bar tex tex-file] '("TeX File" . tex-file))
828 map)
15ca8de7
SM
829 "Keymap shared by TeX modes.")
830
831(defvar latex-mode-map
832 (let ((map (make-sparse-keymap)))
833 (set-keymap-parent map tex-mode-map)
a3d80d4a 834 (define-key map "\C-c\C-s" 'latex-split-block)
15ca8de7
SM
835 map)
836 "Keymap for `latex-mode'. See also `tex-mode-map'.")
837
838(defvar plain-tex-mode-map
839 (let ((map (make-sparse-keymap)))
840 (set-keymap-parent map tex-mode-map)
841 map)
842 "Keymap for `plain-tex-mode'. See also `tex-mode-map'.")
cf6d6e8a 843
d6709b80
SM
844(defvar tex-shell-map
845 (let ((m (make-sparse-keymap)))
846 (set-keymap-parent m shell-mode-map)
847 (tex-define-common-keys m)
848 m)
81c735c0 849 "Keymap for the TeX shell.
dca5ea48 850Inherits `shell-mode-map' with a few additions.")
869bff31 851
6da9bbd6
RS
852(defvar tex-face-alist
853 '((bold . "{\\bf ")
854 (italic . "{\\it ")
855 (bold-italic . "{\\bi ") ; hypothetical
856 (underline . "\\underline{")
857 (default . "{\\rm "))
858 "Alist of face and TeX font name for facemenu.")
859
860(defvar tex-latex-face-alist
861 `((italic . "{\\em ")
862 ,@tex-face-alist)
863 "Alist of face and LaTeX font name for facemenu.")
864
15ca8de7
SM
865;; This would be a lot simpler if we just used a regexp search,
866;; but then it would be too slow.
a3d80d4a 867(defun tex-guess-mode ()
d6709b80 868 (let ((mode tex-default-mode) slash comment)
869bff31 869 (save-excursion
870 (goto-char (point-min))
871 (while (and (setq slash (search-forward "\\" nil t))
872 (setq comment (let ((search-end (point)))
873 (save-excursion
874 (beginning-of-line)
875 (search-forward "%" search-end t))))))
bdbd9606
SM
876 (when (and slash (not comment))
877 (setq mode
878 (if (looking-at
879 (eval-when-compile
880 (concat
881 (regexp-opt '("documentstyle" "documentclass"
95a045bd 882 "begin" "subsection" "section"
bca7a08b 883 "part" "chapter" "newcommand"
29a47b89 884 "renewcommand" "RequirePackage") 'words)
bdbd9606 885 "\\|NeedsTeXFormat{LaTeX")))
dd166d5f
SM
886 (if (and (looking-at
887 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
888 ;; SliTeX is almost never used any more nowadays.
889 (tex-executable-exists-p slitex-run-command))
bdbd9606
SM
890 'slitex-mode
891 'latex-mode)
892 'plain-tex-mode))))
d6709b80 893 (funcall mode)))
e4c8c838 894
a3d80d4a
SM
895;; `tex-mode' plays two roles: it's the parent of several sub-modes
896;; but it's also the function that chooses between those submodes.
897;; To tell the difference between those two cases where the function
898;; might be called, we check `delay-mode-hooks'.
a3d80d4a
SM
899(define-derived-mode tex-mode text-mode "generic-TeX"
900 (tex-common-initialization))
bca7a08b
SM
901;; We now move the function and define it again. This gives a warning
902;; in the byte-compiler :-( but it's difficult to avoid because
903;; `define-derived-mode' will necessarily define the function once
904;; and we need to define it a second time for `autoload' to get the
905;; proper docstring.
906(defalias 'tex-mode-internal (symbol-function 'tex-mode))
907;;;###autoload
908(defun tex-mode ()
909 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
a3d80d4a
SM
910Tries to determine (by looking at the beginning of the file) whether
911this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
912`latex-mode', or `slitex-mode', respectively. If it cannot be determined,
913such as if there are no commands in the file, the value of `tex-default-mode'
914says which mode to use."
bca7a08b
SM
915 (interactive)
916 (if delay-mode-hooks
917 ;; We're called from one of the children already.
918 (tex-mode-internal)
919 (tex-guess-mode)))
a3d80d4a 920
1639cc2e
DK
921;; The following three autoloaded aliases appear to conflict with
922;; AUCTeX. However, even though AUCTeX uses the mixed case variants
923;; for all mode relevant variables and hooks, the invocation function
924;; and setting of `major-mode' themselves need to be lowercase for
925;; AUCTeX to provide a fully functional user-level replacement. So
926;; these aliases should remain as they are, in particular since AUCTeX
927;; users are likely to use them.
928
6503cec3 929;;;###autoload
31e1d920 930(defalias 'TeX-mode 'tex-mode)
6503cec3 931;;;###autoload
c3ce7bf4
RS
932(defalias 'plain-TeX-mode 'plain-tex-mode)
933;;;###autoload
31e1d920 934(defalias 'LaTeX-mode 'latex-mode)
869bff31 935
7229064d 936;;;###autoload
a3d80d4a 937(define-derived-mode plain-tex-mode tex-mode "TeX"
869bff31 938 "Major mode for editing files of input for plain TeX.
939Makes $ and } display the characters they match.
940Makes \" insert `` when it seems to be the beginning of a quotation,
941and '' when it appears to be the end; it inserts \" only after a \\.
942
943Use \\[tex-region] to run TeX on the current region, plus a \"header\"
944copied from the top of the file (containing macro definitions, etc.),
945running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
946\\[tex-file] saves the buffer and then processes the file.
947\\[tex-print] prints the .dvi file made by any of these.
948\\[tex-view] previews the .dvi file made by any of these.
949\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
950
e6b0b773 951Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 952mismatched $'s or braces.
953
954Special commands:
15ca8de7 955\\{plain-tex-mode-map}
869bff31 956
957Mode variables:
958tex-run-command
959 Command string used by \\[tex-region] or \\[tex-buffer].
960tex-directory
961 Directory in which to create temporary files for TeX jobs
962 run by \\[tex-region] or \\[tex-buffer].
963tex-dvi-print-command
964 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
965tex-alt-dvi-print-command
966 Alternative command string used by \\[tex-print] (when given a prefix
967 argument) to print a .dvi file.
869bff31 968tex-dvi-view-command
969 Command string used by \\[tex-view] to preview a .dvi file.
970tex-show-queue-command
971 Command string used by \\[tex-show-print-queue] to show the print
972 queue that \\[tex-print] put your job on.
973
81c735c0
RS
974Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
975`tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
976special subshell is initiated, the hook `tex-shell-hook' is run."
a3d80d4a
SM
977 (set (make-local-variable 'tex-command) tex-run-command)
978 (set (make-local-variable 'tex-start-of-header) "%\\*\\*start of header")
979 (set (make-local-variable 'tex-end-of-header) "%\\*\\*end of header")
980 (set (make-local-variable 'tex-trailer) "\\bye\n"))
869bff31 981
7229064d 982;;;###autoload
a3d80d4a 983(define-derived-mode latex-mode tex-mode "LaTeX"
869bff31 984 "Major mode for editing files of input for LaTeX.
985Makes $ and } display the characters they match.
986Makes \" insert `` when it seems to be the beginning of a quotation,
987and '' when it appears to be the end; it inserts \" only after a \\.
988
989Use \\[tex-region] to run LaTeX on the current region, plus the preamble
990copied from the top of the file (containing \\documentstyle, etc.),
991running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
992\\[tex-file] saves the buffer and then processes the file.
993\\[tex-print] prints the .dvi file made by any of these.
994\\[tex-view] previews the .dvi file made by any of these.
995\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
996
e6b0b773 997Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 998mismatched $'s or braces.
999
1000Special commands:
15ca8de7 1001\\{latex-mode-map}
869bff31 1002
1003Mode variables:
1004latex-run-command
1005 Command string used by \\[tex-region] or \\[tex-buffer].
1006tex-directory
1007 Directory in which to create temporary files for LaTeX jobs
1008 run by \\[tex-region] or \\[tex-buffer].
1009tex-dvi-print-command
1010 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
1011tex-alt-dvi-print-command
1012 Alternative command string used by \\[tex-print] (when given a prefix
1013 argument) to print a .dvi file.
869bff31 1014tex-dvi-view-command
1015 Command string used by \\[tex-view] to preview a .dvi file.
1016tex-show-queue-command
1017 Command string used by \\[tex-show-print-queue] to show the print
1018 queue that \\[tex-print] put your job on.
1019
bed1b0c8 1020Entering Latex mode runs the hook `text-mode-hook', then
81c735c0
RS
1021`tex-mode-hook', and finally `latex-mode-hook'. When the special
1022subshell is initiated, `tex-shell-hook' is run."
a3d80d4a
SM
1023 (set (make-local-variable 'tex-command) latex-run-command)
1024 (set (make-local-variable 'tex-start-of-header)
1025 "\\\\document\\(style\\|class\\)")
1026 (set (make-local-variable 'tex-end-of-header) "\\\\begin\\s-*{document}")
d9cbee57 1027 (set (make-local-variable 'tex-trailer) "\\end{document}\n")
ab2c9f54
RS
1028 ;; A line containing just $$ is treated as a paragraph separator.
1029 ;; A line starting with $$ starts a paragraph,
1030 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80 1031 (setq paragraph-start
a3d80d4a 1032 (concat "[ \t]*\\(\\$\\$\\|"
d6709b80
SM
1033 "\\\\[][]\\|"
1034 "\\\\" (regexp-opt (append
1035 (mapcar 'car latex-section-alist)
1036 '("begin" "label" "end"
1037 "item" "bibitem" "newline" "noindent"
1038 "newpage" "footnote" "marginpar"
1039 "parbox" "caption")) t)
1040 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
dd459839 1041 "\\>\\)"))
d6709b80 1042 (setq paragraph-separate
dd459839 1043 (concat "[\f%]\\|[ \t]*\\($\\|"
d6709b80
SM
1044 "\\\\[][]\\|"
1045 "\\\\" (regexp-opt (append
1046 (mapcar 'car latex-section-alist)
1047 '("begin" "label" "end" )) t)
1048 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
1049 "noindent" "newpage" "footnote"
1050 "marginpar" "parbox" "caption"))
dd459839
SM
1051 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
1052 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
d6709b80
SM
1053 (set (make-local-variable 'imenu-create-index-function)
1054 'latex-imenu-create-index)
1055 (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
95a045bd 1056 (add-hook 'fill-nobreak-predicate 'latex-fill-nobreak-predicate nil t)
ea590e1c 1057 (set (make-local-variable 'indent-line-function) 'latex-indent)
dd459839 1058 (set (make-local-variable 'fill-indent-according-to-mode) t)
d6709b80
SM
1059 (set (make-local-variable 'outline-regexp) latex-outline-regexp)
1060 (set (make-local-variable 'outline-level) 'latex-outline-level)
53c4fe47 1061 (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
a3d80d4a 1062 (set (make-local-variable 'skeleton-end-hook) nil))
869bff31 1063
bd2f2323 1064;;;###autoload
d6709b80 1065(define-derived-mode slitex-mode latex-mode "SliTeX"
869bff31 1066 "Major mode for editing files of input for SliTeX.
1067Makes $ and } display the characters they match.
1068Makes \" insert `` when it seems to be the beginning of a quotation,
1069and '' when it appears to be the end; it inserts \" only after a \\.
1070
1071Use \\[tex-region] to run SliTeX on the current region, plus the preamble
1072copied from the top of the file (containing \\documentstyle, etc.),
1073running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
1074\\[tex-file] saves the buffer and then processes the file.
1075\\[tex-print] prints the .dvi file made by any of these.
1076\\[tex-view] previews the .dvi file made by any of these.
1077\\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1078
e6b0b773 1079Use \\[tex-validate-buffer] to check buffer for paragraphs containing
869bff31 1080mismatched $'s or braces.
1081
1082Special commands:
15ca8de7 1083\\{slitex-mode-map}
869bff31 1084
1085Mode variables:
1086slitex-run-command
1087 Command string used by \\[tex-region] or \\[tex-buffer].
1088tex-directory
1089 Directory in which to create temporary files for SliTeX jobs
1090 run by \\[tex-region] or \\[tex-buffer].
1091tex-dvi-print-command
1092 Command string used by \\[tex-print] to print a .dvi file.
528415e7
RS
1093tex-alt-dvi-print-command
1094 Alternative command string used by \\[tex-print] (when given a prefix
1095 argument) to print a .dvi file.
869bff31 1096tex-dvi-view-command
1097 Command string used by \\[tex-view] to preview a .dvi file.
1098tex-show-queue-command
1099 Command string used by \\[tex-show-print-queue] to show the print
1100 queue that \\[tex-print] put your job on.
1101
81c735c0
RS
1102Entering SliTeX mode runs the hook `text-mode-hook', then the hook
1103`tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
1104`slitex-mode-hook'. When the special subshell is initiated, the hook
1105`tex-shell-hook' is run."
869bff31 1106 (setq tex-command slitex-run-command)
d6709b80 1107 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
869bff31 1108
1109(defun tex-common-initialization ()
822eddf4 1110 ;; Regexp isearch should accept newline and formfeed as whitespace.
d6709b80 1111 (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
64db2461 1112 ;; A line containing just $$ is treated as a paragraph separator.
d6709b80
SM
1113 (set (make-local-variable 'paragraph-start)
1114 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
ab2c9f54
RS
1115 ;; A line starting with $$ starts a paragraph,
1116 ;; but does not separate paragraphs if it has more stuff on it.
d6709b80
SM
1117 (set (make-local-variable 'paragraph-separate)
1118 "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
1119 (set (make-local-variable 'comment-start) "%")
1120 (set (make-local-variable 'comment-add) 1)
1121 (set (make-local-variable 'comment-start-skip)
5ae0d697 1122 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
d6709b80
SM
1123 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1124 (set (make-local-variable 'compare-windows-whitespace)
1125 'tex-categorize-whitespace)
1126 (set (make-local-variable 'facemenu-add-face-function)
1127 (lambda (face end)
6ecedb40
SM
1128 (or (cdr (assq face tex-face-alist))
1129 (error "Face %s not configured for %s mode" face mode-name))))
d6709b80
SM
1130 (set (make-local-variable 'facemenu-end-add-face) "}")
1131 (set (make-local-variable 'facemenu-remove-face-function) t)
1132 (set (make-local-variable 'font-lock-defaults)
7afecb99
SM
1133 '((tex-font-lock-keywords tex-font-lock-keywords-1
1134 tex-font-lock-keywords-2 tex-font-lock-keywords-3)
d6709b80
SM
1135 nil nil ((?$ . "\"")) nil
1136 ;; Who ever uses that anyway ???
bdbd9606
SM
1137 (font-lock-mark-block-function . mark-paragraph)
1138 (font-lock-syntactic-face-function
7afecb99
SM
1139 . tex-font-lock-syntactic-face-function)
1140 (font-lock-unfontify-region-function
1141 . tex-font-lock-unfontify-region)
1142 (font-lock-syntactic-keywords
1143 . tex-font-lock-syntactic-keywords)
1144 (parse-sexp-lookup-properties . t)))
95a045bd
SM
1145 ;; TABs in verbatim environments don't do what you think.
1146 (set (make-local-variable 'indent-tabs-mode) nil)
7afecb99 1147 ;; Other vars that should be buffer-local.
869bff31 1148 (make-local-variable 'tex-command)
1149 (make-local-variable 'tex-start-of-header)
1150 (make-local-variable 'tex-end-of-header)
1151 (make-local-variable 'tex-trailer))
1152
869bff31 1153(defun tex-categorize-whitespace (backward-limit)
1154 ;; compare-windows-whitespace is set to this.
1155 ;; This is basically a finite-state machine.
1156 ;; Returns a symbol telling how TeX would treat
1157 ;; the whitespace we are looking at: null, space, or par.
1158 (let ((category 'null)
1159 (not-finished t))
1160 (skip-chars-backward " \t\n\f" backward-limit)
1161 (while not-finished
1162 (cond ((looking-at "[ \t]+")
1163 (goto-char (match-end 0))
2be5fefb 1164 (if (eq category 'null)
869bff31 1165 (setq category 'space)))
1166 ((looking-at "\n")
2be5fefb 1167 (cond ((eq category 'newline)
869bff31 1168 (setq category 'par)
1169 (setq not-finished nil))
1170 (t
1171 (setq category 'newline) ;a strictly internal state
1172 (goto-char (match-end 0)))))
1173 ((looking-at "\f+")
1174 (setq category 'par)
1175 (setq not-finished nil))
1176 (t
1177 (setq not-finished nil))))
1178 (skip-chars-forward " \t\n\f")
2be5fefb 1179 (if (eq category 'newline)
869bff31 1180 'space ;TeX doesn't distinguish
1181 category)))
1182
1183(defun tex-insert-quote (arg)
1184 "Insert the appropriate quote marks for TeX.
08348502
RS
1185Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
1186\(normally '') depending on the context. With prefix argument, always
869bff31 1187inserts \" characters."
528415e7 1188 (interactive "*P")
95a045bd 1189 (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
014e29b9 1190 (eq (get-text-property (point) 'face) 'tex-verbatim)
95a045bd
SM
1191 (save-excursion
1192 (backward-char (length tex-open-quote))
1193 (when (or (looking-at (regexp-quote tex-open-quote))
1194 (looking-at (regexp-quote tex-close-quote)))
1195 (delete-char (length tex-open-quote))
1196 t)))
869bff31 1197 (self-insert-command (prefix-numeric-value arg))
d1218e3e 1198 (insert (if (memq (char-syntax (preceding-char)) '(?\( ?> ?\s))
95a045bd 1199 tex-open-quote tex-close-quote))))
869bff31 1200
e6b0b773
MR
1201(defun tex-validate-buffer ()
1202 "Check current buffer for paragraphs containing mismatched braces or $s.
bbd93e41 1203Their positions are recorded in the buffer `*Occur*'.
e6b0b773
MR
1204To find a particular invalidity from `*Occur*', switch to that buffer
1205and type C-c C-c or click with mouse-2
1206on the line for the invalidity you want to see."
869bff31 1207 (interactive)
bbd93e41
RS
1208 (let ((buffer (current-buffer))
1209 (prevpos (point-min))
e6b0b773
MR
1210 (linenum nil)
1211 (num-matches 0))
bbd93e41
RS
1212 (with-output-to-temp-buffer "*Occur*"
1213 (princ "Mismatches:\n")
a3d80d4a 1214 (with-current-buffer standard-output
bbd93e41 1215 (occur-mode)
52ab062c
CW
1216 ;; This won't actually work...Really, this whole thing should
1217 ;; be rewritten instead of being a hack on top of occur.
1218 (setq occur-revert-arguments (list nil 0 (list buffer))))
bbd93e41
RS
1219 (save-excursion
1220 (goto-char (point-max))
0a4daff5
GM
1221 ;; Do a little shimmy to place point at the end of the last
1222 ;; "real" paragraph. Need to avoid validating across an \end,
1223 ;; because that blows up latex-forward-sexp.
1224 (backward-paragraph)
1225 (forward-paragraph)
1226 (while (not (bobp))
bbd93e41 1227 ;; Scan the previous paragraph for invalidities.
0a4daff5
GM
1228 (backward-paragraph)
1229 (save-excursion
1230 (or (tex-validate-region (point) (save-excursion
1231 (forward-paragraph)
1232 (point)))
1233 (let ((end (line-beginning-position 2))
bbd93e41
RS
1234 start tem)
1235 (beginning-of-line)
1236 (setq start (point))
1237 ;; Keep track of line number as we scan,
1238 ;; in a cumulative fashion.
1239 (if linenum
0a4daff5
GM
1240 (setq linenum (- linenum
1241 (count-lines prevpos (point))))
bbd93e41
RS
1242 (setq linenum (1+ (count-lines 1 start))))
1243 (setq prevpos (point))
bed1b0c8 1244 ;; Mention this mismatch in *Occur*.
bbd93e41 1245 ;; Since we scan from end of buffer to beginning,
e6b0b773 1246 ;; add each mismatch at the beginning of *Occur*.
bbd93e41
RS
1247 (save-excursion
1248 (setq tem (point-marker))
1249 (set-buffer standard-output)
1250 (goto-char (point-min))
1251 ;; Skip "Mismatches:" header line.
1252 (forward-line 1)
e6b0b773 1253 (setq num-matches (1+ num-matches))
bbd93e41 1254 (insert-buffer-substring buffer start end)
e6b0b773
MR
1255 (let (text-beg (text-end (point-marker)))
1256 (forward-char (- start end))
1257 (setq text-beg (point-marker))
1258 (insert (format "%3d: " linenum))
a865de85
EZ
1259 (add-text-properties
1260 text-beg (- text-end 1)
1261 '(mouse-face highlight
0a4daff5
GM
1262 help-echo
1263 "mouse-2: go to this invalidity"))
1598a961 1264 (put-text-property text-beg (- text-end 1)
0a4daff5 1265 'occur-target tem))))))))
bdbd9606 1266 (with-current-buffer standard-output
003274a0
JPW
1267 (let ((no-matches (zerop num-matches)))
1268 (if no-matches
1269 (insert "None!\n"))
1270 (if (interactive-p)
f04232c3
JPW
1271 (message (cond (no-matches "No mismatches found")
1272 ((= num-matches 1) "1 mismatch found")
1273 (t "%d mismatches found"))
1274 num-matches)))))))
869bff31 1275
1276(defun tex-validate-region (start end)
1277 "Check for mismatched braces or $'s in region.
1278Returns t if no mismatches. Returns nil and moves point to suspect
1279area if a mismatch is found."
1280 (interactive "r")
1281 (let ((failure-point nil) (max-possible-sexps (- end start)))
1282 (save-excursion
1283 (condition-case ()
1284 (save-restriction
1285 (narrow-to-region start end)
2ed2806c 1286 ;; First check that the open and close parens balance in numbers.
869bff31 1287 (goto-char start)
0a4daff5
GM
1288 (while (and (not (eobp))
1289 (<= 0 (setq max-possible-sexps
1290 (1- max-possible-sexps))))
2ed2806c
KH
1291 (forward-sexp 1))
1292 ;; Now check that like matches like.
1293 (goto-char start)
35dccc62
SM
1294 (while (re-search-forward "\\s(" nil t)
1295 (save-excursion
1296 (let ((pos (match-beginning 0)))
1297 (goto-char pos)
09b33024 1298 (skip-chars-backward "\\\\") ; escaped parens
2ed2806c 1299 (forward-sexp 1)
35dccc62
SM
1300 (or (eq (preceding-char) (cdr (syntax-after pos)))
1301 (eq (char-after pos) (cdr (syntax-after (1- (point)))))
1302 (error "Mismatched parentheses"))))))
869bff31 1303 (error
bed1b0c8
RS
1304 (skip-syntax-forward " .>")
1305 (setq failure-point (point)))))
bdbd9606
SM
1306 (if failure-point (goto-char failure-point))
1307 (not failure-point)))
869bff31 1308
1309(defun tex-terminate-paragraph (inhibit-validation)
1310 "Insert two newlines, breaking a paragraph for TeX.
81c735c0 1311Check for mismatched braces or $s in paragraph being terminated.
869bff31 1312A prefix arg inhibits the checking."
528415e7 1313 (interactive "*P")
869bff31 1314 (or inhibit-validation
3cfff67b
GM
1315 (save-excursion
1316 ;; For the purposes of this, a "paragraph" is a block of text
1317 ;; wherein all the brackets etc are expected to be balanced. It
1318 ;; may start after a blank line (ie a "proper" paragraph), or
1319 ;; a begin{} or end{} block, etc.
1320 (tex-validate-region
1321 (save-excursion
1322 (backward-paragraph)
1323 (point))
1324 (point)))
1325 (message "Paragraph being closed appears to contain a mismatch"))
1326 (insert "\n\n"))
869bff31 1327
7afecb99 1328(define-skeleton tex-insert-braces
869bff31 1329 "Make a pair of braces and be poised to type inside of them."
7afecb99
SM
1330 nil
1331 ?\{ _ ?})
869bff31 1332
9bd4f69c
RS
1333;; This function is used as the value of fill-nobreak-predicate
1334;; in LaTeX mode. Its job is to prevent line-breaking inside
1335;; of a \verb construct.
1336(defun latex-fill-nobreak-predicate ()
7afecb99
SM
1337 (save-excursion
1338 (skip-chars-backward " ")
1339 ;; Don't break after \ since `\ ' has special meaning.
1340 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
1341 (let ((opoint (point))
1342 inside)
1343 (beginning-of-line)
1344 (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
1345 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
1346 (setq inside t)))
1347 inside))))
9bd4f69c 1348
53c4fe47
SM
1349(defvar latex-block-default "enumerate")
1350
8084f5d8 1351(defvar latex-block-args-alist
dd166d5f
SM
1352 '(("array" nil ?\{ (skeleton-read "Format: ") ?\})
1353 ("tabular" nil ?\{ (skeleton-read "Format: ") ?\})
1354 ("minipage" nil ?\{ (skeleton-read "Size: ") ?\})
1355 ("picture" nil ?\( (skeleton-read "SizeX,SizeY: ") ?\))
1356 ;; FIXME: This is right for Prosper, but not for seminar.
1357 ;; ("slide" nil ?\{ (skeleton-read "Title: ") ?\})
1358 )
8084f5d8
SM
1359 "Skeleton element to use for arguments to particular environments.
1360Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1361the name of the environment and SKEL-ELEM is an element to use in
1362a skeleton (see `skeleton-insert').")
1363
1364(defvar latex-block-body-alist
1365 '(("enumerate" nil '(latex-insert-item) > _)
1366 ("itemize" nil '(latex-insert-item) > _)
dd166d5f
SM
1367 ("table" nil "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1368 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))
1369 \n _)
1370 ("figure" nil > _ \n "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1371 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))))
8084f5d8
SM
1372 "Skeleton element to use for the body of particular environments.
1373Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1374the name of the environment and SKEL-ELEM is an element to use in
1375a skeleton (see `skeleton-insert').")
1376
15ca8de7 1377;; Like tex-insert-braces, but for LaTeX.
7afecb99
SM
1378(defalias 'tex-latex-block 'latex-insert-block)
1379(define-skeleton latex-insert-block
8a591d52 1380 "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
869bff31 1381Puts point on a blank line between them."
53c4fe47
SM
1382 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1383 latex-block-default)
95a045bd 1384 (append latex-block-names
7afecb99 1385 latex-standard-block-names)
53c4fe47
SM
1386 nil nil nil nil latex-block-default)))
1387 (setq latex-block-default choice)
7afecb99 1388 (unless (or (member choice latex-standard-block-names)
53c4fe47
SM
1389 (member choice latex-block-names))
1390 ;; Remember new block names for later completion.
1391 (push choice latex-block-names))
1392 choice)
95a045bd 1393 \n "\\begin{" str "}"
8084f5d8 1394 (cdr (assoc str latex-block-args-alist))
dd166d5f
SM
1395 > \n (or (cdr (assoc str latex-block-body-alist)) '(nil > _))
1396 (unless (bolp) '\n)
95a045bd 1397 "\\end{" str "}" > \n)
53c4fe47 1398
ea590e1c
SM
1399(define-skeleton latex-insert-item
1400 "Insert a \item macro."
1401 nil
15ca8de7 1402 \n "\\item " >)
ea590e1c 1403
53c4fe47
SM
1404\f
1405;;;;
1406;;;; LaTeX syntax navigation
1407;;;;
869bff31 1408
5e56fb53
SM
1409(defmacro tex-search-noncomment (&rest body)
1410 "Execute BODY as long as it return non-nil and point is in a comment.
1411Return the value returned by the last execution of BODY."
1412 (declare (debug t))
1413 (let ((res-sym (make-symbol "result")))
1414 `(let (,res-sym)
1415 (while
1416 (and (setq ,res-sym (progn ,@body))
1417 (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
1418 ,res-sym)))
1419
869bff31 1420(defun tex-last-unended-begin ()
81c735c0 1421 "Leave point at the beginning of the last `\\begin{...}' that is unended."
95a045bd 1422 (condition-case nil
5e56fb53
SM
1423 (while (and (tex-search-noncomment
1424 (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
95a045bd
SM
1425 (looking-at "\\\\end"))
1426 (tex-last-unended-begin))
1427 (search-failed (error "Couldn't find unended \\begin"))))
869bff31 1428
53c4fe47 1429(defun tex-next-unmatched-end ()
0a4daff5 1430 "Leave point at the end of the next `\\end' that is unmatched."
5e56fb53
SM
1431 (while (and (tex-search-noncomment
1432 (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
ea590e1c
SM
1433 (save-excursion (goto-char (match-beginning 0))
1434 (looking-at "\\\\begin")))
53c4fe47
SM
1435 (tex-next-unmatched-end)))
1436
09b33024
GM
1437(defun tex-next-unmatched-eparen (otype)
1438 "Leave point after the next unmatched escaped closing parenthesis.
2fb34c68 1439The string OTYPE is an opening parenthesis type: `(', `{', or `['."
09b33024
GM
1440 (condition-case nil
1441 (let ((ctype (char-to-string (cdr (aref (syntax-table)
1442 (string-to-char otype))))))
1443 (while (and (tex-search-noncomment
1444 (re-search-forward (format "\\\\[%s%s]" ctype otype)))
1445 (save-excursion
1446 (goto-char (match-beginning 0))
1447 (looking-at (format "\\\\%s" (regexp-quote otype)))))
1448 (tex-next-unmatched-eparen otype)))
1449 (wrong-type-argument (error "Unknown opening parenthesis type: %s" otype))
1450 (search-failed (error "Couldn't find closing escaped paren"))))
1451
2fb34c68
GM
1452(defun tex-last-unended-eparen (ctype)
1453 "Leave point at the start of the last unended escaped opening parenthesis.
1454The string CTYPE is a closing parenthesis type: `)', `}', or `]'."
1455 (condition-case nil
1456 (let ((otype (char-to-string (cdr (aref (syntax-table)
1457 (string-to-char ctype))))))
1458 (while (and (tex-search-noncomment
1459 (re-search-backward (format "\\\\[%s%s]" ctype otype)))
1460 (looking-at (format "\\\\%s" (regexp-quote ctype))))
1461 (tex-last-unended-eparen ctype)))
1462 (wrong-type-argument (error "Unknown opening parenthesis type: %s" ctype))
1463 (search-failed (error "Couldn't find unended escaped paren"))))
1464
6a900cf1
ER
1465(defun tex-goto-last-unclosed-latex-block ()
1466 "Move point to the last unclosed \\begin{...}.
1467Mark is left at original location."
1468 (interactive)
1469 (let ((spot))
1470 (save-excursion
95a045bd 1471 (tex-last-unended-begin)
6a900cf1
ER
1472 (setq spot (point)))
1473 (push-mark)
1474 (goto-char spot)))
1475
2fb34c68
GM
1476;; Don't think this one actually _needs_ (for the purposes of
1477;; tex-mode) to handle escaped parens.
53c4fe47 1478(defun latex-backward-sexp-1 ()
2fb34c68 1479 "Like (backward-sexp 1) but aware of multi-char elements and escaped parens."
53c4fe47
SM
1480 (let ((pos (point))
1481 (forward-sexp-function))
1482 (backward-sexp 1)
2fb34c68
GM
1483 (cond ((looking-at "\\\\\\(begin\\>\\|[[({]\\)")
1484 (signal 'scan-error
1485 (list "Containing expression ends prematurely"
1486 (point) (prog1 (point) (goto-char pos)))))
1487 ((looking-at "\\\\\\([])}]\\)")
1488 (tex-last-unended-eparen (match-string 1)))
1489 ((eq (char-after) ?{)
1490 (let ((newpos (point)))
1491 (when (ignore-errors (backward-sexp 1) t)
1492 (if (or (looking-at "\\\\end\\>")
1493 ;; In case the \\ ends a verbatim section.
1494 (and (looking-at "end\\>") (eq (char-before) ?\\)))
1495 (tex-last-unended-begin)
1496 (goto-char newpos))))))))
53c4fe47 1497
09b33024
GM
1498;; Note this does not handle things like mismatched brackets inside
1499;; begin/end blocks.
2fb34c68
GM
1500;; Needs to handle escaped parens for tex-validate-*.
1501;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2007-09/msg00038.html
53c4fe47 1502(defun latex-forward-sexp-1 ()
09b33024 1503 "Like (forward-sexp 1) but aware of multi-char elements and escaped parens."
53c4fe47
SM
1504 (let ((pos (point))
1505 (forward-sexp-function))
1506 (forward-sexp 1)
1507 (let ((newpos (point)))
1508 (skip-syntax-backward "/w")
1509 (cond
1510 ((looking-at "\\\\end\\>")
1511 (signal 'scan-error
1512 (list "Containing expression ends prematurely"
1513 (point)
1514 (prog1
1515 (progn (ignore-errors (forward-sexp 2)) (point))
1516 (goto-char pos)))))
1517 ((looking-at "\\\\begin\\>")
1518 (goto-char (match-end 0))
1519 (tex-next-unmatched-end))
2fb34c68
GM
1520 ;; A better way to handle this, \( .. \) etc, is probably to
1521 ;; temporarily change the syntax of the \ in \( to punctuation.
09b33024
GM
1522 ((looking-back "\\\\[])}]")
1523 (signal 'scan-error
1524 (list "Containing expression ends prematurely"
1525 (- (point) 2) (prog1 (point)
1526 (goto-char pos)))))
1527 ((looking-back "\\\\\\([({[]\\)")
1528 (tex-next-unmatched-eparen (match-string 1)))
53c4fe47
SM
1529 (t (goto-char newpos))))))
1530
1531(defun latex-forward-sexp (&optional arg)
09b33024 1532 "Like `forward-sexp' but aware of multi-char elements and escaped parens."
53c4fe47
SM
1533 (interactive "P")
1534 (unless arg (setq arg 1))
1535 (let ((pos (point)))
1536 (condition-case err
1537 (while (/= arg 0)
1538 (setq arg
1539 (if (> arg 0)
1540 (progn (latex-forward-sexp-1) (1- arg))
1541 (progn (latex-backward-sexp-1) (1+ arg)))))
1542 (scan-error
1543 (goto-char pos)
1544 (signal (car err) (cdr err))))))
1545
ea590e1c
SM
1546(defun latex-syntax-after ()
1547 "Like (char-syntax (char-after)) but aware of multi-char elements."
15ca8de7 1548 (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
ea590e1c
SM
1549
1550(defun latex-skip-close-parens ()
1551 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1552 (let ((forward-sexp-function nil))
1553 (while (progn (skip-syntax-forward " )")
1554 (looking-at "\\\\end\\>"))
1555 (forward-sexp 2))))
1556
1557(defun latex-down-list ()
1558 "Like (down-list 1) but aware of multi-char elements."
1559 (forward-comment (point-max))
1560 (let ((forward-sexp-function nil))
1561 (if (not (looking-at "\\\\begin\\>"))
1562 (down-list 1)
1563 (forward-sexp 1)
1564 ;; Skip arguments.
7afecb99
SM
1565 (while (looking-at "[ \t]*[[{(]")
1566 (with-syntax-table tex-mode-syntax-table
1567 (forward-sexp))))))
ea590e1c 1568
7afecb99
SM
1569(defalias 'tex-close-latex-block 'latex-close-block)
1570(define-skeleton latex-close-block
1571 "Create an \\end{...} to match the last unclosed \\begin{...}."
1572 (save-excursion
1573 (tex-last-unended-begin)
1574 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1575 (match-string 1)))
1576 \n "\\end" str > \n)
1577
1578(define-skeleton latex-split-block
1579 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1580 (save-excursion
1581 (tex-last-unended-begin)
1582 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1583 (prog1 (match-string 1)
1584 (goto-char (match-end 1))
1585 (setq v1 (buffer-substring (point)
1586 (progn
1587 (while (looking-at "[ \t]*[[{]")
1588 (forward-sexp 1))
1589 (point)))))))
1590 \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
15ca8de7
SM
1591
1592(defconst tex-discount-args-cmds
1593 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1594 "documentclass" "usepackage" "label")
1595 "TeX commands whose arguments should not be counted as text.")
1596
1597(defun tex-count-words (begin end)
1598 "Count the number of words in the buffer."
1599 (interactive
1600 (if (and transient-mark-mode mark-active)
1601 (list (region-beginning) (region-end))
1602 (list (point-min) (point-max))))
1603 ;; TODO: skip comments and math and maybe some environments.
1604 (save-excursion
1605 (goto-char begin)
1606 (let ((count 0))
1607 (while (and (< (point) end) (re-search-forward "\\<" end t))
1608 (if (not (eq (char-syntax (preceding-char)) ?/))
1609 (progn
1610 ;; Don't count single-char words.
1611 (unless (looking-at ".\\>") (incf count))
1612 (forward-char 1))
1613 (let ((cmd
1614 (buffer-substring-no-properties
1615 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1616 (forward-char 1))
1617 (point)))))
1618 (when (member cmd tex-discount-args-cmds)
1619 (skip-chars-forward "*")
1620 (forward-comment (point-max))
1621 (when (looking-at "\\[")
1622 (forward-sexp 1)
1623 (forward-comment (point-max)))
1624 (if (not (looking-at "{"))
1625 (forward-char 1)
1626 (forward-sexp 1))))))
1627 (message "%s words" count))))
b781e739
SS
1628
1629
869bff31 1630\f
1631;;; Invoking TeX in an inferior shell.
1632
15ca8de7
SM
1633;; Why use a shell instead of running TeX directly? Because if TeX
1634;; gets stuck, the user can switch to the shell window and type at it.
869bff31 1635
15ca8de7 1636;; The utility functions:
869bff31 1637
bdbd9606 1638(define-derived-mode tex-shell shell-mode "TeX-Shell"
3f2c97ea
SM
1639 (set (make-local-variable 'compilation-parse-errors-function)
1640 'tex-compilation-parse-errors)
bdbd9606
SM
1641 (compilation-shell-minor-mode t))
1642
d974af30 1643;;;###autoload
869bff31 1644(defun tex-start-shell ()
d6709b80
SM
1645 (with-current-buffer
1646 (make-comint
1647 "tex-shell"
07c16ec4 1648 (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
4042dc25 1649 nil
053be11a 1650 ;; Specify an interactive shell, to make sure it prompts.
4042dc25 1651 "-i")
528415e7
RS
1652 (let ((proc (get-process "tex-shell")))
1653 (set-process-sentinel proc 'tex-shell-sentinel)
003274a0 1654 (set-process-query-on-exit-flag proc nil)
bdbd9606 1655 (tex-shell)
528415e7 1656 (while (zerop (buffer-size))
51b2c841
RS
1657 (sleep-for 1)))))
1658
033306e3
RS
1659(defun tex-feed-input ()
1660 "Send input to the tex shell process.
1661In the tex buffer this can be used to continue an interactive tex run.
bed1b0c8 1662In the tex shell buffer this command behaves like `comint-send-input'."
033306e3 1663 (interactive)
b781e739 1664 (set-buffer (tex-shell-buf))
033306e3
RS
1665 (comint-send-input)
1666 (tex-recenter-output-buffer nil))
1667
51b2c841
RS
1668(defun tex-display-shell ()
1669 "Make the TeX shell buffer visible in a window."
b781e739 1670 (display-buffer (tex-shell-buf))
51b2c841 1671 (tex-recenter-output-buffer nil))
528415e7
RS
1672
1673(defun tex-shell-sentinel (proc msg)
1674 (cond ((null (buffer-name (process-buffer proc)))
1675 ;; buffer killed
1676 (set-process-buffer proc nil)
1677 (tex-delete-last-temp-files))
1678 ((memq (process-status proc) '(signal exit))
1679 (tex-delete-last-temp-files))))
1680
1681(defun tex-set-buffer-directory (buffer directory)
869bff31 1682 "Set BUFFER's default directory to be DIRECTORY."
1683 (setq directory (file-name-as-directory (expand-file-name directory)))
1684 (if (not (file-directory-p directory))
1685 (error "%s is not a directory" directory)
1686 (save-excursion
1687 (set-buffer buffer)
1688 (setq default-directory directory))))
1689
30803a05
RS
1690(defvar tex-send-command-modified-tick 0)
1691(make-variable-buffer-local 'tex-send-command-modified-tick)
1692
bdbd9606 1693(defun tex-shell-proc ()
b781e739 1694 (or (tex-shell-running) (error "No TeX subprocess")))
bdbd9606
SM
1695(defun tex-shell-buf ()
1696 (process-buffer (tex-shell-proc)))
b781e739
SS
1697(defun tex-shell-buf-no-error ()
1698 (let ((proc (tex-shell-running)))
1699 (and proc (process-buffer proc))))
bdbd9606 1700
528415e7 1701(defun tex-send-command (command &optional file background)
4cdc1d4b 1702 "Send COMMAND to TeX shell process, substituting optional FILE for *.
8241d7b9
ER
1703Do this in background if optional BACKGROUND is t. If COMMAND has no *,
1704FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
1705substitution will be made in COMMAND. COMMAND can be any expression that
460e1b7d
RS
1706evaluates to a command string.
1707
1708Return the process in which TeX is running."
528415e7
RS
1709 (save-excursion
1710 (let* ((cmd (eval command))
bdbd9606 1711 (proc (tex-shell-proc))
64db2461 1712 (buf (process-buffer proc))
4f45adda 1713 (star (string-match "\\*" cmd))
4cdc1d4b
RS
1714 (string
1715 (concat
8ca66348
SM
1716 (if (null file)
1717 cmd
1718 (if (file-name-absolute-p file)
1719 (setq file (convert-standard-filename file)))
1720 (if star (concat (substring cmd 0 star)
1721 (shell-quote-argument file)
1722 (substring cmd (1+ star)))
1723 (concat cmd " " (shell-quote-argument file))))
4cdc1d4b 1724 (if background "&" ""))))
64db2461
RS
1725 ;; Switch to buffer before checking for subproc output in it.
1726 (set-buffer buf)
30803a05
RS
1727 ;; If text is unchanged since previous tex-send-command,
1728 ;; we haven't got any output. So wait for output now.
64db2461 1729 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
30803a05 1730 (accept-process-output proc))
4cdc1d4b
RS
1731 (goto-char (process-mark proc))
1732 (insert string)
30803a05 1733 (comint-send-input)
460e1b7d
RS
1734 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
1735 proc)))
528415e7 1736
a15849cb
RS
1737(defun tex-delete-last-temp-files (&optional not-all)
1738 "Delete any junk files from last temp file.
1739If NOT-ALL is non-nil, save the `.dvi' file."
528415e7
RS
1740 (if tex-last-temp-file
1741 (let* ((dir (file-name-directory tex-last-temp-file))
adf6b7f9
KH
1742 (list (and (file-directory-p dir)
1743 (file-name-all-completions
02fd229c
RS
1744 (file-name-sans-extension
1745 (file-name-nondirectory tex-last-temp-file))
1746 dir))))
adf6b7f9 1747 (while list
a15849cb
RS
1748 (if not-all
1749 (and
1750 ;; If arg is non-nil, don't delete the .dvi file.
1751 (not (string-match "\\.dvi$" (car list)))
1752 (delete-file (concat dir (car list))))
1753 (delete-file (concat dir (car list))))
528415e7
RS
1754 (setq list (cdr list))))))
1755
99621a14 1756(add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
869bff31 1757
75035a80
SM
1758;;
1759;; Machinery to guess the command that the user wants to execute.
1760;;
1761
1762(defvar tex-compile-history nil)
1763
1764(defvar tex-input-files-re
1765 (eval-when-compile
1766 (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
1767 "bbl" "ind" "sty" "cls") t)
1768 ;; Include files with no dots (for directories).
1769 "\\'\\|\\`[^.]+\\'")))
1770
1771(defcustom tex-use-reftex t
1772 "If non-nil, use RefTeX's list of files to determine what command to use."
18a8c773
LK
1773 :type 'boolean
1774 :group 'tex)
75035a80
SM
1775
1776(defvar tex-compile-commands
1777 '(((concat "pdf" tex-command
bf4ec222 1778 " " (if (< 0 (length tex-start-commands))
d18fc930 1779 (shell-quote-argument tex-start-commands)) " %f")
75035a80
SM
1780 t "%r.pdf")
1781 ((concat tex-command
bf4ec222 1782 " " (if (< 0 (length tex-start-commands))
d18fc930 1783 (shell-quote-argument tex-start-commands)) " %f")
75035a80
SM
1784 t "%r.dvi")
1785 ("xdvi %r &" "%r.dvi")
29a47b89
SM
1786 ("xpdf %r.pdf &" "%r.pdf")
1787 ("gv %r.ps &" "%r.ps")
1788 ("yap %r &" "%r.dvi")
75035a80 1789 ("advi %r &" "%r.dvi")
29a47b89 1790 ("gv %r.pdf &" "%r.pdf")
75035a80
SM
1791 ("bibtex %r" "%r.aux" "%r.bbl")
1792 ("makeindex %r" "%r.idx" "%r.ind")
1793 ("texindex %r.??")
1794 ("dvipdfm %r" "%r.dvi" "%r.pdf")
1795 ("dvipdf %r" "%r.dvi" "%r.pdf")
dd166d5f 1796 ("dvips -o %r.ps %r" "%r.dvi" "%r.ps")
e70ff1af 1797 ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
75035a80
SM
1798 ("lpr %r.ps" "%r.ps"))
1799 "List of commands for `tex-compile'.
1800Each element should be of the form (FORMAT IN OUT) where
1801FORMAT is an expression that evaluates to a string that can contain
1802 - `%r' the main file name without extension.
1803 - `%f' the main file name.
1804IN can be either a string (with the same % escapes in it) indicating
1805 the name of the input file, or t to indicate that the input is all
1806 the TeX files of the document, or nil if we don't know.
1807OUT describes the output file and is either a %-escaped string
1808 or nil to indicate that there is no output file.")
1809
8084f5d8
SM
1810;; defsubst* gives better byte-code than defsubst.
1811(defsubst* tex-string-prefix-p (str1 str2)
1812 "Return non-nil if STR1 is a prefix of STR2"
1813 (eq t (compare-strings str2 nil (length str1) str1 nil nil)))
1814
dd459839
SM
1815(defun tex-guess-main-file (&optional all)
1816 "Find a likely `tex-main-file'.
1817Looks for hints in other buffers in the same directory or in
8084f5d8
SM
1818ALL other buffers. If ALL is `sub' only look at buffers in parent directories
1819of the current buffer."
dd459839
SM
1820 (let ((dir default-directory)
1821 (header-re tex-start-of-header))
1822 (catch 'found
1823 ;; Look for a buffer with `tex-main-file' set.
1824 (dolist (buf (if (consp all) all (buffer-list)))
1825 (with-current-buffer buf
8084f5d8
SM
1826 (when (and (cond
1827 ((null all) (equal dir default-directory))
1828 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1829 (t))
dd459839
SM
1830 (stringp tex-main-file))
1831 (throw 'found (expand-file-name tex-main-file)))))
1832 ;; Look for a buffer containing the magic `tex-start-of-header'.
1833 (dolist (buf (if (consp all) all (buffer-list)))
1834 (with-current-buffer buf
8084f5d8
SM
1835 (when (and (cond
1836 ((null all) (equal dir default-directory))
1837 ((eq all 'sub) (tex-string-prefix-p default-directory dir))
1838 (t))
dd459839
SM
1839 buffer-file-name
1840 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
1841 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
1842 (save-excursion
cb30255a
SM
1843 (save-restriction
1844 (widen)
1845 (goto-char (point-min))
95a045bd
SM
1846 (re-search-forward
1847 header-re (+ (point) 10000) t))))
dd459839
SM
1848 (throw 'found (expand-file-name buffer-file-name))))))))
1849
07c16ec4
SM
1850(defun tex-main-file ()
1851 "Return the relative name of the main file."
bdbd9606
SM
1852 (let* ((file (or tex-main-file
1853 ;; Compatibility with AUCTeX.
96c0d9e9 1854 (with-no-warnings
034a48f4
MR
1855 (when (boundp 'TeX-master)
1856 (cond ((stringp TeX-master)
1857 (make-local-variable 'tex-main-file)
1858 (setq tex-main-file TeX-master))
1859 ((and (eq TeX-master t) buffer-file-name)
1860 (file-relative-name buffer-file-name)))))
bdbd9606
SM
1861 ;; Try to guess the main file.
1862 (if (not buffer-file-name)
1863 (error "Buffer is not associated with any file")
1864 (file-relative-name
1865 (if (save-excursion
1866 (goto-char (point-min))
95a045bd
SM
1867 (re-search-forward tex-start-of-header
1868 (+ (point) 10000) t))
bdbd9606
SM
1869 ;; This is the main file.
1870 buffer-file-name
1871 ;; This isn't the main file, let's try to find better,
1872 (or (tex-guess-main-file)
8084f5d8 1873 (tex-guess-main-file 'sub)
bdbd9606 1874 ;; (tex-guess-main-file t)
07c16ec4 1875 buffer-file-name)))))))
e70ff1af
SM
1876 (if (or (file-exists-p file) (string-match "\\.tex\\'" file))
1877 file (concat file ".tex"))))
dd459839 1878
75035a80
SM
1879(defun tex-summarize-command (cmd)
1880 (if (not (stringp cmd)) ""
1881 (mapconcat 'identity
1882 (mapcar (lambda (s) (car (split-string s)))
1883 (split-string cmd "\\s-*\\(?:;\\|&&\\)\\s-*"))
1884 "&")))
1885
1886(defun tex-uptodate-p (file)
1887 "Return non-nil if FILE is not uptodate w.r.t the document source files.
1888FILE is typically the output DVI or PDF file."
1889 ;; We should check all the files included !!!
1890 (and
1891 ;; Clearly, the target must exist.
1892 (file-exists-p file)
1893 ;; And the last run must not have asked for a rerun.
1894 ;; FIXME: this should check that the last run was done on the same file.
1895 (let ((buf (condition-case nil (tex-shell-buf) (error nil))))
1896 (when buf
1897 (with-current-buffer buf
1898 (save-excursion
1899 (goto-char (point-max))
1900 (and (re-search-backward
8ca66348
SM
1901 (concat
1902 "(see the transcript file for additional information)"
1903 "\\|^Output written on .*"
1904 (regexp-quote (file-name-nondirectory file))
1905 " (.*)\\.") nil t)
75035a80
SM
1906 (> (save-excursion
1907 (or (re-search-backward "\\[[0-9]+\\]" nil t)
1908 (point-min)))
1909 (save-excursion
1910 (or (re-search-backward "Rerun" nil t)
1911 (point-min)))))))))
1912 ;; And the input files must not have been changed in the meantime.
1913 (let ((files (if (and tex-use-reftex
1914 (fboundp 'reftex-scanning-info-available-p)
1915 (reftex-scanning-info-available-p))
1916 (reftex-all-document-files)
1917 (list (file-name-directory (expand-file-name file)))))
1918 (ignored-dirs-re
1919 (concat
1920 (regexp-opt
1921 (delq nil (mapcar (lambda (s) (if (eq (aref s (1- (length s))) ?/)
1922 (substring s 0 (1- (length s)))))
1923 completion-ignored-extensions))
1924 t) "\\'"))
1925 (uptodate t))
1926 (while (and files uptodate)
1927 (let ((f (pop files)))
e70ff1af
SM
1928 (if (and (file-directory-p f)
1929 ;; Avoid infinite loops.
1930 (not (file-symlink-p f)))
75035a80
SM
1931 (unless (string-match ignored-dirs-re f)
1932 (setq files (nconc
1933 (directory-files f t tex-input-files-re)
1934 files)))
1935 (when (file-newer-than-file-p f file)
1936 (setq uptodate nil)))))
1937 uptodate)))
bf247b6e 1938
75035a80
SM
1939
1940(autoload 'format-spec "format-spec")
1941
1942(defvar tex-executable-cache nil)
1943(defun tex-executable-exists-p (name)
1944 "Like `executable-find' but with a cache."
1945 (let ((cache (assoc name tex-executable-cache)))
1946 (if cache (cdr cache)
1947 (let ((executable (executable-find name)))
1948 (push (cons name executable) tex-executable-cache)
1949 executable))))
1950
1951(defun tex-command-executable (cmd)
1952 (let ((s (if (stringp cmd) cmd (eval (car cmd)))))
1953 (substring s 0 (string-match "[ \t]\\|\\'" s))))
1954
1955(defun tex-command-active-p (cmd fspec)
1956 "Return non-nil if the CMD spec might need to be run."
1957 (let ((in (nth 1 cmd))
1958 (out (nth 2 cmd)))
1959 (if (stringp in)
1960 (let ((file (format-spec in fspec)))
1961 (when (file-exists-p file)
1962 (or (not out)
1963 (file-newer-than-file-p
1964 file (format-spec out fspec)))))
1965 (when (and (eq in t) (stringp out))
1966 (not (tex-uptodate-p (format-spec out fspec)))))))
1967
8084f5d8 1968(defun tex-compile-default (fspec)
dd166d5f 1969 "Guess a default command given the `format-spec' FSPEC."
75035a80
SM
1970 ;; TODO: Learn to do latex+dvips!
1971 (let ((cmds nil)
1972 (unchanged-in nil))
1973 ;; Only consider active commands.
1974 (dolist (cmd tex-compile-commands)
1975 (when (tex-executable-exists-p (tex-command-executable cmd))
1976 (if (tex-command-active-p cmd fspec)
1977 (push cmd cmds)
1978 (push (nth 1 cmd) unchanged-in))))
dd166d5f 1979 ;; If no command seems to be applicable, arbitrarily pick the first one.
29a47b89 1980 (setq cmds (if cmds (nreverse cmds) (list (car tex-compile-commands))))
75035a80
SM
1981 ;; Remove those commands whose input was considered stable for
1982 ;; some other command (typically if (t . "%.pdf") is inactive
1983 ;; then we're using pdflatex and the fact that the dvi file
1984 ;; is inexistent doesn't matter).
1985 (let ((tmp nil))
1986 (dolist (cmd cmds)
1987 (unless (member (nth 1 cmd) unchanged-in)
1988 (push cmd tmp)))
8084f5d8 1989 ;; Only remove if there's something left.
29a47b89 1990 (if tmp (setq cmds (nreverse tmp))))
8084f5d8
SM
1991 ;; Remove commands whose input is not uptodate either.
1992 (let ((outs (delq nil (mapcar (lambda (x) (nth 2 x)) cmds)))
1993 (tmp nil))
1994 (dolist (cmd cmds)
75035a80 1995 (unless (member (nth 1 cmd) outs)
8084f5d8
SM
1996 (push cmd tmp)))
1997 ;; Only remove if there's something left.
29a47b89 1998 (if tmp (setq cmds (nreverse tmp))))
75035a80
SM
1999 ;; Select which file we're going to operate on (the latest).
2000 (let ((latest (nth 1 (car cmds))))
2001 (dolist (cmd (prog1 (cdr cmds) (setq cmds (list (car cmds)))))
2002 (if (equal latest (nth 1 cmd))
2003 (push cmd cmds)
2004 (unless (eq latest t) ;Can't beat that!
2005 (if (or (not (stringp latest))
2006 (eq (nth 1 cmd) t)
2007 (and (stringp (nth 1 cmd))
2008 (file-newer-than-file-p
2009 (format-spec (nth 1 cmd) fspec)
2010 (format-spec latest fspec))))
2011 (setq latest (nth 1 cmd) cmds (list cmd)))))))
2012 ;; Expand the command spec into the actual text.
2013 (dolist (cmd (prog1 cmds (setq cmds nil)))
2014 (push (cons (eval (car cmd)) (cdr cmd)) cmds))
2015 ;; Select the favorite command from the history.
2016 (let ((hist tex-compile-history)
8084f5d8 2017 re hist-cmd)
75035a80 2018 (while hist
8084f5d8 2019 (setq hist-cmd (pop hist))
75035a80 2020 (setq re (concat "\\`"
8084f5d8 2021 (regexp-quote (tex-command-executable hist-cmd))
75035a80
SM
2022 "\\([ \t]\\|\\'\\)"))
2023 (dolist (cmd cmds)
8084f5d8
SM
2024 ;; If the hist entry uses the same command and applies to a file
2025 ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
2026 (and (string-match re (car cmd))
2027 (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd)))
2028 (string-match (regexp-quote (match-string 1 (car cmd)))
2029 hist-cmd))
2030 (setq hist nil cmds (list cmd)))))
2031 ;; Substitute and return.
2032 (if (and hist-cmd
2033 (string-match (concat "[' \t\"]" (format-spec "%r" fspec)
2034 "\\([;&' \t\"]\\|\\'\\)") hist-cmd))
2035 ;; The history command was already applied to the same file,
2036 ;; so just reuse it.
2037 hist-cmd
2038 (if cmds (format-spec (caar cmds) fspec))))))
75035a80
SM
2039
2040(defun tex-compile (dir cmd)
2041 "Run a command CMD on current TeX buffer's file in DIR."
2042 ;; FIXME: Use time-stamps on files to decide the next op.
2043 (interactive
2044 (let* ((file (tex-main-file))
5e56fb53
SM
2045 (default-directory
2046 (prog1 (file-name-directory (expand-file-name file))
2047 (setq file (file-name-nondirectory file))))
75035a80 2048 (root (file-name-sans-extension file))
d18fc930
SM
2049 (fspec (list (cons ?r (shell-quote-argument root))
2050 (cons ?f (shell-quote-argument file))))
8084f5d8 2051 (default (tex-compile-default fspec)))
5e56fb53 2052 (list default-directory
75035a80
SM
2053 (completing-read
2054 (format "Command [%s]: " (tex-summarize-command default))
2055 (mapcar (lambda (x)
2056 (list (format-spec (eval (car x)) fspec)))
2057 tex-compile-commands)
2058 nil nil nil 'tex-compile-history default))))
2059 (save-some-buffers (not compilation-ask-about-save) nil)
2060 (if (tex-shell-running)
2061 (tex-kill-job)
2062 (tex-start-shell))
2063 (tex-send-tex-command cmd dir))
d6709b80
SM
2064
2065(defun tex-start-tex (command file &optional dir)
460e1b7d 2066 "Start a TeX run, using COMMAND on FILE."
6633b891 2067 (let* ((star (string-match "\\*" command))
460e1b7d 2068 (compile-command
6633b891
KH
2069 (if star
2070 (concat (substring command 0 star)
d18fc930 2071 (shell-quote-argument file)
6633b891
KH
2072 (substring command (1+ star)))
2073 (concat command " "
95a045bd 2074 tex-start-options
9e0ad27a 2075 (if (< 0 (length tex-start-commands))
d18fc930
SM
2076 (concat
2077 (shell-quote-argument tex-start-commands) " "))
2078 (shell-quote-argument file)))))
bdbd9606
SM
2079 (tex-send-tex-command compile-command dir)))
2080
2081(defun tex-send-tex-command (cmd &optional dir)
b781e739
SS
2082 (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
2083 (and buf (with-current-buffer buf
2084 default-directory))))
bdbd9606
SM
2085 (not dir))
2086 (let (shell-dirtrack-verbose)
8ca66348 2087 (tex-send-command tex-shell-cd-command dir)))
bdbd9606 2088 (with-current-buffer (process-buffer (tex-send-command cmd))
bdbd9606
SM
2089 (setq compilation-last-buffer (current-buffer))
2090 (compilation-forget-errors)
1598a961 2091 ;; Don't parse previous compilations.
bdbd9606
SM
2092 (set-marker compilation-parsing-end (1- (point-max))))
2093 (tex-display-shell)
2094 (setq tex-last-buffer-texed (current-buffer)))
460e1b7d 2095\f
1598a961
SM
2096(defvar tex-error-parse-syntax-table
2097 (let ((st (make-syntax-table)))
2098 (modify-syntax-entry ?\( "()" st)
2099 (modify-syntax-entry ?\) ")(" st)
2100 (modify-syntax-entry ?\\ "\\" st)
2101 (modify-syntax-entry ?\{ "_" st)
2102 (modify-syntax-entry ?\} "_" st)
2103 (modify-syntax-entry ?\[ "_" st)
2104 (modify-syntax-entry ?\] "_" st)
2105 ;; Single quotations may appear in errors
2106 (modify-syntax-entry ?\" "_" st)
2107 st)
2108 "Syntax-table used while parsing TeX error messages.")
2109
460e1b7d 2110(defun tex-compilation-parse-errors (limit-search find-at-least)
f05bd645
RS
2111 "Parse the current buffer as TeX error messages.
2112See the variable `compilation-parse-errors-function' for the interface it uses.
2113
2114This function parses only the last TeX compilation.
2115It works on TeX compilations only. It is necessary for that purpose,
2116since TeX does not put file names and line numbers on the same line as
2117for the error messages."
460e1b7d
RS
2118 (require 'thingatpt)
2119 (setq compilation-error-list nil)
f05bd645
RS
2120 (let ((default-directory ; Perhaps dir has changed meanwhile.
2121 (file-name-directory (buffer-file-name tex-last-buffer-texed)))
f05bd645
RS
2122 found-desired (num-errors-found 0)
2123 last-filename last-linenum last-position
3d1634c6 2124 begin-of-error end-of-error errfilename)
f05bd645
RS
2125 ;; Don't reparse messages already seen at last parse.
2126 (goto-char compilation-parsing-end)
2127 ;; Parse messages.
2128 (while (and (not (or found-desired (eobp)))
3d1634c6
GM
2129 ;; First alternative handles the newer --file-line-error style:
2130 ;; ./test2.tex:14: Too many }'s.
2131 ;; Second handles the old-style:
2132 ;; ! Too many }'s.
e47a29ad 2133 (prog1 (re-search-forward
3d1634c6 2134 "^\\(?:\\([^:\n]+\\):[[:digit:]]+:\\|!\\) " nil 'move)
f05bd645 2135 (setq begin-of-error (match-beginning 0)
3d1634c6
GM
2136 end-of-error (match-end 0)
2137 errfilename (match-string 1)))
f05bd645
RS
2138 (re-search-forward
2139 "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$" nil 'move))
3f2c97ea 2140 (let* ((this-error (copy-marker begin-of-error))
003274a0 2141 (linenum (string-to-number (match-string 1)))
f05bd645
RS
2142 (error-text (regexp-quote (match-string 3)))
2143 (filename
3d1634c6
GM
2144 ;; Prefer --file-liner-error filename if we have it.
2145 (or errfilename
2146 (save-excursion
2147 (with-syntax-table tex-error-parse-syntax-table
2148 (backward-up-list 1)
2149 (skip-syntax-forward "(_")
2150 (while (not (file-readable-p (thing-at-point 'filename)))
2151 (skip-syntax-backward "(_")
2152 (backward-up-list 1)
2153 (skip-syntax-forward "(_"))
2154 (thing-at-point 'filename)))))
f05bd645
RS
2155 (new-file
2156 (or (null last-filename)
2157 (not (string-equal last-filename filename))))
2158 (error-location
cc9f5376
SM
2159 (with-current-buffer
2160 (if (equal filename (concat tex-zap-file ".tex"))
2161 tex-last-buffer-texed
2162 (find-file-noselect filename))
2163 (save-excursion
2164 (if new-file
2165 (progn (goto-line linenum) (setq last-position nil))
2166 (goto-char last-position)
2167 (forward-line (- linenum last-linenum)))
2168 ;; first try a forward search for the error text,
2169 ;; then a backward search limited by the last error.
2170 (let ((starting-point (point)))
2171 (or (re-search-forward error-text nil t)
2172 (re-search-backward error-text last-position t)
2173 (goto-char starting-point)))
2174 (point-marker)))))
f05bd645
RS
2175 (goto-char this-error)
2176 (if (and compilation-error-list
2177 (or (and find-at-least
2178 (>= num-errors-found
2179 find-at-least))
2180 (and limit-search
2181 (>= end-of-error limit-search)))
2182 new-file)
2183 (setq found-desired t)
2184 (setq num-errors-found (1+ num-errors-found)
2185 last-filename filename
2186 last-linenum linenum
2187 last-position error-location
2188 compilation-error-list ; Add the new error
2189 (cons (cons this-error error-location)
2190 compilation-error-list))
2191 (goto-char end-of-error)))))
ee13a145 2192 (set-marker compilation-parsing-end (point))
13376c78 2193 (setq compilation-error-list (nreverse compilation-error-list)))
460e1b7d 2194\f
528415e7 2195;;; The commands:
869bff31 2196
2197(defun tex-region (beg end)
2198 "Run TeX on the current region, via a temporary file.
2199The file's name comes from the variable `tex-zap-file' and the
2200variable `tex-directory' says where to put it.
2201
2202If the buffer has a header, the header is given to TeX before the
2203region itself. The buffer's header is all lines between the strings
2204defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
2205The header must start in the first 100 lines of the buffer.
2206
2207The value of `tex-trailer' is given to TeX as input after the region.
2208
2209The value of `tex-command' specifies the command to use to run TeX."
2210 (interactive "r")
2211 (if (tex-shell-running)
2212 (tex-kill-job)
2213 (tex-start-shell))
2214 (or tex-zap-file
2215 (setq tex-zap-file (tex-generate-zap-file-name)))
6d34c59f
RS
2216 ;; Temp file will be written and TeX will be run in zap-directory.
2217 ;; If the TEXINPUTS file has relative directories or if the region has
2218 ;; \input of files, this must be the same directory as the file for
2219 ;; TeX to access the correct inputs. That's why it's safest if
2220 ;; tex-directory is ".".
2221 (let* ((zap-directory
528415e7 2222 (file-name-as-directory (expand-file-name tex-directory)))
d6709b80 2223 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
80c2ab0f
GM
2224 zap-directory))
2225 (main-file (expand-file-name (tex-main-file)))
595a68b4
GM
2226 (ismain (string-equal main-file (buffer-file-name)))
2227 already-output)
0d548e5d
RS
2228 ;; Don't delete temp files if we do the same buffer twice in a row.
2229 (or (eq (current-buffer) tex-last-buffer-texed)
2230 (tex-delete-last-temp-files t))
595a68b4
GM
2231 (let ((default-directory zap-directory)) ; why?
2232 ;; We assume the header is fully contained in tex-main-file.
2233 ;; We use f-f-ns so we get prompted about any changes on disk.
2234 (with-current-buffer (find-file-noselect main-file)
2235 (setq already-output (tex-region-header tex-out-file
2236 (and ismain beg))))
2237 ;; Write out the specified region (but don't repeat anything
2238 ;; already written in the header).
2239 (write-region (if ismain
2240 (max beg already-output)
2241 beg)
2242 end tex-out-file (not (zerop already-output)))
2243 ;; Write the trailer, if any.
2244 ;; Precede it with a newline to make sure it
2245 ;; is not hidden in a comment.
2246 (if tex-trailer
2247 (write-region (concat "\n" tex-trailer) nil
2248 tex-out-file t)))
80c2ab0f
GM
2249 ;; Record the file name to be deleted afterward.
2250 (setq tex-last-temp-file tex-out-file)
2251 ;; Use a relative file name here because (1) the proper dir
2252 ;; is already current, and (2) the abs file name is sometimes
2253 ;; too long and can make tex crash.
2254 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
2255 (setq tex-print-file tex-out-file)))
2256
595a68b4
GM
2257(defun tex-region-header (file &optional beg)
2258 "If there is a TeX header in the current buffer, write it to FILE.
2259Return point at the end of the region so written, or zero. If
2260the optional buffer position BEG is specified, then the region
2261written out starts at BEG, if this lies before the start of the header.
2262
2263If the first line matches `tex-first-line-header-regexp', it is
2264also written out. The variables `tex-start-of-header' and
2265`tex-end-of-header' are used to locate the header. Note that the
2266start of the header is required to be within the first 100 lines."
2267 (save-excursion
2268 (save-restriction
2269 (widen)
2270 (goto-char (point-min))
2271 (let ((search-end (save-excursion
2272 (forward-line 100)
2273 (point)))
2274 (already-output 0)
2275 hbeg hend)
2276 ;; Maybe copy first line, such as `\input texinfo', to temp file.
2277 (and tex-first-line-header-regexp
2278 (looking-at tex-first-line-header-regexp)
2279 (write-region (point)
2280 (progn (forward-line 1)
2281 (setq already-output (point)))
2282 file))
2283 ;; Write out the header, if there is one, and any of the
2284 ;; specified region which extends before it. But don't repeat
2285 ;; anything already written.
2286 (and tex-start-of-header
2287 (re-search-forward tex-start-of-header search-end t)
2288 (progn
2289 (beginning-of-line)
2290 (setq hbeg (point)) ; mark beginning of header
2291 (when (re-search-forward tex-end-of-header nil t)
2292 (forward-line 1)
2293 (setq hend (point)) ; mark end of header
2294 (write-region
2295 (max (if beg
2296 (min hbeg beg)
2297 hbeg)
2298 already-output)
2299 hend file (not (zerop already-output)))
2300 (setq already-output hend))))
2301 already-output))))
869bff31 2302
2303(defun tex-buffer ()
2304 "Run TeX on current buffer. See \\[tex-region] for more information.
528415e7
RS
2305Does not save the buffer, so it's useful for trying experimental versions.
2306See \\[tex-file] for an alternative."
869bff31 2307 (interactive)
2308 (tex-region (point-min) (point-max)))
2309
2310(defun tex-file ()
2311 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
2312This function is more useful than \\[tex-buffer] when you need the
2313`.aux' file of LaTeX to have the correct name."
2314 (interactive)
7abc9add
SS
2315 (when tex-offer-save
2316 (save-some-buffers))
d6709b80 2317 (let* ((source-file (tex-main-file))
07c16ec4 2318 (file-dir (file-name-directory (expand-file-name source-file))))
869bff31 2319 (if (tex-shell-running)
2320 (tex-kill-job)
2321 (tex-start-shell))
d6709b80 2322 (tex-start-tex tex-command source-file file-dir)
f05bd645 2323 (setq tex-print-file (expand-file-name source-file))))
869bff31 2324
2325(defun tex-generate-zap-file-name ()
2326 "Generate a unique name suitable for use as a file name."
2327 ;; Include the shell process number and host name
2328 ;; in case there are multiple shells (for same or different user).
f5cdb851
KH
2329 ;; Dec 1998: There is a report that some versions of xdvi
2330 ;; don't work with file names that start with #.
5616ee46 2331 (format "_TZ_%d-%s"
869bff31 2332 (process-id (get-buffer-process "*tex-shell*"))
07c16ec4 2333 (subst-char-in-string ?. ?- (system-name))))
869bff31 2334
2335;; This will perhaps be useful for modifying TEXINPUTS.
2336;; Expand each file name, separated by colons, in the string S.
2337(defun tex-expand-files (s)
2338 (let (elts (start 0))
2339 (while (string-match ":" s start)
2340 (setq elts (cons (substring s start (match-beginning 0)) elts))
2341 (setq start (match-end 0)))
2342 (or (= start 0)
2343 (setq elts (cons (substring s start) elts)))
c0df1972
SM
2344 (mapconcat (lambda (elt)
2345 (if (= (length elt) 0) elt (expand-file-name elt)))
5616ee46 2346 (nreverse elts) ":")))
869bff31 2347
2348(defun tex-shell-running ()
713f7b15 2349 (let ((proc (get-process "tex-shell")))
b781e739
SS
2350 (when proc
2351 (if (and (eq (process-status proc) 'run)
2352 (buffer-live-p (process-buffer proc)))
2353 ;; return the TeX process on success
2354 proc
2355 ;; get rid of the process permanently
2356 ;; this should get rid of the annoying w32 problem with
2357 ;; dead tex-shell buffer and live process
2358 (delete-process proc)))))
869bff31 2359
2360(defun tex-kill-job ()
2361 "Kill the currently running TeX job."
2362 (interactive)
b781e739 2363 ;; `quit-process' leads to core dumps of the tex process (except if
bed1b0c8
RS
2364 ;; coredumpsize has limit 0kb as on many environments). One would
2365 ;; like to use (kill-process proc 'lambda), however that construct
2366 ;; does not work on some systems and kills the shell itself.
b781e739
SS
2367 (let ((proc (get-process "tex-shell")))
2368 (when proc (quit-process proc t))))
869bff31 2369
2370(defun tex-recenter-output-buffer (linenum)
2371 "Redisplay buffer of TeX job output so that most recent output can be seen.
2372The last line of the buffer is displayed on
2373line LINE of the window, or centered if LINE is nil."
2374 (interactive "P")
2375 (let ((tex-shell (get-buffer "*tex-shell*"))
23b64225 2376 (window))
869bff31 2377 (if (null tex-shell)
2378 (message "No TeX output buffer")
23b64225
RS
2379 (setq window (display-buffer tex-shell))
2380 (save-selected-window
2381 (select-window window)
2382 (bury-buffer tex-shell)
2383 (goto-char (point-max))
2384 (recenter (if linenum
2385 (prefix-numeric-value linenum)
2386 (/ (window-height) 2)))))))
869bff31 2387
528415e7 2388(defun tex-print (&optional alt)
869bff31 2389 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
1433a222
CZ
2390Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
2391is provided, use the alternative command, `tex-alt-dvi-print-command'."
528415e7 2392 (interactive "P")
869bff31 2393 (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
2394 test-name)
2395 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
45c3304d
RS
2396 (buffer-file-name)
2397 ;; Check that this buffer's printed file is up to date.
869bff31 2398 (file-newer-than-file-p
2399 (setq test-name (tex-append (buffer-file-name) ".dvi"))
45c3304d 2400 (buffer-file-name)))
869bff31 2401 (setq print-file-name-dvi test-name))
528415e7
RS
2402 (if (not (file-exists-p print-file-name-dvi))
2403 (error "No appropriate `.dvi' file could be found")
460e1b7d
RS
2404 (if (tex-shell-running)
2405 (tex-kill-job)
2406 (tex-start-shell))
528415e7 2407 (tex-send-command
bed1b0c8 2408 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
b5352ff5 2409 print-file-name-dvi
602503c5 2410 t))))
869bff31 2411
cf6d6e8a
RS
2412(defun tex-alt-print ()
2413 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
002b0d00 2414Runs the shell command defined by `tex-alt-dvi-print-command'."
cf6d6e8a
RS
2415 (interactive)
2416 (tex-print t))
2417
869bff31 2418(defun tex-view ()
2419 "Preview the last `.dvi' file made by running TeX under Emacs.
2420This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2b7971c9
RS
2421The variable `tex-dvi-view-command' specifies the shell command for preview.
2422You must set that variable yourself before using this command,
2423because there is no standard value that would generally work."
869bff31 2424 (interactive)
2b7971c9
RS
2425 (or tex-dvi-view-command
2426 (error "You must set `tex-dvi-view-command'"))
3356ce3b
EZ
2427 ;; Restart the TeX shell if necessary.
2428 (or (tex-shell-running)
2429 (tex-start-shell))
746c30e2 2430 (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
869bff31 2431 (tex-print)))
2432
2433(defun tex-append (file-name suffix)
2434 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
cf6d6e8a 2435Pascal-based TeX scans for the first period, C TeX uses the last.
869bff31 2436No period is retained immediately before SUFFIX,
2437so normally SUFFIX starts with one."
2438 (if (stringp file-name)
cf6d6e8a
RS
2439 (let ((file (file-name-nondirectory file-name))
2440 trial-name)
6da9bbd6 2441 ;; Try splitting on last period.
7d0ca249
RS
2442 ;; The first-period split can get fooled when two files
2443 ;; named a.tex and a.b.tex are both tex'd;
2444 ;; the last-period split must be right if it matches at all.
cf6d6e8a
RS
2445 (setq trial-name
2446 (concat (file-name-directory file-name)
2447 (substring file 0
7d0ca249 2448 (string-match "\\.[^.]*$" file))
cf6d6e8a
RS
2449 suffix))
2450 (if (or (file-exists-p trial-name)
2451 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
2452 trial-name
7d0ca249 2453 ;; Not found, so split on first period.
cf6d6e8a
RS
2454 (concat (file-name-directory file-name)
2455 (substring file 0
7d0ca249 2456 (string-match "\\." file))
cf6d6e8a 2457 suffix)))
869bff31 2458 " "))
2459
2460(defun tex-show-print-queue ()
2461 "Show the print queue that \\[tex-print] put your job on.
1433a222 2462Runs the shell command defined by `tex-show-queue-command'."
869bff31 2463 (interactive)
2464 (if (tex-shell-running)
2465 (tex-kill-job)
2466 (tex-start-shell))
51b2c841
RS
2467 (tex-send-command tex-show-queue-command)
2468 (tex-display-shell))
869bff31 2469
2470(defun tex-bibtex-file ()
2471 "Run BibTeX on the current buffer's file."
2472 (interactive)
2473 (if (tex-shell-running)
2474 (tex-kill-job)
2475 (tex-start-shell))
e6b0b773
MR
2476 (let (shell-dirtrack-verbose
2477 (tex-out-file
869bff31 2478 (tex-append (file-name-nondirectory (buffer-file-name)) ""))
2479 (file-dir (file-name-directory (buffer-file-name))))
8ca66348 2480 (tex-send-command tex-shell-cd-command file-dir)
51b2c841
RS
2481 (tex-send-command tex-bibtex-command tex-out-file))
2482 (tex-display-shell))
ea590e1c
SM
2483\f
2484;;;;
2485;;;; LaTeX indentation
2486;;;;
2487
2488(defvar tex-indent-allhanging t)
2489(defvar tex-indent-arg 4)
2490(defvar tex-indent-basic 2)
2491(defvar tex-indent-item tex-indent-basic)
2492(defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
dd166d5f 2493(defvar latex-noindent-environments '("document"))
ea590e1c 2494
8a591d52
SM
2495(defvar tex-latex-indent-syntax-table
2496 (let ((st (make-syntax-table tex-mode-syntax-table)))
2497 (modify-syntax-entry ?$ "." st)
2498 (modify-syntax-entry ?\( "." st)
2499 (modify-syntax-entry ?\) "." st)
2500 st)
2501 "Syntax table used while computing indentation.")
ea590e1c
SM
2502
2503(defun latex-indent (&optional arg)
7afecb99 2504 (if (and (eq (get-text-property (line-beginning-position) 'face)
014e29b9 2505 'tex-verbatim))
a3d80d4a 2506 'noindent
7afecb99
SM
2507 (with-syntax-table tex-latex-indent-syntax-table
2508 ;; TODO: Rather than ignore $, we should try to be more clever about it.
2509 (let ((indent
2510 (save-excursion
2511 (beginning-of-line)
2512 (latex-find-indent))))
2513 (if (< indent 0) (setq indent 0))
2514 (if (<= (current-column) (current-indentation))
2515 (indent-line-to indent)
2516 (save-excursion (indent-line-to indent)))))))
ea590e1c
SM
2517
2518(defun latex-find-indent (&optional virtual)
2519 "Find the proper indentation of text after point.
2520VIRTUAL if non-nil indicates that we're only trying to find the indentation
2521 in order to determine the indentation of something else.
2522There might be text before point."
2523 (save-excursion
2524 (skip-chars-forward " \t")
2525 (or
7afecb99
SM
2526 ;; Stick the first line at column 0.
2527 (and (= (point-min) (line-beginning-position)) 0)
ea590e1c 2528 ;; Trust the current indentation, if such info is applicable.
7afecb99
SM
2529 (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
2530 (current-column))
2531 ;; Stick verbatim environments to the left margin.
2532 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2533 (member (match-string 2) tex-verbatim-environments)
2534 0)
ea590e1c
SM
2535 ;; Put leading close-paren where the matching open brace would be.
2536 (and (eq (latex-syntax-after) ?\))
2537 (ignore-errors
2538 (save-excursion
2539 (latex-skip-close-parens)
2540 (latex-backward-sexp-1)
2541 (latex-find-indent 'virtual))))
2542 ;; Default (maybe an argument)
2543 (let ((pos (point))
ea590e1c
SM
2544 ;; Outdent \item if necessary.
2545 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
2546 up-list-pos)
2547 ;; Find the previous point which determines our current indentation.
2548 (condition-case err
2549 (progn
2550 (latex-backward-sexp-1)
2551 (while (> (current-column) (current-indentation))
2552 (latex-backward-sexp-1)))
2553 (scan-error
2554 (setq up-list-pos (nth 2 err))))
8908cf40
SM
2555 (cond
2556 ((= (point-min) pos) 0) ; We're really just indenting the first line.
2557 ((integerp up-list-pos)
2558 ;; Have to indent relative to the open-paren.
2559 (goto-char up-list-pos)
2560 (if (and (not tex-indent-allhanging)
dd166d5f
SM
2561 (save-excursion
2562 ;; Make sure we're an argument to a macro and
2563 ;; that the macro is at the beginning of a line.
2564 (condition-case nil
2565 (progn
2566 (while (eq (char-syntax (char-after)) ?\()
2567 (forward-sexp -1))
2568 (and (eq (char-syntax (char-after)) ?/)
2569 (progn (skip-chars-backward " \t&")
2570 (bolp))))
2571 (scan-error nil)))
8908cf40
SM
2572 (> pos (progn (latex-down-list)
2573 (forward-comment (point-max))
2574 (point))))
7afecb99 2575 ;; Align with the first element after the open-paren.
8908cf40
SM
2576 (current-column)
2577 ;; We're the first element after a hanging brace.
2578 (goto-char up-list-pos)
dd166d5f
SM
2579 (+ (if (and (looking-at "\\\\begin *{\\([^\n}]+\\)")
2580 (member (match-string 1)
2581 latex-noindent-environments))
2582 0 tex-indent-basic)
2583 indent (latex-find-indent 'virtual))))
8908cf40
SM
2584 ;; We're now at the "beginning" of a line.
2585 ((not (and (not virtual) (eq (char-after) ?\\)))
2586 ;; Nothing particular here: just keep the same indentation.
2587 (+ indent (current-column)))
2588 ;; We're now looking at a macro call.
dd166d5f
SM
2589 ((looking-at tex-indent-item-re)
2590 ;; Indenting relative to an item, have to re-add the outdenting.
8908cf40
SM
2591 (+ indent (current-column) tex-indent-item))
2592 (t
2593 (let ((col (current-column)))
d1218e3e 2594 (if (or (not (eq (char-syntax (or (char-after pos) ?\s)) ?\())
dd166d5f
SM
2595 ;; Can't be an arg if there's an empty line inbetween.
2596 (save-excursion (re-search-forward "^[ \t]*$" pos t)))
8908cf40
SM
2597 ;; If the first char was not an open-paren, there's
2598 ;; a risk that this is really not an argument to the
2599 ;; macro at all.
21749f14
RS
2600 (+ indent col)
2601 (forward-sexp 1)
2602 (if (< (line-end-position)
2603 (save-excursion (forward-comment (point-max))
2604 (point)))
8908cf40
SM
2605 ;; we're indenting the first argument.
2606 (min (current-column) (+ tex-indent-arg col))
2607 (skip-syntax-forward " ")
2608 (current-column))))))))))
a3d80d4a
SM
2609;;; DocTeX support
2610
2611(defun doctex-font-lock-^^A ()
2612 (if (eq (char-after (line-beginning-position)) ?\%)
2613 (progn
2614 (put-text-property
2615 (1- (match-beginning 1)) (match-beginning 1)
2616 'syntax-table
2617 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2618 ;; The `%' is a single-char comment, which Emacs
2619 ;; syntax-table can't deal with. We could turn it
2620 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2621 ;; Instead, we include it in the ^^A comment.
2622 (eval-when-compile (string-to-syntax "< b"))
2623 (eval-when-compile (string-to-syntax ">"))))
2624 (let ((end (line-end-position)))
2625 (if (< end (point-max))
2626 (put-text-property
2627 end (1+ end)
2628 'syntax-table
2629 (eval-when-compile (string-to-syntax "> b")))))
2630 (eval-when-compile (string-to-syntax "< b")))))
2631
2632(defun doctex-font-lock-syntactic-face-function (state)
2633 ;; Mark DocTeX documentation, which is parsed as a style A comment
2634 ;; starting in column 0.
2635 (if (or (nth 3 state) (nth 7 state)
2636 (not (memq (char-before (nth 8 state))
2637 '(?\n nil))))
2638 ;; Anything else is just as for LaTeX.
2639 (tex-font-lock-syntactic-face-function state)
2640 font-lock-doc-face))
2641
2642(defvar doctex-font-lock-syntactic-keywords
2643 (append
2644 tex-font-lock-syntactic-keywords
2645 ;; For DocTeX comment-in-doc.
2646 `(("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A))))))
2647
2648(defvar doctex-font-lock-keywords
2649 (append tex-font-lock-keywords
2650 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t)))))
2651
2652;;;###autoload
2653(define-derived-mode doctex-mode latex-mode "DocTeX"
2654 "Major mode to edit DocTeX files."
2655 (setq font-lock-defaults
2656 (cons (append (car font-lock-defaults) '(doctex-font-lock-keywords))
2657 (mapcar
2658 (lambda (x)
2659 (case (car-safe x)
2660 (font-lock-syntactic-keywords
2661 (cons (car x) 'doctex-font-lock-syntactic-keywords))
2662 (font-lock-syntactic-face-function
2663 (cons (car x) 'doctex-font-lock-syntactic-face-function))
2664 (t x)))
2665 (cdr font-lock-defaults)))))
528415e7
RS
2666
2667(run-hooks 'tex-mode-load-hook)
869bff31 2668
49116ac0
JB
2669(provide 'tex-mode)
2670
dd166d5f 2671;; arch-tag: c0a680b1-63aa-4547-84b9-4193c29c0080
d501f516 2672;;; tex-mode.el ends here