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.

60 lines
1.1 KiB

  1. #!/usr/bin/env perl
  2. # Execute shell commands with the included block passed to their stdin.
  3. #
  4. # See also: filter-exec, filter-exec-raw.
  5. use strict;
  6. use warnings;
  7. use 5.10.0;
  8. use IPC::Cmd qw(can_run run_forked);
  9. my $text;
  10. {
  11. # line separator:
  12. local $/ = undef;
  13. $text = <>;
  14. }
  15. $text =~ s{
  16. <!--[ ]exec-stdin[ ](.*?)[ ]-->\n
  17. (.*?)\n
  18. <!--[ ]end[ ]-->
  19. }{
  20. handle_block($1, $2);
  21. }egsx;
  22. print $text;
  23. sub handle_block {
  24. my ($command, $input) = @_;
  25. my $output_text = '';
  26. my $result = run_forked($command, {
  27. child_stdin => $input,
  28. timeout => 300,
  29. stdout_handler => sub { $output_text .= $_[0]; },
  30. stderr_handler => sub { $output_text .= $_[0]; }
  31. });
  32. # Kill any trailing newlines so that the output will fit between markers
  33. # without adding a blank line (something about this will probably lead to
  34. # bugs eventually):
  35. chomp($output_text);
  36. my $starter = 'exec-stdin';
  37. return "<!-- $starter $command -->\n$output_text\n<!-- end -->";
  38. }
  39. __DATA__
  40. A self-test - add some numbers and use ,r in vim to check:
  41. <!-- exec-stdin sort -n -->
  42. 1
  43. 2
  44. 8
  45. 9
  46. 10
  47. <!-- end -->