Re-file outline tree into new org-mode file?

I'm just getting started with org-mode and imagine a workflow whereby I capture new tasks and notes in an org-mode "inbox" file. For tasks that grow into projects, I would imagine refiling them into a new org-mode file which is then added to my agenda.

The org-mode manual describes refiling a tree mostly the way I'm looking for, except that it only seems to allow refiling the section within the same file. What I'd like to do, is take that tree, and refile it into a new file (and then preferably add the file to the agenda list).

I can copy-paste into a new buffer, and then add the new buffer to the agenda, but it seems like this is the sort of thing that the org-mode gods would have a shortcut for.


Here is a fast-and-filthy elisp function that could be modified as you may wish.

(defun subtree-to-new-file ()
  (interactive)
  "sloppily assists in moving an org subtree to a new file"
  (org-copy-subtree nil t)
;;; This long setq statement gets the title of the first heading, to use as a default filename for the new .org file.
(setq first-heading
  (with-temp-buffer
    (yank)
    (beginning-of-buffer)
    (search-forward " " nil nil 1)
    (setq title-start (point))
    (end-of-visual-line)
    (setq title-end (point))
    (setq first-heading (buffer-substring title-start title-end))
  ))
(setq def-filename (concat first-heading ".org"))
(let ((insert-default-directory t))
  (find-file-other-window  
    (read-file-name "Move subtree to file:" def-filename)
  ))
(org-paste-subtree)
;;; this final command adds the new .org file to the agenda
(org-agenda-file-to-front)
)

You can give this code a quick try by pasting into your *scratch* buffer and hitting Ctrl+j. Then go to a subtree in an org-mode file and hit Alt+x to M-x subtree-to-new-file.

If you want it to be in place every time you use emacs and are completely unfamliar with elisp, the easiest thing might be to also paste this code somewhere into your .emacs configuration file and save it. You can also add a line before or after the function to give it a keybinding. The easiest way to do that (but maybe not the best) would be something like: (global-set-key "\C-xw" 'subtree-to-new-file).


Too add other org-mode buffers to the refile list, you will need to add a line such as follows to your .emacs file. I took this from Brent Hansen's configuration (See here)

; Targets include this file and any file contributing to the agenda - up to 9 levels deep
(setq org-refile-targets (quote ((nil :maxlevel . 9)
                                 (org-agenda-files :maxlevel . 9))))

Only (org-agenda-files :maxlevel .9) is actually needed, the other part sets a maximum number of levels to refile to.