blob: cf3595f1f8600e8eca9019a77e2cec311544441e [file] [log] [blame]
Fred Drake3fe1d321999-01-08 15:25:29 +00001#! /usr/bin/env perl -w
2# html2texi.pl -- Convert HTML documentation to Texinfo format
3# Michael Ernst <mernst@cs.washington.edu>
4# Time-stamp: <1998-09-10 12:52:38 mernst>
5
6# This program converts HTML documentation trees into Texinfo format.
7# Given the name of a main (or contents) HTML file, it processes that file,
8# and other files (transitively) referenced by it, into a Texinfo file
9# (whose name is chosen from the file or directory name of the argument).
10# For instance:
11# html2texi.pl api/index.pl
12# produces file "api.texi".
13
14# Texinfo format can be easily converted to Info format (for browsing in
15# Emacs or the standalone Info browser), to a printed manual, or to HTML.
16# Thus, html2texi.pl permits conversion of HTML files to Info format, and
17# secondarily enables producing printed versions of Web page hierarchies.
18
19# Unlike HTML, Info format is searchable. Since Info is integrated into
20# Emacs, one can read documentation without starting a separate Web
21# browser. Additionally, Info browsers (including Emacs) contain
22# convenient features missing from Web browsers, such as easy index lookup
23# and mouse-free browsing.
24
25# Limitations:
26# html2texi.pl is currently tuned to latex2html output, but should be
27# extensible to arbitrary HTML documents. It will be most useful for HTML
28# with a hierarchical structure and an index. The HTML tree to be
29# traversed must be on local disk, rather than being accessed via HTTP.
30# This script requires the use of "checkargs.pm". To eliminate that
31# dependence, replace calls to check_args* by @_ (which is always the last
32# argument to those functions).
33# Also see the "to do" section, below.
34# Comments, suggestions, bug fixes, and enhancements are welcome.
35
36###
37### Typical usage for the Python documentation:
38###
39
40# (Actually, most of this is in a Makefile instead.)
41# The resulting Info format Python documentation is currently available at
42# ftp://ftp.cs.washington.edu/homes/mernst/python-info.tar.gz
43
44# Fix up HTML problems, eg <DL COMPACT><DD>
45
46# html2texi.pl /homes/fish/mernst/tmp/python-doc/html/api/index.html
47# html2texi.pl /homes/fish/mernst/tmp/python-doc/html/ext/index.html
48# html2texi.pl /homes/fish/mernst/tmp/python-doc/html/lib/index.html
49# html2texi.pl /homes/fish/mernst/tmp/python-doc/html/mac/index.html
50# html2texi.pl /homes/fish/mernst/tmp/python-doc/html/ref/index.html
51# html2texi.pl /homes/fish/mernst/tmp/python-doc/html/tut/index.html
52
53# Edit the generated .texi files:
54# * change @setfilename to prefix "python-"
55# * fix up any sectioning, such as for Abstract
56# * make Texinfo menus
57# * perhaps remove the @detailmenu ... @end detailmenu
58# In Emacs:
59# (progn (goto-char (point-min)) (replace-regexp "\\(@setfilename \\)\\([-a-z]*\\)$" "\\1python-\\2.info") (replace-string "@node Front Matter\n@chapter Abstract\n" "@node Abstract\n@section Abstract\n") (progn (mark-whole-buffer) (texinfo-master-menu 'update-all-nodes)) (save-buffer))
60
61# makeinfo api.texi
62# makeinfo ext.texi
63# makeinfo lib.texi
64# makeinfo mac.texi
65# makeinfo ref.texi
66# makeinfo tut.texi
67
68
69###
70### Structure of the code
71###
72
73# To be written...
74
75
76###
77### Design decisions
78###
79
80# Source and destination languages
81# --------------------------------
82#
83# The goal is Info files; I create Texinfo, so I don't have to worry about
84# the finer details of Info file creation. (I'm not even sure of its exact
85# format.)
86#
87# Why not start from LaTeX rather than HTML?
88# I could hack latex2html itself to produce Texinfo instead, or fix up
89# partparse.py (which already translates LaTeX to Teinfo).
90# Pros:
91# * has high-level information such as index entries, original formatting
92# Cons:
93# * those programs are complicated to read and understand
94# * those programs try to handle arbitrary LaTeX input, track catcodes,
95# and more: I don't want to go to that effort. HTML isn't as powerful
96# as LaTeX, so there are fewer subtleties.
97# * the result wouldn't work for arbitrary HTML documents; it would be
98# nice to eventually extend this program to HTML produced from Docbook,
99# Frame, and more.
100
101# Parsing
102# -------
103#
104# I don't want to view the text as a linear stream; I'd rather parse the
105# whole thing and then do pattern matching over the parsed representation (to
106# find idioms such as indices, lists of child nodes, etc.).
107# * Perl provides HTML::TreeBuilder, which does just what I want.
108# * libwww-perl: http://www.linpro.no/lwp/
109# * TreeBuilder: HTML-Tree-0.51.tar.gz
110# * Python Parsers, Formatters, and Writers don't really provide the right
111# interface (and the version in Grail doesn't correspond to another
112# distributed version, so I'm confused about which to be using). I could
113# write something in Python that creates a parse tree, but why bother?
114
115# Other implementation language issues:
116# * Python lacks variable declarations, reasonable scoping, and static
117# checking tools. I've written some of the latter for myself that make
118# my Perl programming a lot safer than my Python programming will be until
119# I have a similar suite for that language.
120
121
122###########################################################################
123### To do
124###
125
126# Section names:
127# Fix the problem with multiple sections in a single file (eg, Abstract in
128# Front Matter section).
129# Deal with cross-references, as in /homes/fish/mernst/tmp/python-doc/html/ref/types.html:310
130# Index:
131# Perhaps double-check that every tag mentioned in the index is found
132# in the text.
133# Python: email to python-docs@python.org, to get their feedback.
134# Compare to existing lib/ Info manual
135# Write the hooks into info-look; replace pyliblookup1-1.tar.gz.
136# Postpass to remove extra quotation marks around typography already in
137# a different font (to avoid double delimiters as in "`code'"); or
138# perhaps consider using only font-based markup so that we don't get
139# the extra *bold* and `code' markup in Info.
140
141## Perhaps don't rely on automatic means for adding up, next, prev; I have
142## all that info available to me already, so it's not so much trouble to
143## add it. (Right?) But it is *so* easy to use Emacs instead...
144
145
146###########################################################################
147### Strictures
148###
149
150# man HTML::TreeBuilder
151# man HTML::Parser
152# man HTML::Element
153
154# require HTML::ParserWComment;
155require HTML::Parser;
156require HTML::TreeBuilder;
157require HTML::Element;
158
159use File::Basename;
160use Cwd;
161
162use strict;
163# use Carp;
164
165
166use checkargs;
167
168
169###########################################################################
170### Variables
171###
172
173my @section_stack = (); # elements are chapter/section/subsec nodetitles (I think)
174my $current_ref_tdf; # for the file currently being processed;
175 # used in error messages
176my $html_directory;
177my %footnotes;
178
179# First element should not be used.
180my @sectionmarker = ("manual", "chapter", "section", "subsection", "subsubsection");
181
182my %inline_markup = ("b" => "strong",
183 "code" => "code",
184 "i" => "emph",
185 "kbd" => "kbd",
186 "samp" => "samp",
187 "strong" => "strong",
188 "tt" => "code",
189 "var" => "var");
190
191my @deferred_index_entries = ();
192
193my @index_titles = (); # list of (filename, type) lists
194my %index_info = ("Index" => ["\@blindex", "bl"],
195 "Concept Index" => ["\@cindex", "cp"],
196 "Module Index" => ["\@mdindex", "md"]);
197
198
199###########################################################################
200### Main/contents page
201###
202
203# Process first-level page on its own, or just a contents page? Well, I do
204# want the title, author, etc., and the front matter... For now, just add
205# that by hand at the end.
206
207
208# data structure possibilities:
209# * tree-like (need some kind of stack when processing (or parent pointers))
210# * list of name and depth; remember old and new depths.
211
212# Each element is a reference to a list of (nodetitle, depth, filename).
213my @contents_list = ();
214
215# The problem with doing fixups on the fly is that some sections may have
216# already been processed (and no longer available) by the time we notice
217# others with the same name. It's probably better to fully construct the
218# contents list (reading in all files of interest) upfront; that will also
219# let me do a better job with cross-references, because again, all files
220# will already be read in.
221my %contents_hash = ();
222my %contents_fixups = ();
223
224my @current_contents_list = ();
225
226# Merge @current_contents_list into @contents_list,
227# and set @current_contents_list to be empty.
228sub merge_contents_lists ( )
229{ check_args(0, @_);
230
231 # Three possibilities:
232 # * @contents_list is empty: replace it by @current_contents_list.
233 # * prefixes of the two lists are identical: do nothing
234 # * @current_contents_list is all at lower level than $contents_list[0];
235 # prefix @contents_list by @current_contents_list
236
237 if (scalar(@current_contents_list) == 0)
238 { die "empty current_contents_list"; }
239
240 # if (scalar(@contents_list) == 0)
241 # { @contents_list = @current_contents_list;
242 # @current_contents_list = ();
243 # return; }
244
245 # if (($ {$contents_list[0]}[1]) < ($ {$current_contents_list[0]}[1]))
246 # { unshift @contents_list, @current_contents_list;
247 # @current_contents_list = ();
248 # return; }
249
250 for (my $i=0; $i<scalar(@current_contents_list); $i++)
251 { my $ref_c_tdf = $current_contents_list[$i];
252 if ($i >= scalar(@contents_list))
253 { push @contents_list, $ref_c_tdf;
254 my $title = $ {$ref_c_tdf}[0];
255 if (defined $contents_hash{$title})
256 { $contents_fixups{$title} = 1; }
257 else
258 { $contents_hash{$title} = 1; }
259 next; }
260 my $ref_tdf = $contents_list[$i];
261 my ($title, $depth, $file) = @{$ref_tdf};
262 my ($c_title, $c_depth, $c_file) = @{$ref_c_tdf};
263
264 if (($title ne $c_title)
265 && ($depth < $c_depth)
266 && ($file ne $c_file))
267 { splice @contents_list, $i, 0, $ref_c_tdf;
268 if (defined $contents_hash{$c_title})
269 { $contents_fixups{$c_title} = 1; }
270 else
271 { $contents_hash{$c_title} = 1; }
272 next; }
273
274 if (($title ne $c_title)
275 || ($depth != $c_depth)
276 || ($file ne $c_file))
277 { die ("while processing $ {$current_ref_tdf}[2] at depth $ {$current_ref_tdf}[1], mismatch at index $i:",
278 "\n main: <<<$title>>> $depth $file",
279 "\n curr: <<<$c_title>>> $c_depth $c_file"); }
280 }
281 @current_contents_list = ();
282}
283
284
285
286# Set @current_contents_list to a list of (title, href, sectionlevel);
287# then merge that list into @contents_list.
288# Maybe this function should also produce a map
289# from title (or href) to sectionlevel (eg "chapter"?).
290sub process_child_links ( $ )
291{ my ($he) = check_args(1, @_);
292
293 # $he->dump;
294 if (scalar(@current_contents_list) != 0)
295 { die "current_contents_list nonempty: @current_contents_list"; }
296 $he->traverse(\&increment_current_contents_list, 'ignore text');
297
298 # Normalize the depths; for instance, convert 1,3,5 into 0,1,2.
299 my %depths = ();
300 for my $ref_tdf (@current_contents_list)
301 { $depths{$ {$ref_tdf}[1]} = 1; }
302 my @sorted_depths = sort keys %depths;
303 my $current_depth = scalar(@section_stack)-1;
304 my $current_depth_2 = $ {$current_ref_tdf}[1];
305 if ($current_depth != $current_depth_2)
306 { die "mismatch in current depths: $current_depth $current_depth_2; ", join(", ", @section_stack); }
307 for (my $i=0; $i<scalar(@sorted_depths); $i++)
308 { $depths{$sorted_depths[$i]} = $i + $current_depth+1; }
309 for my $ref_tdf (@current_contents_list)
310 { $ {$ref_tdf}[1] = $depths{$ {$ref_tdf}[1]}; }
311
312 # Eliminate uninteresting sections. Hard-coded hack for now.
313 if ($ {$current_contents_list[-1]}[0] eq "About this document ...")
314 { pop @current_contents_list; }
315 if ((scalar(@current_contents_list) > 1)
316 && ($ {$current_contents_list[1]}[0] eq "Contents"))
317 { my $ref_first_tdf = shift @current_contents_list;
318 $current_contents_list[0] = $ref_first_tdf; }
319
320 for (my $i=0; $i<scalar(@current_contents_list); $i++)
321 { my $ref_tdf = $current_contents_list[$i];
322 my $title = $ {$ref_tdf}[0];
323 if (exists $index_info{$title})
324 { my $index_file = $ {$ref_tdf}[2];
325 my ($indexing_command, $suffix) = @{$index_info{$title}};
326 process_index_file($index_file, $indexing_command);
327 print TEXI "\n\@defindex $suffix\n";
328 push @index_titles, $title;
329 splice @current_contents_list, $i, 1;
330 $i--; }
331 elsif ($title =~ /\bIndex$/)
332 { print STDERR "Warning: \"$title\" might be an index; if so, edit \%index_info.\n"; } }
333
334 merge_contents_lists();
335
336 # print_contents_list();
337 # print_index_info();
338}
339
340
341sub increment_current_contents_list ( $$$ )
342{ my ($he, $startflag, $depth) = check_args(3, @_);
343 if (!$startflag)
344 { return; }
345
346 if ($he->tag eq "li")
347 { my @li_content = @{$he->content};
348 if ($li_content[0]->tag ne "a")
349 { die "first element of <LI> should be <A>"; }
350 my ($name, $href, @content) = anchor_info($li_content[0]);
351 # unused $name
352 my $title = join("", collect_texts($li_content[0]));
353 $title = texi_remove_punctuation($title);
354 # The problem with these is that they are formatted differently in
355 # @menu and @node!
356 $title =~ s/``/\"/g;
357 $title =~ s/''/\"/g;
358 $title =~ s/ -- / /g;
359 push @current_contents_list, [ $title, $depth, $href ]; }
360 return 1;
361}
362
363# Simple version for section titles
364sub html_to_texi ( $ )
365{ my ($he) = check_args(1, @_);
366 if (!ref $he)
367 { return $he; }
368
369 my $tag = $he->tag;
370 if (exists $inline_markup{$tag})
371 { my $result = "\@$inline_markup{$tag}\{";
372 for my $elt (@{$he->content})
373 { $result .= html_to_texi($elt); }
374 $result .= "\}";
375 return $result; }
376 else
377 { $he->dump;
378 die "html_to_texi confused by <$tag>"; }
379}
380
381
382
383sub print_contents_list ()
384{ check_args(0, @_);
385 print STDERR "Contents list:\n";
386 for my $ref_tdf (@contents_list)
387 { my ($title, $depth, $file) = @{$ref_tdf};
388 print STDERR "$title $depth $file\n"; }
389}
390
391
392
393###########################################################################
394### Index
395###
396
397my $l2h_broken_link_name = "l2h-";
398
399
400# map from file to (map from anchor name to (list of index texts))
401# (The list is needed when a single LaTeX command like \envvar
402# expands to multiple \index commands.)
403my %file_index_entries = ();
404my %this_index_entries; # map from anchor name to (list of index texts)
405
406my %file_index_entries_broken = (); # map from file to (list of index texts)
407my @this_index_entries_broken;
408
409my $index_prefix = "";
410my @index_prefixes = ();
411
412my $this_indexing_command;
413
414sub print_index_info ()
415{ check_args(0, @_);
416 my ($key, $val);
417 for my $file (sort keys %file_index_entries)
418 { my %index_entries = %{$file_index_entries{$file}};
419 print STDERR "file: $file\n";
420 for my $aname (sort keys %index_entries)
421 { my @entries = @{$index_entries{$aname}};
422 if (scalar(@entries) == 1)
423 { print STDERR " $aname : $entries[0]\n"; }
424 else
425 { print STDERR " $aname : ", join("\n " . (" " x length($aname)), @entries), "\n"; } } }
426 for my $file (sort keys %file_index_entries_broken)
427 { my @entries = @{$file_index_entries_broken{$file}};
428 print STDERR "file: $file\n";
429 for my $entry (@entries)
430 { print STDERR " $entry\n"; }
431 }
432}
433
434
435sub process_index_file ( $$ )
436{ my ($file, $indexing_command) = check_args(2, @_);
437 # print "process_index_file $file $indexing_command\n";
438
439 my $he = file_to_tree($html_directory . $file);
440 # $he->dump();
441
442 $this_indexing_command = $indexing_command;
443 $he->traverse(\&process_if_index_dl_compact, 'ignore text');
444 undef $this_indexing_command;
445 # print "process_index_file done\n";
446}
447
448
449sub process_if_index_dl_compact ( $$$ )
450{ my ($he, $startflag) = (check_args(3, @_))[0,1]; # ignore depth argument
451 if (!$startflag)
452 { return; }
453
454 if (($he->tag() eq "dl") && (defined $he->attr('compact')))
455 { process_index_dl_compact($he);
456 return 0; }
457 else
458 { return 1; }
459}
460
461
462# The elements of a <DL COMPACT> list from a LaTeX2HTML index:
463# * a single space: text to be ignored
464# * <DT> elements with an optional <DD> element following each one
465# Two types of <DT> elements:
466# * Followed by a <DD> element: the <DT> contains a single
467# string, and the <DD> contains a whitespace string to be ignored, a
468# <DL COMPACT> to be recursively processed (with the <DT> string as a
469# prefix), and a whitespace string to be ignored.
470# * Not followed by a <DD> element: contains a list of anchors
471# and texts (ignore the texts, which are only whitespace and commas).
472# Optionally contains a <DL COMPACT> to be recursively processed (with
473# the <DT> string as a prefix)
474sub process_index_dl_compact ( $ )
475{ my ($h) = check_args(1, @_);
476 my @content = @{$h->content()};
477 for (my $i = 0; $i < scalar(@content); $i++)
478 { my $this_he = $content[$i];
479 if ($this_he->tag ne "dt")
480 { $this_he->dump;
481 die "Expected <DT> tag: " . $this_he->tag; }
482 if (($i < scalar(@content) - 1) && ($content[$i+1]->tag eq "dd"))
483 { process_index_dt_and_dd($this_he, $content[$i+1]);
484 $i++; }
485 else
486 { process_index_lone_dt($this_he); } } }
487
488
489
490# Argument is a <DT> element. If it contains more than one anchor, then
491# the texts of all subsequent ones are "[Link]". Example:
492# <DT>
493# <A HREF="embedding.html#l2h-201">
494# "$PATH"
495# ", "
496# <A HREF="embedding.html#l2h-205">
497# "[Link]"
498# Optionally contains a <DL COMPACT> as well. Example:
499# <DT>
500# <A HREF="types.html#l2h-616">
501# "attribute"
502# <DL COMPACT>
503# <DT>
504# <A HREF="assignment.html#l2h-3074">
505# "assignment"
506# ", "
507# <A HREF="assignment.html#l2h-3099">
508# "[Link]"
509# <DT>
510# <A HREF="types.html#l2h-">
511# "assignment, class"
512
513sub process_index_lone_dt ( $ )
514{ my ($dt) = check_args(1, @_);
515 my @dtcontent = @{$dt->content()};
516 my $acontent;
517 my $acontent_suffix;
518 for my $a (@dtcontent)
519 { if ($a eq ", ")
520 { next; }
521 if (!ref $a)
522 { $dt->dump;
523 die "Unexpected <DT> string element: $a"; }
524
525 if ($a->tag eq "dl")
526 { push @index_prefixes, $index_prefix;
527 if (!defined $acontent_suffix)
528 { die "acontent_suffix not yet defined"; }
529 $index_prefix .= $acontent_suffix . ", ";
530 process_index_dl_compact($a);
531 $index_prefix = pop(@index_prefixes);
532 return; }
533
534 if ($a->tag ne "a")
535 { $dt->dump;
536 $a->dump;
537 die "Expected anchor in lone <DT>"; }
538
539 my ($aname, $ahref, @acontent) = anchor_info($a);
540 # unused $aname
541 if (scalar(@acontent) != 1)
542 { die "Expected just one content of <A> in <DT>: @acontent"; }
543 if (ref $acontent[0])
544 { $acontent[0]->dump;
545 die "Expected string content of <A> in <DT>: $acontent[0]"; }
546 if (!defined($acontent))
547 { $acontent = $index_prefix . $acontent[0];
548 $acontent_suffix = $acontent[0]; }
549 elsif (($acontent[0] ne "[Link]") && ($acontent ne ($index_prefix . $acontent[0])))
550 { die "Differing content: <<<$acontent>>>, <<<$acontent[0]>>>"; }
551
552 if (!defined $ahref)
553 { $dt->dump;
554 die "no HREF in nachor in <DT>"; }
555 my ($ahref_file, $ahref_name) = split(/\#/, $ahref);
556 if (!defined $ahref_name)
557 { # Reference to entire file
558 $ahref_name = ""; }
559
560 if ($ahref_name eq $l2h_broken_link_name)
561 { if (!exists $file_index_entries_broken{$ahref_file})
562 { $file_index_entries_broken{$ahref_file} = []; }
563 push @{$file_index_entries_broken{$ahref_file}}, "$this_indexing_command $acontent";
564 next; }
565
566 if (!exists $file_index_entries{$ahref_file})
567 { $file_index_entries{$ahref_file} = {}; }
568 # Don't do this! It appears to make a copy, which is not desired.
569 # my %index_entries = %{$file_index_entries{$ahref_file}};
570 if (!exists $ {$file_index_entries{$ahref_file}}{$ahref_name})
571 { $ {$file_index_entries{$ahref_file}}{$ahref_name} = []; }
572 # { my $oldcontent = $ {$file_index_entries{$ahref_file}}{$ahref_name};
573 # if ($acontent eq $oldcontent)
574 # { die "Multiple identical index entries?"; }
575 # die "Trying to add $acontent, but already have index entry pointing at $ahref_file\#$ahref_name: ${$file_index_entries{$ahref_file}}{$ahref_name}"; }
576
577 push @{$ {$file_index_entries{$ahref_file}}{$ahref_name}}, "$this_indexing_command $acontent";
578 # print STDERR "keys: ", keys %{$file_index_entries{$ahref_file}}, "\n";
579 }
580}
581
582sub process_index_dt_and_dd ( $$ )
583{ my ($dt, $dd) = check_args(2, @_);
584 my $dtcontent;
585 { my @dtcontent = @{$dt->content()};
586 if ((scalar(@dtcontent) != 1) || (ref $dtcontent[0]))
587 { $dd->dump;
588 $dt->dump;
589 die "Expected single string (actual size = " . scalar(@dtcontent) . ") in content of <DT>: @dtcontent"; }
590 $dtcontent = $dtcontent[0];
591 $dtcontent =~ s/ +$//; }
592 my $ddcontent;
593 { my @ddcontent = @{$dd->content()};
594 if (scalar(@ddcontent) != 1)
595 { die "Expected single <DD> content, got ", scalar(@ddcontent), " elements:\n", join("\n", @ddcontent), "\n "; }
596 $ddcontent = $ddcontent[0]; }
597 if ($ddcontent->tag ne "dl")
598 { die "Expected <DL> as content of <DD>, but saw: $ddcontent"; }
599
600 push @index_prefixes, $index_prefix;
601 $index_prefix .= $dtcontent . ", ";
602 process_index_dl_compact($ddcontent);
603 $index_prefix = pop(@index_prefixes);
604}
605
606
607###########################################################################
608### Ordinary sections
609###
610
611sub process_section_file ( $$$ )
612{ my ($file, $depth, $nodetitle) = check_args(3, @_);
613 my $he = file_to_tree(($file =~ /^\//) ? $file : $html_directory . $file);
614
615 # print STDERR "process_section_file: $file $depth $nodetitle\n";
616
617 # Equivalently:
618 # while ($depth >= scalar(@section_stack)) { pop(@section_stack); }
619 @section_stack = @section_stack[0..$depth-1];
620
621 # Not a great nodename fixup scheme; need a more global view
622 if ((defined $contents_fixups{$nodetitle})
623 && (scalar(@section_stack) > 0))
624 { my $up_title = $section_stack[$#section_stack];
625 # hack for Python Standard Library
626 $up_title =~ s/^(Built-in|Standard) Module //g;
627 my ($up_first_word) = split(/ /, $up_title);
628 $nodetitle = "$up_first_word $nodetitle";
629 }
630
631 push @section_stack, $nodetitle;
632 # print STDERR "new section_stack: ", join(", ", @section_stack), "\n";
633
634 $he->traverse(\&process_if_child_links, 'ignore text');
635 %footnotes = ();
636 # $he->dump;
637 $he->traverse(\&process_if_footnotes, 'ignore text');
638
639 # $he->dump;
640
641 if (exists $file_index_entries{$file})
642 { %this_index_entries = %{$file_index_entries{$file}};
643 # print STDERR "this_index_entries:\n ", join("\n ", keys %this_index_entries), "\n";
644 }
645 else
646 { # print STDERR "Warning: no index entries for file $file\n";
647 %this_index_entries = (); }
648
649 if (exists $file_index_entries_broken{$file})
650 { @this_index_entries_broken = @{$file_index_entries_broken{$file}}; }
651 else
652 { # print STDERR "Warning: no index entries for file $file\n";
653 @this_index_entries_broken = (); }
654
655
656 if ($he->tag() ne "html")
657 { die "Expected <HTML> at top level"; }
658 my @content = @{$he->content()};
659 if ((!ref $content[0]) or ($content[0]->tag ne "head"))
660 { $he->dump;
661 die "<HEAD> not first element of <HTML>"; }
662 if ((!ref $content[1]) or ($content[1]->tag ne "body"))
663 { $he->dump;
664 die "<BODY> not second element of <HTML>"; }
665
666 $content[1]->traverse(\&output_body);
667}
668
669# stack of things we're inside that are preventing indexing from occurring now.
670# These are "h1", "h2", "h3", "h4", "h5", "h6", "dt" (and possibly others?)
671my @index_deferrers = ();
672
673sub push_or_pop_index_deferrers ( $$ )
674{ my ($tag, $startflag) = check_args(2, @_);
675 if ($startflag)
676 { push @index_deferrers, $tag; }
677 else
678 { my $old_deferrer = pop @index_deferrers;
679 if ($tag ne $old_deferrer)
680 { die "Expected $tag at top of index_deferrers but saw $old_deferrer; remainder = ", join(" ", @index_deferrers); }
681 do_deferred_index_entries(); }
682}
683
684
685sub label_add_index_entries ( $;$ )
686{ my ($label, $he) = check_args_range(1, 2, @_);
687 # print ((exists $this_index_entries{$label}) ? "*" : " "), " label_add_index_entries $label\n";
688 # $he is the anchor element
689 if (exists $this_index_entries{$label})
690 { push @deferred_index_entries, @{$this_index_entries{$label}};
691 return; }
692
693 if ($label eq $l2h_broken_link_name)
694 { # Try to find some text to use in guessing which links should point here
695 # I should probably only look at the previous element, or if that is
696 # all punctuation, the one before it; collecting all the previous texts
697 # is a bit of overkill.
698 my @anchor_texts = collect_texts($he);
699 my @previous_texts = collect_texts($he->parent, $he);
700 # 4 elements is arbitrary; ought to filter out punctuation and small words
701 # first, then perhaps keep fewer. Perhaps also filter out formatting so
702 # that we can see a larger chunk of text? (Probably not.)
703 # Also perhaps should do further chunking into words, in case the
704 # index term isn't a chunk of its own (eg, was in <tt>...</tt>.
705 my @candidate_texts = (@anchor_texts, (reverse(@previous_texts))[0..min(3,$#previous_texts)]);
706
707 my $guessed = 0;
708 for my $text (@candidate_texts)
709 { # my $orig_text = $text;
710 if ($text =~ /^[\"\`\'().?! ]*$/)
711 { next; }
712 if (length($text) <= 2)
713 { next; }
714 # hack for Python manual; maybe defer until failure first time around?
715 $text =~ s/^sys\.//g;
716 for my $iterm (@this_index_entries_broken)
717 { # I could test for zero: LaTeX2HTML's failures in the Python
718 # documentation are only for items of the form "... (built-in...)"
719 if (index($iterm, $text) != -1)
720 { push @deferred_index_entries, $iterm;
721 # print STDERR "Guessing index term `$iterm' for text `$orig_text'\n";
722 $guessed = 1;
723 } } }
724 if (!$guessed)
725 { # print STDERR "No guess in `", join("'; `", @this_index_entries_broken), "' for texts:\n `", join("'\n `", @candidate_texts), "'\n";
726 }
727 }
728}
729
730
731# Need to add calls to this at various places.
732# Perhaps add HTML::Element argument and do the check for appropriateness
733# here (ie, no action if inside <H1>, etc.).
734sub do_deferred_index_entries ()
735{ check_args(0, @_);
736 if ((scalar(@deferred_index_entries) > 0)
737 && (scalar(@index_deferrers) == 0))
738 { print TEXI "\n", join("\n", @deferred_index_entries), "\n";
739 @deferred_index_entries = (); }
740}
741
742my $table_columns; # undefined if not in a table
743my $table_first_column; # boolean
744
745sub output_body ( $$$ )
746{ my ($he, $startflag) = (check_args(3, @_))[0,1]; # ignore depth argument
747
748 if (!ref $he)
749 { my $space_index = index($he, " ");
750 if ($space_index != -1)
751 { # Why does
752 # print TEXI texi_quote(substr($he, 0, $space_index+1));
753 # give: Can't locate object method "TEXI" via package "texi_quote"
754 # (Because the definition texi_quote hasn't been seen yet.)
755 print TEXI &texi_quote(substr($he, 0, $space_index+1));
756 do_deferred_index_entries();
757 print TEXI &texi_quote(substr($he, $space_index+1)); }
758 else
759 { print TEXI &texi_quote($he); }
760 return; }
761
762 my $tag = $he->tag();
763
764 # Ordinary text markup first
765 if (exists $inline_markup{$tag})
766 { if ($startflag)
767 { print TEXI "\@$inline_markup{$tag}\{"; }
768 else
769 { print TEXI "\}"; } }
770 elsif ($tag eq "a")
771 { my ($name, $href, @content) = anchor_info($he);
772 if (!$href)
773 { # This anchor is only here for indexing/cross referencing purposes.
774 if ($startflag)
775 { label_add_index_entries($name, $he); }
776 }
777 elsif ($href =~ "^(ftp|http|news):")
778 { if ($startflag)
779 { # Should avoid second argument if it's identical to the URL.
780 print TEXI "\@uref\{$href, "; }
781 else
782 { print TEXI "\}"; }
783 }
784 elsif ($href =~ /^\#(foot[0-9]+)$/)
785 { # Footnote
786 if ($startflag)
787 { # Could double-check name and content, but I'm not
788 # currently storing that information.
789 print TEXI "\@footnote\{";
790 $footnotes{$1}->traverse(\&output_body);
791 print TEXI "\}";
792 return 0; } }
793 else
794 { if ($startflag)
795 { $he->dump;
796 warn "Can't deal with internal HREF anchors yet"; }
797 }
798 }
799 elsif ($tag eq "br")
800 { print TEXI "\@\n"; }
801 elsif ($tag eq "body")
802 { }
803 elsif ($tag eq "center")
804 { if (has_single_content_string($he)
805 && ($ {$he->content}[0] =~ /^ *$/))
806 { return 0; }
807 if ($startflag)
808 { print TEXI "\n\@center\n"; }
809 else
810 { print TEXI "\n\@end center\n"; }
811 }
812 elsif ($tag eq "div")
813 { my $align = $he->attr('align');
814 if (defined($align) && ($align eq "center"))
815 { if (has_single_content_string($he)
816 && ($ {$he->content}[0] =~ /^ *$/))
817 { return 0; }
818 if ($startflag)
819 { print TEXI "\n\@center\n"; }
820 else
821 { print TEXI "\n\@end center\n"; } }
822 }
823 elsif ($tag eq "dl")
824 { # Recognize "<dl><dd><pre> ... </pre></dl>" paradigm for "@example"
825 if (has_single_content_with_tag($he, "dd"))
826 { my $he_dd = $ {$he->content}[0];
827 if (has_single_content_with_tag($he_dd, "pre"))
828 { my $he_pre = $ {$he_dd->content}[0];
829 print_pre($he_pre);
830 return 0; } }
831 if ($startflag)
832 { # Could examine the elements, to be cleverer about formatting.
833 # (Also to use ftable, vtable...)
834 print TEXI "\n\@table \@asis\n"; }
835 else
836 { print TEXI "\n\@end table\n"; }
837 }
838 elsif ($tag eq "dt")
839 { push_or_pop_index_deferrers($tag, $startflag);
840 if ($startflag)
841 { print TEXI "\n\@item "; }
842 else
843 { } }
844 elsif ($tag eq "dd")
845 { if ($startflag)
846 { print TEXI "\n"; }
847 else
848 { }
849 if (scalar(@index_deferrers) != 0)
850 { $he->dump;
851 die "index deferrers: ", join(" ", @index_deferrers); }
852 do_deferred_index_entries();
853 }
854 elsif ($tag =~ /^(font|big|small)$/)
855 { # Do nothing for now.
856 }
857 elsif ($tag =~ /^h[1-6]$/)
858 { # We don't need this because we never recursively enter the heading content.
859 # push_or_pop_index_deferrers($tag, $startflag);
860 my $secname = "";
861 my @seclabels = ();
862 for my $elt (@{$he->content})
863 { if (!ref $elt)
864 { $secname .= $elt; }
865 elsif ($elt->tag eq "br")
866 { }
867 elsif ($elt->tag eq "a")
868 { my ($name, $href, @acontent) = anchor_info($elt);
869 if ($href)
870 { $he->dump;
871 $elt->dump;
872 die "Nonsimple anchor in <$tag>"; }
873 if (!defined $name)
874 { die "No NAME for anchor in $tag"; }
875 push @seclabels, $name;
876 for my $subelt (@acontent)
877 { $secname .= html_to_texi($subelt); } }
878 else
879 { $secname .= html_to_texi($elt); } }
880 if ($secname eq "")
881 { die "No section name in <$tag>"; }
882 if (scalar(@section_stack) == 1)
883 { if ($section_stack[-1] ne "Top")
884 { die "Not top? $section_stack[-1]"; }
885 print TEXI "\@settitle $secname\n";
886 print TEXI "\@c %**end of header\n";
887 print TEXI "\n";
888 print TEXI "\@node Top\n";
889 print TEXI "\n"; }
890 else
891 { print TEXI "\n\@node $section_stack[-1]\n";
892 print TEXI "\@$sectionmarker[scalar(@section_stack)-1] ", texi_remove_punctuation($secname), "\n"; }
893 for my $seclabel (@seclabels)
894 { label_add_index_entries($seclabel); }
895 # This should only happen once per file.
896 label_add_index_entries("");
897 if (scalar(@index_deferrers) != 0)
898 { die "index deferrers: ", join(" ", @index_deferrers); }
899 do_deferred_index_entries();
900 return 0;
901 }
902 elsif ($tag eq "hr")
903 { }
904 elsif ($tag eq "ignore")
905 { # Hack for ignored elements
906 return 0;
907 }
908 elsif ($tag eq "li")
909 { if ($startflag)
910 { print TEXI "\n\n\@item\n";
911 do_deferred_index_entries(); } }
912 elsif ($tag eq "ol")
913 { if ($startflag)
914 { print TEXI "\n\@enumerate \@bullet\n"; }
915 else
916 { print TEXI "\n\@end enumerate\n"; } }
917 elsif ($tag eq "p")
918 { if ($startflag)
919 { print TEXI "\n\n"; }
920 if (scalar(@index_deferrers) != 0)
921 { die "index deferrers: ", join(" ", @index_deferrers); }
922 do_deferred_index_entries(); }
923 elsif ($tag eq "pre")
924 { print_pre($he);
925 return 0; }
926 elsif ($tag eq "table")
927 { # Could also indicate common formatting for first column, or
928 # determine relative widths for columns (or determine a prototype row)
929 if ($startflag)
930 { if (defined $table_columns)
931 { $he->dump;
932 die "Can't deal with table nested inside $table_columns-column table"; }
933 $table_columns = table_columns($he);
934 if ($table_columns < 2)
935 { $he->dump;
936 die "Column with $table_columns columns?"; }
937 elsif ($table_columns == 2)
938 { print TEXI "\n\@table \@asis\n"; }
939 else
940 { print TEXI "\n\@multitable \@columnfractions";
941 for (my $i=0; $i<$table_columns; $i++)
942 { print TEXI " ", 1.0/$table_columns; }
943 print TEXI "\n"; } }
944 else
945 { if ($table_columns == 2)
946 { print TEXI "\n\@end table\n"; }
947 else
948 { print TEXI "\n\@end multitable\n"; }
949 undef $table_columns; } }
950 elsif (($tag eq "td") || ($tag eq "th"))
951 { if ($startflag)
952 { if ($table_first_column)
953 { print TEXI "\n\@item ";
954 $table_first_column = 0; }
955 elsif ($table_columns > 2)
956 { print TEXI "\n\@tab "; } }
957 else
958 { print TEXI "\n"; } }
959 elsif ($tag eq "tr")
960 { if ($startflag)
961 { $table_first_column = 1; } }
962 elsif ($tag eq "ul")
963 { if ($startflag)
964 { print TEXI "\n\@itemize \@bullet\n"; }
965 else
966 { print TEXI "\n\@end itemize\n"; } }
967 else
968 { print STDERR "\nBailing out\n";
969 $he->dump;
970 return 0; }
971
972 return 1;
973}
974
975sub print_pre ( $ )
976{ my ($he_pre) = check_args(1, @_);
977 if (!has_single_content_string($he_pre))
978 { die "Multiple or non-string content for <PRE>: ", @{$he_pre->content}; }
979 my $pre_content = $ {$he_pre->content}[0];
980 print TEXI "\n\@example";
981 print TEXI &texi_quote($pre_content);
982 print TEXI "\@end example\n";
983}
984
985sub table_columns ( $ )
986{ my ($table) = check_args(1, @_);
987 my $result = 0;
988 for my $row (@{$table->content})
989 { if ($row->tag ne "tr")
990 { $table->dump;
991 $row->dump;
992 die "Expected <TR> as table row."; }
993 $result = max($result, scalar(@{$row->content})); }
994 return $result;
995}
996
997
998###########################################################################
999### Utilities
1000###
1001
1002sub min ( $$ )
1003{ my ($x, $y) = check_args(2, @_);
1004 return ($x < $y) ? $x : $y;
1005}
1006
1007sub max ( $$ )
1008{ my ($x, $y) = check_args(2, @_);
1009 return ($x > $y) ? $x : $y;
1010}
1011
1012sub file_to_tree ( $ )
1013{ my ($file) = check_args(1, @_);
1014
1015 my $tree = new HTML::TreeBuilder;
1016 $tree->ignore_unknown(1);
1017 # $tree->warn(1);
1018 $tree->parse_file($file);
1019 cleanup_parse_tree($tree);
1020 return $tree
1021}
1022
1023
1024sub has_single_content ( $ )
1025{ my ($he) = check_args(1, @_);
1026 if (!ref $he)
1027 { # return 0;
1028 die "Non-reference argument: $he"; }
1029 my $ref_content = $he->content;
1030 if (!defined $ref_content)
1031 { return 0; }
1032 my @content = @{$ref_content};
1033 if (scalar(@content) != 1)
1034 { return 0; }
1035 return 1;
1036}
1037
1038
1039# Return true if the content of the element contains only one element itself,
1040# and that inner element has the specified tag.
1041sub has_single_content_with_tag ( $$ )
1042{ my ($he, $tag) = check_args(2, @_);
1043 if (!has_single_content($he))
1044 { return 0; }
1045 my $content = $ {$he->content}[0];
1046 if (!ref $content)
1047 { return 0; }
1048 my $content_tag = $content->tag;
1049 if (!defined $content_tag)
1050 { return 0; }
1051 return $content_tag eq $tag;
1052}
1053
1054sub has_single_content_string ( $ )
1055{ my ($he) = check_args(1, @_);
1056 if (!has_single_content($he))
1057 { return 0; }
1058 my $content = $ {$he->content}[0];
1059 if (ref $content)
1060 { return 0; }
1061 return 1;
1062}
1063
1064
1065# Return name, href, content. First two may be undefined; third is an array.
1066# I don't see how to determine if there are more attributes.
1067sub anchor_info ( $ )
1068{ my ($he) = check_args(1, @_);
1069 if ($he->tag ne "a")
1070 { $he->dump;
1071 die "passed non-anchor to anchor_info"; }
1072 my $name = $he->attr('name');
1073 my $href = $he->attr('href');
1074 my @content = ();
1075 { my $ref_content = $he->content;
1076 if (defined $ref_content)
1077 { @content = @{$ref_content}; } }
1078 return ($name, $href, @content);
1079}
1080
1081
1082sub texi_quote ( $ )
1083{ my ($text) = check_args(1, @_);
1084 $text =~ s/([\@\{\}])/\@$1/g;
1085 $text =~ s/ -- / --- /g;
1086 return $text;
1087}
1088
1089# Eliminate bad punctuation (that confuses Makeinfo or Info) for section titles.
1090sub texi_remove_punctuation ( $ )
1091{ my ($text) = check_args(1, @_);
1092
1093 $text =~ s/^ +//g;
1094 $text =~ s/[ :]+$//g;
1095 $text =~ s/^[1-9][0-9.]* +//g;
1096 $text =~ s/,//g;
1097 # Both embedded colons and " -- " confuse makeinfo. (Perhaps " -- "
1098 # gets converted into " - ", just as "---" would be converted into " -- ",
1099 # so the names end up differing.)
1100 # $text =~ s/:/ -- /g;
1101 $text =~ s/://g;
1102 return $text;
1103}
1104
1105
1106## Do not use this inside `traverse': it throws off the traversal. Use
1107## html_replace_by_ignore or html_replace_by_meta instead.
1108# Returns 1 if success, 0 if failure.
1109sub html_remove ( $;$ )
1110{ my ($he, $parent) = check_args_range(1, 2, @_);
1111 if (!defined $parent)
1112 { $parent = $he->parent; }
1113 my $ref_pcontent = $parent->content;
1114 my @pcontent = @{$ref_pcontent};
1115 for (my $i=0; $i<scalar(@pcontent); $i++)
1116 { if ($pcontent[$i] eq $he)
1117 { splice @{$ref_pcontent}, $i, 1;
1118 $he->parent(undef);
1119 return 1; } }
1120 die "Didn't find $he in $parent";
1121}
1122
1123
1124sub html_replace ( $$;$ )
1125{ my ($orig, $new, $parent) = check_args_range(2, 3, @_);
1126 if (!defined $parent)
1127 { $parent = $orig->parent; }
1128 my $ref_pcontent = $parent->content;
1129 my @pcontent = @{$ref_pcontent};
1130 for (my $i=0; $i<scalar(@pcontent); $i++)
1131 { if ($pcontent[$i] eq $orig)
1132 { $ {$ref_pcontent}[$i] = $new;
1133 $new->parent($parent);
1134 $orig->parent(undef);
1135 return 1; } }
1136 die "Didn't find $orig in $parent";
1137}
1138
1139sub html_replace_by_meta ( $;$ )
1140{ my ($orig, $parent) = check_args_range(1, 2, @_);
1141 my $meta = new HTML::Element "meta";
1142 if (!defined $parent)
1143 { $parent = $orig->parent; }
1144 return html_replace($orig, $meta, $parent);
1145}
1146
1147sub html_replace_by_ignore ( $;$ )
1148{ my ($orig, $parent) = check_args_range(1, 2, @_);
1149 my $ignore = new HTML::Element "ignore";
1150 if (!defined $parent)
1151 { $parent = $orig->parent; }
1152 return html_replace($orig, $ignore, $parent);
1153}
1154
1155
1156
1157###
1158### Collect text elements
1159###
1160
1161my @collected_texts;
1162my $collect_texts_stoppoint;
1163my $done_collecting;
1164
1165sub collect_texts ( $;$ )
1166{ my ($root, $stop) = check_args_range(1, 2, @_);
1167 # print STDERR "collect_texts: $root $stop\n";
1168 $collect_texts_stoppoint = $stop;
1169 $done_collecting = 0;
1170 @collected_texts = ();
1171 $root->traverse(\&collect_if_text); # process texts
1172 # print STDERR "collect_texts => ", join(";;;", @collected_texts), "\n";
1173 return @collected_texts;
1174}
1175
1176sub collect_if_text ( $$$ )
1177{ my $he = (check_args(3, @_))[0]; # ignore depth and startflag arguments
1178 if ($done_collecting)
1179 { return 0; }
1180 if (!defined $he)
1181 { return 0; }
1182 if (!ref $he)
1183 { push @collected_texts, $he;
1184 return 0; }
1185 if ((defined $collect_texts_stoppoint) && ($he eq $collect_texts_stoppoint))
1186 { $done_collecting = 1;
1187 return 0; }
1188 return 1;
1189}
1190
1191
1192###########################################################################
1193### Clean up parse tree
1194###
1195
1196sub cleanup_parse_tree ( $ )
1197{ my ($he) = check_args(1, @_);
1198 $he->traverse(\&delete_if_navigation, 'ignore text');
1199 $he->traverse(\&delete_extra_spaces, 'ignore text');
1200 $he->traverse(\&merge_dl, 'ignore text');
1201 return $he;
1202}
1203
1204
1205## Simpler version that deletes contents but not the element itself.
1206# sub delete_if_navigation ( $$$ )
1207# { my $he = (check_args(3, @_))[0]; # ignore startflag and depth
1208# if (($he->tag() eq "div") && ($he->attr('class') eq 'navigation'))
1209# { $he->delete();
1210# return 0; }
1211# else
1212# { return 1; }
1213# }
1214
1215sub delete_if_navigation ( $$$ )
1216{ my ($he, $startflag) = (check_args(3, @_))[0,1]; # ignore depth argument
1217 if (!$startflag)
1218 { return; }
1219
1220 if (($he->tag() eq "div") && (defined $he->attr('class')) && ($he->attr('class') eq 'navigation'))
1221 { my $ref_pcontent = $he->parent()->content();
1222 # Don't try to modify @pcontent, which appears to be a COPY.
1223 # my @pcontent = @{$ref_pcontent};
1224 for (my $i = 0; $i<scalar(@{$ref_pcontent}); $i++)
1225 { if (${$ref_pcontent}[$i] eq $he)
1226 { splice(@{$ref_pcontent}, $i, 1);
1227 last; } }
1228 $he->delete();
1229 return 0; }
1230 else
1231 { return 1; }
1232}
1233
1234sub delete_extra_spaces ( $$$ )
1235{ my ($he, $startflag) = (check_args(3, @_))[0,1]; # ignore depth argument
1236 if (!$startflag)
1237 { return; }
1238
1239 my $tag = $he->tag;
1240 if ($tag =~ /^(head|html|table|tr|ul)$/)
1241 { delete_child_spaces($he); }
1242 delete_trailing_spaces($he);
1243 return 1;
1244}
1245
1246
1247sub delete_child_spaces ( $ )
1248{ my ($he) = check_args(1, @_);
1249 my $ref_content = $he->content();
1250 for (my $i = 0; $i<scalar(@{$ref_content}); $i++)
1251 { if ($ {$ref_content}[$i] =~ /^ *$/)
1252 { splice(@{$ref_content}, $i, 1);
1253 $i--; } }
1254}
1255
1256sub delete_trailing_spaces ( $ )
1257{ my ($he) = check_args(1, @_);
1258 my $ref_content = $he->content();
1259 if (! defined $ref_content)
1260 { return; }
1261 # Could also check for previous element = /^h[1-6]$/.
1262 for (my $i = 0; $i<scalar(@{$ref_content})-1; $i++)
1263 { if ($ {$ref_content}[$i] =~ /^ *$/)
1264 { my $next_elt = $ {$ref_content}[$i+1];
1265 if ((ref $next_elt) && ($next_elt->tag =~ /^(br|dd|dl|dt|hr|p|ul)$/))
1266 { splice(@{$ref_content}, $i, 1);
1267 $i--; } } }
1268 if ($he->tag =~ /^(dd|dt|^h[1-6]|li|p)$/)
1269 { my $last_elt = $ {$ref_content}[$#{$ref_content}];
1270 if ((defined $last_elt) && ($last_elt =~ /^ *$/))
1271 { pop @{$ref_content}; } }
1272}
1273
1274
1275# If we find a paragraph that looks like
1276# <P>
1277# <HR>
1278# <UL>
1279# then accumulate its links into a contents_list and delete the paragraph.
1280sub process_if_child_links ( $$$ )
1281{ my ($he, $startflag) = (check_args(3, @_))[0,1]; # ignore depth argument
1282 if (!$startflag)
1283 { return; }
1284
1285 if ($he->tag() eq "p")
1286 { my $ref_content = $he->content();
1287 if (defined $ref_content)
1288 { my @content = @{$ref_content};
1289 if ((scalar(@content) == 2)
1290 && (ref $content[0]) && $content[0]->tag() eq "hr"
1291 && (ref $content[1]) && $content[1]->tag() eq "ul")
1292 { process_child_links($he);
1293 $he->delete();
1294 return 0; } } }
1295 return 1;
1296}
1297
1298
1299# If we find
1300# <H4>
1301# "Footnotes"
1302# <DL>
1303# <DT>
1304# <A NAME="foot560">
1305# "...borrow"
1306# <A HREF="refcountsInPython.html#tex2html2" NAME="foot560">
1307# "1.2"
1308# <DD>
1309# "The metaphor of ``borrowing'' a reference is not completely correct: the owner still has a copy of the reference. "
1310# ...
1311# then record the footnote information and delete the section and list.
1312
1313my $process_if_footnotes_expect_dl_next = 0;
1314
1315sub process_if_footnotes ( $$$ )
1316{ my ($he, $startflag) = (check_args(3, @_))[0,1]; # ignore depth argument
1317 if (!$startflag)
1318 { return; }
1319
1320 if (($he->tag() eq "h4")
1321 && has_single_content_string($he)
1322 && ($ {$he->content}[0] eq "Footnotes"))
1323 { html_replace_by_ignore($he);
1324 $process_if_footnotes_expect_dl_next = 1;
1325 return 0; }
1326
1327 if ($process_if_footnotes_expect_dl_next && ($he->tag() eq "dl"))
1328 { my $ref_content = $he->content();
1329 if (defined $ref_content)
1330 { $process_if_footnotes_expect_dl_next = 0;
1331 my @content = @{$ref_content};
1332 for (my $i=0; $i<$#content; $i+=2)
1333 { my $he_dt = $content[$i];
1334 my $he_dd = $content[$i+1];
1335 if (($he_dt->tag ne "dt") || ($he_dd->tag ne "dd"))
1336 { $he->dump;
1337 die "expected <DT> and <DD> at positions $i and ", $i+1; }
1338 my @dt_content = @{$he_dt->content()};
1339 if ((scalar(@dt_content) != 2)
1340 || ($dt_content[0]->tag ne "a")
1341 || ($dt_content[1]->tag ne "a"))
1342 { $he_dt->dump;
1343 die "Expected 2 anchors as content of <DT>"; }
1344 my ($dt1_name, $dt1_href, $dt1_content) = anchor_info($dt_content[0]);
1345 my ($dt2_name, $dt2_href, $dt2_content) = anchor_info($dt_content[0]);
1346 # unused: $dt1_href, $dt1_content, $dt2_href, $dt2_content
1347 if ($dt1_name ne $dt2_name)
1348 { $he_dt->dump;
1349 die "Expected identical names for anchors"; }
1350 html_replace_by_ignore($he_dd);
1351 $he_dd->tag("div"); # has no effect
1352 $footnotes{$dt1_name} = $he_dd; }
1353 html_replace_by_ignore($he);
1354 return 0; } }
1355
1356 if ($process_if_footnotes_expect_dl_next)
1357 { $he->dump;
1358 die "Expected <DL> for footnotes next"; }
1359
1360 return 1;
1361}
1362
1363
1364
1365## Merge two adjacent paragraphs containing <DL> items, such as:
1366# <P>
1367# <DL>
1368# <DT>
1369# ...
1370# <DD>
1371# ...
1372# <P>
1373# <DL>
1374# <DT>
1375# ...
1376# <DD>
1377# ...
1378
1379sub merge_dl ( $$$ )
1380{ my ($he, $startflag) = (check_args(3, @_))[0,1]; # ignore depth argument
1381 if (!$startflag)
1382 { return; }
1383
1384 my $ref_content = $he->content;
1385 if (!defined $ref_content)
1386 { return; }
1387 my $i = 0;
1388 while ($i < scalar(@{$ref_content})-1)
1389 { my $p1 = $ {$ref_content}[$i];
1390 if ((ref $p1) && ($p1->tag eq "p")
1391 && has_single_content_with_tag($p1, "dl"))
1392 { my $dl1 = $ {$p1->content}[0];
1393 # In this loop, rhs, not lhs, of < comparison changes,
1394 # because we are removing elements from the content of $he.
1395 while ($i < scalar(@{$ref_content})-1)
1396 { my $p2 = $ {$ref_content}[$i+1];
1397 if (!((ref $p2) && ($p2->tag eq "p")
1398 && has_single_content_with_tag($p2, "dl")))
1399 { last; }
1400 # Merge these two elements.
1401 splice(@{$ref_content}, $i+1, 1); # remove $p2
1402 my $dl2 = $ {$p2->content}[0];
1403 $dl1->push_content(@{$dl2->content}); # put $dl2's content in $dl1
1404 }
1405 # extra increment because next element isn't a candidate for $p1
1406 $i++; }
1407 $i++; }
1408 return 1;
1409}
1410
1411
1412
1413###########################################################################
1414### Testing
1415###
1416
1417sub test ( $$ )
1418{ my ($action, $file) = check_args(2, @_);
1419
1420 # General testing
1421 if (($action eq "view") || ($action eq ""))
1422 { # # $file = "/homes/gws/mernst/www/links.html";
1423 # # $file = "/homes/gws/mernst/www/index.html";
1424 # # $file = "/homes/fish/mernst/java/gud/doc/manual.html";
1425 # # $file = "/projects/cecil/cecil/doc/manuals/stdlib-man/stdlib/stdlib.html";
1426 # # $file = "/homes/fish/mernst/tmp/python-doc/html/index.html";
1427 # $file = "/homes/fish/mernst/tmp/python-doc/html/api/complexObjects.html";
1428 my $tree = file_to_tree($file);
1429
1430 ## Testing
1431 # print STDERR $tree->as_HTML;
1432 $tree->dump();
1433
1434 # print STDERR $tree->tag(), "\n";
1435 # print STDERR @{$tree->content()}, "\n";
1436 #
1437 # for (@{ $tree->extract_links(qw(a img)) }) {
1438 # my ($link, $linkelem) = @$_;
1439 # print STDERR "$link ", $linkelem->as_HTML;
1440 # }
1441 #
1442 # print STDERR @{$tree->extract_links()}, "\n";
1443
1444 # my @top_level_elts = @{$tree->content()};
1445
1446 # if scalar(@{$tree->content()})
1447 return;
1448 }
1449
1450 elsif ($action eq "raw")
1451 { my $tree = new HTML::TreeBuilder;
1452 $tree->ignore_unknown(1);
1453 # $tree->warn(1);
1454 $tree->parse_file($file);
1455
1456 $tree->dump();
1457
1458 # cleanup_parse_tree($tree);
1459 # $tree->dump();
1460 return;
1461 }
1462
1463 # Test dealing with a section.
1464 elsif ($action eq "section")
1465 { # my $file;
1466 # $file = "/homes/fish/mernst/tmp/python-doc/html/api/intro.html";
1467 # $file = "/homes/fish/mernst/tmp/python-doc/html/api/includes.html";
1468 # $file = "/homes/fish/mernst/tmp/python-doc/html/api/complexObjects.html";
1469 process_section_file($file, 0, "Title");
1470 }
1471
1472 # Test dealing with many sections
1473 elsif (0)
1474 { my @files = ("/homes/fish/mernst/tmp/python-doc/html/api/about.html",
1475 "/homes/fish/mernst/tmp/python-doc/html/api/abstract.html",
1476 "/homes/fish/mernst/tmp/python-doc/html/api/api.html",
1477 "/homes/fish/mernst/tmp/python-doc/html/api/cObjects.html",
1478 "/homes/fish/mernst/tmp/python-doc/html/api/complexObjects.html",
1479 "/homes/fish/mernst/tmp/python-doc/html/api/concrete.html",
1480 # "/homes/fish/mernst/tmp/python-doc/html/api/contents.html",
1481 "/homes/fish/mernst/tmp/python-doc/html/api/countingRefs.html",
1482 "/homes/fish/mernst/tmp/python-doc/html/api/debugging.html",
1483 "/homes/fish/mernst/tmp/python-doc/html/api/dictObjects.html",
1484 "/homes/fish/mernst/tmp/python-doc/html/api/embedding.html",
1485 "/homes/fish/mernst/tmp/python-doc/html/api/exceptionHandling.html",
1486 "/homes/fish/mernst/tmp/python-doc/html/api/exceptions.html",
1487 "/homes/fish/mernst/tmp/python-doc/html/api/fileObjects.html",
1488 "/homes/fish/mernst/tmp/python-doc/html/api/floatObjects.html",
1489 "/homes/fish/mernst/tmp/python-doc/html/api/front.html",
1490 "/homes/fish/mernst/tmp/python-doc/html/api/fundamental.html",
1491 # "/homes/fish/mernst/tmp/python-doc/html/api/genindex.html",
1492 "/homes/fish/mernst/tmp/python-doc/html/api/importing.html",
1493 "/homes/fish/mernst/tmp/python-doc/html/api/includes.html",
1494 "/homes/fish/mernst/tmp/python-doc/html/api/index.html",
1495 "/homes/fish/mernst/tmp/python-doc/html/api/initialization.html",
1496 "/homes/fish/mernst/tmp/python-doc/html/api/intObjects.html",
1497 "/homes/fish/mernst/tmp/python-doc/html/api/intro.html",
1498 "/homes/fish/mernst/tmp/python-doc/html/api/listObjects.html",
1499 "/homes/fish/mernst/tmp/python-doc/html/api/longObjects.html",
1500 "/homes/fish/mernst/tmp/python-doc/html/api/mapObjects.html",
1501 "/homes/fish/mernst/tmp/python-doc/html/api/mapping.html",
1502 "/homes/fish/mernst/tmp/python-doc/html/api/newTypes.html",
1503 "/homes/fish/mernst/tmp/python-doc/html/api/node24.html",
1504 "/homes/fish/mernst/tmp/python-doc/html/api/noneObject.html",
1505 "/homes/fish/mernst/tmp/python-doc/html/api/number.html",
1506 "/homes/fish/mernst/tmp/python-doc/html/api/numericObjects.html",
1507 "/homes/fish/mernst/tmp/python-doc/html/api/object.html",
1508 "/homes/fish/mernst/tmp/python-doc/html/api/objects.html",
1509 "/homes/fish/mernst/tmp/python-doc/html/api/os.html",
1510 "/homes/fish/mernst/tmp/python-doc/html/api/otherObjects.html",
1511 "/homes/fish/mernst/tmp/python-doc/html/api/processControl.html",
1512 "/homes/fish/mernst/tmp/python-doc/html/api/refcountDetails.html",
1513 "/homes/fish/mernst/tmp/python-doc/html/api/refcounts.html",
1514 "/homes/fish/mernst/tmp/python-doc/html/api/sequence.html",
1515 "/homes/fish/mernst/tmp/python-doc/html/api/sequenceObjects.html",
1516 "/homes/fish/mernst/tmp/python-doc/html/api/standardExceptions.html",
1517 "/homes/fish/mernst/tmp/python-doc/html/api/stringObjects.html",
1518 "/homes/fish/mernst/tmp/python-doc/html/api/threads.html",
1519 "/homes/fish/mernst/tmp/python-doc/html/api/tupleObjects.html",
1520 "/homes/fish/mernst/tmp/python-doc/html/api/typeObjects.html",
1521 "/homes/fish/mernst/tmp/python-doc/html/api/types.html",
1522 "/homes/fish/mernst/tmp/python-doc/html/api/utilities.html",
1523 "/homes/fish/mernst/tmp/python-doc/html/api/veryhigh.html");
1524 for my $file (@files)
1525 { print STDERR "\n", "=" x 75, "\n", "$file:\n";
1526 process_section_file($file, 0, "Title");
1527 }
1528 }
1529
1530 # Test dealing with index.
1531 elsif ($action eq "index")
1532 { # my $file;
1533 # $file = "/homes/fish/mernst/tmp/python-doc/html/api/genindex.html";
1534
1535 process_index_file($file, "\@cindex");
1536 print_index_info();
1537 }
1538
1539 else
1540 { die "Unrecognized action `$action'"; }
1541}
1542
1543
1544###########################################################################
1545### Main loop
1546###
1547
1548sub process_contents_file ( $ )
1549{ my ($file) = check_args(1, @_);
1550
1551 # could also use File::Basename
1552 my $info_file = $file;
1553 $info_file =~ s/(\/?index)?\.html$//;
1554 if ($info_file eq "")
1555 { chomp($info_file = `pwd`); }
1556 $info_file =~ s/^.*\///; # not the most efficient way to remove dirs
1557
1558 $html_directory = $file;
1559 $html_directory =~ s/(\/|^)[^\/]+$/$1/;
1560
1561 my $texi_file = "$info_file.texi";
1562 open(TEXI, ">$texi_file");
1563
1564 print TEXI "\\input texinfo \@c -*-texinfo-*-\n";
1565 print TEXI "\@c %**start of header\n";
1566 print TEXI "\@setfilename $info_file\n";
1567
1568 # 2. Summary Description and Copyright
1569 # The "Summary Description and Copyright" segment describes the
1570 # document and contains the copyright notice and copying permissions
1571 # for the Info file. The segment must be enclosed between `@ifinfo'
1572 # and `@end ifinfo' commands so that the formatters place it only in
1573 # the Info file.
1574 #
1575 # The summary description and copyright segment does not appear in the
1576 # printed document.
1577 #
1578 # @ifinfo
1579 # This is a short example of a complete Texinfo file.
1580 #
1581 # Copyright @copyright{} 1990 Free Software Foundation, Inc.
1582 # @end ifinfo
1583
1584
1585 # 3. Title and Copyright
1586 # The "Title and Copyright" segment contains the title and copyright
1587 # pages and copying permissions for the printed manual. The segment
1588 # must be enclosed between `@titlepage' and `@end titlepage'
1589 # commands. The title and copyright page appear only in the printed
1590 # manual.
1591 #
1592 # The titlepage segment does not appear in the Info file.
1593 #
1594 # @titlepage
1595 # @sp 10
1596 # @comment The title is printed in a large font.
1597 # @center @titlefont{Sample Title}
1598 #
1599 # @c The following two commands start the copyright page.
1600 # @page
1601 # @vskip 0pt plus 1filll
1602 # Copyright @copyright{} 1990 Free Software Foundation, Inc.
1603 # @end titlepage
1604
1605
1606 # 4. `Top' Node and Master Menu
1607 # The "Master Menu" contains a complete menu of all the nodes in the
1608 # whole Info file. It appears only in the Info file, in the `Top'
1609 # node.
1610 #
1611 # The `Top' node contains the master menu for the Info file. Since a
1612 # printed manual uses a table of contents rather than a menu, the master
1613 # menu appears only in the Info file.
1614 #
1615 # @node Top, First Chapter, , (dir)
1616 # @comment node-name, next, previous, up
1617 #
1618 # @menu
1619 # * First Chapter:: The first chapter is the
1620 # only chapter in this sample.
1621 # * Concept Index:: This index has two entries.
1622 # @end menu
1623
1624
1625
1626 $current_ref_tdf = [ "Top", 0, $ARGV[0] ];
1627 process_section_file($file, 0, "Top");
1628 while (scalar(@contents_list))
1629 { $current_ref_tdf = shift @contents_list;
1630 process_section_file($ {$current_ref_tdf}[2], $ {$current_ref_tdf}[1], $ {$current_ref_tdf}[0]);
1631 }
1632
1633 print TEXI "\n";
1634 for my $indextitle (@index_titles)
1635 { print TEXI "\@node $indextitle\n";
1636 print TEXI "\@unnumbered $indextitle\n";
1637 print TEXI "\@printindex $ {$index_info{$indextitle}}[1]\n";
1638 print TEXI "\n"; }
1639
1640 print TEXI "\@contents\n";
1641 print TEXI "\@bye\n";
1642 close(TEXI);
1643}
1644
1645# This needs to be last so global variable initializations are reached.
1646
1647if (scalar(@ARGV) == 0)
1648{ die "No arguments supplied to html2texi.pl"; }
1649
1650if ($ARGV[0] eq "-test")
1651{ my @test_args = @ARGV[1..$#ARGV];
1652 if (scalar(@test_args) == 0)
1653 { test("", "index.html"); }
1654 elsif (scalar(@test_args) == 1)
1655 { test("", $test_args[0]); }
1656 elsif (scalar(@test_args) == 2)
1657 { test($test_args[0], $test_args[1]); }
1658 else
1659 { die "Too many test arguments passed to html2texi: ", join(" ", @ARGV); }
1660 exit();
1661}
1662
1663if (scalar(@ARGV) != 1)
1664{ die "Pass one argument, the main/contents page"; }
1665
1666process_contents_file($ARGV[0]);