org-attach.el 31 KB

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