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