Skip to content

Provide code fragments feature #748

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/_media/example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import fetch from 'fetch'

const URL = 'https://example.com'
const PORT = 8080

/// [demo]
const result = fetch(`${URL}:${PORT}`)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
/// [demo]

result.then(console.log).catch(console.error)
15 changes: 15 additions & 0 deletions docs/embed-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ You will get it

[filename](_media/example.md ':include :type=code')

## Embedded code fragments
Sometimes you don't want to embed a whole file. Maybe because you need just a few lines but you want to compile and test the file in CI.

```markdown
[filename](_media/example.js ':include :type=code :fragment=demo')
```

In your code file you need to surround the fragment between `/// [demo]` lines (before and after the fragment).
Alternatively you can use `### [demo]`.

Example:

[filename](_media/example.js ':include :type=code :fragment=demo')


## Tag attribute

If you embed the file as `iframe`, `audio` and `video`, then you may need to set the attributes of these tags.
Expand Down
1 change: 1 addition & 0 deletions src/core/render/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ export class Compiler {
embed = compileMedia[type].call(this, href, title)
embed.type = type
}
embed.fragment = config.fragment

return embed
}
Expand Down
5 changes: 5 additions & 0 deletions src/core/render/embed.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ function walkFetchEmbed({embedTokens, compile, fetch}, cb) {
if (token.embed.type === 'markdown') {
embedToken = compile.lexer(text)
} else if (token.embed.type === 'code') {
if (token.embed.fragment) {
const fragment = token.embed.fragment
const pattern = new RegExp(`(?:###|\\/\\/\\/)\\s*\\[${fragment}\\]([\\s\\S]*)(?:###|\\/\\/\\/)\\s*\\[${fragment}\\]`)
text = ((text.match(pattern) || [])[1] || '').trim()
}
embedToken = compile.lexer(
'```' +
token.embed.lang +
Expand Down