# rehype-autolink-headings
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]
**[rehype][]** plugin to add links from headings back to themselves.
## Contents
* [What is this?](#what-is-this)
* [When should I use this?](#when-should-i-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`unified().use(rehypeAutolinkHeadings[, options])`](#unifieduserehypeautolinkheadings-options)
* [`Behavior`](#behavior)
* [`Build`](#build)
* [`BuildProperties`](#buildproperties)
* [`Options`](#options)
* [Examples](#examples)
* [Example: different behaviors](#example-different-behaviors)
* [Example: building content with `hastscript`](#example-building-content-with-hastscript)
* [Example: passing content from a string of HTML](#example-passing-content-from-a-string-of-html)
* [Example: group](#example-group)
* [Types](#types)
* [Compatibility](#compatibility)
* [Security](#security)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This package is a [unified][] ([rehype][]) plugin to add links from headings
back to themselves.
It looks for headings (so `
` through `
`) that have `id` properties,
and injects a link to themselves.
Similar functionality is applied by many places that render markdown.
For example, when browsing this readme on GitHub or npm, an anchor is added
to headings, which you can share to point people to a particular place in a
document.
**unified** is a project that transforms content with abstract syntax trees
(ASTs).
**rehype** adds support for HTML to unified.
**hast** is the HTML AST that rehype uses.
This is a rehype plugin that adds links to headings in the AST.
## When should I use this?
This plugin is useful when you have relatively long documents, where you want
users to be able to link to particular sections, and you already have `id`
properties set on all (or certain?) headings.
A different plugin, [`rehype-slug`][rehype-slug], adds `id`s to headings.
When a heading doesn’t already have an `id` property, it creates a slug from
it, and adds that as the `id` property.
When using both plugins together, all headings (whether explicitly with a
certain `id` or automatically with a generate one) will get a link back to
themselves.
## Install
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
```sh
npm install rehype-autolink-headings
```
In Deno with [`esm.sh`][esmsh]:
```js
import rehypeAutolinkHeadings from 'https://esm.sh/rehype-autolink-headings@7'
```
In browsers with [`esm.sh`][esmsh]:
```html
```
## Use
Say we have the following file `example.html`:
```html
```
## API
This package exports no identifiers.
The default export is [`rehypeAutolinkHeadings`][api-rehype-autolink-headings].
### `unified().use(rehypeAutolinkHeadings[, options])`
Add links from headings back to themselves.
###### Parameters
* `options` ([`Options`][api-options], optional)
— configuration
###### Returns
Transform ([`Transformer`][unified-transformer]).
###### Notes
This plugin only applies to headings with `id`s.
Use `rehype-slug` to generate `id`s for headings that don’t have them.
Several behaviors are supported:
* `'prepend'` (default) — inject link before the heading text
* `'append'` — inject link after the heading text
* `'wrap'` — wrap the whole heading text with the link
* `'before'` — insert link before the heading
* `'after'` — insert link after the heading
### `Behavior`
Behavior (TypeScript type).
###### Type
```ts
type Behavior = 'after' | 'append' | 'before' | 'prepend' | 'wrap'
```
### `Build`
Generate content (TypeScript type).
###### Parameters
* `element` ([`Element`][hast-element])
— current heading
###### Returns
Content ([`Array`][hast-node] or `Node`).
### `BuildProperties`
Generate properties (TypeScript type).
###### Parameters
* `element` ([`Element`][hast-element])
— current heading
###### Returns
Properties ([`Properties`][hast-properties]).
### `Options`
Configuration (TypeScript type).
###### Fields
* `behavior` ([`Behavior`][api-behavior], default: `'prepend'`)
— how to create links
* `content` ([`Array`][hast-node], `Node`, or [`Build`][api-build],
default: if `'wrap'` then `undefined`, otherwise equivalent of
``)
— content to insert in the link;
if `behavior` is `'wrap'` and `Build` is passed, its result replaces the
existing content, otherwise the content is added after existing content
* `group` ([`Array`][hast-node], `Node`, or [`Build`][api-build],
optional)
— content to wrap the heading and link with, if `behavior` is `'after'` or
`'before'`
* `headingProperties` ([`BuildProperties`][api-build-properties] or
[`Properties`][hast-properties], optional)
— extra properties to set on the heading
* `properties` ([`BuildProperties`][api-build-properties] or
[`Properties`][hast-properties], default:
`{ariaHidden: true, tabIndex: -1}` if `'append'` or `'prepend'`, otherwise
`undefined`)
— extra properties to set on the link when injecting
* `test` ([`Test`][hast-util-is-element-test], optional)
— extra test for which headings are linked
## Examples
### Example: different behaviors
This example shows what each behavior generates by default.
```js
import {rehype} from 'rehype'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
const behaviors = ['after', 'append', 'before', 'prepend', 'wrap']
let index = -1
while (++index < behaviors.length) {
const behavior = behaviors[index]
console.log(
String(
await rehype()
.data('settings', {fragment: true})
.use(rehypeAutolinkHeadings, {behavior})
.process('
```
### Example: building content with `hastscript`
The following example passes `options.content` as a function, to generate an
accessible description specific to each link.
It uses [`hastscript`][hastscript] to build nodes.
```js
import {h} from 'hastscript'
import {toString} from 'hast-util-to-string'
import {rehype} from 'rehype'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
const file = await rehype()
.data('settings', {fragment: true})
.use(rehypeAutolinkHeadings, {
content(node) {
return [
h('span.visually-hidden', 'Read the “', toString(node), '” section'),
h('span.icon.icon-link', {ariaHidden: 'true'})
]
}
})
.process('
```
### Example: passing content from a string of HTML
The following example passes `content` as nodes.
It uses [`hast-util-from-html-isomorphic`][hast-util-from-html-isomorphic] to
build nodes from a string of HTML.
```js
/**
* @typedef {import('hast').ElementContent} ElementContent
*/
import {fromHtmlIsomorphic} from 'hast-util-from-html-isomorphic'
import {rehype} from 'rehype'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
const file = await rehype()
.data('settings', {fragment: true})
.use(rehypeAutolinkHeadings, {
content: /** @type {Array} */ (
fromHtmlIsomorphic(
'',
{fragment: true}
).children
)
})
.process('
Makemake
')
console.log(String(file))
```
Yields:
```html
Makemake
```
### Example: group
The following example passes `group` as a function, to dynamically generate a
differing element that wraps the heading.
It uses [`hastscript`][hastscript] to build nodes.
```js
import {h} from 'hastscript'
import {rehype} from 'rehype'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
const file = await rehype()
.data('settings', {fragment: true})
.use(rehypeAutolinkHeadings, {
behavior: 'before',
group(node) {
return h('.heading-' + node.tagName.charAt(1) + '-group')
}
})
.process('