]> git.proxmox.com Git - ceph.git/blame - ceph/src/fmt/doc/syntax.rst
import quincy beta 17.1.0
[ceph.git] / ceph / src / fmt / doc / syntax.rst
CommitLineData
11fdf7f2
TL
1.. _syntax:
2
3********************
4Format String Syntax
5********************
6
7Formatting functions such as :ref:`fmt::format() <format>` and
8:ref:`fmt::print() <print>` use the same format string syntax described in this
9section.
10
11Format strings contain "replacement fields" surrounded by curly braces ``{}``.
12Anything that is not contained in braces is considered literal text, which is
13copied unchanged to the output. If you need to include a brace character in the
14literal text, it can be escaped by doubling: ``{{`` and ``}}``.
15
16The grammar for a replacement field is as follows:
17
18.. productionlist:: sf
20effc67 19 replacement_field: "{" [`arg_id`] [":" (`format_spec` | `chrono_format_spec`)] "}"
11fdf7f2
TL
20 arg_id: `integer` | `identifier`
21 integer: `digit`+
22 digit: "0"..."9"
23 identifier: `id_start` `id_continue`*
24 id_start: "a"..."z" | "A"..."Z" | "_"
25 id_continue: `id_start` | `digit`
26
27In less formal terms, the replacement field can start with an *arg_id*
28that specifies the argument whose value is to be formatted and inserted into
29the output instead of the replacement field.
20effc67
TL
30The *arg_id* is optionally followed by a *format_spec*, which is preceded by a
31colon ``':'``. These specify a non-default format for the replacement value.
11fdf7f2
TL
32
33See also the :ref:`formatspec` section.
34
35If the numerical arg_ids in a format string are 0, 1, 2, ... in sequence,
36they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be
37automatically inserted in that order.
38
39Named arguments can be referred to by their names or indices.
40
41Some simple format string examples::
42
43 "First, thou shalt count to {0}" // References the first argument
44 "Bring me a {}" // Implicitly references the first argument
45 "From {} to {}" // Same as "From {0} to {1}"
46
47The *format_spec* field contains a specification of how the value should be
48presented, including such details as field width, alignment, padding, decimal
49precision and so on. Each value type can define its own "formatting
50mini-language" or interpretation of the *format_spec*.
51
52Most built-in types support a common formatting mini-language, which is
53described in the next section.
54
55A *format_spec* field can also include nested replacement fields in certain
56positions within it. These nested replacement fields can contain only an
57argument id; format specifications are not allowed. This allows the formatting
58of a value to be dynamically specified.
59
60See the :ref:`formatexamples` section for some examples.
61
62.. _formatspec:
63
64Format Specification Mini-Language
65==================================
66
67"Format specifications" are used within replacement fields contained within a
68format string to define how individual values are presented (see
69:ref:`syntax`). Each formattable type may define how the format
70specification is to be interpreted.
71
72Most built-in types implement the following options for format specifications,
73although some of the formatting options are only supported by the numeric types.
74
75The general form of a *standard format specifier* is:
76
77.. productionlist:: sf
20effc67 78 format_spec: [[`fill`]`align`][`sign`]["#"]["0"][`width`]["." `precision`]["L"][`type`]
f67539c2
TL
79 fill: <a character other than '{' or '}'>
80 align: "<" | ">" | "^"
11fdf7f2 81 sign: "+" | "-" | " "
f67539c2
TL
82 width: `integer` | "{" [`arg_id`] "}"
83 precision: `integer` | "{" [`arg_id`] "}"
20effc67
TL
84 type: "a" | "A" | "b" | "B" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" |
85 : "o" | "p" | "s" | "x" | "X"
11fdf7f2 86
f67539c2
TL
87The *fill* character can be any Unicode code point other than ``'{'`` or
88``'}'``. The presence of a fill character is signaled by the character following
89it, which must be one of the alignment options. If the second character of
90*format_spec* is not a valid alignment option, then it is assumed that both the
91fill character and the alignment option are absent.
11fdf7f2
TL
92
93The meaning of the various alignment options is as follows:
94
95+---------+----------------------------------------------------------+
96| Option | Meaning |
97+=========+==========================================================+
98| ``'<'`` | Forces the field to be left-aligned within the available |
99| | space (this is the default for most objects). |
100+---------+----------------------------------------------------------+
101| ``'>'`` | Forces the field to be right-aligned within the |
102| | available space (this is the default for numbers). |
103+---------+----------------------------------------------------------+
11fdf7f2
TL
104| ``'^'`` | Forces the field to be centered within the available |
105| | space. |
106+---------+----------------------------------------------------------+
107
108Note that unless a minimum field width is defined, the field width will always
109be the same size as the data to fill it, so that the alignment option has no
110meaning in this case.
111
112The *sign* option is only valid for number types, and can be one of the
113following:
114
115+---------+----------------------------------------------------------+
116| Option | Meaning |
117+=========+==========================================================+
118| ``'+'`` | indicates that a sign should be used for both |
119| | positive as well as negative numbers. |
120+---------+----------------------------------------------------------+
121| ``'-'`` | indicates that a sign should be used only for negative |
122| | numbers (this is the default behavior). |
123+---------+----------------------------------------------------------+
124| space | indicates that a leading space should be used on |
125| | positive numbers, and a minus sign on negative numbers. |
126+---------+----------------------------------------------------------+
127
128The ``'#'`` option causes the "alternate form" to be used for the
129conversion. The alternate form is defined differently for different
130types. This option is only valid for integer and floating-point types.
131For integers, when binary, octal, or hexadecimal output is used, this
132option adds the prefix respective ``"0b"`` (``"0B"``), ``"0"``, or
133``"0x"`` (``"0X"``) to the output value. Whether the prefix is
134lower-case or upper-case is determined by the case of the type
135specifier, for example, the prefix ``"0x"`` is used for the type ``'x'``
136and ``"0X"`` is used for ``'X'``. For floating-point numbers the
137alternate form causes the result of the conversion to always contain a
138decimal-point character, even if no digits follow it. Normally, a
139decimal-point character appears in the result of these conversions
140only if a digit follows it. In addition, for ``'g'`` and ``'G'``
141conversions, trailing zeros are not removed from the result.
142
143.. ifconfig:: False
144
145 The ``','`` option signals the use of a comma for a thousands separator.
f67539c2 146 For a locale aware separator, use the ``'L'`` integer presentation type
11fdf7f2
TL
147 instead.
148
149*width* is a decimal integer defining the minimum field width. If not
150specified, then the field width will be determined by the content.
151
f67539c2
TL
152Preceding the *width* field by a zero (``'0'``) character enables sign-aware
153zero-padding for numeric types. It forces the padding to be placed after the
154sign or base (if any) but before the digits. This is used for printing fields in
155the form '+000000120'. This option is only valid for numeric types and it has no
156effect on formatting of infinity and NaN.
11fdf7f2
TL
157
158The *precision* is a decimal number indicating how many digits should be
159displayed after the decimal point for a floating-point value formatted with
160``'f'`` and ``'F'``, or before and after the decimal point for a floating-point
161value formatted with ``'g'`` or ``'G'``. For non-number types the field
162indicates the maximum field size - in other words, how many characters will be
163used from the field content. The *precision* is not allowed for integer,
164character, Boolean, and pointer values.
165
20effc67
TL
166The ``'L'`` option uses the current locale setting to insert the appropriate
167number separator characters. This option is only valid for numeric types.
168
11fdf7f2
TL
169Finally, the *type* determines how the data should be presented.
170
171The available string presentation types are:
172
173+---------+----------------------------------------------------------+
174| Type | Meaning |
175+=========+==========================================================+
176| ``'s'`` | String format. This is the default type for strings and |
177| | may be omitted. |
178+---------+----------------------------------------------------------+
179| none | The same as ``'s'``. |
180+---------+----------------------------------------------------------+
181
182The available character presentation types are:
183
184+---------+----------------------------------------------------------+
185| Type | Meaning |
186+=========+==========================================================+
187| ``'c'`` | Character format. This is the default type for |
188| | characters and may be omitted. |
189+---------+----------------------------------------------------------+
190| none | The same as ``'c'``. |
191+---------+----------------------------------------------------------+
192
193The available integer presentation types are:
194
195+---------+----------------------------------------------------------+
196| Type | Meaning |
197+=========+==========================================================+
198| ``'b'`` | Binary format. Outputs the number in base 2. Using the |
199| | ``'#'`` option with this type adds the prefix ``"0b"`` |
200| | to the output value. |
201+---------+----------------------------------------------------------+
202| ``'B'`` | Binary format. Outputs the number in base 2. Using the |
203| | ``'#'`` option with this type adds the prefix ``"0B"`` |
204| | to the output value. |
205+---------+----------------------------------------------------------+
20effc67
TL
206| ``'c'`` | Character format. Outputs the number as a character. |
207+---------+----------------------------------------------------------+
11fdf7f2
TL
208| ``'d'`` | Decimal integer. Outputs the number in base 10. |
209+---------+----------------------------------------------------------+
210| ``'o'`` | Octal format. Outputs the number in base 8. |
211+---------+----------------------------------------------------------+
212| ``'x'`` | Hex format. Outputs the number in base 16, using |
213| | lower-case letters for the digits above 9. Using the |
214| | ``'#'`` option with this type adds the prefix ``"0x"`` |
215| | to the output value. |
216+---------+----------------------------------------------------------+
217| ``'X'`` | Hex format. Outputs the number in base 16, using |
218| | upper-case letters for the digits above 9. Using the |
219| | ``'#'`` option with this type adds the prefix ``"0X"`` |
220| | to the output value. |
221+---------+----------------------------------------------------------+
11fdf7f2
TL
222| none | The same as ``'d'``. |
223+---------+----------------------------------------------------------+
224
225Integer presentation types can also be used with character and Boolean values.
226Boolean values are formatted using textual representation, either ``true`` or
227``false``, if the presentation type is not specified.
228
229The available presentation types for floating-point values are:
230
231+---------+----------------------------------------------------------+
232| Type | Meaning |
233+=========+==========================================================+
234| ``'a'`` | Hexadecimal floating point format. Prints the number in |
235| | base 16 with prefix ``"0x"`` and lower-case letters for |
236| | digits above 9. Uses ``'p'`` to indicate the exponent. |
237+---------+----------------------------------------------------------+
238| ``'A'`` | Same as ``'a'`` except it uses upper-case letters for |
239| | the prefix, digits above 9 and to indicate the exponent. |
240+---------+----------------------------------------------------------+
241| ``'e'`` | Exponent notation. Prints the number in scientific |
242| | notation using the letter 'e' to indicate the exponent. |
243+---------+----------------------------------------------------------+
244| ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
9f95a23c 245| | upper-case ``'E'`` as the separator character. |
11fdf7f2
TL
246+---------+----------------------------------------------------------+
247| ``'f'`` | Fixed point. Displays the number as a fixed-point |
248| | number. |
249+---------+----------------------------------------------------------+
250| ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
251| | ``NAN`` and ``inf`` to ``INF``. |
252+---------+----------------------------------------------------------+
253| ``'g'`` | General format. For a given precision ``p >= 1``, |
254| | this rounds the number to ``p`` significant digits and |
255| | then formats the result in either fixed-point format |
256| | or in scientific notation, depending on its magnitude. |
257| | |
258| | A precision of ``0`` is treated as equivalent to a |
259| | precision of ``1``. |
260+---------+----------------------------------------------------------+
261| ``'G'`` | General format. Same as ``'g'`` except switches to |
262| | ``'E'`` if the number gets too large. The |
263| | representations of infinity and NaN are uppercased, too. |
264+---------+----------------------------------------------------------+
20effc67
TL
265| none | Similar to ``'g'``, except that the default precision is |
266| | as high as needed to represent the particular value. |
11fdf7f2
TL
267+---------+----------------------------------------------------------+
268
11fdf7f2
TL
269.. ifconfig:: False
270
271 +---------+----------------------------------------------------------+
272 | | The precise rules are as follows: suppose that the |
273 | | result formatted with presentation type ``'e'`` and |
274 | | precision ``p-1`` would have exponent ``exp``. Then |
275 | | if ``-4 <= exp < p``, the number is formatted |
276 | | with presentation type ``'f'`` and precision |
277 | | ``p-1-exp``. Otherwise, the number is formatted |
278 | | with presentation type ``'e'`` and precision ``p-1``. |
279 | | In both cases insignificant trailing zeros are removed |
280 | | from the significand, and the decimal point is also |
281 | | removed if there are no remaining digits following it. |
282 | | |
283 | | Positive and negative infinity, positive and negative |
284 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
285 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
286 | | the precision. |
287 | | |
288 +---------+----------------------------------------------------------+
289
290The available presentation types for pointers are:
291
292+---------+----------------------------------------------------------+
293| Type | Meaning |
294+=========+==========================================================+
295| ``'p'`` | Pointer format. This is the default type for |
296| | pointers and may be omitted. |
297+---------+----------------------------------------------------------+
298| none | The same as ``'p'``. |
299+---------+----------------------------------------------------------+
300
20effc67
TL
301.. _chrono-specs:
302
303Chrono Format Specifications
304============================
305
306Format specifications for chrono types have the following syntax:
307
308.. productionlist:: sf
309 chrono_format_spec: [[`fill`]`align`][`width`]["." `precision`][`chrono_specs`]
310 chrono_specs: [`chrono_specs`] `conversion_spec` | `chrono_specs` `literal_char`
311 conversion_spec: "%" [`modifier`] `chrono_type`
312 literal_char: <a character other than '{', '}' or '%'>
313 modifier: "E" | "O"
314 chrono_type: "a" | "A" | "b" | "B" | "c" | "C" | "d" | "D" | "e" | "F" |
315 : "g" | "G" | "h" | "H" | "I" | "j" | "m" | "M" | "n" | "p" |
316 : "q" | "Q" | "r" | "R" | "S" | "t" | "T" | "u" | "U" | "V" |
317 : "w" | "W" | "x" | "X" | "y" | "Y" | "z" | "Z" | "%"
318
319Literal chars are copied unchanged to the output. Precision is valid only for
320``std::chrono::duration`` types with a floating-point representation type.
321
322The available presentation types (*chrono_type*) for chrono durations and time
323points are:
324
325+---------+--------------------------------------------------------------------+
326| Type | Meaning |
327+=========+====================================================================+
328| ``'H'`` | The hour (24-hour clock) as a decimal number. If the result is a |
329| | single digit, it is prefixed with 0. The modified command ``%OH`` |
330| | produces the locale's alternative representation. |
331+---------+--------------------------------------------------------------------+
332| ``'M'`` | The minute as a decimal number. If the result is a single digit, |
333| | it is prefixed with 0. The modified command ``%OM`` produces the |
334| | locale's alternative representation. |
335+---------+--------------------------------------------------------------------+
336| ``'S'`` | Seconds as a decimal number. If the number of seconds is less than |
337| | 10, the result is prefixed with 0. If the precision of the input |
338| | cannot be exactly represented with seconds, then the format is a |
339| | decimal floating-point number with a fixed format and a precision |
340| | matching that of the precision of the input (or to a microseconds |
341| | precision if the conversion to floating-point decimal seconds |
342| | cannot be made within 18 fractional digits). The character for the |
343| | decimal point is localized according to the locale. The modified |
344| | command ``%OS`` produces the locale's alternative representation. |
345+---------+--------------------------------------------------------------------+
346
347Specifiers that have a calendaric component such as `'d'` (the day of month)
348are valid only for ``std::tm`` and not durations or time points.
349
350``std::tm`` uses the system's `strftime
351<https://en.cppreference.com/w/cpp/chrono/c/strftime>`_ so refer to its
352documentation for details on supported conversion specifiers.
353
11fdf7f2
TL
354.. _formatexamples:
355
f67539c2 356Format Examples
11fdf7f2
TL
357===============
358
359This section contains examples of the format syntax and comparison with
360the printf formatting.
361
362In most of the cases the syntax is similar to the printf formatting, with the
363addition of the ``{}`` and with ``:`` used instead of ``%``.
364For example, ``"%03.2f"`` can be translated to ``"{:03.2f}"``.
365
366The new format syntax also supports new and different options, shown in the
367following examples.
368
369Accessing arguments by position::
370
f67539c2 371 fmt::format("{0}, {1}, {2}", 'a', 'b', 'c');
11fdf7f2 372 // Result: "a, b, c"
f67539c2 373 fmt::format("{}, {}, {}", 'a', 'b', 'c');
11fdf7f2 374 // Result: "a, b, c"
f67539c2 375 fmt::format("{2}, {1}, {0}", 'a', 'b', 'c');
11fdf7f2 376 // Result: "c, b, a"
f67539c2 377 fmt::format("{0}{1}{0}", "abra", "cad"); // arguments' indices can be repeated
11fdf7f2
TL
378 // Result: "abracadabra"
379
380Aligning the text and specifying a width::
381
f67539c2 382 fmt::format("{:<30}", "left aligned");
11fdf7f2 383 // Result: "left aligned "
f67539c2 384 fmt::format("{:>30}", "right aligned");
11fdf7f2 385 // Result: " right aligned"
f67539c2 386 fmt::format("{:^30}", "centered");
11fdf7f2 387 // Result: " centered "
f67539c2 388 fmt::format("{:*^30}", "centered"); // use '*' as a fill char
11fdf7f2
TL
389 // Result: "***********centered***********"
390
391Dynamic width::
392
f67539c2 393 fmt::format("{:<{}}", "left aligned", 30);
11fdf7f2
TL
394 // Result: "left aligned "
395
396Dynamic precision::
397
f67539c2 398 fmt::format("{:.{}f}", 3.14, 1);
11fdf7f2
TL
399 // Result: "3.1"
400
401Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
402
f67539c2 403 fmt::format("{:+f}; {:+f}", 3.14, -3.14); // show it always
11fdf7f2 404 // Result: "+3.140000; -3.140000"
f67539c2 405 fmt::format("{: f}; {: f}", 3.14, -3.14); // show a space for positive numbers
11fdf7f2 406 // Result: " 3.140000; -3.140000"
f67539c2 407 fmt::format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}'
11fdf7f2
TL
408 // Result: "3.140000; -3.140000"
409
410Replacing ``%x`` and ``%o`` and converting the value to different bases::
411
f67539c2 412 fmt::format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
11fdf7f2
TL
413 // Result: "int: 42; hex: 2a; oct: 52; bin: 101010"
414 // with 0x or 0 or 0b as prefix:
f67539c2 415 fmt::format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42);
11fdf7f2
TL
416 // Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010"
417
418Padded hex byte with prefix and always prints both hex characters::
419
f67539c2 420 fmt::format("{:#04x}", 0);
11fdf7f2
TL
421 // Result: "0x00"
422
f67539c2
TL
423Box drawing using Unicode fill::
424
425 fmt::print(
426 "┌{0:─^{2}}┐\n"
427 "│{1: ^{2}}│\n"
428 "└{0:─^{2}}┘\n", "", "Hello, world!", 20);
429
430prints::
11fdf7f2 431
f67539c2
TL
432 ┌────────────────────┐
433 │ Hello, world! │
434 └────────────────────┘
11fdf7f2 435
f67539c2 436Using type-specific formatting::
11fdf7f2 437
f67539c2 438 #include <fmt/chrono.h>
11fdf7f2 439
f67539c2
TL
440 auto t = tm();
441 t.tm_year = 2010 - 1900;
20effc67 442 t.tm_mon = 7;
f67539c2
TL
443 t.tm_mday = 4;
444 t.tm_hour = 12;
445 t.tm_min = 15;
446 t.tm_sec = 58;
447 fmt::print("{:%Y-%m-%d %H:%M:%S}", t);
448 // Prints: 2010-08-04 12:15:58
449
450Using the comma as a thousands separator::
451
452 #include <fmt/locale.h>
453
454 auto s = fmt::format(std::locale("en_US.UTF-8"), "{:L}", 1234567890);
455 // s == "1,234,567,890"
456
457.. ifconfig:: False
11fdf7f2
TL
458
459 Nesting arguments and more complex examples::
460
461 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
462 ... '{0:{fill}{align}16}") << text, fill=align, align=align)
463 ...
464 'left<<<<<<<<<<<<'
465 '^^^^^center^^^^^'
466 '>>>>>>>>>>>right'
467 >>>
468 >>> octets = [192, 168, 0, 1]
469 Format("{:02X}{:02X}{:02X}{:02X}") << *octets)
470 'C0A80001'
471 >>> int(_, 16)
472 3232235521
473 >>>
474 >>> width = 5
475 >>> for num in range(5,12):
476 ... for base in 'dXob':
477 ... print('{0:{width}{base}}") << num, base=base, width=width), end=' ')
478 ... print()
479 ...
480 5 5 5 101
481 6 6 6 110
482 7 7 7 111
483 8 8 10 1000
484 9 9 11 1001
485 10 A 12 1010
486 11 B 13 1011