org-refile.el 32 KB

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