• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

valeriangalliat/markdown-it-anchor: A markdown-it plugin that adds an `id` attri ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

valeriangalliat/markdown-it-anchor

开源软件地址(OpenSource Url):

https://github.com/valeriangalliat/markdown-it-anchor

开源编程语言(OpenSource Language):

JavaScript 73.2%

开源软件介绍(OpenSource Introduction):

markdown-it-anchor npm version

A markdown-it plugin that adds an id attribute to headings and optionally permalinks.

English | 中文 (v7.0.1)

Overview

This plugin adds an id attribute to headings, e.g. ## Foo becomes <h2 id="foo">Foo</h2>.

Optionally it can also include permalinks, e.g. <h2 id="foo"><a class="header-anchor" href="#foo">Foo</a></h2> and a bunch of other variants!

Usage

const md = require('markdown-it')()
  .use(require('markdown-it-anchor'), opts)

See a demo as JSFiddle.

The opts object can contain:

Name Description Default
level Minimum level to apply anchors, or array of selected levels. 1
permalink A function to render permalinks, see permalinks below. undefined
slugify A custom slugification function. See index.js
callback Called with token and info after rendering. undefined
getTokensText A custom function to get the text contents of the title from its tokens. See index.js
tabIndex Value of the tabindex attribute on headings, set to false to disable. -1
uniqueSlugStartIndex Index to start with when making duplicate slugs unique. 1

All headers greater than the minimum level will have an id attribute with a slug of their content. For example, you can set level to 2 to add anchors to all headers but h1. You can also pass an array of header levels to apply the anchor, like [2, 3] to have an anchor on only level 2 and 3 headers.

If a permalink renderer is given, it will be called for each matching header to add a permalink. See permalinks below.

If a slugify function is given, you can decide how to transform a heading text to a URL slug. See user-friendly URLs.

The callback option is a function that will be called at the end of rendering with the token and an info object. The info object has title and slug properties with the token content and the slug used for the identifier.

We set by default tabindex="-1" on headers. This marks the headers as focusable elements that are not reachable by keyboard navigation. The effect is that screen readers will read the title content when it's being jumped to. Outside of screen readers, the experience is the same as not setting that attribute. You can override this behavior with the tabIndex option. Set it to false to remove the attribute altogether, otherwise the value will be used as attribute value.

Finally, you can customize how the title text is extracted from the markdown-it tokens (to later generate the slug). See user-friendly URLs.

User-friendly URLs

Starting from v5.0.0, markdown-it-anchor dropped the string package to retain our core value of being an impartial and secure library. Nevertheless, users looking for backward compatibility may want the old slugify function:

npm install string
const string = require('string')
const slugify = s => string(s).slugify().toString()

const md = require('markdown-it')()
  .use(require('markdown-it-anchor'), { slugify })

Another popular library for this is @sindresorhus/slugify, which have better Unicode support and other cool features:

npm install @sindresorhus/slugify
const slugify = require('@sindresorhus/slugify')

const md = require('markdown-it')()
  .use(require('markdown-it-anchor'), { slugify: s => slugify(s) })

Additionally, if you want to further customize the title that gets passed to the slugify function, you can do so by customizing the getTokensText function, that gets the plain text from a list of markdown-it inline tokens:

function getTokensText (tokens) {
  return tokens
    .filter(token => !['html_inline', 'image'].includes(token.type))
    .map(t => t.content)
    .join('')
}

const md = require('markdown-it')()
  .use(require('markdown-it-anchor'), { getTokensText })

By default we include only text and code_inline tokens, which appeared to be a sensible approach for the vast majority of use cases.

An alternative approach is to include every token's content except for html_inline and image tokens, which yields the exact same results as the previous approach with a stock markdown-it, but would also include custom tokens added by any of your markdown-it plugins, which might or might not be desirable for you. Now you have the option!

Manually setting the id attribute

You might want to explicitly set the id attribute of your headings from the Markdown document, for example to keep them consistent across translations.

markdown-it-anchor is designed to reuse any existing id, making markdown-it-attrs a perfect fit for this use case. Make sure to load it before markdown-it-anchor!

Then you can do something like this:

# Your title {#your-custom-id}

The anchor link will reuse the id that you explicitly defined.

Compatible table of contents plugin

Looking for an automatic table of contents (TOC) generator? Take a look at markdown-it-toc-done-right it's made from the ground to be a great companion of this plugin.

Parsing headings from HTML blocks

markdown-it-anchor doesn't parse HTML blocks, so headings defined in HTML blocks will be ignored. If you need to add anchors to both HTML headings and Markdown headings, the easiest way would be to do it on the final HTML rather than during the Markdown parsing phase:

const { parse } = require('node-html-parser')

const root = parse(html)

for (const h of root.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
  const slug = h.getAttribute('id') || slugify(h.textContent)
  h.setAttribute('id', slug)
  h.innerHTML = `<a href="#${slug}>${h.innerHTML}</a>`
}

console.log(root.toString())

Or with a (not accessible) GitHub-style anchor, replace the h.innerHTML part with:


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap