org-attach.el 29 KB

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