I would like emacs to check for a
~/emacs.d/scratch.txt and use it's contents instead of the default message when emacs starts.
How can this be done?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.Sign up to join this community
This can be done using
initial-buffer-choice can be set to a filename, this will load the file as well as any files passed via the command line (splitting the window or not even showing the buffer depending on your setup).
So reading file data into
*scratch* buffer has the advantage that exact behavior is preserved, just replacing the text.
startup.txt, optionally taking a user defined startup file.
startup.orgfor an org-mode buffer.
Adds a short commented line at the top of the file, eg:
# Emacs: 28.0, time: 0.93, packages: 58
;; Load startup text when available. ;; ;; Example usage: ;; ;; (my-startup-buffer-from-file) ;; ;; Or if you like to use an org-mode scratch buffer, ;; an option file path can be passed in. ;; The file extension is used to set the mode: ;; ;; (my-scratch-buffer-from-file (concat user-emacs-directory "scratch.org")) ;; (defvar my-scratch-buffer-from-file--value nil) (defun my-scratch-buffer-from-file (&optional scratch-file) (setq inhibit-startup-screen t) (setq initial-scratch-message nil) (when scratch-file (setq my-scratch-buffer-from-file--value scratch-file)) (setq initial-buffer-choice (lambda () (if (buffer-file-name) (current-buffer) ;; leave as-is (let ((original-buffer (current-buffer)) (filename (or my-scratch-buffer-from-file--value (concat user-emacs-directory "scratch.txt"))) ;; Not essential, just gives some handy startup info. (startup-info (format "Emacs: %d.%d, time: %.2f, packages: %d" emacs-major-version emacs-minor-version (float-time (time-subtract after-init-time before-init-time)) (length package-activated-list)))) (with-current-buffer (get-buffer-create "*scratch*") ;; Don't track undo. (buffer-disable-undo) ;; Set the mode based on the filename, users may use filenames that infer modes. (let ((buffer-file-name filename)) (set-auto-mode t)) ;; Use the comment character set by the mode where possible. (let ((comment-start-or-empty (if comment-start ;; Ensure one trailing space (some comments include space). (concat (replace-regexp-in-string "[[:space:]]*$" "" comment-start) " ") ""))) (if (file-exists-p filename) (insert-file-contents filename) (insert comment-start-or-empty (format "Scratch buffer, create '%s' to replace this text on startup." filename)) (goto-char (point-min))) ;; Add some startup info above the static text. (insert comment-start-or-empty startup-info "\n\n")) (buffer-enable-undo) (set-buffer original-buffer)))))))
Others might suggest how this can be done better, it seems to work well enough though.