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