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