summaryrefslogtreecommitdiff
path: root/pandoc-cs1
blob: 614e2ae8ebbdb35dc4db889db9c45eb695a3fbd5 (plain)
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. use feature qw(switch);
  5. no if $] >= 5.018, warnings => "experimental::smartmatch";
  6. use Pandoc::Filter 0.05;
  7. use Pandoc::Elements;
  8. use Text::BibTeX::Entry;
  9. use Path::Tiny;
  10. use List::Util qw(pairmap);
  11. use DateTime::Format::Flexible;
  12. my $bibfilename = $ENV{'PANDOC_CITEPROC_FILE'} || 'bibliography.bib';
  13. my $bibfile = path($bibfilename);
  14. my $bibdata = new Text::BibTeX::Entry;
  15. my (@a, $i);
  16. pandoc_filter sub {
  17.     my $self = shift;
  18.     return unless ($self->name eq 'RawInline' and $self->format eq 'mediawiki');
  19.     given ($self->content) {
  20.         when (/^{{cite\s+(\w+)\s*\|([^}]*)}}$/) {
  21.             my $id = 'ref'.++$i;
  22.             my @data = pairmap { $b =~ s/"/\\"/g; "$a=\"$b\"" }
  23.                 map { /^\s*(\w+)\s*=\s*"?(.*?)"?\s*$/ }
  24.                     split( /\|/, $2 );
  25.             $bibdata->parse_s (join ",\n",
  26.                 '@'.$1.'{'.$id,
  27.                 @data,
  28.                 '}');
  29.             if ( $bibdata->type =~ /web/i ) {
  30.                 $bibdata->set_type('online');
  31.                 if ( my $urldate = $bibdata->get('accessdate') ) {
  32.                     my $dt = DateTime::Format::Flexible->parse_datetime($urldate);
  33.                     $bibdata->set( 'urldate', $dt->format_cldr('yyyy-MM-dd') );
  34.                     $bibdata->delete('accessdate');
  35.                 };
  36.             };
  37.             $bibfile->spew( '' )
  38.                 if ( $i <= 1 );
  39.             $bibfile->append( $bibdata->print_s );
  40.             return Cite(
  41.                 [{
  42.                     'citationId' => $id,
  43.                     'citationPrefix' => [],
  44.                     'citationSuffix' => [],
  45.                     'citationMode' => {
  46.                         t => 'NormalCitation',
  47.                         c => [],
  48.                     },
  49.                     'citationNoteNum' => 0,
  50.                     'citationHash' => 0,
  51.                  }],
  52.                 [ Str $id ],
  53.             );
  54.         }
  55.         when (/^{{citation needed}}$/) {
  56.             say STDERR "WARNING: Mediawiki citation needed.";
  57.             return [
  58.                 Str "citation",
  59.                 Space,
  60.                 Str "needed",
  61.             ];
  62.         }
  63.         default {
  64.             say STDERR "WARNING: Mediawiki unknown data skipped: "
  65.                 . '"' . $_[0]->content . '"';
  66.             return Str "";
  67.         }
  68.     }
  69. };