generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathrules.ts
1259 lines (1169 loc) · 36.8 KB
/
rules.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 dedent from 'ts-dedent';
import moment from 'moment';
import {escapeDollarSigns, formatYAML, headerRegex, ignoreCodeBlocksAndYAML, initYAML, insert, loadYAML, moveFootnotesToEnd, yamlRegex} from './utils';
import {Option, BooleanOption, MomentFormatOption, TextOption, DropdownOption, DropdownRecord, TextAreaOption} from './option';
export type Options = { [optionName: string]: any };
type ApplyFunction = (text: string, options?: Options) => string;
export interface LinterSettings {
ruleConfigs: {
[ruleName: string]: Options;
};
lintOnSave: boolean;
displayChanged: boolean;
foldersToIgnore: string[];
}
/* eslint-disable no-unused-vars */
enum RuleType {
YAML = 'YAML',
HEADING = 'Heading',
FOOTNOTE = 'Footnote',
CONTENT = 'Content',
SPACING = 'Spacing',
}
/* eslint-enable no-unused-vars */
const RuleTypeOrder = Object.values(RuleType);
/**
* Returns a list of ignored rules in the YAML frontmatter of the text.
* @param {string} text The text to parse
* @return {string[]} The list of ignored rules
*/
export function getDisabledRules(text: string): string[] {
const yaml = text.match(yamlRegex);
if (!yaml) {
return [];
}
const yaml_text = yaml[1];
const parsed_yaml = loadYAML(yaml_text);
if (!Object.prototype.hasOwnProperty.call(parsed_yaml, 'disabled rules')) {
return [];
}
let disabled_rules = (parsed_yaml as { 'disabled rules': string[] | string; })['disabled rules'];
if (!disabled_rules) {
return [];
}
if (typeof disabled_rules === 'string') {
disabled_rules = [disabled_rules];
}
if (disabled_rules.includes('all')) {
return rules.map((rule) => rule.alias());
}
return disabled_rules;
}
/** Class representing a rule */
export class Rule {
public name: string;
public description: string;
public type: RuleType;
public options: Array<Option>;
public apply: ApplyFunction;
public examples: Array<Example>;
/**
* Create a rule
* @param {string} name - The name of the rule
* @param {string} description - The description of the rule
* @param {RuleType} type - The type of the rule
* @param {ApplyFunction} apply - The function to apply the rule
* @param {Array<Example>} examples - The examples to be displayed in the documentation
* @param {Array<Option>} [options=[]] - The options of the rule to be displayed in the documentation
*/
constructor(
name: string,
description: string,
type: RuleType,
apply: ApplyFunction,
examples: Array<Example>,
options: Array<Option> = []) {
this.name = name;
this.description = description;
this.type = type;
this.apply = apply;
this.examples = examples;
options.unshift(new BooleanOption(this.description, '', false));
for (const option of options) {
option.ruleName = name;
}
this.options = options;
}
public alias(): string {
return this.name.replace(/ /g, '-').toLowerCase();
}
public getDefaultOptions() {
const options: { [optionName: string]: any } = {};
for (const option of this.options) {
options[option.name] = option.defaultValue;
}
return options;
}
public getOptions(settings: LinterSettings) {
return settings.ruleConfigs[this.name];
}
public getURL(): string {
const url = 'https://github.com/platers/obsidian-linter/blob/master/docs/rules.md';
return url + '#' + this.alias();
}
public enabledOptionName(): string {
return this.options[0].name;
}
}
/** Class representing an example of a rule */
export class Example {
public description: string;
public options: Options;
public before: string;
public after: string;
/**
* Create an example
* @param {string} description - The description of the example
* @param {string} before - The text before the rule is applied
* @param {string} after - The text after the rule is applied
* @param {object} options - The options of the example
*/
constructor(description: string, before: string, after: string, options: Options = {}) {
this.description = description;
this.options = options;
this.before = before;
this.after = after;
}
}
export const rules: Rule[] = [
new Rule(
'Trailing spaces',
'Removes extra spaces after every line.',
RuleType.SPACING,
(text: string, options = {}) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
if (options['Two Space Linebreak'] === false) {
return text.replace(/[ \t]+$/gm, '');
} else {
text = text.replace(/(\S)[ \t]$/gm, '$1'); // one whitespace
text = text.replace(/(\S)[ \t]{3,}$/gm, '$1'); // three or more whitespaces
text = text.replace(/(\S)( ?\t\t? ?)$/gm, '$1'); // two whitespaces with at least one tab
return text;
}
});
},
[
new Example(
'Removes trailing spaces and tabs.',
dedent`
# H1
Line with trailing spaces and tabs. `, // eslint-disable-line no-tabs
dedent`
# H1
Line with trailing spaces and tabs.`,
),
new Example(
'With `Two Space Linebreak = true`',
dedent`
# H1
Line with trailing spaces and tabs. `,
dedent`
# H1
Line with trailing spaces and tabs. `,
{'Two Space Linebreak': true},
),
],
[
new BooleanOption('Two Space Linebreak', 'Ignore two spaces followed by a line break ("Two Space Rule").', false),
],
),
new Rule(
'Heading blank lines',
'All headings have a blank line both before and after (except where the heading is at the beginning or end of the document).',
RuleType.SPACING,
(text: string, options = {}) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
if (options['Bottom'] === false) {
text = text.replace(/(^#+\s.*)\n+/gm, '$1\n'); // trim blank lines after headings
text = text.replace(/\n+(#+\s.*)/g, '\n\n$1'); // trim blank lines before headings
} else {
text = text.replace(/^(#+\s.*)/gm, '\n\n$1\n\n'); // add blank line before and after headings
text = text.replace(/\n+(#+\s.*)/g, '\n\n$1'); // trim blank lines before headings
text = text.replace(/(^#+\s.*)\n+/gm, '$1\n\n'); // trim blank lines after headings
}
text = text.replace(/^\n+(#+\s.*)/, '$1'); // remove blank lines before first heading
text = text.replace(/(#+\s.*)\n+$/, '$1'); // remove blank lines after last heading
return text;
});
},
[
new Example(
'Headings should be surrounded by blank lines',
dedent`
# H1
## H2
# H1
line
## H2
`,
dedent`
# H1
## H2
# H1
line
## H2
`,
),
new Example(
'With `Bottom=false`',
dedent`
# H1
line
## H2
# H1
line
`,
dedent`
# H1
line
## H2
# H1
line
`,
{Bottom: false},
),
],
[
new BooleanOption('Bottom', 'Insert a blank line after headings', true),
],
),
new Rule(
'Paragraph blank lines',
'All paragraphs should have exactly one blank line both before and after.',
RuleType.SPACING,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
text = text.replace(/\n+([a-zA-Z].*)/g, '\n\n$1'); // trim blank lines before
text = text.replace(/(^[a-zA-Z].*)\n+/gm, '$1\n\n'); // trim blank lines after
text = text.replace(/^\n+([a-zA-Z].*)/, '$1'); // remove blank lines before first line
return text;
});
},
[
new Example(
'Paragraphs should be surrounded by blank lines',
dedent`
# H1
Newlines are inserted.
A paragraph is a line that starts with a letter.
`,
dedent`
# H1
Newlines are inserted.
A paragraph is a line that starts with a letter.
`,
),
],
),
new Rule(
`Space after list markers`,
'There should be a single space after list markers and checkboxes.',
RuleType.SPACING,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
// Space after marker
text = text.replace(/^(\s*\d+\.|\s*[-+*])[^\S\r\n]+/gm, '$1 ');
// Space after checkbox
return text.replace(/^(\s*\d+\.|\s*[-+*]\s+\[[ xX]\])[^\S\r\n]+/gm, '$1 ');
});
},
[
new Example(
'',
dedent`
1. Item 1
2. Item 2
- [ ] Item 1
- [x] Item 2
\t- [ ] Item 3
`,
dedent`
1. Item 1
2. Item 2
- [ ] Item 1
- [x] Item 2
\t- [ ] Item 3
`,
),
],
),
new Rule(
'Compact YAML',
'Removes leading and trailing blank lines in the YAML front matter.',
RuleType.SPACING,
(text: string) => {
return formatYAML(text, (text) => {
text = text.replace(/^---\n+/, '---\n');
text = text.replace(/\n+---/, '\n---');
return text;
});
},
[
new Example(
'',
dedent`
---
date: today
---
`,
dedent`
---
date: today
---
`,
),
],
),
new Rule(
'Consecutive blank lines',
'There should be at most one consecutive blank line.',
RuleType.SPACING,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
return text.replace(/\n{2,}/g, '\n\n');
});
},
[
new Example(
'',
dedent`
Some text
Some more text
`,
dedent`
Some text
Some more text
`,
),
],
),
new Rule(
'Convert Spaces to Tabs',
'Converts leading spaces to tabs.',
RuleType.SPACING,
(text: string, options = {}) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
const tabsize = String(options['Tabsize']);
const tabsize_regex = new RegExp('^(\t*) {' + String(tabsize) + '}', 'gm');
while (text.match(tabsize_regex) != null) {
text = text.replace(tabsize_regex, '$1\t');
}
return text;
});
},
/* eslint-disable no-mixed-spaces-and-tabs, no-tabs */
[
new Example(
'Converting spaces to tabs with `tabsize = 3`',
dedent`
- text with no indention
- text indented with 3 spaces
- text with no indention
- text indented with 6 spaces
`,
dedent`
- text with no indention
\t- text indented with 3 spaces
- text with no indention
\t\t- text indented with 6 spaces
`,
{Tabsize: '3'},
),
],
/* eslint-enable no-mixed-spaces-and-tabs, no-tabs */
[
new TextOption('Tabsize', 'Number of spaces that will be converted to a tab', '4'),
],
),
new Rule(
'Line Break at Document End',
'Ensures that there is exactly one line break at the end of a document.',
RuleType.SPACING,
(text: string) => {
text = text.replace(/\n+$/g, '');
text += '\n';
return text;
},
[
new Example(
'Appending a line break to the end of the document.',
dedent`
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
`,
dedent`
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
`,
),
new Example(
'Removing trailing line breaks to the end of the document, except one.',
dedent`
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
`,
dedent`
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
`,
),
],
),
// Content rules
new Rule(
'Remove Multiple Spaces',
'Removes two or more consecutive spaces. Ignores spaces at the beginning and ending of the line. ',
RuleType.CONTENT,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
return text.replace(/\b {2,}\b/g, ' ');
});
},
[
new Example(
'Removing double and triple space.',
dedent`
Lorem ipsum dolor sit amet.
`,
dedent`
Lorem ipsum dolor sit amet.
`,
),
],
),
new Rule(
'Remove Hyphenated Line Breaks',
'Removes hyphenated line breaks. Useful when pasting text from textbooks.',
RuleType.CONTENT,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
return text.replace(/\b[-‐] \b/g, '');
});
},
[
new Example(
'Removing hyphenated line breaks.',
dedent`
This text has a linebr‐ eak.
`,
dedent`
This text has a linebreak.
`,
),
],
),
new Rule(
'Remove Consecutive List Markers',
'Removes consecutive list markers. Useful when copy-pasting list items.',
RuleType.CONTENT,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
return text.replace(/^([ |\t]*)- - \b/gm, '$1- ');
});
},
[
new Example(
'Removing consecutive list markers.',
dedent`
- item 1
- - copypasted item A
- item 2
- indented item
- - copypasted item B
`,
dedent`
- item 1
- copypasted item A
- item 2
- indented item
- copypasted item B
`,
),
],
),
new Rule(
'Remove Empty List Markers',
'Removes empty list markers, i.e. list items without content.',
RuleType.CONTENT,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
return text.replace(/^\s*-\s*\n/gm, '');
});
},
[
new Example(
'Removes empty list markers.',
dedent`
- item 1
-
- item 2
`,
dedent`
- item 1
- item 2
`,
),
],
),
new Rule(
'Proper Ellipsis',
'Replaces three consecutive dots with an ellipsis.',
RuleType.CONTENT,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
return text.replaceAll('...', '…');
});
},
[
new Example(
'Replacing three consecutive dots with an ellipsis.',
dedent`
Lorem (...) Impsum.
`,
dedent`
Lorem (…) Impsum.
`,
),
],
),
// YAML rules
new Rule(
'Format Tags in YAML',
'Remove Hashtags from tags in the YAML frontmatter, as they make the tags there invalid.',
RuleType.YAML,
(text: string) => {
return formatYAML(text, (text) => {
return text.replace(/\ntags:(.*?)(?=\n(?:[A-Za-z-]+?:|---))/s, function(tagsYAML) {
return tagsYAML.replaceAll('#', '');
});
});
},
[
new Example(
'Format Tags in YAML frontmatter',
dedent`
---
tags: #one #two #three #nested/four/five
---
`,
dedent`
---
tags: one two three nested/four/five
---
`,
),
new Example(
'Format tags in array',
dedent`
---
tags: [#one #two #three]
---
`,
dedent`
---
tags: [one two three]
---
`,
),
new Example(
'Format tags in list',
dedent`
---
tags:
- #tag1
- #tag2
---
`,
dedent`
---
tags:
- tag1
- tag2
---
`,
),
],
),
new Rule(
'Insert YAML attributes',
'Inserts the given YAML attributes into the YAML frontmatter. Put each attribute on a single line.',
RuleType.YAML,
(text: string, options = {}) => {
text = initYAML(text);
return formatYAML(text, (text) => {
const insert_lines = String(options['Text to insert']).split('\n').reverse();
const parsed_yaml = loadYAML(text.match(yamlRegex)[1]);
for (const line of insert_lines) {
const key = line.split(':')[0];
if (!Object.prototype.hasOwnProperty.call(parsed_yaml, key)) {
text = text.replace(/^---\n/, escapeDollarSigns(`---\n${line}\n`));
}
}
return text;
});
},
[
new Example(
'Insert static lines into YAML frontmatter. Text to insert: `aliases:\ntags: doc\nanimal: dog`',
dedent`
---
animal: cat
---
`,
dedent`
---
aliases:
tags: doc
animal: cat
---
`,
{'Text to insert': 'aliases:\ntags: doc\nanimal: dog'},
),
],
[
new TextAreaOption('Text to insert', 'Text to insert into the YAML frontmatter', 'aliases: \ntags: '),
],
),
new Rule(
'YAML Timestamp',
'Keep track of the date the file was last edited in the YAML front matter. Gets dates from file metadata.',
RuleType.YAML,
(text: string, options = {}) => {
text = initYAML(text);
return formatYAML(text, (text) => {
const created_match_str = `\n${options['Date Created Key']}.*\n`;
const created_match = new RegExp(created_match_str);
if (options['Date Created'] === true && !created_match.test(text)) {
const yaml_end = text.indexOf('\n---');
const formatted_date = moment(options['metadata: file created time']).format(options['Format']);
text = insert(text, yaml_end, `\n${options['Date Created Key']}: ${formatted_date}`);
}
if (options['Date Modified'] === true) {
const modified_match_str = `\n${options['Date Modified Key']}.*\n`;
const modified_match = new RegExp(modified_match_str);
const formatted_date = moment(options['metadata: file modified time']).format(options['Format']);
const modified_date_line = `\n${options['Date Modified Key']}: ${formatted_date}`;
if (modified_match.test(text)) {
text = text.replace(modified_match, escapeDollarSigns(modified_date_line) + '\n');
text = text.replace(/\ndate updated:.*\n/, escapeDollarSigns(modified_date_line) + '\n'); // for backwards compatibility
} else {
const yaml_end = text.indexOf('\n---');
text = insert(text, yaml_end, modified_date_line);
}
}
return text;
});
},
[
new Example(
'Adds a header with the date.',
dedent`
# H1
`,
dedent`
---
date created: Wednesday, January 1st 2020, 12:00:00 am
date modified: Thursday, January 2nd 2020, 12:00:00 am
---
# H1
`,
{
'metadata: file created time': '2020-01-01T00:00:00-00:00',
'metadata: file modified time': '2020-01-02T00:00:00-00:00',
},
),
new Example(
'dateCreated option is false',
dedent`
# H1
`,
dedent`
---
date modified: Wednesday, January 1st 2020, 12:00:00 am
---
# H1
`,
{
'Date Created': false,
'metadata: file created time': '2020-01-01T00:00:00-00:00',
'metadata: file modified time': '2020-01-01T00:00:00-00:00',
},
),
new Example(
'Date Created Key is set',
dedent`
# H1
`,
dedent`
---
created: Wednesday, January 1st 2020, 12:00:00 am
---
# H1
`,
{
'Date Created': true,
'Date Modified': false,
'Date Created Key': 'created',
'metadata: file created time': '2020-01-01T00:00:00-00:00',
},
),
new Example(
'Date Modified Key is set',
dedent`
# H1
`,
dedent`
---
modified: Wednesday, January 1st 2020, 12:00:00 am
---
# H1
`,
{
'Date Created': false,
'Date Modified': true,
'Date Modified Key': 'modified',
'metadata: file modified time': '2020-01-01T00:00:00-00:00',
},
),
],
[
new BooleanOption('Date Created', 'Insert the file creation date', true),
new TextOption('Date Created Key', 'Which YAML key to use for creation date', 'date created'),
new BooleanOption('Date Modified', 'Insert the date the file was last modified', true),
new TextOption('Date Modified Key', 'Which YAML key to use for modification date', 'date modified'),
new MomentFormatOption('Format', 'Date format', 'dddd, MMMM Do YYYY, h:mm:ss a'),
],
),
new Rule(
'YAML Title',
'Inserts the title of the file into the YAML frontmatter. Gets the title from the first H1 or filename.',
RuleType.YAML,
(text: string, options = {}) => {
text = initYAML(text);
let title = ignoreCodeBlocksAndYAML(text, (text) => {
const result = text.match(/^#\s+(.*)/m);
if (result) {
return result[1];
}
return '';
});
title = title || options['metadata: file name'];
return formatYAML(text, (text) => {
const title_match_str = `\n${options['Title Key']}.*\n`;
const title_match = new RegExp(title_match_str);
if (title_match.test(text)) {
text = text.replace(title_match, escapeDollarSigns(`\n${options['Title Key']}: ${title}\n`));
} else {
const yaml_end = text.indexOf('\n---');
text = insert(text, yaml_end, `\n${options['Title Key']}: ${title}`);
}
return text;
},
);
},
[
new Example(
'Adds a header with the title from heading.',
dedent`
# Obsidian
`,
dedent`
---
title: Obsidian
---
# Obsidian
`,
{
'metadata: file name': 'Filename',
},
),
new Example(
'Adds a header with the title.',
dedent`
`,
dedent`
---
title: Filename
---
`,
{
'metadata: file name': 'Filename',
},
),
],
[
new TextOption('Title Key', 'Which YAML key to use for title', 'title'),
],
),
// Heading rules
new Rule(
'Header Increment',
'Heading levels should only increment by one level at a time',
RuleType.HEADING,
(text: string) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
const lines = text.split('\n');
let lastLevel = 0; // level of last header processed
let decrement = 0; // number of levels to decrement following headers
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(headerRegex);
if (!match) {
continue;
}
let level = match[2].length - decrement;
if (level > lastLevel + 1) {
decrement += level - (lastLevel + 1);
level = lastLevel + 1;
}
lines[i] = lines[i].replace(headerRegex, `$1${'#'.repeat(level)}$3$4`);
lastLevel = level;
}
return lines.join('\n');
});
},
[
new Example(
'',
dedent`
# H1
### H3
### H3
#### H4
###### H6
We skipped a 2nd level heading
`,
dedent`
# H1
## H3
## H3
### H4
#### H6
We skipped a 2nd level heading
`,
),
],
),
new Rule(
'File Name Heading',
'Inserts the file name as a H1 heading if no H1 heading exists.',
RuleType.HEADING,
(text: string, options = {}) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
// check if there is a H1 heading
const hasH1 = text.match(/^#\s.*/m);
if (hasH1) {
return text;
}
const fileName = options['metadata: file name'];
// insert H1 heading after front matter
let yaml_end = text.indexOf('\n---');
yaml_end = yaml_end == -1 || !text.startsWith('---\n') ? 0 : yaml_end + 5;
return insert(text, yaml_end, `# ${fileName}\n`);
});
},
[
new Example(
'Inserts an H1 heading',
dedent`
This is a line of text
`,
dedent`
# File Name
This is a line of text
`,
{'metadata: file name': 'File Name'},
),
new Example(
'Inserts heading after YAML front matter',
dedent`
---
title: My Title
---
This is a line of text
`,
dedent`
---
title: My Title
---
# File Name
This is a line of text
`,
{'metadata: file name': 'File Name'},
),
],
),
new Rule(
'Capitalize Headings',
'Headings should be formatted with capitalization',
RuleType.HEADING,
(text: string, options = {}) => {
return ignoreCodeBlocksAndYAML(text, (text) => {
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(headerRegex); // match only headings
if (!match) {
continue;
}
switch (options['Style']) {
case 'Title Case': {
const headerWords = lines[i].match(/\S+/g);
// split by comma or whitespace
const keepCasing = (options['Ignore Words'] as string).split(/[,\s]+/);
const ignoreShortWords = (options['Lowercase Words'] as string).split(/[,\s]+/);
for (let j = 1; j < headerWords.length; j++) {
const isWord = headerWords[j].match(/^[A-Za-z'-]+[.?!,:;]?$/);
if (!isWord) {
continue;
}
const ignoreCasedWord = options['Ignore Cased Words'] && (headerWords[j] !== headerWords[j].toLowerCase());
const keepWordCasing = ignoreCasedWord || keepCasing.includes(headerWords[j]);
if (!keepWordCasing) {
headerWords[j] = headerWords[j].toLowerCase();
const ignoreWord = ignoreShortWords.includes(headerWords[j]);
if (!ignoreWord || j == 1) { // ignore words that are not capitalized in titles except if they are the first word
headerWords[j] = headerWords[j][0].toUpperCase() + headerWords[j].slice(1);
}
}
}
lines[i] = lines[i].replace(headerRegex, escapeDollarSigns(`${headerWords.join(' ')}`));
break;