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