From 81910209798d0bb030cd6007286da59c0ea312dd Mon Sep 17 00:00:00 2001 From: P. J. McDermott Date: Sun, 12 Aug 2012 07:23:38 -0400 Subject: Parse Markdown headings. --- (limited to 'scripts/MarkdownBook') diff --git a/scripts/MarkdownBook/Document.pm b/scripts/MarkdownBook/Document.pm index 30c6314..6b6b966 100644 --- a/scripts/MarkdownBook/Document.pm +++ b/scripts/MarkdownBook/Document.pm @@ -16,6 +16,7 @@ use strict; use warnings; +use MarkdownBook::Section; use MarkdownBook::HTMLTree; use HTML::TreeBuilder; @@ -130,4 +131,92 @@ sub sections return $self->{'sections'}; } +sub parse +{ + my ($self) = @_; + my $source_fh; + my $source_text; + + open($source_fh, '<', + $self->{'book'}->dir() . '/' . $self->{'file'} . '.mdwn'); + $source_text = join('', <$source_fh>); + close($source_fh); + + if ($self->{'type'} ne 'index') { + $self->{'section_level_numbers'} = [0, 0]; + $self->{'section_level'} = -1; + $source_text =~ s/ + ^ + (.+) # Heading text + [ \t]* # Optional trailing whitespace + \n # Line break + (=+|-+) # Underline + [ \t]* # Optional trailing whitespace + $ + /$self->_do_header($1, $2)/mexg; + } + + $self->{'source_text'} = $source_text; +} + +sub _do_header +{ + my ($self, $text, $underline) = @_; + my $level; + my $levels; + my $section_number; + my $section_title; + my $section_id; + my $section; + + $underline =~ s/^([=-]).*$/$1/; + if ($underline eq '=') { + $level = 1; + } else { + $level = 2; + } + + $levels = $#{$self->{'section_level_numbers'}}; + if ($level != $self->{'section_level'}) { + foreach (@{$self->{'section_level_numbers'}}[$level .. $levels]) { + $_ = 0; + } + } + $self->{'section_level'} = $level; + ++${$self->{'section_level_numbers'}}[$level - 1]; + $section_number = join('.', @{$self->{'section_level_numbers'}}); + $section_number = $self->{'id'} . '.' . $section_number; + $section_number =~ s/(?:\.0)*$//; + + $section_title = $text; + $section_title =~ s/ + ^ + ([^\[]+) # Section title + [ \t]+ # Whitespace + \[ # Left square bracket + [^\]]+ # Section ID + \] # Right square bracket + $ + /$1/x; + + $section_id = $text; + $section_id =~ s/ + ^ + [^\[\]]+ # Section title + [ \t]+ # Whitespace + \[ # Left square bracket + ([^\]]+) # Section ID + \] # Right square bracket + $ + /$1/x; + + $section = MarkdownBook::Section->new($self, + $section_number, $section_id, $section_title); + push(@{$self->{'sections'}}, $section); + + $text = $section_number . ' ' . $section_title; + + return $text . "\n" . $underline x length($text); +} + 1; -- cgit v0.9.1