Skip to content

Commit

Permalink
🐛 fix #284, #311 setext headings
Browse files Browse the repository at this point in the history
  • Loading branch information
Yu committed Oct 28, 2018
1 parent e0649e3 commit 3c111af
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 36 deletions.
33 changes: 23 additions & 10 deletions src/toc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,17 +221,30 @@ function buildToc() {
let toc;
let editor = vscode.window.activeTextEditor;
if (isMdEditor(editor)) {
toc = editor.document.getText()
let lines = editor.document.getText()
.replace(/(^|\r?\n)```[\W\w]+?(```|$)/g, '') // Remove code blocks
.split(/\r?\n/g)
.filter(lineText => lineText.startsWith('#') && lineText.includes('# ') && !lineText.toLowerCase().includes('<!-- omit in toc -->'))
.map(lineText => {
let entry = {};
let matches = /^(#+) (.*)/.exec(lineText);
entry['level'] = matches[1].length;
entry['text'] = matches[2].replace(/#+$/, '').trim();
return entry;
});
.split(/\r?\n/g);
// Transform setext headings to ATX headings
lines.forEach((lineText, i, arr) => {
if (
i < arr.length - 1
&& lineText.match(/^ {0,3}\S.*$/)
&& arr[i + 1].match(/^ {0,3}(=+|-{2,}) *$/)
) {
arr[i] = (arr[i + 1].includes('=') ? '# ' : '## ') + lineText;
}
});
toc = lines.filter(lineText => {
return lineText.startsWith('#')
&& lineText.includes('# ')
&& !lineText.toLowerCase().includes('<!-- omit in toc -->')
}).map(lineText => {
let entry = {};
let matches = /^(#+) (.*)/.exec(lineText);
entry['level'] = matches[1].length;
entry['text'] = matches[2].replace(/#+$/, '').trim();
return entry;
});
} else {
toc = null;
}
Expand Down
50 changes: 24 additions & 26 deletions test/toc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,32 +218,30 @@ suite("TOC.", () => {
new Selection(2, 18, 2, 18)).then(done, done);
});

// // Not implemented

// test("Setext heading syntax", done => {
// testCommand('markdown.extension.toc.create', {},
// [
// 'Section 1',
// '===',
// '',
// 'Section 1.1',
// '---',
// '',
// ''
// ],
// new Selection(6, 0, 6, 0),
// [
// 'Section 1',
// '===',
// '',
// 'Section 1.1',
// '---',
// '',
// '- [Section 1](#section-1)',
// ' - [Section 1.1](#section-11)'
// ],
// new Selection(7, 32, 7, 32)).then(done, done);
// });
test("Setext headings", done => {
testCommand('markdown.extension.toc.create', {},
[
'Section 1',
'===',
'',
'Section 1.1',
'---',
'',
''
],
new Selection(6, 0, 6, 0),
[
'Section 1',
'===',
'',
'Section 1.1',
'---',
'',
'- [Section 1](#section-1)',
' - [Section 1.1](#section-11)'
],
new Selection(7, 32, 7, 32)).then(done, done);
});

test("Non-Latin symbols", done => {
testCommand('markdown.extension.toc.create',
Expand Down

0 comments on commit 3c111af

Please sign in to comment.