From 69ecdace3bc17f4b9b731cad0969a596ef74748f Mon Sep 17 00:00:00 2001 From: The Mist Date: Sun, 7 Apr 2024 16:17:24 +0800 Subject: [PATCH] [Fix] replace all tab character with space for correct render text (#77) --- generator/src/code.rs | 17 +++++++++++++++-- generator/src/components/editor/code.rs | 4 ++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/generator/src/code.rs b/generator/src/code.rs index b40f2d2..c1e6cde 100644 --- a/generator/src/code.rs +++ b/generator/src/code.rs @@ -11,7 +11,7 @@ fn min_width(width: f32) -> f32 { } pub fn calc_wh(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) { - let trimmed_text = trim_space(text); + let trimmed_text = prepare_code(text); let lines = trimmed_text.lines(); let max_length_line = lines.clone().into_iter().fold("", |max_length_line, cur| { if cur.len() > max_length_line.len() { @@ -26,7 +26,16 @@ pub fn calc_wh(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) { (min_width(width), height) } -pub fn trim_space(text: &str) -> String { +// The tab character is incorrectly render using cosmic, need to replace all tab with space +// before render the code +fn replace_tab_to_space(text: &str) -> String { + let spaces = " ".repeat(2); + + str::replace(text, "\t", &spaces) +} + +// If the first line have indention, remove the same indention from subsequent lines +fn trim_space(text: &str) -> String { let lines = text.split("\n").collect::>(); let first_line = lines.first().unwrap(); let head_spaces = Regex::new(r"^(\s*)").unwrap().find(first_line); @@ -47,3 +56,7 @@ pub fn trim_space(text: &str) -> String { None => text.to_string(), } } + +pub fn prepare_code(code: &str) -> String { + replace_tab_to_space(&trim_space(&code)) +} diff --git a/generator/src/components/editor/code.rs b/generator/src/components/editor/code.rs index 04a5631..ea1ca9a 100644 --- a/generator/src/components/editor/code.rs +++ b/generator/src/components/editor/code.rs @@ -1,5 +1,5 @@ use crate::{ - code::{calc_wh, trim_space}, + code::{calc_wh, prepare_code}, components::interface::{ component::{Component, ComponentContext, RenderParams}, render_error, @@ -71,7 +71,7 @@ impl Component for Code { impl Code { pub fn new(value: String, line_height: f32, font_size: f32) -> Code { Code { - value: trim_space(&value), + value: prepare_code(&value), line_height, font_size, children: vec![],