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