├── .editorconfig
├── .eslintrc.json
├── .gitattributes
├── .github
└── contributing.md
├── .gitignore
├── .travis.yml
├── .verb.md
├── LICENSE
├── README.md
├── examples
├── basic.js
├── example-parse.js
├── fixtures
│ ├── basic.md
│ ├── parse.md
│ └── sections.md
└── sections.js
├── index.js
├── package.json
└── test
├── fixtures
├── hr.md
└── multiple.md
└── test.js
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org/
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | end_of_line = lf
7 | indent_size = 2
8 | indent_style = space
9 | insert_final_newline = true
10 | trim_trailing_whitespace = true
11 |
12 | [{**/{actual,fixtures,expected,templates}/**,*.md}]
13 | trim_trailing_whitespace = false
14 | insert_final_newline = false
15 |
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "browser": false,
4 | "es6": true,
5 | "node": true,
6 | "mocha": true
7 | },
8 |
9 | "globals": {
10 | "document": false,
11 | "navigator": false,
12 | "window": false
13 | },
14 |
15 | "rules": {
16 | "accessor-pairs": 2,
17 | "arrow-spacing": [2, { "before": true, "after": true }],
18 | "block-spacing": [2, "always"],
19 | "brace-style": [2, "1tbs", { "allowSingleLine": true }],
20 | "comma-dangle": [2, "never"],
21 | "comma-spacing": [2, { "before": false, "after": true }],
22 | "comma-style": [2, "last"],
23 | "constructor-super": 2,
24 | "curly": [2, "multi-line"],
25 | "dot-location": [2, "property"],
26 | "eol-last": 2,
27 | "eqeqeq": [2, "allow-null"],
28 | "generator-star-spacing": [2, { "before": true, "after": true }],
29 | "handle-callback-err": [2, "^(err|error)$" ],
30 | "indent": [2, 2, { "SwitchCase": 1 }],
31 | "key-spacing": [2, { "beforeColon": false, "afterColon": true }],
32 | "keyword-spacing": [2, { "before": true, "after": true }],
33 | "new-cap": [2, { "newIsCap": true, "capIsNew": false }],
34 | "new-parens": 2,
35 | "no-array-constructor": 2,
36 | "no-caller": 2,
37 | "no-class-assign": 2,
38 | "no-cond-assign": 2,
39 | "no-const-assign": 2,
40 | "no-control-regex": 2,
41 | "no-debugger": 2,
42 | "no-delete-var": 2,
43 | "no-dupe-args": 2,
44 | "no-dupe-class-members": 2,
45 | "no-dupe-keys": 2,
46 | "no-duplicate-case": 2,
47 | "no-empty-character-class": 2,
48 | "no-eval": 2,
49 | "no-ex-assign": 2,
50 | "no-extend-native": 2,
51 | "no-extra-bind": 2,
52 | "no-extra-boolean-cast": 2,
53 | "no-extra-parens": [2, "functions"],
54 | "no-fallthrough": 2,
55 | "no-floating-decimal": 2,
56 | "no-func-assign": 2,
57 | "no-implied-eval": 2,
58 | "no-inner-declarations": [2, "functions"],
59 | "no-invalid-regexp": 2,
60 | "no-irregular-whitespace": 2,
61 | "no-iterator": 2,
62 | "no-label-var": 2,
63 | "no-labels": 2,
64 | "no-lone-blocks": 2,
65 | "no-mixed-spaces-and-tabs": 2,
66 | "no-multi-spaces": 2,
67 | "no-multi-str": 2,
68 | "no-multiple-empty-lines": [2, { "max": 1 }],
69 | "no-native-reassign": 0,
70 | "no-negated-in-lhs": 2,
71 | "no-new": 2,
72 | "no-new-func": 2,
73 | "no-new-object": 2,
74 | "no-new-require": 2,
75 | "no-new-wrappers": 2,
76 | "no-obj-calls": 2,
77 | "no-octal": 2,
78 | "no-octal-escape": 2,
79 | "no-proto": 0,
80 | "no-redeclare": 2,
81 | "no-regex-spaces": 2,
82 | "no-return-assign": 2,
83 | "no-self-compare": 2,
84 | "no-sequences": 2,
85 | "no-shadow-restricted-names": 2,
86 | "no-spaced-func": 2,
87 | "no-sparse-arrays": 2,
88 | "no-this-before-super": 2,
89 | "no-throw-literal": 2,
90 | "no-trailing-spaces": 0,
91 | "no-undef": 2,
92 | "no-undef-init": 2,
93 | "no-unexpected-multiline": 2,
94 | "no-unneeded-ternary": [2, { "defaultAssignment": false }],
95 | "no-unreachable": 2,
96 | "no-unused-vars": [2, { "vars": "all", "args": "none" }],
97 | "no-useless-call": 0,
98 | "no-with": 2,
99 | "one-var": [0, { "initialized": "never" }],
100 | "operator-linebreak": [0, "after", { "overrides": { "?": "before", ":": "before" } }],
101 | "padded-blocks": [0, "never"],
102 | "quotes": [2, "single", "avoid-escape"],
103 | "radix": 2,
104 | "semi": [2, "always"],
105 | "semi-spacing": [2, { "before": false, "after": true }],
106 | "space-before-blocks": [2, "always"],
107 | "space-before-function-paren": [2, "never"],
108 | "space-in-parens": [2, "never"],
109 | "space-infix-ops": 2,
110 | "space-unary-ops": [2, { "words": true, "nonwords": false }],
111 | "spaced-comment": [0, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }],
112 | "use-isnan": 2,
113 | "valid-typeof": 2,
114 | "wrap-iife": [2, "any"],
115 | "yoda": [2, "never"]
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Enforce Unix newlines
2 | * text eol=lf
3 |
4 | # binaries
5 | *.ai binary
6 | *.psd binary
7 | *.jpg binary
8 | *.gif binary
9 | *.png binary
10 | *.jpeg binary
11 |
--------------------------------------------------------------------------------
/.github/contributing.md:
--------------------------------------------------------------------------------
1 | # Contributing to section-matter
2 |
3 | First and foremost, thank you! We appreciate that you want to contribute to section-matter, your time is valuable, and your contributions mean a lot to us.
4 |
5 | ## Important!
6 |
7 | By contributing to this project, you:
8 |
9 | * Agree that you have authored 100% of the content
10 | * Agree that you have the necessary rights to the content
11 | * Agree that you have received the necessary permissions from your employer to make the contributions (if applicable)
12 | * Agree that the content you contribute may be provided under the Project license(s)
13 |
14 | ## Getting started
15 |
16 | **What does "contributing" mean?**
17 |
18 | Creating an issue is the simplest form of contributing to a project. But there are many ways to contribute, including the following:
19 |
20 | - Updating or correcting documentation
21 | - Feature requests
22 | - Bug reports
23 |
24 | If you'd like to learn more about contributing in general, the [Guide to Idiomatic Contributing](https://github.com/jonschlinkert/idiomatic-contributing) has a lot of useful information.
25 |
26 | **Showing support for section-matter**
27 |
28 | Please keep in mind that open source software is built by people like you, who spend their free time creating things the rest the community can use.
29 |
30 | Don't have time to contribute? No worries, here are some other ways to show your support for section-matter:
31 |
32 | - star the [project](https://github.com/jonschlinkert/section-matter)
33 | - tweet your support for section-matter
34 |
35 | ## Issues
36 |
37 | ### Before creating an issue
38 |
39 | Please try to determine if the issue is caused by an underlying library, and if so, create the issue there. Sometimes this is difficult to know. We only ask that you attempt to give a reasonable attempt to find out. Oftentimes the readme will have advice about where to go to create issues.
40 |
41 | Try to follow these guidelines
42 |
43 | - **Avoid creating issues for implementation help**. It's much better for discoverability, SEO, and semantics - to keep the issue tracker focused on bugs and feature requests - to ask implementation-related questions on [stackoverflow.com][so]
44 | - **Investigate the issue**:
45 | - **Check the readme** - oftentimes you will find notes about creating issues, and where to go depending on the type of issue.
46 | - Create the issue in the appropriate repository.
47 |
48 | ### Creating an issue
49 |
50 | Please be as descriptive as possible when creating an issue. Give us the information we need to successfully answer your question or address your issue by answering the following in your issue:
51 |
52 | - **version**: please note the version of section-matter are you using
53 | - **extensions, plugins, helpers, etc** (if applicable): please list any extensions you're using
54 | - **error messages**: please paste any error messages into the issue, or a [gist](https://gist.github.com/)
55 |
56 | ### Closing issues
57 |
58 | The original poster or the maintainer's of section-matter may close an issue at any time. Typically, but not exclusively, issues are closed when:
59 |
60 | - The issue is resolved
61 | - The project's maintainers have determined the issue is out of scope
62 | - An issue is clearly a duplicate of another issue, in which case the duplicate issue will be linked.
63 | - A discussion has clearly run its course
64 |
65 |
66 | ## Next steps
67 |
68 | **Tips for creating idiomatic issues**
69 |
70 | Spending just a little extra time to review best practices and brush up on your contributing skills will, at minimum, make your issue easier to read, easier to resolve, and more likely to be found by others who have the same or similar issue in the future. At best, it will open up doors and potential career opportunities by helping you be at your best.
71 |
72 | The following resources were hand-picked to help you be the most effective contributor you can be:
73 |
74 | - The [Guide to Idiomatic Contributing](https://github.com/jonschlinkert/idiomatic-contributing) is a great place for newcomers to start, but there is also information for experienced contributors there.
75 | - Take some time to learn basic markdown. We can't stress this enough. Don't start pasting code into GitHub issues before you've taken a moment to review this [markdown cheatsheet](https://gist.github.com/jonschlinkert/5854601)
76 | - The GitHub guide to [basic markdown](https://help.github.com/articles/markdown-basics/) is another great markdown resource.
77 | - Learn about [GitHub Flavored Markdown](https://help.github.com/articles/github-flavored-markdown/). And if you want to really go above and beyond, read [mastering markdown](https://guides.github.com/features/mastering-markdown/).
78 |
79 | At the very least, please try to:
80 |
81 | - Use backticks to wrap code. This ensures that it retains its formatting and isn't modified when it's rendered by GitHub, and makes the code more readable to others
82 | - When applicable, use syntax highlighting by adding the correct language name after the first "code fence"
83 |
84 |
85 | [so]: http://stackoverflow.com/questions/tagged/section-matter
86 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # always ignore files
2 | *.DS_Store
3 | .idea
4 | *.sublime-*
5 |
6 | # test related, or directories generated by tests
7 | test/actual
8 | actual
9 | coverage
10 | .nyc*
11 |
12 | # npm
13 | node_modules
14 | npm-debug.log
15 |
16 | # yarn
17 | yarn.lock
18 | yarn-error.log
19 |
20 | # misc
21 | _gh_pages
22 | _draft
23 | _drafts
24 | bower_components
25 | vendor
26 | temp
27 | tmp
28 | TODO.md
29 | package-lock.json
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | os:
3 | - linux
4 | - osx
5 | language: node_js
6 | node_js:
7 | - node
8 | - '8'
9 | - '7'
10 | - '6'
11 | - '5'
12 | - '4'
13 |
--------------------------------------------------------------------------------
/.verb.md:
--------------------------------------------------------------------------------
1 | ## Usage
2 |
3 | {%= apidocs("index.js") %}
4 |
5 | See available [options](#options).
6 |
7 | ## Example
8 |
9 | _With the exception of front-matter, **which must be the very first thing in the string**, the opening delimiter of all other sections must be followed by a string to be used as the `key` for the section._
10 |
11 | Given the following string:
12 |
13 | ```
14 | Content before the sections.
15 |
16 | ---
17 |
18 | More content.
19 |
20 | ---one
21 | title: One
22 | ---
23 |
24 | This is the first section.
25 | ```
26 |
27 | The following code:
28 |
29 | ```js
30 | console.log(sections(input));
31 | ```
32 |
33 | Results in:
34 |
35 | ```js
36 | {
37 | content: 'Content before the sections.\n\n---\n\nMore content.\n',
38 | sections: [
39 | {
40 | key: 'one',
41 | data: 'title: One',
42 | content: '\nThis is the first section.'
43 | }
44 | ]
45 | }
46 | ```
47 |
48 | ## Options
49 |
50 | ### options.section_parse
51 |
52 | **Type**: `function`
53 |
54 | **Default**: `undefined`
55 |
56 | Function to be called on each section after it's parsed from the string.
57 |
58 | **Example**
59 |
60 | Given the following string (`foo.md`):
61 |
62 | ```
63 | This is content before the sections.
64 |
65 | ---one
66 | title: First section
67 | ---
68 |
69 | This is section one.
70 |
71 | ---two
72 | title: Second section
73 | ---
74 |
75 | This is section two.
76 | ```
77 |
78 | Using the following custom `section_parse` function:
79 |
80 | ```js
81 | var fs = require('fs');
82 | var path = require('path');
83 | var yaml = require('js-yaml');
84 | var sections = require('section-matter');
85 |
86 | var str = fs.readFileSync('foo.md');
87 | var options = {
88 | section_parse: function(section) {
89 | console.log(section)
90 | section.key = 'section-' + section.key;
91 | section.data = yaml.safeLoad(section.data);
92 | }
93 | };
94 |
95 | var result = sections(str, options);
96 | console.log(result);
97 | ```
98 |
99 | Results in:
100 |
101 | ```js
102 | {
103 | content: 'This is content before the sections.\n',
104 | sections: [
105 | {
106 | key: 'section-one',
107 | data: { title: 'First section' },
108 | content: '\nThis is section one.\n'
109 | },
110 | {
111 | key: 'section-two',
112 | data: { title: 'Second section' },
113 | content: '\nThis is section two.\n'
114 | }
115 | ]
116 | }
117 | ```
118 |
119 | ### options.section_delimiter
120 |
121 | **Type**: `string`
122 |
123 | **Default**: `---`
124 |
125 | Delimiter to use as the separator for sections. _With the exception of front-matter, which must be the very first thing in the string, the opening delimiter of all other sections must be followed by a string to be used as the `key` for the section._
126 |
127 | **Example**
128 |
129 | ```js
130 | var input = '~~~\ntitle: bar\n~~~\n\nfoo\n~~~one\ntitle: One\n~~~\nThis is one';
131 | console.log(sections(input, {section_delimiter: '~~~'}));
132 | ```
133 |
134 | Results in:
135 |
136 | ```js
137 | {
138 | content: '',
139 | sections: [
140 | {
141 | key: '',
142 | data: 'title: bar',
143 | content: '\nfoo'
144 | },
145 | {
146 | key: 'one',
147 | data: 'title: One',
148 | content: 'This is one'
149 | }
150 | ]
151 | }
152 | ```
153 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 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 all
13 | 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 THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # section-matter [](https://www.npmjs.com/package/section-matter) [](https://npmjs.org/package/section-matter) [](https://npmjs.org/package/section-matter) [](https://travis-ci.org/jonschlinkert/section-matter)
2 |
3 | > Like front-matter, but supports multiple sections in a document.
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 | ## Install
8 |
9 | Install with [npm](https://www.npmjs.com/):
10 |
11 | ```sh
12 | $ npm install --save section-matter
13 | ```
14 |
15 | ## Usage
16 |
17 | **Params**
18 |
19 | * `input` **{String|Buffer|Object}**: If input is an object, it's `content` property must be a string or buffer.
20 | * **{Object}**: options
21 | * `returns` **{Object}**: Returns an object with a `content` string and an array of `sections` objects.
22 |
23 | **Example**
24 |
25 | ```js
26 | var sections = require('{%= name %}');
27 | var result = sections(input, options);
28 | // { content: 'Content before sections', sections: [] }
29 | ```
30 |
31 | See available [options](#options).
32 |
33 | ## Example
34 |
35 | _With the exception of front-matter, **which must be the very first thing in the string**, the opening delimiter of all other sections must be followed by a string to be used as the `key` for the section._
36 |
37 | Given the following string:
38 |
39 | ```
40 | Content before the sections.
41 |
42 | ---
43 |
44 | More content.
45 |
46 | ---one
47 | title: One
48 | ---
49 |
50 | This is the first section.
51 | ```
52 |
53 | The following code:
54 |
55 | ```js
56 | console.log(sections(input));
57 | ```
58 |
59 | Results in:
60 |
61 | ```js
62 | {
63 | content: 'Content before the sections.\n\n---\n\nMore content.\n',
64 | sections: [
65 | {
66 | key: 'one',
67 | data: 'title: One',
68 | content: '\nThis is the first section.'
69 | }
70 | ]
71 | }
72 | ```
73 |
74 | ## Options
75 |
76 | ### options.section_parse
77 |
78 | **Type**: `function`
79 |
80 | **Default**: `undefined`
81 |
82 | Function to be called on each section after it's parsed from the string.
83 |
84 | **Example**
85 |
86 | Given the following string (`foo.md`):
87 |
88 | ```
89 | This is content before the sections.
90 |
91 | ---one
92 | title: First section
93 | ---
94 |
95 | This is section one.
96 |
97 | ---two
98 | title: Second section
99 | ---
100 |
101 | This is section two.
102 | ```
103 |
104 | Using the following custom `section_parse` function:
105 |
106 | ```js
107 | var fs = require('fs');
108 | var path = require('path');
109 | var yaml = require('js-yaml');
110 | var sections = require('section-matter');
111 |
112 | var str = fs.readFileSync('foo.md');
113 | var options = {
114 | section_parse: function(section) {
115 | console.log(section)
116 | section.key = 'section-' + section.key;
117 | section.data = yaml.safeLoad(section.data);
118 | }
119 | };
120 |
121 | var result = sections(str, options);
122 | console.log(result);
123 | ```
124 |
125 | Results in:
126 |
127 | ```js
128 | {
129 | content: 'This is content before the sections.\n',
130 | sections: [
131 | {
132 | key: 'section-one',
133 | data: { title: 'First section' },
134 | content: '\nThis is section one.\n'
135 | },
136 | {
137 | key: 'section-two',
138 | data: { title: 'Second section' },
139 | content: '\nThis is section two.\n'
140 | }
141 | ]
142 | }
143 | ```
144 |
145 | ### options.section_delimiter
146 |
147 | **Type**: `string`
148 |
149 | **Default**: `---`
150 |
151 | Delimiter to use as the separator for sections. _With the exception of front-matter, which must be the very first thing in the string, the opening delimiter of all other sections must be followed by a string to be used as the `key` for the section._
152 |
153 | **Example**
154 |
155 | ```js
156 | var input = '~~~\ntitle: bar\n~~~\n\nfoo\n~~~one\ntitle: One\n~~~\nThis is one';
157 | console.log(sections(input, {section_delimiter: '~~~'}));
158 | ```
159 |
160 | Results in:
161 |
162 | ```js
163 | {
164 | content: '',
165 | sections: [
166 | {
167 | key: '',
168 | data: 'title: bar',
169 | content: '\nfoo'
170 | },
171 | {
172 | key: 'one',
173 | data: 'title: One',
174 | content: 'This is one'
175 | }
176 | ]
177 | }
178 | ```
179 |
180 | ## About
181 |
182 |
183 | Contributing
184 |
185 | Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
186 |
187 | Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
188 |
189 |
190 |
191 |
192 | Running Tests
193 |
194 | 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:
195 |
196 | ```sh
197 | $ npm install && npm test
198 | ```
199 |
200 |
201 |
202 |
203 | Building docs
204 |
205 | _(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.)_
206 |
207 | To generate the readme, run the following command:
208 |
209 | ```sh
210 | $ npm install -g verbose/verb#dev verb-generate-readme && verb
211 | ```
212 |
213 |
214 |
215 | ### Related projects
216 |
217 | You might also be interested in these projects:
218 |
219 | * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit")
220 | * [gray-matter](https://www.npmjs.com/package/gray-matter): Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML… [more](https://github.com/jonschlinkert/gray-matter) | [homepage](https://github.com/jonschlinkert/gray-matter "Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML front matter by default, but also has support for YAML, JSON, TOML or Coffee Front-Matter, with options to set custom delimiters. Used by metalsmith, assemble, verb and ")
221 | * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.")
222 |
223 | ### Author
224 |
225 | **Jon Schlinkert**
226 |
227 | * [github/jonschlinkert](https://github.com/jonschlinkert)
228 | * [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
229 |
230 | ### License
231 |
232 | Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
233 | Released under the [MIT License](LICENSE).
234 |
235 | ***
236 |
237 | _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on October 23, 2017._
--------------------------------------------------------------------------------
/examples/basic.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var path = require('path');
3 | var yaml = require('js-yaml');
4 | var sections = require('..');
5 |
6 | var str = fs.readFileSync(path.join(__dirname, 'fixtures/basic.md'));
7 | var result = sections(str);
8 | console.log(result);
9 |
--------------------------------------------------------------------------------
/examples/example-parse.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var path = require('path');
3 | var yaml = require('js-yaml');
4 | var sections = require('..');
5 |
6 | var str = fs.readFileSync(path.join(__dirname, 'fixtures/parse.md'));
7 | var options = {
8 | section_parse: function(section) {
9 | console.log(section)
10 | section.key = 'section-' + section.key;
11 | section.data = yaml.safeLoad(section.data);
12 | }
13 | };
14 |
15 | var result = sections(str, options);
16 | console.log(result);
17 |
--------------------------------------------------------------------------------
/examples/fixtures/basic.md:
--------------------------------------------------------------------------------
1 | Content before the sections.
2 |
3 | ---
4 |
5 | More content.
6 |
7 | ---one
8 | title: One
9 | ---
10 |
11 | This is section one.
--------------------------------------------------------------------------------
/examples/fixtures/parse.md:
--------------------------------------------------------------------------------
1 | This is content before the sections.
2 |
3 | ---one
4 | title: First section
5 | ---
6 |
7 | This is section one.
8 |
9 | ---two
10 | title: Second section
11 | ---
12 |
13 | This is section two.
14 |
--------------------------------------------------------------------------------
/examples/fixtures/sections.md:
--------------------------------------------------------------------------------
1 | ---yaml
2 | title: I'm front matter
3 | ---
4 |
5 | This page has front matter that should be parsed before the sections.
6 |
7 | ---aaa
8 | title: First section
9 | ---
10 |
11 | Section one.
12 |
13 | ---bbb
14 | title: Second section
15 | ---
16 |
17 | Part 1.
18 |
19 | ---
20 |
21 | Part 2.
22 |
23 | ---
24 |
25 | Part 3.
26 |
27 | ---ccc
28 | title: Third section
29 | ---
30 |
31 | Section three.
32 |
--------------------------------------------------------------------------------
/examples/sections.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var fs = require('fs');
4 | var path = require('path');
5 | var yaml = require('js-yaml');
6 | var sections = require('..');
7 | var str = fs.readFileSync(path.join(__dirname, 'fixtures', 'sections.md'));
8 |
9 | var opts = {
10 | parse: function(section, file) {
11 | if (typeof section.data === 'string' && section.data.trim() !== '') {
12 | section.data = yaml.safeLoad(section.data.trim());
13 | }
14 | section.content = section.content.trim();
15 | console.log(section);
16 | console.log();
17 | console.log();
18 | }
19 | };
20 |
21 | var res = sections(str, opts);
22 | console.log(res);
23 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var typeOf = require('kind-of');
4 | var extend = require('extend-shallow');
5 |
6 | /**
7 | * Parse sections in `input` with the given `options`.
8 | *
9 | * ```js
10 | * var sections = require('{%= name %}');
11 | * var result = sections(input, options);
12 | * // { content: 'Content before sections', sections: [] }
13 | * ```
14 | * @param {String|Buffer|Object} `input` If input is an object, it's `content` property must be a string or buffer.
15 | * @param {Object} options
16 | * @return {Object} Returns an object with a `content` string and an array of `sections` objects.
17 | * @api public
18 | */
19 |
20 | module.exports = function(input, options) {
21 | if (typeof options === 'function') {
22 | options = { parse: options };
23 | }
24 |
25 | var file = toObject(input);
26 | var defaults = {section_delimiter: '---', parse: identity};
27 | var opts = extend({}, defaults, options);
28 | var delim = opts.section_delimiter;
29 | var lines = file.content.split(/\r?\n/);
30 | var sections = null;
31 | var section = createSection();
32 | var content = [];
33 | var stack = [];
34 |
35 | function initSections(val) {
36 | file.content = val;
37 | sections = [];
38 | content = [];
39 | }
40 |
41 | function closeSection(val) {
42 | if (stack.length) {
43 | section.key = getKey(stack[0], delim);
44 | section.content = val;
45 | opts.parse(section, sections);
46 | sections.push(section);
47 | section = createSection();
48 | content = [];
49 | stack = [];
50 | }
51 | }
52 |
53 | for (var i = 0; i < lines.length; i++) {
54 | var line = lines[i];
55 | var len = stack.length;
56 | var ln = line.trim();
57 |
58 | if (isDelimiter(ln, delim)) {
59 | if (ln.length === 3 && i !== 0) {
60 | if (len === 0 || len === 2) {
61 | content.push(line);
62 | continue;
63 | }
64 | stack.push(ln);
65 | section.data = content.join('\n');
66 | content = [];
67 | continue;
68 | }
69 |
70 | if (sections === null) {
71 | initSections(content.join('\n'));
72 | }
73 |
74 | if (len === 2) {
75 | closeSection(content.join('\n'));
76 | }
77 |
78 | stack.push(ln);
79 | continue;
80 | }
81 |
82 | content.push(line);
83 | }
84 |
85 | if (sections === null) {
86 | initSections(content.join('\n'));
87 | } else {
88 | closeSection(content.join('\n'));
89 | }
90 |
91 | file.sections = sections;
92 | return file;
93 | };
94 |
95 | function isDelimiter(line, delim) {
96 | if (line.slice(0, delim.length) !== delim) {
97 | return false;
98 | }
99 | if (line.charAt(delim.length + 1) === delim.slice(-1)) {
100 | return false;
101 | }
102 | return true;
103 | }
104 |
105 | function toObject(input) {
106 | if (typeOf(input) !== 'object') {
107 | input = { content: input };
108 | }
109 |
110 | if (typeof input.content !== 'string' && !isBuffer(input.content)) {
111 | throw new TypeError('expected a buffer or string');
112 | }
113 |
114 | input.content = input.content.toString();
115 | input.sections = [];
116 | return input;
117 | }
118 |
119 | function getKey(val, delim) {
120 | return val ? val.slice(delim.length).trim() : '';
121 | }
122 |
123 | function createSection() {
124 | return { key: '', data: '', content: '' };
125 | }
126 |
127 | function identity(val) {
128 | return val;
129 | }
130 |
131 | function isBuffer(val) {
132 | if (val && val.constructor && typeof val.constructor.isBuffer === 'function') {
133 | return val.constructor.isBuffer(val);
134 | }
135 | return false;
136 | }
137 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "section-matter",
3 | "description": "Like front-matter, but supports multiple sections in a document.",
4 | "version": "1.0.0",
5 | "homepage": "https://github.com/jonschlinkert/section-matter",
6 | "author": "Jon Schlinkert (https://github.com/jonschlinkert)",
7 | "repository": "jonschlinkert/section-matter",
8 | "bugs": {
9 | "url": "https://github.com/jonschlinkert/section-matter/issues"
10 | },
11 | "license": "MIT",
12 | "files": [
13 | "index.js"
14 | ],
15 | "main": "index.js",
16 | "engines": {
17 | "node": ">=4"
18 | },
19 | "scripts": {
20 | "test": "mocha"
21 | },
22 | "dependencies": {
23 | "extend-shallow": "^2.0.1",
24 | "kind-of": "^6.0.0"
25 | },
26 | "devDependencies": {
27 | "gulp-format-md": "^1.0.0",
28 | "js-yaml": "^3.10.0",
29 | "mocha": "^4.0.1"
30 | },
31 | "keywords": [
32 | "matter",
33 | "section"
34 | ],
35 | "verb": {
36 | "toc": false,
37 | "layout": "default",
38 | "tasks": [
39 | "readme"
40 | ],
41 | "plugins": [
42 | "gulp-format-md"
43 | ],
44 | "related": {
45 | "list": [
46 | "gray-matter",
47 | "assemble",
48 | "verb"
49 | ]
50 | },
51 | "lint": {
52 | "reflinks": true
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/test/fixtures/hr.md:
--------------------------------------------------------------------------------
1 | ---yaml
2 | title: I'm front matter
3 | ---
4 |
5 | This page has front matter that should be parsed before the sections.
6 |
7 | ---aaa
8 | title: First section
9 | ---
10 |
11 | Section one.
12 |
13 | ---bbb
14 | title: Non-section horizontal rules
15 | ---
16 |
17 | Part 1.
18 |
19 | ---
20 |
21 | Part 2.
22 |
23 | ---
24 |
25 | Part 3.
26 |
27 | ---ccc
28 | title: Third section
29 | ---
30 |
31 | Section three.
32 |
--------------------------------------------------------------------------------
/test/fixtures/multiple.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: bar
3 | ---
4 |
5 | foo
6 |
7 | ---one
8 | title: One
9 | ---
10 | This is one
11 |
12 | ---two
13 | title: Two
14 | ---
15 | This is two
16 |
--------------------------------------------------------------------------------
/test/test.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | require('mocha');
4 | var fs = require('fs');
5 | var path = require('path');
6 | var assert = require('assert');
7 | var yaml = require('js-yaml');
8 | var sections = require('..');
9 | var fixtures = path.join.bind(path, __dirname, 'fixtures');
10 |
11 | function read(name) {
12 | return fs.readFileSync(fixtures(name), 'utf8');
13 | }
14 |
15 | describe('section-matter', function() {
16 | it('should export a function', function() {
17 | assert.equal(typeof sections, 'function');
18 | });
19 |
20 | it('should throw an error when invalid args are passed', function() {
21 | assert.throws(function() {
22 | sections();
23 | });
24 | });
25 |
26 | it('should return a file object', function() {
27 | assert.deepEqual(sections(''), { content: '', sections: [] });
28 | assert.deepEqual(sections('foo'), { content: 'foo', sections: [] });
29 | });
30 |
31 | it('should correctly parse non-sections', function() {
32 | assert.deepEqual(sections('foo\n---\nbar'), {
33 | content: 'foo\n---\nbar',
34 | sections: []
35 | });
36 |
37 | assert.deepEqual(sections('foo\n---\nbar\n---'), {
38 | content: 'foo\n---\nbar\n---',
39 | sections: []
40 | });
41 | });
42 |
43 | it('should parse front-matter without language', function() {
44 | assert.deepEqual(sections('---\ntitle: bar\n---\n\nfoo'), {
45 | content: '',
46 | sections: [{ key: '', data: 'title: bar', content: '\nfoo' }]
47 | });
48 |
49 | assert.deepEqual(sections('---\nfoo\n---\nbar'), {
50 | content: '',
51 | sections: [{ key: '', data: 'foo', content: 'bar' }]
52 | });
53 | });
54 |
55 | it('should parse front-matter with language', function() {
56 | var input = '---json\n{"title": "bar"}\n---\n\nfoo';
57 |
58 | assert.deepEqual(sections(input), {
59 | content: '',
60 | sections: [
61 | {
62 | key: 'json',
63 | data: '{"title": "bar"}',
64 | content: '\nfoo'
65 | }
66 | ]
67 | });
68 | });
69 |
70 | it('should parse a section', function() {
71 | var input = '---\ntitle: bar\n---\n\nfoo\n---one\ntitle: One\n---\nThis is one';
72 |
73 | assert.deepEqual(sections(input), {
74 | content: '',
75 | sections: [
76 | {
77 | key: '',
78 | data: 'title: bar',
79 | content: '\nfoo'
80 | },
81 | {
82 | key: 'one',
83 | data: 'title: One',
84 | content: 'This is one'
85 | }
86 | ]
87 | });
88 | });
89 |
90 | it('should use custom section_delimiter', function() {
91 | var input = '~~~\ntitle: bar\n~~~\n\nfoo\n~~~one\ntitle: One\n~~~\nThis is one';
92 |
93 | assert.deepEqual(sections(input, {section_delimiter: '~~~'}), {
94 | content: '',
95 | sections: [
96 | {
97 | key: '',
98 | data: 'title: bar',
99 | content: '\nfoo'
100 | },
101 | {
102 | key: 'one',
103 | data: 'title: One',
104 | content: 'This is one'
105 | }
106 | ]
107 | });
108 | });
109 |
110 | it('should use a custom parser on sections', function() {
111 | var input = '---\ntitle: bar\n---\n\nfoo\n---one\ntitle: One\n---\nThis is one';
112 |
113 | function parse(section) {
114 | section.data = yaml.safeLoad(section.data);
115 | }
116 |
117 | assert.deepEqual(sections(input, parse), {
118 | content: '',
119 | sections: [
120 | {
121 | key: '',
122 | data: { title: 'bar' },
123 | content: '\nfoo'
124 | },
125 | {
126 | key: 'one',
127 | data: { title: 'One' },
128 | content: 'This is one'
129 | }
130 | ]
131 | });
132 | });
133 |
134 | it('should parse multiple sections', function() {
135 | var input = read('multiple.md');
136 | assert.deepEqual(sections(input), {
137 | content: '',
138 | sections: [
139 | {
140 | key: '',
141 | data: 'title: bar',
142 | content: '\nfoo\n'
143 | },
144 | {
145 | key: 'one',
146 | data: 'title: One',
147 | content: 'This is one\n'
148 | },
149 | {
150 | key: 'two',
151 | data: 'title: Two',
152 | content: 'This is two\n'
153 | }
154 | ]
155 | });
156 | });
157 |
158 | it('should not parse non-sections', function() {
159 | var input = read('hr.md');
160 | assert.deepEqual(sections(input), {
161 | content: '',
162 | sections: [
163 | {
164 | key: 'yaml',
165 | data: "title: I'm front matter",
166 | content: '\nThis page has front matter that should be parsed before the sections.\n'
167 | },
168 | {
169 | key: 'aaa',
170 | data: 'title: First section',
171 | content: '\nSection one.\n'
172 | },
173 | {
174 | key: 'bbb',
175 | data: 'title: Non-section horizontal rules',
176 | content: '\nPart 1.\n\n---\n\nPart 2.\n\n---\n\nPart 3.\n'
177 | },
178 | {
179 | key: 'ccc',
180 | data: 'title: Third section',
181 | content: '\nSection three.\n'
182 | }
183 | ]
184 | });
185 | });
186 | });
187 |
--------------------------------------------------------------------------------