eslint-plugin-unicorn
Version:
More than 300 powerful ESLint rules
30 lines (22 loc) • 1.3 kB
JavaScript
const linePattern = /(?<linebreak>\r\n|[\n\r\u2028\u2029])(?<line>[^\n\r\u2028\u2029]*)/g;
/**
Move multi-line text from one indentation to another.
The first line is kept as it is, because the text usually starts in the middle of a line. Every later line that starts with `sourceIndent` gets `targetIndent` in its place. Other lines are kept as they are. A line with only whitespace becomes empty. Line endings are kept.
It works on plain text, so it also changes lines inside a multi-line template literal or a line-continued string, which changes the value. A caller must withhold its fix, or not reindent, when the text has a multi-line token (`hasMultilineToken`).
Pass an empty `sourceIndent` to indent every later line by `targetIndent`.
@param {string} text - The text to reindent.
@param {string} sourceIndent - The indentation the text has now.
@param {string} targetIndent - The indentation the text should have.
@returns {string}
*/
export default function reindentText(text, sourceIndent, targetIndent) {
return text.replaceAll(linePattern, (_, linebreak, line) => {
if (line.trim() === '') {
return linebreak;
}
if (line.startsWith(sourceIndent)) {
return `${linebreak}${targetIndent}${line.slice(sourceIndent.length)}`;
}
return `${linebreak}${line}`;
});
}