Skip to content
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

returning Events from a function #625

Open
danieleades opened this issue Dec 31, 2022 · 0 comments
Open

returning Events from a function #625

danieleades opened this issue Dec 31, 2022 · 0 comments

Comments

@danieleades
Copy link

I'm using this library in an MdBook extension (mdbook-d2)

It's working a treat, but there's one rough edge. I'd like to return some Events from a function, something like the following-

let image_path = "path/to/image/file.svg";
fn generate_inline_img(path: &str) -> Vec<Event<'_>> {
    let snippet = format!("![]({path})");
    Parser::new(&snippet).collect()
}
let _events = generate_inline_img(image_path);

this doesn't work, since the Parser is carrying a reference to the local snippet variable.
Basically i'd like a way to opt out of the zero-copy implementation for cases like this. I think this could be achieved if the Parser accepted an impl Into<CowStr<'input>> instead of &'input str.

My current workaround is to manually construct the snippet like so-

from mdbook-d2

    pub fn render(&self, ctx: RenderContext, content: &str) -> Vec<Event<'static>> {
        fs::create_dir_all(Path::new("src").join(self.output_dir())).unwrap();

        self.run_command(&ctx, content);

        let depth = ctx.path.ancestors().count() - 1;
        let rel_path: PathBuf = std::iter::repeat(Path::new(".."))
            .take(depth)
            .collect::<PathBuf>()
            .join(self.relative_file_path(&ctx));

        vec![
            Event::Start(Tag::Image(
                LinkType::Inline,
                rel_path.to_string_lossy().to_string().into(),
                CowStr::Borrowed(""),
            )),
            Event::End(Tag::Image(
                LinkType::Inline,
                rel_path.to_string_lossy().to_string().into(),
                CowStr::Borrowed(""),
            )),
        ]
    }

or am I perhaps taking the wrong approach entirely in this preprocessor?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants