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