Skip to content

Commit db7eb97

Browse files
Improved YAML regex delimiter
Fixes #1347
1 parent b25152d commit db7eb97

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

packages/foam-vscode/src/utils.test.ts

+6
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@ describe('isInFrontMatter', () => {
8181
const actual = isInFrontMatter(content, 1);
8282
expect(actual).toBeTruthy();
8383
});
84+
it('is false for non valid front matter delimiter #1347', () => {
85+
const content = '---\ntitle: A title\n-..\n\n\n---\ntest\n';
86+
expect(isInFrontMatter(content, 1)).toBeTruthy();
87+
expect(isInFrontMatter(content, 4)).toBeTruthy();
88+
expect(isInFrontMatter(content, 6)).toBeFalsy();
89+
});
8490
it('is false for outside completed front matter', () => {
8591
const content = '---\ntitle: A title\n---\ncontent\nmore content\n';
8692
const actual = isInFrontMatter(content, 3);

packages/foam-vscode/src/utils.ts

+9-4
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,15 @@ export function stripImages(markdown: string): string {
200200
);
201201
}
202202

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

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

217223
const lines = content.split('\n');
218224
lines.shift();
219-
const endLineMatches = (l: string) => l.match(LAST_DELIMITER_MATCH);
220-
const endLineNumber = lines.findIndex(endLineMatches);
225+
const endLineNumber = lines.findIndex(l => l.match(LAST_DELIMITER_MATCH));
221226

222227
return endLineNumber === -1 || endLineNumber >= lineNumber;
223228
}

0 commit comments

Comments
 (0)