forked from Micrified/CXMarkdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCXMarkdown.m
429 lines (329 loc) · 20.5 KB
/
CXMarkdown.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//
// CXMarkdown.m
//
// Created by Owatch
#import "CXMarkdown.h"
@interface CXMarkdown ()
@property (nonatomic)CFMutableAttributedStringRef *mutableAttributedString;
@end
@implementation CXMarkdown
#pragma mark Helper Methods
/* Returns font adjusted for symbolic trait mask */
-(UIFont *)newFontFromFont:(UIFont *)font Mask:(CTFontSymbolicTraits)mask {
CTFontRef fontRef = (__bridge CTFontRef)font;
UIFont *newFont = (UIFont *)CFBridgingRelease(CTFontCreateCopyWithSymbolicTraits(fontRef, [font pointSize], NULL, mask, mask));
return newFont;
}
/* Returns symbolic trait mask for markdown type */
-(uint32_t)symbolicTraitForMarkdownType:(CXMarkdownType)markdown {
if (markdown == CXMarkdownTypeItalics){return UIFontDescriptorTraitItalic;}
if (markdown == CXMarkdownTypeBold){return UIFontDescriptorTraitBold;}
return 0;
}
/* Returns a character array for a CFMutableAttributedStringRef string */
-(char *)charArrayFromAttributedString:(CFMutableAttributedStringRef *)mutableAttributedString {
CFStringRef string = CFAttributedStringGetString(*mutableAttributedString);
CFIndex len = CFStringGetLength(string);
CFIndex maxsize = CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8)+1;
char *buffer = (char *)malloc(maxsize);
if (CFStringGetCString(string, buffer, maxsize, kCFStringEncodingUTF8)){
return buffer;
}
return NULL;
}
/* Removes formatting characters over a range depending on markdown type. Does not cover hyperlinks */
-(void)removeMarkdownType:(CXMarkdownType)type fromString:(CFMutableAttributedStringRef *)mutableAttributedString range:(CFRange)range {
CFAttributedStringBeginEditing(*mutableAttributedString);
CFAttributedStringRef replacementString; UInt8 leadingOffset = 0; UInt8 trailingOffset = 0;
switch (type) {
case CXMarkdownTypeItalics:
leadingOffset = 1; trailingOffset = 2;
break;
case CXMarkdownTypeBold:
leadingOffset = 2; trailingOffset = 4;
break;
case CXMarkdownTypeStrikethrough:
leadingOffset = 2; trailingOffset = 4;
break;
case CXMarkdownTypeSuperscript:
leadingOffset = 1; trailingOffset = 1;
break;
default:
break;
}
replacementString = CFAttributedStringCreateWithSubstring(kCFAllocatorDefault, *mutableAttributedString, CFRangeMake(range.location + leadingOffset, range.length - trailingOffset));
CFAttributedStringReplaceAttributedString(*mutableAttributedString, range, replacementString);
CFRelease(replacementString);
CFAttributedStringEndEditing(*mutableAttributedString);
}
#pragma mark Formatting Methods
/* Replaces range of string with the link title, and adds the URL under the NSLinkAttributeName key to the attributes of the string */
-(void)applyHyperlinkToString:(CFMutableAttributedStringRef *)mutableAttributedString range:(CFRange)range partitionIndex:(UInt32)pindex {
CFAttributedStringBeginEditing(*mutableAttributedString);
CFAttributedStringRef title = CFAttributedStringCreateWithSubstring(kCFAllocatorDefault, *mutableAttributedString, CFRangeMake(range.location+1, pindex - (range.location+2)));
CFMutableAttributedStringRef mutableTitle = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, (pindex - (range.location+2)), title);
CFAttributedStringRef destination = CFAttributedStringCreateWithSubstring(kCFAllocatorDefault, *mutableAttributedString, CFRangeMake(pindex+1, (range.location + range.length) - (pindex+2)));
/* Set Attributes */
NSURL *destURL = [NSURL URLWithString:(__bridge NSString*)CFAttributedStringGetString(destination)];
CFAttributedStringSetAttribute(mutableTitle, CFRangeMake(0, (pindex - (range.location+2))), (__bridge CFStringRef)NSLinkAttributeName, (CFTypeRef)destURL);
/* Replace range with title */
CFAttributedStringReplaceAttributedString(*mutableAttributedString, range, mutableTitle);
CFAttributedStringEndEditing(*mutableAttributedString);
CFRelease(title); CFRelease(mutableTitle); CFRelease(destination);
}
/* Replaces range of string with superscripted variant */
-(void)applySuperscriptToString:(CFMutableAttributedStringRef *)mutableAttributedString range:(CFRange)range degree:(UInt32)degree {
CFAttributedStringBeginEditing(*mutableAttributedString);
/* Set Offset */
CFAttributedStringSetAttribute(*mutableAttributedString, range, (__bridge CFStringRef)NSBaselineOffsetAttributeName, (CFTypeRef)[NSNumber numberWithInt:(5 * degree) + (1.5*(1-degree))]);
/* Extract Attributes from location + 1 to not obtain caret attributes */
CFDictionaryRef attributes = CFAttributedStringGetAttributes(*mutableAttributedString, range.location+1, NULL);
UIFont *font = CFDictionaryGetValue(attributes, (__bridge CFStringRef)NSFontAttributeName);
font = [font fontWithSize:(0.75 * [font pointSize])];
CFAttributedStringSetAttribute(*mutableAttributedString, range, (__bridge CFStringRef)NSFontAttributeName, (CFTypeRef)font);
CFAttributedStringEndEditing(*mutableAttributedString);
}
/* Replaces range of string with a struck-through variant */
-(void)applyStrikethroughToString:(CFMutableAttributedStringRef *)mutableAttributedString range:(CFRange)range {
CFAttributedStringBeginEditing(*mutableAttributedString);
CFAttributedStringSetAttribute(*mutableAttributedString, range, (__bridge CFStringRef)NSStrikethroughStyleAttributeName, (CFTypeRef)[NSNumber numberWithInt:1]);
CFAttributedStringEndEditing(*mutableAttributedString);
}
/* Replaces range of string with a bolded or italicized variant */
-(void)applyItalicsOrBoldToString:(CFMutableAttributedStringRef *)mutableAttributedString range:(CFRange)range type:(CXMarkdownType)type {
CFAttributedStringBeginEditing(*mutableAttributedString);
UInt32 i = (UInt32)range.location;
while (i < (range.location + range.length)){
CFRange er; CFDictionaryRef attributes = CFAttributedStringGetAttributes(*mutableAttributedString, i, &er);
UInt32 erLen = (er.location < range.location) ? (UInt32)(er.length - (range.location - er.location)) : (UInt32)er.length;
erLen = (erLen < (range.length - (i - range.location))) ? erLen : (UInt32)(range.length - (i - range.location));
UIFont *font = CFDictionaryGetValue(attributes, (__bridge CFStringRef)NSFontAttributeName);
NSNumber *symbolicTrait = CFDictionaryGetValue(attributes, (__bridge CFStringRef)UIFontSymbolicTrait);
font = [self newFontFromFont:font Mask:(CTFontSymbolicTraits)[self symbolicTraitForMarkdownType:type]];
symbolicTrait = [NSNumber numberWithLongLong:[symbolicTrait longLongValue] | [self symbolicTraitForMarkdownType:type]];
CFAttributedStringSetAttribute(*mutableAttributedString, CFRangeMake(i, erLen), (__bridge CFStringRef)NSFontAttributeName, (CFTypeRef)font);
CFAttributedStringSetAttribute(*mutableAttributedString, CFRangeMake(i, erLen), (__bridge CFStringRef)UIFontSymbolicTrait, (CFTypeRef)symbolicTrait);
i += erLen;
}
CFAttributedStringEndEditing(*mutableAttributedString);
}
#pragma mark Parser
-(void)parseString:(char *)string ofLength:(UInt16)length {
CFAbsoluteTime a = CFAbsoluteTimeGetCurrent();
/* Variables */
/* (NAME)Count : Tracks occurances of token characters */
/* (NAME)Open : Tracks whether or not the markdown style has been evoked */
/* (NAME)OpenIndex: Tracks index at which markdown style initally detected */
/* boundary: Instructs parser to execute actions when asteriskCount has exceeded boundary. Used to prioritize closing italics */
/* hypPartitionIndex: Stores the index in which a URL is seperated from the title in markdown hyperlink format */
uint8_t asteriskCount = 0; uint8_t tildaCount = 0; uint8_t caretCount = 0;
uint8_t boldOpen = 0; uint8_t italOpen = 0; uint8_t tildaOpen = 0; uint8_t caretOpen = 0; uint8_t hypOpen = 0;
uint16_t boldOpenIndex = 0; uint16_t italOpenIndex = 0; uint16_t tildaOpenIndex = 0; uint16_t caretOpenIndex = 0; uint16_t hypOpenIndex = 0;
uint8_t boundary = 2; uint16_t hypPartitionIndex = 0;
for (int i = 0; i < length+1; i++){
/* Hyperlink */
if (hypOpen){
if (hypPartitionIndex){
if (string[i] == ' '){
hypPartitionIndex = 0; hypOpen = 0;
}
if (string[i] == ')'){
if ((hypPartitionIndex > boldOpenIndex) && (hypPartitionIndex > italOpenIndex) && (hypPartitionIndex > tildaOpenIndex) && (hypPartitionIndex > caretOpenIndex)){
/* Apply hyperlink attributes, and replace formatting */
[self applyHyperlinkToString:[self mutableAttributedString] range:CFRangeMake(hypOpenIndex, (i - hypOpenIndex)+1) partitionIndex:hypPartitionIndex];
/* Adjust length and index */
length -= (1 + (i - hypPartitionIndex)); i -= (2 + (i - hypPartitionIndex));
/* Update string */
free(string); string = [self charArrayFromAttributedString:[self mutableAttributedString]];
}
hypPartitionIndex = 0; hypOpen = 0;
}
} else {
if (string[i] == '('){
hypPartitionIndex = (string[i-1] == ']' ? i:0);
}
}
} else {
if (string[i] == '['){
hypOpen = 1; hypOpenIndex = i;
}
}
/* Italics & Bold */
if (string[i] == '*' && asteriskCount < boundary){
asteriskCount++;
} else {
if (asteriskCount){
if (asteriskCount < 2){
if (italOpen){
if (string[i-2] != ' '){
italOpen = 0; boundary = 2;
/* Apply italic attributes */
[self applyItalicsOrBoldToString:[self mutableAttributedString] range:CFRangeMake(italOpenIndex, (i - italOpenIndex)) type:CXMarkdownTypeItalics];
/* Remove formatting */
[self removeMarkdownType:CXMarkdownTypeItalics fromString:[self mutableAttributedString] range:CFRangeMake(italOpenIndex, (i - italOpenIndex))];
/* Adjust length and index */
length -= 2; i -= 2;
/* Update string */
free(string); string = [self charArrayFromAttributedString:[self mutableAttributedString]];
/* Adjust variables */
if (boldOpen && boldOpenIndex > italOpenIndex){boldOpenIndex -= 1;}
if (tildaOpen && tildaOpenIndex > italOpenIndex){tildaOpenIndex -= 1;}
if (caretOpen && caretOpenIndex > italOpenIndex){caretOpenIndex -= 1;}
}
} else {
if (string[i] != ' '){
if (boldOpen){
boundary = 1;
}
italOpen = 1; italOpenIndex = i-1;
}
}
} else {
if (boldOpen){
if (string[i-3] != ' '){
boldOpen = 0; boundary = 2;
/* Apply bold attributes */
[self applyItalicsOrBoldToString:[self mutableAttributedString] range:CFRangeMake(boldOpenIndex, (i - boldOpenIndex)) type:CXMarkdownTypeBold];
/* Remove formatting */
[self removeMarkdownType:CXMarkdownTypeBold fromString:[self mutableAttributedString] range:CFRangeMake(boldOpenIndex, (i - boldOpenIndex))];
/* Adjust length and index */
length -= 4; i -= 4;
/* Update string */
free (string); string = [self charArrayFromAttributedString:[self mutableAttributedString]];
/* Adjust variables */
if (italOpen && italOpenIndex > boldOpenIndex){italOpenIndex -= 2;}
if (tildaOpen && tildaOpenIndex > boldOpenIndex){tildaOpenIndex -= 2;}
if (caretOpen && caretOpenIndex > boldOpenIndex){caretOpenIndex -= 2;}
}
} else {
if (string[i] != ' '){
if (italOpen){
boundary = 2;
}
boldOpen = 1; boldOpenIndex = i-2;
}
}
}
asteriskCount = 0;
}
if (string[i] == '*'){asteriskCount++;}
}
/* Strikethroughs */
if (string[i] == '~' && tildaCount < 2){
tildaCount++;
} else {
if (tildaCount){
if (tildaCount == 2){
if (tildaOpen){
if (string[i-3] != ' '){
tildaOpen = 0;
/* Apply strikethrough attributes */
[self applyStrikethroughToString:[self mutableAttributedString] range:CFRangeMake(tildaOpenIndex, (i - tildaOpenIndex))];
/* Remove formatting */
[self removeMarkdownType:CXMarkdownTypeStrikethrough fromString:[self mutableAttributedString] range:CFRangeMake(tildaOpenIndex, (i - tildaOpenIndex))];
/* Adjust length and index */
length -= 4; i -= 4;
/* Update string */
free(string); string = [self charArrayFromAttributedString:[self mutableAttributedString]];
/* Adjust variables */
if (boldOpen && boldOpenIndex > tildaOpenIndex){boldOpenIndex -= 2;}
if (italOpen && italOpenIndex > tildaOpenIndex){italOpenIndex -= 2;}
if (caretOpen && caretOpenIndex > tildaOpenIndex){caretOpenIndex -= 2;}
}
} else {
if (string[i] != ' '){
tildaOpen = 1; tildaOpenIndex = i-2;
}
}
}
}
tildaCount = 0;
if (string[i] == '~'){tildaCount++;}
}
/* Superscript */
if (string[i] == '^'){
if (caretOpen){
/* Apply superscript attributes */
[self applySuperscriptToString:[self mutableAttributedString] range:CFRangeMake(caretOpenIndex, (i - caretOpenIndex)) degree:caretCount];
/* Remove formatting */
[self removeMarkdownType:CXMarkdownTypeSuperscript fromString:[self mutableAttributedString] range:CFRangeMake(caretOpenIndex, 1)];
/* Adjust length and index */
length -= 1; i -= 1;
/* Update string */
free(string); string = [self charArrayFromAttributedString:[self mutableAttributedString]];
/* Increase degree */
caretCount++; caretOpenIndex = i;
/* Adjust variables */
if (italOpen && italOpenIndex > caretOpenIndex){caretOpenIndex -= 1;}
if (boldOpen && boldOpenIndex > caretOpenIndex){boldOpenIndex -= 1;}
if (tildaOpen && tildaOpenIndex > caretOpenIndex){tildaOpenIndex -= 1;}
} else { caretOpen = 1; caretCount++; caretOpenIndex = i;}
} else {
if (caretCount && (string[i] == ' ' || string[i] == '\0')){
/* Apply superscript attributes */
[self applySuperscriptToString:[self mutableAttributedString] range:CFRangeMake(caretOpenIndex, (i - caretOpenIndex)) degree:caretCount];
/* Remove formatting */
[self removeMarkdownType:CXMarkdownTypeSuperscript fromString:[self mutableAttributedString] range:CFRangeMake(caretOpenIndex, 1)];
/* Adjust length and index */
length -= 1; i -= 1;
/* Update string */
free(string); string = [self charArrayFromAttributedString:[self mutableAttributedString]];
/* Clear out degree and close superscript tracking */
caretOpen = 0; caretCount = 0;
/* Adjust variables */
if (italOpen && italOpenIndex > caretOpenIndex){caretOpenIndex -= 1;}
if (boldOpen && boldOpenIndex > caretOpenIndex){boldOpenIndex -= 1;}
if (tildaOpen && tildaOpenIndex > caretOpenIndex){tildaOpenIndex -= 1;}
}
}
}
/* Free allocated memory */
free(string);
CFAbsoluteTime b = CFAbsoluteTimeGetCurrent();
printf("Time in Parser: %f\n",b-a);
}
#pragma mark Public Methods
/* Returns an NSAttributedString with applied Markdown based upon character attributes */
-(NSAttributedString *)attributedStringFromString:(NSString *)string attributes:(NSDictionary *)fontAttributes {
/* Obtain string length */
UInt16 len = [string length];
/* Obtain string as char array */
const char *cstring = [string cStringUsingEncoding:NSUTF8StringEncoding];
/* Obtain Mutable Copy */
char *cstringCopy = malloc(len * sizeof(char));
memcpy(cstringCopy, cstring, len);
/* Build Attributed String */
CFStringRef cfString = (__bridge CFStringRef)string;
CFAttributedStringRef attributedString = CFAttributedStringCreate(kCFAllocatorDefault, cfString, NULL);
CFMutableAttributedStringRef mutableAttributedString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, len, attributedString);
/* Begin Editing */
CFAttributedStringBeginEditing(mutableAttributedString);
/* Add Font and Symbolic Trait */
CFAttributedStringSetAttributes(mutableAttributedString, CFRangeMake(0, len), (__bridge CFDictionaryRef)fontAttributes, YES);
/* End Editing */
CFAttributedStringEndEditing(mutableAttributedString);
/* Set Property */
[self setMutableAttributedString:&mutableAttributedString];
/* Parse String & Format */
[self parseString:cstringCopy ofLength:len];
NSMutableAttributedString *returnString = (__bridge NSMutableAttributedString*)*_mutableAttributedString;
/* Free Memory */
CFRelease(cfString);
CFRelease(attributedString);
CFRelease(mutableAttributedString);
return returnString;
}
/* Returns an NSAttributedString with applied Markdown */
-(NSAttributedString *)attributedStringFromString:(NSString *)string withFontDescriptor:(UIFontDescriptor *)fontDescriptor {
UIFont *font = [UIFont fontWithDescriptor:fontDescriptor size:[[[fontDescriptor fontAttributes]valueForKey:UIFontDescriptorSizeAttribute]floatValue]];
NSNumber *symbolicTrait = [NSNumber numberWithLongLong:[fontDescriptor symbolicTraits]];
NSDictionary *fontAttributes = [[NSDictionary alloc]initWithObjects:@[font,symbolicTrait] forKeys:@[NSFontAttributeName,UIFontSymbolicTrait]];
return [self attributedStringFromString:string attributes:fontAttributes];
}
/* Returns an NSAttributedString with applied Markdown */
-(NSAttributedString *)attributedStringFromString:(NSString *)string {
UIFont *defaultFont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
UIFontDescriptor *defaultDescriptor = [UIFontDescriptor fontDescriptorWithName:[defaultFont fontName] size:[defaultFont pointSize]];
return [self attributedStringFromString:string withFontDescriptor:defaultDescriptor];
}
@end