Socket
Socket
Sign inDemoInstall

mdast-util-gfm-table

Package Overview
Dependencies
46
Maintainers
2
Versions
16
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    mdast-util-gfm-table

mdast extension to parse and serialize GFM tables


Version published
Weekly downloads
2.9M
decreased by-6.23%
Maintainers
2
Install size
1.84 MB
Created
Weekly downloads
 

Package description

What is mdast-util-gfm-table?

The mdast-util-gfm-table package is a utility to support GitHub Flavored Markdown (GFM) tables in mdast, which is a syntax tree format for Markdown. It allows users to parse and serialize tables in Markdown files following the GFM specification.

What are mdast-util-gfm-table's main functionalities?

Parsing GFM tables

This feature allows you to parse GFM tables from a Markdown string and convert them into an mdast syntax tree. The code sample demonstrates how to use the package in combination with 'mdast-util-from-markdown' to parse a simple table.

import { fromMarkdown } from 'mdast-util-from-markdown';
import { gfmTable } from 'mdast-util-gfm-table';

const markdown = '| Header 1 | Header 2 |\n| -------- | -------- |\n| Cell 1   | Cell 2   |';

const mdastTree = fromMarkdown(markdown, {
extensions: [gfmTable]
});

console.log(mdastTree);

Serializing GFM tables

This feature allows you to serialize an mdast syntax tree containing a GFM table back into a Markdown string. The code sample shows how to use the package with 'mdast-util-to-markdown' to serialize a simple mdast table structure.

import { toMarkdown } from 'mdast-util-to-markdown';
import { gfmTable } from 'mdast-util-gfm-table';

const mdastTree = {
type: 'table',
align: ['left', 'right'],
children: [
  {
type: 'tableRow',
children: [
    {type: 'tableCell', children: [{type: 'text', value: 'Header 1'}]},
    {type: 'tableCell', children: [{type: 'text', value: 'Header 2'}]}
  ]
},
  {
type: 'tableRow',
children: [
    {type: 'tableCell', children: [{type: 'text', value: 'Cell 1'}]},
    {type: 'tableCell', children: [{type: 'text', value: 'Cell 2'}]}
  ]
}
]
};

const markdown = toMarkdown(mdastTree, {
extensions: [gfmTable]
});

console.log(markdown);

Other packages similar to mdast-util-gfm-table

Readme

Source

mdast-util-gfm-table

Build Coverage Downloads Size Sponsors Backers Chat

mdast extensions to parse and serialize GFM tables.

Contents

What is this?

This package contains extensions that add support for the table syntax enabled by GFM to mdast-util-from-markdown and mdast-util-to-markdown.

When to use this

These tools are all rather low-level. In most cases, you’d want to use remark-gfm with remark instead.

When you are working with syntax trees and want all of GFM, use mdast-util-gfm instead.

When working with mdast-util-from-markdown, you must combine this package with micromark-extension-gfm-table.

This utility does not handle how markdown is turned to HTML. That’s done by mdast-util-to-hast. If your content is not in English, you should configure that utility.

Install

This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:

npm install mdast-util-gfm-table

In Deno with esm.sh:

import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'https://esm.sh/mdast-util-gfm-table@1'

In browsers with esm.sh:

<script type="module">
  import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'https://esm.sh/mdast-util-gfm-table@1?bundle'
</script>

Use

Say our document example.md contains:

| a | b | c | d |
| - | :- | -: | :-: |
| e | f |
| g | h | i | j | k |

…and our module example.js looks as follows:

import fs from 'node:fs/promises'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {toMarkdown} from 'mdast-util-to-markdown'
import {gfmTable} from 'micromark-extension-gfm-table'
import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'

const doc = await fs.readFile('example.md')

const tree = fromMarkdown(doc, {
  extensions: [gfmTable],
  mdastExtensions: [gfmTableFromMarkdown]
})

console.log(tree)

const out = toMarkdown(tree, {extensions: [gfmTableToMarkdown()]})

console.log(out)

…now running node example.js yields (positional info removed for brevity):

{
  type: 'root',
  children: [
    {
      type: 'table',
      align: [null, 'left', 'right', 'center'],
      children: [
        {
          type: 'tableRow',
          children: [
            {type: 'tableCell', children: [{type: 'text', value: 'a'}]},
            {type: 'tableCell', children: [{type: 'text', value: 'b'}]},
            {type: 'tableCell', children: [{type: 'text', value: 'c'}]},
            {type: 'tableCell', children: [{type: 'text', value: 'd'}]}
          ]
        },
        {
          type: 'tableRow',
          children: [
            {type: 'tableCell', children: [{type: 'text', value: 'e'}]},
            {type: 'tableCell', children: [{type: 'text', value: 'f'}]}
          ]
        },
        {
          type: 'tableRow',
          children: [
            {type: 'tableCell', children: [{type: 'text', value: 'g'}]},
            {type: 'tableCell', children: [{type: 'text', value: 'h'}]},
            {type: 'tableCell', children: [{type: 'text', value: 'i'}]},
            {type: 'tableCell', children: [{type: 'text', value: 'j'}]},
            {type: 'tableCell', children: [{type: 'text', value: 'k'}]}
          ]
        }
      ]
    }
  ]
}
| a | b  |  c |  d  |   |
| - | :- | -: | :-: | - |
| e | f  |    |     |   |
| g | h  |  i |  j  | k |

API

This package exports the identifiers gfmTableFromMarkdown and gfmTableToMarkdown. There is no default export.

gfmTableFromMarkdown

Extension for mdast-util-from-markdown.

gfmTableToMarkdown(options?)

Function that can be called to get an extension for mdast-util-to-markdown.

options

Configuration (optional).

options.tableCellPadding

Serialize tables with a space between delimiters (|) and cell content (boolean, default: true).

options.tablePipeAlign

Serialize by aligning the delimiters (|) between table cells so that they all align nicely and form a grid (boolean, default: true).

options.stringLength

Function to detect the length of table cell content (Function, default: s => s.length). This is used when aligning the delimiters (|) between table cells. Full-width characters and emoji mess up delimiter alignment when viewing the markdown source. To fix this, you can pass this function, which receives the cell content and returns its “visible” size. Note that what is and isn’t visible depends on where the text is displayed.

Examples

Example: stringLength

It’s possible to align tables based on the visual width of cells. First, let’s show the problem:

import {fromMarkdown} from 'mdast-util-from-markdown'
import {toMarkdown} from 'mdast-util-to-markdown'
import {gfmTable} from 'micromark-extension-gfm-table'
import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'

const doc = `| Alpha | Bravo |
| - | - |
| 中文 | Charlie |
| 👩‍❤️‍👩 | Delta |`

const tree = fromMarkdown(doc, {
  extensions: [gfmTable],
  mdastExtensions: [gfmTableFromMarkdown]
})

console.log(toMarkdown(tree, {extensions: [gfmTableToMarkdown()]}))

The above code shows how these utilities can be used to format markdown. The output is as follows:

| Alpha    | Bravo   |
| -------- | ------- |
| 中文       | Charlie |
| 👩‍❤️‍👩 | Delta   |

To improve the alignment of these full-width characters and emoji, pass a stringLength function that calculates the visual width of cells. One such algorithm is string-width. It can be used like so:

@@ -2,6 +2,7 @@ import {fromMarkdown} from 'mdast-util-from-markdown'
 import {toMarkdown} from 'mdast-util-to-markdown'
 import {gfmTable} from 'micromark-extension-gfm-table'
 import {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'
+import stringWidth from 'string-width'

 const doc = `| Alpha | Bravo |
 | - | - |
@@ -13,4 +14,8 @@ const tree = fromMarkdown(doc, {
   mdastExtensions: [gfmTableFromMarkdown]
 })

-console.log(toMarkdown(tree, {extensions: [gfmTableToMarkdown()]}))
+console.log(
+  toMarkdown(tree, {
+    extensions: [gfmTableToMarkdown({stringLength: stringWidth})]
+  })
+)

The output of our code with these changes is as follows:

| Alpha | Bravo   |
| ----- | ------- |
| 中文  | Charlie |
| 👩‍❤️‍👩    | Delta   |

Syntax tree

The following interfaces are added to mdast by this utility.

Nodes

Table
interface Table <: Parent {
  type: "table"
  align: [alignType]?
  children: [TableContent]
}

Table (Parent) represents two-dimensional data.

Table can be used where flow content is expected. Its content model is table content.

The head of the node represents the labels of the columns.

An align field can be present. If present, it must be a list of alignTypes. It represents how cells in columns are aligned.

For example, the following markdown:

| foo | bar |
| :-- | :-: |
| baz | qux |

Yields:

{
  type: 'table',
  align: ['left', 'center'],
  children: [
    {
      type: 'tableRow',
      children: [
        {
          type: 'tableCell',
          children: [{type: 'text', value: 'foo'}]
        },
        {
          type: 'tableCell',
          children: [{type: 'text', value: 'bar'}]
        }
      ]
    },
    {
      type: 'tableRow',
      children: [
        {
          type: 'tableCell',
          children: [{type: 'text', value: 'baz'}]
        },
        {
          type: 'tableCell',
          children: [{type: 'text', value: 'qux'}]
        }
      ]
    }
  ]
}
TableRow
interface TableRow <: Parent {
  type: "tableRow"
  children: [RowContent]
}

TableRow (Parent) represents a row of cells in a table.

TableRow can be used where table content is expected. Its content model is row content.

If the node is a head, it represents the labels of the columns for its parent Table.

For an example, see Table.

TableCell
interface TableCell <: Parent {
  type: "tableCell"
  children: [PhrasingContent]
}

TableCell (Parent) represents a header cell in a Table, if its parent is a head, or a data cell otherwise.

TableCell can be used where row content is expected. Its content model is phrasing content excluding Break nodes.

For an example, see Table.

Enumeration

alignType
enum alignType {
  "left" | "right" | "center" | null
}

alignType represents how phrasing content is aligned ([CSSTEXT]).

  • 'left': See the left value of the text-align CSS property
  • 'right': See the right value of the text-align CSS property
  • 'center': See the center value of the text-align CSS property
  • null: phrasing content is aligned as defined by the host environment

Content model

FlowContent (GFM table)
type FlowContentGfm = Table | FlowContent
TableContent
type TableContent = TableRow

Table content represent the rows in a table.

RowContent
type RowContent = TableCell

Row content represent the cells in a row.

Types

This package is fully typed with TypeScript. It exports the additional type Options.

The Table, TableRow, and TableCell node types are supported in @types/mdast by default.

Compatibility

Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.

This plugin works with mdast-util-from-markdown version 1+ and mdast-util-to-markdown version 1+.

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer

Keywords

FAQs

Last updated on 12 Sep 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc