Emacs Command From Outside Emacs

Sometimes it’s convenient to execute an Emacs command from outside Emacs. The traditional way of doing that is to run Emacs in server mode and use emacsclient like this:

emacsclient --eval "(some-emacs-command)"

You can, of course, execute several Emacs commands in a row by wrapping everything in a progn.

The problem comes when the command you want to execute is interactive. If the function you’re calling needs some user input, it’s going to have to open an Emacs window and you’re going to have to change focus to that window. You might just as well have done the whole thing in Emacs to begin with.

Isa Mert Gurbuz has posted a nice way to handle some of those situations. The goal is to call the command and handle all the interaction from the command line without having to change focus to Emacs. His two examples show how to pick a choice from a list as with completing read, and how to read an arbitrary string. Reading an arbitrary string isn’t too useful, of course, but it can be an important building block for more complex functionality.

When I’m not in Emacs, I can’t wait to get back so I’ve never felt the need for this sort of thing but Gurbuz’s example of controlling MPV from Emacs when you’re not in Emacs is compelling. In any event, if you’ve ever felt the need to invoke an Emacs function when you’re not in Emacs, take a look at Gurbuz’s post. It’s got a lot of good ideas.

This entry was posted in General and tagged . Bookmark the permalink.