Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions __tests__/yaml-title.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,5 +374,17 @@ ruleTest({
# Hello world
`,
},
{ // accounts for https://github.com/platers/obsidian-linter/issues/1428
testName: 'Unescapes H1 markdown special characters',
before: dedent`
# Escape \\[\\_\\]
`,
after: dedent`
---
title: Escape [_]
---
# Escape \\[\\_\\]
`,
},
],
});
5 changes: 3 additions & 2 deletions src/utils/regex.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {getAllTablesInText} from './mdast';
import {makeSureContentHasEmptyLinesAddedBeforeAndAfter} from './strings';
import {makeSureContentHasEmptyLinesAddedBeforeAndAfter, unescapeMarkdownSpecialCharacters} from './strings';

// Useful regexes
export const allHeadersRegex = /^([ \t]*)(#+)([ \t]+)([^\n\r]*?)([ \t]+#+)?$/gm;
Expand Down Expand Up @@ -123,7 +123,8 @@ export function getFirstHeaderOneText(text: string): string {
return $2;
});

return headerText.replaceAll(genericLinkRegex, '$2');
headerText = headerText.replaceAll(genericLinkRegex, '$2');
return unescapeMarkdownSpecialCharacters(headerText);
}

return '';
Expand Down
19 changes: 19 additions & 0 deletions src/utils/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -535,3 +535,22 @@ export function parseCustomReplacements(text: string): Map<string, string> {

return customReplacements;
}

/**
* Unescapes the markdown special characters in the provided text.
*
* @param {string} text - The text to unescape the markdown special characters in.
* @return {string} The text with the markdown special characters unescaped.
*
* @example
* ```ts
* unescapeMarkdownSpecialCharacters('Escape \\[\\_\\]'); // Escape [_]
* ```
*/
export function unescapeMarkdownSpecialCharacters(text: string): string {
return text.replace(/(\\+)([!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~])/g, (_, backslashes, specialChar) => {
const backslashCount = backslashes.length;
const keepCount = Math.floor(backslashCount / 2);
return '\\'.repeat(keepCount) + specialChar;
});
}