@substrate-system/markdown-toc 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2013-2023, Jon Schlinkert.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,419 @@
1
+ # markdown-toc
2
+
3
+ Generate a markdown TOC (table of contents) with Remarkable.
4
+
5
+ Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
6
+
7
+ ## fork
8
+
9
+ This is a fork of [jonschlinkert/markdown-toc](https://github.com/jonschlinkert/markdown-toc).
10
+
11
+ <details>
12
+ <summary><h2>Contents</h2></summary>
13
+
14
+ - [Highlights](#highlights)
15
+ - [Usage](#usage)
16
+ - [API](#api)
17
+ * [toc.plugin](#tocplugin)
18
+ * [toc.json](#tocjson)
19
+ * [toc.insert](#tocinsert)
20
+ * [Utility functions](#utility-functions)
21
+ - [Options](#options)
22
+ * [options.append](#optionsappend)
23
+ * [options.filter](#optionsfilter)
24
+ * [options.slugify](#optionsslugify)
25
+ * [options.bullets](#optionsbullets)
26
+ * [options.maxdepth](#optionsmaxdepth)
27
+ * [options.firsth1](#optionsfirsth1)
28
+ * [options.stripHeadingTags](#optionsstripheadingtags)
29
+ - [About](#about)
30
+
31
+ </details>
32
+
33
+ ## Install
34
+
35
+ Install with [npm](https://www.npmjs.com/):
36
+
37
+ ```sh
38
+ npm i -D @substrate-system/markdown-toc
39
+ ```
40
+
41
+ # Sponsors
42
+
43
+ Thanks to the following companies, organizations, and individuals for supporting the ongoing maintenance and development of markdown-toc! [Become a Sponsor](https://github.com/sponsors/jonschlinkert) to add your logo to this README, or any of [my other projects](https://github.com/jonschlinkert?tab=repositories&q=&type=&language=&sort=stargazers)
44
+
45
+ ## Gold Sponsors
46
+
47
+ | [<img src="https://github.com/jonschlinkert/clone-deep/assets/383994/98036489-2cae-48a2-8d29-7dec58ea05c4" alt="https://jaake.tech/" width="100"/>](https://jaake.tech/) |
48
+ |:---:|
49
+ | [https://jaake.tech/](https://jaake.tech/) |
50
+
51
+ <br />
52
+
53
+ ## Quick Start
54
+
55
+ Assuming you want to add a TOC to README.md:
56
+
57
+ 1. `$ npm install -g markdown-toc`
58
+ 2. Edit README.md and insert the following line where you want the TOC inserted:<br />`<!-- toc -->`
59
+ 3. `$ markdown-toc -i README.md`
60
+
61
+ ## CLI
62
+
63
+ ```
64
+ Usage: markdown-toc [options] <input>
65
+
66
+ input: The Markdown file to parse for table of contents,
67
+ or "-" to read from stdin.
68
+
69
+ -i: Edit the <input> file directly, injecting the TOC at - [Highlights](#highlights)
70
+ - [Usage](#usage)
71
+ - [API](#api)
72
+ * [toc.plugin](#tocplugin)
73
+ * [toc.json](#tocjson)
74
+ * [toc.insert](#tocinsert)
75
+ * [Utility functions](#utility-functions)
76
+ - [Options](#options)
77
+ * [options.append](#optionsappend)
78
+ * [options.filter](#optionsfilter)
79
+ * [options.slugify](#optionsslugify)
80
+ * [options.bullets](#optionsbullets)
81
+ * [options.maxdepth](#optionsmaxdepth)
82
+ * [options.firsth1](#optionsfirsth1)
83
+ * [options.stripHeadingTags](#optionsstripheadingtags)
84
+ - [About](#about)
85
+
86
+ _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_;
87
+ (Without this flag, the default is to print the TOC to stdout.)
88
+
89
+ --json: Print the TOC in JSON format
90
+
91
+ --append: Append a string to the end of the TOC
92
+
93
+ --bullets: Bullets to use for items in the generated TOC
94
+ (Supports multiple bullets: --bullets "*" --bullets "-" --bullets "+")
95
+ (Default is "*".)
96
+
97
+ --maxdepth: Use headings whose depth is at most maxdepth
98
+ (Default is 6.)
99
+
100
+ --no-firsth1: Include the first h1-level heading in a file
101
+
102
+ --no-stripHeadingTags: Do not strip extraneous HTML tags from heading
103
+ text before slugifying
104
+
105
+ --indent: Provide the indentation to use - defaults to ' '
106
+ (to specify a tab, use the bash-escaped $'\t')
107
+ ```
108
+
109
+ ## Highlights
110
+
111
+ **Features**
112
+
113
+ * Can optionally be used as a [remarkable](https://github.com/jonschlinkert/remarkable) plugin
114
+ * 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
115
+ * Works with [repeated headings](https://gist.github.com/jonschlinkert/ac5d8122bfaaa394f896)
116
+ * Uses sane defaults, so no customization is necessary, but you can if you need to.
117
+ * [filter](#filter-headings) out headings you don't want
118
+ * [Improve](#titleize) the headings you do want
119
+ * Use a custom [slugify](#optionsslugify) function to change how links are created
120
+
121
+ **Safe!**
122
+
123
+ * 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 `#`)
124
+ * Won't mangle front-matter, or mistake front-matter properties for headings like other TOC generators
125
+
126
+ ## Usage
127
+
128
+ ```js
129
+ var toc = require('markdown-toc');
130
+
131
+ toc('# One\n\n# Two').content;
132
+ // Results in:
133
+ // - [One](#one)
134
+ // - [Two](#two)
135
+ ```
136
+
137
+ To allow customization of the output, an object is returned with the following properties:
138
+
139
+ * `content` **{String}**: The generated table of contents. Unless you want to customize rendering, this is all you need.
140
+ * `highest` **{Number}**: The highest level heading found. This is used to adjust indentation.
141
+ * `tokens` **{Array}**: Headings tokens that can be used for custom rendering
142
+
143
+ ## API
144
+
145
+ ### toc.plugin
146
+
147
+ Use as a [remarkable](https://github.com/jonschlinkert/remarkable) plugin.
148
+
149
+ ```js
150
+ var Remarkable = require('remarkable');
151
+ var toc = require('markdown-toc');
152
+
153
+ function render(str, options) {
154
+ return new Remarkable()
155
+ .use(toc.plugin(options)) // <= register the plugin
156
+ .render(str);
157
+ }
158
+ ```
159
+
160
+ **Usage example**
161
+
162
+ ```js
163
+ var results = render('# AAA\n# BBB\n# CCC\nfoo\nbar\nbaz');
164
+ ```
165
+
166
+ Results in:
167
+
168
+ ```
169
+ - [AAA](#aaa)
170
+ - [BBB](#bbb)
171
+ - [CCC](#ccc)
172
+ ```
173
+
174
+ ### toc.json
175
+
176
+ Object for creating a custom TOC.
177
+
178
+ ```js
179
+ toc('# AAA\n## BBB\n### CCC\nfoo').json;
180
+
181
+ // results in
182
+ [ { content: 'AAA', slug: 'aaa', lvl: 1 },
183
+ { content: 'BBB', slug: 'bbb', lvl: 2 },
184
+ { content: 'CCC', slug: 'ccc', lvl: 3 } ]
185
+ ```
186
+
187
+ ### toc.insert
188
+
189
+ 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.
190
+
191
+ _(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)._
192
+
193
+ **Example**
194
+
195
+ ```
196
+ <!-- toc -->
197
+ - old toc 1
198
+ - old toc 2
199
+ - old toc 3
200
+ <!-- tocstop -->
201
+
202
+ ## abc
203
+ This is a b c.
204
+
205
+ ## xyz
206
+ This is x y z.
207
+ ```
208
+
209
+ Would result in something like:
210
+
211
+ ```
212
+ <!-- toc -->
213
+ - [abc](#abc)
214
+ - [xyz](#xyz)
215
+ <!-- tocstop -->
216
+
217
+ ## abc
218
+ This is a b c.
219
+
220
+ ## xyz
221
+ This is x y z.
222
+ ```
223
+
224
+ ### Utility functions
225
+
226
+ As a convenience to folks who wants to create a custom TOC, markdown-toc's internal utility methods are exposed:
227
+
228
+ ```js
229
+ var toc = require('markdown-toc');
230
+ ```
231
+
232
+ * `toc.bullets()`: render a bullet list from an array of tokens
233
+ * `toc.linkify()`: linking a heading `content` string
234
+ * `toc.slugify()`: slugify a heading `content` string
235
+ * `toc.strip()`: strip words or characters from a heading `content` string
236
+
237
+ **Example**
238
+
239
+ ```js
240
+ var result = toc('# AAA\n## BBB\n### CCC\nfoo');
241
+ var str = '';
242
+
243
+ result.json.forEach(function(heading) {
244
+ str += toc.linkify(heading.content);
245
+ });
246
+ ```
247
+
248
+ ## Options
249
+
250
+ ### options.append
251
+
252
+ Append a string to the end of the TOC.
253
+
254
+ ```js
255
+ toc(str, {append: '\n_(TOC generated by Verb)_'});
256
+ ```
257
+
258
+ ### options.filter
259
+
260
+ Type: `Function`
261
+
262
+ Default: `undefined`
263
+
264
+ Params:
265
+
266
+ * `str` **{String}** the actual heading string
267
+ * `ele` **{Objecct}** object of heading tokens
268
+ * `arr` **{Array}** all of the headings objects
269
+
270
+ **Example**
271
+
272
+ From time to time, we might get junk like this in our TOC.
273
+
274
+ ```
275
+ [.aaa([foo], ...) another bad heading](#-aaa--foo--------another-bad-heading)
276
+ ```
277
+
278
+ Unless you like that kind of thing, you might want to filter these bad headings out.
279
+
280
+ ```js
281
+ function removeJunk(str, ele, arr) {
282
+ return str.indexOf('...') === -1;
283
+ }
284
+
285
+ var result = toc(str, {filter: removeJunk});
286
+ //=> beautiful TOC
287
+ ```
288
+
289
+ ### options.slugify
290
+
291
+ Type: `Function`
292
+
293
+ Default: Basic non-word character replacement.
294
+
295
+ **Example**
296
+
297
+ ```js
298
+ var str = toc('# Some Article', {slugify: require('uslug')});
299
+ ```
300
+
301
+ ### options.bullets
302
+
303
+ Type: `String|Array`
304
+
305
+ Default: `*`
306
+
307
+ 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.
308
+
309
+ ### options.maxdepth
310
+
311
+ Type: `Number`
312
+
313
+ Default: `6`
314
+
315
+ Use headings whose depth is at most maxdepth.
316
+
317
+ ### options.firsth1
318
+
319
+ Type: `Boolean`
320
+
321
+ Default: `true`
322
+
323
+ 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.
324
+
325
+ ### options.stripHeadingTags
326
+
327
+ Type: `Boolean`
328
+
329
+ Default: `true`
330
+
331
+ Strip extraneous HTML tags from heading text before slugifying. This is similar to GitHub markdown behavior.
332
+
333
+ ## About
334
+
335
+ <details>
336
+ <summary><strong>Contributing</strong></summary>
337
+
338
+ Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
339
+
340
+ </details>
341
+
342
+ <details>
343
+ <summary><strong>Running Tests</strong></summary>
344
+
345
+ 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:
346
+
347
+ ```sh
348
+ $ npm install && npm test
349
+ ```
350
+
351
+ </details>
352
+
353
+ <details>
354
+ <summary><strong>Building docs</strong></summary>
355
+
356
+ _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
357
+
358
+ To generate the readme, run the following command:
359
+
360
+ ```sh
361
+ $ npm install -g verbose/verb#dev verb-generate-readme && verb
362
+ ```
363
+
364
+ </details>
365
+
366
+ ### Related projects
367
+
368
+ You might also be interested in these projects:
369
+
370
+ * [gfm-code-blocks](https://www.npmjs.com/package/gfm-code-blocks): Extract gfm (GitHub Flavored Markdown) fenced code blocks from a string. | [homepage](https://github.com/jonschlinkert/gfm-code-blocks "Extract gfm (GitHub Flavored Markdown) fenced code blocks from a string.")
371
+ * [markdown-link](https://www.npmjs.com/package/markdown-link): Micro util for generating a single markdown link. | [homepage](https://github.com/jonschlinkert/markdown-link "Micro util for generating a single markdown link.")
372
+ * [markdown-utils](https://www.npmjs.com/package/markdown-utils): Tiny helpers for creating consistenly-formatted markdown snippets. | [homepage](https://github.com/jonschlinkert/markdown-utils "Tiny helpers for creating consistenly-formatted markdown snippets.")
373
+ * [pretty-remarkable](https://www.npmjs.com/package/pretty-remarkable): Plugin for prettifying markdown with Remarkable using custom renderer rules. | [homepage](https://github.com/jonschlinkert/pretty-remarkable "Plugin for prettifying markdown with Remarkable using custom renderer rules.")
374
+ * [remarkable](https://www.npmjs.com/package/remarkable): Markdown parser, done right. 100% Commonmark support, extensions, syntax plugins, high speed - all in… [more](https://github.com/jonschlinkert/remarkable) | [homepage](https://github.com/jonschlinkert/remarkable "Markdown parser, done right. 100% Commonmark support, extensions, syntax plugins, high speed - all in one.")
375
+
376
+ ### Contributors
377
+
378
+ | **Commits** | **Contributor** |
379
+ | --- | --- |
380
+ | 199 | [jonschlinkert](https://github.com/jonschlinkert) |
381
+ | 9 | [doowb](https://github.com/doowb) |
382
+ | 4 | [dbooth-boston](https://github.com/dbooth-boston) |
383
+ | 3 | [sapegin](https://github.com/sapegin) |
384
+ | 3 | [Marsup](https://github.com/Marsup) |
385
+ | 2 | [dvcrn](https://github.com/dvcrn) |
386
+ | 2 | [maxogden](https://github.com/maxogden) |
387
+ | 2 | [twang2218](https://github.com/twang2218) |
388
+ | 2 | [zeke](https://github.com/zeke) |
389
+ | 1 | [Vortex375](https://github.com/Vortex375) |
390
+ | 1 | [chendaniely](https://github.com/chendaniely) |
391
+ | 1 | [Daniel-Mietchen](https://github.com/Daniel-Mietchen) |
392
+ | 1 | [Feder1co5oave](https://github.com/Feder1co5oave) |
393
+ | 1 | [garygreen](https://github.com/garygreen) |
394
+ | 1 | [TehShrike](https://github.com/TehShrike) |
395
+ | 1 | [citizenmatt](https://github.com/citizenmatt) |
396
+ | 1 | [mgroenhoff](https://github.com/mgroenhoff) |
397
+ | 1 | [rafaelsteil](https://github.com/rafaelsteil) |
398
+ | 1 | [RichardBradley](https://github.com/RichardBradley) |
399
+ | 1 | [sethvincent](https://github.com/sethvincent) |
400
+ | 1 | [shanehughes3](https://github.com/shanehughes3) |
401
+ | 1 | [bcho](https://github.com/bcho) |
402
+ | 1 | [lu22do](https://github.com/lu22do) |
403
+
404
+ ### Author
405
+
406
+ **Jon Schlinkert**
407
+
408
+ * [GitHub Profile](https://github.com/jonschlinkert)
409
+ * [Twitter Profile](https://twitter.com/jonschlinkert)
410
+ * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
411
+
412
+ ### License
413
+
414
+ Copyright © 2023, [Jon Schlinkert](https://github.com/jonschlinkert).
415
+ Released under the [MIT License](LICENSE).
416
+
417
+ ***
418
+
419
+ _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 12, 2023._
package/cli.js ADDED
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+
3
+ var fs = require('fs');
4
+ var toc = require('./index.js');
5
+ var utils = require('./lib/utils');
6
+ var args = utils.minimist(process.argv.slice(2), {
7
+ boolean: ['i', 'json', 'firsth1', 'stripHeadingTags'],
8
+ string: ['append', 'bullets', 'indent'],
9
+ default: {
10
+ firsth1: true,
11
+ stripHeadingTags: true
12
+ }
13
+ });
14
+
15
+ if (args._.length !== 1) {
16
+ console.error([
17
+ 'Usage: markdown-toc [options] <input> ',
18
+ '',
19
+ ' input: The Markdown file to parse for table of contents,',
20
+ ' or "-" to read from stdin.',
21
+ '',
22
+ ' -i: Edit the <input> file directly, injecting the TOC at <!-- toc -->',
23
+ ' (Without this flag, the default is to print the TOC to stdout.)',
24
+ '',
25
+ ' --json: Print the TOC in JSON format',
26
+ '',
27
+ ' --append: Append a string to the end of the TOC',
28
+ '',
29
+ ' --bullets: Bullets to use for items in the generated TOC',
30
+ ' (Supports multiple bullets: --bullets "*" --bullets "-" --bullets "+")',
31
+ ' (Default is "*".)',
32
+ '',
33
+ ' --maxdepth: Use headings whose depth is at most maxdepth',
34
+ ' (Default is 6.)',
35
+ '',
36
+ ' --no-firsth1: Include the first h1-level heading in a file',
37
+ '',
38
+ ' --no-stripHeadingTags: Do not strip extraneous HTML tags from heading',
39
+ ' text before slugifying',
40
+ '',
41
+ ' --indent: Provide the indentation to use - defaults to \' \'',
42
+ ' (to specify a tab, use the bash-escaped $\'\\t\')'
43
+ ].join('\n'));
44
+ process.exit(1);
45
+ }
46
+
47
+ if (args.i && args.json) {
48
+ console.error('markdown-toc: you cannot use both --json and -i');
49
+ process.exit(1);
50
+ }
51
+
52
+ if (args.i && args._[0] === '-') {
53
+ console.error('markdown-toc: you cannot use -i with "-" (stdin) for input');
54
+ process.exit(1);
55
+ }
56
+
57
+ var input = process.stdin;
58
+ if (args._[0] !== '-') input = fs.createReadStream(args._[0]);
59
+
60
+ input.pipe(utils.concat(function(input) {
61
+ if (args.i) {
62
+ var newMarkdown = toc.insert(input.toString(), args);
63
+ fs.writeFileSync(args._[0], newMarkdown);
64
+ } else {
65
+ var parsed = toc(input.toString(), args);
66
+ output(parsed);
67
+ }
68
+ }));
69
+
70
+ input.on('error', function onErr(err) {
71
+ console.error(err);
72
+ process.exit(1);
73
+ });
74
+
75
+ function output(parsed) {
76
+ if (args.json) return console.log(JSON.stringify(parsed.json, null, ' '));
77
+ process.stdout.write(parsed.content);
78
+ }
package/index.js ADDED
@@ -0,0 +1,255 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * markdown-toc <https://github.com/jonschlinkert/markdown-toc>
5
+ *
6
+ * Copyright © 2013-2023, Jon Schlinkert.
7
+ * Released under the MIT License.
8
+ */
9
+
10
+ var utils = require('./lib/utils');
11
+ var querystring = require('querystring');
12
+
13
+ /**
14
+ * expose `toc`
15
+ */
16
+
17
+ module.exports = toc;
18
+
19
+ /**
20
+ * Load `generate` as a remarkable plugin and
21
+ * expose the `toc` function.
22
+ *
23
+ * @param {String} `str` String of markdown
24
+ * @param {Object} `options`
25
+ * @return {String} Markdown-formatted table of contents
26
+ */
27
+
28
+ function toc(str, options) {
29
+ return new utils.Remarkable()
30
+ .use(generate(options))
31
+ .render(str);
32
+ }
33
+
34
+ /**
35
+ * Expose `insert` method
36
+ */
37
+
38
+ toc.insert = require('./lib/insert');
39
+
40
+ /**
41
+ * Generate a markdown table of contents. This is the
42
+ * function that does all of the main work with Remarkable.
43
+ *
44
+ * @param {Object} `options`
45
+ * @return {String}
46
+ */
47
+
48
+ function generate(options) {
49
+ var opts = utils.merge({firsth1: true, maxdepth: 6}, options);
50
+ var stripFirst = opts.firsth1 === false;
51
+ if (typeof opts.linkify === 'undefined') opts.linkify = true;
52
+
53
+ return function(md) {
54
+ md.renderer.render = function(tokens) {
55
+ tokens = tokens.slice();
56
+ var seen = {};
57
+ var len = tokens.length, i = 0, num = 0;
58
+ var tocstart = -1;
59
+ var arr = [];
60
+ var res = {};
61
+
62
+ while (len--) {
63
+ var token = tokens[i++];
64
+ if (/<!--[ \t]*toc[ \t]*-->/.test(token.content)) {
65
+ tocstart = token.lines[1];
66
+ }
67
+
68
+ if (token.type === 'heading_open') {
69
+ tokens[i].lvl = tokens[i - 1].hLevel;
70
+ tokens[i].i = num++;
71
+ arr.push(tokens[i]);
72
+ }
73
+ }
74
+
75
+ var result = [];
76
+ res.json = [];
77
+
78
+ // exclude headings that come before the actual
79
+ // table of contents.
80
+ var alen = arr.length, j = 0;
81
+ while (alen--) {
82
+ var tok = arr[j++];
83
+
84
+ if (tok.lines && (tok.lines[0] > tocstart)) {
85
+ var val = tok.content;
86
+ if (tok.children && tok.children[0].type === 'link_open') {
87
+ if (tok.children[1].type === 'text') {
88
+ val = tok.children[1].content;
89
+ }
90
+ }
91
+
92
+ if (!seen.hasOwnProperty(val)) {
93
+ seen[val] = 0;
94
+ } else {
95
+ seen[val]++;
96
+ }
97
+
98
+ tok.seen = opts.num = seen[val];
99
+ tok.slug = utils.slugify(val, opts);
100
+ res.json.push(utils.pick(tok, ['content', 'slug', 'lvl', 'i', 'seen']));
101
+ if (opts.linkify) tok = linkify(tok, opts);
102
+ result.push(tok);
103
+ }
104
+ }
105
+
106
+ opts.highest = highest(result);
107
+ res.highest = opts.highest;
108
+ res.tokens = tokens;
109
+
110
+ if (stripFirst) result = result.slice(1);
111
+ res.content = bullets(result, opts);
112
+ res.content += (opts.append || '');
113
+ return res;
114
+ };
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Render markdown list bullets
120
+ *
121
+ * @param {Array} `arr` Array of listitem objects
122
+ * @param {Object} `opts`
123
+ * @return {String}
124
+ */
125
+
126
+ function bullets(arr, options) {
127
+ var opts = utils.merge({indent: ' '}, options);
128
+ opts.chars = opts.chars || opts.bullets || ['-', '*', '+'];
129
+ var unindent = 0;
130
+
131
+ var listitem = utils.li(opts);
132
+ var fn = typeof opts.filter === 'function'
133
+ ? opts.filter
134
+ : null;
135
+
136
+ // Keep the first h1? This is `true` by default
137
+ if (opts && opts.firsth1 === false) {
138
+ unindent = 1;
139
+ }
140
+
141
+ var len = arr.length;
142
+ var res = [];
143
+ var i = 0;
144
+
145
+ while (i < len) {
146
+ var ele = arr[i++];
147
+ ele.lvl -= unindent;
148
+ if (fn && !fn(ele.content, ele, arr)) {
149
+ continue;
150
+ }
151
+
152
+ if (ele.lvl > opts.maxdepth) {
153
+ continue;
154
+ }
155
+
156
+ var lvl = ele.lvl - opts.highest;
157
+ res.push(listitem(lvl, ele.content, opts));
158
+ }
159
+ return res.join('\n');
160
+ }
161
+
162
+ /**
163
+ * Get the highest heading level in the array, so
164
+ * we can un-indent the proper number of levels.
165
+ *
166
+ * @param {Array} `arr` Array of tokens
167
+ * @return {Number} Highest level
168
+ */
169
+
170
+ function highest(arr) {
171
+ var res = arr.slice().sort(function(a, b) {
172
+ return a.lvl - b.lvl;
173
+ });
174
+ if (res && res.length) {
175
+ return res[0].lvl;
176
+ }
177
+ return 0;
178
+ }
179
+
180
+ /**
181
+ * Turn headings into anchors
182
+ */
183
+
184
+ function linkify(tok, options) {
185
+ var opts = utils.merge({}, options);
186
+ if (tok && tok.content) {
187
+ opts.num = tok.seen;
188
+ var text = titleize(tok.content, opts);
189
+ var slug = utils.slugify(tok.content, opts);
190
+ slug = querystring.escape(slug);
191
+ if (opts && typeof opts.linkify === 'function') {
192
+ return opts.linkify(tok, text, slug, opts);
193
+ }
194
+ tok.content = utils.mdlink(text, '#' + slug);
195
+ }
196
+ return tok;
197
+ }
198
+
199
+ /**
200
+ * Titleize the title part of a markdown link.
201
+ *
202
+ * @name options.titleize
203
+ * @param {String} `str` The string to titleize
204
+ * @param {Object} `opts` Pass a custom titleize function on `titleize`
205
+ * @return {String}
206
+ * @api public
207
+ */
208
+
209
+ function titleize(str, opts) {
210
+ if (opts && opts.strip) { return strip(str, opts); }
211
+ if (opts && opts.titleize === false) return str;
212
+ if (opts && typeof opts.titleize === 'function') {
213
+ return opts.titleize(str, opts);
214
+ }
215
+ str = utils.getTitle(str);
216
+ str = str.split(/<\/?[^>]+>/).join('');
217
+ str = str.split(/[ \t]+/).join(' ');
218
+ return str.trim();
219
+ }
220
+
221
+ /**
222
+ * Optionally strip specified words from heading text (not url)
223
+ *
224
+ * @name options.strip
225
+ * @param {String} `str`
226
+ * @param {String} `opts`
227
+ * @return {String}
228
+ */
229
+
230
+ function strip(str, opts) {
231
+ opts = opts || {};
232
+ if (!opts.strip) return str;
233
+ if (typeof opts.strip === 'function') {
234
+ return opts.strip(str, opts);
235
+ }
236
+ if (Array.isArray(opts.strip) && opts.strip.length) {
237
+ var res = opts.strip.join('|');
238
+ var re = new RegExp(res, 'g');
239
+ str = str.trim().replace(re, '');
240
+ return str.replace(/^-|-$/g, '');
241
+ }
242
+ return str;
243
+ }
244
+
245
+ /**
246
+ * Expose utils
247
+ */
248
+
249
+ toc.utils = utils;
250
+ toc.bullets = bullets;
251
+ toc.linkify = linkify;
252
+ toc.slugify = utils.slugify;
253
+ toc.titleize = titleize;
254
+ toc.plugin = generate;
255
+ toc.strip = strip;
package/lib/insert.js ADDED
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ var toc = require('..');
4
+ var utils = require('./utils');
5
+
6
+ /**
7
+ * The basic idea:
8
+ *
9
+ * 1. when front-matter exists, we need to avoid turning its properties into headings.
10
+ * 2. We need to detect toc markers on the page. For now it's a simple HTML code comment
11
+ * to ensure the markdown is compatible with any parser.
12
+ *
13
+ * @param {String} `str` Pass a string of markdown
14
+ * @param {Object} `options` Pass options to toc generation
15
+ * @return {String} Get the same string back with a TOC inserted
16
+ */
17
+
18
+ module.exports = function insert(str, options) {
19
+ options = options || {};
20
+
21
+ var regex = options.regex || /(?:<!-- toc(?:\s*stop)? -->)/g;
22
+ var open = typeof options.open === 'string' ? options.open : '<!-- toc -->\n\n';
23
+ var close = typeof options.close === 'string' ? options.close : '<!-- tocstop -->';
24
+ var obj;
25
+
26
+ var newlines = '';
27
+ var m = /\n+$/.exec(str);
28
+ if (m) newlines = m[0];
29
+
30
+ // does the file have front-matter?
31
+ if (/^---/.test(str)) {
32
+ // extract it temporarily so the syntax
33
+ // doesn't get mistaken for a heading
34
+ obj = utils.matter(str);
35
+ str = obj.content;
36
+ }
37
+
38
+ var sections = split(str, regex);
39
+ if (sections.length > 3) {
40
+ throw new Error('markdown-toc only supports one Table of Contents per file.');
41
+ }
42
+
43
+ var last = sections[sections.length - 1];
44
+ if (sections.length === 3) {
45
+ sections.splice(1, 1, open + (options.toc || toc(last, options).content));
46
+ sections.splice(2, 0, close);
47
+ }
48
+
49
+ if (sections.length === 2) {
50
+ sections.splice(1, 0, open + toc(last, options).content + '\n\n' + close);
51
+ }
52
+
53
+ var resultString = sections.join('\n\n') + newlines;
54
+ // if front-matter was found, put it back now
55
+ if (obj) {
56
+ return utils.matter.stringify(resultString, obj.data);
57
+ }
58
+ return resultString;
59
+ };
60
+
61
+ function split(str, re) {
62
+ return str.split(re).map(trim);
63
+ }
64
+
65
+ function trim(str) {
66
+ return str.trim();
67
+ }
package/lib/utils.js ADDED
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Module dependencies
5
+ */
6
+
7
+ var diacritics = require('diacritics-map');
8
+ var utils = require('lazy-cache')(require);
9
+ var fn = require;
10
+ require = utils;
11
+
12
+ /**
13
+ * Lazily required module dependencies
14
+ */
15
+
16
+ require('concat-stream', 'concat');
17
+ require('gray-matter', 'matter');
18
+ require('list-item', 'li');
19
+ require('markdown-link', 'mdlink');
20
+ require('minimist');
21
+ require('mixin-deep', 'merge');
22
+ require('object.pick', 'pick');
23
+ require('remarkable', 'Remarkable');
24
+ require('repeat-string', 'repeat');
25
+ require('strip-color');
26
+ require = fn;
27
+
28
+ /**
29
+ * Get the "title" from a markdown link
30
+ */
31
+
32
+ utils.getTitle = function(str) {
33
+ if (/^\[[^\]]+\]\(/.test(str)) {
34
+ var m = /^\[([^\]]+)\]/.exec(str);
35
+ if (m) return m[1];
36
+ }
37
+ return str;
38
+ };
39
+
40
+ /**
41
+ * Slugify the url part of a markdown link.
42
+ *
43
+ * @name options.slugify
44
+ * @param {String} `str` The string to slugify
45
+ * @param {Object} `options` Pass a custom slugify function on `options.slugify`
46
+ * @return {String}
47
+ * @api public
48
+ */
49
+
50
+ utils.slugify = function(str, options) {
51
+ options = options || {};
52
+ if (options.slugify === false) return str;
53
+ if (typeof options.slugify === 'function') {
54
+ return options.slugify(str, options);
55
+ }
56
+
57
+ str = utils.getTitle(str);
58
+ str = utils.stripColor(str);
59
+ str = str.toLowerCase();
60
+
61
+ // `.split()` is often (but not always) faster than `.replace()`
62
+ str = str.split(' ').join('-');
63
+ str = str.split(/\t/).join('--');
64
+ if (options.stripHeadingTags !== false) {
65
+ str = str.split(/<\/?[^>]+>/).join('');
66
+ }
67
+ str = str.split(/[|$&`~=\\\/@+*!?({[\]})<>=.,;:'"^]/).join('');
68
+ str = str.split(/[。?!,、;:“”【】()〔〕[]﹃﹄“ ”‘’﹁﹂—…-~《》〈〉「」]/).join('');
69
+ str = replaceDiacritics(str);
70
+ if (options.num) {
71
+ str += '-' + options.num;
72
+ }
73
+ return str;
74
+ };
75
+
76
+ function replaceDiacritics(str) {
77
+ return str.replace(/[À-ž]/g, function(ch) {
78
+ return diacritics[ch] || ch;
79
+ });
80
+ }
81
+
82
+ /**
83
+ * Expose `utils` modules
84
+ */
85
+
86
+ module.exports = utils;
package/package.json ADDED
@@ -0,0 +1,120 @@
1
+ {
2
+ "name": "@substrate-system/markdown-toc",
3
+ "description": "Generate a markdown TOC (table of contents) with Remarkable.",
4
+ "version": "1.3.3",
5
+ "homepage": "https://github.com/jonschlinkert/markdown-toc",
6
+ "author": "Jon Schlinkert (https://github.com/jonschlinkert)",
7
+ "scripts": {
8
+ "version": "npm run changelog && git add CHANGELOG.md",
9
+ "changelog": "auto-changelog -p --template keepachangelog --breaking-pattern 'BREAKING CHANGE:'",
10
+ "postversion": "git push --follow-tags && npm publish --access=public",
11
+ "test": "mocha"
12
+ },
13
+ "dependencies": {
14
+ "concat-stream": "^1.5.2",
15
+ "diacritics-map": "^0.1.0",
16
+ "gray-matter": "^4.0.3",
17
+ "lazy-cache": "^2.0.2",
18
+ "list-item": "^1.1.1",
19
+ "markdown-link": "^0.1.1",
20
+ "minimist": "^1.2.0",
21
+ "mixin-deep": "^1.1.3",
22
+ "object.pick": "^1.3.0",
23
+ "remarkable": "^1.7.1",
24
+ "repeat-string": "^1.6.1",
25
+ "strip-color": "^0.1.0"
26
+ },
27
+ "devDependencies": {
28
+ "auto-changelog": "^2.5.0",
29
+ "mocha": "^10.2.0"
30
+ },
31
+ "contributors": [
32
+ "=^._.^= (http://maxogden.com)",
33
+ "Andrés (http://angrykoala.github.io)",
34
+ "Benjamin Schmitz (https://github.com/Vortex375)",
35
+ "Christian Raunitschka (raunitschka.de)",
36
+ "Daniel Chen (http://chendaniely.github.io)",
37
+ "Daniel Mietchen (http://about.me/daniel.mietchen)",
38
+ "David Mohl (https://dvcrn.github.io)",
39
+ "Federico Soave (https://github.com/Feder1co5oave)",
40
+ "Gary Green (https://github.com/garygreen)",
41
+ "Jon Schlinkert (http://twitter.com/jonschlinkert)",
42
+ "Josh Duff (https://tehshrike.github.io)",
43
+ "Matt Ellis (http://sticklebackplastic.com)",
44
+ "Nicolas Morel (https://github.com/Marsup)",
45
+ "Rafael Steil (http://rafaelsteil.com)",
46
+ "Richard Bradley (https://github.com/RichardBradley)",
47
+ "Seth Vincent (https://sethvincent.com)",
48
+ "Stefan Walther (http://qliksite.io)",
49
+ "Tao Wang (https://github.com/twang2218)",
50
+ "(https://github.com/lu22do)",
51
+ "Zeke Sikelianos (http://zeke.sikelianos.com)"
52
+ ],
53
+ "repository": "bicycle-codes/markdown-toc",
54
+ "bugs": {
55
+ "url": "https://github.com/bicycle-codes/markdown-toc/issues"
56
+ },
57
+ "license": "MIT",
58
+ "files": [
59
+ "cli.js",
60
+ "index.js",
61
+ "lib"
62
+ ],
63
+ "main": "index.js",
64
+ "bin": {
65
+ "markdown-toc": "cli.js"
66
+ },
67
+ "engines": {
68
+ "node": ">=0.10.0"
69
+ },
70
+ "keywords": [
71
+ "anchor",
72
+ "API documentation",
73
+ "code documentation",
74
+ "commonmark",
75
+ "content navigation",
76
+ "content organization",
77
+ "developer tools",
78
+ "docs",
79
+ "document structure",
80
+ "document",
81
+ "documentation tool",
82
+ "documentation",
83
+ "glossary",
84
+ "heading",
85
+ "headings",
86
+ "index",
87
+ "javascript",
88
+ "links",
89
+ "markdown parser",
90
+ "markdown tools",
91
+ "Markdown-based",
92
+ "markdown-toc",
93
+ "markdown",
94
+ "markup language",
95
+ "md files",
96
+ "md parser",
97
+ "md-toc",
98
+ "md",
99
+ "node.js",
100
+ "npm",
101
+ "open-source",
102
+ "outline",
103
+ "package.json",
104
+ "plugin",
105
+ "README tool",
106
+ "readme",
107
+ "reference",
108
+ "remarkable",
109
+ "remarkableplugin",
110
+ "render",
111
+ "renderer",
112
+ "structure",
113
+ "table of contents",
114
+ "table-of-contents",
115
+ "table",
116
+ "toc-generator",
117
+ "toc",
118
+ "write"
119
+ ]
120
+ }