org-refile.el 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. ;;; org-refile.el --- Refile Org Subtrees -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2010-2021 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;;
  6. ;; This file is part of GNU Emacs.
  7. ;; This program 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. ;; This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; Org Refile allows you to refile subtrees to various locations.
  19. ;;; Code:
  20. (require 'org)
  21. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  22. (defgroup org-refile nil
  23. "Options concerning refiling entries in Org mode."
  24. :tag "Org Refile"
  25. :group 'org)
  26. (defcustom org-log-refile nil
  27. "Information to record when a task is refiled.
  28. Possible values are:
  29. nil Don't add anything
  30. time Add a time stamp to the task
  31. note Prompt for a note and add it with template `org-log-note-headings'
  32. This option can also be set with on a per-file-basis with
  33. #+STARTUP: nologrefile
  34. #+STARTUP: logrefile
  35. #+STARTUP: lognoterefile
  36. You can have local logging settings for a subtree by setting the LOGGING
  37. property to one or more of these keywords.
  38. When bulk-refiling, e.g., from the agenda, the value `note' is
  39. forbidden and will temporarily be changed to `time'."
  40. :group 'org-refile
  41. :group 'org-progress
  42. :version "24.1"
  43. :type '(choice
  44. (const :tag "No logging" nil)
  45. (const :tag "Record timestamp" time)
  46. (const :tag "Record timestamp with note." note)))
  47. (defcustom org-refile-targets nil
  48. "Targets for refiling entries with `\\[org-refile]'.
  49. This is a list of cons cells. Each cell contains:
  50. - a specification of the files to be considered, either a list of files,
  51. or a symbol whose function or variable value will be used to retrieve
  52. a file name or a list of file names. If you use `org-agenda-files' for
  53. that, all agenda files will be scanned for targets. Nil means consider
  54. headings in the current buffer.
  55. - A specification of how to find candidate refile targets. This may be
  56. any of:
  57. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  58. This tag has to be present in all target headlines, inheritance will
  59. not be considered.
  60. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  61. todo keyword.
  62. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  63. headlines that are refiling targets.
  64. - a cons cell (:level . N). Any headline of level N is considered a target.
  65. Note that, when `org-odd-levels-only' is set, level corresponds to
  66. order in hierarchy, not to the number of stars.
  67. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  68. Note that, when `org-odd-levels-only' is set, level corresponds to
  69. order in hierarchy, not to the number of stars.
  70. Each element of this list generates a set of possible targets.
  71. The union of these sets is presented (with completion) to
  72. the user by `org-refile'.
  73. You can set the variable `org-refile-target-verify-function' to a function
  74. to verify each headline found by the simple criteria above.
  75. When this variable is nil, all top-level headlines in the current buffer
  76. are used, equivalent to the value `((nil . (:level . 1))'."
  77. :group 'org-refile
  78. :type '(repeat
  79. (cons
  80. (choice :value org-agenda-files
  81. (const :tag "All agenda files" org-agenda-files)
  82. (const :tag "Current buffer" nil)
  83. (function) (variable) (file))
  84. (choice :tag "Identify target headline by"
  85. (cons :tag "Specific tag" (const :value :tag) (string))
  86. (cons :tag "TODO keyword" (const :value :todo) (string))
  87. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  88. (cons :tag "Level number" (const :value :level) (integer))
  89. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  90. (defcustom org-refile-target-verify-function nil
  91. "Function to verify if the headline at point should be a refile target.
  92. The function will be called without arguments, with point at the
  93. beginning of the headline. It should return t and leave point
  94. where it is if the headline is a valid target for refiling.
  95. If the target should not be selected, the function must return nil.
  96. In addition to this, it may move point to a place from where the search
  97. should be continued. For example, the function may decide that the entire
  98. subtree of the current entry should be excluded and move point to the end
  99. of the subtree."
  100. :group 'org-refile
  101. :type '(choice
  102. (const nil)
  103. (function)))
  104. (defcustom org-refile-use-cache nil
  105. "Non-nil means cache refile targets to speed up the process.
  106. \\<org-mode-map>\
  107. The cache for a particular file will be updated automatically when
  108. the buffer has been killed, or when any of the marker used for flagging
  109. refile targets no longer points at a live buffer.
  110. If you have added new entries to a buffer that might themselves be targets,
  111. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  112. if you find that easier, \
  113. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  114. \\[org-refile]'."
  115. :group 'org-refile
  116. :version "24.1"
  117. :type 'boolean)
  118. (defcustom org-refile-use-outline-path nil
  119. "Non-nil means provide refile targets as paths.
  120. So a level 3 headline will be available as level1/level2/level3.
  121. When the value is `file', also include the file name (without directory)
  122. into the path. In this case, you can also stop the completion after
  123. the file name, to get entries inserted as top level in the file.
  124. When `full-file-path', include the full file path.
  125. When `buffer-name', use the buffer name."
  126. :group 'org-refile
  127. :type '(choice
  128. (const :tag "Not" nil)
  129. (const :tag "Yes" t)
  130. (const :tag "Start with file name" file)
  131. (const :tag "Start with full file path" full-file-path)
  132. (const :tag "Start with buffer name" buffer-name)))
  133. (defcustom org-outline-path-complete-in-steps t
  134. "Non-nil means complete the outline path in hierarchical steps.
  135. When Org uses the refile interface to select an outline path (see
  136. `org-refile-use-outline-path'), the completion of the path can be
  137. done in a single go, or it can be done in steps down the headline
  138. hierarchy. Going in steps is probably the best if you do not use
  139. a special completion package like `ido' or `icicles'. However,
  140. when using these packages, going in one step can be very fast,
  141. while still showing the whole path to the entry."
  142. :group 'org-refile
  143. :type 'boolean)
  144. (defcustom org-refile-allow-creating-parent-nodes nil
  145. "Non-nil means allow the creation of new nodes as refile targets.
  146. New nodes are then created by adding \"/new node name\" to the completion
  147. of an existing node. When the value of this variable is `confirm',
  148. new node creation must be confirmed by the user (recommended).
  149. When nil, the completion must match an existing entry.
  150. Note that, if the new heading is not seen by the criteria
  151. listed in `org-refile-targets', multiple instances of the same
  152. heading would be created by trying again to file under the new
  153. heading."
  154. :group 'org-refile
  155. :type '(choice
  156. (const :tag "Never" nil)
  157. (const :tag "Always" t)
  158. (const :tag "Prompt for confirmation" confirm)))
  159. (defcustom org-refile-active-region-within-subtree nil
  160. "Non-nil means also refile active region within a subtree.
  161. By default `org-refile' doesn't allow refiling regions if they
  162. don't contain a set of subtrees, but it might be convenient to
  163. do so sometimes: in that case, the first line of the region is
  164. converted to a headline before refiling."
  165. :group 'org-refile
  166. :version "24.1"
  167. :type 'boolean)
  168. (defvar org-refile-target-table nil
  169. "The list of refile targets, created by `org-refile'.")
  170. (defvar org-refile-cache nil
  171. "Cache for refile targets.")
  172. (defvar org-refile-markers nil
  173. "All the markers used for caching refile locations.")
  174. ;; Add org refile commands to the main org menu
  175. (mapc (lambda (i) (easy-menu-add-item
  176. org-org-menu
  177. '("Edit Structure") i))
  178. '(["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  179. ["Refile and copy Subtree" org-copy (org-in-subtree-not-table-p)]))
  180. (defun org-refile-marker (pos)
  181. "Get a new refile marker, but only if caching is in use."
  182. (if (not org-refile-use-cache)
  183. pos
  184. (let ((m (make-marker)))
  185. (move-marker m pos)
  186. (push m org-refile-markers)
  187. m)))
  188. (defun org-refile-cache-clear ()
  189. "Clear the refile cache and disable all the markers."
  190. (dolist (m org-refile-markers) (move-marker m nil))
  191. (setq org-refile-markers nil)
  192. (setq org-refile-cache nil)
  193. (message "Refile cache has been cleared"))
  194. (defun org-refile-cache-check-set (set)
  195. "Check if all the markers in the cache still have live buffers."
  196. (let (marker)
  197. (catch 'exit
  198. (while (and set (setq marker (nth 3 (pop set))))
  199. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  200. (when (and marker (null (marker-buffer marker)))
  201. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  202. (sit-for 3)
  203. (throw 'exit nil)))
  204. t)))
  205. (defun org-refile-cache-put (set &rest identifiers)
  206. "Push the refile targets SET into the cache, under IDENTIFIERS."
  207. (let* ((key (sha1 (prin1-to-string identifiers)))
  208. (entry (assoc key org-refile-cache)))
  209. (if entry
  210. (setcdr entry set)
  211. (push (cons key set) org-refile-cache))))
  212. (defun org-refile-cache-get (&rest identifiers)
  213. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  214. (cond
  215. ((not org-refile-cache) nil)
  216. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  217. (t
  218. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  219. org-refile-cache))))
  220. (and set (org-refile-cache-check-set set) set)))))
  221. (defun org-refile-get-targets (&optional default-buffer)
  222. "Produce a table with refile targets."
  223. (let ((case-fold-search nil)
  224. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  225. (entries (or org-refile-targets '((nil . (:level . 1)))))
  226. targets tgs files desc descre)
  227. (message "Getting targets...")
  228. (with-current-buffer (or default-buffer (current-buffer))
  229. (dolist (entry entries)
  230. (setq files (car entry) desc (cdr entry))
  231. (cond
  232. ((null files) (setq files (list (current-buffer))))
  233. ((eq files 'org-agenda-files)
  234. (setq files (org-agenda-files 'unrestricted)))
  235. ((and (symbolp files) (fboundp files))
  236. (setq files (funcall files)))
  237. ((and (symbolp files) (boundp files))
  238. (setq files (symbol-value files))))
  239. (when (stringp files) (setq files (list files)))
  240. (cond
  241. ((eq (car desc) :tag)
  242. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  243. ((eq (car desc) :todo)
  244. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  245. ((eq (car desc) :regexp)
  246. (setq descre (cdr desc)))
  247. ((eq (car desc) :level)
  248. (setq descre (concat "^\\*\\{" (number-to-string
  249. (if org-odd-levels-only
  250. (1- (* 2 (cdr desc)))
  251. (cdr desc)))
  252. "\\}[ \t]")))
  253. ((eq (car desc) :maxlevel)
  254. (setq descre (concat "^\\*\\{1," (number-to-string
  255. (if org-odd-levels-only
  256. (1- (* 2 (cdr desc)))
  257. (cdr desc)))
  258. "\\}[ \t]")))
  259. (t (error "Bad refiling target description %s" desc)))
  260. (dolist (f files)
  261. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  262. (or
  263. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  264. (progn
  265. (when (bufferp f)
  266. (setq f (buffer-file-name (buffer-base-buffer f))))
  267. (setq f (and f (expand-file-name f)))
  268. (when (eq org-refile-use-outline-path 'file)
  269. (push (list (file-name-nondirectory f) f nil nil) tgs))
  270. (when (eq org-refile-use-outline-path 'buffer-name)
  271. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  272. (when (eq org-refile-use-outline-path 'full-file-path)
  273. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  274. (org-with-wide-buffer
  275. (goto-char (point-min))
  276. (setq org-outline-path-cache nil)
  277. (while (re-search-forward descre nil t)
  278. (beginning-of-line)
  279. (let ((case-fold-search nil))
  280. (looking-at org-complex-heading-regexp))
  281. (let ((begin (point))
  282. (heading (match-string-no-properties 4)))
  283. (unless (or (and
  284. org-refile-target-verify-function
  285. (not
  286. (funcall org-refile-target-verify-function)))
  287. (not heading))
  288. (let ((re (format org-complex-heading-regexp-format
  289. (regexp-quote heading)))
  290. (target
  291. (if (not org-refile-use-outline-path) heading
  292. (mapconcat
  293. #'identity
  294. (append
  295. (pcase org-refile-use-outline-path
  296. (`file (list (file-name-nondirectory
  297. (buffer-file-name
  298. (buffer-base-buffer)))))
  299. (`full-file-path
  300. (list (buffer-file-name
  301. (buffer-base-buffer))))
  302. (`buffer-name
  303. (list (buffer-name
  304. (buffer-base-buffer))))
  305. (_ nil))
  306. (mapcar (lambda (s) (replace-regexp-in-string
  307. "/" "\\/" s nil t))
  308. (org-get-outline-path t t)))
  309. "/"))))
  310. (push (list target f re (org-refile-marker (point)))
  311. tgs)))
  312. (when (= (point) begin)
  313. ;; Verification function has not moved point.
  314. (end-of-line)))))))
  315. (when org-refile-use-cache
  316. (org-refile-cache-put tgs (buffer-file-name) descre))
  317. (setq targets (append tgs targets))))))
  318. (message "Getting targets...done")
  319. (delete-dups (nreverse targets))))
  320. (defvar org-refile-history nil
  321. "History for refiling operations.")
  322. (defvar org-after-refile-insert-hook nil
  323. "Hook run after `org-refile' has inserted its stuff at the new location.
  324. Note that this is still *before* the stuff will be removed from
  325. the *old* location.")
  326. (defvar org-refile-keep nil
  327. "Non-nil means `org-refile' will copy instead of refile.")
  328. (define-obsolete-function-alias 'org-copy 'org-refile-copy "Org 9.4")
  329. ;;;###autoload
  330. (defun org-refile-copy ()
  331. "Like `org-refile', but preserve the refiled subtree."
  332. (interactive)
  333. (let ((org-refile-keep t))
  334. (org-refile nil nil nil "Copy")))
  335. (defvar org-capture-last-stored-marker)
  336. ;;;###autoload
  337. (defun org-refile (&optional arg default-buffer rfloc msg)
  338. "Move the entry or entries at point to another heading.
  339. The list of target headings is compiled using the information in
  340. `org-refile-targets', which see.
  341. At the target location, the entry is filed as a subitem of the
  342. target heading. Depending on `org-reverse-note-order', the new
  343. subitem will either be the first or the last subitem.
  344. If there is an active region, all entries in that region will be
  345. refiled. However, the region must fulfill the requirement that
  346. the first heading sets the top-level of the moved text.
  347. With a `\\[universal-argument]' ARG, the command will only visit the target \
  348. location
  349. and not actually move anything.
  350. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  351. location where the last
  352. refiling operation has put the subtree.
  353. With a numeric prefix argument of `2', refile to the running clock.
  354. With a numeric prefix argument of `3', emulate `org-refile-keep'
  355. being set to t and copy to the target location, don't move it.
  356. Beware that keeping refiled entries may result in duplicated ID
  357. properties.
  358. RFLOC can be a refile location obtained in a different way. It
  359. should be a list with the following 4 elements:
  360. 1. Name - an identifier for the refile location, typically the
  361. headline text
  362. 2. File - the file the refile location is in
  363. 3. nil - used for generating refile location candidates, not
  364. needed when passing RFLOC
  365. 4. Position - the position in the specified file of the
  366. headline to refile under
  367. MSG is a string to replace \"Refile\" in the default prompt with
  368. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  369. See also `org-refile-use-outline-path'.
  370. If you are using target caching (see `org-refile-use-cache'), you
  371. have to clear the target cache in order to find new targets.
  372. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  373. prefix argument (`C-u C-u C-u C-c C-w')."
  374. (interactive "P")
  375. (if (member arg '(0 (64)))
  376. (org-refile-cache-clear)
  377. (let* ((actionmsg (cond (msg msg)
  378. ((equal arg 3) "Refile (and keep)")
  379. (t "Refile")))
  380. (regionp (org-region-active-p))
  381. (region-start (and regionp (region-beginning)))
  382. (region-end (and regionp (region-end)))
  383. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  384. pos it nbuf file level reversed)
  385. (setq last-command nil)
  386. (when regionp
  387. (goto-char region-start)
  388. (beginning-of-line)
  389. (setq region-start (point))
  390. (unless (or (org-kill-is-subtree-p
  391. (buffer-substring region-start region-end))
  392. (prog1 org-refile-active-region-within-subtree
  393. (let ((s (point-at-eol)))
  394. (org-toggle-heading)
  395. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  396. (user-error "The region is not a (sequence of) subtree(s)")))
  397. (if (equal arg '(16))
  398. (org-refile-goto-last-stored)
  399. (when (or
  400. (and (equal arg 2)
  401. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  402. (prog1
  403. (setq it (list (or org-clock-heading "running clock")
  404. (buffer-file-name
  405. (marker-buffer org-clock-hd-marker))
  406. ""
  407. (marker-position org-clock-hd-marker)))
  408. (setq arg nil)))
  409. (setq it
  410. (or rfloc
  411. (let (heading-text)
  412. (save-excursion
  413. (unless (and arg (listp arg))
  414. (org-back-to-heading t)
  415. (setq heading-text
  416. (replace-regexp-in-string
  417. org-link-bracket-re
  418. "\\2"
  419. (or (nth 4 (org-heading-components))
  420. ""))))
  421. (org-refile-get-location
  422. (cond ((and arg (listp arg)) "Goto")
  423. (regionp (concat actionmsg " region to"))
  424. (t (concat actionmsg " subtree \""
  425. heading-text "\" to")))
  426. default-buffer
  427. (and (not (equal '(4) arg))
  428. org-refile-allow-creating-parent-nodes)))))))
  429. (setq file (nth 1 it)
  430. pos (nth 3 it))
  431. (when (and (not arg)
  432. pos
  433. (equal (buffer-file-name) file)
  434. (if regionp
  435. (and (>= pos region-start)
  436. (<= pos region-end))
  437. (and (>= pos (point))
  438. (< pos (save-excursion
  439. (org-end-of-subtree t t))))))
  440. (error "Cannot refile to position inside the tree or region"))
  441. (setq nbuf (or (find-buffer-visiting file)
  442. (find-file-noselect file)))
  443. (if (and arg (not (equal arg 3)))
  444. (progn
  445. (pop-to-buffer-same-window nbuf)
  446. (goto-char (cond (pos)
  447. ((org-notes-order-reversed-p) (point-min))
  448. (t (point-max))))
  449. (org-show-context 'org-goto))
  450. (if regionp
  451. (progn
  452. (org-kill-new (buffer-substring region-start region-end))
  453. (org-save-markers-in-region region-start region-end))
  454. (org-copy-subtree 1 nil t))
  455. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  456. (find-file-noselect file)))
  457. (setq reversed (org-notes-order-reversed-p))
  458. (org-with-wide-buffer
  459. (if pos
  460. (progn
  461. (goto-char pos)
  462. (setq level (org-get-valid-level (funcall outline-level) 1))
  463. (goto-char
  464. (if reversed
  465. (or (outline-next-heading) (point-max))
  466. (or (save-excursion (org-get-next-sibling))
  467. (org-end-of-subtree t t)
  468. (point-max)))))
  469. (setq level 1)
  470. (if (not reversed)
  471. (goto-char (point-max))
  472. (goto-char (point-min))
  473. (or (outline-next-heading) (goto-char (point-max)))))
  474. (unless (bolp) (newline))
  475. (org-paste-subtree level nil nil t)
  476. ;; Record information, according to `org-log-refile'.
  477. ;; Do not prompt for a note when refiling multiple
  478. ;; headlines, however. Simply add a time stamp.
  479. (cond
  480. ((not org-log-refile))
  481. (regionp
  482. (org-map-region
  483. (lambda () (org-add-log-setup 'refile nil nil 'time))
  484. (point)
  485. (+ (point) (- region-end region-start))))
  486. (t
  487. (org-add-log-setup 'refile nil nil org-log-refile)))
  488. (and org-auto-align-tags
  489. (let ((org-loop-over-headlines-in-active-region nil))
  490. (org-align-tags)))
  491. (let ((bookmark-name (plist-get org-bookmark-names-plist
  492. :last-refile)))
  493. (when bookmark-name
  494. (with-demoted-errors
  495. (bookmark-set bookmark-name))))
  496. ;; If we are refiling for capture, make sure that the
  497. ;; last-capture pointers point here
  498. (when (bound-and-true-p org-capture-is-refiling)
  499. (let ((bookmark-name (plist-get org-bookmark-names-plist
  500. :last-capture-marker)))
  501. (when bookmark-name
  502. (with-demoted-errors
  503. (bookmark-set bookmark-name))))
  504. (move-marker org-capture-last-stored-marker (point)))
  505. (when (fboundp 'deactivate-mark) (deactivate-mark))
  506. (run-hooks 'org-after-refile-insert-hook)))
  507. (unless org-refile-keep
  508. (if regionp
  509. (delete-region (point) (+ (point) (- region-end region-start)))
  510. (org-preserve-local-variables
  511. (delete-region
  512. (and (org-back-to-heading t) (point))
  513. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  514. (when (featurep 'org-inlinetask)
  515. (org-inlinetask-remove-END-maybe))
  516. (setq org-markers-to-move nil)
  517. (message "%s to \"%s\" in file %s: done" actionmsg
  518. (car it) file)))))))
  519. (defun org-refile-goto-last-stored ()
  520. "Go to the location where the last refile was stored."
  521. (interactive)
  522. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  523. (message "This is the location of the last refile"))
  524. (defun org-refile--get-location (refloc tbl)
  525. "When user refile to REFLOC, find the associated target in TBL.
  526. Also check `org-refile-target-table'."
  527. (car (delq
  528. nil
  529. (mapcar
  530. (lambda (r) (or (assoc r tbl)
  531. (assoc r org-refile-target-table)))
  532. (list (replace-regexp-in-string "/$" "" refloc)
  533. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  534. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  535. "Prompt the user for a refile location, using PROMPT.
  536. PROMPT should not be suffixed with a colon and a space, because
  537. this function appends the default value from
  538. `org-refile-history' automatically, if that is not empty."
  539. (let ((org-refile-targets org-refile-targets)
  540. (org-refile-use-outline-path org-refile-use-outline-path))
  541. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  542. (unless org-refile-target-table
  543. (user-error "No refile targets"))
  544. (let* ((cbuf (current-buffer))
  545. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  546. (cfunc (if (and org-refile-use-outline-path
  547. org-outline-path-complete-in-steps)
  548. #'org-olpath-completing-read
  549. #'completing-read))
  550. (extra (if org-refile-use-outline-path "/" ""))
  551. (cbnex (concat (buffer-name) extra))
  552. (filename (and cfn (expand-file-name cfn)))
  553. (tbl (mapcar
  554. (lambda (x)
  555. (if (and (not (member org-refile-use-outline-path
  556. '(file full-file-path)))
  557. (not (equal filename (nth 1 x))))
  558. (cons (concat (car x) extra " ("
  559. (file-name-nondirectory (nth 1 x)) ")")
  560. (cdr x))
  561. (cons (concat (car x) extra) (cdr x))))
  562. org-refile-target-table))
  563. (completion-ignore-case t)
  564. cdef
  565. (prompt (concat prompt
  566. (or (and (car org-refile-history)
  567. (concat " (default " (car org-refile-history) ")"))
  568. (and (assoc cbnex tbl) (setq cdef cbnex)
  569. (concat " (default " cbnex ")"))) ": "))
  570. pa answ parent-target child parent old-hist)
  571. (setq old-hist org-refile-history)
  572. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  573. nil 'org-refile-history
  574. (or cdef (concat (car org-refile-history) extra))))
  575. (if (setq pa (org-refile--get-location answ tbl))
  576. (let* ((last-refile-loc (car org-refile-history))
  577. (last-refile-loc-path (concat last-refile-loc extra)))
  578. (org-refile-check-position pa)
  579. (when (or (not org-refile-history)
  580. (not (eq old-hist org-refile-history))
  581. (not (equal (car pa) last-refile-loc-path)))
  582. (setq org-refile-history
  583. (cons (car pa) (if (assoc last-refile-loc tbl)
  584. org-refile-history
  585. (cdr org-refile-history))))
  586. (when (or (equal last-refile-loc-path (nth 1 org-refile-history))
  587. (equal last-refile-loc (nth 1 org-refile-history)))
  588. (pop org-refile-history)))
  589. pa)
  590. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  591. (progn
  592. (setq parent (match-string 1 answ)
  593. child (match-string 2 answ))
  594. (setq parent-target (org-refile--get-location parent tbl))
  595. (when (and parent-target
  596. (or (eq new-nodes t)
  597. (and (eq new-nodes 'confirm)
  598. (y-or-n-p (format "Create new node \"%s\"? "
  599. child)))))
  600. (org-refile-new-child parent-target child)))
  601. (user-error "Invalid target location")))))
  602. (defun org-refile-check-position (refile-pointer)
  603. "Check if the refile pointer matches the headline to which it points."
  604. (let* ((file (nth 1 refile-pointer))
  605. (re (nth 2 refile-pointer))
  606. (pos (nth 3 refile-pointer))
  607. buffer)
  608. (if (and (not (markerp pos)) (not file))
  609. (user-error "Please indicate a target file in the refile path")
  610. (when (org-string-nw-p re)
  611. (setq buffer (if (markerp pos)
  612. (marker-buffer pos)
  613. (or (find-buffer-visiting file)
  614. (find-file-noselect file))))
  615. (with-current-buffer buffer
  616. (org-with-wide-buffer
  617. (goto-char pos)
  618. (beginning-of-line 1)
  619. (unless (looking-at-p re)
  620. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  621. (defun org-refile-new-child (parent-target child)
  622. "Use refile target PARENT-TARGET to add new CHILD below it."
  623. (unless parent-target
  624. (error "Cannot find parent for new node"))
  625. (let ((file (nth 1 parent-target))
  626. (pos (nth 3 parent-target))
  627. level)
  628. (with-current-buffer (or (find-buffer-visiting file)
  629. (find-file-noselect file))
  630. (org-with-wide-buffer
  631. (if pos
  632. (goto-char pos)
  633. (goto-char (point-max))
  634. (unless (bolp) (newline)))
  635. (when (looking-at org-outline-regexp)
  636. (setq level (funcall outline-level))
  637. (org-end-of-subtree t t))
  638. (org-back-over-empty-lines)
  639. (insert "\n" (make-string
  640. (if pos (org-get-valid-level level 1) 1) ?*)
  641. " " child "\n")
  642. (beginning-of-line 0)
  643. (list (concat (car parent-target) "/" child) file "" (point))))))
  644. (defun org-olpath-completing-read (prompt collection &rest args)
  645. "Read an outline path like a file name."
  646. (let ((thetable collection))
  647. (apply #'completing-read
  648. prompt
  649. (lambda (string predicate &optional flag)
  650. (cond
  651. ((eq flag nil) (try-completion string thetable))
  652. ((eq flag t)
  653. (let ((l (length string)))
  654. (mapcar (lambda (x)
  655. (let ((r (substring x l))
  656. (f (if (string-match " ([^)]*)$" x)
  657. (match-string 0 x)
  658. "")))
  659. (if (string-match "/" r)
  660. (concat string (substring r 0 (match-end 0)) f)
  661. x)))
  662. (all-completions string thetable predicate))))
  663. ;; Exact match?
  664. ((eq flag 'lambda) (assoc string thetable))))
  665. args)))
  666. (provide 'org-refile)
  667. ;; Local variables:
  668. ;; generated-autoload-file: "org-loaddefs.el"
  669. ;; End:
  670. ;;; org-refile.el ends here