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