Skip to content

Commit

Permalink
Fix indent detection (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
jfcere authored Sep 29, 2018
1 parent 0d7f750 commit bf23a85
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
11 changes: 7 additions & 4 deletions lib/src/markdown.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down
21 changes: 15 additions & 6 deletions lib/src/markdown.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
Expand Down

0 comments on commit bf23a85

Please sign in to comment.