From 0ac0301d72989f330512b6047389f6e08919b70d Mon Sep 17 00:00:00 2001 From: Mathieu David Date: Thu, 31 Dec 2015 19:25:02 +0100 Subject: [PATCH] Continue #29, Rust files can now be loaded with {{#playpen file.rs}}, they will be displayed as other code snippets included with markdown backticks except they have a playpen css class --- src/renderer/html_handlebars/hbs_renderer.rs | 2 +- .../html_handlebars/helpers/playpen.rs | 24 ++++++++++++++----- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/renderer/html_handlebars/hbs_renderer.rs b/src/renderer/html_handlebars/hbs_renderer.rs index 9f9e8f57..e877c43e 100644 --- a/src/renderer/html_handlebars/hbs_renderer.rs +++ b/src/renderer/html_handlebars/hbs_renderer.rs @@ -73,7 +73,7 @@ impl Renderer for HtmlHandlebars { // Parse for playpen links if let Some(p) = path.parent() { - helpers::playpen::render_playpen(&mut content, p); + content = helpers::playpen::render_playpen(&content, p); } // Render markdown using the pulldown-cmark crate diff --git a/src/renderer/html_handlebars/helpers/playpen.rs b/src/renderer/html_handlebars/helpers/playpen.rs index 7d25a3db..9b499903 100644 --- a/src/renderer/html_handlebars/helpers/playpen.rs +++ b/src/renderer/html_handlebars/helpers/playpen.rs @@ -1,11 +1,15 @@ +extern crate handlebars; + use std::path::{Path, PathBuf}; use std::fs::File; use std::io::Read; -pub fn render_playpen(s: &mut str, path: &Path) { + +pub fn render_playpen(s: &str, path: &Path) -> String { // When replacing one thing in a string by something with a different length, the indices // after that will not correspond, we therefore have to store the difference to correct this - let difference_index = 0; + let mut previous_end_index = 0; + let mut replaced = String::new(); for playpen in find_playpens(s, path) { @@ -20,15 +24,23 @@ pub fn render_playpen(s: &mut str, path: &Path) { let mut file_content = String::new(); if let Err(_) = file.read_to_string(&mut file_content) { continue }; + let replacement = String::new() + "
" + &file_content + "
"; + + replaced.push_str(&s[previous_end_index..playpen.start_index]); + replaced.push_str(&replacement); + previous_end_index = playpen.end_index; //println!("Playpen{{ {}, {}, {:?}, {} }}", playpen.start_index, playpen.end_index, playpen.rust_file, playpen.editable); } + replaced.push_str(&s[previous_end_index..]); + + replaced } #[derive(PartialOrd, PartialEq, Debug)] struct Playpen{ - start_index: u32, - end_index: u32, + start_index: usize, + end_index: usize, rust_file: PathBuf, editable: bool } @@ -59,8 +71,8 @@ fn find_playpens(s: &str, base_path: &Path) -> Vec { playpens.push( Playpen{ - start_index: i as u32, - end_index: end_i as u32, + start_index: i, + end_index: end_i, rust_file: base_path.join(PathBuf::from(params[0])), editable: editable, }