Use System File Open Dialog for File Actions in Emacs (Just Once!)
Emacs users sooner or later disable all the GUI stuff, and usually also get rid of system alerts and file pickers.
But if you just once want to pick a file using your operating system’s file picker, these three temporary variable overrides will do:
(let ((last-nonmenu-event nil)
(use-dialog-box t)
(use-file-dialog t))
(call-interactively #'find-file))
If you’re in this situation, you likely already know use-dialog-box
and use-file-dialog
because you’ve set both to nil
globally.
The interesting piece here is last-nonmenu-event
: this tricks the interactive call of find-file
into believing you used the mouse – which apparently is a prerequisite to make the system dialog appear, even though the docs seem to say that’s not always the case (emphasis mine):
use-file-dialog is a variable defined in ‘C source code’.
Its value is nil
Non-nil means mouse commands use a file dialog to ask for files. This applies to commands from menus and tool bar buttons even when they are initiated from the keyboard. If ‘use-dialog-box’ is nil, that disables the use of a file dialog, regardless of the value of this variable.
Now “Open File” in the main menu is bound to find-file
, so the emphasized sentence doesn’t hold true.
But the last-nonmenu-event
trick works. This variable’s docs say:
Last input event in a command, except for mouse menu events. Mouse menus give back keys that don’t look like mouse events; this variable holds the actual mouse event that led to the menu, so that you can determine whether the command was run by mouse or not.
So there you go – put the above code snippet into a function and bind it to another key and you will have a quick way to open files with your system file picker.