Code Monkey home page Code Monkey logo

jonschlinkert / markdown-toc Goto Github PK

View Code? Open in Web Editor NEW
1.6K 1.6K 698.0 280 KB

API and CLI for generating a markdown TOC (table of contents) for a README or any markdown files. Uses Remarkable to parse markdown. Used by NASA/openmct, Prisma, Joi, Mocha, Sass, Prettier, Orbit DB, FormatJS, Raneto, hapijs/code, webpack-flow, docusaurus, release-it, ts-loader, json-server, reactfire, bunyan, husky, react-easy-state, react-snap, chakra-ui, carbon, alfresco, repolinter, Assemble, Verb, and thousands of other projects.

Home Page: https://github.com/jonschlinkert

License: MIT License

JavaScript 100.00%
javascript jonschlinkert markdown markdown-toc md navigation node nodejs project readme remarkable table-of-contents toc toc-generator

markdown-toc's Introduction

markdown-toc NPM version NPM monthly downloads NPM total downloads

Generate a markdown TOC (table of contents) with Remarkable.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

(TOC generated by verb using markdown-toc)

Install

Install with npm:

$ npm install --save markdown-toc

Sponsors

Thanks to the following companies, organizations, and individuals for supporting the ongoing maintenance and development of markdown-toc! Become a Sponsor to add your logo to this README, or any of my other projects

Gold Sponsors

https://jaake.tech/
https://jaake.tech/

Quick Start

Assuming you want to add a TOC to README.md:

  1. $ npm install -g markdown-toc
  2. Edit README.md and insert the following line where you want the TOC inserted:
    <!-- toc -->
  3. $ markdown-toc -i README.md

CLI

Usage: markdown-toc [options] <input>

  input:        The Markdown file to parse for table of contents,
                or "-" to read from stdin.

  -i:           Edit the <input> file directly, injecting the TOC at - [Highlights](#highlights)
- [Usage](#usage)
- [API](#api)
  * [toc.plugin](#tocplugin)
  * [toc.json](#tocjson)
  * [toc.insert](#tocinsert)
  * [Utility functions](#utility-functions)
- [Options](#options)
  * [options.append](#optionsappend)
  * [options.filter](#optionsfilter)
  * [options.slugify](#optionsslugify)
  * [options.bullets](#optionsbullets)
  * [options.maxdepth](#optionsmaxdepth)
  * [options.firsth1](#optionsfirsth1)
  * [options.stripHeadingTags](#optionsstripheadingtags)
- [About](#about)

_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_;
                (Without this flag, the default is to print the TOC to stdout.)

  --json:       Print the TOC in JSON format

  --append:     Append a string to the end of the TOC

  --bullets:    Bullets to use for items in the generated TOC
                (Supports multiple bullets: --bullets "*" --bullets "-" --bullets "+")
                (Default is "*".)

  --maxdepth:   Use headings whose depth is at most maxdepth
                (Default is 6.)

  --no-firsth1: Include the first h1-level heading in a file

  --no-stripHeadingTags: Do not strip extraneous HTML tags from heading
                         text before slugifying

  --indent:     Provide the indentation to use - defaults to '  '
                (to specify a tab, use the bash-escaped $'\t')

Highlights

Features

  • Can optionally be used as a remarkable plugin
  • Returns an object with the rendered TOC (on content), as well as a json property with the raw TOC object, so you can generate your own TOC using templates or however you want
  • Works with repeated headings
  • Uses sane defaults, so no customization is necessary, but you can if you need to.
  • filter out headings you don't want
  • Improve the headings you do want
  • Use a custom slugify function to change how links are created

Safe!

  • Won't mangle markdown in code examples in gfm code blocks that other TOC generators mistake as being actual headings (this happens when markdown headings are show in examples, meaning they arent' actually headings that should be in the toc. Also happens with yaml and coffee-script comments, or any comments that use #)
  • Won't mangle front-matter, or mistake front-matter properties for headings like other TOC generators

Usage

var toc = require('markdown-toc');

toc('# One\n\n# Two').content;
// Results in:
// - [One](#one)
// - [Two](#two)

To allow customization of the output, an object is returned with the following properties:

  • content {String}: The generated table of contents. Unless you want to customize rendering, this is all you need.
  • highest {Number}: The highest level heading found. This is used to adjust indentation.
  • tokens {Array}: Headings tokens that can be used for custom rendering

API

toc.plugin

Use as a remarkable plugin.

var Remarkable = require('remarkable');
var toc = require('markdown-toc');

function render(str, options) {
  return new Remarkable()
    .use(toc.plugin(options)) // <= register the plugin
    .render(str);
}

Usage example

var results = render('# AAA\n# BBB\n# CCC\nfoo\nbar\nbaz');

Results in:

- [AAA](#aaa)
- [BBB](#bbb)
- [CCC](#ccc)

toc.json

Object for creating a custom TOC.

toc('# AAA\n## BBB\n### CCC\nfoo').json;

// results in
[ { content: 'AAA', slug: 'aaa', lvl: 1 },
  { content: 'BBB', slug: 'bbb', lvl: 2 },
  { content: 'CCC', slug: 'ccc', lvl: 3 } ]

toc.insert

Insert a table of contents immediately after an opening <!-- toc --> code comment, or replace an existing TOC if both an opening comment and a closing comment (<!-- tocstop -->) are found.

(This strategy works well since code comments in markdown are hidden when viewed as HTML, like when viewing a README on GitHub README for example).

Example

<!-- toc -->
- old toc 1
- old toc 2
- old toc 3
<!-- tocstop -->

## abc
This is a b c.

## xyz
This is x y z.

Would result in something like:

<!-- toc -->
- [abc](#abc)
- [xyz](#xyz)
<!-- tocstop -->

## abc
This is a b c.

## xyz
This is x y z.

Utility functions

As a convenience to folks who wants to create a custom TOC, markdown-toc's internal utility methods are exposed:

var toc = require('markdown-toc');
  • toc.bullets(): render a bullet list from an array of tokens
  • toc.linkify(): linking a heading content string
  • toc.slugify(): slugify a heading content string
  • toc.strip(): strip words or characters from a heading content string

Example

var result = toc('# AAA\n## BBB\n### CCC\nfoo');
var str = '';

result.json.forEach(function(heading) {
  str += toc.linkify(heading.content);
});

Options

options.append

Append a string to the end of the TOC.

toc(str, {append: '\n_(TOC generated by Verb)_'});

options.filter

Type: Function

Default: undefined

Params:

  • str {String} the actual heading string
  • ele {Objecct} object of heading tokens
  • arr {Array} all of the headings objects

Example

From time to time, we might get junk like this in our TOC.

[.aaa([foo], ...) another bad heading](#-aaa--foo--------another-bad-heading)

Unless you like that kind of thing, you might want to filter these bad headings out.

function removeJunk(str, ele, arr) {
  return str.indexOf('...') === -1;
}

var result = toc(str, {filter: removeJunk});
//=> beautiful TOC

options.slugify

Type: Function

Default: Basic non-word character replacement.

Example

var str = toc('# Some Article', {slugify: require('uslug')});

options.bullets

Type: String|Array

Default: *

The bullet to use for each item in the generated TOC. If passed as an array (['*', '-', '+']), the bullet point strings will be used based on the header depth.

options.maxdepth

Type: Number

Default: 6

Use headings whose depth is at most maxdepth.

options.firsth1

Type: Boolean

Default: true

Exclude the first h1-level heading in a file. For example, this prevents the first heading in a README from showing up in the TOC.

options.stripHeadingTags

Type: Boolean

Default: true

Strip extraneous HTML tags from heading text before slugifying. This is similar to GitHub markdown behavior.

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

Contributors

Commits Contributor
199 jonschlinkert
9 doowb
4 dbooth-boston
3 sapegin
3 Marsup
2 dvcrn
2 maxogden
2 twang2218
2 zeke
1 Vortex375
1 chendaniely
1 Daniel-Mietchen
1 Feder1co5oave
1 garygreen
1 TehShrike
1 citizenmatt
1 mgroenhoff
1 rafaelsteil
1 RichardBradley
1 sethvincent
1 shanehughes3
1 bcho
1 lu22do

Author

Jon Schlinkert

License

Copyright © 2023, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on July 12, 2023.

markdown-toc's People

Contributors

bcho avatar chendaniely avatar citizenmatt avatar daniel-mietchen avatar dbooth-boston avatar doowb avatar dvcrn avatar feder1co5oave avatar garygreen avatar jonschlinkert avatar lu22do avatar marsup avatar max-mapper avatar mgroenhoff avatar rafaelsteil avatar richardbradley avatar sapegin avatar sethvincent avatar shanehughes3 avatar tehshrike avatar twang2218 avatar vortex375 avatar zeke avatar

Stargazers

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

Watchers

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

markdown-toc's Issues

Optionally disable links from toc

The generated toc provides links to the headers, but in some cases (e.g. pdf output) it could be desirable to ignore that output.

so instead of:

- [AAA](#aaa)
- [BBB](#bbb)
- [CCC](#ccc)

the output is:

- AAA
- BBB
- CCC

Note that I'm currently using toc.insert() and I don't know if currently is a way to modify the generated toc

Sections with "-" in the title don't link correctly

I have a README with a section with a "-" in the title:

# Development - IntelliJ

The link generated by markdown-toc looks like:

https://github.com/me/myproject#development-intellij

But the link generated by GitHub when it renders the README needs to look like

https://github.com/me/myproject#development---intellij

toc generates no unique links for repeating headers

Example:

# Header 1

## Description
blabla

## Examples
blabla

# Header 2

## Description
blabla

## Examples
blabla

In this example the sub headers of "Header 2" must get a numbered suffix in its link separated with a "-".

The resulting toc should look like:

- [Header 1](#header-1)
    - [Description](#description)
    - [Examples](#examples)
- [Header 2](#header-2)
    - [Description](#description-1)
    - [Examples](#examples-1)

Support umlauts in links

It would be nice if there was an option for supporting german umlauts in the links, e.g. this is what markdown-toc creates:

+ [Frachtaufträge](#frachtauftrage)

This is what I desire:

+ [Frachtaufträge](#frachtaufträge)

GitLab creates anchors with umlauts so currently I need to manually edit all anchors with umlauts.

Change TOC's bullet indentation length

This is less of an issue and more of a question. I'm using marked-toc as part of my process for generating documentation. My source is in Markdown which is then converted to HTML and then from HTML to PDF. The Markdown-to-HTML tool that I am using honors only a 4-space indent in Markdown.

Using marked-toc, an outline like

Introduction
============

Overview
--------

### Objectives

gets converted to HTML that looks like

  • Introduction
  • Overview
    • Objectives

because marked-toc uses two spaces. From Markdown Basics I know that four spaces is specified for code blocks, but I am not sure if this is a standard for nesting lists.

The code I use to correct the indentation is (in case other people run into the same issue)

var toc = require('marked-toc');
var fs = require('fs');
var args = process.argv.slice(2);
var str = fs.readFileSync(args[0], 'utf-8');

var strip = /<!-- toc -->[\s\S]+<!-- toc stop -->/;
var strWithTable = toc.insert(str, {firsth1: true});
var betterToc = strWithTable.match(strip)[0];
betterToc = betterToc.replace(/\n\s{10}\*/g,'\n                    *');
betterToc = betterToc.replace(/\n\s{8}\*/g, '\n                *');
betterToc = betterToc.replace(/\n\s{6}\*/g, '\n            *');
betterToc = betterToc.replace(/\n\s{4}\*/g, '\n        *');
betterToc = betterToc.replace(/\n\s{2}\*/g, '\n    *');
fs.writeFileSync(args[0], strWithTable.replace(strip, betterToc));

Any chance of being how to configure the indentation length in the future?

(Optionally) include first heading in generated TOC

I built a little tool called markdown-index that depends on marked-toc. Unfortunately it's not fitting my use case perfectly: I want to build a TOC for all headings in a markdown file, including the first one.

Any bright ideas on how to make this possible without breaking backwards compatibility for your use cases?

feature request: API to avoid escaping slugs

Introduced in f4030e4, this behavior breaks existing code that don't assume the links are escaped (hence don't escape ids when they are rendering headings in the content).

Reading the doc and the code I couldn't find a way to tell markdown-toc not to escape these links, so things like toc('# 标题\n').content is always rendered to '- [标题](#%E6%A0%87%E9%A2%98)'.

I would like to request a feature like toc('# 标题\n', { escapeSlug: false }).content -> '- [标题](#标题)' which give users a choice to skip the escaping. If that sounds plausible I can open a PR.

Depth

Hi. Nice utility for my marked pages - thanks. When I run toc on my markdown I only get 3 levels of indention (from the md #, ##, ###) but I have more levels (####). firsth1 is set true. It is not obvious from the README level examples if or how I can control that (with the empty string depth prop of the json template?). I wanted to ask for clarification before digging deeper.

Slugs for underscores in headlines is wrong

Looks like I found another edgecase :)

# main:hello_world

renders to

- [main:hello_world](#mainhello-world)   

instead of

- [main:hello_world](#mainhello_world)   

Again, as a result the anchor link doesn't match with the github generated one

Bug in generation of toc with similar headers

For example I have such structure:

# h1
blah

## h2
another blah

### h1
fatal blah

for this file the following toc will be generated:

<!-- toc -->

* [h1](#h1)
  * [h2](#h2)
    * [h1](#h1)

<!-- toc stop -->

But I 've expected to recieve this:

<!-- toc -->

* [h1](#h1)
  * [h2](#h2)
    * [h1](#h1-1)

<!-- toc stop -->

Yes, possibly, it is not a good style to generate such kinds of tocs, but such variants are possible!

Thank you.

Anchors and TOC are not always in sync

Hi,

at first, great library! I'll use it for my little blog engine bloggy to generate TOCs.

I think I've found a minor bug.

A heading with a question mark (maybe if also occurs for other special characters) at the end (e.g.: "Neue Platte - Was ist zu tun?") gives these results:

The url in the TOC: #neue-platte-was-ist-zu-tun
The modified heading: <h2 id="neue-platte-was-ist-zu-tun-">Neue Platte - Was ist zu tun?</h2> (recognize the dash at the end of the anchor)

So, a user cannot navigate to this heading.

I think it's not a big change.

Maybe the library https://github.com/dodo/node-slug could help you to valid and consistent slugs.

Kind regards
Marcell

Add ability to generate TOC on random *.md files

Currently, it looks like I need a <!-- toc --> delimiter in my source markdown file.
It may be nice if I could quickly generate a TOC for any random markdown file and just echo the TOC to stdout.

CLI

add a new CLI

Q: How does insert work?

From the Readme I can't tell what it is (function?) or how to use it, am I missing something? I'll look in the source for now but perhaps it could be documented better?

Awkward formatting in README.md

I noticed that the contents in toc.insert look a bit "off" but they look fine in the .verb.md file...

README.md:

### toc.insert

Insert a table of contents immediately after an _opening_ `

` code comment, or replace an existing TOC if both an _opening_ comment and a _closing_ comment (`

`) are found.

.verb.md:

### toc.insert

Insert a table of contents immediately after an _opening_ `<!-- toc -->` code comment, or replace an existing TOC if both an _opening_ comment and a _closing_ comment (`<!-- tocstop -->`) are found.

Looks like somewhere in the verb->readme formatting, the HTML comments are getting parsed and stripped.

Requires -g global install to work

This is a great package, but I could only get it working once I had installed globally, using npm i -g marked-toc --save.

This is not currently reflected by the README. When I tried to use as per the instructions, I got "command not found: toc".

I am using ZSH but I do have my PATH configured in .zshrc

(Disclaimer: I'm reasonably new to the world of Node and NPM).

How do I handle error?

Thanks for your awesome library ;)

My question is that:

For example, I created 2 toc blocks like below

<!-- toc -->
- [hahaha](#hahaha)
<!-- tocstop -->

<!-- toc -->
- [hahaha](#hahaha)
<!-- tocstop -->

# hahaha
### yoooo

then I called toc.insert and I get the exception Uncaught Error: markdown-toc only supports one Table of Contents per file..

If there any way to handle such errors in callback function instead of try/catch?

Thank you

ignore headings in code blocks

The generated TOC should not contain any "perceived" headings that were in code blocks. e.g.:

# coffee
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x

or

# A Markdown Heading

`querystring.escape is not a function`

Hi,

I've followed the advice found at #39 and #44.
I managed to get unlazy-loader to work.

The error appears to be coming from function linkify in index.js.
Uncaught TypeError: querystring.escape is not a function

I don't see querystring listed as a dependancy. I tried to install it but it had no effect.

`toc` strips newline from end of file

Traditionally, text files should end with a newline char.

The toc command strips the trailing newline from a README which has one.

I think that toc should either not change the presence or absence of a trailing newline, or if it does want to take an opinion on this issue, it should add one rather than remove one.

Skip first H1 headline is broken

Generate TOC with the option firsth1:false outputs undefined. Btw, I would also suggest to use a more meaningful name like skipFirstHeadline

Slugs for "`" is wrong, lol

Noticed it before few mins.

having this heading

API

it generates

- [`API`](#-api-)

but the link should be #api only, not #-api-

working example

'use strict'

var toc = require('markdown-toc')
var res = toc('# `API`\n ## [letta](./index.js#L14)\nfoo bar\n## BBB\n## [.promisify](./index.js#L37)\n## CCC\nfoo')

console.log(res.content)

Latest version (0.4) cannot be installed

I tried this on several machines (Windows 7 + Windows 8), and the error is always the same:

>npm install marked-toc
npm WARN package.json [email protected] No repository field.
npm ERR! Error: ENOENT, chmod 'MyPath\node_modules\marked-toc\cli.js'
npm ERR! If you need help, you may report this *entire* log,
npm ERR! including the npm and node versions, at:
npm ERR!     <http://github.com/npm/npm/issues>

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "marked-toc"
npm ERR! cwd MyPath
npm ERR! node -v v0.10.32
npm ERR! npm -v 1.4.28
npm ERR! path MyPath\node_modules\marked-toc\cli.js
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! not ok code 0

Headlines using colons (:) receive wrong target anchor

# hello:world

renders to

   - [hello:world](#hello-world)   

instead of

   - [hello:world](#helloworld)   

Example:

> toc('# hello:world');
{ json:
   [ { content: 'hello:world',
       slug: 'hello-world',
       lvl: 1,
       i: 0,
       seen: 0 } ],
  highest: 1,
  tokens:
   [ { type: 'heading_open', hLevel: 1, lines: [Object], level: 0 },
     { type: 'inline',
       content: '[hello:world](#hello-world)',
       level: 1,
       lines: [Object],
       children: [Object],
       lvl: 1,
       i: 0,
       seen: 0,
       slug: 'hello-world' },
     { type: 'heading_close', hLevel: 1, level: 0 } ],
  content: '- [hello:world](#hello-world)' }

Because of the dash in between the anchor, the URLs don't match the github URL anchors and won't link to them

Remarkable plugin causes `.render()` to return an object.

The example in the README of using toc.plugin() doesn't seem to work as advertised and I can't for the life of me figure out a workaround.

var Remarkable = require('remarkable');
var toc = require('markdown-toc');

function render(str, options) {
  return new utils.Remarkable()
    .use(toc.plugin(options)) // <= register the plugin
    .render(str);
}

The first issue is that utils is not defined. Assuming that's a typo and removing it:

var Remarkable = require('remarkable');
var toc = require('markdown-toc');

function render(str, options) {
  return new Remarkable()
    .use(toc.plugin(options))
    .render(str);
}

console.log(render('<!-- toc -->\n\n# A\nfoo\n\n#B\nbar'));

I expected something like the following to be logged:

<!-- toc -->
<ul>
    <li><a href="#a">A</a></li>
    <li><a href="#b">B</a></li>
</ul>
<!-- tocstop -->

<h1 id="a">A</h1>
<p>foo</p>
<h1 id="b">B</h1>
<p>bar</p>

But I get an object back as though I had invoked toc() directly:

[object Object]

What am I missing? If I use toc.insert(), then pass the result to a Remarkable instance, I get the expected toc, but the <h1> tags don't have id attributes.

Error in slugify() method with version 0.12.9

$ node
> var toc = require("markdown-toc")
undefined
> toc.slugify("Administrator's Guide")
TypeError: Cannot read property 'seen' of undefined
    at Function.slugify (C:\Source\eXLent_master\exlent\node_modules\markdown-toc\index.js:202:12)
    at repl:1:5
    at REPLServer.defaultEval (repl.js:260:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:429:12)
    at emitOne (events.js:95:20)
    at REPLServer.emit (events.js:182:7)
    at REPLServer.Interface._onLine (readline.js:211:10)
    at REPLServer.Interface._line (readline.js:550:8)

Stop generating when met a "maxdepth" item

Like this extremely simplified markdown text, just for example:

# h1
## h2-1
### h3-1
### h3-2
## h2-2
## h2-3

if maxdepth is set to 2, then I will get a list like this:

- h1
  - h2-1

and if it is set to 3 will get this:

- h1
  - h2-1
    - h3-1

what is your definition of maxdepth? if the list above is also what you don't want to see, plz check your code.
It can be easily done, by modifying code in index.js at line 124
from

res.push(listitem(ele.content, ele.lvl, opts));
if (ele.lvl === opts.maxdepth) {
  break;
}

to

if (ele.lvl > opts.maxdepth) {
  continue;
}
res.push(listitem(ele.content, ele.lvl, opts));

then if maxdepth is set to 2, it will work out a list like:

- h1
  - h2-1
  - h2-2
  - h2-3

Unfriendly error when trying to use cli flags

I was trying to see if there were any command line options, but it seems like it assumes everything is a file/input:

$ toc
fs.js:443
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: ENOENT, no such file or directory '/Users/peterdehaan/dev/github/README.md'
    at Error (native)
    at Object.fs.openSync (fs.js:443:18)
    at Object.fs.readFileSync (fs.js:309:15)
    at Object.file.readFileSync (/Users/peterdehaan/npm/lib/node_modules/marked-toc/node_modules/fs-utils/index.js:154:19)
    at Function.toc.add (/Users/peterdehaan/npm/lib/node_modules/marked-toc/index.js:130:22)
    at Object.<anonymous> (/Users/peterdehaan/npm/lib/node_modules/marked-toc/bin/toc:9:5)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)

$ toc --help
fs.js:443
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: ENOENT, no such file or directory '/Users/peterdehaan/dev/github/--help'
    at Error (native)
    at Object.fs.openSync (fs.js:443:18)
    at Object.fs.readFileSync (fs.js:309:15)
    at Object.file.readFileSync (/Users/peterdehaan/npm/lib/node_modules/marked-toc/node_modules/fs-utils/index.js:154:19)
    at Function.toc.add (/Users/peterdehaan/npm/lib/node_modules/marked-toc/index.js:130:22)
    at Object.<anonymous> (/Users/peterdehaan/npm/lib/node_modules/marked-toc/bin/toc:9:5)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)

Not sure if you want to throw a fs.exists() or fs.existsSync() into the mix to ensure that said file/path exists before trying to use it.

Ignore links in headings

When using the script with keep-a-changelog, the links are generated wrong.

The links render fine:

grabbed_20160912-120554

The target is wrong: E.g., "unreleased" points to olivierlacan/keep-a-changelog@v0.3.0...HEAD instead of #unreleased

I assume that simply the the link brackets ( []) have to be removed from the output. E.g., [[Unreleased]](#unreleased) has to be [Unreleased](#unreleased)

The complete example is available at https://github.com/koppor/keep-a-changelog/blob/master/CHANGELOG.md

Usage with webpack

I've had success in the past using this module with webpack. I'm not sure when or which version the change occurred, but this is no longer the case.

I've setup a gist with the bare minimum code showing what I've been doing.

Output from webpack

WARNING in ./~/markdown-toc/lib/utils.js
Critical dependencies:
7:34-41 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/markdown-toc/lib/utils.js 7:34-41

Output from browser

bundle.js:10939 Uncaught Error: Cannot find module 'remarkable'.

I have tried process.env.UNLAZY = true; as suggested in lazy-loader
This results in a failure to resolve minimist

I have tried doowb/unlazy-loader
Though as I'm using babel on my own source files, I can't use unlazy-loader without running babel across all my node_modules which takes a long time.

I have tried using unlazy in my import statement

import toc from '!unlazy!markdowntoc';

This results in just markdown-toc/index.js being resolved with unlazy.

I understand there are a lot of parties involved here, so I thought I'd start here and hopefully involve others as the need arises.

These were the two related issues I found
jonschlinkert/lazy-cache#3
webpack/webpack#1763

Custom slugify

I have a cyrillic symbols in headings and markdown-toc slugifying them into sequence of -----.
There are npm module transliteration.cyr, that converts cyrillic symbols into latin, but i can not use it because there is no custom slugifying support. It would be nice, if you will add it or share another solution.

Is lazy-cache really necessary?

I don't think it's a good idea to wrap require in any way, ever. Many libraries / tools are built on the assumption that it remains untouched, because it's pretty much a language construct by now (being an ES5 equivalent of import).

I've seen the Browserify trick in the lazy-cache readme, but it isn't implemented in markdown-toc, and it's not really a solution, but a hack. I want to use this in my client-side code, which involves putting everything through Webpack, and this is the only issue preventing me from having a warning-free build:

WARNING in ./~/markdown-toc/lib/insert.js
Critical dependencies:
4:33-40 require function is used in a way in which dependencies cannot be statically extracted
@ ./~/markdown-toc/lib/insert.js 4:33-40

I'm not a language expert, so I might be wrong and this is a valid use of require, and I should be looking into just suppressing Webpack instead, but, FWIW, I haven't seen any package do this before (i.e. cause warnings like the one above).

link headings (not exactly bug)

It may be wanted, but for me not make sense. Actual working example

'use strict'

var toc = require('markdown-toc')
var res = toc('# API\n ## [letta](./index.js#L14)\nfoo bar\n## BBB\n## [.promisify](./index.js#L37)\n## CCC\nfoo')

console.log(res.content)

gives

- [API](#api)
  * [[letta](./index.js#L14)](#-letta---indexjs-l14-)
  * [BBB](#bbb)
  * [[.promisify](./index.js#L37)](#-promisify---indexjs-l37-)
  * [CCC](#ccc)

so render like

(huh, strange why github renders it here so indented but nevermind, that's not the case)

Are you noticing the [[letta](./index.js#L14)](#-letta---indexjs-l14-) thing? Which is not okey for table of contents. Because toc link will not redirect you to the section where's that heading, but to the link that heading redirects to, in case to index.js file.

`linkify()` should escape the `tok.content`

The current linkify() code at https://github.com/jonschlinkert/markdown-toc/blob/master/index.js#L178

/**
 * Turn headings into anchors
 */

function linkify(tok, opts) {
  if (tok && tok.content) {
    var text = titleize(tok.content, opts);
    var slug = utils.slugify(tok.content, opts);
    if (tok.seen) {
      slug += '-' + tok.seen;
    }
    if (opts && typeof opts.linkify === 'function') {
      return opts.linkify(tok, text, slug, opts);
    }
    tok.content = utils.mdlink(text, '#' + slug);
  }
  return tok;
}

I think that the slug should be querystring.escape(slug), otherwise the CJK characters may not correctly escaped for the generated URL.

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.