Emacs binding to record new post

1 minute read

Hello, today I’m finishing my emacs package to create new post.

At this end of the post there is the current code. It was not very difficult but I’m a big noob with lisp so I probably took so much time.

Add a binding (global-set-key (kbd "C-x c") 'my-journal-capture) and you are good to go

(setq my-journal-directory "~/jekyll/_posts")

(defun my-journal-capture (topic)
  "This command will generate a new entry in the journal. Don't forget the prefix M"
  (interactive "MWhat it is about: ")
  (message (format "Post topic will be: %s" topic))
  (my-journal--init-now topic)
  )

(defun my-journal--init-now (topic)
  "This function opens the journal file with date and topic, initialize it if needed and open the buffer."
  (interactive)

  ;; find the buffer
  (setq topic-slug (replace-regexp-in-string "[ \s]+" "_" topic))
  (setq my-journal-filepath (format "%s/%s-%s.md" my-journal-directory (my-journal--get-date) topic-slug))
  (find-file-noselect my-journal-filepath t)
  (with-current-buffer (get-file-buffer my-journal-filepath)
    (message (format "Post open at %s" (buffer-file-name)))
    ;; test if already initialized or not
    (goto-char (point-min))
    (setq current-match (search-forward "---\n" nil t))
    (message (format "Post already initialized (Current match is %s for * %s)" current-match (my-journal--get-current-year)))
    ;; if not initialized, write default values
    (unless current-match
      (insert (format "---\npublished: false\ncategories:\nlang:\ntoc:\ntitle: %s\ndate: %s\n---\n" topic (my-journal--get-timestamp)))
      (message (format "Initialized post for %s" (buffer-file-name)))
      )
    )
  ;; open the buffer in the current window
  (set-window-buffer (get-buffer-window) (get-file-buffer my-journal-filepath))
  )

;; (defun my-journal--get-monday ()
;;   "This function return the current monday (such as \"2022-08-15\")."
;;   (format-time-string
;;    "%Y-%m-%d"
;;    (let '(week-day-number (string-to-number (format-time-string "%w" (current-time))))
;;      (time-subtract (current-time) (days-to-time (+ week-day-number -1))) ;; +1 for monday as first weekday
;;      )
;;    )
;;   )

(defun my-journal--get-timestamp ()
  "This function return the current timestamp (such as \"2022-08-17 09:28:13 +0002\")."
  (format-time-string "%Y-%m-%d %H:%M:%S %z")
  )

(defun my-journal--get-date ()
  "This function return the current timestamp (such as \"2022-08-17\")."
  (format-time-string "%Y-%m-%d")
  )