org-refile.el 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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. ;; 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. ;; 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-refile-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. ;;;###autoload
  329. (defun org-refile-copy ()
  330. "Like `org-refile', but preserve the refiled subtree."
  331. (interactive)
  332. (let ((org-refile-keep t))
  333. (org-refile nil nil nil "Copy")))
  334. (defvar org-capture-last-stored-marker)
  335. ;;;###autoload
  336. (defun org-refile (&optional arg default-buffer rfloc msg)
  337. "Move the entry or entries at point to another heading.
  338. The list of target headings is compiled using the information in
  339. `org-refile-targets', which see.
  340. At the target location, the entry is filed as a subitem of the
  341. target heading. Depending on `org-reverse-note-order', the new
  342. subitem will either be the first or the last subitem.
  343. If there is an active region, all entries in that region will be
  344. refiled. However, the region must fulfill the requirement that
  345. the first heading sets the top-level of the moved text.
  346. With a `\\[universal-argument]' ARG, the command will only visit the target \
  347. location
  348. and not actually move anything.
  349. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  350. location where the last
  351. refiling operation has put the subtree.
  352. With a numeric prefix argument of `2', refile to the running clock.
  353. With a numeric prefix argument of `3', emulate `org-refile-keep'
  354. being set to t and copy to the target location, don't move it.
  355. Beware that keeping refiled entries may result in duplicated ID
  356. properties.
  357. RFLOC can be a refile location obtained in a different way. It
  358. should be a list with the following 4 elements:
  359. 1. Name - an identifier for the refile location, typically the
  360. headline text
  361. 2. File - the file the refile location is in
  362. 3. nil - used for generating refile location candidates, not
  363. needed when passing RFLOC
  364. 4. Position - the position in the specified file of the
  365. headline to refile under
  366. MSG is a string to replace \"Refile\" in the default prompt with
  367. another verb. E.g. `org-refile-copy' sets this parameter to \"Copy\".
  368. See also `org-refile-use-outline-path'.
  369. If you are using target caching (see `org-refile-use-cache'), you
  370. have to clear the target cache in order to find new targets.
  371. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  372. prefix argument (`C-u C-u C-u C-c C-w')."
  373. (interactive "P")
  374. (if (member arg '(0 (64)))
  375. (org-refile-cache-clear)
  376. (let* ((actionmsg (cond (msg msg)
  377. ((equal arg 3) "Refile (and keep)")
  378. (t "Refile")))
  379. (regionp (org-region-active-p))
  380. (region-start (and regionp (region-beginning)))
  381. (region-end (and regionp (region-end)))
  382. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  383. pos it nbuf file level reversed)
  384. (setq last-command nil)
  385. (when regionp
  386. (goto-char region-start)
  387. (beginning-of-line)
  388. (setq region-start (point))
  389. (unless (or (org-kill-is-subtree-p
  390. (buffer-substring region-start region-end))
  391. (prog1 org-refile-active-region-within-subtree
  392. (let ((s (point-at-eol)))
  393. (org-toggle-heading)
  394. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  395. (user-error "The region is not a (sequence of) subtree(s)")))
  396. (if (equal arg '(16))
  397. (org-refile-goto-last-stored)
  398. (when (or
  399. (and (equal arg 2)
  400. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  401. (prog1
  402. (setq it (list (or org-clock-heading "running clock")
  403. (buffer-file-name
  404. (marker-buffer org-clock-hd-marker))
  405. ""
  406. (marker-position org-clock-hd-marker)))
  407. (setq arg nil)))
  408. (setq it
  409. (or rfloc
  410. (let (heading-text)
  411. (save-excursion
  412. (unless (and arg (listp arg))
  413. (org-back-to-heading t)
  414. (setq heading-text
  415. (replace-regexp-in-string
  416. org-link-bracket-re
  417. "\\2"
  418. (or (nth 4 (org-heading-components))
  419. ""))))
  420. (org-refile-get-location
  421. (cond ((and arg (listp arg)) "Goto")
  422. (regionp (concat actionmsg " region to"))
  423. (t (concat actionmsg " subtree \""
  424. heading-text "\" to")))
  425. default-buffer
  426. (and (not (equal '(4) arg))
  427. org-refile-allow-creating-parent-nodes)))))))
  428. (setq file (nth 1 it)
  429. pos (nth 3 it))
  430. (when (and (not arg)
  431. pos
  432. (equal (buffer-file-name) file)
  433. (if regionp
  434. (and (>= pos region-start)
  435. (<= pos region-end))
  436. (and (>= pos (point))
  437. (< pos (save-excursion
  438. (org-end-of-subtree t t))))))
  439. (error "Cannot refile to position inside the tree or region"))
  440. (setq nbuf (or (find-buffer-visiting file)
  441. (find-file-noselect file)))
  442. (if (and arg (not (equal arg 3)))
  443. (progn
  444. (pop-to-buffer-same-window nbuf)
  445. (goto-char (cond (pos)
  446. ((org-notes-order-reversed-p) (point-min))
  447. (t (point-max))))
  448. (org-show-context 'org-goto))
  449. (if regionp
  450. (progn
  451. (org-kill-new (buffer-substring region-start region-end))
  452. (org-save-markers-in-region region-start region-end))
  453. (org-copy-subtree 1 nil t))
  454. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  455. (find-file-noselect file)))
  456. (setq reversed (org-notes-order-reversed-p))
  457. (org-with-wide-buffer
  458. (if pos
  459. (progn
  460. (goto-char pos)
  461. (setq level (org-get-valid-level (funcall outline-level) 1))
  462. (goto-char
  463. (if reversed
  464. (or (outline-next-heading) (point-max))
  465. (or (save-excursion (org-get-next-sibling))
  466. (org-end-of-subtree t t)
  467. (point-max)))))
  468. (setq level 1)
  469. (if (not reversed)
  470. (goto-char (point-max))
  471. (goto-char (point-min))
  472. (or (outline-next-heading) (goto-char (point-max)))))
  473. (unless (bolp) (newline))
  474. (org-paste-subtree level nil nil t)
  475. ;; Record information, according to `org-log-refile'.
  476. ;; Do not prompt for a note when refiling multiple
  477. ;; headlines, however. Simply add a time stamp.
  478. (cond
  479. ((not org-log-refile))
  480. (regionp
  481. (org-map-region
  482. (lambda () (org-add-log-setup 'refile nil nil 'time))
  483. (point)
  484. (+ (point) (- region-end region-start))))
  485. (t
  486. (org-add-log-setup 'refile nil nil org-log-refile)))
  487. (and org-auto-align-tags
  488. (let ((org-loop-over-headlines-in-active-region nil))
  489. (org-align-tags)))
  490. (let ((bookmark-name (plist-get org-bookmark-names-plist
  491. :last-refile)))
  492. (when bookmark-name
  493. (with-demoted-errors
  494. (bookmark-set bookmark-name))))
  495. ;; If we are refiling for capture, make sure that the
  496. ;; last-capture pointers point here
  497. (when (bound-and-true-p org-capture-is-refiling)
  498. (let ((bookmark-name (plist-get org-bookmark-names-plist
  499. :last-capture-marker)))
  500. (when bookmark-name
  501. (with-demoted-errors
  502. (bookmark-set bookmark-name))))
  503. (move-marker org-capture-last-stored-marker (point)))
  504. (when (fboundp 'deactivate-mark) (deactivate-mark))
  505. (run-hooks 'org-after-refile-insert-hook)))
  506. (unless org-refile-keep
  507. (if regionp
  508. (delete-region (point) (+ (point) (- region-end region-start)))
  509. (org-preserve-local-variables
  510. (delete-region
  511. (and (org-back-to-heading t) (point))
  512. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  513. (when (featurep 'org-inlinetask)
  514. (org-inlinetask-remove-END-maybe))
  515. (setq org-markers-to-move nil)
  516. (message "%s to \"%s\" in file %s: done" actionmsg
  517. (car it) file)))))))
  518. (defun org-refile-goto-last-stored ()
  519. "Go to the location where the last refile was stored."
  520. (interactive)
  521. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  522. (message "This is the location of the last refile"))
  523. (defun org-refile--get-location (refloc tbl)
  524. "When user refile to REFLOC, find the associated target in TBL.
  525. Also check `org-refile-target-table'."
  526. (car (delq
  527. nil
  528. (mapcar
  529. (lambda (r) (or (assoc r tbl)
  530. (assoc r org-refile-target-table)))
  531. (list (replace-regexp-in-string "/$" "" refloc)
  532. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  533. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  534. "Prompt the user for a refile location, using PROMPT.
  535. PROMPT should not be suffixed with a colon and a space, because
  536. this function appends the default value from
  537. `org-refile-history' automatically, if that is not empty."
  538. (let ((org-refile-targets org-refile-targets)
  539. (org-refile-use-outline-path org-refile-use-outline-path))
  540. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  541. (unless org-refile-target-table
  542. (user-error "No refile targets"))
  543. (let* ((cbuf (current-buffer))
  544. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  545. (cfunc (if (and org-refile-use-outline-path
  546. org-outline-path-complete-in-steps)
  547. #'org-olpath-completing-read
  548. #'completing-read))
  549. (extra (if org-refile-use-outline-path "/" ""))
  550. (cbnex (concat (buffer-name) extra))
  551. (filename (and cfn (expand-file-name cfn)))
  552. (tbl (mapcar
  553. (lambda (x)
  554. (if (and (not (member org-refile-use-outline-path
  555. '(file full-file-path)))
  556. (not (equal filename (nth 1 x))))
  557. (cons (concat (car x) extra " ("
  558. (file-name-nondirectory (nth 1 x)) ")")
  559. (cdr x))
  560. (cons (concat (car x) extra) (cdr x))))
  561. org-refile-target-table))
  562. (completion-ignore-case t)
  563. cdef
  564. (prompt (concat prompt
  565. (or (and (car org-refile-history)
  566. (concat " (default " (car org-refile-history) ")"))
  567. (and (assoc cbnex tbl) (setq cdef cbnex)
  568. (concat " (default " cbnex ")"))) ": "))
  569. pa answ parent-target child parent old-hist)
  570. (setq old-hist org-refile-history)
  571. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  572. nil 'org-refile-history
  573. (or cdef (concat (car org-refile-history) extra))))
  574. (if (setq pa (org-refile--get-location answ tbl))
  575. (let* ((last-refile-loc (car org-refile-history))
  576. (last-refile-loc-path (concat last-refile-loc extra)))
  577. (org-refile-check-position pa)
  578. (when (or (not org-refile-history)
  579. (not (eq old-hist org-refile-history))
  580. (not (equal (car pa) last-refile-loc-path)))
  581. (setq org-refile-history
  582. (cons (car pa) (if (assoc last-refile-loc tbl)
  583. org-refile-history
  584. (cdr org-refile-history))))
  585. (when (or (equal last-refile-loc-path (nth 1 org-refile-history))
  586. (equal last-refile-loc (nth 1 org-refile-history)))
  587. (pop org-refile-history)))
  588. pa)
  589. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  590. (progn
  591. (setq parent (match-string 1 answ)
  592. child (match-string 2 answ))
  593. (setq parent-target (org-refile--get-location parent tbl))
  594. (when (and parent-target
  595. (or (eq new-nodes t)
  596. (and (eq new-nodes 'confirm)
  597. (y-or-n-p (format "Create new node \"%s\"? "
  598. child)))))
  599. (org-refile-new-child parent-target child)))
  600. (user-error "Invalid target location")))))
  601. (defun org-refile-check-position (refile-pointer)
  602. "Check if the refile pointer matches the headline to which it points."
  603. (let* ((file (nth 1 refile-pointer))
  604. (re (nth 2 refile-pointer))
  605. (pos (nth 3 refile-pointer))
  606. buffer)
  607. (if (and (not (markerp pos)) (not file))
  608. (user-error "Please indicate a target file in the refile path")
  609. (when (org-string-nw-p re)
  610. (setq buffer (if (markerp pos)
  611. (marker-buffer pos)
  612. (or (find-buffer-visiting file)
  613. (find-file-noselect file))))
  614. (with-current-buffer buffer
  615. (org-with-wide-buffer
  616. (goto-char pos)
  617. (beginning-of-line 1)
  618. (unless (looking-at-p re)
  619. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  620. (defun org-refile-new-child (parent-target child)
  621. "Use refile target PARENT-TARGET to add new CHILD below it."
  622. (unless parent-target
  623. (error "Cannot find parent for new node"))
  624. (let ((file (nth 1 parent-target))
  625. (pos (nth 3 parent-target))
  626. level)
  627. (with-current-buffer (or (find-buffer-visiting file)
  628. (find-file-noselect file))
  629. (org-with-wide-buffer
  630. (if pos
  631. (goto-char pos)
  632. (goto-char (point-max))
  633. (unless (bolp) (newline)))
  634. (when (looking-at org-outline-regexp)
  635. (setq level (funcall outline-level))
  636. (org-end-of-subtree t t))
  637. (org-back-over-empty-lines)
  638. (insert "\n" (make-string
  639. (if pos (org-get-valid-level level 1) 1) ?*)
  640. " " child "\n")
  641. (beginning-of-line 0)
  642. (list (concat (car parent-target) "/" child) file "" (point))))))
  643. (defun org-olpath-completing-read (prompt collection &rest args)
  644. "Read an outline path like a file name."
  645. (let ((thetable collection))
  646. (apply #'completing-read
  647. prompt
  648. (lambda (string predicate &optional flag)
  649. (cond
  650. ((eq flag nil) (try-completion string thetable))
  651. ((eq flag t)
  652. (let ((l (length string)))
  653. (mapcar (lambda (x)
  654. (let ((r (substring x l))
  655. (f (if (string-match " ([^)]*)$" x)
  656. (match-string 0 x)
  657. "")))
  658. (if (string-match "/" r)
  659. (concat string (substring r 0 (match-end 0)) f)
  660. x)))
  661. (all-completions string thetable predicate))))
  662. ;; Exact match?
  663. ((eq flag 'lambda) (assoc string thetable))))
  664. args)))
  665. (provide 'org-refile)
  666. ;; Local variables:
  667. ;; generated-autoload-file: "org-loaddefs.el"
  668. ;; End:
  669. ;;; org-refile.el ends here