pygmentize.pl 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright (C) 2015 Alex-Daniel Jakimenko <alex.jakimenko@gmail.com>
  2. #
  3. # This program is free software: you can redistribute it and/or modify it under
  4. # the terms of the GNU General Public License as published by the Free Software
  5. # Foundation, either version 3 of the License, or (at your option) any later
  6. # version.
  7. #
  8. # This program is distributed in the hope that it will be useful, but WITHOUT
  9. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  10. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License along with
  13. # this program. If not, see <http://www.gnu.org/licenses/>.
  14. use strict;
  15. # use warnings;
  16. use v5.10;
  17. use utf8;
  18. AddModuleDescription('pygmentize.pl', 'Pygmentize Extension');
  19. our ($q, $bol, @KnownLocks, %RuleOrder, @MyRules, $TempDir, @MyInitVariables);
  20. # You can push other stuff to that list.
  21. # For example: push @PygmentizeArgs, qw(-F whitespace:spaces=true,tabs=true)
  22. # If you want to change existing options then just reinitialize the list
  23. our @PygmentizeArgs = qw(-O noclasses);
  24. push(@MyInitVariables, sub {
  25. push(@KnownLocks, 'pygmentize');
  26. });
  27. push(@MyRules, \&PygmentizeRule);
  28. $RuleOrder{\&PygmentizeRule} = -60;
  29. sub PygmentizeRule {
  30. if ($bol && m/\G\{\{\{(\w+)?[ \t]*\n(.*?)\n\}\}\}[ \t]*(\n|$)/cgs) {
  31. my $lexer = $1;
  32. my $contents = $2;
  33. return CloseHtmlEnvironments() . DoPygmentize($contents, $lexer) . AddHtmlEnvironment('p');
  34. }
  35. return;
  36. }
  37. sub DoPygmentize {
  38. my ($contents, $lexer) = @_;
  39. $lexer = "-l \Q$lexer\E" if $lexer; # should be already safe, but \Q \E just because I'm paranoid
  40. $lexer ||= '-g'; # -g for autodetect
  41. my $args = join ' ', map { quotemeta } @PygmentizeArgs;
  42. CreateDir($TempDir);
  43. $contents = UnquoteHtml($contents);
  44. RequestLockDir('pygmentize') or return '';
  45. WriteStringToFile("$TempDir/pygmentize", $contents);
  46. my $output = decode_utf8(`pygmentize $lexer -f html -O encoding=utf8 $args -- \Q$TempDir/pygmentize\E 2>&1`);
  47. ReleaseLockDir('pygmentize');
  48. if ($?) {
  49. $output = $q->p($q->strong($output)) # "sh: pygmentize: command not found"
  50. . $q->pre($contents);
  51. }
  52. return $output;
  53. }