bdbb82080b6a5004b4486f873bd31af98b10b84d
[gnulib.git] / lib / quotearg.c
1 /* quotearg.c - quote arguments for output
2    Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by Paul Eggert <eggert@twinsun.com> */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <sys/types.h>
25 #include <quotearg.h>
26 #include <xalloc.h>
27
28 #include <ctype.h>
29 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
30 # define ISASCII(c) 1
31 #else
32 # define ISASCII(c) isascii (c)
33 #endif
34 #define ISPRINT(c) (ISASCII (c) && isprint (c))
35
36 #if ENABLE_NLS
37 # include <libintl.h>
38 # define _(text) gettext (text)
39 #else
40 # define _(text) text
41 #endif
42
43 #if HAVE_LIMITS_H
44 # include <limits.h>
45 #endif
46 #ifndef CHAR_BIT
47 # define CHAR_BIT 8
48 #endif
49 #ifndef UCHAR_MAX
50 # define UCHAR_MAX ((unsigned char) -1)
51 #endif
52
53 #if HAVE_STDLIB_H
54 # include <stdlib.h>
55 #endif
56
57 #if HAVE_STRING_H
58 # include <string.h>
59 #endif
60
61 #if HAVE_MBRTOWC && HAVE_WCHAR_H
62 # include <wchar.h>
63 #else
64 # define iswprint(wc) 1
65 # define mbrtowc(pwc, s, n, ps) 1
66 # define mbsinit(ps) 1
67 # define mbstate_t int
68 #endif
69
70 #define INT_BITS (sizeof (int) * CHAR_BIT)
71
72 struct quoting_options
73 {
74   /* Basic quoting style.  */
75   enum quoting_style style;
76
77   /* Quote the characters indicated by this bit vector even if the
78      quoting style would not normally require them to be quoted.  */
79   int quote_these_too[((UCHAR_MAX + 1) / INT_BITS
80                        + ((UCHAR_MAX + 1) % INT_BITS != 0))];
81 };
82
83 /* Names of quoting styles.  */
84 char const *const quoting_style_args[] =
85 {
86   "literal",
87   "shell",
88   "shell-always",
89   "c",
90   "escape",
91   "locale",
92   0
93 };
94
95 /* Correspondences to quoting style names.  */
96 enum quoting_style const quoting_style_vals[] =
97 {
98   literal_quoting_style,
99   shell_quoting_style,
100   shell_always_quoting_style,
101   c_quoting_style,
102   escape_quoting_style,
103   locale_quoting_style
104 };
105
106 /* The default quoting options.  */
107 static struct quoting_options default_quoting_options;
108
109 /* Allocate a new set of quoting options, with contents initially identical
110    to O if O is not null, or to the default if O is null.
111    It is the caller's responsibility to free the result.  */
112 struct quoting_options *
113 clone_quoting_options (struct quoting_options *o)
114 {
115   struct quoting_options *p
116     = (struct quoting_options *) xmalloc (sizeof (struct quoting_options));
117   *p = *(o ? o : &default_quoting_options);
118   return p;
119 }
120
121 /* Get the value of O's quoting style.  If O is null, use the default.  */
122 enum quoting_style
123 get_quoting_style (struct quoting_options *o)
124 {
125   return (o ? o : &default_quoting_options)->style;
126 }
127
128 /* In O (or in the default if O is null),
129    set the value of the quoting style to S.  */
130 void
131 set_quoting_style (struct quoting_options *o, enum quoting_style s)
132 {
133   (o ? o : &default_quoting_options)->style = s;
134 }
135
136 /* In O (or in the default if O is null),
137    set the value of the quoting options for character C to I.
138    Return the old value.  Currently, the only values defined for I are
139    0 (the default) and 1 (which means to quote the character even if
140    it would not otherwise be quoted).  */
141 int
142 set_char_quoting (struct quoting_options *o, char c, int i)
143 {
144   unsigned char uc = c;
145   int *p = (o ? o : &default_quoting_options)->quote_these_too + uc / INT_BITS;
146   int shift = uc % INT_BITS;
147   int r = (*p >> shift) & 1;
148   *p ^= ((i & 1) ^ r) << shift;
149   return r;
150 }
151
152 /* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
153    argument ARG (of size ARGSIZE), using QUOTING_STYLE and the
154    non-quoting-style part of O to control quoting.
155    Terminate the output with a null character, and return the written
156    size of the output, not counting the terminating null.
157    If BUFFERSIZE is too small to store the output string, return the
158    value that would have been returned had BUFFERSIZE been large enough.
159    If ARGSIZE is -1, use the string length of the argument for ARGSIZE.
160
161    This function acts like quotearg_buffer (BUFFER, BUFFERSIZE, ARG,
162    ARGSIZE, O), except it uses QUOTING_STYLE instead of the quoting
163    style specified by O, and O may not be null.  */
164
165 static size_t
166 quotearg_buffer_restyled (char *buffer, size_t buffersize,
167                           char const *arg, size_t argsize,
168                           enum quoting_style quoting_style,
169                           struct quoting_options const *o)
170 {
171   size_t i;
172   size_t len = 0;
173   char const *quote_string = 0;
174   size_t quote_string_len = 0;
175   int backslash_escapes = 0;
176
177 #define STORE(c) \
178     do \
179       { \
180         if (len < buffersize) \
181           buffer[len] = (c); \
182         len++; \
183       } \
184     while (0)
185
186   switch (quoting_style)
187     {
188     case c_quoting_style:
189       STORE ('"');
190       backslash_escapes = 1;
191       quote_string = "\"";
192       quote_string_len = 1;
193       break;
194
195     case escape_quoting_style:
196       backslash_escapes = 1;
197       break;
198
199     case locale_quoting_style:
200       for (quote_string = _("`"); *quote_string; quote_string++)
201         STORE (*quote_string);
202       backslash_escapes = 1;
203       quote_string = _("'");
204       quote_string_len = strlen (quote_string);
205       break;
206
207     case shell_always_quoting_style:
208       STORE ('\'');
209       quote_string = "'";
210       quote_string_len = 1;
211       break;
212
213     default:
214       break;
215     }
216
217   for (i = 0;  ! (argsize == (size_t) -1 ? arg[i] == '\0' : i == argsize);  i++)
218     {
219       unsigned char c;
220       unsigned char esc;
221
222       if (backslash_escapes
223           && quote_string_len
224           && i + quote_string_len <= argsize
225           && memcmp (arg + i, quote_string, quote_string_len) == 0)
226         STORE ('\\');
227
228       c = arg[i];
229       switch (c)
230         {
231         case '?':
232           switch (quoting_style)
233             {
234             case shell_quoting_style:
235               goto use_shell_always_quoting_style;
236
237             case c_quoting_style:
238               if (i + 2 < argsize && arg[i + 1] == '?')
239                 switch (arg[i + 2])
240                   {
241                   case '!': case '\'':
242                   case '(': case ')': case '-': case '/':
243                   case '<': case '=': case '>':
244                     /* Escape the second '?' in what would otherwise be
245                        a trigraph.  */
246                     i += 2;
247                     c = arg[i + 2];
248                     STORE ('?');
249                     STORE ('\\');
250                     STORE ('?');
251                     break;
252                   }
253               break;
254
255             default:
256               break;
257             }
258           break;
259
260 #if HAVE_C_BACKSLASH_A
261         case '\a': esc = 'a'; goto c_escape;
262 #endif
263         case '\b': esc = 'b'; goto c_escape;
264         case '\f': esc = 'f'; goto c_escape;
265         case '\n': esc = 'n'; goto c_and_shell_escape;
266         case '\r': esc = 'r'; goto c_and_shell_escape;
267         case '\t': esc = 't'; goto c_and_shell_escape;
268         case '\v': esc = 'v'; goto c_escape;
269         case '\\': esc = c; goto c_and_shell_escape;
270
271         c_and_shell_escape:
272           if (quoting_style == shell_quoting_style)
273             goto use_shell_always_quoting_style;
274         c_escape:
275           if (backslash_escapes)
276             {
277               c = esc;
278               goto store_escape;
279             }
280           break;
281
282         case '#': case '~':
283           if (i != 0)
284             break;
285           /* Fall through.  */
286         case ' ':
287         case '!': /* special in bash */
288         case '"': case '$': case '&':
289         case '(': case ')': case '*': case ';':
290         case '<': case '>': case '[':
291         case '^': /* special in old /bin/sh, e.g. SunOS 4.1.4 */
292         case '`': case '|':
293           /* A shell special character.  In theory, '$' and '`' could
294              be the first bytes of multibyte characters, which means
295              we should check them with mbrtowc, but in practice this
296              doesn't happen so it's not worth worrying about.  */
297           if (quoting_style == shell_quoting_style)
298             goto use_shell_always_quoting_style;
299           break;
300
301         case '\'':
302           switch (quoting_style)
303             {
304             case shell_quoting_style:
305               goto use_shell_always_quoting_style;
306
307             case shell_always_quoting_style:
308               STORE ('\'');
309               STORE ('\\');
310               STORE ('\'');
311               break;
312
313             default:
314               break;
315             }
316           break;
317
318         case '%': case '+': case ',': case '-': case '.': case '/':
319         case '0': case '1': case '2': case '3': case '4': case '5':
320         case '6': case '7': case '8': case '9': case ':': case '=':
321         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
322         case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
323         case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
324         case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
325         case 'Y': case 'Z': case ']': case '_': case 'a': case 'b':
326         case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
327         case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
328         case 'o': case 'p': case 'q': case 'r': case 's': case 't':
329         case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
330         case '{': case '}':
331           /* These characters don't cause problems, no matter what the
332              quoting style is.  They cannot start multibyte sequences.  */
333           break;
334
335         default:
336           /* If we have a multibyte sequence, copy it until we reach
337              its end, find an error, or come back to the initial shift
338              state.  For C-like styles, if the sequence has
339              unprintable characters, escape the whole sequence, since
340              we can't easily escape single characters within it.  */
341           {
342             /* Length of multibyte sequence found so far.  */
343             size_t m = 0;
344
345             int printable = 1;
346             mbstate_t mbstate;
347             memset (&mbstate, 0, sizeof mbstate);
348
349             if (argsize == (size_t) -1)
350               argsize = strlen (arg);
351
352             do
353               {
354                 wchar_t w;
355                 size_t bytes = mbrtowc (&w, &arg[i + m],
356                                         argsize - (i + m), &mbstate);
357                 if (bytes == 0)
358                   break;
359                 else if (bytes == (size_t) -1)
360                   {
361                     printable = 0;
362                     break;
363                   }
364                 else if (bytes == (size_t) -2)
365                   {
366                     printable = 0;
367                     while (i + m < argsize && arg[i + m])
368                       m++;
369                     break;
370                   }
371                 else
372                   {
373                     if (! iswprint (w))
374                       printable = 0;
375                     m += bytes;
376                   }
377               }
378             while (! mbsinit (&mbstate));
379
380             if (m <= 1)
381               {
382                 /* Escape a unibyte character like a multibyte
383                    sequence if using backslash escapes, and if the
384                    character is not printable.  */
385                 m = backslash_escapes && ! ISPRINT (c);
386                 printable = 0;
387               }
388
389             if (m)
390               {
391                 /* Output a multibyte sequence, or an escaped
392                    unprintable unibyte character.  */
393                 size_t imax = i + m - 1;
394
395                 for (;;)
396                   {
397                     if (backslash_escapes && ! printable)
398                       {
399                         STORE ('\\');
400                         STORE ('0' + (c >> 6));
401                         STORE ('0' + ((c >> 3) & 7));
402                         c = '0' + (c & 7);
403                       }
404                     if (i == imax)
405                       break;
406                     STORE (c);
407                     c = arg[++i];
408                   }
409
410                 goto store_c;
411               }
412           }
413         }
414
415       if (! (backslash_escapes
416              && o->quote_these_too[c / INT_BITS] & (1 << (c % INT_BITS))))
417         goto store_c;
418
419     store_escape:
420       STORE ('\\');
421
422     store_c:
423       STORE (c);
424     }
425
426   if (quote_string)
427     for (; *quote_string; quote_string++)
428       STORE (*quote_string);
429
430   if (len < buffersize)
431     buffer[len] = '\0';
432   return len;
433
434  use_shell_always_quoting_style:
435   return quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
436                                    shell_always_quoting_style, o);
437 }
438
439 /* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
440    argument ARG (of size ARGSIZE), using O to control quoting.
441    If O is null, use the default.
442    Terminate the output with a null character, and return the written
443    size of the output, not counting the terminating null.
444    If BUFFERSIZE is too small to store the output string, return the
445    value that would have been returned had BUFFERSIZE been large enough.
446    If ARGSIZE is -1, use the string length of the argument for ARGSIZE.  */
447 size_t
448 quotearg_buffer (char *buffer, size_t buffersize,
449                  char const *arg, size_t argsize,
450                  struct quoting_options const *o)
451 {
452   struct quoting_options const *p = o ? o : &default_quoting_options;
453   return quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
454                                    p->style, p);
455 }
456
457 /* Use storage slot N to return a quoted version of the string ARG.
458    OPTIONS specifies the quoting options.
459    The returned value points to static storage that can be
460    reused by the next call to this function with the same value of N.
461    N must be nonnegative.  N is deliberately declared with type `int'
462    to allow for future extensions (using negative values).  */
463 static char *
464 quotearg_n_options (int n, char const *arg,
465                     struct quoting_options const *options)
466 {
467   static unsigned int nslots;
468   static struct slotvec
469     {
470       size_t size;
471       char *val;
472     } *slotvec;
473
474   if (nslots <= n)
475     {
476       int n1 = n + 1;
477       size_t s = n1 * sizeof (struct slotvec);
478       if (! (0 < n1 && n1 == s / sizeof (struct slotvec)))
479         abort ();
480       slotvec = (struct slotvec *) xrealloc (slotvec, s);
481       memset (slotvec + nslots, 0, (n1 - nslots) * sizeof (struct slotvec));
482       nslots = n;
483     }
484
485   {
486     size_t size = slotvec[n].size;
487     char *val = slotvec[n].val;
488     size_t qsize = quotearg_buffer (val, size, arg, (size_t) -1, options);
489
490     if (size <= qsize)
491       {
492         slotvec[n].size = size = qsize + 1;
493         slotvec[n].val = val = xrealloc (val, size);
494         quotearg_buffer (val, size, arg, (size_t) -1, options);
495       }
496
497     return val;
498   }
499 }
500
501 char *
502 quotearg_n (unsigned int n, char const *arg)
503 {
504   return quotearg_n_options (n, arg, &default_quoting_options);
505 }
506
507 char *
508 quotearg (char const *arg)
509 {
510   return quotearg_n (0, arg);
511 }
512
513 char *
514 quotearg_n_style (unsigned int n, enum quoting_style s, char const *arg)
515 {
516   struct quoting_options o;
517   o.style = s;
518   memset (o.quote_these_too, 0, sizeof o.quote_these_too);
519   return quotearg_n_options (n, arg, &o);
520 }
521
522 char *
523 quotearg_style (enum quoting_style s, char const *arg)
524 {
525   return quotearg_n_style (0, s, arg);
526 }
527
528 char *
529 quotearg_char (char const *arg, char ch)
530 {
531   struct quoting_options options;
532   options = default_quoting_options;
533   set_char_quoting (&options, ch, 1);
534   return quotearg_n_options (0, arg, &options);
535 }
536
537 char *
538 quotearg_colon (char const *arg)
539 {
540   return quotearg_char (arg, ':');
541 }