CocoaDev

Edit AllPages

This is a subclass of General/NSFormatter that will auto-complete General/URLs based on the string passed by the user, much like Safari will do.

It will also accept properly-formatted General/URLs of any other type and do simple percent escape corrections.

This formatter will translate:

“www.somehost.com” to “http://www.somehost.com”

“somehost” to “http://www.somehost.com/”

“apple/developer” to “http://www.apple.com/developer”

“someone@somehost.com” to “mailto:someone@somehost.com”

“someone@somehost” to “mailto:someone@somehost.com”

“someone at somehost” to “mailto:someone@somehost.com”

“somehost/bad address” to “http://www.somehost.com/bad%20address”

“http://www.somehost.com/bad address” to “http://www.somehost.com/bad%20address”

It does most of its magic by depending on the fact that [NSURL General/URLWithString:] will return nil if it’s not passed a properly formatted URL string.

Header:

#import <Cocoa/Cocoa.h>

@interface General/URLFormatter : General/NSFormatter {

}

@end

Source

#import “General/URLFormatter.h”

@implementation General/URLFormatter

/* given a string that may be a http URL, try to massage it into an RFC-compliant http URL string */

/* given a string that may be a mailto: URL, try to massage it into an RFC-compliant mailto URL string */

/* given a string that may be an URL of some sort, try to massage it into an RFC-compliant http URL string */

// This method just returns the string - it’s here for compatibility with Cocoa Bindings

@end

Please use it any way you would like, but if you modify it, please post the changes for everyone’s sake.


Added editingStringForObjectValue: method for compatibility with Cocoa Bindings. It seems that Cocoa Bindings were calling stringForObjectValue: whenever the General/NSTextField was edited, causing an exception from NSURL. – Adam ‘Raddish’ Radestock