Initial Commit
[packages] / xemacs-packages / auctex / tex-buf.el
1 ;;; tex-buf.el --- External commands for AUCTeX.
2
3 ;; Copyright (C) 1991-1999, 2001-2014 Free Software Foundation, Inc.
4
5 ;; Maintainer: auctex-devel@gnu.org
6 ;; Keywords: tex, wp
7
8 ;; This file is part of AUCTeX.
9
10 ;; AUCTeX is free software; you can redistribute it and/or modify it
11 ;; under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 3, or (at your option)
13 ;; any later version.
14
15 ;; AUCTeX is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 ;; General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with AUCTeX; see the file COPYING.  If not, write to the Free
22 ;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
23 ;; 02110-1301, USA.
24
25 ;;; Commentary:
26
27 ;; This file provides support for external commands.
28
29 ;;; Code:
30
31 (require 'tex)
32
33 ;;; Customization:
34
35 (defcustom TeX-process-asynchronous (not (eq system-type 'ms-dos))
36   "*Use asynchronous processes."
37   :group 'TeX-command
38   :type 'boolean)
39
40 (defcustom TeX-shell
41   (if (memq system-type '(ms-dos emx windows-nt))
42       shell-file-name
43     "/bin/sh")
44   "Name of shell used to parse TeX commands."
45   :group 'TeX-command
46   :type 'file)
47
48 (defcustom TeX-shell-command-option
49   (cond ((memq system-type '(ms-dos emx windows-nt) )
50          (cond ((boundp 'shell-command-option)
51                 shell-command-option)
52                ((boundp 'shell-command-switch)
53                 shell-command-switch)
54                (t
55                 "/c")))
56         (t                              ;Unix & EMX (Emacs 19 port to OS/2)
57          "-c"))
58   "Shell argument indicating that next argument is the command."
59   :group 'TeX-command
60   :type 'string)
61
62 ;;; Interactive Commands
63 ;;
64 ;; The general idea is, that there is one process and process buffer
65 ;; associated with each master file, and one process and process buffer
66 ;; for running TeX on a region.   Thus, if you have N master files, you
67 ;; can run N + 1 processes simultaneously.
68 ;;
69 ;; Some user commands operates on ``the'' process.  The following
70 ;; algorithm determine what ``the'' process is.
71 ;;
72 ;; IF   last process started was on a region
73 ;; THEN ``the'' process is the region process
74 ;; ELSE ``the'' process is the master file (of the current buffer) process
75
76 (defun TeX-save-document (name)
77   "Save all files belonging to the current document.
78 Return non-nil if document needs to be re-TeX'ed."
79   (interactive (list (TeX-master-file)))
80   (if (string-equal name "")
81       (setq name (TeX-master-file)))
82
83   (TeX-check-files (concat name "." (TeX-output-extension))
84                    (cons name (TeX-style-list))
85                    TeX-file-extensions))
86
87 (defun TeX-command-master (&optional override-confirm)
88   "Run command on the current document.
89
90 If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
91 depend on it being positive instead of the entry in `TeX-command-list'."
92   (interactive "P")
93   (TeX-command (TeX-command-query (TeX-master-file nil nil t))
94                'TeX-master-file override-confirm))
95
96 (defvar TeX-command-region-begin nil)
97 (defvar TeX-command-region-end nil)
98 ;; Used for marking the last region.
99
100 (make-variable-buffer-local 'TeX-command-region-begin)
101 (make-variable-buffer-local 'TeX-command-region-end)
102
103 (defun TeX-current-offset (&optional pos)
104   "Calculate line offset of POS, or of point if POS is nil."
105   (save-restriction
106     (widen)
107     (save-excursion
108       (let ((inhibit-point-motion-hooks t)
109             (inhibit-field-text-motion t))
110         (if pos (goto-char pos))
111         (+ (count-lines (point-min) (point))
112            (if (bolp) 0 -1))))))
113
114 (defun TeX-pin-region (begin end)
115   "Pin the TeX region specified by BEGIN and END.
116 If BEGIN is nil, the region is unpinned.
117
118 In interactive use, a positive prefix arg will pin the region,
119 a non-positive one will unpin it.  Without a prefix arg, if
120 a region is actively marked, it will get pinned.  If not, a
121 pinned region will get unpinned and vice versa."
122   (interactive
123    (if
124        (if current-prefix-arg
125            (> (prefix-numeric-value current-prefix-arg) 0)
126          (or (TeX-active-mark)
127              (null TeX-command-region-begin)))
128        (list (region-beginning) (region-end))
129      '(nil nil)))
130   (if begin
131       (progn
132         (unless (markerp TeX-command-region-begin)
133           (setq TeX-command-region-begin (make-marker))
134           (setq TeX-command-region-end (make-marker)))
135         (set-marker TeX-command-region-begin begin)
136         (set-marker TeX-command-region-end end)
137         (message "TeX region pinned."))
138     (when (markerp TeX-command-region-begin)
139       (set-marker TeX-command-region-begin nil)
140       (set-marker TeX-command-region-end nil))
141     (setq TeX-command-region-begin nil)
142     (setq TeX-command-region-end nil)
143     (message "TeX region unpinned.")))
144
145 (defun TeX-command-region (&optional override-confirm)
146   "Run TeX on the current region.
147
148 Query the user for a command to run on the temporary file specified by
149 the variable `TeX-region'.  If there is an explicitly active region,
150 it is stored for later commands.  If not, a previously stored region
151 \(can be also be set with `TeX-pin-region') overrides the current region,
152 if present.
153
154 If a prefix argument OVERRIDE-CONFIRM is given, prompting will
155 ignore the prompting flag from `TeX-command-list' and instead
156 will prompt iff the prefix is positive.
157
158 If the master file for the document has a header, it is written to the
159 temporary file before the region itself.  The document's header is all
160 text before `TeX-header-end'.
161
162 If the master file for the document has a trailer, it is written to
163 the temporary file before the region itself.  The document's trailer is
164 all text after `TeX-trailer-start'."
165   (interactive "P")
166   ;; Note that TeX-command-region-begin is not a marker when called
167   ;; from TeX-command-buffer.
168   (and (or (null TeX-command-region-begin)
169            (markerp TeX-command-region-begin))
170        (TeX-active-mark)
171        (TeX-pin-region (region-beginning) (region-end)))
172   (let ((begin (or TeX-command-region-begin (region-beginning)))
173         (end (or TeX-command-region-end (region-end))))
174     (TeX-region-create (TeX-region-file TeX-default-extension)
175                        (buffer-substring begin end)
176                        (file-name-nondirectory (buffer-file-name))
177                        (TeX-current-offset begin)))
178   (TeX-command (TeX-command-query (TeX-region-file nil t)) 'TeX-region-file
179                override-confirm))
180
181 (defun TeX-command-buffer (&optional override-confirm)
182   "Run TeX on the current buffer.
183
184 Query the user for a command to run on the temporary file specified by
185 the variable `TeX-region'.  The region file will be recreated from the
186 visible part of the buffer.
187
188 If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
189 depend on it being positive instead of the entry in `TeX-command-list'."
190   (interactive "P")
191   (let ((TeX-command-region-begin (point-min))
192         (TeX-command-region-end (point-max)))
193     (TeX-command-region override-confirm)))
194
195 (unless (featurep 'xemacs)
196   ;; This variable is not defined in XEmacs because XEmacs' version of
197   ;; `pop-to-buffer' doesn't support the optional NORECORD argument.  In
198   ;; XEmacs, the third arg is ON-FRAME (Emacs: NORECORD).
199   (defcustom TeX-record-buffer nil
200     "Whether to record buffer names of generated TeX buffers.
201 When non-nil, these buffers are put at the front of the list of
202 recently selected ones."
203     :group 'TeX-command
204     :type 'boolean))
205
206 (defun TeX-pop-to-buffer (buffer &optional other-window norecord)
207   "Compatibility wrapper for `pop-to-buffer'.
208
209 Select buffer BUFFER in some window, preferably a different one.
210 BUFFER may be a buffer, a string (a buffer name), or nil.
211 If BUFFER is a string which is not the name of an existing buffer,
212 then this function creates a buffer with that name.
213 If BUFFER is nil, then it chooses some other buffer.
214 If `pop-up-windows' is non-nil, windows can be split to do this.
215 If optional second arg OTHER-WINDOW is non-nil, insist on finding another
216 window even if BUFFER is already visible in the selected window,
217 and ignore `same-window-regexps' and `same-window-buffer-names'.
218 This function returns the buffer it switched to.
219 This uses the function `display-buffer' as a subroutine; see the documentation
220 of `display-buffer' for additional customization information.
221
222 Optional third arg NORECORD non-nil means do not put this buffer
223 at the front of the list of recently selected ones.
224
225 NORECORD is ignored in XEmacs."
226   ;; Make sure not to use third arg in XEmacs.  In XEmacs, the third arg is
227   ;; ON-FRAME (Emacs: NORECORD), so we set it to nil.
228   (pop-to-buffer buffer other-window (and norecord
229                                           (boundp 'TeX-record-buffer)
230                                           TeX-record-buffer)))
231
232 (defun TeX-recenter-output-buffer (line)
233   "Redisplay buffer of TeX job output so that most recent output can be seen.
234 The last line of the buffer is displayed on line LINE of the window, or
235 at bottom if LINE is nil."
236   (interactive "P")
237   (let ((buffer (TeX-active-buffer)))
238     (if buffer
239         (let ((old-buffer (current-buffer)))
240           (TeX-pop-to-buffer buffer t t)
241           (bury-buffer buffer)
242           (goto-char (point-max))
243           (recenter (if line
244                         (prefix-numeric-value line)
245                       (/ (window-height) 2)))
246           (TeX-pop-to-buffer old-buffer nil t))
247       (message "No process for this document."))))
248
249 (defun TeX-kill-job ()
250   "Kill the currently running TeX job."
251   (interactive)
252   (let ((process (TeX-active-process)))
253     (if process
254         (kill-process process)
255       ;; Should test for TeX background process here.
256       (error "No TeX process to kill"))))
257
258 (defun TeX-home-buffer ()
259   "Go to the buffer where you last issued a TeX command.
260 If there is no such buffer, or you already are in that buffer, find
261 the master file."
262   (interactive)
263   (if (or (null TeX-command-buffer)
264           (null (buffer-name TeX-command-buffer))
265           (eq TeX-command-buffer (current-buffer)))
266       (find-file (TeX-master-file TeX-default-extension))
267     (switch-to-buffer TeX-command-buffer)))
268
269 (defvar TeX-error-last-visited -1
270   "Index of the last visited error listed in `TeX-error-list'.
271
272 This variable is intended to be set only in output buffer so it
273 will be shared among all files of the same document.")
274 (make-variable-buffer-local 'TeX-error-last-visited)
275
276 (defun TeX-get-parse-function ()
277   "Get the parse function for the current buffer."
278   (with-current-buffer TeX-command-buffer
279     (TeX-process-get-variable (TeX-active-master) 'TeX-parse-function)))
280
281 (defun TeX-next-error (&optional arg reparse)
282   "Find the next error in the TeX output buffer.
283
284 A prefix ARG specifies how many error messages to move;
285 negative means move back to previous error messages, if possible.
286
287 If REPARSE is non-nil, reparse the error message buffer.
288
289 \\[universal-argument] as a prefix means reparse the error
290 message buffer and start at the first error."
291   (interactive "P")
292   (if (or (null (TeX-active-buffer))
293           (eq 'compilation-mode (with-current-buffer TeX-command-buffer
294                                   major-mode)))
295       (if (featurep 'xemacs)
296           (next-error arg)
297         (next-error arg reparse))
298
299     ;; Force reparsing when the function is called with a universal-argument.
300     (if (consp arg) (setq reparse t arg nil))
301
302     (funcall (TeX-get-parse-function) arg reparse)))
303
304 (defun TeX-previous-error (arg)
305   "Find the previous error in the TeX output buffer.
306
307 Prefix arg N says how many error messages to move backward (or
308 forward, if negative).
309
310 This works only with TeX commands and if the
311 `TeX-parse-all-errors' variable is non-nil."
312   (interactive "p")
313   (if (or (null (TeX-active-buffer))
314           (eq 'compilation-mode (with-current-buffer TeX-command-buffer
315                                   major-mode)))
316       (previous-error arg)
317
318     (let ((parse-function (TeX-get-parse-function)))
319       (if (and TeX-parse-all-errors (equal parse-function 'TeX-parse-TeX))
320           ;; When `TeX-parse-all-errors' is non-nil and the parsing function is
321           ;; `TeX-parse-TeX' we can move backward in the errors.
322           (TeX-parse-TeX (- arg) nil)
323         ;; XXX: moving backward in the errors hasn't yet been implemented for
324         ;; other parsing functions.
325         (error "Jumping to previous error not supported.")))))
326
327 ;;; Command Query
328
329 (defvar TeX-error-overview-frame nil
330   "The frame of the error overview.")
331
332 (defconst TeX-error-overview-buffer-name "*TeX errors*"
333   "Name of the buffer in which to show error list.")
334
335 (defun TeX-command (name file &optional override-confirm)
336   "Run command NAME on the file returned by calling FILE.
337
338 FILE is the symbol of a function returning a file name.  The
339 function has one optional argument, the extension to use on the
340 file.
341
342 Use the information in `TeX-command-list' to determine how to run
343 the command.
344
345 If OVERRIDE-CONFIRM is a prefix argument, confirmation will be
346 asked if it is positive, and suppressed if it is not."
347   (cond ((eq file 'TeX-region-file)
348          (setq TeX-current-process-region-p t))
349         ((eq file 'TeX-master-file)
350          (setq TeX-current-process-region-p nil)))
351   (let ((command (TeX-command-expand (nth 1 (assoc name TeX-command-list))
352                                      file))
353         (hook (nth 2 (assoc name TeX-command-list)))
354         (confirm (if override-confirm
355                      (> (prefix-numeric-value override-confirm) 0)
356                    (nth 3 (assoc name TeX-command-list)))))
357
358     ;; Verify the expanded command
359     (if confirm
360         (setq command
361               (read-from-minibuffer (concat name " command: ") command
362                                     nil nil)))
363
364     ;; Kill the frame and buffer associated to the error overview before running
365     ;; the command, but keep them if the command to be run is View.
366     (unless (string= name "View")
367       (if (frame-live-p TeX-error-overview-frame)
368                    (delete-frame TeX-error-overview-frame))
369      (if (get-buffer TeX-error-overview-buffer-name)
370          (kill-buffer TeX-error-overview-buffer-name)))
371
372     ;; Now start the process
373     (setq file (funcall file))
374     (TeX-process-set-variable file 'TeX-command-next TeX-command-Show)
375     (funcall hook name command file)))
376
377 (defun TeX-command-expand (command file &optional list)
378   "Expand COMMAND for FILE as described in LIST.
379 LIST default to `TeX-expand-list'.  As a special exception,
380 `%%' can be used to produce a single `%' sign in the output
381 without further expansion."
382   (let (pat
383         pos
384         entry TeX-command-text TeX-command-pos
385         (file `(lambda (&rest args)
386                  (shell-quote-argument
387                   (concat (and (stringp TeX-command-pos) TeX-command-pos)
388                           (apply ',file args)
389                           (and (stringp TeX-command-pos) TeX-command-pos)))))
390         expansion-res case-fold-search string expansion arguments)
391     (setq list (cons
392                 (list "%%" (lambda nil
393                              (setq pos (1+ pos))
394                              "%"))
395                 (or list TeX-expand-list))
396           pat (regexp-opt (mapcar #'car list)))
397     (while (setq pos (string-match pat command pos))
398       (setq string (match-string 0 command)
399             entry (assoc string list)
400             expansion (car (cdr entry)) ;Second element
401             arguments (cdr (cdr entry)) ;Remaining elements
402             string (save-match-data
403                      ;; Note regarding the special casing of `file':
404                      ;; `file' is prevented from being evaluated as a
405                      ;; function because inside of AUCTeX it only has
406                      ;; a meaning as a variable.  This makes sure that
407                      ;; a function definition made by an external
408                      ;; package (e.g. icicles) is not picked up.
409                      (cond ((and (not (eq expansion 'file))
410                                  (TeX-function-p expansion))
411                             (apply expansion arguments))
412                            ((boundp expansion)
413                             (setq expansion-res
414                                   (apply (eval expansion) arguments))
415                             (when (eq expansion 'file)
416                               ;; Advance past the file name in order to
417                               ;; prevent expanding any substring of it.
418                               (setq pos (+ pos (length expansion-res))))
419                               expansion-res)
420                            (t
421                             (error "Nonexpansion %s" expansion)))))
422       (if (stringp string)
423           (setq command
424                 (replace-match string t t command)))))
425   command)
426
427 (defun TeX-check-files (derived originals extensions)
428   "Check if DERIVED is newer than any of the ORIGINALS.
429 Try each original with each member of EXTENSIONS, in all directories
430 in `TeX-check-path'. Returns true if any of the ORIGINALS with any of the
431 EXTENSIONS are newer than DERIVED. Will prompt to save the buffer of any
432 ORIGINALS which are modified but not saved yet."
433   (let (existingoriginals
434         found
435         (extensions (TeX-delete-duplicate-strings extensions))
436         (buffers (buffer-list)))
437     (dolist (path (mapcar (lambda (dir)
438                             (expand-file-name (file-name-as-directory dir)))
439                           TeX-check-path))
440       (dolist (orig originals)
441         (dolist (ext extensions)
442           (let ((filepath (concat path orig "." ext)))
443             (if (or (file-exists-p filepath)
444                     (get-file-buffer filepath))
445                 (setq existingoriginals (cons filepath existingoriginals)))))))
446     (while buffers
447       (let* ((buffer (car buffers))
448              (name (buffer-file-name buffer)))
449         (setq buffers (cdr buffers))
450         (if (and name (member name existingoriginals))
451             (progn
452               (and (buffer-modified-p buffer)
453                    (or (not TeX-save-query)
454                        (y-or-n-p (concat "Save file "
455                                          (buffer-file-name buffer)
456                                          "? ")))
457                    (with-current-buffer buffer (save-buffer)))))))
458     (dolist (eo existingoriginals)
459       (if (file-newer-than-file-p eo derived)
460           (setq found t)))
461     found))
462
463 (defcustom TeX-save-query t
464   "*If non-nil, ask user for permission to save files before starting TeX."
465   :group 'TeX-command
466   :type 'boolean)
467
468 (defvar TeX-command-history nil)
469
470 (defun TeX-command-query (name)
471   "Query the user for what TeX command to use."
472   (let* ((default
473            (cond ((if (string-equal name TeX-region)
474                       (TeX-check-files (concat name "." (TeX-output-extension))
475                                        (list name)
476                                        TeX-file-extensions)
477                     (TeX-save-document (TeX-master-file)))
478                   TeX-command-default)
479                  ((and (memq major-mode '(doctex-mode latex-mode))
480                        ;; Want to know if bib file is newer than .bbl
481                        ;; We don't care whether the bib files are open in emacs
482                        (TeX-check-files (concat name ".bbl")
483                                         (mapcar 'car
484                                                 (LaTeX-bibliography-list))
485                                         (append BibTeX-file-extensions
486                                                 TeX-Biber-file-extensions)))
487                   ;; We should check for bst files here as well.
488                   (if LaTeX-using-Biber TeX-command-Biber TeX-command-BibTeX))
489                  ((TeX-process-get-variable name
490                                             'TeX-command-next
491                                             TeX-command-Show))
492                  (TeX-command-Show)))
493          (completion-ignore-case t)
494          (answer (or TeX-command-force
495                      (completing-read
496                       (concat "Command: (default " default ") ")
497                       (TeX-mode-specific-command-list major-mode) nil t
498                       nil 'TeX-command-history default))))
499     ;; If the answer is "latex" it will not be expanded to "LaTeX"
500     (setq answer (car-safe (TeX-assoc answer TeX-command-list)))
501     (if (and answer
502              (not (string-equal answer "")))
503         answer
504       default)))
505
506 (defvar TeX-command-next nil
507   "The default command next time `TeX-command' is invoked.")
508
509  (make-variable-buffer-local 'TeX-command-next)
510
511 (defun TeX-printer-query (&optional queue)
512   "Query the user for a printer name.
513 QUEUE is non-nil when we are checking for the printer queue."
514   (let (command element printer)
515     (if queue
516         (unless (setq element 2 command TeX-queue-command)
517           (error "Need to customize `TeX-queue-command'"))
518       (unless (setq element 1 command TeX-print-command)
519           (error "Need to customize `TeX-print-command'")))
520     (while (progn
521              (setq printer (if TeX-printer-list
522                                (let ((completion-ignore-case t))
523                                  (completing-read
524                                   (concat "Printer: "
525                                           (and TeX-printer-default
526                                                (concat "(default "
527                                                        TeX-printer-default ") ")))
528                                   TeX-printer-list))
529                              ""))
530              (setq printer (or (car-safe (TeX-assoc printer TeX-printer-list))
531                                printer))
532              (not (if (or (null printer) (string-equal "" printer))
533                       (setq printer TeX-printer-default)
534                     (setq TeX-printer-default printer)))))
535
536     (let ((expansion (let ((entry (assoc printer TeX-printer-list)))
537                        (or (nth element entry)
538                            command))))
539       (if (string-match "%p" printer)
540           (error "Don't use %s in printer names" "%p"))
541       (while (string-match "%p" expansion)
542         (setq expansion (replace-match printer t t expansion 0)))
543       expansion)))
544
545 (defun TeX-style-check (styles)
546   "Check STYLES compared to the current style options."
547   (let ((files (TeX-style-list)))
548     (while (and styles
549                 (not (TeX-member (car (car styles)) files 'string-match)))
550       (setq styles (cdr styles))))
551   (if styles
552       (nth 1 (car styles))
553     ""))
554
555 (defun TeX-output-extension ()
556   "Get the extension of the current TeX output file."
557   (if (listp TeX-output-extension)
558       (car TeX-output-extension)
559     (or (TeX-process-get-variable (TeX-active-master)
560                                 'TeX-output-extension
561                                 TeX-output-extension)
562         TeX-output-extension)))
563
564 (defun TeX-view-mouse (event)
565   "Start `TeX-view' at mouse position."
566   (interactive "e")
567   (with-current-buffer (window-buffer (posn-window (event-start event)))
568     (goto-char (posn-point (event-start event)))
569     (TeX-view)))
570
571 (defun TeX-view ()
572   "Start a viewer without confirmation.
573 The viewer is started either on region or master file,
574 depending on the last command issued."
575   (interactive)
576   (let ((output-file (TeX-active-master (TeX-output-extension))))
577     (if (file-exists-p output-file)
578         (TeX-command "View" 'TeX-active-master 0)
579       (message "Output file %S does not exist." output-file))))
580
581 (defun TeX-output-style-check (styles)
582   "Check STYLES compared to the current view output file extension and
583 the current style options."
584   (let ((ext  (TeX-output-extension))
585         (files (TeX-style-list)))
586     (while (and
587             styles
588             (or
589              (not (string-match (car (car styles)) ext))
590              (let ((style (nth 1 (car styles))))
591                (cond
592                 ((listp style)
593                  (while
594                      (and style
595                           (TeX-member (car style) files 'string-match))
596                    (setq style (cdr style)))
597                  style)
598                 ((not (TeX-member style files 'string-match)))))))
599       (setq styles (cdr styles)))
600     (if styles
601         (nth 2 (car styles))
602       "%v")))
603
604 ;;; Command Hooks
605
606 (defvar TeX-after-start-process-function nil
607   "Hooks to run after starting an asynchronous process.
608 Used by Japanese TeX to set the coding system.")
609
610 (defcustom TeX-show-compilation nil
611   "*If non-nil, show output of TeX compilation in other window."
612   :group 'TeX-command
613   :type 'boolean)
614
615 (defun TeX-run-command (name command file)
616   "Create a process for NAME using COMMAND to process FILE.
617 Return the new process."
618   (let ((default TeX-command-default)
619         (buffer (TeX-process-buffer-name file))
620         (dir (TeX-master-directory))
621         (command-buff (current-buffer)))
622     (TeX-process-check file)            ; Check that no process is running
623     (setq-default TeX-command-buffer command-buff)
624     (get-buffer-create buffer)
625     (set-buffer buffer)
626     (buffer-disable-undo)
627     (erase-buffer)
628     (set (make-local-variable 'line-number-display-limit) 0)
629     (setq TeX-output-extension nil)
630     (set (make-local-variable 'TeX-command-buffer) command-buff)
631     (if dir (cd dir))
632     (insert "Running `" name "' on `" file "' with ``" command "''\n")
633     (TeX-output-mode)
634     (if TeX-show-compilation
635         (display-buffer buffer)
636       (message "Type `%s' to display results of compilation."
637                (substitute-command-keys
638                 "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
639     (setq TeX-parse-function 'TeX-parse-command)
640     (setq TeX-command-default default)
641     (setq TeX-sentinel-function
642           (lambda (process name)
643             (message (concat name ": done."))))
644     (if TeX-process-asynchronous
645         (let ((process (start-process name buffer TeX-shell
646                                       TeX-shell-command-option command)))
647           (if TeX-after-start-process-function
648               (funcall TeX-after-start-process-function process))
649           (TeX-command-mode-line process)
650           (set-process-filter process 'TeX-command-filter)
651           (set-process-sentinel process 'TeX-command-sentinel)
652           (set-marker (process-mark process) (point-max))
653           (setq compilation-in-progress (cons process compilation-in-progress))
654           process)
655       (setq mode-line-process ": run")
656       (set-buffer-modified-p (buffer-modified-p))
657       (sit-for 0)                               ; redisplay
658       (call-process TeX-shell nil buffer nil
659                     TeX-shell-command-option command))))
660
661 (defun TeX-run-set-command (name command)
662   "Remember TeX command to use to NAME and set corresponding output extension."
663   (setq TeX-command-default name
664         TeX-output-extension (if TeX-PDF-mode "pdf" "dvi"))
665   (let ((case-fold-search t)
666         (lst TeX-command-output-list))
667     (while lst
668       (if (string-match (car (car lst)) command)
669           (setq TeX-output-extension (car (cdr (car lst)))
670                 lst nil)
671         (setq lst (cdr lst))))))
672
673 (defun TeX-run-format (name command file)
674   "Create a process for NAME using COMMAND to format FILE with TeX."
675   (TeX-run-set-command name command)
676   (let ((buffer (TeX-process-buffer-name file))
677         (process (TeX-run-command name command file)))
678     ;; Hook to TeX debuger.
679     (with-current-buffer buffer
680       (TeX-parse-reset)
681       (setq TeX-parse-function 'TeX-parse-TeX)
682       (setq TeX-sentinel-function 'TeX-TeX-sentinel)
683       (if TeX-process-asynchronous
684           (progn
685             ;; Updating the mode line.
686             (setq TeX-current-page "[0]")
687             (TeX-format-mode-line process)
688             (set-process-filter process 'TeX-format-filter)))
689       process)))
690
691 (defvar TeX-error-report-switches nil
692   "Reports presence of errors after `TeX-run-TeX'.
693 To test whether the current buffer has an compile error from last
694 run of `TeX-run-TeX', use
695   (plist-get TeX-error-report-switches (intern (TeX-master-file)))")
696
697 (defun TeX-run-TeX (name command file)
698   "Create a process for NAME using COMMAND to format FILE with TeX."
699
700   ;; Save information in TeX-error-report-switches
701   ;; Initialize error to nil (no error) for current master.
702   ;; Presence of error is reported inside `TeX-TeX-sentinel-check'
703   (let ((current-master (TeX-master-file)))
704     ;; the current master file is saved because error routines are
705     ;; parsed in other buffers;
706     (setq TeX-error-report-switches
707           (plist-put TeX-error-report-switches
708                      'TeX-current-master current-master))
709     ;; reset error to nil (no error)
710     (setq TeX-error-report-switches
711           (plist-put TeX-error-report-switches
712                      (intern current-master) nil)))
713
714   ;; can we assume that TeX-sentinel-function will not be changed
715   ;; during (TeX-run-format ..)? --pg
716   ;; rather use let* ? --pg
717
718   (if TeX-interactive-mode
719       (TeX-run-interactive name command file)
720     (let ((sentinel-function TeX-sentinel-default-function))
721       (let ((process (TeX-run-format name command file)))
722         (setq TeX-sentinel-function sentinel-function)
723         (if TeX-process-asynchronous
724             process
725           (TeX-synchronous-sentinel name file process))))))
726
727 ;; backward compatibilty
728
729 (defalias 'TeX-run-LaTeX 'TeX-run-TeX)
730
731
732 (defun TeX-run-BibTeX (name command file)
733   "Create a process for NAME using COMMAND to format FILE with BibTeX."
734   (let ((process (TeX-run-command name command file)))
735     (setq TeX-sentinel-function 'TeX-BibTeX-sentinel)
736     (if TeX-process-asynchronous
737         process
738       (TeX-synchronous-sentinel name file process))))
739
740 (defun TeX-run-Biber (name command file)
741   "Create a process for NAME using COMMAND to format FILE with Biber."
742   (let ((process (TeX-run-command name command file)))
743     (setq TeX-sentinel-function 'TeX-Biber-sentinel)
744     (if TeX-process-asynchronous
745         process
746       (TeX-synchronous-sentinel name file process))))
747
748 (defun TeX-run-compile (name command file)
749   "Ignore first and third argument, start compile with second argument."
750   (let ((default-directory (TeX-master-directory)))
751     (setq TeX-command-buffer (compile command))))
752
753 (defun TeX-run-shell (name command file)
754   "Ignore first and third argument, start shell-command with second argument."
755   (let ((default-directory (TeX-master-directory)))
756     (shell-command command)
757     (if (eq system-type 'ms-dos)
758         (redraw-display))))
759
760 (defun TeX-run-discard (name command file)
761   "Start COMMAND as process, discarding its output.
762 NAME and FILE are ignored."
763   (let ((default-directory (TeX-master-directory)))
764     (call-process TeX-shell
765                   nil 0 nil
766                   TeX-shell-command-option
767                   command)))
768
769 (defun TeX-run-discard-foreground (name command file)
770   "Call process with second argument in the foreground, discarding its output.
771 With support for MS-DOS, especially when dviout is used with PC-9801 series."
772   (if (and (boundp 'dos-machine-type) (eq dos-machine-type 'pc98)) ;if PC-9801
773       (send-string-to-terminal "\e[2J")) ; clear screen
774   (call-process TeX-shell (if (eq system-type 'ms-dos) "con") nil nil
775                 TeX-shell-command-option command)
776   (if (eq system-type 'ms-dos)
777       (redraw-display)))
778 (defalias 'TeX-run-dviout 'TeX-run-discard-foreground)
779
780 (defun TeX-run-background (name command file)
781   "Start process with second argument, show output when and if it arrives."
782   (let ((dir (TeX-master-directory)))
783     (set-buffer (get-buffer-create "*TeX background*"))
784     (if dir (cd dir))
785     (erase-buffer)
786     (let ((process (start-process (concat name " background")
787                                   nil TeX-shell
788                                   TeX-shell-command-option command)))
789       (if TeX-after-start-process-function
790           (funcall TeX-after-start-process-function process))
791       (set-process-filter process 'TeX-background-filter)
792       (process-kill-without-query process))))
793
794 (defun TeX-run-silent (name command file)
795   "Start process with second argument."
796   (let ((dir (TeX-master-directory)))
797     (set-buffer (get-buffer-create "*TeX silent*"))
798     (if dir (cd dir))
799     (erase-buffer)
800     (let ((process (start-process (concat name " silent")
801                                   nil TeX-shell
802                                   TeX-shell-command-option command)))
803       (if TeX-after-start-process-function
804           (funcall TeX-after-start-process-function process))
805       (process-kill-without-query process))))
806
807 (defun TeX-run-interactive (name command file)
808   "Run TeX interactively.
809 Run command in a buffer (in comint-shell-mode) so that it accepts user
810 interaction. If you return to the file buffer after the TeX run,
811 Error parsing on \\[next-error] should work with a bit of luck."
812   (TeX-run-set-command name command)
813   (require 'comint)
814   (let ((default TeX-command-default)
815         (buffer (TeX-process-buffer-name file))
816         (process nil)
817         (dir (TeX-master-directory))
818         (command-buff (current-buffer))
819         (sentinel-function TeX-sentinel-default-function)) ; inherit from major mode
820     (TeX-process-check file)            ; Check that no process is running
821     (setq-default TeX-command-buffer command-buff)
822     (with-output-to-temp-buffer buffer)
823     (set-buffer buffer)
824     (set (make-local-variable 'TeX-command-buffer) command-buff)
825     (setq buffer-read-only nil)
826     (if dir (cd dir))
827     (insert "Running `" name "' on `" file "' with ``" command "''\n")
828     (comint-exec buffer name TeX-shell nil
829                  (list TeX-shell-command-option command))
830     (comint-mode)
831     (add-hook 'comint-output-filter-functions 'TeX-interactive-goto-prompt)
832     (setq mode-name name)
833     (setq TeX-command-default default)
834     (setq process (get-buffer-process buffer))
835     (if TeX-after-start-process-function
836         (funcall TeX-after-start-process-function process))
837     (TeX-command-mode-line process)
838     (set-process-sentinel process 'TeX-command-sentinel)
839     (set-marker (process-mark process) (point-max))
840     (setq compilation-in-progress (cons process compilation-in-progress))
841     (TeX-parse-reset)
842     (setq TeX-parse-function 'TeX-parse-TeX)
843     ;; use the sentinel-function that the major mode sets, not the LaTeX one
844     (setq TeX-sentinel-function sentinel-function)))
845
846 (defun TeX-run-function (name command file)
847   "Execute Lisp function or function call given as the string COMMAND.
848 Parameters NAME and FILE are ignored."
849   (let ((fun (car (read-from-string command))))
850     (if (functionp fun) (funcall fun) (eval fun))))
851
852 (defun TeX-run-discard-or-function (name command file)
853   "Start COMMAND as process or execute it as a Lisp function.
854 If run as a process, the output is discarded.  COMMAND is
855 expected to be a string.  NAME and FILE are ignored."
856   (if (functionp (car (read-from-string command)))
857       (TeX-run-function name command file)
858     (TeX-run-discard name command file)))
859
860 (defun TeX-run-ispell-on-document (command ignored name)
861   "Run ispell on all open files belonging to the current document.
862 This function is *obsolete* and only here for compatibility
863 reasons.  Use `TeX-run-function' instead."
864   (interactive)
865   (TeX-ispell-document ""))
866
867
868 ;;; Command Sentinels
869
870 (defun TeX-synchronous-sentinel (name file result)
871   "Process TeX command output buffer after the process dies."
872   (let ((buffer (TeX-process-buffer (file-name-nondirectory file))))
873     (with-current-buffer buffer
874
875       ;; Append post-mortem information to the buffer
876       (goto-char (point-max))
877       (insert "\n" mode-name (if (and result (zerop result))
878                                  " finished" " exited") " at "
879               (substring (current-time-string) 0 -5))
880       (setq mode-line-process ": exit")
881
882       ;; Do command specific actions.
883       (setq TeX-command-next TeX-command-Show)
884       (goto-char (point-min))
885       (apply TeX-sentinel-function nil name nil)
886
887       ;; Force mode line redisplay soon
888       (set-buffer-modified-p (buffer-modified-p)))))
889
890 (defun TeX-command-sentinel (process msg)
891   "Process TeX command output buffer after the process dies."
892   ;; Set `TeX-transient-master' here because `preview-parse-messages'
893   ;; may open files and thereby trigger master file questions which we
894   ;; don't want and need because we already know the master.  Use
895   ;; `TeX-master-file' instead of `TeX-active-master' to determine the
896   ;; master because the region file should never be the master.
897   (let* ((TeX-transient-master (TeX-master-file))
898          (buffer (process-buffer process))
899          (name (process-name process)))
900     (cond ((null (buffer-name buffer))  ; buffer killed
901            (set-process-buffer process nil)
902            (set-process-sentinel process nil))
903           ((memq (process-status process) '(signal exit))
904            (with-current-buffer buffer
905
906              ;; Append post-mortem information to the buffer
907              (goto-char (point-max))
908              (insert-before-markers "\n" mode-name " " msg)
909              (forward-char -1)
910              (insert " at "
911                      (substring (current-time-string) 0 -5))
912              (forward-char 1)
913
914              ;; Do command specific actions.
915              (TeX-command-mode-line process)
916              (setq TeX-command-next TeX-command-Show)
917              (goto-char (point-min))
918              (apply TeX-sentinel-function process name nil)
919
920
921              ;; If buffer and mode line will show that the process
922              ;; is dead, we can delete it now.  Otherwise it
923              ;; will stay around until M-x list-processes.
924              (delete-process process)
925
926              ;; Force mode line redisplay soon
927              (set-buffer-modified-p (buffer-modified-p))))))
928   (setq compilation-in-progress (delq process compilation-in-progress)))
929
930
931 (defvar TeX-sentinel-function (lambda (process name))
932   "Hook to cleanup TeX command buffer after temination of PROCESS.
933 NAME is the name of the process.")
934
935   (make-variable-buffer-local 'TeX-sentinel-function)
936
937
938 (defvar TeX-sentinel-default-function (lambda (process name))
939   "Default for `TeX-sentinel-function'.  To be set in major mode.
940 Hook to cleanup TeX command buffer after temination of PROCESS.
941 NAME is the name of the process.")
942
943   (make-variable-buffer-local 'TeX-sentinel-default-function)
944
945 (defun TeX-TeX-sentinel (process name)
946   "Cleanup TeX output buffer after running TeX.
947
948 Parse the output buffer to collect errors and warnings if the
949 variable `TeX-parse-all-errors' is non-nil.
950
951 Open the error overview if
952 `TeX-error-overview-open-after-TeX-run' is non-nil and there are
953 errors or warnings to show."
954   (if (TeX-TeX-sentinel-check process name)
955       ()
956     (message (concat name ": formatted " (TeX-current-pages)))
957     (if TeX-parse-all-errors
958         (TeX-parse-all-errors))
959     (if (and TeX-error-overview-open-after-TeX-run TeX-error-list)
960         (TeX-error-overview))
961     (setq TeX-command-next TeX-command-Show)))
962
963 (defun TeX-current-pages ()
964   "Return string indicating the number of pages formatted."
965   (cond ((null TeX-current-page)
966          "some pages")
967         ((string-match "[^0-9]1[^0-9]" TeX-current-page)
968          (concat TeX-current-page " page"))
969         (t
970          (concat TeX-current-page " pages"))))
971
972 (defun TeX-TeX-sentinel-check (process name)
973   "Cleanup TeX output buffer after running TeX.
974 Return nil ifs no errors were found."
975   (save-excursion
976     (goto-char (point-max))
977     (if (re-search-backward "^Output written on \\(.*?\\) (\\([0-9]+\\) page"
978                             nil t)
979         (let ((output-file (TeX-match-buffer 1)))
980           (setq TeX-current-page (concat "{" (TeX-match-buffer 2) "}"))
981           ;; Shave off quotation marks if present.
982           (when (string-match "\\`\"\\(.*\\)\"\\'" output-file)
983             (setq output-file (match-string 1 output-file)))
984           (setq TeX-output-extension
985                 (if (string-match "\\.\\([^.]*\\)$" output-file)
986                     (match-string 1 output-file)
987                   "dvi")))))
988   (if process (TeX-format-mode-line process))
989   (if (re-search-forward "^\\(!\\|.*:[0-9]+:\\) " nil t)
990       (progn
991         (message "%s errors in `%s'. Use %s to display." name (buffer-name)
992                  (substitute-command-keys
993                   "\\<TeX-mode-map>\\[TeX-next-error]"))
994         (setq TeX-command-next TeX-command-default)
995         ;; error reported to TeX-error-report-switches
996         (setq TeX-error-report-switches
997               (plist-put TeX-error-report-switches
998                          (intern (plist-get TeX-error-report-switches
999                                             'TeX-current-master))
1000                          t))
1001         t)
1002     (setq TeX-command-next TeX-command-Show)
1003     nil))
1004
1005 (defun TeX-LaTeX-sentinel-has-warnings ()
1006   "Return non-nil, if the output buffer contains warnings.
1007 Warnings can be indicated by LaTeX or packages."
1008   (save-excursion
1009     (goto-char (point-min))
1010     (re-search-forward
1011      "^\\(LaTeX [A-Za-z]*\\|Package [A-Za-z]+ \\)Warning:" nil t)))
1012
1013 (defun TeX-LaTeX-sentinel-has-bad-boxes ()
1014   "Return non-nil, if LaTeX output indicates overfull or underfull boxes."
1015   (save-excursion
1016     (goto-char (point-min))
1017     (re-search-forward "^\\(Ov\\|Und\\)erfull \\\\" nil t)))
1018
1019 ;; should go into latex.el? --pg
1020 (defun TeX-LaTeX-sentinel (process name)
1021   "Cleanup TeX output buffer after running LaTeX.
1022
1023 Parse the output buffer to collect errors and warnings if the
1024 variable `TeX-parse-all-errors' is non-nil.
1025
1026 Open the error overview if
1027 `TeX-error-overview-open-after-TeX-run' is non-nil and there are
1028 errors or warnings to show."
1029   (if TeX-parse-all-errors
1030       (TeX-parse-all-errors))
1031   (if (and TeX-error-overview-open-after-TeX-run TeX-error-list)
1032       (TeX-error-overview))
1033   (cond ((TeX-TeX-sentinel-check process name))
1034         ((and (save-excursion
1035                 (re-search-forward
1036                  "^Package biblatex Warning: Please (re)run Biber on the file"
1037                  nil t))
1038               (with-current-buffer TeX-command-buffer
1039                 (and (LaTeX-bibliography-list)
1040                      (TeX-check-files (TeX-master-file "bbl")
1041                                       (TeX-style-list)
1042                                       (append TeX-file-extensions
1043                                               BibTeX-file-extensions
1044                                               TeX-Biber-file-extensions)))))
1045          (message "%s%s" "You should run Biber to get citations right, "
1046                   (TeX-current-pages))
1047          (setq TeX-command-next (with-current-buffer TeX-command-buffer
1048                                   TeX-command-Biber)))
1049         ((and (save-excursion
1050                 (re-search-forward
1051                  "^\\(?:LaTeX\\|Package natbib\\) Warning: Citation" nil t))
1052               (with-current-buffer TeX-command-buffer
1053                 (and (LaTeX-bibliography-list)
1054                      (TeX-check-files (TeX-master-file "bbl")
1055                                       (TeX-style-list)
1056                                       (append TeX-file-extensions
1057                                               BibTeX-file-extensions
1058                                               TeX-Biber-file-extensions)))))
1059          (message "%s%s" "You should run BibTeX to get citations right, "
1060                   (TeX-current-pages))
1061          (setq TeX-command-next (with-current-buffer TeX-command-buffer
1062                                   TeX-command-BibTeX)))
1063         ((re-search-forward "Package biblatex Warning: Please rerun LaTeX" nil t)
1064          (message "%s%s" "You should run LaTeX again, " (TeX-current-pages))
1065          (setq TeX-command-next TeX-command-default))
1066         ((re-search-forward "^(biblatex)\\W+Page breaks have changed" nil t)
1067          (message "%s%s" "You should run LaTeX again - page breaks have changed, "
1068                   (TeX-current-pages))
1069          (setq TeX-command-next TeX-command-default))
1070         ((re-search-forward "^\\(?:LaTeX Warning: Label(s)\\|\
1071 Package natbib Warning: Citation(s)\\)" nil t)
1072          (message "%s%s" "You should run LaTeX again to get references right, "
1073                   (TeX-current-pages))
1074          (setq TeX-command-next TeX-command-default))
1075         ((re-search-forward
1076           "^\\(?:(rerunfilecheck)\\|Package hyperref Warning:\\)\\W+\
1077 Rerun to get outlines right" nil t)
1078          (message "%s%s" "You should run LaTeX again to get outlines right, "
1079                   (TeX-current-pages))
1080          (setq TeX-command-next TeX-command-default))
1081         ((re-search-forward "^LaTeX Warning: Reference" nil t)
1082          (message "%s%s%s" name ": there were unresolved references, "
1083                   (TeX-current-pages))
1084          (setq TeX-command-next TeX-command-Show))
1085         ((re-search-forward "^\\(?:LaTeX Warning: Citation\\|\
1086 Package natbib Warning:.*undefined citations\\)" nil t)
1087          (message "%s%s%s" name ": there were unresolved citations, "
1088                   (TeX-current-pages))
1089          (setq TeX-command-next TeX-command-Show))
1090         ((re-search-forward "Package longtable Warning: Table widths have \
1091 changed\\. Rerun LaTeX\\." nil t)
1092          (message
1093           "%s" "You should run LaTeX again to get table formatting right")
1094          (setq TeX-command-next TeX-command-default))
1095         ((re-search-forward
1096           "^\\(\\*\\* \\)?J?I?p?\\(La\\|Sli\\)TeX\\(2e\\)? \
1097 \\(Version\\|ver\\.\\|<[0-9/]*>\\)" nil t)
1098          (let* ((warnings (and TeX-debug-warnings
1099                                (TeX-LaTeX-sentinel-has-warnings)))
1100                 (bad-boxes (and TeX-debug-bad-boxes
1101                                 (TeX-LaTeX-sentinel-has-bad-boxes)))
1102                 (add-info (when (or warnings bad-boxes)
1103                             (concat " (with "
1104                                     (when warnings "warnings")
1105                                     (when (and warnings bad-boxes) " and ")
1106                                     (when bad-boxes "bad boxes")
1107                                     ")"))))
1108            (message "%s" (concat name ": successfully formatted "
1109                                  (TeX-current-pages) add-info)))
1110          (setq TeX-command-next TeX-command-Show))
1111         (t
1112          (message "%s%s%s" name ": problems after " (TeX-current-pages))
1113          (setq TeX-command-next TeX-command-default))))
1114
1115 ;; should go into latex.el? --pg
1116 (defun TeX-BibTeX-sentinel (process name)
1117   "Cleanup TeX output buffer after running BibTeX."
1118   (goto-char (point-max))
1119   (cond
1120    ;; Check whether BibTeX reports any warnings or errors.
1121    ((re-search-backward (concat
1122                          "^(There \\(?:was\\|were\\) \\([0-9]+\\) "
1123                          "\\(warnings?\\|error messages?\\))") nil t)
1124     ;; Tell the user their number so that she sees whether the
1125     ;; situation is getting better or worse.
1126     (message (concat "BibTeX finished with %s %s. "
1127                      "Type `%s' to display output.")
1128              (match-string 1) (match-string 2)
1129              (substitute-command-keys
1130               "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]")))
1131    (t
1132     (message (concat "BibTeX finished successfully. "
1133                      "Run LaTeX again to get citations right."))
1134   (setq TeX-command-next TeX-command-default))))
1135
1136 (defun TeX-Biber-sentinel (process name)
1137   "Cleanup TeX output buffer after running Biber."
1138   (goto-char (point-max))
1139   (cond
1140    ((re-search-backward (concat
1141                          "^INFO - \\(WARNINGS\\|ERRORS\\): \\([0-9]+\\)") nil t)
1142     (message (concat "Biber finished with %s %s. "
1143                      "Type `%s' to display output.")
1144              (match-string 2) (downcase (match-string 1))
1145              (substitute-command-keys
1146               "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]"))
1147     (setq TeX-command-next TeX-command-default))
1148    ((re-search-backward (concat
1149                          "^FATAL") nil t)
1150     (message (concat "Biber had a fatal error and did not finish! "
1151                      "Type `%s' to display output.")
1152              (substitute-command-keys
1153               "\\<TeX-mode-map>\\[TeX-recenter-output-buffer]"))
1154     (setq TeX-command-next TeX-command-Biber))
1155    (t
1156     (message (concat "Biber finished successfully. "
1157                      "Run LaTeX again to get citations right."))
1158     (setq TeX-command-next TeX-command-default))))
1159
1160 ;;; Process Control
1161
1162
1163 ;; This variable is chared with `compile.el'.
1164 (defvar compilation-in-progress nil
1165   "List of compilation processes now running.")
1166
1167 (or (assq 'compilation-in-progress minor-mode-alist)
1168     (setq minor-mode-alist (cons '(compilation-in-progress " Compiling")
1169                                  minor-mode-alist)))
1170
1171 (defun TeX-process-get-variable (name symbol &optional default)
1172   "Return the value in the process buffer for NAME of SYMBOL.
1173
1174 Return DEFAULT if the process buffer does not exist or SYMBOL is not
1175 defined."
1176   (let ((buffer (TeX-process-buffer name)))
1177     (if (and buffer
1178              (local-variable-p symbol buffer))
1179         (with-current-buffer buffer
1180           (symbol-value symbol))
1181       default)))
1182
1183 (defun TeX-process-set-variable (name symbol value)
1184   "Set the variable SYMBOL in the process buffer to VALUE.
1185 Return nil iff no process buffer exist."
1186   (let ((buffer (TeX-process-buffer name)))
1187     (if buffer
1188         (with-current-buffer buffer
1189           (set symbol value)
1190           t)
1191       nil)))
1192
1193 (defun TeX-process-check (name)
1194   "Check if a process for the TeX document NAME already exist.
1195 If so, give the user the choice of aborting the process or the current
1196 command."
1197   (let (process)
1198     (while (and (setq process (TeX-process name))
1199                 (eq (process-status process) 'run))
1200       (cond
1201        ((yes-or-no-p (concat "Process `"
1202                              (process-name process)
1203                              "' for document `"
1204                              name
1205                              "' running, kill it? "))
1206         (delete-process process))
1207        ((eq (process-status process) 'run)
1208            (error "Cannot have two processes for the same document"))))))
1209
1210 (defun TeX-process-buffer-name (name)
1211   "Return name of AUCTeX buffer associated with the document NAME."
1212   (concat "*" (abbreviate-file-name (expand-file-name name)) " output*"))
1213
1214 (defun TeX-process-buffer (name)
1215   "Return the AUCTeX buffer associated with the document NAME."
1216   (get-buffer (TeX-process-buffer-name name)))
1217
1218 (defun TeX-process (name)
1219   "Return AUCTeX process associated with the document NAME."
1220   (and TeX-process-asynchronous
1221        (get-buffer-process (TeX-process-buffer name))))
1222
1223 ;;; Process Filters
1224
1225 (defun TeX-command-mode-line (process)
1226   "Format the mode line for a buffer containing output from PROCESS."
1227     (setq mode-line-process (concat ": "
1228                                     (symbol-name (process-status process))))
1229     (set-buffer-modified-p (buffer-modified-p)))
1230
1231 (defun TeX-command-filter (process string)
1232   "Filter to process normal output."
1233   (with-current-buffer (process-buffer process)
1234     (save-excursion
1235       (goto-char (process-mark process))
1236       (insert-before-markers string)
1237       (set-marker (process-mark process) (point)))))
1238
1239 (defvar TeX-current-page nil
1240   "The page number currently being formatted, enclosed in brackets.")
1241
1242  (make-variable-buffer-local 'TeX-current-page)
1243
1244 (defun TeX-format-mode-line (process)
1245   "Format the mode line for a buffer containing TeX output from PROCESS."
1246     (setq mode-line-process (concat " " TeX-current-page ": "
1247                                     (symbol-name (process-status process))))
1248     (set-buffer-modified-p (buffer-modified-p)))
1249
1250 (defun TeX-format-filter (process string)
1251   "Filter to process TeX output."
1252   (with-current-buffer (process-buffer process)
1253     (let (str pos end (pt (marker-position (process-mark process))))
1254       (save-excursion
1255         (goto-char pt)
1256         (insert-before-markers string)
1257         (set-marker (process-mark process) (point))
1258         ;; Remove line breaks at column 79
1259         (while (> (point) pt)
1260           (end-of-line 0)
1261           (when (and (= (- (point) (line-beginning-position)) 79)
1262                      ;; Heuristic: Don't delete the linebreak if the
1263                      ;; next line is empty or starts with an opening
1264                      ;; parenthesis or if point is located after a period.
1265                      (not (memq (char-after (1+ (point))) '(?\n ?\()))
1266                      (not (eq (char-before) ?.)))
1267             (delete-char 1)))
1268         (goto-char (marker-position (process-mark process)))
1269         ;; Determine current page
1270         (while (and pt
1271                     (skip-chars-backward "^]" pt)
1272                     (> (point) pt))
1273           (setq end (point))
1274           (backward-char)
1275           (skip-chars-backward "-0-9\n." (max (point-min) (- pt 128)))
1276           (when (and (eq ?\[ (char-before))
1277                      (not (eq ?\] (char-after)))
1278                      (progn
1279                        (setq str (buffer-substring (1- (point)) end)
1280                              pos nil)
1281                        (while (setq pos (string-match "\n" str pos))
1282                          (setq str (replace-match "" t t str)))
1283                        (string-match
1284                         "\\`\\[-?[0-9]+\\(\\.-?[0-9]+\\)\\{0,9\\}\\]\\'"
1285                         str)))
1286             (setq TeX-current-page str
1287                   pt nil)
1288             (TeX-format-mode-line process)))))))
1289
1290 (defvar TeX-parse-function nil
1291   "Function to call to parse content of TeX output buffer.")
1292  (make-variable-buffer-local 'TeX-parse-function)
1293
1294 (defun TeX-background-filter (process string)
1295   "Filter to process background output."
1296   (let ((old-window (selected-window))
1297         (pop-up-windows t))
1298     (TeX-pop-to-buffer "*TeX background*" nil t)
1299     (goto-char (point-max))
1300     (insert string)
1301     (select-window old-window)))
1302
1303 ;; Copy and adaption of `comint-postoutput-scroll-to-bottom' from CVS
1304 ;; Emacs of 2005-04-24.
1305 (defun TeX-interactive-goto-prompt (string)
1306   "Move point to prompt of an interactive TeX run."
1307   (let* ((selected (selected-window))
1308          (current (current-buffer))
1309          (process (get-buffer-process current)))
1310     (unwind-protect
1311         (when process
1312           (walk-windows
1313            (lambda (window)
1314              (when (eq (window-buffer window) current)
1315                (select-window window)
1316                (when (and (< (point) (process-mark process))
1317                           (string-match "^\\? $" string))
1318                  (goto-char (process-mark process)))
1319                (select-window selected)))
1320            nil t))
1321       (set-buffer current))))
1322
1323
1324 ;;; Active Process
1325
1326 (defvar TeX-current-process-region-p nil
1327   "This variable is set to t iff the last TeX command is on a region.")
1328
1329 (defun TeX-active-process ()
1330   "Return the active process for the current buffer."
1331   (TeX-process (TeX-active-master)))
1332
1333 (defun TeX-active-buffer ()
1334   "Return the buffer of the active process for this buffer."
1335   (and TeX-command-buffer
1336        (with-current-buffer TeX-command-buffer
1337          (TeX-process-buffer (TeX-active-master)))))
1338
1339 (defun TeX-active-master (&optional extension nondirectory)
1340   "The master file currently being compiled.
1341
1342 If optional argument EXTENSION is non-nil, add that file extension to
1343 the name.  Special value t means use `TeX-default-extension'.
1344
1345 If optional second argument NONDIRECTORY is non-nil, do not include
1346 the directory."
1347   (if TeX-current-process-region-p
1348       (TeX-region-file extension nondirectory)
1349     (TeX-master-file extension nondirectory)))
1350
1351 (defvar TeX-command-buffer nil
1352   "The buffer from where the last TeX command was issued.")
1353
1354 ;;; Region File
1355
1356 (defcustom TeX-region-extra ""
1357   "*String to insert in the region file between the header and the text."
1358   :group 'TeX-command
1359   :type 'string)
1360
1361 ;; This was "{\\makeatletter\\gdef\\AucTeX@cite#1[#2]#3{[#3#1#2]}\
1362 ;;           \\gdef\\cite{\\@ifnextchar[{\\AucTeX@cite{, }}\
1363 ;;           {\\AucTeX@cite{}[]}}}\n"
1364 ;; However, that string is inappropriate for plain TeX and ConTeXt.
1365 ;; This needs reconsideration.
1366
1367
1368 (defvar TeX-region-hook nil
1369   "List of hooks to run before the region file is saved.
1370 The hooks are run in the region buffer, you may use the variable
1371 `master-buffer' to access the buffer of the master file and
1372 `orig-buffer' to access the buffer where \\[TeX-command-region] or
1373 \\[TeX-command-buffer] is invoked from.")
1374
1375 (defun TeX-quote-filename (file)
1376   "Convert file name into a form acceptable to TeX."
1377   (let (pos)
1378     (while (setq pos (string-match "\\\\" file pos))
1379       (setq file (replace-match "/" t t file 0)
1380             pos (1+ pos)))
1381     (while (setq pos (string-match "[~#]" file pos))
1382       (setq file (replace-match "\\\\string\\&" t nil file 0)
1383             pos (+ pos 8))))
1384   file)
1385
1386 (defun TeX-region-create (file region original offset)
1387   "Create a new file named FILE with the string REGION.
1388 The region is taken from ORIGINAL starting at line OFFSET.
1389
1390 The current buffer and master file is searched, in order to ensure
1391 that the TeX header and trailer information is also included.
1392
1393 The OFFSET is used to provide the debugger with information about the
1394 original file."
1395   (let* (;; We shift buffer a lot, so we must keep track of the buffer
1396          ;; local variables.
1397          (header-end TeX-header-end)
1398          (trailer-start TeX-trailer-start)
1399
1400          ;; We seach for header and trailer in the master file.
1401          (orig-buffer (current-buffer))
1402          (master-name (TeX-master-file TeX-default-extension))
1403          (master-buffer (find-file-noselect master-name))
1404
1405          ;; Attempt to disable font lock.
1406          (font-lock-defaults-alist nil)
1407          (font-lock-defaults nil)
1408          (font-lock-maximum-size 0)
1409          (font-lock-mode-hook nil)
1410          (font-lock-auto-fontify nil)
1411          (font-lock-mode-enable-list nil)
1412          ;; And insert them into the FILE buffer.
1413          (file-buffer (let ((TeX-transient-master t))
1414                         (find-file-noselect file)))
1415          ;; But remember original content.
1416          original-content
1417
1418          ;; We search for the header from the master file, if it is
1419          ;; not present in the region.
1420          (header (if (string-match header-end region)
1421                      ""
1422                    (save-excursion
1423                      (save-restriction
1424                        (set-buffer master-buffer)
1425                        (save-excursion
1426                          (save-restriction
1427                            (widen)
1428                            (goto-char (point-min))
1429                            ;; NOTE: We use the local value of
1430                            ;; TeX-header-end from the master file.
1431                            (if (not (re-search-forward TeX-header-end nil t))
1432                                ""
1433                              (re-search-forward "[\r\n]" nil t)
1434                              (buffer-substring (point-min) (point)))))))))
1435
1436          ;; We search for the trailer from the master file, if it is
1437          ;; not present in the region.
1438          (trailer-offset 0)
1439          (trailer (if (string-match trailer-start region)
1440                       ""
1441                     (save-excursion
1442                       (save-restriction
1443                         (set-buffer master-buffer)
1444                         (save-excursion
1445                           (save-restriction
1446                             (widen)
1447                             (goto-char (point-max))
1448                             ;; NOTE: We use the local value of
1449                             ;; TeX-trailer-start from the master file.
1450                             (if (not (re-search-backward TeX-trailer-start nil t))
1451                                 ""
1452                               ;;(beginning-of-line 1)
1453                               (re-search-backward "[\r\n]" nil t)
1454                               (setq trailer-offset (TeX-current-offset))
1455                               (buffer-substring (point) (point-max))))))))))
1456     ;; file name should be relative to master
1457     (setq original (TeX-quote-filename (file-relative-name
1458                                         original (TeX-master-directory)))
1459           master-name (TeX-quote-filename master-name))
1460     (with-current-buffer file-buffer
1461       (setq buffer-undo-list t)
1462       (setq original-content (buffer-string))
1463       (erase-buffer)
1464       (when (boundp 'buffer-file-coding-system)
1465         (setq buffer-file-coding-system
1466               (with-current-buffer master-buffer buffer-file-coding-system)))
1467       (insert "\\message{ !name(" master-name ")}"
1468               header
1469               TeX-region-extra
1470               "\n\\message{ !name(" original ") !offset(")
1471       (insert (int-to-string (- offset
1472                                 (1+ (TeX-current-offset))))
1473               ") }\n"
1474               region
1475               "\n\\message{ !name("  master-name ") !offset(")
1476       (insert (int-to-string (- trailer-offset
1477                                 (1+ (TeX-current-offset))))
1478               ") }\n"
1479               trailer)
1480       (run-hooks 'TeX-region-hook)
1481       (if (string-equal (buffer-string) original-content)
1482           (set-buffer-modified-p nil)
1483         (save-buffer 0)))))
1484
1485 (defun TeX-region-file (&optional extension nondirectory)
1486   "Return TeX-region file name with EXTENSION.
1487 If optional second argument NONDIRECTORY is non-nil, do not include
1488 the directory."
1489   (concat (if nondirectory "" (TeX-master-directory))
1490           (cond ((eq extension t)
1491                  (concat TeX-region "." TeX-default-extension))
1492                 (extension
1493                  (concat TeX-region "." extension))
1494                 (t
1495                  TeX-region))))
1496
1497 (defcustom TeX-region "_region_"
1498   "*Base name of temporary file for `TeX-command-region' and `TeX-command-buffer'."
1499   :group 'TeX-command
1500   :type 'string)
1501
1502 ;;; Parsing
1503
1504 ;;; - Global Parser Variables
1505
1506 (defvar TeX-error-point nil
1507   "How far we have parsed until now.")
1508
1509  (make-variable-buffer-local 'TeX-error-point)
1510
1511 (defvar TeX-error-file nil
1512   "Stack of files in which errors have occurred.")
1513
1514  (make-variable-buffer-local 'TeX-error-file)
1515
1516 (defvar TeX-error-offset nil
1517   "Add this to any line numbers from TeX.  Stack like `TeX-error-file'.")
1518
1519  (make-variable-buffer-local 'TeX-error-offset)
1520
1521 (defun TeX-parse-reset (&optional reparse)
1522   "Reset all variables used for parsing TeX output.
1523 If optional argument REPARSE is non-nil, reparse the output log."
1524   (setq TeX-error-point (point-min)
1525         TeX-error-offset nil
1526         TeX-error-file nil
1527         TeX-error-list nil
1528         TeX-error-last-visited -1)
1529   (if reparse
1530       (TeX-parse-all-errors)))
1531
1532 ;;; - Parsers Hooks
1533
1534 ;; All this parsers hooks should have the same arguments even though they will
1535 ;; be ignored, because `TeX-next-error' can call any of these functions.
1536 (defun TeX-parse-command (arg reparse)
1537   "We can't parse anything but TeX."
1538   (error "I cannot parse %s output, sorry."
1539          (if (TeX-active-process)
1540              (process-name (TeX-active-process))
1541            "this")))
1542
1543 (defun TeX-parse-TeX (arg reparse)
1544   "Find the next error produced by running TeX.
1545
1546 ARG specifies how many error messages to move, when possible;
1547 negative means move back to previous error messages.
1548
1549 If REPARSE is non-nil, reparse the output log.
1550
1551 If the file occurs in an included file, the file is loaded (if not
1552 already in an Emacs buffer) and the cursor is placed at the error."
1553   (let ((old-buffer (current-buffer))
1554         (default-major-mode major-mode)
1555         max-index item)
1556
1557     ;; Switch to the output buffer.
1558     (with-current-buffer (TeX-active-buffer)
1559       (if reparse
1560           (TeX-parse-reset reparse))
1561       (if TeX-parse-all-errors
1562           (progn
1563             (setq max-index (length TeX-error-list)
1564                   TeX-error-last-visited (+ (or arg 1) TeX-error-last-visited)
1565                   item (if (natnump TeX-error-last-visited)
1566                            (nth TeX-error-last-visited TeX-error-list)
1567                          ;; XEmacs doesn't support `nth' with a negative index.
1568                          nil))
1569             (if (< TeX-error-last-visited -1)
1570                 (setq TeX-error-last-visited -1))
1571             (cond ((or (null item)
1572                        (< TeX-error-last-visited 0))
1573                    (if (> TeX-error-last-visited max-index)
1574                        (setq TeX-error-last-visited max-index))
1575                    (message "No more errors.")
1576                    (beep)
1577                    (TeX-pop-to-buffer old-buffer))
1578                   (t
1579                    (apply 'TeX-find-display-help item))))
1580
1581         (goto-char TeX-error-point)
1582         (TeX-parse-error old-buffer)))))
1583
1584 ;;; - Parsing (La)TeX
1585
1586 (defvar TeX-translate-location-hook nil
1587   "List of functions to be called before showing an error or warning.
1588
1589 You might want to examine and modify the free variables `file',
1590 `offset', `line', `string', `error', and `context' from this hook.")
1591
1592 (defvar TeX-error-list nil
1593   "List of warnings and errors.
1594
1595 This variable is intended to be set only in output buffer so it
1596 will be shared among all files of the same document.")
1597 (make-variable-buffer-local 'TeX-error-list)
1598
1599 (defcustom TeX-parse-all-errors t
1600   "Whether to automatically collect all warning and errors after running TeX.
1601
1602 If t, it makes it possible to use `TeX-previous-error' with TeX
1603 commands."
1604   :group 'TeX-command
1605   :type 'boolean)
1606
1607 (defun TeX-parse-all-errors ()
1608   "Parse TeX output buffer to collect all warnings and errors."
1609   ;; Reset error list.
1610   (setq TeX-error-list nil)
1611   (save-excursion
1612     (goto-char (point-min))
1613     (while (TeX-parse-error nil t)))
1614   ;; Reset last visited error.
1615   (setq TeX-error-last-visited -1))
1616
1617 (defun TeX-parse-error (old &optional store)
1618   "Goto next error.  Pop to OLD buffer if no more errors are found.
1619
1620 If the optional argument STORE is non-nil, the function will
1621 store the found warning or error in `TeX-error-list' instead of
1622 displaying the issue.
1623
1624 Return non-nil if an error or warning is found."
1625   (let ((regexp
1626          (concat
1627           ;; TeX error
1628           "^\\(!\\|\\(.*?\\):[0-9]+:\\) \\|"
1629           ;; New file
1630           "(\\(\"[^\"]*?\"\\|/*\
1631 \\(?:\\.+[^()\r\n{} \\/]*\\|[^()\r\n{} .\\/]+\
1632 \\(?: [^()\r\n{} .\\/]+\\)*\\(?:\\.[-0-9a-zA-Z_.]*\\)?\\)\
1633 \\(?:[\\/]+\\(?:\\.+[^()\r\n{} \\/]*\\|[^()\r\n{} .\\/]+\
1634 \\(?: [^()\r\n{} .\\/]+\\)*\\(?:\\.[-0-9a-zA-Z_.]*\\)?\\)?\\)*\\)\
1635 )*\\(?: \\|\r?$\\)\\|"
1636           ;; End of file.  The [^:] skips package messages like:
1637           ;; Package hyperref Message: Driver (autodetected): hpdftex.
1638           ;; [Loading MPS to PDF converter (version 2006.09.02).]
1639           "\\()\\)[^:.]\\|"
1640           ;; Hook to change line numbers
1641           " !\\(?:offset(\\([---0-9]+\\))\\|"
1642           ;; Hook to change file name
1643           "name(\\([^)]+\\))\\)\\|"
1644           ;; LaTeX bad box
1645           "^\\(\\(?:Overfull\\|Underfull\\|Tight\\|Loose\\)\
1646  \\\\.*?[0-9]+--[0-9]+\\)\\|"
1647           ;; LaTeX warning
1648           "^\\(LaTeX [A-Za-z]*\\|Package [A-Za-z]+ \\)Warning:.*"))
1649         (error-found nil))
1650     (while
1651         (cond
1652          ((null
1653            (re-search-forward regexp nil t))
1654           ;; No more errors.
1655           (unless store
1656             (message "No more errors.")
1657             (beep)
1658             (TeX-pop-to-buffer old))
1659           nil)
1660          ;; TeX error
1661          ((match-beginning 1)
1662           (when (match-beginning 2)
1663             (unless TeX-error-file
1664               (push nil TeX-error-file)
1665               (push nil TeX-error-offset))
1666             (unless (car TeX-error-offset)
1667               (rplaca TeX-error-file (TeX-match-buffer 2))))
1668           (setq error-found t)
1669           (if (looking-at "Preview ")
1670               t
1671             (TeX-error store)
1672             nil))
1673          ;; LaTeX bad box
1674          ((match-beginning 7)
1675           (if TeX-debug-bad-boxes
1676               (progn
1677                 (setq error-found t)
1678                 (TeX-warning (TeX-match-buffer 7) store)
1679                 nil)
1680             (re-search-forward "\r?\n\
1681 \\(?:.\\{79\\}\r?\n\
1682 \\)*.*\r?$")
1683             t))
1684          ;; LaTeX warning
1685          ((match-beginning 8)
1686           (if TeX-debug-warnings
1687               (progn
1688                 (setq error-found t)
1689                 (TeX-warning (TeX-match-buffer 8) store)
1690                 nil)
1691             t))
1692
1693          ;; New file -- Push on stack
1694          ((match-beginning 3)
1695           (let ((file (TeX-match-buffer 3))
1696                 (end (match-end 3)))
1697             ;; Strip quotation marks and remove newlines if necessary
1698             (when (or (eq (string-to-char file) ?\")
1699                       (string-match "\n" file))
1700               (setq file
1701                     (mapconcat 'identity (split-string file "[\"\n]+") "")))
1702             (push file TeX-error-file)
1703             (push nil TeX-error-offset)
1704             (goto-char end))
1705           t)
1706
1707          ;; End of file -- Pop from stack
1708          ((match-beginning 4)
1709           (when (> (length TeX-error-file) 0)
1710             (pop TeX-error-file)
1711             (pop TeX-error-offset))
1712           (goto-char (match-end 4))
1713           t)
1714
1715          ;; Hook to change line numbers
1716          ((match-beginning 5)
1717           (setq TeX-error-offset
1718                 (list (string-to-number (TeX-match-buffer 5))))
1719           t)
1720
1721          ;; Hook to change file name
1722          ((match-beginning 6)
1723           (setq TeX-error-file
1724                 (list (TeX-match-buffer 6)))
1725           t)))
1726     error-found))
1727
1728 (defun TeX-find-display-help (type file line error offset context string
1729                                    line-end bad-box error-point)
1730   "Find the error and display the help."
1731   (unless file
1732     (cond
1733      ;; XXX: error messages have to be different?
1734      ((equal type 'error)
1735       (error "Error occurred after last TeX file closed"))
1736      (t
1737       (error "Could not determine file for warning"))))
1738
1739   ;; Go back to TeX-buffer
1740   (let ((runbuf (TeX-active-buffer))
1741         (master (with-current-buffer TeX-command-buffer
1742                   (expand-file-name (TeX-master-file))))
1743         (command-buffer TeX-command-buffer)
1744         error-file-buffer start)
1745     (run-hooks 'TeX-translate-location-hook)
1746     (setq error-file-buffer
1747           (find-file
1748            (expand-file-name file (file-name-directory master))))
1749     ;; Set the value of `TeX-command-buffer' in the next file with an
1750     ;; error to be displayed to the value it has in the current buffer.
1751     (with-current-buffer error-file-buffer
1752       (set (make-local-variable 'TeX-command-buffer) command-buffer))
1753
1754     ;; Find the location of the error or warning.
1755     (when line
1756       (goto-char (point-min))
1757       (forward-line (+ offset line -1))
1758       (cond
1759        ;; Error.
1760        ((equal type 'error)
1761         (if (not (string= string " "))
1762             (search-forward string nil t)))
1763        ;; Warning or bad box.
1764        (t
1765         (beginning-of-line 0)
1766         (setq start (point))
1767         (goto-char (point-min))
1768         (forward-line (+ offset line-end -1))
1769         (end-of-line)
1770         (when string
1771           (search-backward string start t)
1772           (search-forward string nil t)))))
1773
1774     ;; Display the help.
1775     (cond ((eq TeX-display-help 'expert)
1776            (TeX-pop-to-buffer runbuf nil t)
1777            (goto-char error-point)
1778            (TeX-pop-to-buffer error-file-buffer nil t))
1779           (TeX-display-help
1780            (TeX-help-error
1781             error
1782             (if (equal type 'warning) (concat "\n" context) context)
1783             runbuf type))
1784           (t
1785            (message (concat "! " error))))))
1786
1787 (defun TeX-error (&optional store)
1788   "Display an error.
1789
1790 If optional argument STORE is non-nil, store the error
1791 information in `TeX-error-list' instead of displaying the error."
1792
1793   (let* ( ;; We need the error message to show the user.
1794          (error (progn
1795                   (re-search-forward "\\(.*\\)")
1796                   (TeX-match-buffer 1)))
1797
1798          ;; And the context for the help window.
1799          (context-start (point))
1800          context-available
1801
1802          ;; And the line number to position the cursor.
1803          (line (cond
1804                 ;; regular style
1805                 ((re-search-forward "l\\.\\([0-9]+\\)" nil t)
1806                  (setq context-available t)
1807                  (string-to-number (TeX-match-buffer 1)))
1808                 ;; file:line:error style
1809                 ((save-excursion
1810                    (re-search-backward ":\\([0-9]+\\): "
1811                                        (line-beginning-position) t))
1812                  (string-to-number (TeX-match-buffer 1)))
1813                 ;; nothing found
1814                 (t 1)))
1815
1816          ;; And a string of the context to search for.
1817          (string (progn
1818                    (beginning-of-line)
1819                    (re-search-forward " \\(\\([^ \t]*$\\)\\|\\($\\)\\)")
1820                    (TeX-match-buffer 1)))
1821
1822          ;; And we have now found to the end of the context.
1823          (context (if context-available
1824                       (buffer-substring context-start (progn (forward-line 1)
1825                                                              (end-of-line)
1826                                                              (point)))
1827                     ;; There is no real context available, so we
1828                     ;; simply show the line with the error message.
1829                     (buffer-substring (1- (line-beginning-position))
1830                                       context-start)))
1831          ;; We may use these in another buffer.
1832          (offset (or (car TeX-error-offset) 0))
1833          (file (car TeX-error-file)))
1834
1835     ;; Remember where we was.
1836     (setq TeX-error-point (point))
1837     (if store
1838         ;; Store the error information.
1839         (add-to-list 'TeX-error-list
1840                      (list 'error file line error offset context string nil nil
1841                            TeX-error-point) t)
1842       ;; Find the error point and display the help.
1843       (TeX-find-display-help
1844        'error file line error offset context string nil nil TeX-error-point))))
1845
1846 (defun TeX-warning (warning &optional store)
1847   "Display a warning for WARNING.
1848
1849 If optional argument STORE is non-nil, store the warning
1850 information in `TeX-error-list' instead of displaying the
1851 warning."
1852
1853   (let* ( ;; bad-box is nil if this is a "LaTeX Warning"
1854          (bad-box (string-match "\\\\[vh]box.*[0-9]*--[0-9]*" warning))
1855          ;; line-string: match 1 is beginning line, match 2 is end line
1856          (line-string (if bad-box " \\([0-9]*\\)--\\([0-9]*\\)"
1857                         "on input line \\([0-9]*\\)\\."))
1858          ;; word-string: match 1 is the word
1859          (word-string (if bad-box "[][\\W() ---]\\(\\w+\\)[][\\W() ---]*$"
1860                         "`\\(\\w+\\)'"))
1861
1862          ;; Get error-line (warning).
1863          (line (when (save-excursion (re-search-backward line-string nil t))
1864                  (string-to-number (TeX-match-buffer 1))))
1865          (line-end (if bad-box (string-to-number (TeX-match-buffer 2))
1866                      line))
1867
1868          ;; Find the context
1869          (context-start (progn (if bad-box (end-of-line)
1870                                  (beginning-of-line))
1871                                (point)))
1872
1873          (context (progn
1874                     (forward-line 1)
1875                     (end-of-line)
1876                     (while (equal (current-column) 79)
1877                       (forward-line 1)
1878                       (end-of-line))
1879                     (buffer-substring context-start (point))))
1880
1881          ;; This is where we want to be.
1882          (error-point (point))
1883
1884          ;; Now find the error word.
1885          (string (when (save-excursion
1886                          (re-search-backward word-string context-start t))
1887                    (TeX-match-buffer 1)))
1888
1889          ;; We might use these in another file.
1890          (offset (or (car TeX-error-offset) 0))
1891          (file (car TeX-error-file)))
1892
1893     ;; This is where we start next time.
1894     (goto-char error-point)
1895     (setq TeX-error-point (point))
1896
1897     (if store
1898         ;; Store the warning information.
1899         (add-to-list 'TeX-error-list
1900                      (list (if bad-box 'bad-box 'warning) file line warning
1901                            offset context string line-end bad-box
1902                            TeX-error-point) t)
1903       ;; Find the warning point and display the help.
1904       (TeX-find-display-help (if bad-box 'bad-box 'warning) file line warning
1905                              offset context string line-end bad-box
1906                              TeX-error-point))))
1907
1908 ;;; - Help
1909
1910 (defgroup TeX-error-description-faces nil
1911   "Faces used in error descriptions."
1912   :prefix "TeX-error-description-"
1913   :group 'TeX-output)
1914
1915 (defface TeX-error-description-error
1916   (if (< emacs-major-version 22)
1917       nil
1918     ;; This is the same as `error' face in latest GNU Emacs versions.
1919     '((((class color) (min-colors 88) (background light))
1920        :foreground "Red1" :weight bold)
1921       (((class color) (min-colors 88) (background dark))
1922        :foreground "Pink" :weight bold)
1923       (((class color) (min-colors 16) (background light))
1924        :foreground "Red1" :weight bold)
1925       (((class color) (min-colors 16) (background dark))
1926        :foreground "Pink" :weight bold)
1927       (((class color) (min-colors 8))
1928        :foreground "red" :weight bold)
1929       (t (:inverse-video t :weight bold))))
1930   "Face for \"Error\" string in error descriptions.")
1931
1932 (defface TeX-error-description-warning
1933   (if (< emacs-major-version 22)
1934       nil
1935     ;; This is the same as `warning' face in latest GNU Emacs versions.
1936     '((((class color) (min-colors 16)) :foreground "DarkOrange" :weight bold)
1937       (((class color)) :foreground "yellow" :weight bold)))
1938   "Face for \"Warning\" string in error descriptions.")
1939
1940 (defface TeX-error-description-tex-said
1941   (if (< emacs-major-version 22)
1942       nil
1943     ;; This is the same as `font-lock-function-name-face' face in latest GNU
1944     ;; Emacs versions.
1945     '((((class color) (min-colors 88) (background light))
1946        :foreground "Blue1")
1947       (((class color) (min-colors 88) (background dark))
1948        :foreground "LightSkyBlue")
1949       (((class color) (min-colors 16) (background light))
1950        :foreground "Blue")
1951       (((class color) (min-colors 16) (background dark))
1952        :foreground "LightSkyBlue")
1953       (((class color) (min-colors 8))
1954        :foreground "blue" :weight bold)
1955       (t (:inverse-video t :weight bold))))
1956   "Face for \"TeX said\" string in error descriptions.")
1957
1958 (defface TeX-error-description-help
1959   '((t (:inherit TeX-error-description-tex-said)))
1960   "Face for \"Help\" string in error descriptions.")
1961
1962 (defun TeX-help-error (error output runbuffer type)
1963   "Print ERROR in context OUTPUT from RUNBUFFER in another window.
1964 TYPE is a symbol specifing if ERROR is a real error, a warning or
1965 a bad box."
1966
1967   (let ((old-buffer (current-buffer))
1968         (log-file (with-current-buffer runbuffer
1969                     (with-current-buffer TeX-command-buffer
1970                       (expand-file-name (TeX-active-master "log")))))
1971         (TeX-error-pointer 0))
1972
1973     ;; Find help text entry.
1974     (while (not (string-match (car (nth TeX-error-pointer
1975                                         TeX-error-description-list))
1976                               error))
1977       (setq TeX-error-pointer (+ TeX-error-pointer 1)))
1978
1979     (TeX-pop-to-buffer (get-buffer-create "*TeX Help*") nil t)
1980     (let ((inhibit-read-only t))
1981       (erase-buffer)
1982       (insert
1983        (cond
1984         ((equal type 'error)
1985          (propertize "ERROR" 'font-lock-face 'TeX-error-description-error))
1986         ((equal type 'warning)
1987          (propertize "WARNING" 'font-lock-face 'TeX-error-description-warning))
1988         ((equal type 'bad-box)
1989          (propertize "BAD BOX" 'font-lock-face 'TeX-error-description-warning)))
1990        ": " error
1991        (propertize "\n\n--- TeX said ---" 'font-lock-face
1992                    'TeX-error-description-tex-said)
1993        output
1994        (propertize "\n--- HELP ---\n" 'font-lock-face
1995                    'TeX-error-description-help)
1996        (let ((help (cdr (nth TeX-error-pointer
1997                              TeX-error-description-list))))
1998          (save-excursion
1999            (if (and (string= help "No help available")
2000                     (let* ((log-buffer (find-buffer-visiting log-file)))
2001                       (if log-buffer
2002                           (progn
2003                             (set-buffer log-buffer)
2004                             (revert-buffer t t))
2005                         (setq log-buffer
2006                               (find-file-noselect log-file))
2007                         (set-buffer log-buffer))
2008                       (auto-save-mode nil)
2009                       (setq buffer-read-only t)
2010                       (goto-char (point-min))
2011                       (search-forward error nil t 1))
2012                     (re-search-forward "^l\\." nil t)
2013                     (re-search-forward "^ [^\n]+$" nil t))
2014                (let ((start (1+ (point))))
2015                  (forward-char 1)
2016                  (re-search-forward "^$")
2017                  (concat "From the .log file...\n\n"
2018                          (buffer-substring start (point))))
2019              help)))))
2020     (goto-char (point-min))
2021     (TeX-special-mode)
2022     (TeX-pop-to-buffer old-buffer nil t)))
2023
2024 ;;; Error Messages
2025
2026 (defcustom TeX-error-description-list
2027   '(("\\(?:Package Preview Error\\|Preview\\):.*" .
2028 "The `auctex' option to `preview' should not be applied manually.
2029 If you see this error message outside of a preview run, either
2030 you did something too clever, or AUCTeX something too stupid.")
2031
2032     ("Bad \\\\line or \\\\vector argument.*" .
2033 "The first argument of a \\line or \\vector command, which specifies the
2034 slope, is illegal\.")
2035
2036     ("Bad math environment delimiter.*" .
2037 "TeX has found either a math-mode-starting command such as \\[ or \\(
2038 when it is already in math mode, or else a math-mode-ending command
2039 such as \\) or \\] while in LR or paragraph mode.  The problem is caused
2040 by either unmatched math mode delimiters or unbalanced braces\.")
2041
2042     ("Bad use of \\\\\\\\.*" .
2043 "A \\\\ command appears between paragraphs, where it makes no sense. This
2044 error message occurs when the \\\\ is used in a centering or flushing
2045 environment or else in the scope of a centering or flushing
2046 declaration.")
2047
2048     ("\\\\begin{[^ ]*} ended by \\\\end{[^ ]*}." .
2049 "LaTeX has found an \\end command that doesn't match the corresponding
2050 \\begin command. You probably misspelled the environment name in the
2051 \\end command, have an extra \\begin, or else forgot an \\end.")
2052
2053     ("Can be used only in preamble." .
2054 "LaTeX has encountered, after the \\begin{document}, one of the
2055 following commands that should appear only in the preamble:
2056 \\documentclass, \\nofiles, \\includeonly, \\makeindex, or
2057 \\makeglossary.  The error is also caused by an extra \\begin{document}
2058 command.")
2059
2060     ("Command name [^ ]* already used.*" .
2061 "You are using \\newcommand, \\newenvironment, \\newlength, \\newsavebox,
2062 or \\newtheorem to define a command or environment name that is
2063 already defined, or \\newcounter to define a counter that already
2064 exists. (Defining an environment named gnu automatically defines the
2065 command \\gnu.) You'll have to choose a new name or, in the case of
2066 \\newcommand or \\newenvironment, switch to the \\renew ...  command.")
2067
2068     ("Counter too large." .
2069 "1. Some object that is numbered with letters, probably an item in a
2070 enumerated list, has received a number greater than 26. Either you're
2071 making a very long list or you've been resetting counter values.
2072
2073 2. Footnotes are being ``numbered'' with letters or footnote symbols
2074 and LaTeX has run out of letters or symbols. This is probably caused
2075 by too many \\thanks commands.")
2076
2077     ("Environment [^ ]* undefined." .
2078 "LaTeX has encountered a \\begin command for a nonexistent environment.
2079 You probably misspelled the environment name. ")
2080
2081     ("Float(s) lost." .
2082 "You put a figure or table environment or a \\marginpar command inside a
2083 parbox---either one made with a minipage environment or \\parbox
2084 command, or one constructed by LaTeX in making a footnote, figure,
2085 etc. This is an outputting error, and the offending environment or
2086 command may be quite a way back from the point where LaTeX discovered
2087 the problem. One or more figures, tables, and/or marginal notes have
2088 been lost, but not necessarily the one that caused the error.")
2089
2090     ("Illegal character in array arg." .
2091 "There is an illegal character in the argument of an array or tabular
2092 environment, or in the second argument of a \\multicolumn command.")
2093
2094     ("Missing \\\\begin{document}." .
2095 "LaTeX produced printed output before encountering a \\begin{document}
2096 command. Either you forgot the \\begin{document} command or there is
2097 something wrong in the preamble. The problem may be a stray character
2098 or an error in a declaration---for example, omitting the braces around
2099 an argument or forgetting the \\ in a command name.")
2100
2101     ("Missing p-arg in array arg.*" .
2102 "There is a p that is not followed by an expression in braces in the
2103 argument of an array or tabular environment, or in the second argument
2104 of a \\multicolumn command.")
2105
2106     ("Missing @-exp in array arg." .
2107 "There is an @ character not followed by an @-expression in the
2108 argument of an array or tabular environment, or in the second argument
2109 of a \\multicolumn command.")
2110
2111     ("No such counter." .
2112 "You have specified a nonexistent counter in a \\setcounter or
2113 \\addtocounter command. This is probably caused by a simple typing
2114 error.  However, if the error occurred while a file with the extension
2115 aux is being read, then you probably used a \\newcounter command
2116 outside the preamble.")
2117
2118     ("Not in outer par mode." .
2119 "You had a figure or table environment or a \\marginpar command in math
2120 mode or inside a parbox.")
2121
2122     ("\\\\pushtabs and \\\\poptabs don't match." .
2123 "LaTeX found a \\poptabs with no matching \\pushtabs, or has come to the
2124 \\end{tabbing} command with one or more unmatched \\pushtabs commands.")
2125
2126     ("Something's wrong--perhaps a missing \\\\item." .
2127 "The most probable cause is an omitted \\item command in a list-making
2128 environment. It is also caused by forgetting the argument of a
2129 thebibliography environment.")
2130
2131     ("Tab overflow." .
2132 "A \\= command has exceeded the maximum number of tab stops that LaTeX
2133 permits.")
2134
2135     ("There's no line here to end." .
2136 "A \\newline or \\\\ command appears between paragraphs, where it makes no
2137 sense. If you're trying to ``leave a blank line'', use a \\vspace
2138 command.")
2139
2140     ("This may be a LaTeX bug." .
2141 "LaTeX has become thoroughly confused. This is probably due to a
2142 previously detected error, but it is possible that you have found an
2143 error in LaTeX itself. If this is the first error message produced by
2144 the input file and you can't find anything wrong, save the file and
2145 contact the person listed in your Local Guide.")
2146
2147     ("Too deeply nested." .
2148 "There are too many list-making environments nested within one another.
2149 How many levels of nesting are permitted may depend upon what computer
2150 you are using, but at least four levels are provided, which should be
2151 enough.")
2152
2153     ("Too many unprocessed floats." .
2154 "While this error can result from having too many \\marginpar commands
2155 on a page, a more likely cause is forcing LaTeX to save more figures
2156 and tables than it has room for.  When typesetting its continuous
2157 scroll, LaTeX saves figures and tables separately and inserts them as
2158 it cuts off pages. This error occurs when LaTeX finds too many figure
2159 and/or table environments before it is time to cut off a page, a
2160 problem that is solved by moving some of the environments farther
2161 towards the end of the input file. The error can also be caused by a
2162 ``logjam''---a figure or table that cannot be printed causing others
2163 to pile up behind it, since LaTeX will not print figures or tables out
2164 of order. The jam can be started by a figure or table that either is
2165 too large to fit on a page or won't fit where its optional placement
2166 argument says it must go. This is likely to happen if the argument
2167 does not contain a p option.")
2168
2169     ("Undefined tab position." .
2170 "A \\>, \\+, \\-, or \\< command is trying to go to a nonexistent tab
2171 position---one not defined by a \\= command.")
2172
2173     ("\\\\< in mid line." .
2174 "A \\< command appears in the middle of a line in a tabbing environment.
2175 This command should come only at the beginning of a line.")
2176
2177     ("Double subscript." .
2178 "There are two subscripts in a row in a mathematical
2179 formula---something like x_{2}_{3}, which makes no sense.")
2180
2181     ("Double superscript." .
2182 "There are two superscripts in a row in a mathematical
2183 formula---something like x^{2}^{3}, which makes no sense.")
2184
2185     ("Extra alignment tab has been changed to \\\\cr." .
2186 "There are too many separate items (column entries) in a single row of
2187 an array or tabular environment. In other words, there were too many &
2188 's before the end of the row. You probably forgot the \\\\ at the end of
2189 the preceding row.")
2190
2191     ("Extra \\}, or forgotten \\$." .
2192 "The braces or math mode delimiters don't match properly. You probably
2193 forgot a {, \\[, \\(, or $.")
2194
2195     ("Font [^ ]* not loaded: Not enough room left." .
2196 "The document uses more fonts than TeX has room for. If different parts
2197 of the document use different fonts, then you can get around the
2198 problem by processing it in parts.")
2199
2200     ("I can't find file `.*'." .
2201 "TeX can't find a file that it needs. If the name of the missing file
2202 has the extension tex, then it is looking for an input file that you
2203 specified---either your main file or another file inserted with an
2204 \\input or \\include command. If the missing file has the extension sty
2205 , then you have specified a nonexistent document style or style
2206 option.")
2207
2208     ("Illegal parameter number in definition of .*" .
2209 "This is probably caused by a \\newcommand, \\renewcommand,
2210 \\newenvironment, or \\renewenvironment command in which a # is used
2211 incorrectly.  A # character, except as part of the command name \\#,
2212 can be used only to indicate an argument parameter, as in #2, which
2213 denotes the second argument. This error is also caused by nesting one
2214 of the above four commands inside another, or by putting a parameter
2215 like #2 in the last argument of a \\newenvironment or \\renewenvironment
2216 command.")
2217
2218     ("Illegal unit of measure ([^ ]* inserted)." .
2219 "If you just got a
2220
2221       ! Missing number, treated as zero.
2222
2223 error, then this is part of the same problem.  If not, it means that
2224 LaTeX was expecting a length as an argument and found a number
2225 instead.  The most common cause of this error is writing 0 instead of
2226 something like 0in for a length of zero, in which case typing return
2227 should result in correct output. However, the error can also be caused
2228 by omitting a command argument.")
2229
2230     ("Misplaced alignment tab character \\&." .
2231 "The special character &, which should be used only to separate items
2232 in an array or tabular environment, appeared in ordinary text. You
2233 probably meant to type \\&.")
2234
2235     ("Missing control sequence inserted." .
2236 "This is probably caused by a \\newcommand, \\renewcommand, \\newlength,
2237 or \\newsavebox command whose first argument is not a command name.")
2238
2239     ("Missing number, treated as zero." .
2240 "This is usually caused by a LaTeX command expecting but not finding
2241 either a number or a length as an argument. You may have omitted an
2242 argument, or a square bracket in the text may have been mistaken for
2243 the beginning of an optional argument. This error is also caused by
2244 putting \\protect in front of either a length command or a command such
2245 as \\value that produces a number.")
2246
2247     ("Missing [{}] inserted." .
2248 "TeX has become confused. The position indicated by the error locator
2249 is probably beyond the point where the incorrect input is.")
2250
2251     ("Missing \\$ inserted." .
2252 "TeX probably found a command that can be used only in math mode when
2253 it wasn't in math mode.  Remember that unless stated otherwise, all
2254 all the commands of Section 3.3 in LaTeX Book (Lamport) can be used
2255 only in math mode. TeX is not in math mode when it begins processing
2256 the argument of a box-making command, even if that command is inside a
2257 math environment. This error also occurs if TeX encounters a blank
2258 line when it is in math mode.")
2259
2260     ("Not a letter." .
2261 "Something appears in the argument of a \\hyphenation command that
2262 doesn't belong there.")
2263
2264     ("Paragraph ended before [^ ]* was complete." .
2265 "A blank line occurred in a command argument that shouldn't contain
2266 one. You probably forgot the right brace at the end of an argument.")
2267
2268     ("\\\\[^ ]*font [^ ]* is undefined .*" .
2269 "These errors occur when an uncommon font is used in math mode---for
2270 example, if you use a \\sc command in a formula inside a footnote,
2271 calling for a footnote-sized small caps font.  This problem is solved
2272 by using a \\load command.")
2273
2274     ("Font .* not found." .
2275 "You requested a family/series/shape/size combination that is totally
2276 unknown.  There are two cases in which this error can occur:
2277   1) You used the \\size macro to select a size that is not available.
2278   2) If you did not do that, go to your local `wizard' and
2279      complain fiercely that the font selection tables are corrupted!")
2280
2281     ("TeX capacity exceeded, sorry .*" .
2282 "TeX has just run out of space and aborted its execution. Before you
2283 panic, remember that the least likely cause of this error is TeX not
2284 having the capacity to process your document.  It was probably an
2285 error in your input file that caused TeX to run out of room. The
2286 following discussion explains how to decide whether you've really
2287 exceeded TeX's capacity and, if so, what to do. If the problem is an
2288 error in the input, you may have to use the divide and conquer method
2289 described previously to locate it. LaTeX seldom runs out of space on a
2290 short input file, so if running it on the last few pages before the
2291 error indicator's position still produces the error, then there's
2292 almost certainly something wrong in the input file.
2293
2294 The end of the error indicator tells what kind of space TeX ran out
2295 of. The more common ones are listed below, with an explanation of
2296 their probable causes.
2297
2298 buffer size
2299 ===========
2300 Can be caused by too long a piece of text as the argument
2301 of a sectioning, \\caption, \\addcontentsline, or \\addtocontents
2302 command. This error will probably occur when the \\end{document} is
2303 being processed, but it could happen when a \\tableofcontents,
2304 \\listoffigures, or \\listoftables command is executed. To solve this
2305 problem, use a shorter optional argument. Even if you're producing a
2306 table of contents or a list of figures or tables, such a long entry
2307 won't help the reader.
2308
2309 exception dictionary
2310 ====================
2311 You have used \\hyphenation commands to give TeX
2312 more hyphenation information than it has room for. Remove some of the
2313 less frequently used words from the \\hyphenation commands and insert
2314 \\- commands instead.
2315
2316 hash size
2317 =========
2318 Your input file defines too many command names and/or uses
2319 too many cross-ref- erencing labels.
2320
2321 input stack size
2322 ================
2323 This is probably caused by an error in a command
2324 definition. For example, the following command makes a circular
2325 definition, defining \\gnu in terms of itself:
2326
2327           \\newcommand{\\gnu}{a \\gnu} % This is wrong!
2328
2329 When TeX encounters this \\gnu command, it will keep chasing its tail
2330 trying to figure out what \\gnu should produce, and eventually run out
2331 of ``input stack''.
2332
2333 main memory size
2334 ================
2335 This is one kind of space that TeX can run out of when processing a
2336 short file. There are three ways you can run TeX out of main memory
2337 space: (1) defining a lot of very long, complicated commands, (2)
2338 making an index or glossary and having too many \\index or \\glossary
2339 commands on a single page, and (3) creating so complicated a page of
2340 output that TeX can't hold all the information needed to generate it.
2341 The solution to the first two problems is obvious: define fewer
2342 commands or use fewer \\index and \\glossary commands. The third problem
2343 is nastier. It can be caused by large tabbing, tabular, array, and
2344 picture environments. TeX's space may also be filled up with figures
2345 and tables waiting for a place to go.  To find out if you've really
2346 exceeded TeX's capacity in this way, put a \\clearpage command in your
2347 input file right before the place where TeX ran out of room and try
2348 running it again. If it doesn't run out of room with the \\clearpage
2349 command there, then you did exceed TeX's capacity.  If it still runs
2350 out of room, then there's probably an error in your file.  If TeX is
2351 really out of room, you must give it some help. Remember that TeX
2352 processes a complete paragraph before deciding whether to cut the
2353 page. Inserting a \\newpage command in the middle of the paragraph,
2354 where TeX should break the page, may save the day by letting TeX write
2355 the current page before processing the rest of the paragraph. (A
2356 \\pagebreak command won't help.) If the problem is caused by
2357 accumulated figures and tables, you can try to prevent them from
2358 accumulating---either by moving them further towards the end of the
2359 document or by trying to get them to come out sooner.  If you are
2360 still writing the document, simply add a \\clearpage command and forget
2361 about the problem until you're ready to produce the final version.
2362 Changes to the input file are likely to make the problem go away.
2363
2364 pool size
2365 =========
2366 You probably used too many cross-ref-erencing \\labels and/or defined
2367 too many new command names. More precisely, the labels and command
2368 names that you define have too many characters, so this problem can be
2369 solved by using shorter names. However, the error can also be caused
2370 by omitting the right brace that ends the argument of either a counter
2371 command such as \\setcounter, or a \\newenvironment or \\newtheorem
2372 command.
2373
2374 save size
2375 =========
2376 This occurs when commands, environments, and the scopes of
2377 declarations are nested too deeply---for example, by having the
2378 argument of a \\multiput command contain a picture environment that in
2379 turn has a \\footnotesize declaration whose scope contains a \\multiput
2380 command containing a ....")
2381
2382     ("Text line contains an invalid character." .
2383 "The input contains some strange character that it shouldn't. A mistake
2384 when creating the file probably caused your text editor to insert this
2385 character. Exactly what could have happened depends upon what text
2386 editor you used. If examining the input file doesn't reveal the
2387 offending character, consult the Local Guide for suggestions.")
2388
2389     ("Undefined control sequence."   .
2390 "TeX encountered an unknown command name. You probably misspelled the
2391 name. If this message occurs when a LaTeX command is being processed,
2392 the command is probably in the wrong place---for example, the error
2393 can be produced by an \\item command that's not inside a list-making
2394 environment. The error can also be caused by a missing \\documentclass
2395 command.")
2396
2397     ("Use of [^ ]* doesn't match its definition." .
2398 "It's probably one of the picture-drawing commands, and you have used
2399 the wrong syntax for specifying an argument. If it's \\@array that
2400 doesn't match its definition, then there is something wrong in an
2401 @-expression in the argument of an array or tabular
2402 environment---perhaps a fragile command that is not \\protect'ed.")
2403
2404     ("You can't use `macro parameter character \\#' in [^ ]* mode." .
2405 "The special character # has appeared in ordinary text. You probably
2406 meant to type \\#.")
2407
2408     ("Overfull \\\\hbox .*" .
2409 "Because it couldn't find a good place for a line break, TeX put more
2410 on this line than it should.")
2411
2412     ("Overfull \\\\vbox .*" .
2413 "Because it couldn't find a good place for a page break, TeX put more
2414 on the page than it should. ")
2415
2416     ("Underfull \\\\hbox .*" .
2417 "Check your output for extra vertical space.  If you find some, it was
2418 probably caused by a problem with a \\\\ or \\newline command---for
2419 example, two \\\\ commands in succession. This warning can also be
2420 caused by using the sloppypar environment or \\sloppy declaration, or
2421 by inserting a \\linebreak command.")
2422
2423     ("Underfull \\\\vbox .*" .
2424 "TeX could not find a good place to break the page, so it produced a
2425 page without enough text on it. ")
2426
2427 ;; New list items should be placed here
2428 ;;
2429 ;; ("err-regexp" . "context")
2430 ;;
2431 ;; the err-regexp item should match anything
2432
2433     (".*" . "No help available"))       ; end definition
2434 "A list of the form (\"err-regexp\" . \"context\") used by function
2435 `TeX-help-error' to display help-text on an error message or warning.
2436 err-regexp should be a regular expression matching the error message
2437 given from TeX/LaTeX, and context should be some lines describing that
2438 error."
2439   :group 'TeX-output
2440   :type '(repeat (cons :tag "Entry"
2441                        (regexp :tag "Match")
2442                        (string :format "Description:\n%v"))))
2443
2444 ;;; Error Overview
2445
2446 (defvar TeX-error-overview-active-buffer nil
2447   "The active buffer for the current error overview.")
2448
2449 (defvar TeX-error-overview-orig-frame nil
2450   "Frame from which the error overview has been launched.")
2451
2452 (defvar TeX-error-overview-orig-window nil
2453   "Window from which the error overview has been launched.")
2454
2455 (defcustom TeX-error-overview-setup nil
2456   "The frame setup of the error overview.
2457
2458 The possible value is: `separate-frame' (error oveview in a
2459 separate frame); with a nil value the current frame is used.
2460
2461 If the display does not support multi frame, the current frame
2462 will be used regardless of the value of this variable."
2463   :group 'TeX-output
2464   :type '(choice
2465           (const :tag "Error overview in separate frame" separate-frame)
2466           (const :tag "Use current frame" nil)))
2467
2468 (defun TeX-error-overview-setup ()
2469   "Return the frame setup of the error overview for the current display."
2470   (and (display-multi-frame-p) TeX-error-overview-setup))
2471
2472 (defun TeX-error-overview-goto-source (&optional button)
2473   "Go to the error point in the source.
2474 If optional argument BUTTON is non-nil, go to source associated
2475 to the selected error."
2476   (interactive)
2477   (let ((index (if button (button-get button 'id) (tabulated-list-get-id)))
2478         item window)
2479     (if index
2480         (progn
2481           ;; Select the source frame/window, if still live.
2482           (if (TeX-error-overview-setup)
2483               (if (frame-live-p TeX-error-overview-orig-frame)
2484                   (select-frame TeX-error-overview-orig-frame)
2485                 (error "You have deleted a vital frame---\
2486 please restart TeX error overview"))
2487             (if (window-live-p TeX-error-overview-orig-window)
2488                 (select-window TeX-error-overview-orig-window)
2489               (error "You have deleted a vital window---\
2490 please restart TeX error overview")))
2491           ;; Get the error details.
2492           (with-current-buffer TeX-error-overview-active-buffer
2493             (setq item (nth index TeX-error-list)
2494                   TeX-error-last-visited index))
2495           ;; Find the error and display the help.
2496           (with-current-buffer TeX-command-buffer
2497             ;; For consistency with `TeX-parse-TeX', use the major mode of
2498             ;; `TeX-command-buffer' when visiting the error point.
2499             (let ((default-major-mode major-mode))
2500               ;; Find the error and display the help.
2501               (apply 'TeX-find-display-help item)))
2502           ;; Return to the error overview.
2503           (if (TeX-error-overview-setup)
2504               (select-frame TeX-error-overview-frame)
2505             (if (setq window
2506                       (get-buffer-window TeX-error-overview-buffer-name))
2507                 ;; If error overview window is visible just select it.
2508                 (select-window window)
2509               ;; Otherwise, split the help window and display the error overview
2510               ;; near to it.  This should be the only reason for the error
2511               ;; overview window not being still visible after the beginning of
2512               ;; the function.
2513               (select-window
2514                (get-buffer-window (cond
2515                                    ((eq TeX-display-help 'expert)
2516                                     TeX-error-overview-active-buffer)
2517                                    (TeX-display-help  "*TeX Help*"))))
2518               (if (window-splittable-p (selected-window) t)
2519                   (split-window-horizontally)
2520                 (split-window-vertically))
2521               (switch-to-buffer TeX-error-overview-buffer-name))))
2522       (message "No more errors.")
2523       (beep))))
2524
2525 (defun TeX-error-overview-make-entries (&optional master-dir)
2526   "Generate the list of errors to be printed using `tabulated-list-entries'.
2527 Write file names relative to MASTER-DIR when they are not absolute."
2528   (with-current-buffer TeX-error-overview-active-buffer
2529     (let ((id 0)
2530           type file line msg entries)
2531       (mapc
2532        (lambda (entry)
2533          (setq type (nth 0 entry)
2534                file (nth 1 entry)
2535                line (nth 2 entry)
2536                msg  (nth 3 entry))
2537          (add-to-list
2538           'entries
2539           (list
2540            ;; ID.
2541            id
2542            (vector
2543             ;; File.
2544             (if (stringp file)
2545                 (if (file-name-absolute-p file)
2546                     file
2547                   (file-relative-name file master-dir))
2548               "")
2549             ;; Line.
2550             (if (numberp line)
2551                 (number-to-string line)
2552               "")
2553             ;; Type.
2554             (cond
2555              ((equal type 'error)
2556               (propertize "Error" 'font-lock-face 'TeX-error-description-error))
2557              ((equal type 'warning)
2558               (propertize "Warning" 'font-lock-face
2559                           'TeX-error-description-warning))
2560              ((equal type 'bad-box)
2561               (propertize "Bad box" 'font-lock-face
2562                           'TeX-error-description-warning))
2563              (t
2564               ""))
2565             ;; Message.
2566             (list (if (stringp msg) msg "")
2567                   'face 'link
2568                   'follow-link t
2569                   'id id
2570                   'action 'TeX-error-overview-goto-source)
2571             )) t)
2572          (setq id (1+ id))) TeX-error-list)
2573       entries)))
2574
2575 (defun TeX-error-overview-next-error (&optional arg)
2576   "Move to the next line and find the associated error.
2577
2578 A prefix ARG specifies how many error messages to move; negative
2579 means move back to previous error messages."
2580   (interactive "p")
2581   (if (= (forward-line arg) 0)
2582       (TeX-error-overview-goto-source)
2583     ;; If there are lines left to move we are at the beginning or at the end of
2584     ;; the buffer and there are no more errors.
2585     (message "No more errors.")
2586     (beep)))
2587
2588 (defun TeX-error-overview-previous-error (&optional arg)
2589   "Move to the previous line and find the associated error.
2590
2591 Prefix arg N says how many error messages to move backward (or
2592 forward, if negative)."
2593   (interactive "p")
2594   (TeX-error-overview-next-error (- arg)))
2595
2596 (defun TeX-error-overview-quit ()
2597   "Delete the window or the frame of the error overview."
2598   (interactive)
2599   (if (TeX-error-overview-setup)
2600       (delete-frame TeX-error-overview-frame)
2601     (delete-window))
2602   (setq TeX-error-overview-orig-frame nil))
2603
2604 (defvar TeX-error-overview-mode-map
2605   (let ((map (make-sparse-keymap))
2606         (menu-map (make-sparse-keymap)))
2607     (define-key map "n"    'TeX-error-overview-next-error)
2608     (define-key map "p"    'TeX-error-overview-previous-error)
2609     (define-key map "q"    'TeX-error-overview-quit)
2610     (define-key map "\C-m" 'TeX-error-overview-goto-source)
2611     map)
2612   "Local keymap for `TeX-error-overview-mode' buffers.")
2613
2614 (defvar TeX-error-overview-list-entries nil
2615   "List of errors to be used in the error overview.")
2616
2617 (define-derived-mode TeX-error-overview-mode tabulated-list-mode
2618   "TeX errors"
2619   "Major mode for listing TeX errors."
2620   (setq tabulated-list-format [("File" 25 nil)
2621                                ("Line" 4 nil :right-align t)
2622                                ("Type" 7 nil)
2623                                ("Message" 0 nil)]
2624         tabulated-list-padding 1
2625         tabulated-list-entries TeX-error-overview-list-entries)
2626   (tabulated-list-init-header)
2627   (tabulated-list-print))
2628
2629 (defcustom TeX-error-overview-frame-parameters
2630   '((name . "TeX errors")
2631     (title . "TeX errors")
2632     (height . 10)
2633     (width . 80)
2634     (top . (- 0))
2635     (left . (- 0))
2636     (unsplittable . t)
2637     (minibuffer . nil)
2638     (vertical-scroll-bars . t)
2639     (tool-bar-lines . 0))
2640   "Parameters of the error overview frame."
2641   :group 'TeX-output
2642   :type 'alist
2643   :options '((name string) (title string) (height integer) (width integer)
2644              (top integer) (left integer) (unsplittable boolean)
2645              (minibuffer boolean) (vertical-scroll-bars boolean)
2646              (tool-bar-lines integer)))
2647
2648 (defcustom TeX-error-overview-open-after-TeX-run nil
2649   "Whether to open automatically the error overview after running TeX."
2650   :group 'TeX-output
2651   :type 'boolean)
2652
2653 (defun TeX-error-overview ()
2654   "Show an overview of the errors occurred in the last TeX run."
2655   (interactive)
2656   ;; Check requirements before start.
2657   (if (fboundp 'tabulated-list-mode)
2658       (if (setq TeX-error-overview-active-buffer (TeX-active-buffer))
2659           (if (with-current-buffer TeX-error-overview-active-buffer
2660                 TeX-error-list)
2661               (progn
2662                 (setq TeX-error-overview-list-entries
2663                       (TeX-error-overview-make-entries (TeX-master-directory))
2664                       TeX-error-overview-orig-window (selected-window)
2665                       TeX-error-overview-orig-frame
2666                       (window-frame TeX-error-overview-orig-window))
2667                 ;; Create the error overview buffer.  This is
2668                 ;; automatically killed before running TeX commands, so if
2669                 ;; exists it is up-to-date and doesn't need to be
2670                 ;; re-created.
2671                 (unless (get-buffer TeX-error-overview-buffer-name)
2672                   (with-current-buffer
2673                       (get-buffer-create TeX-error-overview-buffer-name)
2674                     (TeX-error-overview-mode)))
2675                 ;; Move point to the line associated to the last visited
2676                 ;; error.
2677                 (with-current-buffer TeX-error-overview-buffer-name
2678                   (goto-char (point-min))
2679                   (forward-line (with-current-buffer
2680                                     TeX-error-overview-active-buffer
2681                                   TeX-error-last-visited))
2682                   ;; Create a new frame for the error overview or display the
2683                   ;; buffer in the same frame, depending on the setup.
2684                   (if (TeX-error-overview-setup)
2685                       (if (frame-live-p TeX-error-overview-frame)
2686                           ;; Do not create a duplicate frame if there is
2687                           ;; already one, just select it.
2688                           (select-frame-set-input-focus
2689                            TeX-error-overview-frame)
2690                         ;; Create a new frame and store its name.
2691                         (select-frame
2692                          (setq TeX-error-overview-frame
2693                                (make-frame
2694                                 TeX-error-overview-frame-parameters)))
2695                         (set-window-buffer (selected-window)
2696                                            TeX-error-overview-buffer-name)
2697                         (set-window-dedicated-p (selected-window) t))
2698                     (TeX-pop-to-buffer TeX-error-overview-buffer-name))))
2699             (error "No errror or warning to show"))
2700         (error "No process for this document"))
2701     (error "Error overview is available only in Emacs 24 or later")))
2702
2703 ;;; Output mode
2704
2705 (if (fboundp 'special-mode)
2706     (progn
2707       (defalias 'TeX-special-mode 'special-mode)
2708       (defvaralias 'TeX-special-mode-map 'special-mode-map))
2709   (defun TeX-special-mode ()
2710     "Placeholder mode for Emacsen which don't have `special-mode'.")
2711   (defvar TeX-special-mode-map
2712     (let ((map (make-sparse-keymap)))
2713       (suppress-keymap map)
2714       (define-key map "q" (if (fboundp 'quit-window)
2715                               'quit-window
2716                             'bury-buffer))
2717       (define-key map " " (if (fboundp 'scroll-up-command)
2718                               'scroll-up-command
2719                             'scroll-up))
2720       (define-key map [backspace] (if (fboundp 'scroll-down-command)
2721                                       'scroll-down-command
2722                                     'scroll-down))
2723       (define-key map "\C-?" (if (fboundp 'scroll-down-command)
2724                                  'scroll-down-command
2725                                'scroll-down))
2726       (define-key map "?" 'describe-mode)
2727       (define-key map "h" 'describe-mode)
2728       (define-key map ">" 'end-of-buffer)
2729       (define-key map "<" 'beginning-of-buffer)
2730       (define-key map "g" 'revert-buffer)
2731       map)
2732     "Keymap for `TeX-special-mode-map'."))
2733
2734 (defvar TeX-output-mode-map
2735   (let ((map (make-sparse-keymap)))
2736     (set-keymap-parent map TeX-special-mode-map)
2737     (define-key map "n" 'TeX-next-error)
2738     (define-key map "p" 'TeX-previous-error)
2739     (define-key map "b" 'TeX-toggle-debug-bad-boxes)
2740     (define-key map "w" 'TeX-toggle-debug-warnings)
2741     (define-key map "i" (lambda ()
2742                           (interactive)
2743                           (with-current-buffer TeX-command-buffer
2744                             (TeX-interactive-mode (if TeX-interactive-mode -1 1)))))
2745     (define-key map "s" (lambda ()
2746                           (interactive)
2747                           (with-current-buffer TeX-command-buffer
2748                             (TeX-source-correlate-mode (if TeX-source-correlate-mode -1 1)))))
2749     map)
2750   "Keymap for `TeX-output-mode'.")
2751
2752 (define-derived-mode TeX-output-mode TeX-special-mode "TeX Output"
2753     "Major mode for viewing TeX output.
2754 \\{TeX-output-mode-map} "
2755     :syntax-table nil
2756     (set (make-local-variable 'revert-buffer-function)
2757          #'TeX-output-revert-buffer)
2758     ;; special-mode makes it read-only which prevents input from TeX.
2759     (setq buffer-read-only nil))
2760
2761 (defun TeX-output-revert-buffer (ignore-auto noconfirm)
2762   "Rerun the TeX command which of which this buffer was the output."
2763   (goto-char (point-min))
2764   (if (looking-at "Running `\\(.*\\)' on `\\(.*\\)' with ``\\(.*\\)''$")
2765       (let ((name (match-string 1))
2766             (file (match-string 2))
2767             (command (match-string 3)))
2768         (with-current-buffer TeX-command-buffer
2769           (TeX-command name (if (string-match "_region_" file)
2770                                 'TeX-region-file
2771                               'TeX-master-file))))
2772     (error "Unable to find what command to run.")))
2773
2774 (provide 'tex-buf)
2775
2776 ;;; tex-buf.el ends here