6906e636510fc98f97048427b89006615a2032c2
[p5sagit/p5-mst-13.2.git] / lib / Pod / Text.pm
1 package Pod::Text;
2
3 =head1 NAME
4
5 Pod::Text - convert POD data to formatted ASCII text
6
7 =head1 SYNOPSIS
8
9         use Pod::Text;
10
11         pod2text("perlfunc.pod");
12
13 Also:
14
15         pod2text < input.pod
16
17 =head1 DESCRIPTION
18
19 Pod::Text is a module that can convert documentation in the POD format (such
20 as can be found throughout the Perl distribution) into formatted ASCII.
21 Termcap is optionally supported for boldface/underline, and can enabled via
22 C<$Pod::Text::termcap=1>. If termcap has not been enabled, then backspaces
23 will be used to simulate bold and underlined text.
24
25 A separate F<pod2text> program is included that is primarily a wrapper for
26 Pod::Text.
27
28 The single function C<pod2text()> can take one or two arguments. The first
29 should be the name of a file to read the pod from, or "E<lt>&STDIN" to read from
30 STDIN. A second argument, if provided, should be a filehandle glob where
31 output should be sent.
32
33 =head1 AUTHOR
34
35 Tom Christiansen E<lt>F<tchrist@mox.perl.com>E<gt>
36
37 =head1 TODO
38
39 Cleanup work. The input and output locations need to be more flexible,
40 termcap shouldn't be a global variable, and the terminal speed needs to
41 be properly calculated.
42
43 =cut
44
45 use Term::Cap;
46 require Exporter;
47 @ISA = Exporter;
48 @EXPORT = qw(pod2text);
49
50 use vars qw($VERSION);
51 $VERSION = "1.0202";
52
53 $termcap=0;
54
55 #$use_format=1;
56
57 $UNDL = "\x1b[4m";
58 $INV = "\x1b[7m";
59 $BOLD = "\x1b[1m";
60 $NORM = "\x1b[0m";
61
62 sub pod2text {
63 local($file,*OUTPUT) = @_;
64 *OUTPUT = *STDOUT if @_<2;
65
66 if($termcap and !$setuptermcap) {
67         $setuptermcap=1;
68
69     my($term) = Tgetent Term::Cap { TERM => undef, OSPEED => 9600 };
70     $UNDL = $term->{'_us'};
71     $INV = $term->{'_mr'};
72     $BOLD = $term->{'_md'};
73     $NORM = $term->{'_me'};
74 }
75
76 $SCREEN = ($_[0] =~ /^-(\d+)/ && (shift, $1))
77        ||  $ENV{COLUMNS}
78        || ($ENV{TERMCAP} =~ /co#(\d+)/)[0]
79        || (`stty -a 2>/dev/null` =~ /(\d+) columns/)[0]
80        || 72;
81
82 $/ = "";
83
84 $FANCY = 0;
85
86 $cutting = 1;
87 $DEF_INDENT = 4;
88 $indent = $DEF_INDENT;
89 $needspace = 0;
90 $begun = "";
91
92 open(IN, $file) || die "Couldn't open $file: $!";
93
94 POD_DIRECTIVE: while (<IN>) {
95     if ($cutting) {
96         next unless /^=/;
97         $cutting = 0;
98     }
99     if ($begun) {
100         if (/^=end\s+$begun/) {
101              $begun = "";
102         }
103         elsif ($begun eq "text") {
104             print OUTPUT $_;
105         }
106         next;
107     }
108     1 while s{^(.*?)(\t+)(.*)$}{
109         $1
110         . (' ' x (length($2) * 8 - length($1) % 8))
111         . $3
112     }me;
113     # Translate verbatim paragraph
114     if (/^\s/) {
115         output($_);
116         next;
117     }
118
119     if (/^=for\s+(\S+)\s*(.*)/s) {
120         if ($1 eq "text") {
121             print OUTPUT $2,"";
122         } else {
123             # ignore unknown for
124         }
125         next;
126     }
127     elsif (/^=begin\s+(\S+)\s*(.*)/s) {
128         $begun = $1;
129         if ($1 eq "text") {
130             print OUTPUT $2."";
131         }
132         next;
133     }
134
135 sub prepare_for_output {
136
137     s/\s*$/\n/;
138     &init_noremap;
139
140     # need to hide E<> first; they're processed in clear_noremap
141     s/(E<[^<>]+>)/noremap($1)/ge;
142     $maxnest = 10;
143     while ($maxnest-- && /[A-Z]</) {
144         unless ($FANCY) {
145             s/C<(.*?)>/`$1'/sg;
146         } else {
147             s/C<(.*?)>/noremap("E<lchevron>${1}E<rchevron>")/sge;
148         }
149         # s/[IF]<(.*?)>/italic($1)/ge;
150         s/I<(.*?)>/*$1*/sg;
151         # s/[CB]<(.*?)>/bold($1)/ge;
152         s/X<.*?>//sg;
153         # LREF: a manpage(3f)
154         s:L<([a-zA-Z][^\s\/]+)(\([^\)]+\))?>:the $1$2 manpage:g;
155         # LREF: an =item on another manpage
156         s{
157             L<
158                 ([^/]+)
159                 /
160                 (
161                     [:\w]+
162                     (\(\))?
163                 )
164             >
165         } {the "$2" entry in the $1 manpage}gx;
166
167         # LREF: an =item on this manpage
168         s{
169            ((?:
170             L<
171                 /
172                 (
173                     [:\w]+
174                     (\(\))?
175                 )
176             >
177             (,?\s+(and\s+)?)?
178           )+)
179         } { internal_lrefs($1) }gex;
180
181         # LREF: a =head2 (head1?), maybe on a manpage, maybe right here
182         # the "func" can disambiguate
183         s{
184             L<
185                 (?:
186                     ([a-zA-Z]\S+?) / 
187                 )?
188                 "?(.*?)"?
189             >
190         }{
191             do {
192                 $1      # if no $1, assume it means on this page.
193                     ?  "the section on \"$2\" in the $1 manpage"
194                     :  "the section on \"$2\""
195             }
196         }sgex;
197
198         s/[A-Z]<(.*?)>/$1/sg;
199     }
200     clear_noremap(1);
201 }
202
203     &prepare_for_output;
204
205     if (s/^=//) {
206         # $needspace = 0;               # Assume this.
207         # s/\n/ /g;
208         ($Cmd, $_) = split(' ', $_, 2);
209         # clear_noremap(1);
210         if ($Cmd eq 'cut') {
211             $cutting = 1;
212         }
213         elsif ($Cmd eq 'pod') {
214             $cutting = 0;
215         }
216         elsif ($Cmd eq 'head1') {
217             makespace();
218             print OUTPUT;
219             # print OUTPUT uc($_);
220         }
221         elsif ($Cmd eq 'head2') {
222             makespace();
223             # s/(\w+)/\u\L$1/g;
224             #print ' ' x $DEF_INDENT, $_;
225             # print "\xA7";
226             s/(\w)/\xA7 $1/ if $FANCY;
227             print OUTPUT ' ' x ($DEF_INDENT/2), $_, "\n";
228         }
229         elsif ($Cmd eq 'over') {
230             push(@indent,$indent);
231             $indent += ($_ + 0) || $DEF_INDENT;
232         }
233         elsif ($Cmd eq 'back') {
234             $indent = pop(@indent);
235             warn "Unmatched =back\n" unless defined $indent;
236             $needspace = 1;
237         }
238         elsif ($Cmd eq 'item') {
239             makespace();
240             # s/\A(\s*)\*/$1\xb7/ if $FANCY;
241             # s/^(\s*\*\s+)/$1 /;
242             {
243                 if (length() + 3 < $indent) {
244                     my $paratag = $_;
245                     $_ = <IN>;
246                     if (/^=/) {  # tricked!
247                         local($indent) = $indent[$#index - 1] || $DEF_INDENT;
248                         output($paratag);
249                         redo POD_DIRECTIVE;
250                     }
251                     &prepare_for_output;
252                     IP_output($paratag, $_);
253                 } else {
254                     local($indent) = $indent[$#index - 1] || $DEF_INDENT;
255                     output($_);
256                 }
257             }
258         }
259         else {
260             warn "Unrecognized directive: $Cmd\n";
261         }
262     }
263     else {
264         # clear_noremap(1);
265         makespace();
266         output($_, 1);
267     }
268 }
269
270 close(IN);
271
272 }
273
274 #########################################################################
275
276 sub makespace {
277     if ($needspace) {
278         print OUTPUT "\n";
279         $needspace = 0;
280     }
281 }
282
283 sub bold {
284     my $line = shift;
285     return $line if $use_format;
286     if($termcap) {
287         $line = "$BOLD$line$NORM";
288     } else {
289             $line =~ s/(.)/$1\b$1/g;
290         }
291 #    $line = "$BOLD$line$NORM" if $ansify;
292     return $line;
293 }
294
295 sub italic {
296     my $line = shift;
297     return $line if $use_format;
298     if($termcap) {
299         $line = "$UNDL$line$NORM";
300     } else {
301             $line =~ s/(.)/$1\b_/g;
302     }
303 #    $line = "$UNDL$line$NORM" if $ansify;
304     return $line;
305 }
306
307 # Fill a paragraph including underlined and overstricken chars.
308 # It's not perfect for words longer than the margin, and it's probably
309 # slow, but it works.
310 sub fill {
311     local $_ = shift;
312     my $par = "";
313     my $indent_space = " " x $indent;
314     my $marg = $SCREEN-$indent;
315     my $line = $indent_space;
316     my $line_length;
317     foreach (split) {
318         my $word_length = length;
319         $word_length -= 2 while /\010/g;  # Subtract backspaces
320
321         if ($line_length + $word_length > $marg) {
322             $par .= $line . "\n";
323             $line= $indent_space . $_;
324             $line_length = $word_length;
325         }
326         else {
327             if ($line_length) {
328                 $line_length++;
329                 $line .= " ";
330             }
331             $line_length += $word_length;
332             $line .= $_;
333         }
334     }
335     $par .= "$line\n" if $line;
336     $par .= "\n";
337     return $par;
338 }
339
340 sub IP_output {
341     local($tag, $_) = @_;
342     local($tag_indent) = $indent[$#index - 1] || $DEF_INDENT;
343     $tag_cols = $SCREEN - $tag_indent;
344     $cols = $SCREEN - $indent;
345     $tag =~ s/\s*$//;
346     s/\s+/ /g;
347     s/^ //;
348     $str = "format OUTPUT = \n"
349         . (" " x ($tag_indent))
350         . '@' . ('<' x ($indent - $tag_indent - 1))
351         . "^" .  ("<" x ($cols - 1)) . "\n"
352         . '$tag, $_'
353         . "\n~~"
354         . (" " x ($indent-2))
355         . "^" .  ("<" x ($cols - 5)) . "\n"
356         . '$_' . "\n\n.\n1";
357     #warn $str; warn "tag is $tag, _ is $_";
358     eval $str || die;
359     write OUTPUT;
360 }
361
362 sub output {
363     local($_, $reformat) = @_;
364     if ($reformat) {
365         $cols = $SCREEN - $indent;
366         s/\s+/ /g;
367         s/^ //;
368         $str = "format OUTPUT = \n~~"
369             . (" " x ($indent-2))
370             . "^" .  ("<" x ($cols - 5)) . "\n"
371             . '$_' . "\n\n.\n1";
372         eval $str || die;
373         write OUTPUT;
374     } else {
375         s/^/' ' x $indent/gem;
376         s/^\s+\n$/\n/gm;
377         print OUTPUT;
378     }
379 }
380
381 sub noremap {
382     local($thing_to_hide) = shift;
383     $thing_to_hide =~ tr/\000-\177/\200-\377/;
384     return $thing_to_hide;
385 }
386
387 sub init_noremap {
388     die "unmatched init" if $mapready++;
389     #mask off high bit characters in input stream
390     s/([\200-\377])/"E<".ord($1).">"/ge;
391 }
392
393 sub clear_noremap {
394     my $ready_to_print = $_[0];
395     die "unmatched clear" unless $mapready--;
396     tr/\200-\377/\000-\177/;
397     # now for the E<>s, which have been hidden until now
398     # otherwise the interative \w<> processing would have
399     # been hosed by the E<gt>
400     s {
401             E<
402             (
403                 ( \d+ )
404                 | ( [A-Za-z]+ )
405             )
406             >   
407     } {
408          do {
409                 defined $2
410                 ? chr($2)
411                 :
412              defined $HTML_Escapes{$3}
413                 ? do { $HTML_Escapes{$3} }
414                 : do {
415                     warn "Unknown escape: E<$1> in $_";
416                     "E<$1>";
417                 }
418          }
419     }egx if $ready_to_print;
420 }
421
422 sub internal_lrefs {
423     local($_) = shift;
424     s{L</([^>]+)>}{$1}g;
425     my(@items) = split( /(?:,?\s+(?:and\s+)?)/ );
426     my $retstr = "the ";
427     my $i;
428     for ($i = 0; $i <= $#items; $i++) {
429         $retstr .= "C<$items[$i]>";
430         $retstr .= ", " if @items > 2 && $i != $#items;
431         $retstr .= " and " if $i+2 == @items;
432     }
433
434     $retstr .= " entr" . ( @items > 1  ? "ies" : "y" )
435             .  " elsewhere in this document ";
436
437     return $retstr;
438
439 }
440
441 BEGIN {
442
443 %HTML_Escapes = (
444     'amp'       =>      '&',    #   ampersand
445     'lt'        =>      '<',    #   left chevron, less-than
446     'gt'        =>      '>',    #   right chevron, greater-than
447     'quot'      =>      '"',    #   double quote
448
449     "Aacute"    =>      "\xC1", #   capital A, acute accent
450     "aacute"    =>      "\xE1", #   small a, acute accent
451     "Acirc"     =>      "\xC2", #   capital A, circumflex accent
452     "acirc"     =>      "\xE2", #   small a, circumflex accent
453     "AElig"     =>      "\xC6", #   capital AE diphthong (ligature)
454     "aelig"     =>      "\xE6", #   small ae diphthong (ligature)
455     "Agrave"    =>      "\xC0", #   capital A, grave accent
456     "agrave"    =>      "\xE0", #   small a, grave accent
457     "Aring"     =>      "\xC5", #   capital A, ring
458     "aring"     =>      "\xE5", #   small a, ring
459     "Atilde"    =>      "\xC3", #   capital A, tilde
460     "atilde"    =>      "\xE3", #   small a, tilde
461     "Auml"      =>      "\xC4", #   capital A, dieresis or umlaut mark
462     "auml"      =>      "\xE4", #   small a, dieresis or umlaut mark
463     "Ccedil"    =>      "\xC7", #   capital C, cedilla
464     "ccedil"    =>      "\xE7", #   small c, cedilla
465     "Eacute"    =>      "\xC9", #   capital E, acute accent
466     "eacute"    =>      "\xE9", #   small e, acute accent
467     "Ecirc"     =>      "\xCA", #   capital E, circumflex accent
468     "ecirc"     =>      "\xEA", #   small e, circumflex accent
469     "Egrave"    =>      "\xC8", #   capital E, grave accent
470     "egrave"    =>      "\xE8", #   small e, grave accent
471     "ETH"       =>      "\xD0", #   capital Eth, Icelandic
472     "eth"       =>      "\xF0", #   small eth, Icelandic
473     "Euml"      =>      "\xCB", #   capital E, dieresis or umlaut mark
474     "euml"      =>      "\xEB", #   small e, dieresis or umlaut mark
475     "Iacute"    =>      "\xCD", #   capital I, acute accent
476     "iacute"    =>      "\xED", #   small i, acute accent
477     "Icirc"     =>      "\xCE", #   capital I, circumflex accent
478     "icirc"     =>      "\xEE", #   small i, circumflex accent
479     "Igrave"    =>      "\xCD", #   capital I, grave accent
480     "igrave"    =>      "\xED", #   small i, grave accent
481     "Iuml"      =>      "\xCF", #   capital I, dieresis or umlaut mark
482     "iuml"      =>      "\xEF", #   small i, dieresis or umlaut mark
483     "Ntilde"    =>      "\xD1",         #   capital N, tilde
484     "ntilde"    =>      "\xF1",         #   small n, tilde
485     "Oacute"    =>      "\xD3", #   capital O, acute accent
486     "oacute"    =>      "\xF3", #   small o, acute accent
487     "Ocirc"     =>      "\xD4", #   capital O, circumflex accent
488     "ocirc"     =>      "\xF4", #   small o, circumflex accent
489     "Ograve"    =>      "\xD2", #   capital O, grave accent
490     "ograve"    =>      "\xF2", #   small o, grave accent
491     "Oslash"    =>      "\xD8", #   capital O, slash
492     "oslash"    =>      "\xF8", #   small o, slash
493     "Otilde"    =>      "\xD5", #   capital O, tilde
494     "otilde"    =>      "\xF5", #   small o, tilde
495     "Ouml"      =>      "\xD6", #   capital O, dieresis or umlaut mark
496     "ouml"      =>      "\xF6", #   small o, dieresis or umlaut mark
497     "szlig"     =>      "\xDF",         #   small sharp s, German (sz ligature)
498     "THORN"     =>      "\xDE", #   capital THORN, Icelandic
499     "thorn"     =>      "\xFE", #   small thorn, Icelandic
500     "Uacute"    =>      "\xDA", #   capital U, acute accent
501     "uacute"    =>      "\xFA", #   small u, acute accent
502     "Ucirc"     =>      "\xDB", #   capital U, circumflex accent
503     "ucirc"     =>      "\xFB", #   small u, circumflex accent
504     "Ugrave"    =>      "\xD9", #   capital U, grave accent
505     "ugrave"    =>      "\xF9", #   small u, grave accent
506     "Uuml"      =>      "\xDC", #   capital U, dieresis or umlaut mark
507     "uuml"      =>      "\xFC", #   small u, dieresis or umlaut mark
508     "Yacute"    =>      "\xDD", #   capital Y, acute accent
509     "yacute"    =>      "\xFD", #   small y, acute accent
510     "yuml"      =>      "\xFF", #   small y, dieresis or umlaut mark
511
512     "lchevron"  =>      "\xAB", #   left chevron (double less than)
513     "rchevron"  =>      "\xBB", #   right chevron (double greater than)
514 );
515 }
516
517 1;