-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathConfigurableTaskParser.ts
More file actions
2054 lines (1829 loc) · 55.1 KB
/
ConfigurableTaskParser.ts
File metadata and controls
2054 lines (1829 loc) · 55.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
/**
* Configurable Markdown Task Parser
* Based on Rust implementation design with TypeScript adaptation
*/
import { Task, TgProject, EnhancedStandardTaskMetadata } from "@/types/task";
import {
TaskParserConfig,
EnhancedTask,
MetadataParseMode,
} from "../../types/TaskParserConfig";
import { parseLocalDate } from "@/utils/date/date-formatter";
import { TASK_REGEX } from "@/common/regex-define";
import { ContextDetector } from "@/parsers/context-detector";
import { TimeParsingService } from "@/services/time-parsing-service";
import { TimeComponent } from "@/types/time-parsing";
export class MarkdownTaskParser {
private config: TaskParserConfig;
private tasks: EnhancedTask[] = [];
private indentStack: Array<{
taskId: string;
indentLevel: number;
actualSpaces: number;
}> = [];
private currentHeading?: string;
private currentHeadingLevel?: number;
private fileMetadata?: Record<string, any>; // Store file frontmatter metadata
private projectConfigCache?: Record<string, any>; // Cache for project config files
private customDateFormats?: string[]; // Store custom date formats from settings
private timeParsingService?: TimeParsingService; // Enhanced time parsing service
// Date parsing cache to improve performance for large-scale parsing
private static dateCache = new Map<string, number | undefined>();
private static readonly MAX_CACHE_SIZE = 10000; // Limit cache size to prevent memory issues
constructor(
config: TaskParserConfig,
timeParsingService?: TimeParsingService,
) {
this.config = config;
// Extract custom date formats if available
this.customDateFormats = config.customDateFormats;
this.timeParsingService = timeParsingService;
}
// Public alias for extractMetadataAndTags
public extractMetadataAndTags(
content: string,
): [string, Record<string, string>, string[]] {
return this.extractMetadataAndTagsInternal(content);
}
/**
* Create parser with predefined status mapping
*/
static createWithStatusMapping(
config: TaskParserConfig,
statusMapping: Record<string, string>,
timeParsingService?: TimeParsingService,
): MarkdownTaskParser {
const newConfig = { ...config, statusMapping };
return new MarkdownTaskParser(newConfig, timeParsingService);
}
/**
* Parse markdown content and return enhanced tasks
*/
parse(
input: string,
filePath = "",
fileMetadata?: Record<string, any>,
projectConfigData?: Record<string, any>,
tgProject?: TgProject,
): EnhancedTask[] {
this.reset();
this.fileMetadata = fileMetadata;
// Store project config data if provided
if (projectConfigData) {
this.projectConfigCache = projectConfigData;
}
const lines = input.split(/\r?\n/);
let i = 0;
let parseIteration = 0;
let inCodeBlock = false;
while (i < lines.length) {
parseIteration++;
if (parseIteration > this.config.maxParseIterations) {
console.warn(
"Warning: Maximum parse iterations reached, stopping to prevent infinite loop",
);
break;
}
const line = lines[i];
// Check for code block fences
if (
line.trim().startsWith("```") ||
line.trim().startsWith("~~~")
) {
inCodeBlock = !inCodeBlock;
i++;
continue;
}
if (inCodeBlock) {
i++;
continue;
}
// Check if it's a heading line
if (this.config.parseHeadings) {
const headingResult = this.extractHeading(line);
if (headingResult) {
const [level, headingText] = headingResult;
this.currentHeading = headingText;
this.currentHeadingLevel = level;
i++;
continue;
}
}
const taskLineResult = this.extractTaskLine(line);
if (taskLineResult) {
const [actualSpaces, , content, listMarker] = taskLineResult;
const taskId = `${filePath}-L${i}`;
const [parentId, indentLevel] =
this.findParentAndLevel(actualSpaces);
const [taskContent, rawStatus] = this.parseTaskContent(content);
const completed = rawStatus.toLowerCase() === "x";
const status = this.getStatusFromMapping(rawStatus);
const [cleanedContent, metadata, tags] =
this.extractMetadataAndTagsInternal(taskContent);
// Inherit metadata from file frontmatter
// A task is a subtask if it has a parent
const isSubtask = parentId !== undefined;
const inheritedMetadata = this.inheritFileMetadata(
metadata,
isSubtask,
filePath,
);
// Extract time components from task content using enhanced time parsing
const enhancedMetadata = this.extractTimeComponents(
taskContent,
inheritedMetadata,
);
// Process inherited tags and merge with task's own tags
let finalTags = tags;
if (inheritedMetadata.tags) {
try {
const inheritedTags = JSON.parse(
inheritedMetadata.tags,
);
if (Array.isArray(inheritedTags)) {
finalTags = this.mergeTags(tags, inheritedTags);
}
} catch (e) {
// If parsing fails, treat as a single tag
finalTags = this.mergeTags(tags, [
inheritedMetadata.tags,
]);
}
}
// Prefer up-to-date detection for current file; fall back to provided tgProject
const taskTgProject =
this.determineTgProject(filePath) || tgProject;
// Check for multiline comments
const [comment, linesToSkip] =
this.config.parseComments && i + 1 < lines.length
? this.extractMultilineComment(
lines,
i + 1,
actualSpaces,
)
: [undefined, 0];
i += linesToSkip;
// Debug: Log priority extraction for each task
const extractedPriority =
this.extractLegacyPriority(inheritedMetadata);
const enhancedTask: EnhancedTask = {
id: taskId,
content: cleanedContent,
status,
rawStatus,
completed,
indentLevel,
parentId,
childrenIds: [],
metadata: enhancedMetadata,
tags: finalTags,
comment,
lineNumber: i + 1,
actualIndent: actualSpaces,
heading: this.currentHeading,
headingLevel: this.currentHeadingLevel,
listMarker,
filePath,
originalMarkdown: line,
tgProject: taskTgProject,
// Legacy fields for backward compatibility
line: i,
children: [],
priority: extractedPriority,
startDate: this.extractLegacyDate(
enhancedMetadata,
"startDate",
),
dueDate: this.extractLegacyDate(
enhancedMetadata,
"dueDate",
),
scheduledDate: this.extractLegacyDate(
enhancedMetadata,
"scheduledDate",
),
completedDate: this.extractLegacyDate(
enhancedMetadata,
"completedDate",
),
createdDate: this.extractLegacyDate(
enhancedMetadata,
"createdDate",
),
recurrence: enhancedMetadata.recurrence,
project: enhancedMetadata.project,
context: enhancedMetadata.context,
};
if (parentId && this.tasks.length > 0) {
const parentTask = this.tasks.find(
(t) => t.id === parentId,
);
if (parentTask) {
parentTask.childrenIds.push(taskId);
parentTask.children.push(taskId); // Legacy field
}
}
this.updateIndentStack(taskId, indentLevel, actualSpaces);
this.tasks.push(enhancedTask);
}
i++;
}
return [...this.tasks];
}
/**
* Parse and return legacy Task format for compatibility
*/
parseLegacy(
input: string,
filePath: string = "",
fileMetadata?: Record<string, any>,
projectConfigData?: Record<string, any>,
tgProject?: TgProject,
): Task[] {
const enhancedTasks = this.parse(
input,
filePath,
fileMetadata,
projectConfigData,
tgProject,
);
return enhancedTasks.map((task) => this.convertToLegacyTask(task));
}
/**
* Parse a single task line
*/
parseTask(line: string, filePath: string = "", lineNum: number = 0): Task {
const enhancedTask = this.parse(line, filePath);
return this.convertToLegacyTask({
...enhancedTask[0],
line: lineNum,
id: `${filePath}-L${lineNum}`,
});
}
private reset(): void {
this.tasks = [];
this.indentStack = [];
this.currentHeading = undefined;
this.currentHeadingLevel = undefined;
}
private extractTaskLine(
line: string,
): [number, number, string, string] | null {
// Preserve trailing spaces to allow parsing of empty-content tasks like "- [ ] "
const trimmed = line.trimStart();
const actualSpaces = line.length - trimmed.length;
if (this.isTaskLine(trimmed)) {
const listMarker = this.extractListMarker(trimmed);
return [actualSpaces, actualSpaces, trimmed, listMarker];
}
return null;
}
private extractListMarker(trimmed: string): string {
// Check unordered list markers
for (const marker of ["-", "*", "+"]) {
if (trimmed.startsWith(marker)) {
return marker;
}
}
// Check ordered list markers
const chars = trimmed.split("");
let i = 0;
while (i < chars.length && /\d/.test(chars[i])) {
i++;
}
if (i > 0 && i < chars.length) {
if (chars[i] === "." || chars[i] === ")") {
return chars.slice(0, i + 1).join("");
}
}
// Fallback: return first character
return trimmed.charAt(0) || " ";
}
private isTaskLine(trimmed: string): boolean {
// Use existing TASK_REGEX from common/regex-define
return TASK_REGEX.test(trimmed);
}
private parseTaskContent(content: string): [string, string] {
const taskMatch = content.match(TASK_REGEX);
if (
taskMatch &&
taskMatch[4] !== undefined &&
taskMatch[5] !== undefined
) {
const status = taskMatch[4];
const taskContent = taskMatch[5].trim();
return [taskContent, status];
}
// Fallback - treat as unchecked task
return [content, " "];
}
private extractMetadataAndTagsInternal(
content: string,
): [string, Record<string, string>, string[]] {
const metadata: Record<string, string> = {};
const tags: string[] = [];
let cleanedContent = "";
let remaining = content;
let metadataIteration = 0;
while (metadataIteration < this.config.maxMetadataIterations) {
metadataIteration++;
let foundMatch = false;
// Check dataview format metadata [key::value]
if (
this.config.parseMetadata &&
(this.config.metadataParseMode ===
MetadataParseMode.DataviewOnly ||
this.config.metadataParseMode === MetadataParseMode.Both)
) {
const bracketMatch = this.extractDataviewMetadata(remaining);
if (bracketMatch) {
const [key, value, newRemaining] = bracketMatch;
metadata[key] = value;
// Debug: Log dataview metadata extraction, especially priority
if (
(process.env.NODE_ENV === "development" || true) &&
key === "priority"
) {
// Always log for debugging
console.log("[Parser] Dataview priority found:", {
key,
value,
remaining: remaining.substring(0, 50),
});
}
remaining = newRemaining;
foundMatch = true;
continue;
}
}
// Check emoji metadata
if (
!foundMatch &&
this.config.parseMetadata &&
(this.config.metadataParseMode ===
MetadataParseMode.EmojiOnly ||
this.config.metadataParseMode === MetadataParseMode.Both)
) {
const emojiMatch = this.extractEmojiMetadata(remaining);
if (emojiMatch) {
const [key, value, beforeContent, afterRemaining] =
emojiMatch;
// Process tags in the content before emoji
const [beforeCleaned, beforeMetadata, beforeTags] =
this.extractTagsOnly(beforeContent);
// Merge metadata and tags from before content
for (const tag of beforeTags) {
tags.push(tag);
}
for (const [k, v] of Object.entries(beforeMetadata)) {
metadata[k] = v;
}
metadata[key] = value;
cleanedContent += beforeCleaned;
remaining = afterRemaining;
foundMatch = true;
continue;
}
}
// Check context (@symbol)
if (!foundMatch && this.config.parseTags) {
const contextMatch = this.extractContext(remaining);
if (contextMatch) {
const [context, beforeContent, afterRemaining] =
contextMatch;
metadata.context = context;
cleanedContent += beforeContent;
remaining = afterRemaining;
foundMatch = true;
continue;
}
}
// Check tags and special tags
if (!foundMatch && this.config.parseTags) {
const tagMatch = this.extractTag(remaining);
if (tagMatch) {
const [tag, beforeContent, afterRemaining] = tagMatch;
// Check if it's a special tag format (prefix/value)
// Remove # prefix for checking special tags
const tagWithoutHash = tag.startsWith("#")
? tag.substring(1)
: tag;
const slashPos = tagWithoutHash.indexOf("/");
if (slashPos !== -1) {
const prefix = tagWithoutHash.substring(0, slashPos);
const value = tagWithoutHash.substring(slashPos + 1);
// Case-insensitive match for special tag prefixes, with debug
const metadataKey =
this.config.specialTagPrefixes[prefix] ??
this.config.specialTagPrefixes[
prefix.toLowerCase()
];
console.debug("[TG] Tag parse", {
tag,
prefix,
mappedKey: metadataKey,
keys: Object.keys(this.config.specialTagPrefixes),
});
if (
metadataKey &&
this.config.metadataParseMode !==
MetadataParseMode.None
) {
metadata[metadataKey] = value;
} else {
tags.push(tag);
}
} else {
tags.push(tag);
}
cleanedContent += beforeContent;
remaining = afterRemaining;
foundMatch = true;
continue;
}
}
if (!foundMatch) {
cleanedContent += remaining;
break;
}
}
return [cleanedContent.trim(), metadata, tags];
}
/**
* Extract time components from task content and merge with existing metadata
*/
private extractTimeComponents(
taskContent: string,
existingMetadata: Record<string, string>,
): EnhancedStandardTaskMetadata {
if (!this.timeParsingService) {
// Return existing metadata as EnhancedStandardTaskMetadata without time components
return {
...existingMetadata,
tags: this.safeParseTagsField(existingMetadata.tags),
children: [],
} as EnhancedStandardTaskMetadata;
}
try {
// Parse time components from task content
let timeComponents: Record<string, TimeComponent> = {};
let errors: any[] = [];
let warnings: any[] = [];
try {
const result =
this.timeParsingService.parseTimeComponents(taskContent);
timeComponents = result.timeComponents;
errors = result.errors || [];
warnings = result.warnings || [];
} catch (innerErr) {
// Swallow JSON.parse or format errors from time parsing; continue without time components
console.warn(
"[MarkdownTaskParser] timeParsingService.parseTimeComponents failed, continuing without time components:",
innerErr,
);
timeComponents = {};
errors = [];
warnings = [];
}
// Log warnings if any
if (warnings.length > 0) {
console.warn(
`[MarkdownTaskParser] Time parsing warnings for "${taskContent}":`,
warnings,
);
}
// Log errors if any (but don't fail)
if (errors.length > 0) {
console.warn(
`[MarkdownTaskParser] Time parsing errors for "${taskContent}":`,
errors,
);
}
// Create enhanced metadata
const enhancedMetadata: EnhancedStandardTaskMetadata = {
...existingMetadata,
tags: this.safeParseTagsField(existingMetadata.tags),
children: [],
} as EnhancedStandardTaskMetadata;
// Add time components if found
if (Object.keys(timeComponents).length > 0) {
enhancedMetadata.timeComponents = timeComponents;
// Create enhanced datetime objects by combining existing dates with time components
enhancedMetadata.enhancedDates =
this.combineTimestampsWithTimeComponents(
{
startDate: existingMetadata.startDate,
dueDate: existingMetadata.dueDate,
scheduledDate: existingMetadata.scheduledDate,
completedDate: existingMetadata.completedDate,
},
timeComponents,
);
}
return enhancedMetadata;
} catch (error) {
console.error(
`[MarkdownTaskParser] Failed to extract time components from "${taskContent}":`,
error,
);
// Return existing metadata without time components on error
return {
...existingMetadata,
tags: this.safeParseTagsField(existingMetadata.tags),
children: [],
} as EnhancedStandardTaskMetadata;
}
}
/**
* Combine date timestamps with time components to create enhanced datetime objects
*/
private combineTimestampsWithTimeComponents(
dates: {
startDate?: number | string;
dueDate?: number | string;
scheduledDate?: number | string;
completedDate?: number | string;
},
timeComponents: EnhancedStandardTaskMetadata["timeComponents"],
): EnhancedStandardTaskMetadata["enhancedDates"] {
if (!timeComponents) {
return undefined;
}
const enhancedDates: EnhancedStandardTaskMetadata["enhancedDates"] = {};
// Helper function to combine date and time component
const combineDateTime = (
dateValue: number | string | undefined,
timeComponent: TimeComponent | undefined,
): Date | undefined => {
if (!dateValue || !timeComponent) {
return undefined;
}
let date: Date;
if (typeof dateValue === "string") {
// Handle date strings like "2025-08-25" or with optional time
const isoDatePattern =
/^\d{4}-\d{2}-\d{2}(?:\s+\d{1,2}:\d{2})?$/;
if (isoDatePattern.test(dateValue)) {
if (dateValue.includes(" ")) {
date = new Date(dateValue);
} else {
const [year, month, day] = dateValue
.split("-")
.map(Number);
date = new Date(year, month - 1, day); // month is 0-based
}
} else {
date = new Date(dateValue);
}
} else {
// Handle timestamp numbers
date = new Date(dateValue);
}
if (isNaN(date.getTime())) {
return undefined;
}
const combinedDate = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
timeComponent.hour,
timeComponent.minute,
timeComponent.second || 0,
);
return combinedDate;
};
// Combine start date with start time
if (dates.startDate && timeComponents.startTime) {
enhancedDates.startDateTime = combineDateTime(
dates.startDate,
timeComponents.startTime,
);
}
// Fallback: If start date exists but no start time, and we have a due time (default context)
// but no due date, assume the time belongs to the start date.
// This handles cases like "🛫 2025-11-29 18:00" where the time defaults to "due" context
// but should actually be associated with the start date.
if (
dates.startDate &&
!timeComponents.startTime &&
!dates.dueDate &&
timeComponents.dueTime
) {
enhancedDates.startDateTime = combineDateTime(
dates.startDate,
timeComponents.dueTime,
);
}
// Combine due date with due time
if (dates.dueDate && timeComponents.dueTime) {
enhancedDates.dueDateTime = combineDateTime(
dates.dueDate,
timeComponents.dueTime,
);
}
// Combine scheduled date with scheduled time
if (dates.scheduledDate && timeComponents.scheduledTime) {
enhancedDates.scheduledDateTime = combineDateTime(
dates.scheduledDate,
timeComponents.scheduledTime,
);
}
// Handle end time - if we have start date and end time, create end datetime
if (dates.startDate && timeComponents.endTime) {
enhancedDates.endDateTime = combineDateTime(
dates.startDate,
timeComponents.endTime,
);
}
// If we have a due date but the time component is scheduledTime (common with "at" keyword),
// create dueDateTime using scheduledTime
if (
dates.dueDate &&
!timeComponents.dueTime &&
timeComponents.scheduledTime
) {
enhancedDates.dueDateTime = combineDateTime(
dates.dueDate,
timeComponents.scheduledTime,
);
}
// If we have a scheduled date but the time component is dueTime,
// create scheduledDateTime using dueTime
if (
dates.scheduledDate &&
!timeComponents.scheduledTime &&
timeComponents.dueTime
) {
enhancedDates.scheduledDateTime = combineDateTime(
dates.scheduledDate,
timeComponents.dueTime,
);
}
return Object.keys(enhancedDates).length > 0
? enhancedDates
: undefined;
}
private extractDataviewMetadata(
content: string,
): [string, string, string] | null {
const start = content.indexOf("[");
if (start === -1) return null;
const end = content.indexOf("]", start);
if (end === -1) return null;
const bracketContent = content.substring(start + 1, end);
if (!bracketContent.includes("::")) return null;
const parts = bracketContent.split("::", 2);
if (parts.length !== 2) return null;
let key = parts[0].trim();
const value = parts[1].trim();
// Map dataview keys to standard field names for consistency
const dataviewKeyMapping: Record<string, string> = {
due: "dueDate",
start: "startDate",
scheduled: "scheduledDate",
completion: "completedDate",
created: "createdDate",
cancelled: "cancelledDate",
id: "id",
dependsOn: "dependsOn",
onCompletion: "onCompletion",
repeat: "recurrence",
};
// Apply key mapping if it exists
const mappedKey = dataviewKeyMapping[key.toLowerCase()];
if (mappedKey) {
key = mappedKey;
} else {
// Check if the key matches any configured special tag prefixes
// specialTagPrefixes format: { "prefixName": "metadataKey" }
// We need to reverse lookup: find prefix that maps to standard metadata keys
const lowerKey = key.toLowerCase();
for (const [prefix, metadataType] of Object.entries(
this.config.specialTagPrefixes || {},
)) {
if (prefix.toLowerCase() === lowerKey) {
key = metadataType; // Map to the target metadata field (project, context, area)
break;
}
}
}
if (key && value) {
// Debug: Log dataview metadata extraction for configured prefixes
const before = content.substring(0, start);
const after = content.substring(end + 1);
return [key, value, before + after];
}
return null;
}
private extractEmojiMetadata(
content: string,
): [string, string, string, string] | null {
// Find the earliest emoji
let earliestEmoji: { pos: number; emoji: string; key: string } | null =
null;
for (const [emoji, key] of Object.entries(this.config.emojiMapping)) {
const pos = content.indexOf(emoji);
if (pos !== -1) {
if (!earliestEmoji || pos < earliestEmoji.pos) {
earliestEmoji = { pos, emoji, key };
}
}
}
if (!earliestEmoji) return null;
const beforeEmoji = content.substring(0, earliestEmoji.pos);
const afterEmoji = content.substring(
earliestEmoji.pos + earliestEmoji.emoji.length,
);
// Extract value after emoji
const valueStartMatch = afterEmoji.match(/^\s*/);
const valueStart = valueStartMatch ? valueStartMatch[0].length : 0;
const valuePart = afterEmoji.substring(valueStart);
let valueEnd = valuePart.length;
for (let i = 0; i < valuePart.length; i++) {
const char = valuePart[i];
// Check if we encounter other emojis or special characters
if (
Object.keys(this.config.emojiMapping).some((e) =>
valuePart.substring(i).startsWith(e),
) ||
char === "["
) {
valueEnd = i;
break;
}
// Check for file extensions followed by space or end of content
const fileExtensionEnd = this.findFileExtensionEnd(valuePart, i);
if (fileExtensionEnd > i) {
valueEnd = fileExtensionEnd;
break;
}
// Check for whitespace followed by # (tag) or @ (context), or direct #/@ without preceding space
if (
/\s/.test(char) &&
i + 1 < valuePart.length &&
(valuePart[i + 1] === "#" || valuePart[i + 1] === "@")
) {
valueEnd = i;
break;
}
// Also stop if we encounter # or @ directly (no whitespace)
if (char === "#" || char === "@") {
valueEnd = i;
break;
}
}
const value = valuePart.substring(0, valueEnd).trim();
// Handle special field processing
let metadataValue: string;
if (earliestEmoji.key === "dependsOn" && value) {
// For dependsOn, split by comma and join back as string for metadata storage
metadataValue = value
.split(",")
.map((id) => id.trim())
.filter((id) => id.length > 0)
.join(",");
} else if (earliestEmoji.key === "priority") {
// For priority emojis, use the emoji itself or the provided value
// This ensures we can distinguish between different priority levels
metadataValue = value || earliestEmoji.emoji;
} else {
// For other emojis, use provided value or default
metadataValue =
value || this.getDefaultEmojiValue(earliestEmoji.emoji);
}
// Sanitize date-like emoji values to avoid trailing context (e.g., "2025-08-15 @work")
if (
[
"dueDate",
"startDate",
"scheduledDate",
"completedDate",
"createdDate",
"cancelledDate",
].includes(earliestEmoji.key as string) &&
typeof metadataValue === "string"
) {
const m = metadataValue.match(
/\d{4}-\d{2}-\d{2}(?:\s+\d{1,2}:\d{2})?/,
);
if (m) {
metadataValue = m[0];
}
}
const newPos =
earliestEmoji.pos +
earliestEmoji.emoji.length +
valueStart +
valueEnd;
const afterRemaining = content.substring(newPos);
return [earliestEmoji.key, metadataValue, beforeEmoji, afterRemaining];
}
/**
* Find the end position of a file extension pattern (e.g., .md, .canvas)
* followed by optional heading (#heading) and then space or end of content
*/
private findFileExtensionEnd(content: string, startPos: number): number {
const supportedExtensions = [".md", ".canvas", ".txt", ".pdf"];
for (const ext of supportedExtensions) {
if (content.substring(startPos).startsWith(ext)) {
let pos = startPos + ext.length;
// Check for optional heading (#heading)
if (pos < content.length && content[pos] === "#") {
// Find the end of the heading (next space or end of content)
while (pos < content.length && content[pos] !== " ") {
pos++;
}
}
// Check if we're at end of content or followed by space
if (pos >= content.length || content[pos] === " ") {
return pos;
}
}
}
return startPos; // No file extension pattern found
}
private getDefaultEmojiValue(emoji: string): string {
const defaultValues: Record<string, string> = {
"🔺": "highest",
"⏫": "high",
"🔼": "medium",
"🔽": "low",
"⏬️": "lowest",
"⏬": "lowest",
};
return defaultValues[emoji] || "true";
}
private extractTag(content: string): [string, string, string] | null {
// Use ContextDetector to find unprotected hash symbols
const detector = new ContextDetector(content);
detector.detectAllProtectedRanges();
const tryFrom = (startPos: number): [string, string, string] | null => {
const hashPos = detector.findNextUnprotectedHash(startPos);
if (hashPos === -1) return null;
// If an odd number of backslashes immediately precede '#', it's escaped → skip
let bsCount = 0;
let j = hashPos - 1;
while (j >= 0 && content[j] === "\\") {
bsCount++;
j--;
}
if (bsCount % 2 === 1) {
return tryFrom(hashPos + 1);
}
// Enhanced word boundary check
const isWordStart = this.isValidTagStart(content, hashPos);
if (!isWordStart) {
return tryFrom(hashPos + 1);
}
const afterHash = content.substring(hashPos + 1);
let tagEnd = 0;
// Find tag end, including '/' for special tags and Unicode characters
for (let i = 0; i < afterHash.length; i++) {
const char = afterHash[i];