]> code.delx.au - gnu-emacs/blob - lisp/doc-view.el
Mouse-wheel scrolling for DocView Continuous mode. (Bug#4896)
[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 (&optional arg)
435 "Scroll page up ARG lines if possible, else goto next page.
436 When `doc-view-continuous-mode' is non-nil, scrolling upward
437 at the bottom edge of the page moves to the next page.
438 Otherwise, goto next page only on typing SPC (ARG is nil)."
439 (interactive "P")
440 (if (or doc-view-continuous-mode (null arg))
441 (let ((hscroll (window-hscroll))
442 (cur-page (doc-view-current-page)))
443 (when (= (window-vscroll) (image-scroll-up arg))
444 (doc-view-next-page)
445 (when (/= cur-page (doc-view-current-page))
446 (image-bob)
447 (image-bol 1))
448 (set-window-hscroll (selected-window) hscroll)))
449 (image-scroll-up arg)))
450
451 (defun doc-view-scroll-down-or-previous-page (&optional arg)
452 "Scroll page down ARG lines if possible, else goto previous page.
453 When `doc-view-continuous-mode' is non-nil, scrolling downward
454 at the top edge of the page moves to the previous page.
455 Otherwise, goto previous page only on typing DEL (ARG is nil)."
456 (interactive "P")
457 (if (or doc-view-continuous-mode (null arg))
458 (let ((hscroll (window-hscroll))
459 (cur-page (doc-view-current-page)))
460 (when (= (window-vscroll) (image-scroll-down arg))
461 (doc-view-previous-page)
462 (when (/= cur-page (doc-view-current-page))
463 (image-eob)
464 (image-bol 1))
465 (set-window-hscroll (selected-window) hscroll)))
466 (image-scroll-down arg)))
467
468 (defun doc-view-next-line-or-next-page (&optional arg)
469 "Scroll upward by ARG lines if possible, else goto next page.
470 When `doc-view-continuous-mode' is non-nil, scrolling a line upward
471 at the bottom edge of the page moves to the next page."
472 (interactive "p")
473 (if doc-view-continuous-mode
474 (let ((hscroll (window-hscroll))
475 (cur-page (doc-view-current-page)))
476 (when (= (window-vscroll) (image-next-line arg))
477 (doc-view-next-page)
478 (when (/= cur-page (doc-view-current-page))
479 (image-bob)
480 (image-bol 1))
481 (set-window-hscroll (selected-window) hscroll)))
482 (image-next-line 1)))
483
484 (defun doc-view-previous-line-or-previous-page (&optional arg)
485 "Scroll downward by ARG lines if possible, else goto previous page.
486 When `doc-view-continuous-mode' is non-nil, scrolling a line downward
487 at the top edge of the page moves to the previous page."
488 (interactive "p")
489 (if doc-view-continuous-mode
490 (let ((hscroll (window-hscroll))
491 (cur-page (doc-view-current-page)))
492 (when (= (window-vscroll) (image-previous-line arg))
493 (doc-view-previous-page)
494 (when (/= cur-page (doc-view-current-page))
495 (image-eob)
496 (image-bol 1))
497 (set-window-hscroll (selected-window) hscroll)))
498 (image-previous-line arg)))
499
500 ;;;; Utility Functions
501
502 (defun doc-view-kill-proc ()
503 "Kill the current converter process(es)."
504 (interactive)
505 (while doc-view-current-converter-processes
506 (ignore-errors ;; Maybe it's dead already?
507 (kill-process (pop doc-view-current-converter-processes))))
508 (when doc-view-current-timer
509 (cancel-timer doc-view-current-timer)
510 (setq doc-view-current-timer nil))
511 (setq mode-line-process nil))
512
513 (defun doc-view-kill-proc-and-buffer ()
514 "Kill the current converter process and buffer."
515 (interactive)
516 (doc-view-kill-proc)
517 (when (eq major-mode 'doc-view-mode)
518 (kill-buffer (current-buffer))))
519
520 (defun doc-view-make-safe-dir (dir)
521 (condition-case nil
522 (let ((umask (default-file-modes)))
523 (unwind-protect
524 (progn
525 ;; Create temp files with strict access rights. It's easy to
526 ;; loosen them later, whereas it's impossible to close the
527 ;; time-window of loose permissions otherwise.
528 (set-default-file-modes #o0700)
529 (make-directory dir))
530 ;; Reset the umask.
531 (set-default-file-modes umask)))
532 (file-already-exists
533 (if (file-symlink-p dir)
534 (error "Danger: %s points to a symbolic link" dir))
535 ;; In case it was created earlier with looser rights.
536 ;; We could check the mode info returned by file-attributes, but it's
537 ;; a pain to parse and it may not tell you what we want under
538 ;; non-standard file-systems. So let's just say what we want and let
539 ;; the underlying C code and file-system figure it out.
540 ;; This also ends up checking a bunch of useful conditions: it makes
541 ;; sure we have write-access to the directory and that we own it, thus
542 ;; closing a bunch of security holes.
543 (set-file-modes dir #o0700))))
544
545 (defun doc-view-current-cache-dir ()
546 "Return the directory where the png files of the current doc should be saved.
547 It's a subdirectory of `doc-view-cache-directory'."
548 (if doc-view-current-cache-dir
549 doc-view-current-cache-dir
550 ;; Try and make sure doc-view-cache-directory exists and is safe.
551 (doc-view-make-safe-dir doc-view-cache-directory)
552 ;; Now compute the subdirectory to use.
553 (setq doc-view-current-cache-dir
554 (file-name-as-directory
555 (expand-file-name
556 (concat (file-name-nondirectory buffer-file-name)
557 "-"
558 (let ((file doc-view-buffer-file-name))
559 (with-temp-buffer
560 (set-buffer-multibyte nil)
561 (insert-file-contents-literally file)
562 (md5 (current-buffer)))))
563 doc-view-cache-directory)))))
564
565 (defun doc-view-remove-if (predicate list)
566 "Return LIST with all items removed that satisfy PREDICATE."
567 (let (new-list)
568 (dolist (item list (nreverse new-list))
569 (when (not (funcall predicate item))
570 (setq new-list (cons item new-list))))))
571
572 ;;;###autoload
573 (defun doc-view-mode-p (type)
574 "Return non-nil if image type TYPE is available for `doc-view'.
575 Image types are symbols like `dvi', `postscript' or `pdf'."
576 (and (display-graphic-p)
577 (image-type-available-p 'png)
578 (cond
579 ((eq type 'dvi)
580 (and (doc-view-mode-p 'pdf)
581 (or (and doc-view-dvipdf-program
582 (executable-find doc-view-dvipdf-program))
583 (and doc-view-dvipdfm-program
584 (executable-find doc-view-dvipdfm-program)))))
585 ((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
586 (eq type 'pdf))
587 (and doc-view-ghostscript-program
588 (executable-find doc-view-ghostscript-program)))
589 (t ;; unknown image type
590 nil))))
591
592 ;;;; Conversion Functions
593
594 (defvar doc-view-shrink-factor 1.125)
595
596 (defun doc-view-enlarge (factor)
597 "Enlarge the document."
598 (interactive (list doc-view-shrink-factor))
599 (set (make-local-variable 'doc-view-resolution)
600 (* factor doc-view-resolution))
601 (doc-view-reconvert-doc))
602
603 (defun doc-view-shrink (factor)
604 "Shrink the document."
605 (interactive (list doc-view-shrink-factor))
606 (doc-view-enlarge (/ 1.0 factor)))
607
608 (defun doc-view-reconvert-doc ()
609 "Reconvert the current document.
610 Should be invoked when the cached images aren't up-to-date."
611 (interactive)
612 (doc-view-kill-proc)
613 ;; Clear the old cached files
614 (when (file-exists-p (doc-view-current-cache-dir))
615 (dired-delete-file (doc-view-current-cache-dir) 'always))
616 (doc-view-initiate-display))
617
618 (defun doc-view-sentinel (proc event)
619 "Generic sentinel for doc-view conversion processes."
620 (if (not (string-match "finished" event))
621 (message "DocView: process %s changed status to %s."
622 (process-name proc)
623 (if (string-match "\\(.+\\)\n?\\'" event)
624 (match-string 1 event)
625 event))
626 (when (buffer-live-p (process-get proc 'buffer))
627 (with-current-buffer (process-get proc 'buffer)
628 (setq doc-view-current-converter-processes
629 (delq proc doc-view-current-converter-processes))
630 (setq mode-line-process
631 (if doc-view-current-converter-processes
632 (format ":%s" (car doc-view-current-converter-processes))))
633 (funcall (process-get proc 'callback))))))
634
635 (defun doc-view-start-process (name program args callback)
636 ;; Make sure the process is started in an existing directory, (rather than
637 ;; some file-name-handler-managed dir, for example).
638 (let* ((default-directory (if (file-readable-p default-directory)
639 default-directory
640 (expand-file-name "~/")))
641 (proc (apply 'start-process name doc-view-conversion-buffer
642 program args)))
643 (push proc doc-view-current-converter-processes)
644 (setq mode-line-process (list (format ":%s" proc)))
645 (set-process-sentinel proc 'doc-view-sentinel)
646 (process-put proc 'buffer (current-buffer))
647 (process-put proc 'callback callback)))
648
649 (defun doc-view-dvi->pdf (dvi pdf callback)
650 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
651 ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
652 ;; references and includes other PS files.
653 (if (and doc-view-dvipdf-program
654 (executable-find doc-view-dvipdf-program))
655 (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
656 (list dvi pdf)
657 callback)
658 (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
659 (list "-o" pdf dvi)
660 callback)))
661
662
663 (defun doc-view-pdf/ps->png (pdf-ps png)
664 "Convert PDF-PS to PNG asynchronously."
665 (doc-view-start-process
666 "pdf/ps->png" doc-view-ghostscript-program
667 (append doc-view-ghostscript-options
668 (list (format "-r%d" (round doc-view-resolution))
669 (concat "-sOutputFile=" png)
670 pdf-ps))
671 (lambda ()
672 (when doc-view-current-timer
673 (cancel-timer doc-view-current-timer)
674 (setq doc-view-current-timer nil))
675 (doc-view-display (current-buffer) 'force)))
676 ;; Update the displayed pages as soon as they're done generating.
677 (when doc-view-conversion-refresh-interval
678 (setq doc-view-current-timer
679 (run-at-time "1 secs" doc-view-conversion-refresh-interval
680 'doc-view-display
681 (current-buffer)))))
682
683 (defun doc-view-pdf->png-1 (pdf png page callback)
684 "Convert a PAGE of a PDF file to PNG asynchronously.
685 Call CALLBACK with no arguments when done."
686 (doc-view-start-process
687 "pdf->png-1" doc-view-ghostscript-program
688 (append doc-view-ghostscript-options
689 (list (format "-r%d" (round doc-view-resolution))
690 ;; Sadly, `gs' only supports the page-range
691 ;; for PDF files.
692 (format "-dFirstPage=%d" page)
693 (format "-dLastPage=%d" page)
694 (concat "-sOutputFile=" png)
695 pdf))
696 callback))
697
698 (declare-function clear-image-cache "image.c" (&optional filter))
699
700 (defun doc-view-pdf->png (pdf png pages)
701 "Convert a PDF file to PNG asynchronously.
702 Start by converting PAGES, and then the rest."
703 (if (null pages)
704 (doc-view-pdf/ps->png pdf png)
705 ;; We could render several `pages' with a single process if they're
706 ;; (almost) consecutive, but since in 99% of the cases, there'll be only
707 ;; a single page anyway, and of the remaining 1%, few cases will have
708 ;; consecutive pages, it's not worth the trouble.
709 (lexical-let ((pdf pdf) (png png) (rest (cdr pages)))
710 (doc-view-pdf->png-1
711 pdf (format png (car pages)) (car pages)
712 (lambda ()
713 (if rest
714 (doc-view-pdf->png pdf png rest)
715 ;; Yippie, the important pages are done, update the display.
716 (clear-image-cache)
717 ;; Convert the rest of the pages.
718 (doc-view-pdf/ps->png pdf png)))))))
719
720 (defun doc-view-pdf->txt (pdf txt callback)
721 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
722 (or doc-view-pdftotext-program
723 (error "You need the `pdftotext' program to convert a PDF to text"))
724 (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
725 (list "-raw" pdf txt)
726 callback))
727
728 (defun doc-view-doc->txt (txt callback)
729 "Convert the current document to text and call CALLBACK when done."
730 (make-directory (doc-view-current-cache-dir) t)
731 (case doc-view-doc-type
732 (pdf
733 ;; Doc is a PDF, so convert it to TXT
734 (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
735 (ps
736 ;; Doc is a PS, so convert it to PDF (which will be converted to
737 ;; TXT thereafter).
738 (lexical-let ((pdf (expand-file-name "doc.pdf"
739 (doc-view-current-cache-dir)))
740 (txt txt)
741 (callback callback))
742 (doc-view-ps->pdf doc-view-buffer-file-name pdf
743 (lambda () (doc-view-pdf->txt pdf txt callback)))))
744 (dvi
745 ;; Doc is a DVI. This means that a doc.pdf already exists in its
746 ;; cache subdirectory.
747 (doc-view-pdf->txt (expand-file-name "doc.pdf"
748 (doc-view-current-cache-dir))
749 txt callback))
750 (t (error "DocView doesn't know what to do"))))
751
752 (defun doc-view-ps->pdf (ps pdf callback)
753 "Convert PS to PDF asynchronously and call CALLBACK when finished."
754 (or doc-view-ps2pdf-program
755 (error "You need the `ps2pdf' program to convert PS to PDF"))
756 (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
757 (list
758 ;; Avoid security problems when rendering files from
759 ;; untrusted sources.
760 "-dSAFER"
761 ;; in-file and out-file
762 ps pdf)
763 callback))
764
765 (defun doc-view-active-pages ()
766 (let ((pages ()))
767 (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
768 (let ((page (image-mode-window-get 'page win)))
769 (unless (memq page pages) (push page pages))))
770 pages))
771
772 (defun doc-view-convert-current-doc ()
773 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
774 Those files are saved in the directory given by the function
775 `doc-view-current-cache-dir'."
776 ;; Let stale files still display while we recompute the new ones, so only
777 ;; flush the cache when the conversion is over. One of the reasons why it
778 ;; is important to keep displaying the stale page is so that revert-buffer
779 ;; preserves the horizontal/vertical scroll settings (which are otherwise
780 ;; resets during the redisplay).
781 (setq doc-view-pending-cache-flush t)
782 (let ((png-file (expand-file-name "page-%d.png"
783 (doc-view-current-cache-dir)))
784 (res-file (expand-file-name "resolution.el"
785 (doc-view-current-cache-dir))))
786 (make-directory (doc-view-current-cache-dir) t)
787 ;; Save the used resolution so that it can be restored when
788 ;; reading the cached files.
789 (let ((res doc-view-resolution))
790 (with-temp-buffer
791 (princ res (current-buffer))
792 ;; Don't use write-file, so as to avoid prompts for `require-newline',
793 ;; or for pre-existing buffers with the same name, ...
794 (write-region nil nil res-file nil 'silently)))
795 (case doc-view-doc-type
796 (dvi
797 ;; DVI files have to be converted to PDF before Ghostscript can process
798 ;; it.
799 (lexical-let
800 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
801 (png-file png-file))
802 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
803 (lambda () (doc-view-pdf/ps->png pdf png-file)))))
804 (pdf
805 (let ((pages (doc-view-active-pages)))
806 ;; Convert PDF to PNG images starting with the active pages.
807 (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
808 (t
809 ;; Convert to PNG images.
810 (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))
811
812 ;;;; Slicing
813
814 (declare-function image-size "image.c" (spec &optional pixels frame))
815
816 (defun doc-view-set-slice (x y width height)
817 "Set the slice of the images that should be displayed.
818 You can use this function to tell doc-view not to display the
819 margins of the document. It prompts for the top-left corner (X
820 and Y) of the slice to display and its WIDTH and HEIGHT.
821
822 See `doc-view-set-slice-using-mouse' for a more convenient way to
823 do that. To reset the slice use `doc-view-reset-slice'."
824 (interactive
825 (let* ((size (image-size (doc-view-current-image) t))
826 (a (read-number (format "Top-left X (0..%d): " (car size))))
827 (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
828 (c (read-number (format "Width (0..%d): " (- (car size) a))))
829 (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
830 (list a b c d)))
831 (setf (doc-view-current-slice) (list x y width height))
832 ;; Redisplay
833 (doc-view-goto-page (doc-view-current-page)))
834
835 (defun doc-view-set-slice-using-mouse ()
836 "Set the slice of the images that should be displayed.
837 You set the slice by pressing mouse-1 at its top-left corner and
838 dragging it to its bottom-right corner. See also
839 `doc-view-set-slice' and `doc-view-reset-slice'."
840 (interactive)
841 (let (x y w h done)
842 (while (not done)
843 (let ((e (read-event
844 (concat "Press mouse-1 at the top-left corner and "
845 "drag it to the bottom-right corner!"))))
846 (when (eq (car e) 'drag-mouse-1)
847 (setq x (car (posn-object-x-y (event-start e))))
848 (setq y (cdr (posn-object-x-y (event-start e))))
849 (setq w (- (car (posn-object-x-y (event-end e))) x))
850 (setq h (- (cdr (posn-object-x-y (event-end e))) y))
851 (setq done t))))
852 (doc-view-set-slice x y w h)))
853
854 (defun doc-view-reset-slice ()
855 "Reset the current slice.
856 After calling this function whole pages will be visible again."
857 (interactive)
858 (setf (doc-view-current-slice) nil)
859 ;; Redisplay
860 (doc-view-goto-page (doc-view-current-page)))
861
862 ;;;; Display
863
864 (defun doc-view-insert-image (file &rest args)
865 "Insert the given png FILE.
866 ARGS is a list of image descriptors."
867 (when doc-view-pending-cache-flush
868 (clear-image-cache)
869 (setq doc-view-pending-cache-flush nil))
870 (let ((ol (doc-view-current-overlay))
871 (image (if (and file (file-readable-p file))
872 (apply 'create-image file 'png nil args)))
873 (slice (doc-view-current-slice)))
874 (setf (doc-view-current-image) image)
875 (move-overlay ol (point-min) (point-max))
876 (overlay-put ol 'display
877 (cond
878 (image
879 (if slice
880 (list (cons 'slice slice) image)
881 image))
882 ;; We're trying to display a page that doesn't exist.
883 (doc-view-current-converter-processes
884 ;; Maybe the page doesn't exist *yet*.
885 "Cannot display this page (yet)!")
886 (t
887 ;; Typically happens if the conversion process somehow
888 ;; failed. Better not signal an error here because it
889 ;; could prevent a subsequent reconversion from fixing
890 ;; the problem.
891 (concat "Cannot display this page!\n"
892 "Maybe because of a conversion failure!"))))
893 (let ((win (overlay-get ol 'window)))
894 (if (stringp (overlay-get ol 'display))
895 (progn ;Make sure the text is not scrolled out of view.
896 (set-window-hscroll win 0)
897 (set-window-vscroll win 0))
898 (let ((hscroll (image-mode-window-get 'hscroll win))
899 (vscroll (image-mode-window-get 'vscroll win)))
900 ;; Reset scroll settings, in case they were changed.
901 (if hscroll (set-window-hscroll win hscroll))
902 (if vscroll (set-window-vscroll win vscroll)))))))
903
904 (defun doc-view-sort (a b)
905 "Return non-nil if A should be sorted before B.
906 Predicate for sorting `doc-view-current-files'."
907 (or (< (length a) (length b))
908 (and (= (length a) (length b))
909 (string< a b))))
910
911 (defun doc-view-display (buffer &optional force)
912 "Start viewing the document in BUFFER.
913 If FORCE is non-nil, start viewing even if the document does not
914 have the page we want to view."
915 (with-current-buffer buffer
916 (let ((prev-pages doc-view-current-files))
917 (setq doc-view-current-files
918 (sort (directory-files (doc-view-current-cache-dir) t
919 "page-[0-9]+\\.png" t)
920 'doc-view-sort))
921 (dolist (win (or (get-buffer-window-list buffer nil t)
922 (list (selected-window))))
923 (let* ((page (doc-view-current-page win))
924 (pagefile (expand-file-name (format "page-%d.png" page)
925 (doc-view-current-cache-dir))))
926 (when (or force
927 (and (not (member pagefile prev-pages))
928 (member pagefile doc-view-current-files)))
929 (with-selected-window win
930 (assert (eq (current-buffer) buffer))
931 (doc-view-goto-page page))))))))
932
933 (defun doc-view-buffer-message ()
934 ;; Only show this message initially, not when refreshing the buffer (in which
935 ;; case it's better to keep displaying the "stale" page while computing
936 ;; the fresh new ones).
937 (unless (overlay-get (doc-view-current-overlay) 'display)
938 (overlay-put (doc-view-current-overlay) 'display
939 (concat (propertize "Welcome to DocView!" 'face 'bold)
940 "\n"
941 "
942 If you see this buffer it means that the document you want to view is being
943 converted to PNG and the conversion of the first page hasn't finished yet or
944 `doc-view-conversion-refresh-interval' is set to nil.
945
946 For now these keys are useful:
947
948 `q' : Bury this buffer. Conversion will go on in background.
949 `k' : Kill the conversion process and this buffer.
950 `K' : Kill the conversion process.\n"))))
951
952 (declare-function tooltip-show "tooltip" (text &optional use-echo-area))
953
954 (defun doc-view-show-tooltip ()
955 (interactive)
956 (tooltip-show (doc-view-current-info)))
957
958 (defun doc-view-open-text ()
959 "Open a buffer with the current doc's contents as text."
960 (interactive)
961 (if doc-view-current-converter-processes
962 (message "DocView: please wait till conversion finished.")
963 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
964 (if (file-readable-p txt)
965 (find-file txt)
966 (doc-view-doc->txt txt 'doc-view-open-text)))))
967
968 ;;;;; Toggle between editing and viewing
969
970
971 (defun doc-view-toggle-display ()
972 "Toggle between editing a document as text or viewing it."
973 (interactive)
974 (if (eq major-mode 'doc-view-mode)
975 ;; Switch to editing mode
976 (progn
977 (doc-view-kill-proc)
978 (setq buffer-read-only nil)
979 (remove-overlays (point-min) (point-max) 'doc-view t)
980 (set (make-local-variable 'image-mode-winprops-alist) t)
981 ;; Switch to the previously used major mode or fall back to fundamental
982 ;; mode.
983 (if doc-view-previous-major-mode
984 (funcall doc-view-previous-major-mode)
985 (fundamental-mode))
986 (doc-view-minor-mode 1))
987 ;; Switch to doc-view-mode
988 (when (and (buffer-modified-p)
989 (y-or-n-p "The buffer has been modified. Save the changes? "))
990 (save-buffer))
991 (doc-view-mode)))
992
993 ;;;; Searching
994
995
996 (defun doc-view-search-internal (regexp file)
997 "Return a list of FILE's pages that contain text matching REGEXP.
998 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
999 the pagenumber and CONTEXTS are all lines of text containing a match."
1000 (with-temp-buffer
1001 (insert-file-contents file)
1002 (let ((page 1)
1003 (lastpage 1)
1004 matches)
1005 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
1006 regexp "\\)\\)") nil t)
1007 (when (match-string 1) (setq page (1+ page)))
1008 (when (match-string 2)
1009 (if (/= page lastpage)
1010 (push (cons page
1011 (list (buffer-substring
1012 (line-beginning-position)
1013 (line-end-position))))
1014 matches)
1015 (setq matches (cons
1016 (append
1017 (or
1018 ;; This page already is a match.
1019 (car matches)
1020 ;; This is the first match on page.
1021 (list page))
1022 (list (buffer-substring
1023 (line-beginning-position)
1024 (line-end-position))))
1025 (cdr matches))))
1026 (setq lastpage page)))
1027 (nreverse matches))))
1028
1029 (defun doc-view-search-no-of-matches (list)
1030 "Extract the number of matches from the search result LIST."
1031 (let ((no 0))
1032 (dolist (p list)
1033 (setq no (+ no (1- (length p)))))
1034 no))
1035
1036 (defun doc-view-search-backward (new-query)
1037 "Call `doc-view-search' for backward search.
1038 If prefix NEW-QUERY is given, ask for a new regexp."
1039 (interactive "P")
1040 (doc-view-search new-query t))
1041
1042 (defun doc-view-search (new-query &optional backward)
1043 "Jump to the next match or initiate a new search if NEW-QUERY is given.
1044 If the current document hasn't been transformed to plain text
1045 till now do that first.
1046 If BACKWARD is non-nil, jump to the previous match."
1047 (interactive "P")
1048 (if (and (not new-query)
1049 doc-view-current-search-matches)
1050 (if backward
1051 (doc-view-search-previous-match 1)
1052 (doc-view-search-next-match 1))
1053 ;; New search, so forget the old results.
1054 (setq doc-view-current-search-matches nil)
1055 (let ((txt (expand-file-name "doc.txt"
1056 (doc-view-current-cache-dir))))
1057 (if (file-readable-p txt)
1058 (progn
1059 (setq doc-view-current-search-matches
1060 (doc-view-search-internal
1061 (read-from-minibuffer "Regexp: ")
1062 txt))
1063 (message "DocView: search yielded %d matches."
1064 (doc-view-search-no-of-matches
1065 doc-view-current-search-matches)))
1066 ;; We must convert to TXT first!
1067 (if doc-view-current-converter-processes
1068 (message "DocView: please wait till conversion finished.")
1069 (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))
1070
1071 (defun doc-view-search-next-match (arg)
1072 "Go to the ARGth next matching page."
1073 (interactive "p")
1074 (let* ((next-pages (doc-view-remove-if
1075 (lambda (i) (<= (car i) (doc-view-current-page)))
1076 doc-view-current-search-matches))
1077 (page (car (nth (1- arg) next-pages))))
1078 (if page
1079 (doc-view-goto-page page)
1080 (when (and
1081 doc-view-current-search-matches
1082 (y-or-n-p "No more matches after current page. Wrap to first match? "))
1083 (doc-view-goto-page (caar doc-view-current-search-matches))))))
1084
1085 (defun doc-view-search-previous-match (arg)
1086 "Go to the ARGth previous matching page."
1087 (interactive "p")
1088 (let* ((prev-pages (doc-view-remove-if
1089 (lambda (i) (>= (car i) (doc-view-current-page)))
1090 doc-view-current-search-matches))
1091 (page (car (nth (1- arg) (nreverse prev-pages)))))
1092 (if page
1093 (doc-view-goto-page page)
1094 (when (and
1095 doc-view-current-search-matches
1096 (y-or-n-p "No more matches before current page. Wrap to last match? "))
1097 (doc-view-goto-page (caar (last doc-view-current-search-matches)))))))
1098
1099 ;;;; User interface commands and the mode
1100
1101 ;; (put 'doc-view-mode 'mode-class 'special)
1102
1103 (defun doc-view-already-converted-p ()
1104 "Return non-nil if the current doc was already converted."
1105 (and (file-exists-p (doc-view-current-cache-dir))
1106 (> (length (directory-files (doc-view-current-cache-dir) nil "\\.png$")) 0)))
1107
1108 (defun doc-view-initiate-display ()
1109 ;; Switch to image display if possible
1110 (if (doc-view-mode-p doc-view-doc-type)
1111 (progn
1112 (doc-view-buffer-message)
1113 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
1114 (if (doc-view-already-converted-p)
1115 (progn
1116 (message "DocView: using cached files!")
1117 ;; Load the saved resolution
1118 (let ((res-file (expand-file-name "resolution.el"
1119 (doc-view-current-cache-dir)))
1120 (res doc-view-resolution))
1121 (with-temp-buffer
1122 (when (file-exists-p res-file)
1123 (insert-file-contents res-file)
1124 (setq res (read (current-buffer)))))
1125 (when (numberp res)
1126 (set (make-local-variable 'doc-view-resolution) res)))
1127 (doc-view-display (current-buffer) 'force))
1128 (doc-view-convert-current-doc))
1129 (message
1130 "%s"
1131 (substitute-command-keys
1132 (concat "Type \\[doc-view-toggle-display] to toggle between "
1133 "editing or viewing the document."))))
1134 (message
1135 "%s"
1136 (concat "No PNG support is available, or some conversion utility for "
1137 (file-name-extension doc-view-buffer-file-name)
1138 " files is missing."))
1139 (if (and (executable-find doc-view-pdftotext-program)
1140 (y-or-n-p
1141 "Unable to render file. View extracted text instead? "))
1142 (doc-view-open-text)
1143 (doc-view-toggle-display))))
1144
1145 (defvar bookmark-make-record-function)
1146
1147 (defun doc-view-clone-buffer-hook ()
1148 ;; FIXME: There are several potential problems linked with reconversion
1149 ;; and auto-revert when we have indirect buffers because they share their
1150 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
1151 ;; for each clone), but that means that clones need to collaborate a bit.
1152 ;; I guess it mostly means: detect when a reconversion process is already
1153 ;; running, and run the sentinel in all clones.
1154 ;;
1155 ;; Maybe the clones should really have a separate /tmp directory
1156 ;; so they could have a different resolution and you could use clones
1157 ;; for zooming.
1158 (remove-overlays (point-min) (point-max) 'doc-view t)
1159 (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))
1160
1161 (defun doc-view-intersection (l1 l2)
1162 (let ((l ()))
1163 (dolist (x l1) (if (memq x l2) (push x l)))
1164 l))
1165
1166 ;;;###autoload
1167 (defun doc-view-mode ()
1168 "Major mode in DocView buffers.
1169
1170 DocView Mode is an Emacs document viewer. It displays PDF, PS
1171 and DVI files (as PNG images) in Emacs buffers.
1172
1173 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1174 toggle between displaying the document or editing it as text.
1175 \\{doc-view-mode-map}"
1176 (interactive)
1177
1178 (if (= (point-min) (point-max))
1179 ;; The doc is empty or doesn't exist at all, so fallback to
1180 ;; another mode. We used to also check file-exists-p, but this
1181 ;; returns nil for tar members.
1182 (let ((auto-mode-alist (remq (rassq 'doc-view-mode auto-mode-alist)
1183 auto-mode-alist)))
1184 (normal-mode))
1185
1186 (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
1187 doc-view-previous-major-mode
1188 major-mode)))
1189 (kill-all-local-variables)
1190 (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))
1191
1192 ;; Figure out the document type.
1193 (let ((name-types
1194 (when buffer-file-name
1195 (cdr (assoc (file-name-extension buffer-file-name)
1196 '(("dvi" dvi)
1197 ("pdf" pdf)
1198 ("epdf" pdf)
1199 ("ps" ps)
1200 ("eps" ps))))))
1201 (content-types
1202 (save-excursion
1203 (goto-char (point-min))
1204 (cond
1205 ((looking-at "%!") '(ps))
1206 ((looking-at "%PDF") '(pdf))
1207 ((looking-at "\367\002") '(dvi))))))
1208 (set (make-local-variable 'doc-view-doc-type)
1209 (car (or (doc-view-intersection name-types content-types)
1210 (when (and name-types content-types)
1211 (error "Conflicting types: name says %s but content says %s"
1212 name-types content-types))
1213 name-types content-types
1214 (error "Cannot determine the document type")))))
1215
1216 (doc-view-make-safe-dir doc-view-cache-directory)
1217 ;; Handle compressed files, remote files, files inside archives
1218 (set (make-local-variable 'doc-view-buffer-file-name)
1219 (cond
1220 (jka-compr-really-do-compress
1221 (expand-file-name
1222 (file-name-nondirectory
1223 (file-name-sans-extension buffer-file-name))
1224 doc-view-cache-directory))
1225 ;; Is the file readable by local processes?
1226 ;; We used to use `file-remote-p' but it's unclear what it's
1227 ;; supposed to return nil for things like local files accessed via
1228 ;; `su' or via file://...
1229 ((let ((file-name-handler-alist nil))
1230 (not (file-readable-p buffer-file-name)))
1231 (expand-file-name
1232 (file-name-nondirectory buffer-file-name)
1233 doc-view-cache-directory))
1234 (t buffer-file-name)))
1235 (when (not (string= doc-view-buffer-file-name buffer-file-name))
1236 (write-region nil nil doc-view-buffer-file-name))
1237
1238 (add-hook 'change-major-mode-hook
1239 (lambda ()
1240 (doc-view-kill-proc)
1241 (remove-overlays (point-min) (point-max) 'doc-view t))
1242 nil t)
1243 (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
1244 (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)
1245
1246 (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
1247 ;; Keep track of display info ([vh]scroll, page number, overlay,
1248 ;; ...) for each window in which this document is shown.
1249 (add-hook 'image-mode-new-window-functions
1250 'doc-view-new-window-function nil t)
1251 (image-mode-setup-winprops)
1252
1253 (set (make-local-variable 'mode-line-position)
1254 '(" P" (:eval (number-to-string (doc-view-current-page)))
1255 "/" (:eval (number-to-string (length doc-view-current-files)))))
1256 ;; Don't scroll unless the user specifically asked for it.
1257 (set (make-local-variable 'auto-hscroll-mode) nil)
1258 (set (make-local-variable 'mwheel-scroll-up-function)
1259 'doc-view-scroll-up-or-next-page)
1260 (set (make-local-variable 'mwheel-scroll-down-function)
1261 'doc-view-scroll-down-or-previous-page)
1262 (set (make-local-variable 'cursor-type) nil)
1263 (use-local-map doc-view-mode-map)
1264 (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
1265 (set (make-local-variable 'bookmark-make-record-function)
1266 'doc-view-bookmark-make-record)
1267 (setq mode-name "DocView"
1268 buffer-read-only t
1269 major-mode 'doc-view-mode)
1270 (doc-view-initiate-display)
1271 ;; Switch off view-mode explicitly, because doc-view-mode is the
1272 ;; canonical view mode for PDF/PS/DVI files. This could be
1273 ;; switched on automatically depending on the value of
1274 ;; `view-read-only'.
1275 (view-mode -1)
1276 (run-mode-hooks 'doc-view-mode-hook)))
1277
1278 ;;;###autoload
1279 (define-minor-mode doc-view-minor-mode
1280 "Toggle Doc view minor mode.
1281 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1282 See the command `doc-view-mode' for more information on this mode."
1283 nil " DocView" doc-view-minor-mode-map
1284 :group 'doc-view
1285 (when doc-view-minor-mode
1286 (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
1287 (message
1288 "%s"
1289 (substitute-command-keys
1290 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1291
1292 (defun doc-view-clear-cache ()
1293 "Delete the whole cache (`doc-view-cache-directory')."
1294 (interactive)
1295 (dired-delete-file doc-view-cache-directory 'always))
1296
1297 (defun doc-view-dired-cache ()
1298 "Open `dired' in `doc-view-cache-directory'."
1299 (interactive)
1300 (dired doc-view-cache-directory))
1301
1302
1303 ;;;; Bookmark integration
1304
1305 (declare-function bookmark-make-record-default "bookmark"
1306 (&optional point-only))
1307 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1308 (declare-function bookmark-default-handler "bookmark" (bmk))
1309
1310 (defun doc-view-bookmark-make-record ()
1311 (nconc (bookmark-make-record-default)
1312 `((page . ,(doc-view-current-page))
1313 (handler . doc-view-bookmark-jump))))
1314
1315
1316 ;;;###autoload
1317 (defun doc-view-bookmark-jump (bmk)
1318 ;; This implements the `handler' function interface for record type
1319 ;; returned by `doc-view-bookmark-make-record', which see.
1320 (prog1 (bookmark-default-handler bmk)
1321 (let ((page (bookmark-prop-get bmk 'page)))
1322 (when (not (eq major-mode 'doc-view-mode))
1323 (doc-view-toggle-display))
1324 (with-selected-window
1325 (or (get-buffer-window (current-buffer) 0)
1326 (selected-window))
1327 (doc-view-goto-page page)))))
1328
1329
1330 (provide 'doc-view)
1331
1332 ;; Local Variables:
1333 ;; mode: outline-minor
1334 ;; End:
1335
1336 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1337 ;;; doc-view.el ends here