generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.ts
2358 lines (2157 loc) · 84.7 KB
/
main.ts
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 {
App,
MarkdownView,
Plugin,
Editor,
PluginSettingTab,
Setting
} from 'obsidian';
import { Prec, Extension } from '@codemirror/state';
import { keymap } from '@codemirror/view';
interface QuickLatexSettings {
useMathKeyboardShortcut_toggle: boolean;
moveIntoMath_toggle: boolean;
autoCloseMath_toggle: boolean;
autoCloseRound_toggle: boolean;
autoCloseSquare_toggle: boolean;
autoCloseCurly_toggle: boolean;
addAlignBlock_toggle: boolean;
addAlignBlock_parameter: string;
autoAlignSymbols: string;
addCasesBlock_toggle: boolean;
shiftEnter_toggle: boolean;
addMatrixBlock_toggle: boolean;
addMatrixBlock_parameter: string;
autoFraction_toggle: boolean;
autoLargeBracket_toggle: boolean;
autoSumLimit_toggle: boolean;
autoEncloseSup_toggle: boolean;
autoEncloseSub_toggle: boolean;
encloseSelection_toggle: boolean;
autoGreekCommandMathMode_toggle: boolean;
customShorthand_toggle: boolean;
useTabtoComplete_toggle: boolean;
customShorthand_parameter: string;
customTab_parameter: string
}
const DEFAULT_SETTINGS: QuickLatexSettings = {
useMathKeyboardShortcut_toggle: false,
moveIntoMath_toggle: true,
autoCloseMath_toggle: true,
autoCloseRound_toggle: true,
autoCloseSquare_toggle: true,
autoCloseCurly_toggle: true,
addAlignBlock_toggle: true,
addAlignBlock_parameter: "align*",
autoAlignSymbols: "= > < \\le \\ge \\neq \\approx",
addCasesBlock_toggle: true,
shiftEnter_toggle: false,
addMatrixBlock_toggle: true,
addMatrixBlock_parameter: "pmatrix",
autoFraction_toggle: true,
autoLargeBracket_toggle: true,
autoSumLimit_toggle: true,
autoEncloseSup_toggle: true,
autoEncloseSub_toggle: true,
encloseSelection_toggle: true,
autoGreekCommandMathMode_toggle: true,
customShorthand_toggle: true,
useTabtoComplete_toggle: false,
customShorthand_parameter: "bi:::\\binom{#cursor}{#tab};\nsq:::\\sqrt{};\nbb:::\\mathbb{};\nbf:::\\mathbf{};\nte:::\\text{};\ninf:::\\infty;\n"+
"cd:::\\cdot;\nqu:::\\quad;\nti:::\\times;\n"+
"al:::\\alpha;\nbe:::\\beta;\nga:::\\gamma;\nGa:::\\Gamma;\n"+
"de:::\\delta;\nDe:::\\Delta;\nep:::\\epsilon;\nze:::\\zeta;\n"+
"et:::\\eta;\nth:::\\theta;\nTh:::\\Theta;\nio:::\\iota;\n"+
"ka:::\\kappa;\nla:::\\lambda;\nLa:::\\Lambda;\nmu:::\\mu;\n"+
"nu:::\\nu;\nxi:::\\xi;\nXi:::\\Xi;\npi:::\\pi;\nPi:::\\Pi;\n"+
"rh:::\\rho;\nsi:::\\sigma;\nSi:::\\Sigma;\nta:::\\tau;\n"+
"up:::\\upsilon;\nUp:::\\Upsilon;\nph:::\\phi;\nPh:::\\Phi;\nch:::\\chi;\n"+
"ps:::\\psi;\nPs:::\\Psi;\nom:::\\omega;\nOm:::\\Omega",
customTab_parameter: "#tab"
}
export default class QuickLatexPlugin extends Plugin {
settings: QuickLatexSettings;
shorthand_array: string[][];
autoAlign_array: string[];
private vimAllow_autoCloseMath: boolean = true;
private readonly makeExtensionThing = ():Extension => Prec.high(keymap.of([
{
key: '$',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (editor.getSelection().length > 0) {
// enclose selected text
if (this.settings.encloseSelection_toggle) {
const anchor = editor.getCursor("anchor")
const head = editor.getCursor("head")
editor.replaceSelection(`$${editor.getSelection()}$`)
if (anchor.line > head.line) {
editor.setSelection({line:anchor.line,ch:anchor.ch},{line:head.line,ch:head.ch+1})
} else if (anchor.line < head.line) {
editor.setSelection({line:anchor.line,ch:anchor.ch+1},{line:head.line,ch:head.ch})
} else {
editor.setSelection({line:anchor.line,ch:anchor.ch+1},{line:head.line,ch:head.ch+1})
}
return true
}
return false
} else {
// close math symbol
const position = editor.getCursor()
const prev_char = editor.getRange(
{line:position.line,ch:position.ch-1},
{line:position.line,ch:position.ch})
const next_char = editor.getRange(
{line:position.line,ch:position.ch},
{line:position.line,ch:position.ch+1})
const next2_char = editor.getRange(
{line:position.line,ch:position.ch},
{line:position.line,ch:position.ch+2})
if (prev_char != "$" && next_char == "$"){
if (next2_char == "$$") {
editor.setCursor({line:position.line,ch:position.ch+2})
return true
} else {
editor.setCursor({line:position.line,ch:position.ch+1})
return true
}
}
// auto close math
if (this.settings.autoCloseMath_toggle && this.vimAllow_autoCloseMath) {
const prev_char = editor.getRange({line:position.line,ch:position.ch-1},{line:position.line,ch:position.ch})
const line = editor.getLine(position.line)
const count = (line.match(/\$/g) || []).length
if (prev_char != "\\" && count % 2 == 0) {
editor.replaceSelection("$");
}
}
// move into math
if (this.settings.moveIntoMath_toggle) {
const position = editor.getCursor();
const t = editor.getRange(
{ line: position.line, ch: position.ch - 1 },
{ line: position.line, ch: position.ch })
const t2 = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch + 1 })
const t_2 = editor.getRange(
{ line: position.line, ch: position.ch - 2 },
{ line: position.line, ch: position.ch })
if (t == '$' && t2 != '$') {
editor.setCursor({ line: position.line, ch: position.ch - 1 })
} else if (t_2 == '$$') {
editor.setCursor({ line: position.line, ch: position.ch - 1 })
};
}
return false
}
},
},
// delete pair of math symbols with backspace
{ key: 'Backspace',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
const position = editor.getCursor()
const prev_char = editor.getRange({line:position.line, ch:position.ch-1},{line:position.line, ch:position.ch})
const next_char = editor.getRange({line:position.line, ch:position.ch},{line:position.line, ch:position.ch+1})
if (prev_char == "$" && next_char == "$") {
editor.replaceRange("",{line:position.line, ch:position.ch-1},{line:position.line, ch:position.ch+1})
return true
}
return false
}
},
{
key: 'Tab',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
const position = editor.getCursor();
const current_line = editor.getLine(position.line);
const end_pos = editor.getLine(position.line).length;
const next_line = editor.getLine(position.line+1)
// check for custom shorthand
if (this.settings.customShorthand_toggle && !this.withinText(editor, position.ch)) {
if(this.settings.useTabtoComplete_toggle) {
if (this.customShorthand(editor, position)){
return true
};
}
};
// Tab to go to next #tab with numbering or without numbering if there are no #tabs with numbers
const indexed_tab_expr = new RegExp(`${this.settings.customTab_parameter}(\\d+)?`, 'g');
let next_match;
let current_match;
while ((current_match = indexed_tab_expr.exec(current_line)) != null) {
if (!next_match || parseInt(current_match[1]) < parseInt(next_match[1]))
next_match = current_match;
}
if (next_match) {
const tab_position = next_match.index;
editor.replaceRange("",
{line:position.line, ch:tab_position},
{line:position.line, ch:tab_position+next_match[0].length})
editor.setCursor({line:position.line, ch:tab_position})
return true
}
// Tab shortcut for matrix block
if (this.settings.addMatrixBlock_toggle) {
const begin_matrix = ['\\begin{' + this.settings.addMatrixBlock_parameter+'}', "\\begin{matrix}","\\begin{bmatrix}", "\\begin{Bmatrix}", "\\begin{vmatrix}", "\\begin{Vmatrix}", "\\begin{smallmatrix}"]
const end_matrix = ['\\end{' + this.settings.addMatrixBlock_parameter+'}', "\\end{matrix}","\\end{bmatrix}", "\\end{Bmatrix}", "\\end{vmatrix}", "\\end{Vmatrix}", "\\end{smallmatrix}"]
let state = false
let end_text = ""
for (let i = 0; i < begin_matrix.length; i++) {
if (this.withinAnyBrackets_document(editor, begin_matrix[i], end_matrix[i])) {
state = true
end_text = end_matrix[i]
break;
};
}
const position = editor.getCursor();
const prev3_char = editor.getRange({line:position.line, ch:position.ch-3},{line:position.line, ch:position.ch})
if (state) {
if (prev3_char == ' & ') {
editor.replaceRange('', {line:position.line, ch:position.ch-3},{line:position.line, ch:position.ch})
editor.setCursor({line:position.line, ch:position.ch+end_text.length-3})
return true
} else {
editor.replaceSelection(' & ')
return true
}
}
}
// Tab shortcut for cases block
if (this.settings.addCasesBlock_toggle) {
if (this.withinAnyBrackets_document(editor,
'\\begin{cases}',
'\\end{cases}'
)) {
const position = editor.getCursor();
const prev3_char = editor.getRange({line:position.line, ch:position.ch-3},{line:position.line, ch:position.ch})
const next_line = editor.getLine(position.line+1)
if (prev3_char == ' & ' && next_line == '\\end{cases}') {
editor.replaceRange('', {line:position.line, ch:position.ch-3},{line:position.line, ch:position.ch})
editor.setCursor({line:position.line+1, ch:next_line.length})
return true
} else {
editor.replaceSelection(' & ')
return true
}
};
}
// Tab out of $
const next_2 = editor.getRange({line:position.line, ch:position.ch},{line:position.line, ch:position.ch+2})
if (next_2 == "$$") {
editor.setCursor({line:position.line, ch:position.ch+2})
return true
} else if (position.ch == end_pos && next_line == "$$") {
editor.setCursor({line:position.line+1, ch:next_line.length})
return true
} else if (next_2[0] == "$") {
editor.setCursor({line:position.line, ch:position.ch+1})
return true
}
// Tab to next close bracket
const following_text = editor.getRange({line:position.line, ch:position.ch+1},{line:position.line, ch:current_line.length})
const close_symbols = ['}', ']', ')', '$']
for (let i = 0; i < following_text.length; i++) {
if (close_symbols.contains(following_text[i])) {
editor.setCursor({line:position.line, ch:position.ch+i+1})
return true
}
}
// Tab out of align block
if (position.ch == end_pos && next_line == '\\end{' + this.settings.addAlignBlock_parameter+'}') {
editor.setCursor({line:position.line+1, ch:next_line.length})
return true
}
}
return false
},
},
{
key: 'Shift-Tab',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
const position = editor.getCursor();
const preceding_text = editor.getRange({line:position.line, ch:0},{line:position.line, ch:position.ch})
const close_symbols = ['}', ']', ')']
for (let i = preceding_text.length; i >= 0; i--) {
if (close_symbols.contains(preceding_text[i])) {
editor.setCursor({line:position.line, ch:i})
return true
} else if (position.ch-i > 1 && preceding_text[i]=="$") {
editor.setCursor({line:position.line, ch:i+1})
return true
} else if (preceding_text.slice(-2)=="$$") {
editor.setCursor({line:position.line, ch:position.ch-2})
return true
} else if (preceding_text[-1]=="$") {
editor.setCursor({line:position.line, ch:position.ch-1})
return true
}
}
}
return false
},
},
{
key: 'Space',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (!this.settings.autoFraction_toggle &&
!this.settings.autoLargeBracket_toggle &&
!this.settings.autoEncloseSup_toggle &&
!this.settings.autoEncloseSub_toggle &&
!this.settings.customShorthand_toggle) return false;
if (this.withinMath(editor)) {
const position = editor.getCursor();
const current_line = editor.getLine(position.line);
const last_dollar = current_line.lastIndexOf('$', position.ch - 1);
// check for custom shorthand
if (this.settings.customShorthand_toggle && !this.withinText(editor, position.ch)) {
if(!this.settings.useTabtoComplete_toggle) {
if (this.customShorthand(editor, position)) {
return true
}
}
};
// find last unbracketed subscript within last 10 characters and perform autoEncloseSub
// ignore expression that contain + - * / ^
const last_math = current_line.lastIndexOf('$', position.ch - 1);
if (this.settings.autoEncloseSub_toggle) {
let last_subscript = current_line.lastIndexOf('_', position.ch);
if (last_subscript != -1 && last_subscript > last_math) {
const letter_after_subscript = editor.getRange(
{ line: position.line, ch: last_subscript + 1 },
{ line: position.line, ch: last_subscript + 2 });
if (letter_after_subscript != "{" &&
(position.ch - last_subscript) <= 10 ) {
editor.replaceSelection("}");
editor.replaceRange("{", {line:position.line, ch:last_subscript+1});
return true;
};
};
};
// retrieve the last unbracketed superscript
let last_superscript = current_line.lastIndexOf('^', position.ch);
while (last_superscript != -1) {
const two_letters_after_superscript = editor.getRange(
{ line: position.line, ch: last_superscript + 1 },
{ line: position.line, ch: last_superscript + 3 });
if (two_letters_after_superscript[0] == '{' || two_letters_after_superscript == ' {') {
last_superscript = current_line.lastIndexOf('^', last_superscript - 1);
} else if (last_superscript < last_math) {
last_superscript = -1
break;
} else {
break;
}
}
// retrieve the last divide symbol
let last_divide = current_line.lastIndexOf('/', position.ch - 2);
while (last_divide != -1) {
const around_divide = editor.getRange(
{ line: position.line, ch: last_divide - 1 },
{ line: position.line, ch: last_divide + 2 });
if (around_divide[0] == ' ' && around_divide[2] == ' ') {
last_divide = current_line.lastIndexOf('^', last_divide - 1);
} else if (last_divide < last_math) {
last_divide = -1
break;
} else {
break;
}
}
// perform autoEncloseSup
if (this.settings.autoEncloseSup_toggle) {
if (last_superscript > last_divide) {
// if any brackets from last sup to cursor still unclosed, dont do autoEncloseSup yet
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
if (!brackets.some(e => this.unclosed_bracket(editor, e[0], e[1], position.ch, last_superscript)[0])) {
return this.autoEncloseSup(editor, event, last_superscript);
}
};
};
// perform autoFraction
if (this.settings.autoFraction_toggle && !this.withinText(editor, last_divide)) {
if (last_divide > last_dollar) {
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
// if any brackets in denominator still unclosed, dont do autoFraction yet
if (!brackets.some(e => this.unclosed_bracket(editor, e[0], e[1], position.ch, last_divide)[0])) {
return this.autoFractionCM6(editor, last_superscript);
};
};
};
// perform autoLargeBracket
if (this.settings.autoLargeBracket_toggle) {
let symbol_before = editor.getRange(
{ line: position.line, ch: position.ch - 1 },
{ line: position.line, ch: position.ch })
if (symbol_before == ')' || symbol_before == ']') {
return this.autoLargeBracket(editor, event);
};
}
// perform autoAlign
if (this.autoAlign_array.length) {
if (this.withinAnyBrackets_document(
editor,
'\\begin{' + this.settings.addAlignBlock_parameter,
'\\end{' + this.settings.addAlignBlock_parameter)
) {
let keyword:string = "";
let keyword_length:number = 0;
for (let i = 0 ; i < this.autoAlign_array.length ; i++) {
keyword_length = this.autoAlign_array[i].length;
if ( keyword_length > position.ch) {
continue;
} else {
keyword = editor.getRange(
{ line: position.line, ch: position.ch - keyword_length },
{ line: position.line, ch: position.ch });
}
if (keyword == this.autoAlign_array[i]) {
editor.replaceRange('&', { line: position.line, ch: position.ch - keyword_length });
return false;
}
}
}
}
} else if (this.settings.autoGreekCommandMathMode_toggle) {
const greekSymbols = ['alpha', 'Alpha', 'beta', 'gamma', 'Gamma', 'delta', 'Delta', 'epsilon', 'zeta', 'eta', 'theta', 'Theta', 'iota', 'kappa', 'lambda', 'Lambda', 'mu', 'nu', 'xi', 'Xi', 'omicron', 'pi', 'Pi', 'rho', 'sigma', 'Sigma', 'tau', 'upsilon', 'Upsilon', 'phi', 'Phi', 'chi', 'psi', 'Psi', 'omega', 'Omega', 'varepsilon', 'vartheta', 'varrho', 'varphi'];
const greekSymbolsSlashed = greekSymbols.map(x => '\\' + x);
const position = editor.getCursor();
const current_line = editor.getLine(position.line);
const last_slash = current_line.lastIndexOf('\\', position.ch - 1);
if (last_slash != -1) {
const entered = current_line.substring(last_slash, position.ch);
if (greekSymbolsSlashed.contains(entered))
editor.replaceRange('$' + entered + '$', { line: position.line, ch: position.ch - entered.length }, { line: position.line, ch: position.ch });
}
}
},
},
{
key: 'Shift-Space',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (!this.settings.customShorthand_toggle) return false;
if (this.withinMath(editor)) {
const position = editor.getCursor();
// check for custom shorthand
if (this.settings.customShorthand_toggle && !this.withinText(editor, position.ch)) {
let keyword:string = "";
let keyword_length:number = 0;
for (let i = 0 ; i < this.shorthand_array.length ; i++) {
keyword_length = this.shorthand_array[i][0].length;
if ( keyword_length > position.ch) {
continue;
} else if ( keyword_length == position.ch ) {
keyword = "@" + editor.getRange(
{ line: position.line, ch: position.ch - keyword_length },
{ line: position.line, ch: position.ch });
} else {
keyword = editor.getRange(
{ line: position.line, ch: position.ch - keyword_length - 1 },
{ line: position.line, ch: position.ch });
}
if (keyword[0].toLowerCase() == keyword[0].toUpperCase() ||
keyword[0] == "@" ) {
if (this.shorthand_array[i][0] == keyword.slice(- keyword_length) &&
this.shorthand_array[i][1] != keyword) {
const replace_slash = (keyword[0]=="\\" && this.shorthand_array[i][1][0]=="\\") ? 1 : 0;
const set_cursor_position = this.shorthand_array[i][1].indexOf("#cursor");
editor.replaceRange(this.shorthand_array[i][1],
{ line: position.line, ch: position.ch - keyword_length - replace_slash },
{ line: position.line, ch: position.ch });
if (set_cursor_position != -1) {
editor.replaceRange("",
{line:position.line, ch:position.ch - keyword_length - replace_slash + set_cursor_position},
{line:position.line, ch:position.ch - keyword_length - replace_slash + set_cursor_position+7});
editor.setCursor({line:position.line, ch:position.ch - keyword_length - replace_slash + set_cursor_position})
} else if (this.shorthand_array[i][1].slice(-2) == "{}") {
editor.setCursor(
{ line: position.line,
ch: position.ch + this.shorthand_array[i][1].length - keyword_length - 1 - replace_slash}
);
} else {
}
return true;
};
};
};
};
};
}
},
{
key: 'Enter',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.settings.addAlignBlock_toggle && this.settings.shiftEnter_toggle==false) {
if (this.withinAnyBrackets_document(
editor,
'\\begin{' + this.settings.addAlignBlock_parameter,
'\\end{' + this.settings.addAlignBlock_parameter)
) {
editor.replaceSelection('\\\\\n')
return true;
}
}
if (this.settings.addCasesBlock_toggle && this.settings.shiftEnter_toggle==false) {
if (this.withinAnyBrackets_document(
editor,
'\\begin{cases}',
'\\end{cases}'
)) {
editor.replaceSelection(' \\\\\n')
return true;
}
}
if (this.settings.addMatrixBlock_toggle) {
const begin_matrix = ['\\begin{' + this.settings.addMatrixBlock_parameter+'}', "\\begin{matrix}","\\begin{bmatrix}", "\\begin{Bmatrix}", "\\begin{vmatrix}", "\\begin{Vmatrix}", "\\begin{smallmatrix}"]
const end_matrix = ['\\end{' + this.settings.addMatrixBlock_parameter+'}', "\\end{matrix}","\\end{bmatrix}", "\\end{Bmatrix}", "\\end{vmatrix}", "\\end{Vmatrix}", "\\end{smallmatrix}"]
let state = false
for (let i = 0; i < begin_matrix.length; i++) {
if (this.withinAnyBrackets_document(editor, begin_matrix[i], end_matrix[i])) {
state = true
break;
};
}
if (state) {
editor.replaceSelection(' \\\\ ')
return true
}
}
// double enter for $$
if (this.withinMath(editor)) {
const position = editor.getCursor();
const prev2_Char = editor.getRange(
{ line: position.line, ch: position.ch - 2 },
{ line: position.line, ch: position.ch })
const next2_Char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch + 2 })
if (prev2_Char=="$$"&&next2_Char=="$$") {
editor.replaceSelection('\n')
editor.setCursor(position)
return false
}
}
return false
},
},
{
key: 'Shift-Enter',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.settings.addAlignBlock_toggle && this.settings.shiftEnter_toggle==true) {
if (this.withinAnyBrackets_document(
editor,
'\\begin{' + this.settings.addAlignBlock_parameter,
'\\end{' + this.settings.addAlignBlock_parameter)
) {
editor.replaceSelection('\\\\\n')
return true;
}
}
if (this.settings.addCasesBlock_toggle && this.settings.shiftEnter_toggle==true) {
if (this.withinAnyBrackets_document(
editor,
'\\begin{cases}',
'\\end{cases}'
)) {
editor.replaceSelection(' \\\\\n')
return true;
}
}
return false;
}
},
{
key: '{',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseCurly_toggle) {
if (editor.getSelection().length > 0) {return false};
const position = editor.getCursor();
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
const next_char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+1 });
const next_2char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+2 });
const followed_by_$spacetabnonedoubleslash = (['$',' ',' ',''].contains(next_char) || next_2char == '\\\\');
if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
editor.replaceSelection('{}');
editor.setCursor({line:position.line, ch:position.ch+1});
return true;
};
};
};
return false
},
},
{
key: '[',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseSquare_toggle) {
if (editor.getSelection().length > 0) {return false};
const position = editor.getCursor();
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
const next_char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+1 });
const next_2char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+2 });
const followed_by_$spacetabnonedoubleslash = (['$',' ',' ',''].contains(next_char) || next_2char == '\\\\');
if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
editor.replaceSelection('[]');
editor.setCursor({line:position.line, ch:position.ch+1});
return true;
};
};
};
return false
},
},
{
key: '(',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseRound_toggle) {
if (editor.getSelection().length > 0) {return false};
const position = editor.getCursor();
const brackets = [['(', ')'], ['{', '}'], ['[', ']']];
const next_char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+1 });
const next_2char = editor.getRange(
{ line: position.line, ch: position.ch },
{ line: position.line, ch: position.ch+2 });
const followed_by_$spacetabnonedoubleslash = (['$',' ',' ',''].contains(next_char) || next_2char == '\\\\');
if (!this.withinAnyBrackets_inline(editor, brackets) && followed_by_$spacetabnonedoubleslash) {
editor.replaceSelection('()');
editor.setCursor({line:position.line, ch:position.ch+1});
return true;
};
};
};
return false
},
},
{
key: '}',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseCurly_toggle) {
const position = editor.getCursor();
const end = editor.getLine(position.line).length
const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
if (!this.unclosed_bracket(editor, "{", "}", end, 0)[0] &&
!this.unclosed_bracket(editor, "{", "}", end, 0, false)[0] &&
next_sym == "}") {
editor.setCursor({line:position.line,ch:position.ch+1})
return true;
} else {
return false;
};
};
};
return false
},
},
{
key: ']',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseSquare_toggle) {
const position = editor.getCursor();
const end = editor.getLine(position.line).length
const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
if (!this.unclosed_bracket(editor, "[", "]", end, 0)[0] &&
!this.unclosed_bracket(editor, "[", "]", end, 0, false)[0] &&
next_sym == "]") {
editor.setCursor({line:position.line,ch:position.ch+1})
return true;
} else {
return false;
};
};
};
return false
},
},
{
key: ')',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (this.withinMath(editor)) {
if (this.settings.autoCloseRound_toggle) {
const position = editor.getCursor();
const end = editor.getLine(position.line).length
const next_sym = editor.getRange({line:position.line,ch:position.ch},{line:position.line,ch:position.ch+1})
if (!this.unclosed_bracket(editor, "(", ")", end, 0)[0] &&
!this.unclosed_bracket(editor, "(", ")", end, 0, false)[0] &&
next_sym == ")") {
editor.setCursor({line:position.line,ch:position.ch+1})
return true;
} else {
return false;
};
};
};
return false
},
},
{
key: 'm',
run: (): boolean => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) return false
const editor = view.editor
if (!this.withinMath(editor)) return false
const position = editor.getCursor();
if (!this.settings.autoSumLimit_toggle) return;
if (this.withinMath(editor)) {
if (editor.getRange(
{ line: position.line, ch: position.ch - 3 },
{ line: position.line, ch: position.ch }) == '\\su') {
editor.replaceSelection('m\\limits')
return true;
};
};
return false
},
},
]));
async onload() {
this.registerEditorExtension(this.makeExtensionThing());
await this.loadSettings();
// preprocess shorthand array
let shorthands = this.settings.customShorthand_parameter
while(shorthands.slice(-2)=="\n"){
shorthands = shorthands.slice(0,-2)
}
if(shorthands.slice(-1)==";"){
shorthands = shorthands.slice(0,-1)
}
if(shorthands.lastIndexOf(";\n")==-1){
this.shorthand_array = shorthands.split(",").map(item=>item.split(":"));
} else if (shorthands.lastIndexOf(":::")==-1) {
this.shorthand_array = shorthands.split(";\n").map(item=>item.split(":"));
} else {
this.shorthand_array = shorthands.split(";\n").map(item=>item.split(":::"));
}
// preprocess autoAlign array
if (this.settings.autoAlignSymbols.trim() == "") {
this.autoAlign_array = [];
} else {
this.autoAlign_array = this.settings.autoAlignSymbols.split(" ");
}
this.app.workspace.onLayoutReady(() => {
this.registerCodeMirror((cm: CodeMirror.Editor) => {
cm.on('vim-mode-change', this.handleVimModeChange);
cm.on('keydown', this.handleKeyDown);
cm.on('keypress', this.handleKeyPress);
});
this.addSettingTab(new QuickLatexSettingTab(this.app, this));
this.addCommand({
id: 'addAlignBlock',
name: 'Add Align Block',
hotkeys: [
{
modifiers: ['Alt', 'Shift'],
key: 'A',
},
],
editorCallback: (editor) => this.addAlignBlock(editor),
});
this.addCommand({
id: 'addInlineMath',
name: 'Add Inline Math',
hotkeys: [
{
modifiers: ['Mod'],
key: 'M',
},
],
editorCallback: (editor) => this.addInlineMath(editor),
});
this.addCommand({
id: 'addBlockMath',
name: 'Add Block Math',
hotkeys: [
{
modifiers: ['Mod', 'Shift'],
key: 'M',
},
],
editorCallback: (editor) => this.addBlockMath(editor),
});
this.addCommand({
id: 'addMatrixBlock',
name: 'Add Matrix Block',
hotkeys: [
{
modifiers: ['Alt', 'Shift'],
key: 'M',
},
],
editorCallback: (editor) => this.addMatrixBlock(editor),
});
this.addCommand({
id: 'addCasesBlock',
name: 'Add Cases Block',
hotkeys: [
{
modifiers: ['Alt', 'Shift'],
key: 'C',
},
],
editorCallback: (editor) => this.addCasesBlock(editor),
});
});
}
private readonly handleVimModeChange = (
modeObj: any
) : void => {
if (!modeObj || modeObj.mode === 'insert')
this.vimAllow_autoCloseMath = true;
else
this.vimAllow_autoCloseMath = false;
};
private readonly handleKeyDown = (
cm: CodeMirror.Editor,
event: KeyboardEvent,
): void => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) return;
const editor = view.editor;
if (['$', ' ', 'Enter', 'Tab'].contains(event.key)) {
switch (event.key) {
case '$':
if (editor.getSelection().length > 0) {
if (this.settings.encloseSelection_toggle) {
const anchor = editor.getCursor("anchor");
const head = editor.getCursor("head");
editor.replaceSelection('$' + editor.getSelection() + '$')
if (anchor.line > head.line) {
editor.setSelection({line:anchor.line,ch:anchor.ch},{line:head.line,ch:head.ch+1})
} else if (anchor.line < head.line) {
editor.setSelection({line:anchor.line,ch:anchor.ch+1},{line:head.line,ch:head.ch})
} else {
editor.setSelection({line:anchor.line,ch:anchor.ch+1},{line:head.line,ch:head.ch+1})
}
event.preventDefault();
return;
}
} else {
// close math symbol
const position = editor.getCursor()
const prev_char = editor.getRange(
{line:position.line,ch:position.ch-1},
{line:position.line,ch:position.ch})
const next_char = editor.getRange(
{line:position.line,ch:position.ch},
{line:position.line,ch:position.ch+1})
const next2_char = editor.getRange(
{line:position.line,ch:position.ch},
{line:position.line,ch:position.ch+2})
if (prev_char != "$" && next_char == "$"){
if (next2_char == "$$") {
editor.setCursor({line:position.line,ch:position.ch+2})
event.preventDefault();
return;
} else {
editor.setCursor({line:position.line,ch:position.ch+1})
event.preventDefault();
return;
}
}
// perform autoCloseMath
if (this.settings.autoCloseMath_toggle && this.vimAllow_autoCloseMath) {
editor.replaceSelection("$");
}
// perform moveIntoMath