Dotfiles, utilities, and other apparatus.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

91 lines
1.9 KiB

#!/usr/bin/env perl
# Execute shell commands and include their output in the current buffer.
#
# This is brittle and probably very subject to quoting problems, but in
# practice it's been a useful hack for local notes and technical writing.
#
# See also:
#
# - filter-exec for formatted output including the original command
#
# - filter-exec-stdin for a version that passes the contained block to
# stdin of the executed command
use strict;
use warnings;
use 5.10.0;
my $text;
{
# Line separator:
local $/ = undef;
$text = <>;
}
# HTML quote markers / commands:
$text =~ s{
<!--[ ]exec-raw[ ](.*?)[ ]-->
.*?
<!--[ ]end[ ]-->
}{
handle_block('<!-- ', $1, ' -->', '<!-- end -->');
}egsx;
# Vim/VimWiki-style markers:
$text =~ s/
[{]{3}exec-raw[ ](.*?)$
.*?
[}]{3}
/
handle_block('{{{', $1, '', '}}}');
/egmsx;
print $text;
sub handle_block {
my ($start, $command, $command_end, $end) = @_;
# Note that we're redirecting stderr here, so it shows up inside the
# output block rather than at the top of the filtered file:
my $result = qx{$command 2>&1};
unless (defined $result) {
# TODO: Make this handle malformed or missing commands better by
# piping the command string to a shell instead of system()ing
# directly.
$result = "Command not found? Exit status: $?\n";
}
return "${start}exec-raw ${command}${command_end}\n${result}${end}";
}
__DATA__
A self-test - use ,r in vim to check:
{{{exec-raw date
Sun 04 Jun 2023 12:25:56 PM MDT
}}}
<!-- exec-raw date -->
Sun 04 Jun 2023 12:25:56 PM MDT
<!-- end -->
<!-- exec-raw pwd -->
/home/brennen/code/bpb-kit/home/bin
<!-- end -->
<!-- exec -->
$ ls -lah ~/bin/filter-exec-raw
-rwxr-xr-x 1 brennen brennen 1.8K Jun 4 12:25 /home/brennen/bin/filter-exec-raw
<!-- end -->
{{{exec-raw ls adfasdfsf
ls: cannot access 'adfasdfsf': No such file or directory
}}}
{{{exec-raw command-which-does-not-exist
error: -1
}}}