-
Notifications
You must be signed in to change notification settings - Fork 0
/
LocalBibStyle.pm
2365 lines (2022 loc) · 76.9 KB
/
LocalBibStyle.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package LocalBibStyle;
use Data::Dumper;
=head1 NAME
Text::BibTeX::BibStyle - Format Text::BibTeX::Entry items using .bst
=cut
our $VERSION = '0.03';
=head1 DESCRIPTION
C<Text::BibTeX::BibStyle> is a module that can format
C<Text::BibTeX::Entry> objects by interpreting a bibstyle (C<.bst>) file
such as C<ieeetr.bst>. In this way, Perl can use the same
bibliographic style files that bibtex does.
For a large collection of C<.bst> files, see
http://www.math.utah.edu/pub/tex/bibtex/index.html.
=head1 SYNOPSIS
$bibstyle = Text::BibTeX::BibStyle->new(%options);
$ENV{BSTINPUTS} = "my/bstfiles/";
$bibstyle->read_bibstyle("bibstyle");
OR
$bibstyle->replace_bibstyle($bibstyle_def);
$ENV{BIBINPUTS} = "my/bibfiles/";
$bibstyle->execute([qw(bibfile1 bibfile2)]);
OR
$bibstyle->execute([qw(bibfile1 bibfile2)], \@ref_list);
@warnings = $bibstyle->warnings;
$output = $bibstyle->get_output();
$output = $bibstyle->convert_format(Text::BibTex::BibStyle::html);
OR
$output = $bibstyle->get_output(\%options);
=cut
use strict;
use warnings;
use vars qw(@ISA @EXPORT_OK $LATEX $HTML $RST);
use Exporter;
@ISA = qw( Exporter );
@EXPORT_OK = qw($HTML $LATEX $RST);
use Carp;
use Text::BibTeX qw(:metatypes :subs :joinmethods :macrosubs);
use Text::BibTeX::Name;
=head1 METHODS
=over
=item C<new [(%options])>
Class method. Creates a new C<Text::BibTeX::BibStyle> object with the
options specified in the optional C<option=>'value'> arguments.The
following options are understood:
=over
=item C<debug>
Turns on debugging messages during execute.
=item C<nowarn>
Turns off warnings from certain sanity checks, such as the existence
of a unique C<ENTRIES> and C<READ> statement within the bibstyle.
=back
=cut
# Exportable output options
$LATEX = { wrap => 1 };
{ # Closure
my $ASCIIMathML_parser;
my %Styles = (
em => 'em',
bf => 'b',
it => 'i',
sl => 'i',
tt => 'tt'
);
$HTML = {
delete_braces => 1,
substitute_newcommand => 1,
character => sub {
my ( $bst, $latex, $unicode, $chars, $accent ) = @_;
use HTML::Entities;
return $unicode ? encode_entities($unicode) : $chars;
},
command => sub {
my ( $bst, $cmd, @args ) = @_;
if ( $cmd =~ /^(begin|end)$/ ) {
if ( $args[0] eq 'thebibliography' ) {
my $slash = $cmd eq 'end' ? '/' : '';
my $pre;
if ( $cmd eq 'begin' ) {
$pre = qq(<h2>References</h2>\n\n);
}
else {
$pre = "</td>";
}
return "$pre<${slash}table>";
}
}
elsif ( $cmd eq 'bibitem' ) {
my $key = pop @args;
$bst->{html}{Bib_count}++;
my $label = $args[0] || $bst->{html}{Bib_count};
( $bst->{html}{Cites}{$key} = $label ) =~
s/[{}]//g; # Remove braces
my $pre = $bst->{html}{Bib_count} > 1 ? "</td>\n" : '';
return
qq($pre<tr valign="top"><td><a name="$key">[$label]</a></td><td>);
}
elsif ( $cmd eq 'mbox' ) {
return $args[0];
}
elsif ( $cmd eq 'cite' ) {
return qq(<a href="#$args[0]"><cite>$args[0]</cite></a>);
}
},
init => sub {
my ($bst) = @_;
# Initialize instance variables
$bst->{html} = { Bib_count => 0, Cites => {} };
},
math => sub {
my ( $bst, $latex, $math ) = @_;
use Text::ASCIIMathML;
$ASCIIMathML_parser = Text::ASCIIMathML->new()
unless $ASCIIMathML_parser;
return $ASCIIMathML_parser->TextToMathML($math);
},
postprocess => sub {
my ( $bst, $text ) = @_;
# Substitute back any cite tags
$text =~ s!<cite>(.*?)</cite>![$bst->{html}{Cites}{$1}]!g;
return $text;
},
style => sub {
my ( $bst, $latex, $style, $text ) = @_;
my $html_style = $Styles{$style};
return defined $html_style
? "<$html_style>$text</$html_style>"
: $text;
},
};
}
{ # Closure
my %Styles = (
em => '*',
bf => '**',
it => '*',
sl => '*',
tt => '``'
);
$RST = {
delete_braces => 1,
substitute_newcommand => 1,
# prologue => "",
character => sub {
my ( $bst, $latex, $unicode, $chars, $accent ) = @_;
return $chars if !$unicode;
my $code = ord $unicode;
$bst->{rst}{unicode}{$code} = 1;
return sprintf '\\ |unicode(%x)|\\ ', $code;
},
command => sub {
my ( $bst, $cmd, @args ) = @_;
if ( $cmd =~ /^(begin|end)$/ ) {
if ( $args[0] eq 'thebibliography' ) {
if ( $cmd eq 'begin' ) {
return qq(**References**\n\n\n);
}
}
}
elsif ( $cmd eq 'bibitem' ) {
my $key = pop @args;
$bst->{rst}{Bib_count}++;
my $label = $args[0] || $bst->{rst}{Bib_count};
if ( $args[0] ) {
my $bst2 = Text::BibTeX::BibStyle->new;
$label = $bst2->convert_format( $label, $RST );
}
$bst->{rst}{Cites}{$key} = $label;
return ".. [$key] ";
}
elsif ( $cmd eq 'mbox' ) {
return $args[0];
}
elsif ( $cmd eq 'cite' ) {
return "\\ [$args[0]]_";
}
},
init => sub {
my ($bst) = @_;
# Initialize instance variables
$bst->{rst} = { Bib_count => 0, Cites => {}, unicode => {} };
},
math => sub {
my ( $bst, $latex, $math ) = @_;
# Latex sometimes starts with ^ or _ for super/subscript
$math =~ s/^([_^])/{::}$1/;
$math =~ s/([{}])/\\$1/g;
$math =~ s/\\/\\\\/g;
return "\\ :mathml:`$math`\\ ";
},
postprocess => sub {
my ( $bst, $text ) = @_;
# Fix the indentations
$text =~ s/^[ ]*$//mg;
$text =~ s/^(?!\A|\.\.|\*\*)[ ]*(.+)/ $1/mg;
$text =~ s/\\([\\{}])/$1/g;
foreach my $code ( sort keys %{ $bst->{rst}{unicode} } ) {
$text .= sprintf ".. |unicode(%x)| unicode:: U+%x\n", $code,
$code;
}
return $text;
},
style => sub {
my ( $bst, $latex, $style, $text ) = @_;
my $rst_style = $Styles{$style};
if ($rst_style) {
my ( $pre, undef, $post ) = $text =~ s/^(\s.)(.*?)(\s.)$/$2/;
$post ||= '';
return "$pre$rst_style$text$rst_style$post";
}
return $text;
},
};
}
sub new {
my ( $class, %options ) = @_;
my $self = bless {}, $class;
$self->{options} = \%options;
return $self;
}
# A Text::BibTeX::BibStyle hash has the following keys:
# bibtex A reference to a "bibtex" hash
# interp Array reference containing the interpreter
# stack Reference to array of evaluation stack
# symbols Reference to "symbols" hash
# warnings Array of warnings produced during execution
#
# "Symbols" hash has the following keys, each of which is a hash reference
# whose key is the symbol name and whose value is its definition:
# const Built-in constants
# field Reference to hash of field/value pairs for current entry
# entry_int Reference to hash of integer/value pairs for current entry
# entry_str Reference to hash of string/value pairs for current entry
# function Function defined in FUNCTION command or built-in function
# integer Integer defined in INTEGERS command
# string String defined in STRINGS command
#
# "Bibtex" hash has the following key/value pairs
# bibfiles Reference to array of bib file names
# bt_entry Reference to the current Text::BibTeX::Entry object
# bt_entries Reference to hash whose keys are bibtex keys and whose value
# is the corresponding Text::BibTeX::Entry for that key
# cite Cite key for the current entry
# cites Optional reference to array of keys of citations to format
# entries Reference to hash whose keys are bibtex keys and whose value
# is a reference to its entry hash
# format Reference to a format hash defined by an ENTRY command
# preamble Reference to array of @PREAMBLE items
#
# "Entry" hash has the following keys, each of which is a hash reference
# whose key is the symbol name and whose value is its definition:
# field Bibliography field from ENTRY command
# integer Entry integer from ENTRY command
# string Entry string from ENTRY command
#
# "Format" hash has the following keys, each of which is a reference to
# an array of names that can appear in a corresponding entry hash
# field Bibliography fields from ENTRY command
# integer Entry integer variables from ENTRY command
# string Entry string variables from ENTRY command
=item C<convert_format ($text, \%options)>
Method. Converts a LaTeX bibliography in $text into some other format
using the options specified by C<%options> and returns the result.
This method can also be used to convert a standard BibTeX output to
a different format.
Assuming that C<$text> contains a LaTeX bibliography (e.g., the
contents of a C<.bbl> file), the following option packages may be
useful for the options hash reference:
=over
=item C<$Text::BibTeX::BibStyle::HTML>
Produces HTML code to render the formatted bibliography. Exportable.
=item C<$Text::BibTeX::BibStyle::LATEX>
Outputs LaTeX code identical to bibtex (specifies (wrap => 1)). Exportable.
=item C<$Text::BibTeX::BibStyle::RST>
Produces reStructuredText code. Exportable.
=back
The following options are supported, if you want to write your own
translation package:
=over
=item C<character>
Reference to a subroutine to call for special characters. The
subroutine is called with the arguments C<($bst, $latex, [$unicode],
$char, [$accent])>, where C<$bst> is the Text::BibTeX::BibStyle
object, C<$latex> is the original latex for the special character,
C<$unicode> is the equivalent unicode character (if it exists), $char
is the special character(s), and C<$accent> is the latex accent code
to be applied (if specified). It should return the string to be
substituted.
=item C<command>
Reference to a subroutine to call for LaTeX commands. The subroutine
is called with the arguments C<($bst, $cmd, @args)>, where C<$bst> is
the Text::BibTeX::BibStyle object, C<$cmd> is the name of the LaTeX
command and C<@args> is the array of arguments (including optional
arguments) to the command. At a minimum, the subroutine should handle
the following commands: C<\begin{thebibliography}>,
C<\bibitem[label]{key}>, C<\cite{ref}>, C<\end{thebibliography}>,
C<\mbox{text}>, C<\newblock>. It should return the string to be
substituted.
=item C<delete_braces>
Boolean to delete from the output any braces that are not
backslash-quoted.
=item C<init>
Reference to a subroutine to call before processing the output. The
subroutine is called with the argument C<($bst)>, which is the
Text::BibTeX::BibStyle object.
=item C<math>
Reference to a subroutine to call for latex math. The subroutine is
called with the arguments C<($bst, $latex, $math)>, where C<$bst> is
the Text::BibTeX::BibStyle object, C<$latex> is the original latex and
C<$math> is the part that actually translates to math. It should
return the string to be substituted.
=item C<postprocess>
Reference to a subroutine to call to post-process the output. The
subroutine is called with the arguments C<($bst, $text)>, where
C<$bst> is the Text::BibTeX::BibStyle object and C<$text> contains the
text of the entire formatted bibliography. It should return the final
formatted bibliography.
=item C<prologue>
A string or reference to a subroutine to call to produce any
pre-bibliography definitions needed by the format.
=item C<style>
Reference to a subroutine to call for different font styles. The
subroutine is called with the arguments C<($bst, $latex, $style,
$text)>, where C<$bst> is the Text::BibTeX::BibStyle object, C<$latex>
is the original latex, C<$style> is one of C<rm>, C<em>, C<bf>, C<it>,
C<sl>, C<sf>, C<sc>, or C<tt> indicating the font style, and C<$text>
is the text to be output in that style. It should return the string
to be substituted.
=item C<substitute_newcommand>
Boolean to process and do substitutions for any C<\newcommand>
definitions in the output.
=item C<wrap>
Boolean to force the standard bibtex wrapping on the output.
=back
=cut
{ # Closure
my $Acc_char = qq([\'\`^\"~=.]);
my $Acc_let = "[uvHtcdb]";
my $Acc_sym =
q(\\\\(?:(?:a[ae]|A[AE]|copyright|dd?ag|[lL]|oe?|OE?|P|pounds|S|ss)\\b)|``|''|\?`|!`|~|---?);
my $Style = '\\\\(?:[er]m|bf|[it]t|s[lfc])\\b';
sub convert_format : method {
my ( $self, $text, $opts ) = @_;
$opts->{init}->($self) if $opts->{init};
$text = _substitute_newcommand($text) if $opts->{substitute_newcommand};
if ( $opts->{wrap} ) {
1 while ( $text =~ s/^(?=.{80})(.{1,79})(\s.*)/$1\n $2/m
|| $text =~ s/^(?=.{80})(.{80,}?)(\s.*)/$1\n $2/m );
}
if ( $opts->{prologue} ) {
my $prologue =
ref $opts->{prologue}
? $opts->{prologue}->($self)
: $opts->{prologue};
$text = "$prologue$text";
}
if ( $opts->{character} ) {
# Handle accents
$text =~ s/\\i\b/i/g;
$text =~ s/(\{ \\ ($Acc_char|$Acc_let\b) [ ]* ([a-zA-Z]+) [ ]*
(?:\}|\Z))/_character($self, $opts, $1, $3, $2)/exog;
$text =~ s/(\\ ($Acc_char|$Acc_let) [ ]* \{ [ ]* ([a-zA-Z]+) [ ]*
(?:\}|\Z))/_character($self, $opts, $1, $3, $2)/exog;
$text =~ s/($Acc_sym)/_character($self, $opts, $1, $1)/exog;
$text =~ s/(\\ ([\#\$\%&_]))/_character($self, $opts, $1, $2)/xge;
$text =~ s!(\\/)!_character($self, $opts, $1, '')!ge;
}
if ( $opts->{math} ) {
# Handle math mode
$text =~ s/((\$\$?)(.*?)\2)/$opts->{math}->($self, $1, $3)/sexg;
$text =~ s/(\\ \( (.*?) \\ \))/$opts->{math}->($self, $1, $2)/sexg;
$text =~ s/(\\ \[ (.*?) \\ \])/$opts->{math}->($self, $1, $2)/sexg;
}
if ( $opts->{style} ) {
# Handle text styles
1 while $text =~ s/(\{ $Style .*)/do {
my ($latex, $next) = _remove_matched_brace($1);
(my $text = $latex) =~ s!\{ ($Style) [ ]*(.*) \}$!$2!sx;
my $style = $1;
$style =~ m!([a-z]+)!;
$opts->{style}->($self, $latex, $1, $text) . $next;
}/sexg;
}
if ( $opts->{command} ) {
1 while $text =~ s/(\A|[^\\])\\([a-z]+)(.*)/do {
my ($pre, $cmd, $next) = ($1, $2, $3);
my @args;
while ($next =~ m!^[\{\[]!) {
if ($next =~ m!^\{!) {
my $arg;
($arg, $next) = _remove_matched_brace($next);
$arg =~ s!^\{ (.*) \}$!$1!sx;
push @args, $arg;
}
else {
$next =~ s!^\[ (.*?) \]!!sx;
push @args, $1;
}
}
$pre . $opts->{command}->($self, $cmd, @args) . $next;
}/exis;
}
if ( $opts->{delete_braces} ) {
# Note: need to do twice to handle {}
$text =~ s/(\A|.) ([{}])/$1 eq "\\" ? "$1$2" : $1/sexg;
$text =~ s/(\A|.) ([{}])/$1 eq "\\" ? "$1$2" : $1/sexg;
}
if ( $opts->{character} ) {
# Handle backslash-quoted braces
$text =~ s/(\\ ([{}]))/_character($self, $opts, $1, $2)/xge;
}
$text = $opts->{postprocess}->( $self, $text ) if $opts->{postprocess};
return $text;
}
=item C<execute [(\@bibfiles[, \@cites])]>
Method. Executes the current bibstyle interpreter on a set of cited
references passed in C<@cites> looking in a set of C<.bib> files
passed in C<@bibfiles>. If the C<@cites> argument is undefined, uses
all the references in all the bibfiles. The files in C<@bibfiles>
should be without the ".bib" extension. The search path for bibfiles
is taken from the C<BIBINPUTS> environment variables if it is defined.
The C<@bibfiles> argument is not needed if the bibstyle interpreter
does not contain a C<READ> command. Croaks if a bibstyle interpreter
has not been defined using either the C<read_bibstyle> or
C<replace_bibstyle> method.
=cut
{
# Closure for local variables
my %Commands = ( # Info is no. of arguments and subroutine reference
entry => [ 3, \&_command_entry ],
execute => [ 1, \&_command_execute ],
function => [ 2, \&_command_function ],
integers => [ 1, \&_command_variables ],
iterate => [ 1, \&_command_iterate ],
macro => [ 2, \&_command_macro ],
read => [ 0, \&_command_read ],
reverse => [ 1, \&_command_iterate ],
sort => [ 0, \&_command_sort ],
strings => [ 1, \&_command_variables ],
);
sub execute : method {
my ( $self, $bibfiles_ar, $rawbib, $cites_ar ) = @_;
croak
"No bibstyle interpreter has been defined: call read_bibstyle or replace_bibstyle first"
unless $self->{interp};
$self->{bibtex} = {
bibfiles => $bibfiles_ar,
rawbib => $rawbib,
bt_entry => undef,
bt_entries => {},
cite => undef,
cites => $cites_ar,
entries => {},
format => undef,
preamble => [],
};
Text::BibTeX::delete_all_macros();
my %cmd_count;
my ( $filename, $lineno );
my @interp = @{ $self->{interp} };
while (@interp) {
my $token = shift @interp;
if ( $token =~ /^\#line (\d+) (\S+)/ ) {
( $lineno, $filename ) = ( $1, $2 );
next;
}
croak "$filename, $lineno: Invalid argument" if ref($token);
my $lc_token = lc $token;
croak "$filename, $lineno: Unknown command '$token'"
unless my $command_ar = $Commands{$lc_token};
my ( $cmd, $cmd_f, $cmd_l ) = ( $token, $filename, $lineno );
$self->{lineno} = "$filename, $lineno";
# Get the arguments
my @args;
while ( @args < $command_ar->[0] ) {
my $token = shift @interp;
if ( $token =~ /^\#line (\d+) (\S+)/ ) {
( $lineno, $filename ) = ( $1, $2 );
next;
}
last unless ref($token);
push @args, $token;
}
croak
"$filename, $lineno: Insufficient arguments for command '$cmd' at line $cmd_l"
if @args < $command_ar->[0];
if ( ++$cmd_count{$lc_token} > 1
&& $lc_token =~ /^(entry|read)$/ )
{
$self->_warning("Duplicate '$token' command ignored");
next;
}
$command_ar->[1]->( $self, $cmd, $cmd_f, $cmd_l, \@args );
}
my @missing_cmds = grep !$cmd_count{$_}, qw(entry read);
$self->_warning(
sprintf(
"Need to have one %s command",
join ' and one ',
map( uc $_, @missing_cmds )
)
) if @missing_cmds && !$self->{options}{nowarn};
}
}
=item C<get_output [(\%options)]>
Method. Returns the output produced by C<write$> commands in the C<.bst>
file. The options are listed under the C<convert_format> method,
which it calls.
=cut
sub get_output : method {
my ( $self, $opts ) = @_;
my $out = join '', @{ $self->{output} };
$out = $self->convert_format( $out, $opts ) if $opts;
return $out;
}
=item C<num_warnings>
Method. Returns the number of warning messages generated during execution.
=cut
sub num_warnings : method {
my ($self) = @_;
return 0 + @{ $self->{warnings} };
}
=item C<read_bibstyle ($bibstyle)>
Method. Replaces the bibstyle interpreter with a new one obtained by
reading the file C<$bibstyle.bst>. The search path for the bibstyle
file is taken from the C<BSTINPUTS> environment variable if it is
defined.
=cut
sub read_bibstyle : method {
my ( $self, $bibstyle ) = @_;
# my $f = "$bibstyle.bst";
# my $path = $ENV{BSTINPUTS} || '.';
# my @path = split /:/, $path;
# my ($dir) = grep -f "$_/$f", @path;
# croak("Cannot find $f on path: $path") unless $dir;
# my $fullfile = "$dir/$f";
my $fullfile = "$bibstyle";
croak("Cannot find bst file $bibstyle") unless -e $bibstyle;
# Read the file
open BSTINPUTS, "$fullfile" or croak("$fullfile: $!");
my @bibstyle = <BSTINPUTS>;
close BSTINPUTS;
my $interp = join '', @bibstyle;
$self->replace_bibstyle( $interp, $fullfile );
}
=item C<replace_bibstyle ($string[, $filename])>
Method. Replaces the bibstyle interpreter by parsing C<$string>. The
optional C<$filename> argument is used for warning messages. Written
primarily for testing purposes; most users will call it only
indirectly through the C<read_bibstyle> method.
=cut
{ # Closure for private variables
my %BuiltIn = (
'>' => \&_function_arith,
'<' => \&_function_arith,
'=' => \&_function_eq,
'+' => \&_function_arith,
'-' => \&_function_arith,
'*' => \&_function_concat,
':=' => \&_function_assign,
'add.period$' => \&_function_add_period,
'call.type$' => \&_function_call_type,
'change.case$' => \&_function_change_case,
'chr.to.int$' => \&_function_chr_to_int,
'cite$' => \&_function_cite,
'duplicate$' => \&_function_duplicate,
'empty$' => \&_function_empty,
'format.name$' => \&_function_format_name,
'if$' => \&_function_if,
'int.to.chr$' => \&_function_int_to_chr,
'int.to.str$' => \&_function_int_to_str,
'missing$' => \&_function_missing,
'newline$' => \&_function_newline,
'num.names$' => \&_function_num_names,
'pop$' => sub { my ($self) = @_; $self->_pop; },
'preamble$' => \&_function_preamble,
'purify$' => \&_function_purify,
'quote$' => 1, # Handled as a constant symbol
'skip$' => sub { },
'stack$' => \&_function_stack,
'substring$' => \&_function_substring,
'swap$' => \&_function_swap,
'text.length$' => \&_function_text_length,
'text.prefix$' => \&_function_text_prefix,
'top$' => \&_function_top,
'type$' => \&_function_type,
'warning$' => \&_function_warning,
'while$' => \&_function_while,
'width$' => \&_function_width,
'write$' => \&_function_write,
);
# Here's where the actual parsing takes place
sub replace_bibstyle : method {
my ( $self, $interp, $filename ) = @_;
$filename ||= '<string>';
# Remove comments
$interp =~ s/(^|[^\\]) \% .*/$1/mgx;
my @interp = grep $_,
split( /(\s+)|([{}]|\".*?\"|\#line \d+ .*\n)/, $interp );
# Put '{' .. '}' pairs into array refs
my @stack;
my $nest = 0;
push @stack, [];
my $lineno = 1;
push @{ $stack[-1] }, "#line $lineno $filename";
foreach (@interp) {
if ( $_ =~ /^\s+$/ ) {
my $nl = y/\n//;
if ($nl) {
$lineno += $nl;
push @{ $stack[-1] }, "#line $lineno $filename";
}
}
elsif ( $_ eq '{' ) {
$nest++;
push @stack, [];
push @{ $stack[-1] }, "#line $lineno $filename";
}
elsif ( $_ eq '}' ) {
$nest--;
croak("$filename, $lineno: Unmatched '}'") if $nest < 0;
push @{ $stack[-2] }, pop(@stack);
}
else {
( $lineno, $filename ) = ( $1, $2 ) if /^\#line (\d+) (.*)/;
push @{ $stack[-1] }, $_;
}
}
if ( $nest > 0 ) {
# Find the error line number
my $errline = 1;
foreach ( reverse @{ $stack[ $nest - 1 ] } ) {
if (/^\#line (\d+)/) {
$errline = $1;
last;
}
}
croak("$filename, $errline: Unmatched '{'");
}
$self->{interp} = $stack[0];
$self->{output} = [];
$self->{stack} = [];
$self->{symbols} = {
const => { 'quote$' => '"""' },
entry_str => { 'sort.key$' => undef },
field => { crossref => undef },
function => { map( ( $_ => "'$_" ), keys %BuiltIn ) },
integer => {
'entry.max$' => 100,
'global.max$' => 1000,
},
};
$self->{warnings} = [];
}
=item C<warnings>
Method. Returns an array of the warning messages generated during execution.
=cut
sub warnings : method {
my ($self) = @_;
return @{ $self->{warnings} };
}
=back
=head1 ENVIRONMENT
The following environment variables are used:
=over
=item C<BIBINPUTS>
The search path for bibliography (.bib) files.
=item C<BSTINPUTS>
The search path for bibstyle (.bst) files.
=back
=head1 LIMITATIONS
The $Text::BibTeX::BibStyle::HTML output filter has the following
limitations:
=over
=item Math mode
The math mode interpretation depends upon using Text::ASCIIMathML to
convert to MathML. ASCIIMathML accepts most, but not all, LaTeX
constructs. In order to render correctly in some browsers, it will
need to use xhtml and put the appropriate MathML entity definitions in
the header.
=item latex2e symbols
Extended symbols defined by latex2e are not supported.
=back
=head1 COPYRIGHT & LICENSE
Copyright 2007 Mark Nodine, all rights reserved.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
################ Internal routines
# Checks a name to be define to be sure it is valid
# Arguments: name
# Returns: name
sub _check_name : method {
my ( $self, $name ) = @_;
my $where = $self->{lineno};
croak "$where: Illegal name '$name'"
unless $name =~ /^[^\"\#\%\'(),={}\s\d][^\"\#\%\'(),={}\s]*$/;
foreach my $sym (
qw(const field entry_int entry_str function
integer string)
)
{
croak "$where: Cannot redefine $sym '$name'"
if exists $self->{symbols}{$sym}{$name};
}
return $name;
}
{ # Closure for static variables
my $Arg_num;
my $Check_type_warnings;
# Checks the type of an argument
# Arguments: argument, type(s), token, true if first arg of function
# The types are a concatenation of
# i: integer
# q: quoted value (e.g., 'a)
# s: string
# x: expression (array ref)
sub _check_type : method {
my ( $self, $arg, $types, $token, $first_arg ) = @_;
$Arg_num = $first_arg ? 1 : $Arg_num + 1;
$Check_type_warnings = 0 if $first_arg;
$_ = $arg;
my $type = (
!defined $_ || /^\"/ ? 's'
: ref($_) ? 'x'
: /^\'/ ? 'q'
: /^-?\d+$/ ? 'i'
: croak("$self->{lineno}: value '$_' has unknown type")
);
$Check_type_warnings += $self->_warning(
sprintf "Argument $Arg_num of '$token' has wrong type (%s)",
$self->_format_token($_)
) unless $types =~ /$type/i;
}
# Returns the number of check_type warnings for this function
sub _check_type_warnings {
return $Check_type_warnings;
}
}
# All the _command routines are used to execute a command.
# Inputs: $self, command name, file name, line num, ref to array of arguments
sub _command_entry {
my ( $self, $cmd, $filename, $lineno, $args_ar ) = @_;
$self->{bibtex}{format} = {
field => [
'crossref',
map( $self->_check_name($_),
grep !/^\#line/,
@{ $args_ar->[0] } )
],
integer => [
map( $self->_check_name($_),
grep !/^\#line/,
@{ $args_ar->[1] } )
],
string => [
'sort.key$',
map( $self->_check_name($_),
grep !/^\#line/,
@{ $args_ar->[2] } )
]
};
$self->{symbols}{field} =
{ map( ( $_ => undef ), @{ $self->{bibtex}{format}{field} } ) };
$self->{symbols}{entry_int} =
{ map( ( $_ => "-0" ), @{ $self->{bibtex}{format}{integer} } ) };
$self->{symbols}{entry_str} =
{ map( ( $_ => undef ), @{ $self->{bibtex}{format}{string} } ) };
1;
}
sub _command_execute {
my ( $self, $cmd, $filename, $lineno, $args_ar ) = @_;
# print "_command_execute $cmd, $filename, $lineno, $args_ar \n";
my @symbols = grep !/^\#line/, @{ $args_ar->[0] };
croak
"$filename, $lineno: first argument to '$cmd' must contain exactly one name"
unless @symbols == 1;
my $func_name = $symbols[0];
my $function = $self->{symbols}{function}{$func_name};
croak
"$filename, $lineno: Function '$func_name' has not been defined"
unless $function;
$self->{stack} = []; # Start with a new stack
_evaluate( $self, $function );
}
sub _command_function {
my ( $self, $cmd, $filename, $lineno, $args_ar ) = @_;
my @symbols = grep !/^\#line/, @{ $args_ar->[0] };
croak
"$filename, $lineno: first argument to '$cmd' must contain exactly one name"
unless @symbols == 1;
my $func_name = $symbols[0];
$self->_check_name($func_name);
$self->{symbols}{function}{$func_name} = $args_ar->[1];
}
sub _command_iterate {
my ( $self, $cmd, $filename, $lineno, $args_ar ) = @_;
my @entries = @{ $self->{bibtex}{cites} };
@entries = reverse @entries if $cmd =~ /reverse/i;
my @symbols = grep !/^\#line/, @{ $args_ar->[0] };
croak
"$filename, $lineno: first argument to '$cmd' must contain exactly one name"
unless @symbols == 1;
my $func_name = $symbols[0];
my $function = $self->{symbols}{function}{$func_name};
croak
"$filename, $lineno: Function '$func_name' has not been defined"
unless $function;
foreach my $cite (@entries) {
$self->{stack} = []; # Start with a new stack
# Initialize the cite, bt_entry, and entry references
$self->{bibtex}{cite} = $cite;
$self->{bibtex}{bt_entry} = $self->{bibtex}{bt_entries}{$cite};
my $entry = $self->{bibtex}{entries}{$cite};
$self->{symbols}{field} = $entry->{field};
$self->{symbols}{entry_int} = $entry->{integer};
$self->{symbols}{entry_str} = $entry->{string};
_evaluate( $self, $function );
}
}
sub _command_macro {
my ( $self, $cmd, $filename, $lineno, $args_ar ) = @_;
my @symbols = grep !/^\#line/, @{ $args_ar->[0] };
croak