toMultiLine static method
Converts single line value
into prefix
ed multi line PO string.
For example, this call:
_toMultiLine("msgid", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
returns following:
msgid ""
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
"tempor incididunt ut labore et dolore magna aliqua."
Implementation
static String toMultiLine(
ExtractSettings settings, String prefix, String value) {
// We create multi lines just for strings that doesn't contain `\n` or are
// longer than the set text width including the length of the prefix.
if (!value.contains("\\n") &&
'$prefix "$value"'.length <= settings.textWidth) {
return '$prefix "$value"'; // Counting the quotes and the space as well.
}
// The ideal would be to split the text along `\n` and it would fit into
// the text width. Let's give it a try.
// Also, we need to put that `\n` back.
final lines = value.split("\\n");
for (int i = 0; i < lines.length - 1; i++) {
lines.insert(i, "${lines.removeAt(i)}\\n");
}
// Let's check how it went. We will go through each line and correct those
// that are longer than the set text width.
for (int i = 0; i < lines.length; i++) {
var line = lines[i];
// It worked? Then skip this line.
if (line.length + 2 <= settings.textWidth) {
continue;
}
// Remove the line from the list, we'll add two new ones back later.
lines.removeAt(i);
final words = line.split(" "); // List of words in the line.
var part = ""; // The first part of the line that fits in the set width.
// Gradually add words until they fit into the set text width.
// + 3 = quotes + space
while (part.length + words[0].length + 3 <= settings.textWidth) {
part += "${words.removeAt(0)} "; // Add the space back as well.
}
// Insert both parts of the line in the original place.
lines.insertAll(i, [part, line.replaceFirst(part, "")]);
}
return [
'$prefix ""',
// Filter out blank lines and enclose them in quotes.
...lines.where((line) => line.isNotEmpty).map((line) => '"$line"')
].join("\n"); // Concatenate the rows back into a single string.
}