cql_noexport void cg_pretty_quote_plaintext()

in sources/encoders.c [238:297]


cql_noexport void cg_pretty_quote_plaintext(CSTR str, charbuf *output, uint32_t flags) {
  Contract(str);

  const char squote = '\'';
  bool_t inQuote = 0;
  bool_t multi_line = !!(flags & PRETTY_QUOTE_MULTI_LINE);
  bool_t for_json = !!(flags & PRETTY_QUOTE_JSON);

  bputc(output, '"');
  for (CSTR p = str; p[0]; p++) {
    // figure out if we're in quoted sql text, if we are then any newlines we see
    // are part of the string not part of our multi-line formatting.  They have to be escaped.
    if (!inQuote && p[0] == squote) {
      inQuote = 1;
      bprintf(output, "'");
    }
    else if (inQuote && p[0] == squote && p[1] == squote) {
      // escaped '' is escaped quote, stay in quoted mode
      bprintf(output, "''");
      // gobble the second quote since we just emitted it already
      // this way it has no way to fool us into leaving quoted mode (a previous bug)
      p++;
    }
    else if (inQuote && p[0] == squote) {
      inQuote = 0;
      bprintf(output, "'");
    }
    else if (!inQuote && p[0] == '\n') {
      if (multi_line) {
        // convert the newline to a space, break the string into multi-part literal
        bprintf(output, " \"\n  ");

        // use the embedded spaces to indent the string literal not to make the string fatter
        while (p[1] == ' ') {
          p++;
          bputc(output, ' ');
        }
        bputc(output, '"');
      }
      else {
        // emit the newline as a single space
        bputc(output, ' ');

        // eat any spaces that follow the newline
        while (p[1] == ' ') {
          p++;
        }
      }
    }
    else {
      if (for_json) {
        cg_encode_char_as_json_string_literal(p[0], output);
      }
      else {
        cg_encode_char_as_c_string_literal(p[0], output);
      }
    }
  }
  bputc(output, '"');
}