Skip to content

Commit

Permalink
Improved YAML regex delimiter
Browse files Browse the repository at this point in the history
Fixes #1347
  • Loading branch information
riccardoferretti committed Mar 22, 2024
1 parent b25152d commit db7eb97
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
6 changes: 6 additions & 0 deletions packages/foam-vscode/src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ describe('isInFrontMatter', () => {
const actual = isInFrontMatter(content, 1);
expect(actual).toBeTruthy();
});
it('is false for non valid front matter delimiter #1347', () => {
const content = '---\ntitle: A title\n-..\n\n\n---\ntest\n';
expect(isInFrontMatter(content, 1)).toBeTruthy();
expect(isInFrontMatter(content, 4)).toBeTruthy();
expect(isInFrontMatter(content, 6)).toBeFalsy();
});
it('is false for outside completed front matter', () => {
const content = '---\ntitle: A title\n---\ncontent\nmore content\n';
const actual = isInFrontMatter(content, 3);
Expand Down
13 changes: 9 additions & 4 deletions packages/foam-vscode/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,15 @@ export function stripImages(markdown: string): string {
);
}

/**
* Returns if the given line is inside a front matter block
* @param content the string to check
* @param lineNumber the line number within the string, 0-based
* @returns true if the line is inside a frontmatter block in content
*/
export function isInFrontMatter(content: string, lineNumber: number): Boolean {
const FIRST_DELIMITER_MATCH = /^---\s*?$/gm;
const LAST_DELIMITER_MATCH = /^[-.]{3}\s*?$/g;
const FIRST_DELIMITER_MATCH = /^---\s*?$/m;
const LAST_DELIMITER_MATCH = /^(-{3}|\.{3})/;

// if we're on the first line, we're not _yet_ in the front matter
if (lineNumber === 0) {
Expand All @@ -216,8 +222,7 @@ export function isInFrontMatter(content: string, lineNumber: number): Boolean {

const lines = content.split('\n');
lines.shift();
const endLineMatches = (l: string) => l.match(LAST_DELIMITER_MATCH);
const endLineNumber = lines.findIndex(endLineMatches);
const endLineNumber = lines.findIndex(l => l.match(LAST_DELIMITER_MATCH));

return endLineNumber === -1 || endLineNumber >= lineNumber;
}
Expand Down

0 comments on commit db7eb97

Please sign in to comment.