org-attach.el 29 KB

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