generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.ts
1310 lines (1170 loc) · 46.5 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, Editor, Menu, EditorSelection, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, Workspace, WorkspaceLeaf, TFile } from 'obsidian';
import { EditorState, Extension, StateField, Transaction, TransactionSpec, Text } from '@codemirror/state';
import { SelectionRange, Prec } from "@codemirror/state";
import { EasyTypingSettingTab, EasyTypingSettings, DEFAULT_SETTINGS, PairString, ConvertRule } from "./settings"
import { EditorView, keymap, ViewUpdate } from '@codemirror/view';
import { posToOffset, offsetToPos, string2pairstring, ruleStringList2RuleList, getTypeStrOfTransac } from './utils'
import { LineFormater, getPosLineType, getPosLineType2, LineType } from './core'
import { syntaxTree, forceParsing, ensureSyntaxTree } from "@codemirror/language";
import { Platform } from "obsidian";
import { print } from './utils';
declare module "obsidian" {
// add type safety for the undocumented methods,
// COPY FROM https://github.com/chrisgrieser/obsidian-smarter-md-hotkeys/tree/master
// interface Editor {
// cm: {
// findWordAt?: (pos: EditorPosition) => EditorSelection;
// state?: { wordAt: (offset: number) => { from: number, to: number} };
// };
// }
// interface App {
// commands: { executeCommandById: (commandID: string) => void };
// }
interface Vault {
setConfig: (config: string, newValue: boolean) => void;
getConfig: (config: string) => boolean;
}
}
export default class EasyTypingPlugin extends Plugin {
settings: EasyTypingSettings;
selectionReplaceMapInitalData: [string, PairString][];
SelectionReplaceMap: Map<string, PairString>;
SymbolPairsMap: Map<string, string>;
halfToFullSymbolMap: Map<string, string>;
BasicConvRules: ConvertRule[];
FW2HWSymbolRules: ConvertRule[];
Formater: LineFormater;
IntrinsicDeleteRules: ConvertRule[];
IntrinsicAutoPairRulesPatch: ConvertRule[];
CurActiveMarkdown: string;
UserDeleteRules: ConvertRule[];
UserConvertRules: ConvertRule[];
lang: string;
compose_begin_pos: number;
compose_end_pos: number;
compose_need_handle: boolean;
onFormatArticle: boolean;
TaboutPairStrs: PairString[];
saved_table_viewupdate: ViewUpdate;
async onload() {
await this.loadSettings();
this.selectionReplaceMapInitalData = [
["【", { left: "[", right: "]" }], ["¥", { left: "$", right: "$" }], ["·", { left: "`", right: "`" }],
["《", { left: "《", right: "》" }], ["“", { left: "“", right: "”" }], ["”", { left: "“", right: "”" }], ["(", { left: "(", right: ")" }],
["<", { left: "<", right: ">" }]
];
this.refreshSelectionReplaceRule();
this.SymbolPairsMap = new Map<string, string>();
let SymbolPairs = ["【】", "()", "《》", "“”", "‘’", "「」", "『』", '[]', '()', '{}', '""', "''"]
for (let pairStr of SymbolPairs) this.SymbolPairsMap.set(pairStr.charAt(0), pairStr.charAt(1));
this.halfToFullSymbolMap = new Map([
[".", "。"],
[",", ","],
['?', '?'],
['!', '!']
]);
let BasicConvRuleStringList: Array<[string, string]> = [['··|', '`|`'], ["!【【|】",'![[|]]'],['!【【|', '![[|]]'],
["【【|】", "[[|]]"], ['【【|', "[[|]]"], ['¥¥|', '$|$'], ['$¥|$', "$$\n|\n$$"],['¥¥|','$|$'], ['$¥|$', "$$\n|\n$$"],["$$|$", "$$\n|\n$$"], ['$$|', "$|$"],
[">》|", ">>|"], ['\n》|', "\n>|"], [" 》|", " >|"], ["\n、|", "\n/|"]];
this.BasicConvRules = ruleStringList2RuleList(BasicConvRuleStringList);
let FW2HWSymbolRulesStrList: Array<[string, string]> = [["。。|", ".|"], ["!!|", "!|"], [";;|", ";|"], [",,|", ",|"],
["::|", ":|"], ['??|', '?|'], ['((|)', "(|)"], ['((|', '(|)'], ["““|”", "\"|\""], ["“”|”", "\"|\""], ["‘‘|’", "'|'"], ["‘’|’", "'|'"],
["》》|", ">|"], ["《《|》", "<|"], ['《《|', "<|"]];
this.FW2HWSymbolRules = ruleStringList2RuleList(FW2HWSymbolRulesStrList);
let fw2hw_rule_0: ConvertRule = {before:{left:'||', right:''}, after:{left:'|', right:''}};
this.FW2HWSymbolRules.push(fw2hw_rule_0)
let DeleteRulesStrList: Array<[string, string]> = [["$|$", "|"], ['==|==', '|'], ['$$\n|\n$$', "|"]];
this.IntrinsicDeleteRules = ruleStringList2RuleList(DeleteRulesStrList);
let autoPairRulesPatchStrList: Array<[string, string]> = [["【】|】", "【】|"], ["()|)", "()|"],
["<>|>", "<>|"], ["《》|》", "《》|"], ["「」|」", "「」|"], ["『』|』", "『』|"], ["()|)", "()|"], ['[]|]', '[]|'],
["{}|}", "{}|"], ["''|'", "''|"], ['""|"', '""|'],
];
this.IntrinsicAutoPairRulesPatch = ruleStringList2RuleList(autoPairRulesPatchStrList);
let TaboutPairStrs = ["【|】", "(|)", "《|》", "“|”", "‘|’",
"「|」", "『|』", "'|'", "\"|\"", "$$|$$", '$|$', '__|__', '_|_',
"==|==", "~~|~~", "**|**", '*|*', "[[|]]", '[|]',"{|}", "(|)", "<|>"];
this.TaboutPairStrs = TaboutPairStrs.map((s:string)=>string2pairstring(s));
this.refreshUserDeleteRule();
this.refreshUserConvertRule();
this.CurActiveMarkdown = "";
this.compose_need_handle = false;
this.Formater = new LineFormater();
this.onFormatArticle = false;
this.saved_table_viewupdate = null;
this.registerEditorExtension([
EditorState.transactionFilter.of(this.transactionFilterPlugin),
EditorView.updateListener.of(this.viewUpdatePlugin),
Prec.highest(EditorView.domEventHandlers({
"keyup": this.onKeyup
}))
]);
this.registerEditorExtension(Prec.highest(keymap.of([
{
key: "Tab",
run: (view: EditorView): boolean => {
const success = this.handleTabDown(view);
return success;
}
},
{
key: "Enter",
run: (view: EditorView): boolean => {
const success = this.handleEnter(view);
return success;
}
}
])));
this.lang = window.localStorage.getItem('language');
let command_name_map = this.getCommandNameMap();
this.addCommand({
id: "easy-typing-format-article",
name: command_name_map.get("format_article"),
editorCallback: (editor: Editor, view: MarkdownView) => {
this.formatArticle(editor, view);
},
hotkeys: [{
modifiers: ['Ctrl', 'Shift'],
key: "s"
}],
});
this.addCommand({
id: "easy-typing-format-selection",
name: command_name_map.get("format_selection"),
editorCallback: (editor: Editor, view: MarkdownView) => {
this.formatSelectionOrCurLine(editor, view);
},
hotkeys: [{
modifiers: ['Ctrl', 'Shift'],
key: "l"
}],
});
this.addCommand({
id: "easy-typing-delete-blank-line",
name: command_name_map.get("delete_blank_line"),
editorCallback: (editor: Editor, view: MarkdownView) => {
this.deleteBlankLines(editor);
},
hotkeys: [{
modifiers: ['Ctrl', 'Shift'],
key: "k"
}],
});
this.addCommand({
id: "easy-typing-insert-codeblock",
name: command_name_map.get("insert_codeblock"),
editorCallback: (editor: Editor, view: MarkdownView) => {
this.convert2CodeBlock(editor);
},
hotkeys: [{
modifiers: ['Ctrl', 'Shift'],
key: "n"
}],
});
this.addCommand({
id: "easy-typing-format-switch",
name: command_name_map.get("switch_autoformat"),
callback: () => this.switchAutoFormatting(),
hotkeys: [{
modifiers: ['Ctrl'],
key: "tab"
}],
});
this.addCommand({
id: "easy-typing-paste-without-format",
name: command_name_map.get("paste_wo_format"),
editorCallback: (editor) => this.normalPaste(editor),
hotkeys: [
{
modifiers: ["Mod", "Shift"],
key: "v",
},
],
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new EasyTypingSettingTab(this.app, this));
this.registerEvent(this.app.workspace.on('active-leaf-change', (leaf: WorkspaceLeaf) => {
if (leaf.view.getViewType() == 'markdown') {
let file = this.app.workspace.getActiveFile();
if (file != null && this.CurActiveMarkdown != file.path) {
this.CurActiveMarkdown = file.path;
if (this.settings.debug)
new Notice('new md-file open: ' + file.path)
}
}
}));
//判断当前是否为MAC系统
if (Platform.isMacOS && this.settings.FixMacOSContextMenu) {
// 检测鼠标右键呼出菜单的事件
this.registerEvent(this.app.workspace.on('editor-menu', (menu: Menu, editor: Editor, view: MarkdownView) => {
// console.log('editor-menu', menu, editor, view);
if (editor.listSelections().length != 1) return;
let selection = editor.listSelections()[0];
let selected = editor.getSelection();
// console.log('selected', selected, selected=='\n');
// console.log('selection', selection);
if (selected=='\n')
{
editor.setSelection(selection.anchor, selection.anchor);
}
}));
}
// this.registerEvent(this.app.workspace.on('file-open', (file: TFile | null) => {
// if (file != null) {
// let editor = this.getEditor();
// if (editor === null) return;
// this.ContentParser.parseNewArticle(editor.getValue());
// if (this.settings.debug) {
// new Notice("EasyTyping: Parse New Article: " + file.vault.getName() + '/' + file.path);
// // if (this.settings.debug) this.ContentParser.print();
// }
// }
// }));
}
onunload() {
}
transactionFilterPlugin = (tr: Transaction): TransactionSpec | readonly TransactionSpec[] => {
const changes: TransactionSpec[] = [];
if (!tr.docChanged) return tr;
let selected = tr.startState.selection.asSingle().main.anchor != tr.startState.selection.asSingle().main.head;
let changeTypeStr = getTypeStrOfTransac(tr);
tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {
let changedStr = tr.startState.sliceDoc(fromA, toA);
let changestr_ = changedStr.replace(/\s/g, '0')
let insertedStr = inserted.sliceString(0);
// if (this.settings.debug)
// {
// console.log("TransactionFilter catch change:",changeTypeStr, fromA, toA, changedStr,fromB, toB, insertedStr);
// }
// 表格编辑时直接返回,解决表格内容编辑有时候会跳出聚焦状态的 Bug
if (getPosLineType(tr.startState, fromA)==LineType.table) return tr;
// ========== Selection Replace ============
if (this.settings.SelectionEnhance) {
if ((changeTypeStr == 'input.type' || changeTypeStr == "input.type.compose") && fromA != toA && ((fromB + 1 === toB)||insertedStr=='——'||insertedStr=='……')) {
if (this.SelectionReplaceMap.has(insertedStr)) {
changes.push({ changes: { from: fromA, insert: this.SelectionReplaceMap.get(insertedStr)?.left }, userEvent: "EasyTyping.change" })
changes.push({ changes: { from: toA, insert: this.SelectionReplaceMap.get(insertedStr)?.right }, userEvent: "EasyTyping.change" })
tr = tr.startState.update(...changes);
return tr;
}
}
}
if (selected) return tr;
// 尝试解决微软旧版输入法的问题~
if (this.settings.TryFixMSIME &&
changeTypeStr == "input.type.compose" &&
changedStr == '' && /^[\u4e00-\u9fa5]+$/.test(insertedStr)){
print("MS-IME Compose detected:", insertedStr);
tr = tr.startState.update(...changes);
return tr;
}
// UserDefined Delete Rule
if (changeTypeStr == "delete.backward") {
for (let rule of this.UserDeleteRules) {
let left = tr.startState.doc.sliceString(toA - rule.before.left.length, toA);
let right = tr.startState.doc.sliceString(toA, toA + rule.before.right.length);
if (left === rule.before.left && right === rule.before.right) {
changes.push({
changes: {
from: toA - rule.before.left.length,
to: toA + rule.before.right.length,
insert: rule.after.left + rule.after.right
},
selection: { anchor: toA - rule.before.left.length + rule.after.left.length },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
}
// ========== delete pair symbol ============
if (changeTypeStr === "delete.backward" && this.settings.IntrinsicSymbolPairs) {
if (this.SymbolPairsMap.has(changedStr) && this.SymbolPairsMap.get(changedStr) === tr.startState.sliceDoc(toA, toA + 1)) {
changes.push({ changes: { from: fromA, to: toA + 1 }, userEvent: "EasyTyping.change" });
tr = tr.startState.update(...changes);
return tr;
}
// 处理删除代码块
let line_content = tr.startState.doc.lineAt(fromA).text;
let next_line_content = tr.startState.doc.sliceString(toA, toA + line_content.length+1);
if (/^\s*```$/.test(line_content) && '\n'+line_content==next_line_content) {
changes.push({
changes:{
from: toA-3,
to: toA+line_content.length+1,
insert: ''
},
selection: { anchor: toA - 3 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
for (let rule of this.IntrinsicDeleteRules) {
let left = tr.startState.doc.sliceString(toA - rule.before.left.length, toA);
let right = tr.startState.doc.sliceString(toA, toA + rule.before.right.length);
if (left === rule.before.left && right === rule.before.right) {
changes.push({
changes: {
from: toA - rule.before.left.length,
to: toA + rule.before.right.length,
insert: rule.after.left + rule.after.right
},
selection: { anchor: toA - rule.before.left.length + rule.after.left.length },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
}
// 处理英文输入法下输入代码块
if (changeTypeStr == 'input.type' && insertedStr =='`\n```' && this.settings.BaseObEditEnhance){
const line_content = tr.startState.doc.lineAt(fromA).text;
if (/^\s*``$/.test(line_content)){
changes.push({
changes: {from: fromA, to: toA, insert: '`\n'+line_content+'`'},
selection: { anchor: fromA + 1 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
// 通常单字输入
if ((changeTypeStr == 'input.type' || changeTypeStr == "input.type.compose") && fromA === toA && fromB + 1 === toB) {
// if (this.settings.debug) console.log("Input.type => ", insertedStr)
// =========== basic convert rules ============
// not support undo and redo
if (this.settings.BaseObEditEnhance) {
// 处理英文标点下``|的情况,光标自动跳转到中间
if (insertedStr === '`' &&
toA-tr.startState.doc.lineAt(toA).from>2 &&
tr.startState.sliceDoc(toA-1, toA) === '`'
&& tr.startState.sliceDoc(toA-2, toA-1) != '`'){
changes.push({
changes: {from:toA, insert:'`'},
selection: { anchor: toA }, userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
// 处理中文输入法下输入代码块
if (insertedStr == '·'){
let line_content = tr.startState.doc.lineAt(fromA).text;
let ch_pos = fromA - tr.startState.doc.lineAt(fromA).from;
if (/^\s*``$/.test(line_content) && ch_pos==line_content.length-1){
changes.push({
changes: {from: fromA+1, to: toA+1, insert: '`\n'+line_content+'`'},
selection: { anchor: fromA + 2 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
for (let rule of this.BasicConvRules) {
if (insertedStr != rule.before.left.charAt(rule.before.left.length - 1)) continue;
// 处理文档第 0 行
if (rule.before.left.charAt(0) === '\n' && offsetToPos(tr.state.doc, fromA).line === 0 && toB - rule.before.left.length + 1 === 0) {
let left = tr.state.doc.sliceString(toB - rule.before.left.length + 1, toB);
let right = tr.state.doc.sliceString(toB, toB + rule.before.right.length);
if (left === rule.before.left.substring(1) && right === rule.before.right) {
changes.push({
changes: {
from: toA - rule.before.left.length + 2,
to: toA + rule.before.right.length,
insert: rule.after.left.substring(1) + rule.after.right
},
selection: { anchor: toA - rule.before.left.length + rule.after.left.length + 1 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
// 通常情况处理
else {
let left = tr.state.doc.sliceString(toB - rule.before.left.length, toB);
let right = tr.state.doc.sliceString(toB, toB + rule.before.right.length);
if (left === rule.before.left && right === rule.before.right) {
changes.push({
changes: {
from: toA - rule.before.left.length + 1,
to: toA + rule.before.right.length,
insert: rule.after.left + rule.after.right
},
selection: { anchor: toA - rule.before.left.length + rule.after.left.length + 1 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
}
}
if (this.settings.FW2HWEnhance) {
for (let rule of this.FW2HWSymbolRules) {
if (insertedStr != rule.before.left.charAt(rule.before.left.length - 1)) continue;
let left = tr.state.doc.sliceString(toB - rule.before.left.length, toB);
let right = tr.state.doc.sliceString(toB, toB + rule.before.right.length);
if (left === rule.before.left && right === rule.before.right) {
changes.push({
changes: {
from: toA - rule.before.left.length + 1,
to: toA + rule.before.right.length,
insert: rule.after.left + rule.after.right
},
selection: { anchor: toA - rule.before.left.length + rule.after.left.length + 1 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
}
// ================ auto pair =================
// let PairValidSet = new Set(["", " ","\n"])
// let charAfterCursor = tr.startState.sliceDoc(toA, toA+1);
if (this.settings.IntrinsicSymbolPairs) {
for (let rule of this.IntrinsicAutoPairRulesPatch) {
if (insertedStr != rule.before.left.charAt(rule.before.left.length - 1)) continue;
let left = tr.state.doc.sliceString(toB - rule.before.left.length, toB);
let right = tr.state.doc.sliceString(toB, toB + rule.before.right.length);
if (left === rule.before.left && right === rule.before.right) {
changes.push({
changes: {
from: toA - rule.before.left.length + 1,
to: toA + rule.before.right.length,
insert: rule.after.left + rule.after.right
},
selection: { anchor: toA - rule.before.left.length + rule.after.left.length + 1 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
if (this.SymbolPairsMap.has(insertedStr) && insertedStr!="'") {
changes.push({
changes: { from: fromA, to: toA, insert: insertedStr + this.SymbolPairsMap.get(insertedStr) },
selection: { anchor: fromA + 1 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
else if (insertedStr === "'") {
let charBeforeCursor = tr.startState.sliceDoc(fromA - 1, fromA);
if (['', ' ', '\n'].includes(charBeforeCursor)) {
changes.push({
changes: { from: fromA, to: toA, insert: "''" },
selection: { anchor: fromA + 1 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
// handle autopair for "”" and "’"
if (insertedStr === '”' || insertedStr === '’') {
let tempStr = insertedStr === "”" ? "“”" : "‘’";
changes.push({
changes: { from: fromA, to: toA, insert: tempStr },
selection: { anchor: fromA + 1 },
userEvent: "EasyTyping.change"
});
tr = tr.startState.update(...changes);
return tr;
}
}
}
})
return tr;
}
async normalPaste(editor: Editor): Promise<void> {
let clipboardText = await navigator.clipboard.readText();
if (clipboardText === null || clipboardText === "") return;
editor.replaceSelection(clipboardText);
}
viewUpdatePlugin = (update: ViewUpdate) => {
if (this.onFormatArticle === true) return;
// console.log(tree);
// if (this.settings.debug) console.log("-------ViewUpdate---------");
let notSelected = true;
let mainSelection = update.view.state.selection.asSingle().main;
if (mainSelection.anchor != mainSelection.head) notSelected = false;
// ------ Debug ------------
// if (notSelected){
// // this.Formater.parseLineWithSyntaxTree(update.state, update.state.doc.lineAt(mainSelection.anchor).number);
// const tree = syntaxTree(update.state);
// let pos = mainSelection.anchor;
// let node = tree.resolve(pos, 1);
// console.log(node.name, node.from, node.to, update.state.doc.sliceString(node.from, node.to));
// }
if (!update.docChanged) return;
// console.log('------------- viewUpdatePlugin -------------')
let isExcludeFile = this.isCurrentFileExclude();
// console.log(this.CurActiveMarkdown, isExcludeFile)
// if (this.settings.debug) console.log("-----ViewUpdateWChange-----");
let tr = update.transactions[0]
let changeType = getTypeStrOfTransac(tr);
let need_update:boolean = true;
tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {
let insertedStr = inserted.sliceString(0);
let changedStr = tr.startState.doc.sliceString(fromA, toA);
if (this.settings.debug)
console.log("ViewUpdate Catch Change-> Type: " + changeType + ", ", 'fromA-toA-changedStr:', fromA, toA, changedStr, "fromB-toB-insertedStr:", fromB, toB, insertedStr);
if (changeType!='none' && getPosLineType(update.view.state, fromB) == LineType.table){
this.saved_table_viewupdate = update;
if (this.settings.debug) console.log('save table viewupdate, and skip viewUpdatePlugin');
need_update = false;
}
});
if (!need_update) return;
if (this.saved_table_viewupdate != null && changeType == 'none'){
this.viewUpdateFn(this.saved_table_viewupdate);
this.saved_table_viewupdate = null;
}
this.viewUpdateFn(update);
}
viewUpdateFn = (update: ViewUpdate) => {
if (this.onFormatArticle === true) return;
// console.log(tree);
// if (this.settings.debug) console.log("-------ViewUpdate---------");
let notSelected = true;
let mainSelection = update.view.state.selection.asSingle().main;
if (mainSelection.anchor != mainSelection.head) notSelected = false;
if (!update.docChanged) return;
let isExcludeFile = this.isCurrentFileExclude();
// console.log(this.CurActiveMarkdown, isExcludeFile)
// if (this.settings.debug) console.log("-----ViewUpdateWChange-----");
let tr = update.transactions[0]
let changeType = getTypeStrOfTransac(tr);
tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {
let insertedStr = inserted.sliceString(0);
let changedStr = tr.startState.doc.sliceString(fromA, toA);
// if (this.settings.debug)
// console.log("ViewUpdate Catch Change-> Type: " + changeType + ", ", 'fromA-toA-changedStr:', fromA, toA, changedStr, "fromB-toB-insertedStr:", fromB, toB, insertedStr);
// 找到光标位置,比较和 toB 的位置是否相同,相同且最终插入文字为中文,则为中文输入结束的状态
let cursor = update.view.state.selection.asSingle().main;
let ChineseRegExp = /^[\u4e00-\u9fa5【】·¥《》?:;’‘”“「」、。,()!——……\d]+$/;
let chineseEndFlag = changeType == "input.type.compose" &&
cursor.anchor == cursor.head && cursor.anchor === toB &&
ChineseRegExp.test(insertedStr);
if (changeType != "input.type.compose") this.compose_need_handle = false;
if (this.settings.AutoFormat && notSelected && !isExcludeFile &&
(getPosLineType(update.view.state, fromB) == LineType.text || getPosLineType(update.view.state, fromB) == LineType.table)) {
if (changeType == "input.type.compose") {
if (!/^\d$/.test(insertedStr)){
if (this.compose_need_handle == false) {
this.compose_begin_pos = fromB;
this.compose_end_pos = toB;
this.compose_need_handle = true;
}
else {
this.compose_end_pos = toB;
if (this.compose_begin_pos == this.compose_end_pos) {
this.compose_need_handle = false;
}
}
if (chineseEndFlag) this.compose_need_handle = false;
}
else{
if (this.compose_need_handle) {
this.compose_end_pos = toB;
if (this.compose_begin_pos == this.compose_end_pos) {
this.compose_need_handle = false;
}
chineseEndFlag = this.compose_need_handle?false:chineseEndFlag;
}
}
}
if (chineseEndFlag) this.compose_need_handle = false;
// console.log("Compose", chineseEndFlag, this.compose_need_handle);
}
// 判断每次输入结束
if (changeType == 'input.type' || changeType == "input" || chineseEndFlag || changeType == 'none') {
// 用户自定义转化规则
for (let rule of this.UserConvertRules) {
// if (insertedStr != rule.before.left.substring(rule.before.left.length - insertedStr.length)) continue;
let left = update.view.state.doc.sliceString(toB - rule.before.left.length, toB);
let right = update.view.state.doc.sliceString(toB, toB + rule.before.right.length);
let inserted = rule.after.left + rule.after.right;
let anchor = toB - rule.before.left.length + rule.after.left.length;
let from = toB - rule.before.left.length;
let to = toB + rule.before.right.length;
// 对文档首行规则做特殊处理
if (rule.before.left.charAt(0) === '\n' && rule.after.left.charAt(0) === '\n' &&
toB - rule.before.left.length+1==0) {
left = '\n' + left;
inserted = inserted.substring(1);
from = 0;
}
if (left === rule.before.left && right === rule.before.right) {
update.view.dispatch({
changes: {
from: from,
to: to,
insert: inserted
},
selection: { anchor: anchor },
userEvent: "EasyTyping.change"
})
return;
}
}
if (this.settings.PuncRectify && chineseEndFlag && this.compose_begin_pos > 1 &&
/[,.?!]/.test(update.view.state.doc.sliceString(this.compose_begin_pos - 1, this.compose_begin_pos))) {
let punc = update.view.state.doc.sliceString(this.compose_begin_pos - 1, this.compose_begin_pos)
if (this.compose_begin_pos > 2 &&
/[\s\n\w]/.test(update.view.state.doc.sliceString(this.compose_begin_pos - 2, this.compose_begin_pos - 1))) { }
else {
update.view.dispatch({
changes: {
from: this.compose_begin_pos - 1,
to: this.compose_begin_pos,
insert: this.halfToFullSymbolMap.get(punc)
},
// selection: { anchor: toB - rule.before.left.length + rule.after.left.length },
userEvent: "EasyTyping.change"
})
return;
}
}
// 判断格式化文本
// console.log("ready to format");
// console.log("check is exclue file:", isExcludeFile)
if (this.settings.AutoFormat && notSelected && !isExcludeFile &&
(changeType != 'none' || insertedStr=="\n")) {
if (getPosLineType(update.view.state, fromB) == LineType.text || getPosLineType(update.view.state, fromB) == LineType.table){
let changes = this.Formater.formatLineOfDoc(update.state, this.settings, fromB, cursor.anchor, insertedStr);
if (changes != null) {
update.view.dispatch(...changes[0]);
update.view.dispatch(changes[1]);
return;
}
}
}
}
if (this.settings.AutoFormat && !isExcludeFile && changeType == "input.paste" && !Platform.isIosApp) {
let updateLineStart = update.state.doc.lineAt(fromB).number;
let updateLineEnd = update.state.doc.lineAt(toB).number;
if (updateLineStart == updateLineEnd && getPosLineType(update.view.state, toB) == LineType.text) {
let changes = this.Formater.formatLineOfDoc(update.state, this.settings, fromB, toB, insertedStr);
if (changes != null) {
update.view.dispatch(...changes[0]);
// update.view.dispatch(changes[1]);
return;
}
}
else {
let all_changes: TransactionSpec[] = [];
let inserted_array = insertedStr.split("\n");
let update_start = fromB
for (let i = updateLineStart; i <= updateLineEnd; i++) {
let real_inserted = inserted_array[i - updateLineStart];
// console.log('real_inserted', real_inserted.replace(/\n/g, '\\n'))
// console.log('update_doc_text', update.state.doc.sliceString(update_start, update_start + real_inserted.length).replace(/\n/g, '\\n'))
let changes = this.Formater.formatLineOfDoc(update.state, this.settings, update_start, update_start + real_inserted.length, real_inserted);
// console.log('changes', changes)
if (changes != null) {
all_changes.push(...changes[0]);
}
update_start += real_inserted.length + 1;
}
if (all_changes.length > 0) {
update.view.dispatch(...all_changes);
return;
}
}
}
}); // iterchanges end
}
private readonly handleTabDown = (view: EditorView) => {
if (!this.settings.Tabout) return false;
let state = view.state;
let doc = state.doc
const tree = syntaxTree(state);
const s = view.state.selection;
if (s.ranges.length > 1) return false;
const pos = s.main.to;
let line = doc.lineAt(pos)
// Debug info
// console.log(line.text)
// for (let p=line.from; p<=line.to; p+=1){
// const token = tree.resolve(p, 1).name
// console.log(p-line.from, token)
// }
// return true;
// 当光标在行内代码内部
if (pos - line.from != 0 && tree.resolve(pos - 1, 1).name.contains('inline-code')) {
if (tree.resolve(pos, 1).name.contains('formatting-code_inline-code')) {
view.dispatch({
selection: { anchor: pos + 1, head: pos + 1 }
})
return true;
}
for (let p = pos + 1; p < line.to && tree.resolve(p, 1).name.contains('inline-code'); p += 1) {
// 如果找到 ` 则光标跳到其后
if (tree.resolve(p, 1).name.contains('formatting-code_inline-code')) {
view.dispatch({
selection: { anchor: p, head: p }
})
return true;
}
// 如果没找到 ` 则直接跳到行尾
if (p == line.to - 1 && tree.resolve(p, 1).name.contains('inline-code')) {
view.dispatch({
selection: { anchor: p + 1, head: p + 1 }
})
return true;
}
}
}
// 当光标在行内代码外部,并在选中文本的情况下,tab将会跳出到pairstring的外部
let selection = view.state.selection.asSingle().main;
let selected = selection.anchor != selection.head;
if (selected){
let new_anchor = selection.anchor<selection.head?selection.anchor:selection.head;
let new_head = selection.anchor>selection.head?selection.anchor:selection.head;
console.log("selection", selection.anchor, selection.head)
for (let pstr of this.TaboutPairStrs){
if (doc.sliceString(new_anchor-pstr.left.length, new_anchor) == pstr.left &&
doc.sliceString(new_head, new_head+pstr.right.length) == pstr.right){
view.dispatch({
selection: { anchor: new_head+pstr.right.length, head: new_head+pstr.right.length }
})
return true;
}
}
}
return false;
}
private readonly handleEnter = (view: EditorView) => {
// console.log("this.settings.EnterTwice", this.settings.EnterTwice)
if (!this.settings.EnterTwice) return false;
// const basePath = (this.app.vault.adapter as any).basePath
// let config_path = basePath + "/" + this.app.vault.configDir + "/app.json";
// let config = JSON.parse(fs.readFileSync(config_path, 'utf-8'))
// let strictLineBreaks = config.strictLineBreaks || false;
let strictLineBreaks = this.app.vault.getConfig("strictLineBreaks");
if (!strictLineBreaks) return false;
let state = view.state;
let doc = state.doc
const tree = syntaxTree(state);
const s = view.state.selection;
if (s.ranges.length > 1) return false;
const pos = s.main.to;
let line = doc.lineAt(pos)
// console.log(line.text, getPosLineType2(state, pos))
// for (let p=line.from; p<=line.to; p+=1){
// const token = tree.resolve(p, 1).name
// console.log(p-line.from, token)
// }
if (/^\s*$/.test(line.text)) return false;
else if (getPosLineType2(state, pos) == LineType.text) {
view.dispatch({
changes: {
from: pos,
to: pos,
insert: '\n\n'
},
selection: { anchor: pos + 2 },
userEvent: "EasyTyping.change"
})
return true;
}
return false;
}
private readonly onKeyup = (event: KeyboardEvent, view: EditorView) => {
if (this.settings.debug) {
// console.log("Keyup:", event.key, event.shiftKey, event.ctrlKey||event.metaKey);
console.log("Keyup:", event.key);
}
this.handleEndComposeTypeKey(event, view);
}
handleEndComposeTypeKey = (event: KeyboardEvent, view: EditorView) => {
if (!this.settings.TryFixChineseIM) return;
if (['Enter', 'Process', ' ', 'Shift'].contains(event.key) && this.settings.AutoFormat &&
this.compose_need_handle && !this.isCurrentFileExclude()) {
let cursor = view.state.selection.asSingle().main;
if (getPosLineType(view.state, cursor.anchor) != LineType.text) return;
if (cursor.head != cursor.anchor) return;
let insertedStr = view.state.doc.sliceString(this.compose_begin_pos, cursor.anchor);
// console.log("inserted str", insertedStr);
let changes = this.Formater.formatLineOfDoc(view.state, this.settings,
this.compose_begin_pos, cursor.anchor, insertedStr);
this.compose_need_handle = false;
if (changes != null) {
view.dispatch(...changes[0]);
view.dispatch(changes[1]);
return;
}
}
}
formatArticle = (editor: Editor, view: MarkdownView): void => {
// @ts-expect-error, not typed
const editorView = editor.cm as EditorView;
const tree = ensureSyntaxTree(editorView.state, editorView.state.doc.length);
if (!tree){
new Notice('EasyTyping: Syntax tree is not ready yet, please wait a moment and try again later!', 5000);
return;
}
this.onFormatArticle = true;
let lineCount = editor.lineCount();
let new_article = "";
let cs = editor.getCursor();
let ch = 0;
for (let i = 0; i < lineCount; i++) {
if (i != 0) new_article += '\n';
if (i != cs.line) {
new_article += this.preFormatOneLine(editor, i + 1)[0];
}
else {
let newData = this.preFormatOneLine(editor, i + 1, cs.ch);
new_article += newData[0];
ch = newData[1];
}
}
editor.setValue(new_article);
editor.setCursor({ line: cs.line, ch: ch });
this.onFormatArticle = false;
new Notice("EasyTyping: Format Article Done!");
}
isCurrentFileExclude(): boolean {
if (this.CurActiveMarkdown == "") {
let file = this.app.workspace.getActiveFile();
if (file != null && this.CurActiveMarkdown != file.path) {
this.CurActiveMarkdown = file.path;
}
else {
return true;
}
}
let excludePaths = this.settings.ExcludeFiles.split('\n');
for (let epath of excludePaths) {
if (epath.charAt(0) == '/') epath = epath.substring(1);
if (this.CurActiveMarkdown == epath) return true;
let len = epath.length;
if (this.CurActiveMarkdown.substring(0, len) == epath && (this.CurActiveMarkdown.charAt(len) == '/' || this.CurActiveMarkdown.charAt(len) == '\\' ||
epath.charAt(len - 1) == "/" || epath.charAt(len - 1) == "\\")) {
return true;
}
}
return false;
}
formatSelectionOrCurLine = (editor: Editor, view: MarkdownView): void => {
if (!editor.somethingSelected() || editor.getSelection() === '') {
let lineNumber = editor.getCursor().line;
let newLineData = this.preFormatOneLine(editor, lineNumber + 1, editor.getCursor().ch);
editor.replaceRange(newLineData[0], { line: lineNumber, ch: 0 }, { line: lineNumber, ch: editor.getLine(lineNumber).length });
editor.setSelection({ line: lineNumber, ch: newLineData[1] });
return;
}
let selection = editor.listSelections()[0];
let begin = selection.anchor.line;
let end = selection.head.line;
if (begin > end) {
let temp = begin;
begin = end;
end = temp;
}
// console.log(begin, end)
let new_lines = "";
for (let i = begin; i <= end; i++) {
if (i != begin) new_lines += '\n';
new_lines += this.preFormatOneLine(editor, i + 1)[0];
}
editor.replaceRange(new_lines, { line: begin, ch: 0 }, { line: end, ch: editor.getLine(end).length });
if (selection.anchor.line < selection.head.line) {
editor.setSelection({ line: selection.anchor.line, ch: 0 }, { line: selection.head.line, ch: editor.getLine(selection.head.line).length });
}
else {
editor.setSelection({ line: selection.anchor.line, ch: editor.getLine(selection.anchor.line).length }, { line: selection.head.line, ch: 0 });
}
}
// param: lineNumber is (1-based), 废弃函数
formatOneLine = (editor: Editor, lineNumber: number): void => {
// @ts-expect-error, not typed
const editorView = editor.cm as EditorView;
let state = editorView.state;
let line = state.doc.line(lineNumber)
if (getPosLineType(state, line.from) == LineType.text || getPosLineType(state, line.from) == LineType.table) {
let oldLine = line.text;
let newLine = this.Formater.formatLine(state, lineNumber, this.settings, oldLine.length, 0)[0];
if (oldLine != newLine) {
editor.replaceRange(newLine, { line: lineNumber - 1, ch: 0 }, { line: lineNumber - 1, ch: oldLine.length });
editor.setCursor({ line: lineNumber - 1, ch: editor.getLine(lineNumber - 1).length });
}
}