(syms_of_buffer): Doc fix.
[bpt/emacs.git] / lisp / textmodes / tex-mode.el
index ed06f21..41ff420 100644 (file)
@@ -1,12 +1,13 @@
 ;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands.
 
-;; Copyright (C) 1985, 1986, 1989, 1992 Free Software Foundation, Inc.
+;; Copyright (C) 1985, 86, 89, 92, 94, 95, 96, 1997
+;;       Free Software Foundation, Inc.
 
-;; Maintainer: Edward M. Reingold <reingold@cs.uiuc.edu>
+;; Maintainer: FSF
 ;; Keywords: tex
 
 ;; Contributions over the years by William F. Schelter, Dick King,
-;; Stephen Gildea, Michael Prange, and Jacob Gore.
+;; Stephen Gildea, Michael Prange, Jacob Gore, and Edward M. Reingold.
 
 ;; This file is part of GNU Emacs.
 
 ;; GNU General Public License for more details.
 
 ;; You should have received a copy of the GNU General Public License
-;; along with GNU Emacs; see the file COPYING.  If not, write to
-;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+;; along with GNU Emacs; see the file COPYING.  If not, write to the
+;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
 
 ;;; Code:
 
 (require 'shell)
 (require 'compile)
 
+(defgroup tex-file nil
+  "TeX files and directories"
+  :prefix "tex-"
+  :group 'tex)
+
+(defgroup tex-run nil
+  "Running external commands from TeX mode"
+  :prefix "tex-"
+  :group 'tex)
+
+(defgroup tex-view nil
+  "Viewing and printing TeX files"
+  :prefix "tex-"
+  :group 'tex)
+
 ;;;###autoload
-(defvar tex-shell-file-name nil
-  "*If non-nil, is file name to use for the subshell in which TeX is run.")
+(defcustom tex-shell-file-name nil
+  "*If non-nil, the shell file name to run in the subshell used to run TeX."
+  :type '(choice (const :tag "None" nil)
+                string)
+  :group 'tex-run)
 
 ;;;###autoload
-(defvar tex-directory "."
-  "*Directory in which temporary files are left.
-You can make this /tmp if your TEXINPUTS has no relative directories in it
+(defcustom tex-directory "."
+  "*Directory in which temporary files are written.
+You can make this `/tmp' if your TEXINPUTS has no relative directories in it
 and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
-\\input commands with relative directories.")
+`\\input' commands with relative directories."
+  :type 'directory
+  :group 'tex-file)
+
+;;;###autoload
+(defcustom tex-first-line-header-regexp nil
+  "Regexp for matching a first line which `tex-region' should include.
+If this is non-nil, it should be a regular expression string;
+if it matches the first line of the file,
+`tex-region' always includes the first line in the TeX run."
+  :type '(choice (const :tag "None" nil)
+                 regexp)
+  :group 'tex-file)
 
 ;;;###autoload
-(defvar tex-offer-save t
-  "*If non-nil, ask about saving modified buffers before \\[tex-file] is run.")
+(defcustom tex-main-file nil
+  "*The main TeX source file which includes this buffer's file.
+The command `tex-file' runs TeX on the file specified by `tex-main-file'
+if the variable is non-nil."
+  :type '(choice (const :tag "None" nil)
+                 file)
+  :group 'tex-file)
 
 ;;;###autoload
-(defvar tex-run-command "tex"
+(defcustom tex-offer-save t
+  "*If non-nil, ask about saving modified buffers before \\[tex-file] is run."
+  :type 'boolean
+  :group 'tex-file)
+
+;;;###autoload
+(defcustom tex-run-command "tex"
   "*Command used to run TeX subjob.
-If this string contains an asterisk (*), it will be replaced by the
-filename; if not, the name of the file, preceded by blank, will be added to
-this string.")
+If this string contains an asterisk (`*'), that is replaced by the file name;
+otherwise the value of tex-start-options-string and the file name are added
+at the end, with blanks as separators."
+  :type 'string
+  :group 'tex-run)
+
+(defcustom tex-start-options-string "\\\\nonstopmode\\\\input"
+  "*TeX options to use when running TeX.
+These precede the input file name."
+  :type 'string
+  :group 'tex-run
+  :version "20.4")
 
 ;;;###autoload
-(defvar latex-run-command "latex"
+(defcustom latex-run-command "latex"
   "*Command used to run LaTeX subjob.
-If this string contains an asterisk (*), it will be replaced by the
-filename; if not, the name of the file, preceded by blank, will be added to
-this string.")
+If this string contains an asterisk (`*'), that is replaced by the file name;
+otherwise, the file name, preceded by blank, is added at the end."
+  :type 'string
+  :group 'tex-run)
 
 (defvar standard-latex-block-names
       '("abstract"         "array"            "center"       "description"
@@ -71,54 +124,60 @@ this string.")
   "Standard LaTeX block names.")
 
 ;;;###autoload
-(defvar latex-block-names nil
+(defcustom latex-block-names nil
   "*User defined LaTeX block names.
-Combined with `standard-latex-block-names' for minibuffer completion.")
+Combined with `standard-latex-block-names' for minibuffer completion."
+  :type '(repeat string)
+  :group 'tex-run)
 
 ;;;###autoload
-(defvar slitex-run-command "slitex"
+(defcustom slitex-run-command "slitex"
   "*Command used to run SliTeX subjob.
-If this string contains an asterisk (*), it will be replaced by the
-filename; if not, the name of the file, preceded by blank, will be added to
-this string.")
+If this string contains an asterisk (`*'), that is replaced by the file name;
+otherwise, the file name, preceded by blank, is added at the end."
+  :type 'string
+  :group 'tex-run)
 
 ;;;###autoload
-(defvar tex-bibtex-command "bibtex"
+(defcustom tex-bibtex-command "bibtex"
   "*Command used by `tex-bibtex-file' to gather bibliographic data.
-If this string contains an asterisk (*), it will be replaced by the
-filename; if not, the name of the file, preceded by blank, will be added to
-this string.")
+If this string contains an asterisk (`*'), that is replaced by the file name;
+otherwise, the file name, preceded by blank, is added at the end."
+  :type 'string
+  :group 'tex-run)
 
 ;;;###autoload
-(defvar tex-dvi-print-command "lpr -d"
+(defcustom tex-dvi-print-command "lpr -d"
   "*Command used by \\[tex-print] to print a .dvi file.
-If this string contains an asterisk (*), it will be replaced by the
-filename; if not, the name of the file, preceded by blank, will be added to
-this string.")
+If this string contains an asterisk (`*'), that is replaced by the file name;
+otherwise, the file name, preceded by blank, is added at the end."
+  :type 'string
+  :group 'tex-view)
 
 ;;;###autoload
-(defvar tex-alt-dvi-print-command "lpr -d"
+(defcustom tex-alt-dvi-print-command "lpr -d"
   "*Command used by \\[tex-print] with a prefix arg to print a .dvi file.
-If this string contains an asterisk (*), it will be replaced by the
-filename; if not, the name of the file, preceded by blank, will be added to
-this string.
+If this string contains an asterisk (`*'), that is replaced by the file name;
+otherwise, the file name, preceded by blank, is added at the end.
 
-If two printers are not enough of a choice, you can define the value
-of tex-alt-dvi-print-command to be an expression that asks what you want;
+If two printers are not enough of a choice, you can set the variable
+`tex-alt-dvi-print-command' to an expression that asks what you want;
 for example,
 
     (setq tex-alt-dvi-print-command
          '(format \"lpr -P%s\" (read-string \"Use printer: \")))
 
 would tell \\[tex-print] with a prefix argument to ask you which printer to
-use.")
+use."
+  :type '(choice (string :tag "Command")
+                (sexp :tag "Expression"))
+  :group 'tex-view)
 
 ;;;###autoload
-(defvar tex-dvi-view-command nil
-  "*Command used by \\[tex-view] to display a .dvi file.
-If this string contains an asterisk (*), it will be replaced by the
-filename; if not, the name of the file, preceded by blank, will be added to
-this string.
+(defcustom tex-dvi-view-command nil
+  "*Command used by \\[tex-view] to display a `.dvi' file.
+If this string contains an asterisk (`*'), that is replaced by the file name;
+otherwise, the file name, preceded by blank, is added at the end.
 
 This can be set conditionally so that the previewer used is suitable for the
 window system being used.  For example,
@@ -126,33 +185,43 @@ window system being used.  For example,
     (setq tex-dvi-view-command
           (if (eq window-system 'x) \"xdvi\" \"dvi2tty * | cat -s\"))
 
-would tell \\[tex-view] use xdvi under X windows and to use dvi2tty
-otherwise.")
+would tell \\[tex-view] to use xdvi under X windows and to use dvi2tty
+otherwise."
+  :type '(choice (const nil) string)
+  :group 'tex-view)
 
 ;;;###autoload
-(defvar tex-show-queue-command "lpq"
+(defcustom tex-show-queue-command "lpq"
   "*Command used by \\[tex-show-print-queue] to show the print queue.
-Should show the queue(s) that \\[tex-print] puts jobs on.")
+Should show the queue(s) that \\[tex-print] puts jobs on."
+  :type 'string
+  :group 'tex-view)
 
 ;;;###autoload
-(defvar tex-default-mode 'plain-tex-mode
+(defcustom tex-default-mode 'plain-tex-mode
   "*Mode to enter for a new file that might be either TeX or LaTeX.
 This variable is used when it can't be determined whether the file
 is plain TeX or LaTeX or what because the file contains no commands.
-Normally set to either 'plain-tex-mode or 'latex-mode.")
+Normally set to either `plain-tex-mode' or `latex-mode'."
+  :type 'function
+  :group 'tex)
 
 ;;;###autoload
-(defvar tex-open-quote "``"
-  "*String inserted by typing \\[tex-insert-quote] to open a quotation.")
+(defcustom tex-open-quote "``"
+  "*String inserted by typing \\[tex-insert-quote] to open a quotation."
+  :type 'string
+  :group 'tex)
 
 ;;;###autoload
-(defvar tex-close-quote "''"
-  "*String inserted by typing \\[tex-insert-quote] to close a quotation.")
+(defcustom tex-close-quote "''"
+  "*String inserted by typing \\[tex-insert-quote] to close a quotation."
+  :type 'string
+  :group 'tex)
 
 (defvar tex-last-temp-file nil
   "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
 Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
-tex-shell goes away.")
+tex shell terminates.")
 
 (defvar tex-command nil
   "Command to run TeX.
@@ -162,14 +231,14 @@ The name of the file, preceded by a blank, will be added to this string.")
   "String appended after the end of a region sent to TeX by \\[tex-region].")
 
 (defvar tex-start-of-header nil
-  "String used by \\[tex-region] to delimit the start of the file's header.")
+  "Regular expression used by \\[tex-region] to find start of file's header.")
 
 (defvar tex-end-of-header nil
-  "String used by \\[tex-region] to delimit the end of the file's header.")
+  "Regular expression used by \\[tex-region] to find end of file's header.")
 
 (defvar tex-shell-cd-command "cd"
   "Command to give to shell running TeX to change directory.
-The value of tex-directory will be appended to this, separated by a space.")
+The value of `tex-directory' is appended to this, separated by a space.")
 
 (defvar tex-zap-file nil
   "Temporary file name used for text being sent as input to TeX.
@@ -185,8 +254,87 @@ Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
 (defvar tex-mode-syntax-table nil
   "Syntax table used while in TeX mode.")
 
+(defcustom latex-imenu-indent-string "."
+  "*String to add repeated in front of nested sectional units for Imenu.
+An alternative value is \" . \", if you use a font with a narrow period."
+  :type 'string
+  :group 'tex)
+
+(defun latex-imenu-create-index ()
+  "Generates an alist for imenu from a LaTeX buffer."
+  (let (i0 menu case-fold-search)
+    (save-excursion
+      ;; Find the top-most level in this file but don't allow it to be
+      ;; any deeper than "section" (which is top-level in an article).
+      (goto-char (point-min))
+      (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t)
+         (setq i0 0)
+       (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
+           (setq i0 1)
+         (setq i0 2)))
+
+      ;; Look for chapters and sections.
+      (goto-char (point-min))
+      (while (search-forward-regexp
+             "\\\\\\(part\\|chapter\\|section\\|subsection\\|\
+subsubsection\\|paragraph\\|subparagraph\\)\\*?[ \t]*{" nil t)
+       (let ((start (match-beginning 0))
+             (here (point))
+             (i (cdr (assoc (buffer-substring-no-properties
+                             (match-beginning 1)
+                             (match-end 1))
+                            '(("part" . 0) ("chapter" . 1)
+                              ("section" . 2) ("subsection" . 3)
+                              ("subsubsection" . 4)
+                              ("paragraph" . 5) ("subparagraph" . 6))))))
+         (backward-char 1)
+         (condition-case err
+             (progn
+               ;; Using sexps allows some use of matching {...} inside
+               ;; titles.
+               (forward-sexp 1)
+               (setq menu
+                     (cons (cons (concat (apply 'concat
+                                                (make-list
+                                                 (max 0 (- i i0))
+                                                 latex-imenu-indent-string))
+                                         (buffer-substring-no-properties
+                                          here (1- (point))))
+                                 start)
+                           menu))
+               )
+           (error nil))))
+
+      ;; Look for included material.
+      (goto-char (point-min))
+      (while (search-forward-regexp
+             "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
+[ \t]*{\\([^}\n]+\\)}"
+             nil t)
+       (setq menu
+             (cons (cons (concat "<<" (buffer-substring-no-properties
+                                       (match-beginning 2)
+                                       (match-end 2))
+                                 (if (= (char-after (match-beginning 1)) ?b)
+                                     ".bbl"
+                                   ".tex"))
+                         (match-beginning 0))
+                   menu)))
+
+      ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
+      (goto-char (point-min))
+      (while (search-forward-regexp
+             "\\\\\\(frontmatter\\|mainmatter\\|backmatter\\|appendix\\)\\b"
+             nil t)
+       (setq menu
+             (cons (cons "--" (match-beginning 0))
+                   menu)))
+
+      ;; Sort in increasing buffer position order.
+      (sort menu (function (lambda (a b) (< (cdr a) (cdr b))))))))
+
 (defun tex-define-common-keys (keymap)
-  "Define the keys that we want defined both in TeX mode and in the tex-shell."
+  "Define the keys that we want defined both in TeX mode and in the TeX shell."
   (define-key keymap "\C-c\C-k" 'tex-kill-job)
   (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
   (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
@@ -222,15 +370,18 @@ Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
   (define-key tex-mode-map "\C-c\C-i" 'tex-bibtex-file)
   (define-key tex-mode-map "\C-c\C-o" 'tex-latex-block)
   (define-key tex-mode-map "\C-c\C-e" 'tex-close-latex-block)
+  (define-key tex-mode-map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
+  (define-key tex-mode-map [menu-bar tex tex-bibtex-file]
+    '("BibTeX File" . tex-bibtex-file))
   (define-key tex-mode-map [menu-bar tex tex-validate-region]
     '("Validate Region" . tex-validate-region))
   (define-key tex-mode-map [menu-bar tex validate-tex-buffer]
     '("Validate Buffer" . validate-tex-buffer))
   (define-key tex-mode-map [menu-bar tex tex-region]
-    '("Tex Region" . tex-region))
+    '("TeX Region" . tex-region))
   (define-key tex-mode-map [menu-bar tex tex-buffer]
-    '("Tex Buffer" . tex-buffer))
-  (define-key tex-mode-map [menu-bar tex tex-file] '("Tex File" . tex-file)))
+    '("TeX Buffer" . tex-buffer))
+  (define-key tex-mode-map [menu-bar tex tex-file] '("TeX File" . tex-file)))
 
 (put 'tex-region 'menu-enable 'mark-active)
 (put 'tex-validate-region 'menu-enable 'mark-active)
@@ -242,9 +393,24 @@ Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
 
 
 (defvar tex-shell-map nil
-  "Keymap for the tex-shell.  A comint-mode-map with a few additions.")
+  "Keymap for the TeX shell.
+Inherits `shell-mode-map' with a few additions.")
 
-(defvar compare-windows-whitespace nil)        ; Pacify the byte-compiler
+(defvar tex-face-alist
+  '((bold . "{\\bf ")
+    (italic . "{\\it ")
+    (bold-italic . "{\\bi ")           ; hypothetical
+    (underline . "\\underline{")
+    (default . "{\\rm "))
+  "Alist of face and TeX font name for facemenu.")
+
+(defvar tex-latex-face-alist
+  `((italic . "{\\em ")
+    ,@tex-face-alist)
+  "Alist of face and LaTeX font name for facemenu.")
+
+
+(defvar compare-windows-whitespace)    ; Pacify the byte-compiler
 
 ;;; This would be a lot simpler if we just used a regexp search,
 ;;; but then it would be too slow.
@@ -252,10 +418,10 @@ Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
 (defun tex-mode ()
   "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
 Tries to determine (by looking at the beginning of the file) whether
-this file is for plain TeX, LaTeX, or SliTeX and calls plain-tex-mode,
-latex-mode, or slitex-mode, respectively.  If it cannot be determined,
-such as if there are no commands in the file, the value of tex-default-mode
-is used."
+this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
+`latex-mode', or `slitex-mode', respectively.  If it cannot be determined,
+such as if there are no commands in the file, the value of `tex-default-mode'
+says which mode to use."
   (interactive)
   (let (mode slash comment)
     (save-excursion
@@ -266,8 +432,9 @@ is used."
                                    (beginning-of-line)
                                    (search-forward "%" search-end t))))))
       (if (and slash (not comment))
-         (setq mode (if (looking-at "documentstyle")
-                         (if (looking-at "documentstyle{slides}")
+         (setq mode (if (looking-at "documentstyle\\|documentclass\\|begin\\b\\|NeedsTeXFormat{LaTeX")
+                         (if (looking-at
+                             "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
                              'slitex-mode
                            'latex-mode)
                       'plain-tex-mode))))
@@ -317,17 +484,17 @@ tex-show-queue-command
        Command string used by \\[tex-show-print-queue] to show the print
        queue that \\[tex-print] put your job on.
 
-Entering Plain-tex mode calls the value of `text-mode-hook', then the value
-of `tex-mode-hook', and then the value of `plain-tex-mode-hook'.  When the
-special subshell is initiated, the value of `tex-shell-hook' is called."
+Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
+`tex-mode-hook', and finally the hook `plain-tex-mode-hook'.  When the
+special subshell is initiated, the hook `tex-shell-hook' is run."
 
   (interactive)
   (tex-common-initialization)
   (setq mode-name "TeX")
   (setq major-mode 'plain-tex-mode)
   (setq tex-command tex-run-command)
-  (setq tex-start-of-header "%**start of header")
-  (setq tex-end-of-header "%**end of header")
+  (setq tex-start-of-header "%\\*\\*start of header")
+  (setq tex-end-of-header "%\\*\\*end of header")
   (setq tex-trailer "\\bye\n")
   (run-hooks 'text-mode-hook 'tex-mode-hook 'plain-tex-mode-hook))
 ;;;###autoload
@@ -371,38 +538,44 @@ tex-show-queue-command
        Command string used by \\[tex-show-print-queue] to show the print
        queue that \\[tex-print] put your job on.
 
-Entering Latex mode calls the value of text-mode-hook, then the value of
-tex-mode-hook, and then the value of latex-mode-hook.  When the special
-subshell is initiated, the value of tex-shell-hook is called."
+Entering Latex mode runs the hook `text-mode-hook', then 
+`tex-mode-hook', and finally `latex-mode-hook'.  When the special
+subshell is initiated, `tex-shell-hook' is run."
   (interactive)
   (tex-common-initialization)
   (setq mode-name "LaTeX")
   (setq major-mode 'latex-mode)
   (setq tex-command latex-run-command)
-  (setq tex-start-of-header "\\documentstyle")
-  (setq tex-end-of-header "\\begin{document}")
+  (setq tex-start-of-header "\\\\documentstyle\\|\\\\documentclass")
+  (setq tex-end-of-header "\\\\begin{document}")
   (setq tex-trailer "\\end{document}\n")
   ;; A line containing just $$ is treated as a paragraph separator.
   ;; A line starting with $$ starts a paragraph,
   ;; but does not separate paragraphs if it has more stuff on it.
-  (setq paragraph-start "^[ \t]*$\\|^[\f%]\\|^[ \t]*\\$\\$\\|\
-^\\\\begin\\>\\|^\\\\label\\>\\|^\\\\end\\>\\|^\\\\\\[\\|\
-^\\\\chapter\\>\\|^\\\\section\\>\\|\
-^\\\\subsection\\>\\|^\\\\subsubsection\\>\\|\
-^\\\\paragraph\\>\\|^\\\\subparagraph\\>\\|\
-^\\\\item\\>\\|^\\\\bibitem\\>\\|^\\\\newline\\>\\|^\\\\noindent\\>\\|\
-^\\\\[a-z]*space\\>\\|^\\\\[a-z]*skip\\>\\|\
-^\\\\newpage\\>\\|^\\\\[a-z]*page\\|^\\\\footnote\\>\\|\
-^\\\\marginpar\\>\\|^\\\\parbox\\>\\|^\\\\caption\\>")
-  (setq paragraph-separate "^[ \t]*$\\|^[\f\\\\%]\\|^[ \t]*\\$\\$[ \t]*$\\|\
-^\\\\begin\\>\\|^\\\\label\\>\\|^\\\\end\\>\\|^\\\\\\[\\|\
-^\\\\chapter\\>\\|^\\\\section\\>\\|\
-^\\\\subsection\\>\\|^\\\\subsubsection\\>\\|\
-^\\\\paragraph\\>\\|^\\\\subparagraph\\>\\|\
-^\\\\item[ \t]*$\\|^\\\\bibitem[ \t]*$\\|^\\\\newline[ \t]*$\\|^\\\\noindent[ \t]*$\\|\
-^\\\\[a-z]*space[ \t]*$\\|^\\\\[a-z]*skip[ \t]*$\\|\
-^\\\\newpage[ \t]*$\\|^\\\\[a-z]*page[a-z]*[ \t]*$\\|^\\\\footnote[ \t]*$\\|\
-^\\\\marginpar[ \t]*$\\|^\\\\parbox[ \t]*$\\|^\\\\caption[ \t]*$")
+  (setq paragraph-start "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$\\|\
+\\\\begin\\>\\|\\\\label\\>\\|\\\\end\\>\\|\\\\\\[\\|\\\\\\]\\|\
+\\\\chapter\\>\\|\\\\section\\>\\|\
+\\\\subsection\\>\\|\\\\subsubsection\\>\\|\
+\\\\paragraph\\>\\|\\\\subparagraph\\>\\|\
+\\\\item\\>\\|\\\\bibitem\\>\\|\\\\newline\\>\\|\\\\noindent\\>\\|\
+\\\\[a-z]*space\\>\\|\\\\[a-z]*skip\\>\\|\
+\\\\newpage\\>\\|\\\\[a-z]*page\\|\\\\footnote\\>\\|\
+\\\\marginpar\\>\\|\\\\parbox\\>\\|\\\\caption\\>")
+  (setq paragraph-separate "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$[ \t]*$\\|\
+\\\\begin\\>\\|\\\\label\\>\\|\\\\end\\>\\|\\\\\\[\\|\\\\\\]\\|\
+\\\\chapter\\>\\|\\\\section\\>\\|\
+\\\\subsection\\>\\|\\\\subsubsection\\>\\|\
+\\\\paragraph\\>\\|\\\\subparagraph\\>\\|\
+\\(\\\\item\\|\\\\bibitem\\|\\\\newline\\|\\\\noindent\\|\
+\\\\[a-z]*space\\|\\\\[a-z]*skip\\|\
+\\\\newpage\\|\\\\[a-z]*page[a-z]*\\|\\\\footnote\\|\
+\\\\marginpar\\|\\\\parbox\\|\\\\caption\\)[ \t]*\\($\\|%\\)")
+  (make-local-variable 'imenu-create-index-function)
+  (setq imenu-create-index-function 'latex-imenu-create-index)
+  (make-local-variable 'tex-face-alist)
+  (setq tex-face-alist tex-latex-face-alist)
+  (make-local-variable 'fill-nobreak-predicate)
+  (setq fill-nobreak-predicate 'latex-fill-nobreak-predicate)
   (run-hooks 'text-mode-hook 'tex-mode-hook 'latex-mode-hook))
 
 ;;;###autoload
@@ -443,39 +616,45 @@ tex-show-queue-command
        Command string used by \\[tex-show-print-queue] to show the print
        queue that \\[tex-print] put your job on.
 
-Entering SliTeX mode calls the value of `text-mode-hook', then the value of
-`tex-mode-hook', then the value of `latex-mode-hook', and then the value of
-`slitex-mode-hook'.  When the special subshell is initiated, the value of
-`tex-shell-hook' is called."
+Entering SliTeX mode runs the hook `text-mode-hook', then the hook
+`tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
+`slitex-mode-hook'.  When the special subshell is initiated, the hook
+`tex-shell-hook' is run."
   (interactive)
   (tex-common-initialization)
   (setq mode-name "SliTeX")
   (setq major-mode 'slitex-mode)
   (setq tex-command slitex-run-command)
-  (setq tex-start-of-header "\\documentstyle{slides}")
-  (setq tex-end-of-header "\\begin{document}")
+  (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}")
+  (setq tex-end-of-header "\\\\begin{document}")
   (setq tex-trailer "\\end{document}\n")
   ;; A line containing just $$ is treated as a paragraph separator.
   ;; A line starting with $$ starts a paragraph,
   ;; but does not separate paragraphs if it has more stuff on it.
-  (setq paragraph-start "^[ \t]*$\\|^[\f%]\\|^[ \t]*\\$\\$\\|\
-^\\\\begin\\>\\|^\\\\label\\>\\|^\\\\end\\>\\|^\\\\\\[\\|\
-^\\\\chapter\\>\\|^\\\\section\\>\\|\
-^\\\\subsection\\>\\|^\\\\subsubsection\\>\\|\
-^\\\\paragraph\\>\\|^\\\\subparagraph\\>\\|\
-^\\\\item\\>\\|^\\\\bibitem\\>\\|^\\\\newline\\>\\|^\\\\noindent\\>\\|\
-^\\\\[a-z]*space\\>\\|^\\\\[a-z]*skip\\>\\|\
-^\\\\newpage\\>\\|^\\\\[a-z]*page\\|^\\\\footnote\\>\\|\
-^\\\\marginpar\\>\\|^\\\\parbox\\>\\|^\\\\caption\\>")
-  (setq paragraph-separate "^[ \t]*$\\|^[\f\\\\%]\\|^[ \t]*\\$\\$[ \t]*$\\|\
-^\\\\begin\\>\\|^\\\\label\\>\\|^\\\\end\\>\\|^\\\\\\[\\|\
-^\\\\chapter\\>\\|^\\\\section\\>\\|\
-^\\\\subsection\\>\\|^\\\\subsubsection\\>\\|\
-^\\\\paragraph\\>\\|^\\\\subparagraph\\>\\|\
-^\\\\item[ \t]*$\\|^\\\\bibitem[ \t]*$\\|^\\\\newline[ \t]*$\\|^\\\\noindent[ \t]*$\\|\
-^\\\\[a-z]*space[ \t]*$\\|^\\\\[a-z]*skip[ \t]*$\\|\
-^\\\\newpage[ \t]*$\\|^\\\\[a-z]*page[a-z]*[ \t]*$\\|^\\\\footnote[ \t]*$\\|\
-^\\\\marginpar[ \t]*$\\|^\\\\parbox[ \t]*$\\|^\\\\caption[ \t]*$")
+  (setq paragraph-start "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$\\|\
+\\\\begin\\>\\|\\\\label\\>\\|\\\\end\\>\\|\\\\\\[\\|\\\\\\]\\|\
+\\\\chapter\\>\\|\\\\section\\>\\|\
+\\\\subsection\\>\\|\\\\subsubsection\\>\\|\
+\\\\paragraph\\>\\|\\\\subparagraph\\>\\|\
+\\\\item\\>\\|\\\\bibitem\\>\\|\\\\newline\\>\\|\\\\noindent\\>\\|\
+\\\\[a-z]*space\\>\\|\\\\[a-z]*skip\\>\\|\
+\\\\newpage\\>\\|\\\\[a-z]*page\\|\\\\footnote\\>\\|\
+\\\\marginpar\\>\\|\\\\parbox\\>\\|\\\\caption\\>")
+  (setq paragraph-separate "[ \t]*$\\|[\f%]\\|[ \t]*\\$\\$[ \t]*$\\|\
+\\\\begin\\>\\|\\\\label\\>\\|\\\\end\\>\\|\\\\\\[\\|\\\\\\]\\|\
+\\\\chapter\\>\\|\\\\section\\>\\|\
+\\\\subsection\\>\\|\\\\subsubsection\\>\\|\
+\\\\paragraph\\>\\|\\\\subparagraph\\>\\|\
+\\\\item[ \t]*$\\|\\\\bibitem[ \t]*$\\|\\\\newline[ \t]*$\\|\\\\noindent[ \t]*$\\|\
+\\\\[a-z]*space[ \t]*$\\|\\\\[a-z]*skip[ \t]*$\\|\
+\\\\newpage[ \t]*$\\|\\\\[a-z]*page[a-z]*[ \t]*$\\|\\\\footnote[ \t]*$\\|\
+\\\\marginpar[ \t]*$\\|\\\\parbox[ \t]*$\\|\\\\caption[ \t]*$")
+  (make-local-variable 'imenu-create-index-function)
+  (setq imenu-create-index-function 'latex-imenu-create-index)
+  (make-local-variable 'tex-face-alist)
+  (setq tex-face-alist tex-latex-face-alist)
+  (make-local-variable 'fill-nobreak-predicate)
+  (setq fill-nobreak-predicate 'latex-fill-nobreak-predicate)
   (run-hooks
    'text-mode-hook 'tex-mode-hook 'latex-mode-hook 'slitex-mode-hook))
 
@@ -504,13 +683,16 @@ Entering SliTeX mode calls the value of `text-mode-hook', then the value of
        (modify-syntax-entry ?~ " ")
        (modify-syntax-entry ?' "w"))
     (set-syntax-table tex-mode-syntax-table))
+  ;; Regexp isearch should accept newline and formfeed as whitespace.
+  (make-local-variable 'search-whitespace-regexp)
+  (setq search-whitespace-regexp "[ \t\r\n\f]+")
   (make-local-variable 'paragraph-start)
   ;; A line containing just $$ is treated as a paragraph separator.
-  (setq paragraph-start "^[ \t]*$\\|^[\f\\\\%]\\|^[ \t]*\\$\\$")
+  (setq paragraph-start "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
   (make-local-variable 'paragraph-separate)
   ;; A line starting with $$ starts a paragraph,
   ;; but does not separate paragraphs if it has more stuff on it.
-  (setq paragraph-separate "^[ \t]*$\\|^[\f\\\\%]\\|^[ \t]*\\$\\$[ \t]*$")
+  (setq paragraph-separate "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
   (make-local-variable 'comment-start)
   (setq comment-start "%")
   (make-local-variable 'comment-start-skip)
@@ -521,6 +703,20 @@ Entering SliTeX mode calls the value of `text-mode-hook', then the value of
   (setq parse-sexp-ignore-comments t)
   (make-local-variable 'compare-windows-whitespace)
   (setq compare-windows-whitespace 'tex-categorize-whitespace)
+  (make-local-variable 'skeleton-further-elements)
+  (setq skeleton-further-elements
+         '((indent-line-function 'indent-relative-maybe)))
+  (make-local-variable 'facemenu-add-face-function)
+  (make-local-variable 'facemenu-end-add-face)
+  (make-local-variable 'facemenu-remove-face-function)
+  (setq facemenu-add-face-function
+       (lambda (face end)
+         (let ((face-text (cdr (assq face tex-face-alist))))
+           (if face-text
+               face-text
+             (error "Face %s not configured for %s mode" face mode-name))))
+       facemenu-end-add-face "}"
+       facemenu-remove-face-function t)
   (make-local-variable 'tex-command)
   (make-local-variable 'tex-start-of-header)
   (make-local-variable 'tex-end-of-header)
@@ -544,10 +740,10 @@ Entering SliTeX mode calls the value of `text-mode-hook', then the value of
     (while not-finished
       (cond ((looking-at "[ \t]+")
             (goto-char (match-end 0))
-            (if (eql category 'null)
+            (if (eq category 'null)
                 (setq category 'space)))
            ((looking-at "\n")
-            (cond ((eql category 'newline)
+            (cond ((eq category 'newline)
                    (setq category 'par)
                    (setq not-finished nil))
                   (t
@@ -559,7 +755,7 @@ Entering SliTeX mode calls the value of `text-mode-hook', then the value of
            (t
             (setq not-finished nil))))
     (skip-chars-forward " \t\n\f")
-    (if (eql category 'newline)
+    (if (eq category 'newline)
        'space                          ;TeX doesn't distinguish
       category)))
 
@@ -603,11 +799,17 @@ for the invalidity you want to see."
       (save-excursion
        (goto-char (point-max))
        (while (and (not (input-pending-p)) (not (bobp)))
-         (let ((end (point)))
+         (let ((end (point))
+               prev-end)
            ;; Scan the previous paragraph for invalidities.
-           (search-backward "\n\n" nil 'move)
+           (if (search-backward "\n\n" nil t)
+               (progn
+                 (setq prev-end (point))
+                 (forward-char 2))
+             (goto-char (setq prev-end (point-min))))
            (or (tex-validate-region (point) end)
-               (let* ((end (save-excursion (forward-line 1) (point)))
+               (let* ((oend end)
+                      (end (save-excursion (forward-line 1) (point)))
                       start tem)
                  (beginning-of-line)
                  (setq start (point))
@@ -630,7 +832,8 @@ for the invalidity you want to see."
                    (setq occur-pos-list (cons tem occur-pos-list))
                    (insert-buffer-substring buffer start end)
                    (forward-char (- start end))
-                   (insert (format "%3d: " linenum))))))))
+                   (insert (format "%3d: " linenum)))))
+           (goto-char prev-end))))
       (save-excursion
        (set-buffer standard-output)
        (if (null occur-pos-list)
@@ -648,10 +851,22 @@ area if a mismatch is found."
       (condition-case ()
          (save-restriction
            (narrow-to-region start end)
+           ;; First check that the open and close parens balance in numbers.
            (goto-char start)
            (while (< 0 (setq max-possible-sexps (1- max-possible-sexps)))
-             (forward-sexp 1)))
+             (forward-sexp 1))
+           ;; Now check that like matches like.
+           (goto-char start)
+           (while (progn (skip-syntax-forward "^(")
+                         (not (eobp)))
+             (let ((match (matching-paren (following-char))))
+               (save-excursion
+                 (forward-sexp 1)
+                 (or (= (preceding-char) match)
+                     (error "Mismatched parentheses"))))
+             (forward-char 1)))
        (error
+         (skip-syntax-forward " .>")
          (setq failure-point (point)))))
     (if failure-point
        (progn
@@ -661,7 +876,7 @@ area if a mismatch is found."
 
 (defun tex-terminate-paragraph (inhibit-validation)
   "Insert two newlines, breaking a paragraph for TeX.
-Check for mismatched braces/$'s in paragraph being terminated.
+Check for mismatched braces or $s in paragraph being terminated.
 A prefix arg inhibits the checking."
   (interactive "*P")
   (or inhibit-validation
@@ -681,33 +896,56 @@ A prefix arg inhibits the checking."
   (save-excursion
     (insert ?})))
 
+;; This function is used as the value of fill-nobreak-predicate
+;; in LaTeX mode.  Its job is to prevent line-breaking inside
+;; of a \verb construct.
+(defun latex-fill-nobreak-predicate ()
+  (let ((opoint (point))
+       inside)
+    (save-excursion 
+      (save-restriction
+       (beginning-of-line)
+       (narrow-to-region (point) opoint)
+       (while (re-search-forward "\\\\verb\\(.\\)" nil t)
+         (unless (re-search-forward (regexp-quote (match-string 1)) nil t)
+           (setq inside t)))))
+    inside))
+
 ;;; Like tex-insert-braces, but for LaTeX.
-(defun tex-latex-block (name)
-  "Creates a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
+(define-skeleton tex-latex-block
+  "Create a matching pair of lines \\begin[OPT]{NAME} and \\end{NAME} at point.
 Puts point on a blank line between them."
-  (interactive
-   (prog2
-      (barf-if-buffer-read-only)
-      (list
-       (completing-read "LaTeX block name: "
-                       (mapcar 'list
-                                (append standard-latex-block-names
-                                        latex-block-names))))))
-  (let ((col (current-column)))
-    (insert (format "\\begin{%s}\n" name))
-    (indent-to col)
-    (save-excursion
-      (insert ?\n)
-      (indent-to col)
-      (insert-string (format "\\end{%s}" name))
-      (if (eobp) (insert ?\n)))))
+  (completing-read "LaTeX block name: "
+                  (mapcar 'list
+                          (append standard-latex-block-names
+                                  latex-block-names)))
+  "\\begin["
+  (skeleton-read "[options]: ") & ?\] | -1
+  ?\{
+  str
+  ?\} \n
+  _ \n
+  "\\end{" str ?\})
 
 (defun tex-last-unended-begin ()
-  "Leave point at the beginning of the last \\begin{...} that is unended."
+  "Leave point at the beginning of the last `\\begin{...}' that is unended."
   (while (and (re-search-backward "\\(\\\\begin\\s *{\\)\\|\\(\\\\end\\s *{\\)")
               (looking-at "\\\\end{"))
     (tex-last-unended-begin)))
 
+(defun tex-goto-last-unclosed-latex-block ()
+  "Move point to the last unclosed \\begin{...}.
+Mark is left at original location."
+  (interactive)
+  (let ((spot))
+    (save-excursion
+      (condition-case nil
+          (tex-last-unended-begin)
+        (error (error "Couldn't find unended \\begin")))
+      (setq spot (point)))
+    (push-mark)
+    (goto-char spot)))
+
 (defun tex-close-latex-block ()
   "Creates an \\end{...} to match the last unclosed \\begin{...}."
   (interactive "*")
@@ -724,79 +962,6 @@ Puts point on a blank line between them."
     (insert "\\end" text)
     (if new-line-needed (insert ?\n))))
 \f
-(defun tex-compilation-parse-errors ()
-  "Parse the current buffer as error messages.
-This makes a list of error descriptors, compilation-error-list.
-For each source-file, line-number pair in the buffer,
-the source file is read in, and the text location is saved in
-compilation-error-list.  The function `next-error', assigned to
-\\[next-error], takes the next error off the list and visits its location.
-
-This function works on TeX compilations only.  It is necessary for
-that purpose, since TeX does not put file names on the same line as
-line numbers for the errors."
-  (setq compilation-error-list nil)
-  (message "Parsing error messages...")
-  (modify-syntax-entry ?\{ "_")
-  (modify-syntax-entry ?\} "_")
-  (modify-syntax-entry ?\[ "_")
-  (modify-syntax-entry ?\] "_")
-  (let (text-buffer
-       last-filename last-linenum)
-    ;; Don't reparse messages already seen at last parse.
-    (goto-char compilation-parsing-end)
-    ;; Don't parse the first two lines as error messages.
-    ;; This matters for grep.
-    (if (bobp)
-       (forward-line 2))
-    (while (re-search-forward "^l\.[0-9]+ " nil t)
-      (let (linenum filename
-           error-marker text-marker)
-       ;; Extract file name and line number from error message.
-       ;; Line number is 2 away from beginning of line: "l.23"
-       (beginning-of-line)
-       (goto-char (+ (point) 2))
-       (setq linenum (read (current-buffer)))
-       ;; The file is the one that was opened last and is still open.
-       ;; We need to find the last open parenthesis.
-       (insert ?\))
-       (backward-sexp)
-       (forward-char)
-       (setq filename (current-word))
-       ;; Locate the erring file and line.
-       (if (and (equal filename last-filename)
-                (= linenum last-linenum))
-           nil
-         (skip-chars-backward "^(")
-         (backward-char)
-         (forward-sexp)
-         (backward-delete-char 1)
-         (setq error-marker (point-marker))
-         ;; text-buffer gets the buffer containing this error's file.
-         (if (not (equal filename last-filename))
-             (setq text-buffer
-                   (and (file-exists-p (setq last-filename filename))
-                        (find-file-noselect filename))
-                   last-linenum 0))
-         (if text-buffer
-             ;; Go to that buffer and find the erring line.
-             (save-excursion
-               (set-buffer text-buffer)
-               (if (zerop last-linenum)
-                   (progn
-                     (goto-char 1)
-                     (setq last-linenum 1)))
-               (forward-line (- linenum last-linenum))
-               (setq last-linenum linenum)
-               (setq text-marker (point-marker))
-               (setq compilation-error-list
-                     (cons (list error-marker text-marker)
-                           compilation-error-list)))))
-       (forward-line 1)))
-    (setq compilation-parsing-end (point-max)))
-  (message "Parsing error messages...done")
-  (setq compilation-error-list (nreverse compilation-error-list)))
-\f
 ;;; Invoking TeX in an inferior shell.
 
 ;;; Why use a shell instead of running TeX directly?  Because if TeX
@@ -804,6 +969,7 @@ line numbers for the errors."
 
 ;;; The utility functions:
 
+;;;###autoload
 (defun tex-start-shell ()
   (save-excursion
     (set-buffer
@@ -814,12 +980,20 @@ line numbers for the errors."
     (let ((proc (get-process "tex-shell")))
       (set-process-sentinel proc 'tex-shell-sentinel)
       (process-kill-without-query proc)
-      (setq tex-shell-map (copy-keymap shell-mode-map))
+      (setq comint-prompt-regexp shell-prompt-pattern)
+      (setq tex-shell-map (nconc (make-sparse-keymap) shell-mode-map))
       (tex-define-common-keys tex-shell-map)
       (use-local-map tex-shell-map)
+      (compilation-minor-mode)
       (run-hooks 'tex-shell-hook)
+      (setq comint-input-filter-functions 'shell-directory-tracker)
       (while (zerop (buffer-size))
-          (sleep-for 1)))))
+       (sleep-for 1)))))
+
+(defun tex-display-shell ()
+  "Make the TeX shell buffer visible in a window."
+  (display-buffer (process-buffer (get-process "tex-shell")))
+  (tex-recenter-output-buffer nil))
 
 (defun tex-shell-sentinel (proc msg)
   (cond ((null (buffer-name (process-buffer proc)))
@@ -846,10 +1020,12 @@ line numbers for the errors."
 Do this in background if optional BACKGROUND is t.  If COMMAND has no *,
 FILE will be appended, preceded by a blank, to COMMAND.  If FILE is nil, no
 substitution will be made in COMMAND.  COMMAND can be any expression that
-evaluates to a command string."
+evaluates to a command string.
+
+Return the process in which TeX is running."
   (save-excursion
     (let* ((cmd (eval command))
-          (proc (get-process "tex-shell"))
+          (proc (or (get-process "tex-shell") (error "No TeX subprocess")))
           (buf (process-buffer proc))
            (star (string-match "\\*" cmd))
           (string
@@ -869,16 +1045,20 @@ evaluates to a command string."
       (goto-char (process-mark proc))
       (insert string)
       (comint-send-input)
-      (setq tex-send-command-modified-tick (buffer-modified-tick buf)))))
+      (setq tex-send-command-modified-tick (buffer-modified-tick buf))
+      proc)))
 
 (defun tex-delete-last-temp-files (&optional not-all)
   "Delete any junk files from last temp file.
 If NOT-ALL is non-nil, save the `.dvi' file."
   (if tex-last-temp-file
       (let* ((dir (file-name-directory tex-last-temp-file))
-             (list (file-name-all-completions
-                    (file-name-nondirectory tex-last-temp-file) dir)))
-        (while list
+            (list (and (file-directory-p dir)
+                       (file-name-all-completions
+                        (file-name-sans-extension
+                         (file-name-nondirectory tex-last-temp-file))
+                        dir))))
+       (while list
          (if not-all
              (and
               ;; If arg is non-nil, don't delete the .dvi file.
@@ -889,6 +1069,125 @@ If NOT-ALL is non-nil, save the `.dvi' file."
 
 (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
 
+(defvar tex-start-tex-marker nil
+  "Marker pointing after last TeX-running command in the TeX shell buffer.")
+
+(defun tex-start-tex (command file)
+  "Start a TeX run, using COMMAND on FILE."
+  (let* ((star (string-match "\\*" command))
+         (compile-command
+          (if star
+             (concat (substring command 0 star)
+                     (comint-quote-filename file)
+                     (substring command (1+ star)))
+            (concat command " "
+                   (comint-quote-filename tex-start-options-string) " "
+                   (comint-quote-filename file)))))
+    (with-current-buffer (process-buffer (tex-send-command compile-command))
+      (save-excursion
+       (forward-line -1)
+       (setq tex-start-tex-marker (point-marker)))
+      (make-local-variable 'compilation-parse-errors-function)
+      (setq compilation-parse-errors-function 'tex-compilation-parse-errors))))
+\f
+(defun tex-compilation-parse-errors (limit-search find-at-least)
+  "Parse the current buffer as error messages.
+This makes a list of error descriptors, `compilation-error-list'.
+For each source-file, line-number pair in the buffer,
+the source file is read in, and the text location is saved in
+`compilation-error-list'.  The function `next-error', assigned to
+\\[next-error], takes the next error off the list and visits its location.
+
+If LIMIT-SEARCH is non-nil, don't bother parsing past that location.
+If FIND-AT-LEAST is non-nil, don't bother parsing after finding that
+
+This function works on TeX compilations only.  It is necessary for
+that purpose, since TeX does not put file names on the same line as
+line numbers for the errors."
+  (require 'thingatpt)
+  (setq compilation-error-list nil)
+  (message "Parsing error messages...")
+  (let ((old-lc-syntax (char-syntax ?\{))
+        (old-rc-syntax (char-syntax ?\}))
+        (old-lb-syntax (char-syntax ?\[))
+        (old-rb-syntax (char-syntax ?\]))
+        (num-found 0) last-filename last-linenum last-position)
+    (unwind-protect
+        (progn
+          (modify-syntax-entry ?\{ "_")
+          (modify-syntax-entry ?\} "_")
+          (modify-syntax-entry ?\[ "_")
+          (modify-syntax-entry ?\] "_")
+          ;; Don't reparse messages already seen at last parse.
+          (goto-char (max (or compilation-parsing-end 0)
+                         tex-start-tex-marker))
+          ;; Don't parse the first two lines as error messages.
+          ;; This matters for grep.
+          (if (bobp) (forward-line 2))
+          (while (re-search-forward
+                  "^l\\.\\([0-9]+\\) \\(\\.\\.\\.\\)?\\(.*\\)$"
+                  (and (or (null find-at-least)
+                           (>= num-found find-at-least)) limit-search) t)
+            ;; Extract file name and line number from error message.
+            ;; Line number is 2 away from beginning of line: "l.23"
+            ;; The file is the one that was opened last and is still open.
+            ;; We need to find the last open parenthesis.
+            (let* ((linenum (string-to-int (match-string 1)))
+                   (error-text (regexp-quote (match-string 3)))
+                   (filename
+                    (save-excursion
+                      (backward-up-list 1)
+                      (skip-syntax-forward "(_")
+                      (while (not (file-readable-p
+                                   (thing-at-point 'filename)))
+                        (skip-syntax-backward "(_")
+                        (backward-up-list 1)
+                        (skip-syntax-forward "(_"))
+                      (thing-at-point 'filename)))
+                   (error-marker 
+                    (save-excursion
+                      (re-search-backward "^! " nil t)
+                      (point-marker)))
+                   (new-file (or (null last-filename)
+                                 (not (string-equal last-filename filename))))
+                   (error-location
+                    (save-excursion
+                     (if (equal filename tex-last-temp-file)
+                         (set-buffer tex-last-buffer-texed)
+                       (set-buffer (find-file-noselect filename)))
+                      (if new-file
+                         (goto-line linenum)
+                        (goto-char last-position)
+                        (forward-line (- linenum last-linenum)))
+                                        ;first try a forward search
+                                        ;for the error text, then a
+                                        ;backward search limited by
+                                        ;the last error
+                      (let ((starting-point (point)))
+                        (or (re-search-forward error-text nil t)
+                           (re-search-backward
+                            error-text
+                            (marker-position last-position) t)
+                           (goto-char starting-point)))
+                      (point-marker))))
+              (setq last-filename filename)
+              (if (or new-file
+                      (not (= last-position error-location)))
+                  (progn
+                    (setq num-found (1+ num-found))
+                    (setq last-position error-location)
+                    (setq last-linenum linenum)
+                    (setq compilation-error-list
+                          (nconc compilation-error-list
+                                 (list (cons error-marker
+                                             error-location)))))))))
+      (modify-syntax-entry ?\{ (char-to-string old-lc-syntax))
+      (modify-syntax-entry ?\} (char-to-string old-rc-syntax))
+      (modify-syntax-entry ?\[ (char-to-string old-lb-syntax))
+      (modify-syntax-entry ?\] (char-to-string old-rb-syntax))))
+  (setq compilation-parsing-end (point))
+  (message "Parsing error messages...done"))
+\f
 ;;; The commands:
 
 (defun tex-region (beg end)
@@ -910,16 +1209,17 @@ The value of `tex-command' specifies the command to use to run TeX."
     (tex-start-shell))
   (or tex-zap-file
       (setq tex-zap-file (tex-generate-zap-file-name)))
-  (let* ((temp-buffer (get-buffer-create " TeX-Output-Buffer"))
-         ; Temp file will be written and TeX will be run in zap-directory.
-         ; If the TEXINPUTS file has relative directories or if the region has
-         ; \input of files, this must be the same directory as the file for
-         ; TeX to access the correct inputs.  That's why it's safest if
-         ; tex-directory is ".".
-         (zap-directory
+  ;; Temp file will be written and TeX will be run in zap-directory.
+  ;; If the TEXINPUTS file has relative directories or if the region has
+  ;; \input of files, this must be the same directory as the file for
+  ;; TeX to access the correct inputs.  That's why it's safest if
+  ;; tex-directory is ".".
+  (let* ((zap-directory
           (file-name-as-directory (expand-file-name tex-directory)))
-         (tex-out-file (concat zap-directory tex-zap-file)))
-    (tex-delete-last-temp-files t)
+         (tex-out-file (concat zap-directory tex-zap-file ".tex")))
+    ;; Don't delete temp files if we do the same buffer twice in a row.
+    (or (eq (current-buffer) tex-last-buffer-texed)
+       (tex-delete-last-temp-files t))
     ;; Write the new temp file.
     (save-excursion
       (save-restriction
@@ -927,34 +1227,51 @@ The value of `tex-command' specifies the command to use to run TeX."
        (goto-char (point-min))
        (forward-line 100)
        (let ((search-end (point))
-             (hbeg (point-min)) (hend (point-min))
-             (default-directory zap-directory))
+             (default-directory zap-directory)
+             (already-output 0))
          (goto-char (point-min))
-         ;; Initialize the temp file with either the header or nothing
-         (if (search-forward tex-start-of-header search-end t)
-             (progn
+
+          ;; Maybe copy first line, such as `\input texinfo', to temp file.
+         (and tex-first-line-header-regexp
+              (looking-at tex-first-line-header-regexp)
+              (write-region (point) 
+                            (progn (forward-line 1)
+                                   (setq already-output (point)))
+                            tex-out-file nil nil))
+
+         ;; Write out the header, if there is one,
+         ;; and any of the specified region which extends before it.
+         ;; But don't repeat anything already written.
+         (if (re-search-forward tex-start-of-header search-end t)
+             (let (hbeg)
                (beginning-of-line)
                (setq hbeg (point))     ;mark beginning of header
-               (if (search-forward tex-end-of-header nil t)
-                   (progn (forward-line 1)
-                          (setq hend (point))) ;mark end of header
-                 (setq hbeg (point-min))))) ;no header
-         (write-region (min hbeg beg) hend
-                        (concat tex-out-file ".tex") nil nil)
-         (write-region (max beg hend) end (concat tex-out-file ".tex") t nil))
-       (let ((local-tex-trailer tex-trailer))
-         (set-buffer temp-buffer)
-         (erase-buffer)
-         ;; make sure trailer isn't hidden by a comment
-         (insert-string "\n")
-         (if local-tex-trailer (insert-string local-tex-trailer))
-         (tex-set-buffer-directory temp-buffer zap-directory)
-         (write-region (point-min) (point-max)
-                        (concat tex-out-file ".tex") t nil))))
+               (if (re-search-forward tex-end-of-header nil t)
+                   (let (hend)
+                     (forward-line 1)
+                     (setq hend (point))       ;mark end of header
+                     (write-region (max (min hbeg beg) already-output)
+                                   hend
+                                   tex-out-file
+                                   (not (zerop already-output)) nil)
+                     (setq already-output hend)))))
+
+         ;; Write out the specified region
+         ;; (but don't repeat anything already written).
+         (write-region (max beg already-output) end
+                       tex-out-file
+                       (not (zerop already-output)) nil))
+       ;; Write the trailer, if any.
+       ;; Precede it with a newline to make sure it
+       ;; is not hidden in a comment.
+       (if tex-trailer
+           (write-region (concat "\n" tex-trailer) nil
+                         tex-out-file t nil))))
     ;; Record the file name to be deleted afterward.
     (setq tex-last-temp-file tex-out-file)
     (tex-send-command tex-shell-cd-command zap-directory)
-    (tex-send-command tex-command tex-out-file)
+    (tex-start-tex tex-command tex-out-file)
+    (tex-display-shell)
     (setq tex-print-file tex-out-file)
     (setq tex-last-buffer-texed (current-buffer))))
 
@@ -970,10 +1287,11 @@ See \\[tex-file] for an alternative."
 This function is more useful than \\[tex-buffer] when you need the
 `.aux' file of LaTeX to have the correct name."
   (interactive)
-  (let ((tex-out-file
-         (if (buffer-file-name)
-             (file-name-nondirectory (buffer-file-name))
-           (error "Buffer does not seem to be associated with any file")))
+  (let ((source-file
+        (or tex-main-file 
+            (if (buffer-file-name)
+                (file-name-nondirectory (buffer-file-name))
+              (error "Buffer does not seem to be associated with any file"))))
        (file-dir (file-name-directory (buffer-file-name))))
     (if tex-offer-save
         (save-some-buffers))
@@ -981,9 +1299,10 @@ This function is more useful than \\[tex-buffer] when you need the
         (tex-kill-job)
       (tex-start-shell))
     (tex-send-command tex-shell-cd-command file-dir)
-    (tex-send-command tex-command tex-out-file))
-  (setq tex-last-buffer-texed (current-buffer))
-  (setq tex-print-file (buffer-file-name)))
+    (tex-start-tex tex-command source-file)
+    (tex-display-shell)
+    (setq tex-last-buffer-texed (current-buffer))
+    (setq tex-print-file source-file)))
 
 (defun tex-generate-zap-file-name ()
   "Generate a unique name suitable for use as a file name."
@@ -1025,16 +1344,18 @@ The last line of the buffer is displayed on
 line LINE of the window, or centered if LINE is nil."
   (interactive "P")
   (let ((tex-shell (get-buffer "*tex-shell*"))
-       (old-buffer (current-buffer)))
+       (old-buffer (current-buffer))
+       (window))
     (if (null tex-shell)
        (message "No TeX output buffer")
-      (pop-to-buffer tex-shell)
-      (bury-buffer tex-shell)
-      (goto-char (point-max))
-      (recenter (if linenum
-                   (prefix-numeric-value linenum)
-                 (/ (window-height) 2)))
-      (pop-to-buffer old-buffer))))
+      (setq window (display-buffer tex-shell))
+      (save-selected-window
+       (select-window window)
+       (bury-buffer tex-shell)
+       (goto-char (point-max))
+       (recenter (if linenum
+                     (prefix-numeric-value linenum)
+                   (/ (window-height) 2)))))))
 
 (defun tex-print (&optional alt)
   "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
@@ -1044,27 +1365,36 @@ is provided, use the alternative command, `tex-alt-dvi-print-command'."
   (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
        test-name)
     (if (and (not (equal (current-buffer) tex-last-buffer-texed))
+            (buffer-file-name)
+            ;; Check that this buffer's printed file is up to date.
             (file-newer-than-file-p
              (setq test-name (tex-append (buffer-file-name) ".dvi"))
-             print-file-name-dvi))
+             (buffer-file-name)))
        (setq print-file-name-dvi test-name))
     (if (not (file-exists-p print-file-name-dvi))
         (error "No appropriate `.dvi' file could be found")
+      (if (tex-shell-running)
+          (tex-kill-job)
+        (tex-start-shell))
       (tex-send-command
         (if alt tex-alt-dvi-print-command tex-dvi-print-command)
         print-file-name-dvi t))))
 
 (defun tex-alt-print ()
   "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
-Runs the shell command defined by tex-alt-dvi-print-command."
+Runs the shell command defined by `tex-alt-dvi-print-command'."
   (interactive)
   (tex-print t))
 
 (defun tex-view ()
   "Preview the last `.dvi' file made by running TeX under Emacs.
 This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
-The variable `tex-dvi-view-command' specifies the shell command for preview."
+The variable `tex-dvi-view-command' specifies the shell command for preview.
+You must set that variable yourself before using this command,
+because there is no standard value that would generally work."
   (interactive)
+  (or tex-dvi-view-command
+      (error "You must set `tex-dvi-view-command'"))
   (let ((tex-dvi-print-command tex-dvi-view-command))
     (tex-print)))
 
@@ -1076,19 +1406,22 @@ so normally SUFFIX starts with one."
   (if (stringp file-name)
       (let ((file (file-name-nondirectory file-name))
            trial-name)
-       ;; try spliting on first period
+       ;; Try splitting on last period.
+       ;; The first-period split can get fooled when two files
+       ;; named a.tex and a.b.tex are both tex'd;
+       ;; the last-period split must be right if it matches at all.
        (setq trial-name
              (concat (file-name-directory file-name)
                      (substring file 0
-                                (string-match "\\." file))
+                                (string-match "\\.[^.]*$" file))
                      suffix))
        (if (or (file-exists-p trial-name)
                (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
            trial-name
-         ;; not found, so split on last period
+         ;; Not found, so split on first period.
          (concat (file-name-directory file-name)
                  (substring file 0
-                            (string-match "\\.[^.]*$" file))
+                            (string-match "\\." file))
                  suffix)))
     " "))
 
@@ -1099,7 +1432,8 @@ Runs the shell command defined by `tex-show-queue-command'."
   (if (tex-shell-running)
       (tex-kill-job)
     (tex-start-shell))
-  (tex-send-command tex-show-queue-command))
+  (tex-send-command tex-show-queue-command)
+  (tex-display-shell))
 
 (defun tex-bibtex-file ()
   "Run BibTeX on the current buffer's file."
@@ -1111,11 +1445,11 @@ Runs the shell command defined by `tex-show-queue-command'."
          (tex-append (file-name-nondirectory (buffer-file-name)) ""))
        (file-dir (file-name-directory (buffer-file-name))))
     (tex-send-command tex-shell-cd-command file-dir)
-    (tex-send-command tex-bibtex-command tex-out-file)))
+    (tex-send-command tex-bibtex-command tex-out-file))
+  (tex-display-shell))
 
 (run-hooks 'tex-mode-load-hook)
 
 (provide 'tex-mode)
 
 ;;; tex-mode.el ends here
-