-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
1242 lines (1241 loc) · 55.2 KB
/
main.js
File metadata and controls
1242 lines (1241 loc) · 55.2 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
// src/editor/extensions.ts
var import_state = require("@codemirror/state");
var import_view = require("@codemirror/view");
function insertNewlineWithColumnPrefix(view, ctx) {
const range = view.state.selection.main;
const insertText = `
${ctx.prefixWithSpace}`;
const anchor = range.from + insertText.length;
view.dispatch({
changes: { from: range.from, to: range.to, insert: insertText },
selection: import_state.EditorSelection.cursor(anchor),
annotations: import_state.Transaction.userEvent.of("input.enter")
});
return true;
}
function findEnclosingMultiColumnContainer(view, fromLine, expectedDepth) {
const minLine = Math.max(1, fromLine - 400);
for (let lineNumber = fromLine; lineNumber >= minLine; lineNumber--) {
const text = view.state.doc.line(lineNumber).text;
const m = /^(\s*)(>+)\s*\[!multi-column([^\]]*)\]/.exec(text);
if (!m) continue;
if (m[2].length !== expectedDepth) continue;
return true;
}
return false;
}
function getColumnContext(view) {
const pos = view.state.selection.main.head;
const doc = view.state.doc;
const currentLine = doc.lineAt(pos);
const minLine = Math.max(1, currentLine.number - 200);
for (let lineNumber = currentLine.number; lineNumber >= minLine; lineNumber--) {
const text = doc.line(lineNumber).text;
const m = /^(\s*)(>+)\s*\[!col([^\]]*)\]/.exec(text);
if (!m) continue;
const colDepth = m[2].length;
if (colDepth !== 2 && colDepth !== 4) continue;
const containerDepth = colDepth - 1;
const hasContainer = findEnclosingMultiColumnContainer(view, lineNumber - 1, containerDepth);
if (!hasContainer) continue;
const prefixBare = `${m[1]}${m[2]}`;
return {
prefixBare,
prefixWithSpace: `${prefixBare} `,
colDepth,
colHeaderLineNumber: lineNumber
};
}
return null;
}
function hasUnquotedBoundarySinceColHeader(doc, colHeaderLineNumber, currentLineNumber) {
const start = Math.max(1, colHeaderLineNumber + 1);
for (let lineNumber = start; lineNumber <= currentLineNumber; lineNumber++) {
const text = doc.line(lineNumber).text;
if (!/^\s*>/.test(text)) return true;
}
return false;
}
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function isPrefixOnlyLine(lineText, ctx) {
const re = new RegExp(`^${escapeRegExp(ctx.prefixBare)}\\s*$`);
return re.test(lineText);
}
function clearCurrentLineAndKeepCursor(view) {
const range = view.state.selection.main;
if (!range.empty) return false;
const line = view.state.doc.lineAt(range.from);
view.dispatch({
changes: { from: line.from, to: line.to, insert: "" },
selection: import_state.EditorSelection.cursor(line.from),
annotations: import_state.Transaction.userEvent.of("input.enter")
});
return true;
}
function normalizeNewlines(text) {
return text.replace(/\r\n?/g, "\n");
}
function buildPrefixedPasteText(ctx, clipboardText, opts) {
const normalized = normalizeNewlines(clipboardText);
if (!normalized.includes("\n")) return null;
const parts = normalized.split("\n");
if (parts.length <= 1) return null;
const [first, ...rest] = parts;
const firstWithPrefix = (() => {
if (!opts.prefixFirstLine) return first;
if (first.length === 0) return ctx.prefixBare;
return `${ctx.prefixWithSpace}${first}`;
})();
const suffix = rest.map((line) => {
if (line.length === 0) return `
${ctx.prefixBare}`;
return `
${ctx.prefixWithSpace}${line}`;
}).join("");
return `${firstWithPrefix}${suffix}`;
}
function buildMultiColumnEditorExtensions(plugin) {
return [
import_state.Prec.high(
import_view.keymap.of([
{
key: "Enter",
run(view) {
var _a;
const ctx = getColumnContext(view);
if (!ctx) return false;
const markdownExitOnEmptyEnter = Boolean((_a = plugin.settings) == null ? void 0 : _a.markdownExitOnEmptyEnter);
if (!markdownExitOnEmptyEnter) {
return insertNewlineWithColumnPrefix(view, ctx);
}
const range = view.state.selection.main;
const line = view.state.doc.lineAt(range.from);
if (hasUnquotedBoundarySinceColHeader(
view.state.doc,
ctx.colHeaderLineNumber,
line.number
)) {
return false;
}
if (range.empty && isPrefixOnlyLine(line.text, ctx)) {
return clearCurrentLineAndKeepCursor(view);
}
return insertNewlineWithColumnPrefix(view, ctx);
}
}
])
),
import_view.EditorView.domEventHandlers({
paste(event, view) {
var _a, _b;
const ctx = getColumnContext(view);
if (!ctx) return;
const markdownExitOnEmptyEnter = Boolean((_a = plugin.settings) == null ? void 0 : _a.markdownExitOnEmptyEnter);
const range = view.state.selection.main;
const line = view.state.doc.lineAt(range.from);
if (markdownExitOnEmptyEnter && hasUnquotedBoundarySinceColHeader(view.state.doc, ctx.colHeaderLineNumber, line.number)) {
return;
}
const clipboardText = (_b = event.clipboardData) == null ? void 0 : _b.getData("text/plain");
if (!clipboardText) return;
const prefixEndInLine = line.text.startsWith(ctx.prefixWithSpace) ? ctx.prefixWithSpace.length : ctx.prefixBare.length;
const prefixEndPos = line.from + prefixEndInLine;
const prefixFirstLine = range.from < prefixEndPos;
const insertText = buildPrefixedPasteText(ctx, clipboardText, { prefixFirstLine });
if (!insertText) return;
event.preventDefault();
const anchor = range.from + insertText.length;
view.dispatch({
changes: { from: range.from, to: range.to, insert: insertText },
selection: import_state.EditorSelection.cursor(anchor),
annotations: import_state.Transaction.userEvent.of("input.paste")
});
}
})
];
}
// src/main.ts
var import_obsidian = require("obsidian");
var DEFAULT_SETTINGS = {
language: "en",
markdownExitOnEmptyEnter: true,
dividerWidth: "1px",
dividerStyle: "solid",
dividerColor: "gray",
horzDivider: false,
horzDividerWidth: "1px",
horzDividerStyle: "solid",
horzDividerColor: "gray",
backgroundColor: "none",
borderEnabled: false,
borderWidth: "1px",
borderRadius: "0",
separateColumnAppearance: false
};
var PRESET_COLORS = {
"none": "transparent",
"gray": "#cfd3d7",
"red": "#f4a5a5",
"orange": "#f7c48f",
"yellow": "#f5f1a6",
"green": "#8fddb0",
"cyan": "#95eded",
"blue": "#9cbcf2",
"purple": "#c8acef",
"black": "#4a4a4a",
"white": "#ffffff"
};
var TEXTS = {
en: {
"settings.title": "Multi-Column Layout Settings",
"settings.general": "General",
"settings.language": "Language",
"settings.language.desc": "Choose the display language for the plugin.",
"settings.markdownExitOnEmptyEnter": "Markdown-style exit on empty Enter",
"settings.markdownExitOnEmptyEnter.desc": "When enabled, pressing Enter on an empty prefixed column line exits the column instead of continuing >>/>>>>.",
"settings.background": "Background Color",
"settings.background.desc": "Background color for the multi-column container.",
"settings.border": "Container Border",
"settings.border.enable": "Show Border",
"settings.border.enable.desc": "Draw a border around the multi-column container. Border color follows background (slightly darker).",
"settings.border.width": "Border Width",
"settings.border.radius": "Corner Radius",
"settings.border.separate": "Separate Columns Visually",
"settings.border.separate.desc": "When enabled, bordered layouts render each direct column as its own card instead of one continuous panel.",
"colors.none": "Transparent",
"colors.gray": "Gray",
"colors.red": "Red",
"colors.orange": "Orange",
"colors.yellow": "Yellow",
"colors.green": "Green",
"colors.cyan": "Cyan",
"colors.blue": "Blue",
"colors.purple": "Purple",
"colors.black": "Black",
"colors.white": "White",
"settings.vertical": "Vertical Dividers (Bordered)",
"settings.horizontal": "Horizontal Dividers",
"settings.width": "Width",
"settings.width.desc": "Width of the line (e.g., 1px, 2px).",
"settings.style": "Style",
"settings.style.desc": "Style of the line.",
"style.solid": "Solid",
"style.dashed": "Dashed",
"style.dotted": "Dotted",
"style.double": "Double",
"settings.color": "Color",
"settings.color.desc": "Color of the line.",
"settings.horz.enable": "Enable Horizontal Dividers",
"settings.horz.enable.desc": "Automatically add top and bottom borders to NEW inserted layouts.",
"settings.migrate": "Apply current appearance to all existing layouts",
"settings.migrate.desc": "Migrates every multi-column callout in your vault to use the current bordered/horizontal flags. This updates old notes for a consistent look.",
"settings.migrate.running": "Applying appearance to existing layouts...",
"settings.migrate.done": "Updated {0} file(s).",
"settings.migrate.error": "Failed to apply appearance. See console for details.",
"menu.2col": "2 Columns",
"menu.3col": "3 Columns",
"menu.nested": "Nested Columns",
"menu.nested.2col": "Parent + Nested 2 Columns",
"menu.nested.3col": "Parent + Nested 3 Columns",
"menu.nested.here.2col": "Insert Nested 2 Columns Here",
"menu.nested.here.3col": "Insert Nested 3 Columns Here",
"menu.custom": "Custom Layout...",
"notice.nested.notInCol": "Place the cursor inside a column to insert nested columns.",
"notice.nested.limit": "Nested columns are limited to 1 level.",
"modal.title": "Custom Column Ratios",
"modal.instruction": "Enter ratios separated by slashes (e.g. 30/70 or 20/30/50). Sum must be 100.",
"modal.insert": "Insert Layout",
"modal.error.format": "Invalid format. Use numbers separated by /.",
"modal.error.sum": "Sum is {0}%, but must be 100%."
},
zh: {
"settings.title": "\u591A\u5217\u5E03\u5C40\u8BBE\u7F6E",
"settings.general": "\u5E38\u89C4",
"settings.language": "\u8BED\u8A00",
"settings.language.desc": "\u9009\u62E9\u63D2\u4EF6\u663E\u793A\u7684\u8BED\u8A00\u3002",
"settings.markdownExitOnEmptyEnter": "\u7A7A\u884C\u56DE\u8F66\u6309 Markdown \u65B9\u5F0F\u9000\u51FA",
"settings.markdownExitOnEmptyEnter.desc": "\u542F\u7528\u540E\uFF0C\u5728\u5217\u5185\u7A7A\u524D\u7F00\u884C\u518D\u6B21\u56DE\u8F66\u4F1A\u9000\u51FA\u5206\u680F\uFF0C\u4E0D\u518D\u7EE7\u7EED\u8865 >>/>>>>\u3002",
"settings.background": "\u80CC\u666F\u989C\u8272",
"settings.background.desc": "\u591A\u5217\u5E03\u5C40\u5BB9\u5668\u7684\u80CC\u666F\u989C\u8272\u3002",
"settings.border": "\u8FB9\u6846",
"settings.border.enable": "\u663E\u793A\u8FB9\u6846",
"settings.border.enable.desc": "\u4E3A\u591A\u5217\u5BB9\u5668\u7ED8\u5236\u8FB9\u6846\uFF0C\u989C\u8272\u4E0E\u80CC\u666F\u4E00\u81F4\u4F46\u7565\u6DF1\u3002",
"settings.border.width": "\u8FB9\u6846\u5BBD\u5EA6",
"settings.border.radius": "\u5706\u89D2\u534A\u5F84",
"settings.border.separate": "\u8BA9\u5404\u5206\u680F\u89C6\u89C9\u4E0A\u72EC\u7ACB",
"settings.border.separate.desc": "\u542F\u7528\u540E\uFF0C\u5E26\u8FB9\u6846\u7684\u5E03\u5C40\u4F1A\u628A\u6BCF\u4E2A\u76F4\u63A5\u5206\u680F\u6E32\u67D3\u4E3A\u72EC\u7ACB\u5361\u7247\uFF0C\u800C\u4E0D\u662F\u8FDE\u7EED\u7684\u4E00\u6574\u5757\u3002",
"colors.none": "\u900F\u660E",
"colors.gray": "\u7070\u8272",
"colors.red": "\u7EA2\u8272",
"colors.orange": "\u6A59\u8272",
"colors.yellow": "\u9EC4\u8272",
"colors.green": "\u7EFF\u8272",
"colors.cyan": "\u9752\u8272",
"colors.blue": "\u84DD\u8272",
"colors.purple": "\u7D2B\u8272",
"colors.black": "\u6DF1\u7070",
"colors.white": "\u767D\u8272",
"settings.vertical": "\u5782\u76F4\u5206\u5272\u7EBF",
"settings.horizontal": "\u6C34\u5E73\u5206\u5272\u7EBF",
"settings.width": "\u5BBD\u5EA6",
"settings.width.desc": "\u7EBF\u6761\u5BBD\u5EA6\uFF08\u4F8B\u5982 1px, 2px\uFF09\u3002",
"settings.style": "\u6837\u5F0F",
"settings.style.desc": "\u7EBF\u6761\u6837\u5F0F\u3002",
"style.solid": "\u5B9E\u7EBF",
"style.dashed": "\u865A\u7EBF",
"style.dotted": "\u70B9\u7EBF",
"style.double": "\u53CC\u7EBF",
"settings.color": "\u989C\u8272",
"settings.color.desc": "\u7EBF\u6761\u989C\u8272\u3002",
"settings.horz.enable": "\u542F\u7528\u6C34\u5E73\u5206\u5272\u7EBF",
"settings.horz.enable.desc": "\u5728\u65B0\u63D2\u5165\u7684\u5E03\u5C40\u4E0A\u81EA\u52A8\u6DFB\u52A0\u4E0A\u4E0B\u8FB9\u6846\u3002",
"settings.migrate": "\u5C06\u5F53\u524D\u5916\u89C2\u5E94\u7528\u4E8E\u6240\u6709\u5DF2\u5199\u5E03\u5C40",
"settings.migrate.desc": "\u628A\u5F53\u524D\u7684\u5206\u5272\u7EBF\u98CE\u683C\u540C\u6B65\u5230\u5E93\u91CC\u5DF2\u6709\u7684 multi-column callout\uFF0C\u786E\u4FDD\u7EDF\u4E00\u663E\u793A\u3002",
"settings.migrate.running": "\u6B63\u5728\u5E94\u7528\u5230\u5DF2\u6709\u5E03\u5C40\u2026",
"settings.migrate.done": "\u5DF2\u66F4\u65B0 {0} \u4E2A\u6587\u4EF6\u3002",
"settings.migrate.error": "\u5E94\u7528\u5916\u89C2\u5931\u8D25\uFF0C\u8BF7\u67E5\u770B\u63A7\u5236\u53F0\u65E5\u5FD7\u3002",
"menu.2col": "2 \u5217",
"menu.3col": "3 \u5217",
"menu.nested": "\u5B50\u5206\u680F\uFF08\u5206\u680F\u4E2D\u5D4C\u5957\u5206\u680F\uFF09",
"menu.nested.2col": "\u7236\u5217 + \u5B50\u5206\u680F 2 \u5217",
"menu.nested.3col": "\u7236\u5217 + \u5B50\u5206\u680F 3 \u5217",
"menu.nested.here.2col": "\u5728\u6B64\u5904\u63D2\u5165\u5B50\u5206\u680F 2 \u5217",
"menu.nested.here.3col": "\u5728\u6B64\u5904\u63D2\u5165\u5B50\u5206\u680F 3 \u5217",
"menu.custom": "\u81EA\u5B9A\u4E49\u5206\u680F...",
"notice.nested.notInCol": "\u8BF7\u628A\u5149\u6807\u653E\u5728\u67D0\u4E00\u5217\u7684\u5185\u5BB9\u4E2D\uFF0C\u518D\u63D2\u5165\u5B50\u5206\u680F\u3002",
"notice.nested.limit": "\u5B50\u5206\u680F\u4EC5\u652F\u6301 1 \u5C42\u5D4C\u5957\u3002",
"modal.title": "\u81EA\u5B9A\u4E49\u5217\u6BD4\u4F8B",
"modal.instruction": "\u7528\u659C\u6760\u5206\u9694\u6BD4\u4F8B\uFF08\u4F8B\u5982 30/70 \u6216 20/30/50\uFF09\uFF0C\u603B\u548C\u5FC5\u987B\u662F 100\u3002",
"modal.insert": "\u63D2\u5165\u5E03\u5C40",
"modal.error.format": "\u683C\u5F0F\u65E0\u6548\uFF0C\u8BF7\u7528\u6570\u5B57\u52A0\u659C\u6760\u3002",
"modal.error.sum": "\u5F53\u524D\u603B\u548C\u4E3A {0}% \uFF0C\u5FC5\u987B\u662F 100%\u3002"
}
};
var RESIZER_HANDLE_WIDTH_PX = 12;
var MultiColumnLayoutPlugin = class extends import_obsidian.Plugin {
constructor() {
super(...arguments);
this.settings = DEFAULT_SETTINGS;
}
async onload() {
await this.loadSettings();
this.addSettingTab(new MultiColumnLayoutSettingTab(this.app, this));
this.applySettingsStyles();
this.registerEvent(
this.app.workspace.on("editor-menu", (menu, editor) => {
this.addInsertMenu(menu, editor);
})
);
this.registerMarkdownPostProcessor((el, ctx) => {
this.applyColumnWidths(el);
this.attachColumnResizers(el, ctx);
});
this.registerEvent(
this.app.workspace.on("resize", () => {
this.repositionAllColumnResizers();
})
);
this.registerEditorExtension(buildMultiColumnEditorExtensions(this));
}
onunload() {
document.body.classList.remove("mcl-separated-columns-enabled");
}
getCM6EditorView(markdownView) {
var _a, _b, _c, _d;
const editor = markdownView == null ? void 0 : markdownView.editor;
if (!editor) return null;
const editorUnknown = editor;
const maybeCM = editorUnknown.cm;
if (maybeCM && typeof maybeCM === "object") {
const cmUnknown = maybeCM;
const nested = (_b = (_a = cmUnknown.cm) != null ? _a : cmUnknown.editorView) != null ? _b : null;
return nested && typeof nested === "object" ? nested : null;
}
const direct = (_d = (_c = editorUnknown.cm) != null ? _c : editorUnknown.editorView) != null ? _d : null;
return direct && typeof direct === "object" ? direct : null;
}
t(key, ...args) {
const lang = this.settings.language || "en";
const langKey = lang in TEXTS ? lang : "en";
let str = TEXTS[langKey][key] || TEXTS["en"][key] || key;
args.forEach((arg, i) => {
str = str.replace(`{${i}}`, arg);
});
return str;
}
colorLabel(key) {
return this.t(`colors.${key}`) || key;
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
this.applySettingsStyles();
}
applySettingsStyles() {
const { body } = document;
const style = body.style;
const vColor = PRESET_COLORS[this.settings.dividerColor] || this.settings.dividerColor;
const hColor = PRESET_COLORS[this.settings.horzDividerColor] || this.settings.horzDividerColor;
const baseColor = PRESET_COLORS[this.settings.backgroundColor] || this.settings.backgroundColor;
const hexMatch = typeof baseColor === "string" && baseColor.startsWith("#") && baseColor.length === 7;
const toRGBA = (hex, alpha) => {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};
let bgColor = baseColor;
let borderColor = baseColor;
if (hexMatch) {
bgColor = toRGBA(baseColor, 0.13);
borderColor = toRGBA(baseColor, 0.26);
} else {
bgColor = baseColor || "transparent";
borderColor = baseColor || "transparent";
}
const borderWidth = this.settings.borderEnabled ? this.settings.borderWidth : "0";
const borderRadius = this.settings.borderRadius || "0";
style.setProperty("--mcl-divider-width", this.settings.dividerWidth);
style.setProperty("--mcl-divider-style", this.settings.dividerStyle);
style.setProperty("--mcl-divider-color", vColor);
style.setProperty("--mcl-horz-divider-width", this.settings.horzDividerWidth);
style.setProperty("--mcl-horz-divider-style", this.settings.horzDividerStyle);
style.setProperty("--mcl-horz-divider-color", hColor);
style.setProperty("--mcl-background-color", bgColor);
style.setProperty("--mcl-border-color", borderColor || "transparent");
style.setProperty("--mcl-border-width", borderWidth);
style.setProperty("--mcl-border-radius", borderRadius);
body.classList.toggle("mcl-separated-columns-enabled", this.settings.separateColumnAppearance);
}
addInsertMenu(menu, editor) {
menu.addItem((item) => {
item.setTitle(this.t("menu.2col"));
item.setIcon("columns");
item.onClick(() => this.safeInsert(editor, 2, [50, 50], "bordered"));
});
menu.addItem((item) => {
item.setTitle(this.t("menu.3col"));
item.setIcon("columns");
item.onClick(() => this.safeInsert(editor, 3, [33, 34, 33], "bordered"));
});
menu.addItem((item) => {
item.setTitle(this.t("menu.nested"));
item.setIcon("layout");
const subMenu = item.setSubmenu();
subMenu.addItem((subItem) => {
subItem.setTitle(this.t("menu.nested.2col"));
subItem.setIcon("columns");
subItem.onClick(() => this.safeInsertNested(editor, 2));
});
subMenu.addItem((subItem) => {
subItem.setTitle(this.t("menu.nested.3col"));
subItem.setIcon("columns");
subItem.onClick(() => this.safeInsertNested(editor, 3));
});
subMenu.addSeparator();
subMenu.addItem((subItem) => {
subItem.setTitle(this.t("menu.nested.here.2col"));
subItem.setIcon("columns");
subItem.onClick(() => this.safeInsertNestedHere(editor, 2));
});
subMenu.addItem((subItem) => {
subItem.setTitle(this.t("menu.nested.here.3col"));
subItem.setIcon("columns");
subItem.onClick(() => this.safeInsertNestedHere(editor, 3));
});
});
menu.addSeparator();
menu.addItem((item) => {
item.setTitle(this.t("menu.custom"));
item.setIcon("settings-sliders");
item.onClick(() => {
const activeEditor = this.getActiveEditor() || editor;
if (activeEditor) {
new CustomRatioModal(this.app, this, (cols, ratios) => {
this.insertColumnLayout(activeEditor, cols, ratios, "bordered");
}).open();
}
});
});
}
safeInsert(passedEditor, cols, ratios, meta) {
const activeEditor = this.getActiveEditor() || passedEditor;
if (!activeEditor) {
console.error("Multi-Column Plugin: No active editor found.");
return;
}
this.insertColumnLayout(activeEditor, cols, ratios, meta);
}
safeInsertNested(passedEditor, innerCols) {
const activeEditor = this.getActiveEditor() || passedEditor;
if (!activeEditor) {
console.error("Multi-Column Plugin: No active editor found.");
return;
}
this.insertNestedLayout(activeEditor, innerCols);
}
safeInsertNestedHere(passedEditor, innerCols) {
const activeEditor = this.getActiveEditor() || passedEditor;
if (!activeEditor) {
console.error("Multi-Column Plugin: No active editor found.");
return;
}
this.insertNestedHere(activeEditor, innerCols);
}
getActiveEditor() {
const view = this.app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
return view ? view.editor : null;
}
insertColumnLayout(editor, columnCount, ratios, metadata = "") {
if (!editor) return;
editor.focus();
const metaParts = [];
if (metadata) metaParts.push(metadata);
if (this.settings.horzDivider) metaParts.push("horizontal");
const metaStr = metaParts.length > 0 ? `|${metaParts.join("|")}` : "";
const lines = [];
lines.push(`> [!multi-column${metaStr}]`);
lines.push(">");
for (let i = 0; i < columnCount; i++) {
const ratio = Array.isArray(ratios) ? ratios[i] : void 0;
const colMeta = typeof ratio === "number" && !isNaN(ratio) ? `|${ratio}` : "";
lines.push(`>> [!col${colMeta}]`);
lines.push(">>");
if (i < columnCount - 1) {
lines.push(">");
}
}
const block = lines.join("\n") + "\n";
try {
const cursor = editor.getCursor();
editor.replaceSelection(block);
const target = { line: cursor.line + 3, ch: 3 };
editor.setCursor(target);
editor.focus();
} catch (err) {
console.error("Multi-Column Plugin: Failed to insert text", err);
}
}
insertNestedLayout(editor, innerCols) {
if (!editor) return;
editor.focus();
const outerMetaParts = ["bordered"];
if (this.settings.horzDivider) outerMetaParts.push("horizontal");
const outerMetaStr = outerMetaParts.length ? `|${outerMetaParts.join("|")}` : "";
const innerMetaParts = ["bordered"];
if (this.settings.horzDivider) innerMetaParts.push("horizontal");
const innerMetaStr = innerMetaParts.length ? `|${innerMetaParts.join("|")}` : "";
const outerRatios = [40, 60];
const innerRatios = this.buildDefaultRatios(innerCols);
const lines = [];
lines.push(`> [!multi-column${outerMetaStr}]`);
lines.push(">");
lines.push(`>> [!col|${outerRatios[0]}]`);
lines.push(">> ## Parent Column");
lines.push(">> - Add your content here.");
lines.push(">");
lines.push(`>> [!col|${outerRatios[1]}]`);
lines.push(">> ## Nested Columns");
lines.push(">>");
lines.push(`>>> [!multi-column${innerMetaStr}]`);
lines.push(">>>");
for (let i = 0; i < innerCols; i++) {
const ratio = innerRatios[i];
const colMeta = typeof ratio === "number" ? `|${ratio}` : "";
lines.push(`>>>> [!col${colMeta}]`);
lines.push(">>>> ");
if (i < innerCols - 1) {
lines.push(">>>");
}
}
const block = lines.join("\n") + "\n";
try {
const cursor = editor.getCursor();
editor.replaceSelection(block);
const target = { line: cursor.line + 7, ch: 4 };
editor.setCursor(target);
editor.focus();
} catch (err) {
console.error("Multi-Column Plugin: Failed to insert nested layout", err);
}
}
buildDefaultRatios(count) {
if (!count || count < 1) return [];
const base = Math.floor(100 / count);
const ratios = new Array(count).fill(base);
const remainder = 100 - base * count;
if (remainder !== 0) {
ratios[ratios.length - 1] += remainder;
}
return ratios;
}
applyColumnWidths(el) {
const columns = el.querySelectorAll('div.callout[data-callout="col"][data-callout-metadata]');
columns.forEach((col) => {
const raw = col.getAttribute("data-callout-metadata");
const width = parseInt(raw, 10);
if (Number.isFinite(width) && width > 0 && width <= 100) {
col.style.flex = `0 0 ${width}%`;
}
});
}
repositionAllColumnResizers() {
requestAnimationFrame(() => {
const containers = document.querySelectorAll('div.callout[data-callout="multi-column"]');
containers.forEach((container) => {
var _a;
const content = container.querySelector(":scope > .callout-content") || container.querySelector(".callout-content");
if (!content) return;
const handles = content.querySelectorAll(":scope > .mcl-resizer");
if (handles.length === 0) return;
const isColEl = (child) => child instanceof HTMLElement && child.matches('div.callout[data-callout="col"]');
const cols = Array.from(content.children).filter(isColEl);
if (cols.length < 2) return;
const topInset = ((_a = getComputedStyle(container).getPropertyValue("--mcl-divider-inset")) == null ? void 0 : _a.trim()) || "1rem";
for (let i = 0; i < cols.length - 1; i++) {
const handle = content.querySelector(`:scope > .mcl-resizer[data-index="${i}"]`);
if (!handle) continue;
const x = cols[i].offsetLeft + cols[i].offsetWidth;
handle.style.left = `${x - RESIZER_HANDLE_WIDTH_PX / 2}px`;
handle.style.top = topInset;
handle.style.bottom = topInset;
handle.style.width = `${RESIZER_HANDLE_WIDTH_PX}px`;
}
});
});
}
attachColumnResizers(rootEl, ctx) {
const containers = rootEl.querySelectorAll('div.callout[data-callout="multi-column"]');
containers.forEach((container) => {
var _a, _b, _c, _d, _e, _f, _g;
const content = container.querySelector(":scope > .callout-content") || container.querySelector(".callout-content");
if (!content) return;
if (content.classList.contains("mcl-resizing")) return;
content.querySelectorAll(":scope > .mcl-resizer").forEach((el) => el.remove());
const isColEl = (child) => child instanceof HTMLElement && child.matches('div.callout[data-callout="col"]');
const cols = Array.from(content.children).filter(isColEl);
if (cols.length < 2) return;
try {
let expectedDepth = 1;
let parent = container.parentElement;
while (parent) {
if (parent instanceof HTMLElement && parent.matches('div.callout[data-callout="col"]')) {
expectedDepth += 2;
}
parent = parent.parentElement;
}
container.dataset.mclExpectedDepth = String(expectedDepth);
} catch (e) {
delete container.dataset.mclExpectedDepth;
}
const section = (_d = (_c = (_a = ctx == null ? void 0 : ctx.getSectionInfo) == null ? void 0 : _a.call(ctx, container)) != null ? _c : (_b = ctx == null ? void 0 : ctx.getSectionInfo) == null ? void 0 : _b.call(ctx, rootEl)) != null ? _d : null;
const initialView = this.app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
const sourcePath = (_g = (_f = ctx == null ? void 0 : ctx.sourcePath) != null ? _f : (_e = initialView == null ? void 0 : initialView.file) == null ? void 0 : _e.path) != null ? _g : null;
if (sourcePath) {
container.dataset.mclSourcePath = sourcePath;
}
if (section) {
container.dataset.mclLineStart = String(section.lineStart);
container.dataset.mclLineEnd = String(section.lineEnd);
} else {
delete container.dataset.mclLineStart;
delete container.dataset.mclLineEnd;
}
const positionHandles = () => {
var _a2;
const topInset = ((_a2 = getComputedStyle(container).getPropertyValue("--mcl-divider-inset")) == null ? void 0 : _a2.trim()) || "1rem";
for (let i = 0; i < cols.length - 1; i++) {
const handle = content.querySelector(`:scope > .mcl-resizer[data-index="${i}"]`);
if (!handle) continue;
const x = cols[i].offsetLeft + cols[i].offsetWidth;
handle.style.left = `${x - RESIZER_HANDLE_WIDTH_PX / 2}px`;
handle.style.top = topInset;
handle.style.bottom = topInset;
handle.style.width = `${RESIZER_HANDLE_WIDTH_PX}px`;
}
};
for (let i = 0; i < cols.length - 1; i++) {
const handle = document.createElement("div");
handle.className = "mcl-resizer";
handle.dataset.index = String(i);
handle.setAttribute("aria-label", "Resize columns");
content.insertBefore(handle, cols[i + 1]);
const onMouseDown = (ev) => {
var _a2, _b2;
if (ev.button !== 0) return;
ev.preventDefault();
ev.stopPropagation();
const view = this.app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
const editor = (_a2 = view == null ? void 0 : view.editor) != null ? _a2 : null;
if (((_b2 = view == null ? void 0 : view.getMode) == null ? void 0 : _b2.call(view)) !== "source" || !editor || !(view == null ? void 0 : view.file) || sourcePath && view.file.path !== sourcePath) {
new import_obsidian.Notice("Please use live preview (editable) to resize columns.");
return;
}
const containerRect = content.getBoundingClientRect();
const totalWidth = Math.max(1, content.clientWidth);
const startX = ev.clientX;
const widths = cols.map((colEl) => colEl.getBoundingClientRect().width);
const ratios = widths.map((w) => Math.max(1, Math.round(w / totalWidth * 100)));
const existingRatiosHint = cols.map((colEl) => {
const raw = colEl.getAttribute("data-callout-metadata");
const n = parseInt(String(raw != null ? raw : ""), 10);
return Number.isFinite(n) ? n : null;
});
const sum = ratios.reduce((a, b) => a + b, 0);
if (sum !== 100 && sum > 0) {
const normalized = ratios.map((r) => Math.max(1, Math.round(r / sum * 100)));
const diff = 100 - normalized.reduce((a, b) => a + b, 0);
normalized[normalized.length - 1] += diff;
for (let k = 0; k < normalized.length; k++) ratios[k] = normalized[k];
}
const idx = i;
const pairTotal = ratios[idx] + ratios[idx + 1];
const minPx = 60;
const minPct = Math.max(1, Math.ceil(minPx / totalWidth * 100));
const beforePct = ratios.slice(0, idx).reduce((a, b) => a + b, 0);
content.classList.add("mcl-resizing");
document.body.classList.add("mcl-global-resizing");
const applyRatiosToDOM = () => {
for (let k = 0; k < cols.length; k++) {
cols[k].style.flex = `0 0 ${ratios[k]}%`;
cols[k].setAttribute("data-callout-metadata", String(ratios[k]));
}
positionHandles();
};
const onMove = (moveEv) => {
moveEv.preventDefault();
moveEv.stopPropagation();
moveEv.stopImmediatePropagation();
const mouseX = moveEv.clientX;
const rel = Math.min(Math.max(mouseX - containerRect.left, 0), totalWidth);
const targetPct = Math.round(rel / totalWidth * 100);
let newLeft = targetPct - beforePct;
newLeft = Math.min(Math.max(newLeft, minPct), pairTotal - minPct);
ratios[idx] = newLeft;
ratios[idx + 1] = pairTotal - newLeft;
applyRatiosToDOM();
};
const onUp = (upEv) => {
var _a3, _b3, _c2, _d2, _e2, _f2;
upEv.preventDefault();
upEv.stopPropagation();
upEv.stopImmediatePropagation();
window.removeEventListener("mousemove", onMove, true);
window.removeEventListener("mouseup", onUp, true);
content.classList.remove("mcl-resizing");
document.body.classList.remove("mcl-global-resizing");
const suppressClick = (clickEv) => {
var _a4;
clickEv.preventDefault();
clickEv.stopPropagation();
(_a4 = clickEv.stopImmediatePropagation) == null ? void 0 : _a4.call(clickEv);
};
window.addEventListener("click", suppressClick, true);
window.setTimeout(() => window.removeEventListener("click", suppressClick, true), 0);
if (Math.abs(upEv.clientX - startX) < 1) {
applyRatiosToDOM();
return;
}
const prevSelections = editor.listSelections();
const prevScroll = editor.getScrollInfo();
let lineHint = null;
try {
const cmView = this.getCM6EditorView(view);
const pos = (_a3 = cmView == null ? void 0 : cmView.posAtCoords) == null ? void 0 : _a3.call(cmView, { x: ev.clientX, y: ev.clientY });
if (typeof pos === "number") {
if (typeof editor.offsetToPos === "function") {
lineHint = editor.offsetToPos(pos).line;
} else if ((_c2 = (_b3 = cmView == null ? void 0 : cmView.state) == null ? void 0 : _b3.doc) == null ? void 0 : _c2.lineAt) {
lineHint = cmView.state.doc.lineAt(pos).number - 1;
}
}
} catch (e) {
}
const sectionNow = (_f2 = (_e2 = (_d2 = ctx == null ? void 0 : ctx.getSectionInfo) == null ? void 0 : _d2.call(ctx, container)) != null ? _e2 : section) != null ? _f2 : null;
if (sectionNow) {
container.dataset.mclLineStart = String(sectionNow.lineStart);
container.dataset.mclLineEnd = String(sectionNow.lineEnd);
}
this.writeBackColumnRatios(container, ratios, {
editor,
sourcePath,
expectedDepth: container.dataset.mclExpectedDepth,
lineStart: sectionNow == null ? void 0 : sectionNow.lineStart,
lineEnd: sectionNow == null ? void 0 : sectionNow.lineEnd,
lineHint,
existingRatiosHint,
prevSelections,
prevScroll
});
};
window.addEventListener("mousemove", onMove, true);
window.addEventListener("mouseup", onUp, true);
applyRatiosToDOM();
};
handle.addEventListener("mousedown", onMouseDown);
}
requestAnimationFrame(positionHandles);
});
}
writeBackColumnRatios(containerEl, ratios, ctx) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u;
const view = this.app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
const editor = (_b = (_a = ctx == null ? void 0 : ctx.editor) != null ? _a : view == null ? void 0 : view.editor) != null ? _b : null;
const activePath = (_d = (_c = view == null ? void 0 : view.file) == null ? void 0 : _c.path) != null ? _d : null;
const dsPath = (_f = (_e = containerEl == null ? void 0 : containerEl.dataset) == null ? void 0 : _e.mclSourcePath) != null ? _f : null;
const sourcePath = (_h = (_g = ctx == null ? void 0 : ctx.sourcePath) != null ? _g : dsPath) != null ? _h : activePath;
if (!activePath || !editor || sourcePath && activePath !== sourcePath) {
new import_obsidian.Notice("Resize applied visually, but write-back requires the note to be open in live preview.");
return;
}
const parseMaybeInt = (v) => {
const n = typeof v === "number" ? v : parseInt(String(v != null ? v : ""), 10);
return Number.isFinite(n) ? n : null;
};
const lineStart = (_j = parseMaybeInt(ctx == null ? void 0 : ctx.lineStart)) != null ? _j : parseMaybeInt((_i = containerEl == null ? void 0 : containerEl.dataset) == null ? void 0 : _i.mclLineStart);
const lineEnd = (_l = parseMaybeInt(ctx == null ? void 0 : ctx.lineEnd)) != null ? _l : parseMaybeInt((_k = containerEl == null ? void 0 : containerEl.dataset) == null ? void 0 : _k.mclLineEnd);
const expectedDepth = (_n = parseMaybeInt(ctx == null ? void 0 : ctx.expectedDepth)) != null ? _n : parseMaybeInt((_m = containerEl == null ? void 0 : containerEl.dataset) == null ? void 0 : _m.mclExpectedDepth);
const existingRatiosHint = Array.isArray(ctx == null ? void 0 : ctx.existingRatiosHint) ? ctx.existingRatiosHint : null;
const maxLine = editor.lastLine();
const cursorLine = (_p = (_o = editor.getCursor) == null ? void 0 : _o.call(editor).line) != null ? _p : 0;
const lineHint = (_r = (_q = parseMaybeInt(ctx == null ? void 0 : ctx.lineHint)) != null ? _q : lineStart) != null ? _r : cursorLine;
const clamp = (n, min, max) => Math.min(Math.max(n, min), max);
const expandLines = 10;
let scanMin = Math.max(0, lineHint - 5e3);
let scanMax = Math.min(maxLine, lineHint + 5e3);
if (lineStart != null) scanMin = Math.max(0, lineStart - expandLines);
if (lineEnd != null) scanMax = Math.min(maxLine, lineEnd + expandLines);
if (scanMin > scanMax) {
const tmp = scanMin;
scanMin = scanMax;
scanMax = tmp;
}
const anchorLine = clamp(lineHint, scanMin, scanMax);
const getQuoteDepth = (text) => {
const m = /^(\s*)(>+)/.exec(text);
return m ? m[2].length : 0;
};
const extractColRatioFromHeader = (lineText) => {
const m = /\[!col([^\]]*)\]/.exec(lineText);
if (!m) return null;
const raw = String(m[1] || "");
const parts = raw.startsWith("|") ? raw.slice(1).split("|").filter((p) => p.length > 0) : [];
if (parts.length === 0) return null;
const n = parseInt(parts[0], 10);
return Number.isFinite(n) ? n : null;
};
const scoreAgainstHint = (colLines2) => {
if (!existingRatiosHint || existingRatiosHint.length !== colLines2.length) return null;
let score = 0;
for (let i = 0; i < colLines2.length; i++) {
const hinted = existingRatiosHint[i];
const actual = extractColRatioFromHeader(colLines2[i].text);
if (typeof hinted !== "number") continue;
if (hinted === actual) score++;
}
return score;
};
const distanceToHint = (line) => {
const cursorDistance = Math.abs(line - anchorLine);
if (lineStart != null && lineEnd != null) {
const inSection = line >= lineStart && line <= lineEnd;
return (inSection ? 0 : 1e4) + cursorDistance;
}
return cursorDistance;
};
const findBestHeaderAndCols = (depthFilter) => {
var _a2;
let best = null;
let bestScore = -1;
let bestDistance = Number.POSITIVE_INFINITY;
for (let line = scanMin; line <= scanMax; line++) {
const text = editor.getLine(line);
const m = /^(\s*)(>+)\s*\[!multi-column([^\]]*)\]/.exec(text);
if (!m) continue;
const depth = m[2].length;
if (typeof depthFilter === "number" && depth !== depthFilter) continue;
const colDepth = depth + 1;
const colHeaderRe = new RegExp(`^(\\s*)(>{${colDepth}})\\s*\\[!col([^\\]]*)\\]`);
const scanEnd = Math.min(scanMax, maxLine, line + 2e3);
const colLines2 = [];
for (let j = line; j <= scanEnd; j++) {
const t = editor.getLine(j);
if (j > line) {
const qd = getQuoteDepth(t);
if (qd === 0) break;
if (qd < depth && t.trim() !== "") break;
}
if (colHeaderRe.test(t)) colLines2.push({ line: j, text: t });
if (colLines2.length >= ratios.length) break;
}
if (colLines2.length !== ratios.length) continue;
const score = (_a2 = scoreAgainstHint(colLines2)) != null ? _a2 : 0;
const dist = distanceToHint(line);
const isBetter = score > bestScore || score === bestScore && dist < bestDistance;
if (isBetter) {
bestScore = score;
bestDistance = dist;
best = { header: { line, depth }, colLines: colLines2 };
}
}
return best;
};
const found = (_s = findBestHeaderAndCols(expectedDepth)) != null ? _s : expectedDepth != null ? findBestHeaderAndCols(null) : null;
if (!found) {
new import_obsidian.Notice("Resize applied visually, but failed to locate the multi-column block for write-back.");
return;
}
const { colLines } = found;
if (colLines.length !== ratios.length) {
new import_obsidian.Notice(`Resize write-back failed: expected ${ratios.length} columns, found ${colLines.length}.`);
return;
}
const rewriteColHeader = (lineText, ratio) => {
return lineText.replace(/\[!col([^\]]*)\]/, (_m2, meta) => {
const raw = String(meta || "");
const parts = raw.startsWith("|") ? raw.slice(1).split("|").filter((p) => p.length > 0) : [];
if (parts.length > 0 && /^\d+$/.test(parts[0])) {
parts[0] = String(ratio);
} else {
parts.unshift(String(ratio));
}
return `[!col|${parts.join("|")}]`;
});
};
const changes = colLines.map(({ line, text }, idx) => {
const updated = rewriteColHeader(text, ratios[idx]);
if (updated === text) return null;
return {
from: { line, ch: 0 },
to: { line, ch: text.length },
text: updated
};
}).filter(Boolean).sort((a, b) => b.from.line - a.from.line);
if (changes.length === 0) return;
const prevSelections = (_t = ctx == null ? void 0 : ctx.prevSelections) != null ? _t : editor.listSelections();
const prevScroll = (_u = ctx == null ? void 0 : ctx.prevScroll) != null ? _u : editor.getScrollInfo();
editor.transaction({ changes }, "mcl-resize");
requestAnimationFrame(() => {
try {
editor.setSelections(prevSelections, 0);
editor.scrollTo(prevScroll.left, prevScroll.top);
editor.focus();
} catch (e) {
}
});
}
/**
* Apply current appearance flags (bordered/horizontal) to all existing multi-column callouts in the vault.
*/
async applyAppearanceToAllFiles() {
const files = this.app.vault.getMarkdownFiles();
let updated = 0;
for (const file of files) {
const content = await this.app.vault.read(file);
const migrated = this.migrateContent(content);
if (migrated !== content) {
await this.app.vault.modify(file, migrated);
updated++;
}
}
return updated;
}
migrateContent(content) {
const hasHorizontal = !!this.settings.horzDivider;
return content.replace(/^(\s*>\s*\[!multi-column)([^\]]*)(\])/gm, (_m, prefix, metaStr, suffix) => {
const metaRaw = metaStr || "";
const parts = metaRaw.startsWith("|") ? metaRaw.slice(1).split("|").filter(Boolean) : [];
if (!parts.includes("bordered")) parts.push("bordered");
const filtered = parts.filter((p) => p !== "horizontal");
if (hasHorizontal) filtered.push("horizontal");
const rebuilt = filtered.length > 0 ? `|${filtered.join("|")}` : "";
return `${prefix}${rebuilt}${suffix}`;
});
}
getColDepthAtCursor(editor) {
const cursor = editor.getCursor();
const minLine = Math.max(0, cursor.line - 5e3);
for (let line = cursor.line; line >= minLine; line--) {
const text = editor.getLine(line);
const m = /^(\s*)(>+)\s*\[!col([^\]]*)\]/.exec(text);
if (!m) continue;
const depth = m[2].length;
if (depth !== 2 && depth !== 4) continue;
return depth;
}
const currentText = editor.getLine(cursor.line) || "";
const prefixMatch = /^(\s*)(>+)\s+/.exec(currentText);
if (prefixMatch) {
const depth = prefixMatch[2].length;
if (depth >= 4) return 4;
if (depth >= 2) return 2;
}
return null;
}
insertNestedHere(editor, innerCols) {
if (!editor) return;
editor.focus();
const colDepth = this.getColDepthAtCursor(editor);
if (!colDepth) {
new import_obsidian.Notice(this.t("notice.nested.notInCol"));
return;
}
if (colDepth !== 2) {
new import_obsidian.Notice(this.t("notice.nested.limit"));
return;
}
const metaParts = ["bordered"];
if (this.settings.horzDivider) metaParts.push("horizontal");
const metaStr = metaParts.length ? `|${metaParts.join("|")}` : "";
const containerPrefix = ">".repeat(colDepth + 1);
const colPrefix = ">".repeat(colDepth + 2);
const ratios = this.buildDefaultRatios(innerCols);
const lines = [];
lines.push(`${containerPrefix} [!multi-column${metaStr}]`);
lines.push(containerPrefix);