rStripComments function
Implementation
String rStripComments(String txt) {
List<String> lines = txt.split('\n');
List<String> result = [];
for (int i = 0; i < lines.length; i++) {
// Keep only those lines that are not comments and not empty.
if (!lines[i].startsWith('#') && lines[i].isNotEmpty) {
// Strip comments at the end of the line.
// Need to be clever to not strip # where # is embedded like in
//
// Ecdf(eds[eds$grp=="All",1], col="#E495A5", ...)
//
// Or like in
//
// title <- glue("Risk Chart — {mdesc}")
//
// Use a pattern with a negative lookbehind assertion (?<!\") which
// ensures that the # is not preceded by a ".
result.add(lines[i].replaceAll(RegExp(r' *(?<!\".*)#.*'), ''));
}
}
// Remove empty lines on joining.
String compressed = result.where((line) => line.trim().isNotEmpty).join('\n');
// Add newlines at the beginning and the end to ensure the commands are on
// lines of their own.
return '\n$compressed\n';
}