Expand description
§convert-to-spaces
Convert tabs to spaces in a string, respecting tab stop logic.
§Overview
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.
§Features
- Accurate Tab Stop Conversion: Converts
\t
characters into the correct number of spaces based on the current column position and a defined tab size. - Flexible Input: Accepts any type that can be referenced as a string (
&str
,String
,&String
, etc.) usingAsRef<str>
. - Configurable Tab Size: Easily specify how many spaces each tab stop represents.
- Lightweight: No dependencies, focusing solely on efficient whitespace conversion.
- MSRV 1.56: Access to entire Rust 2021 Edition.
- Public domain: No need to give credits. Fully free software.
§Installation
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
.
§Usage
The primary function provided by this crate is convert_to_spaces
.
Here’s how to use it:
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
}
§License
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.
Functions§
- convert_
to_ spaces - Converts tabs in a string to a specified number of spaces, respecting tab stop logic.