Bryan Garza

Automating Blog Posts With Org-mode ( January 31, 2016)

The best way to get me writing is to remove all barriers that slow me down. This especially includes the setup of creating a new post in org-mode and writing its index entry. It might be really easy but it’s annoying to have to do this every time for each new post. So I whipped up some elisp that does all of this for me. It just takes the title, keywords, and description of the post, and takes care of the rest.

(defun bryan/blog-new-post (title keywords description)
  "Create a new post"
  (interactive "sTitle: \nsKeywords: \nsDescription: ")
  ;; (message "Keywords are: %s" keywords)
  (let* ((filename-prepared (string-trim
                             (replace-regexp-in-string " " "-" (downcase title))))
         (relfile (concat filename-prepared ".org"))
         (relfile-html (concat "./" filename-prepared ".html"))
         (absfile (concat bryan/blog-blogdir relfile))
         (date (format-time-string "[%Y-%m-%d %a]"))
         (date-day-not-padded (string-trim (format-time-string "%e")))
         (mon (format-time-string "%B"))
         (yr (format-time-string "%Y"))
         (date-human-readable
          (concat "(" mon (format " %s, " date-day-not-padded) yr ")"))
         (my-html-link-and-span
          `(,(html-a
              :href relfile-html title)
            ,(html-span " ")
            ,(html-span
              :class "timestamp-wrapper"
              (html-span
               :class "timestamp"
               date-human-readable)))))

    (with-current-buffer (find-file-noselect bryan/blog-indexfile)
      (goto-char (point-min))
      (search-forward ">@@")
      (insert "\n#+BEGIN_HTML\n")
      (html-lite-write-tree-single-line
       (butlast
        (html-div
         :class "outline-3"
         (html-h3
          my-html-link-and-span))))
      (insert "\n#+END_HTML\n")
      (insert (format "#+INCLUDE: \"%s\" :lines \"11-\"" relfile))
      (insert (bryan/org-escape-html "</div>"))
      (with-temp-message (format "Writing to %s" bryan/blog-indexfile)
        (save-buffer))
      (message "Writing file...done"))

    (with-temp-buffer
      (-each `(,(format "#+TITLE: %s\n" title)
               ,(format "#+DATE: %s\n" date)
               ,(format "#+KEYWORDS: %s\n" keywords)
               ,(format "#+DESCRIPTION: %s\n" description)
               "#+OPTIONS: title:nil\n\n"
               "#+BEGIN_HTML\n")
        #'insert)
      (html-lite-write-tree-single-line
       (html-header
        (html-h1 :class "title" my-html-link-and-span)))
      (insert "\n#+END_HTML\n\n")
      (when (file-writable-p absfile)
        (write-region (point-min)
                      (point-max)
                      absfile)))
    (find-file absfile))
  (goto-char (point-max))
  (message "Generated template"))

Archive