-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
4210 lines (3623 loc) · 148 KB
/
main.ts
File metadata and controls
4210 lines (3623 loc) · 148 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
import { Plugin, MarkdownView, TFile, Modal, PluginSettingTab, WorkspaceLeaf, Setting, Notice, App } from 'obsidian';
import { MarginaliaView, EditMarginaliaModal, DeleteConfirmationModal } from './src/sidebar';
import { MarginaliaEditorExtension } from './src/editorExtension';
import { MarginaliaData, MarginaliaItem } from './src/types';
// Settings are stored in data.json via Obsidian's loadData()/saveData()
// Marginalia data is stored in marginalia.json
// Note embeddings are stored in notes_embedding.json
// Interface for note embedding chunks
export interface NoteEmbeddingChunk {
chunk_id: string;
char_start: number;
char_end: number;
vector: number[];
}
// Interface for note embedding entries
export interface NoteEmbedding {
embedding_id: string;
source_path: string;
noteEdited: string;
chunks: NoteEmbeddingChunk[];
}
export interface MarginaliaSettings {
highlightColor: string;
opacity: number;
ollamaAddress: string;
ollamaPort: string;
indicatorVisibility: 'pen' | 'highlight' | 'both' | 'neither';
penIconPosition: 'left' | 'right'; // Position of pen icon in margin
ollamaAvailable: boolean; // Track if Ollama is available (server reachable AND both models available)
ollamaServerStatus: 'available' | 'unavailable' | 'unknown'; // Individual server status
nomicModelStatus: 'available' | 'unavailable' | 'unknown'; // Individual nomic model status
qwenModelStatus: 'available' | 'unavailable' | 'unknown'; // Individual qwen model status
sortOrder: 'position' | 'date-asc' | 'date-desc'; // Sort order for current note marginalia
defaultSimilarity: number; // Default similarity threshold for AI functions (0.5 to 1.0)
embeddingOn: boolean; // Whether note embedding is active
similarityFolders: string; // Folders to include in similarity analysis (comma-separated)
maxChunkSize: number; // Maximum size of note before forcing chunking (1000-7000)
}
const DEFAULT_SETTINGS: MarginaliaSettings = {
highlightColor: '#ffeb3d', // Yellow
opacity: 0.5, // 50% opacity
ollamaAddress: 'localhost',
ollamaPort: '11434',
indicatorVisibility: 'both',
penIconPosition: 'right', // Default to right margin
ollamaAvailable: false,
ollamaServerStatus: 'unknown',
nomicModelStatus: 'unknown',
qwenModelStatus: 'unknown',
sortOrder: 'position',
defaultSimilarity: 0.60, // Default similarity threshold for AI functions
embeddingOn: false, // Note embedding starts as inactive
similarityFolders: '', // Empty by default, user specifies folders
maxChunkSize: 1800 // Default maximum chunk size before forcing chunking
};
export default class MarginaliaPlugin extends Plugin {
public marginaliaData: Map<string, MarginaliaData> = new Map();
private sidebarView: MarginaliaView | null = null;
settings: MarginaliaSettings;
public embeddingProgressCallback: (() => void) | null = null;
private embeddingQueue: Set<string> = new Set(); // Queue of file paths to process
private isProcessingEmbeddingQueue: boolean = false;
private embeddingDebounceTimers: Map<string, NodeJS.Timeout> = new Map();
private embeddingRetryCount: Map<string, number> = new Map(); // Track retry count per file
private readonly MAX_RETRIES = 3; // Maximum number of retries for a file
private embeddingListenersRegistered: boolean = false; // Track if listeners are already registered
async onload() {
// Load settings and merge with defaults
const loadedData = await this.loadData();
// Backwards compatibility: Check if marginalia data exists in data.json and migrate it
let loadedSettings: any = loadedData || {};
let marginaliaDataToMigrate: Record<string, MarginaliaData> | null = null;
// Check if data.json contains marginalia data (file paths as keys with MarginaliaData structure)
// Settings have known property names, marginalia data has file paths as keys
const settingsKeys = Object.keys(DEFAULT_SETTINGS);
const potentialMarginaliaKeys: string[] = [];
for (const key in loadedData) {
// If key is not a known setting and looks like a file path, it might be marginalia data
if (!settingsKeys.includes(key) && typeof loadedData[key] === 'object' && loadedData[key] !== null) {
const value = loadedData[key];
// Check if it has the structure of MarginaliaData (has 'items' array)
if (Array.isArray(value.items) && value.items.length > 0) {
// Verify items structure looks like MarginaliaItem
const firstItem = value.items[0];
if (firstItem && typeof firstItem === 'object' && ('id' in firstItem || 'text' in firstItem || 'note' in firstItem)) {
potentialMarginaliaKeys.push(key);
}
}
}
}
// If we found marginalia data, extract it
if (potentialMarginaliaKeys.length > 0) {
marginaliaDataToMigrate = {};
for (const key of potentialMarginaliaKeys) {
marginaliaDataToMigrate[key] = loadedData[key] as MarginaliaData;
delete loadedSettings[key];
}
}
// Handle migration from 'transparency' to 'opacity'
if (loadedSettings && 'transparency' in loadedSettings && !('opacity' in loadedSettings)) {
loadedSettings.opacity = (loadedSettings as any).transparency;
delete (loadedSettings as any).transparency;
}
// Merge defaults with loaded settings (loaded settings take precedence)
// This ensures new settings get defaults, but existing saved settings are preserved
this.settings = Object.assign({}, DEFAULT_SETTINGS, loadedSettings || {});
// Ensure critical settings have valid values (defensive programming)
// Only validate/reset if the value is truly invalid (not just missing)
// This prevents overwriting valid saved values with defaults
if (loadedSettings && loadedSettings.highlightColor !== undefined) {
// Value was explicitly loaded - validate it strictly
if (typeof loadedSettings.highlightColor !== 'string' || loadedSettings.highlightColor.trim() === '') {
// Invalid value - reset to default
this.settings.highlightColor = DEFAULT_SETTINGS.highlightColor;
}
// If valid, keep the loaded value (already in this.settings from Object.assign)
}
// If highlightColor wasn't in loadedSettings, Object.assign already set it to default
if (loadedSettings && loadedSettings.opacity !== undefined) {
// Value was explicitly loaded - validate it strictly
if (typeof loadedSettings.opacity !== 'number' || isNaN(loadedSettings.opacity) || loadedSettings.opacity < 0.1 || loadedSettings.opacity > 1) {
// Invalid value - reset to default
this.settings.opacity = DEFAULT_SETTINGS.opacity;
}
// If valid, keep the loaded value (already in this.settings from Object.assign)
}
// If opacity wasn't in loadedSettings, Object.assign already set it to default
// Validate new settings fields
if (loadedSettings && loadedSettings.embeddingOn !== undefined) {
if (typeof loadedSettings.embeddingOn !== 'boolean') {
this.settings.embeddingOn = DEFAULT_SETTINGS.embeddingOn;
}
}
if (loadedSettings && loadedSettings.similarityFolders !== undefined) {
if (typeof loadedSettings.similarityFolders !== 'string') {
this.settings.similarityFolders = DEFAULT_SETTINGS.similarityFolders;
}
}
if (loadedSettings && loadedSettings.maxChunkSize !== undefined) {
if (typeof loadedSettings.maxChunkSize !== 'number' || loadedSettings.maxChunkSize < 1000 || loadedSettings.maxChunkSize > 7000) {
this.settings.maxChunkSize = DEFAULT_SETTINGS.maxChunkSize;
}
}
// Backwards compatibility: Migrate marginalia data from data.json to marginalia.json if found
if (marginaliaDataToMigrate) {
try {
const marginaliaPath = this.getMarginaliaFilePath();
const marginaliaExists = await this.app.vault.adapter.exists(marginaliaPath);
// Read existing marginalia data if it exists
let existingMarginalia: Record<string, MarginaliaData> = {};
if (marginaliaExists) {
const existingData = await this.app.vault.adapter.read(marginaliaPath);
if (existingData) {
existingMarginalia = JSON.parse(existingData);
}
}
// Merge migrated data with existing data (migrated data takes precedence for conflicts)
const mergedMarginalia = Object.assign({}, existingMarginalia, marginaliaDataToMigrate);
// Write to marginalia.json
await this.app.vault.adapter.write(marginaliaPath, JSON.stringify(mergedMarginalia, null, 2));
console.log(`Migrated ${Object.keys(marginaliaDataToMigrate).length} file(s) of marginalia data from data.json to marginalia.json`);
} catch (error) {
console.error('Error migrating marginalia data:', error);
}
}
// Always save to ensure settings are persisted correctly (this will save cleaned settings without marginalia data)
await this.saveData(this.settings);
this.applySettings();
// Register the sidebar view
this.registerView('marginalia-view', (leaf: WorkspaceLeaf) => {
this.sidebarView = new MarginaliaView(leaf, this);
return this.sidebarView;
});
this.addRibbonIcon('book-open', 'Marginalia', () => {
this.activateView();
});
// Register editor extension
this.registerEditorExtension(MarginaliaEditorExtension(this));
// Register context menu item for editor mode
this.registerEvent(
this.app.workspace.on('editor-menu', (menu, editor, view) => {
if (view instanceof MarkdownView) {
this.addContextMenuItem(menu, editor, view);
}
})
);
// Load existing marginalia data
await this.loadMarginaliaData();
// If embedding is on, ensure the embedding file exists and start monitoring
if (this.settings.embeddingOn) {
try {
await this.initializeEmbeddingFile();
// Start monitoring folders for embedding
this.startEmbeddingMonitor();
} catch (error) {
console.error('Error initializing embedding file on load:', error);
// Don't fail plugin load, just log the error
}
}
// Check Ollama availability on startup (non-blocking)
setTimeout(async () => {
await this.checkOllamaOnStartup();
// Only generate embeddings if Ollama check succeeded
if (this.settings.ollamaAvailable) {
this.generateMissingEmbeddings();
this.generateMissingSelectionEmbeddings();
}
}, 1000);
// Refresh sidebar when file changes
this.registerEvent(
this.app.workspace.on('file-open', (file: TFile | null) => {
if (file instanceof TFile) {
this.loadMarginaliaForFile(file.path);
}
if (this.sidebarView) {
this.sidebarView.refresh();
}
})
);
// Register sidebar view
this.addSettingTab(new MarginaliaSettingTab(this.app, this));
}
async onunload() {
await this.saveMarginaliaData();
}
private async activateView() {
const leaf = this.app.workspace.getRightLeaf(false);
if (leaf) {
await leaf.setViewState({
type: 'marginalia-view',
active: true,
});
this.app.workspace.revealLeaf(leaf);
}
}
private addContextMenuItem(menu: any, editor: any, view: MarkdownView) {
const file = view.file;
if (!file) return;
// Check if current selection would overlap with existing marginalia
const selection = editor.getSelection();
const cursor = editor.getCursor();
let from = selection ? editor.getCursor('from') : cursor;
let to = selection ? editor.getCursor('to') : cursor;
if (!selection) {
// For cursor-only notes, use the cursor position
from = { line: cursor.line, ch: cursor.ch };
to = { line: cursor.line, ch: cursor.ch };
}
// Create a temporary item to check for overlap
const tempItem: MarginaliaItem = {
id: '',
text: selection || '',
note: '',
from: from,
to: to,
line: cursor.line,
ch: cursor.ch
};
// Only show menu item if there's no overlap
if (!this.wouldOverlap(file.path, tempItem)) {
menu.addItem((item: any) => {
item.setTitle('Add marginalia')
.setIcon('sticky-note')
.onClick(() => {
this.showMarginNoteModal(editor, view);
});
});
}
}
private showMarginNoteModal(editor: any, view: MarkdownView) {
const selection = editor.getSelection();
const cursor = editor.getCursor();
const file = view.file;
if (!file) return;
// If no selection, try to get the word at cursor position
let from = selection ? editor.getCursor('from') : cursor;
let to = selection ? editor.getCursor('to') : cursor;
let text = selection || '';
if (!selection) {
// For cursor-only notes, use the cursor position
// Ensure from and to are the same for cursor positions
from = { line: cursor.line, ch: cursor.ch };
to = { line: cursor.line, ch: cursor.ch };
text = ''; // Empty text indicates cursor-only note
}
// Create modal for entering margin note
const modal = new MarginNoteModal(this.app, this.settings.highlightColor, async (note: string, color?: string) => {
if (note.trim()) {
await this.addMarginalia(file.path, {
id: this.generateId(),
text: text,
note: note,
from: from,
to: to,
line: cursor.line,
ch: cursor.ch,
timestamp: Date.now(),
color: color
});
}
}, text, this);
modal.open();
}
public async addMarginalia(filePath: string, item: MarginaliaItem) {
// Check for overlaps before adding
if (this.wouldOverlap(filePath, item)) {
new Notice('Cannot create marginalia: This area overlaps with an existing highlight.');
return;
}
// Ensure color is set (use default if not provided)
if (!item.color) {
item.color = this.settings.highlightColor;
}
if (!this.marginaliaData.has(filePath)) {
this.marginaliaData.set(filePath, { items: [] });
}
const data = this.marginaliaData.get(filePath)!;
data.items.push(item);
// Generate embeddings for the new marginalia
if (this.hasMeaningfulText(item.note)) {
await this.generateEmbeddingForItem(item); // For note text
} else {
// Set to null if no meaningful note text
item.embedding = null;
}
if (this.hasMeaningfulText(item.text)) {
await this.generateSelectionEmbeddingForItem(item); // For selection text
} else {
// Set to null if no meaningful text (empty, whitespace, linefeeds, etc.)
item.selectionEmbedding = null;
}
await this.saveMarginaliaForFile(filePath);
this.refreshEditor(filePath);
if (this.sidebarView) {
this.sidebarView.refresh();
}
}
public async updateMarginalia(filePath: string, id: string, note: string, color?: string) {
const data = this.marginaliaData.get(filePath);
if (data) {
const item = data.items.find(i => i.id === id);
if (item) {
item.note = note;
// Update color if provided
if (color !== undefined) {
item.color = color;
}
// Update timestamp to reflect the edit time
item.timestamp = Date.now();
// Regenerate embedding since note changed
if (this.hasMeaningfulText(item.note)) {
await this.generateEmbeddingForItem(item);
} else {
// Set to null if no meaningful note text
item.embedding = null;
}
// Ensure selection embedding is null if selection text is not meaningful
if (!this.hasMeaningfulText(item.text)) {
item.selectionEmbedding = null;
}
await this.saveMarginaliaForFile(filePath);
this.refreshEditor(filePath);
if (this.sidebarView) {
this.sidebarView.refresh();
}
}
}
}
public async deleteMarginalia(filePath: string, id: string) {
const data = this.marginaliaData.get(filePath);
if (data) {
data.items = data.items.filter(i => i.id !== id);
await this.saveMarginaliaForFile(filePath);
// Immediately refresh editor
this.refreshEditor(filePath);
if (this.sidebarView) {
this.sidebarView.refresh();
}
}
}
public getMarginalia(filePath: string): MarginaliaItem[] {
const data = this.marginaliaData.get(filePath);
return data ? data.items : [];
}
/**
* Update marginalia positions when document changes
* Converts line/ch to absolute positions in OLD document, maps through changes, then converts back to line/ch in NEW document
*/
public async updateMarginaliaPositions(filePath: string, changes: any, oldDoc: any, newDoc: any): Promise<void> {
const data = this.marginaliaData.get(filePath);
if (!data || !data.items || data.items.length === 0) return;
let needsSave = false;
// Calculate leading blank lines offset for OLD document
let oldLeadingBlankLinesOffset = 0;
try {
for (let i = 1; i <= oldDoc.lines; i++) {
const line = oldDoc.line(i);
if (line.text.trim().length === 0) {
oldLeadingBlankLinesOffset++;
} else {
break;
}
}
} catch (e) {
// Ignore errors
}
// Calculate leading blank lines offset for NEW document
let newLeadingBlankLinesOffset = 0;
try {
for (let i = 1; i <= newDoc.lines; i++) {
const line = newDoc.line(i);
if (line.text.trim().length === 0) {
newLeadingBlankLinesOffset++;
} else {
break;
}
}
} catch (e) {
// Ignore errors
}
for (const item of data.items) {
try {
// Convert Obsidian line/ch to CodeMirror absolute positions in OLD document
const fromLineNum = item.from.line + 1 + oldLeadingBlankLinesOffset;
const toLineNum = item.to.line + 1 + oldLeadingBlankLinesOffset;
if (fromLineNum < 1 || fromLineNum > oldDoc.lines) continue;
if (toLineNum < 1 || toLineNum > oldDoc.lines) continue;
const fromLine = oldDoc.line(fromLineNum);
const toLine = oldDoc.line(toLineNum);
const fromAbs = fromLine.from + Math.min(item.from.ch, fromLine.length);
const toAbs = toLine.from + Math.min(item.to.ch, toLine.length);
// Map through changes to get positions in NEW document
const newFromAbs = changes.mapPos(fromAbs, 1);
const newToAbs = changes.mapPos(toAbs, 1);
// Convert back to line/ch in NEW document
const newFromLine = newDoc.lineAt(newFromAbs);
const newToLine = newDoc.lineAt(newToAbs);
const newFromCh = newFromAbs - newFromLine.from;
const newToCh = newToAbs - newToLine.from;
// Convert CodeMirror line numbers (1-indexed) back to Obsidian (0-indexed)
const newFromLineNum = newFromLine.number - 1 - newLeadingBlankLinesOffset;
const newToLineNum = newToLine.number - 1 - newLeadingBlankLinesOffset;
// Check if positions changed
const positionsChanged = item.from.line !== newFromLineNum || item.from.ch !== newFromCh ||
item.to.line !== newToLineNum || item.to.ch !== newToCh;
// Get the text at the new position
let newText = '';
if (newFromAbs < newToAbs) {
try {
newText = newDoc.sliceString(newFromAbs, newToAbs);
} catch (e) {
// If text can't be read, it was likely deleted
newText = '';
}
}
// Check if text changed or was deleted
const textChanged = item.text !== newText;
const textDeleted = newFromAbs >= newToAbs || newText.length === 0;
// Update if positions or text changed
if (positionsChanged || textChanged) {
const oldTimestamp = item.timestamp; // Preserve timestamp
item.from = { line: newFromLineNum, ch: newFromCh };
item.to = { line: newToLineNum, ch: newToCh };
item.line = newFromLineNum;
item.ch = newFromCh;
// Update text - if deleted, set to empty and make from === to (cursor position)
if (textDeleted) {
item.text = '';
item.to = { line: newFromLineNum, ch: newFromCh };
// Clear selection embedding if text is deleted
item.selectionEmbedding = null;
} else {
item.text = newText;
// Regenerate selection embedding if text changed and is meaningful
if (textChanged) {
if (this.hasMeaningfulText(newText)) {
await this.generateSelectionEmbeddingForItem(item);
} else {
// Set to null if no meaningful text (empty, whitespace, linefeeds, etc.)
item.selectionEmbedding = null;
}
}
}
// Ensure timestamp exists (use preserved or current if missing)
if (!item.timestamp || typeof item.timestamp !== 'number') {
item.timestamp = oldTimestamp || Date.now();
}
needsSave = true;
}
} catch (e) {
console.error('Error updating marginalia position:', e, item);
}
}
if (needsSave) {
await this.saveMarginaliaForFile(filePath);
}
}
public getCurrentFileMarginalia(): MarginaliaItem[] {
const activeFile = this.app.workspace.getActiveFile();
if (activeFile) {
return this.getMarginalia(activeFile.path);
}
return [];
}
public async jumpToMarginalia(filePath: string, id: string) {
const data = this.marginaliaData.get(filePath);
if (data) {
const item = data.items.find(i => i.id === id);
if (item) {
// Get or open the file
const file = this.app.vault.getAbstractFileByPath(filePath);
if (file instanceof TFile) {
// Try to find existing leaf with this file
let leaf = this.app.workspace.getLeavesOfType("markdown")
.find(l => (l.view as MarkdownView).file?.path === filePath);
// If not found, open in a new leaf
if (!leaf) {
leaf = this.app.workspace.getLeaf();
await leaf.openFile(file);
}
// Get the markdown view
const view = leaf.view;
if (view instanceof MarkdownView) {
const editor = view.editor;
// Set cursor position
const cursorPos = { line: item.line, ch: item.ch };
editor.setCursor(cursorPos);
// Try to select the range if it's valid
try {
const fromPos = { line: item.from.line, ch: item.from.ch };
const toPos = { line: item.to.line, ch: item.to.ch };
// Set selection
editor.setSelection(fromPos, toPos);
// Scroll into view - need EditorRange format
const range = { from: fromPos, to: toPos };
editor.scrollIntoView(range, true);
} catch (e) {
// Fallback: just set cursor and scroll
editor.setCursor(cursorPos);
const range = { from: cursorPos, to: cursorPos };
editor.scrollIntoView(range, true);
}
}
}
}
}
}
public showEditModal(item: MarginaliaItem, filePath: string) {
// Use the sidebar view's method if available, otherwise create modal directly
if (this.sidebarView) {
(this.sidebarView as any).showEditModal(item, filePath);
} else {
// Create modal directly
const modal = new EditMarginaliaModal(this.app, item, this.settings.highlightColor, async (newNote: string, color?: string) => {
await this.updateMarginalia(filePath, item.id, newNote, color);
this.refreshEditor(filePath);
}, async () => {
// Delete handler
const deleteModal = new DeleteConfirmationModal(this.app, async () => {
await this.deleteMarginalia(filePath, item.id);
});
deleteModal.open();
}, this);
modal.open();
}
}
public refreshEditor(filePath: string) {
// Trigger editor refresh by dispatching an update through the extension
// The ViewPlugin will detect the change and update decorations
const leaves = this.app.workspace.getLeavesOfType("markdown");
for (const leaf of leaves) {
const view = leaf.view as MarkdownView;
if (view.file && view.file.path === filePath) {
// Force editor to refresh immediately
const editor = view.editor;
if (editor) {
// Get marginalia items and trigger a refresh
const items = this.getMarginalia(filePath);
// Immediately trigger a refresh by dispatching a viewport change
// This forces the ViewPlugin to update
requestAnimationFrame(() => {
// Trigger a refresh by reading and setting cursor
const cursor = editor.getCursor();
// Force a re-render by temporarily moving cursor
editor.setCursor({ line: cursor.line, ch: cursor.ch + 1 });
editor.setCursor(cursor);
// Also trigger a scroll to force viewport update
setTimeout(() => {
editor.scrollIntoView({ from: cursor, to: cursor }, true);
}, 10);
});
}
}
}
}
private generateId(): string {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
/**
* Check if text has meaningful content (not just whitespace, linefeeds, spaces, etc.)
*/
public hasMeaningfulText(text: string | null | undefined): boolean {
if (!text) return false;
// Remove all whitespace (spaces, tabs, linefeeds, etc.) and check if anything remains
return text.trim().length > 0;
}
/**
* Check if two ranges overlap
* Returns true if the ranges share any common area
*/
private rangesOverlap(
from1: { line: number; ch: number },
to1: { line: number; ch: number },
from2: { line: number; ch: number },
to2: { line: number; ch: number }
): boolean {
// If ranges are on completely different lines, they don't overlap
if (to1.line < from2.line || to2.line < from1.line) {
return false;
}
// If they're on the same line, check character positions
if (from1.line === from2.line && to1.line === to2.line) {
// Overlap if: from1 < to2 AND from2 < to1
// Use <= for one end to allow touching ranges to be considered overlapping
return from1.ch < to2.ch && from2.ch < to1.ch;
}
// For multi-line ranges, they overlap if:
// The start of one is before or at the end of the other, AND
// The start of the other is before or at the end of the first
const range1BeforeRange2 = from1.line < to2.line || (from1.line === to2.line && from1.ch <= to2.ch);
const range2BeforeRange1 = from2.line < to1.line || (from2.line === to1.line && from2.ch <= to1.ch);
return range1BeforeRange2 && range2BeforeRange1;
}
/**
* Check if a new marginalia would overlap with any existing ones
* Only checks for actual text selections (not cursor-only positions)
*/
private wouldOverlap(filePath: string, newItem: MarginaliaItem): boolean {
// Don't check overlaps for cursor-only positions (no selection)
// Only check if there's actual selected text
const hasSelection = newItem.from.line !== newItem.to.line ||
newItem.from.ch !== newItem.to.ch ||
(newItem.text && newItem.text.trim().length > 0);
if (!hasSelection) {
return false; // Cursor-only positions don't overlap
}
const data = this.marginaliaData.get(filePath);
if (!data || !data.items || data.items.length === 0) {
return false;
}
for (const existingItem of data.items) {
// Only check against existing items that have actual selections
const existingHasSelection = existingItem.from.line !== existingItem.to.line ||
existingItem.from.ch !== existingItem.to.ch ||
(existingItem.text && existingItem.text.trim().length > 0);
if (existingHasSelection && this.rangesOverlap(
newItem.from,
newItem.to,
existingItem.from,
existingItem.to
)) {
return true;
}
}
return false;
}
private getMarginaliaFilePath(): string {
return `${this.app.vault.configDir}/plugins/marginalia/marginalia.json`;
}
public getEmbeddingFilePath(): string {
return `${this.app.vault.configDir}/plugins/marginalia/notes_embedding.json`;
}
public async initializeEmbeddingFile(): Promise<void> {
const embeddingPath = this.getEmbeddingFilePath();
const exists = await this.app.vault.adapter.exists(embeddingPath);
if (!exists) {
// Create the file with empty array structure
// The file will contain an array of NoteEmbedding objects
// Each NoteEmbedding can have multiple chunks (though most notes will have just one)
const initialData: NoteEmbedding[] = [];
try {
await this.app.vault.adapter.write(embeddingPath, JSON.stringify(initialData, null, 2));
} catch (error) {
console.error('Error creating notes_embedding.json:', error);
throw error;
}
}
}
/**
* Queue a file for embedding processing (with debouncing)
*/
private queueFileForEmbedding(filePath: string): void {
if (!this.settings.embeddingOn) {
return;
}
// Clear existing debounce timer for this file
const existingTimer = this.embeddingDebounceTimers.get(filePath);
if (existingTimer) {
clearTimeout(existingTimer);
}
// Add to queue
this.embeddingQueue.add(filePath);
// Set debounce timer (wait 2 seconds after last change before processing)
const timer = setTimeout(() => {
this.embeddingDebounceTimers.delete(filePath);
this.processEmbeddingQueue();
}, 2000);
this.embeddingDebounceTimers.set(filePath, timer);
}
/**
* Process the embedding queue one file at a time
*/
private async processEmbeddingQueue(): Promise<void> {
if (this.isProcessingEmbeddingQueue || this.embeddingQueue.size === 0 || !this.settings.embeddingOn) {
return;
}
this.isProcessingEmbeddingQueue = true;
while (this.embeddingQueue.size > 0 && this.settings.embeddingOn) {
// Get the first file from the queue
const filePath = this.embeddingQueue.values().next().value;
this.embeddingQueue.delete(filePath);
// Get the file object
const file = this.app.vault.getAbstractFileByPath(filePath);
if (file instanceof TFile) {
try {
await this.processFileForEmbedding(file);
} catch (error) {
console.error(`Error processing file ${filePath} from queue:`, error);
}
}
// Small delay between files to avoid overwhelming the server
if (this.embeddingQueue.size > 0 && this.settings.embeddingOn) {
await new Promise(resolve => setTimeout(resolve, 500));
}
}
this.isProcessingEmbeddingQueue = false;
}
/**
* Clear the embedding queue and stop processing
*/
public clearEmbeddingQueue(): void {
this.embeddingQueue.clear();
// Clear all debounce timers
for (const timer of this.embeddingDebounceTimers.values()) {
clearTimeout(timer);
}
this.embeddingDebounceTimers.clear();
// Clear retry counts
this.embeddingRetryCount.clear();
// Note: We don't reset embeddingListenersRegistered here because
// the listeners are still registered, just paused
}
/**
* Start monitoring folders for embedding generation
*/
public startEmbeddingMonitor(): void {
if (!this.settings.embeddingOn) {
return;
}
// Prevent duplicate listener registration
if (this.embeddingListenersRegistered) {
// Listeners already registered, just process files if needed
this.processFoldersForEmbedding();
return;
}
// Process files after a short delay to ensure vault is fully loaded
// The listener will catch any files that are created/modified after this
setTimeout(() => {
this.processFoldersForEmbedding();
}, 2000);
// Register file system events to watch for changes (only once)
this.registerEvent(
this.app.vault.on('modify', (file: TFile) => {
if (this.settings.embeddingOn && file.extension === 'md' && this.isFileInSimilarityFolders(file.path)) {
this.queueFileForEmbedding(file.path);
}
})
);
this.registerEvent(
this.app.vault.on('create', (file: TFile) => {
if (this.settings.embeddingOn && file.extension === 'md' && this.isFileInSimilarityFolders(file.path)) {
this.queueFileForEmbedding(file.path);
}
})
);
// Periodically check for files that need embedding (catches files added from outside Obsidian)
// Check every 5 minutes
const checkInterval = setInterval(async () => {
if (!this.settings.embeddingOn || !this.settings.ollamaAvailable) {
return;
}
try {
await this.checkAndQueueFilesNeedingEmbedding();
} catch (error) {
console.error('Error in periodic embedding check:', error);
}
}, 5 * 60 * 1000); // 5 minutes
// Store interval ID so we can clear it if needed
(this as any).embeddingCheckInterval = checkInterval;
this.embeddingListenersRegistered = true;
console.log('Embedding file system listeners registered (including periodic check)');
}
/**
* Check for files that need embedding and queue them for processing
* This catches files added from outside Obsidian or files that were missed
*/
private async checkAndQueueFilesNeedingEmbedding(): Promise<void> {
if (!this.settings.embeddingOn || !this.settings.ollamaAvailable) {
return;
}
try {
// Load existing embeddings to check what's already done
const embeddings = await this.loadEmbeddings();
const allFiles = this.app.vault.getMarkdownFiles();
// Find files in similarity folders that need processing
const filesToQueue: string[] = [];
for (const file of allFiles) {
if (!this.isFileInSimilarityFolders(file.path)) {
continue;
}
const filePath = this.normalizePath(file.path);
const existingEmbedding = embeddings.find(e => this.normalizePath(e.source_path) === filePath);
// File needs processing if no embedding exists
if (!existingEmbedding) {
filesToQueue.push(file.path);
continue;
}
// Check if file was modified after embedding
try {
const fileStat = await this.app.vault.adapter.stat(file.path);
if (fileStat && new Date(fileStat.mtime) > new Date(existingEmbedding.noteEdited)) {
filesToQueue.push(file.path);
}
} catch (error) {
// If we can't check the stat, skip it (don't queue to avoid duplicates)
continue;
}
}
if (filesToQueue.length > 0) {
console.log(`Periodic check: Found ${filesToQueue.length} file(s) that need embedding`);
for (const filePath of filesToQueue) {
this.queueFileForEmbedding(filePath);
}
// Process the queue (it will handle debouncing internally)
this.processEmbeddingQueue();
}
} catch (error) {
console.error('Error in periodic embedding check:', error);
}
}
/**
* Process all folders specified in settings for embedding
*/
private async processFoldersForEmbedding(): Promise<void> {
if (!this.settings.embeddingOn || !this.settings.similarityFolders) {
return;
}