#import "TextParsingHelper.h" NS_ASSUME_NONNULL_BEGIN @implementation TextParsingHelper + (NSMutableDictionary *)parseText:(NSString *)text { if (!text || [text length] == 0) { return nil; } NSArray *lines = [text componentsSeparatedByString:@"\n"]; if ([lines count] == 0) { return nil; } NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; NSMutableString *notes = nil; BOOL processingNotes = NO; for (NSInteger i = 0; i < [lines count]; i++) { NSString *line = [lines objectAtIndex:i]; // The first line is always interpreted as the title. No matter what. Notes start with >> if (i == 0) { NSRange rangeOfSeparator = [line rangeOfString:@">>"]; if (rangeOfSeparator.location != NSNotFound) { NSString *title = [line substringToIndex:rangeOfSeparator.location]; NSString *notesPart = [line substringFromIndex:rangeOfSeparator.location + 2]; if ([title length] > 0) { [result setObject:title forKey:@"title"]; } if ([notesPart length] > 0) { notes = [[NSMutableString alloc] initWithString:notesPart]; processingNotes = YES; } } else { if ([line length] > 0) { [result setObject:line forKey:@"title"]; } } } else { if ([line length] > 0) { unichar firstChar = [line characterAtIndex:0]; // Once we encounter a special line, we stop parsing notes. if (firstChar == '#' || firstChar == '@' || firstChar == '!') { processingNotes = NO; NSString *content = nil; if ([line length] > 1) { content = [line substringFromIndex:1]; } if (content && [content length] > 0) { switch (firstChar) { case '#': if (![result objectForKey:@"tags"]) { [result setObject:content forKey:@"tags"]; } break; case '@': if (![result objectForKey:@"when"]) { [result setObject:content forKey:@"when"]; } break; case '!': if (![result objectForKey:@"deadline"]) { [result setObject:content forKey:@"deadline"]; } break; } } } else if (processingNotes) { if (notes) { [notes appendString:@"\n"]; [notes appendString:line]; } else { notes = [[NSMutableString alloc] initWithString:line]; } } } else if (processingNotes) { // This is an empty notes line if (notes) { [notes appendString:@"\n"]; } } } } if (notes && [notes length] > 0) { [result setObject:[NSString stringWithString:notes] forKey:@"notes"]; } if (notes) { [notes release]; } if ([result count] == 0) { [result release]; return nil; } return [result autorelease]; } @end NS_ASSUME_NONNULL_END