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