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

  1. #!/usr/bin/env perl
  2. # Execute shell commands and include their output in the current buffer.
  3. #
  4. # This is brittle and probably very subject to quoting problems, but in
  5. # practice it's been a useful hack for local notes and technical writing.
  6. #
  7. # See also:
  8. #
  9. # - filter-exec for formatted output including the original command
  10. #
  11. # - filter-exec-stdin for a version that passes the contained block to
  12. # stdin of the executed command
  13. use strict;
  14. use warnings;
  15. use 5.10.0;
  16. my $text;
  17. {
  18. # Line separator:
  19. local $/ = undef;
  20. $text = <>;
  21. }
  22. # HTML quote markers / commands:
  23. $text =~ s{
  24. <!--[ ]exec-raw[ ](.*?)[ ]-->
  25. .*?
  26. <!--[ ]end[ ]-->
  27. }{
  28. handle_block('<!-- ', $1, ' -->', '<!-- end -->');
  29. }egsx;
  30. # Vim/VimWiki-style markers:
  31. $text =~ s/
  32. [{]{3}exec-raw[ ](.*?)$
  33. .*?
  34. [}]{3}
  35. /
  36. handle_block('{{{', $1, '', '}}}');
  37. /egmsx;
  38. print $text;
  39. sub handle_block {
  40. my ($start, $command, $command_end, $end) = @_;
  41. # Note that we're redirecting stderr here, so it shows up inside the
  42. # output block rather than at the top of the filtered file:
  43. my $result = qx{$command 2>&1};
  44. unless (defined $result) {
  45. # TODO: Make this handle malformed or missing commands better by
  46. # piping the command string to a shell instead of system()ing
  47. # directly.
  48. $result = "Command not found? Exit status: $?\n";
  49. }
  50. return "${start}exec-raw ${command}${command_end}\n${result}${end}";
  51. }
  52. __DATA__
  53. A self-test - use ,r in vim to check:
  54. {{{exec-raw date
  55. Sun 04 Jun 2023 12:25:56 PM MDT
  56. }}}
  57. <!-- exec-raw date -->
  58. Sun 04 Jun 2023 12:25:56 PM MDT
  59. <!-- end -->
  60. <!-- exec-raw pwd -->
  61. /home/brennen/code/bpb-kit/home/bin
  62. <!-- end -->
  63. <!-- exec -->
  64. $ ls -lah ~/bin/filter-exec-raw
  65. -rwxr-xr-x 1 brennen brennen 1.8K Jun 4 12:25 /home/brennen/bin/filter-exec-raw
  66. <!-- end -->
  67. {{{exec-raw ls adfasdfsf
  68. ls: cannot access 'adfasdfsf': No such file or directory
  69. }}}
  70. {{{exec-raw command-which-does-not-exist
  71. error: -1
  72. }}}