---
title: "mdast"
description: "Extract segments from markdown with remark and splice translations into the source."
canonical_url: "https://diglot.sh/adapters/mdast"
---
# mdast

> Extract segments from markdown with remark and splice translations into the source.

`@diglot/mdast` is the remark and mdast adapter, for markdown parsed with `remark-parse`, `remark-gfm`, `remark-frontmatter` and `remark-mdc`. It suits Astro, Docusaurus, Starlight or plain markdown sources.

<package-info directory="packages/mdast" install="pnpm add @diglot/mdast @diglot/core" name="@diglot/mdast">



</package-info>

## Usage

```ts
import { apply, extract } from '@diglot/mdast'

const segments = await extract(markdown, { file: 'docs/intro.md' })

const { markdown: translated, report } = await apply(markdown, new Map([[segments[0].hash, 'Introduction']]))
```

## extract

`extract(source, { file, policy })` returns the same segments, with the same hashes, as `@diglot/comark` for the same document, with line positions that are exact for each node. Protected spans are sliced from the source.

## apply

`apply(source, translations, { policy })` validates each translation and splices it into the source, so everything outside the translated units is preserved byte for byte. Frontmatter and YAML props are rewritten as YAML scalars, inline props keep their attribute syntax, and code comments keep their indentation and comment syntax. A unit that can't be located in the source is reported as `unaddressable` and keeps its source text.

With `onSegment`, each segment produces an [`ApplySegmentEvent`](https://diglot.sh/core/apply). Attributes you set with `target.setAttribute(name, value)` on headings, paragraphs and table cells are returned as `annotations`, located in the applied markdown. Other segments have a `null` target. `annotate(tree, annotations)` sets them as `data.hProperties` on a tree parsed from the applied markdown, and renders the paragraphs of tight list items as `<span>` so that their attributes reach the HTML.

```ts
const { markdown: translated, annotations } = await apply(markdown, segment => records.get(segment.hash), {
  onSegment(event) {
    if (event.outcome === 'missing' || event.outcome === 'rejected')
      event.target?.setAttribute('lang', 'en')
  },
})
const tree = processor.parse(translated)
annotate(tree, annotations)
```

## parse

`parse(source)` exposes the remark pipeline the adapter uses.

## Heading anchors

The renderer generates heading anchors from the heading text, so translated headings get translated anchors unless your renderer supports explicit ids. Links from other pages to a heading therefore need the anchor of the translated heading, or an explicit id on the heading.


## Sitemap

See the full [sitemap](https://diglot.sh/sitemap.md) for all pages.
