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