HTML Encoder in Pasteboard

Before posting more, I needed an html encoder in Pasteboard to change <,>,&,… into <,>&… before pasting into in <pre>code-here</pre>.

I copy text/code into Pasteboard by cmd+c, run the program and cmd+v to paste the encoded string.

AppDelegate.m

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSPasteboard*  pasteBoard  = [NSPasteboard generalPasteboard];
    // get string from the pasteboard
    NSString* copiedString = [pasteBoard stringForType:NSPasteboardTypeString];
    // html encode
    NSString* encodedString = [NSString HtmlEncode:copiedString];
    // copy it into the pasteboard
    [pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil];
    [pasteBoard setString:encodedString forType:NSStringPboardType];
    
    // quit the app
    [[NSApplication sharedApplication] terminate:self];
}

NSString+HTML.h/.m

#import <Foundation/Foundation.h>

@interface NSString (HTML)

+ (NSString*)HtmlEncode:(NSString*)htmlString;

@end

#import "NSString+HTML.h"

@implementation NSString (HTML)

+ (NSString*)HtmlEncode:(NSString*)htmlString {
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"&"  withString:@"&amp;"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<"  withString:@"&lt;"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@">"  withString:@"&gt;"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"""" withString:@"&quot;"];    
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"'"  withString:@"&#039;"];
    return htmlString;
}

@end

Leave a Reply

Your email address will not be published. Required fields are marked *