New utils function escape_internal_quotes
authorRicardo Mones <ricardo@mones.org>
Mon, 4 Nov 2013 23:55:10 +0000 (00:55 +0100)
committerRicardo Mones <ricardo@mones.org>
Mon, 4 Nov 2013 23:55:10 +0000 (00:55 +0100)
Searchs for all quotation characters within a string, creating
(only if required) a copy with the quotation characters escaped.

src/common/utils.c
src/common/utils.h

index 53a9ddb47ac7f89bd3a254564e2340a3c5b4c775..fb4ba75f593a69c7f6ec78af323b156652cb6d32 100644 (file)
@@ -810,6 +810,47 @@ void extract_quote(gchar *str, gchar quote_chr)
        }
 }
 
        }
 }
 
+/* Returns a newly allocated string with all quote_chr not at the beginning
+   or the end of str escaped with '\' or the given str if not required. */
+gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
+{
+       register gchar *p, *q;
+       gchar *qstr;
+       int k = 0, l = 0;
+
+       if (str == NULL || *str == '\0')
+               return str;
+
+       /* search for unescaped quote_chr */
+       p = str;
+       if (*p == quote_chr)
+               ++p, ++l;
+       while (*p) {
+               if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
+                       ++k;
+               ++p, ++l;
+       }
+       if (!k) /* nothing to escape */
+               return str;
+
+       /* unescaped quote_chr found */
+       qstr = g_malloc(l + k + 1);
+       p = str;
+       q = qstr;
+       if (*p == quote_chr) {
+               *q = quote_chr;
+               ++p, ++q;
+       }
+       while (*p) {
+               if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
+                       *q++ = '\\';
+               *q++ = *p++;
+       }
+       *q = '\0';
+
+       return qstr;
+}
+
 void eliminate_address_comment(gchar *str)
 {
        register gchar *srcp, *destp;
 void eliminate_address_comment(gchar *str)
 {
        register gchar *srcp, *destp;
index b613499dc6af3b0eb86cb5c0dc08f4583eb1dca1..8766ff28e190ca8056792449bfb7c9aee8bba9a5 100644 (file)
@@ -338,6 +338,8 @@ void extract_parenthesis            (gchar          *str,
 
 void extract_quote                     (gchar          *str,
                                         gchar           quote_chr);
 
 void extract_quote                     (gchar          *str,
                                         gchar           quote_chr);
+gchar *escape_internal_quotes          (gchar          *str,
+                                        gchar           quote_chr);
 void eliminate_address_comment         (gchar          *str);
 gchar *strchr_with_skip_quote          (const gchar    *str,
                                         gint            quote_chr,
 void eliminate_address_comment         (gchar          *str);
 gchar *strchr_with_skip_quote          (const gchar    *str,
                                         gint            quote_chr,