1 /*
2 File: quote.c
3
4 Copyright (C) 2003 Andreas Gruenbacher <andreas.gruenbacher@gmail.com>
5
6 This program is free software; you can redistribute it and/or modify it under
7 the terms of the GNU Lesser General Public License as published by the
8 Free Software Foundation; either version 2.1 of the License, or (at
9 your option) any later version.
10
11 This program is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
14 License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "config.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include "misc.h"
27
28 const char *quote(const char *str, const char *quote_chars)
29 {
30 static char *quoted_str;
31 static size_t quoted_str_len;
32 const unsigned char *s;
33 char *q;
34 size_t nonpr;
35
36 if (!str)
37 return str;
38
39 for (nonpr = 0, s = (unsigned char *)str; *s != '\0'; s++)
40 if (*s == '\\' || strchr(quote_chars, *s))
41 nonpr++;
42 if (nonpr == 0)
43 return str;
44
45 if (high_water_alloc((void **)"ed_str, "ed_str_len,
46 (s - (unsigned char *)str) + nonpr * 3 + 1))
47 return NULL;
48 for (s = (unsigned char *)str, q = quoted_str; *s != '\0'; s++) {
49 if (*s == '\\' || strchr(quote_chars, *s)) {
50 *q++ = '\\';
51 *q++ = '0' + ((*s >> 6) );
52 *q++ = '0' + ((*s >> 3) & 7);
53 *q++ = '0' + ((*s ) & 7);
54 } else
55 *q++ = *s;
56 }
57 *q++ = '\0';
58
59 return quoted_str;
60 }