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