#!/usr/local/bin/perl
#  Time-stamp: "2006-04-18 18:07:16 ADT"  sburke@cpan.org
#
# desc{   Searches the emacs load-path for files matching your regexp.   }
#
#  Example:
#     where_emacs dissociate.el
#     where_emacs  'is+oc'
#
# This is an example of getting elisp to talk to Perl, via
#  (princ (mapconcat 'prin1-to-string SEQUENCE ", "))
#
# Now,
#   emacs --batch --eval '(print (locate-library "dissociate.el"))'
# would do something like the same, but wouldn't provide RE matching.

use strict;
die "Usage: where_emacs [regexp]\n" unless @ARGV;
my $it = $ARGV[0];

# test the validity of the regexp
eval { '' =~ /$it/o };
die "bad regexp: $@\n" if $@;

open(IN, "-|")  # yes, that funny fork-and-open
    || exec qw(emacs --batch --eval), <<EOLISP;
(princ (mapconcat 'prin1-to-string load-path '", "))

EOLISP

my $load_path = join(' ', <IN>);  close(IN);

my @load_path = eval("($load_path)");
die "Error in eval: $@" if $@;
die "No \@load_path" unless @load_path;

# for just a straight implementation of locate-library:
#   foreach (@load_path) { print "$_/$it\n" if -e "$_/$it"; }

foreach my $dir (@load_path) {
    next unless -e $dir && -d _ && -r _;
    next unless opendir(INDIR, $dir);
    print map "$dir/$_\n", sort grep /$it/o, readdir(INDIR);
    close(INDIR);
}

__END__
