Begin main content

Piping to an emacs buffer with emacsclient

GNU Emacs buffs will know all about emacsclient - it's a commandline program that allows you to open files in a new buffer in an already running emacs instance. It's very handy. What you may not know is you can also evaluate arbitrary Emacs lisp using emacsclient. Using this fact and based on an existing example from EmacsWiki I have written a perl script that you can pipe to, and the piped data will appear in a buffer via emacsclient.

My ultimate aim is for a PAGER script to use instead of less in my emacs shell. While this isn't quite perfect for that use, it's still pretty useful.

NB: The code below is probably out of date by the time you read this - see this gist for the latest version that you can clone, fork etc.

#!/usr/bin/perl
usestrict;
usewarnings;

useIO::Select;

my$emacsclient = "/usr/local/bin/emacsclient";

# This script uses emacsclient, be sure to have a running server session.
# A server-session can be started by "M-x server-start".
exit 1
    if 0 != system("$emacsclient -n --eval '(progn (pop-to-buffer (get-buffer-create \"*piped*\")))'");

my$s = IO::Select->new;
$s->add(\*STDIN);

while (1)
{
    # block until data available
my$data = <STDIN>;

    # exit if STDIN closed
exit(0)
        if!$data;

    # keep reading while data is available, or we have a bunch of lines
my$lines = 0;
    $data .= <STDIN>
        while$lines++ < 100 && $s->can_read(.5);

    $data =~ s/"/\\"/g;
    $data =~ s/'/'\\''/g;
    $data =~ s/\\/\\\\/g;
    system(qq{$emacsclient -n --eval '(with-current-buffer "*piped*" (goto-char (point-max)) (insert "}
            . $data . qq{"))'});
}

06:23 PM, 02 Mar 2011 by Mark Aufflick Permalink

One more escape

Just needs to escape backslashes too, $data =~ s/\\/\\\\/g;

by Unregistered Visitor on 03/03/11

Good point

I was thinking it's not necessary since the shell single quote doesn't treat backslashes specially, but of course the emacs lisp double quoted string will. I've updated the main post accordingly.

by Mark Aufflick on 03/06/11

Note I've updated the gist

So it now works for file paths as arguments too, since some commands assume the PAGER can do that.

by Unregistered Visitor on 03/04/14

Nice post

Guar protein offer a wide selection of products for your specific requirements. Established in the year 2008, we are one of the leading Manufacturer, Exporter and Supplier of Compound Guar Protein Meal Feeds and Poultry Feeds.
Guar meal exporter india and Organic Poultry feed

by Unregistered Visitor on 09/17/14

Add comment