5

In Emacs, is there a command to open the most recently opened file? Like a visit-most-recent-file?

Note that I don't want to view a LIST of recent files and then select one. I want to automatically visit the most recently opened one.

It would be great to visit a recently-opened file (that's no longer in a current buffer) with a single keystroke. And then be able to visit the next most recently opened file by invoking the keystroke again, and so on.

So that by pressing that keystroke four times (e.g. A-UP), I could automatically open the top four files on my recent files list.

I can kind of sort of do this already by browsing through recent files, by pressing C-x C-f UP RET, but it would be cool to do it in a single keystroke (e.g. A-UP).

incandescentman
  • 6,168
  • 3
  • 46
  • 86

2 Answers2

3

Building off of pokita's answer,

(defun visit-most-recent-file ()
  "Visits the most recently open file in `recentf-list' that is not already being visited."
  (interactive)
  (let ((buffer-file-name-list (mapcar 'buffer-file-name (buffer-list)))
        most-recent-filename)
    (dolist (filename recentf-list)
      (unless (memq filename buffer-file-name-list)
        (setq most-recent-filename filename)
        (return)))
    (find-file most-recent-filename)))

I haven't tested this very much.

jpkotta
  • 9,237
  • 3
  • 29
  • 34
2

You can do this by using the recentf package:

(require 'recentf)
(defvar my-recentf-counter 0)
(global-set-key (kbd "<M-up>")
        (lambda ()
          (interactive)
          (setq my-recentf-counter (1+ my-recentf-counter))
          (recentf-open-most-recent-file my-recentf-counter)))

You will probably face the problem that there are files in the "recent" list which you are not interested in (temporary stuff that was saved upon exiting Emacs). Use the recentf-exclude variable to exclude those files from the list of recently opened files.

pokita
  • 1,241
  • 10
  • 12
  • Thanks! That kind of works EXCEPT THAT we need a way to reset the recent-f list. i.e. if I press , it successfully opens my most recent file. If I then make the changes I need, save the file, kill the buffer, then press later when I need to open it again, it opens my NEXT most recent file, instead of re-opening the file I'd been working on even though THAT FILE is now the most recent. Solution? – incandescentman Feb 17 '13 at 04:29
  • 1
    You could do (add-hook 'kill-buffer-hook (lambda () (setq my-recentf-counter 0))), but I have a hunch that you'll soon see other problems with that, too. I'm just using recentf-interactive-complete and am happy with that. Alternatively, since you're using ido, take a look at the ido-virtual-buffers variable in newer Emacsen. – pokita Feb 17 '13 at 10:16