アクトインディ開発者ブログ

子供とお出かけ情報「いこーよ」を運営する、アクトインディ株式会社の開発者ブログです

次の日のファイルも作りたい

自分は、以前も「Emacsでスクラッチファイルを日付順にして管理するライフハック」で紹介したように日付を元にファイル名を付けて、スクラッチファイルやブログの下書きなどを書いているのですが、たまに、次の日付のファイルが欲しくなることがあります。
これはブログのネタになりそうだということで、そういうファイルを作成するEmacs Lispを適当に書いてみました。
自分は、Emacs Lispを書くときは、なんとなく(require ‘cl)したくないのですが、欲しい関数を調べるのが億劫だったのでべたべたに(require ‘cl)になってしまいました。

(require 'cl)

(defun buffer-name-prefix ()
  (let ((buffer-name (buffer-name (current-buffer))))
    (substring buffer-name 0 (position-if #'digit-char-p buffer-name)) ))

(defun prefix-Y-m-d.suffix-to-list (string)
  (destructuring-bind
      (prefix Y m &optional d)
      (split-string string "-")
    (when (and (null d)
               (every #'digit-char-p prefix) )
      (shiftf d m Y prefix ""))
    (destructuring-bind
        (d &optional suffix)
        (split-string d "\\.")
      (list prefix Y m d (or suffix "")) )))

(defun next-file-name (name)
  (destructuring-bind
      (prefix Y m d suffix)
      (prefix-Y-m-d.suffix-to-list name)
    (let ((time (encode-time 0
                             0
                             0
                             (parse-integer d)
                             (parse-integer m)
                             (parse-integer Y)
                             nil
                             0) ))
      (concat (if (string= "" prefix) "" (concat prefix "-"))
              (format-time-string "%Y-%m-%d" (progn (incf (first time)) time))
              (if (string= "" suffix) "" (concat "." suffix)) ))))

(defun make-next-file ()
  (interactive)
  (find-file (next-file-name (buffer-name))) )

使い方ですが、foo-2000-02-28.txtのようなファイル名のバッファで作業している時に(make-next-file)すると、foo-2000-02-29.txtのようなファイルをfind-fileします。
バッファの名前は、{prefix-}yyyy-mm-dd{.suffix}のようなものを想定していて、これ以外では上手く動きませんが、それなりに便利に使えています。Emacs便利です。 ■