Update copyright year to 2014 by running admin/update-copyright.
[bpt/emacs.git] / src / doprnt.c
CommitLineData
24f98398 1/* Output like sprintf to a buffer of specified size.
762b15be
EZ
2 Also takes args differently: pass one pointer to the end
3 of the format string in addition to the format string itself.
ba318903 4 Copyright (C) 1985, 2001-2014 Free Software Foundation, Inc.
24f98398
JA
5
6This file is part of GNU Emacs.
7
9ec0b715 8GNU Emacs is free software: you can redistribute it and/or modify
24f98398 9it under the terms of the GNU General Public License as published by
9ec0b715
GM
10the Free Software Foundation, either version 3 of the License, or
11(at your option) any later version.
24f98398
JA
12
13GNU Emacs is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
9ec0b715 19along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24f98398 20
762b15be
EZ
21/* If you think about replacing this with some similar standard C function of
22 the printf family (such as vsnprintf), please note that this function
23 supports the following Emacs-specific features:
24
25 . For %c conversions, it produces a string with the multibyte representation
26 of the (`int') argument, suitable for display in an Emacs buffer.
27
28 . For %s and %c, when field width is specified (e.g., %25s), it accounts for
4c36be58 29 the display width of each character, according to char-width-table. That
762b15be
EZ
30 is, it does not assume that each character takes one column on display.
31
32 . If the size of the buffer is not enough to produce the formatted string in
33 its entirety, it makes sure that truncation does not chop the last
34 character in the middle of its multibyte sequence, producing an invalid
35 sequence.
36
37 . It accepts a pointer to the end of the format string, so the format string
38 could include embedded null characters.
39
40 . It signals an error if the length of the formatted string is about to
ea6e730c 41 overflow ptrdiff_t or size_t, to avoid producing strings longer than what
762b15be
EZ
42 Emacs can handle.
43
44 OTOH, this function supports only a small subset of the standard C formatted
45 output facilities. E.g., %u and %ll are not supported, and precision is
825cd63c
EZ
46 ignored %s and %c conversions. (See below for the detailed documentation of
47 what is supported.) However, this is okay, as this function is supposed to
48 be called from `error' and similar functions, and thus does not need to
49 support features beyond those in `Fformat', which is used by `error' on the
50 Lisp level. */
51
52/* This function supports the following %-sequences in the `format'
53 argument:
54
55 %s means print a string argument.
56 %S is silently treated as %s, for loose compatibility with `Fformat'.
57 %d means print a `signed int' argument in decimal.
825cd63c
EZ
58 %o means print an `unsigned int' argument in octal.
59 %x means print an `unsigned int' argument in hex.
60 %e means print a `double' argument in exponential notation.
61 %f means print a `double' argument in decimal-point notation.
62 %g means print a `double' argument in exponential notation
63 or in decimal-point notation, whichever uses fewer characters.
64 %c means print a `signed int' argument as a single character.
65 %% means produce a literal % character.
66
94dcfacf
EZ
67 A %-sequence may contain optional flag, width, and precision specifiers, and
68 a length modifier, as follows:
825cd63c 69
94dcfacf 70 %<flags><width><precision><length>character
825cd63c 71
b71a1728 72 where flags is [+ -0], width is [0-9]+, precision is .[0-9]+, and length
62f19c19
PE
73 is empty or l or the value of the pD or pI or pMd (sans "d") macros.
74 Also, %% in a format stands for a single % in the output. A % that
75 does not introduce a valid %-sequence causes undefined behavior.
825cd63c
EZ
76
77 The + flag character inserts a + before any positive number, while a space
94dcfacf
EZ
78 inserts a space before any positive number; these flags only affect %d, %o,
79 %x, %e, %f, and %g sequences. The - and 0 flags affect the width specifier,
80 as described below. For signed numerical arguments only, the ` ' (space)
81 flag causes the result to be prefixed with a space character if it does not
82 start with a sign (+ or -).
83
84 The l (lower-case letter ell) length modifier is a `long' data type
85 modifier: it is supported for %d, %o, and %x conversions of integral
54b8e3f7 86 arguments, must immediately precede the conversion specifier, and means that
94dcfacf 87 the respective argument is to be treated as `long int' or `unsigned long
62f19c19
PE
88 int'. Similarly, the value of the pD macro means to use ptrdiff_t,
89 the value of the pI macro means to use EMACS_INT or EMACS_UINT, the
90 value of the pMd etc. macros means to use intmax_t or uintmax_t,
91 and the empty length modifier means `int' or `unsigned int'.
825cd63c
EZ
92
93 The width specifier supplies a lower limit for the length of the printed
94 representation. The padding, if any, normally goes on the left, but it goes
95 on the right if the - flag is present. The padding character is normally a
96 space, but (for numerical arguments only) it is 0 if the 0 flag is present.
97 The - flag takes precedence over the 0 flag.
98
99 For %e, %f, and %g sequences, the number after the "." in the precision
100 specifier says how many decimal places to show; if zero, the decimal point
101 itself is omitted. For %s and %S, the precision specifier is ignored. */
24f98398 102
6d291527 103#include <config.h>
24f98398 104#include <stdio.h>
be65c2f4 105#include <float.h>
48236137 106#include <unistd.h>
e6c3da20 107#include <limits.h>
e6c3da20 108
523e9291
RS
109#include "lisp.h"
110
a0ca925c
KH
111/* Since we use the macro CHAR_HEAD_P, we have to include this, but
112 don't have to include others because CHAR_HEAD_P does not contains
113 another macro. */
83be827a 114#include "character.h"
a0ca925c 115
f4c730d3
RS
116/* Generate output from a format-spec FORMAT,
117 terminated at position FORMAT_END.
f40b429d 118 (*FORMAT_END is not part of the format, but must exist and be readable.)
f4c730d3 119 Output goes in BUFFER, which has room for BUFSIZE chars.
f40b429d
PE
120 BUFSIZE must be positive. If the output does not fit, truncate it
121 to fit and return BUFSIZE - 1; if this truncates a multibyte
122 sequence, store '\0' into the sequence's first byte.
825cd63c
EZ
123 Returns the number of bytes stored into BUFFER, excluding
124 the terminating null byte. Output is always null-terminated.
1513af9e
RS
125 String arguments are passed as C strings.
126 Integers are passed as C integers. */
f4c730d3 127
c2d1e36d
PE
128ptrdiff_t
129doprnt (char *buffer, ptrdiff_t bufsize, const char *format,
a8fe7202 130 const char *format_end, va_list ap)
24f98398 131{
c7f2cd7f
PE
132 const char *fmt = format; /* Pointer into format string. */
133 char *bufptr = buffer; /* Pointer into output buffer. */
03383aaf 134
f4c730d3 135 /* Use this for sprintf unless we need something really big. */
be65c2f4 136 char tembuf[DBL_MAX_10_EXP + 100];
03383aaf 137
f4c730d3 138 /* Size of sprintf_buffer. */
c2d1e36d 139 ptrdiff_t size_allocated = sizeof (tembuf);
03383aaf 140
f4c730d3
RS
141 /* Buffer to use for sprintf. Either tembuf or same as BIG_BUFFER. */
142 char *sprintf_buffer = tembuf;
03383aaf 143
f4c730d3 144 /* Buffer we have got with malloc. */
e6c3da20 145 char *big_buffer = NULL;
03383aaf 146
c7f2cd7f 147 ptrdiff_t tem = -1;
7469ef5d 148 char *string;
03383aaf
BF
149 char fixed_buffer[20]; /* Default buffer for small formatting. */
150 char *fmtcpy;
24f98398 151 int minlen;
7469ef5d 152 char charbuf[MAX_MULTIBYTE_LENGTH + 1]; /* Used for %c. */
825cd63c 153 USE_SAFE_ALLOCA;
24f98398
JA
154
155 if (format_end == 0)
156 format_end = format + strlen (format);
157
98c6f1e3
PE
158 fmtcpy = (format_end - format < sizeof (fixed_buffer) - 1
159 ? fixed_buffer
160 : SAFE_ALLOCA (format_end - format + 1));
03383aaf 161
24f98398 162 bufsize--;
03383aaf
BF
163
164 /* Loop until end of format string or buffer full. */
94dcfacf 165 while (fmt < format_end && bufsize > 0)
24f98398
JA
166 {
167 if (*fmt == '%') /* Check for a '%' character */
168 {
c2d1e36d 169 ptrdiff_t size_bound = 0;
d311d28c 170 ptrdiff_t width; /* Columns occupied by STRING on display. */
62f19c19
PE
171 enum {
172 pDlen = sizeof pD - 1,
173 pIlen = sizeof pI - 1,
174 pMlen = sizeof pMd - 2
175 };
176 enum {
177 no_modifier, long_modifier, pD_modifier, pI_modifier, pM_modifier
178 } length_modifier = no_modifier;
179 static char const modifier_len[] = { 0, 1, pDlen, pIlen, pMlen };
180 int maxmlen = max (max (1, pDlen), max (pIlen, pMlen));
181 int mlen;
f4c730d3 182
24f98398 183 fmt++;
d427b66a 184 /* Copy this one %-spec into fmtcpy. */
7469ef5d 185 string = fmtcpy;
24f98398 186 *string++ = '%';
94dcfacf 187 while (fmt < format_end)
24f98398
JA
188 {
189 *string++ = *fmt;
be65c2f4
PE
190 if ('0' <= *fmt && *fmt <= '9')
191 {
192 /* Get an idea of how much space we might need.
193 This might be a field width or a precision; e.g.
194 %1.1000f and %1000.1f both might need 1000+ bytes.
195 Parse the width or precision, checking for overflow. */
c2d1e36d 196 ptrdiff_t n = *fmt - '0';
ad5f9eea 197 while (fmt + 1 < format_end
94dcfacf 198 && '0' <= fmt[1] && fmt[1] <= '9')
be65c2f4 199 {
c2d1e36d 200 /* Avoid ptrdiff_t, size_t, and int overflow, as
ca2d6274
PE
201 many sprintfs mishandle widths greater than INT_MAX.
202 This test is simple but slightly conservative: e.g.,
203 (INT_MAX - INT_MAX % 10) is reported as an overflow
204 even when it's not. */
c2d1e36d 205 if (n >= min (INT_MAX, min (PTRDIFF_MAX, SIZE_MAX)) / 10)
be65c2f4 206 error ("Format width or precision too large");
26898943 207 n = n * 10 + fmt[1] - '0';
be65c2f4
PE
208 *string++ = *++fmt;
209 }
210
211 if (size_bound < n)
212 size_bound = n;
213 }
ad5f9eea
PE
214 else if (! (*fmt == '-' || *fmt == ' ' || *fmt == '.'
215 || *fmt == '+'))
24f98398
JA
216 break;
217 fmt++;
218 }
ad5f9eea 219
62f19c19
PE
220 /* Check for the length modifiers in textual length order, so
221 that longer modifiers override shorter ones. */
222 for (mlen = 1; mlen <= maxmlen; mlen++)
ad5f9eea 223 {
62f19c19
PE
224 if (format_end - fmt < mlen)
225 break;
226 if (mlen == 1 && *fmt == 'l')
227 length_modifier = long_modifier;
228 if (mlen == pDlen && memcmp (fmt, pD, pDlen) == 0)
229 length_modifier = pD_modifier;
230 if (mlen == pIlen && memcmp (fmt, pI, pIlen) == 0)
231 length_modifier = pI_modifier;
232 if (mlen == pMlen && memcmp (fmt, pMd, pMlen) == 0)
233 length_modifier = pM_modifier;
ad5f9eea 234 }
62f19c19
PE
235
236 mlen = modifier_len[length_modifier];
237 memcpy (string, fmt + 1, mlen);
238 string += mlen;
239 fmt += mlen;
24f98398 240 *string = 0;
03383aaf 241
be65c2f4
PE
242 /* Make the size bound large enough to handle floating point formats
243 with large numbers. */
c2d1e36d 244 if (size_bound > min (PTRDIFF_MAX, SIZE_MAX) - DBL_MAX_10_EXP - 50)
be65c2f4 245 error ("Format width or precision too large");
01769a73 246 size_bound += DBL_MAX_10_EXP + 50;
6e951728 247
f4c730d3
RS
248 /* Make sure we have that much. */
249 if (size_bound > size_allocated)
250 {
251 if (big_buffer)
94dcfacf 252 xfree (big_buffer);
23f86fce 253 big_buffer = xmalloc (size_bound);
f4c730d3
RS
254 sprintf_buffer = big_buffer;
255 size_allocated = size_bound;
256 }
24f98398
JA
257 minlen = 0;
258 switch (*fmt++)
259 {
260 default:
ad5f9eea 261 error ("Invalid format operation %s", fmtcpy);
24f98398
JA
262
263/* case 'b': */
e6c3da20 264 case 'l':
24f98398 265 case 'd':
62f19c19
PE
266 switch (length_modifier)
267 {
268 case no_modifier:
e810457d 269 {
62f19c19 270 int v = va_arg (ap, int);
99027bdd 271 tem = sprintf (sprintf_buffer, fmtcpy, v);
e810457d 272 }
62f19c19
PE
273 break;
274 case long_modifier:
e6c3da20 275 {
62f19c19 276 long v = va_arg (ap, long);
99027bdd 277 tem = sprintf (sprintf_buffer, fmtcpy, v);
e6c3da20 278 }
62f19c19
PE
279 break;
280 case pD_modifier:
281 signed_pD_modifier:
e6c3da20 282 {
62f19c19 283 ptrdiff_t v = va_arg (ap, ptrdiff_t);
99027bdd 284 tem = sprintf (sprintf_buffer, fmtcpy, v);
e6c3da20 285 }
62f19c19
PE
286 break;
287 case pI_modifier:
288 {
289 EMACS_INT v = va_arg (ap, EMACS_INT);
99027bdd 290 tem = sprintf (sprintf_buffer, fmtcpy, v);
62f19c19
PE
291 }
292 break;
293 case pM_modifier:
294 {
295 intmax_t v = va_arg (ap, intmax_t);
99027bdd 296 tem = sprintf (sprintf_buffer, fmtcpy, v);
62f19c19
PE
297 }
298 break;
299 }
300 /* Now copy into final output, truncating as necessary. */
301 string = sprintf_buffer;
302 goto doit;
e6c3da20 303
24f98398
JA
304 case 'o':
305 case 'x':
62f19c19
PE
306 switch (length_modifier)
307 {
308 case no_modifier:
e810457d 309 {
62f19c19 310 unsigned v = va_arg (ap, unsigned);
99027bdd 311 tem = sprintf (sprintf_buffer, fmtcpy, v);
e810457d 312 }
62f19c19
PE
313 break;
314 case long_modifier:
e6c3da20 315 {
62f19c19 316 unsigned long v = va_arg (ap, unsigned long);
99027bdd 317 tem = sprintf (sprintf_buffer, fmtcpy, v);
e6c3da20 318 }
62f19c19
PE
319 break;
320 case pD_modifier:
321 goto signed_pD_modifier;
322 case pI_modifier:
e6c3da20 323 {
62f19c19 324 EMACS_UINT v = va_arg (ap, EMACS_UINT);
99027bdd 325 tem = sprintf (sprintf_buffer, fmtcpy, v);
e6c3da20 326 }
62f19c19
PE
327 break;
328 case pM_modifier:
329 {
330 uintmax_t v = va_arg (ap, uintmax_t);
99027bdd 331 tem = sprintf (sprintf_buffer, fmtcpy, v);
62f19c19
PE
332 }
333 break;
334 }
335 /* Now copy into final output, truncating as necessary. */
336 string = sprintf_buffer;
337 goto doit;
24f98398 338
f4c730d3
RS
339 case 'f':
340 case 'e':
341 case 'g':
342 {
5e617bc2 343 double d = va_arg (ap, double);
99027bdd 344 tem = sprintf (sprintf_buffer, fmtcpy, d);
e6c3da20 345 /* Now copy into final output, truncating as necessary. */
7469ef5d 346 string = sprintf_buffer;
f4c730d3
RS
347 goto doit;
348 }
349
24f98398
JA
350 case 'S':
351 string[-1] = 's';
352 case 's':
24f98398
JA
353 if (fmtcpy[1] != 's')
354 minlen = atoi (&fmtcpy[1]);
7469ef5d 355 string = va_arg (ap, char *);
e267324c 356 tem = strlen (string);
c9d624c6 357 if (STRING_BYTES_BOUND < tem)
e6c3da20 358 error ("String for %%s or %%S format is too long");
a0ca925c 359 width = strwidth (string, tem);
1513af9e
RS
360 goto doit1;
361
24f98398
JA
362 /* Copy string into final output, truncating if no room. */
363 doit:
c7f2cd7f 364 eassert (0 <= tem);
a0ca925c 365 /* Coming here means STRING contains ASCII only. */
c9d624c6 366 if (STRING_BYTES_BOUND < tem)
e6c3da20
EZ
367 error ("Format width or precision too large");
368 width = tem;
35a65fce 369 doit1:
a0ca925c
KH
370 /* We have already calculated:
371 TEM -- length of STRING,
372 WIDTH -- columns occupied by STRING when displayed, and
373 MINLEN -- minimum columns of the output. */
24f98398
JA
374 if (minlen > 0)
375 {
a0ca925c 376 while (minlen > width && bufsize > 0)
24f98398
JA
377 {
378 *bufptr++ = ' ';
379 bufsize--;
380 minlen--;
381 }
382 minlen = 0;
383 }
384 if (tem > bufsize)
a0ca925c
KH
385 {
386 /* Truncate the string at character boundary. */
387 tem = bufsize;
86f158bc
PE
388 do
389 {
390 tem--;
391 if (CHAR_HEAD_P (string[tem]))
392 {
393 if (BYTES_BY_CHAR_HEAD (string[tem]) <= bufsize - tem)
394 tem = bufsize;
395 break;
396 }
397 }
398 while (tem != 0);
399
400 memcpy (bufptr, string, tem);
afda1437
EZ
401 bufptr[tem] = 0;
402 /* Trigger exit from the loop, but make sure we
403 return to the caller a value which will indicate
404 that the buffer was too small. */
405 bufptr += bufsize;
406 bufsize = 0;
407 continue;
a0ca925c 408 }
99027bdd 409 memcpy (bufptr, string, tem);
24f98398
JA
410 bufptr += tem;
411 bufsize -= tem;
412 if (minlen < 0)
413 {
a0ca925c 414 while (minlen < - width && bufsize > 0)
24f98398
JA
415 {
416 *bufptr++ = ' ';
417 bufsize--;
418 minlen++;
419 }
420 minlen = 0;
421 }
422 continue;
423
424 case 'c':
6a8033e1 425 {
5e617bc2 426 int chr = va_arg (ap, int);
e6c3da20 427 tem = CHAR_STRING (chr, (unsigned char *) charbuf);
6a8033e1
KR
428 string = charbuf;
429 string[tem] = 0;
430 width = strwidth (string, tem);
431 if (fmtcpy[1] != 'c')
432 minlen = atoi (&fmtcpy[1]);
433 goto doit1;
434 }
24f98398
JA
435
436 case '%':
437 fmt--; /* Drop thru and this % will be treated as normal */
438 }
439 }
a0ca925c
KH
440
441 {
442 /* Just some character; Copy it if the whole multi-byte form
443 fit in the buffer. */
444 char *save_bufptr = bufptr;
445
446 do { *bufptr++ = *fmt++; }
94dcfacf 447 while (fmt < format_end && --bufsize > 0 && !CHAR_HEAD_P (*fmt));
a50545d9 448 if (!CHAR_HEAD_P (*fmt))
a0ca925c 449 {
d178f871
EZ
450 /* Truncate, but return value that will signal to caller
451 that the buffer was too small. */
452 *save_bufptr = 0;
a0ca925c
KH
453 break;
454 }
455 }
24f98398
JA
456 };
457
f4c730d3 458 /* If we had to malloc something, free it. */
70fdbb46 459 xfree (big_buffer);
f4c730d3 460
e6c3da20 461 *bufptr = 0; /* Make sure our string ends with a '\0' */
825cd63c
EZ
462
463 SAFE_FREE ();
24f98398
JA
464 return bufptr - buffer;
465}
62f19c19
PE
466
467/* Format to an unbounded buffer BUF. This is like sprintf, except it
468 is not limited to returning an 'int' so it doesn't have a silly 2
469 GiB limit on typical 64-bit hosts. However, it is limited to the
470 Emacs-style formats that doprnt supports.
471
472 Return the number of bytes put into BUF, excluding the terminating
473 '\0'. */
474ptrdiff_t
475esprintf (char *buf, char const *format, ...)
476{
477 ptrdiff_t nbytes;
478 va_list ap;
479 va_start (ap, format);
480 nbytes = doprnt (buf, TYPE_MAXIMUM (ptrdiff_t), format, 0, ap);
481 va_end (ap);
482 return nbytes;
483}
484
1c14176c
PE
485#if defined HAVE_X_WINDOWS && defined USE_X_TOOLKIT
486
62f19c19
PE
487/* Format to buffer *BUF of positive size *BUFSIZE, reallocating *BUF
488 and updating *BUFSIZE if the buffer is too small, and otherwise
489 behaving line esprintf. When reallocating, free *BUF unless it is
490 equal to NONHEAPBUF, and if BUFSIZE_MAX is nonnegative then signal
491 memory exhaustion instead of growing the buffer size past
492 BUFSIZE_MAX. */
493ptrdiff_t
494exprintf (char **buf, ptrdiff_t *bufsize,
495 char const *nonheapbuf, ptrdiff_t bufsize_max,
496 char const *format, ...)
497{
498 ptrdiff_t nbytes;
499 va_list ap;
500 va_start (ap, format);
501 nbytes = evxprintf (buf, bufsize, nonheapbuf, bufsize_max, format, ap);
502 va_end (ap);
503 return nbytes;
504}
505
1c14176c
PE
506#endif
507
62f19c19
PE
508/* Act like exprintf, except take a va_list. */
509ptrdiff_t
510evxprintf (char **buf, ptrdiff_t *bufsize,
511 char const *nonheapbuf, ptrdiff_t bufsize_max,
512 char const *format, va_list ap)
513{
514 for (;;)
515 {
516 ptrdiff_t nbytes;
517 va_list ap_copy;
518 va_copy (ap_copy, ap);
519 nbytes = doprnt (*buf, *bufsize, format, 0, ap_copy);
520 va_end (ap_copy);
521 if (nbytes < *bufsize - 1)
522 return nbytes;
523 if (*buf != nonheapbuf)
2dd2e622
PE
524 {
525 xfree (*buf);
526 *buf = NULL;
527 }
62f19c19
PE
528 *buf = xpalloc (NULL, bufsize, 1, bufsize_max, 1);
529 }
530}