Skip to main content

indent

Function indent 

Source
pub fn indent<'a>(text: &'a str, prefix: &str) -> Cow<'a, str>
Expand description

Indent each line by the given prefix.

§Examples


assert_eq!(indent("First line.\nSecond line.\n", "  "),
           "  First line.\n  Second line.\n");

When indenting, trailing whitespace is stripped from the prefix. This means that empty lines remain empty afterwards:


assert_eq!(indent("First line.\n\n\nSecond line.\n", "  "),
           "  First line.\n\n\n  Second line.\n");

Notice how "\n\n\n" remained as "\n\n\n".

This feature is useful when you want to indent text and have a space between your prefix and the text. In this case, you don’t want a trailing space on empty lines:


assert_eq!(indent("foo = 123\n\nprint(foo)\n", "# "),
           "# foo = 123\n#\n# print(foo)\n");

Notice how "\n\n" became "\n#\n" instead of "\n# \n" which would have trailing whitespace.

Leading and trailing whitespace coming from the text itself is kept unchanged:


assert_eq!(indent(" \t  Foo   ", "->"), "-> \t  Foo   ");