From 74026fd847453f2b9f55839eece9d7c0436ac945 Mon Sep 17 00:00:00 2001 From: Michael Aaron Murphy Date: Wed, 18 Aug 2021 22:39:11 +0200 Subject: [PATCH] fix(calc): Improve string slicing of complex equations --- plugins/src/calc/mod.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/plugins/src/calc/mod.rs b/plugins/src/calc/mod.rs index 4830662..aa9eac5 100644 --- a/plugins/src/calc/mod.rs +++ b/plugins/src/calc/mod.rs @@ -123,6 +123,7 @@ async fn qcalc(regex: &mut Regex, expression: &str) -> Option { } let normalized = regex.replace_all(line, ""); + let mut normalized = normalized.as_ref(); if has_issue(&normalized) { return None; @@ -131,6 +132,22 @@ async fn qcalc(regex: &mut Regex, expression: &str) -> Option { output.push(' '); } + if normalized.starts_with('(') { + let mut level = 1; + for (byte_pos, character) in normalized[1..].char_indices() { + if character == '(' { + level += 1; + } else if character == ')' { + level -= 1; + + if level == 0 { + normalized = &normalized[byte_pos + 2..].trim_start(); + break; + } + } + } + } + let cut = if let Some(pos) = normalized.find('=') { pos + 1 } else if let Some(pos) = normalized.find('≈') { @@ -139,7 +156,13 @@ async fn qcalc(regex: &mut Regex, expression: &str) -> Option { return None; }; - output.push_str(normalized[cut..].trim_start()); + normalized = normalized[cut..].trim_start(); + + if normalized.starts_with('(') && normalized.ends_with(')') { + normalized = &normalized[1..normalized.len() - 1]; + } + + output.push_str(normalized); }; }