#!/usr/bin/perl

# Batch syntax highlighting of a source " la Kate" with line numbers,
# my two cents!
# usage: hilite foo.pas > foo.pas.html

# THIS tool SHOULD BELONG TO Kate to be absolutely consistent
# with whatever behaviour of Kate and plugins happens to be locally.
# Unfortunately not easy to do without experience in KDE development tools.

# NOTE: autom. language identification is mostly correct from the file name
# This is why stdin is not used as there would be a need of some option to
# choose the ad hoc variant of the syntax highlighter.
# BUG: "#" comments in a Makefile are not highlighted as comments...

require Syntax::Highlight::Engine::Kate;
use Syntax::Highlight::Engine::Kate::All;
use File::Basename;

my $hl = new Syntax::Highlight::Engine::Kate(
	substitutions => {
		"<" => "&lt;",
		">" => "&gt;",
		"&" => "&amp;",
		" " => "&nbsp;",
		"\t" => "&nbsp;&nbsp;&nbsp;",
		"\n" => "<BR>\n"
	},
	format_table => { # TODO replace obsolete font by span
		Alert =>        ["<font color=\"#0000ff\">", "</font>"],
		BaseN =>        ["<font color=\"#007f00\">", "</font>"],
		BString =>      ["<font color=\"#c9a7ff\">", "</font>"],
		Char =>         ["<font color=\"#ff00ff\">", "</font>"],
		Comment =>      ["<font color=\"#7f7f7f\"><i>", "</i></font>"],
		DataType =>     ["<font color=\"#0000ff\">", "</font>"],
		DecVal =>       ["<font color=\"#00007f\">", "</font>"],
		Error =>        ["<font color=\"#ff0000\"><b><i>", "</i></b></font>"],
		Float =>        ["<font color=\"#00007f\">", "</font>"],
		Function =>     ["<font color=\"#007f00\">", "</font>"],
		IString =>      ["<font color=\"#ff0000\">", ""],
		Keyword =>      ["<b>", "</b>"],
		Normal =>       ["", ""],
		Operator =>     ["<font color=\"#009961\"><b>", "</b></font>"],
		Others =>       ["<font color=\"#b03060\">", "</font>"],
		RegionMarker => ["<font color=\"#96b9ff\"><i>", "</i></font>"],
		Reserved =>     ["<font color=\"#9b30ff\"><b>", "</b></font>"],
		String =>       ["<font color=\"#ff0000\">", "</font>"],
		Variable =>     ["<font color=\"#0000ff\"><b>", "</b></font>"],
		Warning =>      ["<font color=\"#0000ff\"><b><i>", "</b></i></font>"]
	}
);
my $fi = $ARGV[0];
$hl->languageAutoSet($fi);
my $lng = $hl->language;
open(FI,"< $fi") or die $!;
if ($lng ne "Off") {
	print "<html>\n<head>\n</head>\n<body>\n";
	print '<span style="font-family:monospace;">'."\n";
	my $n = 0;
	while (my $in = <FI>) {
		$n += 1;
		$s0 = "&nbsp;"x(4 - length($n))."$n"."&nbsp;";
		my $s1 = $hl->highlightText($in);
		print '<small><small><span style="color: rgb(140,140,200);">'.$s0.'</span></small></small>'.$s1;
	}
	print "</span>\n</body>\n</html>\n";
} else {
	print "Unknown language!";
	# TODO output in a <pre></pre> html block
}
