org-attach.el 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. ;;; org-attach.el --- Manage file attachments to Org outlines -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2008-2022 Free Software Foundation, Inc.
  3. ;; Author: John Wiegley <johnw@newartisans.com>
  4. ;; Keywords: org data attachment
  5. ;; This file is part of GNU Emacs.
  6. ;;
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; See the Org manual for information on how to use it.
  19. ;;
  20. ;; Attachments are managed either by using a custom property DIR or by
  21. ;; using property ID from org-id. When DIR is defined, a location in
  22. ;; the filesystem is directly attached to the outline node. When
  23. ;; org-id is used, attachments are stored in a folder named after the
  24. ;; ID, in a location defined by `org-attach-id-dir'. DIR has
  25. ;; precedence over ID when both parameters are defined for the current
  26. ;; outline node (also when inherited parameters are taken into
  27. ;; account).
  28. ;;; Code:
  29. (require 'cl-lib)
  30. (require 'org)
  31. (require 'ol)
  32. (require 'org-id)
  33. (declare-function dired-dwim-target-directory "dired-aux")
  34. (declare-function dired-get-marked-files "dired" (&optional localp arg filter distinguish-one-marked error))
  35. (declare-function org-element-property "org-element" (property element))
  36. (declare-function org-element-type "org-element" (element))
  37. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  38. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  39. (defgroup org-attach nil
  40. "Options concerning attachments in Org mode."
  41. :tag "Org Attach"
  42. :group 'org)
  43. (defcustom org-attach-id-dir "data/"
  44. "The directory where attachments are stored.
  45. If this is a relative path, it will be interpreted relative to the directory
  46. where the Org file lives."
  47. :group 'org-attach
  48. :type 'directory
  49. :safe #'stringp)
  50. (defcustom org-attach-dir-relative nil
  51. "Non-nil means directories in DIR property are added as relative links.
  52. Defaults to absolute location."
  53. :group 'org-attach
  54. :type 'boolean
  55. :package-version '(Org . "9.3")
  56. :safe #'booleanp)
  57. (defcustom org-attach-auto-tag "ATTACH"
  58. "Tag that will be triggered automatically when an entry has an attachment."
  59. :group 'org-attach
  60. :type '(choice
  61. (const :tag "None" nil)
  62. (string :tag "Tag")))
  63. (defcustom org-attach-preferred-new-method 'id
  64. "Preferred way to attach to nodes without existing ID and DIR property.
  65. This choice is used when adding attachments to nodes without ID
  66. and DIR properties.
  67. Allowed values are:
  68. id Create and use an ID parameter
  69. dir Create and use a DIR parameter
  70. ask Ask the user for input of which method to choose
  71. nil Prefer to not create a new parameter
  72. nil means that ID or DIR has to be created explicitly
  73. before attaching files."
  74. :group 'org-attach
  75. :package-version '(org . "9.3")
  76. :type '(choice
  77. (const :tag "ID parameter" id)
  78. (const :tag "DIR parameter" dir)
  79. (const :tag "Ask user" ask)
  80. (const :tag "Don't create" nil)))
  81. (defcustom org-attach-method 'cp
  82. "The preferred method to attach a file.
  83. Allowed values are:
  84. mv rename the file to move it into the attachment directory
  85. cp copy the file
  86. ln create a hard link. Note that this is not supported
  87. on all systems, and then the result is not defined.
  88. lns create a symbol link. Note that this is not supported
  89. on all systems, and then the result is not defined."
  90. :group 'org-attach
  91. :type '(choice
  92. (const :tag "Copy" cp)
  93. (const :tag "Move/Rename" mv)
  94. (const :tag "Hard Link" ln)
  95. (const :tag "Symbol Link" lns)))
  96. (defcustom org-attach-expert nil
  97. "Non-nil means do not show the splash buffer with the attach dispatcher."
  98. :group 'org-attach
  99. :type 'boolean)
  100. (defcustom org-attach-use-inheritance 'selective
  101. "Attachment inheritance for the outline.
  102. Enabling inheritance for `org-attach' implies two things. First,
  103. that attachment links will look through all parent headings until
  104. it finds the linked attachment. Second, that running org-attach
  105. inside a node without attachments will make org-attach operate on
  106. the first parent heading it finds with an attachment.
  107. Selective means to respect the inheritance setting in
  108. `org-use-property-inheritance'."
  109. :group 'org-attach
  110. :type '(choice
  111. (const :tag "Don't use inheritance" nil)
  112. (const :tag "Inherit parent node attachments" t)
  113. (const :tag "Respect org-use-property-inheritance" selective)))
  114. (defcustom org-attach-store-link-p nil
  115. "Non-nil means store a link to a file when attaching it."
  116. :group 'org-attach
  117. :version "24.1"
  118. :type '(choice
  119. (const :tag "Don't store link" nil)
  120. (const :tag "Link to origin location" t)
  121. (const :tag "Attachment link to the attach-dir location" attached)
  122. (const :tag "File link to the attach-dir location" file)))
  123. (defcustom org-attach-archive-delete nil
  124. "Non-nil means attachments are deleted upon archiving a subtree.
  125. When set to `query', ask the user instead."
  126. :group 'org-attach
  127. :version "26.1"
  128. :package-version '(Org . "8.3")
  129. :type '(choice
  130. (const :tag "Never delete attachments" nil)
  131. (const :tag "Always delete attachments" t)
  132. (const :tag "Query the user" query)))
  133. (defun org-attach-id-uuid-folder-format (id)
  134. "Translate an UUID ID into a folder-path.
  135. Default format for how Org translates ID properties to a path for
  136. attachments. Useful if ID is generated with UUID."
  137. (format "%s/%s"
  138. (substring id 0 2)
  139. (substring id 2)))
  140. (defun org-attach-id-ts-folder-format (id)
  141. "Translate an ID based on a timestamp to a folder-path.
  142. Useful way of translation if ID is generated based on ISO8601
  143. timestamp. Splits the attachment folder hierarchy into
  144. year-month, the rest."
  145. (format "%s/%s"
  146. (substring id 0 6)
  147. (substring id 6)))
  148. (defcustom org-attach-id-to-path-function-list '(org-attach-id-uuid-folder-format
  149. org-attach-id-ts-folder-format)
  150. "List of functions parsing an ID string into a folder-path.
  151. The first function in this list defines the preferred function
  152. which will be used when creating new attachment folders. All
  153. functions of this list will be tried when looking for existing
  154. attachment folders based on ID."
  155. :group 'org-attach
  156. :package-version '(Org . "9.3")
  157. :type '(repeat (function :tag "Function with ID as input")))
  158. (defvar org-attach-after-change-hook nil
  159. "Hook called when files have been added or removed to the attachment folder.")
  160. (defvar org-attach-open-hook nil
  161. "Hook that is invoked by `org-attach-open'.
  162. Created mostly to be compatible with org-attach-git after removing
  163. git-functionality from this file.")
  164. (defcustom org-attach-commands
  165. '(((?a ?\C-a) org-attach-attach
  166. "Select a file and attach it to the task, using `org-attach-method'.")
  167. ((?c ?\C-c) org-attach-attach-cp
  168. "Attach a file using copy method.")
  169. ((?m ?\C-m) org-attach-attach-mv
  170. "Attach a file using move method.")
  171. ((?l ?\C-l) org-attach-attach-ln
  172. "Attach a file using link method.")
  173. ((?y ?\C-y) org-attach-attach-lns
  174. "Attach a file using symbolic-link method.")
  175. ((?u ?\C-u) org-attach-url
  176. "Attach a file from URL (downloading it).")
  177. ((?b) org-attach-buffer
  178. "Select a buffer and attach its contents to the task.")
  179. ((?n ?\C-n) org-attach-new
  180. "Create a new attachment, as an Emacs buffer.")
  181. ((?z ?\C-z) org-attach-sync
  182. "Synchronize the current node with its attachment\n directory, in case \
  183. you added attachments yourself.\n")
  184. ((?o ?\C-o) org-attach-open
  185. "Open current node's attachments.")
  186. ((?O) org-attach-open-in-emacs
  187. "Like \"o\", but force opening in Emacs.")
  188. ((?f ?\C-f) org-attach-reveal
  189. "Open current node's attachment directory. Create if missing.")
  190. ((?F) org-attach-reveal-in-emacs
  191. "Like \"f\", but force using Dired in Emacs.\n")
  192. ((?d ?\C-d) org-attach-delete-one
  193. "Delete one attachment, you will be prompted for a file name.")
  194. ((?D) org-attach-delete-all
  195. "Delete all of a node's attachments. A safer way is\n to open the \
  196. directory in dired and delete from there.\n")
  197. ((?s ?\C-s) org-attach-set-directory
  198. "Set a specific attachment directory for this entry. Sets DIR property.")
  199. ((?S ?\C-S) org-attach-unset-directory
  200. "Unset the attachment directory for this entry. Removes DIR property.")
  201. ((?q) (lambda () (interactive) (message "Abort")) "Abort."))
  202. "The list of commands for the attachment dispatcher.
  203. Each entry in this list is a list of three elements:
  204. - A list of keys (characters) to select the command (the fist
  205. character in the list is shown in the attachment dispatcher's
  206. splash buffer and minibuffer prompt).
  207. - A command that is called interactively when one of these keys
  208. is pressed.
  209. - A docstring for this command in the attachment dispatcher's
  210. splash buffer."
  211. :group 'org-attach
  212. :package-version '(Org . "9.3")
  213. :type '(repeat (list (repeat :tag "Keys" character)
  214. (function :tag "Command")
  215. (string :tag "Docstring"))))
  216. (defcustom org-attach-sync-delete-empty-dir 'query
  217. "Determine what to do with an empty attachment directory on sync.
  218. When set to nil, don't touch the directory. When set to `query',
  219. ask the user instead, else remove without asking."
  220. :group 'org-attach
  221. :package-version '(Org . "9.5")
  222. :type '(choice
  223. (const :tag "Never delete" nil)
  224. (const :tag "Always delete" t)
  225. (const :tag "Query the user" query)))
  226. ;;;###autoload
  227. (defun org-attach ()
  228. "The dispatcher for attachment commands.
  229. Shows a list of commands and prompts for another key to execute a command."
  230. (interactive)
  231. (let ((dir (org-attach-dir nil 'no-fs-check))
  232. c marker)
  233. (when (eq major-mode 'org-agenda-mode)
  234. (setq marker (or (get-text-property (point) 'org-hd-marker)
  235. (get-text-property (point) 'org-marker)))
  236. (unless marker
  237. (error "No item in current line")))
  238. (org-with-point-at marker
  239. (if (and (featurep 'org-inlinetask)
  240. (not (org-inlinetask-in-task-p)))
  241. (org-with-limited-levels
  242. (org-back-to-heading-or-point-min t))
  243. (if (and (featurep 'org-inlinetask)
  244. (org-inlinetask-in-task-p))
  245. (org-inlinetask-goto-beginning)
  246. (org-back-to-heading-or-point-min t)))
  247. (save-excursion
  248. (save-window-excursion
  249. (unless org-attach-expert
  250. (org-switch-to-buffer-other-window "*Org Attach*")
  251. (erase-buffer)
  252. (setq cursor-type nil
  253. header-line-format "Use C-v, M-v, C-n or C-p to navigate.")
  254. (insert
  255. (concat "Attachment folder:\n"
  256. (or dir
  257. "Can't find an existing attachment-folder")
  258. (unless (and dir (file-directory-p dir))
  259. "\n(Not yet created)")
  260. "\n\n"
  261. (format "Select an Attachment Command:\n\n%s"
  262. (mapconcat
  263. (lambda (entry)
  264. (pcase entry
  265. (`((,key . ,_) ,_ ,docstring)
  266. (format "%c %s"
  267. key
  268. (replace-regexp-in-string "\n\\([\t ]*\\)"
  269. " "
  270. docstring
  271. nil nil 1)))
  272. (_
  273. (user-error
  274. "Invalid `org-attach-commands' item: %S"
  275. entry))))
  276. org-attach-commands
  277. "\n")))))
  278. (org-fit-window-to-buffer (get-buffer-window "*Org Attach*"))
  279. (let ((msg (format "Select command: [%s]"
  280. (concat (mapcar #'caar org-attach-commands)))))
  281. (message msg)
  282. (while (and (setq c (read-char-exclusive))
  283. (memq c '(14 16 22 134217846)))
  284. (org-scroll c t)))
  285. (and (get-buffer "*Org Attach*") (kill-buffer "*Org Attach*"))))
  286. (let ((command (cl-some (lambda (entry)
  287. (and (memq c (nth 0 entry)) (nth 1 entry)))
  288. org-attach-commands)))
  289. (if (commandp command t)
  290. (call-interactively command)
  291. (error "No such attachment command: %c" c))))))
  292. (defun org-attach-dir (&optional create-if-not-exists-p no-fs-check)
  293. "Return the directory associated with the current outline node.
  294. First check for DIR property, then ID property.
  295. `org-attach-use-inheritance' determines whether inherited
  296. properties also will be considered.
  297. If an ID property is found the default mechanism using that ID
  298. will be invoked to access the directory for the current entry.
  299. Note that this method returns the directory as declared by ID or
  300. DIR even if the directory doesn't exist in the filesystem.
  301. If CREATE-IF-NOT-EXIST-P is non-nil, `org-attach-dir-get-create'
  302. is run. If NO-FS-CHECK is non-nil, the function returns the path
  303. to the attachment even if it has not yet been initialized in the
  304. filesystem.
  305. If no attachment directory can be derived, return nil."
  306. (let (attach-dir id)
  307. (cond
  308. (create-if-not-exists-p
  309. (setq attach-dir (org-attach-dir-get-create)))
  310. ((setq attach-dir (org-entry-get nil "DIR" org-attach-use-inheritance))
  311. (org-attach-check-absolute-path attach-dir))
  312. ;; Deprecated and removed from documentation, but still
  313. ;; works. FIXME: Remove after major nr change.
  314. ((setq attach-dir (org-entry-get nil "ATTACH_DIR" org-attach-use-inheritance))
  315. (org-attach-check-absolute-path attach-dir))
  316. ((setq id (org-entry-get nil "ID" org-attach-use-inheritance))
  317. (org-attach-check-absolute-path nil)
  318. (setq attach-dir (org-attach-dir-from-id id 'try-all))))
  319. (if no-fs-check
  320. attach-dir
  321. (when (and attach-dir (file-directory-p attach-dir))
  322. attach-dir))))
  323. (defun org-attach-dir-get-create ()
  324. "Return existing or new directory associated with the current outline node.
  325. `org-attach-preferred-new-method' decides how to attach new
  326. directory if neither ID nor DIR property exist.
  327. If the attachment by some reason cannot be created an error will be raised."
  328. (interactive)
  329. (let ((attach-dir (org-attach-dir nil 'no-fs-check)))
  330. (unless attach-dir
  331. (let (answer)
  332. (when (eq org-attach-preferred-new-method 'ask)
  333. (message "Create new ID [1] property or DIR [2] property for attachments?")
  334. (setq answer (read-char-exclusive)))
  335. (cond
  336. ((or (eq org-attach-preferred-new-method 'id) (eq answer ?1))
  337. (setq attach-dir (org-attach-dir-from-id (org-id-get nil t))))
  338. ((or (eq org-attach-preferred-new-method 'dir) (eq answer ?2))
  339. (setq attach-dir (org-attach-set-directory)))
  340. ((eq org-attach-preferred-new-method 'nil)
  341. (error "No existing directory. DIR or ID property has to be explicitly created")))))
  342. (unless attach-dir
  343. (error "No attachment directory is associated with the current node"))
  344. (unless (file-directory-p attach-dir)
  345. (make-directory attach-dir t))
  346. attach-dir))
  347. (defun org-attach-dir-from-id (id &optional try-all)
  348. "Return a folder path based on `org-attach-id-dir' and ID.
  349. If TRY-ALL is non-nil, try all id-to-path functions in
  350. `org-attach-id-to-path-function-list' and return the first path
  351. that exist in the filesystem, or the first one if none exist.
  352. Otherwise only use the first function in that list."
  353. (let ((attach-dir-preferred (expand-file-name
  354. (funcall (car org-attach-id-to-path-function-list) id)
  355. (expand-file-name org-attach-id-dir))))
  356. (if try-all
  357. (let ((attach-dir attach-dir-preferred)
  358. (fun-list (cdr org-attach-id-to-path-function-list)))
  359. (while (and fun-list (not (file-directory-p attach-dir)))
  360. (setq attach-dir (expand-file-name
  361. (funcall (car fun-list) id)
  362. (expand-file-name org-attach-id-dir)))
  363. (setq fun-list (cdr fun-list)))
  364. (if (file-directory-p attach-dir)
  365. attach-dir
  366. attach-dir-preferred))
  367. attach-dir-preferred)))
  368. (defun org-attach-check-absolute-path (dir)
  369. "Check if we have enough information to root the attachment directory.
  370. When DIR is given, check also if it is already absolute. Otherwise,
  371. assume that it will be relative, and check if `org-attach-id-dir' is
  372. absolute, or if at least the current buffer has a file name.
  373. Throw an error if we cannot root the directory."
  374. (or (and dir (file-name-absolute-p dir))
  375. (file-name-absolute-p org-attach-id-dir)
  376. (buffer-file-name (buffer-base-buffer))
  377. (error "Need absolute `org-attach-id-dir' to attach in buffers without filename")))
  378. (defun org-attach-set-directory ()
  379. "Set the DIR node property and ask to move files there.
  380. The property defines the directory that is used for attachments
  381. of the entry. Creates relative links if `org-attach-dir-relative'
  382. is non-nil.
  383. Return the directory."
  384. (interactive)
  385. (let ((old (org-attach-dir))
  386. (new
  387. (let* ((attach-dir (read-directory-name
  388. "Attachment directory: "
  389. (org-entry-get nil "DIR")))
  390. (current-dir (file-name-directory (or default-directory
  391. buffer-file-name)))
  392. (attach-dir-relative (file-relative-name attach-dir current-dir)))
  393. (org-entry-put nil "DIR" (if org-attach-dir-relative
  394. attach-dir-relative
  395. attach-dir))
  396. attach-dir)))
  397. (unless (or (string= old new)
  398. (not old))
  399. (when (yes-or-no-p "Copy over attachments from old directory? ")
  400. (copy-directory old new t t t))
  401. (when (yes-or-no-p (concat "Delete " old))
  402. (delete-directory old t)))
  403. new))
  404. (defun org-attach-unset-directory ()
  405. "Remove DIR node property.
  406. If attachment folder is changed due to removal of DIR-property
  407. ask to move attachments to new location and ask to delete old
  408. attachment-folder.
  409. Change of attachment-folder due to unset might be if an ID
  410. property is set on the node, or if a separate inherited
  411. DIR-property exists (that is different from the unset one)."
  412. (interactive)
  413. (let ((old (org-attach-dir))
  414. (new
  415. (progn
  416. (org-entry-delete nil "DIR")
  417. ;; ATTACH-DIR is deprecated and removed from documentation,
  418. ;; but still works. Remove code for it after major nr change.
  419. (org-entry-delete nil "ATTACH_DIR")
  420. (org-attach-dir))))
  421. (unless (or (string= old new)
  422. (not old))
  423. (when (and new (yes-or-no-p "Copy over attachments from old directory? "))
  424. (copy-directory old new t nil t))
  425. (when (yes-or-no-p (concat "Delete " old))
  426. (delete-directory old t)))))
  427. (defun org-attach-tag (&optional off)
  428. "Turn the autotag on or (if OFF is set) off."
  429. (when org-attach-auto-tag
  430. (save-excursion
  431. (org-back-to-heading t)
  432. (org-toggle-tag org-attach-auto-tag (if off 'off 'on)))))
  433. (defun org-attach-untag ()
  434. "Turn the autotag off."
  435. (org-attach-tag 'off))
  436. (defun org-attach-url (url)
  437. (interactive "MURL of the file to attach: \n")
  438. (let ((org-attach-method 'url))
  439. (org-attach-attach url)))
  440. (defun org-attach-buffer (buffer-name)
  441. "Attach BUFFER-NAME's contents to current outline node.
  442. BUFFER-NAME is a string. Signals a `file-already-exists' error
  443. if it would overwrite an existing filename."
  444. (interactive "bBuffer whose contents should be attached: ")
  445. (let* ((attach-dir (org-attach-dir 'get-create))
  446. (output (expand-file-name buffer-name attach-dir)))
  447. (when (file-exists-p output)
  448. (signal 'file-already-exists (list "File exists" output)))
  449. (run-hook-with-args 'org-attach-after-change-hook attach-dir)
  450. (org-attach-tag)
  451. (with-temp-file output
  452. (insert-buffer-substring buffer-name))))
  453. (defun org-attach-attach (file &optional visit-dir method)
  454. "Move/copy/link FILE into the attachment directory of the current outline node.
  455. If VISIT-DIR is non-nil, visit the directory with dired.
  456. METHOD may be `cp', `mv', `ln', `lns' or `url' default taken from
  457. `org-attach-method'."
  458. (interactive
  459. (list
  460. (read-file-name "File to keep as an attachment: "
  461. (or (progn
  462. (require 'dired-aux)
  463. (dired-dwim-target-directory))
  464. default-directory))
  465. current-prefix-arg
  466. nil))
  467. (setq method (or method org-attach-method))
  468. (let ((basename (file-name-nondirectory file)))
  469. (let* ((attach-dir (org-attach-dir 'get-create))
  470. (attach-file (expand-file-name basename attach-dir)))
  471. (cond
  472. ((eq method 'mv) (rename-file file attach-file))
  473. ((eq method 'cp) (copy-file file attach-file))
  474. ((eq method 'ln) (add-name-to-file file attach-file))
  475. ((eq method 'lns) (make-symbolic-link file attach-file))
  476. ((eq method 'url) (url-copy-file file attach-file)))
  477. (run-hook-with-args 'org-attach-after-change-hook attach-dir)
  478. (org-attach-tag)
  479. (cond ((eq org-attach-store-link-p 'attached)
  480. (push (list (concat "attachment:" (file-name-nondirectory attach-file))
  481. (file-name-nondirectory attach-file))
  482. org-stored-links))
  483. ((eq org-attach-store-link-p t)
  484. (push (list (concat "file:" file)
  485. (file-name-nondirectory file))
  486. org-stored-links))
  487. ((eq org-attach-store-link-p 'file)
  488. (push (list (concat "file:" attach-file)
  489. (file-name-nondirectory attach-file))
  490. org-stored-links)))
  491. (if visit-dir
  492. (dired attach-dir)
  493. (message "File %S is now an attachment" basename)))))
  494. (defun org-attach-attach-cp ()
  495. "Attach a file by copying it."
  496. (interactive)
  497. (let ((org-attach-method 'cp)) (call-interactively 'org-attach-attach)))
  498. (defun org-attach-attach-mv ()
  499. "Attach a file by moving (renaming) it."
  500. (interactive)
  501. (let ((org-attach-method 'mv)) (call-interactively 'org-attach-attach)))
  502. (defun org-attach-attach-ln ()
  503. "Attach a file by creating a hard link to it.
  504. Beware that this does not work on systems that do not support hard links.
  505. On some systems, this apparently does copy the file instead."
  506. (interactive)
  507. (let ((org-attach-method 'ln)) (call-interactively 'org-attach-attach)))
  508. (defun org-attach-attach-lns ()
  509. "Attach a file by creating a symbolic link to it.
  510. Beware that this does not work on systems that do not support symbolic links.
  511. On some systems, this apparently does copy the file instead."
  512. (interactive)
  513. (let ((org-attach-method 'lns)) (call-interactively 'org-attach-attach)))
  514. (defun org-attach-new (file)
  515. "Create a new attachment FILE for the current outline node.
  516. The attachment is created as an Emacs buffer."
  517. (interactive "sCreate attachment named: ")
  518. (let ((attach-dir (org-attach-dir 'get-create)))
  519. (org-attach-tag)
  520. (find-file (expand-file-name file attach-dir))
  521. (message "New attachment %s" file)))
  522. (defun org-attach-delete-one (&optional file)
  523. "Delete a single attachment."
  524. (interactive)
  525. (let* ((attach-dir (org-attach-dir))
  526. (files (org-attach-file-list attach-dir))
  527. (file (or file
  528. (completing-read
  529. "Delete attachment: "
  530. (mapcar (lambda (f)
  531. (list (file-name-nondirectory f)))
  532. files)))))
  533. (setq file (expand-file-name file attach-dir))
  534. (unless (file-exists-p file)
  535. (error "No such attachment: %s" file))
  536. (delete-file file)
  537. (run-hook-with-args 'org-attach-after-change-hook attach-dir)))
  538. (defun org-attach-delete-all (&optional force)
  539. "Delete all attachments from the current outline node.
  540. This actually deletes the entire attachment directory.
  541. A safer way is to open the directory in dired and delete from there.
  542. With prefix argument FORCE, directory will be recursively deleted
  543. with no prompts."
  544. (interactive "P")
  545. (let ((attach-dir (org-attach-dir)))
  546. (when (and attach-dir
  547. (or force
  548. (yes-or-no-p "Really remove all attachments of this entry? ")))
  549. (delete-directory attach-dir
  550. (or force (yes-or-no-p "Recursive?"))
  551. t)
  552. (message "Attachment directory removed")
  553. (run-hook-with-args 'org-attach-after-change-hook attach-dir)
  554. (org-attach-untag))))
  555. (defun org-attach-sync ()
  556. "Synchronize the current outline node with its attachments.
  557. Useful after files have been added/removed externally. Option
  558. `org-attach-sync-delete-empty-dir' controls the behavior for
  559. empty attachment directories."
  560. (interactive)
  561. (let ((attach-dir (org-attach-dir)))
  562. (if (not attach-dir)
  563. (org-attach-tag 'off)
  564. (run-hook-with-args 'org-attach-after-change-hook attach-dir)
  565. (let ((files (org-attach-file-list attach-dir)))
  566. (org-attach-tag (not files)))
  567. (when org-attach-sync-delete-empty-dir
  568. (when (and (org-directory-empty-p attach-dir)
  569. (if (eq 'query org-attach-sync-delete-empty-dir)
  570. (yes-or-no-p "Attachment directory is empty. Delete?")
  571. t))
  572. (delete-directory attach-dir))))))
  573. (defun org-attach-file-list (dir)
  574. "Return a list of files in the attachment directory.
  575. This ignores files ending in \"~\"."
  576. (delq nil
  577. (mapcar (lambda (x) (if (string-match "^\\.\\.?\\'" x) nil x))
  578. (directory-files dir nil "[^~]\\'"))))
  579. (defun org-attach-reveal ()
  580. "Show the attachment directory of the current outline node.
  581. This will attempt to use an external program to show the
  582. directory. Will create an attachment and folder if it doesn't
  583. exist yet. Respects `org-attach-preferred-new-method'."
  584. (interactive)
  585. (org-open-file (org-attach-dir-get-create)))
  586. (defun org-attach-reveal-in-emacs ()
  587. "Show the attachment directory of the current outline node in dired.
  588. Will create an attachment and folder if it doesn't exist yet.
  589. Respects `org-attach-preferred-new-method'."
  590. (interactive)
  591. (dired (org-attach-dir-get-create)))
  592. (defun org-attach-open (&optional in-emacs)
  593. "Open an attachment of the current outline node.
  594. If there are more than one attachment, you will be prompted for the file name.
  595. This command will open the file using the settings in `org-file-apps'
  596. and in the system-specific variants of this variable.
  597. If IN-EMACS is non-nil, force opening in Emacs."
  598. (interactive "P")
  599. (let ((attach-dir (org-attach-dir)))
  600. (if attach-dir
  601. (let* ((file (pcase (org-attach-file-list attach-dir)
  602. (`(,file) file)
  603. (files (completing-read "Open attachment: "
  604. (mapcar #'list files) nil t))))
  605. (path (expand-file-name file attach-dir)))
  606. (run-hook-with-args 'org-attach-open-hook path)
  607. (org-open-file path in-emacs))
  608. (error "No attachment directory exist"))))
  609. (defun org-attach-open-in-emacs ()
  610. "Open attachment, force opening in Emacs.
  611. See `org-attach-open'."
  612. (interactive)
  613. (org-attach-open 'in-emacs))
  614. (defun org-attach-expand (file)
  615. "Return the full path to the current entry's attachment file FILE.
  616. Basically, this adds the path to the attachment directory."
  617. (expand-file-name file (org-attach-dir)))
  618. (defun org-attach-expand-links (_)
  619. "Expand links in current buffer.
  620. It is meant to be added to `org-export-before-parsing-hook'."
  621. (save-excursion
  622. (while (re-search-forward "attachment:" nil t)
  623. (let ((link (org-element-context)))
  624. (when (and (eq 'link (org-element-type link))
  625. (string-equal "attachment"
  626. (org-element-property :type link)))
  627. (let* ((description (and (org-element-property :contents-begin link)
  628. (buffer-substring-no-properties
  629. (org-element-property :contents-begin link)
  630. (org-element-property :contents-end link))))
  631. (file (org-element-property :path link))
  632. (new-link (org-link-make-string
  633. (concat "file:" (org-attach-expand file))
  634. description)))
  635. (goto-char (org-element-property :end link))
  636. (skip-chars-backward " \t")
  637. (delete-region (org-element-property :begin link) (point))
  638. (insert new-link)))))))
  639. (defun org-attach-follow (file arg)
  640. "Open FILE attachment.
  641. See `org-open-file' for details about ARG."
  642. (org-link-open-as-file (org-attach-expand file) arg))
  643. (org-link-set-parameters "attachment"
  644. :follow #'org-attach-follow
  645. :complete #'org-attach-complete-link)
  646. (defun org-attach-complete-link ()
  647. "Advise the user with the available files in the attachment directory."
  648. (let ((attach-dir (org-attach-dir)))
  649. (if attach-dir
  650. (let* ((attached-dir (expand-file-name attach-dir))
  651. (file (read-file-name "File: " attached-dir))
  652. (pwd (file-name-as-directory attached-dir))
  653. (pwd-relative (file-name-as-directory
  654. (abbreviate-file-name attached-dir))))
  655. (cond
  656. ((string-match (concat "^" (regexp-quote pwd-relative) "\\(.+\\)") file)
  657. (concat "attachment:" (match-string 1 file)))
  658. ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
  659. (expand-file-name file))
  660. (concat "attachment:" (match-string 1 (expand-file-name file))))
  661. (t (concat "attachment:" file))))
  662. (error "No attachment directory exist"))))
  663. (defun org-attach-archive-delete-maybe ()
  664. "Maybe delete subtree attachments when archiving.
  665. This function is called by `org-archive-hook'. The option
  666. `org-attach-archive-delete' controls its behavior."
  667. (when org-attach-archive-delete
  668. (org-attach-delete-all (not (eq org-attach-archive-delete 'query)))))
  669. ;; Attach from dired.
  670. ;; Add the following lines to the config file to get a binding for
  671. ;; dired-mode.
  672. ;; (add-hook
  673. ;; 'dired-mode-hook
  674. ;; (lambda ()
  675. ;; (define-key dired-mode-map (kbd "C-c C-x a") #'org-attach-dired-to-subtree))))
  676. ;;;###autoload
  677. (defun org-attach-dired-to-subtree (files)
  678. "Attach FILES marked or current file in dired to subtree in other window.
  679. Takes the method given in `org-attach-method' for the attach action.
  680. Precondition: Point must be in a dired buffer.
  681. Idea taken from `gnus-dired-attach'."
  682. (interactive
  683. (list (dired-get-marked-files)))
  684. (unless (eq major-mode 'dired-mode)
  685. (user-error "This command must be triggered in a dired buffer"))
  686. (let ((start-win (selected-window))
  687. (other-win
  688. (get-window-with-predicate
  689. (lambda (window)
  690. (with-current-buffer (window-buffer window)
  691. (eq major-mode 'org-mode))))))
  692. (unless other-win
  693. (user-error
  694. "Can't attach to subtree. No window displaying an Org buffer"))
  695. (select-window other-win)
  696. (dolist (file files)
  697. (org-attach-attach file))
  698. (select-window start-win)
  699. (when (eq 'mv org-attach-method)
  700. (revert-buffer))))
  701. (add-hook 'org-archive-hook 'org-attach-archive-delete-maybe)
  702. (add-hook 'org-export-before-parsing-hook 'org-attach-expand-links)
  703. (provide 'org-attach)
  704. ;; Local variables:
  705. ;; generated-autoload-file: "org-loaddefs.el"
  706. ;; End:
  707. ;;; org-attach.el ends here