Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 38 additions & 6 deletions src/string_utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

///
pub fn trim_length_left(s: &str, width: usize) -> &str {
Expand All @@ -15,13 +15,36 @@ pub fn trim_length_left(s: &str, width: usize) -> &str {
s
}

//TODO: allow customize tabsize
const TAB_WIDTH: usize = 8;

// TODO: allow customize tabsize (e.g. via .editorconfig)
pub fn tabs_to_spaces(input: String) -> String {
if input.contains('\t') {
input.replace('\t', " ")
} else {
input
if !input.contains('\t') {
return input;
}

let mut out = String::with_capacity(input.len());
let mut column = 0usize;

for ch in input.chars() {
match ch {
'\t' => {
let spaces = TAB_WIDTH - (column % TAB_WIDTH);
out.extend(std::iter::repeat_n(' ', spaces));
column += spaces;
}
'\n' => {
out.push('\n');
column = 0;
}
ch => {
out.push(ch);
column += ch.width().unwrap_or(0);
}
}
}

out
}

/// This function will return a str slice which start at specified offset.
Expand Down Expand Up @@ -51,4 +74,13 @@ mod test {
assert_eq!(trim_length_left("👍foo", 3), "foo");
assert_eq!(trim_length_left("👍foo", 4), "foo");
}

#[test]
fn test_tabs_to_spaces() {
use super::tabs_to_spaces;

assert_eq!(tabs_to_spaces("no-tabs".into()), "no-tabs");
assert_eq!(tabs_to_spaces("\tfoo".into()), " foo");
assert_eq!(tabs_to_spaces("a\tb".into()), "a b");
}
}