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

fix enumeration of nested code blocks #10

Merged
merged 3 commits into from
Aug 9, 2022
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
22 changes: 19 additions & 3 deletions src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,18 @@ impl MDBook {
self
}

fn prefix_matches(line: &str, prefix: &String) -> bool {
let lang = line.trim_matches('`');
let prefix_length = line.len() - lang.len();
prefix_length == prefix.len()
}

fn parse_prefix(line: &str) -> (&str, &str) {
let lang = line.trim_matches('`');
let prefix_length = line.len() - lang.len();
(&line[0..prefix_length], lang)
}

fn enumerate_blocks(content: &String, target_language: &str) -> Vec<CodeSnippet> {
// Read the file line by line looking for ```{target_language} blocks.
let mut result: Vec<CodeSnippet> = Vec::new();
Expand All @@ -259,9 +271,12 @@ impl MDBook {
let mut sample: String = String::new();
let mut index: i32 = 1;
let mut start: i32 = 1;
let mut prefix: String = String::new();
for line in content.lines() {
if line.starts_with("```") {
if in_block {
if line.starts_with("```")
&& (!in_block || (in_block && MDBook::prefix_matches(line, &prefix)))
{
if in_block && MDBook::prefix_matches(line, &prefix) {
in_block = false;
if is_target {
// this block is our target language!
Expand All @@ -274,8 +289,9 @@ impl MDBook {
is_target = false;
}
} else {
let (p, lang) = MDBook::parse_prefix(line);
prefix = p.to_string();
in_block = true;
let lang = line.trim_matches('`');
if lang == target_language {
is_target = true;
start = index;
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/html_handlebars/helpers/navigation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ fn render(
_h.template()
.ok_or_else(|| RenderError::new("Error with the handlebars template"))
.and_then(|t| {
let mut local_rc = rc.clone();
let local_ctx = Context::wraps(&context)?;
let mut local_rc = rc.clone();
t.render(r, &local_ctx, &mut local_rc, out)
})?;

Expand Down