]> code.delx.au - gnu-emacs/blob - lisp/doc-view.el
* doc-view.el (doc-view-mode): Switch off view-mode explicitly,
[gnu-emacs] / lisp / doc-view.el
1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs
2
3 ;; Copyright (C) 2007, 2008, 2009 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Tassilo Horn <tassilo@member.fsf.org>
6 ;; Maintainer: Tassilo Horn <tassilo@member.fsf.org>
7 ;; Keywords: files, pdf, ps, dvi
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; 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/>.
23
24 ;;; Requirements:
25
26 ;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
27 ;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
28 ;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
29 ;; poppler (http://poppler.freedesktop.org/).
30
31 ;;; Commentary:
32
33 ;; DocView is a document viewer for Emacs. It converts PDF, PS and DVI files
34 ;; to a set of PNG files, one PNG for each page, and displays the PNG images
35 ;; inside an Emacs buffer. This buffer uses `doc-view-mode' which provides
36 ;; convenient key bindings for browsing the document.
37 ;;
38 ;; To use it simply open a document file with
39 ;;
40 ;; C-x C-f ~/path/to/document RET
41 ;;
42 ;; and the document will be converted and displayed, if your emacs supports png
43 ;; images. With `C-c C-c' you can toggle between the rendered images
44 ;; representation and the source text representation of the document.
45 ;;
46 ;; Since conversion may take some time all the PNG images are cached in a
47 ;; subdirectory of `doc-view-cache-directory' and reused when you want to view
48 ;; that file again. To reconvert a document hit `g' (`doc-view-reconvert-doc')
49 ;; when displaying the document. To delete all cached files use
50 ;; `doc-view-clear-cache'. To open the cache with dired, so that you can tidy
51 ;; it out use `doc-view-dired-cache'.
52 ;;
53 ;; When conversion in underway the first page will be displayed as soon as it
54 ;; is available and the available pages are refreshed every
55 ;; `doc-view-conversion-refresh-interval' seconds. If that variable is nil the
56 ;; pages won't be displayed before conversion of the document finished
57 ;; completely.
58 ;;
59 ;; DocView lets you select a slice of the displayed pages. This slice will be
60 ;; remembered and applied to all pages of the current document. This enables
61 ;; you to cut away the margins of a document to save some space. To select a
62 ;; slice you can use `doc-view-set-slice' (bound to `s s') which will query you
63 ;; for the coordinates of the slice's top-left corner and its width and height.
64 ;; A much more convenient way to do the same is offered by the command
65 ;; `doc-view-set-slice-using-mouse' (bound to `s m'). After invocation you
66 ;; only have to press mouse-1 at the top-left corner and drag it to the
67 ;; bottom-right corner of the desired slice. To reset the slice use
68 ;; `doc-view-reset-slice' (bound to `s r').
69 ;;
70 ;; You can also search within the document. The command `doc-view-search'
71 ;; (bound to `C-s') queries for a search regexp and initializes a list of all
72 ;; matching pages and messages how many match-pages were found. After that you
73 ;; can jump to the next page containing a match with an additional `C-s'. With
74 ;; `C-r' you can do the same, but backwards. To search for a new regexp give a
75 ;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'. The
76 ;; searching works by using a plain text representation of the document. If
77 ;; that doesn't already exist the first invocation of `doc-view-search' (or
78 ;; `doc-view-search-backward') starts the conversion. When that finishes and
79 ;; you're still viewing the document (i.e. you didn't switch to another buffer)
80 ;; you're queried for the regexp then.
81 ;;
82 ;; Dired users can simply hit `v' on a document file. If it's a PS, PDF or DVI
83 ;; it will be opened using `doc-view-mode'.
84 ;;
85
86 ;;; Configuration:
87
88 ;; If the images are too small or too big you should set the "-rXXX" option in
89 ;; `doc-view-ghostscript-options' to another value. (The bigger your screen,
90 ;; the higher the value.)
91 ;;
92 ;; This and all other options can be set with the customization interface.
93 ;; Simply do
94 ;;
95 ;; M-x customize-group RET doc-view RET
96 ;;
97 ;; and modify them to your needs.
98
99 ;;; Todo:
100
101 ;; - add print command.
102 ;; - share more code with image-mode.
103 ;; - better menu.
104 ;; - 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 ;; - get rid of the silly arrow in the fringe.
108 ;; - improve anti-aliasing (pdf-utils gets it better).
109
110 ;;;; About isearch support
111
112 ;; I tried implementing isearch by setting
113 ;; `isearch-search-fun-function' buffer-locally, but that didn't
114 ;; work too good. The function doing the real search was called
115 ;; endlessly somehow. But even if we'd get that working no real
116 ;; isearch feeling comes up due to the missing match highlighting.
117 ;; Currently I display all lines containing a match in a tooltip and
118 ;; each C-s or C-r jumps directly to the next/previous page with a
119 ;; match. With isearch we could only display the current match. So
120 ;; we had to decide if another C-s jumps to the next page with a
121 ;; match (thus only the first match in a page will be displayed in a
122 ;; tooltip) or to the next match, which would do nothing visible
123 ;; (except the tooltip) if the next match is on the same page.
124
125 ;; And it's much slower than the current search facility, because
126 ;; isearch really searches for each step forward or backward wheras
127 ;; the current approach searches once and then it knows to which
128 ;; pages to jump.
129
130 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
131 ;; feel free to do it. --Tassilo
132
133 ;;; Code:
134
135 (eval-when-compile (require 'cl))
136 (require 'dired)
137 (require 'image-mode)
138 (require 'jka-compr)
139
140 ;;;; Customization Options
141
142 (defgroup doc-view nil
143 "In-buffer viewer for PDF, PostScript and DVI files."
144 :link '(function-link doc-view)
145 :version "22.2"
146 :group 'applications
147 :group 'multimedia
148 :prefix "doc-view-")
149
150 (defcustom doc-view-ghostscript-program (executable-find "gs")
151 "Program to convert PS and PDF files to PNG."
152 :type 'file
153 :group 'doc-view)
154
155 (defcustom doc-view-ghostscript-options
156 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
157 ;; sources.
158 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
159 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
160 "A list of options to give to ghostscript."
161 :type '(repeat string)
162 :group 'doc-view)
163
164 (defcustom doc-view-resolution 100
165 "Dots per inch resolution used to render the documents.
166 Higher values result in larger images."
167 :type 'number
168 :group 'doc-view)
169
170 (defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
171 "Program to convert DVI files to PDF.
172
173 DVI file will be converted to PDF before the resulting PDF is
174 converted to PNG.
175
176 If this and `doc-view-dvipdf-program' are set,
177 `doc-view-dvipdf-program' will be preferred."
178 :type 'file
179 :group 'doc-view)
180
181 (defcustom doc-view-dvipdf-program (executable-find "dvipdf")
182 "Program to convert DVI files to PDF.
183
184 DVI file will be converted to PDF before the resulting PDF is
185 converted to PNG.
186
187 If this and `doc-view-dvipdfm-program' are set,
188 `doc-view-dvipdf-program' will be preferred."
189 :type 'file
190 :group 'doc-view)
191
192 (defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
193 "Program to convert PS files to PDF.
194
195 PS files will be converted to PDF before searching is possible."
196 :type 'file
197 :group 'doc-view)
198
199 (defcustom doc-view-pdftotext-program (executable-find "pdftotext")
200 "Program to convert PDF files to plain text.
201
202 Needed for searching."
203 :type 'file
204 :group 'doc-view)
205
206 (defcustom doc-view-cache-directory
207 (expand-file-name (format "docview%d" (user-uid))
208 temporary-file-directory)
209 "The base directory, where the PNG images will be saved."
210 :type 'directory
211 :group 'doc-view)
212
213 (defvar doc-view-conversion-buffer " *doc-view conversion output*"
214 "The buffer where messages from the converter programs go to.")
215
216 (defcustom doc-view-conversion-refresh-interval 1
217 "Interval in seconds between refreshes of the DocView buffer while converting.
218 After such a refresh newly converted pages will be available for
219 viewing. If set to nil there won't be any refreshes and the
220 pages won't be displayed before conversion of the whole document
221 has finished."
222 :type 'integer
223 :group 'doc-view)
224
225 (defcustom doc-view-continuous-mode nil
226 "In Continuous mode reaching the page edge advances to next/previous page.
227 When non-nil, scrolling a line upward at the bottom edge of the page
228 moves to the next page, and scrolling a line downward at the top edge
229 of the page moves to the previous page."
230 :type 'boolean
231 :group 'doc-view
232 :version "23.2")
233
234 ;;;; Internal Variables
235
236 (defun doc-view-new-window-function (winprops)
237 (let ((ol (image-mode-window-get 'overlay winprops)))
238 (if ol
239 (setq ol (copy-overlay ol))
240 (assert (not (get-char-property (point-min) 'display)))
241 (setq ol (make-overlay (point-min) (point-max) nil t))
242 (overlay-put ol 'doc-view t))
243 (overlay-put ol 'window (car winprops))
244 (image-mode-window-put 'overlay ol winprops)))
245
246 (defvar doc-view-current-files nil
247 "Only used internally.")
248 (make-variable-buffer-local 'doc-view-current-files)
249
250 (defvar doc-view-current-converter-processes nil
251 "Only used internally.")
252 (make-variable-buffer-local 'doc-view-current-converter-processes)
253
254 (defvar doc-view-current-timer nil
255 "Only used internally.")
256 (make-variable-buffer-local 'doc-view-current-timer)
257
258 (defvar doc-view-current-cache-dir nil
259 "Only used internally.")
260 (make-variable-buffer-local 'doc-view-current-cache-dir)
261
262 (defvar doc-view-current-search-matches nil
263 "Only used internally.")
264 (make-variable-buffer-local 'doc-view-current-search-matches)
265
266 (defvar doc-view-pending-cache-flush nil
267 "Only used internally.")
268
269 (defvar doc-view-previous-major-mode nil
270 "Only used internally.")
271
272 (defvar doc-view-buffer-file-name nil
273 "Only used internally.
274 The file name used for conversion. Normally it's the same as
275 `buffer-file-name', but for remote files, compressed files and
276 files inside an archive it is a temporary copy of
277 the (uncompressed, extracted) file residing in
278 `doc-view-cache-directory'.")
279
280 (defvar doc-view-doc-type nil
281 "The type of document in the current buffer.
282 Can be `dvi', `pdf', or `ps'.")
283
284 ;;;; DocView Keymaps
285
286 (defvar doc-view-mode-map
287 (let ((map (make-sparse-keymap)))
288 (set-keymap-parent map image-mode-map)
289 ;; Navigation in the document
290 (define-key map (kbd "n") 'doc-view-next-page)
291 (define-key map (kbd "p") 'doc-view-previous-page)
292 (define-key map (kbd "<next>") 'forward-page)
293 (define-key map (kbd "<prior>") 'backward-page)
294 (define-key map [remap forward-page] 'doc-view-next-page)
295 (define-key map [remap backward-page] 'doc-view-previous-page)
296 (define-key map (kbd "SPC") 'doc-view-scroll-up-or-next-page)
297 (define-key map (kbd "DEL") 'doc-view-scroll-down-or-previous-page)
298 (define-key map (kbd "C-n") 'doc-view-next-line-or-next-page)
299 (define-key map (kbd "<down>") 'doc-view-next-line-or-next-page)
300 (define-key map (kbd "C-p") 'doc-view-previous-line-or-previous-page)
301 (define-key map (kbd "<up>") 'doc-view-previous-line-or-previous-page)
302 (define-key map (kbd "M-<") 'doc-view-first-page)
303 (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 ;; Zoom in/out.
307 (define-key map "+" 'doc-view-enlarge)
308 (define-key map "-" 'doc-view-shrink)
309 ;; Killing the buffer (and the process)
310 (define-key map (kbd "k") 'doc-view-kill-proc-and-buffer)
311 (define-key map (kbd "K") 'doc-view-kill-proc)
312 ;; Slicing the image
313 (define-key map (kbd "s s") 'doc-view-set-slice)
314 (define-key map (kbd "s m") 'doc-view-set-slice-using-mouse)
315 (define-key map (kbd "s r") 'doc-view-reset-slice)
316 ;; Searching
317 (define-key map (kbd "C-s") 'doc-view-search)
318 (define-key map (kbd "<find>") 'doc-view-search)
319 (define-key map (kbd "C-r") 'doc-view-search-backward)
320 ;; Show the tooltip
321 (define-key map (kbd "C-t") 'doc-view-show-tooltip)
322 ;; Toggle between text and image display or editing
323 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
324 ;; Open a new buffer with doc's text contents
325 (define-key map (kbd "C-c C-t") 'doc-view-open-text)
326 ;; Reconvert the current document
327 (define-key map (kbd "g") 'revert-buffer)
328 (define-key map (kbd "r") 'revert-buffer)
329 map)
330 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
331
332 (easy-menu-define doc-view-menu doc-view-mode-map
333 "Menu for Doc View mode."
334 '("DocView"
335 ["Set Slice" doc-view-set-slice-using-mouse]
336 ["Set Slice (manual)" doc-view-set-slice]
337 ["Reset Slice" doc-view-reset-slice]
338 "---"
339 ["Search" doc-view-search]
340 ["Search Backwards" doc-view-search-backward]
341 ["Toggle display" doc-view-toggle-display]
342 ))
343
344 (defvar doc-view-minor-mode-map
345 (let ((map (make-sparse-keymap)))
346 ;; Toggle between text and image display or editing
347 (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
348 map)
349 "Keymap used by `doc-minor-view-mode'.")
350
351 ;;;; Navigation Commands
352
353 (defmacro doc-view-current-page (&optional win)
354 `(image-mode-window-get 'page ,win))
355 (defmacro doc-view-current-info () `(image-mode-window-get 'info))
356 (defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
357 (defmacro doc-view-current-image () `(image-mode-window-get 'image))
358 (defmacro doc-view-current-slice () `(image-mode-window-get 'slice))
359
360 (defun doc-view-goto-page (page)
361 "View the page given by PAGE."
362 (interactive "nPage: ")
363 (let ((len (length doc-view-current-files))
364 (hscroll (window-hscroll)))
365 (if (< page 1)
366 (setq page 1)
367 (when (and (> page len)
368 ;; As long as the converter is running, we don't know
369 ;; how many pages will be available.
370 (null doc-view-current-converter-processes))
371 (setq page len)))
372 (setf (doc-view-current-page) page
373 (doc-view-current-info)
374 (concat
375 (propertize
376 (format "Page %d of %d." page len) 'face 'bold)
377 ;; Tell user if converting isn't finished yet
378 (if doc-view-current-converter-processes
379 " (still converting...)\n"
380 "\n")
381 ;; Display context infos if this page matches the last search
382 (when (and doc-view-current-search-matches
383 (assq page doc-view-current-search-matches))
384 (concat (propertize "Search matches:\n" 'face 'bold)
385 (let ((contexts ""))
386 (dolist (m (cdr (assq page
387 doc-view-current-search-matches)))
388 (setq contexts (concat contexts " - \"" m "\"\n")))
389 contexts)))))
390 ;; Update the buffer
391 ;; We used to find the file name from doc-view-current-files but
392 ;; that's not right if the pages are not generated sequentially
393 ;; or if the page isn't in doc-view-current-files yet.
394 (let ((file (expand-file-name (format "page-%d.png" page)
395 (doc-view-current-cache-dir))))
396 (doc-view-insert-image file :pointer 'arrow)
397 (set-window-hscroll (selected-window) hscroll)
398 (when (and (not (file-exists-p file))
399 doc-view-current-converter-processes)
400 ;; The PNG file hasn't been generated yet.
401 (doc-view-pdf->png-1 doc-view-buffer-file-name file page
402 (lexical-let ((page page)
403 (win (selected-window)))
404 (lambda ()
405 (and (eq (current-buffer) (window-buffer win))
406 ;; If we changed page in the mean
407 ;; time, don't mess things up.
408 (eq (doc-view-current-page win) page)
409 (with-selected-window win
410 (doc-view-goto-page page))))))))
411 (overlay-put (doc-view-current-overlay)
412 'help-echo (doc-view-current-info))))
413
414 (defun doc-view-next-page (&optional arg)
415 "Browse ARG pages forward."
416 (interactive "p")
417 (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))
418
419 (defun doc-view-previous-page (&optional arg)
420 "Browse ARG pages backward."
421 (interactive "p")
422 (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))
423
424 (defun doc-view-first-page ()
425 "View the first page."
426 (interactive)
427 (doc-view-goto-page 1))
428
429 (defun doc-view-last-page ()
430 "View the last page."
431 (interactive)
432 (doc-view-goto-page (length doc-view-current-files)))
433
434 (defun doc-view-scroll-up-or-next-page ()
435 "Scroll page up if possible, else goto next page."
436 (interactive)
437 (let ((hscroll (window-hscroll))
438 (cur-page (doc-view-current-page)))
439 (when (= (window-vscroll) (image-scroll-up nil))
440 (doc-view-next-page)
441 (when (/= cur-page (doc-view-current-page))
442 (image-bob)
443 (image-bol 1))
444 (set-window-hscroll (selected-window) hscroll))))
445
446 (defun doc-view-scroll-down-or-previous-page ()
447 "Scroll page down if possible, else goto previous page."
448 (interactive)
449 (let ((hscroll (window-hscroll))
450 (cur-page (doc-view-current-page)))
451 (when (= (window-vscroll) (image-scroll-down nil))
452 (doc-view-previous-page)
453 (when (/= cur-page (doc-view-current-page))
454 (image-eob)
455 (image-bol 1))
456 (set-window-hscroll (selected-window) hscroll))))
457
458 (defun doc-view-next-line-or-next-page (&optional n)
459 "Scroll upward by N lines if possible, else goto next page.
460 When `doc-view-continuous-mode' is non-nil, scrolling a line upward at
461 the bottom edge of the page moves to the next page."
462 (interactive "p")
463 (if doc-view-continuous-mode
464 (let ((hscroll (window-hscroll))
465 (cur-page (doc-view-current-page)))
466 (when (= (window-vscroll) (image-next-line n))
467 (doc-view-next-page)
468 (when (/= cur-page (doc-view-current-page))
469 (image-bob)
470 (image-bol 1))
471 (set-window-hscroll (selected-window) hscroll)))
472 (image-next-line 1)))
473
474 (defun doc-view-previous-line-or-previous-page (&optional n)
475 "Scroll downward by N lines if possible, else goto previous page.
476 When `doc-view-continuous-mode' is non-nil, scrolling a line downward
477 at the top edge of the page moves to the previous page."
478 (interactive "p")
479 (if doc-view-continuous-mode
480 (let ((hscroll (window-hscroll))
481 (cur-page (doc-view-current-page)))
482 (when (= (window-vscroll) (image-previous-line n))
483 (doc-view-previous-page)
484 (when (/= cur-page (doc-view-current-page))
485 (image-eob)
486 (image-bol 1))
487 (set-window-hscroll (selected-window) hscroll)))
488 (image-previous-line n)))
489
490 ;;;; Utility Functions
491
492 (defun doc-view-kill-proc ()
493 "Kill the current converter process(es)."
494 (interactive)
495 (while doc-view-current-converter-processes
496 (ignore-errors ;; Maybe it's dead already?
497 (kill-process (pop doc-view-current-converter-processes))))
498 (when doc-view-current-timer
499 (cancel-timer doc-view-current-timer)
500 (setq doc-view-current-timer nil))
501 (setq mode-line-process nil))
502
503 (defun doc-view-kill-proc-and-buffer ()
504 "Kill the current converter process and buffer."
505 (interactive)
506 (doc-view-kill-proc)
507 (when (eq major-mode 'doc-view-mode)
508 (kill-buffer (current-buffer))))
509
510 (defun doc-view-make-safe-dir (dir)
511 (condition-case nil
512 (let ((umask (default-file-modes)))
513 (unwind-protect
514 (progn
515 ;; Create temp files with strict access rights. It's easy to
516 ;; loosen them later, whereas it's impossible to close the
517 ;; time-window of loose permissions otherwise.
518 (set-default-file-modes #o0700)
519 (make-directory dir))
520 ;; Reset the umask.
521 (set-default-file-modes umask)))
522 (file-already-exists
523 (if (file-symlink-p dir)
524 (error "Danger: %s points to a symbolic link" dir))
525 ;; In case it was created earlier with looser rights.
526 ;; We could check the mode info returned by file-attributes, but it's
527 ;; a pain to parse and it may not tell you what we want under
528 ;; non-standard file-systems. So let's just say what we want and let
529 ;; the underlying C code and file-system figure it out.
530 ;; This also ends up checking a bunch of useful conditions: it makes
531 ;; sure we have write-access to the directory and that we own it, thus
532 ;; closing a bunch of security holes.
533 (set-file-modes dir #o0700))))
534
535 (defun doc-view-current-cache-dir ()
536 "Return the directory where the png files of the current doc should be saved.
537 It's a subdirectory of `doc-view-cache-directory'."
538 (if doc-view-current-cache-dir
539 doc-view-current-cache-dir
540 ;; Try and make sure doc-view-cache-directory exists and is safe.
541 (doc-view-make-safe-dir doc-view-cache-directory)
542 ;; Now compute the subdirectory to use.
543 (setq doc-view-current-cache-dir
544 (file-name-as-directory
545 (expand-file-name
546 (concat (file-name-nondirectory buffer-file-name)
547 "-"
548 (let ((file doc-view-buffer-file-name))
549 (with-temp-buffer
550 (set-buffer-multibyte nil)
551 (insert-file-contents-literally file)
552 (md5 (current-buffer)))))
553 doc-view-cache-directory)))))
554
555 (defun doc-view-remove-if (predicate list)
556 "Return LIST with all items removed that satisfy PREDICATE."
557 (let (new-list)
558 (dolist (item list (nreverse new-list))
559 (when (not (funcall predicate item))
560 (setq new-list (cons item new-list))))))
561
562 ;;;###autoload
563 (defun doc-view-mode-p (type)
564 "Return non-nil if image type TYPE is available for `doc-view'.
565 Image types are symbols like `dvi', `postscript' or `pdf'."
566 (and (display-graphic-p)
567 (image-type-available-p 'png)
568 (cond
569 ((eq type 'dvi)
570 (and (doc-view-mode-p 'pdf)
571 (or (and doc-view-dvipdf-program
572 (executable-find doc-view-dvipdf-program))
573 (and doc-view-dvipdfm-program
574 (executable-find doc-view-dvipdfm-program)))))
575 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
576 (eq type 'pdf))
577 (and doc-view-ghostscript-program
578 (executable-find doc-view-ghostscript-program)))
579 (t ;; unknown image type
580 nil))))
581
582 ;;;; Conversion Functions
583
584 (defvar doc-view-shrink-factor 1.125)
585
586 (defun doc-view-enlarge (factor)
587 "Enlarge the document."
588 (interactive (list doc-view-shrink-factor))
589 (set (make-local-variable 'doc-view-resolution)
590 (* factor doc-view-resolution))
591 (doc-view-reconvert-doc))
592
593 (defun doc-view-shrink (factor)
594 "Shrink the document."
595 (interactive (list doc-view-shrink-factor))
596 (doc-view-enlarge (/ 1.0 factor)))
597
598 (defun doc-view-reconvert-doc ()
599 "Reconvert the current document.
600 Should be invoked when the cached images aren't up-to-date."
601 (interactive)
602 (doc-view-kill-proc)
603 ;; Clear the old cached files
604 (when (file-exists-p (doc-view-current-cache-dir))
605 (dired-delete-file (doc-view-current-cache-dir) 'always))
606 (doc-view-initiate-display))
607
608 (defun doc-view-sentinel (proc event)
609 "Generic sentinel for doc-view conversion processes."
610 (if (not (string-match "finished" event))
611 (message "DocView: process %s changed status to %s."
612 (process-name proc)
613 (if (string-match "\\(.+\\)\n?\\'" event)
614 (match-string 1 event)
615 event))
616 (when (buffer-live-p (process-get proc 'buffer))
617 (with-current-buffer (process-get proc 'buffer)
618 (setq doc-view-current-converter-processes
619 (delq proc doc-view-current-converter-processes))
620 (setq mode-line-process
621 (if doc-view-current-converter-processes
622 (format ":%s" (car doc-view-current-converter-processes))))
623 (funcall (process-get proc 'callback))))))
624
625 (defun doc-view-start-process (name program args callback)
626 ;; Make sure the process is started in an existing directory, (rather than
627 ;; some file-name-handler-managed dir, for example).
628 (let* ((default-directory (if (file-readable-p default-directory)
629 default-directory
630 (expand-file-name "~/")))
631 (proc (apply 'start-process name doc-view-conversion-buffer
632 program args)))
633 (push proc doc-view-current-converter-processes)
634 (setq mode-line-process (list (format ":%s" proc)))
635 (set-process-sentinel proc 'doc-view-sentinel)
636 (process-put proc 'buffer (current-buffer))
637 (process-put proc 'callback callback)))
638
639 (defun doc-view-dvi->pdf (dvi pdf callback)
640 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
641 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
642 ;; references and includes other PS files.
643 (if (and doc-view-dvipdf-program
644 (executable-find doc-view-dvipdf-program))
645 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
646 (list dvi pdf)
647 callback)
648 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
649 (list "-o" pdf dvi)
650 callback)))
651
652
653 (defun doc-view-pdf/ps->png (pdf-ps png)
654 "Convert PDF-PS to PNG asynchronously."
655 (doc-view-start-process
656 "pdf/ps->png" doc-view-ghostscript-program
657 (append doc-view-ghostscript-options
658 (list (format "-r%d" (round doc-view-resolution))
659 (concat "-sOutputFile=" png)
660 pdf-ps))
661 (lambda ()
662 (when doc-view-current-timer
663 (cancel-timer doc-view-current-timer)
664 (setq doc-view-current-timer nil))
665 (doc-view-display (current-buffer) 'force)))
666 ;; Update the displayed pages as soon as they're done generating.
667 (when doc-view-conversion-refresh-interval
668 (setq doc-view-current-timer
669 (run-at-time "1 secs" doc-view-conversion-refresh-interval
670 'doc-view-display
671 (current-buffer)))))
672
673 (defun doc-view-pdf->png-1 (pdf png page callback)
674 "Convert a PAGE of a PDF file to PNG asynchronously.
675 Call CALLBACK with no arguments when done."
676 (doc-view-start-process
677 "pdf->png-1" doc-view-ghostscript-program
678 (append doc-view-ghostscript-options
679 (list (format "-r%d" (round doc-view-resolution))
680 ;; Sadly, `gs' only supports the page-range
681 ;; for PDF files.
682 (format "-dFirstPage=%d" page)
683 (format "-dLastPage=%d" page)
684 (concat "-sOutputFile=" png)
685 pdf))
686 callback))
687
688 (declare-function clear-image-cache "image.c" (&optional filter))
689
690 (defun doc-view-pdf->png (pdf png pages)
691 "Convert a PDF file to PNG asynchronously.
692 Start by converting PAGES, and then the rest."
693 (if (null pages)
694 (doc-view-pdf/ps->png pdf png)
695 ;; We could render several `pages' with a single process if they're
696 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
697 ;; a single page anyway, and of the remaining 1%, few cases will have
698 ;; consecutive pages, it's not worth the trouble.
699 (lexical-let ((pdf pdf) (png png) (rest (cdr pages)))
700 (doc-view-pdf->png-1
701 pdf (format png (car pages)) (car pages)
702 (lambda ()
703 (if rest
704 (doc-view-pdf->png pdf png rest)
705 ;; Yippie, the important pages are done, update the display.
706 (clear-image-cache)
707 ;; Convert the rest of the pages.
708 (doc-view-pdf/ps->png pdf png)))))))
709
710 (defun doc-view-pdf->txt (pdf txt callback)
711 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
712 (or doc-view-pdftotext-program
713 (error "You need the `pdftotext' program to convert a PDF to text"))
714 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
715 (list "-raw" pdf txt)
716 callback))
717
718 (defun doc-view-doc->txt (txt callback)
719 "Convert the current document to text and call CALLBACK when done."
720 (make-directory (doc-view-current-cache-dir) t)
721 (case doc-view-doc-type
722 (pdf
723 ;; Doc is a PDF, so convert it to TXT
724 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
725 (ps
726 ;; Doc is a PS, so convert it to PDF (which will be converted to
727 ;; TXT thereafter).
728 (lexical-let ((pdf (expand-file-name "doc.pdf"
729 (doc-view-current-cache-dir)))
730 (txt txt)
731 (callback callback))
732 (doc-view-ps->pdf doc-view-buffer-file-name pdf
733 (lambda () (doc-view-pdf->txt pdf txt callback)))))
734 (dvi
735 ;; Doc is a DVI. This means that a doc.pdf already exists in its
736 ;; cache subdirectory.
737 (doc-view-pdf->txt (expand-file-name "doc.pdf"
738 (doc-view-current-cache-dir))
739 txt callback))
740 (t (error "DocView doesn't know what to do"))))
741
742 (defun doc-view-ps->pdf (ps pdf callback)
743 "Convert PS to PDF asynchronously and call CALLBACK when finished."
744 (or doc-view-ps2pdf-program
745 (error "You need the `ps2pdf' program to convert PS to PDF"))
746 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
747 (list
748 ;; Avoid security problems when rendering files from
749 ;; untrusted sources.
750 "-dSAFER"
751 ;; in-file and out-file
752 ps pdf)
753 callback))
754
755 (defun doc-view-active-pages ()
756 (let ((pages ()))
757 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
758 (let ((page (image-mode-window-get 'page win)))
759 (unless (memq page pages) (push page pages))))
760 pages))
761
762 (defun doc-view-convert-current-doc ()
763 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
764 Those files are saved in the directory given by the function
765 `doc-view-current-cache-dir'."
766 ;; Let stale files still display while we recompute the new ones, so only
767 ;; flush the cache when the conversion is over. One of the reasons why it
768 ;; is important to keep displaying the stale page is so that revert-buffer
769 ;; preserves the horizontal/vertical scroll settings (which are otherwise
770 ;; resets during the redisplay).
771 (setq doc-view-pending-cache-flush t)
772 (let ((png-file (expand-file-name "page-%d.png"
773 (doc-view-current-cache-dir)))
774 (res-file (expand-file-name "resolution.el"
775 (doc-view-current-cache-dir))))
776 (make-directory (doc-view-current-cache-dir) t)
777 ;; Save the used resolution so that it can be restored when
778 ;; reading the cached files.
779 (let ((res doc-view-resolution))
780 (with-temp-buffer
781 (princ res (current-buffer))
782 ;; Don't use write-file, so as to avoid prompts for `require-newline',
783 ;; or for pre-existing buffers with the same name, ...
784 (write-region nil nil res-file nil 'silently)))
785 (case doc-view-doc-type
786 (dvi
787 ;; DVI files have to be converted to PDF before Ghostscript can process
788 ;; it.
789 (lexical-let
790 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
791 (png-file png-file))
792 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
793 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
794 (pdf
795 (let ((pages (doc-view-active-pages)))
796 ;; Convert PDF to PNG images starting with the active pages.
797 (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
798 (t
799 ;; Convert to PNG images.
800 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
801
802 ;;;; Slicing
803
804 (declare-function image-size "image.c" (spec &optional pixels frame))
805
806 (defun doc-view-set-slice (x y width height)
807 "Set the slice of the images that should be displayed.
808 You can use this function to tell doc-view not to display the
809 margins of the document. It prompts for the top-left corner (X
810 and Y) of the slice to display and its WIDTH and HEIGHT.
811
812 See `doc-view-set-slice-using-mouse' for a more convenient way to
813 do that. To reset the slice use `doc-view-reset-slice'."
814 (interactive
815 (let* ((size (image-size (doc-view-current-image) t))
816 (a (read-number (format "Top-left X (0..%d): " (car size))))
817 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
818 (c (read-number (format "Width (0..%d): " (- (car size) a))))
819 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
820 (list a b c d)))
821 (setf (doc-view-current-slice) (list x y width height))
822 ;; Redisplay
823 (doc-view-goto-page (doc-view-current-page)))
824
825 (defun doc-view-set-slice-using-mouse ()
826 "Set the slice of the images that should be displayed.
827 You set the slice by pressing mouse-1 at its top-left corner and
828 dragging it to its bottom-right corner. See also
829 `doc-view-set-slice' and `doc-view-reset-slice'."
830 (interactive)
831 (let (x y w h done)
832 (while (not done)
833 (let ((e (read-event
834 (concat "Press mouse-1 at the top-left corner and "
835 "drag it to the bottom-right corner!"))))
836 (when (eq (car e) 'drag-mouse-1)
837 (setq x (car (posn-object-x-y (event-start e))))
838 (setq y (cdr (posn-object-x-y (event-start e))))
839 (setq w (- (car (posn-object-x-y (event-end e))) x))
840 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
841 (setq done t))))
842 (doc-view-set-slice x y w h)))
843
844 (defun doc-view-reset-slice ()
845 "Reset the current slice.
846 After calling this function whole pages will be visible again."
847 (interactive)
848 (setf (doc-view-current-slice) nil)
849 ;; Redisplay
850 (doc-view-goto-page (doc-view-current-page)))
851
852 ;;;; Display
853
854 (defun doc-view-insert-image (file &rest args)
855 "Insert the given png FILE.
856 ARGS is a list of image descriptors."
857 (when doc-view-pending-cache-flush
858 (clear-image-cache)
859 (setq doc-view-pending-cache-flush nil))
860 (let ((ol (doc-view-current-overlay))
861 (image (if (and file (file-readable-p file))
862 (apply 'create-image file 'png nil args)))
863 (slice (doc-view-current-slice)))
864 (setf (doc-view-current-image) image)
865 (move-overlay ol (point-min) (point-max))
866 (overlay-put ol 'display
867 (cond
868 (image
869 (if slice
870 (list (cons 'slice slice) image)
871 image))
872 ;; We're trying to display a page that doesn't exist.
873 (doc-view-current-converter-processes
874 ;; Maybe the page doesn't exist *yet*.
875 "Cannot display this page (yet)!")
876 (t
877 ;; Typically happens if the conversion process somehow
878 ;; failed. Better not signal an error here because it
879 ;; could prevent a subsequent reconversion from fixing
880 ;; the problem.
881 (concat "Cannot display this page!\n"
882 "Maybe because of a conversion failure!"))))
883 (let ((win (overlay-get ol 'window)))
884 (if (stringp (overlay-get ol 'display))
885 (progn ;Make sure the text is not scrolled out of view.
886 (set-window-hscroll win 0)
887 (set-window-vscroll win 0))
888 (let ((hscroll (image-mode-window-get 'hscroll win))
889 (vscroll (image-mode-window-get 'vscroll win)))
890 ;; Reset scroll settings, in case they were changed.
891 (if hscroll (set-window-hscroll win hscroll))
892 (if vscroll (set-window-vscroll win vscroll)))))))
893
894 (defun doc-view-sort (a b)
895 "Return non-nil if A should be sorted before B.
896 Predicate for sorting `doc-view-current-files'."
897 (or (< (length a) (length b))
898 (and (= (length a) (length b))
899 (string< a b))))
900
901 (defun doc-view-display (buffer &optional force)
902 "Start viewing the document in BUFFER.
903 If FORCE is non-nil, start viewing even if the document does not
904 have the page we want to view."
905 (with-current-buffer buffer
906 (let ((prev-pages doc-view-current-files))
907 (setq doc-view-current-files
908 (sort (directory-files (doc-view-current-cache-dir) t
909 "page-[0-9]+\\.png" t)
910 'doc-view-sort))
911 (dolist (win (or (get-buffer-window-list buffer nil t)
912 (list (selected-window))))
913 (let* ((page (doc-view-current-page win))
914 (pagefile (expand-file-name (format "page-%d.png" page)
915 (doc-view-current-cache-dir))))
916 (when (or force
917 (and (not (member pagefile prev-pages))
918 (member pagefile doc-view-current-files)))
919 (with-selected-window win
920 (assert (eq (current-buffer) buffer))
921 (doc-view-goto-page page))))))))
922
923 (defun doc-view-buffer-message ()
924 ;; Only show this message initially, not when refreshing the buffer (in which
925 ;; case it's better to keep displaying the "stale" page while computing
926 ;; the fresh new ones).
927 (unless (overlay-get (doc-view-current-overlay) 'display)
928 (overlay-put (doc-view-current-overlay) 'display
929 (concat (propertize "Welcome to DocView!" 'face 'bold)
930 "\n"
931 "
932 If you see this buffer it means that the document you want to view is being
933 converted to PNG and the conversion of the first page hasn't finished yet or
934 `doc-view-conversion-refresh-interval' is set to nil.
935
936 For now these keys are useful:
937
938 `q' : Bury this buffer. Conversion will go on in background.
939 `k' : Kill the conversion process and this buffer.
940 `K' : Kill the conversion process.\n"))))
941
942 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
943
944 (defun doc-view-show-tooltip ()
945 (interactive)
946 (tooltip-show (doc-view-current-info)))
947
948 (defun doc-view-open-text ()
949 "Open a buffer with the current doc's contents as text."
950 (interactive)
951 (if doc-view-current-converter-processes
952 (message "DocView: please wait till conversion finished.")
953 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
954 (if (file-readable-p txt)
955 (find-file txt)
956 (doc-view-doc->txt txt 'doc-view-open-text)))))
957
958 ;;;;; Toggle between editing and viewing
959
960
961 (defun doc-view-toggle-display ()
962 "Toggle between editing a document as text or viewing it."
963 (interactive)
964 (if (eq major-mode 'doc-view-mode)
965 ;; Switch to editing mode
966 (progn
967 (doc-view-kill-proc)
968 (setq buffer-read-only nil)
969 (remove-overlays (point-min) (point-max) 'doc-view t)
970 (set (make-local-variable 'image-mode-winprops-alist) t)
971 ;; Switch to the previously used major mode or fall back to fundamental
972 ;; mode.
973 (if doc-view-previous-major-mode
974 (funcall doc-view-previous-major-mode)
975 (fundamental-mode))
976 (doc-view-minor-mode 1))
977 ;; Switch to doc-view-mode
978 (when (and (buffer-modified-p)
979 (y-or-n-p "The buffer has been modified. Save the changes? "))
980 (save-buffer))
981 (doc-view-mode)))
982
983 ;;;; Searching
984
985
986 (defun doc-view-search-internal (regexp file)
987 "Return a list of FILE's pages that contain text matching REGEXP.
988 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
989 the pagenumber and CONTEXTS are all lines of text containing a match."
990 (with-temp-buffer
991 (insert-file-contents file)
992 (let ((page 1)
993 (lastpage 1)
994 matches)
995 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
996 regexp "\\)\\)") nil t)
997 (when (match-string 1) (setq page (1+ page)))
998 (when (match-string 2)
999 (if (/= page lastpage)
1000 (push (cons page
1001 (list (buffer-substring
1002 (line-beginning-position)
1003 (line-end-position))))
1004 matches)
1005 (setq matches (cons
1006 (append
1007 (or
1008 ;; This page already is a match.
1009 (car matches)
1010 ;; This is the first match on page.
1011 (list page))
1012 (list (buffer-substring
1013 (line-beginning-position)
1014 (line-end-position))))
1015 (cdr matches))))
1016 (setq lastpage page)))
1017 (nreverse matches))))
1018
1019 (defun doc-view-search-no-of-matches (list)
1020 "Extract the number of matches from the search result LIST."
1021 (let ((no 0))
1022 (dolist (p list)
1023 (setq no (+ no (1- (length p)))))
1024 no))
1025
1026 (defun doc-view-search-backward (new-query)
1027 "Call `doc-view-search' for backward search.
1028 If prefix NEW-QUERY is given, ask for a new regexp."
1029 (interactive "P")
1030 (doc-view-search new-query t))
1031
1032 (defun doc-view-search (new-query &optional backward)
1033 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1034 If the current document hasn't been transformed to plain text
1035 till now do that first.
1036 If BACKWARD is non-nil, jump to the previous match."
1037 (interactive "P")
1038 (if (and (not new-query)
1039 doc-view-current-search-matches)
1040 (if backward
1041 (doc-view-search-previous-match 1)
1042 (doc-view-search-next-match 1))
1043 ;; New search, so forget the old results.
1044 (setq doc-view-current-search-matches nil)
1045 (let ((txt (expand-file-name "doc.txt"
1046 (doc-view-current-cache-dir))))
1047 (if (file-readable-p txt)
1048 (progn
1049 (setq doc-view-current-search-matches
1050 (doc-view-search-internal
1051 (read-from-minibuffer "Regexp: ")
1052 txt))
1053 (message "DocView: search yielded %d matches."
1054 (doc-view-search-no-of-matches
1055 doc-view-current-search-matches)))
1056 ;; We must convert to TXT first!
1057 (if doc-view-current-converter-processes
1058 (message "DocView: please wait till conversion finished.")
1059 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1060
1061 (defun doc-view-search-next-match (arg)
1062 "Go to the ARGth next matching page."
1063 (interactive "p")
1064 (let* ((next-pages (doc-view-remove-if
1065 (lambda (i) (<= (car i) (doc-view-current-page)))
1066 doc-view-current-search-matches))
1067 (page (car (nth (1- arg) next-pages))))
1068 (if page
1069 (doc-view-goto-page page)
1070 (when (and
1071 doc-view-current-search-matches
1072 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1073 (doc-view-goto-page (caar doc-view-current-search-matches))))))
1074
1075 (defun doc-view-search-previous-match (arg)
1076 "Go to the ARGth previous matching page."
1077 (interactive "p")
1078 (let* ((prev-pages (doc-view-remove-if
1079 (lambda (i) (>= (car i) (doc-view-current-page)))
1080 doc-view-current-search-matches))
1081 (page (car (nth (1- arg) (nreverse prev-pages)))))
1082 (if page
1083 (doc-view-goto-page page)
1084 (when (and
1085 doc-view-current-search-matches
1086 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1087 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
1088
1089 ;;;; User interface commands and the mode
1090
1091 ;; (put 'doc-view-mode 'mode-class 'special)
1092
1093 (defun doc-view-already-converted-p ()
1094 "Return non-nil if the current doc was already converted."
1095 (and (file-exists-p (doc-view-current-cache-dir))
1096 (> (length (directory-files (doc-view-current-cache-dir) nil "\\.png$")) 0)))
1097
1098 (defun doc-view-initiate-display ()
1099 ;; Switch to image display if possible
1100 (if (doc-view-mode-p doc-view-doc-type)
1101 (progn
1102 (doc-view-buffer-message)
1103 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1104 (if (doc-view-already-converted-p)
1105 (progn
1106 (message "DocView: using cached files!")
1107 ;; Load the saved resolution
1108 (let ((res-file (expand-file-name "resolution.el"
1109 (doc-view-current-cache-dir)))
1110 (res doc-view-resolution))
1111 (with-temp-buffer
1112 (when (file-exists-p res-file)
1113 (insert-file-contents res-file)
1114 (setq res (read (current-buffer)))))
1115 (when (numberp res)
1116 (set (make-local-variable 'doc-view-resolution) res)))
1117 (doc-view-display (current-buffer) 'force))
1118 (doc-view-convert-current-doc))
1119 (message
1120 "%s"
1121 (substitute-command-keys
1122 (concat "Type \\[doc-view-toggle-display] to toggle between "
1123 "editing or viewing the document."))))
1124 (message
1125 "%s"
1126 (concat "No PNG support is available, or some conversion utility for "
1127 (file-name-extension doc-view-buffer-file-name)
1128 " files is missing."))
1129 (if (and (executable-find doc-view-pdftotext-program)
1130 (y-or-n-p
1131 "Unable to render file. View extracted text instead? "))
1132 (doc-view-open-text)
1133 (doc-view-toggle-display))))
1134
1135 (defvar bookmark-make-record-function)
1136
1137 (defun doc-view-clone-buffer-hook ()
1138 ;; FIXME: There are several potential problems linked with reconversion
1139 ;; and auto-revert when we have indirect buffers because they share their
1140 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1141 ;; for each clone), but that means that clones need to collaborate a bit.
1142 ;; I guess it mostly means: detect when a reconversion process is already
1143 ;; running, and run the sentinel in all clones.
1144 ;;
1145 ;; Maybe the clones should really have a separate /tmp directory
1146 ;; so they could have a different resolution and you could use clones
1147 ;; for zooming.
1148 (remove-overlays (point-min) (point-max) 'doc-view t)
1149 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1150
1151 (defun doc-view-intersection (l1 l2)
1152 (let ((l ()))
1153 (dolist (x l1) (if (memq x l2) (push x l)))
1154 l))
1155
1156 ;;;###autoload
1157 (defun doc-view-mode ()
1158 "Major mode in DocView buffers.
1159
1160 DocView Mode is an Emacs document viewer. It displays PDF, PS
1161 and DVI files (as PNG images) in Emacs buffers.
1162
1163 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1164 toggle between displaying the document or editing it as text.
1165 \\{doc-view-mode-map}"
1166 (interactive)
1167
1168 (if (= (point-min) (point-max))
1169 ;; The doc is empty or doesn't exist at all, so fallback to
1170 ;; another mode. We used to also check file-exists-p, but this
1171 ;; returns nil for tar members.
1172 (let ((auto-mode-alist (remq (rassq 'doc-view-mode auto-mode-alist)
1173 auto-mode-alist)))
1174 (normal-mode))
1175
1176 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
1177 doc-view-previous-major-mode
1178 major-mode)))
1179 (kill-all-local-variables)
1180 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
1181
1182 ;; Figure out the document type.
1183 (let ((name-types
1184 (when buffer-file-name
1185 (cdr (assoc (file-name-extension buffer-file-name)
1186 '(("dvi" dvi)
1187 ("pdf" pdf)
1188 ("epdf" pdf)
1189 ("ps" ps)
1190 ("eps" ps))))))
1191 (content-types
1192 (save-excursion
1193 (goto-char (point-min))
1194 (cond
1195 ((looking-at "%!") '(ps))
1196 ((looking-at "%PDF") '(pdf))
1197 ((looking-at "\367\002") '(dvi))))))
1198 (set (make-local-variable 'doc-view-doc-type)
1199 (car (or (doc-view-intersection name-types content-types)
1200 (when (and name-types content-types)
1201 (error "Conflicting types: name says %s but content says %s"
1202 name-types content-types))
1203 name-types content-types
1204 (error "Cannot determine the document type")))))
1205
1206 (doc-view-make-safe-dir doc-view-cache-directory)
1207 ;; Handle compressed files, remote files, files inside archives
1208 (set (make-local-variable 'doc-view-buffer-file-name)
1209 (cond
1210 (jka-compr-really-do-compress
1211 (expand-file-name
1212 (file-name-nondirectory
1213 (file-name-sans-extension buffer-file-name))
1214 doc-view-cache-directory))
1215 ;; Is the file readable by local processes?
1216 ;; We used to use `file-remote-p' but it's unclear what it's
1217 ;; supposed to return nil for things like local files accessed via
1218 ;; `su' or via file://...
1219 ((let ((file-name-handler-alist nil))
1220 (not (file-readable-p buffer-file-name)))
1221 (expand-file-name
1222 (file-name-nondirectory buffer-file-name)
1223 doc-view-cache-directory))
1224 (t buffer-file-name)))
1225 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1226 (write-region nil nil doc-view-buffer-file-name))
1227
1228 (add-hook 'change-major-mode-hook
1229 (lambda ()
1230 (doc-view-kill-proc)
1231 (remove-overlays (point-min) (point-max) 'doc-view t))
1232 nil t)
1233 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1234 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1235
1236 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1237 ;; Keep track of display info ([vh]scroll, page number, overlay,
1238 ;; ...) for each window in which this document is shown.
1239 (add-hook 'image-mode-new-window-functions
1240 'doc-view-new-window-function nil t)
1241 (image-mode-setup-winprops)
1242
1243 (set (make-local-variable 'mode-line-position)
1244 '(" P" (:eval (number-to-string (doc-view-current-page)))
1245 "/" (:eval (number-to-string (length doc-view-current-files)))))
1246 ;; Don't scroll unless the user specifically asked for it.
1247 (set (make-local-variable 'auto-hscroll-mode) nil)
1248 (set (make-local-variable 'cursor-type) nil)
1249 (use-local-map doc-view-mode-map)
1250 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1251 (set (make-local-variable 'bookmark-make-record-function)
1252 'doc-view-bookmark-make-record)
1253 (setq mode-name "DocView"
1254 buffer-read-only t
1255 major-mode 'doc-view-mode)
1256 (doc-view-initiate-display)
1257 ;; Switch off view-mode explicitly, because doc-view-mode is the
1258 ;; canonical view mode for PDF/PS/DVI files. This could be
1259 ;; switched on automatically depending on the value of
1260 ;; `view-read-only'.
1261 (view-mode -1)
1262 (run-mode-hooks 'doc-view-mode-hook)))
1263
1264 ;;;###autoload
1265 (define-minor-mode doc-view-minor-mode
1266 "Toggle Doc view minor mode.
1267 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1268 See the command `doc-view-mode' for more information on this mode."
1269 nil " DocView" doc-view-minor-mode-map
1270 :group 'doc-view
1271 (when doc-view-minor-mode
1272 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1273 (message
1274 "%s"
1275 (substitute-command-keys
1276 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1277
1278 (defun doc-view-clear-cache ()
1279 "Delete the whole cache (`doc-view-cache-directory')."
1280 (interactive)
1281 (dired-delete-file doc-view-cache-directory 'always))
1282
1283 (defun doc-view-dired-cache ()
1284 "Open `dired' in `doc-view-cache-directory'."
1285 (interactive)
1286 (dired doc-view-cache-directory))
1287
1288
1289 ;;;; Bookmark integration
1290
1291 (declare-function bookmark-make-record-default "bookmark"
1292 (&optional point-only))
1293 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1294 (declare-function bookmark-default-handler "bookmark" (bmk))
1295
1296 (defun doc-view-bookmark-make-record ()
1297 (nconc (bookmark-make-record-default)
1298 `((page . ,(doc-view-current-page))
1299 (handler . doc-view-bookmark-jump))))
1300
1301
1302 ;;;###autoload
1303 (defun doc-view-bookmark-jump (bmk)
1304 ;; This implements the `handler' function interface for record type
1305 ;; returned by `doc-view-bookmark-make-record', which see.
1306 (prog1 (bookmark-default-handler bmk)
1307 (let ((page (bookmark-prop-get bmk 'page)))
1308 (when (not (eq major-mode 'doc-view-mode))
1309 (doc-view-toggle-display))
1310 (with-selected-window
1311 (or (get-buffer-window (current-buffer) 0)
1312 (selected-window))
1313 (doc-view-goto-page page)))))
1314
1315
1316 (provide 'doc-view)
1317
1318 ;; Local Variables:
1319 ;; mode: outline-minor
1320 ;; End:
1321
1322 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1323 ;;; doc-view.el ends here