removeComments function

String removeComments(
  1. String text, {
  2. String? language,
})

Remove comments from source text.

Supported language values:

  • 'c', 'cpp', 'java', 'dart', 'js', 'ts'// and /* */
  • 'python', 'ruby', 'shell', 'bash'#
  • 'html', 'xml'<!-- -->
  • 'sql'-- and /* */

If language is null, removes //, /* */, and # style comments.

Implementation

String removeComments(String text, {String? language}) {
  final lang = language?.toLowerCase();

  String removeLineComments(String src, String marker) {
    return src
        .split('\n')
        .map((line) {
          // Naive: does not handle strings containing the marker
          final idx = line.indexOf(marker);
          if (idx == -1) return line;
          // Check we are not inside a string (simple heuristic)
          final beforeMarker = line.substring(0, idx);
          final singleQuotes = "'".allMatches(beforeMarker).length;
          final doubleQuotes = '"'.allMatches(beforeMarker).length;
          if (singleQuotes % 2 != 0 || doubleQuotes % 2 != 0) return line;
          return line.substring(0, idx);
        })
        .join('\n');
  }

  String removeBlockComments(String src, String open, String close) {
    final buf = StringBuffer();
    var i = 0;
    while (i < src.length) {
      final openIdx = src.indexOf(open, i);
      if (openIdx == -1) {
        buf.write(src.substring(i));
        break;
      }
      buf.write(src.substring(i, openIdx));
      final closeIdx = src.indexOf(close, openIdx + open.length);
      if (closeIdx == -1) {
        // Unterminated block comment - remove to end
        break;
      }
      i = closeIdx + close.length;
    }
    return buf.toString();
  }

  var result = text;

  switch (lang) {
    case 'python' || 'ruby' || 'shell' || 'bash':
      result = removeLineComments(result, '#');
    case 'html' || 'xml':
      result = removeBlockComments(result, '<!--', '-->');
    case 'sql':
      result = removeLineComments(result, '--');
      result = removeBlockComments(result, '/*', '*/');
    case 'c' ||
        'cpp' ||
        'java' ||
        'dart' ||
        'js' ||
        'ts' ||
        'javascript' ||
        'typescript' ||
        'swift' ||
        'kotlin' ||
        'go' ||
        'rust':
      result = removeBlockComments(result, '/*', '*/');
      result = removeLineComments(result, '//');
    default:
      // General: remove all common comment styles
      result = removeBlockComments(result, '/*', '*/');
      result = removeLineComments(result, '//');
      result = removeLineComments(result, '#');
  }

  return result;
}