#!/usr/bin/perl
# The HTML viewer to call, can be anything, for instance firefox -remote.
my $viewer = 'links';
# Paths to search.
my @dirs = qw(/usr/share/gtk-doc/html);

if (not @ARGV or scalar @ARGV > 1) {
    print "gtkdoc-view SYMBOL\n";
    exit 1;
}
my $id = mangle($ARGV[0]);
my $regexp = "^<ANCHOR\\s+id=\"$id\"\\s+href=\"([^\"]+)\">\$";

undef $/;
for my $dir (@dirs) {
    search_dir($dir, $id);
}
exit 1;

sub search_dir {
    my ($dir, $term) = @_;
    my $file = "$dir/index.sgml";
    if (-f "$file") {
        search_index($file, $term);
        return;
    }

    my @subdirs;
    opendir DIR, $dir || return;
    for $file (readdir DIR) {
        next if $file eq '.' or $file eq '..';
        push @subdirs, "$dir/$file" if -d "$dir/$file";
    }
    closedir DIR;
    for $file (@subdirs) {
        search_dir($file);
    }
}

sub search_index {
    my ($file, $id) = @_;
    my ($name, $link);
    open FILE, $file || return;
    my $text = <FILE>;
    close FILE;
    if ($text =~ m/$regexp/m) {
        my $link = $1;
        $file =~ s#/[^/]+/[^/]+$##;
        exec $viewer, "file://$file/$link";
    }
}

sub mangle {
    my ($id) = @_;
    if ($id eq "_") { return "gettext-macro"; }
    if ($id !~ /[a-z]/) { $id .= ":CAPS" };
    $id =~ s/[_ ]/-/g;
    $id =~ s/[,\.]//g;
    $id =~ s/^-*//;
    $id =~ s/::/-/g;
    if ($id !~ /:CAPS$/) { $id =~ s/:/--/g }
    return $id;
}

