hanoo
hanoo

Reputation: 4245

Emacs : how to load file content in scratch screen

I would like to load "~/todo.org" file content in scratch buffer at startup.

I have tried:

(setq initial-buffer-choice "~/todo.org")

But it opens the file in a new buffer (not scratch).

I have also tried:

(setq initial-scratch-message "~/todo.org")

But it prints the file path in the scratch buffer and i would like it's content.

I also would like to change the mode of the scratch buffer to org-mode.

I have tried:

(setq initial-major-mode org-mode)

But i have an initialisation error

Symbol's value as variable is void: org-mode

Upvotes: 0

Views: 598

Answers (2)

hanoo
hanoo

Reputation: 4245

Finally, i'll go for this:

(condition-case err
  (when (get-buffer "*scratch*")
    (with-current-buffer "*scratch*"
      (erase-buffer)
      (insert-file-contents "~/todo.org")
      (org-mode)
    )
  )
(error (message "%s" error-message-string err)))

Upvotes: 1

Thomas
Thomas

Reputation: 17422

You can achieve the desired effect with a little bit of Lisp code that you put in your init file:

(condition-case err
    (with-current-buffer "*scratch*"
      (let ((min (point-min))
            (max (point-max))
        (goto-char max)
        (insert-file-contents "~/todo.org")
        (delete-region min max)
        (org-mode)))
  (error (message "%s" error-message-string err)))

But as @phils pointed out in a comment to your question, the *scratch* buffer might not be the best buffer to use for this functionality. Thus, I suggest to consider the following alternative:

(condition-case err
    (let ((buffer (get-buffer-create "*todo*")))
      (with-current-buffer buffer
        (insert-file-contents "~/todo.org")
        (org-mode))
      (setq initial-buffer-choice buffer))
  (error (message "%s" error-message-string err)))

By using this version, you leave the *scratch* buffer alone. Your .org file will be inserted in a separate buffer by the name of *todo*. This buffer is not associated with your ~/todo.org file, so when you first try save it, you will have to specify a file name.

Upvotes: 1

Related Questions