Crates.io | convert-to-spaces |
lib.rs | convert-to-spaces |
version | 0.1.1 |
created_at | 2025-05-29 22:20:22.348385+00 |
updated_at | 2025-05-30 01:43:38.162838+00 |
description | Convert tabs to spaces in a string |
homepage | https://gitlab.com/hsn10/convert-to-spaces |
repository | https://gitlab.com/hsn10/convert-to-spaces.git |
max_upload_size | |
id | 1694470 |
size | 16,733 |
Convert tabs to spaces in a string, respecting tab stop logic.
convert-to-spaces
is a lightweight Rust crate designed to precisely transform tab characters (\t
)
into the appropriate number of spaces.
Unlike simple find-and-replace, this crate correctly applies tab stop logic,
ensuring that text aligns to the next multiple of your specified tab size.
This is crucial for maintaining consistent indentation and code readability,
mimicking the behavior of modern text editors.
Whether you're processing code, cleaning up text files, or preparing content for display, convert-to-spaces
helps standardize your whitespace.
\t
characters into the correct number of spaces based on the current column position and a defined tab size.&str
, String
, &String
, etc.) using AsRef<str>
.Add convert-to-spaces
to your Cargo.toml
file:
[dependencies]
convert-to-spaces = "0.1" # Use the latest version from crates.io
Then, run cargo build or cargo update.
Here's how to use the convert_to_spaces function in your Rust project:
use convert_to_spaces::convert_to_spaces;
fn main() {
// Example 1: Basic conversion with a tab size of 4
let input1 = "fn main() {\n\tprintln!(\"Hello, world!\");\n}";
let output1 = convert_to_spaces(input1, 4);
println!("Input:\n{}", input1);
println!("Output (tab size 4):\n{}", output1);
// Expected output:
// fn main() {
// println!("Hello, world!");
// }
println!("--------------------");
// Example 2: Text that doesn't start at column 0
let input2 = " Some text\taligned"; // 4 spaces before "Some text"
let output2 = convert_to_spaces(input2, 8);
println!("Input:\n{}", input2);
println!("Output (tab size 8):\n{}", output2);
// Expected output:
// Some text aligned
// ("Some text" is 9 chars. current_column=4+9=13. Next multiple of 8 after 13 is 16. Need 16-13=3 spaces)
println!("--------------------");
// Example 3: Zero tab size (effectively removes tabs)
let input3 = "Tab\tremoved";
let output3 = convert_to_spaces(input3, 0);
println!("Input:\n{}", input3);
println!("Output (tab size 0):\n{}", output3);
// Expected output:
// Tabremoved
}
fn convert_to_spaces <S: AsRef<str>> (input: S, tab_size: usize) -> String
This is free and unencumbered software released into the public domain.
You may use, modify, distribute, and contribute to this code without restriction. To the extent possible under law, the author(s) of this work waive all copyright and related rights.
Licensed under CC0-1.0 OR Unlicense.