From 0588e1f2fe35d24354f59f1e782c1f35194acd0b Mon Sep 17 00:00:00 2001 From: Araozu Date: Sun, 2 Apr 2023 19:38:17 -0500 Subject: [PATCH] [Web] Highlight multiple tokens (datatype, number, string) --- doc-generator/src/generator/inline_code.rs | 60 +++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/doc-generator/src/generator/inline_code.rs b/doc-generator/src/generator/inline_code.rs index ef2e637..789f72f 100644 --- a/doc-generator/src/generator/inline_code.rs +++ b/doc-generator/src/generator/inline_code.rs @@ -23,6 +23,7 @@ impl Printable for InlineCode { } fn highlight(input: &String) -> String { + // The tokens come in order let tokens = misti::tokenize(&input); if tokens.is_err() { @@ -34,6 +35,9 @@ fn highlight(input: &String) -> String { } let mut output = input.clone(); + // Offset to the position of the tokens in the string, to allow + // several tokens to be highlighted + let mut offset = 0; for token in tokens.unwrap() { match &token.token_type { @@ -41,9 +45,34 @@ fn highlight(input: &String) -> String { let start_pos = token.position; let end_pos = token.get_end_position(); - let range = start_pos..end_pos; + let range = (start_pos + offset)..(end_pos + offset); let html = format!("{}", token.value); + // 38 is the number of extra characters added to the token + offset += 38; + + output.replace_range(range, html.as_str()); + } + TokenType::Number => { + let start_pos = token.position; + let end_pos = token.get_end_position(); + + let range = (start_pos + offset)..(end_pos + offset); + let html = format!("{}", token.value); + + offset += 34; + + output.replace_range(range, html.as_str()); + } + TokenType::String => { + let start_pos = token.position; + let end_pos = token.get_end_position(); + + let range = (start_pos + offset)..(end_pos + offset); + let html = format!("\"{}\"", token.value); + + offset += 34; + output.replace_range(range, html.as_str()); } _ => {} @@ -69,4 +98,33 @@ mod tests { highlight(&String::from("Num")) ) } + + #[test] + fn should_highlight_number() { + assert_eq!( + "322", + highlight(&String::from("322")) + ) + } + + #[test] + fn should_highlight_string() { + assert_eq!( + "\"Hello\"", + highlight(&String::from("\"Hello\"")) + ) + } + + #[test] + fn should_highlight_multiple_tokens() { + assert_eq!( + "Str x = 322", + highlight(&String::from("Str x = 322")) + ); + + assert_eq!( + "Str x = \"hello\" 322", + highlight(&String::from("Str x = \"hello\" 322")) + ); + } }