-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmarkdown-editor.ts
1103 lines (989 loc) · 39.7 KB
/
markdown-editor.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 CodeMirror, { EditorConfiguration } from 'codemirror';
import 'codemirror/mode/gfm/gfm.js';
import 'codemirror/addon/display/placeholder.js';
import _ from 'lodash-es';
import prettier from 'prettier/standalone';
import parserMarkdown from 'prettier/parser-markdown';
import {
MarkdownEditorOptionsComplete,
MarkdownEditorOptions,
FromTextareaOptionsComplete,
MdeFromTextareaOptions,
MarkdownEditorShortcuts,
DEFAULT_OPTIONS,
DEFAULT_FROM_TEXTAREA_OPTIONS,
} from './markdown-editor-options';
class MarkdownEditorBase {
protected static readonly ORDERED_LIST_PATTERN = /^(\t| )*(\d)+\.(\t| )+/;
protected static readonly UNORDERED_LIST_PATTERN = /^(\t| )*(\*|-)(\t| )+/;
protected static readonly CHECK_LIST_PATTERN = /^(\t| )*(\*|-) \[(X|x| )\](\t| )+/;
protected static readonly INDENTATION_OFFSET_PATTERN = /(?<=(^(\s)+))(\S|$)/;
protected static readonly BOLD_TOKENS = ['**', '__'];
protected static readonly ITALIC_TOKENS = ['*', '_'];
public readonly cm: CodeMirror.Editor;
protected options: MarkdownEditorOptionsComplete;
constructor(codemirror: CodeMirror.Editor, options: MarkdownEditorOptionsComplete) {
this.cm = codemirror;
this.options = options;
this.applyCodemirrorOptions();
this.applyEditorKeyMappings();
this.removeLinkClassFromImageTexts();
}
/***** Basic Editor API *****/
/**
* Toggle "bold" for each selection.
*/
public toggleBold() {
const preferred = this.options.preferredTokens.bold;
this.toggleInlineFormatting(
preferred,
MarkdownEditorBase.BOLD_TOKENS.filter((t) => t !== preferred)
);
}
/**
* Toggle "italic" for each selection.
*/
public toggleItalic() {
const preferred = this.options.preferredTokens.italic;
this.toggleInlineFormatting(
preferred,
MarkdownEditorBase.ITALIC_TOKENS.filter((t) => t !== preferred),
true
);
}
/**
* Toggle "strikethrough" for each selection.
*/
public toggleStrikethrough() {
this.toggleInlineFormatting('~~');
}
/**
* Toggle "inline code" for each selection.
*/
public toggleInlineCode() {
this.toggleInlineFormatting('`');
}
/**
* Toggle inline formatting for each selection by wrapping it with the specified token
* and unwrapping it with the specified token or one of the alternative tokens.
* @param token the token
* @param altTokens the alternative tokens
*/
protected toggleInlineFormatting(token: string, altTokens: string[] = [], preventDoubledTokenMatch = false) {
const newSelections: CodeMirror.Range[] = [];
const selections = _.cloneDeep(this.cm.listSelections());
for (let i = 0; i < selections.length; i++) {
const oldSelection = selections[i];
const newSelection = _.cloneDeep(oldSelection);
const from = oldSelection.from();
const to = oldSelection.to();
const endLineLength = this.cm.getLine(to.line).length;
const linePartBefore = this.cm.getRange({ line: from.line, ch: 0 }, from);
const linePartAfter = this.cm.getRange(to, { line: to.line, ch: endLineLength });
const prefixToken = [token, ...altTokens].find((t) => {
const escapedToken = escapeRegexChars(t);
const lookBehind = preventDoubledTokenMatch ? '(?<!' + escapedToken + ')' : '';
return linePartBefore.search(RegExp(lookBehind + escapedToken + '$')) > -1;
});
const suffixToken = [token, ...altTokens].find((t) => {
const escapedToken = escapeRegexChars(t);
const lookAhead = preventDoubledTokenMatch ? '(?!' + escapedToken + ')' : '';
return linePartAfter.search(RegExp('^' + escapedToken + lookAhead)) > -1;
});
// indicate whether the tokens before/after the selection have been inserted or deleted
let beforeShift = 0;
let afterShift = 0;
// Insert or delete tokens depending whether they exist
if (suffixToken) {
const suffixEnd = {
line: to.line,
ch: to.ch <= endLineLength - suffixToken.length ? to.ch + suffixToken.length : endLineLength,
};
this.cm.replaceRange('', to, suffixEnd, '+toggleBlock');
afterShift = -1;
} else {
this.cm.replaceRange(token, to, undefined, '+toggleBlock');
afterShift = 1;
}
if (prefixToken) {
const prefixStart = { line: from.line, ch: from.ch >= prefixToken.length ? from.ch - prefixToken.length : 0 };
this.cm.replaceRange('', prefixStart, from, '+toggleBlock');
beforeShift = -1;
} else {
this.cm.replaceRange(token, from, undefined, '+toggleBlock');
beforeShift = 1;
}
// Adjust selections to originally selected characters
if (oldSelection.empty()) newSelection.head = newSelection.anchor;
else if (from.line === to.line) newSelection.to().ch += beforeShift * token.length;
newSelection.from().ch += beforeShift * token.length;
newSelections.push(newSelection);
// Adjust all following selections to originally selected characters
for (let j = i + 1; j < selections.length; j++) {
const s = selections[j];
if (s.empty()) {
s.head = s.anchor;
} else {
if (s.head.line === from.line) s.head.ch += beforeShift * token.length;
if (s.head.line === to.line) s.head.ch += afterShift * token.length;
}
if (s.anchor.line === from.line) s.anchor.ch += beforeShift * token.length;
if (s.anchor.line === to.line) s.anchor.ch += afterShift * token.length;
else break;
}
}
this.cm.setSelections(newSelections, undefined, { origin: '+toggleBlock' });
this.cm.focus();
}
/**
* Set the specified heading level for each selected line. If `level` is 0, the heading token is removed.
* @param level the heading level
*/
public setHeadingLevel(level: 0 | 1 | 2 | 3 | 4 | 5 | 6) {
const headingToken = '#'.repeat(level) + (level === 0 ? '' : ' ');
this.replaceTokenAtLineStart((oldLineContent) => oldLineContent.replace(/^((#)*( )?)/, headingToken));
}
/**
* Increase the heading level for each selected line, i.e. make the heading smaller.
* If the current heading level is at the maximum of 6, the heading token is just removed.
* If the current heading level is 0 (no heading), the new heading level is set to 1.
*/
public increaseHeadingLevel() {
this.replaceTokenAtLineStart((oldLineContent) => {
let currentHeadingLevel = oldLineContent.search(/(?<=(^((#)+ ))).*/) - 1;
if (currentHeadingLevel < 0) currentHeadingLevel = 0;
const newLevel = currentHeadingLevel < 6 ? currentHeadingLevel + 1 : 0;
const headingToken = '#'.repeat(newLevel) + (newLevel === 0 ? '' : ' ');
return oldLineContent.replace(/^((#)*( )?)/, headingToken);
});
}
/**
* Decrease the heading level for each selected line, i.e. make the heading bigger.
* If the current heading level is at the minimum of 1, the heading token is just removed.
* If the current heading level is 0 (no heading), the new heading level is set to 6.
*/
public decreaseHeadingLevel() {
this.replaceTokenAtLineStart((oldLineContent) => {
const currentHeadingLevel = oldLineContent.search(/(?<=(^((#)+ ))).*/) - 1;
const newLevel = currentHeadingLevel > 0 ? currentHeadingLevel - 1 : 6;
const headingToken = '#'.repeat(newLevel) + (newLevel === 0 ? '' : ' ');
return oldLineContent.replace(/^((#)*( )?)/, headingToken);
});
}
/**
* Toggle "quote" for each selected line.
*/
public toggleQuote() {
this.replaceTokenAtLineStart((oldLineContent) => {
// Has selected line a quote token?
if (oldLineContent.search(/^>(\t| )*/) === -1) {
return '> ' + oldLineContent;
} else {
return oldLineContent.replace(/^>(\t| )*/, '');
}
});
}
/**
* Toggle "unordered list" for each selected line. Furthermore, a selected ordered list line is
* transformed to an unordered list.
*/
public toggleUnorderedList() {
const preferred = this.options.preferredTokens.unorderedList + ' ';
this.replaceTokenAtLineStart((oldLineContent) => {
// Has selected line a check list token?
if (oldLineContent.search(MarkdownEditorBase.CHECK_LIST_PATTERN) !== -1) {
return oldLineContent.replace(MarkdownEditorBase.CHECK_LIST_PATTERN, preferred);
}
// Has selected line an enumeration token?
if (oldLineContent.search(MarkdownEditorBase.ORDERED_LIST_PATTERN) !== -1) {
return oldLineContent.replace(MarkdownEditorBase.ORDERED_LIST_PATTERN, preferred);
}
// Has selected line a bullet point token?
if (oldLineContent.search(MarkdownEditorBase.UNORDERED_LIST_PATTERN) !== -1) {
return oldLineContent.replace(MarkdownEditorBase.UNORDERED_LIST_PATTERN, '');
} else {
return preferred + oldLineContent;
}
});
}
/**
* Toggle "ordered list" for each selected line. Furthermore, a selected unordered list line is
* transformed to an ordered list. Additionally adjusts the subsequent lines that are connected
* to the list of the selected line.
*/
public toggleOrderedList() {
this.replaceTokenAtLineStart((oldLineContent, lineNumber, indentationLevel) => {
// Has selected line an enumeration token?
if (oldLineContent.search(MarkdownEditorBase.ORDERED_LIST_PATTERN) === -1) {
const newListNumber = this.getPreviousListNumberOfLevel(lineNumber, indentationLevel) + 1;
this.processNextLinesOfOrderedList(lineNumber, newListNumber, indentationLevel);
const numberToken = newListNumber + '. ';
// Has selected line a check list token?
if (oldLineContent.search(MarkdownEditorBase.CHECK_LIST_PATTERN) !== -1) {
return oldLineContent.replace(MarkdownEditorBase.CHECK_LIST_PATTERN, numberToken);
}
// Has selected line a bullet point token?
if (oldLineContent.search(MarkdownEditorBase.UNORDERED_LIST_PATTERN) !== -1) {
return oldLineContent.replace(MarkdownEditorBase.UNORDERED_LIST_PATTERN, numberToken);
}
return numberToken + oldLineContent;
} else {
this.processNextLinesOfOrderedList(lineNumber, 0, indentationLevel);
return oldLineContent.replace(MarkdownEditorBase.ORDERED_LIST_PATTERN, '');
}
});
}
/**
* Determines the list number of the previous line with the specified `indentationLevel`
* within the same ordered list starting at the specified `baseLineNumber`.
*
* @param baseLineNumber the selected line which is toggled
* @param indentationLevel the level of indentation to search for
* @returns
* - 0, if no line is found meeting the criteria
* - the list number of the found line, otherwise
*/
protected getPreviousListNumberOfLevel(baseLineNumber: number, indentationLevel: number): number {
let prevLineNumber = baseLineNumber - 1;
let prevLine = this.cm.getLine(prevLineNumber);
while (prevLine && prevLine.search(MarkdownEditorBase.ORDERED_LIST_PATTERN) !== -1) {
const dotPos = prevLine.search(/\./);
const lineOffset = prevLine.search(MarkdownEditorBase.INDENTATION_OFFSET_PATTERN);
const prevLineIndentation = prevLine.substring(0, lineOffset);
const prevLineIndentationLevel = this.getIndentationLevel(prevLineIndentation);
if (indentationLevel === prevLineIndentationLevel) {
return +prevLine.substring(lineOffset, dotPos);
} else if (indentationLevel > prevLineIndentationLevel) {
return 0;
}
prevLine = this.cm.getLine(--baseLineNumber - 1);
}
return 0;
}
/**
* Adjust the enumeration of subsequent lines in same ordered list as line *baseLineNumber*.
* @param baseLineNumber the selected line which is toggled
* @param baseListNumber the list number of the selected line (should be 0, if list starts after selected line)
*/
protected processNextLinesOfOrderedList(
baseLineNumber: number,
baseListNumber: number,
baseIndentationLevel: number
) {
let listNumber = baseListNumber;
let nextLineNumber = baseLineNumber + 1;
let nextLine = this.cm.getLine(nextLineNumber);
while (nextLine && nextLine.search(MarkdownEditorBase.ORDERED_LIST_PATTERN) !== -1) {
const firstNonWS = nextLine.search(MarkdownEditor.INDENTATION_OFFSET_PATTERN);
const indentation = nextLine.substring(0, firstNonWS);
const indentationLevel = this.getIndentationLevel(indentation);
if (indentationLevel === baseIndentationLevel) {
const listNumberString = `${++listNumber}`;
const dotPos = nextLine.search(/\./);
this.cm.replaceRange(
listNumberString,
{ line: nextLineNumber, ch: firstNonWS },
{ line: nextLineNumber, ch: dotPos },
'+replaceTokenAtLineStart'
);
} else if (indentationLevel < baseIndentationLevel) {
break;
}
nextLine = this.cm.getLine(++nextLineNumber);
}
}
/**
* Toggle "check list" for each selected line. Furthermore, a selected (un)ordered list line is
* transformed to a check list.
*/
public toggleCheckList() {
const preferred = this.options.preferredTokens.checkList + ' [ ] ';
this.replaceTokenAtLineStart((oldLineContent) => {
// Has selected line a bullet point token?
if (oldLineContent.search(MarkdownEditorBase.CHECK_LIST_PATTERN) === -1) {
// Has selected line an enumeration token?
if (oldLineContent.search(MarkdownEditorBase.ORDERED_LIST_PATTERN) !== -1) {
return oldLineContent.replace(MarkdownEditorBase.ORDERED_LIST_PATTERN, preferred);
}
// Has selected line a check list token?
if (oldLineContent.search(MarkdownEditorBase.UNORDERED_LIST_PATTERN) !== -1) {
return oldLineContent.replace(MarkdownEditorBase.UNORDERED_LIST_PATTERN, preferred);
}
return preferred + oldLineContent;
} else {
return oldLineContent.replace(MarkdownEditorBase.CHECK_LIST_PATTERN, '');
}
});
}
/**
* Replace each selected line with the result of the callback function `replaceFn`.
* Additionally adjusts the selection boundaries to the originally selected boundaries.
* @param replaceFn callback function to the calculate the line replacements
*/
protected replaceTokenAtLineStart(
replaceFn: (oldLineContent: string, lineNumber: number, indentationLevel: number) => string
) {
const newSelections: CodeMirror.Range[] = [];
for (const sel of this.cm.listSelections()) {
const selection = _.cloneDeep(sel);
let shiftFrom = 0;
let shiftTo = 0;
for (let lineNumber = selection.from().line; lineNumber <= selection.to().line; lineNumber++) {
const oldLineContent = this.cm.getLine(lineNumber);
const firstNonWS = oldLineContent.search(MarkdownEditor.INDENTATION_OFFSET_PATTERN);
const indentation = oldLineContent.substring(0, firstNonWS);
const indentationLevel = this.getIndentationLevel(indentation);
const stripedOldLineContent = oldLineContent.substring(firstNonWS);
const newLineContent = indentation + replaceFn(stripedOldLineContent, lineNumber, indentationLevel);
this.cm.replaceRange(
newLineContent,
{ line: lineNumber, ch: 0 },
{ line: lineNumber, ch: oldLineContent.length },
'+replaceTokenAtLineStart'
);
// Set shifts for selection start and end
if (lineNumber === selection.from().line && selection.from().ch >= firstNonWS) {
shiftFrom = newLineContent.length - oldLineContent.length;
}
if (lineNumber === selection.to().line && selection.to().ch >= firstNonWS) {
shiftTo = newLineContent.length - oldLineContent.length;
}
}
// Adjust selection boundaries to originally selected boundaries
if (_.isEqual(selection.anchor, selection.from())) {
selection.anchor.ch += shiftFrom;
if (!selection.empty()) selection.head.ch += shiftTo;
} else {
selection.anchor.ch += shiftTo;
if (!selection.empty()) selection.head.ch += shiftFrom;
}
newSelections.push(selection);
}
this.cm.setSelections(newSelections, undefined, { origin: 'replaceTokenAtLineStart' });
this.cm.focus();
}
/**
* Returns the level of indentation of the specified string of `whitespaces` based on
* the current tab size configuration and the length of the specified string.
*/
protected getIndentationLevel(whitespaces: string): number {
const tabSize = this.cm.getOption('tabSize') || this.options.tabSize;
const normalizedWhiteSpaces = whitespaces.replace(/\t/gi, ' '.repeat(tabSize));
return Math.floor(normalizedWhiteSpaces.length / tabSize);
}
/**
* Wrap each selection with code block tokens, which are inserted in separate lines.
*/
public insertCodeBlock() {
const newSelections: CodeMirror.Range[] = [];
const selections = _.cloneDeep(this.cm.listSelections());
for (let i = 0; i < selections.length; i++) {
const oldSelection = selections[i];
const newSelection = _.cloneDeep(oldSelection);
const preferredToken = this.options.preferredTokens.codeBlock;
// Wrap selection with code block tokens
let currentShift = 3;
let startToken = preferredToken + '\n';
if (newSelection.from().ch > 0) {
startToken = '\n' + startToken;
currentShift++;
}
this.cm.replaceRange('\n' + preferredToken + '\n', newSelection.to(), undefined, '+insertCodeBlock');
this.cm.replaceRange(startToken, newSelection.from(), undefined, '+insertCodeBlock');
// Adjust selections to originally selected characters
const offset = newSelection.from().line === newSelection.to().line ? newSelection.from().ch : 0;
if (!newSelection.empty()) {
newSelection.to().line += currentShift - 2;
newSelection.to().ch -= offset;
} else {
// fix for edge case bug of empty selection with not synchronous anchor and head
newSelection.anchor = newSelection.head;
}
newSelection.from().line += currentShift - 2;
newSelection.from().ch = 0;
newSelections.push(newSelection);
// Adjust all following selections to originally selected characters
for (let j = i + 1; j < selections.length; j++) {
const s = selections[j];
const remainderIndex = oldSelection.to().ch;
if (s.from().line === oldSelection.to().line) {
s.from().ch -= remainderIndex;
}
if (s.to().line === oldSelection.to().line) {
s.to().ch -= remainderIndex;
}
if (!s.empty()) s.to().line += currentShift;
s.from().line += currentShift;
}
}
this.cm.setSelections(newSelections, undefined, { origin: '+insertCodeBlock' });
this.cm.focus();
}
/**
* Wrap a link template around each selection.
*/
public insertLink() {
const [before, after] = this.options.preferredTemplates.link;
this.insertInlineTemplate(before, after);
}
/**
* Wrap a image link template around each selection.
*/
public insertImageLink() {
const [before, after] = this.options.preferredTemplates.imageLink;
this.insertInlineTemplate(before, after);
}
/**
* Wrap a template around each selection with the specified `before` and `after` template parts.
* @param before the template part inserted **before** the selection start
* @param after the template part inserted **after** the selection start
*/
protected insertInlineTemplate(before: string, after: string) {
const newSelections: CodeMirror.Range[] = [];
const selections = this.cm.listSelections();
for (let i = 0; i < selections.length; i++) {
const oldSelection = selections[i];
const newSelection = _.cloneDeep(oldSelection);
// Insert template parts before and after the selection
this.cm.replaceRange(after, newSelection.to(), undefined, '+toggleBlock');
this.cm.replaceRange(before, newSelection.from(), undefined, '+toggleBlock');
// Adjust selections to originally selected characters
if (newSelection.empty()) newSelection.head = newSelection.anchor;
else newSelection.to().ch += before.length;
newSelection.from().ch += before.length;
newSelections.push(newSelection);
// Adjust all following selections to originally selected characters
for (let j = i + 1; j < selections.length; j++) {
const s = selections[j];
if (s.empty()) {
s.head = s.anchor;
} else {
if (s.head.line === oldSelection.from().line) s.head.ch += before.length;
if (s.head.line === oldSelection.to().line) s.head.ch += after.length;
}
if (s.anchor.line === oldSelection.from().line) s.anchor.ch += before.length;
if (s.anchor.line === oldSelection.to().line) s.anchor.ch += after.length;
else break;
}
}
this.cm.setSelections(newSelections, undefined, { origin: '+toggleBlock' });
this.cm.focus();
}
/**
* Insert a horizontal rule in the subsequent line of each selection.
*/
public insertHorizontalRule() {
const preferred = this.options.preferredTokens.horizontalRule;
this.insertBlockTemplateBelow(`\n${preferred}\n\n`);
}
/**
* Insert a table template with the specified number of rows and columns
* in the subsequent line of each selection.
* @param rows number of rows
* @param columns number columns
*/
public insertTable(rows?: number, columns?: number) {
const tableOptions = this.options.preferredTemplates.table;
if (typeof tableOptions === 'string') {
this.insertBlockTemplateBelow(tableOptions);
} else {
if (!rows) {
rows = tableOptions.rows;
}
if (!columns) {
columns = tableOptions.columns;
}
let template = '\n';
for (let c = 1; c <= columns; c++) {
template += `| Column ${c} `;
}
template += '|\n';
for (let c = 1; c <= columns; c++) {
template += '| -------- ';
}
template += '|\n';
for (let r = 1; r <= rows; r++) {
for (let c = 1; c <= columns; c++) {
template += '| Content ';
}
template += '|\n';
}
template += '\n';
this.insertBlockTemplateBelow(template);
}
}
/**
* Insert a block template in the subsequent line of each selection.
* The template can contain multiple lines separated with the specified `lineSeparator`.
* @param template the template
* @param lineSeparator The line separator. Default is `\n`.
*/
protected insertBlockTemplateBelow(template: string, lineSeparator = '\n') {
if (lineSeparator !== '\n') template = template.replace(RegExp(lineSeparator, 'g'), '\n');
let currentShift = 0; // indicates how many lines have been inserted
const selections = this.cm.listSelections();
for (let i = 0; i < selections.length; i++) {
const oldSelection = selections[i];
const newSelection = _.cloneDeep(oldSelection);
// Shift selection back to correct position in respect to previously inserted lines
if (newSelection.empty()) newSelection.head = newSelection.anchor;
else newSelection.to().line += currentShift;
newSelection.from().line += currentShift;
const toLineNumber = newSelection.to().line;
const toLineLength = this.cm.getLine(toLineNumber).length;
const toLineEnd: CodeMirror.Position = { line: toLineNumber, ch: toLineLength };
if (toLineLength > 0) {
template = '\n' + template;
}
currentShift += template.match(/\n/g)?.length || 0;
// Insert template in the subsequent line of the selection
this.cm.replaceRange(template, toLineEnd, undefined, '+insertHorizontalRule');
}
this.cm.focus();
}
/**
* Open a Markdown Guide in a new tab.
*/
public openMarkdownGuide() {
window.open(this.options.markdownGuideUrl, '_blank');
}
/***** Extended Editor API *****/
/**
* Undo one edit. Shortcut for `Codemirror.undo()`.
*/
public undo() {
this.cm.undo();
}
/**
* Redo one edit. Shortcut for `Codemirror.redo()`.
*/
public redo() {
this.cm.redo();
}
/**
* Toggle the editor's rich-text mode. If off, there is no markdown styling inside the editor.
*/
public toggleRichTextMode() {
const currentMode = this.cm.getOption('mode');
if (currentMode === 'gfm' || (typeof currentMode !== 'string' && currentMode?.name === 'gfm')) {
this.cm.setOption('mode', '');
} else {
this.cm.setOption('mode', this.getGfmMode());
}
}
/**
* Start a file download containing the editor content as plain text.
* The name of the file is either `fileName` if specified, or the default `downloadFileName`
* specified in the Markdown Editor options.
* @param fileName The name of the downloaded file. Preferred over `options.downloadFileName`.
*/
public downloadAsFile(fileName?: string) {
const data = new Blob([this.getContent()], { type: 'text/plain' });
const url = window.URL.createObjectURL(data);
const a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', fileName || this.options.downloadFileNameGenerator());
a.click();
}
/**
* Import content from a file. Reads the content of `file` if specified, or opens the browser's
* file selection dialog and reads the content of the user-selected file.
* @param file The file to import the content from.
*/
public importFromFile(file?: File) {
const readFile = (file: File) => {
const reader = new FileReader();
reader.onload = (event) => this.setContent(((event.target as FileReader).result || '') as string);
reader.readAsText(file);
};
if (file) {
readFile(file);
} else {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', '.txt, .text, .markdown, .mdown, .mkdn, .md, .mkd, .mdwn, .mdtxt, .mdtext');
input.onchange = (event) => {
const files = (event?.target as HTMLInputElement).files;
if (files) {
readFile(files[0]);
}
};
input.click();
}
}
/**
* Formats the content using Prettier's Markdown parser.
*/
public formatContent() {
this.setContent(
prettier.format(this.getContent(), {
parser: 'markdown',
plugins: [parserMarkdown],
})
);
}
/***** Developer API *****/
/**
* Get the editor's content with the specified line break format.
* @param lineSeparator The line break format. Default is `\n`.
*/
public getContent(lineSeparator = '\n'): string {
return this.cm.getValue(lineSeparator);
}
/**
* Get the editor's content with the lines as array.
*/
public getContentPerLine(): string[] {
return this.cm.getValue().split('\n');
}
/**
* Set the editor's content with the specified line break format.
* @param content The content.
* @param lineSeparator The line break format. Default is `\n`.
*/
public setContent(content: string, lineSeparator = '\n') {
if (lineSeparator !== '\n') content = content.replace(RegExp(lineSeparator, 'g'), '\n');
this.cm.setValue(content);
}
/**
* Get the editor's content with the lines as array.
*/
public setContentPerLine(content: string[]) {
this.cm.setValue(content.join('\n'));
}
/**
* Focus the editor. Shortcut for `Codemirror.focus()`.
*/
public focus() {
this.cm.focus();
}
/**
* Get the number of characters in the document.
*/
public getCharacterCount() {
// eslint-disable-next-line no-control-regex
return this.cm.getValue().replace(RegExp('\n', 'gi'), '').length;
}
/**
* Get the number of words in the document.
*/
public getWordCount() {
const content = this.cm.getValue();
let s = content.replace(/(^\s*)|(\s*$)/gi, ''); // Trim left and right
s = s.replace(/\t/gi, ' '); // Replace tabs by single whitespace
s = s.replace(/\n/gi, ' '); // Replace line breaks by single whitespace
s = s.replace(/[ ]{2,}/gi, ' '); // Reduce multiple whitespaces to a single one
let split = s.split(' '); // Split string by whitespaces
split = split.filter((x) => !/^\W+$/.test(x)); // Filter out non-alphanumeric words
return s === '' ? 0 : split.length;
}
/**
* Get the current cursor position as a `{line, ch}` object.
* Shortcut for `Codemirror.getCursor()`.
*/
public getCursorPos() {
return this.cm.getCursor();
}
/**
* Returns whether the document has been modified.
* Inverted shortcut for `Codemirror.isClean()`
*/
public isDirty() {
return !this.cm.isClean();
}
/**
* Check if text at current cursor position has specified token type
* like returned by `CodeMirror.getTokenTypeAt()`.
* @param token
*/
public hasTokenAtCursorPos(token: string): boolean {
return this.cm.getTokenTypeAt(this.getCursorPos())?.split(' ').includes(token) || false;
}
/**
* Get the type of list in the specified line. Return undefined, if the line contains no list token.
* @param lineNumber
*/
public getListTypeOfLine(lineNumber: number): 'unordered' | 'ordered' | 'check' | undefined {
const line = this.cm.getLine(lineNumber);
if (MarkdownEditorBase.CHECK_LIST_PATTERN.test(line)) return 'check';
if (MarkdownEditorBase.UNORDERED_LIST_PATTERN.test(line)) return 'unordered';
if (MarkdownEditorBase.ORDERED_LIST_PATTERN.test(line)) return 'ordered';
return undefined;
}
/**
* Get the action shortcuts effectively applied to the editor.
*
* This might be a mix of custom shortcuts
* and default shortcuts as specified in `DEFAULT_OPTIONS`.
*/
public getShortcuts(): MarkdownEditorShortcuts {
return this.options.shortcuts;
}
/**
* Add the specified keyboard shortcut to the specified action function.
*
* **Note:** This does **not** replace an existing shortcut to the specified action,
* but only **adds** it. In case of an already existing shortcut, the result will be
* two distinct shortcuts to the same function. However, you can use `removeShortcut()`
* to remove the old one.
* @param hotkeys the hotkeys string as required by Codemirror
* @param action the action function
* @see https://codemirror.net/doc/manual.html#keymaps
*/
public addShortcut(hotkeys: string, action: () => void) {
const extraKeys = (this.cm.getOption('extraKeys') || {}) as CodeMirror.KeyMap;
let shortcut: string;
if (isMac()) {
shortcut = hotkeys.replace('Ctrl', 'Cmd');
} else {
shortcut = hotkeys.replace('Cmd', 'Ctrl');
}
extraKeys[shortcut] = action;
this.cm.setOption('extraKeys', extraKeys);
}
/**
* Remove the specified keyboard shortcut.
*
* @param hotkeys the hotkeys string as required by Codemirror
* @see https://codemirror.net/doc/manual.html#keymaps
*/
public removeShortcut(hotkeys: string) {
const extraKeys = (this.cm.getOption('extraKeys') || {}) as CodeMirror.KeyMap;
let shortcut: string;
if (isMac()) {
shortcut = hotkeys.replace('Ctrl', 'Cmd');
} else {
shortcut = hotkeys.replace('Cmd', 'Ctrl');
}
delete extraKeys[shortcut];
this.cm.setOption('extraKeys', extraKeys);
}
/***** Markdown Editor Options *****/
/**
* Overwrites current options with specified options.
* Options that are not included in specified `options` will not be modified.
* @param options the set of options that shall be changed
*/
public setOptions(options: MarkdownEditorOptions | undefined) {
if (!options) return;
this.options = _.merge(this.options, options);
this.applyCodemirrorOptions();
this.applyEditorKeyMappings();
}
/**
* Apply codemirror-specific options that are specified in `this.options`.
*/
protected applyCodemirrorOptions() {
this.cm.setOption('autofocus', this.options.autofocus);
this.cm.setOption(
'configureMouse' as keyof EditorConfiguration,
this.options.multipleCursors ? undefined : () => ({ addNew: false })
);
this.cm.setOption('lineNumbers', this.options.lineNumbers);
this.cm.setOption('lineWrapping', this.options.lineWrapping);
// IDE fails to recognize addon types since they are declared for module '../../' instead of 'codemirror'
this.cm.setOption('placeholder' as any, this.options.placeholder);
this.cm.setOption('readOnly', this.options.disabled);
this.cm.setOption('tabSize', this.options.tabSize);
this.cm.setOption('theme', this.options.themes.join(' '));
const mode = this.cm.getOption('mode');
if (this.options.richTextMode) {
if (typeof mode !== 'string' && mode?.name !== 'gfm') {
this.cm.setOption('mode', this.getGfmMode());
}
} else {
this.cm.setOption('mode', '');
}
}
/**
* Apply the key map for markdown editor actions specified in `this.options.shortcuts`
* to the Codemirror editor instance.
*/
protected applyEditorKeyMappings() {
if (this.options.shortcutsEnabled === 'none') {
this.cm.setOption('extraKeys', {});
return;
}
const bindings: { [key in keyof Required<MarkdownEditorShortcuts>]: () => void } = {
increaseHeadingLevel: () => this.increaseHeadingLevel(),
decreaseHeadingLevel: () => this.decreaseHeadingLevel(),
toggleBold: () => this.toggleBold(),
toggleItalic: () => this.toggleItalic(),
toggleStrikethrough: () => this.toggleStrikethrough(),
toggleUnorderedList: () => this.toggleUnorderedList(),
toggleOrderedList: () => this.toggleOrderedList(),
toggleCheckList: () => this.toggleCheckList(),
toggleQuote: () => this.toggleQuote(),
insertLink: () => this.insertLink(),
insertImageLink: () => this.insertImageLink(),
insertTable: () => this.insertTable(),
insertHorizontalRule: () => this.insertHorizontalRule(),
toggleInlineCode: () => this.toggleInlineCode(),
insertCodeBlock: () => this.insertCodeBlock(),
openMarkdownGuide: () => this.openMarkdownGuide(),
toggleRichTextMode: () => this.toggleRichTextMode(),
downloadAsFile: () => this.downloadAsFile(),
importFromFile: () => this.importFromFile(),
formatContent: () => this.formatContent(),
};
const shortcuts = this.options.shortcuts;
const extraKeys = {} as CodeMirror.KeyMap;
for (const [key, value] of Object.entries(shortcuts)) {
if (value) {
let shortcut: string;
if (isMac()) {
shortcut = value.replace('Ctrl', 'Cmd');
} else {
shortcut = value.replace('Cmd', 'Ctrl');
}
if (extraKeys[shortcut]) {
console.warn(
`Caution: Duplicate keybinding! Shortcut '${shortcut}' was already ` +
`bound to action '${extraKeys[shortcut].toString().slice(27, -5)}' ` +
`and is now overridden with action '${key}'.`
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} else if ((CodeMirror as any).keyMap.default[shortcut]) {
console.warn(
`Caution: Duplicate keybinding! Shortcut '${shortcut}' was already ` +
// eslint-disable-next-line @typescript-eslint/no-explicit-any
`bound to native CodeMirror action '${(CodeMirror as any).keyMap.default[shortcut]}' ` +
`and is now overridden with action '${key}'.`
);
}
extraKeys[shortcut] = bindings[key as keyof MarkdownEditorShortcuts];
}
}
// if (!(_.matches(this.cm.getOption('extraKeys'))(extraKeys)))
this.cm.setOption('extraKeys', extraKeys);
}
/***** Private methods *****/
/**
* Create the GFM mode object. It includes some adjustments for the default
* theme to use Codemirror's default markup styling while always providing
* expressive class names for the tokens.
*/
private getGfmMode() {
const isDefaultTheme = this.options.themes === undefined || this.options.themes.includes('default');
return {
name: 'gfm',
tokenTypeOverrides: {
header: 'header',
code: 'code' + (isDefaultTheme ? ' comment' : ''),
quote: 'quote',
list1: 'list list-level-1' + (isDefaultTheme ? ' variable-2' : ''),
list2: 'list list-level-2' + (isDefaultTheme ? ' variable-3' : ''),
list3: 'list list-level-gt-2' + (isDefaultTheme ? ' keyword' : ''),
hr: 'hr',
image: 'image',
imageAltText: 'image-alt-text' + (isDefaultTheme ? ' string' : ''),
imageMarker: 'image-marker',
formatting: 'token',
linkInline: 'link link-inline',
linkEmail: 'link link-email',
linkText: 'link-text' + (isDefaultTheme ? ' string' : ''),
linkHref: 'link link-href',
em: 'em',
strong: 'strong',
strikethrough: 'strikethrough',
emoji: 'emoji' + (isDefaultTheme ? ' builtin' : ''),
},
highlightFormatting: this.options.highlightTokens,
};
}
/**
* Remove the `.cm-link` class from images' alt texts because text is not a link.
* This has been hardcoded to Codemirror's Markdown mode and thus cannot be changed
* without compiling Codemirror ourselves within this project, which is not the
* desired way so far.