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