#!/usr/bin/env perl

# converts vim documentation to simple html
# Sirtaj Singh Kang (taj@kde.org)

# Wed Oct  8 01:15:48 EST 1997

$date = `date`;
chop $date;

%url = ();

# Read the specified tag file.  For each tag, convert the filename into a
# hyperlink and save it in an associative array using the tag as the index.
sub readTagFile
{
	my($tagfile) = @_;
	local( $tag, $file, $name );

	open(TAGS,"$tagfile") || die "can't read tags\n";

	while( <TAGS> ) {
		s/</&lt;/g;
		s/>/&gt;/g;

		# For each line in the tag file, save the first two items
		# into backreferences, the first holding the tag itself,
		# and the second holding the file containing the tag.
		/^(.*)\t(.*)\t/;

		$tag = $1;
		($file= $2) =~ s/.txt$/.html/g;

		$url{ $tag } = "<A HREF=\"$file#$tag\">$tag</A>";

		#print "($tag, $file, $tag)\n";
	}
	close( TAGS );
}

# Convert the specified text file into an html file.  For each line in the
# file, convert any words between asterices into page anchors, and convert
# any words between bar characters into hyperlinks.
sub vim2html
{
	my( $infile ) = @_;
	local( $outfile );

	open(IN, "$infile" ) || die "Couldn't read from $infile.\n";

	# Strip off any path information from the supplied filename.
	# TODO: will this work on DOS paths using a backslash?
	($outfile = $infile) =~ s%.*/%%g;
	$outfile =~ s/\.txt$//g;

	open( OUT, ">$outfile.html" )
			|| die "Couldn't write to $outfile.html.\n";

	print OUT<<EOF;
<HTML>
<HEAD><TITLE>$outfile</TITLE></HEAD>
<BODY BGCOLOR="#ffffff">
<H1>Vim Documentation: $outfile</H1>
<HR>
<PRE>
EOF

	while( <IN> ) {
		s/</&lt;/g;
		s/>/&gt;/g;

		# Convert tags between asterices into page targets
		s/\*([^*\s]*)\*/\*<A NAME="$1"><B>$1<\/B><\/A>\*/g;

		# Convert tags between bars into hyperlinks
		s/\|([^|\s]*)\|/\|$url{$1}\|/g;

		print OUT $_;
	}
	print OUT<<EOF;
</PRE>
<p><i>Generated by vim2html on $date</i></p>
</BODY>
</HTML>
EOF

}

# Display the usage information for the script.
sub usage
{
die<<EOF;
vim2html.pl: converts vim documentation to HTML.
usage:

	vim2html.pl <tag file> <text files>
EOF
}

# Main processing

if ( scalar(@ARGV) < 2 ) {
	usage();
}

print "Processing tags...\n";
readTagFile( $ARGV[ 0 ] );

# Individually process each file pattern supplied on the command line.
foreach $file ( 1..$#ARGV ) {
    # Process each pattern as if it contains wildcards.
    while ($filename = <$ARGV[$file]>) {
	print "Processing ".$filename."...\n";
	vim2html( $filename );
    }
}
