view lisp/doc-view.el @ 105973:b7d8222914b4

2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-clone-subtree-with-time-shift): Make it work at the end of the buffer. * org-mobile.el (org-mobile-write-checksums): Specify coding system. (org-mobile-timestamp-buffer): Keep local variable/mode line at beginning of buffer. * org-latex.el (org-latex-entities-regexp): Fix typo in regexp. * org.el (org-block-todo-from-children-or-siblings-or-parent) (org-block-todo-from-checkboxes): Do not block changes to a nil TODO state. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-habit.el (org-habit-parse-todo): Indicate which habit is wrongly set up in the error messages. * org-colview.el (org-columns-display-here): Don't try to calculate values if the underlying property is not set. (org-columns-string-to-number): Convert age strings back into fractional days. (org-agenda-colview-summarize): Handle extended summary types properly. * org-colview-xemacs.el (org-columns-display-here): Don't try to calculate values if the underlying property is not set. (org-columns-string-to-number): Convert age strings back into fractional days. (org-agenda-colview-summarize): Handle extended summary types properly. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-exp.el (org-export-format-drawer-function): New variable. (org-export-format-drawer): New function. (org-export-preprocess-string): Pass the backend as a parameter to `org-export-remove-or-extract-drawers'. (org-export-remove-or-extract-drawers): New parameter BACKEND. * org-protocol.el (org-protocol-char-to-string): New defsubst. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-diary-entry-in-org-file): Add error message when no block is selected. * org-latex.el (org-export-latex-links): Check for protectedness in the last matched character, not after the match. * org-datetree.el (org-datetree-find-date-create): Respect restriction when KEEP-RESTRICTION is set. (org-datetree-file-entry-under): New function. (org-datetree-cleanup): New command. 2009-11-13 Dan Davison <davison@stats.ox.ac.uk> * org-src.el (org-edit-src-code): New optional argument context allows calling functions to avoid altering the saved window configuration. (org-edit-src-exit): Do not restore window configuration when this function is used in the context of saving the edit buffer. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-out, org-clock-cancel): Revert to instances to switching to with-current-buffer, because these seem to cause problems - no idea why. * org-agenda.el (org-agenda-add-entry-to-org-agenda-diary-file): Require diary-lib for (diary-date-display-form). 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-log-reschedule, org-log-redeadline): New options. (org-log-note-headings): Add templates for rescheduling and deadline changing. (org-startup-options): Add in-buffer settings for logging changing schedule and deadline time stamps. (org-deadline, org-schedule): Check for existing date and arrange for logging if the user requests it. (org-add-log-note): Prepare proper note buffers for rescheduling and deadline changes. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-diary-entry-in-org-file) (org-agenda-add-entry-to-org-agenda-diary-file) (org-agenda-insert-diary-make-new-entry): New functions. (org-agenda-diary-entry): Call `org-agenda-diary-entry-in-org-file' when appropriate. * org.el (org-calendar-insert-diary-entry-key): New option. (org-agenda-diary-file): New option. ("calendar"): Install our insertion function in the calendar. * org-remember.el (org-datetree): Require. (org-remember-templates): Add new positioning option. (org-remember-reference-date): New variable. (org-remember-apply-template): Store the reference date in a local variable. (org-remember-handler): Implement date tree positioning of entries. * org-datetree.el: New file. * org-latex.el (org-export-latex-preprocess): Protect targets in verbatim emphasis. * org-html.el (org-export-as-html): Protect targets in verbatim emphasis. * org-docbook.el (org-export-as-docbook): Protect targets in verbatim emphasis. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-show-notification): Handle messages that contain a percent character. * org-remember.el (org-remember-apply-template): Turn of partial completion. * org-mobile.el (org-mobile-before-process-capture-hook): New hook. (org-mobile-pull): Run `org-mobile-before-process-capture-hook'. * org.el (org-indent-mode): Define variable already in org.el. (org-unfontify-region): Remove line-prefix and wrap-prefix properties only if org-indent-mode is active. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-icalendar.el (org-print-icalendar-entries): Save match data around call to verify function. (org-print-icalendar-entries): Add a call to the verification function. * org.el (org-speedbar-set-agenda-restriction): Remove unnecessary save-restrivtion' form. 2009-11-13 Dan Davison <davison@stats.ox.ac.uk> * org-exp.el (org-export-format-source-code-or-example): restrict scope of preserve-indentp to the let binding. (org-src): require org-src, since org-src-preserve-indentation is used. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-timer.el (org-timer-set-timer): Set variables org-timer-timer[123] correctly. * org-mobile.el (org-mobile-files-alist): Make it work when `agenda-archives' is included in `org-agenda-text-search-extra-files'. (org-mobile-push): Restore agenda after mobile push. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-clock.el (org-resolve-clocks-if-idle): Another fix to the way the amount of idle time is presented in the minibuffer. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-icalendar.el (org-print-icalendar-entries): Use org-icalendar-verify-function only if non-nil. * org.el (org-refile): Refile to clock only if the prefix arg is 2. (org-sparse-tree): Fix docstring to be in line with prompt. (org-update-parent-todo-statistics): Call `org-after-todo-statistics-hook' on each level. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-remember.el (org-remember-apply-template): Make sure the buffer exists. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-tab-ind-state): New variable. (org-cycle-level): New function. (org-cycle-level-after-item/entry-creation): New option. (org-flag-subtree): New function. (org-hide-archived-subtrees): Call `org-flag-subtree'. (org-set-effort): Indexed access. * org-list.el (org-cycle-item-indentation): New function. * org.el (org-refile): Make prefix argument 2 refile to current clock. (org-priority): Interpret action `remove' as call to remove the priority cookie. * org-remember.el (org-remember-apply-template): Don't depend on buffer name being like file name. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-play-sound): Expand file in org-clock-sound, to allow ~ for home. * org-remember.el (org-remember-handler): Set text-before-node-creation even if this already looks like a node, because the string might be needed on non-org-mode target files. * org-agenda.el (org-agenda-open-link): Make this work in agenda clocktables. (org-agenda-switch-to): Follow a link at point if org-return-follows-link' is set and there is nothing else to do in this line. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-colview-xemacs.el: Add in changes from org-colview.el 2009-11-13 Dan Davison <davison@stats.ox.ac.uk> * org-exp-blocks.el: Modify split separator regexp to avoid empty strings. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-colview.el (org-columns-new): Make this work with the new operators. (org-columns-store-format): Make this work with the new operators. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-src.el (org-src-preserve-indentation): Document that this variable is also used during export. * org-exp.el (org-export-format-source-code-or-example): Preserve indentation if a block has a -i option, or if `org-src-preserve-indentation' is set. * org-exp-blocks.el (org-export-blocks-preprocess): Preserve indentation if a block has a -i option, or if `org-src-preserve-indentation' is set. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-mode-map): Define the new archiving keys. (org-speed-commands-default): Define an archiving key in the speed command map. (org-org-menu): Improve the menu structure concerning archiving. * org-archive.el (org-archive-subtree-default-with-confirmation): New command. * org-agenda.el (org-agenda-mode-map): Define the new archiving keys. (org-agenda-menu): Add the new archiving commands to the menu. (org-agenda-archive-default) (org-agenda-archive-default-with-confirmation): New commands. (org-agenda-archive, org-agenda-archive-to-archive-sibling): Just call `org-agenda-archive-with'. (org-agenda-archive-with): New function. * org-table.el (org-table-convert-region): Inert spaces around "|" to avoid line beginnings like "|-1" which will be mistaken as hlines. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-offer-links-in-entry): Return nil if there are no links, t if a link has been selected. (org-open-at-point): Open attachment directory when called in the headline and there are no links in the entry body. (org-speed-commands-default): Add "o" for open-at-point as a speed command. * org-attach.el (org-attach-reveal): Optional prefix arg IF-EXISTS, which avoids creating the attachment directory if it does not yet exist. * org-agenda.el (org-agenda, org-run-agenda-series): Evaluate MATCH. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el ("abbrev"): Work with abbrev tables only after they have been loaded. * org-list.el (org-list-send-list): Fix bug related to match data. * org-latex.el (org-export-latex-fontify): Apply verbatim emphasis. (org-export-latex-make-header): Insert \obeylines if line breaks should be preserved. * org-exp.el (org-export-protect-verbatim): Add an `org-verbatim-emph' property to such text. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-icalendar.el (org-icalendar-use-plain-timestamp): New option. (org-print-icalendar-entries): Skip entries where the timestamp is not a deadline and not scheduled, if the user requests that. * org-latex.el (org-export-latex-quotation-marks): Allow a bracket before an opening quote. * org-archive.el (org-archive-subtree): Keep archive after archiving something. * org-id.el (org-id-update-id-locations): Add archive files if that is required by `org-id-extra-files'. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-src.el (org-src-window-setup): New option. (org-src-switch-to-buffer): New function. (org-edit-src-exit): Add optional argument CONTEXT and use it to restore window configuration. (org-edit-src-code, org-edit-src-continue, org-edit-src-exit): Call `org-src-switch-to-buffer'. * org.el (org-default-properties): Add STYLE property. (org-files-list): Use the function call to get the files. (org-additional-option-like-keywords): Add SETUPFILE to completion list. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-table.el (org-table-convert-region): Correctly interpret quoting in csv import. * org.el (org-icompleting-read): Make iswitchb completion work with lists and tables. * org-agenda.el (org-agenda-add-entry-text): Never add entry text while pushing the mobile agenda. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-clock.el (org-clock-auto-clock-resolution): Now takes three values: nil, t and `when-no-clock-is-running'. (org-clock-in): Use `org-clock-auto-clock-resolution' to determine whether or not to resolve Org buffers on clock in. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-colview.el (org-format-time-period): Function to format times in fractional days for display. (org-columns-display-here): Add support for showing a calculated value in place of the property. (org-columns): Set `org-columns-time' to the current time so time difference calculations will work. (org-columns-time): Use to store the current time when column view is displayed, so all time differences will use the same reference point. (org-columns-compile-map): There is now an extra position in each entry specifying the function to use to calculate the displayed value for the non-calculated properties in the column, (org-columns-compute-all): Set `org-columns-time' to the current time so time difference calculations will work. (org-columns-compute): Handle column operators where the values used are calculated from the underlying property. (org-columns-number-to-string): Handle the 'age' column format (org-columns-string-to-number): Correct the function name (was org-column...). Add support for the 'age' column format. (org-columns-compile-format): Support the additional parameter in org-columns-compile-map. 2009-11-13 Bastien Guerry <bzg@altern.org> * org.el (org-mode-hook): Turn `org-mode-hook' into a customizable variable. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-has-been-used): New variable. (org-clock-in): Set `org-clock-has-been-used'. (org-clock-save): Save only if clock data has been used or created during this session. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-persist): New value, to store only the clock history. (org-clock-save): Don't save the clock if only the history should be stored. (org-clock-load): Turn off John Wiegley's auto resolving mechanism when restoring a saved clock. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-clock.el (org-clock-display, org-clock-put-overlay): Use `org-time-clock-use-fractional'. * org.el (org-time-clocksum-use-fractional) (org-time-clocksum-fractional-format): Two new customizable variables which allow the user to select fractional times (1.25 instead of 1:25) in the `org-clock-display' report. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-ascii.el (org-export-ascii-table-keep-all-vertical-lines): New option. * org.el (org-tag-alist): Fix customization type. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-mobile.el (org-mobile-update-checksum-for-capture-file): Make sure the regexp search can fail without throwing an error. (org-mobile-apply): Save the inbox buffer after removing successfully applied changes. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-clock.el (org-resolve-clocks-if-idle): Fix to the way idle time is reported after the user comes back (but before they resolve time). * org.el (org-get-repeat): Change so that this function can be called with either `org-scheduled-string' or `org-deadline-string'. * org-clock.el (org-clock-auto-clock-resolution): Renamed `org-clock-disable-clock-resolution', since negatives don't sound good in customization variables. (org-clock-in): Don't use the auto-resolution logic if the user is clocking into a different task while an active clock is running. This then allows the default behavior of clocking out of the open task and then into the new task. * org.el (org-modules): Made this variable more consistent, since it was referring to Org, OrgMode and Org-mode, whereas the docs for the variable always refer to Org-mode. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org.el (org-repeat-re): The changed org-repeat-re no longer matched simple +2d type repeaters. Fix it so it does. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-latex.el (org-export-latex-preprocess): Protect the vspace macro in the VERSE environment. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-habit.el (org-habit-get-priority): A new function that determines the relative priority of a habit, based on how long past its scheduled date it is, and how near the deadline is. * org-agenda.el (org-agenda-get-scheduled): Set habit priority using `org-habit-get-priority'. * org-habit.el (org-habit-build-graph): Start displaying colors from the first scheduled date, if that date is earlier than the first completion date. * org-habit.el: Changed all "color" variables to faces, and made them appropriate for light and dark backgrounds. * org-habit.el (org-habit-duration-to-days): Made this function more general. (org-habit-parse-todo): Parse the new ".+N/N" style repeater. * org-agenda.el (org-agenda-get-deadlines): Removed all mention of habits, since they don't use DEADLINE anymore. * org.el (org-repeat-re, org-display-custom-time) (org-timestamp-change): Extended to support the new ".+N/N" syntax, used for habits. * org-clock.el (org-clock-resolve-clock): Fixed an incorrect variable reference. * org-agenda.el (org-agenda-set-mode-name): Show Habit in the modeline when habits are being displayed (if that module is being loaded). 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-clock.el (org-x11-idle-seconds): Add a method to get the X11 idle time using the xscreensaver extension. (org-user-idle-seconds): Use X11 idle time if available. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-next-line): New command. (org-agenda-previous-line): New commands. (org-agenda-show-and-scroll-up, org-agenda-show-scroll-down): New commands. (org-agenda-follow-mode): Do the follow immediately if the mode is turned on here. (previous-line, next-line): Replace keys with the corresponding org functions. (org-agenda-mode-map): Bind backspace and delete to the scrolling command. * org.el (org-icompleting-read): Turn off partial completion mode for the duration of this completion round. * org-latex.el (org-export-latex-fontify-headline): Protect TeX macros in author lines and similar stuff. * org.el (org-file-tags): Fix docstring. (org-get-buffer-tags): Add the #+FILETAGS tags. ("ecb"): Maks ecb show context after jumping into an Org file. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-agenda.el (org-finalize-agenda): Draw habit consistency graphs after everything else in the buffer has been setup. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-mobile.el (org-mobile-apply): Count success and failure. * org.el (org-indent-line-function): Fix regexp replace problem. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-clock.el (org-clock-disable-clock-resolution): New customization variable that disable automatic clock resolution on clock in. (org-clock-in): If `org-clock-disable-clock-resolution' is set, do not automatically resolve anything. This is does not affect idle-time resolution, however, if `org-clock-idle-time' is set. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-habit.el: New file, which implements code to build a "habit consistency graph". * org-agenda.el (org-agenda-get-deadlines) (org-agenda-get-scheduled): Display consistency graphs when outputting habits into the agenda. The graphs are always relative to the current time. (org-format-agenda-item): Added new parameter `habitp', which indicates whether we are formatting a habit or not. Do not display "extra" leading information if habitp is true. * org.el (org-repeat-re): Improved regexp to include .+ and ++ leaders for repeat strings. (org-get-repeat): Now takes a string parameter `tagline', so the caller can obtain the SCHEDULED repeat, or the DEADLINE repeat. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-agenda.el (org-agenda-auto-exclude-function): New customization variable for allowing the user to create an "auto exclusion" filter for doing context-aware auto tag filtering. (org-agenda-filter-by-tag): Changes to support the use of `org-agenda-auto-exclude-function'. See the new manual addition,. 2009-11-13 John Wiegley <johnw@newartisans.com> * org.el (org-files-list): Don't attempt to return a file name for Org buffers which have no associated file. * org-agenda.el (org-agenda-do-action): Fixed a typo. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-mobile.el (org-mobile-locate-entry): Interpret files relative to org-directory. (org-mobile-inbox-for-pull): Document the best location for this file. (org-mobile-check-setup): Verify `org-directory'. (org-mobile-create-index-file): Sort the files to be listed in index.org. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org.el (org-fast-tag-selection): Add a way to display a description for a tag group. This is done by adding a string to either the startgroup or endgroup cell. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-resolve, org-resolve-clocks) (org-emacs-idle-seconds): Use `org-float-time' instead of `time-to-seconds' 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-sorting-strategy): Fix customization type. * org.el (org-pre-cycle-hook): Document that `empty' can also be the value of ARG when doing local cycling. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-clock.el (org-clock-resolve-clock): If keeping or subtracting time results in a clock out at a time in the past, and if the resolution occurred due to idleness or invoking `M-x org-resolve-clocks', remember that past moment in time. On the next clock in, the user will be prompted to see if they want to back-date their new clock to then. (org-clock-resolve): Do not jump the user to the location of a dangling clock if the resolution is occuring due to an idle timeout. In that case there is typically only one dangling clock, the active one, and there is no value gained by shuffling their windows around to show it to them. Being prompted to resolve an idle clock should be as inobtrusive as possible. (org-resolve-clocks-if-idle): New function that resolves only the currently active clock if the user has exceeded the time returned by `org-user-idle-seconds', based on the value of `org-clock-idle-time'. (org-clock-in): If, after resolving clocks, (org-clock-out): Cancel the `org-clock-idle-timer' on clock out. * org-clock.el (org-clock-resolve-clock): New function that resolves a clock to a specific time, closing or resuming as need be, and possibly even starting a new clock. (org-clock-resolve): New function used by `org-resolve-clocks' that sets up for the call to `org-clock-resolve-clock'. It determines the time to resolve to based on a single-character selection from the user to either keep time, subtract away time or cancel the clock. (org-resolve-clocks): New user command which resolves dangling clocks -- that is, open but not active -- anywhere in the file list returned by `org-files-list'. (org-clock-in): Automatically resolve dangling clocks whenever a user clocks in. (org-clock-cancel): If the user cancels the solely clock in a LOGBOOK, remove the empty drawer. * org-clock.el (org-clock-idle-time): New user customizable option for detecting whether the user has left a clock idle. Note: it is only used in this commit to test whether it's worthwhile to check OS X to get the Mac user's current idle time. If the Emacs idle time is less than the value, the user hasn't been away long enough to be worth checking (a more expensive test than just getting Emacs idle time). (org-user-idle-seconds, org-mac-idle-seconds) (org-emacs-idle-seconds): This three functions, in conjunction with the user customization variable `org-clock-idle-time', return the number of seconds (as a floating point) that the user has been away from their Emacs (or, if running on OS X, their computer). * org-clock.el (org-find-open-clocks): New function that returns a list of all open clocks in the given FILE. Note that each clock it returns is a cons cell of the format (MARKER . START-TIME). This "clock" value is used by several of the new clock module utility functions. (org-is-active-clock): New inline function which tests whether the given clock value is the same as the currently active clock. Returns non-nil if this is the case. (org-with-clock-position): New macro that evaluates FORMS with point in the buffer and at the position of the given clock. Changes to the current clock are global. (org-with-clock): New macro that evaluates FORMS with point in the buffer and at the position of the given clock. However, changes to the current clock are local and have no effect on the user's active clock. This allows, for example, far any clock to be cancelled without cancelling the active clock. (org-clock-clock-in): New inline function that switches the active clock to the given clock. If either the argument RESUME, or the global `org-clock-in-resume', are non-nil, it will resume a clock that was previously left open. (org-clock-clock-out): New inline function that clocks out the given clock value without affecting the currently active clock. (org-clock-clock-cancel): New inline function that cancels the given clock value without affecting the currently active clock. * org-clock.el (org-clock-in): Before creating `org-clock-mode-line-timer', check to make sure an older timer is not currently running. (org-clock-out): Accept new third parameter `at-time', which permits a clock to be clocked out at a specific time. Note that no attempt is made to verify that the clock out time is later than the clock in time. * org.el (org-files-list): New utility function for returning a list of all open org-mode buffers, plus all files used to build the agenda buffer. Note that not all the files will necessarily be visited by a buffer at time of call. (org-entry-beginning-position): Like the function `line-beginning-position', this inline function returns the beginning position of the current heading/entry. (org-entry-end-position): Like the function `line-end-position', this inline function returns the end position of the current heading/entry. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-list): Mark the all-todo items line as a header line. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-exp.el (org-inlinetask-remove-END-maybe): Declare function. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-filter-make-matcher): Allow to filter entries that have no tags. (org-agenda-search-view): New customize group. (org-agenda-search-view-search-words-only): New option. (org-search-view): Implement substring search. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-outline-level): Add doc string. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-inlinetask.el (org-inlinetask-export): Re-introduce variable. (org-inlinetask-export-handler): Only export inline task if the user option calls for it. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-exp.el (org-export-handle-export-tags): Remove inlinetask END if present. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-latex.el (org-export-latex-tables): Don't format in protected regions. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-src.el (org-edit-src-code) (org-edit-src-find-region-and-lang, org-edit-src-exit): Handle macro editing. * org-agenda.el (org-prefix-category-max-length): New variable. (org-format-agenda-item): Use `org-prefix-category-max-length'. (org-compile-prefix-format): Set `org-prefix-category-max-length'. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-mobile.el (org-mobile-create-index-file): Improve the listing of tags and todo keywords. * org-latex.el (org-export-latex-format-image): New function. (org-export-latex-links): Use `org-export-latex-format-image'. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-inlinetask.el (org-inlinetask-get-current-indentation) (org-inlinetask-remove-terminator): New functions. (org-inlinetask-export-handler): Terminate the description list. * org-exp.el (org-export-select-backend-specific-text): Remove the region markers. * org-inlinetask.el (org-inlinetask-export-handler): fix bug for tasks without content. * org-clock.el: Make sure the clock-in target position does not move to a different node by widening the buffer. * org-html.el (org-export-html-format-image): Wrap image into figure div only when there is a caption. * org-archive.el (org-archive-mark-done): Change default value to nil. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-context): Call `bobp', not `eobp'. * org-clock.el (org-clock-cancel): Remove quotes from marker variables. * org.el (org-read-date-prefer-future): New allowed value `time'. (org-read-date-analyze): Shift day to tomorrow depending on time entered and value of `org-read-date-prefer-future'.
author Carsten Dominik <dominik@science.uva.nl>
date Fri, 13 Nov 2009 08:37:55 +0000
parents 53e13148fb68
children 936dfb675acf
line wrap: on
line source

;;; doc-view.el --- View PDF/PostScript/DVI files in Emacs

;; Copyright (C) 2007, 2008, 2009 Free Software Foundation, Inc.
;;
;; Author: Tassilo Horn <tassilo@member.fsf.org>
;; Maintainer: Tassilo Horn <tassilo@member.fsf.org>
;; Keywords: files, pdf, ps, dvi

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Requirements:

;; doc-view.el requires GNU Emacs 22.1 or newer.  You also need Ghostscript,
;; `dvipdf' (comes with Ghostscript) or `dvipdfm' (comes with teTeX or TeXLive)
;; and `pdftotext', which comes with xpdf (http://www.foolabs.com/xpdf/) or
;; poppler (http://poppler.freedesktop.org/).

;;; Commentary:

;; DocView is a document viewer for Emacs.  It converts PDF, PS and DVI files
;; to a set of PNG files, one PNG for each page, and displays the PNG images
;; inside an Emacs buffer.  This buffer uses `doc-view-mode' which provides
;; convenient key bindings for browsing the document.
;;
;; To use it simply open a document file with
;;
;;     C-x C-f ~/path/to/document RET
;;
;; and the document will be converted and displayed, if your emacs supports png
;; images.  With `C-c C-c' you can toggle between the rendered images
;; representation and the source text representation of the document.
;;
;; Since conversion may take some time all the PNG images are cached in a
;; subdirectory of `doc-view-cache-directory' and reused when you want to view
;; that file again.  To reconvert a document hit `g' (`doc-view-reconvert-doc')
;; when displaying the document.  To delete all cached files use
;; `doc-view-clear-cache'.  To open the cache with dired, so that you can tidy
;; it out use `doc-view-dired-cache'.
;;
;; When conversion in underway the first page will be displayed as soon as it
;; is available and the available pages are refreshed every
;; `doc-view-conversion-refresh-interval' seconds.  If that variable is nil the
;; pages won't be displayed before conversion of the document finished
;; completely.
;;
;; DocView lets you select a slice of the displayed pages.  This slice will be
;; remembered and applied to all pages of the current document.  This enables
;; you to cut away the margins of a document to save some space.  To select a
;; slice you can use `doc-view-set-slice' (bound to `s s') which will query you
;; for the coordinates of the slice's top-left corner and its width and height.
;; A much more convenient way to do the same is offered by the command
;; `doc-view-set-slice-using-mouse' (bound to `s m').  After invocation you
;; only have to press mouse-1 at the top-left corner and drag it to the
;; bottom-right corner of the desired slice.  To reset the slice use
;; `doc-view-reset-slice' (bound to `s r').
;;
;; You can also search within the document.  The command `doc-view-search'
;; (bound to `C-s') queries for a search regexp and initializes a list of all
;; matching pages and messages how many match-pages were found.  After that you
;; can jump to the next page containing a match with an additional `C-s'.  With
;; `C-r' you can do the same, but backwards.  To search for a new regexp give a
;; prefix arg to one of the search functions, e.g. by typing `C-u C-s'.  The
;; searching works by using a plain text representation of the document.  If
;; that doesn't already exist the first invocation of `doc-view-search' (or
;; `doc-view-search-backward') starts the conversion.  When that finishes and
;; you're still viewing the document (i.e. you didn't switch to another buffer)
;; you're queried for the regexp then.
;;
;; Dired users can simply hit `v' on a document file.  If it's a PS, PDF or DVI
;; it will be opened using `doc-view-mode'.
;;

;;; Configuration:

;; If the images are too small or too big you should set the "-rXXX" option in
;; `doc-view-ghostscript-options' to another value.  (The bigger your screen,
;; the higher the value.)
;;
;; This and all other options can be set with the customization interface.
;; Simply do
;;
;;     M-x customize-group RET doc-view RET
;;
;; and modify them to your needs.

;;; Todo:

;; - add print command.
;; - share more code with image-mode.
;; - better menu.
;; - Bind slicing to a drag event.
;; - doc-view-fit-doc-to-window and doc-view-fit-window-to-doc?
;; - zoom the region around the cursor (like xdvi).
;; - get rid of the silly arrow in the fringe.
;; - improve anti-aliasing (pdf-utils gets it better).

;;;; About isearch support

;; I tried implementing isearch by setting
;; `isearch-search-fun-function' buffer-locally, but that didn't
;; work too good.  The function doing the real search was called
;; endlessly somehow.  But even if we'd get that working no real
;; isearch feeling comes up due to the missing match highlighting.
;; Currently I display all lines containing a match in a tooltip and
;; each C-s or C-r jumps directly to the next/previous page with a
;; match.  With isearch we could only display the current match.  So
;; we had to decide if another C-s jumps to the next page with a
;; match (thus only the first match in a page will be displayed in a
;; tooltip) or to the next match, which would do nothing visible
;; (except the tooltip) if the next match is on the same page.

;; And it's much slower than the current search facility, because
;; isearch really searches for each step forward or backward wheras
;; the current approach searches once and then it knows to which
;; pages to jump.

;; Anyway, if someone with better isearch knowledge wants to give it a try,
;; feel free to do it.  --Tassilo

;;; Code:

(eval-when-compile (require 'cl))
(require 'dired)
(require 'image-mode)
(require 'jka-compr)

;;;; Customization Options

(defgroup doc-view nil
  "In-buffer viewer for PDF, PostScript and DVI files."
  :link '(function-link doc-view)
  :version "22.2"
  :group 'applications
  :group 'multimedia
  :prefix "doc-view-")

(defcustom doc-view-ghostscript-program (executable-find "gs")
  "Program to convert PS and PDF files to PNG."
  :type 'file
  :group 'doc-view)

(defcustom doc-view-ghostscript-options
  '("-dSAFER" ;; Avoid security problems when rendering files from untrusted
	      ;; sources.
    "-dNOPAUSE" "-sDEVICE=png16m" "-dTextAlphaBits=4"
    "-dBATCH" "-dGraphicsAlphaBits=4" "-dQUIET")
  "A list of options to give to ghostscript."
  :type '(repeat string)
  :group 'doc-view)

(defcustom doc-view-resolution 100
  "Dots per inch resolution used to render the documents.
Higher values result in larger images."
  :type 'number
  :group 'doc-view)

(defcustom doc-view-dvipdfm-program (executable-find "dvipdfm")
  "Program to convert DVI files to PDF.

DVI file will be converted to PDF before the resulting PDF is
converted to PNG.

If this and `doc-view-dvipdf-program' are set,
`doc-view-dvipdf-program' will be preferred."
  :type 'file
  :group 'doc-view)

(defcustom doc-view-dvipdf-program (executable-find "dvipdf")
  "Program to convert DVI files to PDF.

DVI file will be converted to PDF before the resulting PDF is
converted to PNG.

If this and `doc-view-dvipdfm-program' are set,
`doc-view-dvipdf-program' will be preferred."
  :type 'file
  :group 'doc-view)

(defcustom doc-view-ps2pdf-program (executable-find "ps2pdf")
  "Program to convert PS files to PDF.

PS files will be converted to PDF before searching is possible."
  :type 'file
  :group 'doc-view)

(defcustom doc-view-pdftotext-program (executable-find "pdftotext")
  "Program to convert PDF files to plain text.

Needed for searching."
  :type 'file
  :group 'doc-view)

(defcustom doc-view-cache-directory
  (expand-file-name (format "docview%d" (user-uid))
		    temporary-file-directory)
  "The base directory, where the PNG images will be saved."
  :type 'directory
  :group 'doc-view)

(defvar doc-view-conversion-buffer " *doc-view conversion output*"
  "The buffer where messages from the converter programs go to.")

(defcustom doc-view-conversion-refresh-interval 1
  "Interval in seconds between refreshes of the DocView buffer while converting.
After such a refresh newly converted pages will be available for
viewing.  If set to nil there won't be any refreshes and the
pages won't be displayed before conversion of the whole document
has finished."
  :type 'integer
  :group 'doc-view)

;;;; Internal Variables

(defun doc-view-new-window-function (winprops)
  (let ((ol (image-mode-window-get 'overlay winprops)))
    (if ol
        (setq ol (copy-overlay ol))
      (assert (not (get-char-property (point-min) 'display)))
      (setq ol (make-overlay (point-min) (point-max) nil t))
      (overlay-put ol 'doc-view t))
    (overlay-put ol 'window (car winprops))
    (image-mode-window-put 'overlay ol winprops)))

(defvar doc-view-current-files nil
  "Only used internally.")
(make-variable-buffer-local 'doc-view-current-files)

(defvar doc-view-current-converter-processes nil
  "Only used internally.")
(make-variable-buffer-local 'doc-view-current-converter-processes)

(defvar doc-view-current-timer nil
  "Only used internally.")
(make-variable-buffer-local 'doc-view-current-timer)

(defvar doc-view-current-cache-dir nil
  "Only used internally.")
(make-variable-buffer-local 'doc-view-current-cache-dir)

(defvar doc-view-current-search-matches nil
  "Only used internally.")
(make-variable-buffer-local 'doc-view-current-search-matches)

(defvar doc-view-pending-cache-flush nil
  "Only used internally.")

(defvar doc-view-previous-major-mode nil
  "Only used internally.")

(defvar doc-view-buffer-file-name nil
  "Only used internally.
The file name used for conversion.  Normally it's the same as
`buffer-file-name', but for remote files, compressed files and
files inside an archive it is a temporary copy of
the (uncompressed, extracted) file residing in
`doc-view-cache-directory'.")

(defvar doc-view-doc-type nil
  "The type of document in the current buffer.
Can be `dvi', `pdf', or `ps'.")

;;;; DocView Keymaps

(defvar doc-view-mode-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent map image-mode-map)
    ;; Navigation in the document
    (define-key map (kbd "n")         'doc-view-next-page)
    (define-key map (kbd "p")         'doc-view-previous-page)
    (define-key map (kbd "<next>")    'forward-page)
    (define-key map (kbd "<prior>")   'backward-page)
    (define-key map [remap forward-page]  'doc-view-next-page)
    (define-key map [remap backward-page] 'doc-view-previous-page)
    (define-key map (kbd "SPC")       'doc-view-scroll-up-or-next-page)
    (define-key map (kbd "DEL")       'doc-view-scroll-down-or-previous-page)
    (define-key map (kbd "M-<")       'doc-view-first-page)
    (define-key map (kbd "M->")       'doc-view-last-page)
    (define-key map [remap goto-line] 'doc-view-goto-page)
    (define-key map (kbd "RET")       'image-next-line)
    ;; Zoom in/out.
    (define-key map "+"               'doc-view-enlarge)
    (define-key map "-"               'doc-view-shrink)
    ;; Killing the buffer (and the process)
    (define-key map (kbd "k")         'doc-view-kill-proc-and-buffer)
    (define-key map (kbd "K")         'doc-view-kill-proc)
    ;; Slicing the image
    (define-key map (kbd "s s")       'doc-view-set-slice)
    (define-key map (kbd "s m")       'doc-view-set-slice-using-mouse)
    (define-key map (kbd "s r")       'doc-view-reset-slice)
    ;; Searching
    (define-key map (kbd "C-s")       'doc-view-search)
    (define-key map (kbd "<find>")    'doc-view-search)
    (define-key map (kbd "C-r")       'doc-view-search-backward)
    ;; Show the tooltip
    (define-key map (kbd "C-t")       'doc-view-show-tooltip)
    ;; Toggle between text and image display or editing
    (define-key map (kbd "C-c C-c")   'doc-view-toggle-display)
    ;; Open a new buffer with doc's text contents
    (define-key map (kbd "C-c C-t")   'doc-view-open-text)
    ;; Reconvert the current document
    (define-key map (kbd "g")         'revert-buffer)
    (define-key map (kbd "r")         'revert-buffer)
    map)
  "Keymap used by `doc-view-mode' when displaying a doc as a set of images.")

(easy-menu-define doc-view-menu doc-view-mode-map
  "Menu for Doc View mode."
  '("DocView"
    ["Set Slice"		doc-view-set-slice-using-mouse]
    ["Set Slice (manual)"	doc-view-set-slice]
    ["Reset Slice"		doc-view-reset-slice]
    "---"
    ["Search"			doc-view-search]
    ["Search Backwards"         doc-view-search-backward]
    ["Toggle display"		doc-view-toggle-display]
    ))

(defvar doc-view-minor-mode-map
  (let ((map (make-sparse-keymap)))
    ;; Toggle between text and image display or editing
    (define-key map (kbd "C-c C-c") 'doc-view-toggle-display)
    map)
  "Keymap used by `doc-minor-view-mode'.")

;;;; Navigation Commands

(defmacro doc-view-current-page (&optional win)
  `(image-mode-window-get 'page ,win))
(defmacro doc-view-current-info () `(image-mode-window-get 'info))
(defmacro doc-view-current-overlay () `(image-mode-window-get 'overlay))
(defmacro doc-view-current-image () `(image-mode-window-get 'image))
(defmacro doc-view-current-slice () `(image-mode-window-get 'slice))

(defun doc-view-goto-page (page)
  "View the page given by PAGE."
  (interactive "nPage: ")
  (let ((len (length doc-view-current-files))
	(hscroll (window-hscroll)))
    (if (< page 1)
	(setq page 1)
      (when (and (> page len)
                 ;; As long as the converter is running, we don't know
                 ;; how many pages will be available.
                 (null doc-view-current-converter-processes))
	(setq page len)))
    (setf (doc-view-current-page) page
	  (doc-view-current-info)
	  (concat
	   (propertize
	    (format "Page %d of %d." page len) 'face 'bold)
	   ;; Tell user if converting isn't finished yet
	   (if doc-view-current-converter-processes
	       " (still converting...)\n"
	     "\n")
	   ;; Display context infos if this page matches the last search
	   (when (and doc-view-current-search-matches
		      (assq page doc-view-current-search-matches))
	     (concat (propertize "Search matches:\n" 'face 'bold)
		     (let ((contexts ""))
		       (dolist (m (cdr (assq page
					     doc-view-current-search-matches)))
			 (setq contexts (concat contexts "  - \"" m "\"\n")))
		       contexts)))))
    ;; Update the buffer
    ;; We used to find the file name from doc-view-current-files but
    ;; that's not right if the pages are not generated sequentially
    ;; or if the page isn't in doc-view-current-files yet.
    (let ((file (expand-file-name (format "page-%d.png" page)
                                  (doc-view-current-cache-dir))))
      (doc-view-insert-image file :pointer 'arrow)
      (set-window-hscroll (selected-window) hscroll)
      (when (and (not (file-exists-p file))
                 doc-view-current-converter-processes)
        ;; The PNG file hasn't been generated yet.
        (doc-view-pdf->png-1 doc-view-buffer-file-name file page
                             (lexical-let ((page page)
                                           (win (selected-window)))
                               (lambda ()
                                 (and (eq (current-buffer) (window-buffer win))
                                      ;; If we changed page in the mean
                                      ;; time, don't mess things up.
                                      (eq (doc-view-current-page win) page)
                                      (with-selected-window win
                                        (doc-view-goto-page page))))))))
    (overlay-put (doc-view-current-overlay)
                 'help-echo (doc-view-current-info))))

(defun doc-view-next-page (&optional arg)
  "Browse ARG pages forward."
  (interactive "p")
  (doc-view-goto-page (+ (doc-view-current-page) (or arg 1))))

(defun doc-view-previous-page (&optional arg)
  "Browse ARG pages backward."
  (interactive "p")
  (doc-view-goto-page (- (doc-view-current-page) (or arg 1))))

(defun doc-view-first-page ()
  "View the first page."
  (interactive)
  (doc-view-goto-page 1))

(defun doc-view-last-page ()
  "View the last page."
  (interactive)
  (doc-view-goto-page (length doc-view-current-files)))

(defun doc-view-scroll-up-or-next-page ()
  "Scroll page up if possible, else goto next page."
  (interactive)
  (let ((hscroll (window-hscroll))
	(cur-page (doc-view-current-page)))
    (when (= (window-vscroll) (image-scroll-up nil))
      (doc-view-next-page)
      (when (/= cur-page (doc-view-current-page))
	(image-bob)
	(image-bol 1))
      (set-window-hscroll (selected-window) hscroll))))

(defun doc-view-scroll-down-or-previous-page ()
  "Scroll page down if possible, else goto previous page."
  (interactive)
  (let ((hscroll (window-hscroll))
	(cur-page (doc-view-current-page)))
    (when (= (window-vscroll) (image-scroll-down nil))
      (doc-view-previous-page)
      (when (/= cur-page (doc-view-current-page))
	(image-eob)
	(image-bol 1))
      (set-window-hscroll (selected-window) hscroll))))

;;;; Utility Functions

(defun doc-view-kill-proc ()
  "Kill the current converter process(es)."
  (interactive)
  (while doc-view-current-converter-processes
    (ignore-errors ;; Maybe it's dead already?
      (kill-process (pop doc-view-current-converter-processes))))
  (when doc-view-current-timer
    (cancel-timer doc-view-current-timer)
    (setq doc-view-current-timer nil))
  (setq mode-line-process nil))

(defun doc-view-kill-proc-and-buffer ()
  "Kill the current converter process and buffer."
  (interactive)
  (doc-view-kill-proc)
  (when (eq major-mode 'doc-view-mode)
    (kill-buffer (current-buffer))))

(defun doc-view-make-safe-dir (dir)
  (condition-case nil
      (let ((umask (default-file-modes)))
        (unwind-protect
            (progn
              ;; Create temp files with strict access rights.  It's easy to
              ;; loosen them later, whereas it's impossible to close the
              ;; time-window of loose permissions otherwise.
              (set-default-file-modes #o0700)
              (make-directory dir))
          ;; Reset the umask.
          (set-default-file-modes umask)))
    (file-already-exists
     (if (file-symlink-p dir)
         (error "Danger: %s points to a symbolic link" dir))
     ;; In case it was created earlier with looser rights.
     ;; We could check the mode info returned by file-attributes, but it's
     ;; a pain to parse and it may not tell you what we want under
     ;; non-standard file-systems.  So let's just say what we want and let
     ;; the underlying C code and file-system figure it out.
     ;; This also ends up checking a bunch of useful conditions: it makes
     ;; sure we have write-access to the directory and that we own it, thus
     ;; closing a bunch of security holes.
     (set-file-modes dir #o0700))))

(defun doc-view-current-cache-dir ()
  "Return the directory where the png files of the current doc should be saved.
It's a subdirectory of `doc-view-cache-directory'."
  (if doc-view-current-cache-dir
      doc-view-current-cache-dir
    ;; Try and make sure doc-view-cache-directory exists and is safe.
    (doc-view-make-safe-dir doc-view-cache-directory)
    ;; Now compute the subdirectory to use.
    (setq doc-view-current-cache-dir
	  (file-name-as-directory
	   (expand-file-name
	    (concat (file-name-nondirectory buffer-file-name)
		    "-"
		    (let ((file doc-view-buffer-file-name))
		      (with-temp-buffer
			(set-buffer-multibyte nil)
			(insert-file-contents-literally file)
			(md5 (current-buffer)))))
            doc-view-cache-directory)))))

(defun doc-view-remove-if (predicate list)
  "Return LIST with all items removed that satisfy PREDICATE."
  (let (new-list)
    (dolist (item list (nreverse new-list))
      (when (not (funcall predicate item))
	(setq new-list (cons item new-list))))))

;;;###autoload
(defun doc-view-mode-p (type)
  "Return non-nil if image type TYPE is available for `doc-view'.
Image types are symbols like `dvi', `postscript' or `pdf'."
  (and (display-graphic-p)
       (image-type-available-p 'png)
       (cond
	((eq type 'dvi)
	 (and (doc-view-mode-p 'pdf)
	      (or (and doc-view-dvipdf-program
		       (executable-find doc-view-dvipdf-program))
		  (and doc-view-dvipdfm-program
		       (executable-find doc-view-dvipdfm-program)))))
	((or (eq type 'postscript) (eq type 'ps) (eq type 'eps)
	     (eq type 'pdf))
	 (and doc-view-ghostscript-program
	      (executable-find doc-view-ghostscript-program)))
	(t ;; unknown image type
	 nil))))

;;;; Conversion Functions

(defvar doc-view-shrink-factor 1.125)

(defun doc-view-enlarge (factor)
  "Enlarge the document."
  (interactive (list doc-view-shrink-factor))
  (set (make-local-variable 'doc-view-resolution)
       (* factor doc-view-resolution))
  (doc-view-reconvert-doc))

(defun doc-view-shrink (factor)
  "Shrink the document."
  (interactive (list doc-view-shrink-factor))
  (doc-view-enlarge (/ 1.0 factor)))

(defun doc-view-reconvert-doc ()
  "Reconvert the current document.
Should be invoked when the cached images aren't up-to-date."
  (interactive)
  (doc-view-kill-proc)
  ;; Clear the old cached files
  (when (file-exists-p (doc-view-current-cache-dir))
    (dired-delete-file (doc-view-current-cache-dir) 'always))
  (doc-view-initiate-display))

(defun doc-view-sentinel (proc event)
  "Generic sentinel for doc-view conversion processes."
  (if (not (string-match "finished" event))
      (message "DocView: process %s changed status to %s."
               (process-name proc)
	       (if (string-match "\\(.+\\)\n?\\'" event)
		   (match-string 1 event)
		 event))
    (when (buffer-live-p (process-get proc 'buffer))
      (with-current-buffer (process-get proc 'buffer)
        (setq doc-view-current-converter-processes
              (delq proc doc-view-current-converter-processes))
        (setq mode-line-process
              (if doc-view-current-converter-processes
                  (format ":%s" (car doc-view-current-converter-processes))))
        (funcall (process-get proc 'callback))))))

(defun doc-view-start-process (name program args callback)
  ;; Make sure the process is started in an existing directory, (rather than
  ;; some file-name-handler-managed dir, for example).
  (let* ((default-directory (if (file-readable-p default-directory)
				default-directory
			      (expand-file-name "~/")))
         (proc (apply 'start-process name doc-view-conversion-buffer
                      program args)))
    (push proc doc-view-current-converter-processes)
    (setq mode-line-process (list (format ":%s" proc)))
    (set-process-sentinel proc 'doc-view-sentinel)
    (process-put proc 'buffer   (current-buffer))
    (process-put proc 'callback callback)))

(defun doc-view-dvi->pdf (dvi pdf callback)
  "Convert DVI to PDF asynchronously and call CALLBACK when finished."
  ;; Prefer dvipdf over dvipdfm, because the latter has problems if the DVI
  ;; references and includes other PS files.
  (if (and doc-view-dvipdf-program
	   (executable-find doc-view-dvipdf-program))
      (doc-view-start-process "dvi->pdf" doc-view-dvipdf-program
			    (list dvi pdf)
			    callback)
    (doc-view-start-process "dvi->pdf" doc-view-dvipdfm-program
			    (list "-o" pdf dvi)
			    callback)))


(defun doc-view-pdf/ps->png (pdf-ps png)
  "Convert PDF-PS to PNG asynchronously."
  (doc-view-start-process
   "pdf/ps->png" doc-view-ghostscript-program
   (append doc-view-ghostscript-options
           (list (format "-r%d" (round doc-view-resolution))
                 (concat "-sOutputFile=" png)
                 pdf-ps))
   (lambda ()
     (when doc-view-current-timer
       (cancel-timer doc-view-current-timer)
       (setq doc-view-current-timer nil))
     (doc-view-display (current-buffer) 'force)))
  ;; Update the displayed pages as soon as they're done generating.
  (when doc-view-conversion-refresh-interval
    (setq doc-view-current-timer
          (run-at-time "1 secs" doc-view-conversion-refresh-interval
                       'doc-view-display
                       (current-buffer)))))

(defun doc-view-pdf->png-1 (pdf png page callback)
  "Convert a PAGE of a PDF file to PNG asynchronously.
Call CALLBACK with no arguments when done."
  (doc-view-start-process
   "pdf->png-1" doc-view-ghostscript-program
   (append doc-view-ghostscript-options
           (list (format "-r%d" (round doc-view-resolution))
                 ;; Sadly, `gs' only supports the page-range
                 ;; for PDF files.
                 (format "-dFirstPage=%d" page)
                 (format "-dLastPage=%d" page)
                 (concat "-sOutputFile=" png)
                 pdf))
   callback))

(declare-function clear-image-cache "image.c" (&optional filter))

(defun doc-view-pdf->png (pdf png pages)
  "Convert a PDF file to PNG asynchronously.
Start by converting PAGES, and then the rest."
  (if (null pages)
      (doc-view-pdf/ps->png pdf png)
    ;; We could render several `pages' with a single process if they're
    ;; (almost) consecutive, but since in 99% of the cases, there'll be only
    ;; a single page anyway, and of the remaining 1%, few cases will have
    ;; consecutive pages, it's not worth the trouble.
    (lexical-let ((pdf pdf) (png png) (rest (cdr pages)))
      (doc-view-pdf->png-1
       pdf (format png (car pages)) (car pages)
       (lambda ()
         (if rest
             (doc-view-pdf->png pdf png rest)
           ;; Yippie, the important pages are done, update the display.
           (clear-image-cache)
           ;; Convert the rest of the pages.
           (doc-view-pdf/ps->png pdf png)))))))

(defun doc-view-pdf->txt (pdf txt callback)
  "Convert PDF to TXT asynchronously and call CALLBACK when finished."
  (or doc-view-pdftotext-program
      (error "You need the `pdftotext' program to convert a PDF to text"))
  (doc-view-start-process "pdf->txt" doc-view-pdftotext-program
                          (list "-raw" pdf txt)
                          callback))

(defun doc-view-doc->txt (txt callback)
  "Convert the current document to text and call CALLBACK when done."
  (make-directory (doc-view-current-cache-dir) t)
  (case doc-view-doc-type
    (pdf
     ;; Doc is a PDF, so convert it to TXT
     (doc-view-pdf->txt doc-view-buffer-file-name txt callback))
    (ps
     ;; Doc is a PS, so convert it to PDF (which will be converted to
     ;; TXT thereafter).
     (lexical-let ((pdf (expand-file-name "doc.pdf"
                                          (doc-view-current-cache-dir)))
                   (txt txt)
                   (callback callback))
       (doc-view-ps->pdf doc-view-buffer-file-name pdf
                         (lambda () (doc-view-pdf->txt pdf txt callback)))))
    (dvi
     ;; Doc is a DVI.  This means that a doc.pdf already exists in its
     ;; cache subdirectory.
     (doc-view-pdf->txt (expand-file-name "doc.pdf"
                                          (doc-view-current-cache-dir))
                        txt callback))
    (t (error "DocView doesn't know what to do"))))

(defun doc-view-ps->pdf (ps pdf callback)
  "Convert PS to PDF asynchronously and call CALLBACK when finished."
  (or doc-view-ps2pdf-program
      (error "You need the `ps2pdf' program to convert PS to PDF"))
  (doc-view-start-process "ps->pdf" doc-view-ps2pdf-program
                          (list
                           ;; Avoid security problems when rendering files from
                           ;; untrusted sources.
                           "-dSAFER"
                           ;; in-file and out-file
                           ps pdf)
                          callback))

(defun doc-view-active-pages ()
  (let ((pages ()))
    (dolist (win (get-buffer-window-list (current-buffer) nil 'visible))
      (let ((page (image-mode-window-get 'page win)))
        (unless (memq page pages) (push page pages))))
    pages))

(defun doc-view-convert-current-doc ()
  "Convert `doc-view-buffer-file-name' to a set of png files, one file per page.
Those files are saved in the directory given by the function
`doc-view-current-cache-dir'."
  ;; Let stale files still display while we recompute the new ones, so only
  ;; flush the cache when the conversion is over.  One of the reasons why it
  ;; is important to keep displaying the stale page is so that revert-buffer
  ;; preserves the horizontal/vertical scroll settings (which are otherwise
  ;; resets during the redisplay).
  (setq doc-view-pending-cache-flush t)
  (let ((png-file (expand-file-name "page-%d.png"
                                    (doc-view-current-cache-dir)))
	(res-file (expand-file-name "resolution.el"
                                    (doc-view-current-cache-dir))))
    (make-directory (doc-view-current-cache-dir) t)
    ;; Save the used resolution so that it can be restored when
    ;; reading the cached files.
    (let ((res doc-view-resolution))
      (with-temp-buffer
	(princ res (current-buffer))
        ;; Don't use write-file, so as to avoid prompts for `require-newline',
        ;; or for pre-existing buffers with the same name, ...
	(write-region nil nil res-file nil 'silently)))
    (case doc-view-doc-type
      (dvi
       ;; DVI files have to be converted to PDF before Ghostscript can process
       ;; it.
       (lexical-let
           ((pdf (expand-file-name "doc.pdf" doc-view-current-cache-dir))
            (png-file png-file))
         (doc-view-dvi->pdf doc-view-buffer-file-name pdf
                            (lambda () (doc-view-pdf/ps->png pdf png-file)))))
     (pdf
      (let ((pages (doc-view-active-pages)))
        ;; Convert PDF to PNG images starting with the active pages.
        (doc-view-pdf->png doc-view-buffer-file-name png-file pages)))
      (t
       ;; Convert to PNG images.
       (doc-view-pdf/ps->png doc-view-buffer-file-name png-file)))))

;;;; Slicing

(declare-function image-size "image.c" (spec &optional pixels frame))

(defun doc-view-set-slice (x y width height)
  "Set the slice of the images that should be displayed.
You can use this function to tell doc-view not to display the
margins of the document.  It prompts for the top-left corner (X
and Y) of the slice to display and its WIDTH and HEIGHT.

See `doc-view-set-slice-using-mouse' for a more convenient way to
do that.  To reset the slice use `doc-view-reset-slice'."
  (interactive
   (let* ((size (image-size (doc-view-current-image) t))
	  (a (read-number (format "Top-left X (0..%d): " (car size))))
	  (b (read-number (format "Top-left Y (0..%d): " (cdr size))))
	  (c (read-number (format "Width (0..%d): " (- (car size) a))))
	  (d (read-number (format "Height (0..%d): " (- (cdr size) b)))))
     (list a b c d)))
  (setf (doc-view-current-slice) (list x y width height))
  ;; Redisplay
  (doc-view-goto-page (doc-view-current-page)))

(defun doc-view-set-slice-using-mouse ()
  "Set the slice of the images that should be displayed.
You set the slice by pressing mouse-1 at its top-left corner and
dragging it to its bottom-right corner.  See also
`doc-view-set-slice' and `doc-view-reset-slice'."
  (interactive)
  (let (x y w h done)
    (while (not done)
      (let ((e (read-event
		(concat "Press mouse-1 at the top-left corner and "
			"drag it to the bottom-right corner!"))))
	(when (eq (car e) 'drag-mouse-1)
	  (setq x (car (posn-object-x-y (event-start e))))
	  (setq y (cdr (posn-object-x-y (event-start e))))
	  (setq w (- (car (posn-object-x-y (event-end e))) x))
	  (setq h (- (cdr (posn-object-x-y (event-end e))) y))
	  (setq done t))))
    (doc-view-set-slice x y w h)))

(defun doc-view-reset-slice ()
  "Reset the current slice.
After calling this function whole pages will be visible again."
  (interactive)
  (setf (doc-view-current-slice) nil)
  ;; Redisplay
  (doc-view-goto-page (doc-view-current-page)))

;;;; Display

(defun doc-view-insert-image (file &rest args)
  "Insert the given png FILE.
ARGS is a list of image descriptors."
  (when doc-view-pending-cache-flush
    (clear-image-cache)
    (setq doc-view-pending-cache-flush nil))
  (let ((ol (doc-view-current-overlay))
        (image (if (and file (file-readable-p file))
                   (apply 'create-image file 'png nil args)))
        (slice (doc-view-current-slice)))
    (setf (doc-view-current-image) image)
    (move-overlay ol (point-min) (point-max))
    (overlay-put ol 'display
                 (cond
                  (image
                   (if slice
                       (list (cons 'slice slice) image)
                     image))
                  ;; We're trying to display a page that doesn't exist.
                  (doc-view-current-converter-processes
                   ;; Maybe the page doesn't exist *yet*.
                   "Cannot display this page (yet)!")
                  (t
                   ;; Typically happens if the conversion process somehow
                   ;; failed.  Better not signal an error here because it
                   ;; could prevent a subsequent reconversion from fixing
                   ;; the problem.
                   (concat "Cannot display this page!\n"
                           "Maybe because of a conversion failure!"))))
    (let ((win (overlay-get ol 'window)))
      (if (stringp (overlay-get ol 'display))
          (progn            ;Make sure the text is not scrolled out of view.
            (set-window-hscroll win 0)
            (set-window-vscroll win 0))
        (let ((hscroll (image-mode-window-get 'hscroll win))
              (vscroll (image-mode-window-get 'vscroll win)))
          ;; Reset scroll settings, in case they were changed.
          (if hscroll (set-window-hscroll win hscroll))
          (if vscroll (set-window-vscroll win vscroll)))))))

(defun doc-view-sort (a b)
  "Return non-nil if A should be sorted before B.
Predicate for sorting `doc-view-current-files'."
  (or (< (length a) (length b))
      (and (= (length a) (length b))
           (string< a b))))

(defun doc-view-display (buffer &optional force)
  "Start viewing the document in BUFFER.
If FORCE is non-nil, start viewing even if the document does not
have the page we want to view."
  (with-current-buffer buffer
    (let ((prev-pages doc-view-current-files))
      (setq doc-view-current-files
            (sort (directory-files (doc-view-current-cache-dir) t
                                   "page-[0-9]+\\.png" t)
                  'doc-view-sort))
      (dolist (win (or (get-buffer-window-list buffer nil t)
		       (list (selected-window))))
	(let* ((page (doc-view-current-page win))
	       (pagefile (expand-file-name (format "page-%d.png" page)
					   (doc-view-current-cache-dir))))
	  (when (or force
		    (and (not (member pagefile prev-pages))
			 (member pagefile doc-view-current-files)))
	    (with-selected-window win
	      (assert (eq (current-buffer) buffer))
	      (doc-view-goto-page page))))))))

(defun doc-view-buffer-message ()
  ;; Only show this message initially, not when refreshing the buffer (in which
  ;; case it's better to keep displaying the "stale" page while computing
  ;; the fresh new ones).
  (unless (overlay-get (doc-view-current-overlay) 'display)
    (overlay-put (doc-view-current-overlay) 'display
                 (concat (propertize "Welcome to DocView!" 'face 'bold)
                         "\n"
                         "
If you see this buffer it means that the document you want to view is being
converted to PNG and the conversion of the first page hasn't finished yet or
`doc-view-conversion-refresh-interval' is set to nil.

For now these keys are useful:

`q' : Bury this buffer.  Conversion will go on in background.
`k' : Kill the conversion process and this buffer.
`K' : Kill the conversion process.\n"))))

(declare-function tooltip-show "tooltip" (text &optional use-echo-area))

(defun doc-view-show-tooltip ()
  (interactive)
  (tooltip-show (doc-view-current-info)))

(defun doc-view-open-text ()
  "Open a buffer with the current doc's contents as text."
  (interactive)
  (if doc-view-current-converter-processes
      (message "DocView: please wait till conversion finished.")
    (let ((txt (expand-file-name "doc.txt" (doc-view-current-cache-dir))))
      (if (file-readable-p txt)
	  (find-file txt)
	(doc-view-doc->txt txt 'doc-view-open-text)))))

;;;;; Toggle between editing and viewing


(defun doc-view-toggle-display ()
  "Toggle between editing a document as text or viewing it."
  (interactive)
  (if (eq major-mode 'doc-view-mode)
      ;; Switch to editing mode
      (progn
	(doc-view-kill-proc)
	(setq buffer-read-only nil)
	(remove-overlays (point-min) (point-max) 'doc-view t)
	(set (make-local-variable 'image-mode-winprops-alist) t)
	;; Switch to the previously used major mode or fall back to fundamental
	;; mode.
	(if doc-view-previous-major-mode
	    (funcall doc-view-previous-major-mode)
	  (fundamental-mode))
	(doc-view-minor-mode 1))
    ;; Switch to doc-view-mode
    (when (and (buffer-modified-p)
	       (y-or-n-p "The buffer has been modified.  Save the changes? "))
      (save-buffer))
    (doc-view-mode)))

;;;; Searching


(defun doc-view-search-internal (regexp file)
  "Return a list of FILE's pages that contain text matching REGEXP.
The value is an alist of the form (PAGE CONTEXTS) where PAGE is
the pagenumber and CONTEXTS are all lines of text containing a match."
  (with-temp-buffer
    (insert-file-contents file)
    (let ((page 1)
	  (lastpage 1)
	  matches)
      (while (re-search-forward (concat "\\(?:\\([]\\)\\|\\("
					regexp "\\)\\)") nil t)
	(when (match-string 1) (setq page (1+ page)))
	(when (match-string 2)
	  (if (/= page lastpage)
	      (push (cons page
			  (list (buffer-substring
				 (line-beginning-position)
				 (line-end-position))))
		    matches)
	    (setq matches (cons
			   (append
			    (or
			     ;; This page already is a match.
			     (car matches)
			     ;; This is the first match on page.
			     (list page))
			    (list (buffer-substring
				   (line-beginning-position)
				   (line-end-position))))
			   (cdr matches))))
	  (setq lastpage page)))
      (nreverse matches))))

(defun doc-view-search-no-of-matches (list)
  "Extract the number of matches from the search result LIST."
  (let ((no 0))
    (dolist (p list)
      (setq no (+ no (1- (length p)))))
    no))

(defun doc-view-search-backward (new-query)
  "Call `doc-view-search' for backward search.
If prefix NEW-QUERY is given, ask for a new regexp."
  (interactive "P")
  (doc-view-search new-query t))

(defun doc-view-search (new-query &optional backward)
  "Jump to the next match or initiate a new search if NEW-QUERY is given.
If the current document hasn't been transformed to plain text
till now do that first.
If BACKWARD is non-nil, jump to the previous match."
  (interactive "P")
  (if (and (not new-query)
	   doc-view-current-search-matches)
      (if backward
	  (doc-view-search-previous-match 1)
	(doc-view-search-next-match 1))
    ;; New search, so forget the old results.
    (setq doc-view-current-search-matches nil)
    (let ((txt (expand-file-name "doc.txt"
				 (doc-view-current-cache-dir))))
      (if (file-readable-p txt)
	  (progn
	    (setq doc-view-current-search-matches
		  (doc-view-search-internal
		   (read-from-minibuffer "Regexp: ")
		   txt))
	    (message "DocView: search yielded %d matches."
		     (doc-view-search-no-of-matches
		      doc-view-current-search-matches)))
	;; We must convert to TXT first!
	(if doc-view-current-converter-processes
	    (message "DocView: please wait till conversion finished.")
	  (doc-view-doc->txt txt (lambda () (doc-view-search nil))))))))

(defun doc-view-search-next-match (arg)
  "Go to the ARGth next matching page."
  (interactive "p")
  (let* ((next-pages (doc-view-remove-if
		      (lambda (i) (<= (car i) (doc-view-current-page)))
		      doc-view-current-search-matches))
	 (page (car (nth (1- arg) next-pages))))
    (if page
	(doc-view-goto-page page)
      (when (and
	     doc-view-current-search-matches
	     (y-or-n-p "No more matches after current page.  Wrap to first match? "))
	(doc-view-goto-page (caar doc-view-current-search-matches))))))

(defun doc-view-search-previous-match (arg)
  "Go to the ARGth previous matching page."
  (interactive "p")
  (let* ((prev-pages (doc-view-remove-if
		      (lambda (i) (>= (car i) (doc-view-current-page)))
		      doc-view-current-search-matches))
	 (page (car (nth (1- arg) (nreverse prev-pages)))))
    (if page
	(doc-view-goto-page page)
      (when (and
	     doc-view-current-search-matches
	     (y-or-n-p "No more matches before current page.  Wrap to last match? "))
	(doc-view-goto-page (caar (last doc-view-current-search-matches)))))))

;;;; User interface commands and the mode

;; (put 'doc-view-mode 'mode-class 'special)

(defun doc-view-already-converted-p ()
  "Return non-nil if the current doc was already converted."
  (and (file-exists-p (doc-view-current-cache-dir))
       (> (length (directory-files (doc-view-current-cache-dir) nil "\\.png$")) 0)))

(defun doc-view-initiate-display ()
  ;; Switch to image display if possible
  (if (doc-view-mode-p doc-view-doc-type)
      (progn
	(doc-view-buffer-message)
	(setf (doc-view-current-page) (or (doc-view-current-page) 1))
	(if (doc-view-already-converted-p)
	    (progn
	      (message "DocView: using cached files!")
	      ;; Load the saved resolution
	      (let ((res-file (expand-file-name "resolution.el"
						(doc-view-current-cache-dir)))
		    (res doc-view-resolution))
		(with-temp-buffer
		  (when (file-exists-p res-file)
		    (insert-file-contents res-file)
		    (setq res (read (current-buffer)))))
		(when (numberp res)
		  (set (make-local-variable 'doc-view-resolution) res)))
	      (doc-view-display (current-buffer) 'force))
	  (doc-view-convert-current-doc))
	(message
	 "%s"
	 (substitute-command-keys
	  (concat "Type \\[doc-view-toggle-display] to toggle between "
		  "editing or viewing the document."))))
    (message
     "%s"
     (concat "No PNG support is available, or some conversion utility for "
	     (file-name-extension doc-view-buffer-file-name)
	     " files is missing."))
    (if (and (executable-find doc-view-pdftotext-program)
	     (y-or-n-p
	      "Unable to render file.  View extracted text instead? "))
	(doc-view-open-text)
      (doc-view-toggle-display))))

(defvar bookmark-make-record-function)

(defun doc-view-clone-buffer-hook ()
  ;; FIXME: There are several potential problems linked with reconversion
  ;; and auto-revert when we have indirect buffers because they share their
  ;; /tmp cache directory.  This sharing is good (you'd rather not reconvert
  ;; for each clone), but that means that clones need to collaborate a bit.
  ;; I guess it mostly means: detect when a reconversion process is already
  ;; running, and run the sentinel in all clones.
  ;;
  ;; Maybe the clones should really have a separate /tmp directory
  ;; so they could have a different resolution and you could use clones
  ;; for zooming.
  (remove-overlays (point-min) (point-max) 'doc-view t)
  (if (consp image-mode-winprops-alist) (setq image-mode-winprops-alist nil)))

(defun doc-view-intersection (l1 l2)
  (let ((l ()))
    (dolist (x l1) (if (memq x l2) (push x l)))
    l))

;;;###autoload
(defun doc-view-mode ()
  "Major mode in DocView buffers.

DocView Mode is an Emacs document viewer.  It displays PDF, PS
and DVI files (as PNG images) in Emacs buffers.

You can use \\<doc-view-mode-map>\\[doc-view-toggle-display] to
toggle between displaying the document or editing it as text.
\\{doc-view-mode-map}"
  (interactive)

  (if (= (point-min) (point-max))
      ;; The doc is empty or doesn't exist at all, so fallback to
      ;; another mode.  We used to also check file-exists-p, but this
      ;; returns nil for tar members.
      (let ((auto-mode-alist (remq (rassq 'doc-view-mode auto-mode-alist)
				   auto-mode-alist)))
	(normal-mode))

    (let* ((prev-major-mode (if (eq major-mode 'doc-view-mode)
				doc-view-previous-major-mode
			      major-mode)))
      (kill-all-local-variables)
      (set (make-local-variable 'doc-view-previous-major-mode) prev-major-mode))

    ;; Figure out the document type.
    (let ((name-types
	   (when buffer-file-name
	     (cdr (assoc (file-name-extension buffer-file-name)
			 '(("dvi" dvi)
			   ("pdf" pdf)
			   ("epdf" pdf)
			   ("ps" ps)
			   ("eps" ps))))))
	  (content-types
	   (save-excursion
	     (goto-char (point-min))
	     (cond
	      ((looking-at "%!") '(ps))
	      ((looking-at "%PDF") '(pdf))
	      ((looking-at "\367\002") '(dvi))))))
      (set (make-local-variable 'doc-view-doc-type)
	   (car (or (doc-view-intersection name-types content-types)
		    (when (and name-types content-types)
		      (error "Conflicting types: name says %s but content says %s"
			     name-types content-types))
		    name-types content-types
		    (error "Cannot determine the document type")))))

    (doc-view-make-safe-dir doc-view-cache-directory)
    ;; Handle compressed files, remote files, files inside archives
    (set (make-local-variable 'doc-view-buffer-file-name)
	 (cond
	  (jka-compr-really-do-compress
	   (expand-file-name
	    (file-name-nondirectory
	     (file-name-sans-extension buffer-file-name))
	    doc-view-cache-directory))
	  ;; Is the file readable by local processes?
	  ;; We used to use `file-remote-p' but it's unclear what it's
	  ;; supposed to return nil for things like local files accessed via
	  ;; `su' or via file://...
	  ((let ((file-name-handler-alist nil))
	     (not (file-readable-p buffer-file-name)))
	   (expand-file-name
	    (file-name-nondirectory buffer-file-name)
	    doc-view-cache-directory))
	  (t buffer-file-name)))
    (when (not (string= doc-view-buffer-file-name buffer-file-name))
      (write-region nil nil doc-view-buffer-file-name))

    (add-hook 'change-major-mode-hook
	      (lambda ()
		(doc-view-kill-proc)
		(remove-overlays (point-min) (point-max) 'doc-view t))
	      nil t)
    (add-hook 'clone-indirect-buffer-hook 'doc-view-clone-buffer-hook nil t)
    (add-hook 'kill-buffer-hook 'doc-view-kill-proc nil t)

    (remove-overlays (point-min) (point-max) 'doc-view t) ;Just in case.
    ;; Keep track of display info ([vh]scroll, page number, overlay,
    ;; ...)  for each window in which this document is shown.
    (add-hook 'image-mode-new-window-functions
	      'doc-view-new-window-function nil t)
    (image-mode-setup-winprops)

    (set (make-local-variable 'mode-line-position)
	 '(" P" (:eval (number-to-string (doc-view-current-page)))
	   "/" (:eval (number-to-string (length doc-view-current-files)))))
    ;; Don't scroll unless the user specifically asked for it.
    (set (make-local-variable 'auto-hscroll-mode) nil)
    (set (make-local-variable 'cursor-type) nil)
    (use-local-map doc-view-mode-map)
    (set (make-local-variable 'after-revert-hook) 'doc-view-reconvert-doc)
    (set (make-local-variable 'bookmark-make-record-function)
	 'doc-view-bookmark-make-record)
    (setq mode-name "DocView"
	  buffer-read-only t
	  major-mode 'doc-view-mode)
    (doc-view-initiate-display)
    (run-mode-hooks 'doc-view-mode-hook)))

;;;###autoload
(define-minor-mode doc-view-minor-mode
  "Toggle Doc view minor mode.
With arg, turn Doc view minor mode on if arg is positive, off otherwise.
See the command `doc-view-mode' for more information on this mode."
  nil " DocView" doc-view-minor-mode-map
  :group 'doc-view
  (when doc-view-minor-mode
    (add-hook 'change-major-mode-hook (lambda () (doc-view-minor-mode -1)) nil t)
    (message
     "%s"
     (substitute-command-keys
      "Type \\[doc-view-toggle-display] to toggle between editing or viewing the document."))))

(defun doc-view-clear-cache ()
  "Delete the whole cache (`doc-view-cache-directory')."
  (interactive)
  (dired-delete-file doc-view-cache-directory 'always))

(defun doc-view-dired-cache ()
  "Open `dired' in `doc-view-cache-directory'."
  (interactive)
  (dired doc-view-cache-directory))


;;;; Bookmark integration

(declare-function bookmark-make-record-default "bookmark"
                  (&optional point-only))
(declare-function bookmark-prop-get "bookmark" (bookmark prop))
(declare-function bookmark-default-handler "bookmark" (bmk))

(defun doc-view-bookmark-make-record ()
  (nconc (bookmark-make-record-default)
         `((page     . ,(doc-view-current-page))
           (handler  . doc-view-bookmark-jump))))


;;;###autoload
(defun doc-view-bookmark-jump (bmk)
  ;; This implements the `handler' function interface for record type
  ;; returned by `doc-view-bookmark-make-record', which see.
  (prog1 (bookmark-default-handler bmk)
    (let ((page (bookmark-prop-get bmk 'page)))
      (when (not (eq major-mode 'doc-view-mode))
        (doc-view-toggle-display))
      (with-selected-window
          (or (get-buffer-window (current-buffer) 0)
              (selected-window))
        (doc-view-goto-page page)))))


(provide 'doc-view)

;; Local Variables:
;; mode: outline-minor
;; End:

;; arch-tag: 5d6e5c5e-095f-489e-b4e4-1ca90a7d79be
;;; doc-view.el ends here