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