1 /* Copyright 2008 James Bunton <jamesbunton@fastmail.fm>
2 * Licensed for distribution under the GPL version 2.
4 * Dump the contents of the OSX address book as a Mutt alias file
8 #import <Foundation/Foundation.h>
9 #import <AddressBook/AddressBook.h>
13 NSPrint(NSString* format, ...)
16 va_start(args, format);
17 NSString* string = [[NSString alloc] initWithFormat:format arguments:args];
19 [string writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];
24 @interface NSString (james)
25 -(NSString*) keepOnlyCharacterSet:(NSCharacterSet*)keepChars;
27 @implementation NSString (james)
29 keepOnlyCharacterSet:(NSCharacterSet*)keepChars;
31 NSMutableString* ret = [[NSMutableString alloc] init];
32 NSScanner* scanner = [NSScanner scannerWithString:self];
34 while(![scanner isAtEnd]) {
35 if([scanner scanCharactersFromSet:keepChars intoString:&temp]) {
36 [ret appendString:temp];
38 [scanner setScanLocation:1+[scanner scanLocation]];
41 return [ret autorelease];
47 printMuttAlias(NSString* key, NSString* firstName, NSString* lastName, ABMultiValue* emails)
49 key = [[key lowercaseString] keepOnlyCharacterSet:[NSCharacterSet lowercaseLetterCharacterSet]];
51 for(unsigned int i = 0; i < [emails count]; ++i) {
52 NSString* keySuffix = @"";
54 keySuffix = [NSString stringWithFormat:@"%d", i];
56 NSPrint(@"alias %@%@ \"%@ %@\" <%@>\n", key, keySuffix, firstName, lastName, [emails valueAtIndex:i]);
63 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
65 for(ABPerson* person in [[ABAddressBook sharedAddressBook] people]) {
66 NSString* firstName = [[person valueForProperty:kABFirstNameProperty] description];
67 NSString* lastName = [[person valueForProperty:kABLastNameProperty] description];
68 NSString* nickName = [[person valueForProperty:kABNicknameProperty] description];
69 // WTF does ABMultiValue exist for? No fast enumeration? What's wrong with NSArray?!
70 ABMultiValue* emails = [person valueForProperty:kABEmailProperty];
72 if([emails count] == 0) {
76 // Generate an entry for Nick and FirstLast
77 if([nickName length] > 0) {
78 printMuttAlias(nickName, firstName, lastName, emails);
80 if([firstName length] > 0 && [lastName length] > 0) {
81 NSString* key = [NSString stringWithFormat:@"%@%@", firstName, lastName];
82 printMuttAlias(key, firstName, lastName, emails);