-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
5701 lines (5670 loc) · 210 KB
/
main.js
File metadata and controls
5701 lines (5670 loc) · 210 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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// main.ts
var main_exports = {};
__export(main_exports, {
default: () => SpaceCommandPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian12 = require("obsidian");
// src/TodoScanner.ts
var import_obsidian4 = require("obsidian");
// src/utils.ts
var import_obsidian3 = require("obsidian");
// ../shared/ui/Notice.ts
var import_obsidian = require("obsidian");
function showNotice(logoPrefix, logoClass, message, timeout) {
const fragment = document.createDocumentFragment();
const logo = document.createElement("span");
logo.className = logoClass;
logo.textContent = logoPrefix;
fragment.appendChild(logo);
fragment.appendChild(document.createTextNode(" " + message));
return new import_obsidian.Notice(fragment, timeout);
}
function createNoticeFactory(logoPrefix, logoClass) {
return (message, timeout) => showNotice(logoPrefix, logoClass, message, timeout);
}
// ../shared/plugin/SidebarManager.ts
var SidebarManager = class {
constructor(app, viewType) {
this.app = app;
this.viewType = viewType;
}
/**
* Activate the sidebar view (create if needed, reveal if exists).
*/
async activate() {
const { workspace } = this.app;
let leaf = null;
const leaves = workspace.getLeavesOfType(this.viewType);
if (leaves.length > 0) {
leaf = leaves[0];
} else {
const rightLeaf = workspace.getRightLeaf(false);
if (rightLeaf) {
leaf = rightLeaf;
await leaf.setViewState({
type: this.viewType,
active: true
});
}
}
if (leaf) {
workspace.revealLeaf(leaf);
}
}
/**
* Toggle the sidebar view (close if open, open if closed).
*/
async toggle() {
const { workspace } = this.app;
const leaves = workspace.getLeavesOfType(this.viewType);
if (leaves.length > 0) {
leaves.forEach((leaf) => leaf.detach());
} else {
await this.activate();
}
}
/**
* Refresh all instances of the sidebar view.
* Calls render() on each view instance.
*/
refresh() {
const { workspace } = this.app;
const leaves = workspace.getLeavesOfType(this.viewType);
for (const leaf of leaves) {
const view = leaf.view;
if (view && "render" in view && typeof view.render === "function") {
view.render();
}
}
}
/**
* Get the first leaf of this sidebar type, if any.
*/
getLeaf() {
const leaves = this.app.workspace.getLeavesOfType(this.viewType);
return leaves.length > 0 ? leaves[0] : null;
}
/**
* Get the view instance from the first leaf, if any.
*/
getView() {
const leaf = this.getLeaf();
return leaf ? leaf.view : null;
}
/**
* Execute a callback on each sidebar view instance.
*/
forEach(callback) {
const leaves = this.app.workspace.getLeavesOfType(this.viewType);
for (const leaf of leaves) {
callback(leaf.view);
}
}
};
// ../shared/llm/LLMClient.ts
var import_obsidian2 = require("obsidian");
// src/utils.ts
var LOGO_PREFIX = "\u2423\u2318";
var showNotice2 = createNoticeFactory(LOGO_PREFIX, "space-command-logo");
var PLUGIN_TAGS = /* @__PURE__ */ new Set([
"#todo",
"#todos",
"#todone",
"#todones",
"#moved",
"#idea",
"#ideas",
"#ideation",
"#principle",
"#principles"
]);
var PRIORITY_TAG_MAP = {
"#focus": 0,
"#today": 1,
"#p0": 2,
"#p1": 3,
"#p2": 4,
"#p3": 5,
"#p4": 6,
"#future": 7
};
function hasTag(tags, tag) {
const lowerTag = tag.toLowerCase();
return tags.some((t) => t.toLowerCase() === lowerTag);
}
function getTagColourInfo(tag, projectColourMap) {
var _a;
const normalizedTag = tag.toLowerCase();
if (PLUGIN_TAGS.has(normalizedTag)) {
return { type: "plugin", priority: 3 };
}
if (PRIORITY_TAG_MAP[normalizedTag] !== void 0) {
return { type: "priority", priority: PRIORITY_TAG_MAP[normalizedTag] };
}
const colourIndex = (_a = projectColourMap == null ? void 0 : projectColourMap.get(normalizedTag)) != null ? _a : 4;
return { type: "project", priority: colourIndex };
}
function hasCachedRelevantTags(tags) {
if (!tags || tags.length === 0)
return false;
return tags.some((t) => PLUGIN_TAGS.has(t.tag.toLowerCase()));
}
function formatDate(date, format) {
return (0, import_obsidian3.moment)(date).format(format);
}
function getPriorityValue(tags) {
if (hasTag(tags, "#today"))
return 1;
if (hasTag(tags, "#p0"))
return 2;
if (hasTag(tags, "#p1"))
return 3;
if (hasTag(tags, "#p2"))
return 4;
if (hasTag(tags, "#p3"))
return 5;
if (hasTag(tags, "#p4"))
return 6;
if (hasTag(tags, "#future") || hasTag(tags, "#snooze") || hasTag(tags, "#snoozed"))
return 9;
if (hasTag(tags, "#focus"))
return 7;
return 8;
}
function getTagCount(tags) {
const systemTags = /* @__PURE__ */ new Set([
"#todo",
"#todos",
"#todone",
"#todones",
"#moved",
"#idea",
"#ideas",
"#ideation",
"#principle",
"#principles",
"#focus",
"#today",
"#future",
"#snooze",
"#snoozed",
"#p0",
"#p1",
"#p2",
"#p3",
"#p4"
]);
return tags.filter((tag) => !systemTags.has(tag.toLowerCase())).length;
}
function isSnoozed(tags) {
return hasTag(tags, "#future") || hasTag(tags, "#snooze") || hasTag(tags, "#snoozed");
}
function getEffectivePriority(item, allItems) {
const headerPriority = getPriorityValue(item.tags);
if (!item.isHeader || !item.childLineNumbers || item.childLineNumbers.length === 0) {
return headerPriority;
}
const childPriorities = [];
for (const childLine of item.childLineNumbers) {
const child = allItems.find(
(t) => t.filePath === item.filePath && t.lineNumber === childLine
);
if (child && !isSnoozed(child.tags)) {
childPriorities.push(getPriorityValue(child.tags));
}
}
if (childPriorities.length === 0) {
return headerPriority;
}
const sum = childPriorities.reduce((a, b) => a + b, 0);
const childAverage = sum / childPriorities.length;
return Math.min(headerPriority, childAverage);
}
function compareWithEffectivePriority(a, b, allItems) {
const priorityDiff = getEffectivePriority(a, allItems) - getEffectivePriority(b, allItems);
if (priorityDiff !== 0)
return priorityDiff;
const tagCountDiff = getTagCount(b.tags) - getTagCount(a.tags);
return tagCountDiff;
}
function extractTags(text) {
const textWithoutCode = text.replace(/`[^`]*`/g, "");
const tagRegex = /#[\w-]+/g;
return textWithoutCode.match(tagRegex) || [];
}
function filenameToTag(basename) {
return "#" + basename.toLowerCase().replace(/\s+/g, "-").replace(/[^\w-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "");
}
function hasCheckboxFormat(text) {
return /^-\s*\[[ x]\]/i.test(text.trim());
}
function isCheckboxChecked(text) {
return /^-\s*\[x\]/i.test(text.trim());
}
function markCheckboxComplete(text) {
return text.replace(/^(-\s*\[)[ ](\])/, "$1x$2");
}
function replaceTodoWithTodone(text, date) {
if (text.includes("#todos")) {
return text.replace(/#todos\b/, `#todones @${date}`);
}
return text.replace(/#todo\b/, `#todone @${date}`);
}
function replaceTodoWithMoved(text, date) {
if (text.includes("#todos")) {
return text.replace(/#todos\b/, `#moved @${date}`);
}
return text.replace(/#todo\b/, `#moved @${date}`);
}
function extractDateFromFilename(basename) {
const match = basename.match(/(\d{4}-\d{2}-\d{2})/);
return match ? match[1] : null;
}
function replaceTodoneWithTodo(text) {
if (text.includes("#todones")) {
let result2 = text.replace(/#todones\s+@\d{4}-\d{2}-\d{2}/, "#todos");
result2 = result2.replace(/#todones\b/, "#todos");
return result2;
}
let result = text.replace(/#todone\s+@\d{4}-\d{2}-\d{2}/, "#todo");
result = result.replace(/#todone\b/, "#todo");
return result;
}
function markCheckboxIncomplete(text) {
return text.replace(/^(-\s*\[)x(\])/i, "$1 $2");
}
function removeIdeaTag(text) {
return text.replace(/#idea(?:s|tion)?\b\s*/, "").trim();
}
function replaceIdeaWithTodo(text) {
return text.replace(/#idea(?:s|tion)?\b/, "#todo");
}
function renderTextWithTags(text, container, mutedTags = [], projectColourMap) {
const tagRegex = /(#[\w-]+)/g;
let lastIndex = 0;
let match;
while ((match = tagRegex.exec(text)) !== null) {
if (match.index > lastIndex) {
container.appendText(text.substring(lastIndex, match.index));
}
const tag = match[1];
const colourInfo = getTagColourInfo(tag, projectColourMap);
let tagEl;
if (mutedTags.length > 0 && mutedTags.includes(tag)) {
tagEl = container.createEl("span", {
cls: "tag muted-pill",
text: tag
});
} else {
tagEl = container.createEl("span", {
cls: "tag",
text: tag
});
}
tagEl.dataset.scTagType = colourInfo.type;
tagEl.dataset.scPriority = colourInfo.priority.toString();
lastIndex = tagRegex.lastIndex;
}
if (lastIndex < text.length) {
container.appendText(text.substring(lastIndex));
}
}
function highlightLine(editor, line) {
const lineText = editor.getLine(line);
const lineLength = lineText.length;
editor.setSelection({ line, ch: 0 }, { line, ch: lineLength });
setTimeout(() => {
editor.setCursor({ line, ch: 0 });
}, 1500);
}
function extractCompletionDate(text) {
const match = text.match(/@(\d{4}-\d{2}-\d{2})/);
return match ? match[1] : null;
}
function compareByStatusAndDate(a, b) {
const aIsComplete = a.itemType === "todone";
const bIsComplete = b.itemType === "todone";
if (!aIsComplete && bIsComplete)
return -1;
if (aIsComplete && !bIsComplete)
return 1;
if (!aIsComplete && !bIsComplete)
return 0;
const aDate = extractCompletionDate(a.text);
const bDate = extractCompletionDate(b.text);
if (aDate && !bDate)
return -1;
if (!aDate && bDate)
return 1;
if (aDate && bDate) {
return bDate.localeCompare(aDate);
}
return 0;
}
function createFingerprint(text) {
let content = text.trim();
content = content.replace(/`[^`]*`/g, "");
content = content.replace(/^#{1,6}\s+/, "");
content = content.replace(/^[-*+]\s*/, "");
content = content.replace(/^\d+\.\s*/, "");
content = content.replace(/^\[[ xX]?\]\s*/, "");
content = content.replace(/#[\w-]+/g, "");
content = content.replace(/@\d{4}-\d{2}-\d{2}/g, "");
content = content.replace(/\^[\w-]+/g, "");
return content.trim();
}
function resolveLineNumber(lines, hint, fingerprint) {
if (!fingerprint)
return hint;
if (hint >= 0 && hint < lines.length && createFingerprint(lines[hint]) === fingerprint) {
return hint;
}
const NEARBY = 15;
for (let delta = 1; delta <= NEARBY; delta++) {
const before = hint - delta;
const after = hint + delta;
if (before >= 0 && before < lines.length && createFingerprint(lines[before]) === fingerprint)
return before;
if (after < lines.length && createFingerprint(lines[after]) === fingerprint)
return after;
}
return lines.findIndex((l) => createFingerprint(l) === fingerprint);
}
async function modifyFileLine(vault, file, lineNumber, transform, validate, fingerprint) {
const content = await vault.read(file);
const lines = content.split("\n");
const resolved = fingerprint ? resolveLineNumber(lines, lineNumber, fingerprint) : lineNumber;
if (resolved < 0 || resolved >= lines.length) {
throw new Error(
`Cannot locate line ${lineNumber} in ${file.path}` + (fingerprint ? ` (fingerprint: "${fingerprint}")` : "")
);
}
const currentLine = lines[resolved];
if (validate) {
const error = validate(currentLine);
if (error)
throw new Error(error);
}
lines[resolved] = transform(currentLine);
await vault.modify(file, lines.join("\n"));
}
function openFileAtLine(app, file, line) {
const leaf = app.workspace.getLeaf(false);
leaf.openFile(file, { active: true }).then(() => {
const view = app.workspace.getActiveViewOfType(import_obsidian3.MarkdownView);
if (view == null ? void 0 : view.editor) {
const editor = view.editor;
editor.setCursor({ line, ch: 0 });
editor.scrollIntoView({ from: { line, ch: 0 }, to: { line, ch: 0 } }, true);
highlightLine(editor, line);
}
});
}
// src/TodoScanner.ts
var TodoScanner = class extends import_obsidian4.Events {
constructor(app) {
super();
this.todosCache = /* @__PURE__ */ new Map();
this.todonesCache = /* @__PURE__ */ new Map();
this.ideasCache = /* @__PURE__ */ new Map();
this.principlesCache = /* @__PURE__ */ new Map();
this.excludeFiles = /* @__PURE__ */ new Set();
this.app = app;
this.debouncedScanFile = (0, import_obsidian4.debounce)(
(file) => this.scanFile(file),
100,
true
);
}
setExcludeFiles(filePaths) {
this.excludeFiles = new Set(filePaths);
}
// Remove all cached items for a given file path across all four caches.
evictFile(filePath) {
this.todosCache.delete(filePath);
this.todonesCache.delete(filePath);
this.ideasCache.delete(filePath);
this.principlesCache.delete(filePath);
}
// Return true if the metadataCache shows this file contains at least one
// plugin-relevant tag. Files without relevant tags are skipped before reading.
fileHasRelevantTags(file) {
const cache = this.app.metadataCache.getFileCache(file);
return hasCachedRelevantTags(cache == null ? void 0 : cache.tags);
}
async scanVault() {
this.todosCache.clear();
this.todonesCache.clear();
this.ideasCache.clear();
this.principlesCache.clear();
const files = this.app.vault.getMarkdownFiles();
for (const file of files) {
if (this.fileHasRelevantTags(file)) {
await this.scanFile(file);
}
}
this.trigger("todos-updated");
}
async scanFile(file) {
if (!this.fileHasRelevantTags(file)) {
this.evictFile(file.path);
this.trigger("todos-updated");
return;
}
try {
const content = await this.app.vault.read(file);
const lines = content.split("\n");
const todos = [];
const todones = [];
const ideas = [];
const principles = [];
const linesToCleanup = [];
const linesToSyncTodone = [];
const linesToRemoveIdea = [];
const linesToStampMoved = [];
let inCodeBlock = false;
let currentHeaderTodo = null;
let currentHeaderIdea = null;
let currentHeaderPrinciple = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.trim().startsWith("```")) {
inCodeBlock = !inCodeBlock;
continue;
}
if (inCodeBlock) {
continue;
}
const tags = extractTags(line);
if (tags.includes("#moved")) {
if (!/@\d{4}-\d{2}-\d{2}/.test(line)) {
linesToStampMoved.push(i);
}
continue;
}
const headerInfo = this.detectHeader(line);
if (headerInfo) {
currentHeaderTodo = null;
currentHeaderIdea = null;
currentHeaderPrinciple = null;
}
if (headerInfo && (tags.includes("#todo") || tags.includes("#todos")) && !tags.includes("#todone") && !tags.includes("#todones")) {
if (!this.hasContent(line))
continue;
const headerTodo = this.createTodoItem(file, i, line, tags, "todo");
headerTodo.isHeader = true;
headerTodo.headerLevel = headerInfo.level;
headerTodo.childLineNumbers = [];
todos.push(headerTodo);
currentHeaderTodo = { lineNumber: i, level: headerInfo.level, todoItem: headerTodo };
continue;
}
if (headerInfo && (tags.includes("#todone") || tags.includes("#todones"))) {
if (!this.hasContent(line))
continue;
const headerTodone = this.createTodoItem(file, i, line, tags, "todone");
headerTodone.isHeader = true;
headerTodone.headerLevel = headerInfo.level;
todones.push(headerTodone);
currentHeaderTodo = null;
continue;
}
if (currentHeaderTodo && this.isListItem(line)) {
const hasIdeaTag = tags.includes("#idea") || tags.includes("#ideas") || tags.includes("#ideation");
if (hasIdeaTag) {
continue;
}
const hasPrincipleTag = tags.includes("#principle") || tags.includes("#principles");
if (hasPrincipleTag) {
} else {
const isChecked = isCheckboxChecked(line);
const hasTodoneTag = tags.includes("#todone");
if (isChecked && !hasTodoneTag) {
linesToSyncTodone.push(i);
tags.push("#todone");
}
if (!this.hasContent(line))
continue;
const childItemType = tags.includes("#todone") ? "todone" : "todo";
const childItem = this.createTodoItem(file, i, line, tags, childItemType);
childItem.parentLineNumber = currentHeaderTodo.lineNumber;
currentHeaderTodo.todoItem.childLineNumbers.push(i);
if (tags.includes("#todone")) {
todones.push(childItem);
} else {
todos.push(childItem);
}
continue;
}
}
const hasTodo = tags.includes("#todo") || tags.includes("#todos");
let hasTodone = tags.includes("#todone") || tags.includes("#todones");
const hasIdea = tags.includes("#idea") || tags.includes("#ideas") || tags.includes("#ideation");
const lineHasContent = this.hasContent(line);
if (hasTodo && !hasTodone && !hasIdea && isCheckboxChecked(line)) {
linesToSyncTodone.push(i);
tags.push("#todone");
hasTodone = true;
}
if (hasTodone && hasTodo) {
linesToCleanup.push(i);
if (lineHasContent)
todones.push(this.createTodoItem(file, i, line, tags, "todone"));
} else if (hasTodo && !hasIdea) {
if (lineHasContent)
todos.push(this.createTodoItem(file, i, line, tags, "todo"));
} else if (hasTodone) {
if (lineHasContent)
todones.push(this.createTodoItem(file, i, line, tags, "todone"));
}
if (tags.includes("#idea") || tags.includes("#ideas") || tags.includes("#ideation")) {
if (!lineHasContent)
continue;
if (isCheckboxChecked(line)) {
linesToRemoveIdea.push(i);
continue;
}
if (headerInfo) {
const headerIdea = this.createTodoItem(file, i, line, tags, "idea");
headerIdea.isHeader = true;
headerIdea.headerLevel = headerInfo.level;
headerIdea.childLineNumbers = [];
ideas.push(headerIdea);
currentHeaderIdea = { lineNumber: i, level: headerInfo.level, todoItem: headerIdea };
} else {
ideas.push(this.createTodoItem(file, i, line, tags, "idea"));
}
} else if (currentHeaderIdea && this.isListItem(line) && !tags.includes("#todo") && !tags.includes("#todone")) {
if (!this.hasContent(line))
continue;
const childItem = this.createTodoItem(file, i, line, tags, "idea");
childItem.parentLineNumber = currentHeaderIdea.lineNumber;
currentHeaderIdea.todoItem.childLineNumbers.push(i);
ideas.push(childItem);
}
if (tags.includes("#principle") || tags.includes("#principles")) {
if (!lineHasContent)
continue;
if (headerInfo) {
const headerPrinciple = this.createTodoItem(file, i, line, tags, "principle");
headerPrinciple.isHeader = true;
headerPrinciple.headerLevel = headerInfo.level;
headerPrinciple.childLineNumbers = [];
principles.push(headerPrinciple);
currentHeaderPrinciple = { lineNumber: i, level: headerInfo.level, todoItem: headerPrinciple };
} else {
principles.push(this.createTodoItem(file, i, line, tags, "principle"));
}
} else if (currentHeaderPrinciple && this.isListItem(line) && !tags.includes("#todo") && !tags.includes("#todone") && !tags.includes("#idea") && !tags.includes("#ideas") && !tags.includes("#ideation")) {
if (!this.hasContent(line))
continue;
const childItem = this.createTodoItem(file, i, line, tags, "principle");
childItem.parentLineNumber = currentHeaderPrinciple.lineNumber;
currentHeaderPrinciple.todoItem.childLineNumbers.push(i);
principles.push(childItem);
}
}
await this.applyLineMutations(file, lines, linesToCleanup, linesToSyncTodone, linesToRemoveIdea, linesToStampMoved);
if (todos.length > 0) {
this.todosCache.set(file.path, todos);
} else {
this.todosCache.delete(file.path);
}
if (todones.length > 0) {
this.todonesCache.set(file.path, todones);
} else {
this.todonesCache.delete(file.path);
}
if (ideas.length > 0) {
this.ideasCache.set(file.path, ideas);
} else {
this.ideasCache.delete(file.path);
}
if (principles.length > 0) {
this.principlesCache.set(file.path, principles);
} else {
this.principlesCache.delete(file.path);
}
this.trigger("todos-updated");
} catch (error) {
console.error(`Error scanning file ${file.path}:`, error);
}
}
// Detect markdown header and return its level
detectHeader(line) {
const match = line.match(/^(#{1,6})\s+/);
if (match) {
return { level: match[1].length };
}
return null;
}
// Check if a line is a list item (bullet or numbered)
isListItem(line) {
return /^[\s]*[-*+]\s/.test(line) || /^[\s]*\d+\.\s/.test(line);
}
createTodoItem(file, lineNumber, text, tags, itemType) {
var _a;
return {
file,
filePath: file.path,
folder: ((_a = file.parent) == null ? void 0 : _a.path) || "",
lineNumber,
fingerprint: createFingerprint(text),
text: text.trim(),
hasCheckbox: hasCheckboxFormat(text),
tags,
dateCreated: file.stat.mtime,
itemType,
inferredFileTag: filenameToTag(file.basename)
};
}
/**
* Check if a line has meaningful content beyond tags and markers.
* Returns false for empty items like "- [ ] #todo" or "- #idea "
*/
hasContent(text) {
let content = text.trim();
content = content.replace(/^#{1,6}\s*/, "");
content = content.replace(/^[-*+]\s*/, "");
content = content.replace(/^\d+\.\s*/, "");
content = content.replace(/^\[[ xX]?\]\s*/, "");
content = content.replace(/#[\w-]+/g, "");
content = content.replace(/@\d{4}-\d{2}-\d{2}/g, "");
content = content.replace(/\^[\w-]+/g, "");
return content.trim().length > 0;
}
getTodos() {
const allTodos = [];
for (const [filePath, todos] of this.todosCache.entries()) {
if (this.excludeFiles.has(filePath))
continue;
allTodos.push(...todos);
}
return allTodos.sort((a, b) => a.dateCreated - b.dateCreated);
}
getTodones(limit) {
const allTodones = [];
for (const [filePath, todones] of this.todonesCache.entries()) {
if (this.excludeFiles.has(filePath)) {
continue;
}
allTodones.push(...todones);
}
const sorted = allTodones.sort((a, b) => b.dateCreated - a.dateCreated);
return limit ? sorted.slice(0, limit) : sorted;
}
getIdeas() {
const allIdeas = [];
for (const [filePath, ideas] of this.ideasCache.entries()) {
if (this.excludeFiles.has(filePath)) {
continue;
}
allIdeas.push(...ideas);
}
return allIdeas.sort((a, b) => a.dateCreated - b.dateCreated);
}
getPrinciples() {
const allPrinciples = [];
for (const [filePath, principles] of this.principlesCache.entries()) {
if (this.excludeFiles.has(filePath)) {
continue;
}
allPrinciples.push(...principles);
}
return allPrinciples.sort((a, b) => a.dateCreated - b.dateCreated);
}
watchFiles() {
this.app.metadataCache.on("changed", (file) => {
if (file instanceof import_obsidian4.TFile && file.extension === "md") {
this.debouncedScanFile(file);
}
});
this.app.vault.on("create", (file) => {
if (file instanceof import_obsidian4.TFile && file.extension === "md") {
this.debouncedScanFile(file);
}
});
this.app.vault.on("delete", (file) => {
if (file instanceof import_obsidian4.TFile) {
this.evictFile(file.path);
this.trigger("todos-updated");
}
});
this.app.vault.on("rename", (file, oldPath) => {
if (file instanceof import_obsidian4.TFile && file.extension === "md") {
this.evictFile(oldPath);
this.debouncedScanFile(file);
}
});
}
// Apply all queued line mutations in a single vault.modify() call.
// Processes cleanup, checkbox sync, and idea tag removal together so only one write occurs.
async applyLineMutations(file, lines, linesToCleanup, linesToSyncTodone, linesToRemoveIdea, linesToStampMoved = []) {
if (linesToCleanup.length === 0 && linesToSyncTodone.length === 0 && linesToRemoveIdea.length === 0 && linesToStampMoved.length === 0) {
return;
}
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
let modified = false;
for (const lineNum of linesToCleanup) {
const newLine = lines[lineNum].replace(/#todos?\b\s*/g, "");
if (newLine !== lines[lineNum]) {
lines[lineNum] = newLine;
modified = true;
}
}
for (const lineNum of linesToSyncTodone) {
const newLine = lines[lineNum].trimEnd() + ` #todone @${today}`;
if (newLine !== lines[lineNum]) {
lines[lineNum] = newLine;
modified = true;
}
}
for (const lineNum of linesToRemoveIdea) {
const newLine = lines[lineNum].replace(/#idea(?:s|tion)?\b\s*/g, "");
if (newLine !== lines[lineNum]) {
lines[lineNum] = newLine;
modified = true;
}
}
if (linesToStampMoved.length > 0) {
const movedDate = extractDateFromFilename(file.basename) || today;
for (const lineNum of linesToStampMoved) {
const newLine = lines[lineNum].trimEnd() + ` @${movedDate}`;
if (newLine !== lines[lineNum]) {
lines[lineNum] = newLine;
modified = true;
}
}
}
if (modified) {
await this.app.vault.modify(file, lines.join("\n"));
}
}
};
// src/TodoProcessor.ts
var import_obsidian5 = require("obsidian");
var TodoProcessor = class {
constructor(app, dateFormat = "YYYY-MM-DD") {
this.app = app;
this.dateFormat = dateFormat;
}
setScanner(scanner) {
this.scanner = scanner;
}
setOnCompleteCallback(callback) {
this.onComplete = callback;
}
setOnMoveHistoryUpdate(callback) {
this.onMoveHistoryUpdate = callback;
}
async completeTodo(todo, todoneFilePath) {
var _a;
try {
const today = formatDate(/* @__PURE__ */ new Date(), this.dateFormat);
if (todo.isHeader && todo.childLineNumbers && todo.childLineNumbers.length > 0) {
await this.completeChildrenLines(todo.file, todo.childLineNumbers, today);
}
await this.updateSourceFile(todo, today);
await this.appendToTodoneFile(todo, todoneFilePath, today);
if (this.scanner) {
await this.scanner.scanFile(todo.file);
}
if (this.onComplete) {
this.onComplete();
}
const childCount = ((_a = todo.childLineNumbers) == null ? void 0 : _a.length) || 0;
const message = childCount > 0 ? `TODO marked as complete! (including ${childCount} child item${childCount > 1 ? "s" : ""})` : "TODO marked as complete!";
showNotice2(message);
return true;
} catch (error) {
console.error("Error completing TODO:", error);
showNotice2("Failed to complete TODO. See console for details.");
return false;
}
}
// Complete all child lines of a header TODO
async completeChildrenLines(file, lineNumbers, date) {
const content = await this.app.vault.read(file);
const lines = content.split("\n");
for (const lineNum of lineNumbers) {
if (lineNum >= lines.length)
continue;
let line = lines[lineNum];
if (!line.includes("#todone")) {
if (line.includes("#todo")) {
line = replaceTodoWithTodone(line, date);
} else {
line = line.trimEnd() + ` #todone @${date}`;
}
}
if (/\[\s*\]/.test(line)) {
line = markCheckboxComplete(line);
}
lines[lineNum] = line;
}
await this.app.vault.modify(file, lines.join("\n"));
}
async uncompleteTodo(todo) {
try {
await this.revertSourceFile(todo);
if (this.scanner) {
await this.scanner.scanFile(todo.file);
}
if (this.onComplete) {
this.onComplete();
}
showNotice2("TODO marked as incomplete!");
return true;
} catch (error) {
console.error("Error uncompleting TODO:", error);
showNotice2("Failed to uncomplete TODO. See console for details.");
return false;
}
}
/**
* Move a TODO from its current file to a destination file.
* Source line gets #todo → #moved @date; destination gets a fresh #todo copy.
* Header TODOs move with all their children as a block.
*/
async moveTodo(todo, destinationPath) {
var _a, _b;
try {
if (todo.filePath === destinationPath) {
showNotice2("Cannot move to the same file.");
return false;
}
const today = formatDate(/* @__PURE__ */ new Date(), this.dateFormat);
const sourceContent = await this.app.vault.read(todo.file);
const sourceLines = sourceContent.split("\n");
const lineNumbers = [todo.lineNumber];
if (todo.isHeader && todo.childLineNumbers && todo.childLineNumbers.length > 0) {
lineNumbers.push(...todo.childLineNumbers);
}
lineNumbers.sort((a, b) => a - b);
const destLines = [];
for (const lineNum of lineNumbers) {
if (lineNum < 0 || lineNum >= sourceLines.length)
continue;
destLines.push(sourceLines[lineNum]);
}
await this.appendToDestination(destinationPath, destLines.join("\n"));
for (const lineNum of lineNumbers) {
if (lineNum < 0 || lineNum >= sourceLines.length)
continue;
let line = sourceLines[lineNum];
if (line.includes("#todo")) {
line = replaceTodoWithMoved(line, today);
} else {
line = line.trimEnd() + ` #moved @${today}`;
}
sourceLines[lineNum] = line;
}
await this.app.vault.modify(todo.file, sourceLines.join("\n"));
if (this.scanner) {
await this.scanner.scanFile(todo.file);
const destFile = this.app.vault.getAbstractFileByPath(destinationPath);
if (destFile instanceof import_obsidian5.TFile) {
await this.scanner.scanFile(destFile);
}
}
if (this.onMoveHistoryUpdate) {
this.onMoveHistoryUpdate(destinationPath);
}
if (this.onComplete) {
this.onComplete();
}
const basename = ((_a = destinationPath.split("/").pop()) == null ? void 0 : _a.replace(/\.md$/, "")) || destinationPath;
const childCount = todo.isHeader && ((_b = todo.childLineNumbers) == null ? void 0 : _b.length) || 0;
const message = childCount > 0 ? `Moved to ${basename} (including ${childCount} child item${childCount > 1 ? "s" : ""})` : `Moved to ${basename}`;
showNotice2(message);
return true;
} catch (error) {
console.error("Error moving TODO:", error);
showNotice2("Failed to move TODO. See console for details.");
return false;
}
}
/**
* Append text to a destination file, creating it if it doesn't exist.
*/
async appendToDestination(filePath, text) {
let file = this.app.vault.getAbstractFileByPath(filePath);
if (!file) {
const pathParts = filePath.split("/");
pathParts.pop();
const folderPath = pathParts.join("/");
if (folderPath) {
await this.ensureFolderExists(folderPath);
}
file = await this.app.vault.create(filePath, "");
}
if (!(file instanceof import_obsidian5.TFile)) {
throw new Error(`${filePath} is not a file`);
}
const currentContent = await this.app.vault.read(file);
const newContent = currentContent ? `${currentContent}
${text}` : text;
await this.app.vault.modify(file, newContent);
}
async revertSourceFile(todo) {
await modifyFileLine(
this.app.vault,
todo.file,
todo.lineNumber,
(line) => {
let updated = replaceTodoneWithTodo(line);
if (todo.hasCheckbox)
updated = markCheckboxIncomplete(updated);
return updated;
},
(line) => {
if (!line.includes("#todone")) {
return `Line ${todo.lineNumber} in ${todo.filePath} no longer contains #todone tag. File may have been modified.`;
}
return null;
},
todo.fingerprint
);
}