#!/usr/bin/perl -CDS
use utf8;
+use POSIX qw(strftime);
+use MIME::Base64;
# char-level modes
my $poetry = 0;
my $verbatim = 0;
xmlns:l=\"http://www.w3.org/1999/xlink\">\n";
my $metadata = shift @ARGV;
open F,"<",$metadata;
+my $pics = "";
while (<F>) {
+ # Replace empty date with current date
+ if (/<date\s+\/>/ || /<date>\s*<\/date>/) {
+ $_ = "<date value=\"".strftime("%Y-%m-%d",localtime())."\">".
+ strftime("%d/%m/%Y",localtime())."</date>\n";
+ }
+ # Add current to date as fractional part to version
+ if (/<version>(\d*)(.\d*)?<\/version>/) {
+ my $ver = $1+time()/1E10;
+ $_=tag(sprintf("%g",$ver),"version")."\n";
+ }
+ # Если существует cover.png, добавляем coverpage
+ if (/<coverpage \/>/) {
+ $_="";
+ if (-f "cover.png") {
+ my $id = "cover_png";
+ $_ = "<coverpage>\n<image l:href=\"#$id\" />\n</coverpage>\n";
+ $pics .= mkbinary("cover.png",$id);
+ }
+ }
print $_;
}
close F;
next LINE;
}
next LINE if /\\pagebreak\b/;
+#replace ' and " with entities
+s/&/&/g;
+s/'/'/g;
+s/"/"/g;
+s/</</g;
+s/>/>/g;
#normal mode:
if (!$verbatim) {
#strip TeX comments
s/(\s)\s+/$1/g;
#replace TeX ligatures ~ --- << >> \% with appropriate unicode symbols
s/~/\xA0/g;
-s/---/-/g;
+s/\\-/\xAD/g;
+s/---/—/g;
s/<</«/g;
s/>>/»/g;
s/\\%/%/g;
s/\\dots/\x{2026}/g;
+s/\\verb(.)(.*)\1/<code>$2<\/code>/;
}
-#replace ' and " with entities
-s/&/&/g;
-s/'/'/g;
-s/"/"/g;
-s/</</g;
-s/>/>/g;
if ($poetry) {
chomp;
+ if ($poetic_buffer) {
+ $_ = $poetic_buffer." ".$_;
+ $poetic_buffer = undef;
+ }
+ if (/{[^}]+$/) {
+ $poetic_buffer=$_;
+ next LINE;
+ }
+ s/\\footnote{(.*)}/push_footnote($1)/e;
s/\s*\\\\$//;
$buffer.=tag($_,'v')."\n";
} elsif ($verbatim) {
}
print "</body>\n";
## print footnotes
-print "<body id=\"notes\">\n$footnotes\n</body>" if $footnotes;
+print "<body>\n$footnotes\n</body>" if $footnotes;
+print $pics;
print "</FictionBook>";
sub add_to_section {
my $data = shift;
return if ($#sections<0) ;
+ if ($data =~ /^\s*<section>/ && $sections[$#sections]->{data} !~ /^\s*<section>/) {
+ $sections[$#sections]->{data} = tag($sections[$#sections]->{data},"section")."\n";
+ }
$sections[$#sections]->{data}.=$data;
}
if ($str->{title}) {
$content = tag($str->{title},"title");
}
- $content .= $str->{data};
+ if ($str->{data} =~ /^\s*$/s) {
+ $content .= "<p>\n</p>";
+ } else {
+ $content .= $str->{data};
+ }
if ($#sections >=0) {
add_to_section(tag($content,$tag)."\n");
} else {
sub tag {
my ($content,$name) = @_;
- return "" if $content =~ /^\s*$/s;
+ $content =~s/^\s+//s;
+ return "" unless $content;
return "<$name>$content</$name>";
}
$footnotes.="<section id=\"$id\">".tag(shift,'p')."</section>\n";
return "<a l:href=\"#$id\" type=\"note\">$idseq</a>";
}
+
+sub mkbinary {
+ my ($filename,$id) = @_;
+ my $f;
+ open $f,"<",$filename;
+ binmode $f;
+ local $/;
+ my $data = encode_base64(<$f>);
+ return "<binary id=\"$id\" content-type=\"image/png\">$data</binary>\n";
+ close $f;
+}