Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-attach.el
blobcf8a1cafd0f0a4c6457604824d71bb461bb964c4
1 ;;; org-attach.el --- Manage file attachments to Org tasks -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2008-2016 Free Software Foundation, Inc.
5 ;; Author: John Wiegley <johnw@newartisans.com>
6 ;; Keywords: org data task
8 ;; This file is part of GNU Emacs.
9 ;;
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; See the Org-mode manual for information on how to use it.
27 ;; Attachments are managed in a special directory called "data", which
28 ;; lives in the same directory as the org file itself. If this data
29 ;; directory is initialized as a Git repository, then org-attach will
30 ;; automatically commit changes when it sees them.
32 ;; Attachment directories are identified using a UUID generated for the
33 ;; task which has the attachments. These are added as property to the
34 ;; task when necessary, and should not be deleted or changed by the
35 ;; user, ever. UUIDs are generated by a mechanism defined in the variable
36 ;; `org-id-method'.
38 ;;; Code:
40 (eval-when-compile
41 (require 'cl))
42 (require 'org-id)
43 (require 'org)
44 (require 'vc-git)
46 (defgroup org-attach nil
47 "Options concerning entry attachments in Org-mode."
48 :tag "Org Attach"
49 :group 'org)
51 (defcustom org-attach-directory "data/"
52 "The directory where attachments are stored.
53 If this is a relative path, it will be interpreted relative to the directory
54 where the Org file lives."
55 :group 'org-attach
56 :type 'directory)
58 (defcustom org-attach-commit t
59 "If non-nil commit attachments with git.
60 This is only done if the Org file is in a git repository."
61 :group 'org-attach
62 :type 'boolean
63 :version "25.1"
64 :package-version '(Org . "9.0"))
66 (defcustom org-attach-git-annex-cutoff (* 32 1024)
67 "If non-nil, files larger than this will be annexed instead of stored."
68 :group 'org-attach
69 :version "24.4"
70 :package-version '(Org . "8.0")
71 :type '(choice
72 (const :tag "None" nil)
73 (integer :tag "Bytes")))
75 (defcustom org-attach-auto-tag "ATTACH"
76 "Tag that will be triggered automatically when an entry has an attachment."
77 :group 'org-attach
78 :type '(choice
79 (const :tag "None" nil)
80 (string :tag "Tag")))
82 (defcustom org-attach-file-list-property "Attachments"
83 "The property used to keep a list of attachment belonging to this entry.
84 This is not really needed, so you may set this to nil if you don't want it.
85 Also, for entries where children inherit the directory, the list of
86 attachments is not kept in this property."
87 :group 'org-attach
88 :type '(choice
89 (const :tag "None" nil)
90 (string :tag "Tag")))
92 (defcustom org-attach-method 'cp
93 "The preferred method to attach a file.
94 Allowed values are:
96 mv rename the file to move it into the attachment directory
97 cp copy the file
98 ln create a hard link. Note that this is not supported
99 on all systems, and then the result is not defined.
100 lns create a symbol link. Note that this is not supported
101 on all systems, and then the result is not defined."
102 :group 'org-attach
103 :type '(choice
104 (const :tag "Copy" cp)
105 (const :tag "Move/Rename" mv)
106 (const :tag "Hard Link" ln)
107 (const :tag "Symbol Link" lns)))
109 (defcustom org-attach-expert nil
110 "Non-nil means do not show the splash buffer with the attach dispatcher."
111 :group 'org-attach
112 :type 'boolean)
114 (defcustom org-attach-allow-inheritance t
115 "Non-nil means allow attachment directories be inherited."
116 :group 'org-attach
117 :type 'boolean)
119 (defvar org-attach-inherited nil
120 "Indicates if the last access to the attachment directory was inherited.")
122 (defcustom org-attach-store-link-p nil
123 "Non-nil means store a link to a file when attaching it."
124 :group 'org-attach
125 :version "24.1"
126 :type '(choice
127 (const :tag "Don't store link" nil)
128 (const :tag "Link to origin location" t)
129 (const :tag "Link to the attach-dir location" attached)))
131 (defcustom org-attach-archive-delete nil
132 "Non-nil means attachments are deleted upon archiving a subtree.
133 When set to `query', ask the user instead."
134 :group 'org-attach
135 :version "25.1"
136 :package-version '(Org . "8.3")
137 :type '(choice
138 (const :tag "Never delete attachments" nil)
139 (const :tag "Always delete attachments" t)
140 (const :tag "Query the user" query)))
142 (defcustom org-attach-annex-auto-get 'ask
143 "Confirmation preference for automatically getting annex files.
144 If \\='ask, prompt using `y-or-n-p'. If t, always get. If nil, never get."
145 :group 'org-attach
146 :package-version '(Org . "9")
147 :version "25.1"
148 :type '(choice
149 (const :tag "confirm with `y-or-n-p'" ask)
150 (const :tag "always get from annex if necessary" t)
151 (const :tag "never get from annex" nil)))
153 ;;;###autoload
154 (defun org-attach ()
155 "The dispatcher for attachment commands.
156 Shows a list of commands and prompts for another key to execute a command."
157 (interactive)
158 (let (c marker)
159 (when (eq major-mode 'org-agenda-mode)
160 (setq marker (or (get-text-property (point) 'org-hd-marker)
161 (get-text-property (point) 'org-marker)))
162 (unless marker
163 (error "No task in current line")))
164 (save-excursion
165 (when marker
166 (set-buffer (marker-buffer marker))
167 (goto-char marker))
168 (org-back-to-heading t)
169 (save-excursion
170 (save-window-excursion
171 (unless org-attach-expert
172 (with-output-to-temp-buffer "*Org Attach*"
173 (princ "Select an Attachment Command:
175 a Select a file and attach it to the task, using `org-attach-method'.
176 c/m/l/y Attach a file using copy/move/link/symbolic-link method.
177 n Create a new attachment, as an Emacs buffer.
178 z Synchronize the current task with its attachment
179 directory, in case you added attachments yourself.
181 o Open current task's attachments.
182 O Like \"o\", but force opening in Emacs.
183 f Open current task's attachment directory.
184 F Like \"f\", but force using dired in Emacs.
186 d Delete one attachment, you will be prompted for a file name.
187 D Delete all of a task's attachments. A safer way is
188 to open the directory in dired and delete from there.
190 s Set a specific attachment directory for this entry.
191 i Make children of the current entry inherit its attachment directory.")))
192 (org-fit-window-to-buffer (get-buffer-window "*Org Attach*"))
193 (message "Select command: [acmlzoOfFdD]")
194 (setq c (read-char-exclusive))
195 (and (get-buffer "*Org Attach*") (kill-buffer "*Org Attach*"))))
196 (cond
197 ((memq c '(?a ?\C-a)) (call-interactively 'org-attach-attach))
198 ((memq c '(?c ?\C-c))
199 (let ((org-attach-method 'cp)) (call-interactively 'org-attach-attach)))
200 ((memq c '(?m ?\C-m))
201 (let ((org-attach-method 'mv)) (call-interactively 'org-attach-attach)))
202 ((memq c '(?l ?\C-l))
203 (let ((org-attach-method 'ln)) (call-interactively 'org-attach-attach)))
204 ((memq c '(?y ?\C-y))
205 (let ((org-attach-method 'lns)) (call-interactively 'org-attach-attach)))
206 ((memq c '(?n ?\C-n)) (call-interactively 'org-attach-new))
207 ((memq c '(?z ?\C-z)) (call-interactively 'org-attach-sync))
208 ((memq c '(?o ?\C-o)) (call-interactively 'org-attach-open))
209 ((eq c ?O) (call-interactively 'org-attach-open-in-emacs))
210 ((memq c '(?f ?\C-f)) (call-interactively 'org-attach-reveal))
211 ((memq c '(?F)) (call-interactively 'org-attach-reveal-in-emacs))
212 ((memq c '(?d ?\C-d)) (call-interactively
213 'org-attach-delete-one))
214 ((eq c ?D) (call-interactively 'org-attach-delete-all))
215 ((eq c ?q) (message "Abort"))
216 ((memq c '(?s ?\C-s)) (call-interactively
217 'org-attach-set-directory))
218 ((memq c '(?i ?\C-i)) (call-interactively
219 'org-attach-set-inherit))
220 (t (error "No such attachment command %c" c))))))
222 (defun org-attach-dir (&optional create-if-not-exists-p)
223 "Return the directory associated with the current entry.
224 This first checks for a local property ATTACH_DIR, and then for an inherited
225 property ATTACH_DIR_INHERIT. If neither exists, the default mechanism
226 using the entry ID will be invoked to access the unique directory for the
227 current entry.
228 If the directory does not exist and CREATE-IF-NOT-EXISTS-P is non-nil,
229 the directory and (if necessary) the corresponding ID will be created."
230 (let (attach-dir uuid)
231 (setq org-attach-inherited (org-entry-get nil "ATTACH_DIR_INHERIT"))
232 (cond
233 ((setq attach-dir (org-entry-get nil "ATTACH_DIR"))
234 (org-attach-check-absolute-path attach-dir))
235 ((and org-attach-allow-inheritance
236 (org-entry-get nil "ATTACH_DIR_INHERIT" t))
237 (setq attach-dir
238 (org-with-wide-buffer
239 (if (marker-position org-entry-property-inherited-from)
240 (goto-char org-entry-property-inherited-from)
241 (org-back-to-heading t))
242 (let (org-attach-allow-inheritance)
243 (org-attach-dir create-if-not-exists-p))))
244 (org-attach-check-absolute-path attach-dir)
245 (setq org-attach-inherited t))
246 (t ; use the ID
247 (org-attach-check-absolute-path nil)
248 (setq uuid (org-id-get (point) create-if-not-exists-p))
249 (when (or uuid create-if-not-exists-p)
250 (unless uuid (error "ID retrieval/creation failed"))
251 (setq attach-dir (expand-file-name
252 (format "%s/%s"
253 (substring uuid 0 2)
254 (substring uuid 2))
255 (expand-file-name org-attach-directory))))))
256 (when attach-dir
257 (if (and create-if-not-exists-p
258 (not (file-directory-p attach-dir)))
259 (make-directory attach-dir t))
260 (and (file-exists-p attach-dir)
261 attach-dir))))
263 (defun org-attach-check-absolute-path (dir)
264 "Check if we have enough information to root the attachment directory.
265 When DIR is given, check also if it is already absolute. Otherwise,
266 assume that it will be relative, and check if `org-attach-directory' is
267 absolute, or if at least the current buffer has a file name.
268 Throw an error if we cannot root the directory."
269 (or (and dir (file-name-absolute-p dir))
270 (file-name-absolute-p org-attach-directory)
271 (buffer-file-name (buffer-base-buffer))
272 (error "Need absolute `org-attach-directory' to attach in buffers without filename")))
274 (defun org-attach-set-directory ()
275 "Set the ATTACH_DIR property of the current entry.
276 The property defines the directory that is used for attachments
277 of the entry."
278 (interactive)
279 (let ((dir (org-entry-get nil "ATTACH_DIR")))
280 (setq dir (read-directory-name "Attachment directory: " dir))
281 (org-entry-put nil "ATTACH_DIR" dir)))
283 (defun org-attach-set-inherit ()
284 "Set the ATTACH_DIR_INHERIT property of the current entry.
285 The property defines the directory that is used for attachments
286 of the entry and any children that do not explicitly define (by setting
287 the ATTACH_DIR property) their own attachment directory."
288 (interactive)
289 (org-entry-put nil "ATTACH_DIR_INHERIT" "t")
290 (message "Children will inherit attachment directory"))
292 (defun org-attach-use-annex ()
293 "Return non-nil if git annex can be used."
294 (let ((git-dir (vc-git-root (expand-file-name org-attach-directory))))
295 (and org-attach-git-annex-cutoff
296 (or (file-exists-p (expand-file-name "annex" git-dir))
297 (file-exists-p (expand-file-name ".git/annex" git-dir))))))
299 (defun org-attach-annex-get-maybe (path)
300 "Call git annex get PATH (via shell) if using git annex.
301 Signals an error if the file content is not available and it was not retrieved."
302 (let ((path-relative (file-relative-name path)))
303 (when (and (org-attach-use-annex)
304 (not
305 (string-equal
306 "found"
307 (shell-command-to-string
308 (format "git annex find --format=found --in=here %s"
309 (shell-quote-argument path-relative))))))
310 (let ((should-get
311 (if (eq org-attach-annex-auto-get 'ask)
312 (y-or-n-p (format "Run git annex get %s? " path-relative))
313 org-attach-annex-auto-get)))
314 (if should-get
315 (progn (message "Running git annex get \"%s\"." path-relative)
316 (call-process "git" nil nil nil "annex" "get" path-relative))
317 (error "File %s stored in git annex but it is not available, and was not retrieved"
318 path))))))
320 (defun org-attach-commit ()
321 "Commit changes to git if `org-attach-directory' is properly initialized.
322 This checks for the existence of a \".git\" directory in that directory."
323 (let* ((dir (expand-file-name org-attach-directory))
324 (git-dir (vc-git-root dir))
325 (use-annex (org-attach-use-annex))
326 (changes 0))
327 (when (and git-dir (executable-find "git"))
328 (with-temp-buffer
329 (cd dir)
330 (dolist (new-or-modified
331 (split-string
332 (shell-command-to-string
333 "git ls-files -zmo --exclude-standard") "\0" t))
334 (if (and use-annex
335 (>= (nth 7 (file-attributes new-or-modified))
336 org-attach-git-annex-cutoff))
337 (call-process "git" nil nil nil "annex" "add" new-or-modified)
338 (call-process "git" nil nil nil "add" new-or-modified))
339 (incf changes))
340 (dolist (deleted
341 (split-string
342 (shell-command-to-string "git ls-files -z --deleted") "\0" t))
343 (call-process "git" nil nil nil "rm" deleted)
344 (incf changes))
345 (when (> changes 0)
346 (shell-command "git commit -m 'Synchronized attachments'"))))))
348 (defun org-attach-tag (&optional off)
349 "Turn the autotag on or (if OFF is set) off."
350 (when org-attach-auto-tag
351 (save-excursion
352 (org-back-to-heading t)
353 (org-toggle-tag org-attach-auto-tag (if off 'off 'on)))))
355 (defun org-attach-untag ()
356 "Turn the autotag off."
357 (org-attach-tag 'off))
359 (defun org-attach-store-link (file)
360 "Add a link to `org-stored-link' when attaching a file.
361 Only do this when `org-attach-store-link-p' is non-nil."
362 (setq org-stored-links
363 (cons (list (org-attach-expand-link file)
364 (file-name-nondirectory file))
365 org-stored-links)))
367 (defun org-attach-attach (file &optional visit-dir method)
368 "Move/copy/link FILE into the attachment directory of the current task.
369 If VISIT-DIR is non-nil, visit the directory with dired.
370 METHOD may be `cp', `mv', `ln', or `lns' default taken from
371 `org-attach-method'."
372 (interactive "fFile to keep as an attachment: \nP")
373 (setq method (or method org-attach-method))
374 (let ((basename (file-name-nondirectory file)))
375 (when (and org-attach-file-list-property (not org-attach-inherited))
376 (org-entry-add-to-multivalued-property
377 (point) org-attach-file-list-property basename))
378 (let* ((attach-dir (org-attach-dir t))
379 (fname (expand-file-name basename attach-dir)))
380 (cond
381 ((eq method 'mv) (rename-file file fname))
382 ((eq method 'cp) (copy-file file fname))
383 ((eq method 'ln) (add-name-to-file file fname))
384 ((eq method 'lns) (make-symbolic-link file fname)))
385 (when org-attach-commit
386 (org-attach-commit))
387 (org-attach-tag)
388 (cond ((eq org-attach-store-link-p 'attached)
389 (org-attach-store-link fname))
390 ((eq org-attach-store-link-p t)
391 (org-attach-store-link file)))
392 (if visit-dir
393 (dired attach-dir)
394 (message "File \"%s\" is now a task attachment." basename)))))
396 (defun org-attach-attach-cp ()
397 "Attach a file by copying it."
398 (interactive)
399 (let ((org-attach-method 'cp)) (call-interactively 'org-attach-attach)))
400 (defun org-attach-attach-mv ()
401 "Attach a file by moving (renaming) it."
402 (interactive)
403 (let ((org-attach-method 'mv)) (call-interactively 'org-attach-attach)))
404 (defun org-attach-attach-ln ()
405 "Attach a file by creating a hard link to it.
406 Beware that this does not work on systems that do not support hard links.
407 On some systems, this apparently does copy the file instead."
408 (interactive)
409 (let ((org-attach-method 'ln)) (call-interactively 'org-attach-attach)))
410 (defun org-attach-attach-lns ()
411 "Attach a file by creating a symbolic link to it.
413 Beware that this does not work on systems that do not support symbolic links.
414 On some systems, this apparently does copy the file instead."
415 (interactive)
416 (let ((org-attach-method 'lns)) (call-interactively 'org-attach-attach)))
418 (defun org-attach-new (file)
419 "Create a new attachment FILE for the current task.
420 The attachment is created as an Emacs buffer."
421 (interactive "sCreate attachment named: ")
422 (when (and org-attach-file-list-property (not org-attach-inherited))
423 (org-entry-add-to-multivalued-property
424 (point) org-attach-file-list-property file))
425 (let ((attach-dir (org-attach-dir t)))
426 (org-attach-tag)
427 (find-file (expand-file-name file attach-dir))
428 (message "New attachment %s" file)))
430 (defun org-attach-delete-one (&optional file)
431 "Delete a single attachment."
432 (interactive)
433 (let* ((attach-dir (org-attach-dir t))
434 (files (org-attach-file-list attach-dir))
435 (file (or file
436 (completing-read
437 "Delete attachment: "
438 (mapcar (lambda (f)
439 (list (file-name-nondirectory f)))
440 files)))))
441 (setq file (expand-file-name file attach-dir))
442 (unless (file-exists-p file)
443 (error "No such attachment: %s" file))
444 (delete-file file)
445 (org-attach-commit)))
447 (defun org-attach-delete-all (&optional force)
448 "Delete all attachments from the current task.
449 This actually deletes the entire attachment directory.
450 A safer way is to open the directory in dired and delete from there."
451 (interactive "P")
452 (when (and org-attach-file-list-property (not org-attach-inherited))
453 (org-entry-delete (point) org-attach-file-list-property))
454 (let ((attach-dir (org-attach-dir)))
455 (when
456 (and attach-dir
457 (or force
458 (y-or-n-p "Are you sure you want to remove all attachments of this entry? ")))
459 (shell-command (format "rm -fr %s" attach-dir))
460 (message "Attachment directory removed")
461 (org-attach-commit)
462 (org-attach-untag))))
464 (defun org-attach-sync ()
465 "Synchronize the current tasks with its attachments.
466 This can be used after files have been added externally."
467 (interactive)
468 (org-attach-commit)
469 (when (and org-attach-file-list-property (not org-attach-inherited))
470 (org-entry-delete (point) org-attach-file-list-property))
471 (let ((attach-dir (org-attach-dir)))
472 (when attach-dir
473 (let ((files (org-attach-file-list attach-dir)))
474 (and files (org-attach-tag))
475 (when org-attach-file-list-property
476 (dolist (file files)
477 (unless (string-match "^\\.\\.?\\'" file)
478 (org-entry-add-to-multivalued-property
479 (point) org-attach-file-list-property file))))))))
481 (defun org-attach-file-list (dir)
482 "Return a list of files in the attachment directory.
483 This ignores files ending in \"~\"."
484 (delq nil
485 (mapcar (lambda (x) (if (string-match "^\\.\\.?\\'" x) nil x))
486 (directory-files dir nil "[^~]\\'"))))
488 (defun org-attach-reveal (&optional if-exists)
489 "Show the attachment directory of the current task.
490 This will attempt to use an external program to show the directory."
491 (interactive "P")
492 (let ((attach-dir (org-attach-dir (not if-exists))))
493 (and attach-dir (org-open-file attach-dir))))
495 (defun org-attach-reveal-in-emacs ()
496 "Show the attachment directory of the current task in dired."
497 (interactive)
498 (let ((attach-dir (org-attach-dir t)))
499 (dired attach-dir)))
501 (defun org-attach-open (&optional in-emacs)
502 "Open an attachment of the current task.
503 If there are more than one attachment, you will be prompted for the file name.
504 This command will open the file using the settings in `org-file-apps'
505 and in the system-specific variants of this variable.
506 If IN-EMACS is non-nil, force opening in Emacs."
507 (interactive "P")
508 (let* ((attach-dir (org-attach-dir t))
509 (files (org-attach-file-list attach-dir))
510 (file (if (= (length files) 1)
511 (car files)
512 (completing-read "Open attachment: "
513 (mapcar #'list files) nil t)))
514 (path (expand-file-name file attach-dir)))
515 (org-attach-annex-get-maybe path)
516 (org-open-file path in-emacs)))
518 (defun org-attach-open-in-emacs ()
519 "Open attachment, force opening in Emacs.
520 See `org-attach-open'."
521 (interactive)
522 (org-attach-open 'in-emacs))
524 (defun org-attach-expand (file)
525 "Return the full path to the current entry's attachment file FILE.
526 Basically, this adds the path to the attachment directory."
527 (expand-file-name file (org-attach-dir)))
529 (defun org-attach-expand-link (file)
530 "Return a file link pointing to the current entry's attachment file FILE.
531 Basically, this adds the path to the attachment directory, and a \"file:\"
532 prefix."
533 (concat "file:" (org-attach-expand file)))
535 (defun org-attach-archive-delete-maybe ()
536 "Maybe delete subtree attachments when archiving.
537 This function is called by `org-archive-hook'. The option
538 `org-attach-archive-delete' controls its behavior."
539 (when (if (eq org-attach-archive-delete 'query)
540 (yes-or-no-p "Delete all attachments? ")
541 org-attach-archive-delete)
542 (org-attach-delete-all t)))
544 (add-hook 'org-archive-hook 'org-attach-archive-delete-maybe)
546 (provide 'org-attach)
548 ;; Local variables:
549 ;; generated-autoload-file: "org-loaddefs.el"
550 ;; End:
552 ;;; org-attach.el ends here