From 6ad70651bbfaa8b41c653b924de154e02e10a3a8 Mon Sep 17 00:00:00 2001 From: rDuckDev Date: Thu, 30 May 2019 12:00:54 -0500 Subject: [PATCH 1/2] feat: conditionally preserve MD table without THEAD --- src/tables.js | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/tables.js b/src/tables.js index e4fd987..b978b64 100644 --- a/src/tables.js +++ b/src/tables.js @@ -32,13 +32,27 @@ rules.tableRow = { } rules.table = { - // Only convert tables with a heading row. + // Only convert tables with a heading row, unless the heading row is forced. // Tables with no heading row are kept using `keep` (see below). - filter: function (node) { - return node.nodeName === 'TABLE' && isHeadingRow(node.rows[0]) + filter: function (node, options) { + return node.nodeName === 'TABLE' && (isHeadingRow(node.rows[0]) || options.forceHeadingRow) }, - replacement: function (content) { + replacement: function (content, node, options) { + var emptyHeader = '' + + if (options.forceHeadingRow) { + var firstRow = node.rows.length ? node.rows[0] : null + var columnCount = firstRow ? firstRow.childNodes.length : 0 + + // Add an empty heading row, if one is not already present, to ensure a valid Markdown table. + if (columnCount && !isHeadingRow(firstRow)) { + emptyHeader = '|' + ' |'.repeat(columnCount) + '\n' + '|' + ' --- |'.repeat(columnCount) + } + } + + content = emptyHeader + content + // Ensure there are no blank lines content = content.replace('\n\n', '\n') return '\n\n' + content + '\n\n' @@ -90,8 +104,8 @@ function cell (content, node) { } export default function tables (turndownService) { - turndownService.keep(function (node) { - return node.nodeName === 'TABLE' && !isHeadingRow(node.rows[0]) + turndownService.keep(function (node, options) { + return node.nodeName === 'TABLE' && (!isHeadingRow(node.rows[0]) || !options.forceHeadingRow) }) for (var key in rules) turndownService.addRule(key, rules[key]) } From 0b997e30c15aaabea2ae7105a2a491b954535f82 Mon Sep 17 00:00:00 2001 From: rDuckDev Date: Thu, 30 May 2019 12:07:11 -0500 Subject: [PATCH 2/2] docs: specify option to force heading row on tables --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index f8caa81..da50295 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,12 @@ var turndownService = new TurndownService() turndownService.use(tables) ``` +## Options + +| Option | Valid values | Default | +| :---------------- | :---------------- | :------ | +| `forceHeadingRow` | `true` or `false` | `false` | + ## License turndown-plugin-gfm is copyright © 2017+ Dom Christie and released under the MIT license.