org-attach.el 29 KB

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