3d0b55b32f999ab6afb73126f60535b101ef2cfe
[p5sagit/p5-mst-13.2.git] / pod / pod2latex.PL
1 #!/usr/local/bin/perl
2
3 use Config;
4 use File::Basename qw(&basename &dirname);
5
6 # List explicitly here the variables you want Configure to
7 # generate.  Metaconfig only looks for shell variables, so you
8 # have to mention them as if they were shell variables, not
9 # %Config entries.  Thus you write
10 #  $startperl
11 # to ensure Configure will look for $Config{startperl}.
12
13 # This forces PL files to create target in same directory as PL file.
14 # This is so that make depend always knows where to find PL derivatives.
15 chdir dirname($0);
16 $file = basename($0, '.PL');
17 $file .= '.com' if $^O eq 'VMS';
18
19 open OUT,">$file" or die "Can't create $file: $!";
20
21 print "Extracting $file (with variable substitutions)\n";
22
23 # In this section, perl variables will be expanded during extraction.
24 # You can use $Config{...} to use Configure variables.
25
26 print OUT <<"!GROK!THIS!";
27 $Config{startperl}
28     eval 'exec $Config{perlpath} -S \$0 \${1+"\$@"}'
29         if \$running_under_some_shell;
30 !GROK!THIS!
31
32 # In the following, perl variables are not expanded during extraction.
33
34 print OUT <<'!NO!SUBS!';
35 #
36 # pod2latex, version 1.1
37 # by Taro Kawagish (kawagish@imslab.co.jp),  Jan 11, 1995.
38 #
39 # pod2latex filters Perl pod documents to LaTeX documents.
40 #
41 # What pod2latex does:
42 # 1. Pod file 'perl_doc_entry.pod' is filtered to 'perl_doc_entry.tex'.
43 # 2. Indented paragraphs are translated into
44 #    '\begin{verbatim} ... \end{verbatim}'.
45 # 3. '=head1 heading' command is translated into '\section{heading}'
46 # 4. '=head2 heading' command is translated into '\subsection*{heading}'
47 # 5. '=over N' command is translated into
48 #        '\begin{itemize}'      if following =item starts with *,
49 #        '\begin{enumerate}'    if following =item starts with 1.,
50 #        '\begin{description}'  if else.
51 #      (indentation level N is ignored.)
52 # 6. '=item * heading' command is translated into '\item heading',
53 #    '=item 1. heading' command is translated into '\item heading',
54 #    '=item heading' command(other) is translated into '\item[heading]'.
55 # 7. '=back' command is translated into
56 #        '\end{itemize}'        if started with '\begin{itemize}',
57 #        '\end{enumerate}'      if started with '\begin{enumerate}',
58 #        '\end{description}'    if started with '\begin{description}'.
59 # 8. other paragraphs are translated into strings with TeX special characters
60 #    escaped.
61 # 9. In heading text, and other paragraphs, the following translation of pod
62 #    quotes are done, and then TeX special characters are escaped after that.
63 #      I<text> to {\em text\/},
64 #      B<text> to {\bf text},
65 #      S<text> to text1,
66 #        where text1 is a string with blank characters replaced with ~,
67 #      C<text> to {\tt text2},
68 #        where text2 is a string with TeX special characters escaped to
69 #        obtain a literal printout,
70 #      E<text> (HTML escape) to TeX escaped string,
71 #      L<text> to referencing string as is done by pod2man,
72 #      F<file> to {\em file\/},
73 #      Z<> to a null string,
74 # 10. those headings are indexed:
75 #       '=head1 heading'   =>  \section{heading}\index{heading}
76 #       '=head2 heading'   =>  \subsection*{heading}\index{heading}
77 #                 only when heading does not match frequent patterns such as
78 #                 DESCRIPTION, DIAGNOSTICS,...
79 #       '=item heading'   =>  \item{heading}\index{heading}
80 #
81 # Usage:
82 #     pod2latex perl_doc_entry.pod
83 # this will write to a file 'perl_doc_entry.tex'.
84 #
85 # To LaTeX:
86 # The following commands need to be defined in the preamble of the LaTeX
87 # document:
88 # \def\C++{{\rm C\kern-.05em\raise.3ex\hbox{\footnotesize ++}}}
89 # \def\underscore{\leavevmode\kern.04em\vbox{\hrule width 0.4em height 0.3pt}}
90 # and \parindent should be set zero:
91 # \setlength{\parindent}{0pt}
92 #
93 # Note:
94 # This script was written modifing pod2man.
95 #
96 # Bug:
97 # If HTML escapes E<text> other than E<amp>,E<lt>,E<gt>,E<quot> are used
98 # in C<>, translation will produce wrong character strings.
99 # Translation of HTML escapes of various European accents might be wrong.
100
101
102 $/ = "";                        # record separator is blank lines
103 # TeX special characters.
104 ##$tt_ables = "!@*()-=+|;:'\"`,./?<>";
105 $backslash_escapables = "#\$%&{}_";
106 $backslash_escapables2 = "#\$%&{}";     # except _
107 ##$nonverbables = "^\\~";
108 ##$bracketesc = "[]";
109 ##@tex_verb_fences = unpack("aaaaaaaaa","|#@!*+?:;");
110
111 @head1_freq_patterns            # =head1 patterns which need not be index'ed
112     = ("AUTHOR","Author","BUGS","DATE","DESCRIPTION","DIAGNOSTICS",
113        "ENVIRONMENT","EXAMPLES","FILES","INTRODUCTION","NAME","NOTE",
114        "SEE ALSO","SYNOPSIS","WARNING");
115
116 $indent = 0;
117
118 # parse the pods, produce LaTeX.
119
120 open(POD,"<$ARGV[0]") || die "cant open $ARGV[0]";
121 ($pod=$ARGV[0]) =~ s/\.pod$//;
122 open(LATEX,">$pod.tex");
123 &do_hdr();
124
125 $cutting = 1;
126 $begun = "";
127 while (<POD>) {
128     if ($cutting) {
129         next unless /^=/;
130         $cutting = 0;
131     }
132     if ($begun) {
133        if (/^=end\s+$begun/) {
134            $begun = "";
135        }
136        elsif ($begun =~ /^(tex|latex)$/) {
137            print LATEX $_;
138        }
139        next;
140     }
141     chop;
142     length || (print LATEX  "\n") && next;
143
144     # translate indented lines as a verabatim paragraph
145     if (/^\s/) {
146         @lines = split(/\n/);
147         print LATEX  "\\begin{verbatim}\n";
148         for (@lines) {
149             1 while s
150                 {^( [^\t]* ) \t ( \t* ) }
151                 { $1 . ' ' x (8 - (length($1)%8) + 8*(length($2))) }ex;
152             print LATEX  $_,"\n";
153         }
154         print LATEX  "\\end{verbatim}\n";
155         next;
156     }
157
158     if (/^=for\s+(\S+)\s*/s) {
159         if ($1 eq "tex" or $1 eq "latex") {
160             print LATEX $',"\n";
161         } else {
162             # ignore unknown for
163         }
164         next;
165     }
166     elsif (/^=begin\s+(\S+)\s*/s) {
167         $begun = $1;
168         if ($1 eq "tex" or $1 eq "latex") {
169             print LATEX $'."\n";
170         }
171         next;
172     }
173
174     # preserve '=item' line with pod quotes as they are.
175     if (/^=item/) {
176         ($bareitem = $_) =~ s/^=item\s*//;
177     }
178
179     # check for things that'll hosed our noremap scheme; affects $_
180     &init_noremap();
181
182     # expand strings "func()" as pod quotes.
183     if (!/^=item/) {
184         # first hide pod escapes.
185         # escaped strings are mapped into the ones with the MSB's on.
186         s/([A-Z]<[^<>]*>)/noremap($1)/ge;
187
188         # func() is a reference to a perl function
189         s{\b([:\w]+\(\))}{I<$1>}g;
190         # func(n) is a reference to a man page
191         s{(\w+)(\([^\s,\051]+\))}{I<$1>$2}g;
192         # convert simple variable references
193 #       s/([\$\@%][\w:]+)/C<$1>/g;
194 #       s/\$[\w:]+\[[0-9]+\]/C<$&>/g;
195
196         if (m{ ([\-\w]+\([^\051]*?[\@\$,][^\051]*?\))
197                }x && $` !~ /([LCI]<[^<>]*|-)$/ && !/^=\w/)
198         {
199             warn "``$1'' should be a [LCI]<$1> ref";
200         }
201         while (/(-[a-zA-Z])\b/g && $` !~ /[\w\-]$/) {
202             warn "``$1'' should be [CB]<$1> ref";
203         }
204
205         # put back pod quotes so we get the inside of <> processed;
206         $_ = &clear_noremap($_);
207     }
208
209
210     # process TeX special characters
211
212     # First hide HTML quotes E<> since they can be included in C<>.
213     s/(E<[^<>]+>)/noremap($1)/ge;
214
215     # Then hide C<> type literal quotes.
216     # String inside of C<> will later be expanded into {\tt ..} strings
217     # with TeX special characters escaped as needed.
218     s/(C<[^<>]*>)/&noremap($1)/ge;
219
220     # Next escape TeX special characters including other pod quotes B< >,...
221     #
222     # NOTE: s/re/&func($str)/e evaluates $str just once in perl5.
223     # (in perl4 evaluation takes place twice before getting passed to func().)
224
225     # - hyphen => ---
226     s/(\S+)(\s+)-+(\s+)(\S+)/"$1".&noremap(" --- ")."$4"/ge;
227     # '-', '--', "-"  =>  '{\tt -}', '{\tt --}', "{\tt -}"
228 ##    s/("|')(\s*)(-+)(\s*)\1/&noremap("$1$2\{\\tt $3\}$4$1")/ge;
229 ## changed Wed Jan 25 15:26:39 JST 1995
230     # '-', '--', "-"  =>  '$-$', '$--$', "$-$"
231     s/(\s+)(['"])(-+)([^'"\-]*)\2(\s+|[,.])/"$1$2".&noremap("\$$3\$")."$4$2$5"/ge;
232     s/(\s+)(['"])([^'"\-]*)(-+)(\s*)\2(\s+|[,.])/"$1$2$3".&noremap("\$$4\$")."$5$2$6"/ge;
233     # (--|-)  =>  ($--$|$-$)
234     s/(\s+)\((-+)([=@%\$\+\\\|\w]*)(-*)([=@%\$\+\\\|\w]*)\)(\s+|[,.])/"$1\(".&noremap("\$$2\$")."$3".&noremap("\$$4\$")."$5\)$6"/ge;
235     # numeral -  =>  $-$
236     s/(\(|[0-9]+|\s+)-(\s*\(?\s*[0-9]+)/&noremap("$1\$-\$$2")/ge;
237     # -- in quotes  =>  two separate -
238     s/B<([^<>]*)--([^<>]*)>/&noremap("B<$1\{\\tt --\}$2>")/ge;
239
240     # backslash escapable characters except _.
241     s/([$backslash_escapables2])/&noremap("\\$1")/ge;
242     s/_/&noremap("\\underscore{}")/ge;          # a litle thicker than \_.
243     # quote TeX special characters |, ^, ~, \.
244     s/\|/&noremap("\$|\$")/ge;
245     s/\^/&noremap("\$\\hat{\\hspace{0.4em}}\$")/ge;
246     s/\~/&noremap("\$\\tilde{\\hspace{0.4em}}\$")/ge;
247     s/\\/&noremap("\$\\backslash{}\$")/ge;
248     # quote [ and ] to be used in \item[]
249     s/([\[\]])/&noremap("{\\tt $1}")/ge;
250     # characters need to be treated differently in TeX
251     # keep * if an item heading
252     s/^(=item[ \t]+)[*]((.|\n)*)/"$1" . &noremap("*") . "$2"/ge;
253     s/[*]/&noremap("\$\\ast\$")/ge;     # other *
254
255     # hide other pod quotes.
256     s/([ABD-Z]<[^<>]*>)/&noremap($1)/ge;
257
258     # escape < and > as math strings,
259     # now that we are done with hiding pod <> quotes.
260     s/</&noremap("\$<\$")/ge;
261     s/>/&noremap("\$>\$")/ge;
262
263     # put it back so we get the <> processed again;
264     $_ = &clear_noremap($_);
265
266
267     # Expand pod quotes recursively:
268     # (1) type face directives [BIFS]<[^<>]*> to appropriate TeX commands,
269     # (2) L<[^<>]*> to reference strings,
270     # (3) C<[^<>]*> to TeX literal quotes,
271     # (4) HTML quotes E<> inside of C<> quotes.
272
273     # Hide E<> again since they can be included in C<>.
274     s/(E<[^<>]+>)/noremap($1)/ge;
275
276     $maxnest = 10;
277     while ($maxnest-- && /[A-Z]</) {
278
279         # bold and italic quotes
280         s/B<([^<>]*)>/"{\\bf $1}"/eg;
281         s#I<([^<>]*)>#"{\\em $1\\/}"#eg;
282
283         # files and filelike refs in italics
284         s#F<([^<>]*)>#"{\\em $1\\/}"#eg;
285
286         # no break quote -- usually we want C<> for this
287         s/S<([^<>]*)>/&nobreak($1)/eg;
288
289         # LREF: a manpage(3f)
290         s:L<([a-zA-Z][^\s\/]+)(\([^\)]+\))?>:the {\\em $1\\/}$2 manpage:g;
291
292         # LREF: an =item on another manpage
293         s{
294             L<([^/]+)/([:\w]+(\(\))?)>
295         } {the C<$2> entry in the I<$1> manpage}gx;
296
297         # LREF: an =item on this manpage
298         s{
299            ((?:L</([:\w]+(\(\))?)>
300             (,?\s+(and\s+)?)?)+)
301         } { &internal_lrefs($1) }gex;
302
303         # LREF: a =head2 (head1?), maybe on a manpage, maybe right here
304         # the "func" can disambiguate
305         s{
306             L<(?:([a-zA-Z]\S+?) /)?"?(.*?)"?>
307         }{
308             do {
309                 $1      # if no $1, assume it means on this page.
310                     ?  "the section on I<$2> in the I<$1> manpage"
311                     :  "the section on I<$2>"
312             } 
313         }gex;
314
315         s/Z<>/\\&/g;            # the "don't format me" thing
316
317         # comes last because not subject to reprocessing
318         s{
319             C<([^<>]*)>
320         }{
321             do {
322                 ($str = $1) =~ tr/\200-\377/\000-\177/; #normalize hidden stuff
323                 # expand HTML escapes if any;
324                 # WARNING: if HTML escapes other than E<amp>,E<lt>,E<gt>,
325                 # E<quot> are in C<>, they will not be printed correctly.
326                 $str = &expand_HTML_escapes($str);
327                 $strverb = &alltt($str);    # Tex verbatim escape of a string.
328                 &noremap("$strverb");
329             }
330         }gex;
331
332 #       if ( /C<([^<>]*)/ ) {
333 #           $str = $1;
334 #           if ($str !~ /\|/) {         # if includes |
335 #               s/C<([^<>]*)>/&noremap("\\verb|$str|")/eg;
336 #           } else {
337 #               print STDERR "found \| in C<.*> at paragraph $.\n";
338 #               # find a character not contained in $str to use it as a
339 #               # separator of the \verb
340 #               ($chars = $str) =~ s/(\W)/\\$1/g;
341 #               ## ($chars = $str) =~ s/([\$<>,\|"'\-^{}()*+?\\])/\\$1/g;
342 #               @fence = grep(!/[ $chars]/,@tex_verb_fences);
343 #               s/C<([^<>]*)>/&noremap("\\verb$fence[0]$str$fence[0]")/eg;
344 #           }
345 #       }
346     }
347
348
349     # process each pod command
350     if (s/^=//) {                               # if a command
351         s/\n/ /g;
352         ($cmd, $rest) = split(' ', $_, 2);
353         $rest =~ s/^\s*//;
354         $rest =~ s/\s*$//;
355
356         if (defined $rest) {
357             &escapes;
358         }
359
360         $rest = &clear_noremap($rest);
361         $rest = &expand_HTML_escapes($rest);
362
363         if ($cmd eq 'cut') {
364             $cutting = 1;
365             $lastcmd = 'cut';
366         }
367         elsif ($cmd eq 'head1') {       # heading type 1
368             $rest =~ s/^\s*//; $rest =~ s/\s*$//;
369             print LATEX  "\n\\subsection*{$rest}";
370             # put index entry
371             ($index = $rest) =~ s/^(An?\s+|The\s+)//i;  # remove 'A' and 'The'
372             # index only those heads not matching the frequent patterns.
373             foreach $pat (@head1_freq_patterns) {
374                 if ($index =~ /^$pat/) {
375                     goto freqpatt;
376                 }
377             }
378             print LATEX  "%\n\\index{$index}\n" if ($index);
379           freqpatt:
380             $lastcmd = 'head1';
381         }
382         elsif ($cmd eq 'head2') {       # heading type 2
383             $rest =~ s/^\s*//; $rest =~ s/\s*$//;
384             print LATEX  "\n\\subsubsection*{$rest}";
385             # put index entry
386             ($index = $rest) =~ s/^(An?\s+|The\s+)//i;  # remove 'A' and 'The'
387             $index =~ s/^Example\s*[1-9][0-9]*\s*:\s*//; # remove 'Example :'
388             print LATEX  "%\n\\index{$index}\n"  if ($index);
389             $lastcmd = 'head2';
390         }
391         elsif ($cmd eq 'over') {        # 1 level within a listing environment
392             push(@indent,$indent);
393             $indent = $rest + 0;
394             $lastcmd = 'over';
395         }
396         elsif ($cmd eq 'back') {        # 1 level out of a listing environment
397             $indent = pop(@indent);
398             warn "Unmatched =back\n" unless defined $indent;
399             $listingcmd = pop(@listingcmd);
400             print LATEX  "\n\\end{$listingcmd}\n"  if ($listingcmd);
401             $lastcmd = 'back';
402         }
403         elsif ($cmd eq 'item') {        # an item paragraph starts
404             if ($lastcmd eq 'over') {   # if we have just entered listing env
405                 # see what type of list environment we are in.
406                 if ($rest =~ /^[0-9]\.?/) {     # if numeral heading
407                     $listingcmd = 'enumerate';
408                 } elsif ($rest =~ /^\*\s*/) {   # if * heading
409                     $listingcmd = 'itemize';
410                 } elsif ($rest =~ /^[^*]/) {    # if other headings
411                     $listingcmd = 'description';
412                 } else {
413                     warn "unknown list type for item $rest";
414                 }
415                 print LATEX  "\n\\begin{$listingcmd}\n";
416                 push(@listingcmd,$listingcmd);
417             } elsif ($lastcmd ne 'item') {
418                 warn "Illegal '=item' command without preceding 'over':";
419                 warn "=item $bareitem";
420             }
421
422             if ($listingcmd eq 'enumerate') {
423                 $rest =~ s/^[0-9]+\.?\s*//;     # remove numeral heading
424                 print LATEX  "\n\\item";
425                 print LATEX  "{\\bf $rest}" if $rest;
426             } elsif ($listingcmd eq 'itemize') {
427                 $rest =~ s/^\*\s*//;            # remove * heading
428                 print LATEX  "\n\\item";
429                 print LATEX  "{\\bf $rest}" if $rest;
430             } else {                            # description item
431                 print LATEX  "\n\\item[$rest]";
432             }
433             $lastcmd = 'item';
434             $rightafter_item = 'yes';
435
436             # check if the item heading is short or long.
437             ($itemhead = $rest) =~ s/{\\bf (\S*)}/$1/g;
438             if (length($itemhead) < 4) {
439                 $itemshort = "yes";
440             } else {
441                 $itemshort = "no";
442             }
443             # write index entry
444             if ($pod =~ "perldiag") {                   # skip 'perldiag.pod'
445                 goto noindex;
446             }
447             # strip out the item of pod quotes and get a plain text entry
448             $bareitem =~ s/\n/ /g;                      # remove newlines
449             $bareitem =~ s/\s*$//;                      # remove trailing space
450             $bareitem =~ s/[A-Z]<([^<>]*)>/$1/g;        # remove <> quotes
451             ($index = $bareitem) =~ s/^\*\s+//;         # remove leading '*'
452             $index =~ s/^(An?\s+|The\s+)//i;            # remove 'A' and 'The'
453             $index =~ s/^\s*[1-9][0-9]*\s*[.]\s*$//; # remove numeral only
454             $index =~ s/^\s*\w\s*$//;                   # remove 1 char only's
455                 # quote ", @ and ! with " to be used in makeindex.
456             $index =~ s/"/""/g;                         # quote "
457             $index =~ s/@/"@/g;                         # quote @
458             $index =~ s/!/"!/g;                         # quote !
459             ($rest2=$rest) =~ s/^\*\s+//;       # remove *
460             $rest2 =~ s/"/""/g;                         # quote "
461             $rest2 =~ s/@/"@/g;                         # quote @
462             $rest2 =~ s/!/"!/g;                         # quote !
463             if ($pod =~ "(perlfunc|perlvar)") { # when doc is perlfunc,perlvar
464                 # take only the 1st word of item heading
465                 $index =~ s/^([^{}\s]*)({.*})?([^{}\s]*)\s+.*/\1\2\3/;
466                 $rest2 =~ s/^([^{}\s]*)({.*})?([^{}\s]*)\s+.*/\1\2\3/;
467             }
468             if ($index =~ /[A-Za-z\$@%]/) {
469                     #  write  \index{plain_text_entry@TeX_string_entry}
470                 print LATEX  "%\n\\index{$index\@$rest2}%\n";
471             }
472           noindex:
473             ;
474         }
475         else {
476             warn "Unrecognized directive: $cmd\n";
477         }
478     }
479     else {                                      # if not command
480         &escapes;
481         $_ = &clear_noremap($_);
482         $_ = &expand_HTML_escapes($_);
483
484         # if the present paragraphs follows an =item declaration,
485         # put a line break.
486         if ($lastcmd eq 'item' &&
487             $rightafter_item eq 'yes' && $itemshort eq "no") {
488             print LATEX  "\\hfil\\\\";
489             $rightafter_item = 'no';
490         }
491         print LATEX  "\n",$_;
492     }
493 }
494
495 print LATEX  "\n";
496 close(POD);
497 close(LATEX);
498
499
500 #########################################################################
501
502 sub do_hdr {
503     print LATEX "% LaTeX document produced by pod2latex from \"$pod.pod\".\n";
504     print LATEX "% The followings need be defined in the preamble of this document:\n";
505     print LATEX "%\\def\\C++{{\\rm C\\kern-.05em\\raise.3ex\\hbox{\\footnotesize ++}}}\n";
506     print LATEX "%\\def\\underscore{\\leavevmode\\kern.04em\\vbox{\\hrule width 0.4em height 0.3pt}}\n";
507     print LATEX "%\\setlength{\\parindent}{0pt}\n";
508     print LATEX "\n";
509     $podq = &escape_tex_specials("\U$pod\E");
510     print LATEX "\\section{$podq}%\n";
511     print LATEX "\\index{$podq}";
512     print LATEX "\n";
513 }
514
515 sub nobreak {
516     my $string = shift;
517     $string =~ s/ +/~/g;                # TeX no line break
518     $string;
519 }
520
521 sub noremap {
522     local($thing_to_hide) = shift;
523     $thing_to_hide =~ tr/\000-\177/\200-\377/;
524     return $thing_to_hide;
525 }
526
527 sub init_noremap {
528         # escape high bit characters in input stream
529         s/([\200-\377])/"E<".ord($1).">"/ge;
530 }
531
532 sub clear_noremap {
533     local($tmp) = shift;
534     $tmp =~ tr/\200-\377/\000-\177/;
535     return $tmp;
536 }
537
538 sub expand_HTML_escapes {
539     local($s) = $_[0];
540     $s =~ s { E<((\d+)|([A-Za-z]+))> }
541     {
542         do {
543                 defined($2) 
544                 ? do { chr($2) }
545                 : 
546             exists $HTML_Escapes{$3}
547             ? do { $HTML_Escapes{$3} }
548             : do {
549                 warn "Unknown escape: $& in $_";
550                 "E<$1>";
551             }
552         }
553     }egx;
554     return $s;
555 }
556
557 sub escapes {
558     # make C++ into \C++, which is to be defined as
559     # \def\C++{{\rm C\kern-.05em\raise.3ex\hbox{\footnotesize ++}}}
560     s/\bC\+\+/\\C++{}/g;
561 }
562
563 # Translate a string into a TeX \tt string to obtain a verbatim print out.
564 # TeX special characters are escaped by \.
565 # This can be used inside of LaTeX command arguments.
566 # We don't use LaTeX \verb since it doesn't work inside of command arguments.
567 sub alltt {
568     local($str) = shift;
569         # other chars than #,\,$,%,&,{,},_,\,^,~ ([ and ] included).
570     $str =~ s/([^${backslash_escapables}\\\^\~]+)/&noremap("$&")/eg;
571         # chars #,\,$,%,&,{,}  =>  \# , ...
572     $str =~ s/([$backslash_escapables2])/&noremap("\\$&")/eg;
573         # chars _,\,^,~  =>  \char`\_ , ...
574     $str =~ s/_/&noremap("\\char`\\_")/eg;
575     $str =~ s/\\/&noremap("\\char`\\\\")/ge;
576     $str =~ s/\^/\\char`\\^/g;
577     $str =~ s/\~/\\char`\\~/g;
578
579     $str =~ tr/\200-\377/\000-\177/;            # put back
580     $str = "{\\tt ".$str."}";                   # make it a \tt string
581     return $str;
582 }
583
584 sub escape_tex_specials {
585     local($str) = shift;
586         # other chars than #,\,$,%,&,{,},  _,\,^,~ ([ and ] included).
587     # backslash escapable characters #,\,$,%,&,{,} except _.
588     $str =~ s/([$backslash_escapables2])/&noremap("\\$1")/ge;
589     $str =~ s/_/&noremap("\\underscore{}")/ge;  # \_ is too thin.
590     # quote TeX special characters |, ^, ~, \.
591     $str =~ s/\|/&noremap("\$|\$")/ge;
592     $str =~ s/\^/&noremap("\$\\hat{\\hspace{0.4em}}\$")/ge;
593     $str =~ s/\~/&noremap("\$\\tilde{\\hspace{0.4em}}\$")/ge;
594     $str =~ s/\\/&noremap("\$\\backslash{}\$")/ge;
595     # characters need to be treated differently in TeX
596     # *
597     $str =~ s/[*]/&noremap("\$\\ast\$")/ge;
598     # escape < and > as math string,
599     $str =~ s/</&noremap("\$<\$")/ge;
600     $str =~ s/>/&noremap("\$>\$")/ge;
601     $str =~ tr/\200-\377/\000-\177/;            # put back
602     return $str;
603 }
604
605 sub internal_lrefs {
606     local($_) = shift;
607
608     s{L</([^>]+)>}{$1}g;
609     my(@items) = split( /(?:,?\s+(?:and\s+)?)/ );
610     my $retstr = "the ";
611     my $i;
612     for ($i = 0; $i <= $#items; $i++) {
613         $retstr .= "C<$items[$i]>";
614         $retstr .= ", " if @items > 2 && $i != $#items;
615         $retstr .= " and " if $i+2 == @items;
616     }
617     $retstr .= " entr" . ( @items > 1  ? "ies" : "y" )
618             .  " elsewhere in this document";
619
620     return $retstr;
621 }
622
623 # map of HTML escapes to TeX escapes.
624 BEGIN {
625 %HTML_Escapes = (
626     'amp'       =>      '&',    #   ampersand
627     'lt'        =>      '<',    #   left chevron, less-than
628     'gt'        =>      '>',    #   right chevron, greater-than
629     'quot'      =>      '"',    #   double quote
630
631     "Aacute"    =>      "\\'{A}",       #   capital A, acute accent
632     "aacute"    =>      "\\'{a}",       #   small a, acute accent
633     "Acirc"     =>      "\\^{A}",       #   capital A, circumflex accent
634     "acirc"     =>      "\\^{a}",       #   small a, circumflex accent
635     "AElig"     =>      '\\AE',         #   capital AE diphthong (ligature)
636     "aelig"     =>      '\\ae',         #   small ae diphthong (ligature)
637     "Agrave"    =>      "\\`{A}",       #   capital A, grave accent
638     "agrave"    =>      "\\`{a}",       #   small a, grave accent
639     "Aring"     =>      '\\u{A}',       #   capital A, ring
640     "aring"     =>      '\\u{a}',       #   small a, ring
641     "Atilde"    =>      '\\~{A}',       #   capital A, tilde
642     "atilde"    =>      '\\~{a}',       #   small a, tilde
643     "Auml"      =>      '\\"{A}',       #   capital A, dieresis or umlaut mark
644     "auml"      =>      '\\"{a}',       #   small a, dieresis or umlaut mark
645     "Ccedil"    =>      '\\c{C}',       #   capital C, cedilla
646     "ccedil"    =>      '\\c{c}',       #   small c, cedilla
647     "Eacute"    =>      "\\'{E}",       #   capital E, acute accent
648     "eacute"    =>      "\\'{e}",       #   small e, acute accent
649     "Ecirc"     =>      "\\^{E}",       #   capital E, circumflex accent
650     "ecirc"     =>      "\\^{e}",       #   small e, circumflex accent
651     "Egrave"    =>      "\\`{E}",       #   capital E, grave accent
652     "egrave"    =>      "\\`{e}",       #   small e, grave accent
653     "ETH"       =>      '\\OE',         #   capital Eth, Icelandic
654     "eth"       =>      '\\oe',         #   small eth, Icelandic
655     "Euml"      =>      '\\"{E}',       #   capital E, dieresis or umlaut mark
656     "euml"      =>      '\\"{e}',       #   small e, dieresis or umlaut mark
657     "Iacute"    =>      "\\'{I}",       #   capital I, acute accent
658     "iacute"    =>      "\\'{i}",       #   small i, acute accent
659     "Icirc"     =>      "\\^{I}",       #   capital I, circumflex accent
660     "icirc"     =>      "\\^{i}",       #   small i, circumflex accent
661     "Igrave"    =>      "\\`{I}",       #   capital I, grave accent
662     "igrave"    =>      "\\`{i}",       #   small i, grave accent
663     "Iuml"      =>      '\\"{I}',       #   capital I, dieresis or umlaut mark
664     "iuml"      =>      '\\"{i}',       #   small i, dieresis or umlaut mark
665     "Ntilde"    =>      '\\~{N}',       #   capital N, tilde
666     "ntilde"    =>      '\\~{n}',       #   small n, tilde
667     "Oacute"    =>      "\\'{O}",       #   capital O, acute accent
668     "oacute"    =>      "\\'{o}",       #   small o, acute accent
669     "Ocirc"     =>      "\\^{O}",       #   capital O, circumflex accent
670     "ocirc"     =>      "\\^{o}",       #   small o, circumflex accent
671     "Ograve"    =>      "\\`{O}",       #   capital O, grave accent
672     "ograve"    =>      "\\`{o}",       #   small o, grave accent
673     "Oslash"    =>      "\\O",          #   capital O, slash
674     "oslash"    =>      "\\o",          #   small o, slash
675     "Otilde"    =>      "\\~{O}",       #   capital O, tilde
676     "otilde"    =>      "\\~{o}",       #   small o, tilde
677     "Ouml"      =>      '\\"{O}',       #   capital O, dieresis or umlaut mark
678     "ouml"      =>      '\\"{o}',       #   small o, dieresis or umlaut mark
679     "szlig"     =>      '\\ss',         #   small sharp s, German (sz ligature)
680     "THORN"     =>      '\\L',          #   capital THORN, Icelandic
681     "thorn"     =>      '\\l',,         #   small thorn, Icelandic
682     "Uacute"    =>      "\\'{U}",       #   capital U, acute accent
683     "uacute"    =>      "\\'{u}",       #   small u, acute accent
684     "Ucirc"     =>      "\\^{U}",       #   capital U, circumflex accent
685     "ucirc"     =>      "\\^{u}",       #   small u, circumflex accent
686     "Ugrave"    =>      "\\`{U}",       #   capital U, grave accent
687     "ugrave"    =>      "\\`{u}",       #   small u, grave accent
688     "Uuml"      =>      '\\"{U}',       #   capital U, dieresis or umlaut mark
689     "uuml"      =>      '\\"{u}',       #   small u, dieresis or umlaut mark
690     "Yacute"    =>      "\\'{Y}",       #   capital Y, acute accent
691     "yacute"    =>      "\\'{y}",       #   small y, acute accent
692     "yuml"      =>      '\\"{y}',       #   small y, dieresis or umlaut mark
693 );
694 }
695 !NO!SUBS!
696
697 close OUT or die "Can't close $file: $!";
698 chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
699 exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';