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