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