Skip to content

Instantly share code, notes, and snippets.

@kobapan
Last active January 16, 2023 08:41
Show Gist options
  • Save kobapan/034d5123321b32bb68ca to your computer and use it in GitHub Desktop.
Save kobapan/034d5123321b32bb68ca to your computer and use it in GitHub Desktop.
elisp *scratch* の永続化
(setq initial-scratch-message "") ; とりあえず initial message を消す
(add-hook 'kill-emacs-hook 'scratch-save) ; Emacs終了時に *scratch* を保存
(add-hook 'window-setup-hook 'scratch-resume); 起動時に.scratchを読み込み
;; window-setup-hook が最後に呼ばれるっぽい
;; @see info 38.1.1 Summary: Sequence of Actions at Startup
(add-hook 'kill-buffer-hook; *scratch* バッファで kill-buffer したら内容を保存
(lambda () (if (equal (buffer-name) "*scratch*") (scratch-save))))
(add-hook 'after-save-hook ; *scratch*をファイル保存したら、*scratch*復帰
(lambda () (unless (get-buffer "*scratch*") (scratch-resume))))
(defvar scratch-file "~/.emacs.d/.scratch")
(defvar scratch-file-bakup (concat scratch-file ".bak"))
(defun scratch-save ()
"*scratch* を保存する"
(interactive)
(let ((buf (get-buffer "*scratch*")))
(when buf
(copy-file scratch-file scratch-file-bakup t t) ; bakup
(set-buffer buf)
(write-file scratch-file)
(ignore-errors (kill-buffer ".scratch")))))
(defun scratch-resume ()
"*scratch* を保存した内容で復帰する"
(interactive)
(if (eq 0 (nth 7 (file-attributes scratch-file))) ; if file size is zero
(copy-file scratch-file-bakup scratch-file t t)) ; fail safe
(set-buffer (get-buffer-create "*scratch*"))
(funcall initial-major-mode)
(insert-file-contents scratch-file nil nil nil t)
(ignore-errors (kill-buffer ".scratch")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment