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