-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-notes-cli.py
More file actions
1405 lines (1215 loc) · 63.3 KB
/
Copy pathgenerate-notes-cli.py
File metadata and controls
1405 lines (1215 loc) · 63.3 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
#!/usr/bin/env python3
"""
Generate notekit-generated.m from NotesShared private API.
USAGE:
python3 generate-notes-cli.py > notekit-generated.m
# Then: make notekit
MAINTENANCE:
This generator produces notekit-generated.m — the foundation layer of
notekit: framework loading, helpers, Core Data queries, note serialization,
and basic CRUD commands.
Handwritten code (markdown I/O, diff engine, install-skill, tests, usage,
main) lives in notekit-handwritten.m, notekit-tests.m, and notekit.m.
To add a new READ property:
1. Add to NOTE_READ_PROPS below
2. Regenerate: python3 generate-notes-cli.py > notekit-generated.m && make notekit
To add a new framework class:
1. Add to FRAMEWORK_CLASSES below
2. Regenerate
To discover new properties/methods:
make notes-inspect && ./notes-inspect 2>&1 | less
Architecture:
notes-inspect.m → dumps ObjC runtime properties/methods
generate-notes-cli.py → generates notekit-generated.m (this file)
notekit-generated.m → AUTO-GENERATED, do not edit manually
notekit-handwritten.m → manually maintained features
notekit-tests.m → manually maintained tests
notekit.m → hub file (#includes + main)
"""
# --- Configuration ---
# Properties to expose on ICNote (read)
NOTE_READ_PROPS = {
"title": ("title", "string"),
"noteAsPlainTextWithoutTitle": ("body", "string"),
"folderName": ("folder", "string"),
"creationDate": ("createdAt", "date"),
"modificationDate": ("modifiedAt", "date"),
"hasChecklist": ("hasChecklist", "bool"),
"isPinned": ("isPinned", "bool"),
"hasTags": ("hasTags", "bool"),
"identifier": ("id", "string"),
"snippet": ("snippet", "string"),
}
# Classes to load from NotesShared.framework
FRAMEWORK_CLASSES = [
"ICNoteContext",
"ICNote",
"ICTTParagraphStyle",
"ICTTTodo",
"ICTTAttachment",
]
def generate_framework_loading():
lines = ['// --- Framework Loading ---', '']
for cls in FRAMEWORK_CLASSES:
lines.append(f'static Class {cls}Class;')
lines.append('')
lines.append('static void loadFramework(void) {')
lines.append(' [[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/NotesShared.framework"] load];')
for cls in FRAMEWORK_CLASSES:
lines.append(f' {cls}Class = NSClassFromString(@"{cls}");')
lines.append('}')
lines.append('')
lines.append('static void printFDATroubleshootingSteps(void); // forward declaration')
lines.append('')
lines.append('static id getViewContext(void) {')
lines.append(' ((void (*)(id, SEL, NSUInteger))objc_msgSend)(ICNoteContextClass, sel_registerName("startSharedContextWithOptions:"), 0);')
lines.append(' id context = ((id (*)(id, SEL))objc_msgSend)(ICNoteContextClass, sel_registerName("sharedContext"));')
lines.append(' id container = ((id (*)(id, SEL))objc_msgSend)(context, sel_registerName("persistentContainer"));')
lines.append(' // Check if persistent stores loaded — if empty, Core Data could not open')
lines.append(' // the SQLite database (typically a Full Disk Access / sandbox denial).')
lines.append(' // Core Data logs errors to stderr but does not propagate an NSError,')
lines.append(' // so fetch requests succeed with empty results instead of failing.')
lines.append(' id coordinator = ((id (*)(id, SEL))objc_msgSend)(container, sel_registerName("persistentStoreCoordinator"));')
lines.append(' NSArray *stores = ((id (*)(id, SEL))objc_msgSend)(coordinator, sel_registerName("persistentStores"));')
lines.append(' if (!stores || stores.count == 0) {')
lines.append(' fprintf(stderr, "\\nError: Could not open Apple Notes database.\\n");')
lines.append(' fprintf(stderr, "Diagnostics: container=%s, coordinator=%s, stores=%s\\n",')
lines.append(' container ? "ok" : "nil", coordinator ? "ok" : "nil",')
lines.append(' stores ? [[NSString stringWithFormat:@"empty(%lu)", (unsigned long)stores.count] UTF8String] : "nil");')
lines.append(' fprintf(stderr, "\\nPossible causes:\\n");')
lines.append(' fprintf(stderr, " - Missing Full Disk Access (most common)\\n");')
lines.append(' fprintf(stderr, " - Corrupted Notes database\\n");')
lines.append(' fprintf(stderr, " - Core Data initialization failure\\n\\n");')
lines.append(' fprintf(stderr, "If Full Disk Access is missing, try:\\n");')
lines.append(' printFDATroubleshootingSteps();')
lines.append(' exit(1);')
lines.append(' }')
lines.append(' return ((id (*)(id, SEL))objc_msgSend)(container, sel_registerName("viewContext"));')
lines.append('}')
return '\n'.join(lines)
def generate_helpers():
return '''// --- Helpers ---
static void errorExit(NSString *msg) {
fprintf(stderr, "Error: %s\\n", [msg UTF8String]);
exit(1);
}
// Return Full Disk Access troubleshooting text (no preamble).
// Testable: callers can inspect the string; printFDATroubleshootingSteps() prints it.
static NSString *fdaTroubleshootingText(void) {
return @" 1. Open Full Disk Access settings (run this command):\\n"
@" open \\"x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles\\"\\n\\n"
@" 2. Add the app that launched notekit and toggle it ON\\n"
@" Examples: Terminal, iTerm, Ghostty, VS Code, Cursor, or Claude\\n\\n"
@" 3. If access still fails, remove stale notekit entries from the list\\n"
@" and make sure the launching app is toggled ON\\n\\n"
@"Then retry: notekit folders\\n\\n"
@"If you run notekit with NOTEKIT_SELF_DISCLAIM=1:\\n"
@" Grant Full Disk Access to the notekit entry instead of the launching app.\\n";
}
static void printFDATroubleshootingSteps(void) {
fprintf(stderr, "%s", [fdaTroubleshootingText() UTF8String]);
}
// Recursively check an NSError chain for a specific domain+code pair.
// Inspects the error itself, NSUnderlyingError, and NSDetailedErrors.
static BOOL errorChainContains(NSError *error, NSString *domain, NSInteger code) {
if (!error) return NO;
if ([[error domain] isEqualToString:domain] && [error code] == code) return YES;
// Check single underlying error
NSError *underlying = [[error userInfo] objectForKey:@"NSUnderlyingError"];
if (errorChainContains(underlying, domain, code)) return YES;
// Check detailed errors array (Core Data batch errors)
NSArray *detailed = [[error userInfo] objectForKey:@"NSDetailedErrors"];
for (NSError *detail in detailed) {
if (errorChainContains(detail, domain, code)) return YES;
}
return NO;
}
// Check if a Core Data error is a permission/sandbox denial and print
// actionable troubleshooting steps. Returns YES if it handled the error
// (and exited), NO if the error is unrelated to permissions.
static BOOL checkNotesAccessError(NSError *error) {
if (!error) return NO;
// NSCocoaErrorDomain 256 = NSFileReadNoPermissionError (sandbox / Full Disk Access)
BOOL isSandbox = errorChainContains(error, @"NSCocoaErrorDomain", 256);
// NSSQLiteErrorDomain 23 = SQLITE_AUTH (sandbox denied at SQLite level)
if (!isSandbox) isSandbox = errorChainContains(error, @"NSSQLiteErrorDomain", 23);
// NSCocoaErrorDomain 4097 = NSXPCConnectionInterrupted — only treat as
// permission denied when the description mentions access/permission to
// avoid false positives from transient XPC failures.
BOOL isPermDenied = NO;
if (errorChainContains(error, @"NSCocoaErrorDomain", 4097)) {
NSString *desc = [[error localizedDescription] lowercaseString];
if ([desc containsString:@"permission"] || [desc containsString:@"denied"] ||
[desc containsString:@"access"]) {
isPermDenied = YES;
}
}
if (!isSandbox && !isPermDenied) return NO;
fprintf(stderr, "Error: Notes access denied.\\n\\n");
fprintf(stderr, "notekit requires Full Disk Access to read Apple Notes.\\n");
printFDATroubleshootingSteps();
exit(1);
return YES; // unreachable, silences compiler warning
}
static BOOL isStrictInteger(NSString *str, NSInteger *outValue) {
NSScanner *scanner = [NSScanner scannerWithString:str];
NSInteger value;
if ([scanner scanInteger:&value] && [scanner isAtEnd]) {
if (outValue) *outValue = value;
return YES;
}
return NO;
}
static BOOL isValidStyle(NSInteger style) {
return style == 0 || style == 1 || style == 2 || style == 3 || style == 4 || style == 100 || style == 101 || style == 102 || style == 103;
}
static NSString *hexStringForColor(id color) {
if (!color) return nil;
@try {
if (CFGetTypeID((__bridge CFTypeRef)color) == CGColorGetTypeID()) {
CGColorRef cgColor = (__bridge CGColorRef)color;
NSColor *nsColor = [NSColor colorWithCGColor:cgColor];
if (!nsColor) return nil;
color = nsColor;
}
if (![color respondsToSelector:@selector(colorUsingColorSpace:)]) return nil;
NSColor *rgb = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]];
if (!rgb) return nil;
CGFloat r = 0, g = 0, b = 0, a = 0;
[rgb getRed:&r green:&g blue:&b alpha:&a];
return [NSString stringWithFormat:@"#%02x%02x%02x",
(unsigned int)lrint(MAX(0.0, MIN(1.0, r)) * 255.0),
(unsigned int)lrint(MAX(0.0, MIN(1.0, g)) * 255.0),
(unsigned int)lrint(MAX(0.0, MIN(1.0, b)) * 255.0)];
} @catch (NSException *e) {
return nil;
}
}
static BOOL parseHexColor(NSString *input, NSString **normalizedHex, NSColor **outColor) {
if (!input) return NO;
NSString *trimmed = [input stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([trimmed hasPrefix:@"#"]) trimmed = [trimmed substringFromIndex:1];
if (trimmed.length != 3 && trimmed.length != 6) return NO;
NSCharacterSet *hexSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF"];
if ([trimmed rangeOfCharacterFromSet:[hexSet invertedSet]].location != NSNotFound) return NO;
if (trimmed.length == 3) {
unichar r = [trimmed characterAtIndex:0];
unichar g = [trimmed characterAtIndex:1];
unichar b = [trimmed characterAtIndex:2];
trimmed = [NSString stringWithFormat:@"%C%C%C%C%C%C", r, r, g, g, b, b];
}
NSString *lower = [trimmed lowercaseString];
unsigned int rgb = 0;
NSScanner *scanner = [NSScanner scannerWithString:lower];
if (![scanner scanHexInt:&rgb] || ![scanner isAtEnd]) return NO;
CGFloat r = ((rgb >> 16) & 0xff) / 255.0;
CGFloat g = ((rgb >> 8) & 0xff) / 255.0;
CGFloat b = (rgb & 0xff) / 255.0;
if (normalizedHex) *normalizedHex = [@"#" stringByAppendingString:lower];
if (outColor) *outColor = [NSColor colorWithSRGBRed:r green:g blue:b alpha:1.0];
return YES;
}
static void setMergeableAttributesPreservingText(id ms, NSDictionary *attrs, NSRange range) {
if (range.length == 0) return;
id msAS = ((id (*)(id, SEL))objc_msgSend)(ms, sel_registerName("string"));
NSString *msStr = (msAS && [msAS respondsToSelector:@selector(string)]) ? [msAS string] : (NSString *)msAS;
if (msStr && range.location + range.length <= msStr.length) {
NSString *text = [msStr substringWithRange:range];
NSAttributedString *replacement = [[NSAttributedString alloc] initWithString:text attributes:attrs];
if ([ms respondsToSelector:sel_registerName("replaceCharactersInRange:withAttributedString:")]) {
((void (*)(id, SEL, NSRange, id))objc_msgSend)(ms,
sel_registerName("replaceCharactersInRange:withAttributedString:"), range, replacement);
return;
}
}
((void (*)(id, SEL, id, NSRange))objc_msgSend)(ms, sel_registerName("setAttributes:range:"), attrs, range);
}
static id makeParagraphStyle(NSInteger style) {
id paraStyle = [[ICTTParagraphStyleClass alloc] init];
((void (*)(id, SEL, NSUInteger))objc_msgSend)(paraStyle, sel_registerName("setStyle:"), (NSUInteger)style);
if (style == 103) {
id todo = ((id (*)(id, SEL, id, BOOL))objc_msgSend)(
[ICTTTodoClass alloc],
sel_registerName("initWithIdentifier:done:"),
[NSUUID UUID], NO);
((void (*)(id, SEL, id))objc_msgSend)(paraStyle, sel_registerName("setTodo:"), todo);
}
return paraStyle;
}
static NSString *dateToISO(NSDate *date) {
if (!date) return nil;
NSISO8601DateFormatter *fmt = [[NSISO8601DateFormatter alloc] init];
return [fmt stringFromDate:date];
}
static void printJSON(id obj) {
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:obj
options:NSJSONWritingPrettyPrinted | NSJSONWritingSortedKeys error:&error];
if (error) errorExit([error localizedDescription]);
printf("%s\\n", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding].UTF8String);
}'''
def generate_fetch_helpers():
return '''// --- Fetch Helpers ---
// Predicate helpers to exclude soft-deleted items from Core Data queries.
// markedForDeletion is set by ICFolder/ICNote.markForDeletion when items
// are moved to Recently Deleted. folderType=1 is the Recently Deleted
// system folder container itself.
static NSPredicate *activeFolderPredicate(void) {
return [NSPredicate predicateWithFormat:@"markedForDeletion == NO AND folderType != 1"];
}
static NSPredicate *activeNotePredicate(void) {
return [NSPredicate predicateWithFormat:@"markedForDeletion == NO AND folder.markedForDeletion == NO"];
}
static NSArray *fetchFolders(id viewContext) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ICFolder"];
request.predicate = activeFolderPredicate();
NSError *error = nil;
NSArray *folders = [viewContext executeFetchRequest:request error:&error];
if (error) {
checkNotesAccessError(error);
errorExit([NSString stringWithFormat:@"Failed to fetch folders: %@", error]);
}
return folders;
}
static NSArray *fetchNotes(id viewContext, NSString *folderName, NSUInteger limit) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ICNote"];
NSMutableArray *predicates = [NSMutableArray array];
[predicates addObject:activeNotePredicate()];
if (folderName) {
[predicates addObject:[NSPredicate predicateWithFormat:@"folder.title == %@", folderName]];
}
request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"modificationDate" ascending:NO]];
if (limit > 0) request.fetchLimit = limit;
NSError *error = nil;
NSArray *notes = [viewContext executeFetchRequest:request error:&error];
if (error) {
checkNotesAccessError(error);
errorExit([NSString stringWithFormat:@"Failed to fetch notes: %@", error]);
}
return notes;
}
static NSDictionary *noteToDict(id note); // forward declaration
static NSString *noteToMarkdownString(id note); // forward declaration (defined in notekit-handwritten.m)
static NSArray *findNotes(id viewContext, NSString *title, NSString *folderName) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ICNote"];
NSMutableArray *predicates = [NSMutableArray array];
[predicates addObject:activeNotePredicate()];
[predicates addObject:[NSPredicate predicateWithFormat:@"title CONTAINS %@", title]];
if (folderName) {
[predicates addObject:[NSPredicate predicateWithFormat:@"folder.title == %@", folderName]];
}
request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
NSError *error = nil;
NSArray *notes = [viewContext executeFetchRequest:request error:&error];
if (error) {
checkNotesAccessError(error);
errorExit([NSString stringWithFormat:@"Failed to find notes: %@", error]);
}
if (notes.count == 0) return @[];
return notes;
}
static NSArray *findNotesExact(id viewContext, NSString *title, NSString *folderName) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ICNote"];
NSMutableArray *predicates = [NSMutableArray array];
[predicates addObject:activeNotePredicate()];
[predicates addObject:[NSPredicate predicateWithFormat:@"title == %@", title]];
if (folderName) {
[predicates addObject:[NSPredicate predicateWithFormat:@"folder.title == %@", folderName]];
}
request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
NSError *error = nil;
NSArray *notes = [viewContext executeFetchRequest:request error:&error];
if (error) {
checkNotesAccessError(error);
errorExit([NSString stringWithFormat:@"Failed to find notes: %@", error]);
}
return notes;
}
static id findNote(id viewContext, NSString *title, NSString *folderName) {
NSArray *notes = findNotes(viewContext, title, folderName);
if (notes.count == 0) return nil;
return notes[0];
}
// Returns exactly one note matching title, or exits with an error listing all matches.
// Use this for commands that operate on a single note (read, read-attrs, etc.)
// to avoid silently acting on the wrong note when multiple match.
static id requireSingleNote(id viewContext, NSString *title, NSString *folderName) {
NSArray *notes = findNotes(viewContext, title, folderName);
if (notes.count == 0) errorExit([NSString stringWithFormat:@"Note not found: %@", title]);
if (notes.count == 1) return notes[0];
NSMutableString *msg = [NSMutableString stringWithFormat:
@"Multiple notes match \\"%@\\". Use --id to specify:\\n", title];
for (id note in notes) {
NSDictionary *d = noteToDict(note);
[msg appendFormat:@" %@ %@\\n", d[@"id"], d[@"title"]];
}
errorExit(msg);
return nil; // unreachable
}
static id findNoteByID(id viewContext, NSString *identifier) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ICNote"];
request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[
activeNotePredicate(),
[NSPredicate predicateWithFormat:@"identifier == %@", identifier]
]];
request.fetchLimit = 1;
NSError *error = nil;
NSArray *notes = [viewContext executeFetchRequest:request error:&error];
if (error) {
checkNotesAccessError(error);
errorExit([NSString stringWithFormat:@"Failed to find note by ID: %@", error]);
}
if (notes.count == 0) return nil;
return notes[0];
}
// Returns the character offset where the body starts in the full mergeableString
// (after leading \\n + title + \\n)
// Returns NSNotFound if the note has no body (title-only note).
// Handles both canonical format (\\n + title + \\n + body) and non-canonical
// format (title + \\n + body) for test-created notes.
static NSUInteger bodyOffsetForNote(id note) {
NSAttributedString *attrStr = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("attributedString"));
NSString *fullText = [attrStr string];
NSUInteger length = fullText.length;
// Guard: empty note
if (length == 0) return NSNotFound;
NSUInteger idx = 0;
// Skip all leading newlines (canonical notes have exactly one, but be
// robust against malformed or legacy notes with extra leading newlines)
while (idx < length && [fullText characterAtIndex:idx] == 0x0A) idx++;
// Skip title text (all non-newline characters)
while (idx < length && [fullText characterAtIndex:idx] != 0x0A) idx++;
// Skip the newline after title
if (idx < length && [fullText characterAtIndex:idx] == 0x0A) idx++;
// If idx >= length, the note has no body (title-only)
if (idx >= length) return NSNotFound;
return idx;
}'''
def generate_note_to_dict():
lines = [
'// --- Note Serialization (generated from NOTE_READ_PROPS) ---',
'',
'static NSDictionary *noteToDict(id note) {',
' NSMutableDictionary *dict = [NSMutableDictionary dictionary];',
'',
]
for prop, (json_key, type_hint) in NOTE_READ_PROPS.items():
if type_hint == "string":
lines.append(f' @try {{')
lines.append(f' NSString *val = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("{prop}"));')
lines.append(f' if (val) dict[@"{json_key}"] = val;')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "bool":
lines.append(f' @try {{')
lines.append(f' BOOL val = ((BOOL (*)(id, SEL))objc_msgSend)(note, sel_registerName("{prop}"));')
lines.append(f' dict[@"{json_key}"] = @(val);')
lines.append(f' }} @catch (NSException *e) {{}}')
elif type_hint == "date":
lines.append(f' @try {{')
lines.append(f' NSDate *val = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("{prop}"));')
lines.append(f' if (val) dict[@"{json_key}"] = dateToISO(val);')
lines.append(f' }} @catch (NSException *e) {{}}')
lines.append('')
# URL property (not data-driven, but always included)
lines.append(' @try {')
lines.append(' Class ICAppURLUtilities = NSClassFromString(@"ICAppURLUtilities");')
lines.append(' if (ICAppURLUtilities) {')
lines.append(' NSURL *appURL = ((id (*)(id, SEL, id))objc_msgSend)(')
lines.append(' ICAppURLUtilities, sel_registerName("appURLForNote:"), note);')
lines.append(' if (appURL) dict[@"url"] = [appURL absoluteString];')
lines.append(' }')
lines.append(' } @catch (NSException *e) {}')
lines.append('')
lines.append(' return dict;')
lines.append('}')
return '\n'.join(lines)
def generate_commands():
return '''
// --- Commands ---
static int cmdFolders(id viewContext) {
NSArray *folders = fetchFolders(viewContext);
NSMutableArray *result = [NSMutableArray array];
for (id folder in folders) {
NSString *title = ((id (*)(id, SEL))objc_msgSend)(folder, sel_registerName("title"));
if (title && title.length > 0) {
[result addObject:@{@"name": title}];
}
}
printJSON(result);
return 0;
}
static int cmdList(id viewContext, NSString *folderName, NSUInteger limit) {
NSArray *notes = fetchNotes(viewContext, folderName, limit);
NSMutableArray *result = [NSMutableArray array];
for (id note in notes) {
[result addObject:noteToDict(note)];
}
printJSON(result);
return 0;
}
static int cmdGetNote(id note) {
printJSON(noteToDict(note));
return 0;
}
static int cmdGet(id viewContext, NSString *title, NSString *folderName, BOOL exact) {
NSArray *notes = exact ? findNotesExact(viewContext, title, folderName) : findNotes(viewContext, title, folderName);
if (notes.count == 0) errorExit([NSString stringWithFormat:@"Note not found: %@", title]);
if (exact && notes.count > 1) {
NSMutableString *msg = [NSMutableString stringWithFormat:
@"Multiple notes have the exact title \\\"%@\\\". Use --id to specify:\\n", title];
for (id note in notes) {
NSDictionary *d = noteToDict(note);
[msg appendFormat:@" %@ %@\\n", d[@"id"], d[@"title"]];
}
errorExit(msg);
}
if (notes.count == 1) return cmdGetNote(notes[0]);
NSMutableArray *results = [NSMutableArray array];
for (id note in notes) {
[results addObject:noteToDict(note)];
}
printJSON(results);
return 0;
}
static int cmdReadNote(id note) {
NSString *body = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("noteAsPlainTextWithoutTitle"));
if (body) printf("%s\\n", [body UTF8String]);
return 0;
}
static int cmdRead(id viewContext, NSString *title, NSString *folderName) {
id note = requireSingleNote(viewContext, title, folderName);
return cmdReadNote(note);
}
static int cmdReadAttrsNote(id note) {
id doc = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("document"));
id ms = ((id (*)(id, SEL))objc_msgSend)(doc, sel_registerName("mergeableString"));
NSAttributedString *attrStr = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("attributedString"));
NSString *fullText = [attrStr string];
NSUInteger length = fullText.length;
if (length == 0) { printJSON(@[]); return 0; }
NSMutableArray *ranges = [NSMutableArray array];
NSUInteger idx = 0;
NSRange effectiveRange;
while (idx < length) {
NSDictionary *attrs = ((id (*)(id, SEL, NSUInteger, NSRange*))objc_msgSend)(
ms, sel_registerName("attributesAtIndex:effectiveRange:"), idx, &effectiveRange);
NSString *text = [fullText substringWithRange:effectiveRange];
NSMutableDictionary *entry = [NSMutableDictionary dictionary];
entry[@"offset"] = @(effectiveRange.location);
entry[@"length"] = @(effectiveRange.length);
entry[@"text"] = text;
id style = attrs[@"TTStyle"];
if (style) {
entry[@"style"] = @(((NSInteger (*)(id, SEL))objc_msgSend)(style, sel_registerName("style")));
entry[@"indent"] = @(((NSUInteger (*)(id, SEL))objc_msgSend)(style, sel_registerName("indent")));
NSString *uuid = [((id (*)(id, SEL))objc_msgSend)(style, sel_registerName("uuid")) description];
if (uuid) entry[@"uuid"] = uuid;
id todo = ((id (*)(id, SEL))objc_msgSend)(style, sel_registerName("todo"));
if (todo) {
entry[@"todoDone"] = @(((BOOL (*)(id, SEL))objc_msgSend)(todo, sel_registerName("done")));
}
NSUInteger hints = ((NSUInteger (*)(id, SEL))objc_msgSend)(style, sel_registerName("hints"));
if (hints > 0) entry[@"hints"] = @(hints);
}
// Inline attributes
id nsLink = attrs[@"NSLink"];
if (nsLink) {
entry[@"link"] = [nsLink description];
Class ICAppURLUtilities = NSClassFromString(@"ICAppURLUtilities");
if (ICAppURLUtilities) {
BOOL isNoteLink = ((BOOL (*)(id, SEL, id))objc_msgSend)(
ICAppURLUtilities, sel_registerName("isShowNoteURL:"), nsLink);
if (isNoteLink) {
entry[@"linkType"] = @"note";
NSString *noteId = ((id (*)(id, SEL, id))objc_msgSend)(
ICAppURLUtilities, sel_registerName("noteIdentifierFromNotesAppURL:"), nsLink);
if (!noteId && [nsLink isKindOfClass:[NSURL class]]) {
NSURLComponents *comps = [NSURLComponents componentsWithURL:nsLink resolvingAgainstBaseURL:NO];
for (NSURLQueryItem *item in comps.queryItems) {
if ([item.name isEqualToString:@"identifier"]) { noteId = item.value; break; }
}
}
if (noteId) entry[@"linkedNoteId"] = noteId;
} else {
entry[@"linkType"] = @"url";
}
}
}
id strikethrough = attrs[@"TTStrikethrough"];
if (strikethrough) entry[@"strikethrough"] = strikethrough;
id ttHints = attrs[@"TTHints"];
if (ttHints) {
NSUInteger hints = [ttHints unsignedIntegerValue];
if (hints & 1) entry[@"bold"] = @YES;
if (hints & 2) entry[@"italic"] = @YES;
}
id ttUnderline = attrs[@"TTUnderline"];
if (ttUnderline) entry[@"underline"] = @YES;
NSString *colorHex = hexStringForColor(attrs[@"TTColor"] ?: attrs[NSForegroundColorAttributeName]);
if (colorHex) entry[@"color"] = colorHex;
id attachment = attrs[@"NSAttachment"];
if (attachment) entry[@"hasAttachment"] = @YES;
[ranges addObject:entry];
idx = effectiveRange.location + effectiveRange.length;
}
printJSON(ranges);
return 0;
}
static int cmdReadAttrs(id viewContext, NSString *title, NSString *folderName) {
id note = requireSingleNote(viewContext, title, folderName);
return cmdReadAttrsNote(note);
}
static int cmdCreateFolder(id viewContext, NSString *name, NSString *parentName) {
NSArray *folders = fetchFolders(viewContext);
// If --parent specified, find the parent folder and use its account
id parentFolder = nil;
if (parentName) {
NSInteger matchCount = 0;
for (id f in folders) {
NSString *fname = ((id (*)(id, SEL))objc_msgSend)(f, sel_registerName("title"));
if ([fname isEqualToString:parentName]) { parentFolder = f; matchCount++; }
}
if (!parentFolder) errorExit([NSString stringWithFormat:@"Parent folder not found: %@", parentName]);
if (matchCount > 1) errorExit([NSString stringWithFormat:@"Multiple folders named '%@' found — cannot determine parent unambiguously", parentName]);
}
// Get account: prefer parent's account when nesting, otherwise first available
id account = nil;
if (parentFolder) {
account = ((id (*)(id, SEL))objc_msgSend)(parentFolder, sel_registerName("account"));
}
if (!account) {
for (id f in folders) {
account = ((id (*)(id, SEL))objc_msgSend)(f, sel_registerName("account"));
if (account) break;
}
}
if (!account) errorExit(@"No account found");
Class ICFolder = NSClassFromString(@"ICFolder");
id newFolder = ((id (*)(id, SEL, id))objc_msgSend)(ICFolder, sel_registerName("newFolderInAccount:"), account);
if (!newFolder) errorExit(@"Failed to create folder");
((void (*)(id, SEL, id))objc_msgSend)(newFolder, sel_registerName("setTitle:"), name);
// Set parent folder relationship for nesting
if (parentFolder) {
((void (*)(id, SEL, id))objc_msgSend)(newFolder, sel_registerName("setParent:"), parentFolder);
}
NSError *error = nil;
[viewContext save:&error];
if (error) errorExit([NSString stringWithFormat:@"Save error: %@", error]);
NSMutableDictionary *output = [NSMutableDictionary dictionaryWithDictionary:@{@"name": name, @"created": @YES}];
if (parentName) output[@"parent"] = parentName;
printJSON(output);
return 0;
}
static int cmdDeleteFolder(id viewContext, NSString *name) {
NSArray *folders = fetchFolders(viewContext);
id targetFolder = nil;
for (id f in folders) {
NSString *fname = ((id (*)(id, SEL))objc_msgSend)(f, sel_registerName("title"));
if ([fname isEqualToString:name]) { targetFolder = f; break; }
}
if (!targetFolder) errorExit([NSString stringWithFormat:@"Folder not found: %@", name]);
// markForDeletion soft-deletes (moves to Recently Deleted) without
// triggering aggressive CloudKit sync that can corrupt shared folder state.
((void (*)(id, SEL))objc_msgSend)(targetFolder, sel_registerName("markForDeletion"));
[viewContext deleteObject:targetFolder];
NSError *error = nil;
[viewContext save:&error];
if (error) errorExit([NSString stringWithFormat:@"Save error: %@", error]);
printJSON(@{@"name": name, @"deleted": @YES});
return 0;
}
static int cmdDuplicate(id viewContext, NSString *identifier, NSString *newTitle) {
id note = findNoteByID(viewContext, identifier);
if (!note) errorExit([NSString stringWithFormat:@"Note not found with id: %@", identifier]);
// Get source document
id doc = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("document"));
id ms = ((id (*)(id, SEL))objc_msgSend)(doc, sel_registerName("mergeableString"));
NSAttributedString *attrStr = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("attributedString"));
NSString *fullText = [attrStr string];
NSUInteger length = fullText.length;
// Get folder
id folder = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("primitiveFolder"));
// Create new note
id newNote = ((id (*)(id, SEL, id))objc_msgSend)(ICNoteClass, sel_registerName("newEmptyNoteInFolder:"), folder);
id newDoc = ((id (*)(id, SEL))objc_msgSend)(newNote, sel_registerName("document"));
id newMs = ((id (*)(id, SEL))objc_msgSend)(newDoc, sel_registerName("mergeableString"));
((void (*)(id, SEL))objc_msgSend)(newNote, sel_registerName("beginEditing"));
// Find the title boundary: skip leading newline, then find next newline
// Notes start with 0x0A, then title text, then 0x0A
NSUInteger titleStart = 0;
while (titleStart < length && [fullText characterAtIndex:titleStart] == 0x0A) titleStart++;
NSUInteger titleEnd = titleStart;
while (titleEnd < length && [fullText characterAtIndex:titleEnd] != 0x0A) titleEnd++;
// Build: leading chars + new title + rest of body
NSString *prefix = [fullText substringToIndex:titleStart]; // leading newlines
NSString *titleStr = newTitle ? newTitle : [fullText substringWithRange:NSMakeRange(titleStart, titleEnd - titleStart)];
NSString *suffix = titleEnd < length ? [fullText substringFromIndex:titleEnd] : @"";
NSString *newText = [[prefix stringByAppendingString:titleStr] stringByAppendingString:suffix];
NSUInteger newLength = newText.length;
NSInteger titleDelta = (NSInteger)newLength - (NSInteger)length;
// Insert the combined text
((void (*)(id, SEL, id, NSUInteger))objc_msgSend)(newMs, sel_registerName("insertString:atIndex:"), newText, 0);
// Copy body attributes from source, skipping original title range
NSUInteger idx = titleEnd; // start after original title
NSRange effectiveRange;
while (idx < length) {
NSDictionary *attrs = ((id (*)(id, SEL, NSUInteger, NSRange*))objc_msgSend)(
ms, sel_registerName("attributesAtIndex:effectiveRange:"), idx, &effectiveRange);
// Copy ALL attributes (TTStyle, links, strikethrough, etc.)
NSMutableDictionary *newAttrs = [attrs mutableCopy];
// For TTStyle, create a new copy with fresh todo UUIDs
id style = attrs[@"TTStyle"];
if (style) {
id newStyle = [style mutableCopy];
id todo = ((id (*)(id, SEL))objc_msgSend)(style, sel_registerName("todo"));
if (todo) {
BOOL done = ((BOOL (*)(id, SEL))objc_msgSend)(todo, sel_registerName("done"));
id newTodo = ((id (*)(id, SEL, id, BOOL))objc_msgSend)(
[ICTTTodoClass alloc], sel_registerName("initWithIdentifier:done:"), [NSUUID UUID], done);
((void (*)(id, SEL, id))objc_msgSend)(newStyle, sel_registerName("setTodo:"), newTodo);
}
newAttrs[@"TTStyle"] = newStyle;
}
NSRange newRange = NSMakeRange(effectiveRange.location + titleDelta, effectiveRange.length);
if (newAttrs.count > 0) {
((void (*)(id, SEL, id, NSRange))objc_msgSend)(newMs, sel_registerName("setAttributes:range:"),
newAttrs, newRange);
}
idx = effectiveRange.location + effectiveRange.length;
}
// Set title style AFTER copying body attrs so it doesn't get overwritten
id titleStyle = [[ICTTParagraphStyleClass alloc] init];
((void (*)(id, SEL, NSUInteger))objc_msgSend)(titleStyle, sel_registerName("setStyle:"), 0);
((void (*)(id, SEL, id, NSRange))objc_msgSend)(newMs, sel_registerName("setAttributes:range:"),
@{@"TTStyle": titleStyle}, NSMakeRange(0, prefix.length + titleStr.length));
length = newLength;
((void (*)(id, SEL, NSUInteger, NSRange, NSInteger))objc_msgSend)(
newNote, sel_registerName("edited:range:changeInLength:"), 1, NSMakeRange(0, length), length);
((void (*)(id, SEL))objc_msgSend)(newNote, sel_registerName("endEditing"));
((void (*)(id, SEL))objc_msgSend)(newNote, sel_registerName("saveNoteData"));
NSError *error = nil;
[viewContext save:&error];
if (error) errorExit([NSString stringWithFormat:@"Save error: %@", error]);
printJSON(noteToDict(newNote));
return 0;
}
static int cmdSetAttr(id viewContext, NSString *identifier,
NSUInteger offset, NSUInteger length, NSDictionary *attrOpts) {
id note = findNoteByID(viewContext, identifier);
if (!note) errorExit([NSString stringWithFormat:@"Note not found with id: %@", identifier]);
// Adjust offset if --body-offset flag is set
if (attrOpts[@"body-offset"]) {
NSUInteger bodyOff = bodyOffsetForNote(note);
if (bodyOff == NSNotFound) {
errorExit(@"Note has no body text; --body-offset requires body content");
}
if (offset > NSUIntegerMax - bodyOff) {
errorExit(@"Offset overflow: body-relative offset too large");
}
offset += bodyOff;
}
id doc = ((id (*)(id, SEL))objc_msgSend)(note, sel_registerName("document"));
id ms = ((id (*)(id, SEL))objc_msgSend)(doc, sel_registerName("mergeableString"));
NSUInteger msLen = ((NSUInteger (*)(id, SEL))objc_msgSend)(ms, sel_registerName("length"));
if (offset > msLen || length > msLen - offset) errorExit(@"Range exceeds note length");
BOOL hasStyleOpts = (attrOpts[@"style"] || attrOpts[@"indent"] || attrOpts[@"todo-done"]);
BOOL hasLinkOpt = (attrOpts[@"link"] != nil);
BOOL hasStrikethroughOpt = (attrOpts[@"strikethrough"] != nil);
BOOL hasColorOpt = (attrOpts[@"color"] != nil);
// Validate --strikethrough upfront if provided
if (hasStrikethroughOpt) {
NSString *val = attrOpts[@"strikethrough"];
if (![val isEqualToString:@"true"] && ![val isEqualToString:@"false"]) {
errorExit(@"--strikethrough must be 'true' or 'false'");
}
}
NSColor *colorValue = nil;
if (hasColorOpt) {
NSString *val = attrOpts[@"color"];
if (![val isEqualToString:@"reset"] && !parseHexColor(val, nil, &colorValue)) {
errorExit(@"--color must be a hex color (#rgb or #rrggbb) or 'reset'");
}
}
// Validate --style upfront if provided
if (attrOpts[@"style"]) {
NSInteger styleVal;
if (!isStrictInteger(attrOpts[@"style"], &styleVal)) {
errorExit(@"--style must be a number. Valid styles: 0=title, 1=heading, 2=subheading, 3=body, 4=code-block, 100=bullet-list, 101=dash-list, 102=numbered-list, 103=checklist");
}
if (!isValidStyle(styleVal)) {
errorExit(@"Invalid --style value. Valid styles: 0=title, 1=heading, 2=subheading, 3=body, 4=code-block, 100=bullet-list, 101=dash-list, 102=numbered-list, 103=checklist");
}
}
// Validate URL upfront if --link is provided
NSURL *linkURL = nil;
if (hasLinkOpt) {
NSString *linkStr = attrOpts[@"link"];
if (linkStr.length > 0) {
linkURL = [NSURL URLWithString:linkStr];
if (!linkURL) {
errorExit([NSString stringWithFormat:@"Invalid URL: %@", linkStr]);
}
NSString *scheme = [linkURL.scheme lowercaseString];
if (!scheme || (![scheme isEqualToString:@"http"] &&
![scheme isEqualToString:@"https"] &&
![scheme isEqualToString:@"mailto"])) {
errorExit([NSString stringWithFormat:
@"Unsupported URL scheme '%@'. Allowed: http, https, mailto", scheme ?: @"(none)"]);
}
}
// If linkStr.length == 0, linkURL stays nil => link will be removed
}
if (length == 0) {
errorExit(@"--length must be greater than 0 for set-attr");
}
((void (*)(id, SEL))objc_msgSend)(note, sel_registerName("beginEditing"));
// Get the full plain string for paragraph-boundary splitting when applying links.
// ICTTMergeableString's setAttributes:range: can bleed link attributes into
// adjacent paragraphs when the range crosses a '\\n' character. We split any
// write that would cross a newline so each setAttributes:range: call stays
// within a single paragraph.
// Note: [ms string] returns the underlying NSMutableAttributedString, not a
// plain NSString; call -string on that attributed string to get the raw text.
id msAS = ((id (*)(id, SEL))objc_msgSend)(ms, sel_registerName("string"));
NSString *msStr = (msAS && [msAS respondsToSelector:@selector(string)]) ? [msAS string] : (NSString *)msAS;
// Enumerate existing attribute runs in the target range (per-run patch strategy)
NSUInteger idx = offset;
NSUInteger end = offset + length;
while (idx < end) {
NSRange effectiveRange;
NSDictionary *existingAttrs = ((id (*)(id, SEL, NSUInteger, NSRange*))objc_msgSend)(
ms, sel_registerName("attributesAtIndex:effectiveRange:"), idx, &effectiveRange);
// Intersect effectiveRange with our target range
NSUInteger subStart = MAX(effectiveRange.location, offset);
NSUInteger subEnd = MIN(effectiveRange.location + effectiveRange.length, end);
// When a link operation is in play, further split the sub-range at every
// newline so that setAttributes:range: never crosses a paragraph boundary.
// For style-only operations (no link) the existing per-attribute-run loop
// is sufficient; paragraph styles are intentionally paragraph-scoped and
// ICTTMergeableString handles that correctly.
NSUInteger segStart = subStart;
while (segStart < subEnd) {
// Find the next newline within [segStart, subEnd)
NSRange searchRange = NSMakeRange(segStart, subEnd - segStart);
NSRange nlRange = (hasLinkOpt && msStr)
? [msStr rangeOfString:@"\\n" options:0 range:searchRange]
: NSMakeRange(NSNotFound, 0);
// segEnd: stop just after the newline (inclusive) or at subEnd
NSUInteger segEnd = (nlRange.location != NSNotFound)
? nlRange.location + 1 // include the '\\n' in this segment
: subEnd;
NSRange segRange = NSMakeRange(segStart, segEnd - segStart);
// Re-fetch attributes at segStart so TTStyle reflects the paragraph
// that owns this segment (important when segStart != subStart, i.e.
// we have crossed into a new paragraph mid-run).
NSDictionary *segAttrs = (segStart == subStart)
? existingAttrs
: ((id (*)(id, SEL, NSUInteger, NSRange*))objc_msgSend)(
ms, sel_registerName("attributesAtIndex:effectiveRange:"), segStart, &effectiveRange);
// Build new attrs dict from existing (preserves TTStrikethrough, attachments, etc.)
NSMutableDictionary *patchedAttrs = [NSMutableDictionary dictionary];
for (NSString *key in segAttrs) {
patchedAttrs[key] = segAttrs[key];
}
// Apply style delta if requested
if (hasStyleOpts) {
id style = [[ICTTParagraphStyleClass alloc] init];
// Start from existing style as base, then override requested fields
id existingStyle = segAttrs[@"TTStyle"];
if (existingStyle) {
((void (*)(id, SEL, NSInteger))objc_msgSend)(style, sel_registerName("setStyle:"),
((NSInteger (*)(id, SEL))objc_msgSend)(existingStyle, sel_registerName("style")));
((void (*)(id, SEL, NSUInteger))objc_msgSend)(style, sel_registerName("setIndent:"),
((NSUInteger (*)(id, SEL))objc_msgSend)(existingStyle, sel_registerName("indent")));
id existingTodo = ((id (*)(id, SEL))objc_msgSend)(existingStyle, sel_registerName("todo"));
if (existingTodo) {
((void (*)(id, SEL, id))objc_msgSend)(style, sel_registerName("setTodo:"), existingTodo);
}
}
if (attrOpts[@"style"]) {
((void (*)(id, SEL, NSInteger))objc_msgSend)(style, sel_registerName("setStyle:"),
[attrOpts[@"style"] integerValue]);
}
if (attrOpts[@"indent"]) {
((void (*)(id, SEL, NSUInteger))objc_msgSend)(style, sel_registerName("setIndent:"),
[attrOpts[@"indent"] integerValue]);
}
if (attrOpts[@"todo-done"]) {
BOOL done = [attrOpts[@"todo-done"] isEqualToString:@"true"];
id todo = ((id (*)(id, SEL, id, BOOL))objc_msgSend)(
[ICTTTodoClass alloc], sel_registerName("initWithIdentifier:done:"), [NSUUID UUID], done);
((void (*)(id, SEL, id))objc_msgSend)(style, sel_registerName("setTodo:"), todo);
if (!attrOpts[@"style"]) {
((void (*)(id, SEL, NSUInteger))objc_msgSend)(style, sel_registerName("setStyle:"), 103);
}
}
patchedAttrs[@"TTStyle"] = style;
}
// Apply link delta if requested
if (hasLinkOpt) {
if (linkURL) {
patchedAttrs[@"NSLink"] = linkURL;
} else {
[patchedAttrs removeObjectForKey:@"NSLink"];
}
}
// Apply strikethrough delta if requested
if (hasStrikethroughOpt) {
if ([attrOpts[@"strikethrough"] isEqualToString:@"true"]) {
patchedAttrs[@"TTStrikethrough"] = @1;
} else {
[patchedAttrs removeObjectForKey:@"TTStrikethrough"];
}
}
// Apply color delta if requested
if (hasColorOpt) {
if ([attrOpts[@"color"] isEqualToString:@"reset"]) {
[patchedAttrs removeObjectForKey:@"TTColor"];
[patchedAttrs removeObjectForKey:NSForegroundColorAttributeName];
} else {
patchedAttrs[@"TTColor"] = (__bridge id)[colorValue CGColor];
}