Skip to content

Commit dc752cd

Browse files
committed
fix: escape markdown characters
1 parent 7693128 commit dc752cd

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

__tests__/file-name-heading.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,16 @@ ruleTest({
4444
fileName: 'Test note',
4545
},
4646
},
47+
{ // accounts for https://github.com/platers/obsidian-linter/issues/1426
48+
testName: 'Escapes the markdown special characters in the file name',
49+
before: '',
50+
after: dedent`
51+
# Escape \\[\\_\\]
52+
${''}
53+
`,
54+
options: {
55+
fileName: 'Escape [_]',
56+
},
57+
},
4758
],
4859
});

src/rules/file-name-heading.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import {Options, rulesDict, RuleType} from '../rules';
22
import RuleBuilder, {ExampleBuilder, OptionBuilderBase} from './rule-builder';
33
import dedent from 'ts-dedent';
44
import {IgnoreTypes} from '../utils/ignore-types';
5-
import {insert} from '../utils/strings';
5+
import {escapeMarkdownSpecialCharacters, insert} from '../utils/strings';
66
import {App} from 'obsidian';
77
import {BooleanOption} from '../option';
88
import {ConfirmRuleDisableModal} from '../ui/modals/confirm-rule-disable-modal';
@@ -51,7 +51,7 @@ export default class FileNameHeading extends RuleBuilder<FileNameHeadingOptions>
5151
yaml_end =
5252
yaml_end == -1 || !text.startsWith('---\n') ? 0 : yaml_end + 5;
5353

54-
let header = `# ${fileName}\n`;
54+
let header = `# ${escapeMarkdownSpecialCharacters(fileName)}\n`;
5555
if (text.length < yaml_end) {
5656
header = '\n' + header;
5757
}

src/utils/strings.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,3 +535,18 @@ export function parseCustomReplacements(text: string): Map<string, string> {
535535

536536
return customReplacements;
537537
}
538+
539+
/**
540+
* Escapes the markdown special characters in the provided text.
541+
*
542+
* @param text The text to escape the markdown special characters in.
543+
* @return The text with the markdown special characters escaped.
544+
*
545+
* @example
546+
* ```ts
547+
* escapeMarkdownSpecialCharacters('Escape [_]'); // Escape \[\_\]
548+
* ```
549+
*/
550+
export function escapeMarkdownSpecialCharacters(text: string): string {
551+
return text.replace(/[\\[\]<>_*~=`$]/g, '\\$&');
552+
}

0 commit comments

Comments
 (0)