header

Torsten Curdt’s weblog

Service to convert to HTML entities

Lately I was looking for nice way to convert special characters to their entity equivalent. Of course there are editors out there that can do this for you. But what if I need this inside a textarea form field in my browser? You would have to cut-and-past it back and forth. Works – but is not convenient. Actually this one of the areas where one of the most forgotten OSX feature -a service- would be good.

The HTML Character Converter does exactly that. But frankly speaking I did not want to pay any money for something that simple. So I thought it would be a good exercise to get a bit more into Cocoa and Objective-C. The Apple “SimpleService” example was good starting point …but a mate of mine showed me a much easier and supposedly better way. The general idea is the same though. You have a function that acts as a service that can be executed from any program (if applicable). So first we define the service itself.


@interface QuotingServiceProvider : NSObject {
}

- (void)doQuotingService:(NSPasteboard *)pboard
                userData:(NSString *)data
                   error:(NSString **)error;

Opposed to what the Apple example does we don’t tinker with main() function though. We let the nib create the service as a custom class. Once the application has finished launching we have it self register as a service.


 - (void)applicationDidFinishLaunching:(NSNotification *)notification {
        [NSApp setServicesProvider:self];
 }

One thing that is common and required for both approaches is that you have to “announce” your service in the Info.plist file by adding a section like this.


<key>NSServices</key>
<array>
        <dict>
                <key>NSMenuItem</key>
                <dict>
                        <key>default</key>
                        <string>Quote String</string>
                </dict>
                <key>NSMessage</key>
                <string>doQuotingService</string>
                <key>NSPortName</key>
                <string>QuotingService</string>
                <key>NSReturnTypes</key>
                <array>
                        <string>NSStringPboardType</string>
                </array>
                <key>NSSendTypes</key>
                <array>
                        <string>NSStringPboardType</string>
                </array>
        </dict>
</array>

Have a look at the “doCapitalizeService” in Apple’s “SimpleService” to get an idea how to access and then return the modified data. From there it’s easy …but probably not really worth finishing. As it turns out there is already something that does exactly that for free. Just install the UnicodeChecker. It’s an incredible useful tool if you have to tinker with all different kind of encodings …and it also provides a service “Unicode <-> HTML entities”.

    blog comments powered by Disqus