1

G'day! it's my "learn some more Elisp" day.

I'm trying to make a shortcut that opens my main org file. I've made it this far

(global-set-key (kbd "C-c h") 'switch-to-most-recent-org-file)

(defun switch-to-most-recent-org-file ()
  (interactive)
  (message "hi"))

Instead of (message "hi"), I want emacs to switch to the .org file in the Buffer List. Sometimes there will be multiple .org files in the Buffer List, in that case go for the one at the top.

4
  • (global-set-key (kbd "C-c h") 'switch-to-most-recent-org-file) (defun switch-to-most-recent-org-file () (interactive) (message "hi")) Commented Sep 27, 2017 at 16:11
  • 1
    Yes, I read that the first time. Very cheeky. What have you tried in place of (message "hi")? If the answer is "I tried X, Y, and Z, but I'm stuck," then say so so people can help. If the answer is "nothing," however, please do some basic background research before posting a question. Start with the elisp manual nodes on Switching to a Buffer in a Window and The Buffer List. I found these nodes via google searches.
    – Dan
    Commented Sep 27, 2017 at 17:09
  • I come here for help with code and I go away with life advice :) Commented Sep 27, 2017 at 17:10
  • Here is something to get you started. If the buffer-list is not being processed with mapc in the right order, then you can reverse the order with (nreverse (buffer-list)) -- If you want the second to the most recent assuming that you are already in an org-mode buffer, then you'll need to tweak the example: (let (found) (catch 'done (mapc (lambda (x) (when (with-current-buffer x (eq major-mode 'org-mode)) (switch-to-buffer x) (setq found t) (throw 'done nil))) (buffer-list)) (unless found (message "not found")))) I'm not writing an answer, because I don't have much free time.
    – lawlist
    Commented Sep 27, 2017 at 20:23

2 Answers 2

1

The answer given by @lawlist works for me.

(global-set-key (kbd "C-c h") 'switch-to-most-recent-org-file)

(defun switch-to-most-recent-org-file ()
  (interactive)
  (let (found)
    (catch 'done
      (mapc (lambda (x)
              (when (with-current-buffer x (eq major-mode 'org-mode))
                (switch-to-buffer x)
                (setq found t)
                (throw 'done nil)))
            (buffer-list))
      (unless found (message "not found")))))
0

Sometimes the file you want to switch to might not be in the buffer-list. (Very early in the morning after a reboot)

So I find the answer mentioned at https://stackoverflow.com/questions/12558019/shortcut-to-open-a-specific-file-in-emacs useful.

Personally I prefer to use emacs registers to store files which I use often. I would store '~/.emacs' in a register:

(set-register ?e (cons 'file "~/.emacs"))

and open it with C-x r j e

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.