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