org-mode: Literature Handling

Date: 2014-03-17

At the moment I'm working on my master's thesis. For this i have to manage the notes on the related work. For this purpose i use Emacs and org-mode. I wrote two snippets that are extremely useful when working with related work in org-mode. First of all, I attach the discussed paper to the subtree. This is done normally with C-c C-a a, but most of the time the to be attached file is available on the web. So i wrote a function that downloads an URL and attaches the file to the current subtree.

(require 'url)
(require 'org-attach

(defun org-attach-download-file (&optional url download-dir download-name)
  (let* ((selection (x-selection))
         (initial-input (if (string-match "^http:" selection)
                            selection
                          ""))
         (url (or url
                 (read-string "Enter download URL: " initial-input))))
    (let ((download-buffer (url-retrieve-synchronously url)))
      (save-excursion
        (set-buffer download-buffer)
        ;; we may have to trim the http response
        (goto-char (point-min))
        (re-search-forward "^$" nil 'move)
        (forward-char)
        (delete-region (point-min) (point))

        (let ((filename
               (concat (or download-dir
                           "/tmp/")
                       (or download-name
                           (car (last (split-string url "/" t)))))))
          (write-file filename)
          filename)))))

(defun org-attach-url ()
  (interactive)
  (let ((filename (org-attach-download-file)))
    (message filename)
    (let ((org-attach-method 'mv))
      (org-attach-attach filename))))

The snippet preselects asks for a URL, but uses the current X selection as default value. Another quite common task is, that i want to share my notes with a colleague. This snippet exports the current subtree as ASCII and inserts into a notmuch mail buffer. All files attached to the subtree are added as an attachment to the mail.

(defun org-subtree-as-mail ()
  "Send current subtree as mail with notmuch and attach subtree
   attachments"
  (interactive)
  (let* ((subject (org-get-heading t t))
        (attach-dir (org-attach-dir))
        (files  (and attach-dir
                     (org-attach-file-list attach-dir))))
    (org-export-to-buffer 'ascii " *org-subtree-as-mail*" nil t nil t)
    ;; Fix this if you don't use notmuch.
    (notmuch-mua-mail nil subject)
    (goto-char (point-max))
    (insert-buffer (get-buffer " *org-subtree-as-mail*"))
    (kill-buffer " *org-subtree-as-mail*")
    ;; Attach files
    (mapc (lambda (file)
            (mml-attach-file (concat attach-dir "/" file)))
          files)
    ;; Set Cursor to To:
    (goto-char (point-min))
    (search-forward "To:")))