From bf23a8535f85208e4b80f540b2ad16b7a66f024e Mon Sep 17 00:00:00 2001 From: Jean-Francois Cere Date: Sat, 29 Sep 2018 13:06:05 -0400 Subject: [PATCH] Fix indent detection (#99) --- lib/src/markdown.service.spec.ts | 11 +++++++---- lib/src/markdown.service.ts | 21 +++++++++++++++------ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/lib/src/markdown.service.spec.ts b/lib/src/markdown.service.spec.ts index 7f368121..133da0b3 100644 --- a/lib/src/markdown.service.spec.ts +++ b/lib/src/markdown.service.spec.ts @@ -71,16 +71,19 @@ describe('MarkdowService', () => { it('should return line with indent correctly', () => { const mockRaw = [ - '* list', // find first line with non-whitespaces to set offset - ' * sub-list', // keep indent while removing from previous row offset - '', // keep blank line - 'Lorem Ipsum', // keep everthing else + ' ', // first line with only whitespaces should not determine indent offset + ' * list', // find first line with non-whitespaces to set offset + ' * sub-list', // keep indent while removing from previous row offset + ' ', // keep blank line + ' Negative indent', // keep line with negative offset according to first non-whitespaces line indent + ' Lorem Ipsum', // keep indent like equals to first non-whitespaces line ident ].join('\n'); const expected = [ '* list', ' * sub-list', '', + 'Negative indent', 'Lorem Ipsum', ].join('\n'); diff --git a/lib/src/markdown.service.ts b/lib/src/markdown.service.ts index ae790819..2bb49c75 100644 --- a/lib/src/markdown.service.ts +++ b/lib/src/markdown.service.ts @@ -77,14 +77,23 @@ export class MarkdownService { return markdown .split('\n') .map(line => { + // set current line ident start to base reference indentation + let lineIdentStart = indentStart; // find position of 1st non-whitespace character - // to determine the markdown indentation start - if (line.length > 0 && isNaN(indentStart)) { - indentStart = line.search(/\S|$/); + // to determine the current line indentation start + if (line.length > 0) { + lineIdentStart = isNaN(lineIdentStart) + ? line.search(/\S|$/) + : Math.min(line.search(/\S|$/), lineIdentStart); } - // remove whitespaces before indentation start - return indentStart - ? line.substring(indentStart) + // keep 1st non-whitespace line indentation + // as base reference for other lines + if (isNaN(indentStart)) { + indentStart = lineIdentStart; + } + // remove whitespaces before current line indentation + return !!lineIdentStart + ? line.substring(lineIdentStart) : line; }).join('\n'); }