From ed1a216121e1deb16e1cfb900a66bf17ad7f9247 Mon Sep 17 00:00:00 2001 From: CrazyMerlyn Date: Thu, 23 Mar 2017 23:24:26 +0530 Subject: [PATCH] Fix header links Header fragment links now use "id" attribute instead of the depreciated "name" attribute. Similar headers are given numbered ids to avoid id collisions. For instance, if there are three headers named "Example", their ids would be "#example", "#example-1", and "#example-2" respectively. --- src/renderer/html_handlebars/hbs_renderer.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/renderer/html_handlebars/hbs_renderer.rs b/src/renderer/html_handlebars/hbs_renderer.rs index a36fc83a..6d49f21d 100644 --- a/src/renderer/html_handlebars/hbs_renderer.rs +++ b/src/renderer/html_handlebars/hbs_renderer.rs @@ -11,6 +11,7 @@ use std::fs::{self, File}; use std::error::Error; use std::io::{self, Read}; use std::collections::BTreeMap; +use std::collections::HashMap; use handlebars::Handlebars; @@ -229,6 +230,7 @@ fn make_data(book: &MDBook) -> Result fn build_header_links(html: String, filename: &str) -> String { let regex = Regex::new(r"(.*?)").unwrap(); + let mut id_counter = HashMap::new(); regex.replace_all(&html, |caps: &Captures| { let level = &caps[1]; @@ -254,7 +256,16 @@ fn build_header_links(html: String, filename: &str) -> String { } }).collect::(); - format!("{text}", + let id_count = *id_counter.get(&id).unwrap_or(&0); + id_counter.insert(id.clone(), id_count + 1); + + let id = if id_count > 0 { + format!("{}-{}", id, id_count) + } else { + id + }; + + format!("{text}", level=level, id=id, text=text, filename=filename) }).into_owned() }