<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl
#
# muttbook 1.0
#
#  ** search the Mac OS X Address Book from Mutt.
#  Based on an ugly, hackish ObjC version I wrote years ago.
#  See end of this file for documentation.
#
# $Rev: 1 $
# $Date: 2008-07-27 00:14:33 -0400 (Sun, 27 Jul 2008) $
#
# Copyright (c) 2008, Jeremy Nixon
# 
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer. Redistributions
# in binary form must reproduce the above copyright notice, this list of
# conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# 
# Neither the name of the author nor the names of any contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use Foundation;
use strict;

# These are basically magic values. We are not providing a full AddressBook
# interface here, just what we need.
use constant kABNotEqual =&gt; 1;
use constant kABContainsSubStringCaseInsensitive =&gt; 8;
use constant kABSearchOr =&gt; 1;
use constant kABShowAsCompany =&gt; 1;

use constant kABEmailProperty     =&gt; 'Email';
use constant kABFirstNameProperty =&gt; 'First';
use constant kABLastNameProperty  =&gt; 'Last';
use constant kABOrganizationProperty =&gt; 'Organization';
use constant kABPersonFlags =&gt; 'ABPersonFlags';

# Load the AddressBook framework.
my $abframework = NSBundle-&gt;alloc-&gt;initWithPath_('/System/Library/Frameworks/AddressBook.framework');
unless ($abframework and $$abframework) {
    die "Couldn't init AddressBook.framework";
}
$abframework-&gt;load;
if (not $abframework-&gt;isLoaded) {
    die "Couldn't load AddressBook.framework";
}

sub main {
    my $search = shift;

    my $result = ab_fullsubsearch($search);

    # Go through each match and extract the relevent data, possibly to print.
    my $i = obj_enumerator($result);
    my $namehas;
    my @results;
    while (defined(my $person = $i-&gt;())) {
        my $email = $person-&gt;valueForProperty_(kABEmailProperty);
        next unless ($email and $$email);

        # If the entry is a "company" we want the company name.
        # If not, we want the first and last name.
        my $fullname;
        my $flags = $person-&gt;valueForProperty_(kABPersonFlags); # NSNumber
        if ($flags and $$flags) {
            $flags = $flags-&gt;intValue;
        } else {
            $flags = 0;
        }
        if ($flags &amp; kABShowAsCompany) {
            my $org = $person-&gt;valueForProperty_(kABOrganizationProperty);
            if ($org and $$org) {
                $fullname = $org-&gt;UTF8String;
            } else {
                $fullname = '';
            }
        } else {
            my $first = $person-&gt;valueForProperty_(kABFirstNameProperty);
            my $last = $person-&gt;valueForProperty_(kABLastNameProperty);

            if ($first and $$first and $last and $$last) {
                $fullname = $first-&gt;UTF8String .' '. $last-&gt;UTF8String;
            } else {
                $fullname = ($first and $$first) ? $first-&gt;UTF8String :
                            ($last and $$last) ? $last-&gt;UTF8String : '';
            }
        }
        if (index(lc($fullname),lc($search)) &gt; -1) {
            $namehas = 1;
        }

        # If the email address has multiple values, check each one.
        # If the match was due to only one of the addresses, we don't
        # want to print non-matching entries. We only want to print
        # entries for addresses that match, or all of them if the
        # name itself was the match.
        if ($email-&gt;isKindOfClass_(ABMultiValue-&gt;class)) {
            my $c = $email-&gt;count;
            my $i = 0;
            while ($i &lt; $c) {
                my $e = $email-&gt;valueAtIndex_($i);
                my $t = $email-&gt;labelAtIndex_($i);
                $t = $t-&gt;UTF8String;
                my $emailhas;
                if (index(lc($e-&gt;UTF8String),lc($search)) &gt; -1) {
                    $emailhas = 1;
                }

                # PerlObjCBridge can't get us to ABLocalizedPropertyOrLabel,
                # so we just wing it here.
                if ($t =~ /^_\$!\&lt;(\w+)\&gt;!\$_/) {
                    $t = lc($1);
                }

                my $estr = $e-&gt;UTF8String;
                if (defined($estr) and length($estr) and ($namehas or $emailhas)) {
                    push @results, "$estr\t$fullname\t$t";
                }
                $i++;
            }
        } else {
            my $estr = $email-&gt;UTF8String;
            if (defined($estr) and length($estr)) {
                push @results, "$estr\t$fullname";
            }
        }
    }
    my $count = scalar @results;
    if (not $count) {
        print "no matches.\n";
    } elsif ($count == 1) {
        print "1 matching record.\n";
    } else {
        print "$count matching records.\n";
    }
    foreach my $item (@results) {
        print "$item\n";
    }
}

# Return value is an NSArray.
sub ab_fullsubsearch {
    my $str = shift;
    my $abook = ABAddressBook-&gt;sharedAddressBook;

    if (defined($str) and length($str)) {
        my $se1 = ABPerson-&gt;searchElementForProperty_label_key_value_comparison_(
            kABEmailProperty,
            0,0,
            $str,
            kABContainsSubStringCaseInsensitive);
        my $se2 = ABPerson-&gt;searchElementForProperty_label_key_value_comparison_(
            kABFirstNameProperty,
            0,0,
            $str,
            kABContainsSubStringCaseInsensitive);
        my $se3 = ABPerson-&gt;searchElementForProperty_label_key_value_comparison_(
            kABLastNameProperty,
            0,0,
            $str,
            kABContainsSubStringCaseInsensitive);
    
        my $children = NSMutableArray-&gt;arrayWithCapacity_(3);
        foreach my $item ($se1,$se2,$se3) {
            $children-&gt;addObject_($item);
        }
    
        my $srch = ABSearchElement-&gt;searchElementForConjunction_children_(kABSearchOr,$children);
        my $results = $abook-&gt;recordsMatchingSearchElement_($srch);
        return $results;
    }
    # If no query specified, get all records with email addresses.
    my $se = ABPerson-&gt;searchElementForProperty_label_key_value_comparison_(
        kABEmailProperty,0,0,0,kABNotEqual);
    my $results = $abook-&gt;recordsMatchingSearchElement_($se);
    return $results;
}

# return an iterator for the given NSDictionary or NSArray.
sub obj_enumerator {
    my $obj = shift;
    my $enum = $obj-&gt;objectEnumerator;
    return sub {
        my $val = $enum-&gt;nextObject;
        if ($$val) { return $val } # check for nil object.
        return undef;
    };
}

main(@ARGV);

package ABAddressBook;
use base qw(PerlObjCBridge);

package ABPerson;
use base qw(PerlObjCBridge);

package ABSearchElement;
use base qw(PerlObjCBridge);

package ABMultiValue;
use base qw(PerlObjCBridge);

__END__
=pod

=head1 NAME

muttbook - allow Mutt to search the OS X Address Book

=head1 README

This script allows the Mutt email client to perform its address book
searches using your OS X system Address Book. It simply performs a search
using the provided string, against the name and email address fields of
your address book, and returns the results in the format Mutt expects.

Place the script somewhere on your PATH, and add something like this to
your .muttrc file:

 set query_command = "muttbook '%s'"
 bind editor &lt;tab&gt; complete-query

Now, in mutt, when prompted for an email address, enter a substring and
hit tab, and you will get a menu of matching entries.

=head1 PREREQUISITES

Requires Apple's C&lt;PerlObjCBridge&gt; module(s). At the time of this writing,
Apple hasn't yet open-sourced this code, so you can't compile it with a
custom Perl installation. Therefore, this script should be run using the
Apple-supplied Perl.

=head1 OSNAMES

Specific to Mac OS X (C&lt;darwin&gt;).

=head1 SCRIPT CATEGORIES

Mail

=head1 STATUS

"Works for me."

=head1 LICENSE

Released under a BSD license.

=head1 AUTHOR

Jeremy Nixon &lt;jnixon@cpan.org&gt;
</pre></body></html>