重构生成文件的elisp代码

时间:2014-01-11 15:57:36

标签: emacs refactoring elisp

我编写了一个简单的emacs模块,用于生成我用于博客静态网站生成器的标准模板。

(defun hakyll-site-location ()
  "Return the location of the Hakyll files."
  "~/Sites/hblog/")

(defun hakyll-new-post (title tags)
  "Create a new Hakyll post for today with TITLE and TAGS."
  (interactive "sTitle: \nsTags: ")
  (let ((file-name (hakyll-post-title title)))
    (set-buffer (get-buffer-create file-name))
    (markdown-mode)
    (insert
     (format "---\ntitle: %s\ntags: %s\ndescription: \n---\n\n" title tags))
    (write-file
     (expand-file-name file-name (concat (hakyll-site-location) "posts")))
    (switch-to-buffer file-name)))

(defun hakyll-new-note (title)
  "Create a new Note with TITLE."
  (interactive "sTitle: ")
  (let ((file-name (hakyll-note-title title)))
    (set-buffer (get-buffer-create file-name))
    (markdown-mode)
    (insert (format "---\ntitle: %s\ndescription: \n---\n\n" title))
    (write-file
     (expand-file-name file-name (concat (hakyll-site-location) "notes")))
    (switch-to-buffer file-name)))

(defun hakyll-post-title (title)
  "Return a file name based on TITLE for the post."
  (concat
   (format-time-string "%Y-%m-%d")
   "-"
   (replace-regexp-in-string " " "-" (downcase title))
   ".markdown"))

(defun hakyll-note-title (title)
  "Return a file name based on TITLE for the note."
  (concat
   (replace-regexp-in-string " " "-" (downcase title))
   ".markdown"))

现在,这可行,但它可以做一点干,但我不知道足够的elisp自己做。

  • hakyll-new-posthakyll-new-note非常相似,可以干预,但我不确定如何将正确的参数传递给任何重构函数
  • 我很难编码hakyll-site-location。有什么方法可以在我的emacs dotfiles中请求和存储配置吗?

欢迎提供任何文档帮助或指示。

1 个答案:

答案 0 :(得分:2)

这是代码。我无法保证它有效,但如果以前有效, 它现在应该可以工作了。

(defvar hakyll-site-location "~/Sites/hblog/"
  "Return the location of the Hakyll files.")

(defun hakyll-new-post (title tags)
  "Create a new Hakyll post for today with TITLE and TAGS."
  (interactive "sTitle: \nsTags: ")
  (hakyll-do-write
   (format "%s/posts/%s-%s.markdown"
           hakyll-site-location
           (format-time-string "%Y-%m-%d")
           (replace-regexp-in-string " " "-" (downcase title)))
   (format "---\ntitle: %s\ntags: %s\ndescription: \n---\n\n"
           title
           tags)))

(defun hakyll-new-note (title)
  "Create a new Note with TITLE."
  (interactive "sTitle: ")
  (hakyll-do-write
   (format "%s/notes/%s.markdown"
           hakyll-site-location
           (replace-regexp-in-string " " "-" (downcase title)))
   (format "---\ntitle: %s\ndescription: \n---\n\n" title)))

(defun hakyll-do-write (file-name str)
  (find-file file-name)
  (insert str)
  (save-buffer))

您可以在点文件中使用(setq hakyll-site-location "~/Sites/")设置位置。 您甚至可以将defvar更改为defcustom,并使用自定义设置位置。