Git Product home page Git Product logo

marked-gfm-heading-id's Introduction

marked-gfm-heading-id

Add ids to headings like GitHub.

Usage

import { marked } from "marked";
import { gfmHeadingId } from "marked-gfm-heading-id";

// or UMD script
// <script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js"></script>
// <script src="https://cdn.jsdelivr.net/npm/marked-gfm-heading-id/lib/index.umd.js"></script>

const options = {
	prefix: "my-prefix-",
};

marked.use(gfmHeadingId(options));

marked("# heading");
// <h1 id="my-prefix-heading">heading</h1>

Get heading list

getHeadingList is a function that is exported to provide the list of headings.

The headings will each be an object with the following properties:

  • text: The rendered HTML for the heading
  • level: The heading level (1-7)
  • id: The id given to the heading including any prefix
import { marked } from "marked";
import { gfmHeadingId, getHeadingList } from "marked-gfm-heading-id";

marked.use(gfmHeadingId({prefix: "my-prefix-"}), {
	hooks: {
		postprocess(html) {
			const headings = getHeadingList();

			return `
<ul id="table-of-contents">
	${headings.map(({id, text, level}) => `<li><a href="#${id}" class="h${level}">${text}</a></li>`)}
</ul>
${html}`;
		}
	}
});

marked("# heading");
// <ul id="table-of-contents">
//   <li><a href="#my-prefix-heading" class="h1">heading</a></li>
// </ul>
// <h1 id="my-prefix-heading">heading</h1>

Clear Heading List

resetHeadings is a function to purge the stored list of headings and reset the Slugger. This is only needed when the globalSlugs option ( see below) is set to true and you wish to reset the slugger and exportable Headers list.

options

option type default description
prefix string "" A string to prepend to all ids.
globalSlugs bool false Track ids from one use of marked to the next. This ensures unique headers when parsing multiple markdown fragments and rendering the results as a single document. When set to false, the slugger and headers lists are cleared on every marked run.

marked-gfm-heading-id's People

Contributors

dbolack-ab avatar dependabot[bot] avatar github-actions[bot] avatar jeanmeche avatar krzysdz avatar semantic-release-bot avatar theseg avatar uzitech avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

marked-gfm-heading-id's Issues

Need pass the plain text value

As described in the github-slugger readme, you should pass in plain text to this library, these examples will lead to differences to GitHub:

# Hello **world!**

# <samp>Hello <ins>world!</ins></samp>

Typescript support

Issue

This module does not seem to provide typescript definitions. This causes compile errors in the projects using TypeScript + marked.

Do you think it be possible to provide these either out of the box or through @types/marked-gfm-heading-id?

provide a way to extract the table of content

Right now, this package allows to generate headings with ids for markdown content and this works great !

Often for long document, you like to generate a table of content, with anchor links to those ids.

The issue is that I have found that hard to generate a TOC data set when using this plugin.

I was thinking about opening a PR to provide such function with the lexer output as argument :

const convertRaw = (raw) =>
  raw
    .toLowerCase()
    .trim()
    .replace(/<[!\/a-z].*?>/gi, '');

export function extractHeadings(lexer, { prefix = '' } = {}) {
  const slugger = new GithubSlugger();
  const headings = lexer.filter((x) => x.type === 'heading');

  return headings.map((heading) => {
    const raw = heading.raw); // doesn't work
    const raw = heading.text); // doesn't work
    const raw = heading.tokens.reduce((acc, token) => `${acc}${token.raw}`, ''); // doesn't work

    const slugged = slugger.slug(convertRaw(raw));
    console.log(raw, slugged, heading);
    return {
      raw: heading.raw,
      level: heading.depth,
      text: heading.text,
      id: `${prefix}${slugged}`,
    };
  });
}

It'd be great to have a way to acess the same raw as the one provided with the renderer. Wdyt ?

Peer Dependency breaks on Marked v6.*

Only Marked version 4.* and 5.* are allowed as peerDependencies for this project, breaking Marked 6.*. This breaks installing, upgrading, or doing a CI clean with this project included.

Permit "global" GFM Headings

Introduces the notion of larger scale header uniqueness

Changes:

Adds globalSlugs parameter to the extension paramters. When set to false, the extension behaves as it historically has. If set to true, the slugger and headers list are not reset on each parse.

When set to true, the slugger and headers[] persist until the new `resetheadings` function is called.

Use Case:
Projects like Homebrewery where markdown parsing is chunked but headers should still have unique IDs.

How to use from CLI in bash script?

I use marked to convert markdown to html, and I want to use this plugin, but I don't see how to install or invoke it from the bash script.

I can install it as a dev-dependency, but then I get stuck, as I'd like to use a JSON config file.

Can you please provide some documentation for that? Thanks!

Importing into a non-ESM Node.js environment throws an error.

Like the title says, importing into a non-ESM node module causes an error.

Here is my code:

const { marked } = require("marked");
const { gfmHeadingId } = require("marked-gfm-heading-id");

marked.use(
	{
		langPrefix: "",
		mangle: false,
		headerIds: false,
	},
	gfmHeadingId()
);

// ...

const convertedData = marked.parse(existingData);

Here is the output at runtime:

D:\Code\extrusive-test-env\extrusive.md\node_modules\marked-gfm-heading-id\lib\index.cjs:3
var GithubSlugger = require('github-slugger');     
                    ^

Error [ERR_REQUIRE_ESM]: require() of ES Module D:\Code\extrusive-test-env\extrusive.md\node_modules\github-slugger\index.js from D:\Code\extrusive-test-env\extrusive.md\node_modules\marked-gfm-heading-id\lib\index.cjs not supported.
Instead change the require of index.js in D:\Code\extrusive-test-env\extrusive.md\node_modules\marked-gfm-heading-id\lib\index.cjs to a dynamic import() which is available in all CommonJS modules.        
    at Object.<anonymous> (D:\Code\extrusive-test-env\extrusive.md\node_modules\marked-gfm-heading-id\lib\index.cjs:3:21)
    at Object.<anonymous> (D:\Code\extrusive-test-env\extrusive.md\resources\scripts\build_app.js:6:26)
    at Object.<anonymous> (D:\Code\extrusive-test-env\extrusive.md\index.js:6:19) {
  code: 'ERR_REQUIRE_ESM'
}

Node.js v18.16.0

Let me know if you need more information.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.