doc-view.el 51.9 KB
Newer Older
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
1 2
;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs

Glenn Morris's avatar
Glenn Morris committed
3
;; Copyright (C) 2007, 2008, 2009 Free Software Foundation, Inc.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
4 5 6 7 8 9 10
;;
;; Author: Tassilo Horn <tassilo@member.fsf.org>
;; Maintainer: Tassilo Horn <tassilo@member.fsf.org>
;; Keywords: files, pdf, ps, dvi

;; This file is part of GNU Emacs.

11
;; GNU Emacs is free software: you can redistribute it and/or modify
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
15 16 17 18 19 20 21

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
23 24 25

;;; Requirements:

26
;; doc-view.el requires GNU Emacs 22.1 or newer.  You also need Ghostscript,
27 28 29
;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
;; poppler (http://poppler.freedesktop.org/).
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
30 31 32 33 34 35 36 37

;;; Commentary:

;; DocView is a document viewer for Emacs.  It converts PDF, PS and DVI files
;; to a set of PNG files, one PNG for each page, and displays the PNG images
;; inside an Emacs buffer.  This buffer uses `doc-view-mode' which provides
;; convenient key bindings for browsing the document.
;;
38
;; To use it simply open a document file with
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
39
;;
40
;;     C-x C-f ~/path/to/document RET
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
41
;;
42 43
;; and the document will be converted and displayed, if your emacs supports png
;; images.  With `C-c C-c' you can toggle between the rendered images
44
;; representation and the source text representation of the document.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
45 46 47
;;
;; Since conversion may take some time all the PNG images are cached in a
;; subdirectory of `doc-view-cache-directory' and reused when you want to view
48 49
;; that file again.  To reconvert a document hit `g' (`doc-view-reconvert-doc')
;; when displaying the document.  To delete all cached files use
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
;; `doc-view-clear-cache'.  To open the cache with dired, so that you can tidy
;; it out use `doc-view-dired-cache'.
;;
;; When conversion in underway the first page will be displayed as soon as it
;; is available and the available pages are refreshed every
;; `doc-view-conversion-refresh-interval' seconds.  If that variable is nil the
;; pages won't be displayed before conversion of the document finished
;; completely.
;;
;; DocView lets you select a slice of the displayed pages.  This slice will be
;; remembered and applied to all pages of the current document.  This enables
;; you to cut away the margins of a document to save some space.  To select a
;; slice you can use `doc-view-set-slice' (bound to `s s') which will query you
;; for the coordinates of the slice's top-left corner and its width and height.
;; A much more convenient way to do the same is offered by the command
Juanma Barranquero's avatar
Juanma Barranquero committed
65
;; `doc-view-set-slice-using-mouse' (bound to `s m').  After invocation you
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
66 67 68 69 70 71 72
;; only have to press mouse-1 at the top-left corner and drag it to the
;; bottom-right corner of the desired slice.  To reset the slice use
;; `doc-view-reset-slice' (bound to `s r').
;;
;; You can also search within the document.  The command `doc-view-search'
;; (bound to `C-s') queries for a search regexp and initializes a list of all
;; matching pages and messages how many match-pages were found.  After that you
73 74 75 76
;; can jump to the next page containing a match with an additional `C-s'.  With
;; `C-r' you can do the same, but backwards.  To search for a new regexp give a
;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'.  The
;; searching works by using a plain text representation of the document.  If
Juanma Barranquero's avatar
Juanma Barranquero committed
77
;; that doesn't already exist the first invocation of `doc-view-search' (or
78 79 80
;; `doc-view-search-backward') starts the conversion.  When that finishes and
;; you're still viewing the document (i.e. you didn't switch to another buffer)
;; you're queried for the regexp then.
81 82 83 84
;;
;; Dired users can simply hit `v' on a document file.  If it's a PS, PDF or DVI
;; it will be opened using `doc-view-mode'.
;;
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
85 86 87

;;; Configuration:

88 89 90
;; If the images are too small or too big you should set the "-rXXX" option in
;; `doc-view-ghostscript-options' to another value.  (The bigger your screen,
;; the higher the value.)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
91 92 93 94 95 96 97 98
;;
;; This and all other options can be set with the customization interface.
;; Simply do
;;
;;     M-x customize-group RET doc-view RET
;;
;; and modify them to your needs.

99
;;; Todo:
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
100

101 102
;; - add print command.
;; - share more code with image-mode.
103 104
;; - better menu.
;; - Bind slicing to a drag event.
105
;; - doc-view-fit-doc-to-window and doc-view-fit-window-to-doc?
106
;; - zoom the region around the cursor (like xdvi).
107 108
;; - get rid of the silly arrow in the fringe.
;; - improve anti-aliasing (pdf-utils gets it better).
109

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
;;;; About isearch support

;; I tried implementing isearch by setting
;; `isearch-search-fun-function' buffer-locally, but that didn't
;; work too good.  The function doing the real search was called
;; endlessly somehow.  But even if we'd get that working no real
;; isearch feeling comes up due to the missing match highlighting.
;; Currently I display all lines containing a match in a tooltip and
;; each C-s or C-r jumps directly to the next/previous page with a
;; match.  With isearch we could only display the current match.  So
;; we had to decide if another C-s jumps to the next page with a
;; match (thus only the first match in a page will be displayed in a
;; tooltip) or to the next match, which would do nothing visible
;; (except the tooltip) if the next match is on the same page.

;; And it's much slower than the current search facility, because
;; isearch really searches for each step forward or backward wheras
;; the current approach searches once and then it knows to which
;; pages to jump.

;; Anyway, if someone with better isearch knowledge wants to give it a try,
;; feel free to do it.  --Tassilo

;;; Code:

135
(eval-when-compile (require 'cl))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
136
(require 'dired)
137
(require 'image-mode)
138
(require 'jka-compr)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
139 140 141 142 143 144 145 146 147 148 149

;;;; Customization Options

(defgroup doc-view nil
  "In-buffer viewer for PDF, PostScript and DVI files."
  :link '(function-link doc-view)
  :version "22.2"
  :group 'applications
  :group 'multimedia
  :prefix "doc-view-")

Reiner Steib's avatar
Reiner Steib committed
150
(defcustom doc-view-ghostscript-program (executable-find "gs")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
151
  "Program to convert PS and PDF files to PNG."
Reiner Steib's avatar
Reiner Steib committed
152
  :type 'file
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
153 154 155
  :group 'doc-view)

(defcustom doc-view-ghostscript-options
156 157 158
  '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
	      ;; sources.
    "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
159
    "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
160
  "A list of options to give to ghostscript."
Reiner Steib's avatar
Reiner Steib committed
161
  :type '(repeat string)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
162 163
  :group 'doc-view)

164 165 166
(defcustom doc-view-resolution 100
  "Dots per inch resolution used to render the documents.
Higher values result in larger images."
Dan Nicolaescu's avatar
Dan Nicolaescu committed
167 168
  :type 'number
  :group 'doc-view)
169

Reiner Steib's avatar
Reiner Steib committed
170
(defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
171 172 173
  "Program to convert DVI files to PDF.

DVI file will be converted to PDF before the resulting PDF is
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
converted to PNG.

If this and `doc-view-dvipdf-program' are set,
`doc-view-dvipdf-program' will be preferred."
  :type 'file
  :group 'doc-view)

(defcustom doc-view-dvipdf-program (executable-find "dvipdf")
  "Program to convert DVI files to PDF.

DVI file will be converted to PDF before the resulting PDF is
converted to PNG.

If this and `doc-view-dvipdfm-program' are set,
`doc-view-dvipdf-program' will be preferred."
Reiner Steib's avatar
Reiner Steib committed
189
  :type 'file
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
190 191
  :group 'doc-view)

Reiner Steib's avatar
Reiner Steib committed
192
(defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
193 194 195
  "Program to convert PS files to PDF.

PS files will be converted to PDF before searching is possible."
Reiner Steib's avatar
Reiner Steib committed
196
  :type 'file
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
197 198
  :group 'doc-view)

Reiner Steib's avatar
Reiner Steib committed
199
(defcustom doc-view-pdftotext-program (executable-find "pdftotext")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
200 201 202
  "Program to convert PDF files to plain text.

Needed for searching."
Reiner Steib's avatar
Reiner Steib committed
203
  :type 'file
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
204 205
  :group 'doc-view)

206
(defcustom doc-view-cache-directory
207
  (expand-file-name (format "docview%d" (user-uid))
208
		    temporary-file-directory)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
209
  "The base directory, where the PNG images will be saved."
Reiner Steib's avatar
Reiner Steib committed
210
  :type 'directory
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
211 212
  :group 'doc-view)

213 214
(defvar doc-view-conversion-buffer " *doc-view conversion output*"
  "The buffer where messages from the converter programs go to.")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
215

216
(defcustom doc-view-conversion-refresh-interval 1
217 218
  "Interval in seconds between refreshes of the DocView buffer while converting.
After such a refresh newly converted pages will be available for
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
219 220 221
viewing.  If set to nil there won't be any refreshes and the
pages won't be displayed before conversion of the whole document
has finished."
Reiner Steib's avatar
Reiner Steib committed
222
  :type 'integer
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
223 224
  :group 'doc-view)

Juri Linkov's avatar
Juri Linkov committed
225
(defcustom doc-view-continuous nil
226 227 228 229 230 231 232 233
  "In Continuous mode reaching the page edge advances to next/previous page.
When non-nil, scrolling a line upward at the bottom edge of the page
moves to the next page, and scrolling a line downward at the top edge
of the page moves to the previous page."
  :type 'boolean
  :group 'doc-view
  :version "23.2")

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
234 235
;;;; Internal Variables

236 237 238 239
(defun doc-view-new-window-function (winprops)
  (let ((ol (image-mode-window-get 'overlay winprops)))
    (if ol
        (setq ol (copy-overlay ol))
240
      (assert (not (get-char-property (point-min) 'display)))
241 242 243 244
      (setq ol (make-overlay (point-min) (point-max) nil t))
      (overlay-put ol 'doc-view t))
    (overlay-put ol 'window (car winprops))
    (image-mode-window-put 'overlay ol winprops)))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
245

246
(defvar doc-view-current-files nil
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
247
  "Only used internally.")
248
(make-variable-buffer-local 'doc-view-current-files)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
249

250
(defvar doc-view-current-converter-processes nil
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
251
  "Only used internally.")
252
(make-variable-buffer-local 'doc-view-current-converter-processes)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
253 254 255

(defvar doc-view-current-timer nil
  "Only used internally.")
256
(make-variable-buffer-local 'doc-view-current-timer)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
257 258 259

(defvar doc-view-current-cache-dir nil
  "Only used internally.")
260
(make-variable-buffer-local 'doc-view-current-cache-dir)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
261 262 263

(defvar doc-view-current-search-matches nil
  "Only used internally.")
264
(make-variable-buffer-local 'doc-view-current-search-matches)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
265

266 267
(defvar doc-view-pending-cache-flush nil
  "Only used internally.")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
268

269
(defvar doc-view-previous-major-mode nil
270 271
  "Only used internally.")

272 273 274 275 276 277 278 279
(defvar doc-view-buffer-file-name nil
  "Only used internally.
The file name used for conversion.  Normally it's the same as
`buffer-file-name', but for remote files, compressed files and
files inside an archive it is a temporary copy of
the (uncompressed, extracted) file residing in
`doc-view-cache-directory'.")

280 281 282 283
(defvar doc-view-doc-type nil
  "The type of document in the current buffer.
Can be `dvi', `pdf', or `ps'.")

284
;;;; DocView Keymaps
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
285 286 287

(defvar doc-view-mode-map
  (let ((map (make-sparse-keymap)))
288
    (set-keymap-parent map image-mode-map)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
289 290 291
    ;; Navigation in the document
    (define-key map (kbd "n")         'doc-view-next-page)
    (define-key map (kbd "p")         'doc-view-previous-page)
292 293 294 295
    (define-key map (kbd "<next>")    'forward-page)
    (define-key map (kbd "<prior>")   'backward-page)
    (define-key map [remap forward-page]  'doc-view-next-page)
    (define-key map [remap backward-page] 'doc-view-previous-page)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
296 297
    (define-key map (kbd "SPC")       'doc-view-scroll-up-or-next-page)
    (define-key map (kbd "DEL")       'doc-view-scroll-down-or-previous-page)
298 299 300 301
    (define-key map (kbd "C-n")       'doc-view-next-line-or-next-page)
    (define-key map (kbd "<down>")    'doc-view-next-line-or-next-page)
    (define-key map (kbd "C-p")       'doc-view-previous-line-or-previous-page)
    (define-key map (kbd "<up>")      'doc-view-previous-line-or-previous-page)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
302 303
    (define-key map (kbd "M-<")       'doc-view-first-page)
    (define-key map (kbd "M->")       'doc-view-last-page)
304
    (define-key map [remap goto-line] 'doc-view-goto-page)
305
    (define-key map (kbd "RET")       'image-next-line)
306 307 308
    ;; Zoom in/out.
    (define-key map "+"               'doc-view-enlarge)
    (define-key map "-"               'doc-view-shrink)
309
    ;; Killing the buffer (and the process)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
310
    (define-key map (kbd "k")         'doc-view-kill-proc-and-buffer)
311
    (define-key map (kbd "K")         'doc-view-kill-proc)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
312 313 314 315 316 317 318
    ;; Slicing the image
    (define-key map (kbd "s s")       'doc-view-set-slice)
    (define-key map (kbd "s m")       'doc-view-set-slice-using-mouse)
    (define-key map (kbd "s r")       'doc-view-reset-slice)
    ;; Searching
    (define-key map (kbd "C-s")       'doc-view-search)
    (define-key map (kbd "<find>")    'doc-view-search)
319
    (define-key map (kbd "C-r")       'doc-view-search-backward)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
320 321
    ;; Show the tooltip
    (define-key map (kbd "C-t")       'doc-view-show-tooltip)
322 323
    ;; Toggle between text and image display or editing
    (define-key map (kbd "C-c C-c")   'doc-view-toggle-display)
324 325
    ;; Open a new buffer with doc's text contents
    (define-key map (kbd "C-c C-t")   'doc-view-open-text)
326
    ;; Reconvert the current document
327 328
    (define-key map (kbd "g")         'revert-buffer)
    (define-key map (kbd "r")         'revert-buffer)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
329
    map)
330 331
  "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")

332 333 334
(easy-menu-define doc-view-menu doc-view-mode-map
  "Menu for Doc View mode."
  '("DocView"
Juri Linkov's avatar
Juri Linkov committed
335 336 337 338 339 340 341 342 343 344 345
    ["Toggle display"		doc-view-toggle-display]
    ("Continuous"
     ["Off"                     (setq doc-view-continuous nil)
      :style radio :selected    (eq doc-view-continuous nil)]
     ["On"		        (setq doc-view-continuous t)
      :style radio :selected    (eq doc-view-continuous t)]
     "---"
     ["Save as Default"
      (customize-save-variable 'doc-view-continuous doc-view-continuous) t]
     )
    "---"
346 347 348 349 350
    ["Set Slice"		doc-view-set-slice-using-mouse]
    ["Set Slice (manual)"	doc-view-set-slice]
    ["Reset Slice"		doc-view-reset-slice]
    "---"
    ["Search"			doc-view-search]
351
    ["Search Backwards"         doc-view-search-backward]
352 353
    ))

354
(defvar doc-view-minor-mode-map
355 356 357 358
  (let ((map (make-sparse-keymap)))
    ;; Toggle between text and image display or editing
    (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
    map)
359
  "Keymap used by `doc-minor-view-mode'.")
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
360 361 362

;;;; Navigation Commands

363 364
(defmacro doc-view-current-page (&optional win)
  `(image-mode-window-get 'page ,win))
365 366 367 368 369
(defmacro doc-view-current-info () `(image-mode-window-get 'info))
(defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
(defmacro doc-view-current-image () `(image-mode-window-get 'image))
(defmacro doc-view-current-slice () `(image-mode-window-get 'slice))

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
370 371 372
(defun doc-view-goto-page (page)
  "View the page given by PAGE."
  (interactive "nPage: ")
373 374
  (let ((len (length doc-view-current-files))
	(hscroll (window-hscroll)))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
375
    (if (< page 1)
376
	(setq page 1)
377 378 379
      (when (and (> page len)
                 ;; As long as the converter is running, we don't know
                 ;; how many pages will be available.
380
                 (null doc-view-current-converter-processes))
381
	(setq page len)))
382 383
    (setf (doc-view-current-page) page
	  (doc-view-current-info)
384 385
	  (concat
	   (propertize
386
	    (format "Page %d of %d." page len) 'face 'bold)
387
	   ;; Tell user if converting isn't finished yet
388
	   (if doc-view-current-converter-processes
389 390 391 392
	       " (still converting...)\n"
	     "\n")
	   ;; Display context infos if this page matches the last search
	   (when (and doc-view-current-search-matches
393
		      (assq page doc-view-current-search-matches))
394 395
	     (concat (propertize "Search matches:\n" 'face 'bold)
		     (let ((contexts ""))
396
		       (dolist (m (cdr (assq page
397 398 399
					     doc-view-current-search-matches)))
			 (setq contexts (concat contexts "  - \"" m "\"\n")))
		       contexts)))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
400
    ;; Update the buffer
401 402 403
    ;; We used to find the file name from doc-view-current-files but
    ;; that's not right if the pages are not generated sequentially
    ;; or if the page isn't in doc-view-current-files yet.
404 405 406
    (let ((file (expand-file-name (format "page-%d.png" page)
                                  (doc-view-current-cache-dir))))
      (doc-view-insert-image file :pointer 'arrow)
407
      (set-window-hscroll (selected-window) hscroll)
408 409 410 411 412 413 414 415 416 417 418 419 420
      (when (and (not (file-exists-p file))
                 doc-view-current-converter-processes)
        ;; The PNG file hasn't been generated yet.
        (doc-view-pdf->png-1 doc-view-buffer-file-name file page
                             (lexical-let ((page page)
                                           (win (selected-window)))
                               (lambda ()
                                 (and (eq (current-buffer) (window-buffer win))
                                      ;; If we changed page in the mean
                                      ;; time, don't mess things up.
                                      (eq (doc-view-current-page win) page)
                                      (with-selected-window win
                                        (doc-view-goto-page page))))))))
421 422
    (overlay-put (doc-view-current-overlay)
                 'help-echo (doc-view-current-info))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
423 424 425 426

(defun doc-view-next-page (&optional arg)
  "Browse ARG pages forward."
  (interactive "p")
427
  (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
428 429 430 431

(defun doc-view-previous-page (&optional arg)
  "Browse ARG pages backward."
  (interactive "p")
432
  (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
433 434 435 436 437 438 439 440 441 442 443

(defun doc-view-first-page ()
  "View the first page."
  (interactive)
  (doc-view-goto-page 1))

(defun doc-view-last-page ()
  "View the last page."
  (interactive)
  (doc-view-goto-page (length doc-view-current-files)))

444 445
(defun doc-view-scroll-up-or-next-page (&optional arg)
  "Scroll page up ARG lines if possible, else goto next page.
Juri Linkov's avatar
Juri Linkov committed
446
When `doc-view-continuous' is non-nil, scrolling upward
447 448 449
at the bottom edge of the page moves to the next page.
Otherwise, goto next page only on typing SPC (ARG is nil)."
  (interactive "P")
Juri Linkov's avatar
Juri Linkov committed
450
  (if (or doc-view-continuous (null arg))
451 452 453 454 455 456 457 458 459 460 461 462
      (let ((hscroll (window-hscroll))
	    (cur-page (doc-view-current-page)))
	(when (= (window-vscroll) (image-scroll-up arg))
	  (doc-view-next-page)
	  (when (/= cur-page (doc-view-current-page))
	    (image-bob)
	    (image-bol 1))
	  (set-window-hscroll (selected-window) hscroll)))
    (image-scroll-up arg)))

(defun doc-view-scroll-down-or-previous-page (&optional arg)
  "Scroll page down ARG lines if possible, else goto previous page.
Juri Linkov's avatar
Juri Linkov committed
463
When `doc-view-continuous' is non-nil, scrolling downward
464 465 466
at the top edge of the page moves to the previous page.
Otherwise, goto previous page only on typing DEL (ARG is nil)."
  (interactive "P")
Juri Linkov's avatar
Juri Linkov committed
467
  (if (or doc-view-continuous (null arg))
468 469 470 471 472 473 474 475 476 477 478 479
      (let ((hscroll (window-hscroll))
	    (cur-page (doc-view-current-page)))
	(when (= (window-vscroll) (image-scroll-down arg))
	  (doc-view-previous-page)
	  (when (/= cur-page (doc-view-current-page))
	    (image-eob)
	    (image-bol 1))
	  (set-window-hscroll (selected-window) hscroll)))
    (image-scroll-down arg)))

(defun doc-view-next-line-or-next-page (&optional arg)
  "Scroll upward by ARG lines if possible, else goto next page.
Juri Linkov's avatar
Juri Linkov committed
480
When `doc-view-continuous' is non-nil, scrolling a line upward
481
at the bottom edge of the page moves to the next page."
482
  (interactive "p")
Juri Linkov's avatar
Juri Linkov committed
483
  (if doc-view-continuous
484 485
      (let ((hscroll (window-hscroll))
	    (cur-page (doc-view-current-page)))
486
	(when (= (window-vscroll) (image-next-line arg))
487 488 489 490 491 492 493
	  (doc-view-next-page)
	  (when (/= cur-page (doc-view-current-page))
	    (image-bob)
	    (image-bol 1))
	  (set-window-hscroll (selected-window) hscroll)))
    (image-next-line 1)))

494 495
(defun doc-view-previous-line-or-previous-page (&optional arg)
  "Scroll downward by ARG lines if possible, else goto previous page.
Juri Linkov's avatar
Juri Linkov committed
496
When `doc-view-continuous' is non-nil, scrolling a line downward
497 498
at the top edge of the page moves to the previous page."
  (interactive "p")
Juri Linkov's avatar
Juri Linkov committed
499
  (if doc-view-continuous
500 501
      (let ((hscroll (window-hscroll))
	    (cur-page (doc-view-current-page)))
502
	(when (= (window-vscroll) (image-previous-line arg))
503 504 505 506 507
	  (doc-view-previous-page)
	  (when (/= cur-page (doc-view-current-page))
	    (image-eob)
	    (image-bol 1))
	  (set-window-hscroll (selected-window) hscroll)))
508
    (image-previous-line arg)))
509

510 511
;;;; Utility Functions

512
(defun doc-view-kill-proc ()
513
  "Kill the current converter process(es)."
514
  (interactive)
515
  (while doc-view-current-converter-processes
516
    (ignore-errors ;; Maybe it's dead already?
517
      (kill-process (pop doc-view-current-converter-processes))))
518 519 520 521 522
  (when doc-view-current-timer
    (cancel-timer doc-view-current-timer)
    (setq doc-view-current-timer nil))
  (setq mode-line-process nil))

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
523 524 525
(defun doc-view-kill-proc-and-buffer ()
  "Kill the current converter process and buffer."
  (interactive)
526
  (doc-view-kill-proc)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
527 528 529
  (when (eq major-mode 'doc-view-mode)
    (kill-buffer (current-buffer))))

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
(defun doc-view-make-safe-dir (dir)
  (condition-case nil
      (let ((umask (default-file-modes)))
        (unwind-protect
            (progn
              ;; Create temp files with strict access rights.  It's easy to
              ;; loosen them later, whereas it's impossible to close the
              ;; time-window of loose permissions otherwise.
              (set-default-file-modes #o0700)
              (make-directory dir))
          ;; Reset the umask.
          (set-default-file-modes umask)))
    (file-already-exists
     (if (file-symlink-p dir)
         (error "Danger: %s points to a symbolic link" dir))
     ;; In case it was created earlier with looser rights.
     ;; We could check the mode info returned by file-attributes, but it's
     ;; a pain to parse and it may not tell you what we want under
     ;; non-standard file-systems.  So let's just say what we want and let
     ;; the underlying C code and file-system figure it out.
     ;; This also ends up checking a bunch of useful conditions: it makes
     ;; sure we have write-access to the directory and that we own it, thus
     ;; closing a bunch of security holes.
     (set-file-modes dir #o0700))))

555 556 557 558 559
(defun doc-view-current-cache-dir ()
  "Return the directory where the png files of the current doc should be saved.
It's a subdirectory of `doc-view-cache-directory'."
  (if doc-view-current-cache-dir
      doc-view-current-cache-dir
560 561 562
    ;; Try and make sure doc-view-cache-directory exists and is safe.
    (doc-view-make-safe-dir doc-view-cache-directory)
    ;; Now compute the subdirectory to use.
563 564
    (setq doc-view-current-cache-dir
	  (file-name-as-directory
565
	   (expand-file-name
566
	    (concat (file-name-nondirectory doc-view-buffer-file-name)
567 568 569
		    "-"
		    (let ((file doc-view-buffer-file-name))
		      (with-temp-buffer
570
			(set-buffer-multibyte nil)
571 572
			(insert-file-contents-literally file)
			(md5 (current-buffer)))))
573
            doc-view-cache-directory)))))
574 575 576 577 578 579 580 581

(defun doc-view-remove-if (predicate list)
  "Return LIST with all items removed that satisfy PREDICATE."
  (let (new-list)
    (dolist (item list (nreverse new-list))
      (when (not (funcall predicate item))
	(setq new-list (cons item new-list))))))

582 583 584 585 586 587 588 589 590
;;;###autoload
(defun doc-view-mode-p (type)
  "Return non-nil if image type TYPE is available for `doc-view'.
Image types are symbols like `dvi', `postscript' or `pdf'."
  (and (display-graphic-p)
       (image-type-available-p 'png)
       (cond
	((eq type 'dvi)
	 (and (doc-view-mode-p 'pdf)
591 592 593 594
	      (or (and doc-view-dvipdf-program
		       (executable-find doc-view-dvipdf-program))
		  (and doc-view-dvipdfm-program
		       (executable-find doc-view-dvipdfm-program)))))
595
	((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
596 597 598 599 600 601
	     (eq type 'pdf))
	 (and doc-view-ghostscript-program
	      (executable-find doc-view-ghostscript-program)))
	(t ;; unknown image type
	 nil))))

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
602 603
;;;; Conversion Functions

604 605 606 607 608 609 610 611 612 613 614 615 616 617
(defvar doc-view-shrink-factor 1.125)

(defun doc-view-enlarge (factor)
  "Enlarge the document."
  (interactive (list doc-view-shrink-factor))
  (set (make-local-variable 'doc-view-resolution)
       (* factor doc-view-resolution))
  (doc-view-reconvert-doc))

(defun doc-view-shrink (factor)
  "Shrink the document."
  (interactive (list doc-view-shrink-factor))
  (doc-view-enlarge (/ 1.0 factor)))

618
(defun doc-view-reconvert-doc ()
619 620 621
  "Reconvert the current document.
Should be invoked when the cached images aren't up-to-date."
  (interactive)
622 623 624 625
  (doc-view-kill-proc)
  ;; Clear the old cached files
  (when (file-exists-p (doc-view-current-cache-dir))
    (dired-delete-file (doc-view-current-cache-dir) 'always))
626
  (doc-view-initiate-display))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
627

628 629
(defun doc-view-sentinel (proc event)
  "Generic sentinel for doc-view conversion processes."
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
630
  (if (not (string-match "finished" event))
631
      (message "DocView: process %s changed status to %s."
632 633 634 635
               (process-name proc)
	       (if (string-match "\\(.+\\)\n?\\'" event)
		   (match-string 1 event)
		 event))
636 637 638 639 640 641 642 643 644 645
    (when (buffer-live-p (process-get proc 'buffer))
      (with-current-buffer (process-get proc 'buffer)
        (setq doc-view-current-converter-processes
              (delq proc doc-view-current-converter-processes))
        (setq mode-line-process
              (if doc-view-current-converter-processes
                  (format ":%s" (car doc-view-current-converter-processes))))
        (funcall (process-get proc 'callback))))))

(defun doc-view-start-process (name program args callback)
646 647 648 649 650
  ;; Make sure the process is started in an existing directory, (rather than
  ;; some file-name-handler-managed dir, for example).
  (let* ((default-directory (if (file-readable-p default-directory)
				default-directory
			      (expand-file-name "~/")))
651 652 653 654 655 656 657
         (proc (apply 'start-process name doc-view-conversion-buffer
                      program args)))
    (push proc doc-view-current-converter-processes)
    (setq mode-line-process (list (format ":%s" proc)))
    (set-process-sentinel proc 'doc-view-sentinel)
    (process-put proc 'buffer   (current-buffer))
    (process-put proc 'callback callback)))
658 659 660

(defun doc-view-dvi->pdf (dvi pdf callback)
  "Convert DVI to PDF asynchronously and call CALLBACK when finished."
661 662 663 664 665 666 667 668 669 670
  ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
  ;; references and includes other PS files.
  (if (and doc-view-dvipdf-program
	   (executable-find doc-view-dvipdf-program))
      (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
			    (list dvi pdf)
			    callback)
    (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
			    (list "-o" pdf dvi)
			    callback)))
671

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
672 673

(defun doc-view-pdf/ps->png (pdf-ps png)
674
  "Convert PDF-PS to PNG asynchronously."
675 676 677 678 679 680
  (doc-view-start-process
   "pdf/ps->png" doc-view-ghostscript-program
   (append doc-view-ghostscript-options
           (list (format "-r%d" (round doc-view-resolution))
                 (concat "-sOutputFile=" png)
                 pdf-ps))
681
   (lambda ()
682 683 684 685 686
     (when doc-view-current-timer
       (cancel-timer doc-view-current-timer)
       (setq doc-view-current-timer nil))
     (doc-view-display (current-buffer) 'force)))
  ;; Update the displayed pages as soon as they're done generating.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
687 688
  (when doc-view-conversion-refresh-interval
    (setq doc-view-current-timer
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
          (run-at-time "1 secs" doc-view-conversion-refresh-interval
                       'doc-view-display
                       (current-buffer)))))

(defun doc-view-pdf->png-1 (pdf png page callback)
  "Convert a PAGE of a PDF file to PNG asynchronously.
Call CALLBACK with no arguments when done."
  (doc-view-start-process
   "pdf->png-1" doc-view-ghostscript-program
   (append doc-view-ghostscript-options
           (list (format "-r%d" (round doc-view-resolution))
                 ;; Sadly, `gs' only supports the page-range
                 ;; for PDF files.
                 (format "-dFirstPage=%d" page)
                 (format "-dLastPage=%d" page)
                 (concat "-sOutputFile=" png)
                 pdf))
   callback))

708 709
(declare-function clear-image-cache "image.c" (&optional filter))

710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
(defun doc-view-pdf->png (pdf png pages)
  "Convert a PDF file to PNG asynchronously.
Start by converting PAGES, and then the rest."
  (if (null pages)
      (doc-view-pdf/ps->png pdf png)
    ;; We could render several `pages' with a single process if they're
    ;; (almost) consecutive, but since in 99% of the cases, there'll be only
    ;; a single page anyway, and of the remaining 1%, few cases will have
    ;; consecutive pages, it's not worth the trouble.
    (lexical-let ((pdf pdf) (png png) (rest (cdr pages)))
      (doc-view-pdf->png-1
       pdf (format png (car pages)) (car pages)
       (lambda ()
         (if rest
             (doc-view-pdf->png pdf png rest)
           ;; Yippie, the important pages are done, update the display.
           (clear-image-cache)
           ;; Convert the rest of the pages.
           (doc-view-pdf/ps->png pdf png)))))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
729

730 731
(defun doc-view-pdf->txt (pdf txt callback)
  "Convert PDF to TXT asynchronously and call CALLBACK when finished."
732 733
  (or doc-view-pdftotext-program
      (error "You need the `pdftotext' program to convert a PDF to text"))
734 735 736
  (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
                          (list "-raw" pdf txt)
                          callback))
737

738 739
(defun doc-view-doc->txt (txt callback)
  "Convert the current document to text and call CALLBACK when done."
740
  (make-directory (doc-view-current-cache-dir) t)
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
  (case doc-view-doc-type
    (pdf
     ;; Doc is a PDF, so convert it to TXT
     (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
    (ps
     ;; Doc is a PS, so convert it to PDF (which will be converted to
     ;; TXT thereafter).
     (lexical-let ((pdf (expand-file-name "doc.pdf"
                                          (doc-view-current-cache-dir)))
                   (txt txt)
                   (callback callback))
       (doc-view-ps->pdf doc-view-buffer-file-name pdf
                         (lambda () (doc-view-pdf->txt pdf txt callback)))))
    (dvi
     ;; Doc is a DVI.  This means that a doc.pdf already exists in its
     ;; cache subdirectory.
     (doc-view-pdf->txt (expand-file-name "doc.pdf"
                                          (doc-view-current-cache-dir))
                        txt callback))
    (t (error "DocView doesn't know what to do"))))

(defun doc-view-ps->pdf (ps pdf callback)
  "Convert PS to PDF asynchronously and call CALLBACK when finished."
764 765
  (or doc-view-ps2pdf-program
      (error "You need the `ps2pdf' program to convert PS to PDF"))
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
  (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
                          (list
                           ;; Avoid security problems when rendering files from
                           ;; untrusted sources.
                           "-dSAFER"
                           ;; in-file and out-file
                           ps pdf)
                          callback))

(defun doc-view-active-pages ()
  (let ((pages ()))
    (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
      (let ((page (image-mode-window-get 'page win)))
        (unless (memq page pages) (push page pages))))
    pages))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
781

782
(defun doc-view-convert-current-doc ()
783
  "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
784 785
Those files are saved in the directory given by the function
`doc-view-current-cache-dir'."
786 787 788 789 790 791 792
  ;; Let stale files still display while we recompute the new ones, so only
  ;; flush the cache when the conversion is over.  One of the reasons why it
  ;; is important to keep displaying the stale page is so that revert-buffer
  ;; preserves the horizontal/vertical scroll settings (which are otherwise
  ;; resets during the redisplay).
  (setq doc-view-pending-cache-flush t)
  (let ((png-file (expand-file-name "page-%d.png"
793 794
                                    (doc-view-current-cache-dir)))
	(res-file (expand-file-name "resolution.el"
795
                                    (doc-view-current-cache-dir))))
796
    (make-directory (doc-view-current-cache-dir) t)
797 798 799 800 801
    ;; Save the used resolution so that it can be restored when
    ;; reading the cached files.
    (let ((res doc-view-resolution))
      (with-temp-buffer
	(princ res (current-buffer))
802 803 804
        ;; Don't use write-file, so as to avoid prompts for `require-newline',
        ;; or for pre-existing buffers with the same name, ...
	(write-region nil nil res-file nil 'silently)))
805 806 807 808
    (case doc-view-doc-type
      (dvi
       ;; DVI files have to be converted to PDF before Ghostscript can process
       ;; it.
809 810 811 812 813
       (lexical-let
           ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
            (png-file png-file))
         (doc-view-dvi->pdf doc-view-buffer-file-name pdf
                            (lambda () (doc-view-pdf/ps->png pdf png-file)))))
814 815 816 817
     (pdf
      (let ((pages (doc-view-active-pages)))
        ;; Convert PDF to PNG images starting with the active pages.
        (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
818 819 820
      (t
       ;; Convert to PNG images.
       (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
821 822 823

;;;; Slicing

824 825
(declare-function image-size "image.c" (spec &optional pixels frame))

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
826 827 828 829 830 831 832 833 834
(defun doc-view-set-slice (x y width height)
  "Set the slice of the images that should be displayed.
You can use this function to tell doc-view not to display the
margins of the document.  It prompts for the top-left corner (X
and Y) of the slice to display and its WIDTH and HEIGHT.

See `doc-view-set-slice-using-mouse' for a more convenient way to
do that.  To reset the slice use `doc-view-reset-slice'."
  (interactive
835
   (let* ((size (image-size (doc-view-current-image) t))
836 837 838 839
	  (a (read-number (format "Top-left X (0..%d): " (car size))))
	  (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
	  (c (read-number (format "Width (0..%d): " (- (car size) a))))
	  (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
840
     (list a b c d)))
841
  (setf (doc-view-current-slice) (list x y width height))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
842
  ;; Redisplay
843
  (doc-view-goto-page (doc-view-current-page)))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
844 845 846 847 848 849 850 851 852 853

(defun doc-view-set-slice-using-mouse ()
  "Set the slice of the images that should be displayed.
You set the slice by pressing mouse-1 at its top-left corner and
dragging it to its bottom-right corner.  See also
`doc-view-set-slice' and `doc-view-reset-slice'."
  (interactive)
  (let (x y w h done)
    (while (not done)
      (let ((e (read-event
854 855 856 857 858 859 860 861
		(concat "Press mouse-1 at the top-left corner and "
			"drag it to the bottom-right corner!"))))
	(when (eq (car e) 'drag-mouse-1)
	  (setq x (car (posn-object-x-y (event-start e))))
	  (setq y (cdr (posn-object-x-y (event-start e))))
	  (setq w (- (car (posn-object-x-y (event-end e))) x))
	  (setq h (- (cdr (posn-object-x-y (event-end e))) y))
	  (setq done t))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
862 863 864
    (doc-view-set-slice x y w h)))

(defun doc-view-reset-slice ()
865
  "Reset the current slice.
866
After calling this function whole pages will be visible again."
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
867
  (interactive)
868
  (setf (doc-view-current-slice) nil)
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
869
  ;; Redisplay
870
  (doc-view-goto-page (doc-view-current-page)))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
871 872 873 874 875

;;;; Display

(defun doc-view-insert-image (file &rest args)
  "Insert the given png FILE.
876
ARGS is a list of image descriptors."
877 878 879
  (when doc-view-pending-cache-flush
    (clear-image-cache)
    (setq doc-view-pending-cache-flush nil))
880
  (let ((ol (doc-view-current-overlay))
881 882
        (image (if (and file (file-readable-p file))
                   (apply 'create-image file 'png nil args)))
883 884
        (slice (doc-view-current-slice)))
    (setf (doc-view-current-image) image)
885
    (move-overlay ol (point-min) (point-max))
886
    (overlay-put ol 'display
887 888
                 (cond
                  (image
889 890
                   (if slice
                       (list (cons 'slice slice) image)
891 892
                     image))
                  ;; We're trying to display a page that doesn't exist.
893
                  (doc-view-current-converter-processes
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
                   ;; Maybe the page doesn't exist *yet*.
                   "Cannot display this page (yet)!")
                  (t
                   ;; Typically happens if the conversion process somehow
                   ;; failed.  Better not signal an error here because it
                   ;; could prevent a subsequent reconversion from fixing
                   ;; the problem.
                   (concat "Cannot display this page!\n"
                           "Maybe because of a conversion failure!"))))
    (let ((win (overlay-get ol 'window)))
      (if (stringp (overlay-get ol 'display))
          (progn            ;Make sure the text is not scrolled out of view.
            (set-window-hscroll win 0)
            (set-window-vscroll win 0))
        (let ((hscroll (image-mode-window-get 'hscroll win))
              (vscroll (image-mode-window-get 'vscroll win)))
          ;; Reset scroll settings, in case they were changed.
          (if hscroll (set-window-hscroll win hscroll))
          (if vscroll (set-window-vscroll win vscroll)))))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
913 914 915 916

(defun doc-view-sort (a b)
  "Return non-nil if A should be sorted before B.
Predicate for sorting `doc-view-current-files'."
917 918 919
  (or (< (length a) (length b))
      (and (= (length a) (length b))
           (string< a b))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
920

921 922
(defun doc-view-display (buffer &optional force)
  "Start viewing the document in BUFFER.
923 924
If FORCE is non-nil, start viewing even if the document does not
have the page we want to view."
925
  (with-current-buffer buffer
926 927 928 929 930
    (let ((prev-pages doc-view-current-files))
      (setq doc-view-current-files
            (sort (directory-files (doc-view-current-cache-dir) t
                                   "page-[0-9]+\\.png" t)
                  'doc-view-sort))
931 932 933 934 935 936 937 938 939 940 941
      (dolist (win (or (get-buffer-window-list buffer nil t)
		       (list (selected-window))))
	(let* ((page (doc-view-current-page win))
	       (pagefile (expand-file-name (format "page-%d.png" page)
					   (doc-view-current-cache-dir))))
	  (when (or force
		    (and (not (member pagefile prev-pages))
			 (member pagefile doc-view-current-files)))
	    (with-selected-window win
	      (assert (eq (current-buffer) buffer))
	      (doc-view-goto-page page))))))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
942 943

(defun doc-view-buffer-message ()
944 945 946
  ;; Only show this message initially, not when refreshing the buffer (in which
  ;; case it's better to keep displaying the "stale" page while computing
  ;; the fresh new ones).
947 948
  (unless (overlay-get (doc-view-current-overlay) 'display)
    (overlay-put (doc-view-current-overlay) 'display
949 950 951
                 (concat (propertize "Welcome to DocView!" 'face 'bold)
                         "\n"
                         "
952
If you see this buffer it means that the document you want to view is being
953
converted to PNG and the conversion of the first page hasn't finished yet or
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
954 955 956 957
`doc-view-conversion-refresh-interval' is set to nil.

For now these keys are useful:

958
`q' : Bury this buffer.  Conversion will go on in background.
959
`k' : Kill the conversion process and this buffer.
960
`K' : Kill the conversion process.\n"))))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
961

962 963
(declare-function tooltip-show "tooltip" (text &optional use-echo-area))

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
964 965
(defun doc-view-show-tooltip ()
  (interactive)
966
  (tooltip-show (doc-view-current-info)))
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
967

968 969 970
(defun doc-view-open-text ()
  "Open a buffer with the current doc's contents as text."
  (interactive)
971
  (if doc-view-current-converter-processes
972 973 974 975
      (message "DocView: please wait till conversion finished.")
    (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
      (if (file-readable-p txt)
	  (find-file txt)
976
	(doc-view-doc->txt txt 'doc-view-open-text)))))
977

978
;;;;; Toggle between editing and viewing
979

980

981
(defun doc-view-toggle-display ()
982
  "Toggle between editing a document as text or viewing it."
983
  (interactive)
984 985 986 987 988
  (if (eq major-mode 'doc-view-mode)
      ;; Switch to editing mode
      (progn
	(doc-view-kill-proc)
	(setq buffer-read-only nil)
989 990
	(remove-overlays (point-min) (point-max) 'doc-view t)
	(set (make-local-variable 'image-mode-winprops-alist) t)
991 992 993 994 995
	;; Switch to the previously used major mode or fall back to fundamental
	;; mode.
	(if doc-view-previous-major-mode
	    (funcall doc-view-previous-major-mode)
	  (fundamental-mode))
996
	(doc-view-minor-mode 1))
997 998 999 1000 1001
    ;; Switch to doc-view-mode
    (when (and (buffer-modified-p)
	       (y-or-n-p "The buffer has been modified.  Save the changes? "))
      (save-buffer))
    (doc-view-mode)))
1002

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
1003 1004
;;;; Searching

1005

Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
1006 1007
(defun doc-view-search-internal (regexp file)
  "Return a list of FILE's pages that contain text matching REGEXP.
1008 1009
The value is an alist of the form (PAGE CONTEXTS) where PAGE is
the pagenumber and CONTEXTS are all lines of text containing a match."
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
1010 1011 1012
  (with-temp-buffer
    (insert-file-contents file)
    (let ((page 1)
1013 1014
	  (lastpage 1)
	  matches)