-
Notifications
You must be signed in to change notification settings - Fork 560
Expand file tree
/
Copy pathNotesTextProcessor.swift
More file actions
1379 lines (1092 loc) · 59.1 KB
/
NotesTextProcessor.swift
File metadata and controls
1379 lines (1092 loc) · 59.1 KB
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// NotesTextStorage.swift
// FSNotes
//
// Created by Oleksandr Glushchenko on 12/26/17.
// Copyright © 2017 Oleksandr Glushchenko. All rights reserved.
//
#if os(OSX)
import Cocoa
import MASShortcut
#else
import UIKit
#endif
public class NotesTextProcessor {
#if os(OSX)
typealias Color = NSColor
typealias Image = NSImage
typealias Font = NSFont
public static var fontColor: NSColor {
get {
return NSColor(named: "mainText")!
}
}
#else
typealias Color = UIColor
typealias Image = UIImage
typealias Font = UIFont
public static var fontColor: UIColor {
get {
return UIColor { (traits) -> UIColor in
return traits.userInterfaceStyle == .dark ?
UIColor.white :
UIColor.black
}
}
}
#endif
// MARK: Syntax highlight customisation
/**
Color used to highlight markdown syntax. Default value is light grey.
*/
public static var syntaxColor = Color.lightGray
public static var yamlOpenerColor = Color.systemRed
public static var codeBackground: PlatformColor {
get {
let isDark = UserDataService.instance.isDark
let editorTheme = UserDefaultsManagement.codeTheme.makeStyle(isDark: isDark)
return editorTheme.backgroundColor
}
}
#if os(OSX)
public static var font: NSFont {
get {
return UserDefaultsManagement.noteFont
}
}
public static var codeSpanBackground: NSColor {
get {
return NSColor(named: "code") ?? NSColor(red:0.97, green:0.97, blue:0.97, alpha:1.0)
}
}
public static var quoteColor: NSColor {
get {
return NSColor(named: "quoteColor")!
}
}
#else
public static var font: UIFont {
get {
return UserDefaultsManagement.noteFont
}
}
public static var codeSpanBackground: UIColor {
get {
return UIColor.codeBackground
}
}
public static var quoteColor: UIColor {
get {
return UIColor.darkGray
}
}
#endif
/**
Quote indentation in points. Default 20.
*/
open var quoteIndendation : CGFloat = 20
static var codeFont = UserDefaultsManagement.codeFont
/**
If the markdown syntax should be hidden or visible
*/
public static var hideSyntax = false
private var note: Note?
private var storage: NSTextStorage?
private var range: NSRange?
private var width: CGFloat?
public static var hl: SwiftHighlighter? = nil
init(note: Note? = nil, storage: NSTextStorage? = nil, range: NSRange? = nil) {
self.note = note
self.storage = storage
self.range = range
}
public static func getHighlighter() -> SwiftHighlighter {
if let instance = self.hl {
return instance
}
let isDark = UserDataService.instance.isDark
let style = UserDefaultsManagement.codeTheme.makeStyle(isDark: isDark)
let highlighter = SwiftHighlighter(options: .init(style: style))
self.hl = highlighter
return highlighter
}
public static func resetCaches() {
NotesTextProcessor.hl = nil
NotesTextProcessor.codeFont = UserDefaultsManagement.codeFont
}
public static func getSpanCodeBlockRange(content: NSMutableAttributedString, range: NSRange) -> NSRange? {
var codeSpan: NSRange?
let paragraphRange = content.mutableString.paragraphRange(for: range)
let paragraph = content.attributedSubstring(from: paragraphRange).string
if paragraph.contains("`") {
NotesTextProcessor.codeSpanRegex.matches(content.string, range: paragraphRange) { (result) -> Void in
if let spanRange = result?.range, spanRange.intersection(range) != nil {
codeSpan = spanRange
}
}
}
return codeSpan
}
fileprivate static var quoteIndendationStyle : NSParagraphStyle {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = CGFloat(UserDefaultsManagement.editorLineSpacing)
return paragraphStyle
}
/**
Coverts App links:`[[Link Title]]` to Markdown: `[Link](fsnotes://find/link%20title)`
- parameter content: A string containing CommonMark Markdown
- returns: Content string with converted links
*/
public static func convertAppLinks(in content: NSMutableAttributedString, codeBlockRanges: [NSRange]?) -> NSMutableAttributedString {
let attributedString = content.mutableCopy() as! NSMutableAttributedString
let range = NSRange(0..<content.string.utf16.count)
let tagQuery = "fsnotes://find?id="
NotesTextProcessor.appUrlRegex.matches(content.string, range: range, completion: { (result) -> (Void) in
guard let innerRange = result?.range else { return }
var substring = attributedString.mutableString.substring(with: innerRange)
substring = substring
.replacingOccurrences(of: "[[", with: "")
.replacingOccurrences(of: "]]", with: "")
.trim()
guard let tag = substring.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else { return }
attributedString.addAttribute(.link, value: "\(tagQuery)\(tag)", range: innerRange)
})
attributedString.enumerateAttribute(.link, in: range) { (value, range, _) in
if let value = value as? String, value.starts(with: tagQuery) {
if let tag = value
.replacingOccurrences(of: tagQuery, with: "")
.removingPercentEncoding
{
if NotesTextProcessor.getSpanCodeBlockRange(content: attributedString, range: range) != nil {
return
}
if let codeRanges = codeBlockRanges {
for codeRange in codeRanges {
if NSIntersectionRange(codeRange, range).length > 0 {
return
}
}
}
let link = "[\(tag)](\(value))"
attributedString.replaceCharacters(in: range, with: link)
}
}
}
return attributedString
}
public static func convertAppTags(in content: NSMutableAttributedString, codeBlockRanges: [NSRange]?) -> NSMutableAttributedString {
let attributedString = content.mutableCopy() as! NSMutableAttributedString
guard UserDefaultsManagement.inlineTags else { return attributedString}
let range = NSRange(0..<content.string.utf16.count)
let tagQuery = "fsnotes://open/?tag="
FSParser.tagsInlineRegex.matches(content.string, range: range) { (result) -> Void in
guard var range = result?.range(at: 1) else { return }
var substring = attributedString.mutableString.substring(with: range)
guard !substring.isNumber else { return }
range = NSRange(location: range.location - 1, length: range.length + 1)
substring = attributedString.mutableString.substring(with: range)
.replacingOccurrences(of: "#", with: "")
.replacingOccurrences(of: "\n", with: "")
.trim()
guard let tag = substring.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return }
attributedString.addAttribute(.link, value: "\(tagQuery)\(tag)", range: range)
}
attributedString.enumerateAttribute(.link, in: range) { (value, range, _) in
if let value = value as? String, value.starts(with: tagQuery) {
if let tag = value
.replacingOccurrences(of: tagQuery, with: "")
.removingPercentEncoding
{
if NotesTextProcessor.getSpanCodeBlockRange(content: attributedString, range: range) != nil {
return
}
if let codeRanges = codeBlockRanges {
for codeRange in codeRanges {
if NSIntersectionRange(codeRange, range).length > 0 {
return
}
}
}
let link = "[#\(tag)](\(value))"
attributedString.replaceCharacters(in: range, with: link)
}
}
}
return attributedString
}
public static func highlight(attributedString: NSMutableAttributedString) {
let ranges = CodeBlockDetector.shared.findCodeBlocks(in: attributedString)
NotesTextProcessor.highlightMarkdown(attributedString: attributedString, codeBlockRanges: ranges)
for range in ranges {
NotesTextProcessor
.getHighlighter()
.highlight(in: attributedString, fullRange: range)
}
}
public static func removeFontTraits(
_ traitsToRemove: FontTraits,
range: NSRange,
attributedString: NSMutableAttributedString
) {
let baseFont = UserDefaultsManagement.noteFont
let pointSize = baseFont.pointSize
attributedString.enumerateAttribute(.font, in: range) { value, subrange, _ in
guard let font = value as? PlatformFont else { return }
let currentTraits = font.fontDescriptor.symbolicTraits
guard !currentTraits.isDisjoint(with: traitsToRemove) else { return }
let newTraits = currentTraits.subtracting(traitsToRemove)
let newDesc = font.fontDescriptor.withSymbolicTraits(newTraits)
#if os(iOS)
guard let newDesc = newDesc else { return }
let newFont = PlatformFont(descriptor: newDesc, size: pointSize)
#else
guard let newFont = PlatformFont(descriptor: newDesc, size: pointSize) else { return }
#endif
attributedString.addAttribute(.font, value: newFont, range: subrange)
}
}
public static func addFontTraits(
_ traitsToAdd: FontTraits,
range: NSRange,
attributedString: NSMutableAttributedString
) {
attributedString.enumerateAttribute(.font, in: range) { value, subrange, _ in
guard let font = (value as? PlatformFont) else { return }
let currentTraits = font.fontDescriptor.symbolicTraits
let newTraits = currentTraits.union(traitsToAdd)
let newDesc = font.fontDescriptor.withSymbolicTraits(newTraits)
#if os(iOS)
guard let newDesc = newDesc else { return }
let newFont = PlatformFont(descriptor: newDesc, size: font.pointSize)
#else
guard let newFont = PlatformFont(descriptor: newDesc, size: font.pointSize) else { return }
#endif
attributedString.addAttribute(.font, value: newFont, range: subrange)
}
}
public static func resetFont(attributedString: NSMutableAttributedString, paragraphRange: NSRange) {
attributedString.addAttribute(.font, value: font, range: paragraphRange)
attributedString.fixAttributes(in: paragraphRange)
}
public static func highlightMarkdown(attributedString: NSMutableAttributedString, paragraphRange: NSRange? = nil, codeBlockRanges: [NSRange]? = nil) {
let paragraphRange = paragraphRange ?? NSRange(0..<attributedString.length)
attributedString.beginEditing()
if paragraphRange.length == attributedString.length {
// Initial operation
resetFont(attributedString: attributedString, paragraphRange: paragraphRange)
} else {
removeFontTraits([.bold, .italic], range: paragraphRange, attributedString: attributedString)
}
defer {
attributedString.endEditing()
}
let string = attributedString.string
let pointSize = UserDefaultsManagement.noteFont.pointSize
let codeFont = UserDefaultsManagement.codeFont
#if os(OSX)
let hiddenFont = NSFont.systemFont(ofSize: 0.1)
#else
let hiddenFont = UIFont.systemFont(ofSize: 0.1)
#endif
let hiddenColor = Color.clear
let hiddenAttributes: [NSAttributedString.Key : Any] = [
.font : hiddenFont,
.foregroundColor : hiddenColor
]
func hideSyntaxIfNecessary(range: @autoclosure () -> NSRange) {
guard NotesTextProcessor.hideSyntax else { return }
attributedString.addAttributes(hiddenAttributes, range: range())
}
attributedString.enumerateAttribute(.link, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if value != nil && attributedString.attribute(.attachment, at: range.location, effectiveRange: nil) == nil {
attributedString.removeAttribute(.link, range: range)
}
}
attributedString.enumerateAttribute(.strikethroughStyle, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if value != nil {
attributedString.removeAttribute(.strikethroughStyle, range: range)
}
}
attributedString.enumerateAttribute(.tag, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if value != nil {
attributedString.removeAttribute(.tag, range: range)
}
}
#if os(iOS)
attributedString.addAttribute(.foregroundColor, value: UIColor.blackWhite, range: paragraphRange)
#else
attributedString.addAttribute(.foregroundColor, value: fontColor, range: paragraphRange)
attributedString.enumerateAttribute(.foregroundColor, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if (value as? NSColor) != nil {
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.fontColor, range: range)
}
}
#endif
// We detect and process inline links not formatted
NotesTextProcessor.autolinkRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard var range = result?.range else { return }
var substring = attributedString.mutableString.substring(with: range)
guard substring.lengthOfBytes(using: .utf8) > 0 else { return }
if ["!", "?", ";", ":", ".", ",", "_"].contains(substring.last) {
range = NSRange(location: range.location, length: range.length - 1)
substring = String(substring.dropLast())
}
if substring.first == "(" {
range = NSRange(location: range.location + 1, length: range.length - 1)
}
if substring.last == ")" {
range = NSRange(location: range.location, length: range.length - 1)
}
if let url = URL(string: substring) {
attributedString.addAttribute(.link, value: url, range: range)
} else if let substring = String(substring).addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) {
attributedString.addAttribute(.link, value: substring, range: range)
}
if NotesTextProcessor.hideSyntax {
NotesTextProcessor.autolinkPrefixRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.font, value: hiddenFont, range: innerRange)
attributedString.fixAttributes(in: innerRange)
attributedString.addAttribute(.foregroundColor, value: hiddenColor, range: innerRange)
}
}
}
FSParser.yamlBlockRegex.matches(string, range: NSRange(location: 0, length: attributedString.length)) { (result) -> Void in
guard let range = result?.range(at: 1) else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.fontColor, range: range)
if range.location == 0 {
let listOpeningRegex = MarklightRegex(pattern: "([a-zA-Z_]+):", options: [.allowCommentsAndWhitespace])
listOpeningRegex.matches(string, range: range) { (result) -> Void in
guard let range = result?.range(at: 0) else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.yamlOpenerColor, range: range)
}
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.yamlOpenerColor, range: NSRange(location: 0, length: 3))
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.yamlOpenerColor, range: NSRange(location: range.length - 3, length: 3))
attributedString.addAttribute(NSAttributedString.Key.yamlBlock, value: range, range: range)
}
}
// We detect and process underlined headers
NotesTextProcessor.headersSetextRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.enumerateAttribute(.font, in: range) { value, subrange, _ in
guard let font = value as? PlatformFont else { return }
let headerFont = NotesTextProcessor.getHeaderFont(level: 1, baseFont: font, baseFontSize: pointSize)
attributedString.addAttribute(.font, value: headerFont, range: subrange)
}
NotesTextProcessor.headersSetextUnderlineRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: NSMakeRange(innerRange.location, innerRange.length))
}
}
// We detect and process dashed headers
NotesTextProcessor.headersAtxRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range,
let headerMarksRange = result?.range(at: 1) else { return }
let headerLevel = headerMarksRange.length
attributedString.enumerateAttribute(.font, in: range) { value, subrange, _ in
guard let font = value as? PlatformFont else { return }
let headerFont = NotesTextProcessor.getHeaderFont(level: headerLevel, baseFont: font, baseFontSize: pointSize)
attributedString.addAttribute(.font, value: headerFont, range: subrange)
}
NotesTextProcessor.headersAtxOpeningRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
let syntaxRange = NSMakeRange(innerRange.location, innerRange.length + 1)
hideSyntaxIfNecessary(range: syntaxRange)
}
NotesTextProcessor.headersAtxClosingRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
}
// We detect and process reference links
NotesTextProcessor.referenceLinkRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: range)
}
// We detect and process lists
NotesTextProcessor.listRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
NotesTextProcessor.listOpeningRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
}
#if IOS_APP || os(OSX)
// We detect and process inline anchors (links)
NotesTextProcessor.anchorInlineRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.font, value: codeFont, range: range)
//attributedString.fixAttributes(in: range)
var destinationLink : String?
NotesTextProcessor.coupleRoundRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
guard let linkRange = result?.range(at: 3), linkRange.length > 0 else { return }
let substring = attributedString.mutableString.substring(with: linkRange)
guard substring.count > 0 else { return }
destinationLink = substring
attributedString.addAttribute(.link, value: substring, range: linkRange)
hideSyntaxIfNecessary(range: innerRange)
}
NotesTextProcessor.openingSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
NotesTextProcessor.closingSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
guard let destinationLinkString = destinationLink else { return }
NotesTextProcessor.coupleSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
var _range = innerRange
_range.location = _range.location + 1
_range.length = _range.length - 2
let substring = attributedString.mutableString.substring(with: _range)
guard substring.lengthOfBytes(using: .utf8) > 0 else { return }
attributedString.addAttribute(.link, value: destinationLinkString, range: _range)
}
}
#endif
NotesTextProcessor.anchorInlineGFMRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.font, value: codeFont, range: range)
//attributedString.fixAttributes(in: range)
var destinationLink : String?
NotesTextProcessor.coupleRoundRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
if let linkRange = result?.range(at: 3), linkRange.length > 0 {
let substring = attributedString.mutableString.substring(with: linkRange)
guard substring.count > 0 else { return }
destinationLink = substring
attributedString.addAttribute(.link, value: substring, range: linkRange)
let fullURL = attributedString.mutableString.substring(with: innerRange)
if let angleStart = fullURL.range(of: "<")?.lowerBound,
let angleEnd = fullURL.range(of: ">", options: .backwards)?.upperBound {
let startOffset = fullURL.distance(from: fullURL.startIndex, to: angleStart)
let endOffset = fullURL.distance(from: fullURL.startIndex, to: angleEnd)
let openAngleRange = NSRange(location: innerRange.location + startOffset, length: 1)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: openAngleRange)
hideSyntaxIfNecessary(range: openAngleRange)
let closeAngleRange = NSRange(location: innerRange.location + endOffset - 1, length: 1)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: closeAngleRange)
hideSyntaxIfNecessary(range: closeAngleRange)
}
} else if let linkRange = result?.range(at: 4), linkRange.length > 0 {
let substring = attributedString.mutableString.substring(with: linkRange)
guard substring.count > 0 else { return }
destinationLink = substring
attributedString.addAttribute(.link, value: substring, range: linkRange)
}
hideSyntaxIfNecessary(range: innerRange)
}
// Opening [
NotesTextProcessor.openingSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
// Closing ]
NotesTextProcessor.closingSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
guard let destinationLinkString = destinationLink else { return }
// Title [text]
NotesTextProcessor.coupleSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
var _range = innerRange
_range.location = _range.location + 1
_range.length = _range.length - 2
let substring = attributedString.mutableString.substring(with: _range)
guard substring.lengthOfBytes(using: .utf8) > 0 else { return }
attributedString.addAttribute(.link, value: destinationLinkString, range: _range)
}
}
// We detect and process app urls [[link]]
NotesTextProcessor.appUrlRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let innerRange = result?.range else { return }
var _range = innerRange
_range.location = _range.location + 2
_range.length = _range.length - 4
let appLink = attributedString.mutableString.substring(with: _range)
guard !appLink.startsWith(string: "`") else { return }
if let link = appLink.addingPercentEncoding(withAllowedCharacters: .alphanumerics) {
#if os(iOS)
attributedString.addAttribute(.foregroundColor, value: UIColor.wikiColor, range: innerRange)
#endif
attributedString.addAttribute(.link, value: "fsnotes://find?id=" + link, range: _range)
if let range = result?.range(at: 0) {
attributedString.addAttribute(.foregroundColor, value: Color.gray, range: range)
}
if let range = result?.range(at: 2) {
attributedString.addAttribute(.foregroundColor, value: Color.gray, range: range)
}
}
}
// We detect and process quotes
NotesTextProcessor.blockQuoteRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.foregroundColor, value: quoteColor, range: range)
NotesTextProcessor.blockQuoteOpeningRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
}
// We detect and process italics
NotesTextProcessor.strictItalicRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range(at: 3) else { return }
if NotesTextProcessor.isLink(attributedString: attributedString, range: range) {
return
}
addFontTraits([.italic], range: range, attributedString: attributedString)
NotesTextProcessor.strictBoldRegex.matches(string, range: range) { (result) -> Void in
guard let range = result?.range else { return }
addFontTraits([.bold], range: range, attributedString: attributedString)
}
let preRange = NSMakeRange(range.location - 1, 1)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: preRange)
hideSyntaxIfNecessary(range: preRange)
let postRange = NSMakeRange(range.location + range.length, 1)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: postRange)
hideSyntaxIfNecessary(range: postRange)
}
// We detect and process bolds
NotesTextProcessor.strictBoldRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range(at: 3) else { return }
let boldString = attributedString.attributedSubstring(from: range)
if boldString.string.contains("__") || boldString.string == "_" {
return
}
if NotesTextProcessor.isLink(attributedString: attributedString, range: range) {
return
}
if let font = boldString.attribute(.font, at: 0, effectiveRange: nil) as? Font, font.isItalic {
} else {
addFontTraits([.bold], range: range, attributedString: attributedString)
NotesTextProcessor.strictItalicRegex.matches(string, range: range) { (result) -> Void in
guard let range = result?.range else { return }
addFontTraits([.italic], range: range, attributedString: attributedString)
}
}
let preRange = NSMakeRange(range.location - 2, 2)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: preRange)
hideSyntaxIfNecessary(range: preRange)
let postRange = NSMakeRange(range.location + range.length, 2)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: postRange)
hideSyntaxIfNecessary(range: postRange)
}
// NotesTextProcessor.italicRegex.matches(string, range: paragraphRange) { (result) -> Void in
// guard let range = result?.range else { return }
// addFontTraits([.italic], range: range, attributedString: attributedString)
//
// let preRange = NSMakeRange(range.location, 1)
// attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: preRange)
//
// let postRange = NSMakeRange(range.location + range.length - 1, 1)
// attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: postRange)
// }
//
// NotesTextProcessor.boldRegex.matches(string, range: paragraphRange) { (result) -> Void in
// guard let range = result?.range else { return }
// addFontTraits([.bold], range: range, attributedString: attributedString)
//
// let preRange = NSMakeRange(range.location, 2)
// attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: preRange)
//
// let postRange = NSMakeRange(range.location + range.length - 2, 2)
// attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: postRange)
// }
// We detect and process bolds
NotesTextProcessor.strikeRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: range.location + 2, length: range.length - 4))
//attributedString.fixAttributes(in: range)
let preRange = NSMakeRange(range.location, 2)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: preRange)
hideSyntaxIfNecessary(range: preRange)
let postRange = NSMakeRange(range.location + range.length - 2, 2)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: postRange)
hideSyntaxIfNecessary(range: postRange)
}
// We detect and process inline mailto links not formatted
NotesTextProcessor.autolinkEmailRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
let substring = attributedString.mutableString.substring(with: range)
guard substring.lengthOfBytes(using: .utf8) > 0, URL(string: substring) != nil else { return }
if substring.isValidEmail() {
attributedString.addAttribute(.link, value: "mailto:\(substring)", range: range)
} else {
attributedString.addAttribute(.link, value: substring, range: range)
}
if NotesTextProcessor.hideSyntax {
NotesTextProcessor.mailtoRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.font, value: hiddenFont, range: innerRange)
attributedString.addAttribute(.foregroundColor, value: hiddenColor, range: innerRange)
}
}
}
// Inline tags
if UserDefaultsManagement.inlineTags {
FSParser.tagsInlineRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard var range = result?.range(at: 1) else { return }
// Skip if indented code block
let parRange = attributedString.mutableString.paragraphRange(for: range)
let parString = attributedString.mutableString.substring(with: parRange)
if parString.starts(with: " ") || parString.starts(with: "\t") {
return
}
if NotesTextProcessor.getSpanCodeBlockRange(content: attributedString, range: range) != nil {
return
}
if let ranges = codeBlockRanges {
for range in ranges {
if NSIntersectionRange(range, parRange).length > 0 {
return
}
}
}
var substring = attributedString.mutableString.substring(with: range)
guard !substring.isNumber && !substring.isHexColor() else { return }
range = NSRange(location: range.location - 1, length: range.length + 1)
substring = attributedString.mutableString.substring(with: range)
.replacingOccurrences(of: "#", with: "")
.replacingOccurrences(of: "\n", with: "")
.trim()
guard let tag = substring.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return }
attributedString.addAttribute(.link, value: "fsnotes://open/?tag=\(tag)", range: range)
attributedString.addAttribute(.tag, value: "\(tag)", range: range)
}
}
attributedString.enumerateAttribute(.attachment, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if value != nil, let todo = attributedString.attribute(.todo, at: range.location, effectiveRange: nil) {
let strikeRange = attributedString.mutableString.paragraphRange(for: range)
attributedString.addAttribute(.strikethroughStyle, value: todo, range: strikeRange)
}
}
guard UserDefaultsManagement.codeBlockHighlight else { return }
// Code span removed
attributedString.enumerateAttribute(.backgroundColor, in: paragraphRange) { (value, innerRange, _) in
if value != nil {
let font = UserDefaultsManagement.noteFont
attributedString.removeAttribute(.backgroundColor, range: innerRange)
attributedString.addAttribute(.font, value: font, range: innerRange)
attributedString.fixAttributes(in: innerRange)
}
}
NotesTextProcessor.codeSpanRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
if attributedString.mutableString.substring(with: range).startsWith(string: "```") {
return
}
attributedString.addAttribute(.font, value: codeFont, range: range)
attributedString.fixAttributes(in: range)
attributedString.addAttribute(.backgroundColor, value: NotesTextProcessor.codeSpanBackground, range: range)
NotesTextProcessor.codeSpanOpeningRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
NotesTextProcessor.codeSpanClosingRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
}
}
public static func isLink(attributedString: NSAttributedString, range: NSRange) -> Bool {
return attributedString.attributedSubstring(from: range).attribute(.link, at: 0, effectiveRange: nil) != nil
}
/// Tabs are automatically converted to spaces as part of the transform
/// this constant determines how "wide" those tabs become in spaces
public static let _tabWidth = 4
// MARK: Headers
/*
Head
======
Subhead
-------
*/
fileprivate static let headerSetextPattern = [
"^(.+?)",
"\\p{Z}*",
"\\n",
"(==+)", // $1 = string of ='s or -'s
"\\p{Z}*",
"\\n|\\Z"
].joined(separator: "\n")
public static let headersSetextRegex = MarklightRegex(pattern: headerSetextPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let setextUnderlinePattern = [
"(==+|--+) # $1 = string of ='s or -'s",
"\\p{Z}*$"
].joined(separator: "\n")
public static let headersSetextUnderlineRegex = MarklightRegex(pattern: setextUnderlinePattern, options: [.allowCommentsAndWhitespace])
/*
# Head
## Subhead ##
*/
fileprivate static let headerAtxPattern = [
"^(\\#{1,6}\\ ) # $1 = string of #'s",
"\\p{Z}*",
"(.+?) # $2 = Header text",
"\\p{Z}*",
"\\#* # optional closing #'s (not counted)",
"(?:\\n|\\Z)"
].joined(separator: "\n")
public static let headersAtxRegex = MarklightRegex(pattern: headerAtxPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let headersAtxOpeningPattern = [
"^(\\#{1,6}\\ )"
].joined(separator: "\n")
public static let headersAtxOpeningRegex = MarklightRegex(pattern: headersAtxOpeningPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let headersAtxClosingPattern = [
"\\#{1,6}\\ \\n+"
].joined(separator: "\n")
public static let headersAtxClosingRegex = MarklightRegex(pattern: headersAtxClosingPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
// MARK: Reference links
/*
TODO: we don't know how reference links are formed
*/
fileprivate static let referenceLinkPattern = [
"^\\p{Z}{0,\(_tabWidth - 1)}\\[([^\\[\\]]+)\\]: # id = $1",
" \\p{Z}*",
" \\n? # maybe *one* newline",
" \\p{Z}*",
"<?(\\S+?)>? # url = $2",
" \\p{Z}*",
" \\n? # maybe one newline",
" \\p{Z}*",
"(?:",
" (?<=\\s) # lookbehind for whitespace",
" [\"(]",
" (.+?) # title = $3",
" [\")]",
" \\p{Z}*",
")? # title is optional",
"(?:\\n|\\Z)"
].joined(separator: "")
public static let referenceLinkRegex = MarklightRegex(pattern: referenceLinkPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
// MARK: Lists
/*
* First element
* Second element
*/
fileprivate static let _markerUL = "[*+-]"
fileprivate static let _markerOL = "[0-9-]+[.]"
fileprivate static let _listMarker = "(?:\\p{Z}|\\t)*(?:\(_markerUL)|\(_markerOL))"
fileprivate static let _listSingleLinePattern = "^(?:\\p{Z}|\\t)*((?:[*+-]|\\d+[.]))\\p{Z}+"
public static let listRegex = MarklightRegex(pattern: _listSingleLinePattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
public static let listOpeningRegex = MarklightRegex(pattern: _listMarker, options: [.allowCommentsAndWhitespace])
// MARK: Anchors
/*
[Title](http://example.com)
*/
fileprivate static let anchorPattern = [
"( # wrap whole match in $1",
" \\[",
" (\(NotesTextProcessor.getNestedBracketsPattern())) # link text = $2",
" \\]",
"",
" \\p{Z}? # one optional space",