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