App-sdview

 view release on metacpan or  search on metacpan

lib/App/sdview/Parser/Markdown.pm  view on Meta::CPAN

use v5.26;
use warnings;

use Object::Pad 0.807;

package App::sdview::Parser::Markdown 0.20;
class App::sdview::Parser::Markdown :strict(params);

apply App::sdview::Parser;

use File::Slurper 'read_text';

use String::Tagged::Markdown 0.05;

use constant format => "Markdown";
use constant sort_order => 20;

=head1 NAME

C<App::sdview::Parser::Markdown> - parse Markdown files for L<App::sdview>

=head1 SYNOPSIS

   $ sdview README.md

   $ sdview -f Markdown my-document

=head1 DESCRIPTION

This parser module adds to L<App::sdview> the ability to parse input text in
Markdown formatting.

It uses a custom in-built parser for the block-level parts of the formatting,
able to handle comments, verbatim blocks, headings in both C<#>-prefixed and
C<=>-underlined styles, bullet and numbered lists, and tables.

It uses L<String::Tagged::Markdown> to parse the inline-level formatting,
supporting bold, italic, strikethrough, and fixed-width styles, and links.

=cut

sub find_file ( $class, $name ) { return undef }

sub can_parse_file ( $class, $file )
{
   return $file =~ m/\.(?:md|markdown)$/;
}

method parse_file ( $fh )
{
   return $self->parse_string( read_text $fh );
}

field @_paragraphs;

sub _split_table_row ( $str )
{
   $str =~ m/^\s*\|/ or return undef;
   $str =~ m/\|\s*$/ or return undef;

   my @cols = split m/\|/, $str, -1;
   shift @cols; pop @cols;

   s/^\s+//, s/\s+$// for @cols;

   return \@cols;
}

method parse_string ( $str )
{
   my $in_verb;

   my @lines;

   foreach ( split( m/\n/, $str ), "" ) {
      my $line = $_; # So we have a copy, because foreach my ... will alias the readonly ""

      if( $in_verb ) {
         my $para = $_paragraphs[-1];

         if( $line =~ m/^\`\`\`/ ) {
            undef $in_verb;
            next
         }

         length $para->text and
            $para->text->append( "\n" );

         $para->text->append( $line );
         next;
      }

      if( $line =~ s/^\`\`\`// ) {
         my $language = $line =~ s/^\s+|\s+$//gr;
         push @_paragraphs, App::sdview::Para::Verbatim->new(
            language => ( length $language ? $language : undef ),
            text     => String::Tagged->new,
         );
         $in_verb++;
         next;
      }

      if( length $line ) {
         push @lines, $line;
         next;
      }

      while( @lines ) {
         if( $lines[0] =~ m/^<!--/ ) { # comment
            ;
         }
         elsif( $lines[0] =~ m/^    / ) { # verbatim
            my $raw = join "\n", @lines;
            $raw =~ s/^    //mg;

            push @_paragraphs, App::sdview::Para::Verbatim->new(
               text => String::Tagged->new( $raw ),
            );
         }
         elsif( $lines[0] =~ s/^(#+)\s+// ) { # heading
            my $level = length $1;



( run in 1.617 second using v1.01-cache-2.11-cpan-af0e5977854 )