Skip to content

Instantly share code, notes, and snippets.

@tristanstraub
Last active October 3, 2016 03:35
Show Gist options
  • Save tristanstraub/39b2c232e8c2342d482fadc725f11920 to your computer and use it in GitHub Desktop.
Save tristanstraub/39b2c232e8c2342d482fadc725f11920 to your computer and use it in GitHub Desktop.
Capture region to separate org buffer.
(defun append-text-to-buffer (buffer text)
  "Append to specified buffer the text of the region.
It is inserted into that buffer before its point.

When calling from a program, give three arguments:
BUFFER (or buffer name), START and END.
START and END specify the portion of the current buffer to be copied."
  (interactive
   (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
	   (region-beginning) (region-end)))
  (let* ((oldbuf (current-buffer))
         (append-to (get-buffer-create buffer))
         (windows (get-buffer-window-list append-to t t))
         point)
    (save-excursion
      (with-current-buffer append-to
        (setq point (point))
        (barf-if-buffer-read-only)
        (end-of-buffer)
        (insert text)
        (dolist (window windows)
          (when (= (window-point window) point)
            (set-window-point window (point))))))))

(defun stack/capture-region (beg end)
  (interactive (if (use-region-p)
                   (list (region-beginning) (region-end))
                 (list (point-min) (point-min))))
  (let ((selection (buffer-substring-no-properties beg end))
        (buffer (get-buffer-create "*stack.org*")))
    (save-excursion
      (with-current-buffer buffer
        (org-mode)))
    (append-text-to-buffer buffer (concat "* " (file-name-nondirectory (buffer-file-name)) ":" (number-to-string (line-number-at-pos (region-beginning)))))
    (append-text-to-buffer buffer (concat "\n#+FILE:" (buffer-file-name)))
    (append-text-to-buffer buffer (concat "\n#+LINE_NUMBER:" (number-to-string (line-number-at-pos (region-beginning))) "\n"))
    (append-text-to-buffer buffer "#+BEGIN_SRC\n")
    (append-to-buffer buffer beg end)
    (append-text-to-buffer buffer "\n#+END_SRC\n")
    (display-buffer buffer)))

(global-set-key (kbd "C-c m") 'stack/capture-region)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment