hopefully made the documentation more clearer on what concerns preprocessor implementation with non rust languages

This commit is contained in:
pauliyobo 2021-03-05 21:11:29 +01:00
parent 536873ca26
commit 5637a66459
1 changed files with 30 additions and 3 deletions

View File

@ -34,8 +34,8 @@ command = "python3 /path/to/foo.py"
renderer = ["html", "epub"]
```
In typical unix style, all inputs to the plugin will be written to `stdin` as
JSON and `mdbook` will read from `stdout` if it is expecting output.
Once the preprocessor has been defined and the build process has started, MdBook will execute the command defined in the `preprocessor.foo.command` key passing the arguments support and the renderer name, monitoring the status code of the executed command.
If the status code retrieved is 0, the library will be sending through stdin both the context and the book representation serialized in JSON format, and it'll be capturing the response from stdout, which will be the modified book which has to also be serialized in json format.
The easiest way to get started is by creating your own implementation of the
`Preprocessor` trait (e.g. in `lib.rs`) and then creating a shell binary which
@ -80,7 +80,7 @@ without accidentally breaking the document.
```rust
fn remove_emphasis(
num_removed_items: &mut usize,
chapter: &mut Chapter,
chapter: &mut Chapter,
) -> Result<String> {
let mut buf = String::with_capacity(chapter.content.len());
@ -106,6 +106,33 @@ fn remove_emphasis(
For everything else, have a look [at the complete example][example].
## implementing a preprocessor with a different language
The fact that MdBook utilizes stdin and stdout to communicate with the preprocessors, makes it easy for developers to implement them in a language different than rust.
The following code shows how to implement a simple preprocessor in python, which will modify the content of the first chapter.
The example will follow the configuration shown above with `preprocessor.foo.command` actually pointing to a python script. The code of said script is below:
```python
import json
import sys
if __name__ == '__main__':
if len(sys.argv) > 1: # we check if we received any argument
if sys.argv[1] == "supports":
# then we are good to return an exit status code of 0, since the other argument will just be the renderer's name
sys.exit(0)
# we will load both the context and the book representations from stdin
stdin = sys.stdin
context, book = json.load(stdin)
# and now, we can just modify the content of the first chapter
book['sections'][0]['Chapter']['content'] = '<h3>Hello</h3>'
# we are done with the book's modification, we can just print it to stdout,
print(json.dumps(book))
```
[preprocessor-docs]: https://docs.rs/mdbook/latest/mdbook/preprocess/trait.Preprocessor.html
[pc]: https://crates.io/crates/pulldown-cmark
[pctc]: https://crates.io/crates/pulldown-cmark-to-cmark