Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditionally force MD for tables without THEAD #16

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
26 changes: 20 additions & 6 deletions src/tables.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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])
}