Skip to main content

edit_content

Function edit_content 

Source
pub fn edit_content(
    path: &str,
    content: &str,
    re: &Regex,
    replacement: &str,
    literal: bool,
) -> (String, usize, Vec<Site>)
Expand description

Apply re/replacement to one file’s content, per line, preserving line terminators and every untouched byte. Returns the new content, the number of occurrences replaced, and the changed lines. literal selects literal replacement (no $ capture expansion), used for literal/glob finds.

§Examples

use coding_tools::edit::edit_content;
use coding_tools::pattern::compile;

let re = compile("foo").unwrap();
let (out, n, sites) = edit_content("f.rs", "a\nfoo bar\n  foo\n", &re, "X", true);
assert_eq!(n, 2);
// Untouched lines and the indentation on the changed line are preserved.
assert_eq!(out, "a\nX bar\n  X\n");
assert_eq!(sites.len(), 2);
assert_eq!(sites[1].after, "  X");

// A literal find does not expand `$` in the replacement.
let key = compile("KEY").unwrap();
assert_eq!(edit_content("f", "KEY\n", &key, "$1 cost", true).0, "$1 cost\n");