@ohos-ports/markdown-toc-unlazy 0.0.0-stage → 1.0.1-beta.1

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-2017, 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 CHANGED
@@ -1,3 +1,364 @@
1
- # Temporary Holding Version
1
+ # markdown-toc [![NPM version](https://img.shields.io/npm/v/markdown-toc.svg?style=flat)](https://www.npmjs.com/package/markdown-toc) [![NPM monthly downloads](https://img.shields.io/npm/dm/markdown-toc.svg?style=flat)](https://npmjs.org/package/markdown-toc) [![NPM total downloads](https://img.shields.io/npm/dt/markdown-toc.svg?style=flat)](https://npmjs.org/package/markdown-toc) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/markdown-toc.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/markdown-toc) [![Windows Build Status](https://img.shields.io/appveyor/ci/jonschlinkert/markdown-toc.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/jonschlinkert/markdown-toc)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Generate a markdown TOC (table of contents) with Remarkable.
4
+
5
+ ## About This Fork
6
+ Unlazified version of the Jon Schlinkert's markdown-toc (https://github.com/jonschlinkert/markdown-toc)
7
+ Works with webpack
8
+ Note: Stripped down some functions not needed for my use case
9
+
10
+ ## Table of Contents
11
+
12
+ - [Install](#install)
13
+ - [CLI](#cli)
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
+ _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
32
+
33
+ ## Install
34
+
35
+ Install with [npm](https://www.npmjs.com/):
36
+
37
+ ```sh
38
+ $ npm install --save markdown-toc
39
+ ```
40
+
41
+ ## CLI
42
+
43
+ ```
44
+ Usage: markdown-toc [options] <input>
45
+
46
+ input: The Markdown file to parse for table of contents,
47
+ or "-" to read from stdin.
48
+
49
+ -i: Edit the <input> file directly, injecting the TOC at <!-- toc -->;
50
+ (Without this flag, the default is to print the TOC to stdout.)
51
+
52
+ --json: Print the TOC in JSON format
53
+
54
+ --append: Append a string to the end of the TOC
55
+
56
+ --bullets: Bullets to use for items in the generated TOC
57
+ (Supports multiple bullets: --bullets "*" --bullets "-" --bullets "+")
58
+ (Default is "*".)
59
+
60
+ --maxdepth: Use headings whose depth is at most maxdepth
61
+ (Default is 6.)
62
+
63
+ --no-firsth1: Include the first h1-level heading in a file
64
+
65
+ --no-stripHeadingTags: Do not strip extraneous HTML tags from heading
66
+ text before slugifying
67
+ ```
68
+
69
+ ## Highlights
70
+
71
+ **Features**
72
+
73
+ * Can optionally be used as a [remarkable](https://github.com/jonschlinkert/remarkable) plugin
74
+ * 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
75
+ * Works with [repeated headings](https://gist.github.com/jonschlinkert/ac5d8122bfaaa394f896)
76
+ * Uses sane defaults, so no customization is necessary, but you can if you need to.
77
+ * [filter](#filter-headings) out headings you don't want
78
+ * [Improve](#titleize) the headings you do want
79
+ * Use a custom [slugify](#optionsslugify) function to change how links are created
80
+
81
+ **Safe!**
82
+
83
+ * 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 `#`)
84
+ * Won't mangle front-matter, or mistake front-matter properties for headings like other TOC generators
85
+
86
+ ## Usage
87
+
88
+ ```js
89
+ var toc = require('markdown-toc');
90
+
91
+ toc('# One\n\n# Two').content;
92
+ // Results in:
93
+ // - [One](#one)
94
+ // - [Two](#two)
95
+ ```
96
+
97
+ To allow customization of the output, an object is returned with the following properties:
98
+
99
+ * `content` **{String}**: The generated table of contents. Unless you want to customize rendering, this is all you need.
100
+ * `highest` **{Number}**: The highest level heading found. This is used to adjust indentation.
101
+ * `tokens` **{Array}**: Headings tokens that can be used for custom rendering
102
+
103
+ ## API
104
+
105
+ ### toc.plugin
106
+
107
+ Use as a [remarkable](https://github.com/jonschlinkert/remarkable) plugin.
108
+
109
+ ```js
110
+ var Remarkable = require('remarkable');
111
+ var toc = require('markdown-toc');
112
+
113
+ function render(str, options) {
114
+ return new Remarkable()
115
+ .use(toc.plugin(options)) // <= register the plugin
116
+ .render(str);
117
+ }
118
+ ```
119
+
120
+ **Usage example**
121
+
122
+ ```js
123
+ var results = render('# AAA\n# BBB\n# CCC\nfoo\nbar\nbaz');
124
+ ```
125
+
126
+ Results in:
127
+
128
+ ```
129
+ - [AAA](#aaa)
130
+ - [BBB](#bbb)
131
+ - [CCC](#ccc)
132
+ ```
133
+
134
+ ### toc.json
135
+
136
+ Object for creating a custom TOC.
137
+
138
+ ```js
139
+ toc('# AAA\n## BBB\n### CCC\nfoo').json;
140
+
141
+ // results in
142
+ [ { content: 'AAA', slug: 'aaa', lvl: 1 },
143
+ { content: 'BBB', slug: 'bbb', lvl: 2 },
144
+ { content: 'CCC', slug: 'ccc', lvl: 3 } ]
145
+ ```
146
+
147
+ ### toc.insert
148
+
149
+ 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.
150
+
151
+ _(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)._
152
+
153
+ **Example**
154
+
155
+ ```
156
+ <!-- toc -->
157
+ - old toc 1
158
+ - old toc 2
159
+ - old toc 3
160
+ <!-- tocstop -->
161
+
162
+ ## abc
163
+ This is a b c.
164
+
165
+ ## xyz
166
+ This is x y z.
167
+ ```
168
+
169
+ Would result in something like:
170
+
171
+ ```
172
+ <!-- toc -->
173
+ - [abc](#abc)
174
+ - [xyz](#xyz)
175
+ <!-- tocstop -->
176
+
177
+ ## abc
178
+ This is a b c.
179
+
180
+ ## xyz
181
+ This is x y z.
182
+ ```
183
+
184
+ ### Utility functions
185
+
186
+ As a convenience to folks who wants to create a custom TOC, markdown-toc's internal utility methods are exposed:
187
+
188
+ ```js
189
+ var toc = require('markdown-toc');
190
+ ```
191
+
192
+ * `toc.bullets()`: render a bullet list from an array of tokens
193
+ * `toc.linkify()`: linking a heading `content` string
194
+ * `toc.slugify()`: slugify a heading `content` string
195
+ * `toc.strip()`: strip words or characters from a heading `content` string
196
+
197
+ **Example**
198
+
199
+ ```js
200
+ var result = toc('# AAA\n## BBB\n### CCC\nfoo');
201
+ var str = '';
202
+
203
+ result.json.forEach(function(heading) {
204
+ str += toc.linkify(heading.content);
205
+ });
206
+ ```
207
+
208
+ ## Options
209
+
210
+ ### options.append
211
+
212
+ Append a string to the end of the TOC.
213
+
214
+ ```js
215
+ toc(str, {append: '\n_(TOC generated by Verb)_'});
216
+ ```
217
+
218
+ ### options.filter
219
+
220
+ Type: `Function`
221
+
222
+ Default: `undefined`
223
+
224
+ Params:
225
+
226
+ * `str` **{String}** the actual heading string
227
+ * `ele` **{Objecct}** object of heading tokens
228
+ * `arr` **{Array}** all of the headings objects
229
+
230
+ **Example**
231
+
232
+ From time to time, we might get junk like this in our TOC.
233
+
234
+ ```
235
+ [.aaa([foo], ...) another bad heading](#-aaa--foo--------another-bad-heading)
236
+ ```
237
+
238
+ Unless you like that kind of thing, you might want to filter these bad headings out.
239
+
240
+ ```js
241
+ function removeJunk(str, ele, arr) {
242
+ return str.indexOf('...') === -1;
243
+ }
244
+
245
+ var result = toc(str, {filter: removeJunk});
246
+ //=> beautiful TOC
247
+ ```
248
+
249
+ ### options.slugify
250
+
251
+ Type: `Function`
252
+
253
+ Default: Basic non-word character replacement.
254
+
255
+ **Example**
256
+
257
+ ```js
258
+ var str = toc('# Some Article', {slugify: require('uslug')});
259
+ ```
260
+
261
+ ### options.bullets
262
+
263
+ Type: `String|Array`
264
+
265
+ Default: `*`
266
+
267
+ 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.
268
+
269
+ ### options.maxdepth
270
+
271
+ Type: `Number`
272
+
273
+ Default: `6`
274
+
275
+ Use headings whose depth is at most maxdepth.
276
+
277
+ ### options.firsth1
278
+
279
+ Type: `Boolean`
280
+
281
+ Default: `true`
282
+
283
+ 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.
284
+
285
+ ### options.stripHeadingTags
286
+
287
+ Type: `Boolean`
288
+
289
+ Default: `true`
290
+
291
+ Strip extraneous HTML tags from heading text before slugifying. This is similar to GitHub markdown behavior.
292
+
293
+ ## About
294
+
295
+ ### Related projects
296
+
297
+ * [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.")
298
+ * [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.")
299
+ * [markdown-utils](https://www.npmjs.com/package/markdown-utils): Micro-utils for creating markdown snippets. | [homepage](https://github.com/jonschlinkert/markdown-utils "Micro-utils for creating markdown snippets.")
300
+ * [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.")
301
+ * [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.")
302
+
303
+ ### Contributing
304
+
305
+ Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
306
+
307
+ ### Contributors
308
+
309
+ | **Commits** | **Contributor** |
310
+ | --- | --- |
311
+ | 196 | [jonschlinkert](https://github.com/jonschlinkert) |
312
+ | 4 | [stefanwalther](https://github.com/stefanwalther) |
313
+ | 3 | [Marsup](https://github.com/Marsup) |
314
+ | 2 | [dvcrn](https://github.com/dvcrn) |
315
+ | 2 | [maxogden](https://github.com/maxogden) |
316
+ | 2 | [twang2218](https://github.com/twang2218) |
317
+ | 2 | [angrykoala](https://github.com/angrykoala) |
318
+ | 2 | [zeke](https://github.com/zeke) |
319
+ | 1 | [Vortex375](https://github.com/Vortex375) |
320
+ | 1 | [owzim](https://github.com/owzim) |
321
+ | 1 | [chendaniely](https://github.com/chendaniely) |
322
+ | 1 | [Daniel-Mietchen](https://github.com/Daniel-Mietchen) |
323
+ | 1 | [Feder1co5oave](https://github.com/Feder1co5oave) |
324
+ | 1 | [garygreen](https://github.com/garygreen) |
325
+ | 1 | [TehShrike](https://github.com/TehShrike) |
326
+ | 1 | [citizenmatt](https://github.com/citizenmatt) |
327
+ | 1 | [rafaelsteil](https://github.com/rafaelsteil) |
328
+ | 1 | [RichardBradley](https://github.com/RichardBradley) |
329
+ | 1 | [sethvincent](https://github.com/sethvincent) |
330
+ | 1 | [lu22do](https://github.com/lu22do) |
331
+
332
+ ### Building docs
333
+
334
+ _(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.)_
335
+
336
+ To generate the readme, run the following command:
337
+
338
+ ```sh
339
+ $ npm install -g verbose/verb#dev verb-generate-readme && verb
340
+ ```
341
+
342
+ ### Running tests
343
+
344
+ 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:
345
+
346
+ ```sh
347
+ $ npm install && npm test
348
+ ```
349
+
350
+ ### Author
351
+
352
+ **Jon Schlinkert**
353
+
354
+ * [github/jonschlinkert](https://github.com/jonschlinkert)
355
+ * [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
356
+
357
+ ### License
358
+
359
+ Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
360
+ Released under the [MIT License](LICENSE).
361
+
362
+ ***
363
+
364
+ _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on September 19, 2017._
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,247 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * markdown-toc <https://github.com/jonschlinkert/markdown-toc>
5
+ *
6
+ * Copyright © 2013-2017, Jon Schlinkert.
7
+ * Released under the MIT License.
8
+ */
9
+
10
+ var utils = require('./lib/utils');
11
+
12
+ /**
13
+ * expose `toc`
14
+ */
15
+
16
+ module.exports = toc;
17
+
18
+ /**
19
+ * Load `generate` as a remarkable plugin and
20
+ * expose the `toc` function.
21
+ *
22
+ * @param {String} `str` String of markdown
23
+ * @param {Object} `options`
24
+ * @return {String} Markdown-formatted table of contents
25
+ */
26
+
27
+ function toc(str, options) {
28
+ return new utils.Remarkable()
29
+ .use(generate(options))
30
+ .render(str);
31
+ }
32
+
33
+ /**
34
+ * Generate a markdown table of contents. This is the
35
+ * function that does all of the main work with Remarkable.
36
+ *
37
+ * @param {Object} `options`
38
+ * @return {String}
39
+ */
40
+
41
+ function generate(options) {
42
+ var opts = utils.merge({firsth1: true, maxdepth: 6}, options);
43
+ var stripFirst = opts.firsth1 === false;
44
+ if (typeof opts.linkify === 'undefined') opts.linkify = true;
45
+
46
+ return function(md) {
47
+ md.renderer.render = function(tokens) {
48
+ tokens = tokens.slice();
49
+ var seen = {};
50
+ var len = tokens.length, i = 0, num = 0;
51
+ var tocstart = -1;
52
+ var arr = [];
53
+ var res = {};
54
+
55
+ while (len--) {
56
+ var token = tokens[i++];
57
+ if (/<!--[ \t]*toc[ \t]*-->/.test(token.content)) {
58
+ tocstart = token.lines[1];
59
+ }
60
+
61
+ if (token.type === 'heading_open') {
62
+ tokens[i].lvl = tokens[i - 1].hLevel;
63
+ tokens[i].i = num++;
64
+ arr.push(tokens[i]);
65
+ }
66
+ }
67
+
68
+ var result = [];
69
+ res.json = [];
70
+
71
+ // exclude headings that come before the actual
72
+ // table of contents.
73
+ var alen = arr.length, j = 0;
74
+ while (alen--) {
75
+ var tok = arr[j++];
76
+
77
+ if (tok.lines && (tok.lines[0] > tocstart)) {
78
+ var val = tok.content;
79
+ if (tok.children && tok.children[0].type === 'link_open') {
80
+ if (tok.children[1].type === 'text') {
81
+ val = tok.children[1].content;
82
+ }
83
+ }
84
+
85
+ if (!seen.hasOwnProperty(val)) {
86
+ seen[val] = 0;
87
+ } else {
88
+ seen[val]++;
89
+ }
90
+
91
+ tok.seen = opts.num = seen[val];
92
+ tok.slug = utils.slugify(val, opts);
93
+ res.json.push(utils.pick(tok, ['content', 'slug', 'lvl', 'i', 'seen']));
94
+ if (opts.linkify) tok = linkify(tok, opts);
95
+ result.push(tok);
96
+ }
97
+ }
98
+
99
+ opts.highest = highest(result);
100
+ res.highest = opts.highest;
101
+ res.tokens = tokens;
102
+
103
+ if (stripFirst) result = result.slice(1);
104
+ res.content = bullets(result, opts);
105
+ res.content += (opts.append || '');
106
+ return res;
107
+ };
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Render markdown list bullets
113
+ *
114
+ * @param {Array} `arr` Array of listitem objects
115
+ * @param {Object} `opts`
116
+ * @return {String}
117
+ */
118
+
119
+ function bullets(arr, options) {
120
+ var opts = utils.merge({indent: ' '}, options);
121
+ opts.chars = opts.chars || opts.bullets || ['-', '*', '+'];
122
+ var unindent = 0;
123
+
124
+ var listitem = utils.li(opts);
125
+ var fn = typeof opts.filter === 'function'
126
+ ? opts.filter
127
+ : null;
128
+
129
+ // Keep the first h1? This is `true` by default
130
+ if (opts && opts.firsth1 === false) {
131
+ unindent = 1;
132
+ }
133
+
134
+ var len = arr.length;
135
+ var res = [];
136
+ var i = 0;
137
+
138
+ while (i < len) {
139
+ var ele = arr[i++];
140
+ ele.lvl -= unindent;
141
+ if (fn && !fn(ele.content, ele, arr)) {
142
+ continue;
143
+ }
144
+
145
+ if (ele.lvl > opts.maxdepth) {
146
+ continue;
147
+ }
148
+
149
+ var lvl = ele.lvl - opts.highest;
150
+ res.push(listitem(lvl, ele.content, opts));
151
+ }
152
+ return res.join('\n');
153
+ }
154
+
155
+ /**
156
+ * Get the highest heading level in the array, so
157
+ * we can un-indent the proper number of levels.
158
+ *
159
+ * @param {Array} `arr` Array of tokens
160
+ * @return {Number} Highest level
161
+ */
162
+
163
+ function highest(arr) {
164
+ var res = arr.slice().sort(function(a, b) {
165
+ return a.lvl - b.lvl;
166
+ });
167
+ if (res && res.length) {
168
+ return res[0].lvl;
169
+ }
170
+ return 0;
171
+ }
172
+
173
+ /**
174
+ * Turn headings into anchors
175
+ */
176
+
177
+ function linkify(tok, options) {
178
+ var opts = utils.merge({}, options);
179
+ if (tok && tok.content) {
180
+ opts.num = tok.seen;
181
+ var text = titleize(tok.content, opts);
182
+ var slug = utils.slugify(tok.content, opts);
183
+ if (opts && typeof opts.linkify === 'function') {
184
+ return opts.linkify(tok, text, slug, opts);
185
+ }
186
+ tok.content = utils.mdlink(text, '#' + slug);
187
+ }
188
+ return tok;
189
+ }
190
+
191
+ /**
192
+ * Titleize the title part of a markdown link.
193
+ *
194
+ * @name options.titleize
195
+ * @param {String} `str` The string to titleize
196
+ * @param {Object} `opts` Pass a custom titleize function on `titleize`
197
+ * @return {String}
198
+ * @api public
199
+ */
200
+
201
+ function titleize(str, opts) {
202
+ if (opts && opts.strip) { return strip(str, opts); }
203
+ if (opts && opts.titleize === false) return str;
204
+ if (opts && typeof opts.titleize === 'function') {
205
+ return opts.titleize(str, opts);
206
+ }
207
+ str = utils.getTitle(str);
208
+ str = str.split(/<\/?[^>]+>/).join('');
209
+ str = str.split(/[ \t]+/).join(' ');
210
+ return str.trim();
211
+ }
212
+
213
+ /**
214
+ * Optionally strip specified words from heading text (not url)
215
+ *
216
+ * @name options.strip
217
+ * @param {String} `str`
218
+ * @param {String} `opts`
219
+ * @return {String}
220
+ */
221
+
222
+ function strip(str, opts) {
223
+ opts = opts || {};
224
+ if (!opts.strip) return str;
225
+ if (typeof opts.strip === 'function') {
226
+ return opts.strip(str, opts);
227
+ }
228
+ if (Array.isArray(opts.strip) && opts.strip.length) {
229
+ var res = opts.strip.join('|');
230
+ var re = new RegExp(res, 'g');
231
+ str = str.trim().replace(re, '');
232
+ return str.replace(/^-|-$/g, '');
233
+ }
234
+ return str;
235
+ }
236
+
237
+ /**
238
+ * Expose utils
239
+ */
240
+
241
+ toc.bullets = bullets;
242
+ toc.linkify = linkify;
243
+ toc.slugify = utils.slugify;
244
+ toc.titleize = titleize;
245
+ toc.plugin = generate;
246
+ toc.strip = strip;
247
+ toc.insert = require('./lib/insert');
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,93 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Module dependencies
5
+ */
6
+
7
+ var diacritics = require('diacritics-map');
8
+ var concat = require('concat-stream');
9
+ var li = require('list-item');
10
+ var mdlink = require('markdown-link');
11
+ var m = require('minimist');
12
+ var merge = require('mixin-deep');
13
+ var pick = require('object.pick');
14
+ var remarkable = require('remarkable');
15
+ var repeat = require('repeat-string');
16
+ var strip_color = require('strip-color');
17
+
18
+ /**
19
+ * Get the "title" from a markdown link
20
+ */
21
+
22
+ function getTitle(str) {
23
+ if (/^\[[^\]]+\]\(/.test(str)) {
24
+ var m = /^\[([^\]]+)\]/.exec(str);
25
+ if (m) return m[1];
26
+ }
27
+ return str;
28
+ };
29
+
30
+ /**
31
+ * Slugify the url part of a markdown link.
32
+ *
33
+ * @name options.slugify
34
+ * @param {String} `str` The string to slugify
35
+ * @param {Object} `options` Pass a custom slugify function on `options.slugify`
36
+ * @return {String}
37
+ * @api public
38
+ */
39
+
40
+ function slugify(str, options) {
41
+ options = options || {};
42
+ if (options.slugify === false) return str;
43
+ if (typeof options.slugify === 'function') {
44
+ return options.slugify(str, options);
45
+ }
46
+
47
+ str = getTitle(str);
48
+ str = strip_color(str);
49
+ str = str.toLowerCase();
50
+
51
+ // `.split()` is often (but not always) faster than `.replace()`
52
+ str = str.split(' ').join('-');
53
+ str = str.split(/\t/).join('--');
54
+ if (options.stripHeadingTags !== false) {
55
+ str = str.split(/<\/?[^>]+>/).join('');
56
+ }
57
+ str = str.split(/[|$&`~=\\\/@+*!?({[\]})<>=.,;:'"^]/).join('');
58
+ str = str.split(/[。?!,、;:“”【】()〔〕[]﹃﹄“ ”‘’﹁﹂—…-~《》〈〉「」]/).join('');
59
+ str = replaceDiacritics(str);
60
+ if (options.num) {
61
+ str += '-' + options.num;
62
+ }
63
+ return str;
64
+ };
65
+
66
+ function replaceDiacritics(str) {
67
+ return str.replace(/[À-ž]/g, function(ch) {
68
+ return diacritics[ch] || ch;
69
+ });
70
+ }
71
+
72
+ /**
73
+ * Expose `utils` modules
74
+ */
75
+
76
+ const utils = {
77
+ concat: concat,
78
+ li: li,
79
+ mdlink: mdlink,
80
+ minimist: m,
81
+ merge: merge,
82
+ pick: pick,
83
+ Remarkable: remarkable,
84
+ repeat: repeat,
85
+ strip_color: strip_color,
86
+ slugify: slugify,
87
+ getTitle: getTitle,
88
+ replaceDiacritics: replaceDiacritics
89
+ };
90
+
91
+ utils.matter = require('gray-matter');
92
+
93
+ module.exports = utils;
package/package.json CHANGED
@@ -1,6 +1,98 @@
1
1
  {
2
2
  "name": "@ohos-ports/markdown-toc-unlazy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Generate a markdown TOC (table of contents) with Remarkable. (HarmonyOS port: pure JS, platform-agnostic, runs on OpenHarmony Node.js)",
4
+ "version": "1.0.1-beta.1",
5
+ "homepage": "https://github.com/jonschlinkert/markdown-toc",
6
+ "author": "Zain Imran",
7
+ "contributors": [
8
+ "=^._.^= (http://maxogden.com)",
9
+ "Andrés (http://angrykoala.github.io)",
10
+ "Benjamin Schmitz (https://github.com/Vortex375)",
11
+ "Christian Raunitschka (raunitschka.de)",
12
+ "Daniel Chen (http://chendaniely.github.io)",
13
+ "Daniel Mietchen (http://about.me/daniel.mietchen)",
14
+ "David Mohl (https://dvcrn.github.io)",
15
+ "Federico Soave (https://github.com/Feder1co5oave)",
16
+ "Gary Green (https://github.com/garygreen)",
17
+ "Jon Schlinkert (http://twitter.com/jonschlinkert)",
18
+ "Josh Duff (https://tehshrike.github.io)",
19
+ "Matt Ellis (http://sticklebackplastic.com)",
20
+ "Nicolas Morel (https://github.com/Marsup)",
21
+ "Rafael Steil (http://rafaelsteil.com)",
22
+ "Richard Bradley (https://github.com/RichardBradley)",
23
+ "Seth Vincent (https://sethvincent.com)",
24
+ "Stefan Walther (http://qliksite.io)",
25
+ "Tao Wang (https://github.com/twang2218)",
26
+ "(https://github.com/lu22do)",
27
+ "Zeke Sikelianos (http://zeke.sikelianos.com)"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/ohos-ports/ohos-ports.git",
32
+ "directory": "ports/markdown-toc-unlazy/1.0.1"
33
+ },
34
+ "bugs": {
35
+ "url": "https://github.com/ohos-ports/ohos-ports/issues"
36
+ },
37
+ "license": "MIT",
38
+ "files": [
39
+ "cli.js",
40
+ "index.js",
41
+ "lib"
42
+ ],
43
+ "main": "index.js",
44
+ "bin": {
45
+ "markdown-toc": "cli.js"
46
+ },
47
+ "engines": {
48
+ "node": ">=0.10.0"
49
+ },
50
+ "scripts": {
51
+ "test": "mocha"
52
+ },
53
+ "dependencies": {
54
+ "concat-stream": "^1.5.2",
55
+ "diacritics-map": "^0.1.0",
56
+ "gray-matter": "^3.1.1",
57
+ "list-item": "^1.1.1",
58
+ "markdown-link": "^0.1.1",
59
+ "minimist": "^1.2.0",
60
+ "mixin-deep": "^1.1.3",
61
+ "object.pick": "^1.2.0",
62
+ "remarkable": "^1.7.1",
63
+ "repeat-string": "^1.6.1",
64
+ "strip-color": "^0.1.0"
65
+ },
66
+ "devDependencies": {
67
+ "gulp-format-md": "^0.1.11",
68
+ "mocha": "^3.2.0"
69
+ },
70
+ "keywords": [
71
+ "anchor",
72
+ "commonmark",
73
+ "docs",
74
+ "document",
75
+ "documentation",
76
+ "glossary",
77
+ "heading",
78
+ "index",
79
+ "links",
80
+ "markdown",
81
+ "md",
82
+ "plugin",
83
+ "readme",
84
+ "reference",
85
+ "remarkable",
86
+ "remarkableplugin",
87
+ "render",
88
+ "renderer",
89
+ "table",
90
+ "table of contents",
91
+ "table-of-contents",
92
+ "toc",
93
+ "write"
94
+ ],
95
+ "directories": {
96
+ "test": "test"
97
+ }
98
+ }