Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alphapapa/84ec3396442915ca277b to your computer and use it in GitHub Desktop.
Save alphapapa/84ec3396442915ca277b to your computer and use it in GitHub Desktop.
Enclose a region in an org-mode block (e.g. #+BEGIN_SRC), or insert a structure template with completion
(defun org-read-structure-template ()
"Read org-mode structure template with completion. Returns template string."
(let* ((templates (map 'list 'second org-structure-template-alist))
(prefixes (map 'list (lambda (tp)
;; Get template and pre-whitespace prefix for completion
(reverse (s-match (rx (group
(1+ (not (any "\n" space))))
(1+ anything))
tp)))
templates))
(prefix (completing-read "Template: " prefixes nil t))
(template (second (assoc prefix prefixes))))
template))
(defun org-insert-structure-template-or-enclose-region ()
"Insert structure block template. When region is active, enclose region in block."
(require 's)
(interactive)
(let* ((template (ap/org-read-structure-template))
(text "")
enclosed-text)
(when (use-region-p)
(setq text (buffer-substring-no-properties (region-beginning) (region-end)))
(delete-region (region-beginning) (region-end)))
(setq enclosed-text (s-replace "?" text template))
(insert enclosed-text)
(backward-char (- (length enclosed-text) (length (s-shared-start enclosed-text template))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment