org-refile.el 28 KB

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