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