|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298 |
- //
- // MMSpanParser.m
- // MMMarkdown
- //
- // Copyright (c) 2012 Matt Diephouse.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- //
-
- #import "MMSpanParser.h"
-
-
- #import "MMElement.h"
- #import "MMHTMLParser.h"
- #import "MMScanner.h"
-
- static NSString * const ESCAPABLE_CHARS = @"\\`*_{}[]()#+-.!>";
-
- @interface MMSpanParser ()
- @property (assign, nonatomic, readonly) MMMarkdownExtensions extensions;
- @property (strong, nonatomic, readonly) MMHTMLParser *htmlParser;
-
- @property (strong, nonatomic) NSMutableArray *elements;
- @property (strong, nonatomic) NSMutableArray *openElements;
-
- @property (strong, nonatomic) MMElement *blockElement;
- @property (assign, nonatomic) BOOL parseEm;
- @property (assign, nonatomic) BOOL parseImages;
- @property (assign, nonatomic) BOOL parseLinks;
- @property (assign, nonatomic) BOOL parseStrong;
- @end
-
- @implementation MMSpanParser
-
- #pragma mark - Public Methods
-
- - (id)initWithExtensions:(MMMarkdownExtensions)extensions
- {
- self = [super init];
-
- if (self)
- {
- _extensions = extensions;
- _htmlParser = [MMHTMLParser new];
- self.parseEm = YES;
- self.parseImages = YES;
- self.parseLinks = YES;
- self.parseStrong = YES;
- }
-
- return self;
- }
-
- - (NSArray *)parseSpansInBlockElement:(MMElement *)block withScanner:(MMScanner *)scanner
- {
- self.blockElement = block;
- [scanner skipWhitespace];
- return [self _parseWithScanner:scanner untilTestPasses:^{ return scanner.atEndOfString; }];
- }
-
- - (NSArray *)parseSpansInTableColumns:(NSArray *)columns withScanner:(MMScanner *)scanner
- {
- NSMutableArray *cells = [NSMutableArray new];
-
- for (NSNumber *alignment in columns)
- {
- [scanner skipWhitespace];
-
- NSUInteger startLocation = scanner.location;
- NSArray *spans = scanner.nextCharacter == '|' ? @[] : [self _parseWithScanner:scanner untilTestPasses:^ BOOL {
- [scanner skipWhitespace];
- return scanner.nextCharacter == '|' || scanner.atEndOfLine;
- }];
-
- if (!spans)
- return nil;
-
- MMElement *cell = [MMElement new];
- cell.type = MMElementTypeTableRowCell;
- cell.children = spans;
- cell.range = NSMakeRange(startLocation, scanner.location-startLocation);
- cell.alignment = alignment.integerValue;
- [cells addObject:cell];
-
- if (scanner.nextCharacter == '|')
- [scanner advance];
- }
-
- return cells;
- }
-
-
- #pragma mark - Private Methods
-
- - (NSArray *)_parseWithScanner:(MMScanner *)scanner untilTestPasses:(BOOL (^)(void))test
- {
- NSMutableArray *result = [NSMutableArray array];
-
- NSCharacterSet *specialChars = [NSCharacterSet characterSetWithCharactersInString:@"\\`*_<&[! ~w:@|"];
- NSCharacterSet *boringChars = [specialChars invertedSet];
-
- [scanner beginTransaction];
- while (!scanner.atEndOfString)
- {
- MMElement *element = [self _parseNextElementWithScanner:scanner];
- if (element)
- {
- if (scanner.startLocation != element.range.location)
- {
- MMElement *text = [MMElement new];
- text.type = MMElementTypeNone;
- text.range = NSMakeRange(scanner.startLocation, element.range.location-scanner.startLocation);
- [result addObject:text];
- }
-
- [result addObject:element];
-
- [scanner commitTransaction:YES];
- [scanner beginTransaction];
- }
- else if (scanner.atEndOfLine)
- {
- // This is done here (and not in _parseNextElementWithScanner:)
- // because it can result in 2 elements.
-
- if (scanner.startLocation != scanner.location)
- {
- MMElement *text = [MMElement new];
- text.type = MMElementTypeNone;
- text.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- [result addObject:text];
- }
-
- if (self.extensions & MMMarkdownExtensionsHardNewlines && self.blockElement.type == MMElementTypeParagraph)
- {
- MMElement *lineBreak = [MMElement new];
- lineBreak.range = NSMakeRange(scanner.location, 1);
- lineBreak.type = MMElementTypeLineBreak;
- [result addObject:lineBreak];
- }
-
- // Add a newline
- MMElement *newline = [MMElement new];
- newline.range = NSMakeRange(scanner.location, 1);
- newline.type = MMElementTypeEntity;
- newline.stringValue = @"\n";
- [result addObject:newline];
-
- [scanner advanceToNextLine];
- [scanner commitTransaction:YES];
- [scanner beginTransaction];
- }
- else if ([scanner skipCharactersFromSet:boringChars])
- {
- }
- else
- {
- [scanner advance];
- }
-
- // Check for the end character
- [scanner beginTransaction];
- NSUInteger location = scanner.location;
- if (test())
- {
- [scanner commitTransaction:YES];
-
- if (scanner.startLocation != location)
- {
- MMElement *text = [MMElement new];
- text.type = MMElementTypeNone;
- text.range = NSMakeRange(scanner.startLocation, location-scanner.startLocation);
- [result addObject:text];
- }
-
- [scanner commitTransaction:YES];
-
- return result;
- }
- [scanner commitTransaction:NO];
- }
- [scanner commitTransaction:NO];
-
- return nil;
- }
-
- - (MMElement *)_parseNextElementWithScanner:(MMScanner *)scanner
- {
- MMElement *element;
-
- if (self.extensions & MMMarkdownExtensionsStrikethroughs)
- {
- [scanner beginTransaction];
- element = [self _parseStrikethroughWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
- }
-
- // URL Autolinking
- if (self.parseLinks && self.extensions & MMMarkdownExtensionsAutolinkedURLs)
- {
- [scanner beginTransaction];
- element = [self _parseAutolinkEmailAddressWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseAutolinkURLWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseAutolinkWWWURLWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
- }
-
- [scanner beginTransaction];
- element = [self _parseBackslashWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseEmAndStrongWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseCodeSpanWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseLineBreakWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- if (self.parseLinks)
- {
- [scanner beginTransaction];
- element = [self _parseAutomaticLinkWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseAutomaticEmailLinkWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseLinkWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
- }
-
- if (self.parseImages)
- {
- [scanner beginTransaction];
- element = [self _parseImageWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
- }
-
- [scanner beginTransaction];
- element = [self.htmlParser parseInlineTagWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self.htmlParser parseCommentWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseAmpersandWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- [scanner beginTransaction];
- element = [self _parseLeftAngleBracketWithScanner:scanner];
- [scanner commitTransaction:element != nil];
- if (element)
- return element;
-
- return nil;
- }
-
- - (BOOL)_parseAutolinkDomainWithScanner:(MMScanner *)scanner
- {
- NSCharacterSet *alphanumerics = NSCharacterSet.alphanumericCharacterSet;
- NSMutableCharacterSet *domainChars = [alphanumerics mutableCopy];
- [domainChars addCharactersInString:@"-:"];
-
- // Domain should be at least one alphanumeric
- if (![alphanumerics characterIsMember:scanner.nextCharacter])
- return NO;
- [scanner skipCharactersFromSet:domainChars];
-
- // Dot between domain and TLD
- if (scanner.nextCharacter != '.')
- return NO;
- [scanner advance];
-
- // TLD must be at least 1 character
- if ([scanner skipCharactersFromSet:domainChars] == 0)
- return NO;
-
- return YES;
- }
-
- - (void)_parseAutolinkPathWithScanner:(MMScanner *)scanner
- {
- NSCharacterSet *alphanumerics = NSCharacterSet.alphanumericCharacterSet;
- NSMutableCharacterSet *boringChars = [alphanumerics mutableCopy];
- [boringChars addCharactersInString:@",_-/:?&;%~!#+=@"];
-
- NSUInteger parenLevel = 0;
- while (1)
- {
- if ([scanner skipCharactersFromSet:boringChars] > 0)
- {
- continue;
- }
- else if (scanner.nextCharacter == '\\')
- {
- [scanner advance];
- if (scanner.nextCharacter == '(' || scanner.nextCharacter == ')')
- [scanner advance];
- }
- else if (scanner.nextCharacter == '(')
- {
- parenLevel++;
- [scanner advance];
- }
- else if (scanner.nextCharacter == ')' && parenLevel > 0)
- {
- parenLevel--;
- [scanner advance];
- }
- else if (scanner.nextCharacter == '.')
- {
- // Can't end on a '.'
- [scanner beginTransaction];
- [scanner advance];
- if ([boringChars characterIsMember:scanner.nextCharacter])
- {
- [scanner commitTransaction:YES];
- }
- else
- {
- [scanner commitTransaction:NO];
- break;
- }
- }
- else
- {
- break;
- }
- }
- }
-
- - (MMElement *)_parseAutolinkEmailAddressWithScanner:(MMScanner *)scanner
- {
- if (scanner.nextCharacter != '@')
- return nil;
-
- NSCharacterSet *alphanumerics = NSCharacterSet.alphanumericCharacterSet;
- NSMutableCharacterSet *localChars = [alphanumerics mutableCopy];
- [localChars addCharactersInString:@"._-+"];
- NSMutableCharacterSet *domainChars = [alphanumerics mutableCopy];
- [domainChars addCharactersInString:@"._-"];
-
- // Look for the previous word outside of the current transaction
- [scanner commitTransaction:NO];
- NSString *localPart = [scanner previousWordWithCharactersFromSet:localChars];
- [scanner beginTransaction];
-
- if (localPart.length == 0)
- return nil;
-
- // '@'
- [scanner advance];
-
- NSString *domainPart = [scanner nextWordWithCharactersFromSet:localChars];
-
- // Must end on a letter or number
- NSRange lastAlphanum = [domainPart rangeOfCharacterFromSet:alphanumerics options:NSBackwardsSearch];
- if (lastAlphanum.location == NSNotFound)
- return nil;
- domainPart = [domainPart substringToIndex:NSMaxRange(lastAlphanum)];
-
- // Must contain at least one .
- if ([domainPart rangeOfString:@"."].location == NSNotFound)
- return nil;
-
- scanner.location += domainPart.length;
-
- NSUInteger startLocation = scanner.startLocation - localPart.length;
- NSRange range = NSMakeRange(startLocation, scanner.location-startLocation);
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeMailTo;
- element.range = range;
- element.href = [scanner.string substringWithRange:range];
-
- return element;
- }
-
- - (MMElement *)_parseAutolinkURLWithScanner:(MMScanner *)scanner
- {
- if (scanner.nextCharacter != ':')
- return nil;
-
- NSArray *protocols = @[ @"https", @"http", @"ftp" ];
-
- // Look for the previous word outside of the current transaction
- [scanner commitTransaction:NO];
- NSString *previousWord = scanner.previousWord;
- [scanner beginTransaction];
-
- if (![protocols containsObject:previousWord.lowercaseString])
- return nil;
-
- if (![scanner matchString:@"://"])
- return nil;
-
- if (![self _parseAutolinkDomainWithScanner:scanner])
- return nil;
- [self _parseAutolinkPathWithScanner:scanner];
-
- NSUInteger startLocation = scanner.startLocation - previousWord.length;
- NSRange range = NSMakeRange(startLocation, scanner.location-startLocation);
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeLink;
- element.range = range;
- element.href = [scanner.string substringWithRange:range];
-
- MMElement *text = [MMElement new];
- text.type = MMElementTypeNone;
- text.range = range;
- [element addChild:text];
-
- return element;
- }
-
- - (MMElement *)_parseAutolinkWWWURLWithScanner:(MMScanner *)scanner
- {
- if (![scanner matchString:@"www."])
- return nil;
-
- if (![self _parseAutolinkDomainWithScanner:scanner])
- return nil;
- [self _parseAutolinkPathWithScanner:scanner];
-
- NSRange range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- NSString *link = [scanner.string substringWithRange:range];
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeLink;
- element.range = range;
- element.href = [@"http://" stringByAppendingString:link];
-
- MMElement *text = [MMElement new];
- text.type = MMElementTypeNone;
- text.range = range;
- [element addChild:text];
-
- return element;
- }
-
- - (MMElement *)_parseStrikethroughWithScanner:(MMScanner *)scanner
- {
- if (![scanner matchString:@"~~"])
- return nil;
-
- NSCharacterSet *whitespaceSet = NSCharacterSet.whitespaceCharacterSet;
- NSArray *children = [self _parseWithScanner:scanner untilTestPasses:^{
- // Can't be at the beginning of the line
- if (scanner.atBeginningOfLine)
- return NO;
-
- // Must follow the end of a word
- if ([whitespaceSet characterIsMember:scanner.previousCharacter])
- return NO;
-
- if (![scanner matchString:@"~~"])
- return NO;
-
- return YES;
- }];
-
- if (!children)
- return nil;
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeStrikethrough;
- element.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- element.children = children;
-
- return element;
- }
-
- - (MMElement *)_parseEmAndStrongWithScanner:(MMScanner *)scanner
- {
- // Must have 1-3 *s or _s
- unichar character = scanner.nextCharacter;
- if (!(character == '*' || character == '_'))
- return nil;
-
- NSCharacterSet *alphanumericSet = NSCharacterSet.alphanumericCharacterSet;
- if (self.extensions & MMMarkdownExtensionsUnderscoresInWords && character == '_')
- {
- // GFM doesn't italicize parts of words
-
- [scanner commitTransaction:NO];
- // Look for the previous char outside of the current transaction
- unichar prevChar = scanner.previousCharacter;
- [scanner beginTransaction];
-
- BOOL isWordChar = [alphanumericSet characterIsMember:prevChar];
- if (isWordChar)
- return nil;
- }
-
- // Must not be preceded by one of the same
- if (scanner.previousCharacter == character)
- return nil;
-
- NSUInteger numberOfChars = 0;
- while (scanner.nextCharacter == character)
- {
- numberOfChars++;
- [scanner advance];
- }
-
- if (numberOfChars > 3)
- return nil;
-
- BOOL parseEm = numberOfChars == 1 || numberOfChars == 3;
- BOOL parseStrong = numberOfChars == 2 || numberOfChars == 3;
-
- if ((parseEm && !self.parseEm) || (parseStrong && !self.parseStrong))
- return nil;
-
- NSCharacterSet *whitespaceSet = NSCharacterSet.whitespaceCharacterSet;
- __block NSUInteger remainingChars = numberOfChars;
- BOOL (^atEnd)(void) = ^{
- // Can't be at the beginning of the line
- if (scanner.atBeginningOfLine)
- return NO;
-
- // Must follow the end of a word
- if ([whitespaceSet characterIsMember:scanner.previousCharacter])
- return NO;
-
- // Must have 1-3 *s or _s
- NSUInteger numberOfEndChars = 0;
- while (scanner.nextCharacter == character && numberOfEndChars < remainingChars)
- {
- numberOfEndChars++;
- [scanner advance];
- }
-
- if (numberOfEndChars == 0 || (numberOfEndChars != remainingChars && remainingChars != 3))
- return NO;
-
- if (self.extensions & MMMarkdownExtensionsUnderscoresInWords && character == '_')
- {
- // GFM doesn't italicize parts of words
- unichar nextChar = scanner.nextCharacter;
-
- BOOL isWordChar = [alphanumericSet characterIsMember:nextChar];
- if (isWordChar)
- return NO;
- }
-
- remainingChars -= numberOfEndChars;
-
- return YES;
- };
-
- if (parseEm)
- self.parseEm = NO;
- if (parseStrong)
- self.parseStrong = NO;
- NSArray *children = [self _parseWithScanner:scanner untilTestPasses:atEnd];
- if (parseEm && (!children || remainingChars != 1))
- self.parseEm = YES;
- if (parseStrong && (!children || remainingChars != 2))
- self.parseStrong = YES;
-
- if (!children)
- return nil;
-
- BOOL isEm = (numberOfChars == 1) || (numberOfChars == 3 && remainingChars != 1);
- NSUInteger startLocation = scanner.startLocation + remainingChars;
- MMElement *element = [MMElement new];
- element.type = isEm ? MMElementTypeEm : MMElementTypeStrong;
- element.range = NSMakeRange(startLocation, scanner.location-startLocation);
- element.children = children;
-
- if (numberOfChars == 3 && remainingChars == 0)
- {
- NSArray *outerChildren = @[ element ];
- element = [MMElement new];
- element.type = MMElementTypeStrong;
- element.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- element.children = outerChildren;
- }
- else if (remainingChars > 0)
- {
- NSMutableArray *outerChildren = [[self _parseWithScanner:scanner untilTestPasses:atEnd] mutableCopy];
- if (parseEm)
- self.parseEm = YES;
- if (parseStrong)
- self.parseStrong = YES;
- if (!outerChildren)
- return nil;
-
- [outerChildren insertObject:element atIndex:0];
-
- element = [MMElement new];
- element.type = !isEm ? MMElementTypeEm : MMElementTypeStrong;
- element.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- element.children = outerChildren;
- }
-
- return element;
- }
-
- - (MMElement *)_parseCodeSpanWithScanner:(MMScanner *)scanner
- {
- if (scanner.nextCharacter != '`')
- return nil;
- [scanner advance];
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeCodeSpan;
-
- // Check for more `s
- NSUInteger level = 1;
- while (scanner.nextCharacter == '`')
- {
- level++;
- [scanner advance];
- }
-
- // skip leading whitespace
- [scanner skipCharactersFromSet:NSCharacterSet.whitespaceCharacterSet];
-
- // Skip to the next '`'
- NSCharacterSet *boringChars = [[NSCharacterSet characterSetWithCharactersInString:@"`&<>"] invertedSet];
- NSUInteger textLocation = scanner.location;
- while (1)
- {
- if (scanner.atEndOfString)
- return nil;
-
- // Skip other characters
- [scanner skipCharactersFromSet:boringChars];
-
- // Add the code as text
- if (textLocation != scanner.location)
- {
- MMElement *text = [MMElement new];
- text.type = MMElementTypeNone;
- text.range = NSMakeRange(textLocation, scanner.location-textLocation);
- [element addChild:text];
- }
-
- // Check for closing `s
- if (scanner.nextCharacter == '`')
- {
- // Set the text location to catch the ` in case it isn't the closing `s
- textLocation = scanner.location;
-
- NSUInteger idx;
- for (idx=0; idx<level; idx++)
- {
- if (scanner.nextCharacter != '`')
- break;
- [scanner advance];
- }
- if (idx >= level)
- break;
- else
- continue;
- }
-
- unichar nextChar = scanner.nextCharacter;
- // Check for entities
- if (nextChar == '&')
- {
- MMElement *entity = [MMElement new];
- entity.type = MMElementTypeEntity;
- entity.range = NSMakeRange(scanner.location, 1);
- entity.stringValue = @"&";
- [element addChild:entity];
- [scanner advance];
- }
- else if (nextChar == '<')
- {
- MMElement *entity = [MMElement new];
- entity.type = MMElementTypeEntity;
- entity.range = NSMakeRange(scanner.location, 1);
- entity.stringValue = @"<";
- [element addChild:entity];
- [scanner advance];
- }
- else if (nextChar == '>')
- {
- MMElement *entity = [MMElement new];
- entity.type = MMElementTypeEntity;
- entity.range = NSMakeRange(scanner.location, 1);
- entity.stringValue = @">";
- [element addChild:entity];
- [scanner advance];
- }
- // Or did we hit the end of the line?
- else if (scanner.atEndOfLine)
- {
- textLocation = scanner.location;
- [scanner advanceToNextLine];
- continue;
- }
-
- textLocation = scanner.location;
- }
-
- // remove trailing whitespace
- if (element.children.count > 0)
- {
- MMElement *lastText = element.children.lastObject;
- unichar lastCharacter = [scanner.string characterAtIndex:NSMaxRange(lastText.range)-1];
- while ([NSCharacterSet.whitespaceCharacterSet characterIsMember:lastCharacter])
- {
- NSRange range = lastText.range;
- range.length -= 1;
- lastText.range = range;
-
- lastCharacter = [scanner.string characterAtIndex:NSMaxRange(lastText.range)-1];
- }
- }
-
- element.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
-
- return element;
- }
-
- - (MMElement *)_parseLineBreakWithScanner:(MMScanner *)scanner
- {
- NSCharacterSet *spaces = [NSCharacterSet characterSetWithCharactersInString:@" "];
- if ([scanner skipCharactersFromSet:spaces] < 2)
- return nil;
-
- if (!scanner.atEndOfLine)
- return nil;
-
- // Don't ever add a line break to the last line
- if (scanner.atEndOfString)
- return nil;
-
- NSUInteger startLocation = scanner.startLocation + 1;
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeLineBreak;
- element.range = NSMakeRange(startLocation, scanner.location-startLocation);
-
- return element;
- }
-
- - (MMElement *)_parseAutomaticLinkWithScanner:(MMScanner *)scanner
- {
- // Leading <
- if (scanner.nextCharacter != '<')
- return nil;
- [scanner advance];
-
- NSUInteger textLocation = scanner.location;
-
- // Find the trailing >
- [scanner skipCharactersFromSet:[[NSCharacterSet characterSetWithCharactersInString:@">"] invertedSet]];
- if (scanner.atEndOfLine)
- return nil;
- [scanner advance];
-
- NSRange linkRange = NSMakeRange(textLocation, (scanner.location-1)-textLocation);
- NSString *linkText = [scanner.string substringWithRange:linkRange];
-
- // Make sure it looks like a link
- static NSRegularExpression *regex;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- regex = [NSRegularExpression regularExpressionWithPattern:@"^(\\w+)://" options:0 error:nil];
- });
- NSRange matchRange;
- matchRange = [regex rangeOfFirstMatchInString:linkText options:0 range:NSMakeRange(0, linkText.length)];
- if (matchRange.location == NSNotFound)
- return nil;
- NSURL *url = [NSURL URLWithString:linkText];
- if (!url)
- return nil;
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeLink;
- element.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- element.href = linkText;
-
- // Do the text the hard way to take care of ampersands
- NSRange textRange = NSMakeRange(textLocation, NSMaxRange(linkRange)-textLocation);
- NSCharacterSet *ampersands = [NSCharacterSet characterSetWithCharactersInString:@"&"];
- while (textRange.length > 0)
- {
- NSRange result = [scanner.string rangeOfCharacterFromSet:ampersands
- options:0
- range:textRange];
-
- if (result.location != NSNotFound)
- {
- if (textRange.location != result.location)
- {
- MMElement *text = [MMElement new];
- text.type = MMElementTypeNone;
- text.range = NSMakeRange(textRange.location, result.location-textRange.location);
- [element addChild:text];
- }
-
- MMElement *ampersand = [MMElement new];
- ampersand.type = MMElementTypeEntity;
- ampersand.range = NSMakeRange(textRange.location, 1);
- ampersand.stringValue = @"&";
- [element addChild:ampersand];
-
- textRange = NSMakeRange(result.location+1, NSMaxRange(textRange)-(result.location+1));
- }
- else
- {
- if (textRange.length > 0)
- {
- MMElement *text = [MMElement new];
- text.type = MMElementTypeNone;
- text.range = textRange;
- [element addChild:text];
- }
- break;
- }
- }
-
- return element;
- }
-
- - (MMElement *)_parseAutomaticEmailLinkWithScanner:(MMScanner *)scanner
- {
- // Leading <
- if (scanner.nextCharacter != '<')
- return nil;
- [scanner advance];
-
- NSUInteger textLocation = scanner.location;
-
- // Find the trailing >
- [scanner skipCharactersFromSet:[[NSCharacterSet characterSetWithCharactersInString:@">"] invertedSet]];
- if (scanner.atEndOfLine)
- return nil;
- [scanner advance];
-
- NSRange linkRange = NSMakeRange(textLocation, (scanner.location-1)-textLocation);
- NSString *linkText = [scanner.string substringWithRange:linkRange];
-
- // Make sure it looks like a link
- static NSRegularExpression *regex;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- regex = [NSRegularExpression regularExpressionWithPattern:@"^[-._0-9\\p{L}]+@[-\\p{L}0-9][-.\\p{L}0-9]*\\.\\p{L}+$"
- options:NSRegularExpressionCaseInsensitive
- error:nil];
- });
- NSRange matchRange;
- matchRange = [regex rangeOfFirstMatchInString:linkText options:0 range:NSMakeRange(0, linkText.length)];
- if (matchRange.location == NSNotFound)
- return nil;
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeMailTo;
- element.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- element.href = linkText;
-
- return element;
- }
-
- - (NSArray *)_parseLinkTextBodyWithScanner:(MMScanner *)scanner
- {
- NSMutableArray *ranges = [NSMutableArray new];
- NSCharacterSet *boringChars;
- NSUInteger level;
-
- if (scanner.nextCharacter != '[')
- return nil;
- [scanner advance];
-
- boringChars = [[NSCharacterSet characterSetWithCharactersInString:@"[]\\"] invertedSet];
- level = 1;
- NSRange textRange = scanner.currentRange;
- while (level > 0)
- {
- if (scanner.atEndOfString)
- return nil;
-
- if (scanner.atEndOfLine)
- {
- if (textRange.length > 0)
- {
- [ranges addObject:[NSValue valueWithRange:textRange]];
- }
- [scanner advanceToNextLine];
- textRange = scanner.currentRange;
- }
-
- [scanner skipCharactersFromSet:boringChars];
-
- unichar character = scanner.nextCharacter;
- if (character == '[')
- {
- level += 1;
- }
- else if (character == ']')
- {
- level -= 1;
- }
- else if (character == '\\')
- {
- [scanner advance];
- }
-
- textRange.length = scanner.location - textRange.location;
- [scanner advance];
- }
-
- if (textRange.length > 0)
- {
- [ranges addObject:[NSValue valueWithRange:textRange]];
- }
-
- return ranges;
- }
-
- - (MMElement *)_parseInlineLinkWithScanner:(MMScanner *)scanner
- {
- NSCharacterSet *boringChars;
- NSUInteger level;
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeLink;
-
- // Find the []
- element.innerRanges = [self _parseLinkTextBodyWithScanner:scanner];
- if (!element.innerRanges)
- return nil;
-
- // Find the ()
- if (scanner.nextCharacter != '(')
- return nil;
- [scanner advance];
- [scanner skipWhitespace];
-
- NSUInteger urlLocation = scanner.location;
- NSUInteger urlEnd = urlLocation;
- boringChars = [[NSCharacterSet characterSetWithCharactersInString:@"()\\ \t"] invertedSet];
- level = 1;
- while (level > 0)
- {
- [scanner skipCharactersFromSet:boringChars];
- if (scanner.atEndOfLine)
- return nil;
- urlEnd = scanner.location;
-
- unichar character = scanner.nextCharacter;
- if (character == '(')
- {
- level += 1;
- }
- else if (character == ')')
- {
- level -= 1;
- }
- else if (character == '\\')
- {
- [scanner advance]; // skip over the backslash
- // skip over the next character below
- }
- else if ([NSCharacterSet.whitespaceCharacterSet characterIsMember:character])
- {
- if (level != 1)
- return nil;
-
- [scanner skipWhitespace];
- if (scanner.nextCharacter == ')')
- {
- [scanner advance];
- level -= 1;
- }
- break;
- }
- urlEnd = scanner.location;
- [scanner advance];
- }
-
- NSUInteger titleLocation = NSNotFound;
- NSUInteger titleEnd = NSNotFound;
-
- // If the level is still 1, then we hit a space.
- if (level == 1)
- {
- // make sure there's a "
- if (scanner.nextCharacter != '"')
- return nil;
- [scanner advance];
-
- titleLocation = scanner.location;
- boringChars = [[NSCharacterSet characterSetWithCharactersInString:@"\""] invertedSet];
- while (1)
- {
- [scanner skipCharactersFromSet:boringChars];
-
- if (scanner.atEndOfLine)
- return nil;
-
- [scanner advance];
- if (scanner.nextCharacter == ')')
- {
- titleEnd = scanner.location - 1;
- [scanner advance];
- break;
- }
- }
- }
-
- NSRange urlRange = NSMakeRange(urlLocation, urlEnd-urlLocation);
- NSString *href = [scanner.string substringWithRange:urlRange];
-
- // If the URL is surrounded by angle brackets, ditch them
- if ([href hasPrefix:@"<"] && [href hasSuffix:@">"])
- {
- href = [href substringWithRange:NSMakeRange(1, href.length-2)];
- }
-
- element.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- element.href = [self _stringWithBackslashEscapesRemoved:href];
-
- if (titleLocation != NSNotFound)
- {
- NSRange titleRange = NSMakeRange(titleLocation, titleEnd-titleLocation);
- element.title = [scanner.string substringWithRange:titleRange];
- }
-
- return element;
- }
-
- - (MMElement *)_parseReferenceLinkWithScanner:(MMScanner *)scanner
- {
- MMElement *element = [MMElement new];
- element.type = MMElementTypeLink;
-
- // Find the []
- element.innerRanges = [self _parseLinkTextBodyWithScanner:scanner];
- if (!element.innerRanges.count)
- return nil;
-
- // Skip optional whitespace
- if (scanner.nextCharacter == ' ')
- [scanner advance];
- // or possible newline
- else if (scanner.atEndOfLine)
- [scanner advanceToNextLine];
-
- // Look for the second []
- NSArray *idRanges = [self _parseLinkTextBodyWithScanner:scanner];
- if (!idRanges)
- return nil;
- if (!idRanges.count)
- {
- idRanges = element.innerRanges;
- }
-
- NSMutableString *idString = [NSMutableString new];
- for (NSValue *value in idRanges)
- {
- NSRange range = [value rangeValue];
- [idString appendString:[scanner.string substringWithRange:range]];
- [idString appendString:@" "]; // newlines are replaced by spaces for the id
- }
- // Delete the last space
- [idString deleteCharactersInRange:NSMakeRange(idString.length-1, 1)];
-
- element.range = NSMakeRange(scanner.startLocation, scanner.location-scanner.startLocation);
- element.identifier = idString;
-
- return element;
- }
-
- - (MMElement *)_parseLinkWithScanner:(MMScanner *)scanner
- {
- MMElement *element;
-
- element = [self _parseInlineLinkWithScanner:scanner];
-
- if (element == nil)
- {
- // Assume that this method will already be wrapped in a transaction
- [scanner commitTransaction:NO];
- [scanner beginTransaction];
- element = [self _parseReferenceLinkWithScanner:scanner];
- }
-
- if (element != nil && element.innerRanges.count > 0)
- {
- self.parseLinks = NO;
- MMScanner *innerScanner = [MMScanner scannerWithString:scanner.string lineRanges:element.innerRanges];
- element.children = [self _parseWithScanner:innerScanner untilTestPasses:^{ return [innerScanner atEndOfString]; }];
- self.parseLinks = YES;
- }
-
- return element;
- }
-
- - (MMElement *)_parseImageWithScanner:(MMScanner *)scanner
- {
- MMElement *element;
-
- // An image starts with a !, but then is a link
- if (scanner.nextCharacter != '!')
- return nil;
- [scanner advance];
-
- // Add a transaction to protect the ! that was scanned
- [scanner beginTransaction];
-
- self.parseImages = NO;
- element = [self _parseInlineLinkWithScanner:scanner];
- self.parseImages = YES;
-
- if (element == nil)
- {
- // Assume that this method will already be wrapped in a transaction
- [scanner commitTransaction:NO];
- [scanner beginTransaction];
- element = [self _parseReferenceLinkWithScanner:scanner];
- }
-
- [scanner commitTransaction:YES];
-
- if (element != nil)
- {
- element.type = MMElementTypeImage;
-
- // Adjust the range to include the !
- NSRange range = element.range;
- range.location -= 1;
- range.length += 1;
- element.range = range;
-
- NSMutableString *altText = [NSMutableString new];
- for (NSValue *value in element.innerRanges)
- {
- NSRange range = [value rangeValue];
- [altText appendString:[scanner.string substringWithRange:range]];
- }
- element.stringValue = altText;
- }
-
- return element;
- }
-
- - (MMElement *)_parseAmpersandWithScanner:(MMScanner *)scanner
- {
- if (scanner.nextCharacter != '&')
- return nil;
- [scanner advance];
-
- // check if this is an html entity
- [scanner beginTransaction];
-
- if (scanner.nextCharacter == '#')
- [scanner advance];
- [scanner skipCharactersFromSet:NSCharacterSet.alphanumericCharacterSet];
- if (scanner.nextCharacter == ';')
- {
- [scanner commitTransaction:NO];
- return nil;
- }
- [scanner commitTransaction:NO];
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeEntity;
- element.range = NSMakeRange(scanner.location-1, 1);
- element.stringValue = @"&";
-
- return element;
- }
-
- - (MMElement *)_parseBackslashWithScanner:(MMScanner *)scanner
- {
- if (scanner.nextCharacter != '\\')
- return nil;
- [scanner advance];
-
- NSCharacterSet *escapable = [NSCharacterSet characterSetWithCharactersInString:ESCAPABLE_CHARS];
- if (![escapable characterIsMember:scanner.nextCharacter])
- return nil;
-
- // Return the character
-
- MMElement *character = [MMElement new];
- character.type = MMElementTypeEntity;
- character.range = NSMakeRange(scanner.location-1, 2);
- character.stringValue = [scanner.string substringWithRange:NSMakeRange(scanner.location, 1)];
-
- [scanner advance];
-
- return character;
- }
-
- - (MMElement *)_parseLeftAngleBracketWithScanner:(MMScanner *)scanner
- {
- if (scanner.nextCharacter != '<')
- return nil;
- [scanner advance];
-
- MMElement *element = [MMElement new];
- element.type = MMElementTypeEntity;
- element.range = NSMakeRange(scanner.location-1, 1);
- element.stringValue = @"<";
-
- return element;
- }
-
- - (NSString *)_stringWithBackslashEscapesRemoved:(NSString *)string
- {
- NSMutableString *result = [string mutableCopy];
-
- NSCharacterSet *escapableChars = [NSCharacterSet characterSetWithCharactersInString:ESCAPABLE_CHARS];
-
- NSRange searchRange = NSMakeRange(0, result.length);
- while (searchRange.length > 0)
- {
- NSRange range = [result rangeOfString:@"\\" options:0 range:searchRange];
-
- if (range.location == NSNotFound || NSMaxRange(range) == NSMaxRange(searchRange))
- break;
-
- // If it is escapable, than remove the backslash
- unichar nextChar = [result characterAtIndex:range.location + 1];
- if ([escapableChars characterIsMember:nextChar])
- {
- [result replaceCharactersInRange:range withString:@""];
- }
-
- searchRange.location = range.location + 1;
- searchRange.length = result.length - searchRange.location;
- }
-
- return result;
- }
-
-
- @end
|