1 ;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs
3 ;; Copyright (C) 2007, 2008 Free Software Foundation, Inc.
5 ;; Author: Tassilo Horn <tassilo@member.fsf.org>
6 ;; Maintainer: Tassilo Horn <tassilo@member.fsf.org>
7 ;; Keywords: files, pdf, ps, dvi
9 ;; This file is part of GNU Emacs.
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, or (at your option)
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.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
28 ;; doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript,
29 ;; `dvipdfm' which comes with teTeX and `pdftotext', which comes with xpdf
30 ;; (http://www.foolabs.com/xpdf/) or poppler (http://poppler.freedesktop.org/).
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.
39 ;; To use it simply open a document file with
41 ;; C-x C-f ~/path/to/document RET
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.
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'.
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
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 invokation 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').
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 invokation 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.
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'.
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.)
93 ;; This and all other options can be set with the customization interface.
96 ;; M-x customize-group RET doc-view RET
98 ;; and modify them to your needs.
102 ;; - add print command.
103 ;; - share more code with image-mode.
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).
111 ;;;; About isearch support
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.
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
131 ;; Anyway, if someone with better isearch knowledge wants to give it a try,
132 ;; feel free to do it. --Tassilo
137 (require 'image-mode
)
140 ;;;; Customization Options
142 (defgroup doc-view nil
143 "In-buffer viewer for PDF, PostScript and DVI files."
144 :link
'(function-link doc-view
)
150 (defcustom doc-view-ghostscript-program
(executable-find "gs")
151 "Program to convert PS and PDF files to PNG."
155 (defcustom doc-view-ghostscript-options
156 '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
158 "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
159 "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
160 "A list of options to give to ghostscript."
161 :type
'(repeat string
)
164 (defcustom doc-view-resolution
100
165 "Dots per inch resolution used to render the documents.
166 Higher values result in larger images."
170 (defcustom doc-view-dvipdfm-program
(executable-find "dvipdfm")
171 "Program to convert DVI files to PDF.
173 DVI file will be converted to PDF before the resulting PDF is
178 (defcustom doc-view-ps2pdf-program
(executable-find "ps2pdf")
179 "Program to convert PS files to PDF.
181 PS files will be converted to PDF before searching is possible."
185 (defcustom doc-view-pdftotext-program
(executable-find "pdftotext")
186 "Program to convert PDF files to plain text.
188 Needed for searching."
192 (defcustom doc-view-cache-directory
193 (expand-file-name (format "docview%d" (user-uid))
194 temporary-file-directory
)
195 "The base directory, where the PNG images will be saved."
199 (defvar doc-view-conversion-buffer
" *doc-view conversion output*"
200 "The buffer where messages from the converter programs go to.")
202 (defcustom doc-view-conversion-refresh-interval
1
203 "Interval in seconds between refreshes of the DocView buffer while converting.
204 After such a refresh newly converted pages will be available for
205 viewing. If set to nil there won't be any refreshes and the
206 pages won't be displayed before conversion of the whole document
211 ;;;; Internal Variables
213 (defun doc-view-new-window-function (winprops)
214 (let ((ol (image-mode-window-get 'overlay winprops
)))
216 (setq ol
(copy-overlay ol
))
217 (assert (not (get-char-property (point-min) 'display
(car winprops
))))
218 (setq ol
(make-overlay (point-min) (point-max) nil t
))
219 (overlay-put ol
'doc-view t
))
220 (overlay-put ol
'window
(car winprops
))
221 (image-mode-window-put 'overlay ol winprops
)))
223 (defvar doc-view-current-files nil
224 "Only used internally.")
226 (defvar doc-view-current-converter-process nil
227 "Only used internally.")
229 (defvar doc-view-current-timer nil
230 "Only used internally.")
232 (defvar doc-view-current-cache-dir nil
233 "Only used internally.")
235 (defvar doc-view-current-search-matches nil
236 "Only used internally.")
238 (defvar doc-view-pending-cache-flush nil
239 "Only used internally.")
241 (defvar doc-view-previous-major-mode nil
242 "Only used internally.")
244 (defvar doc-view-buffer-file-name nil
245 "Only used internally.
246 The file name used for conversion. Normally it's the same as
247 `buffer-file-name', but for remote files, compressed files and
248 files inside an archive it is a temporary copy of
249 the (uncompressed, extracted) file residing in
250 `doc-view-cache-directory'.")
252 (defvar doc-view-doc-type nil
253 "The type of document in the current buffer.
254 Can be `dvi', `pdf', or `ps'.")
258 (defvar doc-view-mode-map
259 (let ((map (make-sparse-keymap)))
260 (suppress-keymap map
)
261 ;; Navigation in the document
262 (define-key map
(kbd "n") 'doc-view-next-page
)
263 (define-key map
(kbd "p") 'doc-view-previous-page
)
264 (define-key map
(kbd "<next>") 'forward-page
)
265 (define-key map
(kbd "<prior>") 'backward-page
)
266 (define-key map
[remap forward-page
] 'doc-view-next-page
)
267 (define-key map
[remap backward-page
] 'doc-view-previous-page
)
268 (define-key map
(kbd "SPC") 'doc-view-scroll-up-or-next-page
)
269 (define-key map
(kbd "DEL") 'doc-view-scroll-down-or-previous-page
)
270 (define-key map
(kbd "M-<") 'doc-view-first-page
)
271 (define-key map
(kbd "M->") 'doc-view-last-page
)
272 (define-key map
[remap goto-line
] 'doc-view-goto-page
)
273 (define-key map
[remap scroll-up
] 'image-scroll-up
)
274 (define-key map
[remap scroll-down
] 'image-scroll-down
)
276 (define-key map
"+" 'doc-view-enlarge
)
277 (define-key map
"-" 'doc-view-shrink
)
278 ;; Killing/burying the buffer (and the process)
279 (define-key map
(kbd "q") 'bury-buffer
)
280 (define-key map
(kbd "k") 'doc-view-kill-proc-and-buffer
)
281 (define-key map
(kbd "K") 'doc-view-kill-proc
)
283 (define-key map
(kbd "s s") 'doc-view-set-slice
)
284 (define-key map
(kbd "s m") 'doc-view-set-slice-using-mouse
)
285 (define-key map
(kbd "s r") 'doc-view-reset-slice
)
287 (define-key map
(kbd "C-s") 'doc-view-search
)
288 (define-key map
(kbd "<find>") 'doc-view-search
)
289 (define-key map
(kbd "C-r") 'doc-view-search-backward
)
291 (define-key map
[remap forward-char
] 'image-forward-hscroll
)
292 (define-key map
[remap backward-char
] 'image-backward-hscroll
)
293 (define-key map
[remap next-line
] 'image-next-line
)
294 (define-key map
[remap previous-line
] 'image-previous-line
)
296 (define-key map
(kbd "C-t") 'doc-view-show-tooltip
)
297 ;; Toggle between text and image display or editing
298 (define-key map
(kbd "C-c C-c") 'doc-view-toggle-display
)
299 ;; Open a new buffer with doc's text contents
300 (define-key map
(kbd "C-c C-t") 'doc-view-open-text
)
301 ;; Reconvert the current document
302 (define-key map
(kbd "g") 'revert-buffer
)
303 (define-key map
(kbd "r") 'revert-buffer
)
305 "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")
307 (easy-menu-define doc-view-menu doc-view-mode-map
308 "Menu for Doc View mode."
310 ["Set Slice" doc-view-set-slice-using-mouse
]
311 ["Set Slice (manual)" doc-view-set-slice
]
312 ["Reset Slice" doc-view-reset-slice
]
314 ["Search" doc-view-search
]
315 ["Search Backwards" doc-view-search-backward
]
316 ["Toggle display" doc-view-toggle-display
]
319 (defvar doc-view-minor-mode-map
320 (let ((map (make-sparse-keymap)))
321 ;; Toggle between text and image display or editing
322 (define-key map
(kbd "C-c C-c") 'doc-view-toggle-display
)
324 "Keymap used by `doc-minor-view-mode'.")
326 ;;;; Navigation Commands
328 (defmacro doc-view-current-page
(&optional win
)
329 `(image-mode-window-get 'page
,win
))
330 (defmacro doc-view-current-info
() `(image-mode-window-get 'info
))
331 (defmacro doc-view-current-overlay
() `(image-mode-window-get 'overlay
))
332 (defmacro doc-view-current-image
() `(image-mode-window-get 'image
))
333 (defmacro doc-view-current-slice
() `(image-mode-window-get 'slice
))
335 (defun doc-view-goto-page (page)
336 "View the page given by PAGE."
337 (interactive "nPage: ")
338 (let ((len (length doc-view-current-files
)))
341 (when (and (> page len
)
342 ;; As long as the converter is running, we don't know
343 ;; how many pages will be available.
344 (null doc-view-current-converter-process
))
346 (setf (doc-view-current-page) page
347 (doc-view-current-info)
350 (format "Page %d of %d." page len
) 'face
'bold
)
351 ;; Tell user if converting isn't finished yet
352 (if doc-view-current-converter-process
353 " (still converting...)\n"
355 ;; Display context infos if this page matches the last search
356 (when (and doc-view-current-search-matches
357 (assq page doc-view-current-search-matches
))
358 (concat (propertize "Search matches:\n" 'face
'bold
)
360 (dolist (m (cdr (assq page
361 doc-view-current-search-matches
)))
362 (setq contexts
(concat contexts
" - \"" m
"\"\n")))
365 ;; We used to find the file name from doc-view-current-files but
366 ;; that's not right if the pages are not generated sequentially
367 ;; or if the page isn't in doc-view-current-files yet.
368 (doc-view-insert-image (expand-file-name (format "page-%d.png" page
)
369 (doc-view-current-cache-dir))
371 (overlay-put (doc-view-current-overlay)
372 'help-echo
(doc-view-current-info))))
374 (defun doc-view-next-page (&optional arg
)
375 "Browse ARG pages forward."
377 (doc-view-goto-page (+ (doc-view-current-page) (or arg
1))))
379 (defun doc-view-previous-page (&optional arg
)
380 "Browse ARG pages backward."
382 (doc-view-goto-page (- (doc-view-current-page) (or arg
1))))
384 (defun doc-view-first-page ()
385 "View the first page."
387 (doc-view-goto-page 1))
389 (defun doc-view-last-page ()
390 "View the last page."
392 (doc-view-goto-page (length doc-view-current-files
)))
394 (defun doc-view-scroll-up-or-next-page ()
395 "Scroll page up if possible, else goto next page."
397 (when (= (window-vscroll) (image-scroll-up nil
))
398 (let ((cur-page (doc-view-current-page)))
400 (when (/= cur-page
(doc-view-current-page))
401 (set-window-vscroll nil
0)))))
403 (defun doc-view-scroll-down-or-previous-page ()
404 "Scroll page down if possible, else goto previous page."
406 (when (= (window-vscroll) (image-scroll-down nil
))
407 (let ((cur-page (doc-view-current-page)))
408 (doc-view-previous-page)
409 (when (/= cur-page
(doc-view-current-page))
410 (image-scroll-up nil
)))))
412 ;;;; Utility Functions
414 (defun doc-view-kill-proc ()
415 "Kill the current converter process."
417 (when doc-view-current-converter-process
418 (ignore-errors ;; Maybe it's dead already?
419 (kill-process doc-view-current-converter-process
))
420 (setq doc-view-current-converter-process nil
))
421 (when doc-view-current-timer
422 (cancel-timer doc-view-current-timer
)
423 (setq doc-view-current-timer nil
))
424 (setq mode-line-process nil
))
426 (defun doc-view-kill-proc-and-buffer ()
427 "Kill the current converter process and buffer."
430 (when (eq major-mode
'doc-view-mode
)
431 (kill-buffer (current-buffer))))
433 (defun doc-view-make-safe-dir (dir)
435 (let ((umask (default-file-modes)))
438 ;; Create temp files with strict access rights. It's easy to
439 ;; loosen them later, whereas it's impossible to close the
440 ;; time-window of loose permissions otherwise.
441 (set-default-file-modes #o0700
)
442 (make-directory dir
))
444 (set-default-file-modes umask
)))
446 (if (file-symlink-p dir
)
447 (error "Danger: %s points to a symbolic link" dir
))
448 ;; In case it was created earlier with looser rights.
449 ;; We could check the mode info returned by file-attributes, but it's
450 ;; a pain to parse and it may not tell you what we want under
451 ;; non-standard file-systems. So let's just say what we want and let
452 ;; the underlying C code and file-system figure it out.
453 ;; This also ends up checking a bunch of useful conditions: it makes
454 ;; sure we have write-access to the directory and that we own it, thus
455 ;; closing a bunch of security holes.
456 (set-file-modes dir
#o0700
))))
458 (defun doc-view-current-cache-dir ()
459 "Return the directory where the png files of the current doc should be saved.
460 It's a subdirectory of `doc-view-cache-directory'."
461 (if doc-view-current-cache-dir
462 doc-view-current-cache-dir
463 ;; Try and make sure doc-view-cache-directory exists and is safe.
464 (doc-view-make-safe-dir doc-view-cache-directory
)
465 ;; Now compute the subdirectory to use.
466 (setq doc-view-current-cache-dir
467 (file-name-as-directory
469 (concat (file-name-nondirectory buffer-file-name
)
471 (let ((file doc-view-buffer-file-name
))
473 (set-buffer-multibyte nil
)
474 (insert-file-contents-literally file
)
475 (md5 (current-buffer)))))
476 doc-view-cache-directory
)))))
478 (defun doc-view-remove-if (predicate list
)
479 "Return LIST with all items removed that satisfy PREDICATE."
481 (dolist (item list
(nreverse new-list
))
482 (when (not (funcall predicate item
))
483 (setq new-list
(cons item new-list
))))))
486 (defun doc-view-mode-p (type)
487 "Return non-nil if image type TYPE is available for `doc-view'.
488 Image types are symbols like `dvi', `postscript' or `pdf'."
489 (and (display-graphic-p)
490 (image-type-available-p 'png
)
493 (and (doc-view-mode-p 'pdf
)
494 doc-view-dvipdfm-program
495 (executable-find doc-view-dvipdfm-program
)))
496 ((or (eq type
'postscript
) (eq type
'ps
) (eq type
'eps
)
498 (and doc-view-ghostscript-program
499 (executable-find doc-view-ghostscript-program
)))
500 (t ;; unknown image type
503 ;;;; Conversion Functions
505 (defvar doc-view-shrink-factor
1.125)
507 (defun doc-view-enlarge (factor)
508 "Enlarge the document."
509 (interactive (list doc-view-shrink-factor
))
510 (set (make-local-variable 'doc-view-resolution
)
511 (* factor doc-view-resolution
))
512 (doc-view-reconvert-doc))
514 (defun doc-view-shrink (factor)
515 "Shrink the document."
516 (interactive (list doc-view-shrink-factor
))
517 (doc-view-enlarge (/ 1.0 factor
)))
519 (defun doc-view-reconvert-doc ()
520 "Reconvert the current document.
521 Should be invoked when the cached images aren't up-to-date."
524 ;; Clear the old cached files
525 (when (file-exists-p (doc-view-current-cache-dir))
526 (dired-delete-file (doc-view-current-cache-dir) 'always
))
527 (doc-view-initiate-display))
529 (defun doc-view-sentinel (proc event
)
530 "Generic sentinel for doc-view conversion processes."
531 (if (not (string-match "finished" event
))
532 (message "DocView: process %s changed status to %s."
533 (process-name proc
) event
)
534 (with-current-buffer (process-get proc
'buffer
)
535 (setq doc-view-current-converter-process nil
536 mode-line-process nil
)
537 (funcall (process-get proc
'callback
)))))
539 (defun doc-view-dvi->pdf
(dvi pdf callback
)
540 "Convert DVI to PDF asynchronously and call CALLBACK when finished."
541 (setq doc-view-current-converter-process
542 (start-process "dvi->pdf" doc-view-conversion-buffer
543 doc-view-dvipdfm-program
545 mode-line-process
(list (format ":%s" doc-view-current-converter-process
)))
546 (set-process-sentinel doc-view-current-converter-process
'doc-view-sentinel
)
547 (process-put doc-view-current-converter-process
'buffer
(current-buffer))
548 (process-put doc-view-current-converter-process
'callback callback
))
550 (defun doc-view-pdf/ps-
>png-sentinel
(proc event
)
551 "If PDF/PS->PNG conversion was successful, update the display."
552 (if (not (string-match "finished" event
))
553 (message "DocView: converter process changed status to %s." event
)
554 ;; FIXME: kill the process if we kill the buffer?
555 (when (buffer-live-p (process-get proc
'buffer
))
556 (with-current-buffer (process-get proc
'buffer
)
557 (setq doc-view-current-converter-process nil
558 mode-line-process nil
)
559 (when doc-view-current-timer
560 (cancel-timer doc-view-current-timer
)
561 (setq doc-view-current-timer nil
))
562 ;; Yippie, finished. Update the display!
563 (doc-view-display (current-buffer) 'force
)))))
565 (defun doc-view-pdf/ps-
>png
(pdf-ps png
)
566 "Convert PDF-PS to PNG asynchronously."
567 (setq doc-view-current-converter-process
568 ;; Make sure the process is started in an existing directory,
569 ;; (rather than some file-name-handler-managed dir, for example).
570 (let ((default-directory (file-name-directory pdf-ps
)))
571 (apply 'start-process
572 (append (list "pdf/ps->png" doc-view-conversion-buffer
573 doc-view-ghostscript-program
)
574 doc-view-ghostscript-options
575 (list (format "-r%d" (round doc-view-resolution
)))
576 (list (concat "-sOutputFile=" png
))
578 mode-line-process
(list (format ":%s" doc-view-current-converter-process
)))
579 (process-put doc-view-current-converter-process
580 'buffer
(current-buffer))
581 (set-process-sentinel doc-view-current-converter-process
582 'doc-view-pdf
/ps-
>png-sentinel
)
583 (when doc-view-conversion-refresh-interval
584 (setq doc-view-current-timer
585 (run-at-time "1 secs" doc-view-conversion-refresh-interval
589 (defun doc-view-pdf->txt
(pdf txt callback
)
590 "Convert PDF to TXT asynchronously and call CALLBACK when finished."
591 (setq doc-view-current-converter-process
592 (start-process "pdf->txt" doc-view-conversion-buffer
593 doc-view-pdftotext-program
"-raw"
595 mode-line-process
(list (format ":%s" doc-view-current-converter-process
)))
596 (set-process-sentinel doc-view-current-converter-process
598 (process-put doc-view-current-converter-process
'buffer
(current-buffer))
599 (process-put doc-view-current-converter-process
'callback callback
))
601 (defun doc-view-doc->txt
(txt callback
)
602 "Convert the current document to text and call CALLBACK when done."
603 (unless (file-exists-p (doc-view-current-cache-dir))
604 (make-directory (doc-view-current-cache-dir)))
605 (case doc-view-doc-type
607 ;; Doc is a PDF, so convert it to TXT
608 (doc-view-pdf->txt doc-view-buffer-file-name txt callback
))
610 ;; Doc is a PS, so convert it to PDF (which will be converted to
612 (lexical-let ((pdf (expand-file-name "doc.pdf"
613 (doc-view-current-cache-dir)))
616 (doc-view-ps->pdf doc-view-buffer-file-name pdf
617 (lambda () (doc-view-pdf->txt pdf txt callback
)))))
619 ;; Doc is a DVI. This means that a doc.pdf already exists in its
620 ;; cache subdirectory.
621 (doc-view-pdf->txt
(expand-file-name "doc.pdf"
622 (doc-view-current-cache-dir))
624 (t (error "DocView doesn't know what to do"))))
626 (defun doc-view-ps->pdf
(ps pdf callback
)
627 "Convert PS to PDF asynchronously and call CALLBACK when finished."
628 (setq doc-view-current-converter-process
629 (start-process "ps->pdf" doc-view-conversion-buffer
630 doc-view-ps2pdf-program
631 ;; Avoid security problems when rendering files from
632 ;; untrusted sources.
634 ;; in-file and out-file
636 mode-line-process
(list (format ":%s" doc-view-current-converter-process
)))
637 (set-process-sentinel doc-view-current-converter-process
'doc-view-sentinel
)
638 (process-put doc-view-current-converter-process
'buffer
(current-buffer))
639 (process-put doc-view-current-converter-process
'callback callback
))
641 (defun doc-view-convert-current-doc ()
642 "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
643 Those files are saved in the directory given by the function
644 `doc-view-current-cache-dir'."
645 ;; Let stale files still display while we recompute the new ones, so only
646 ;; flush the cache when the conversion is over. One of the reasons why it
647 ;; is important to keep displaying the stale page is so that revert-buffer
648 ;; preserves the horizontal/vertical scroll settings (which are otherwise
649 ;; resets during the redisplay).
650 (setq doc-view-pending-cache-flush t
)
651 (let ((png-file (expand-file-name "page-%d.png"
652 (doc-view-current-cache-dir))))
653 (unless (file-exists-p (doc-view-current-cache-dir))
654 (make-directory (doc-view-current-cache-dir)))
655 (case doc-view-doc-type
657 ;; DVI files have to be converted to PDF before Ghostscript can process
660 ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir
))
662 (doc-view-dvi->pdf doc-view-buffer-file-name pdf
663 (lambda () (doc-view-pdf/ps-
>png pdf png-file
)))))
665 ;; Convert to PNG images.
666 (doc-view-pdf/ps-
>png doc-view-buffer-file-name png-file
)))))
670 (defun doc-view-set-slice (x y width height
)
671 "Set the slice of the images that should be displayed.
672 You can use this function to tell doc-view not to display the
673 margins of the document. It prompts for the top-left corner (X
674 and Y) of the slice to display and its WIDTH and HEIGHT.
676 See `doc-view-set-slice-using-mouse' for a more convenient way to
677 do that. To reset the slice use `doc-view-reset-slice'."
679 (let* ((size (image-size (doc-view-current-image) t
))
680 (a (read-number (format "Top-left X (0..%d): " (car size
))))
681 (b (read-number (format "Top-left Y (0..%d): " (cdr size
))))
682 (c (read-number (format "Width (0..%d): " (- (car size
) a
))))
683 (d (read-number (format "Height (0..%d): " (- (cdr size
) b
)))))
685 (setf (doc-view-current-slice) (list x y width height
))
687 (doc-view-goto-page (doc-view-current-page)))
689 (defun doc-view-set-slice-using-mouse ()
690 "Set the slice of the images that should be displayed.
691 You set the slice by pressing mouse-1 at its top-left corner and
692 dragging it to its bottom-right corner. See also
693 `doc-view-set-slice' and `doc-view-reset-slice'."
698 (concat "Press mouse-1 at the top-left corner and "
699 "drag it to the bottom-right corner!"))))
700 (when (eq (car e
) 'drag-mouse-1
)
701 (setq x
(car (posn-object-x-y (event-start e
))))
702 (setq y
(cdr (posn-object-x-y (event-start e
))))
703 (setq w
(- (car (posn-object-x-y (event-end e
))) x
))
704 (setq h
(- (cdr (posn-object-x-y (event-end e
))) y
))
706 (doc-view-set-slice x y w h
)))
708 (defun doc-view-reset-slice ()
709 "Reset the current slice.
710 After calling this function whole pages will be visible again."
712 (setf (doc-view-current-slice) nil
)
714 (doc-view-goto-page (doc-view-current-page)))
718 (defun doc-view-insert-image (file &rest args
)
719 "Insert the given png FILE.
720 ARGS is a list of image descriptors."
721 (when doc-view-pending-cache-flush
723 (setq doc-view-pending-cache-flush nil
))
724 (let ((ol (doc-view-current-overlay))
725 (image (if (and file
(file-readable-p file
))
726 (apply 'create-image file
'png nil args
)))
727 (slice (doc-view-current-slice)))
728 (setf (doc-view-current-image) image
)
729 (move-overlay ol
(point-min) (point-max))
730 (overlay-put ol
'display
734 (list (cons 'slice slice
) image
)
736 ;; We're trying to display a page that doesn't exist.
737 (doc-view-current-converter-process
738 ;; Maybe the page doesn't exist *yet*.
739 "Cannot display this page (yet)!")
741 ;; Typically happens if the conversion process somehow
742 ;; failed. Better not signal an error here because it
743 ;; could prevent a subsequent reconversion from fixing
745 (concat "Cannot display this page!\n"
746 "Maybe because of a conversion failure!"))))
747 (let ((win (overlay-get ol
'window
)))
748 (if (stringp (overlay-get ol
'display
))
749 (progn ;Make sure the text is not scrolled out of view.
750 (set-window-hscroll win
0)
751 (set-window-vscroll win
0))
752 (let ((hscroll (image-mode-window-get 'hscroll win
))
753 (vscroll (image-mode-window-get 'vscroll win
)))
754 ;; Reset scroll settings, in case they were changed.
755 (if hscroll
(set-window-hscroll win hscroll
))
756 (if vscroll
(set-window-vscroll win vscroll
)))))))
758 (defun doc-view-sort (a b
)
759 "Return non-nil if A should be sorted before B.
760 Predicate for sorting `doc-view-current-files'."
761 (or (< (length a
) (length b
))
762 (and (= (length a
) (length b
))
765 (defun doc-view-display (buffer &optional force
)
766 "Start viewing the document in BUFFER.
767 If FORCE is non-nil, start viewing even if the document does not
768 have the page we want to view."
769 (with-current-buffer buffer
770 (let ((prev-pages doc-view-current-files
))
771 (setq doc-view-current-files
772 (sort (directory-files (doc-view-current-cache-dir) t
773 "page-[0-9]+\\.png" t
)
775 (dolist (win (get-buffer-window-list buffer nil t
))
776 (let* ((page (doc-view-current-page win
))
777 (pagefile (expand-file-name (format "page-%d.png" page
)
778 (doc-view-current-cache-dir))))
780 (and (not (member pagefile prev-pages
))
781 (member pagefile doc-view-current-files
)))
782 (with-selected-window win
783 (assert (eq (current-buffer) buffer
))
784 (doc-view-goto-page page
))))))))
786 (defun doc-view-buffer-message ()
787 ;; Only show this message initially, not when refreshing the buffer (in which
788 ;; case it's better to keep displaying the "stale" page while computing
789 ;; the fresh new ones).
790 (unless (overlay-get (doc-view-current-overlay) 'display
)
791 (overlay-put (doc-view-current-overlay) 'display
792 (concat (propertize "Welcome to DocView!" 'face
'bold
)
795 If you see this buffer it means that the document you want to view is being
796 converted to PNG and the conversion of the first page hasn't finished yet or
797 `doc-view-conversion-refresh-interval' is set to nil.
799 For now these keys are useful:
801 `q' : Bury this buffer. Conversion will go on in background.
802 `k' : Kill the conversion process and this buffer.
803 `K' : Kill the conversion process.\n"))))
805 (defun doc-view-show-tooltip ()
807 (tooltip-show (doc-view-current-info)))
809 (defun doc-view-open-text ()
810 "Open a buffer with the current doc's contents as text."
812 (if doc-view-current-converter-process
813 (message "DocView: please wait till conversion finished.")
814 (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
815 (if (file-readable-p txt
)
817 (doc-view-doc->txt txt
'doc-view-open-text
)))))
819 ;;;;; Toggle between editing and viewing
822 (defun doc-view-toggle-display ()
823 "Toggle between editing a document as text or viewing it."
825 (if (eq major-mode
'doc-view-mode
)
826 ;; Switch to editing mode
829 (setq buffer-read-only nil
)
830 (remove-overlays (point-min) (point-max) 'doc-view t
)
831 (set (make-local-variable 'image-mode-winprops-alist
) t
)
832 ;; Switch to the previously used major mode or fall back to fundamental
834 (if doc-view-previous-major-mode
835 (funcall doc-view-previous-major-mode
)
837 (doc-view-minor-mode 1))
838 ;; Switch to doc-view-mode
839 (when (and (buffer-modified-p)
840 (y-or-n-p "The buffer has been modified. Save the changes? "))
847 (defun doc-view-search-internal (regexp file
)
848 "Return a list of FILE's pages that contain text matching REGEXP.
849 The value is an alist of the form (PAGE CONTEXTS) where PAGE is
850 the pagenumber and CONTEXTS are all lines of text containing a match."
852 (insert-file-contents file
)
856 (while (re-search-forward (concat "\\(?:\\([\f]\\)\\|\\("
857 regexp
"\\)\\)") nil t
)
858 (when (match-string 1) (setq page
(1+ page
)))
859 (when (match-string 2)
860 (if (/= page lastpage
)
862 (list (buffer-substring
863 (line-beginning-position)
864 (line-end-position))))
869 ;; This page already is a match.
871 ;; This is the first match on page.
873 (list (buffer-substring
874 (line-beginning-position)
875 (line-end-position))))
877 (setq lastpage page
)))
878 (nreverse matches
))))
880 (defun doc-view-search-no-of-matches (list)
881 "Extract the number of matches from the search result LIST."
884 (setq no
(+ no
(1- (length p
)))))
887 (defun doc-view-search-backward (new-query)
888 "Call `doc-view-search' for backward search.
889 If prefix NEW-QUERY is given, ask for a new regexp."
891 (doc-view-search new-query t
))
893 (defun doc-view-search (new-query &optional backward
)
894 "Jump to the next match or initiate a new search if NEW-QUERY is given.
895 If the current document hasn't been transformed to plain text
896 till now do that first.
897 If BACKWARD is non-nil, jump to the previous match."
899 (if (and (not new-query
)
900 doc-view-current-search-matches
)
902 (doc-view-search-previous-match 1)
903 (doc-view-search-next-match 1))
904 ;; New search, so forget the old results.
905 (setq doc-view-current-search-matches nil
)
906 (let ((txt (expand-file-name "doc.txt"
907 (doc-view-current-cache-dir))))
908 (if (file-readable-p txt
)
910 (setq doc-view-current-search-matches
911 (doc-view-search-internal
912 (read-from-minibuffer "Regexp: ")
914 (message "DocView: search yielded %d matches."
915 (doc-view-search-no-of-matches
916 doc-view-current-search-matches
)))
917 ;; We must convert to TXT first!
918 (if doc-view-current-converter-process
919 (message "DocView: please wait till conversion finished.")
920 (doc-view-doc->txt txt
(lambda () (doc-view-search nil
))))))))
922 (defun doc-view-search-next-match (arg)
923 "Go to the ARGth next matching page."
925 (let* ((next-pages (doc-view-remove-if
926 (lambda (i) (<= (car i
) (doc-view-current-page)))
927 doc-view-current-search-matches
))
928 (page (car (nth (1- arg
) next-pages
))))
930 (doc-view-goto-page page
)
932 doc-view-current-search-matches
933 (y-or-n-p "No more matches after current page. Wrap to first match? "))
934 (doc-view-goto-page (caar doc-view-current-search-matches
))))))
936 (defun doc-view-search-previous-match (arg)
937 "Go to the ARGth previous matching page."
939 (let* ((prev-pages (doc-view-remove-if
940 (lambda (i) (>= (car i
) (doc-view-current-page)))
941 doc-view-current-search-matches
))
942 (page (car (nth (1- arg
) (nreverse prev-pages
)))))
944 (doc-view-goto-page page
)
946 doc-view-current-search-matches
947 (y-or-n-p "No more matches before current page. Wrap to last match? "))
948 (doc-view-goto-page (caar (last doc-view-current-search-matches
)))))))
950 ;;;; User interface commands and the mode
952 ;; (put 'doc-view-mode 'mode-class 'special)
954 (defun doc-view-already-converted-p ()
955 "Return non-nil if the current doc was already converted."
956 (and (file-exists-p (doc-view-current-cache-dir))
957 (> 0 (length (directory-files (doc-view-current-cache-dir) nil
"\\.png$")))))
959 (defun doc-view-initiate-display ()
960 ;; Switch to image display if possible
961 (if (doc-view-mode-p (intern (file-name-extension doc-view-buffer-file-name
)))
963 (doc-view-buffer-message)
964 (setf (doc-view-current-page) (or (doc-view-current-page) 1))
965 (if (doc-view-already-converted-p)
967 (message "DocView: using cached files!")
968 (doc-view-display (current-buffer) 'force
))
969 (doc-view-convert-current-doc))
972 (substitute-command-keys
973 (concat "Type \\[doc-view-toggle-display] to toggle between "
974 "editing or viewing the document."))))
977 (substitute-command-keys
978 (concat "No image (png) support available or some conversion utility for "
979 (file-name-extension doc-view-buffer-file-name
)" files is missing. "
980 "Type \\[doc-view-toggle-display] to switch to an editing mode or "
981 "\\[doc-view-open-text] to open a buffer showing the doc as text.")))))
983 (defvar bookmark-make-record-function
)
985 (defun doc-view-clone-buffer-hook ()
986 ;; FIXME: There are several potential problems linked with reconversion
987 ;; and auto-revert when we have indirect buffers because they share their
988 ;; /tmp cache directory. This sharing is good (you'd rather not reconvert
989 ;; for each clone), but that means that clones need to collaborate a bit.
990 ;; I guess it mostly means: detect when a reconversion process is already
991 ;; running, and run the sentinel in all clones.
993 ;; Maybe the clones should really have a separate /tmp directory
994 ;; so they could have a different resolution and you could use clones
996 (remove-overlays (point-min) (point-max) 'doc-view t
)
997 (if (consp image-mode-winprops-alist
) (setq image-mode-winprops-alist nil
)))
999 (defun doc-view-intersection (l1 l2
)
1001 (dolist (x l1
) (if (memq x l2
) (push x l
)))
1005 (defun doc-view-mode ()
1006 "Major mode in DocView buffers.
1007 You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
1008 toggle between displaying the document or editing it as text.
1009 \\{doc-view-mode-map}"
1012 (let* ((prev-major-mode (if (eq major-mode
'doc-view-mode
)
1013 doc-view-previous-major-mode
1015 (kill-all-local-variables)
1016 (set (make-local-variable 'doc-view-previous-major-mode
) prev-major-mode
))
1018 ;; Figure out the document type.
1020 (when buffer-file-name
1021 (cdr (assoc (file-name-extension buffer-file-name
)
1029 (goto-char (point-min))
1031 ((looking-at "%!") '(ps))
1032 ((looking-at "%PDF") '(pdf))
1033 ((looking-at "\367\002") '(dvi))))))
1034 (set (make-local-variable 'doc-view-doc-type
)
1035 (car (or (doc-view-intersection name-types content-types
)
1036 (when (and name-types content-types
)
1037 (error "Conflicting types: name says %s but content says %s"
1038 name-types content-types
))
1039 name-types content-types
1040 (error "Cannot determine the document type")))))
1042 (doc-view-make-safe-dir doc-view-cache-directory
)
1043 ;; Handle compressed files, remote files, files inside archives
1044 (set (make-local-variable 'doc-view-buffer-file-name
)
1046 (jka-compr-really-do-compress
1048 (file-name-nondirectory
1049 (file-name-sans-extension buffer-file-name
))
1050 doc-view-cache-directory
))
1051 ;; Is the file readable by local processes?
1052 ;; We used to use `file-remote-p' but it's unclear what it's
1053 ;; supposed to return nil for things like local files accessed via
1054 ;; `su' or via file://...
1055 ((let ((file-name-handler-alist nil
))
1056 (not (file-readable-p buffer-file-name
)))
1058 (file-name-nondirectory buffer-file-name
)
1059 doc-view-cache-directory
))
1060 (t buffer-file-name
)))
1061 (when (not (string= doc-view-buffer-file-name buffer-file-name
))
1062 (write-region nil nil doc-view-buffer-file-name
))
1064 (make-local-variable 'doc-view-current-files
)
1065 (make-local-variable 'doc-view-current-converter-process
)
1066 (make-local-variable 'doc-view-current-timer
)
1067 (make-local-variable 'doc-view-current-cache-dir
)
1068 (make-local-variable 'doc-view-current-search-matches
)
1069 (add-hook 'change-major-mode-hook
1070 (lambda () (remove-overlays (point-min) (point-max) 'doc-view t
))
1072 (add-hook 'clone-indirect-buffer-hook
'doc-view-clone-buffer-hook nil t
)
1074 (remove-overlays (point-min) (point-max) 'doc-view t
) ;Just in case.
1075 ;; Keep track of display info ([vh]scroll, page number, overlay, ...)
1076 ;; for each window in which this document is shown.
1077 (add-hook 'image-mode-new-window-functions
1078 'doc-view-new-window-function nil t
)
1079 (image-mode-setup-winprops)
1081 (set (make-local-variable 'mode-line-position
)
1082 '(" P" (:eval
(number-to-string (doc-view-current-page)))
1083 "/" (:eval
(number-to-string (length doc-view-current-files
)))))
1084 ;; Don't scroll unless the user specifically asked for it.
1085 (set (make-local-variable 'auto-hscroll-mode
) nil
)
1086 (set (make-local-variable 'cursor-type
) nil
)
1087 (use-local-map doc-view-mode-map
)
1088 (set (make-local-variable 'after-revert-hook
) 'doc-view-reconvert-doc
)
1089 (set (make-local-variable 'bookmark-make-record-function
)
1090 'doc-view-bookmark-make-record
)
1091 (setq mode-name
"DocView"
1093 major-mode
'doc-view-mode
)
1094 (doc-view-initiate-display)
1095 (run-mode-hooks 'doc-view-mode-hook
))
1098 (define-minor-mode doc-view-minor-mode
1099 "Toggle Doc view minor mode.
1100 With arg, turn Doc view minor mode on if arg is positive, off otherwise.
1101 See the command `doc-view-mode' for more information on this mode."
1102 nil
" DocView" doc-view-minor-mode-map
1104 (when doc-view-minor-mode
1105 (add-hook 'change-major-mode-hook
(lambda () (doc-view-minor-mode -
1)) nil t
)
1108 (substitute-command-keys
1109 "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))
1111 (defun doc-view-clear-cache ()
1112 "Delete the whole cache (`doc-view-cache-directory')."
1114 (dired-delete-file doc-view-cache-directory
'always
))
1116 (defun doc-view-dired-cache ()
1117 "Open `dired' in `doc-view-cache-directory'."
1119 (dired doc-view-cache-directory
))
1122 ;;;; Bookmark integration
1124 (declare-function bookmark-buffer-file-name
"bookmark" ())
1125 (declare-function bookmark-prop-get
"bookmark" (bookmark prop
))
1127 (defun doc-view-bookmark-make-record ()
1128 `((filename .
,(bookmark-buffer-file-name))
1129 (page .
,(doc-view-current-page))
1130 (handler . doc-view-bookmark-jump
)))
1134 (defun doc-view-bookmark-jump (bmk)
1135 ;; This implements the `handler' function interface for record type
1136 ;; returned by `doc-view-bookmark-make-record', which see.
1137 (let ((filename (bookmark-prop-get bmk
'filename
))
1138 (page (bookmark-prop-get bmk
'page
)))
1139 (with-current-buffer (find-file-noselect filename
)
1140 (when (not (eq major-mode
'doc-view-mode
))
1141 (doc-view-toggle-display))
1142 (with-selected-window
1143 (or (get-buffer-window (current-buffer) 0)
1145 (doc-view-goto-page page
))
1146 `((buffer ,(current-buffer)) (position ,1)))))
1152 ;; mode: outline-minor
1155 ;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
1156 ;;; doc-view.el ends here