[Web] Highlight VAR and VAL tokens. Create macro for simple highlighting

This commit is contained in:
Araozu 2023-04-05 11:28:43 -05:00
parent 55b466f3b4
commit 04b373283c
2 changed files with 24 additions and 35 deletions

View File

@ -13,7 +13,8 @@
## v0.0.5 ## v0.0.5
- ... - Scan single line comments
- Refactor String token to include double quotes (") in its content
## v0.0.4 ## v0.0.4

View File

@ -1,5 +1,22 @@
use misti::TokenType; use misti::TokenType;
#[macro_export]
macro_rules! replace {
($classes:literal, $token:ident, $offset:ident, $output:ident) => {
{
let start_pos = $token.position;
let end_pos = $token.get_end_position();
let range = (start_pos + $offset)..(end_pos + $offset);
let html = format!("<span class=\"token {}\">{}</span>", $classes, $token.value);
$offset += 28 + $classes.len();
$output.replace_range(range, html.as_str());
}
};
}
pub fn highlight(input: &String) -> String { pub fn highlight(input: &String) -> String {
// The tokens come in order // The tokens come in order
let tokens = misti::tokenize(&input); let tokens = misti::tokenize(&input);
@ -19,29 +36,8 @@ pub fn highlight(input: &String) -> String {
for token in tokens.unwrap() { for token in tokens.unwrap() {
match &token.token_type { match &token.token_type {
TokenType::Datatype => { TokenType::Datatype => replace!("class-name", token, offset, output),
let start_pos = token.position; TokenType::Number => replace!("number", token, offset, output),
let end_pos = token.get_end_position();
let range = (start_pos + offset)..(end_pos + offset);
let html = format!("<span class=\"token class-name\">{}</span>", 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!("<span class=\"token number\">{}</span>", token.value);
offset += 34;
output.replace_range(range, html.as_str());
}
TokenType::String => { TokenType::String => {
let start_pos = token.position; let start_pos = token.position;
let end_pos = token.get_end_position(); let end_pos = token.get_end_position();
@ -53,17 +49,8 @@ pub fn highlight(input: &String) -> String {
output.replace_range(range, html.as_str()); output.replace_range(range, html.as_str());
} }
TokenType::Comment => { TokenType::Comment => replace!("comment", token, offset, output),
let start_pos = token.position; TokenType::VAL | TokenType::VAR => replace!("keyword", token, offset, output),
let end_pos = token.get_end_position();
let range = (start_pos + offset)..(end_pos + offset);
let html = format!("<span class=\"token comment\">{}</span>", token.value);
offset += 35;
output.replace_range(range, html.as_str());
}
_ => {} _ => {}
} }
} }
@ -71,6 +58,7 @@ pub fn highlight(input: &String) -> String {
output output
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;