]> code.delx.au - gnu-emacs/blob - lisp/textmodes/tex-mode.el
Handle Bug#23186
[gnu-emacs] / lisp / textmodes / tex-mode.el
1 ;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 1985-1986, 1989, 1992, 1994-1999, 2001-2016 Free
4 ;; Software Foundation, Inc.
5
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: tex
8
9 ;; Contributions over the years by William F. Schelter, Dick King,
10 ;; Stephen Gildea, Michael Prange, Jacob Gore, and Edward M. Reingold.
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;;; Code:
30
31 ;; Pacify the byte-compiler
32 (eval-when-compile
33 (require 'compare-w)
34 (require 'cl-lib)
35 (require 'skeleton))
36
37 (defvar font-lock-comment-face)
38 (defvar font-lock-doc-face)
39
40 (require 'shell)
41 (require 'compile)
42
43 (defgroup tex-file nil
44 "TeX files and directories."
45 :prefix "tex-"
46 :group 'tex)
47
48 (defgroup tex-run nil
49 "Running external commands from TeX mode."
50 :prefix "tex-"
51 :group 'tex)
52
53 (defgroup tex-view nil
54 "Viewing and printing TeX files."
55 :prefix "tex-"
56 :group 'tex)
57
58 ;;;###autoload
59 (defcustom tex-shell-file-name nil
60 "If non-nil, the shell file name to run in the subshell used to run TeX."
61 :type '(choice (const :tag "None" nil)
62 string)
63 :group 'tex-run)
64
65 ;;;###autoload
66 (defcustom tex-directory (purecopy ".")
67 "Directory in which temporary files are written.
68 You can make this `/tmp' if your TEXINPUTS has no relative directories in it
69 and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
70 `\\input' commands with relative directories."
71 :type 'directory
72 :group 'tex-file)
73
74 ;;;###autoload
75 (defcustom tex-first-line-header-regexp nil
76 "Regexp for matching a first line which `tex-region' should include.
77 If this is non-nil, it should be a regular expression string;
78 if it matches the first line of the file,
79 `tex-region' always includes the first line in the TeX run."
80 :type '(choice (const :tag "None" nil)
81 regexp)
82 :group 'tex-file)
83
84 ;;;###autoload
85 (defcustom tex-main-file nil
86 "The main TeX source file which includes this buffer's file.
87 The command `tex-file' runs TeX on the file specified by `tex-main-file'
88 if the variable is non-nil."
89 :type '(choice (const :tag "None" nil)
90 file)
91 :group 'tex-file)
92
93 ;;;###autoload
94 (defcustom tex-offer-save t
95 "If non-nil, ask about saving modified buffers before \\[tex-file] is run."
96 :type 'boolean
97 :group 'tex-file)
98
99 ;;;###autoload
100 (defcustom tex-run-command (purecopy "tex")
101 "Command used to run TeX subjob.
102 TeX Mode sets `tex-command' to this string.
103 See the documentation of that variable."
104 :type 'string
105 :group 'tex-run)
106
107 ;;;###autoload
108 (defcustom latex-run-command (purecopy "latex")
109 "Command used to run LaTeX subjob.
110 LaTeX Mode sets `tex-command' to this string.
111 See the documentation of that variable."
112 :type 'string
113 :group 'tex-run)
114
115 ;;;###autoload
116 (defcustom slitex-run-command (purecopy "slitex")
117 "Command used to run SliTeX subjob.
118 SliTeX Mode sets `tex-command' to this string.
119 See the documentation of that variable."
120 :type 'string
121 :group 'tex-run)
122
123 ;;;###autoload
124 (defcustom tex-start-options (purecopy "")
125 "TeX options to use when starting TeX.
126 These immediately precede the commands in `tex-start-commands'
127 and the input file name, with no separating space and are not shell-quoted.
128 If nil, TeX runs with no options. See the documentation of `tex-command'."
129 :type 'string
130 :group 'tex-run
131 :version "22.1")
132
133 ;;;###autoload
134 (defcustom tex-start-commands (purecopy "\\nonstopmode\\input")
135 "TeX commands to use when starting TeX.
136 They are shell-quoted and precede the input file name, with a separating space.
137 If nil, no commands are used. See the documentation of `tex-command'."
138 :type '(radio (const :tag "Interactive (nil)" nil)
139 (const :tag "Nonstop (\"\\nonstopmode\\input\")"
140 "\\nonstopmode\\input")
141 (string :tag "String at your choice"))
142 :group 'tex-run
143 :version "22.1")
144
145 (defvar latex-standard-block-names
146 '("abstract" "array" "center" "description"
147 "displaymath" "document" "enumerate" "eqnarray"
148 "eqnarray*" "equation" "figure" "figure*"
149 "flushleft" "flushright" "itemize" "letter"
150 "list" "minipage" "picture" "quotation"
151 "quote" "slide" "sloppypar" "tabbing"
152 "table" "table*" "tabular" "tabular*"
153 "thebibliography" "theindex*" "titlepage" "trivlist"
154 "verbatim" "verbatim*" "verse" "math")
155 "Standard LaTeX block names.")
156
157 ;;;###autoload
158 (defcustom latex-block-names nil
159 "User defined LaTeX block names.
160 Combined with `latex-standard-block-names' for minibuffer completion."
161 :type '(repeat string)
162 :group 'tex-run)
163
164 ;;;###autoload
165 (defcustom tex-bibtex-command (purecopy "bibtex")
166 "Command used by `tex-bibtex-file' to gather bibliographic data.
167 If this string contains an asterisk (`*'), that is replaced by the file name;
168 otherwise, the file name, preceded by blank, is added at the end."
169 :type 'string
170 :group 'tex-run)
171
172 ;;;###autoload
173 (defcustom tex-dvi-print-command (purecopy "lpr -d")
174 "Command used by \\[tex-print] to print a .dvi file.
175 If this string contains an asterisk (`*'), that is replaced by the file name;
176 otherwise, the file name, preceded by blank, is added at the end."
177 :type 'string
178 :group 'tex-view)
179
180 ;;;###autoload
181 (defcustom tex-alt-dvi-print-command (purecopy "lpr -d")
182 "Command used by \\[tex-print] with a prefix arg to print a .dvi file.
183 If this string contains an asterisk (`*'), that is replaced by the file name;
184 otherwise, the file name, preceded by blank, is added at the end.
185
186 If two printers are not enough of a choice, you can set the variable
187 `tex-alt-dvi-print-command' to an expression that asks what you want;
188 for example,
189
190 (setq tex-alt-dvi-print-command
191 \\='(format \"lpr -P%s\" (read-string \"Use printer: \")))
192
193 would tell \\[tex-print] with a prefix argument to ask you which printer to
194 use."
195 :type '(choice (string :tag "Command")
196 (sexp :tag "Expression"))
197 :group 'tex-view)
198
199 ;;;###autoload
200 (defcustom tex-dvi-view-command
201 `(cond
202 ((eq window-system 'x) ,(purecopy "xdvi"))
203 ((eq window-system 'w32) ,(purecopy "yap"))
204 (t ,(purecopy "dvi2tty * | cat -s")))
205 "Command used by \\[tex-view] to display a `.dvi' file.
206 If it is a string, that specifies the command directly.
207 If this string contains an asterisk (`*'), that is replaced by the file name;
208 otherwise, the file name, preceded by a space, is added at the end.
209
210 If the value is a form, it is evaluated to get the command to use."
211 :type '(choice (const nil) string sexp)
212 :group 'tex-view)
213
214 ;;;###autoload
215 (defcustom tex-show-queue-command (purecopy "lpq")
216 "Command used by \\[tex-show-print-queue] to show the print queue.
217 Should show the queue(s) that \\[tex-print] puts jobs on."
218 :type 'string
219 :group 'tex-view)
220
221 ;;;###autoload
222 (defcustom tex-default-mode 'latex-mode
223 "Mode to enter for a new file that might be either TeX or LaTeX.
224 This variable is used when it can't be determined whether the file
225 is plain TeX or LaTeX or what because the file contains no commands.
226 Normally set to either `plain-tex-mode' or `latex-mode'."
227 :type 'function
228 :group 'tex)
229
230 ;;;###autoload
231 (defcustom tex-open-quote (purecopy "``")
232 "String inserted by typing \\[tex-insert-quote] to open a quotation."
233 :type 'string
234 :options '("``" "\"<" "\"`" "<<" "«")
235 :group 'tex)
236
237 ;;;###autoload
238 (defcustom tex-close-quote (purecopy "''")
239 "String inserted by typing \\[tex-insert-quote] to close a quotation."
240 :type 'string
241 :options '("''" "\">" "\"'" ">>" "»")
242 :group 'tex)
243
244 (defcustom tex-fontify-script t
245 "If non-nil, fontify subscript and superscript strings."
246 :type 'boolean
247 :group 'tex
248 :version "23.1")
249 (put 'tex-fontify-script 'safe-local-variable 'booleanp)
250
251 (defcustom tex-font-script-display '(-0.2 0.2)
252 "How much to lower and raise subscript and superscript content.
253 This is a list of two floats. The first is negative and
254 specifies how much subscript is lowered, the second is positive
255 and specifies how much superscript is raised. Heights are
256 measured relative to that of the normal text."
257 :group 'tex
258 :type '(list (float :tag "Subscript")
259 (float :tag "Superscript"))
260 :version "23.1")
261
262 (defvar tex-last-temp-file nil
263 "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
264 Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
265 tex shell terminates.")
266
267 (defvar tex-command "tex"
268 "Command to run TeX.
269 If this string contains an asterisk \(`*'), that is replaced by the file name;
270 otherwise the value of `tex-start-options', the \(shell-quoted)
271 value of `tex-start-commands', and the file name are added at the end
272 with blanks as separators.
273
274 In TeX, LaTeX, and SliTeX Mode this variable becomes buffer local.")
275
276 (defvar tex-trailer nil
277 "String appended after the end of a region sent to TeX by \\[tex-region].")
278
279 (defvar tex-start-of-header nil
280 "Regular expression used by \\[tex-region] to find start of file's header.")
281
282 (defvar tex-end-of-header nil
283 "Regular expression used by \\[tex-region] to find end of file's header.")
284
285 (defvar tex-shell-cd-command "cd"
286 "Command to give to shell running TeX to change directory.
287 The value of `tex-directory' is appended to this, separated by a space.")
288
289 (defvar tex-zap-file nil
290 "Temporary file name used for text being sent as input to TeX.
291 Should be a simple file name with no extension or directory specification.")
292
293 (defvar tex-last-buffer-texed nil
294 "Buffer which was last TeXed.")
295
296 (defvar tex-print-file nil
297 "File name that \\[tex-print] prints.
298 Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
299
300 (defvar tex-mode-syntax-table
301 (let ((st (make-syntax-table)))
302 (modify-syntax-entry ?% "<" st)
303 (modify-syntax-entry ?\n ">" st)
304 (modify-syntax-entry ?\f ">" st)
305 (modify-syntax-entry ?\C-@ "w" st)
306 (modify-syntax-entry ?' "w" st)
307 (modify-syntax-entry ?@ "_" st)
308 (modify-syntax-entry ?* "_" st)
309 (modify-syntax-entry ?\t " " st)
310 ;; ~ is printed by TeX as a space, but it's semantics in the syntax
311 ;; of TeX is not `whitespace' (i.e. it's just like \hspace{foo}).
312 (modify-syntax-entry ?~ "." st)
313 (modify-syntax-entry ?$ "$$" st)
314 (modify-syntax-entry ?\\ "/" st)
315 (modify-syntax-entry ?\" "." st)
316 (modify-syntax-entry ?& "." st)
317 (modify-syntax-entry ?_ "." st)
318 (modify-syntax-entry ?^ "." st)
319 st)
320 "Syntax table used while in TeX mode.")
321 \f
322 ;;;;
323 ;;;; Imenu support
324 ;;;;
325
326 (defcustom latex-imenu-indent-string ". "
327 "String to add repeated in front of nested sectional units for Imenu.
328 An alternative value is \" . \", if you use a font with a narrow period."
329 :type 'string
330 :group 'tex)
331
332 (defvar latex-section-alist
333 '(("part" . 0) ("chapter" . 1)
334 ("section" . 2) ("subsection" . 3)
335 ("subsubsection" . 4)
336 ("paragraph" . 5) ("subparagraph" . 6)))
337
338 (defvar latex-metasection-list
339 '("documentstyle" "documentclass"
340 "begin{document}" "end{document}"
341 "appendix" "frontmatter" "mainmatter" "backmatter"))
342
343 (defun latex-imenu-create-index ()
344 "Generate an alist for imenu from a LaTeX buffer."
345 (let ((section-regexp
346 (concat "\\\\" (regexp-opt (mapcar 'car latex-section-alist) t)
347 "\\*?[ \t]*{"))
348 (metasection-regexp
349 (concat "\\\\" (regexp-opt latex-metasection-list t)))
350 i0 menu case-fold-search)
351 (save-excursion
352 ;; Find the top-most level in this file but don't allow it to be
353 ;; any deeper than "section" (which is top-level in an article).
354 (goto-char (point-min))
355 (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t)
356 (setq i0 0)
357 (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
358 (setq i0 1)
359 (setq i0 2)))
360
361 ;; Look for chapters and sections.
362 (goto-char (point-min))
363 (while (search-forward-regexp section-regexp nil t)
364 (let ((start (match-beginning 0))
365 (here (point))
366 (i (cdr (assoc (buffer-substring-no-properties
367 (match-beginning 1)
368 (match-end 1))
369 latex-section-alist))))
370 (backward-char 1)
371 (condition-case nil
372 (progn
373 ;; Using sexps allows some use of matching {...} inside
374 ;; titles.
375 (forward-sexp 1)
376 (push (cons (concat (apply 'concat
377 (make-list
378 (max 0 (- i i0))
379 latex-imenu-indent-string))
380 (buffer-substring-no-properties
381 here (1- (point))))
382 start)
383 menu))
384 (error nil))))
385
386 ;; Look for included material.
387 (goto-char (point-min))
388 (while (search-forward-regexp
389 "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
390 [ \t]*{\\([^}\n]+\\)}"
391 nil t)
392 (push (cons (concat "<<" (buffer-substring-no-properties
393 (match-beginning 2)
394 (match-end 2))
395 (if (= (char-after (match-beginning 1)) ?b)
396 ".bbl"
397 ".tex"))
398 (match-beginning 0))
399 menu))
400
401 ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
402 (goto-char (point-min))
403 (while (search-forward-regexp metasection-regexp nil t)
404 (push (cons "--" (match-beginning 0)) menu))
405
406 ;; Sort in increasing buffer position order.
407 (sort menu (function (lambda (a b) (< (cdr a) (cdr b))))))))
408 \f
409 ;;;;
410 ;;;; Outline support
411 ;;;;
412
413 (defvar latex-outline-regexp
414 (concat "\\\\"
415 (regexp-opt (append latex-metasection-list
416 (mapcar 'car latex-section-alist)) t)))
417
418 (defun latex-outline-level ()
419 (if (looking-at latex-outline-regexp)
420 (1+ (or (cdr (assoc (match-string 1) latex-section-alist)) -1))
421 1000))
422
423 (defun tex-current-defun-name ()
424 "Return the name of the TeX section/paragraph/chapter at point, or nil."
425 (save-excursion
426 (when (re-search-backward
427 "\\\\\\(sub\\)*\\(section\\|paragraph\\|chapter\\)"
428 nil t)
429 (goto-char (match-beginning 0))
430 (buffer-substring-no-properties
431 (1+ (point)) ; without initial backslash
432 (line-end-position)))))
433 \f
434 ;;;;
435 ;;;; Font-Lock support
436 ;;;;
437
438 ;(defvar tex-font-lock-keywords
439 ; ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
440 ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
441 ; 2 font-lock-function-name-face)
442 ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
443 ; 2 font-lock-constant-face)
444 ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
445 ; ;; not be able to display those fonts.
446 ; ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
447 ; ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
448 ; ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
449 ; ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
450 ; ;; Rewritten and extended for LaTeX2e by Ulrik Dickow <dickow@nbi.dk>.
451 ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
452 ; 2 font-lock-function-name-face)
453 ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
454 ; 2 font-lock-constant-face)
455 ; ("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)" 1 font-lock-function-name-face)
456 ; "\\\\\\([a-zA-Z@]+\\|.\\)"
457 ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
458 ; ;; not be able to display those fonts.
459 ; ;; LaTeX2e: \emph{This is emphasized}.
460 ; ("\\\\emph{\\([^}]+\\)}" 1 'italic keep)
461 ; ;; LaTeX2e: \textbf{This is bold}, \textit{...}, \textsl{...}
462 ; ("\\\\text\\(\\(bf\\)\\|it\\|sl\\){\\([^}]+\\)}"
463 ; 3 (if (match-beginning 2) 'bold 'italic) keep)
464 ; ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
465 ; ("\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)"
466 ; 3 (if (match-beginning 2) 'bold 'italic) keep))
467
468 ;; Rewritten with the help of Alexandra Bac <abac@welcome.disi.unige.it>.
469 (defconst tex-font-lock-keywords-1
470 (eval-when-compile
471 (let* (;; Names of commands whose arg should be fontified as heading, etc.
472 (headings (regexp-opt
473 '("title" "begin" "end" "chapter" "part"
474 "section" "subsection" "subsubsection"
475 "paragraph" "subparagraph" "subsubparagraph"
476 "newcommand" "renewcommand" "providecommand"
477 "newenvironment" "renewenvironment"
478 "newtheorem" "renewtheorem")
479 t))
480 (variables (regexp-opt
481 '("newcounter" "newcounter*" "setcounter" "addtocounter"
482 "setlength" "addtolength" "settowidth")
483 t))
484 (includes (regexp-opt
485 '("input" "include" "includeonly" "bibliography"
486 "epsfig" "psfig" "epsf" "nofiles" "usepackage"
487 "documentstyle" "documentclass" "verbatiminput"
488 "includegraphics" "includegraphics*")
489 t))
490 (verbish (regexp-opt '("url" "nolinkurl" "path") t))
491 ;; Miscellany.
492 (slash "\\\\")
493 (opt " *\\(\\[[^]]*\\] *\\)*")
494 ;; This would allow highlighting \newcommand\CMD but requires
495 ;; adapting subgroup numbers below.
496 ;; (arg "\\(?:{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)\\|\\\\[a-z*]+\\)"))
497 (inbraces-re (lambda (re)
498 (concat "\\(?:[^{}\\]\\|\\\\.\\|" re "\\)")))
499 (arg (concat "{\\(" (funcall inbraces-re "{[^}]*}") "+\\)")))
500 `( ;; Highlight $$math$$ and $math$.
501 ;; This is done at the very beginning so as to interact with the other
502 ;; keywords in the same way as comments and strings.
503 (,(concat "\\$\\$?\\(?:[^$\\{}]\\|\\\\.\\|{"
504 (funcall inbraces-re
505 (concat "{" (funcall inbraces-re "{[^}]*}") "*}"))
506 "*}\\)+\\$?\\$")
507 (0 tex-math-face))
508 ;; Heading args.
509 (,(concat slash headings "\\*?" opt arg)
510 ;; If ARG ends up matching too much (if the {} don't match, e.g.)
511 ;; jit-lock will do funny things: when updating the buffer
512 ;; the re-highlighting is only done locally so it will just
513 ;; match the local line, but defer-contextually will
514 ;; match more lines at a time, so ARG will end up matching
515 ;; a lot more, which might suddenly include a comment
516 ;; so you get things highlighted bold when you type them
517 ;; but they get turned back to normal a little while later
518 ;; because "there's already a face there".
519 ;; Using `keep' works around this un-intuitive behavior as well
520 ;; as improves the behavior in the very rare case where you do
521 ;; have a comment in ARG.
522 3 font-lock-function-name-face keep)
523 (,(concat slash "\\(?:provide\\|\\(?:re\\)?new\\)command\\** *\\(\\\\[A-Za-z@]+\\)")
524 1 font-lock-function-name-face keep)
525 ;; Variable args.
526 (,(concat slash variables " *" arg) 2 font-lock-variable-name-face)
527 ;; Include args.
528 (,(concat slash includes opt arg) 3 font-lock-builtin-face)
529 ;; Verbatim-like args.
530 (,(concat slash verbish opt arg) 3 'tex-verbatim)
531 ;; Definitions. I think.
532 ("^[ \t]*\\\\def *\\\\\\(\\(\\w\\|@\\)+\\)"
533 1 font-lock-function-name-face))))
534 "Subdued expressions to highlight in TeX modes.")
535
536 (defun tex-font-lock-append-prop (prop)
537 (unless (memq (get-text-property (match-end 1) 'face)
538 '(font-lock-comment-face tex-verbatim))
539 prop))
540
541 (defconst tex-font-lock-keywords-2
542 (append tex-font-lock-keywords-1
543 (eval-when-compile
544 (let* (;;
545 ;; Names of commands whose arg should be fontified with fonts.
546 (bold (regexp-opt '("textbf" "textsc" "textup"
547 "boldsymbol" "pmb") t))
548 (italic (regexp-opt '("textit" "textsl" "emph") t))
549 ;; FIXME: unimplemented yet.
550 ;; (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
551 ;;
552 ;; Names of commands whose arg should be fontified as a citation.
553 (citations (regexp-opt
554 '("label" "ref" "pageref" "vref" "eqref"
555 "cite" "nocite" "index" "glossary" "bibitem"
556 ;; natbib's two variants of \cite:
557 "citep" "citet"
558 ;; These are text, rather than citations.
559 ;; "caption" "footnote" "footnotemark" "footnotetext"
560 )
561 t))
562 ;;
563 ;; Names of commands that should be fontified.
564 (specials-1 (regexp-opt '("\\" "\\*") t)) ;; "-"
565 (specials-2 (regexp-opt
566 '("linebreak" "nolinebreak" "pagebreak" "nopagebreak"
567 "newline" "newpage" "clearpage" "cleardoublepage"
568 "displaybreak" "allowdisplaybreaks"
569 "enlargethispage") t))
570 (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
571 ;;
572 ;; Miscellany.
573 (slash "\\\\")
574 (opt " *\\(\\[[^]]*\\] *\\)*")
575 (args "\\(\\(?:[^{}&\\]+\\|\\\\.\\|{[^}]*}\\)+\\)")
576 (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
577 (list
578 ;;
579 ;; Citation args.
580 (list (concat slash citations opt arg) 3 'font-lock-constant-face)
581 ;;
582 ;; Text between `` quotes ''.
583 (cons (concat (regexp-opt `("``" "\"<" "\"`" "<<" "«") t)
584 "[^'\">{]+" ;a bit pessimistic
585 (regexp-opt `("''" "\">" "\"'" ">>" "»") t))
586 'font-lock-string-face)
587 ;;
588 ;; Command names, special and general.
589 (cons (concat slash specials-1) 'font-lock-warning-face)
590 (list (concat "\\(" slash specials-2 "\\)\\([^a-zA-Z@]\\|\\'\\)")
591 1 'font-lock-warning-face)
592 (concat slash general)
593 ;;
594 ;; Font environments. It seems a bit dubious to use `bold' etc. faces
595 ;; since we might not be able to display those fonts.
596 (list (concat slash bold " *" arg) 2
597 '(tex-font-lock-append-prop 'bold) 'append)
598 (list (concat slash italic " *" arg) 2
599 '(tex-font-lock-append-prop 'italic) 'append)
600 ;; (list (concat slash type arg) 2 '(quote bold-italic) 'append)
601 ;;
602 ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
603 (list (concat "\\\\\\(em\\|it\\|sl\\)\\>" args)
604 2 '(tex-font-lock-append-prop 'italic) 'append)
605 ;; This is separate from the previous one because of cases like
606 ;; {\em foo {\bf bar} bla} where both match.
607 (list (concat "\\\\\\(bf\\(series\\)?\\)\\>" args)
608 3 '(tex-font-lock-append-prop 'bold) 'append)))))
609 "Gaudy expressions to highlight in TeX modes.")
610
611 (defun tex-font-lock-suscript (pos)
612 (unless (or (memq (get-text-property pos 'face)
613 '(font-lock-constant-face font-lock-builtin-face
614 font-lock-comment-face tex-verbatim))
615 ;; Check for backslash quoting
616 (let ((odd nil)
617 (pos pos))
618 (while (eq (char-before pos) ?\\)
619 (setq pos (1- pos) odd (not odd)))
620 odd))
621 (if (eq (char-after pos) ?_)
622 `(face subscript display (raise ,(car tex-font-script-display)))
623 `(face superscript display (raise ,(cadr tex-font-script-display))))))
624
625 (defun tex-font-lock-match-suscript (limit)
626 "Match subscript and superscript patterns up to LIMIT."
627 (when (and tex-fontify-script
628 (re-search-forward "[_^] *\\([^\n\\{}]\\|\
629 \\\\\\([a-zA-Z@]+\\|[^ \t\n]\\)\\|\\({\\)\\)" limit t))
630 (when (match-end 3)
631 (let ((beg (match-beginning 3))
632 (end (save-restriction
633 (narrow-to-region (point-min) limit)
634 (condition-case nil (scan-lists (point) 1 1) (error nil)))))
635 (store-match-data (if end
636 (list (match-beginning 0) end beg end)
637 (list beg beg beg beg)))))
638 t))
639
640 (defconst tex-font-lock-keywords-3
641 (append tex-font-lock-keywords-2
642 '((tex-font-lock-match-suscript
643 (1 (tex-font-lock-suscript (match-beginning 0)) append))))
644 "Experimental expressions to highlight in TeX modes.")
645
646 (defconst tex-font-lock-keywords tex-font-lock-keywords-1
647 "Default expressions to highlight in TeX modes.")
648
649 (defvar tex-verbatim-environments
650 '("verbatim" "verbatim*"))
651 (put 'tex-verbatim-environments 'safe-local-variable
652 (lambda (x) (null (delq t (mapcar 'stringp x)))))
653
654 (eval-when-compile
655 (defconst tex-syntax-propertize-rules
656 (syntax-propertize-precompile-rules
657 ("\\\\verb\\**\\([^a-z@*]\\)"
658 (1 (prog1 "\""
659 (tex-font-lock-verb
660 (match-beginning 0) (char-after (match-beginning 1))))))))
661
662 (defconst latex-syntax-propertize-rules
663 (syntax-propertize-precompile-rules
664 tex-syntax-propertize-rules
665 ("\\\\\\(?:end\\|begin\\) *\\({[^\n{}]*}\\)"
666 (1 (ignore
667 (tex-env-mark (match-beginning 0)
668 (match-beginning 1) (match-end 1))))))))
669
670 (defun tex-env-mark (cmd start end)
671 (when (= cmd (line-beginning-position))
672 (let ((arg (buffer-substring-no-properties (1+ start) (1- end))))
673 (when (member arg tex-verbatim-environments)
674 (if (eq ?b (char-after (1+ cmd)))
675 ;; \begin
676 (put-text-property (line-end-position)
677 (line-beginning-position 2)
678 'syntax-table (string-to-syntax "< c"))
679 ;; In the case of an empty verbatim env, the \n after the \begin is
680 ;; the same as the \n before the \end. Lucky for us, the "> c"
681 ;; property associated to the \end will be placed afterwards, so it
682 ;; will override the "< c".
683 (put-text-property (1- cmd) cmd
684 'syntax-table (string-to-syntax "> c"))
685 ;; The text between \end{verbatim} and \n is ignored, so we'll treat
686 ;; it as a comment.
687 (put-text-property end (min (1+ end) (line-end-position))
688 'syntax-table (string-to-syntax "<"))))))
689 ;; Mark env args for possible electric pairing.
690 (unless (get-char-property (1+ start) 'text-clones) ;Already paired-up.
691 (put-text-property start end 'latex-env-pair t)))
692
693 (define-minor-mode latex-electric-env-pair-mode
694 "Toggle Latex Electric Env Pair mode.
695 With a prefix argument ARG, enable the mode if ARG is positive,
696 and disable it otherwise. If called from Lisp, enable it if ARG
697 is omitted or nil.
698
699 Latex Electric Env Pair mode is a buffer-local minor mode for use
700 with `latex-mode'. When enabled, typing a \\begin or \\end tag
701 automatically inserts its partner."
702 :lighter "/e"
703 (if latex-electric-env-pair-mode
704 (add-hook 'before-change-functions
705 #'latex-env-before-change nil 'local)
706 (remove-hook 'before-change-functions
707 #'latex-env-before-change 'local)))
708
709 (defun latex-env-before-change (start end)
710 (when (get-text-property start 'latex-env-pair)
711 (condition-case err
712 (with-silent-modifications
713 ;; Remove properties even if don't find a pair.
714 (remove-text-properties
715 (previous-single-property-change (1+ start) 'latex-env-pair)
716 (next-single-property-change start 'latex-env-pair)
717 '(latex-env-pair))
718 (unless (or (get-char-property start 'text-clones)
719 (get-char-property (1+ start) 'text-clones)
720 (save-excursion
721 (goto-char start)
722 (not (re-search-backward
723 "\\\\\\(?:end\\|begi\\(n\\)\\) *{"
724 (line-beginning-position) t))))
725 (let ((cmd-start (match-beginning 0))
726 (type (match-end 1)) ;nil for \end, else \begin.
727 (arg-start (1- (match-end 0))))
728 (save-excursion
729 (goto-char (match-end 0))
730 (when (and (looking-at "[^\n{}]*}")
731 (> (match-end 0) end))
732 (let ((arg-end (match-end 0)))
733 (if (null type) ;\end
734 (progn (goto-char arg-end)
735 (latex-forward-sexp -1)
736 (forward-word-strictly 1))
737 (goto-char cmd-start)
738 (latex-forward-sexp 1)
739 (let (forward-sexp-function) (backward-sexp)))
740 (when (looking-at
741 (regexp-quote (buffer-substring arg-start arg-end)))
742 (text-clone-create arg-start arg-end))))))))
743 (scan-error nil)
744 (error (message "Error in latex-env-before-change: %s" err)))))
745
746 (defun tex-font-lock-unfontify-region (beg end)
747 (font-lock-default-unfontify-region beg end)
748 (while (< beg end)
749 (let ((next (next-single-property-change beg 'display nil end))
750 (prop (get-text-property beg 'display)))
751 (if (and (eq (car-safe prop) 'raise)
752 (member (car-safe (cdr prop)) tex-font-script-display)
753 (null (cddr prop)))
754 (put-text-property beg next 'display nil))
755 (setq beg next))))
756
757 (defcustom tex-suscript-height-ratio 0.8
758 "Ratio of subscript/superscript height to that of the preceding text.
759 In nested subscript/superscript, this factor is applied repeatedly,
760 subject to the limit set by `tex-suscript-height-minimum'."
761 :type 'float
762 :group 'tex
763 :version "23.1")
764
765 (defcustom tex-suscript-height-minimum 0.0
766 "Integer or float limiting the minimum size of subscript/superscript text.
767 An integer is an absolute height in units of 1/10 point, a float
768 is a height relative to that of the default font. Zero means no minimum."
769 :type '(choice (integer :tag "Integer height in 1/10 point units")
770 (float :tag "Fraction of default font height"))
771 :group 'tex
772 :version "23.1")
773
774 (defun tex-suscript-height (height)
775 "Return the integer height of subscript/superscript font in 1/10 points.
776 Not smaller than the value set by `tex-suscript-height-minimum'."
777 (ceiling (max (if (integerp tex-suscript-height-minimum)
778 tex-suscript-height-minimum
779 ;; For bootstrapping.
780 (condition-case nil
781 (* tex-suscript-height-minimum
782 (face-attribute 'default :height))
783 (error 0)))
784 ;; NB assumes height is integer.
785 (* height tex-suscript-height-ratio))))
786
787 (defface superscript
788 '((t :height tex-suscript-height)) ;; :raise 0.2
789 "Face used for superscripts."
790 :group 'tex)
791 (defface subscript
792 '((t :height tex-suscript-height)) ;; :raise -0.2
793 "Face used for subscripts."
794 :group 'tex)
795
796 (defface tex-math
797 '((t :inherit font-lock-string-face))
798 "Face used to highlight TeX math expressions."
799 :group 'tex)
800 (define-obsolete-face-alias 'tex-math-face 'tex-math "22.1")
801 (defvar tex-math-face 'tex-math)
802
803 (defface tex-verbatim
804 ;; '((t :inherit font-lock-string-face))
805 '((t :family "courier"))
806 "Face used to highlight TeX verbatim environments."
807 :group 'tex)
808 (define-obsolete-face-alias 'tex-verbatim-face 'tex-verbatim "22.1")
809 (defvar tex-verbatim-face 'tex-verbatim)
810
811 (defun tex-font-lock-verb (start delim)
812 "Place syntax table properties on the \\verb construct.
813 START is the position of the \\ and DELIM is the delimiter char."
814 ;; Do nothing if the \verb construct is itself inside a comment or
815 ;; verbatim env.
816 (unless (nth 8 (save-excursion (syntax-ppss start)))
817 ;; Let's find the end and mark it.
818 (let ((afterdelim (point)))
819 (skip-chars-forward (string ?^ delim) (line-end-position))
820 (if (eolp)
821 ;; "LaTeX Error: \verb ended by end of line."
822 ;; Remove the syntax-table property we've just put on the
823 ;; start-delimiter, so it doesn't spill over subsequent lines.
824 (put-text-property (1- afterdelim) afterdelim
825 'syntax-table nil)
826 (when (eq (char-syntax (preceding-char)) ?/)
827 (put-text-property (1- (point)) (point)
828 'syntax-table (string-to-syntax ".")))
829 (put-text-property (point) (1+ (point))
830 'syntax-table (string-to-syntax "\""))))))
831
832 ;; Use string syntax but math face for $...$.
833 (defun tex-font-lock-syntactic-face-function (state)
834 (let ((char (nth 3 state)))
835 (cond
836 ((not char)
837 (if (eq 2 (nth 7 state)) tex-verbatim-face font-lock-comment-face))
838 ((eq char ?$) tex-math-face)
839 ;; A \verb element.
840 (t tex-verbatim-face))))
841
842 \f
843 (defun tex-define-common-keys (keymap)
844 "Define the keys that we want defined both in TeX mode and in the TeX shell."
845 (define-key keymap "\C-c\C-k" 'tex-kill-job)
846 (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
847 (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
848 (define-key keymap "\C-c\C-p" 'tex-print)
849 (define-key keymap "\C-c\C-v" 'tex-view)
850
851 (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
852
853 (define-key keymap [menu-bar tex tex-kill-job]
854 '(menu-item "Tex Kill" tex-kill-job :enable (tex-shell-running)))
855 (define-key keymap [menu-bar tex tex-recenter-output-buffer]
856 '(menu-item "Tex Recenter" tex-recenter-output-buffer
857 :enable (get-buffer "*tex-shell*")))
858 (define-key keymap [menu-bar tex tex-show-print-queue]
859 '("Show Print Queue" . tex-show-print-queue))
860 (define-key keymap [menu-bar tex tex-alt-print]
861 '(menu-item "Tex Print (alt printer)" tex-alt-print
862 :enable (stringp tex-print-file)))
863 (define-key keymap [menu-bar tex tex-print]
864 '(menu-item "Tex Print" tex-print :enable (stringp tex-print-file)))
865 (define-key keymap [menu-bar tex tex-view]
866 '(menu-item "Tex View" tex-view :enable (stringp tex-print-file))))
867
868 (defvar tex-mode-map
869 (let ((map (make-sparse-keymap)))
870 (set-keymap-parent map text-mode-map)
871 (tex-define-common-keys map)
872 (define-key map "\"" 'tex-insert-quote)
873 (define-key map "\n" 'tex-terminate-paragraph)
874 (define-key map "\M-\r" 'latex-insert-item)
875 (define-key map "\C-c}" 'up-list)
876 (define-key map "\C-c{" 'tex-insert-braces)
877 (define-key map "\C-c\C-r" 'tex-region)
878 (define-key map "\C-c\C-b" 'tex-buffer)
879 (define-key map "\C-c\C-f" 'tex-file)
880 (define-key map "\C-c\C-c" 'tex-compile)
881 (define-key map "\C-c\C-i" 'tex-bibtex-file)
882 (define-key map "\C-c\C-o" 'latex-insert-block)
883
884 ;; Redundant keybindings, for consistency with SGML mode.
885 (define-key map "\C-c\C-t" 'latex-insert-block)
886 (define-key map "\C-c]" 'latex-close-block)
887 (define-key map "\C-c/" 'latex-close-block)
888
889 (define-key map "\C-c\C-e" 'latex-close-block)
890 (define-key map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
891 (define-key map "\C-c\C-m" 'tex-feed-input)
892 (define-key map [(control return)] 'tex-feed-input)
893 (define-key map [menu-bar tex tex-bibtex-file]
894 '("BibTeX File" . tex-bibtex-file))
895 (define-key map [menu-bar tex tex-validate-region]
896 '(menu-item "Validate Region" tex-validate-region :enable mark-active))
897 (define-key map [menu-bar tex tex-validate-buffer]
898 '("Validate Buffer" . tex-validate-buffer))
899 (define-key map [menu-bar tex tex-region]
900 '(menu-item "TeX Region" tex-region :enable mark-active))
901 (define-key map [menu-bar tex tex-buffer]
902 '("TeX Buffer" . tex-buffer))
903 (define-key map [menu-bar tex tex-file] '("TeX File" . tex-file))
904 map)
905 "Keymap shared by TeX modes.")
906
907 (defvar latex-mode-map
908 (let ((map (make-sparse-keymap)))
909 (set-keymap-parent map tex-mode-map)
910 (define-key map "\C-c\C-s" 'latex-split-block)
911 map)
912 "Keymap for `latex-mode'. See also `tex-mode-map'.")
913
914 (defvar plain-tex-mode-map
915 (let ((map (make-sparse-keymap)))
916 (set-keymap-parent map tex-mode-map)
917 map)
918 "Keymap for `plain-tex-mode'. See also `tex-mode-map'.")
919
920 (defvar tex-shell-map
921 (let ((m (make-sparse-keymap)))
922 (set-keymap-parent m shell-mode-map)
923 (tex-define-common-keys m)
924 m)
925 "Keymap for the TeX shell.
926 Inherits `shell-mode-map' with a few additions.")
927
928 (defvar tex-face-alist
929 '((bold . "{\\bf ")
930 (italic . "{\\it ")
931 (bold-italic . "{\\bi ") ; hypothetical
932 (underline . "\\underline{")
933 (default . "{\\rm "))
934 "Alist of face and TeX font name for facemenu.")
935
936 (defvar tex-latex-face-alist
937 `((italic . "{\\em ")
938 ,@tex-face-alist)
939 "Alist of face and LaTeX font name for facemenu.")
940
941 (defun tex-facemenu-add-face-function (face _end)
942 (or (cdr (assq face tex-face-alist))
943 (or (and (consp face)
944 (consp (car face))
945 (null (cdr face))
946 (eq major-mode 'latex-mode)
947 ;; This actually requires the `color' LaTeX package.
948 (cond ((eq (caar face) :foreground)
949 (format "{\\color{%s} " (cadr (car face))))
950 ((eq (caar face) :background)
951 (format "\\colorbox{%s}{" (cadr (car face))))))
952 (error "Face %s not configured for %s mode" face mode-name))))
953
954 ;; This would be a lot simpler if we just used a regexp search,
955 ;; but then it would be too slow.
956 (defun tex-guess-mode ()
957 (let ((mode tex-default-mode) slash comment)
958 (save-excursion
959 (goto-char (point-min))
960 (while (and (setq slash (search-forward "\\" nil t))
961 (setq comment (let ((search-end (point)))
962 (save-excursion
963 (beginning-of-line)
964 (search-forward "%" search-end t))))))
965 (when (and slash (not comment))
966 (setq mode
967 (if (looking-at
968 (eval-when-compile
969 (concat
970 (regexp-opt '("documentstyle" "documentclass"
971 "begin" "subsection" "section"
972 "part" "chapter" "newcommand"
973 "renewcommand" "RequirePackage") 'words)
974 "\\|NeedsTeXFormat{LaTeX")))
975 (if (and (looking-at
976 "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
977 ;; SliTeX is almost never used any more nowadays.
978 (tex-executable-exists-p slitex-run-command))
979 'slitex-mode
980 'latex-mode)
981 'plain-tex-mode))))
982 (funcall mode)))
983
984 ;; `tex-mode' plays two roles: it's the parent of several sub-modes
985 ;; but it's also the function that chooses between those submodes.
986 ;; To tell the difference between those two cases where the function
987 ;; might be called, we check `delay-mode-hooks'.
988 (define-derived-mode tex-mode text-mode "generic-TeX"
989 (tex-common-initialization))
990 ;; We now move the function and define it again. This gives a warning
991 ;; in the byte-compiler :-( but it's difficult to avoid because
992 ;; `define-derived-mode' will necessarily define the function once
993 ;; and we need to define it a second time for `autoload' to get the
994 ;; proper docstring.
995 (defalias 'tex-mode-internal (symbol-function 'tex-mode))
996
997 ;; Suppress the byte-compiler warning about multiple definitions.
998 ;; This is a) ugly, and b) cheating, but this was the last
999 ;; remaining warning from byte-compiling all of Emacs...
1000 (eval-when-compile
1001 (setq byte-compile-function-environment
1002 (delq (assq 'tex-mode byte-compile-function-environment)
1003 byte-compile-function-environment)))
1004
1005 ;;;###autoload
1006 (defun tex-mode ()
1007 "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
1008 Tries to determine (by looking at the beginning of the file) whether
1009 this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
1010 `latex-mode', or `slitex-mode', respectively. If it cannot be determined,
1011 such as if there are no commands in the file, the value of `tex-default-mode'
1012 says which mode to use."
1013 (interactive)
1014 (if delay-mode-hooks
1015 ;; We're called from one of the children already.
1016 (tex-mode-internal)
1017 (tex-guess-mode)))
1018
1019 ;; The following three autoloaded aliases appear to conflict with
1020 ;; AUCTeX. However, even though AUCTeX uses the mixed case variants
1021 ;; for all mode relevant variables and hooks, the invocation function
1022 ;; and setting of `major-mode' themselves need to be lowercase for
1023 ;; AUCTeX to provide a fully functional user-level replacement. So
1024 ;; these aliases should remain as they are, in particular since AUCTeX
1025 ;; users are likely to use them.
1026
1027 ;;;###autoload
1028 (defalias 'TeX-mode 'tex-mode)
1029 ;;;###autoload
1030 (defalias 'plain-TeX-mode 'plain-tex-mode)
1031 ;;;###autoload
1032 (defalias 'LaTeX-mode 'latex-mode)
1033
1034 ;;;###autoload
1035 (define-derived-mode plain-tex-mode tex-mode "TeX"
1036 "Major mode for editing files of input for plain TeX.
1037 Makes $ and } display the characters they match.
1038 Makes \" insert \\=`\\=` when it seems to be the beginning of a quotation,
1039 and \\='\\=' when it appears to be the end; it inserts \" only after a \\.
1040
1041 Use \\[tex-region] to run TeX on the current region, plus a \"header\"
1042 copied from the top of the file (containing macro definitions, etc.),
1043 running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
1044 \\[tex-file] saves the buffer and then processes the file.
1045 \\[tex-print] prints the .dvi file made by any of these.
1046 \\[tex-view] previews the .dvi file made by any of these.
1047 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1048
1049 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1050 mismatched $'s or braces.
1051
1052 Special commands:
1053 \\{plain-tex-mode-map}
1054
1055 Mode variables:
1056 tex-run-command
1057 Command string used by \\[tex-region] or \\[tex-buffer].
1058 tex-directory
1059 Directory in which to create temporary files for TeX jobs
1060 run by \\[tex-region] or \\[tex-buffer].
1061 tex-dvi-print-command
1062 Command string used by \\[tex-print] to print a .dvi file.
1063 tex-alt-dvi-print-command
1064 Alternative command string used by \\[tex-print] (when given a prefix
1065 argument) to print a .dvi file.
1066 tex-dvi-view-command
1067 Command string used by \\[tex-view] to preview a .dvi file.
1068 tex-show-queue-command
1069 Command string used by \\[tex-show-print-queue] to show the print
1070 queue that \\[tex-print] put your job on.
1071
1072 Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
1073 `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
1074 special subshell is initiated, the hook `tex-shell-hook' is run."
1075 (setq-local tex-command tex-run-command)
1076 (setq-local tex-start-of-header "%\\*\\*start of header")
1077 (setq-local tex-end-of-header "%\\*\\*end of header")
1078 (setq-local tex-trailer "\\bye\n"))
1079
1080 ;;;###autoload
1081 (define-derived-mode latex-mode tex-mode "LaTeX"
1082 "Major mode for editing files of input for LaTeX.
1083 Makes $ and } display the characters they match.
1084 Makes \" insert \\=`\\=` when it seems to be the beginning of a quotation,
1085 and \\='\\=' when it appears to be the end; it inserts \" only after a \\.
1086
1087 Use \\[tex-region] to run LaTeX on the current region, plus the preamble
1088 copied from the top of the file (containing \\documentstyle, etc.),
1089 running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
1090 \\[tex-file] saves the buffer and then processes the file.
1091 \\[tex-print] prints the .dvi file made by any of these.
1092 \\[tex-view] previews the .dvi file made by any of these.
1093 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1094
1095 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1096 mismatched $'s or braces.
1097
1098 Special commands:
1099 \\{latex-mode-map}
1100
1101 Mode variables:
1102 latex-run-command
1103 Command string used by \\[tex-region] or \\[tex-buffer].
1104 tex-directory
1105 Directory in which to create temporary files for LaTeX jobs
1106 run by \\[tex-region] or \\[tex-buffer].
1107 tex-dvi-print-command
1108 Command string used by \\[tex-print] to print a .dvi file.
1109 tex-alt-dvi-print-command
1110 Alternative command string used by \\[tex-print] (when given a prefix
1111 argument) to print a .dvi file.
1112 tex-dvi-view-command
1113 Command string used by \\[tex-view] to preview a .dvi file.
1114 tex-show-queue-command
1115 Command string used by \\[tex-show-print-queue] to show the print
1116 queue that \\[tex-print] put your job on.
1117
1118 Entering Latex mode runs the hook `text-mode-hook', then
1119 `tex-mode-hook', and finally `latex-mode-hook'. When the special
1120 subshell is initiated, `tex-shell-hook' is run."
1121 (setq-local tex-command latex-run-command)
1122 (setq-local tex-start-of-header "\\\\document\\(style\\|class\\)")
1123 (setq-local tex-end-of-header "\\\\begin\\s-*{document}")
1124 (setq-local tex-trailer "\\end{document}\n")
1125 ;; A line containing just $$ is treated as a paragraph separator.
1126 ;; A line starting with $$ starts a paragraph,
1127 ;; but does not separate paragraphs if it has more stuff on it.
1128 (setq paragraph-start
1129 (concat "[ \t]*\\(\\$\\$\\|"
1130 "\\\\[][]\\|"
1131 "\\\\" (regexp-opt (append
1132 (mapcar 'car latex-section-alist)
1133 '("begin" "label" "end"
1134 "item" "bibitem" "newline" "noindent"
1135 "newpage" "footnote" "marginpar"
1136 "parbox" "caption")) t)
1137 "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
1138 "\\>\\)"))
1139 (setq paragraph-separate
1140 (concat "[\f%]\\|[ \t]*\\($\\|"
1141 "\\\\[][]\\|"
1142 "\\\\" (regexp-opt (append
1143 (mapcar 'car latex-section-alist)
1144 '("begin" "label" "end" )) t)
1145 "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
1146 "noindent" "newpage" "footnote"
1147 "marginpar" "parbox" "caption"))
1148 "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
1149 "\\>\\)[ \t]*\\($\\|%\\)\\)"))
1150 (setq-local imenu-create-index-function 'latex-imenu-create-index)
1151 (setq-local tex-face-alist tex-latex-face-alist)
1152 (add-hook 'fill-nobreak-predicate 'latex-fill-nobreak-predicate nil t)
1153 (setq-local indent-line-function 'latex-indent)
1154 (setq-local fill-indent-according-to-mode t)
1155 (add-hook 'completion-at-point-functions
1156 'latex-complete-data nil 'local)
1157 (setq-local outline-regexp latex-outline-regexp)
1158 (setq-local outline-level 'latex-outline-level)
1159 (setq-local forward-sexp-function 'latex-forward-sexp)
1160 (setq-local skeleton-end-hook nil))
1161
1162 ;;;###autoload
1163 (define-derived-mode slitex-mode latex-mode "SliTeX"
1164 "Major mode for editing files of input for SliTeX.
1165 Makes $ and } display the characters they match.
1166 Makes \" insert \\=`\\=` when it seems to be the beginning of a quotation,
1167 and \\='\\=' when it appears to be the end; it inserts \" only after a \\.
1168
1169 Use \\[tex-region] to run SliTeX on the current region, plus the preamble
1170 copied from the top of the file (containing \\documentstyle, etc.),
1171 running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
1172 \\[tex-file] saves the buffer and then processes the file.
1173 \\[tex-print] prints the .dvi file made by any of these.
1174 \\[tex-view] previews the .dvi file made by any of these.
1175 \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
1176
1177 Use \\[tex-validate-buffer] to check buffer for paragraphs containing
1178 mismatched $'s or braces.
1179
1180 Special commands:
1181 \\{slitex-mode-map}
1182
1183 Mode variables:
1184 slitex-run-command
1185 Command string used by \\[tex-region] or \\[tex-buffer].
1186 tex-directory
1187 Directory in which to create temporary files for SliTeX jobs
1188 run by \\[tex-region] or \\[tex-buffer].
1189 tex-dvi-print-command
1190 Command string used by \\[tex-print] to print a .dvi file.
1191 tex-alt-dvi-print-command
1192 Alternative command string used by \\[tex-print] (when given a prefix
1193 argument) to print a .dvi file.
1194 tex-dvi-view-command
1195 Command string used by \\[tex-view] to preview a .dvi file.
1196 tex-show-queue-command
1197 Command string used by \\[tex-show-print-queue] to show the print
1198 queue that \\[tex-print] put your job on.
1199
1200 Entering SliTeX mode runs the hook `text-mode-hook', then the hook
1201 `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
1202 `slitex-mode-hook'. When the special subshell is initiated, the hook
1203 `tex-shell-hook' is run."
1204 (setq tex-command slitex-run-command)
1205 (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
1206
1207 (defvar tildify-space-string)
1208 (defvar tildify-foreach-region-function)
1209 (defvar tex--prettify-symbols-alist)
1210
1211 (defun tex-common-initialization ()
1212 ;; Regexp isearch should accept newline and formfeed as whitespace.
1213 (setq-local search-whitespace-regexp "[ \t\r\n\f]+")
1214 ;; Use tilde as hard-space character in tildify package.
1215 (setq-local tildify-space-string "~")
1216 ;; FIXME: Use the fact that we're parsing the document already
1217 ;; rather than using regex-based filtering.
1218 (setq-local tildify-foreach-region-function
1219 (apply-partially
1220 'tildify-foreach-ignore-environments
1221 `(("\\\\\\\\" . "") ; do not remove this
1222 (,(eval-when-compile
1223 (concat "\\\\begin{\\("
1224 (regexp-opt '("verbatim" "math" "displaymath"
1225 "equation" "eqnarray" "eqnarray*"))
1226 "\\)}"))
1227 . ("\\\\end{" 1 "}"))
1228 ("\\\\verb\\*?\\(.\\)" . (1))
1229 ("\\$\\$?" . (0))
1230 ("\\\\(" . "\\\\)")
1231 ("\\\\[[]" . "\\\\[]]")
1232 ("\\\\[a-zA-Z]+\\( +\\|{}\\)[a-zA-Z]*" . "")
1233 ("%" . "$"))))
1234 ;; A line containing just $$ is treated as a paragraph separator.
1235 (setq-local paragraph-start "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
1236 ;; A line starting with $$ starts a paragraph,
1237 ;; but does not separate paragraphs if it has more stuff on it.
1238 (setq-local paragraph-separate "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
1239 (setq-local add-log-current-defun-function #'tex-current-defun-name)
1240 (setq-local comment-start "%")
1241 (setq-local comment-add 1)
1242 (setq-local comment-start-skip
1243 "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
1244 (setq-local parse-sexp-ignore-comments t)
1245 (setq-local compare-windows-whitespace 'tex-categorize-whitespace)
1246 (setq-local facemenu-add-face-function 'tex-facemenu-add-face-function)
1247 (setq-local facemenu-end-add-face "}")
1248 (setq-local facemenu-remove-face-function t)
1249 (setq-local font-lock-defaults
1250 '((tex-font-lock-keywords tex-font-lock-keywords-1
1251 tex-font-lock-keywords-2 tex-font-lock-keywords-3)
1252 nil nil nil nil
1253 ;; Who ever uses that anyway ???
1254 (font-lock-mark-block-function . mark-paragraph)
1255 (font-lock-syntactic-face-function
1256 . tex-font-lock-syntactic-face-function)
1257 (font-lock-unfontify-region-function
1258 . tex-font-lock-unfontify-region)))
1259 (setq-local prettify-symbols-alist tex--prettify-symbols-alist)
1260 (add-function :override (local 'prettify-symbols-compose-predicate)
1261 #'tex--prettify-symbols-compose-p)
1262 (setq-local syntax-propertize-function
1263 (syntax-propertize-rules latex-syntax-propertize-rules))
1264 ;; TABs in verbatim environments don't do what you think.
1265 (setq-local indent-tabs-mode nil)
1266 ;; Other vars that should be buffer-local.
1267 (make-local-variable 'tex-command)
1268 (make-local-variable 'tex-start-of-header)
1269 (make-local-variable 'tex-end-of-header)
1270 (make-local-variable 'tex-trailer))
1271
1272 (defun tex-categorize-whitespace (backward-limit)
1273 ;; compare-windows-whitespace is set to this.
1274 ;; This is basically a finite-state machine.
1275 ;; Returns a symbol telling how TeX would treat
1276 ;; the whitespace we are looking at: null, space, or par.
1277 (let ((category 'null)
1278 (not-finished t))
1279 (skip-chars-backward " \t\n\f" backward-limit)
1280 (while not-finished
1281 (cond ((looking-at "[ \t]+")
1282 (goto-char (match-end 0))
1283 (if (eq category 'null)
1284 (setq category 'space)))
1285 ((looking-at "\n")
1286 (cond ((eq category 'newline)
1287 (setq category 'par)
1288 (setq not-finished nil))
1289 (t
1290 (setq category 'newline) ;a strictly internal state
1291 (goto-char (match-end 0)))))
1292 ((looking-at "\f+")
1293 (setq category 'par)
1294 (setq not-finished nil))
1295 (t
1296 (setq not-finished nil))))
1297 (skip-chars-forward " \t\n\f")
1298 (if (eq category 'newline)
1299 'space ;TeX doesn't distinguish
1300 category)))
1301
1302 (defun tex-insert-quote (arg)
1303 "Insert the appropriate quote marks for TeX.
1304 Inserts the value of `tex-open-quote' (normally \\=`\\=`) or `tex-close-quote'
1305 \(normally \\='\\=') depending on the context. With prefix argument, always
1306 inserts \" characters."
1307 (interactive "*P")
1308 ;; Discover if we'll be inserting normal double quotes.
1309 ;;
1310 (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
1311 (eq (get-text-property (point) 'face) 'tex-verbatim)
1312 ;; Discover if a preceding occurrence of `tex-open-quote'
1313 ;; should be morphed to a normal double quote.
1314 ;;
1315 (and (>= (point) (+ (point-min) (length tex-open-quote)))
1316 (save-excursion
1317 (backward-char (length tex-open-quote))
1318 (when (or (looking-at (regexp-quote tex-open-quote))
1319 (looking-at (regexp-quote tex-close-quote)))
1320 (delete-char (length tex-open-quote))
1321 (when (looking-at (regexp-quote tex-close-quote))
1322 (delete-char (length tex-close-quote)))
1323 t))))
1324 ;; Insert the normal quote (eventually letting
1325 ;; `electric-pair-mode' do its thing).
1326 ;;
1327 (self-insert-command (prefix-numeric-value arg))
1328 ;; We'll be inserting fancy TeX quotes, but consider and imitate
1329 ;; `electric-pair-mode''s two behaviors: pair-insertion and
1330 ;; region wrapping.
1331 ;;
1332 (if (and electric-pair-mode (use-region-p))
1333 (let* ((saved (point-marker)))
1334 (goto-char (mark))
1335 (insert (if (> saved (mark)) tex-open-quote tex-close-quote))
1336 (goto-char saved)
1337 (insert (if (> saved (mark)) tex-close-quote tex-open-quote)))
1338 (if (or (memq (char-syntax (preceding-char)) '(?\( ?> ?\s))
1339 (memq (preceding-char) '(?~ ?')))
1340 ;; We're in an "opening" context
1341 ;;
1342 (if electric-pair-mode
1343 (if (looking-at (regexp-quote tex-close-quote))
1344 (forward-char (length tex-close-quote))
1345 (insert tex-open-quote)
1346 (insert tex-close-quote)
1347 (backward-char (length tex-close-quote)))
1348 (insert tex-open-quote))
1349 ;; We're in a "closing" context.
1350 ;;
1351 (if (looking-at (regexp-quote tex-close-quote))
1352 (forward-char (length tex-close-quote))
1353 (insert tex-close-quote))))))
1354
1355 (defun tex-validate-buffer ()
1356 "Check current buffer for paragraphs containing mismatched braces or $s.
1357 Their positions are recorded in the buffer `*Occur*'.
1358 To find a particular invalidity from `*Occur*', switch to that buffer
1359 and type C-c C-c or click with mouse-2
1360 on the line for the invalidity you want to see."
1361 (interactive)
1362 (let ((buffer (current-buffer))
1363 (prevpos (point-min))
1364 (linenum nil)
1365 (num-matches 0))
1366 (with-output-to-temp-buffer "*Occur*"
1367 (princ "Mismatches:\n")
1368 (with-current-buffer standard-output
1369 (occur-mode)
1370 ;; This won't actually work...Really, this whole thing should
1371 ;; be rewritten instead of being a hack on top of occur.
1372 (setq occur-revert-arguments (list nil 0 (list buffer))))
1373 (save-excursion
1374 (goto-char (point-max))
1375 ;; Do a little shimmy to place point at the end of the last
1376 ;; "real" paragraph. Need to avoid validating across an \end,
1377 ;; because that blows up latex-forward-sexp.
1378 (backward-paragraph)
1379 (forward-paragraph)
1380 (while (not (bobp))
1381 ;; Scan the previous paragraph for invalidities.
1382 (backward-paragraph)
1383 (save-excursion
1384 (or (tex-validate-region (point) (save-excursion
1385 (forward-paragraph)
1386 (point)))
1387 (let ((end (line-beginning-position 2))
1388 start tem)
1389 (beginning-of-line)
1390 (setq start (point))
1391 ;; Keep track of line number as we scan,
1392 ;; in a cumulative fashion.
1393 (if linenum
1394 (setq linenum (- linenum
1395 (count-lines prevpos (point))))
1396 (setq linenum (1+ (count-lines 1 start))))
1397 (setq prevpos (point))
1398 ;; Mention this mismatch in *Occur*.
1399 ;; Since we scan from end of buffer to beginning,
1400 ;; add each mismatch at the beginning of *Occur*.
1401 (save-excursion
1402 (setq tem (point-marker))
1403 (set-buffer standard-output)
1404 (goto-char (point-min))
1405 ;; Skip "Mismatches:" header line.
1406 (forward-line 1)
1407 (setq num-matches (1+ num-matches))
1408 (insert-buffer-substring buffer start end)
1409 (let (text-beg (text-end (point-marker)))
1410 (forward-char (- start end))
1411 (setq text-beg (point-marker))
1412 (insert (format "%3d: " linenum))
1413 (add-text-properties
1414 text-beg (- text-end 1)
1415 '(mouse-face highlight
1416 help-echo
1417 "mouse-2: go to this invalidity"))
1418 (put-text-property text-beg (- text-end 1)
1419 'occur-target tem))))))))
1420 (with-current-buffer standard-output
1421 (let ((no-matches (zerop num-matches)))
1422 (if no-matches
1423 (insert "None!\n"))
1424 (if (called-interactively-p 'interactive)
1425 (message (cond (no-matches "No mismatches found")
1426 ((= num-matches 1) "1 mismatch found")
1427 (t "%d mismatches found"))
1428 num-matches)))))))
1429
1430 (defun tex-validate-region (start end)
1431 "Check for mismatched braces or $'s in region.
1432 Returns t if no mismatches. Returns nil and moves point to suspect
1433 area if a mismatch is found."
1434 (interactive "r")
1435 (let ((failure-point nil) (max-possible-sexps (- end start)))
1436 (save-excursion
1437 (condition-case ()
1438 (save-restriction
1439 (narrow-to-region start end)
1440 ;; First check that the open and close parens balance in numbers.
1441 (goto-char start)
1442 (while (and (not (eobp))
1443 (<= 0 (setq max-possible-sexps
1444 (1- max-possible-sexps))))
1445 (forward-sexp 1))
1446 ;; Now check that like matches like.
1447 (goto-char start)
1448 (while (re-search-forward "\\s(" nil t)
1449 (save-excursion
1450 (let ((pos (match-beginning 0)))
1451 (goto-char pos)
1452 (skip-chars-backward "\\\\") ; escaped parens
1453 (forward-sexp 1)
1454 (or (eq (preceding-char) (cdr (syntax-after pos)))
1455 (eq (char-after pos) (cdr (syntax-after (1- (point)))))
1456 (error "Mismatched parentheses"))))))
1457 (error
1458 (skip-syntax-forward " .>")
1459 (setq failure-point (point)))))
1460 (if failure-point (goto-char failure-point))
1461 (not failure-point)))
1462
1463 (defun tex-terminate-paragraph (inhibit-validation)
1464 "Insert two newlines, breaking a paragraph for TeX.
1465 Check for mismatched braces or $s in paragraph being terminated.
1466 A prefix arg inhibits the checking."
1467 (interactive "*P")
1468 (or inhibit-validation
1469 (save-excursion
1470 ;; For the purposes of this, a "paragraph" is a block of text
1471 ;; wherein all the brackets etc are expected to be balanced. It
1472 ;; may start after a blank line (ie a "proper" paragraph), or
1473 ;; a begin{} or end{} block, etc.
1474 (tex-validate-region
1475 (save-excursion
1476 (backward-paragraph)
1477 (point))
1478 (point)))
1479 (message "Paragraph being closed appears to contain a mismatch"))
1480 (insert "\n\n"))
1481
1482 (define-skeleton tex-insert-braces
1483 "Make a pair of braces and be poised to type inside of them."
1484 nil
1485 ?\{ _ ?})
1486
1487 ;; This function is used as the value of fill-nobreak-predicate
1488 ;; in LaTeX mode. Its job is to prevent line-breaking inside
1489 ;; of a \verb construct.
1490 (defun latex-fill-nobreak-predicate ()
1491 (save-excursion
1492 (skip-chars-backward " ")
1493 ;; Don't break after \ since `\ ' has special meaning.
1494 (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
1495 (let ((opoint (point))
1496 inside)
1497 (beginning-of-line)
1498 (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
1499 (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
1500 (setq inside t)))
1501 inside))))
1502
1503 (defvar latex-block-default "enumerate")
1504
1505 (defvar latex-block-args-alist
1506 '(("array" nil ?\{ (skeleton-read "Format: ") ?\})
1507 ("tabular" nil ?\{ (skeleton-read "Format: ") ?\})
1508 ("minipage" nil ?\{ (skeleton-read "Size: ") ?\})
1509 ("picture" nil ?\( (skeleton-read "SizeX,SizeY: ") ?\))
1510 ;; FIXME: This is right for Prosper, but not for seminar.
1511 ;; ("slide" nil ?\{ (skeleton-read "Title: ") ?\})
1512 )
1513 "Skeleton element to use for arguments to particular environments.
1514 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1515 the name of the environment and SKEL-ELEM is an element to use in
1516 a skeleton (see `skeleton-insert').")
1517
1518 (defvar latex-block-body-alist
1519 '(("enumerate" nil '(latex-insert-item) > _)
1520 ("itemize" nil '(latex-insert-item) > _)
1521 ("table" nil "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1522 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))
1523 \n _)
1524 ("figure" nil > _ \n "\\caption{" > (skeleton-read "Caption: ") "}" > \n
1525 '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))))
1526 "Skeleton element to use for the body of particular environments.
1527 Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
1528 the name of the environment and SKEL-ELEM is an element to use in
1529 a skeleton (see `skeleton-insert').")
1530
1531 ;; Like tex-insert-braces, but for LaTeX.
1532 (defalias 'tex-latex-block 'latex-insert-block)
1533 (define-skeleton latex-insert-block
1534 "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
1535 Puts point on a blank line between them."
1536 (let ((choice (completing-read (format "LaTeX block name [%s]: "
1537 latex-block-default)
1538 (append latex-block-names
1539 latex-standard-block-names)
1540 nil nil nil nil latex-block-default)))
1541 (setq latex-block-default choice)
1542 (unless (or (member choice latex-standard-block-names)
1543 (member choice latex-block-names))
1544 ;; Remember new block names for later completion.
1545 (push choice latex-block-names))
1546 choice)
1547 \n "\\begin{" str "}"
1548 (cdr (assoc str latex-block-args-alist))
1549 > \n (or (cdr (assoc str latex-block-body-alist)) '(nil > _))
1550 (unless (bolp) '\n)
1551 "\\end{" str "}" > \n)
1552
1553 (define-skeleton latex-insert-item
1554 "Insert an \\item macro."
1555 nil
1556 \n "\\item " >)
1557
1558 \f
1559 ;;;; LaTeX completion.
1560
1561 (defvar latex-complete-bibtex-cache nil)
1562
1563 (define-obsolete-function-alias 'latex-string-prefix-p
1564 'string-prefix-p "24.3")
1565
1566 (defvar bibtex-reference-key)
1567 (declare-function reftex-get-bibfile-list "reftex-cite.el" ())
1568
1569 (defun latex-complete-bibtex-keys ()
1570 (when (bound-and-true-p reftex-mode)
1571 (lambda (key pred action)
1572 (let ((re (concat "^[ \t]*@\\([a-zA-Z]+\\)[ \t\n]*\\([{(][ \t\n]*\\)"
1573 (regexp-quote key)))
1574 (files (reftex-get-bibfile-list))
1575 keys)
1576 (if (and (eq (car latex-complete-bibtex-cache)
1577 (reftex-get-bibfile-list))
1578 (string-prefix-p (nth 1 latex-complete-bibtex-cache)
1579 key))
1580 ;; Use the cache.
1581 (setq keys (nth 2 latex-complete-bibtex-cache))
1582 (dolist (file files)
1583 (with-current-buffer (find-file-noselect file)
1584 (goto-char (point-min))
1585 (while (re-search-forward re nil t)
1586 (goto-char (match-end 2))
1587 (when (and (not (member-ignore-case (match-string 1)
1588 '("c" "comment" "string")))
1589 (looking-at bibtex-reference-key))
1590 (push (match-string-no-properties 0) keys)))))
1591 ;; Fill the cache.
1592 (setq-local latex-complete-bibtex-cache (list files key keys)))
1593 (complete-with-action action keys key pred)))))
1594
1595 (defun latex-complete-envnames ()
1596 (append latex-block-names latex-standard-block-names))
1597
1598 (defun latex-complete-refkeys ()
1599 (when (boundp 'reftex-docstruct-symbol)
1600 (symbol-value reftex-docstruct-symbol)))
1601
1602 (defvar latex-complete-alist
1603 ;; TODO: Add \begin, \end, \ref, ...
1604 '(("\\`\\\\\\(short\\)?cite\\'" . latex-complete-bibtex-keys)
1605 ("\\`\\\\\\(begin\\|end\\)\\'" . latex-complete-envnames)
1606 ("\\`\\\\[vf]?ref\\'" . latex-complete-refkeys)))
1607
1608 (defun latex-complete-data ()
1609 "Get completion-data at point."
1610 (save-excursion
1611 (let ((pt (point)))
1612 (skip-chars-backward "^ {}\n\t\\\\")
1613 (pcase (char-before)
1614 ((or `nil ?\s ?\n ?\t ?\}) nil)
1615 (?\\
1616 ;; TODO: Complete commands.
1617 nil)
1618 (?\{
1619 ;; Complete args to commands.
1620 (let* ((cmd
1621 (save-excursion
1622 (forward-char -1)
1623 (skip-chars-backward " \n")
1624 (buffer-substring (point)
1625 (progn
1626 (skip-chars-backward "a-zA-Z@*")
1627 (let ((n (skip-chars-backward "\\\\")))
1628 (forward-char (* 2 (/ n 2))))
1629 (point)))))
1630 (start (point))
1631 (_ (progn (goto-char pt) (skip-chars-backward "^," start)))
1632 (comp-beg (point))
1633 (_ (progn (goto-char pt) (skip-chars-forward "^, {}\n\t\\\\")))
1634 (comp-end (point))
1635 (table
1636 (funcall
1637 (let ((f (lambda () t)))
1638 (dolist (comp latex-complete-alist)
1639 (if (string-match (car comp) cmd)
1640 (setq f (cdr comp))))
1641 f))))
1642 (if (eq table t)
1643 ;; Unknown command.
1644 nil
1645 (list comp-beg comp-end table))))))))
1646
1647 ;;;;
1648 ;;;; LaTeX syntax navigation
1649 ;;;;
1650
1651 (defmacro tex-search-noncomment (&rest body)
1652 "Execute BODY as long as it return non-nil and point is in a comment.
1653 Return the value returned by the last execution of BODY."
1654 (declare (debug t))
1655 (let ((res-sym (make-symbol "result")))
1656 `(let (,res-sym)
1657 (while
1658 (and (setq ,res-sym (progn ,@body))
1659 (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
1660 ,res-sym)))
1661
1662 (defun tex-last-unended-begin ()
1663 "Leave point at the beginning of the last `\\begin{...}' that is unended."
1664 (condition-case nil
1665 (while (and (tex-search-noncomment
1666 (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
1667 (looking-at "\\\\end"))
1668 (tex-last-unended-begin))
1669 (search-failed (error "Couldn't find unended \\begin"))))
1670
1671 (defun tex-next-unmatched-end ()
1672 "Leave point at the end of the next `\\end' that is unmatched."
1673 (while (and (tex-search-noncomment
1674 (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
1675 (save-excursion (goto-char (match-beginning 0))
1676 (looking-at "\\\\begin")))
1677 (tex-next-unmatched-end)))
1678
1679 (defun tex-next-unmatched-eparen (otype)
1680 "Leave point after the next unmatched escaped closing parenthesis.
1681 The string OTYPE is an opening parenthesis type: `(', `{', or `['."
1682 (condition-case nil
1683 (let ((ctype (char-to-string (cdr (aref (syntax-table)
1684 (string-to-char otype))))))
1685 (while (and (tex-search-noncomment
1686 (re-search-forward (format "\\\\[%s%s]" ctype otype)))
1687 (save-excursion
1688 (goto-char (match-beginning 0))
1689 (looking-at (format "\\\\%s" (regexp-quote otype)))))
1690 (tex-next-unmatched-eparen otype)))
1691 (wrong-type-argument (error "Unknown opening parenthesis type: %s" otype))
1692 (search-failed (error "Couldn't find closing escaped paren"))))
1693
1694 (defun tex-last-unended-eparen (ctype)
1695 "Leave point at the start of the last unended escaped opening parenthesis.
1696 The string CTYPE is a closing parenthesis type: `)', `}', or `]'."
1697 (condition-case nil
1698 (let ((otype (char-to-string (cdr (aref (syntax-table)
1699 (string-to-char ctype))))))
1700 (while (and (tex-search-noncomment
1701 (re-search-backward (format "\\\\[%s%s]" ctype otype)))
1702 (looking-at (format "\\\\%s" (regexp-quote ctype))))
1703 (tex-last-unended-eparen ctype)))
1704 (wrong-type-argument (error "Unknown opening parenthesis type: %s" ctype))
1705 (search-failed (error "Couldn't find unended escaped paren"))))
1706
1707 (defun tex-goto-last-unclosed-latex-block ()
1708 "Move point to the last unclosed \\begin{...}.
1709 Mark is left at original location."
1710 (interactive)
1711 (let ((spot))
1712 (save-excursion
1713 (tex-last-unended-begin)
1714 (setq spot (point)))
1715 (push-mark)
1716 (goto-char spot)))
1717
1718 (defvar latex-handle-escaped-parens t)
1719
1720 ;; Don't think this one actually _needs_ (for the purposes of
1721 ;; tex-mode) to handle escaped parens.
1722 ;; Does not handle escaped parens when latex-handle-escaped-parens is nil.
1723 (defun latex-backward-sexp-1 ()
1724 "Like (backward-sexp 1) but aware of multi-char elements and escaped parens."
1725 (let ((pos (point))
1726 (forward-sexp-function))
1727 (backward-sexp 1)
1728 (cond ((looking-at
1729 (if latex-handle-escaped-parens
1730 "\\\\\\(begin\\>\\|[[({]\\)"
1731 "\\\\begin\\>"))
1732 (signal 'scan-error
1733 (list "Containing expression ends prematurely"
1734 (point) (prog1 (point) (goto-char pos)))))
1735 ((and latex-handle-escaped-parens
1736 (looking-at "\\\\\\([])}]\\)"))
1737 (tex-last-unended-eparen (match-string 1)))
1738 ((eq (char-after) ?{)
1739 (let ((newpos (point)))
1740 (when (ignore-errors (backward-sexp 1) t)
1741 (if (or (looking-at "\\\\end\\>")
1742 ;; In case the \\ ends a verbatim section.
1743 (and (looking-at "end\\>") (eq (char-before) ?\\)))
1744 (tex-last-unended-begin)
1745 (goto-char newpos))))))))
1746
1747 ;; Note this does not handle things like mismatched brackets inside
1748 ;; begin/end blocks.
1749 ;; Needs to handle escaped parens for tex-validate-*.
1750 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2007-09/msg00038.html
1751 ;; Does not handle escaped parens when latex-handle-escaped-parens is nil.
1752 (defun latex-forward-sexp-1 ()
1753 "Like (forward-sexp 1) but aware of multi-char elements and escaped parens."
1754 (let ((pos (point))
1755 (forward-sexp-function))
1756 (forward-sexp 1)
1757 (let ((newpos (point)))
1758 (skip-syntax-backward "/w")
1759 (cond
1760 ((looking-at "\\\\end\\>")
1761 (signal 'scan-error
1762 (list "Containing expression ends prematurely"
1763 (point)
1764 (prog1
1765 (progn (ignore-errors (forward-sexp 2)) (point))
1766 (goto-char pos)))))
1767 ((looking-at "\\\\begin\\>")
1768 (goto-char (match-end 0))
1769 (tex-next-unmatched-end))
1770 ;; A better way to handle this, \( .. \) etc, is probably to
1771 ;; temporarily change the syntax of the \ in \( to punctuation.
1772 ((and latex-handle-escaped-parens
1773 (looking-back "\\\\[])}]" (- (point) 2)))
1774 (signal 'scan-error
1775 (list "Containing expression ends prematurely"
1776 (- (point) 2) (prog1 (point)
1777 (goto-char pos)))))
1778 ((and latex-handle-escaped-parens
1779 (looking-back "\\\\\\([({[]\\)" (- (point) 2)))
1780 (tex-next-unmatched-eparen (match-string 1)))
1781 (t (goto-char newpos))))))
1782
1783 (defun latex-forward-sexp (&optional arg)
1784 "Like `forward-sexp' but aware of multi-char elements and escaped parens."
1785 (interactive "P")
1786 (unless arg (setq arg 1))
1787 (let ((pos (point))
1788 (opoint 0))
1789 (condition-case err
1790 (while (and (/= (point) opoint)
1791 (/= arg 0))
1792 (setq opoint (point))
1793 (setq arg
1794 (if (> arg 0)
1795 (progn (latex-forward-sexp-1) (1- arg))
1796 (progn (latex-backward-sexp-1) (1+ arg)))))
1797 (scan-error
1798 (goto-char pos)
1799 (signal (car err) (cdr err))))))
1800
1801 (defun latex-syntax-after ()
1802 "Like (char-syntax (char-after)) but aware of multi-char elements."
1803 (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
1804
1805 (defun latex-skip-close-parens ()
1806 "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
1807 (let ((forward-sexp-function nil))
1808 (while (progn (skip-syntax-forward " )")
1809 (looking-at "\\\\end\\>"))
1810 (forward-sexp 2))))
1811
1812 (defun latex-down-list ()
1813 "Like (down-list 1) but aware of multi-char elements."
1814 (forward-comment (point-max))
1815 (let ((forward-sexp-function nil))
1816 (if (not (looking-at "\\\\begin\\>"))
1817 (down-list 1)
1818 (forward-sexp 1)
1819 ;; Skip arguments.
1820 (while (looking-at "[ \t]*[[{(]")
1821 (with-syntax-table tex-mode-syntax-table
1822 (forward-sexp))))))
1823
1824 (defalias 'tex-close-latex-block 'latex-close-block)
1825 (define-skeleton latex-close-block
1826 "Create an \\end{...} to match the last unclosed \\begin{...}."
1827 (save-excursion
1828 (tex-last-unended-begin)
1829 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1830 (match-string 1)))
1831 \n "\\end" str > \n)
1832
1833 (define-skeleton latex-split-block
1834 "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
1835 (save-excursion
1836 (tex-last-unended-begin)
1837 (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
1838 (prog1 (match-string 1)
1839 (goto-char (match-end 1))
1840 (setq v1 (buffer-substring (point)
1841 (progn
1842 (while (looking-at "[ \t]*[[{]")
1843 (forward-sexp 1))
1844 (point)))))))
1845 \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
1846
1847 (defconst tex-discount-args-cmds
1848 '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
1849 "documentclass" "usepackage" "label")
1850 "TeX commands whose arguments should not be counted as text.")
1851
1852 (defun tex-count-words (begin end)
1853 "Count the number of words in the buffer."
1854 (interactive
1855 (if (and transient-mark-mode mark-active)
1856 (list (region-beginning) (region-end))
1857 (list (point-min) (point-max))))
1858 ;; TODO: skip comments and math and maybe some environments.
1859 (save-excursion
1860 (goto-char begin)
1861 (let ((count 0))
1862 (while (and (< (point) end) (re-search-forward "\\<" end t))
1863 (if (not (eq (char-syntax (preceding-char)) ?/))
1864 (progn
1865 ;; Don't count single-char words.
1866 (unless (looking-at ".\\>") (cl-incf count))
1867 (forward-char 1))
1868 (let ((cmd
1869 (buffer-substring-no-properties
1870 (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
1871 (forward-char 1))
1872 (point)))))
1873 (when (member cmd tex-discount-args-cmds)
1874 (skip-chars-forward "*")
1875 (forward-comment (point-max))
1876 (when (looking-at "\\[")
1877 (forward-sexp 1)
1878 (forward-comment (point-max)))
1879 (if (not (looking-at "{"))
1880 (forward-char 1)
1881 (forward-sexp 1))))))
1882 (message "%s words" count))))
1883
1884
1885 \f
1886 ;;; Invoking TeX in an inferior shell.
1887
1888 ;; Why use a shell instead of running TeX directly? Because if TeX
1889 ;; gets stuck, the user can switch to the shell window and type at it.
1890
1891 (defvar tex-error-parse-syntax-table
1892 (let ((st (make-syntax-table)))
1893 (modify-syntax-entry ?\( "()" st)
1894 (modify-syntax-entry ?\) ")(" st)
1895 (modify-syntax-entry ?\\ "\\" st)
1896 (modify-syntax-entry ?\{ "_" st)
1897 (modify-syntax-entry ?\} "_" st)
1898 (modify-syntax-entry ?\[ "_" st)
1899 (modify-syntax-entry ?\] "_" st)
1900 ;; Single quotations may appear in errors
1901 (modify-syntax-entry ?\" "_" st)
1902 st)
1903 "Syntax-table used while parsing TeX error messages.")
1904
1905 (defun tex-old-error-file-name ()
1906 ;; This is unreliable, partly because we don't try very hard, and
1907 ;; partly because TeX's output format is eminently ambiguous and unfriendly
1908 ;; to automation.
1909 (save-excursion
1910 (save-match-data
1911 (with-syntax-table tex-error-parse-syntax-table
1912 (beginning-of-line)
1913 (backward-up-list 1)
1914 (skip-syntax-forward "(_")
1915 (while (not (let ((try-filename (thing-at-point 'filename)))
1916 (and try-filename
1917 (not (string= "" try-filename))
1918 (file-readable-p try-filename))))
1919 (skip-syntax-backward "(_")
1920 (backward-up-list 1)
1921 (skip-syntax-forward "(_"))
1922 (thing-at-point 'filename)))))
1923
1924 (defconst tex-error-regexp-alist
1925 ;; First alternative handles the newer --file-line-error style:
1926 ;; ./test2.tex:14: Too many }'s.
1927 '(gnu
1928 ;; Second handles the old-style, which spans two lines but doesn't include
1929 ;; any file info:
1930 ;; ! Too many }'s.
1931 ;; l.396 toto}
1932 ("^l\\.\\([1-9][0-9]*\\) \\(?:\\.\\.\\.\\)?\\(.*\\)$"
1933 tex-old-error-file-name 1 nil nil nil
1934 ;; Since there's no filename to highlight, let's highlight the message.
1935 (2 compilation-error-face))
1936 ;; A few common warning messages.
1937 ("^\\(?:Und\\|Ov\\)erfull \\\\[hv]box .* at lines? \\(\\([1-9][0-9]*\\)\\(?:--\\([1-9][0-9]*\\)\\)?\\)$"
1938 tex-old-error-file-name (2 . 3) nil 1 nil
1939 (1 compilation-warning-face))
1940 ("^(Font) *\\([^ \n].* on input line \\([1-9][0-9]*\\)\\)\\.$"
1941 tex-old-error-file-name 2 nil 1 1
1942 (2 compilation-warning-face))
1943 ;; Included files get output as (<file> ...).
1944 ;; FIXME: there tend to be a boatload of them at the beginning of the
1945 ;; output which aren't that interesting. Maybe we should filter out
1946 ;; all the file name that start with /usr/share?
1947 ;; ("(\\.?/\\([^() \n]+\\)" 1 nil nil 0)
1948 ))
1949
1950 ;; The utility functions:
1951
1952 (define-derived-mode tex-shell shell-mode "TeX-Shell"
1953 (setq-local compilation-error-regexp-alist tex-error-regexp-alist)
1954 (compilation-shell-minor-mode t))
1955
1956 ;;;###autoload
1957 (defun tex-start-shell ()
1958 (with-current-buffer
1959 (make-comint
1960 "tex-shell"
1961 (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
1962 nil
1963 ;; Specify an interactive shell, to make sure it prompts.
1964 "-i")
1965 (let ((proc (get-process "tex-shell")))
1966 (set-process-sentinel proc 'tex-shell-sentinel)
1967 (set-process-query-on-exit-flag proc nil)
1968 (tex-shell)
1969 (while (zerop (buffer-size))
1970 (sleep-for 1)))))
1971
1972 (defun tex-feed-input ()
1973 "Send input to the tex shell process.
1974 In the tex buffer this can be used to continue an interactive tex run.
1975 In the tex shell buffer this command behaves like `comint-send-input'."
1976 (interactive)
1977 (set-buffer (tex-shell-buf))
1978 (comint-send-input)
1979 (tex-recenter-output-buffer nil))
1980
1981 (defun tex-display-shell ()
1982 "Make the TeX shell buffer visible in a window."
1983 (display-buffer (tex-shell-buf))
1984 (tex-recenter-output-buffer nil))
1985
1986 (defun tex-shell-sentinel (proc _msg)
1987 (cond ((null (buffer-name (process-buffer proc)))
1988 ;; buffer killed
1989 (set-process-buffer proc nil)
1990 (tex-delete-last-temp-files))
1991 ((memq (process-status proc) '(signal exit))
1992 (tex-delete-last-temp-files))))
1993
1994 (defun tex-set-buffer-directory (buffer directory)
1995 "Set BUFFER's default directory to be DIRECTORY."
1996 (setq directory (file-name-as-directory (expand-file-name directory)))
1997 (if (not (file-directory-p directory))
1998 (error "%s is not a directory" directory)
1999 (with-current-buffer buffer
2000 (setq default-directory directory))))
2001
2002 (defvar tex-send-command-modified-tick 0)
2003 (make-variable-buffer-local 'tex-send-command-modified-tick)
2004
2005 (defun tex-shell-proc ()
2006 (or (tex-shell-running) (error "No TeX subprocess")))
2007 (defun tex-shell-buf ()
2008 (process-buffer (tex-shell-proc)))
2009 (defun tex-shell-buf-no-error ()
2010 (let ((proc (tex-shell-running)))
2011 (and proc (process-buffer proc))))
2012
2013 (defun tex-send-command (command &optional file background)
2014 "Send COMMAND to TeX shell process, substituting optional FILE for *.
2015 Do this in background if optional BACKGROUND is t. If COMMAND has no *,
2016 FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
2017 substitution will be made in COMMAND. COMMAND can be any expression that
2018 evaluates to a command string.
2019
2020 Return the process in which TeX is running."
2021 (save-excursion
2022 (let* ((cmd (eval command))
2023 (proc (tex-shell-proc))
2024 (buf (process-buffer proc))
2025 (star (string-match "\\*" cmd))
2026 (string
2027 (concat
2028 (if (null file)
2029 cmd
2030 (if (file-name-absolute-p file)
2031 (setq file (convert-standard-filename file)))
2032 (if star (concat (substring cmd 0 star)
2033 (shell-quote-argument file)
2034 (substring cmd (1+ star)))
2035 (concat cmd " " (shell-quote-argument file))))
2036 (if background "&" ""))))
2037 ;; Switch to buffer before checking for subproc output in it.
2038 (set-buffer buf)
2039 ;; If text is unchanged since previous tex-send-command,
2040 ;; we haven't got any output. So wait for output now.
2041 (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
2042 (accept-process-output proc))
2043 (goto-char (process-mark proc))
2044 (insert string)
2045 (comint-send-input)
2046 (setq tex-send-command-modified-tick (buffer-modified-tick buf))
2047 proc)))
2048
2049 (defun tex-delete-last-temp-files (&optional not-all)
2050 "Delete any junk files from last temp file.
2051 If NOT-ALL is non-nil, save the `.dvi' file."
2052 (if tex-last-temp-file
2053 (let* ((dir (file-name-directory tex-last-temp-file))
2054 (list (and (file-directory-p dir)
2055 (file-name-all-completions
2056 (file-name-base tex-last-temp-file)
2057 dir))))
2058 (while list
2059 (if not-all
2060 (and
2061 ;; If arg is non-nil, don't delete the .dvi file.
2062 (not (string-match "\\.dvi$" (car list)))
2063 (delete-file (concat dir (car list))))
2064 (delete-file (concat dir (car list))))
2065 (setq list (cdr list))))))
2066
2067 (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
2068
2069 ;;
2070 ;; Machinery to guess the command that the user wants to execute.
2071 ;;
2072
2073 (defvar tex-compile-history nil)
2074
2075 (defvar tex-input-files-re
2076 (eval-when-compile
2077 (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
2078 "bbl" "ind" "sty" "cls") t)
2079 ;; Include files with no dots (for directories).
2080 "\\'\\|\\`[^.]+\\'")))
2081
2082 (defcustom tex-use-reftex t
2083 "If non-nil, use RefTeX's list of files to determine what command to use."
2084 :type 'boolean
2085 :group 'tex)
2086
2087 (defvar tex-compile-commands
2088 '(((concat "pdf" tex-command
2089 " " (if (< 0 (length tex-start-commands))
2090 (shell-quote-argument tex-start-commands)) " %f")
2091 t "%r.pdf")
2092 ((concat tex-command
2093 " " (if (< 0 (length tex-start-commands))
2094 (shell-quote-argument tex-start-commands)) " %f")
2095 t "%r.dvi")
2096 ("xdvi %r &" "%r.dvi")
2097 ("\\doc-view \"%r.pdf\"" "%r.pdf")
2098 ("xpdf %r.pdf &" "%r.pdf")
2099 ("gv %r.ps &" "%r.ps")
2100 ("yap %r &" "%r.dvi")
2101 ("advi %r &" "%r.dvi")
2102 ("gv %r.pdf &" "%r.pdf")
2103 ("bibtex %r" "%r.aux" "%r.bbl")
2104 ("makeindex %r" "%r.idx" "%r.ind")
2105 ("texindex %r.??")
2106 ("dvipdfm %r" "%r.dvi" "%r.pdf")
2107 ("dvipdf %r" "%r.dvi" "%r.pdf")
2108 ("dvips -o %r.ps %r" "%r.dvi" "%r.ps")
2109 ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
2110 ("lpr %r.ps" "%r.ps"))
2111 "List of commands for `tex-compile'.
2112 Each element should be of the form (FORMAT IN OUT) where
2113 FORMAT is an expression that evaluates to a string that can contain
2114 - `%r' the main file name without extension.
2115 - `%f' the main file name.
2116 IN can be either a string (with the same % escapes in it) indicating
2117 the name of the input file, or t to indicate that the input is all
2118 the TeX files of the document, or nil if we don't know.
2119 OUT describes the output file and is either a %-escaped string
2120 or nil to indicate that there is no output file.")
2121
2122 (define-obsolete-function-alias 'tex-string-prefix-p 'string-prefix-p "24.3")
2123
2124 (defun tex-guess-main-file (&optional all)
2125 "Find a likely `tex-main-file'.
2126 Looks for hints in other buffers in the same directory or in
2127 ALL other buffers. If ALL is `sub' only look at buffers in parent directories
2128 of the current buffer."
2129 (let ((dir default-directory)
2130 (header-re tex-start-of-header))
2131 (catch 'found
2132 ;; Look for a buffer with `tex-main-file' set.
2133 (dolist (buf (if (consp all) all (buffer-list)))
2134 (with-current-buffer buf
2135 (when (and (cond
2136 ((null all) (equal dir default-directory))
2137 ((eq all 'sub) (string-prefix-p default-directory dir))
2138 (t))
2139 (stringp tex-main-file))
2140 (throw 'found (expand-file-name tex-main-file)))))
2141 ;; Look for a buffer containing the magic `tex-start-of-header'.
2142 (dolist (buf (if (consp all) all (buffer-list)))
2143 (with-current-buffer buf
2144 (when (and (cond
2145 ((null all) (equal dir default-directory))
2146 ((eq all 'sub) (string-prefix-p default-directory dir))
2147 (t))
2148 buffer-file-name
2149 ;; (or (easy-mmode-derived-mode-p 'latex-mode)
2150 ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
2151 (save-excursion
2152 (save-restriction
2153 (widen)
2154 (goto-char (point-min))
2155 (re-search-forward
2156 header-re (+ (point) 10000) t))))
2157 (throw 'found (expand-file-name buffer-file-name))))))))
2158
2159 (defun tex-main-file ()
2160 "Return the relative name of the main file."
2161 (let* ((file (or tex-main-file
2162 ;; Compatibility with AUCTeX.
2163 (with-no-warnings
2164 (when (boundp 'TeX-master)
2165 (cond ((stringp TeX-master)
2166 (setq-local tex-main-file TeX-master))
2167 ((and (eq TeX-master t) buffer-file-name)
2168 (file-relative-name buffer-file-name)))))
2169 ;; Try to guess the main file.
2170 (if (not buffer-file-name)
2171 (error "Buffer is not associated with any file")
2172 (file-relative-name
2173 (if (save-excursion
2174 (goto-char (point-min))
2175 (re-search-forward tex-start-of-header
2176 (+ (point) 10000) t))
2177 ;; This is the main file.
2178 buffer-file-name
2179 ;; This isn't the main file, let's try to find better,
2180 (or (tex-guess-main-file)
2181 (tex-guess-main-file 'sub)
2182 ;; (tex-guess-main-file t)
2183 buffer-file-name)))))))
2184 (if (or (file-exists-p file) (string-match "\\.tex\\'" file))
2185 file (concat file ".tex"))))
2186
2187 (defun tex-summarize-command (cmd)
2188 (if (not (stringp cmd)) ""
2189 (mapconcat 'identity
2190 (mapcar (lambda (s) (car (split-string s)))
2191 (split-string cmd "\\s-*\\(?:;\\|&&\\)\\s-*"))
2192 "&")))
2193
2194 (defun tex-uptodate-p (file)
2195 "Return non-nil if FILE is not uptodate w.r.t the document source files.
2196 FILE is typically the output DVI or PDF file."
2197 ;; We should check all the files included !!!
2198 (and
2199 ;; Clearly, the target must exist.
2200 (file-exists-p file)
2201 ;; And the last run must not have asked for a rerun.
2202 ;; FIXME: this should check that the last run was done on the same file.
2203 (let ((buf (condition-case nil (tex-shell-buf) (error nil))))
2204 (when buf
2205 (with-current-buffer buf
2206 (save-excursion
2207 (goto-char (point-max))
2208 (and (re-search-backward
2209 (concat "(see the transcript file for additional information)"
2210 "\\|^Output written on .*"
2211 (regexp-quote (file-name-nondirectory file))
2212 " (.*)\\.")
2213 nil t)
2214 (> (save-excursion
2215 ;; Usually page numbers are output as [N], but
2216 ;; I've already seen things like
2217 ;; [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
2218 (or (re-search-backward "\\[[0-9]+\\({[^}]*}\\)?\\]"
2219 nil t)
2220 (point-min)))
2221 (save-excursion
2222 (or (re-search-backward "Rerun" nil t)
2223 (point-min)))))))))
2224 ;; And the input files must not have been changed in the meantime.
2225 (let ((files (if (and tex-use-reftex
2226 (fboundp 'reftex-scanning-info-available-p)
2227 (reftex-scanning-info-available-p))
2228 (reftex-all-document-files)
2229 (list (file-name-directory (expand-file-name file)))))
2230 (ignored-dirs-re
2231 (concat
2232 (regexp-opt
2233 (delq nil (mapcar (lambda (s) (if (eq (aref s (1- (length s))) ?/)
2234 (substring s 0 (1- (length s)))))
2235 completion-ignored-extensions))
2236 t) "\\'"))
2237 (uptodate t))
2238 (while (and files uptodate)
2239 (let ((f (pop files)))
2240 (if (and (file-directory-p f)
2241 ;; Avoid infinite loops.
2242 (not (file-symlink-p f)))
2243 (unless (string-match ignored-dirs-re f)
2244 (setq files (nconc
2245 (ignore-errors ;Not readable or something.
2246 (directory-files f t tex-input-files-re))
2247 files)))
2248 (when (file-newer-than-file-p f file)
2249 (setq uptodate nil)))))
2250 uptodate)))
2251
2252
2253 (autoload 'format-spec "format-spec")
2254
2255 (defvar tex-executable-cache nil)
2256 (defun tex-executable-exists-p (name)
2257 "Like `executable-find' but with a cache."
2258 (let ((f (and (string-match "^\\\\\\([^ \t\n]+\\)" name)
2259 (intern-soft (concat "tex-cmd-" (match-string 1 name))))))
2260 (if (fboundp f)
2261 f
2262 (let ((cache (assoc name tex-executable-cache)))
2263 (if cache (cdr cache)
2264 (let ((executable (executable-find name)))
2265 (push (cons name executable) tex-executable-cache)
2266 executable))))))
2267
2268 (defun tex-command-executable (cmd)
2269 (let ((s (if (stringp cmd) cmd (eval (car cmd)))))
2270 (substring s 0 (string-match "[ \t]\\|\\'" s))))
2271
2272 (defun tex-command-active-p (cmd fspec)
2273 "Return non-nil if the CMD spec might need to be run."
2274 (let ((in (nth 1 cmd))
2275 (out (nth 2 cmd)))
2276 (if (stringp in)
2277 (let ((file (format-spec in fspec)))
2278 (when (file-exists-p file)
2279 (or (not out)
2280 (file-newer-than-file-p
2281 file (format-spec out fspec)))))
2282 (when (and (eq in t) (stringp out))
2283 (not (tex-uptodate-p (format-spec out fspec)))))))
2284
2285 (defcustom tex-cmd-bibtex-args "--min-crossref=100"
2286 "Extra args to pass to `bibtex' by default."
2287 :type 'string
2288 :version "23.1"
2289 :group 'tex-run)
2290
2291 (defun tex-format-cmd (format fspec)
2292 "Like `format-spec' but adds user-specified args to the command.
2293 Only applies the FSPEC to the args part of FORMAT."
2294 (if (not (string-match "\\([^ /\\]+\\) " format))
2295 (format-spec format fspec)
2296 (let* ((prefix (substring format 0 (match-beginning 0)))
2297 (cmd (match-string 1 format))
2298 (args (substring format (match-end 0)))
2299 (sym (intern-soft (format "tex-cmd-%s-args" cmd)))
2300 (extra-args (and sym (symbol-value sym))))
2301 (concat prefix cmd
2302 (if extra-args (concat " " extra-args))
2303 " " (format-spec args fspec)))))
2304
2305 (defun tex-compile-default (fspec)
2306 "Guess a default command given the `format-spec' FSPEC."
2307 ;; TODO: Learn to do latex+dvips!
2308 (let ((cmds nil)
2309 (unchanged-in nil))
2310 ;; Only consider active commands.
2311 (dolist (cmd tex-compile-commands)
2312 (when (tex-executable-exists-p (tex-command-executable cmd))
2313 (if (tex-command-active-p cmd fspec)
2314 (push cmd cmds)
2315 (push (nth 1 cmd) unchanged-in))))
2316 ;; If no command seems to be applicable, arbitrarily pick the first one.
2317 (setq cmds (if cmds (nreverse cmds) (list (car tex-compile-commands))))
2318 ;; Remove those commands whose input was considered stable for
2319 ;; some other command (typically if (t . "%.pdf") is inactive
2320 ;; then we're using pdflatex and the fact that the dvi file
2321 ;; is nonexistent doesn't matter).
2322 (let ((tmp nil))
2323 (dolist (cmd cmds)
2324 (unless (member (nth 1 cmd) unchanged-in)
2325 (push cmd tmp)))
2326 ;; Only remove if there's something left.
2327 (if tmp (setq cmds (nreverse tmp))))
2328 ;; Remove commands whose input is not uptodate either.
2329 (let ((outs (delq nil (mapcar (lambda (x) (nth 2 x)) cmds)))
2330 (tmp nil))
2331 (dolist (cmd cmds)
2332 (unless (member (nth 1 cmd) outs)
2333 (push cmd tmp)))
2334 ;; Only remove if there's something left.
2335 (if tmp (setq cmds (nreverse tmp))))
2336 ;; Select which file we're going to operate on (the latest).
2337 (let ((latest (nth 1 (car cmds))))
2338 (dolist (cmd (prog1 (cdr cmds) (setq cmds (list (car cmds)))))
2339 (if (equal latest (nth 1 cmd))
2340 (push cmd cmds)
2341 (unless (eq latest t) ;Can't beat that!
2342 (if (or (not (stringp latest))
2343 (eq (nth 1 cmd) t)
2344 (and (stringp (nth 1 cmd))
2345 (file-newer-than-file-p
2346 (format-spec (nth 1 cmd) fspec)
2347 (format-spec latest fspec))))
2348 (setq latest (nth 1 cmd) cmds (list cmd)))))))
2349 ;; Expand the command spec into the actual text.
2350 (dolist (cmd (prog1 cmds (setq cmds nil)))
2351 (push (cons (eval (car cmd)) (cdr cmd)) cmds))
2352 ;; Select the favorite command from the history.
2353 (let ((hist tex-compile-history)
2354 re hist-cmd)
2355 (while hist
2356 (setq hist-cmd (pop hist))
2357 (setq re (concat "\\`"
2358 (regexp-quote (tex-command-executable hist-cmd))
2359 "\\([ \t]\\|\\'\\)"))
2360 (dolist (cmd cmds)
2361 ;; If the hist entry uses the same command and applies to a file
2362 ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
2363 (and (string-match re (car cmd))
2364 (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd)))
2365 (string-match (regexp-quote (match-string 1 (car cmd)))
2366 hist-cmd))
2367 (setq hist nil cmds (list cmd)))))
2368 ;; Substitute and return.
2369 (if (and hist-cmd
2370 (string-match (concat "[' \t\"]" (format-spec "%r" fspec)
2371 "\\([;&' \t\"]\\|\\'\\)") hist-cmd))
2372 ;; The history command was already applied to the same file,
2373 ;; so just reuse it.
2374 hist-cmd
2375 (if cmds (tex-format-cmd (caar cmds) fspec))))))
2376
2377 (defun tex-cmd-doc-view (file)
2378 (pop-to-buffer (find-file-noselect file)))
2379
2380 (defun tex-compile (dir cmd)
2381 "Run a command CMD on current TeX buffer's file in DIR."
2382 ;; FIXME: Use time-stamps on files to decide the next op.
2383 (interactive
2384 (let* ((file (tex-main-file))
2385 (default-directory
2386 (prog1 (file-name-directory (expand-file-name file))
2387 (setq file (file-name-nondirectory file))))
2388 (root (file-name-sans-extension file))
2389 (fspec (list (cons ?r (shell-quote-argument root))
2390 (cons ?f (shell-quote-argument file))))
2391 (default (tex-compile-default fspec)))
2392 (list default-directory
2393 (completing-read
2394 (format "Command [%s]: " (tex-summarize-command default))
2395 (mapcar (lambda (x)
2396 (list (tex-format-cmd (eval (car x)) fspec)))
2397 tex-compile-commands)
2398 nil nil nil 'tex-compile-history default))))
2399 (save-some-buffers (not compilation-ask-about-save) nil)
2400 (let ((f (and (string-match "^\\\\\\([^ \t\n]+\\)" cmd)
2401 (intern-soft (concat "tex-cmd-" (match-string 1 cmd))))))
2402 (if (functionp f)
2403 (condition-case nil
2404 (let ((default-directory dir))
2405 (apply f (split-string-and-unquote
2406 (substring cmd (match-end 0)))))
2407 (wrong-number-of-arguments
2408 (error "Wrong number of arguments to %s"
2409 (substring (symbol-name f) 8))))
2410 (if (tex-shell-running)
2411 (tex-kill-job)
2412 (tex-start-shell))
2413 (tex-send-tex-command cmd dir))))
2414
2415 (defun tex-start-tex (command file &optional dir)
2416 "Start a TeX run, using COMMAND on FILE."
2417 (let* ((star (string-match "\\*" command))
2418 (compile-command
2419 (if star
2420 (concat (substring command 0 star)
2421 (shell-quote-argument file)
2422 (substring command (1+ star)))
2423 (concat command " "
2424 tex-start-options
2425 (if (< 0 (length tex-start-commands))
2426 (concat
2427 (shell-quote-argument tex-start-commands) " "))
2428 (shell-quote-argument file)))))
2429 (tex-send-tex-command compile-command dir)))
2430
2431 (defun tex-send-tex-command (cmd &optional dir)
2432 (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
2433 (and buf (with-current-buffer buf
2434 default-directory))))
2435 (not dir))
2436 (let (shell-dirtrack-verbose)
2437 (tex-send-command tex-shell-cd-command dir)))
2438 (with-current-buffer (process-buffer (tex-send-command cmd))
2439 (setq compilation-last-buffer (current-buffer))
2440 (compilation-forget-errors)
2441 ;; Don't parse previous compilations.
2442 (set-marker compilation-parsing-end (1- (point-max))))
2443 (tex-display-shell)
2444 (setq tex-last-buffer-texed (current-buffer)))
2445 \f
2446 ;;; The commands:
2447
2448 (defun tex-region (beg end)
2449 "Run TeX on the current region, via a temporary file.
2450 The file's name comes from the variable `tex-zap-file' and the
2451 variable `tex-directory' says where to put it.
2452
2453 If the buffer has a header, the header is given to TeX before the
2454 region itself. The buffer's header is all lines between the strings
2455 defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
2456 The header must start in the first 100 lines of the buffer.
2457
2458 The value of `tex-trailer' is given to TeX as input after the region.
2459
2460 The value of `tex-command' specifies the command to use to run TeX."
2461 (interactive "r")
2462 (if (tex-shell-running)
2463 (tex-kill-job)
2464 (tex-start-shell))
2465 (or tex-zap-file
2466 (setq tex-zap-file (tex-generate-zap-file-name)))
2467 ;; Temp file will be written and TeX will be run in zap-directory.
2468 ;; If the TEXINPUTS file has relative directories or if the region has
2469 ;; \input of files, this must be the same directory as the file for
2470 ;; TeX to access the correct inputs. That's why it's safest if
2471 ;; tex-directory is ".".
2472 (let* ((zap-directory
2473 (file-name-as-directory (expand-file-name tex-directory)))
2474 (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
2475 zap-directory))
2476 (main-file (expand-file-name (tex-main-file)))
2477 (ismain (string-equal main-file (buffer-file-name)))
2478 already-output)
2479 ;; Don't delete temp files if we do the same buffer twice in a row.
2480 (or (eq (current-buffer) tex-last-buffer-texed)
2481 (tex-delete-last-temp-files t))
2482 (let ((default-directory zap-directory)) ; why?
2483 ;; We assume the header is fully contained in tex-main-file.
2484 ;; We use f-f-ns so we get prompted about any changes on disk.
2485 (with-current-buffer (find-file-noselect main-file)
2486 (setq already-output (tex-region-header tex-out-file
2487 (and ismain beg))))
2488 ;; Write out the specified region (but don't repeat anything
2489 ;; already written in the header).
2490 (write-region (if ismain
2491 (max beg already-output)
2492 beg)
2493 end tex-out-file (not (zerop already-output)))
2494 ;; Write the trailer, if any.
2495 ;; Precede it with a newline to make sure it
2496 ;; is not hidden in a comment.
2497 (if tex-trailer
2498 (write-region (concat "\n" tex-trailer) nil
2499 tex-out-file t)))
2500 ;; Record the file name to be deleted afterward.
2501 (setq tex-last-temp-file tex-out-file)
2502 ;; Use a relative file name here because (1) the proper dir
2503 ;; is already current, and (2) the abs file name is sometimes
2504 ;; too long and can make tex crash.
2505 (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
2506 (setq tex-print-file tex-out-file)))
2507
2508 (defun tex-region-header (file &optional beg)
2509 "If there is a TeX header in the current buffer, write it to FILE.
2510 Return point at the end of the region so written, or zero. If
2511 the optional buffer position BEG is specified, then the region
2512 written out starts at BEG, if this lies before the start of the header.
2513
2514 If the first line matches `tex-first-line-header-regexp', it is
2515 also written out. The variables `tex-start-of-header' and
2516 `tex-end-of-header' are used to locate the header. Note that the
2517 start of the header is required to be within the first 100 lines."
2518 (save-excursion
2519 (save-restriction
2520 (widen)
2521 (goto-char (point-min))
2522 (let ((search-end (save-excursion
2523 (forward-line 100)
2524 (point)))
2525 (already-output 0)
2526 hbeg hend)
2527 ;; Maybe copy first line, such as `\input texinfo', to temp file.
2528 (and tex-first-line-header-regexp
2529 (looking-at tex-first-line-header-regexp)
2530 (write-region (point)
2531 (progn (forward-line 1)
2532 (setq already-output (point)))
2533 file))
2534 ;; Write out the header, if there is one, and any of the
2535 ;; specified region which extends before it. But don't repeat
2536 ;; anything already written.
2537 (and tex-start-of-header
2538 (re-search-forward tex-start-of-header search-end t)
2539 (progn
2540 (beginning-of-line)
2541 (setq hbeg (point)) ; mark beginning of header
2542 (when (re-search-forward tex-end-of-header nil t)
2543 (forward-line 1)
2544 (setq hend (point)) ; mark end of header
2545 (write-region
2546 (max (if beg
2547 (min hbeg beg)
2548 hbeg)
2549 already-output)
2550 hend file (not (zerop already-output)))
2551 (setq already-output hend))))
2552 already-output))))
2553
2554 (defun tex-buffer ()
2555 "Run TeX on current buffer. See \\[tex-region] for more information.
2556 Does not save the buffer, so it's useful for trying experimental versions.
2557 See \\[tex-file] for an alternative."
2558 (interactive)
2559 (tex-region (point-min) (point-max)))
2560
2561 (defun tex-file ()
2562 "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
2563 This function is more useful than \\[tex-buffer] when you need the
2564 `.aux' file of LaTeX to have the correct name."
2565 (interactive)
2566 (when tex-offer-save
2567 (save-some-buffers))
2568 (let* ((source-file (tex-main-file))
2569 (file-dir (file-name-directory (expand-file-name source-file))))
2570 (if (tex-shell-running)
2571 (tex-kill-job)
2572 (tex-start-shell))
2573 (tex-start-tex tex-command source-file file-dir)
2574 (setq tex-print-file (expand-file-name source-file))))
2575
2576 (defun tex-generate-zap-file-name ()
2577 "Generate a unique name suitable for use as a file name."
2578 ;; Include the shell process number and host name
2579 ;; in case there are multiple shells (for same or different user).
2580 ;; Dec 1998: There is a report that some versions of xdvi
2581 ;; don't work with file names that start with #.
2582 (format "_TZ_%d-%s"
2583 (process-id (get-buffer-process "*tex-shell*"))
2584 (subst-char-in-string ?. ?- (system-name))))
2585
2586 ;; This will perhaps be useful for modifying TEXINPUTS.
2587 ;; Expand each file name, separated by colons, in the string S.
2588 (defun tex-expand-files (s)
2589 (let (elts (start 0))
2590 (while (string-match ":" s start)
2591 (setq elts (cons (substring s start (match-beginning 0)) elts))
2592 (setq start (match-end 0)))
2593 (or (= start 0)
2594 (setq elts (cons (substring s start) elts)))
2595 (mapconcat (lambda (elt)
2596 (if (= (length elt) 0) elt (expand-file-name elt)))
2597 (nreverse elts) ":")))
2598
2599 (defun tex-shell-running ()
2600 (let ((proc (get-process "tex-shell")))
2601 (when proc
2602 (if (and (eq (process-status proc) 'run)
2603 (buffer-live-p (process-buffer proc)))
2604 ;; return the TeX process on success
2605 proc
2606 ;; get rid of the process permanently
2607 ;; this should get rid of the annoying w32 problem with
2608 ;; dead tex-shell buffer and live process
2609 (delete-process proc)))))
2610
2611 (defun tex-kill-job ()
2612 "Kill the currently running TeX job."
2613 (interactive)
2614 ;; `quit-process' leads to core dumps of the tex process (except if
2615 ;; coredumpsize has limit 0kb as on many environments). One would
2616 ;; like to use (kill-process proc 'lambda), however that construct
2617 ;; does not work on some systems and kills the shell itself.
2618 (let ((proc (get-process "tex-shell")))
2619 (when proc (quit-process proc t))))
2620
2621 (defun tex-recenter-output-buffer (linenum)
2622 "Redisplay buffer of TeX job output so that most recent output can be seen.
2623 The last line of the buffer is displayed on
2624 line LINE of the window, or centered if LINE is nil."
2625 (interactive "P")
2626 (let ((tex-shell (get-buffer "*tex-shell*"))
2627 (window))
2628 (if (null tex-shell)
2629 (message "No TeX output buffer")
2630 (setq window (display-buffer tex-shell))
2631 (with-selected-window window
2632 (bury-buffer tex-shell)
2633 (goto-char (point-max))
2634 (recenter (if linenum
2635 (prefix-numeric-value linenum)
2636 (/ (window-height) 2)))))))
2637
2638 (defcustom tex-print-file-extension ".dvi"
2639 "The TeX-compiled file extension for viewing and printing.
2640 If you use pdflatex instead of latex, set this to \".pdf\" and modify
2641 `tex-dvi-view-command' and `tex-dvi-print-command' appropriately."
2642 :type 'string
2643 :group 'tex-view
2644 :version "25.1")
2645
2646 (defun tex-print (&optional alt)
2647 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2648 Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
2649 is provided, use the alternative command, `tex-alt-dvi-print-command'."
2650 (interactive "P")
2651 (let ((print-file-name-dvi (tex-append tex-print-file
2652 tex-print-file-extension))
2653 test-name)
2654 (if (and (not (equal (current-buffer) tex-last-buffer-texed))
2655 (buffer-file-name)
2656 ;; Check that this buffer's printed file is up to date.
2657 (file-newer-than-file-p
2658 (setq test-name (tex-append (buffer-file-name)
2659 tex-print-file-extension))
2660 (buffer-file-name)))
2661 (setq print-file-name-dvi test-name))
2662 (if (not (file-exists-p print-file-name-dvi))
2663 (error "No appropriate `.dvi' file could be found")
2664 (if (tex-shell-running)
2665 (tex-kill-job)
2666 (tex-start-shell))
2667 (tex-send-command
2668 (if alt tex-alt-dvi-print-command tex-dvi-print-command)
2669 print-file-name-dvi
2670 t))))
2671
2672 (defun tex-alt-print ()
2673 "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
2674 Runs the shell command defined by `tex-alt-dvi-print-command'."
2675 (interactive)
2676 (tex-print t))
2677
2678 (defun tex-view ()
2679 "Preview the last `.dvi' file made by running TeX under Emacs.
2680 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
2681 The variable `tex-dvi-view-command' specifies the shell command for preview.
2682 You must set that variable yourself before using this command,
2683 because there is no standard value that would generally work."
2684 (interactive)
2685 (or tex-dvi-view-command
2686 (error "You must set `tex-dvi-view-command'"))
2687 ;; Restart the TeX shell if necessary.
2688 (or (tex-shell-running)
2689 (tex-start-shell))
2690 (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
2691 (tex-print)))
2692
2693 (defun tex-append (file-name suffix)
2694 "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
2695 Pascal-based TeX scans for the first period, C TeX uses the last.
2696 No period is retained immediately before SUFFIX,
2697 so normally SUFFIX starts with one."
2698 (if (stringp file-name)
2699 (let ((file (file-name-nondirectory file-name))
2700 trial-name)
2701 ;; Try splitting on last period.
2702 ;; The first-period split can get fooled when two files
2703 ;; named a.tex and a.b.tex are both tex'd;
2704 ;; the last-period split must be right if it matches at all.
2705 (setq trial-name
2706 (concat (file-name-directory file-name)
2707 (substring file 0
2708 (string-match "\\.[^.]*$" file))
2709 suffix))
2710 (if (or (file-exists-p trial-name)
2711 (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
2712 trial-name
2713 ;; Not found, so split on first period.
2714 (concat (file-name-directory file-name)
2715 (substring file 0
2716 (string-match "\\." file))
2717 suffix)))
2718 " "))
2719
2720 (defun tex-show-print-queue ()
2721 "Show the print queue that \\[tex-print] put your job on.
2722 Runs the shell command defined by `tex-show-queue-command'."
2723 (interactive)
2724 (if (tex-shell-running)
2725 (tex-kill-job)
2726 (tex-start-shell))
2727 (tex-send-command tex-show-queue-command)
2728 (tex-display-shell))
2729
2730 (defun tex-bibtex-file ()
2731 "Run BibTeX on the current buffer's file."
2732 (interactive)
2733 (if (tex-shell-running)
2734 (tex-kill-job)
2735 (tex-start-shell))
2736 (let* (shell-dirtrack-verbose
2737 (source-file (expand-file-name (tex-main-file)))
2738 (tex-out-file
2739 (tex-append (file-name-nondirectory source-file) ""))
2740 (file-dir (file-name-directory source-file)))
2741 (tex-send-command tex-shell-cd-command file-dir)
2742 (tex-send-command tex-bibtex-command tex-out-file))
2743 (tex-display-shell))
2744 \f
2745 ;;;;
2746 ;;;; LaTeX indentation
2747 ;;;;
2748
2749 (defvar tex-indent-allhanging t)
2750 (defvar tex-indent-arg 4)
2751 (defvar tex-indent-basic 2)
2752 (defvar tex-indent-item tex-indent-basic)
2753 (defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
2754 (defvar latex-noindent-environments '("document"))
2755 (put 'latex-noindent-environments 'safe-local-variable
2756 (lambda (x) (null (delq t (mapcar 'stringp x)))))
2757
2758 (defvar tex-latex-indent-syntax-table
2759 (let ((st (make-syntax-table tex-mode-syntax-table)))
2760 (modify-syntax-entry ?$ "." st)
2761 (modify-syntax-entry ?\( "." st)
2762 (modify-syntax-entry ?\) "." st)
2763 st)
2764 "Syntax table used while computing indentation.")
2765
2766 (defun latex-indent (&optional _arg)
2767 (if (and (eq (get-text-property (if (and (eobp) (bolp))
2768 (max (point-min) (1- (point)))
2769 (line-beginning-position))
2770 'face)
2771 'tex-verbatim))
2772 'noindent
2773 (with-syntax-table tex-latex-indent-syntax-table
2774 ;; TODO: Rather than ignore $, we should try to be more clever about it.
2775 (let ((indent
2776 (save-excursion
2777 (beginning-of-line)
2778 (latex-find-indent))))
2779 (if (< indent 0) (setq indent 0))
2780 (if (<= (current-column) (current-indentation))
2781 (indent-line-to indent)
2782 (save-excursion (indent-line-to indent)))))))
2783
2784 (defcustom latex-indent-within-escaped-parens nil
2785 "Non-nil means add extra indent to text within escaped parens.
2786 When this is non-nil, text within matching pairs of escaped
2787 parens is indented at the column following the open paren. The
2788 default value does not add any extra indent thus providing the
2789 behavior of Emacs 22 and earlier."
2790 :type 'boolean
2791 :group 'tex
2792 :version "23.1")
2793
2794 (defun latex-find-indent (&optional virtual)
2795 "Find the proper indentation of text after point.
2796 VIRTUAL if non-nil indicates that we're only trying to find the indentation
2797 in order to determine the indentation of something else.
2798 There might be text before point."
2799 (let ((latex-handle-escaped-parens latex-indent-within-escaped-parens))
2800 (save-excursion
2801 (skip-chars-forward " \t")
2802 (or
2803 ;; Stick the first line at column 0.
2804 (and (= (point-min) (line-beginning-position)) 0)
2805 ;; Trust the current indentation, if such info is applicable.
2806 (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
2807 (current-column))
2808 ;; Stick verbatim environments to the left margin.
2809 (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
2810 (member (match-string 2) tex-verbatim-environments)
2811 0)
2812 ;; Put leading close-paren where the matching open paren would be.
2813 (let (escaped)
2814 (and (or (eq (latex-syntax-after) ?\))
2815 ;; Try to handle escaped close parens but keep
2816 ;; original position if it doesn't work out.
2817 (and latex-handle-escaped-parens
2818 (setq escaped (looking-at "\\\\\\([])}]\\)"))))
2819 (ignore-errors
2820 (save-excursion
2821 (when escaped
2822 (goto-char (match-beginning 1)))
2823 (latex-skip-close-parens)
2824 (latex-backward-sexp-1)
2825 (latex-find-indent 'virtual)))))
2826 ;; Default (maybe an argument)
2827 (let ((pos (point))
2828 ;; Outdent \item if necessary.
2829 (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
2830 up-list-pos)
2831 ;; Find the previous point which determines our current indentation.
2832 (condition-case err
2833 (progn
2834 (latex-backward-sexp-1)
2835 (while (> (current-column) (current-indentation))
2836 (latex-backward-sexp-1)))
2837 (scan-error
2838 (setq up-list-pos (nth 2 err))))
2839 (cond
2840 ((= (point-min) pos) 0) ; We're really just indenting the first line.
2841 ((integerp up-list-pos)
2842 ;; Have to indent relative to the open-paren.
2843 (goto-char up-list-pos)
2844 (if (and (not tex-indent-allhanging)
2845 (save-excursion
2846 ;; Make sure we're an argument to a macro and
2847 ;; that the macro is at the beginning of a line.
2848 (condition-case nil
2849 (progn
2850 (while (eq (char-syntax (char-after)) ?\()
2851 (forward-sexp -1))
2852 (and (eq (char-syntax (char-after)) ?/)
2853 (progn (skip-chars-backward " \t&")
2854 (bolp))))
2855 (scan-error nil)))
2856 (> pos (progn (latex-down-list)
2857 (forward-comment (point-max))
2858 (point))))
2859 ;; Align with the first element after the open-paren.
2860 (current-column)
2861 ;; We're the first element after a hanging brace.
2862 (goto-char up-list-pos)
2863 (+ (if (and (looking-at "\\\\begin *{\\([^\n}]+\\)")
2864 (member (match-string 1)
2865 latex-noindent-environments))
2866 0 tex-indent-basic)
2867 indent (latex-find-indent 'virtual))))
2868 ;; We're now at the "beginning" of a line.
2869 ((not (and (not virtual) (eq (char-after) ?\\)))
2870 ;; Nothing particular here: just keep the same indentation.
2871 (+ indent (current-column)))
2872 ;; We're now looking at a macro call.
2873 ((looking-at tex-indent-item-re)
2874 ;; Indenting relative to an item, have to re-add the outdenting.
2875 (+ indent (current-column) tex-indent-item))
2876 (t
2877 (let ((col (current-column)))
2878 (if (or (not (eq (char-syntax (or (char-after pos) ?\s)) ?\())
2879 ;; Can't be an arg if there's an empty line in between.
2880 (save-excursion (re-search-forward "^[ \t]*$" pos t)))
2881 ;; If the first char was not an open-paren, there's
2882 ;; a risk that this is really not an argument to the
2883 ;; macro at all.
2884 (+ indent col)
2885 (forward-sexp 1)
2886 (if (< (line-end-position)
2887 (save-excursion (forward-comment (point-max))
2888 (point)))
2889 ;; we're indenting the first argument.
2890 (min (current-column) (+ tex-indent-arg col))
2891 (skip-syntax-forward " ")
2892 (current-column)))))))))))
2893 ;;; DocTeX support
2894
2895 (defun doctex-font-lock-^^A ()
2896 (if (eq (char-after (line-beginning-position)) ?\%)
2897 (progn
2898 (put-text-property
2899 (1- (match-beginning 1)) (match-beginning 1)
2900 'syntax-table
2901 (if (= (1+ (line-beginning-position)) (match-beginning 1))
2902 ;; The `%' is a single-char comment, which Emacs
2903 ;; syntax-table can't deal with. We could turn it
2904 ;; into a non-comment, or use `\n%' or `%^' as the comment.
2905 ;; Instead, we include it in the ^^A comment.
2906 (string-to-syntax "< b")
2907 (string-to-syntax ">")))
2908 (let ((end (line-end-position)))
2909 (if (< end (point-max))
2910 (put-text-property
2911 end (1+ end)
2912 'syntax-table
2913 (string-to-syntax "> b"))))
2914 (string-to-syntax "< b"))))
2915
2916 (defun doctex-font-lock-syntactic-face-function (state)
2917 ;; Mark DocTeX documentation, which is parsed as a style A comment
2918 ;; starting in column 0.
2919 (if (or (nth 3 state) (nth 7 state)
2920 (not (memq (char-before (nth 8 state))
2921 '(?\n nil))))
2922 ;; Anything else is just as for LaTeX.
2923 (tex-font-lock-syntactic-face-function state)
2924 font-lock-doc-face))
2925
2926 (eval-when-compile
2927 (defconst doctex-syntax-propertize-rules
2928 (syntax-propertize-precompile-rules
2929 latex-syntax-propertize-rules
2930 ;; For DocTeX comment-in-doc.
2931 ("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A))))))
2932
2933 (defvar doctex-font-lock-keywords
2934 (append tex-font-lock-keywords
2935 '(("^%<[^>]*>" (0 font-lock-preprocessor-face t)))))
2936
2937 ;;;###autoload
2938 (define-derived-mode doctex-mode latex-mode "DocTeX"
2939 "Major mode to edit DocTeX files."
2940 (setq font-lock-defaults
2941 (cons (append (car font-lock-defaults) '(doctex-font-lock-keywords))
2942 (mapcar
2943 (lambda (x)
2944 (pcase (car-safe x)
2945 (`font-lock-syntactic-face-function
2946 (cons (car x) 'doctex-font-lock-syntactic-face-function))
2947 (_ x)))
2948 (cdr font-lock-defaults))))
2949 (setq-local syntax-propertize-function
2950 (syntax-propertize-rules doctex-syntax-propertize-rules)))
2951
2952 ;;; Prettify Symbols Support
2953
2954 (defvar tex--prettify-symbols-alist
2955 '( ;; Lowercase Greek letters.
2956 ("\\alpha" . ?α)
2957 ("\\beta" . ?β)
2958 ("\\gamma" . ?γ)
2959 ("\\delta" . ?δ)
2960 ("\\epsilon" . ?ϵ)
2961 ("\\zeta" . ?ζ)
2962 ("\\eta" . ?η)
2963 ("\\theta" . ?θ)
2964 ("\\iota" . ?ι)
2965 ("\\kappa" . ?κ)
2966 ("\\lambda" . ?λ)
2967 ("\\mu" . ?μ)
2968 ("\\nu" . ?ν)
2969 ("\\xi" . ?ξ)
2970 ;; There is no \omicron because it looks like a latin o.
2971 ("\\pi" . ?π)
2972 ("\\rho" . ?ρ)
2973 ("\\sigma" . ?σ)
2974 ("\\tau" . ?τ)
2975 ("\\upsilon" . ?υ)
2976 ("\\phi" . ?φ)
2977 ("\\chi" . ?χ)
2978 ("\\psi" . ?ψ)
2979 ("\\omega" . ?ω)
2980 ;; Uppercase Greek letters.
2981 ("\\Gamma" . ?Γ)
2982 ("\\Delta" . ?Δ)
2983 ("\\Lambda" . ?Λ)
2984 ("\\Phi" . ?Φ)
2985 ("\\Pi" . ?Π)
2986 ("\\Psi" . ?Ψ)
2987 ("\\Sigma" . ?Σ)
2988 ("\\Theta" . ?Θ)
2989 ("\\Upsilon" . ?Υ)
2990 ("\\Xi" . ?Ξ)
2991 ("\\Omega" . ?Ω)
2992
2993 ;; Other math symbols (taken from leim/quail/latin-ltx.el).
2994 ("\\Box" . ?□)
2995 ("\\Bumpeq" . ?≎)
2996 ("\\Cap" . ?⋒)
2997 ("\\Cup" . ?⋓)
2998 ("\\Diamond" . ?◇)
2999 ("\\Downarrow" . ?⇓)
3000 ("\\H{o}" . ?ő)
3001 ("\\Im" . ?ℑ)
3002 ("\\Join" . ?⋈)
3003 ("\\Leftarrow" . ?⇐)
3004 ("\\Leftrightarrow" . ?⇔)
3005 ("\\Ll" . ?⋘)
3006 ("\\Lleftarrow" . ?⇚)
3007 ("\\Longleftarrow" . ?⇐)
3008 ("\\Longleftrightarrow" . ?⇔)
3009 ("\\Longrightarrow" . ?⇒)
3010 ("\\Lsh" . ?↰)
3011 ("\\Re" . ?ℜ)
3012 ("\\Rightarrow" . ?⇒)
3013 ("\\Rrightarrow" . ?⇛)
3014 ("\\Rsh" . ?↱)
3015 ("\\Subset" . ?⋐)
3016 ("\\Supset" . ?⋑)
3017 ("\\Uparrow" . ?⇑)
3018 ("\\Updownarrow" . ?⇕)
3019 ("\\Vdash" . ?⊩)
3020 ("\\Vert" . ?‖)
3021 ("\\Vvdash" . ?⊪)
3022 ("\\aleph" . ?ℵ)
3023 ("\\amalg" . ?∐)
3024 ("\\angle" . ?∠)
3025 ("\\approx" . ?≈)
3026 ("\\approxeq" . ?≊)
3027 ("\\ast" . ?∗)
3028 ("\\asymp" . ?≍)
3029 ("\\backcong" . ?≌)
3030 ("\\backepsilon" . ?∍)
3031 ("\\backprime" . ?‵)
3032 ("\\backsim" . ?∽)
3033 ("\\backsimeq" . ?⋍)
3034 ("\\backslash" . ?\\)
3035 ("\\barwedge" . ?⊼)
3036 ("\\because" . ?∵)
3037 ("\\beth" . ?ℶ)
3038 ("\\between" . ?≬)
3039 ("\\bigcap" . ?⋂)
3040 ("\\bigcirc" . ?◯)
3041 ("\\bigcup" . ?⋃)
3042 ("\\bigstar" . ?★)
3043 ("\\bigtriangledown" . ?▽)
3044 ("\\bigtriangleup" . ?△)
3045 ("\\bigvee" . ?⋁)
3046 ("\\bigwedge" . ?⋀)
3047 ("\\blacklozenge" . ?✦)
3048 ("\\blacksquare" . ?▪)
3049 ("\\blacktriangle" . ?▴)
3050 ("\\blacktriangledown" . ?▾)
3051 ("\\blacktriangleleft" . ?◂)
3052 ("\\blacktriangleright" . ?▸)
3053 ("\\bot" . ?⊥)
3054 ("\\bowtie" . ?⋈)
3055 ("\\boxminus" . ?⊟)
3056 ("\\boxplus" . ?⊞)
3057 ("\\boxtimes" . ?⊠)
3058 ("\\bullet" . ?•)
3059 ("\\bumpeq" . ?≏)
3060 ("\\cap" . ?∩)
3061 ("\\cdots" . ?⋯)
3062 ("\\centerdot" . ?·)
3063 ("\\checkmark" . ?✓)
3064 ("\\chi" . ?χ)
3065 ("\\cdot" . ?⋅)
3066 ("\\cdots" . ?⋯)
3067 ("\\circ" . ?∘)
3068 ("\\circeq" . ?≗)
3069 ("\\circlearrowleft" . ?↺)
3070 ("\\circlearrowright" . ?↻)
3071 ("\\circledR" . ?®)
3072 ("\\circledS" . ?Ⓢ)
3073 ("\\circledast" . ?⊛)
3074 ("\\circledcirc" . ?⊚)
3075 ("\\circleddash" . ?⊝)
3076 ("\\clubsuit" . ?♣)
3077 ("\\coloneq" . ?≔)
3078 ("\\complement" . ?∁)
3079 ("\\cong" . ?≅)
3080 ("\\coprod" . ?∐)
3081 ("\\cup" . ?∪)
3082 ("\\curlyeqprec" . ?⋞)
3083 ("\\curlyeqsucc" . ?⋟)
3084 ("\\curlypreceq" . ?≼)
3085 ("\\curlyvee" . ?⋎)
3086 ("\\curlywedge" . ?⋏)
3087 ("\\curvearrowleft" . ?↶)
3088 ("\\curvearrowright" . ?↷)
3089 ("\\dag" . ?†)
3090 ("\\dagger" . ?†)
3091 ("\\daleth" . ?ℸ)
3092 ("\\dashv" . ?⊣)
3093 ("\\ddag" . ?‡)
3094 ("\\ddagger" . ?‡)
3095 ("\\ddots" . ?⋱)
3096 ("\\diamond" . ?⋄)
3097 ("\\diamondsuit" . ?♢)
3098 ("\\divideontimes" . ?⋇)
3099 ("\\doteq" . ?≐)
3100 ("\\doteqdot" . ?≑)
3101 ("\\dotplus" . ?∔)
3102 ("\\dotsquare" . ?⊡)
3103 ("\\downarrow" . ?↓)
3104 ("\\downdownarrows" . ?⇊)
3105 ("\\downleftharpoon" . ?⇃)
3106 ("\\downrightharpoon" . ?⇂)
3107 ("\\ell" . ?ℓ)
3108 ("\\emptyset" . ?∅)
3109 ("\\eqcirc" . ?≖)
3110 ("\\eqcolon" . ?≕)
3111 ("\\eqslantgtr" . ?⋝)
3112 ("\\eqslantless" . ?⋜)
3113 ("\\equiv" . ?≡)
3114 ("\\exists" . ?∃)
3115 ("\\fallingdotseq" . ?≒)
3116 ("\\flat" . ?♭)
3117 ("\\forall" . ?∀)
3118 ("\\frown" . ?⌢)
3119 ("\\ge" . ?≥)
3120 ("\\geq" . ?≥)
3121 ("\\geqq" . ?≧)
3122 ("\\geqslant" . ?≥)
3123 ("\\gets" . ?←)
3124 ("\\gg" . ?≫)
3125 ("\\ggg" . ?⋙)
3126 ("\\gimel" . ?ℷ)
3127 ("\\gnapprox" . ?⋧)
3128 ("\\gneq" . ?≩)
3129 ("\\gneqq" . ?≩)
3130 ("\\gnsim" . ?⋧)
3131 ("\\gtrapprox" . ?≳)
3132 ("\\gtrdot" . ?⋗)
3133 ("\\gtreqless" . ?⋛)
3134 ("\\gtreqqless" . ?⋛)
3135 ("\\gtrless" . ?≷)
3136 ("\\gtrsim" . ?≳)
3137 ("\\gvertneqq" . ?≩)
3138 ("\\hbar" . ?ℏ)
3139 ("\\heartsuit" . ?♥)
3140 ("\\hookleftarrow" . ?↩)
3141 ("\\hookrightarrow" . ?↪)
3142 ("\\iff" . ?⇔)
3143 ("\\imath" . ?ı)
3144 ("\\in" . ?∈)
3145 ("\\infty" . ?∞)
3146 ("\\int" . ?∫)
3147 ("\\intercal" . ?⊺)
3148 ("\\langle" . 10216) ; Literal ?⟨ breaks indentation.
3149 ("\\lbrace" . ?{)
3150 ("\\lbrack" . ?\[)
3151 ("\\lceil" . ?⌈)
3152 ("\\ldots" . ?…)
3153 ("\\le" . ?≤)
3154 ("\\leadsto" . ?↝)
3155 ("\\leftarrow" . ?←)
3156 ("\\leftarrowtail" . ?↢)
3157 ("\\leftharpoondown" . ?↽)
3158 ("\\leftharpoonup" . ?↼)
3159 ("\\leftleftarrows" . ?⇇)
3160 ;; ("\\leftparengtr" ?〈), see bug#12948.
3161 ("\\leftrightarrow" . ?↔)
3162 ("\\leftrightarrows" . ?⇆)
3163 ("\\leftrightharpoons" . ?⇋)
3164 ("\\leftrightsquigarrow" . ?↭)
3165 ("\\leftthreetimes" . ?⋋)
3166 ("\\leq" . ?≤)
3167 ("\\leqq" . ?≦)
3168 ("\\leqslant" . ?≤)
3169 ("\\lessapprox" . ?≲)
3170 ("\\lessdot" . ?⋖)
3171 ("\\lesseqgtr" . ?⋚)
3172 ("\\lesseqqgtr" . ?⋚)
3173 ("\\lessgtr" . ?≶)
3174 ("\\lesssim" . ?≲)
3175 ("\\lfloor" . ?⌊)
3176 ("\\lhd" . ?◁)
3177 ("\\rhd" . ?▷)
3178 ("\\ll" . ?≪)
3179 ("\\llcorner" . ?⌞)
3180 ("\\lnapprox" . ?⋦)
3181 ("\\lneq" . ?≨)
3182 ("\\lneqq" . ?≨)
3183 ("\\lnsim" . ?⋦)
3184 ("\\longleftarrow" . ?←)
3185 ("\\longleftrightarrow" . ?↔)
3186 ("\\longmapsto" . ?↦)
3187 ("\\longrightarrow" . ?→)
3188 ("\\looparrowleft" . ?↫)
3189 ("\\looparrowright" . ?↬)
3190 ("\\lozenge" . ?✧)
3191 ("\\lq" . ?‘)
3192 ("\\lrcorner" . ?⌟)
3193 ("\\ltimes" . ?⋉)
3194 ("\\lvertneqq" . ?≨)
3195 ("\\maltese" . ?✠)
3196 ("\\mapsto" . ?↦)
3197 ("\\measuredangle" . ?∡)
3198 ("\\mho" . ?℧)
3199 ("\\mid" . ?∣)
3200 ("\\models" . ?⊧)
3201 ("\\mp" . ?∓)
3202 ("\\multimap" . ?⊸)
3203 ("\\nLeftarrow" . ?⇍)
3204 ("\\nLeftrightarrow" . ?⇎)
3205 ("\\nRightarrow" . ?⇏)
3206 ("\\nVDash" . ?⊯)
3207 ("\\nVdash" . ?⊮)
3208 ("\\nabla" . ?∇)
3209 ("\\napprox" . ?≉)
3210 ("\\natural" . ?♮)
3211 ("\\ncong" . ?≇)
3212 ("\\ne" . ?≠)
3213 ("\\nearrow" . ?↗)
3214 ("\\neg" . ?¬)
3215 ("\\neq" . ?≠)
3216 ("\\nequiv" . ?≢)
3217 ("\\newline" . ?
)
3218 ("\\nexists" . ?∄)
3219 ("\\ngeq" . ?≱)
3220 ("\\ngeqq" . ?≱)
3221 ("\\ngeqslant" . ?≱)
3222 ("\\ngtr" . ?≯)
3223 ("\\ni" . ?∋)
3224 ("\\nleftarrow" . ?↚)
3225 ("\\nleftrightarrow" . ?↮)
3226 ("\\nleq" . ?≰)
3227 ("\\nleqq" . ?≰)
3228 ("\\nleqslant" . ?≰)
3229 ("\\nless" . ?≮)
3230 ("\\nmid" . ?∤)
3231 ;; ("\\not" ?̸) ;FIXME: conflict with "NOT SIGN" ¬.
3232 ("\\notin" . ?∉)
3233 ("\\nparallel" . ?∦)
3234 ("\\nprec" . ?⊀)
3235 ("\\npreceq" . ?⋠)
3236 ("\\nrightarrow" . ?↛)
3237 ("\\nshortmid" . ?∤)
3238 ("\\nshortparallel" . ?∦)
3239 ("\\nsim" . ?≁)
3240 ("\\nsimeq" . ?≄)
3241 ("\\nsubset" . ?⊄)
3242 ("\\nsubseteq" . ?⊈)
3243 ("\\nsubseteqq" . ?⊈)
3244 ("\\nsucc" . ?⊁)
3245 ("\\nsucceq" . ?⋡)
3246 ("\\nsupset" . ?⊅)
3247 ("\\nsupseteq" . ?⊉)
3248 ("\\nsupseteqq" . ?⊉)
3249 ("\\ntriangleleft" . ?⋪)
3250 ("\\ntrianglelefteq" . ?⋬)
3251 ("\\ntriangleright" . ?⋫)
3252 ("\\ntrianglerighteq" . ?⋭)
3253 ("\\nvDash" . ?⊭)
3254 ("\\nvdash" . ?⊬)
3255 ("\\nwarrow" . ?↖)
3256 ("\\odot" . ?⊙)
3257 ("\\oint" . ?∮)
3258 ("\\ominus" . ?⊖)
3259 ("\\oplus" . ?⊕)
3260 ("\\oslash" . ?⊘)
3261 ("\\otimes" . ?⊗)
3262 ("\\par" . ?
)
3263 ("\\parallel" . ?∥)
3264 ("\\partial" . ?∂)
3265 ("\\perp" . ?⊥)
3266 ("\\pitchfork" . ?⋔)
3267 ("\\prec" . ?≺)
3268 ("\\precapprox" . ?≾)
3269 ("\\preceq" . ?≼)
3270 ("\\precnapprox" . ?⋨)
3271 ("\\precnsim" . ?⋨)
3272 ("\\precsim" . ?≾)
3273 ("\\prime" . ?′)
3274 ("\\prod" . ?∏)
3275 ("\\propto" . ?∝)
3276 ("\\qed" . ?∎)
3277 ("\\qquad" . ?⧢)
3278 ("\\quad" . ?␣)
3279 ("\\rangle" . 10217) ; Literal ?⟩ breaks indentation.
3280 ("\\rbrace" . ?})
3281 ("\\rbrack" . ?\])
3282 ("\\rceil" . ?⌉)
3283 ("\\rfloor" . ?⌋)
3284 ("\\rightarrow" . ?→)
3285 ("\\rightarrowtail" . ?↣)
3286 ("\\rightharpoondown" . ?⇁)
3287 ("\\rightharpoonup" . ?⇀)
3288 ("\\rightleftarrows" . ?⇄)
3289 ("\\rightleftharpoons" . ?⇌)
3290 ;; ("\\rightparengtr" ?⦔) ;; Was ?〉, see bug#12948.
3291 ("\\rightrightarrows" . ?⇉)
3292 ("\\rightthreetimes" . ?⋌)
3293 ("\\risingdotseq" . ?≓)
3294 ("\\rtimes" . ?⋊)
3295 ("\\times" . ?×)
3296 ("\\sbs" . ?﹨)
3297 ("\\searrow" . ?↘)
3298 ("\\setminus" . ?∖)
3299 ("\\sharp" . ?♯)
3300 ("\\shortmid" . ?∣)
3301 ("\\shortparallel" . ?∥)
3302 ("\\sim" . ?∼)
3303 ("\\simeq" . ?≃)
3304 ("\\smallamalg" . ?∐)
3305 ("\\smallsetminus" . ?∖)
3306 ("\\smallsmile" . ?⌣)
3307 ("\\smile" . ?⌣)
3308 ("\\spadesuit" . ?♠)
3309 ("\\sphericalangle" . ?∢)
3310 ("\\sqcap" . ?⊓)
3311 ("\\sqcup" . ?⊔)
3312 ("\\sqsubset" . ?⊏)
3313 ("\\sqsubseteq" . ?⊑)
3314 ("\\sqsupset" . ?⊐)
3315 ("\\sqsupseteq" . ?⊒)
3316 ("\\square" . ?□)
3317 ("\\squigarrowright" . ?⇝)
3318 ("\\star" . ?⋆)
3319 ("\\straightphi" . ?φ)
3320 ("\\subset" . ?⊂)
3321 ("\\subseteq" . ?⊆)
3322 ("\\subseteqq" . ?⊆)
3323 ("\\subsetneq" . ?⊊)
3324 ("\\subsetneqq" . ?⊊)
3325 ("\\succ" . ?≻)
3326 ("\\succapprox" . ?≿)
3327 ("\\succcurlyeq" . ?≽)
3328 ("\\succeq" . ?≽)
3329 ("\\succnapprox" . ?⋩)
3330 ("\\succnsim" . ?⋩)
3331 ("\\succsim" . ?≿)
3332 ("\\sum" . ?∑)
3333 ("\\supset" . ?⊃)
3334 ("\\supseteq" . ?⊇)
3335 ("\\supseteqq" . ?⊇)
3336 ("\\supsetneq" . ?⊋)
3337 ("\\supsetneqq" . ?⊋)
3338 ("\\surd" . ?√)
3339 ("\\swarrow" . ?↙)
3340 ("\\therefore" . ?∴)
3341 ("\\thickapprox" . ?≈)
3342 ("\\thicksim" . ?∼)
3343 ("\\to" . ?→)
3344 ("\\top" . ?⊤)
3345 ("\\triangle" . ?▵)
3346 ("\\triangledown" . ?▿)
3347 ("\\triangleleft" . ?◃)
3348 ("\\trianglelefteq" . ?⊴)
3349 ("\\triangleq" . ?≜)
3350 ("\\triangleright" . ?▹)
3351 ("\\trianglerighteq" . ?⊵)
3352 ("\\twoheadleftarrow" . ?↞)
3353 ("\\twoheadrightarrow" . ?↠)
3354 ("\\ulcorner" . ?⌜)
3355 ("\\uparrow" . ?↑)
3356 ("\\updownarrow" . ?↕)
3357 ("\\upleftharpoon" . ?↿)
3358 ("\\uplus" . ?⊎)
3359 ("\\uprightharpoon" . ?↾)
3360 ("\\upuparrows" . ?⇈)
3361 ("\\urcorner" . ?⌝)
3362 ("\\u{i}" . ?ĭ)
3363 ("\\vDash" . ?⊨)
3364 ("\\varepsilon" . ?ε)
3365 ("\\varprime" . ?′)
3366 ("\\varpropto" . ?∝)
3367 ("\\varrho" . ?ϱ)
3368 ;; ("\\varsigma" ?ς) ;FIXME: Looks reversed with the non\var.
3369 ("\\vartriangleleft" . ?⊲)
3370 ("\\vartriangleright" . ?⊳)
3371 ("\\vdash" . ?⊢)
3372 ("\\vdots" . ?⋮)
3373 ("\\vee" . ?∨)
3374 ("\\veebar" . ?⊻)
3375 ("\\vert" . ?|)
3376 ("\\wedge" . ?∧)
3377 ("\\wp" . ?℘)
3378 ("\\wr" . ?≀)
3379 ("\\Bbb{N}" . ?ℕ) ; AMS commands for blackboard bold
3380 ("\\Bbb{P}" . ?ℙ) ; Also sometimes \mathbb.
3381 ("\\Bbb{Q}" . ?ℚ)
3382 ("\\Bbb{R}" . ?ℝ)
3383 ("\\Bbb{Z}" . ?ℤ)
3384 ("--" . ?–)
3385 ("---" . ?—)
3386 ("\\ordfeminine" . ?ª)
3387 ("\\ordmasculine" . ?º)
3388 ("\\lambdabar" . ?ƛ)
3389 ("\\celsius" . ?℃)
3390 ("\\textmu" . ?µ)
3391 ("\\textfractionsolidus" . ?⁄)
3392 ("\\textbigcircle" . ?⃝)
3393 ("\\textmusicalnote" . ?♪)
3394 ("\\textdied" . ?✝)
3395 ("\\textcolonmonetary" . ?₡)
3396 ("\\textwon" . ?₩)
3397 ("\\textnaira" . ?₦)
3398 ("\\textpeso" . ?₱)
3399 ("\\textlira" . ?₤)
3400 ("\\textrecipe" . ?℞)
3401 ("\\textinterrobang" . ?‽)
3402 ("\\textpertenthousand" . ?‱)
3403 ("\\textbaht" . ?฿)
3404 ("\\textnumero" . ?№)
3405 ("\\textdiscount" . ?⁒)
3406 ("\\textestimated" . ?℮)
3407 ("\\textopenbullet" . ?◦)
3408 ("\\textlquill" . 8261) ; Literal ?⁅ breaks indentation.
3409 ("\\textrquill" . 8262) ; Literal ?⁆ breaks indentation.
3410 ("\\textcircledP" . ?℗)
3411 ("\\textreferencemark" . ?※))
3412 "A `prettify-symbols-alist' usable for (La)TeX modes.")
3413
3414 (defun tex--prettify-symbols-compose-p (_start end _match)
3415 (or
3416 ;; If the matched symbol doesn't end in a word character, then we
3417 ;; simply allow composition. The symbol is probably something like
3418 ;; \|, \(, etc.
3419 (not (eq ?w (char-syntax (char-before end))))
3420 ;; Else we look at what follows the match in order to decide.
3421 (let* ((after-char (char-after end))
3422 (after-syntax (char-syntax after-char)))
3423 (not (or
3424 ;; Don't compose \alpha@foo.
3425 (eq after-char ?@)
3426 ;; The \alpha in \alpha2 or \alpha-\beta may be composed but
3427 ;; of course \alphax may not.
3428 (and (eq after-syntax ?w)
3429 (not (memq after-char
3430 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?+ ?- ?' ?\"))))
3431 ;; Don't compose inside verbatim blocks.
3432 (eq 2 (nth 7 (syntax-ppss))))))))
3433
3434 (run-hooks 'tex-mode-load-hook)
3435
3436 (provide 'tex-mode)
3437
3438 ;;; tex-mode.el ends here