]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/libxo/doc/libxo.txt
Merge ^/head r319801 through r320041.
[FreeBSD/FreeBSD.git] / contrib / libxo / doc / libxo.txt
1 #
2 # Copyright (c) 2014, Juniper Networks, Inc.
3 # All rights reserved.
4 # This SOFTWARE is licensed under the LICENSE provided in the
5 # ../Copyright file. By downloading, installing, copying, or 
6 # using the SOFTWARE, you agree to be bound by the terms of that
7 # LICENSE.
8 # Phil Shafer, July 2014
9 #
10
11 * Overview
12
13 libxo - A Library for Generating Text, XML, JSON, and HTML Output
14
15 You want to prepare for the future, but you need to live in the
16 present.  You'd love a flying car, but need to get to work today.  You
17 want to support features like XML, JSON, and HTML rendering to allow
18 integration with NETCONF, REST, and web browsers, but you need to make
19 text output for command line users.
20
21 And you don't want multiple code paths that can't help but get out of
22 sync:
23
24     /* None of this "if (xml) {... } else {...}"  logic */
25     if (xml) {
26         /* some code to make xml*/
27     } else {
28         /* other code to make text */
29         /* oops forgot to add something on both clauses! */
30     }
31
32     /* And ifdefs are right out. */
33     #ifdef MAKE_XML
34         /* icky */
35     #else
36         /* pooh */
37     #endif
38
39 But you'd really, really like all the fancy features that modern
40 encoding formats can provide.  libxo can help.
41
42 The libxo library allows an application to generate text, XML, JSON,
43 and HTML output using a common set of function calls.  The application
44 decides at run time which output style should be produced.  The
45 application calls a function "xo_emit" to product output that is
46 described in a format string.  A "field descriptor" tells libxo what
47 the field is and what it means.  Each field descriptor is placed in
48 braces with a printf-like format string (^format-strings^):
49
50     xo_emit(" {:lines/%7ju} {:words/%7ju} "
51             "{:characters/%7ju} {d:filename/%s}\n",
52             linect, wordct, charct, file);
53
54 Each field can have a role, with the 'value' role being the default,
55 and the role tells libxo how and when to render that field (see
56 ^field-roles^ for details).  Modifiers change how the field is
57 rendered in different output styles (see ^field-modifiers^ for
58 details.  Output can then be generated in various style, using the
59 "--libxo" option:
60
61     % wc /etc/motd
62           25     165    1140 /etc/motd
63     % wc --libxo xml,pretty,warn /etc/motd
64     <wc>
65       <file>
66         <lines>25</lines>
67         <words>165</words>
68         <characters>1140</characters>
69         <filename>/etc/motd</filename>
70       </file>
71     </wc>
72     % wc --libxo json,pretty,warn /etc/motd
73     {
74       "wc": {
75         "file": [
76           {
77             "lines": 25,
78             "words": 165,
79             "characters": 1140,
80             "filename": "/etc/motd"
81           }
82         ]
83       }
84     }
85     % wc --libxo html,pretty,warn /etc/motd
86     <div class="line">
87       <div class="text"> </div>
88       <div class="data" data-tag="lines">     25</div>
89       <div class="text"> </div>
90       <div class="data" data-tag="words">    165</div>
91       <div class="text"> </div>
92       <div class="data" data-tag="characters">   1140</div>
93       <div class="text"> </div>
94       <div class="data" data-tag="filename">/etc/motd</div>
95     </div>
96
97 Same code path, same format strings, same information, but it's
98 rendered in distinct styles based on run-time flags.
99
100 * Getting libxo
101
102 libxo now ships as part of the FreeBSD Operating System (as of -11).
103
104 libxo lives on github as:
105
106   https://github.com/Juniper/libxo
107
108 The latest release of libxo is available at:
109
110   https://github.com/Juniper/libxo/releases
111
112 We are following the branching scheme from
113 ^http://nvie.com/posts/a-successful-git-branching-model/^ which means
114 we will do development under the "develop" branch, and release from
115 the "master" branch.  To clone a developer tree, run the following
116 command:
117
118   git clone https://github.com/Juniper/libxo.git -b develop
119
120 We're using semantic release numbering, as defined in
121 ^http://semver.org/spec/v2.0.0.html^.
122
123 libxo is open source, distributed under the BSD license.  It shipped
124 as part of the FreeBSD operating system starting with release 11.0.
125
126 Issues, problems, and bugs should be directly to the issues page on
127 our github site.
128
129 ** Downloading libxo Source Code
130
131 You can retrieve the source for libxo in two ways:
132
133 A) Use a "distfile" for a specific release.  We use
134 github to maintain our releases.  Visit
135 github release page (^https://github.com/Juniper/libxo/releases^)
136 to see the list of releases.  To download the latest, look for the
137 release with the green "Latest release" button and the green
138 "libxo-RELEASE.tar.gz" button under that section.
139
140 After downloading that release's distfile, untar it as follows:
141
142     tar -zxf libxo-RELEASE.tar.gz
143     cd libxo-RELEASE
144
145 [Note: for Solaris users, your "tar" command lacks the "-z" flag,
146 so you'll need to substitute "gzip -dc "file" | tar xf -" instead of
147 "tar -zxf "file"".]
148
149 B) Use the current build from github.  This gives you the most recent
150 source code, which might be less stable than a specific release.  To
151 build libxo from the git repo:
152
153     git clone https://github.com/Juniper/libxo.git
154     cd libxo
155
156 _BE AWARE_: The github repository does _not_ contain the files
157 generated by "autoreconf", with the notable exception of the "m4"
158 directory.  Since these files (depcomp, configure, missing,
159 install-sh, etc) are generated files, we keep them out of the source
160 code repository.
161
162 This means that if you download the a release distfile, these files
163 will be ready and you'll just need to run "configure", but if you
164 download the source code from svn, then you'll need to run
165 "autoreconf" by hand.  This step is done for you by the "setup.sh"
166 script, described in the next section.
167
168 ** Building libxo
169
170 To build libxo, you'll need to set up the build, run the "configure"
171 script, run the "make" command, and run the regression tests.
172
173 The following is a summary of the commands needed.  These commands are
174 explained in detail in the rest of this section.
175
176     sh bin/setup.sh
177     cd build
178     ../configure
179     make
180     make test
181     sudo make install
182
183 The following sections will walk through each of these steps with
184 additional details and options, but the above directions should be all
185 that's needed.
186
187 *** Setting up the build
188
189 [If you downloaded a distfile, you can skip this step.]
190
191 Run the "setup.sh" script to set up the build.  This script runs the
192 "autoreconf" command to generate the "configure" script and other
193 generated files.
194
195     sh bin/setup.sh
196
197 Note: We're are currently using autoreconf version 2.69.
198
199 *** Running the "configure" Script
200
201 Configure (and autoconf in general) provides a means of building
202 software in diverse environments.  Our configure script supports
203 a set of options that can be used to adjust to your operating
204 environment. Use "configure --help" to view these options.
205
206 We use the "build" directory to keep object files and generated files
207 away from the source tree.
208
209 To run the configure script, change into the "build" directory, and
210 run the "configure" script.  Add any required options to the
211 "../configure" command line.
212
213     cd build
214     ../configure
215
216 Expect to see the "configure" script generate the following error:
217
218     /usr/bin/rm: cannot remove `libtoolT': No such file or directory
219
220 This error is harmless and can be safely ignored.
221
222 By default, libxo installs architecture-independent files, including
223 extension library files, in the /usr/local directories. To specify an
224 installation prefix other than /usr/local for all installation files,
225 include the --prefix=prefix option and specify an alternate
226 location. To install just the extension library files in a different,
227 user-defined location, include the --with-extensions-dir=dir option
228 and specify the location where the extension libraries will live.
229
230     cd build
231     ../configure [OPTION]... [VAR=VALUE]...
232
233 **** Running the "make" command
234
235 Once the "configure" script is run, build the images using the "make"
236 command:
237
238     make
239
240 **** Running the Regression Tests
241
242 libxo includes a set of regression tests that can be run to ensure
243 the software is working properly.  These test are optional, but will
244 help determine if there are any issues running libxo on your
245 machine.  To run the regression tests:
246
247     make test
248
249 *** Installing libxo
250
251 Once the software is built, you'll need to install libxo using the
252 "make install" command.  If you are the root user, or the owner of the
253 installation directory, simply issue the command:
254
255     make install
256
257 If you are not the "root" user and are using the "sudo" package, use:
258
259     sudo make install
260
261 Verify the installation by viewing the output of "xo --version":
262
263     % xo --version
264     libxo version 0.3.5-git-develop
265     xo version 0.3.5-git-develop
266
267 * Formatting with libxo
268
269 Most unix commands emit text output aimed at humans.  It is designed
270 to be parsed and understood by a user.  Humans are gifted at
271 extracting details and pattern matching in such output.  Often
272 programmers need to extract information from this human-oriented
273 output.  Programmers use tools like grep, awk, and regular expressions
274 to ferret out the pieces of information they need.  Such solutions are
275 fragile and require maintenance when output contents change or evolve,
276 along with testing and validation.
277
278 Modern tool developers favor encoding schemes like XML and JSON,
279 which allow trivial parsing and extraction of data.  Such formats are
280 simple, well understood, hierarchical, easily parsed, and often
281 integrate easier with common tools and environments.  Changes to
282 content can be done in ways that do not break existing users of the
283 data, which can reduce maintenance costs and increase feature velocity.
284
285 In addition, modern reality means that more output ends up in web
286 browsers than in terminals, making HTML output valuable.
287
288 libxo allows a single set of function calls in source code to generate
289 traditional text output, as well as XML and JSON formatted data.  HTML
290 can also be generated; "<div>" elements surround the traditional text
291 output, with attributes that detail how to render the data.
292
293 A single libxo function call in source code is all that's required:
294
295     xo_emit("Connecting to {:host}.{:domain}...\n", host, domain);
296
297     TEXT:
298       Connecting to my-box.example.com...
299     XML:
300       <host>my-box</host>
301       <domain>example.com</domain>
302     JSON:
303       "host": "my-box",
304       "domain": "example.com"
305     HTML:
306        <div class="line">
307          <div class="text">Connecting to </div>
308          <div class="data" data-tag="host" 
309               data-xpath="/top/host">my-box</div>
310          <div class="text">.</div>
311          <div class="data" data-tag="domain"
312               data-xpath="/top/domain">example.com</div>
313          <div class="text">...</div>
314        </div>
315
316 ** Encoding Styles
317
318 There are four encoding styles supported by libxo:
319
320 - TEXT output can be display on a terminal session, allowing
321 compatibility with traditional command line usage.
322 - XML output is suitable for tools like XPath and protocols like
323 NETCONF.
324 - JSON output can be used for RESTful APIs and integration with
325 languages like Javascript and Python.
326 - HTML can be matched with a small CSS file to permit rendering in any
327 HTML5 browser.
328
329 In general, XML and JSON are suitable for encoding data, while TEXT is
330 suited for terminal output and HTML is suited for display in a web
331 browser (see ^xohtml^).
332
333 *** Text Output
334
335 Most traditional programs generate text output on standard output,
336 with contents like:
337
338     36      ./src
339     40      ./bin
340     90      .
341
342 In this example (taken from du source code), the code to generate this
343 data might look like:
344
345     printf("%d\t%s\n", num_blocks, path);
346
347 Simple, direct, obvious.  But it's only making text output.  Imagine
348 using a single code path to make TEXT, XML, JSON or HTML, deciding at
349 run time which to generate.
350
351 libxo expands on the idea of printf format strings to make a single
352 format containing instructions for creating multiple output styles:
353
354     xo_emit("{:blocks/%d}\t{:path/%s}\n", num_blocks, path);
355
356 This line will generate the same text output as the earlier printf
357 call, but also has enough information to generate XML, JSON, and HTML.
358
359 The following sections introduce the other formats.
360
361 *** XML Output
362
363 XML output consists of a hierarchical set of elements, each encoded
364 with a start tag and an end tag.  The element should be named for data
365 value that it is encoding:
366
367     <item>
368       <blocks>36</blocks>
369       <path>./src</path>
370     </item>
371     <item>
372       <blocks>40</blocks>
373       <path>./bin</path>
374     </item>
375     <item>
376       <blocks>90</blocks>
377       <path>.</path>
378     </item>
379
380 XML is a W3C standard for encoding data.  See w3c.org/TR/xml for
381 additional information.
382
383 *** JSON Output
384
385 JSON output consists of a hierarchical set of objects and lists, each
386 encoded with a quoted name, a colon, and a value.  If the value is a
387 string, it must be quoted, but numbers are not quoted.  Objects are
388 encoded using braces; lists are encoded using square brackets.
389 Data inside objects and lists is separated using commas:
390
391     items: [
392         { "blocks": 36, "path" : "./src" },
393         { "blocks": 40, "path" : "./bin" },
394         { "blocks": 90, "path" : "./" }
395     ]
396
397 *** HTML Output
398
399 HTML output is designed to allow the output to be rendered in a web
400 browser with minimal effort.  Each piece of output data is rendered
401 inside a <div> element, with a class name related to the role of the
402 data.  By using a small set of class attribute values, a CSS
403 stylesheet can render the HTML into rich text that mirrors the
404 traditional text content.
405
406 Additional attributes can be enabled to provide more details about the
407 data, including data type, description, and an XPath location.
408
409     <div class="line">
410       <div class="data" data-tag="blocks">36</div>
411       <div class="padding">      </div>
412       <div class="data" data-tag="path">./src</div>
413     </div>
414     <div class="line">
415       <div class="data" data-tag="blocks">40</div>
416       <div class="padding">      </div>
417       <div class="data" data-tag="path">./bin</div>
418     </div>
419     <div class="line">
420       <div class="data" data-tag="blocks">90</div>
421       <div class="padding">      </div>
422       <div class="data" data-tag="path">./</div>
423     </div>
424
425 ** Format Strings @format-strings@
426
427 libxo uses format strings to control the rendering of data into the
428 various output styles.  Each format string contains a set of zero or
429 more field descriptions, which describe independent data fields.  Each
430 field description contains a set of modifiers, a content string, and
431 zero, one, or two format descriptors.  The modifiers tell libxo what
432 the field is and how to treat it, while the format descriptors are
433 formatting instructions using printf-style format strings, telling
434 libxo how to format the field.  The field description is placed inside
435 a set of braces, with a colon (":") after the modifiers and a slash
436 ("/") before each format descriptors.  Text may be intermixed with
437 field descriptions within the format string.
438
439 The field description is given as follows:
440
441     '{' [ role | modifier ]* [',' long-names ]* ':' [ content ]
442             [ '/' field-format [ '/' encoding-format ]] '}'
443
444 The role describes the function of the field, while the modifiers
445 enable optional behaviors.  The contents, field-format, and
446 encoding-format are used in varying ways, based on the role.  These
447 are described in the following sections.
448
449 In the following example, three field descriptors appear.  The first
450 is a padding field containing three spaces of padding, the second is a
451 label ("In stock"), and the third is a value field ("in-stock").  The
452 in-stock field has a "%u" format that will parse the next argument
453 passed to the xo_emit function as an unsigned integer.
454
455     xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n", 65);
456
457 This single line of code can generate text (" In stock: 65\n"), XML
458 ("<in-stock>65</in-stock>"), JSON ('"in-stock": 6'), or HTML (too
459 lengthy to be listed here).
460
461 While roles and modifiers typically use single character for brevity,
462 there are alternative names for each which allow more verbose
463 formatting strings.  These names must be preceded by a comma, and may
464 follow any single-character values:
465
466     xo_emit("{L,white,colon:In stock}{,key:in-stock/%u}\n", 65);
467
468 *** Field Roles
469
470 Field roles are optional, and indicate the role and formatting of the
471 content.  The roles are listed below; only one role is permitted:
472
473 |---+--------------+-------------------------------------------------|
474 | R | Name         | Description                                     |
475 |---+--------------+-------------------------------------------------|
476 | C | color        | Field has color and effect controls             |
477 | D | decoration   | Field is non-text (e.g., colon, comma)          |
478 | E | error        | Field is an error message                       |
479 | G | gettext      | Call gettext(3) on the format string            |
480 | L | label        | Field is text that prefixes a value             |
481 | N | note         | Field is text that follows a value              |
482 | P | padding      | Field is spaces needed for vertical alignment   |
483 | T | title        | Field is a title value for headings             |
484 | U | units        | Field is the units for the previous value field |
485 | V | value        | Field is the name of field (the default)        |
486 | W | warning      | Field is a warning message                      |
487 | [ | start-anchor | Begin a section of anchored variable-width text |
488 | ] | stop-anchor  | End a section of anchored variable-width text   |
489 |---+--------------+-------------------------------------------------|
490
491     EXAMPLE:
492         xo_emit("{L:Free}{D::}{P:   }{:free/%u} {U:Blocks}\n",
493                 free_blocks);
494
495 When a role is not provided, the "value" role is used as the default.
496
497 Roles and modifiers can also use more verbose names, when preceded by
498 a comma:
499
500     EXAMPLE:
501         xo_emit("{,label:Free}{,decoration::}{,padding:   }"
502                 "{,value:free/%u} {,units:Blocks}\n",
503                 free_blocks);
504
505 **** The Color Role ({C:}) @color-role@
506
507 Colors and effects control how text values are displayed; they are
508 used for display styles (TEXT and HTML).
509
510     xo_emit("{C:bold}{:value}{C:no-bold}\n", value);
511
512 Colors and effects remain in effect until modified by other "C"-role
513 fields.
514
515     xo_emit("{C:bold}{C:inverse}both{C:no-bold}only inverse\n");
516
517 If the content is empty, the "reset" action is performed.
518
519     xo_emit("{C:both,underline}{:value}{C:}\n", value);
520
521 The content should be a comma-separated list of zero or more colors or
522 display effects.
523
524     xo_emit("{C:bold,inverse}Ugly{C:no-bold,no-inverse}\n");
525
526 The color content can be either static, when placed directly within
527 the field descriptor, or a printf-style format descriptor can be used,
528 if preceded by a slash ("/"):
529
530    xo_emit("{C:/%s%s}{:value}{C:}", need_bold ? "bold" : "",
531            need_underline ? "underline" : "", value);
532
533 Color names are prefixed with either "fg-" or "bg-" to change the
534 foreground and background colors, respectively.
535
536     xo_emit("{C:/fg-%s,bg-%s}{Lwc:Cost}{:cost/%u}{C:reset}\n",
537             fg_color, bg_color, cost);
538
539 The following table lists the supported effects:
540
541 |---------------+-------------------------------------------------|
542 |  Name         | Description                                     |
543 |---------------+-------------------------------------------------|
544 |  bg-XXXXX     | Change background color                         |
545 |  bold         | Start bold text effect                          |
546 |  fg-XXXXX     | Change foreground color                         |
547 |  inverse      | Start inverse (aka reverse) text effect         |
548 |  no-bold      | Stop bold text effect                           |
549 |  no-inverse   | Stop inverse (aka reverse) text effect          |
550 |  no-underline | Stop underline text effect                      |
551 |  normal       | Reset effects (only)                            |
552 |  reset        | Reset colors and effects (restore defaults)     |
553 |  underline    | Start underline text effect                     |
554 |---------------+-------------------------------------------------|
555
556 The following color names are supported:
557
558 |---------+--------------------------------------------|
559 | Name    | Description                                |
560 |---------+--------------------------------------------|
561 | black   |                                            |
562 | blue    |                                            |
563 | cyan    |                                            |
564 | default | Default color for foreground or background |
565 | green   |                                            |
566 | magenta |                                            |
567 | red     |                                            |
568 | white   |                                            |
569 | yellow  |                                            |
570 |---------+--------------------------------------------|
571
572 When using colors, the developer should remember that users will
573 change the foreground and background colors of terminal session
574 according to their own tastes, so assuming that "blue" looks nice is
575 never safe, and is a constant annoyance to your dear author.  In
576 addition, a significant percentage of users (1 in 12) will be color
577 blind.  Depending on color to convey critical information is not a
578 good idea.  Color should enhance output, but should not be used as the
579 sole means of encoding information.
580
581 **** The Decoration Role ({D:})
582
583 Decorations are typically punctuation marks such as colons,
584 semi-colons, and commas used to decorate the text and make it simpler
585 for human readers.  By marking these distinctly, HTML usage scenarios
586 can use CSS to direct their display parameters.
587
588     xo_emit("{D:((}{:name}{D:))}\n", name);
589
590 **** The Gettext Role ({G:}) @gettext-role@
591
592 libxo supports internationalization (i18n) through its use of
593 gettext(3).  Use the "{G:}" role to request that the remaining part of
594 the format string, following the "{G:}" field, be handled using
595 gettext().
596
597 Since gettext() uses the string as the key into the message catalog,
598 libxo uses a simplified version of the format string that removes
599 unimportant field formatting and modifiers, stopping minor formatting
600 changes from impacting the expensive translation process.  A developer
601 change such as changing "/%06d" to "/%08d" should not force hand
602 inspection of all .po files.
603
604 The simplified version can be generated for a single message using the
605 "xopo -s <text>" command, or an entire .pot can be translated using
606 the "xopo -f <input> -o <output>" command.
607
608    xo_emit("{G:}Invalid token\n");
609
610 The {G:} role allows a domain name to be set.  gettext calls will
611 continue to use that domain name until the current format string
612 processing is complete, enabling a library function to emit strings
613 using it's own catalog.  The domain name can be either static as the
614 content of the field, or a format can be used to get the domain name
615 from the arguments.
616
617    xo_emit("{G:libc}Service unavailable in restricted mode\n");
618
619 See ^howto-i18n^ for additional details.
620
621 **** The Label Role ({L:})
622
623 Labels are text that appears before a value.
624
625     xo_emit("{Lwc:Cost}{:cost/%u}\n", cost);
626
627 **** The Note Role ({N:})
628
629 Notes are text that appears after a value.
630
631     xo_emit("{:cost/%u} {N:per year}\n", cost);
632
633 **** The Padding Role ({P:}) @padding-role@
634
635 Padding represents whitespace used before and between fields.
636
637 The padding content can be either static, when placed directly within
638 the field descriptor, or a printf-style format descriptor can be used,
639 if preceded by a slash ("/"):
640
641     xo_emit("{P:        }{Lwc:Cost}{:cost/%u}\n", cost);
642     xo_emit("{P:/%30s}{Lwc:Cost}{:cost/%u}\n", "", cost);
643
644 **** The Title Role ({T:})
645
646 Title are heading or column headers that are meant to be displayed to
647 the user.  The title can be either static, when placed directly within
648 the field descriptor, or a printf-style format descriptor can be used,
649 if preceded by a slash ("/"):
650
651     xo_emit("{T:Interface Statistics}\n");
652     xo_emit("{T:/%20.20s}{T:/%6.6s}\n", "Item Name", "Cost");
653
654 Title fields have an extra convenience feature; if both content and
655 format are specified, instead of looking to the argument list for a
656 value, the content is used, allowing a mixture of format and content
657 within the field descriptor:
658
659     xo_emit("{T:Name/%20s}{T:Count/%6s}\n");
660
661 Since the incoming argument is a string, the format must be "%s" or
662 something suitable.
663
664 **** The Units Role ({U:})
665
666 Units are the dimension by which values are measured, such as degrees,
667 miles, bytes, and decibels.  The units field carries this information
668 for the previous value field.
669
670     xo_emit("{Lwc:Distance}{:distance/%u}{Uw:miles}\n", miles);
671
672 Note that the sense of the 'w' modifier is reversed for units;
673 a blank is added before the contents, rather than after it.
674
675 When the XOF_UNITS flag is set, units are rendered in XML as the
676 "units" attribute:
677
678     <distance units="miles">50</distance>
679
680 Units can also be rendered in HTML as the "data-units" attribute:
681
682     <div class="data" data-tag="distance" data-units="miles"
683          data-xpath="/top/data/distance">50</div>
684
685 **** The Value Role ({V:} and {:})
686
687 The value role is used to represent the a data value that is
688 interesting for the non-display output styles (XML and JSON).  Value
689 is the default role; if no other role designation is given, the field
690 is a value.  The field name must appear within the field descriptor,
691 followed by one or two format descriptors.  The first format
692 descriptor is used for display styles (TEXT and HTML), while the
693 second one is used for encoding styles (XML and JSON).  If no second
694 format is given, the encoding format defaults to the first format,
695 with any minimum width removed.  If no first format is given, both
696 format descriptors default to "%s".
697
698     xo_emit("{:length/%02u}x{:width/%02u}x{:height/%02u}\n",
699             length, width, height);
700     xo_emit("{:author} wrote \"{:poem}\" in {:year/%4d}\n,
701             author, poem, year);
702
703 **** The Anchor Roles ({[:} and {]:}) @anchor-role@
704
705 The anchor roles allow a set of strings by be padded as a group,
706 but still be visible to xo_emit as distinct fields.  Either the start
707 or stop anchor can give a field width and it can be either directly in
708 the descriptor or passed as an argument.  Any fields between the start
709 and stop anchor are padded to meet the minimum width given.
710
711 To give a width directly, encode it as the content of the anchor tag:
712
713     xo_emit("({[:10}{:min/%d}/{:max/%d}{]:})\n", min, max);
714
715 To pass a width as an argument, use "%d" as the format, which must
716 appear after the "/".  Note that only "%d" is supported for widths.
717 Using any other value could ruin your day.
718
719     xo_emit("({[:/%d}{:min/%d}/{:max/%d}{]:})\n", width, min, max);
720
721 If the width is negative, padding will be added on the right, suitable
722 for left justification.  Otherwise the padding will be added to the
723 left of the fields between the start and stop anchors, suitable for
724 right justification.  If the width is zero, nothing happens.  If the
725 number of columns of output between the start and stop anchors is less
726 than the absolute value of the given width, nothing happens.
727
728 Widths over 8k are considered probable errors and not supported.  If
729 XOF_WARN is set, a warning will be generated.
730
731 *** Field Modifiers
732
733 Field modifiers are flags which modify the way content emitted for
734 particular output styles:
735
736 |---+---------------+--------------------------------------------------|
737 | M | Name          | Description                                      |
738 |---+---------------+--------------------------------------------------|
739 | a | argument      | The content appears as a 'const char *' argument |
740 | c | colon         | A colon (":") is appended after the label        |
741 | d | display       | Only emit field for display styles (text/HTML)   |
742 | e | encoding      | Only emit for encoding styles (XML/JSON)         |
743 | g | gettext       | Call gettext on field's render content           |
744 | h | humanize (hn) | Format large numbers in human-readable style     |
745 |   | hn-space      | Humanize: Place space between numeric and unit   |
746 |   | hn-decimal    | Humanize: Add a decimal digit, if number < 10    |
747 |   | hn-1000       | Humanize: Use 1000 as divisor instead of 1024    |
748 | k | key           | Field is a key, suitable for XPath predicates    |
749 | l | leaf-list     | Field is a leaf-list                             |
750 | n | no-quotes     | Do not quote the field when using JSON style     |
751 | p | plural        | Gettext: Use comma-separated plural form         |
752 | q | quotes        | Quote the field when using JSON style            |
753 | t | trim          | Trim leading and trailing whitespace             |
754 | w | white         | A blank (" ") is appended after the label        |
755 |---+---------------+--------------------------------------------------|
756
757 Roles and modifiers can also use more verbose names, when preceded by
758 a comma.  For example, the modifier string "Lwc" (or "L,white,colon")
759 means the field has a label role (text that describes the next field)
760 and should be followed by a colon ('c') and a space ('w').  The
761 modifier string "Vkq" (or ":key,quote") means the field has a value
762 role (the default role), that it is a key for the current instance,
763 and that the value should be quoted when encoded for JSON.
764
765 **** The Argument Modifier ({a:})
766
767 The argument modifier indicates that the content of the field
768 descriptor will be placed as a UTF-8 string (const char *) argument
769 within the xo_emit parameters.
770
771     EXAMPLE:
772       xo_emit("{La:} {a:}\n", "Label text", "label", "value");
773     TEXT:
774       Label text value
775     JSON:
776       "label": "value"
777     XML:
778       <label>value</label>
779
780 The argument modifier allows field names for value fields to be passed
781 on the stack, avoiding the need to build a field descriptor using
782 snprintf.  For many field roles, the argument modifier is not needed,
783 since those roles have specific mechanisms for arguments, such as
784 "{C:fg-%s}".
785
786 **** The Colon Modifier ({c:})
787
788 The colon modifier appends a single colon to the data value:
789
790     EXAMPLE:
791       xo_emit("{Lc:Name}{:name}\n", "phil");
792     TEXT:
793       Name:phil
794
795 The colon modifier is only used for the TEXT and HTML output
796 styles. It is commonly combined with the space modifier ('{w:}').
797 It is purely a convenience feature.
798
799 **** The Display Modifier ({d:})
800
801 The display modifier indicated the field should only be generated for
802 the display output styles, TEXT and HTML.
803
804     EXAMPLE:
805       xo_emit("{Lcw:Name}{d:name} {:id/%d}\n", "phil", 1);
806     TEXT:
807       Name: phil 1
808     XML:
809       <id>1</id>
810
811 The display modifier is the opposite of the encoding modifier, and
812 they are often used to give to distinct views of the underlying data.
813
814 **** The Encoding Modifier ({e:}) @e-modifier@
815
816 The display modifier indicated the field should only be generated for
817 the display output styles, TEXT and HTML.
818
819     EXAMPLE:
820       xo_emit("{Lcw:Name}{:name} {e:id/%d}\n", "phil", 1);
821     TEXT:
822       Name: phil
823     XML:
824       <name>phil</name><id>1</id>
825
826 The encoding modifier is the opposite of the display modifier, and
827 they are often used to give to distinct views of the underlying data.
828
829 **** The Gettext Modifier ({g:}) @gettext-modifier@
830
831 The gettext modifier is used to translate individual fields using the
832 gettext domain (typically set using the "{G:}" role) and current
833 language settings.  Once libxo renders the field value, it is passed
834 to gettext(3), where it is used as a key to find the native language
835 translation.
836
837 In the following example, the strings "State" and "full" are passed
838 to gettext() to find locale-based translated strings.
839
840     xo_emit("{Lgwc:State}{g:state}\n", "full");
841
842 See ^gettext-role^, ^plural-modifier^, and ^howto-i18n^ for additional
843 details.
844
845 **** The Humanize Modifier ({h:})
846
847 The humanize modifier is used to render large numbers as in a
848 human-readable format.  While numbers like "44470272" are completely
849 readable to computers and savants, humans will generally find "44M"
850 more meaningful.
851
852 "hn" can be used as an alias for "humanize".
853
854 The humanize modifier only affects display styles (TEXT and HMTL).
855 The "no-humanize" option (See ^options^) will block the function of
856 the humanize modifier.
857
858 There are a number of modifiers that affect details of humanization.
859 These are only available in as full names, not single characters.  The
860 "hn-space" modifier places a space between the number and any
861 multiplier symbol, such as "M" or "K" (ex: "44 K").  The "hn-decimal"
862 modifier will add a decimal point and a single tenths digit when the number is
863 less than 10 (ex: "4.4K").  The "hn-1000" modifier will use 1000 as divisor
864 instead of 1024, following the JEDEC-standard instead of the more
865 natural binary powers-of-two tradition.
866
867     EXAMPLE:
868         xo_emit("{h:input/%u}, {h,hn-space:output/%u}, "
869             "{h,hn-decimal:errors/%u}, {h,hn-1000:capacity/%u}, "
870             "{h,hn-decimal:remaining/%u}\n",
871             input, output, errors, capacity, remaining);
872     TEXT:
873         21, 57 K, 96M, 44M, 1.2G
874
875 In the HTML style, the original numeric value is rendered in the
876 "data-number" attribute on the <div> element:
877
878     <div class="data" data-tag="errors"
879          data-number="100663296">96M</div>
880
881 **** The Key Modifier ({k:})
882
883 The key modifier is used to indicate that a particular field helps
884 uniquely identify an instance of list data.
885
886     EXAMPLE:
887         xo_open_list("user");
888         for (i = 0; i < num_users; i++) {
889             xo_open_instance("user");
890             xo_emit("User {k:name} has {:count} tickets\n",
891                user[i].u_name, user[i].u_tickets);
892             xo_close_instance("user");
893         }
894         xo_close_list("user");
895
896 Currently the key modifier is only used when generating XPath value
897 for the HTML output style when XOF_XPATH is set, but other uses are
898 likely in the near future.
899
900 **** The Leaf-List Modifier ({l:})
901
902 The leaf-list modifier is used to distinguish lists where each
903 instance consists of only a single value.  In XML, these are
904 rendered as single elements, where JSON renders them as arrays.
905
906     EXAMPLE:
907         for (i = 0; i < num_users; i++) {
908             xo_emit("Member {l:user}\n", user[i].u_name);
909         }
910     XML:
911         <user>phil</user>
912         <user>pallavi</user>
913     JSON:
914         "user": [ "phil", "pallavi" ]
915
916 The name of the field must match the name of the leaf list.
917
918 **** The No-Quotes Modifier ({n:})
919
920 The no-quotes modifier (and its twin, the 'quotes' modifier) affect
921 the quoting of values in the JSON output style.  JSON uses quotes for
922 string value, but no quotes for numeric, boolean, and null data.
923 xo_emit applies a simple heuristic to determine whether quotes are
924 needed, but often this needs to be controlled by the caller.
925
926     EXAMPLE:
927       const char *bool = is_true ? "true" : "false";
928       xo_emit("{n:fancy/%s}", bool);
929     JSON:
930       "fancy": true
931
932 **** The Plural Modifier ({p:}) @plural-modifier@
933
934 The plural modifier selects the appropriate plural form of an
935 expression based on the most recent number emitted and the current
936 language settings.  The contents of the field should be the singular
937 and plural English values, separated by a comma:
938
939     xo_emit("{:bytes} {Ngp:byte,bytes}\n", bytes);
940
941 The plural modifier is meant to work with the gettext modifier ({g:})
942 but can work independently.  See ^gettext-modifier^.
943
944 When used without the gettext modifier or when the message does not
945 appear in the message catalog, the first token is chosen when the last
946 numeric value is equal to 1; otherwise the second value is used,
947 mimicking the simple pluralization rules of English.
948
949 When used with the gettext modifier, the ngettext(3) function is
950 called to handle the heavy lifting, using the message catalog to
951 convert the singular and plural forms into the native language.
952
953 **** The Quotes Modifier ({q:})
954
955 The quotes modifier (and its twin, the 'no-quotes' modifier) affect
956 the quoting of values in the JSON output style.  JSON uses quotes for
957 string value, but no quotes for numeric, boolean, and null data.
958 xo_emit applies a simple heuristic to determine whether quotes are
959 needed, but often this needs to be controlled by the caller.
960
961     EXAMPLE:
962       xo_emit("{q:time/%d}", 2014);
963     JSON:
964       "year": "2014"
965
966 The heuristic is based on the format; if the format uses any of the
967 following conversion specifiers, then no quotes are used:
968
969     d i o u x X D O U e E f F g G a A c C p
970
971 **** The Trim Modifier ({t:})
972
973 The trim modifier removes any leading or trailing whitespace from
974 the value.
975
976     EXAMPLE:
977       xo_emit("{t:description}", "   some  input   ");
978     JSON:
979       "description": "some input"
980
981 **** The White Space Modifier ({w:})
982
983 The white space modifier appends a single space to the data value:
984
985     EXAMPLE:
986       xo_emit("{Lw:Name}{:name}\n", "phil");
987     TEXT:
988       Name phil
989
990 The white space modifier is only used for the TEXT and HTML output
991 styles. It is commonly combined with the colon modifier ('{c:}').
992 It is purely a convenience feature.
993
994 Note that the sense of the 'w' modifier is reversed for the units role
995 ({Uw:}); a blank is added before the contents, rather than after it.
996
997 *** Field Formatting
998
999 The field format is similar to the format string for printf(3).  Its
1000 use varies based on the role of the field, but generally is used to
1001 format the field's contents.
1002
1003 If the format string is not provided for a value field, it defaults to
1004 "%s".
1005
1006 Note a field definition can contain zero or more printf-style
1007 'directives', which are sequences that start with a '%' and end with
1008 one of following characters: "diouxXDOUeEfFgGaAcCsSp".  Each directive
1009 is matched by one of more arguments to the xo_emit function.
1010
1011 The format string has the form:
1012
1013   '%' format-modifier * format-character
1014
1015 The format- modifier can be:
1016 - a '#' character, indicating the output value should be prefixed with
1017 '0x', typically to indicate a base 16 (hex) value.
1018 - a minus sign ('-'), indicating the output value should be padded on
1019 the right instead of the left.
1020 - a leading zero ('0') indicating the output value should be padded on the
1021 left with zeroes instead of spaces (' ').
1022 - one or more digits ('0' - '9') indicating the minimum width of the
1023 argument.  If the width in columns of the output value is less than
1024 the minimum width, the value will be padded to reach the minimum.
1025 - a period followed by one or more digits indicating the maximum
1026 number of bytes which will be examined for a string argument, or the maximum
1027 width for a non-string argument.  When handling ASCII strings this
1028 functions as the field width but for multi-byte characters, a single
1029 character may be composed of multiple bytes.
1030 xo_emit will never dereference memory beyond the given number of bytes.
1031 - a second period followed by one or more digits indicating the maximum
1032 width for a string argument.  This modifier cannot be given for non-string
1033 arguments. 
1034 - one or more 'h' characters, indicating shorter input data.
1035 - one or more 'l' characters, indicating longer input data.
1036 - a 'z' character, indicating a 'size_t' argument.
1037 - a 't' character, indicating a 'ptrdiff_t' argument.
1038 - a ' ' character, indicating a space should be emitted before
1039 positive numbers.
1040 - a '+' character, indicating sign should emitted before any number.
1041
1042 Note that 'q', 'D', 'O', and 'U' are considered deprecated and will be
1043 removed eventually.
1044
1045 The format character is described in the following table:
1046
1047 |-----+-----------------+----------------------|
1048 | Ltr | Argument Type   | Format               |
1049 |-----+-----------------+----------------------|
1050 | d   | int             | base 10 (decimal)    |
1051 | i   | int             | base 10 (decimal)    |
1052 | o   | int             | base 8 (octal)       |
1053 | u   | unsigned        | base 10 (decimal)    |
1054 | x   | unsigned        | base 16 (hex)        |
1055 | X   | unsigned long   | base 16 (hex)        |
1056 | D   | long            | base 10 (decimal)    |
1057 | O   | unsigned long   | base 8 (octal)       |
1058 | U   | unsigned long   | base 10 (decimal)    |
1059 | e   | double          | [-]d.ddde+-dd        |
1060 | E   | double          | [-]d.dddE+-dd        |
1061 | f   | double          | [-]ddd.ddd           |
1062 | F   | double          | [-]ddd.ddd           |
1063 | g   | double          | as 'e' or 'f'        |
1064 | G   | double          | as 'E' or 'F'        |
1065 | a   | double          | [-]0xh.hhhp[+-]d     |
1066 | A   | double          | [-]0Xh.hhhp[+-]d     |
1067 | c   | unsigned char   | a character          |
1068 | C   | wint_t          | a character          |
1069 | s   | char *          | a UTF-8 string       |
1070 | S   | wchar_t *       | a unicode/WCS string |
1071 | p   | void *          | '%#lx'               |
1072 |-----+-----------------+----------------------|
1073
1074 The 'h' and 'l' modifiers affect the size and treatment of the
1075 argument:
1076
1077 |-----+-------------+--------------------|
1078 | Mod | d, i        | o, u, x, X         |
1079 |-----+-------------+--------------------|
1080 | hh  | signed char | unsigned char      |
1081 | h   | short       | unsigned short     |
1082 | l   | long        | unsigned long      |
1083 | ll  | long long   | unsigned long long |
1084 | j   | intmax_t    | uintmax_t          |
1085 | t   | ptrdiff_t   | ptrdiff_t          |
1086 | z   | size_t      | size_t             |
1087 | q   | quad_t      | u_quad_t           |
1088 |-----+-------------+--------------------|
1089
1090 *** UTF-8 and Locale Strings
1091
1092 For strings, the 'h' and 'l' modifiers affect the interpretation of
1093 the bytes pointed to argument.  The default '%s' string is a 'char *'
1094 pointer to a string encoded as UTF-8.  Since UTF-8 is compatible with
1095 ASCII data, a normal 7-bit ASCII string can be used.  '%ls' expects a
1096 'wchar_t *' pointer to a wide-character string, encoded as a 32-bit
1097 Unicode values.  '%hs' expects a 'char *' pointer to a multi-byte
1098 string encoded with the current locale, as given by the LC_CTYPE,
1099 LANG, or LC_ALL environment varibles.  The first of this list of
1100 variables is used and if none of the variables are set, the locale
1101 defaults to "UTF-8".
1102
1103 libxo will convert these arguments as needed to either UTF-8 (for XML,
1104 JSON, and HTML styles) or locale-based strings for display in text
1105 style.
1106
1107    xo_emit("All strings are utf-8 content {:tag/%ls}",
1108            L"except for wide strings");
1109
1110 "%S" is equivalent to "%ls".
1111
1112 |--------+-----------------+-------------------------------|
1113 | Format | Argument Type   | Argument Contents             |
1114 |--------+-----------------+-------------------------------|
1115 | %s     | const char *    | UTF-8 string                  |
1116 | %S     | const char *    | UTF-8 string (alias for '%s') |
1117 | %ls    | const wchar_t * | Wide character UNICODE string |
1118 | %hs    | const char *    | locale-based string           |
1119 |--------+-----------------+-------------------------------|
1120
1121 For example, a function is passed a locale-base name, a hat size,
1122 and a time value.  The hat size is formatted in a UTF-8 (ASCII)
1123 string, and the time value is formatted into a wchar_t string.
1124
1125     void print_order (const char *name, int size,
1126                       struct tm *timep) {
1127         char buf[32];
1128         const char *size_val = "unknown";
1129
1130         if (size > 0)
1131             snprintf(buf, sizeof(buf), "%d", size);
1132             size_val = buf;
1133         }
1134
1135         wchar_t when[32];
1136         wcsftime(when, sizeof(when), L"%d%b%y", timep);
1137
1138         xo_emit("The hat for {:name/%hs} is {:size/%s}.\n",
1139                 name, size_val);
1140         xo_emit("It was ordered on {:order-time/%ls}.\n",
1141                 when);
1142     }
1143
1144 It is important to note that xo_emit will perform the conversion
1145 required to make appropriate output.  Text style output uses the
1146 current locale (as described above), while XML, JSON, and HTML use
1147 UTF-8.
1148
1149 UTF-8 and locale-encoded strings can use multiple bytes to encode one
1150 column of data.  The traditional "precision'" (aka "max-width") value
1151 for "%s" printf formatting becomes overloaded since it specifies both
1152 the number of bytes that can be safely referenced and the maximum
1153 number of columns to emit.  xo_emit uses the precision as the former,
1154 and adds a third value for specifying the maximum number of columns.
1155
1156 In this example, the name field is printed with a minimum of 3 columns
1157 and a maximum of 6.  Up to ten bytes of data at the location given by
1158 'name' are in used in filling those columns.
1159
1160     xo_emit("{:name/%3.10.6s}", name);
1161
1162 *** Characters Outside of Field Definitions
1163
1164 Characters in the format string that are not part of a field
1165 definition are copied to the output for the TEXT style, and are
1166 ignored for the JSON and XML styles.  For HTML, these characters are
1167 placed in a <div> with class "text".
1168
1169   EXAMPLE:
1170       xo_emit("The hat is {:size/%s}.\n", size_val);
1171   TEXT:
1172       The hat is extra small.
1173   XML:
1174       <size>extra small</size>
1175   JSON:
1176       "size": "extra small"
1177   HTML:
1178       <div class="text">The hat is </div>
1179       <div class="data" data-tag="size">extra small</div>
1180       <div class="text">.</div>
1181
1182 *** "%m" Is Supported
1183
1184 libxo supports the '%m' directive, which formats the error message
1185 associated with the current value of "errno".  It is the equivalent
1186 of "%s" with the argument strerror(errno).
1187
1188     xo_emit("{:filename} cannot be opened: {:error/%m}", filename);
1189     xo_emit("{:filename} cannot be opened: {:error/%s}",
1190             filename, strerror(errno));
1191
1192 *** "%n" Is Not Supported
1193
1194 libxo does not support the '%n' directive.  It's a bad idea and we
1195 just don't do it.
1196
1197 *** The Encoding Format (eformat)
1198
1199 The "eformat" string is the format string used when encoding the field
1200 for JSON and XML.  If not provided, it defaults to the primary format
1201 with any minimum width removed.  If the primary is not given, both
1202 default to "%s".
1203
1204 *** Content Strings
1205
1206 For padding and labels, the content string is considered the content,
1207 unless a format is given.
1208
1209 *** Argument Validation @printf-like@
1210
1211 Many compilers and tool chains support validation of printf-like
1212 arguments.  When the format string fails to match the argument list, 
1213 a warning is generated.  This is a valuable feature and while the
1214 formatting strings for libxo differ considerably from printf, many of
1215 these checks can still provide build-time protection against bugs.
1216
1217 libxo provide variants of functions that provide this ability, if the
1218 "--enable-printflike" option is passed to the "configure" script.
1219 These functions use the "_p" suffix, like "xo_emit_p()",
1220 xo_emit_hp()", etc.
1221
1222 The following are features of libxo formatting strings that are
1223 incompatible with printf-like testing:
1224
1225 - implicit formats, where "{:tag}" has an implicit "%s";
1226 - the "max" parameter for strings, where "{:tag/%4.10.6s}" means up to
1227 ten bytes of data can be inspected to fill a minimum of 4 columns and
1228 a maximum of 6;
1229 - percent signs in strings, where "{:filled}%" makes a single,
1230 trailing percent sign;
1231 - the "l" and "h" modifiers for strings, where "{:tag/%hs}" means
1232 locale-based string and "{:tag/%ls}" means a wide character string;
1233 - distinct encoding formats, where "{:tag/#%s/%s}" means the display
1234 styles (text and HTML) will use "#%s" where other styles use "%s";
1235
1236 If none of these features are in use by your code, then using the "_p"
1237 variants might be wise.
1238
1239 |------------------+------------------------|
1240 | Function         | printf-like Equivalent |
1241 |------------------+------------------------|
1242 | xo_emit_hv       | xo_emit_hvp            |
1243 | xo_emit_h        | xo_emit_hp             |
1244 | xo_emit          | xo_emit_p              |
1245 | xo_emit_warn_hcv | xo_emit_warn_hcvp      |
1246 | xo_emit_warn_hc  | xo_emit_warn_hcp       |
1247 | xo_emit_warn_c   | xo_emit_warn_cp        |
1248 | xo_emit_warn     | xo_emit_warn_p         |
1249 | xo_emit_warnx_   | xo_emit_warnx_p        |
1250 | xo_emit_err      | xo_emit_err_p          |
1251 | xo_emit_errx     | xo_emit_errx_p         |
1252 | xo_emit_errc     | xo_emit_errc_p         |
1253 |------------------+------------------------|
1254
1255 *** Retaining Parsed Format Information @retain@
1256
1257 libxo can retain the parsed internal information related to the given
1258 format string, allowing subsequent xo_emit calls, the retained
1259 information is used, avoiding repetitive parsing of the format string.
1260
1261     SYNTAX:
1262       int xo_emit_f(xo_emit_flags_t flags, const char fmt, ...);
1263     EXAMPLE:
1264       xo_emit_f(XOEF_RETAIN, "{:some/%02d}{:thing/%-6s}{:fancy}\n",
1265                      some, thing, fancy);
1266
1267 To retain parsed format information, use the XOEF_RETAIN flag to the
1268 xo_emit_f() function.  A complete set of xo_emit_f functions exist to
1269 match all the xo_emit function signatures (with handles, varadic
1270 argument, and printf-like flags):
1271
1272 |------------------+------------------------|
1273 | Function         | Flags Equivalent       |
1274 |------------------+------------------------|
1275 | xo_emit_hv       | xo_emit_hvf            |
1276 | xo_emit_h        | xo_emit_hf             |
1277 | xo_emit          | xo_emit_f              |
1278 | xo_emit_hvp      | xo_emit_hvfp           |
1279 | xo_emit_hp       | xo_emit_hfp            |
1280 | xo_emit_p        | xo_emit_fp             |
1281 |------------------+------------------------|
1282
1283 The format string must be immutable across multiple calls to xo_emit_f(),
1284 since the library retains the string.  Typically this is done by using
1285 static constant strings, such as string literals. If the string is not
1286 immutable, the XOEF_RETAIN flag must not be used.
1287
1288 The functions xo_retain_clear() and xo_retain_clear_all() release
1289 internal information on either a single format string or all format
1290 strings, respectively.  Neither is required, but the library will
1291 retain this information until it is cleared or the process exits.
1292
1293     const char *fmt = "{:name}  {:count/%d}\n";
1294     for (i = 0; i < 1000; i++) {
1295         xo_open_instance("item");
1296         xo_emit_f(XOEF_RETAIN, fmt, name[i], count[i]);
1297     }
1298     xo_retain_clear(fmt);
1299
1300 The retained information is kept as thread-specific data.
1301
1302 *** Example
1303
1304 In this example, the value for the number of items in stock is emitted:
1305
1306         xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n",
1307                 instock);
1308
1309 This call will generate the following output:
1310
1311   TEXT: 
1312        In stock: 144
1313   XML:
1314       <in-stock>144</in-stock>
1315   JSON:
1316       "in-stock": 144,
1317   HTML:
1318       <div class="line">
1319         <div class="padding">   </div>
1320         <div class="label">In stock</div>
1321         <div class="decoration">:</div>
1322         <div class="padding"> </div>
1323         <div class="data" data-tag="in-stock">144</div>
1324       </div>
1325
1326 Clearly HTML wins the verbosity award, and this output does
1327 not include XOF_XPATH or XOF_INFO data, which would expand the
1328 penultimate line to:
1329
1330        <div class="data" data-tag="in-stock"
1331           data-xpath="/top/data/item/in-stock"
1332           data-type="number"
1333           data-help="Number of items in stock">144</div>
1334
1335 ** Representing Hierarchy
1336
1337 For XML and JSON, individual fields appear inside hierarchies which
1338 provide context and meaning to the fields.  Unfortunately, these
1339 encoding have a basic disconnect between how lists is similar objects
1340 are represented.
1341
1342 XML encodes lists as set of sequential elements:
1343
1344     <user>phil</user>
1345     <user>pallavi</user>
1346     <user>sjg</user>
1347
1348 JSON encodes lists using a single name and square brackets:
1349
1350     "user": [ "phil", "pallavi", "sjg" ]
1351
1352 This means libxo needs three distinct indications of hierarchy: one
1353 for containers of hierarchy appear only once for any specific parent,
1354 one for lists, and one for each item in a list.
1355
1356 *** Containers
1357
1358 A "container" is an element of a hierarchy that appears only once
1359 under any specific parent.  The container has no value, but serves to
1360 contain other nodes.
1361
1362 To open a container, call xo_open_container() or
1363 xo_open_container_h().  The former uses the default handle and
1364 the latter accepts a specific handle.
1365
1366     int xo_open_container_h (xo_handle_t *xop, const char *name);
1367     int xo_open_container (const char *name);
1368
1369 To close a level, use the xo_close_container() or
1370 xo_close_container_h() functions:
1371
1372     int xo_close_container_h (xo_handle_t *xop, const char *name);
1373     int xo_close_container (const char *name);
1374
1375 Each open call must have a matching close call.  If the XOF_WARN flag
1376 is set and the name given does not match the name of the currently open
1377 container, a warning will be generated.
1378
1379     Example:
1380
1381         xo_open_container("top");
1382         xo_open_container("system");
1383         xo_emit("{:host-name/%s%s%s", hostname,
1384                 domainname ? "." : "", domainname ?: "");
1385         xo_close_container("system");
1386         xo_close_container("top");
1387
1388     Sample Output:
1389       Text:
1390         my-host.example.org
1391       XML:
1392         <top>
1393           <system>
1394               <host-name>my-host.example.org</host-name>
1395           </system>
1396         </top>
1397       JSON:
1398         "top" : {
1399           "system" : {
1400               "host-name": "my-host.example.org"
1401           }
1402         }
1403       HTML:
1404         <div class="data"
1405              data-tag="host-name">my-host.example.org</div>
1406
1407 *** Lists and Instances
1408
1409 A list is set of one or more instances that appear under the same
1410 parent.  The instances contain details about a specific object.  One
1411 can think of instances as objects or records.  A call is needed to
1412 open and close the list, while a distinct call is needed to open and
1413 close each instance of the list:
1414
1415     xo_open_list("item");
1416
1417     for (ip = list; ip->i_title; ip++) {
1418         xo_open_instance("item");
1419         xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title);
1420         xo_close_instance("item");
1421     }
1422
1423     xo_close_list("item");
1424
1425 Getting the list and instance calls correct is critical to the proper
1426 generation of XML and JSON data.
1427
1428 *** DTRT Mode
1429
1430 Some users may find tracking the names of open containers, lists, and
1431 instances inconvenient.  libxo offers a "Do The Right Thing" mode, where
1432 libxo will track the names of open containers, lists, and instances so
1433 the close function can be called without a name.  To enable DTRT mode,
1434 turn on the XOF_DTRT flag prior to making any other libxo output.
1435
1436     xo_set_flags(NULL, XOF_DTRT);
1437
1438 Each open and close function has a version with the suffix "_d", which
1439 will close the open container, list, or instance:
1440
1441     xo_open_container("top");
1442     ...
1443     xo_close_container_d();
1444
1445 This also works for lists and instances:
1446
1447     xo_open_list("item");
1448     for (...) {
1449         xo_open_instance("item");
1450         xo_emit(...);
1451         xo_close_instance_d();
1452     }
1453     xo_close_list_d();
1454
1455 Note that the XOF_WARN flag will also cause libxo to track open
1456 containers, lists, and instances.  A warning is generated when the
1457 name given to the close function and the name recorded do not match.
1458
1459 *** Markers
1460
1461 Markers are used to protect and restore the state of open constructs.
1462 While a marker is open, no other open constructs can be closed.  When
1463 a marker is closed, all constructs open since the marker was opened
1464 will be closed.
1465
1466 Markers use names which are not user-visible, allowing the caller to
1467 choose appropriate internal names.
1468
1469 In this example, the code whiffles through a list of fish, calling a
1470 function to emit details about each fish.  The marker "fish-guts" is
1471 used to ensure that any constructs opened by the function are closed
1472 properly.
1473
1474     for (i = 0; fish[i]; i++) {
1475         xo_open_instance("fish");
1476         xo_open_marker("fish-guts");
1477         dump_fish_details(i);
1478         xo_close_marker("fish-guts");
1479     }
1480
1481 * Command-line Arguments @options@
1482
1483 libxo uses command line options to trigger rendering behavior.  The
1484 following options are recognised:
1485
1486 - --libxo <options>
1487 - --libxo=<options>
1488 - --libxo:<brief-options>
1489
1490 The following invocations are all identical in outcome:
1491
1492   my-app --libxo warn,pretty arg1
1493   my-app --libxo=warn,pretty arg1
1494   my-app --libxo:WP arg1
1495
1496 Programs using libxo are expecting to call the xo_parse_args function
1497 to parse these arguments.  See ^xo_parse_args^ for details.
1498
1499 ** Option keywords
1500
1501 Options is a comma-separated list of tokens that correspond to output
1502 styles, flags, or features:
1503
1504 |-------------+-------------------------------------------------------|
1505 | Token       | Action                                                |
1506 |-------------+-------------------------------------------------------|
1507 | color       | Enable colors/effects for display styles (TEXT, HTML) |
1508 | colors=xxxx | Adjust color output values                            |
1509 | dtrt        | Enable "Do The Right Thing" mode                      |
1510 | flush       | Flush after every libxo function call                 |
1511 | flush-line  | Flush after every line (line-buffered)                |
1512 | html        | Emit HTML output                                      |
1513 | indent=xx   | Set the indentation level                             |
1514 | info        | Add info attributes (HTML)                            |
1515 | json        | Emit JSON output                                      |
1516 | keys        | Emit the key attribute for keys (XML)                 |
1517 | log-gettext | Log (via stderr) each gettext(3) string lookup        |
1518 | log-syslog  | Log (via stderr) each syslog message (via xo_syslog)  |
1519 | no-humanize | Ignore the {h:} modifier (TEXT, HTML)                 |
1520 | no-locale   | Do not initialize the locale setting                  |
1521 | no-retain   | Prevent retaining formatting information              |
1522 | no-top      | Do not emit a top set of braces (JSON)                |
1523 | not-first   | Pretend the 1st output item was not 1st (JSON)        |
1524 | pretty      | Emit pretty-printed output                            |
1525 | retain      | Force retaining formatting information                |
1526 | text        | Emit TEXT output                                      |
1527 | underscores | Replace XML-friendly "-"s with JSON friendly "_"s     |
1528 | units       | Add the 'units' (XML) or 'data-units (HTML) attribute |
1529 | warn        | Emit warnings when libxo detects bad calls            |
1530 | warn-xml    | Emit warnings in XML                                  |
1531 | xml         | Emit XML output                                       |
1532 | xpath       | Add XPath expressions (HTML)                          |
1533 |-------------+-------------------------------------------------------|
1534
1535 Most of these option are simple and direct, but some require
1536 additional details:
1537
1538 - "colors" is described in ^color-mapping^.
1539 - "flush-line" performs line buffering, even when the output is not
1540 directed to a TTY device.
1541 - "info" generates additional data for HTML, encoded in attributes
1542 using names that state with "data-".
1543 - "keys" adds a "key" attribute for XML output to indicate that a leaf
1544 is an identifier for the list member.
1545 - "no-humanize"avoids "humanizing" numeric output (see
1546 humanize_number(3) for details).
1547 - "no-locale" instructs libxo to avoid translating output to the
1548 current locale.
1549 - "no-retain" disables the ability of libxo to internally retain
1550 "compiled" information about formatting strings.
1551 - "underscores" can be used with JSON output to change XML-friendly
1552 names with dashes into JSON-friendly name with underscores.
1553 - "warn" allows libxo to emit warnings on stderr when application code
1554 make incorrect calls.
1555 - "warn-xml" causes those warnings to be placed in XML inside the
1556 output.
1557
1558 ** Brief Options
1559
1560 The brief options are simple single-letter aliases to the normal
1561 keywords, as detailed below:
1562
1563 |--------+---------------------------------------------|
1564 | Option | Action                                      |
1565 |--------+---------------------------------------------|
1566 | c      | Enable color/effects for TEXT/HTML          |
1567 | F      | Force line-buffered flushing                |
1568 | H      | Enable HTML output (XO_STYLE_HTML)          |
1569 | I      | Enable info output (XOF_INFO)               |
1570 | i<num> | Indent by <number>                          |
1571 | J      | Enable JSON output (XO_STYLE_JSON)          |
1572 | k      | Add keys to XPATH expressions in HTML       |
1573 | n      | Disable humanization (TEXT, HTML)           |
1574 | P      | Enable pretty-printed output (XOF_PRETTY)   |
1575 | T      | Enable text output (XO_STYLE_TEXT)          |
1576 | U      | Add units to HTML output                    |
1577 | u      | Change "-"s to "_"s in element names (JSON) |
1578 | W      | Enable warnings (XOF_WARN)                  |
1579 | X      | Enable XML output (XO_STYLE_XML)            |
1580 | x      | Enable XPath data (XOF_XPATH)               |
1581 |--------+---------------------------------------------|
1582
1583 ** Color Mapping
1584 The "colors" option takes a value that is a set of mappings from the
1585 pre-defined set of colors to new foreground and background colors.
1586 The value is a series of "fg/bg" values, separated by a "+".  Each
1587 pair of "fg/bg" values gives the colors to which a basic color is
1588 mapped when used as a foreground or background color.  The order is
1589 the mappings is:
1590
1591 - black
1592 - red
1593 - green
1594 - yellow
1595 - blue
1596 - magenta
1597 - cyan
1598 - white
1599
1600 Pairs may be skipped, leaving them mapped as normal, as are missing
1601 pairs or single colors.
1602
1603 For example consider the following xo_emit call:
1604
1605     xo_emit("{C:fg-red,bg-green}Merry XMas!!{C:}\n");
1606
1607 To turn all colored output to red-on-blue, use eight pairs of
1608 "red/blue" mappings separated by "+"s:
1609
1610     --libxo colors=red/blue+red/blue+red/blue+red/blue+\
1611                    red/blue+red/blue+red/blue+red/blue
1612
1613 To turn the red-on-green text to magenta-on-cyan, give a "magenta"
1614 foreground value for red (the second mapping) and a "cyan" background
1615 to green (the third mapping):
1616
1617     --libxo colors=+magenta+/cyan
1618
1619 Consider the common situation where blue output looks unreadable on a
1620 terminal session with a black background.  To turn both "blue"
1621 foreground and background output to "yellow", give only the fifth
1622 mapping, skipping the first four mappings with bare "+"s:
1623
1624     --libxo colors=++++yellow/yellow
1625
1626 * The libxo API
1627
1628 This section gives details about the functions in libxo, how to call
1629 them, and the actions they perform.
1630
1631 ** Handles @handles@
1632
1633 libxo uses "handles" to control its rendering functionality.  The
1634 handle contains state and buffered data, as well as callback functions
1635 to process data.
1636
1637 Handles give an abstraction for libxo that encapsulates the state of a
1638 stream of output.  Handles have the data type "xo_handle_t" and are
1639 opaque to the caller.
1640
1641 The library has a default handle that is automatically initialized.
1642 By default, this handle will send text style output (XO_STYLE_TEXT) to
1643 standard output.  The xo_set_style and xo_set_flags functions can be
1644 used to change this behavior.
1645
1646 For the typical command that is generating output on standard output,
1647 there is no need to create an explicit handle, but they are available
1648 when needed, e.g., for daemons that generate multiple streams of
1649 output.
1650
1651 Many libxo functions take a handle as their first parameter; most that
1652 do not use the default handle.  Any function taking a handle can be
1653 passed NULL to access the default handle.  For the convenience of
1654 callers, the libxo library includes handle-less functions that
1655 implicitly use the default handle.
1656
1657 For example, the following are equivalent:
1658
1659     xo_emit("test");
1660     xo_emit_h(NULL, "test");
1661
1662 Handles are created using xo_create() and destroy using xo_destroy().
1663
1664 *** xo_create
1665
1666 A handle can be allocated using the xo_create() function:
1667
1668     xo_handle_t *xo_create (unsigned style, unsigned flags);
1669
1670   Example:
1671     xo_handle_t *xop = xo_create(XO_STYLE_JSON, XOF_WARN);
1672     ....
1673     xo_emit_h(xop, "testing\n");
1674
1675 See also ^styles^ and ^flags^.
1676
1677 *** xo_create_to_file
1678
1679 By default, libxo writes output to standard output.  A convenience
1680 function is provided for situations when output should be written to
1681 a different file:
1682
1683     xo_handle_t *xo_create_to_file (FILE *fp, unsigned style,
1684                                     unsigned flags);
1685
1686 Use the XOF_CLOSE_FP flag to trigger a call to fclose() for
1687 the FILE pointer when the handle is destroyed.
1688
1689 *** xo_set_writer
1690
1691 The xo_set_writer function allows custom 'write' functions
1692 which can tailor how libxo writes data.  An opaque argument is
1693 recorded and passed back to the write function, allowing the function
1694 to acquire context information. The 'close' function can
1695 release this opaque data and any other resources as needed.
1696 The flush function can flush buffered data associated with the opaque
1697 object.
1698
1699     void xo_set_writer (xo_handle_t *xop, void *opaque,
1700                         xo_write_func_t write_func,
1701                         xo_close_func_t close_func);
1702                         xo_flush_func_t flush_func);
1703
1704 *** xo_set_style
1705
1706 To set the style, use the xo_set_style() function:
1707
1708     void xo_set_style(xo_handle_t *xop, unsigned style);
1709
1710 To use the default handle, pass a NULL handle:
1711
1712     xo_set_style(NULL, XO_STYLE_XML);
1713
1714 *** xo_get_style
1715
1716 To find the current style, use the xo_get_style() function:
1717
1718     xo_style_t xo_get_style(xo_handle_t *xop);
1719
1720 To use the default handle, pass a NULL handle:
1721
1722     style = xo_get_style(NULL);
1723
1724 **** Output Styles (XO_STYLE_*) @styles@
1725
1726 The libxo functions accept a set of output styles:
1727
1728 |---------------+-------------------------|
1729 | Flag          | Description             |
1730 |---------------+-------------------------|
1731 | XO_STYLE_TEXT | Traditional text output |
1732 | XO_STYLE_XML  | XML encoded data        |
1733 | XO_STYLE_JSON | JSON encoded data       |
1734 | XO_STYLE_HTML | HTML encoded data       |
1735 |---------------+-------------------------|
1736
1737 **** xo_set_style_name
1738
1739 The xo_set_style_name() can be used to set the style based on a name
1740 encoded as a string:
1741
1742     int xo_set_style_name (xo_handle_t *xop, const char *style);
1743
1744 The name can be any of the styles: "text", "xml", "json", or "html".
1745
1746     EXAMPLE:
1747         xo_set_style_name(NULL, "html");
1748
1749 *** xo_set_flags
1750
1751 To set the flags, use the xo_set_flags() function:
1752
1753     void xo_set_flags(xo_handle_t *xop, unsigned flags);
1754
1755 To use the default handle, pass a NULL handle:
1756
1757     xo_set_style(NULL, XO_STYLE_XML);
1758
1759 **** Flags (XOF_*) @flags@
1760
1761 The set of valid flags include:
1762
1763 |-------------------+----------------------------------------|
1764 | Flag              | Description                            |
1765 |-------------------+----------------------------------------|
1766 | XOF_CLOSE_FP      | Close file pointer on xo_destroy()     |
1767 | XOF_COLOR         | Enable color and effects in output     |
1768 | XOF_COLOR_ALLOWED | Allow color/effect for terminal output |
1769 | XOF_DTRT          | Enable "do the right thing" mode       |
1770 | XOF_INFO          | Display info data attributes (HTML)    |
1771 | XOF_KEYS          | Emit the key attribute (XML)           |
1772 | XOF_NO_ENV        | Do not use the LIBXO_OPTIONS env var   |
1773 | XOF_NO_HUMANIZE   | Display humanization (TEXT, HTML)      |
1774 | XOF_PRETTY        | Make 'pretty printed' output           |
1775 | XOF_UNDERSCORES   | Replaces hyphens with underscores      |
1776 | XOF_UNITS         | Display units (XML, HMTL)              |
1777 | XOF_WARN          | Generate warnings for broken calls     |
1778 | XOF_WARN_XML      | Generate warnings in XML on stdout     |
1779 | XOF_XPATH         | Emit XPath expressions (HTML)          |
1780 | XOF_COLUMNS       | Force xo_emit to return columns used   |
1781 | XOF_FLUSH         | Flush output after each xo_emit call   |
1782 |-------------------+----------------------------------------|
1783
1784 The XOF_CLOSE_FP flag will trigger the call of the close_func
1785 (provided via xo_set_writer()) when the handle is destroyed.
1786
1787 The XOF_COLOR flag enables color and effects in output regardless of
1788 output device, while the XOF_COLOR_ALLOWED flag allows color and
1789 effects only if the output device is a terminal.
1790
1791 The XOF_PRETTY flag requests 'pretty printing', which will trigger the
1792 addition of indentation and newlines to enhance the readability of
1793 XML, JSON, and HTML output.  Text output is not affected.
1794
1795 The XOF_WARN flag requests that warnings will trigger diagnostic
1796 output (on standard error) when the library notices errors during
1797 operations, or with arguments to functions.  Without warnings enabled,
1798 such conditions are ignored.
1799
1800 Warnings allow developers to debug their interaction with libxo.
1801 The function "xo_failure" can used as a breakpoint for a debugger,
1802 regardless of whether warnings are enabled.
1803
1804 If the style is XO_STYLE_HTML, the following additional flags can be
1805 used:
1806
1807 |---------------+-----------------------------------------|
1808 | Flag          | Description                             |
1809 |---------------+-----------------------------------------|
1810 | XOF_XPATH     | Emit "data-xpath" attributes            |
1811 | XOF_INFO      | Emit additional info fields             |
1812 |---------------+-----------------------------------------|
1813
1814 The XOF_XPATH flag enables the emission of XPath expressions detailing
1815 the hierarchy of XML elements used to encode the data field, if the
1816 XPATH style of output were requested.
1817
1818 The XOF_INFO flag encodes additional informational fields for HTML
1819 output.  See ^info^ for details.
1820
1821 If the style is XO_STYLE_XML, the following additional flags can be
1822 used:
1823
1824 |---------------+-----------------------------------------|
1825 | Flag          | Description                             |
1826 |---------------+-----------------------------------------|
1827 | XOF_KEYS      | Flag 'key' fields for xml               |
1828 |---------------+-----------------------------------------|
1829
1830 The XOF_KEYS flag adds 'key' attribute to the XML encoding for
1831 field definitions that use the 'k' modifier.  The key attribute has
1832 the value "key":
1833
1834     xo_emit("{k:name}", item);
1835
1836   XML:
1837       <name key="key">truck</name>
1838
1839 **** xo_clear_flags
1840
1841 The xo_clear_flags() function turns off the given flags in a specific
1842 handle. 
1843
1844     void xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags);
1845
1846 **** xo_set_options
1847
1848 The xo_set_options() function accepts a comma-separated list of styles
1849 and flags and enables them for a specific handle.
1850
1851     int xo_set_options (xo_handle_t *xop, const char *input);
1852
1853 The options are identical to those listed in ^options^.
1854
1855 *** xo_destroy
1856
1857 The xo_destroy function releases a handle and any resources it is
1858 using.  Calling xo_destroy with a NULL handle will release any
1859 resources associated with the default handle.
1860
1861     void xo_destroy(xo_handle_t *xop);
1862
1863 ** Emitting Content (xo_emit)
1864
1865 The following functions are used to emit output:
1866
1867     int xo_emit (const char *fmt, ...);
1868     int xo_emit_h (xo_handle_t *xop, const char *fmt, ...);
1869     int xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap);
1870
1871 The "fmt" argument is a string containing field descriptors as
1872 specified in ^format-strings^.  The use of a handle is optional and
1873 NULL can be passed to access the internal 'default' handle.  See
1874 ^handles^.
1875
1876 The remaining arguments to xo_emit() and xo_emit_h() are a set of
1877 arguments corresponding to the fields in the format string.  Care must
1878 be taken to ensure the argument types match the fields in the format
1879 string, since an inappropriate cast can ruin your day.  The vap
1880 argument to xo_emit_hv() points to a variable argument list that can
1881 be used to retrieve arguments via va_arg().
1882
1883 *** Single Field Emitting Functions (xo_emit_field) @xo_emit_field@
1884
1885 The following functions can also make output, but only make a single
1886 field at a time:
1887
1888     int xo_emit_field_hv (xo_handle_t *xop, const char *rolmod,
1889                   const char *contents, const char *fmt, 
1890                   const char *efmt, va_list vap);
1891
1892     int xo_emit_field_h (xo_handle_t *xop, const char *rolmod, 
1893                  const char *contents, const char *fmt,
1894                  const char *efmt, ...);
1895
1896     int xo_emit_field (const char *rolmod, const char *contents,
1897                  const char *fmt, const char *efmt, ...);
1898
1899 These functions are intended to avoid the scenario where one
1900 would otherwise need to compose a format descriptors using
1901 snprintf().  The individual parts of the format descriptor are
1902 passed in distinctly.
1903
1904     xo_emit("T", "Host name is ", NULL, NULL);
1905     xo_emit("V", "host-name", NULL, NULL, host-name);
1906
1907 *** Attributes (xo_attr) @xo_attr@
1908
1909 The xo_attr() function emits attributes for the XML output style.
1910
1911     int xo_attr (const char *name, const char *fmt, ...);
1912     int xo_attr_h (xo_handle_t *xop, const char *name, 
1913                    const char *fmt, ...);
1914     int xo_attr_hv (xo_handle_t *xop, const char *name, 
1915                    const char *fmt, va_list vap);
1916
1917 The name parameter give the name of the attribute to be encoded.  The
1918 fmt parameter gives a printf-style format string used to format the
1919 value of the attribute using any remaining arguments, or the vap
1920 parameter passed to xo_attr_hv().
1921
1922     EXAMPLE:
1923       xo_attr("seconds", "%ld", (unsigned long) login_time);
1924       struct tm *tmp = localtime(login_time);
1925       strftime(buf, sizeof(buf), "%R", tmp);
1926       xo_emit("Logged in at {:login-time}\n", buf);
1927     XML:
1928         <login-time seconds="1408336270">00:14</login-time>
1929
1930 xo_attr is placed on the next container, instance, leaf, or leaf list
1931 that is emitted.
1932
1933 Since attributes are only emitted in XML, their use should be limited
1934 to meta-data and additional or redundant representations of data
1935 already emitted in other form.
1936
1937 *** Flushing Output (xo_flush)
1938
1939 libxo buffers data, both for performance and consistency, but also to
1940 allow some advanced features to work properly.  At various times, the
1941 caller may wish to flush any data buffered within the library.  The
1942 xo_flush() call is used for this:
1943
1944     void xo_flush (void);
1945     void xo_flush_h (xo_handle_t *xop);
1946
1947 Calling xo_flush also triggers the flush function associated with the
1948 handle.  For the default handle, this is equivalent to
1949 "fflush(stdio);". 
1950
1951 *** Finishing Output (xo_finish)
1952
1953 When the program is ready to exit or close a handle, a call to
1954 xo_finish() is required.  This flushes any buffered data, closes
1955 open libxo constructs, and completes any pending operations.
1956
1957     int xo_finish (void);
1958     int xo_finish_h (xo_handle_t *xop);
1959     void xo_finish_atexit (void);
1960
1961 Calling this function is vital to the proper operation of libxo,
1962 especially for the non-TEXT output styles.
1963
1964 xo_finish_atexit is suitable for use with atexit(3).
1965
1966 ** Emitting Hierarchy
1967
1968 libxo represents to types of hierarchy: containers and lists.  A
1969 container appears once under a given parent where a list contains
1970 instances that can appear multiple times.  A container is used to hold
1971 related fields and to give the data organization and scope.
1972
1973 To create a container, use the xo_open_container and
1974 xo_close_container functions:
1975
1976     int xo_open_container (const char *name);
1977     int xo_open_container_h (xo_handle_t *xop, const char *name);
1978     int xo_open_container_hd (xo_handle_t *xop, const char *name);
1979     int xo_open_container_d (const char *name);
1980
1981     int xo_close_container (const char *name);
1982     int xo_close_container_h (xo_handle_t *xop, const char *name);
1983     int xo_close_container_hd (xo_handle_t *xop);
1984     int xo_close_container_d (void);
1985
1986 The name parameter gives the name of the container, encoded in UTF-8.
1987 Since ASCII is a proper subset of UTF-8, traditional C strings can be
1988 used directly.
1989
1990 The close functions with the "_d" suffix are used in "Do The Right
1991 Thing" mode, where the name of the open containers, lists, and
1992 instances are maintained internally by libxo to allow the caller to
1993 avoid keeping track of the open container name.
1994
1995 Use the XOF_WARN flag to generate a warning if the name given on the
1996 close does not match the current open container.
1997
1998 For TEXT and HTML output, containers are not rendered into output
1999 text, though for HTML they are used when the XOF_XPATH flag is set.
2000
2001     EXAMPLE:
2002        xo_open_container("system");
2003        xo_emit("The host name is {:host-name}\n", hn);
2004        xo_close_container("system");
2005     XML:
2006        <system><host-name>foo</host-name></system>
2007
2008 *** Lists and Instances
2009
2010 Lists are sequences of instances of homogeneous data objects.  Two
2011 distinct levels of calls are needed to represent them in our output
2012 styles.  Calls must be made to open and close a list, and for each
2013 instance of data in that list, calls must be make to open and close
2014 that instance.
2015
2016 The name given to all calls must be identical, and it is strongly
2017 suggested that the name be singular, not plural, as a matter of
2018 style and usage expectations.
2019
2020     EXAMPLE:
2021         xo_open_list("user");
2022         for (i = 0; i < num_users; i++) {
2023             xo_open_instance("user");
2024             xo_emit("{k:name}:{:uid/%u}:{:gid/%u}:{:home}\n",
2025                     pw[i].pw_name, pw[i].pw_uid,
2026                     pw[i].pw_gid, pw[i].pw_dir);
2027             xo_close_instance("user");
2028         }
2029         xo_close_list("user");
2030     TEXT:
2031         phil:1001:1001:/home/phil
2032         pallavi:1002:1002:/home/pallavi
2033     XML:
2034         <user>
2035             <name>phil</name>
2036             <uid>1001</uid>
2037             <gid>1001</gid>
2038             <home>/home/phil</home>
2039         </user>
2040         <user>
2041             <name>pallavi</name>
2042             <uid>1002</uid>
2043             <gid>1002</gid>
2044             <home>/home/pallavi</home>
2045         </user>
2046     JSON:
2047         user: [
2048             {
2049                 "name": "phil",
2050                 "uid": 1001,
2051                 "gid": 1001,
2052                 "home": "/home/phil",
2053             },
2054             {
2055                 "name": "pallavi",
2056                 "uid": 1002,
2057                 "gid": 1002,
2058                 "home": "/home/pallavi",
2059             }
2060         ]
2061
2062 ** Support Functions
2063
2064 *** Parsing Command-line Arguments (xo_parse_args) @xo_parse_args@
2065
2066 The xo_parse_args() function is used to process a program's
2067 arguments.  libxo-specific options are processed and removed
2068 from the argument list so the calling application does not
2069 need to process them.  If successful, a new value for argc
2070 is returned.  On failure, a message it emitted and -1 is returned.
2071
2072     argc = xo_parse_args(argc, argv);
2073     if (argc < 0)
2074         exit(EXIT_FAILURE);
2075
2076 Following the call to xo_parse_args, the application can process the
2077 remaining arguments in a normal manner.  See ^options^
2078 for a description of valid arguments.
2079
2080 *** xo_set_program
2081
2082 The xo_set_program function sets name of the program as reported by
2083 functions like xo_failure, xo_warn, xo_err, etc.  The program name is
2084 initialized by xo_parse_args, but subsequent calls to xo_set_program
2085 can override this value.
2086
2087     xo_set_program(argv[0]);
2088
2089 Note that the value is not copied, so the memory passed to
2090 xo_set_program (and xo_parse_args) must be maintained by the caller.
2091
2092 *** xo_set_version
2093
2094 The xo_set_version function records a version number to be emitted as
2095 part of the data for encoding styles (XML and JSON).  This version
2096 number is suitable for tracking changes in the content, allowing a
2097 user of the data to discern which version of the data model is in use.
2098
2099      void xo_set_version (const char *version);
2100      void xo_set_version_h (xo_handle_t *xop, const char *version);
2101
2102 *** Field Information (xo_info_t) @info@
2103
2104 HTML data can include additional information in attributes that
2105 begin with "data-".  To enable this, three things must occur:
2106
2107 First the application must build an array of xo_info_t structures,
2108 one per tag.  The array must be sorted by name, since libxo uses a
2109 binary search to find the entry that matches names from format
2110 instructions.
2111
2112 Second, the application must inform libxo about this information using
2113 the xo_set_info() call:
2114
2115     typedef struct xo_info_s {
2116         const char *xi_name;    /* Name of the element */
2117         const char *xi_type;    /* Type of field */
2118         const char *xi_help;    /* Description of field */
2119     } xo_info_t;
2120
2121     void xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count);
2122
2123 Like other libxo calls, passing NULL for the handle tells libxo to use
2124 the default handle.
2125
2126 If the count is -1, libxo will count the elements of infop, but there
2127 must be an empty element at the end.  More typically, the number is
2128 known to the application:
2129
2130     xo_info_t info[] = {
2131         { "in-stock", "number", "Number of items in stock" },
2132         { "name", "string", "Name of the item" },
2133         { "on-order", "number", "Number of items on order" },
2134         { "sku", "string", "Stock Keeping Unit" },
2135         { "sold", "number", "Number of items sold" },
2136     };
2137     int info_count = (sizeof(info) / sizeof(info[0]));
2138     ...
2139     xo_set_info(NULL, info, info_count);
2140
2141 Third, the emission of info must be triggered with the XOF_INFO flag
2142 using either the xo_set_flags() function or the "--libxo=info" command
2143 line argument.
2144
2145 The type and help values, if present, are emitted as the "data-type"
2146 and "data-help" attributes:
2147
2148   <div class="data" data-tag="sku" data-type="string" 
2149        data-help="Stock Keeping Unit">GRO-000-533</div>
2150
2151 *** Memory Allocation
2152
2153 The xo_set_allocator function allows libxo to be used in environments
2154 where the standard realloc() and free() functions are not available.
2155
2156     void xo_set_allocator (xo_realloc_func_t realloc_func,
2157                            xo_free_func_t free_func);
2158
2159 realloc_func should expect the same arguments as realloc(3) and return
2160 a pointer to memory following the same convention.  free_func will
2161 receive the same argument as free(3) and should release it, as
2162 appropriate for the environment.
2163
2164 By default, the standard realloc() and free() functions are used.
2165
2166 *** LIBXO_OPTIONS @LIBXO_OPTIONS@
2167
2168 The environment variable "LIBXO_OPTIONS" can be set to a subset of
2169 libxo options, including:
2170
2171 - color
2172 - flush
2173 - flush-line
2174 - no-color
2175 - no-humanize
2176 - no-locale
2177 - no-retain
2178 - pretty
2179 - retain
2180 - underscores
2181 - warn
2182
2183 For example, warnings can be enabled by:
2184
2185     % env LIBXO_OPTIONS=warn my-app
2186
2187 Since environment variables are inherited, child processes will have
2188 the same options, which may be undesirable, making the use of the
2189 "--libxo" option is preferable in most situations.
2190
2191 *** Errors, Warnings, and Messages
2192
2193 Many programs make use of the standard library functions err() and
2194 warn() to generate errors and warnings for the user.  libxo wants to
2195 pass that information via the current output style, and provides
2196 compatible functions to allow this:
2197
2198     void xo_warn (const char *fmt, ...);
2199     void xo_warnx (const char *fmt, ...);
2200     void xo_warn_c (int code, const char *fmt, ...);
2201     void xo_warn_hc (xo_handle_t *xop, int code,
2202                      const char *fmt, ...);
2203     void xo_err (int eval, const char *fmt, ...);
2204     void xo_errc (int eval, int code, const char *fmt, ...);
2205     void xo_errx (int eval, const char *fmt, ...);
2206     void xo_message (const char *fmt, ...);
2207     void xo_message_c (int code, const char *fmt, ...);
2208     void xo_message_hc (xo_handle_t *xop, int code,
2209                         const char *fmt, ...);
2210     void xo_message_hcv (xo_handle_t *xop, int code, 
2211                          const char *fmt, va_list vap);
2212
2213 These functions display the program name, a colon, a formatted message
2214 based on the arguments, and then optionally a colon and an error
2215 message associated with either "errno" or the "code" parameter.
2216
2217     EXAMPLE:
2218         if (open(filename, O_RDONLY) < 0)
2219             xo_err(1, "cannot open file '%s'", filename);
2220
2221 *** xo_error
2222
2223 The xo_error function can be used for generic errors that should be
2224 reported over the handle, rather than to stderr.  The xo_error
2225 function behaves like xo_err for TEXT and HTML output styles, but puts
2226 the error into XML or JSON elements:
2227
2228     EXAMPLE::
2229         xo_error("Does not %s", "compute");
2230     XML::
2231         <error><message>Does not compute</message></error>
2232     JSON::
2233         "error": { "message": "Does not compute" }
2234
2235 *** xo_no_setlocale
2236
2237 libxo automatically initializes the locale based on setting of the
2238 environment variables LC_CTYPE, LANG, and LC_ALL.  The first of this
2239 list of variables is used and if none of the variables, the locale
2240 defaults to "UTF-8".  The caller may wish to avoid this behavior, and
2241 can do so by calling the xo_no_setlocale() function.
2242
2243     void xo_no_setlocale (void);
2244
2245 ** Emitting syslog Messages
2246
2247 syslog is the system logging facility used throughout the unix world.
2248 Messages are sent from commands, applications, and daemons to a
2249 hierarchy of servers, where they are filtered, saved, and forwarded
2250 based on configuration behaviors.
2251
2252 syslog is an older protocol, originally documented only in source
2253 code.  By the time RFC 3164 published, variation and mutation left the
2254 leading "<pri>" string as only common content.  RFC 5424 defines a new
2255 version (version 1) of syslog and introduces structured data into the
2256 messages.  Structured data is a set of name/value pairs transmitted
2257 distinctly alongside the traditional text message, allowing filtering
2258 on precise values instead of regular expressions.
2259
2260 These name/value pairs are scoped by a two-part identifier; an
2261 enterprise identifier names the party responsible for the message
2262 catalog and a name identifying that message.  Enterprise IDs are
2263 defined by IANA, the Internet Assigned Numbers Authority:
2264
2265 https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
2266
2267 Use the ^xo_set_syslog_enterprise_id^() function to set the Enterprise
2268 ID, as needed.
2269
2270 The message name should follow the conventions in ^good-field-names^,
2271 as should the fields within the message.
2272
2273     /* Both of these calls are optional */
2274     xo_set_syslog_enterprise_id(32473);
2275     xo_open_log("my-program", 0, LOG_DAEMON);
2276
2277     /* Generate a syslog message */
2278     xo_syslog(LOG_ERR, "upload-failed",
2279               "error <%d> uploading file '{:filename}' "
2280               "as '{:target/%s:%s}'",
2281               code, filename, protocol, remote);
2282
2283     xo_syslog(LOG_INFO, "poofd-invalid-state",
2284               "state {:current/%u} is invalid {:connection/%u}",
2285               state, conn);
2286
2287 The developer should be aware that the message name may be used in the
2288 future to allow access to further information, including
2289 documentation.  Care should be taken to choose quality, descriptive
2290 names.
2291
2292 *** Priority, Facility, and Flags @priority@
2293
2294 The xo_syslog, xo_vsyslog, and xo_open_log functions accept a set of
2295 flags which provide the priority of the message, the source facility,
2296 and some additional features.  These values are OR'd together to
2297 create a single integer argument:
2298
2299     xo_syslog(LOG_ERR | LOG_AUTH, "login-failed",
2300              "Login failed; user '{:user}' from host '{:address}'",
2301              user, addr);
2302
2303 These values are defined in <syslog.h>.
2304
2305 The priority value indicates the importance and potential impact of
2306 each message.
2307
2308 |-------------+-------------------------------------------------------|
2309 | Priority    | Description                                           |
2310 |-------------+-------------------------------------------------------|
2311 | LOG_EMERG   | A panic condition, normally broadcast to all users    |
2312 | LOG_ALERT   | A condition that should be corrected immediately      |
2313 | LOG_CRIT    | Critical conditions                                   |
2314 | LOG_ERR     | Generic errors                                        |
2315 | LOG_WARNING | Warning messages                                      |
2316 | LOG_NOTICE  | Non-error conditions that might need special handling |
2317 | LOG_INFO    | Informational messages                                |
2318 | LOG_DEBUG   | Developer-oriented messages                           |
2319 |-------------+-------------------------------------------------------|
2320
2321 The facility value indicates the source of message, in fairly generic
2322 terms. 
2323
2324 |---------------+-------------------------------------------------|
2325 | Facility      | Description                                     |
2326 |---------------+-------------------------------------------------|
2327 | LOG_AUTH      | The authorization system (e.g. login(1))        |
2328 | LOG_AUTHPRIV  | As LOG_AUTH, but logged to a privileged file    |
2329 | LOG_CRON      | The cron daemon: cron(8)                        |
2330 | LOG_DAEMON    | System daemons, not otherwise explicitly listed |
2331 | LOG_FTP       | The file transfer protocol daemons              |
2332 | LOG_KERN      | Messages generated by the kernel                |
2333 | LOG_LPR       | The line printer spooling system                |
2334 | LOG_MAIL      | The mail system                                 |
2335 | LOG_NEWS      | The network news system                         |
2336 | LOG_SECURITY  | Security subsystems, such as ipfw(4)            |
2337 | LOG_SYSLOG    | Messages generated internally by syslogd(8)     |
2338 | LOG_USER      | Messages generated by user processes (default)  |
2339 | LOG_UUCP      | The uucp system                                 |
2340 | LOG_LOCAL0..7 | Reserved for local use                          |
2341 |---------------+-------------------------------------------------|
2342
2343 In addition to the values listed above, xo_open_log accepts a set of
2344 addition flags requesting specific behaviors.
2345
2346 |------------+----------------------------------------------------|
2347 | Flag       | Description                                        |
2348 |------------+----------------------------------------------------|
2349 | LOG_CONS   | If syslogd fails, attempt to write to /dev/console |
2350 | LOG_NDELAY | Open the connection to syslogd(8) immediately      |
2351 | LOG_PERROR | Write the message also to standard error output    |
2352 | LOG_PID    | Log the process id with each message               |
2353 |------------+----------------------------------------------------|
2354
2355 *** xo_syslog
2356
2357 Use the xo_syslog function to generate syslog messages by calling it
2358 with a log priority and facility, a message name, a format string, and
2359 a set of arguments.  The priority/facility argument are discussed
2360 above, as is the message name.
2361
2362 The format string follows the same conventions as xo_emit's format
2363 string, with each field being rendered as an SD-PARAM pair.
2364
2365     xo_syslog(LOG_ERR, "poofd-missing-file",
2366               "'{:filename}' not found: {:error/%m}", filename);
2367
2368     ... [poofd-missing-file@32473 filename="/etc/poofd.conf"
2369           error="Permission denied"] '/etc/poofd.conf' not
2370           found: Permission denied
2371
2372 *** Support functions
2373
2374 **** xo_vsyslog
2375
2376 xo_vsyslog is identical in function to xo_syslog, but takes the set of
2377 arguments using a va_list.
2378
2379     void my_log (const char *name, const char *fmt, ...)
2380     {
2381         va_list vap;
2382         va_start(vap, fmt);
2383         xo_vsyslog(LOG_ERR, name, fmt, vap);
2384         va_end(vap);
2385     }
2386
2387 **** xo_open_log
2388
2389 xo_open_log functions similar to openlog(3), allowing customization of
2390 the program name, the log facility number, and the additional option
2391 flags described in ^priority^.
2392
2393     void
2394     xo_open_log (const char *ident, int logopt, int facility);
2395
2396 **** xo_close_log
2397
2398 xo_close_log functions similar to closelog(3), closing the log file
2399 and releasing any associated resources.
2400
2401     void
2402     xo_close_log (void);
2403
2404 **** xo_set_logmask
2405
2406 xo_set_logmask function similar to setlogmask(3), restricting the set
2407 of generated log event to those whose associated bit is set in
2408 maskpri.  Use LOG_MASK(pri) to find the appropriate bit, or
2409 LOG_UPTO(toppri) to create a mask for all priorities up to and
2410 including toppri.
2411
2412     int
2413     xo_set_logmask (int maskpri);
2414
2415   Example:
2416     setlogmask(LOG_UPTO(LOG_WARN));
2417
2418 **** xo_set_syslog_enterprise_id
2419
2420 Use the xo_set_syslog_enterprise_id to supply a platform- or
2421 application-specific enterprise id.  This value is used in any
2422 future syslog messages.
2423
2424 Ideally, the operating system should supply a default value via the
2425 "kern.syslog.enterprise_id" sysctl value.  Lacking that, the
2426 application should provide a suitable value.
2427
2428     void
2429     xo_set_syslog_enterprise_id (unsigned short eid);
2430
2431 Enterprise IDs are administered by IANA, the Internet Assigned Number
2432 Authority.  The complete list is EIDs on their web site:
2433
2434     https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
2435
2436 New EIDs can be requested from IANA using the following page:
2437
2438     http://pen.iana.org/pen/PenApplication.page
2439
2440 Each software development organization that defines a set of syslog
2441 messages should register their own EID and use that value in their
2442 software to ensure that messages can be uniquely identified by the
2443 combination of EID + message name.
2444
2445 ** Creating Custom Encoders
2446
2447 The number of encoding schemes in current use is staggering, with new
2448 and distinct schemes appearing daily.  While libxo provide XML, JSON,
2449 HMTL, and text natively, there are requirements for other encodings.
2450
2451 Rather than bake support for all possible encoders into libxo, the API
2452 allows them to be defined externally.  libxo can then interfaces with
2453 these encoding modules using a simplistic API.  libxo processes all
2454 functions calls, handles state transitions, performs all formatting,
2455 and then passes the results as operations to a customized encoding
2456 function, which implements specific encoding logic as required.  This
2457 means your encoder doesn't need to detect errors with unbalanced
2458 open/close operations but can rely on libxo to pass correct data.
2459
2460 By making a simple API, libxo internals are not exposed, insulating the
2461 encoder and the library from future or internal changes.
2462
2463 The three elements of the API are:
2464 - loading
2465 - initialization
2466 - operations
2467
2468 The following sections provide details about these topics.
2469
2470 libxo source contain an encoder for Concise Binary Object
2471 Representation, aka CBOR (RFC 7049) which can be used as used as an
2472 example for the API.
2473
2474 *** Loading Encoders
2475
2476 Encoders can be registered statically or discovered dynamically.
2477 Applications can choose to call the xo_encoder_register()
2478 function to explicitly register encoders, but more typically they are
2479 built as shared libraries, placed in the libxo/extensions directory,
2480 and loaded based on name.  libxo looks for a file with the name of the encoder
2481 and an extension of ".enc".  This can be a file or a symlink to the
2482 shared library file that supports the encoder.
2483
2484     % ls -1 lib/libxo/extensions/*.enc
2485     lib/libxo/extensions/cbor.enc
2486     lib/libxo/extensions/test.enc
2487
2488 *** Encoder Initialization
2489
2490 Each encoder must export a symbol used to access the library, which
2491 must have the following signature:
2492
2493     int xo_encoder_library_init (XO_ENCODER_INIT_ARGS);
2494
2495 XO_ENCODER_INIT_ARGS is a macro defined in xo_encoder.h that defines
2496 an argument called "arg", a pointer of the type
2497 xo_encoder_init_args_t.  This structure contains two fields:
2498
2499 - xei_version is the version number of the API as implemented within
2500 libxo.  This version is currently as 1 using XO_ENCODER_VERSION.  This
2501 number can be checked to ensure compatibility.  The working assumption
2502 is that all versions should be backward compatible, but each side may
2503 need to accurately know the version supported by the other side.  
2504 xo_encoder_library_init can optionally check this value, and must then
2505 set it to the version number used by the encoder, allowing libxo to
2506 detect version differences and react accordingly.  For example, if
2507 version 2 adds new operations, then libxo will know that an encoding
2508 library that set xei_version to 1 cannot be expected to handle those
2509 new operations.
2510
2511 - xei_handler must be set to a pointer to a function of type
2512 xo_encoder_func_t, as defined in xo_encoder.h.  This function
2513 takes a set of parameters:
2514 -- xop is a pointer to the opaque xo_handle_t structure
2515 -- op is an integer representing the current operation
2516 -- name is a string whose meaning differs by operation
2517 -- value is a string whose meaning differs by operation
2518 -- private is an opaque structure provided by the encoder
2519
2520 Additional arguments may be added in the future, so handler functions
2521 should use the XO_ENCODER_HANDLER_ARGS macro.  An appropriate
2522 "extern" declaration is provided to help catch errors.
2523
2524 Once the encoder initialization function has completed processing, it
2525 should return zero to indicate that no error has occurred.  A non-zero
2526 return code will cause the handle initialization to fail.
2527
2528 *** Operations
2529
2530 The encoder API defines a set of operations representing the
2531 processing model of libxo.  Content is formatted within libxo, and
2532 callbacks are made to the encoder's handler function when data is
2533 ready to be processed.
2534
2535 |-----------------------+---------------------------------------|
2536 | Operation             | Meaning  (Base function)              |
2537 |-----------------------+---------------------------------------|
2538 | XO_OP_CREATE          | Called when the handle is created     |
2539 | XO_OP_OPEN_CONTAINER  | Container opened (xo_open_container)  |
2540 | XO_OP_CLOSE_CONTAINER | Container closed (xo_close_container) |
2541 | XO_OP_OPEN_LIST       | List opened (xo_open_list)            |
2542 | XO_OP_CLOSE_LIST      | List closed (xo_close_list)           |
2543 | XO_OP_OPEN_LEAF_LIST  | Leaf list opened (xo_open_leaf_list)  |
2544 | XO_OP_CLOSE_LEAF_LIST | Leaf list closed (xo_close_leaf_list) |
2545 | XO_OP_OPEN_INSTANCE   | Instance opened (xo_open_instance)    |
2546 | XO_OP_CLOSE_INSTANCE  | Instance closed (xo_close_instance)   |
2547 | XO_OP_STRING          | Field with Quoted UTF-8 string        |
2548 | XO_OP_CONTENT         | Field with content                    |
2549 | XO_OP_FINISH          | Finish any pending output             |
2550 | XO_OP_FLUSH           | Flush any buffered output             |
2551 | XO_OP_DESTROY         | Clean up resources                    |
2552 | XO_OP_ATTRIBUTE       | An attribute name/value pair          |
2553 | XO_OP_VERSION         | A version string                      |
2554 |-----------------------+---------------------------------------|
2555
2556 For all the open and close operations, the name parameter holds the
2557 name of the construct.  For string, content, and attribute operations,
2558 the name parameter is the name of the field and the value parameter is
2559 the value.  "string" are differentiated from "content" to allow differing
2560 treatment of true, false, null, and numbers from real strings, though
2561 content values are formatted as strings before the handler is called.
2562 For version operations, the value parameter contains the version.
2563
2564 All strings are encoded in UTF-8.
2565
2566 * The "xo" Utility
2567
2568 The "xo" utility allows command line access to the functionality of
2569 the libxo library.  Using "xo", shell scripts can emit XML, JSON, and
2570 HTML using the same commands that emit text output.
2571
2572 The style of output can be selected using a specific option: "-X" for
2573 XML, "-J" for JSON, "-H" for HTML, or "-T" for TEXT, which is the
2574 default.  The "--style <style>" option can also be used.  The standard
2575 set of "--libxo" options are available (see ^options^), as well as the
2576 LIBXO_OPTIONS environment variable (see ^LIBXO_OPTIONS^).
2577
2578 The "xo" utility accepts a format string suitable for xo_emit() and a
2579 set of zero or more arguments used to supply data for that string.
2580
2581     xo "The {k:name} weighs {:weight/%d} pounds.\n" fish 6
2582
2583   TEXT:
2584     The fish weighs 6 pounds.
2585   XML:
2586     <name>fish</name>
2587     <weight>6</weight>
2588   JSON:
2589     "name": "fish",
2590     "weight": 6
2591   HTML:
2592     <div class="line">
2593       <div class="text">The </div>
2594       <div class="data" data-tag="name">fish</div>
2595       <div class="text"> weighs </div>
2596       <div class="data" data-tag="weight">6</div>
2597       <div class="text"> pounds.</div>
2598     </div>
2599
2600 The "--wrap <path>" option can be used to wrap emitted content in a
2601 specific hierarchy.  The path is a set of hierarchical names separated
2602 by the '/' character.
2603
2604     xo --wrap top/a/b/c '{:tag}' value
2605
2606   XML:
2607     <top>
2608       <a>
2609         <b>
2610           <c>
2611             <tag>value</tag>
2612           </c>
2613         </b>
2614       </a>
2615     </top>
2616   JSON:
2617     "top": {
2618       "a": {
2619         "b": {
2620           "c": {
2621             "tag": "value"
2622           }
2623         }
2624       }
2625     }
2626
2627 The "--open <path>" and "--close <path>" can be used to emit
2628 hierarchical information without the matching close and open
2629 tag.  This allows a shell script to emit open tags, data, and
2630 then close tags.  The "--depth" option may be used to set the
2631 depth for indentation.  The "--leading-xpath" may be used to
2632 prepend data to the XPath values used for HTML output style.
2633
2634     #!/bin/sh
2635     xo --open top/data
2636     xo --depth 2 '{tag}' value
2637     xo --close top/data
2638   XML:
2639     <top>
2640       <data>
2641         <tag>value</tag>
2642       </data>
2643     </top>
2644   JSON:
2645     "top": {
2646       "data": {
2647         "tag": "value"
2648       }
2649     }
2650
2651 ** Command Line Options
2652
2653 Usage: xo [options] format [fields]
2654   --close <path>        Close tags for the given path
2655   --depth <num>         Set the depth for pretty printing
2656   --help                Display this help text
2657   --html OR -H          Generate HTML output
2658   --json OR -J          Generate JSON output
2659   --leading-xpath <path> Add a prefix to generated XPaths (HTML)
2660   --open <path>         Open tags for the given path
2661   --pretty OR -p        Make 'pretty' output (add indent, newlines)
2662   --style <style>       Generate given style (xml, json, text, html)
2663   --text OR -T          Generate text output (the default style)
2664   --version             Display version information
2665   --warn OR -W          Display warnings in text on stderr
2666   --warn-xml            Display warnings in xml on stdout
2667   --wrap <path>         Wrap output in a set of containers
2668   --xml OR -X           Generate XML output
2669   --xpath               Add XPath data to HTML output);
2670
2671 ** Example
2672
2673   % xo 'The {:product} is {:status}\n' stereo "in route"
2674   The stereo is in route
2675   % ./xo/xo -p -X 'The {:product} is {:status}\n' stereo "in route"
2676   <product>stereo</product>
2677   <status>in route</status>
2678
2679 * xolint
2680
2681 xolint is a tool for reporting common mistakes in format strings
2682 in source code that invokes xo_emit().  It allows these errors
2683 to be diagnosed at build time, rather than waiting until runtime.
2684
2685 xolint takes the one or more C files as arguments, and reports
2686 and errors, warning, or informational messages as needed.
2687
2688 |------------+---------------------------------------------------|
2689 | Option     | Meaning                                           |
2690 |------------+---------------------------------------------------|
2691 | -c         | Invoke 'cpp' against the input file               |
2692 | -C <flags> | Flags that are passed to 'cpp                     |
2693 | -d         | Enable debug output                               |
2694 | -D         | Generate documentation for all xolint messages    |
2695 | -I         | Generate info table code                          |
2696 | -p         | Print the offending lines after the message       |
2697 | -V         | Print vocabulary of all field names               |
2698 | -X         | Extract samples from xolint, suitable for testing |
2699 |------------+---------------------------------------------------|
2700
2701 The output message will contain the source filename and line number, the
2702 class of the message, the message, and, if -p is given, the
2703 line that contains the error:
2704
2705     % xolint.pl -t xolint.c
2706     xolint.c: 16: error: anchor format should be "%d"
2707     16         xo_emit("{[:/%s}");
2708
2709 The "-I" option will generate a table of xo_info_t structures , 
2710
2711 The "-V" option does not report errors, but prints a complete list of
2712 all field names, sorted alphabetically.  The output can help spot
2713 inconsistencies and spelling errors.
2714
2715 * xohtml @xohtml@
2716
2717 xohtml is a tool for turning the output of libxo-enabled commands into
2718 html files suitable for display in modern HTML web browsers.  It can
2719 be used to test and debug HTML output, as well as to make the user
2720 ache to escape the world of 70s terminal devices.
2721
2722 xohtml is given a command, either on the command line or via the "-c"
2723 option.  If not command is given, standard input is used.  The
2724 command's output is wrapped in HTML tags, with references to
2725 supporting CSS and Javascript files, and written to standard output or
2726 the file given in the "-f" option.  The "-b" option can be used to
2727 provide an alternative base path for the support files.
2728
2729 |--------------+---------------------------------------------------|
2730 | Option       | Meaning                                           |
2731 |--------------+---------------------------------------------------|
2732 | -b <base>    | Base path for finding css/javascript files        |
2733 | -c <command> | Command to execute                                |
2734 | -f <file>    | Output file name                                  |
2735 |--------------+---------------------------------------------------|
2736
2737 The "-c" option takes a full command with arguments, including
2738 any libxo options needed to generate html ("--libxo=html").  This
2739 value must be quoted if it consists of multiple tokens.
2740
2741 * xopo
2742
2743 The "xopo" utility filters ".pot" files generated by the "xgettext"
2744 utility to remove formatting information suitable for use with
2745 the "{G:}" modifier.  This means that when the developer changes the
2746 formatting portion of the field definitions, or the fields modifiers,
2747 the string passed to gettext(3) is unchanged, avoiding the expense of
2748 updating any existing translation files (".po" files).
2749
2750 The syntax for the xopo command is one of two forms; it can be used as
2751 a filter for processing a .po or .pot file, rewriting the "msgid"
2752 strings with a simplified message string.  In this mode, the input is
2753 either standard input or a file given by the "-f" option, and the
2754 output is either standard output or a file given by the "-o" option.
2755
2756 In the second mode, a simple message given using the "-s" option on
2757 the command, and the simplified version of that message is printed on
2758 stdout.
2759
2760 |-----------+---------------------------------|
2761 | Option    | Meaning                         |
2762 |-----------+---------------------------------|
2763 | -o <file> | Output file name                |
2764 | -f <file> | Use the given .po file as input |
2765 | -s <text> | Simplify a format string        |
2766 |-----------+---------------------------------|
2767
2768     EXAMPLE:
2769         % xopo -s "There are {:count/%u} {:event/%.6s} events\n"
2770         There are {:count} {:event} events\n
2771
2772         % xgettext --default-domain=foo --no-wrap \
2773             --add-comments --keyword=xo_emit --keyword=xo_emit_h \
2774             --keyword=xo_emit_warn -C -E -n --foreign-user \
2775             -o foo.pot.raw foo.c
2776         % xopo -f foo.pot.raw -o foo.pot
2777
2778 Use of the "--no-wrap" option for xgettext is required to ensure that
2779 incoming msgid strings are not wrapped across multiple lines.
2780
2781 * FAQs
2782
2783 This section contains the set of questions that users typically ask,
2784 along with answers that might be helpful.
2785
2786 !! list-sections
2787
2788 ** General
2789
2790 *** Can you share the history of libxo?
2791
2792 In 2001, we added an XML API to the JUNOS operating system, which is
2793 built on top of FreeBSD.  Eventually this API became standardized as
2794 the NETCONF API (RFC 6241).  As part of this effort, we modified many
2795 FreeBSD utilities to emit XML, typically via a "-X" switch.  The
2796 results were mixed.  The cost of maintaining this code, updating it,
2797 and carrying it were non-trivial, and contributed to our expense (and
2798 the associated delay) with upgrading the version of FreeBSD on which
2799 each release of JUNOS is based.
2800
2801 A recent (2014) effort within JUNOS aims at removing our modifications
2802 to the underlying FreeBSD code as a means of reducing the expense and
2803 delay in tracking HEAD.  JUNOS is structured to have system components
2804 generate XML that is rendered by the CLI (think: login shell) into
2805 human-readable text.  This allows the API to use the same plumbing as
2806 the CLI, and ensures that all components emit XML, and that it is
2807 emitted with knowledge of the consumer of that XML, yielding an API
2808 that have no incremental cost or feature delay.
2809
2810 libxo is an effort to mix the best aspects of the JUNOS strategy into
2811 FreeBSD in a seemless way, allowing commands to make printf-like
2812 output calls with a single code path.
2813
2814 *** Did the complex semantics of format strings evolve over time?
2815
2816 The history is both long and short: libxo's functionality is based
2817 on what JUNOS does in a data modeling language called ODL (output
2818 definition language).  In JUNOS, all subcomponents generate XML,
2819 which is feed to the CLI, where data from the ODL files tell is
2820 how to render that XML into text.  ODL might had a set of tags
2821 like:
2822
2823      tag docsis-state {
2824          help "State of the DOCSIS interface";
2825          type string;
2826      }
2827
2828      tag docsis-mode {
2829          help "DOCSIS mode (2.0/3.0) of the DOCSIS interface";
2830          type string;
2831      }
2832
2833      tag docsis-upstream-speed {
2834          help "Operational upstream speed of the interface";
2835          type string;
2836      }
2837
2838      tag downstream-scanning {
2839          help "Result of scanning in downstream direction";
2840          type string;
2841      }
2842
2843      tag ranging {
2844          help "Result of ranging action";
2845          type string;
2846      }
2847
2848      tag signal-to-noise-ratio {
2849          help "Signal to noise ratio for all channels";
2850          type string;
2851      }
2852
2853      tag power {
2854          help "Operational power of the signal on all channels";
2855          type string;
2856      }
2857
2858      format docsis-status-format {
2859          picture "
2860    State   : @, Mode: @, Upstream speed: @
2861    Downstream scanning: @, Ranging: @
2862    Signal to noise ratio: @
2863    Power: @
2864 ";
2865          line {
2866              field docsis-state;
2867              field docsis-mode;
2868              field docsis-upstream-speed;
2869              field downstream-scanning;
2870              field ranging;
2871              field signal-to-noise-ratio;
2872              field power;
2873          }
2874      }
2875
2876 These tag definitions are compiled into field definitions
2877 that are triggered when matching XML elements are seen.  ODL
2878 also supports other means of defining output.
2879
2880 The roles and modifiers describe these details.
2881
2882 In moving these ideas to bsd, two things had to happen: the
2883 formatting had to happen at the source since BSD won't have
2884 a JUNOS-like CLI to do the rendering, and we can't depend on
2885 external data models like ODL, which was seen as too hard a
2886 sell to the BSD community.
2887
2888 The results were that the xo_emit strings are used to encode the
2889 roles, modifiers, names, and formats.  They are dense and a bit
2890 cryptic, but not so unlike printf format strings that developers will
2891 be lost.
2892
2893 libxo is a new implementation of these ideas and is distinct from
2894 the previous implementation in JUNOS.
2895
2896 *** What makes a good field name? @good-field-names@
2897
2898 To make useful, consistent field names, follow these guidelines:
2899
2900 = Use lower case, even for TLAs
2901 Lower case is more civilized.  Even TLAs should be lower case
2902 to avoid scenarios where the differences between "XPath" and
2903 "Xpath" drive your users crazy.  Using "xpath" is simpler and better.
2904 = Use hyphens, not underscores
2905 Use of hyphens is traditional in XML, and the XOF_UNDERSCORES
2906 flag can be used to generate underscores in JSON, if desired.
2907 But the raw field name should use hyphens.
2908 = Use full words
2909 Don't abbreviate especially when the abbreviation is not obvious or
2910 not widely used.  Use "data-size", not "dsz" or "dsize".  Use
2911 "interface" instead of "ifname", "if-name", "iface", "if", or "intf".
2912 = Use <verb>-<units>
2913 Using the form <verb>-<units> or <verb>-<classifier>-<units> helps in
2914 making consistent, useful names, avoiding the situation where one app
2915 uses "sent-packet" and another "packets-sent" and another
2916 "packets-we-have-sent".  The <units> can be dropped when it is
2917 obvious, as can obvious words in the classification.
2918 Use "receive-after-window-packets" instead of
2919 "received-packets-of-data-after-window".
2920 = Reuse existing field names
2921 Nothing's worse than writing expressions like:
2922
2923     if ($src1/process[pid == $pid]/name == 
2924         $src2/proc-table/proc-list
2925                    /proc-entry[process-id == $pid]/proc-name) {
2926         ...
2927     }
2928
2929 Find someone else who is expressing similar data and follow their
2930 fields and hierarchy.  Remember the quote is not "Consistency is the
2931 hobgoblin of little minds", but "A foolish consistency is the
2932 hobgoblin of little minds".
2933 = Use containment as scoping
2934 In the previous example, all the names are prefixed with "proc-",
2935 which is redundant given that they are nested under the process table.
2936 = Think about your users
2937 Have empathy for your users, choosing clear and useful fields that
2938 contain clear and useful data.  You may need to augment the display
2939 content with xo_attr() calls (^xo_attr^) or "{e:}" fields
2940 (^e-modifier^) to make the data useful.
2941 = Don't use an arbitrary number postfix
2942 What does "errors2" mean?  No one will know.  "errors-after-restart"
2943 would be a better choice.  Think of your users, and think of the
2944 future.  If you make "errors2", the next guy will happily make
2945 "errors3" and before you know it, someone will be asking what's the
2946 difference between errors37 and errors63.
2947 = Be consistent, uniform, unsurprising, and predictable
2948 Think of your field vocabulary as an API.  You want it useful,
2949 expressive, meaningful, direct, and obvious.  You want the client
2950 application's programmer to move between without the need to
2951 understand a variety of opinions on how fields are named.  They should
2952 see the system as a single cohesive whole, not a sack of cats.
2953
2954 Field names constitute the means by which client programmers interact
2955 with our system.  By choosing wise names now, you are making their
2956 lives better.
2957
2958 After using "xolint" to find errors in your field descriptors, use
2959 "xolint -V" to spell check your field names and to detect different
2960 names for the same data.  "dropped-short" and "dropped-too-short" are
2961 both reasonable names, but using them both will lead users to ask the
2962 difference between the two fields.  If there is no difference,
2963 use only one of the field names.  If there is a difference, change the
2964 names to make that difference more obvious.
2965
2966 ** What does this message mean?
2967
2968 !!include-file xolint.txt
2969
2970 * Howtos: Focused Directions
2971
2972 This section provides task-oriented instructions for selected tasks.
2973 If you have a task that needs instructions, please open a request as
2974 an enhancement issue on github.
2975
2976 ** Howto: Report bugs
2977
2978 libxo uses github to track bugs or request enhancements.  Please use
2979 the following URL:
2980
2981   https://github.com/Juniper/libxo/issues
2982
2983 ** Howto: Install libxo
2984
2985 libxo is open source, under a new BSD license.  Source code is
2986 available on github, as are recent releases.  To get the most
2987 current release, please visit:
2988
2989   https://github.com/Juniper/libxo/releases
2990
2991 After downloading and untarring the source code, building involves the
2992 following steps:
2993
2994     sh bin/setup.sh
2995     cd build
2996     ../configure
2997     make
2998     make test
2999     sudo make install
3000
3001 libxo uses a distinct "build" directory to keep generated files
3002 separated from source files.
3003
3004 Use "../configure --help" to display available configuration options,
3005 which include the following:
3006
3007   --enable-warnings      Turn on compiler warnings
3008   --enable-debug         Turn on debugging
3009   --enable-text-only     Turn on text-only rendering
3010   --enable-printflike    Enable use of GCC __printflike attribute
3011   --disable-libxo-options  Turn off support for LIBXO_OPTIONS
3012   --with-gettext=PFX     Specify location of gettext installation
3013   --with-libslax-prefix=PFX  Specify location of libslax config
3014
3015 Compiler warnings are a very good thing, but recent compiler version
3016 have added some very pedantic checks.  While every attempt is made to
3017 keep libxo code warning-free, warnings are now optional.  If you are
3018 doing development work on libxo, it is required that you
3019 use --enable-warnings to keep the code warning free, but most users
3020 need not use this option.
3021
3022 libxo provides the --enable-text-only option to reduce the footprint
3023 of the library for smaller installations.  XML, JSON, and HTML
3024 rendering logic is removed.
3025
3026 The gettext library does not provide a simple means of learning its
3027 location, but libxo will look for it in /usr and /opt/local.  If
3028 installed elsewhere, the installer will need to provide this
3029 information using the --with-gettext=/dir/path option.
3030
3031 libslax is not required by libxo; it contains the "oxtradoc" program
3032 used to format documentation.
3033
3034 For additional information, see ^building-libxo^.
3035
3036 ** Howto: Convert command line applications
3037
3038     How do I convert an existing command line application?
3039
3040 There are three basic steps for converting command line application to
3041 use libxo.
3042
3043 - Setting up the context
3044 - Converting printf calls
3045 - Creating hierarchy
3046 - Converting error functions
3047
3048 *** Setting up the context
3049
3050 To use libxo, you'll need to include the "xo.h" header file in your
3051 source code files:
3052
3053     #include <libxo/xo.h>
3054
3055 In your main() function, you'll need to call xo_parse_args to handling
3056 argument parsing (^xo_parse_args^).  This function removes
3057 libxo-specific arguments the program's argv and returns either the
3058 number of remaining arguments or -1 to indicate an error.
3059
3060     int main (int argc, char **argv)
3061     {
3062         argc = xo_parse_args(argc, argv);
3063         if (argc < 0)
3064             return argc;
3065         ....
3066     }
3067
3068 At the bottom of your main(), you'll need to call xo_finish() to
3069 complete output processing for the default handle (^handles^).  libxo
3070 provides the xo_finish_atexit function that is suitable for use with
3071 the atexit(3) function.
3072
3073     atexit(xo_finish_atexit);
3074
3075 *** Converting printf Calls
3076
3077 The second task is inspecting code for printf(3) calls and replacing
3078 them with xo_emit() calls.  The format strings are similar in task,
3079 but libxo format strings wrap output fields in braces.  The following
3080 two calls produce identical text output:
3081
3082     printf("There are %d %s events\n", count, etype);
3083     xo_emit("There are {:count/%d} {:event} events\n", count, etype);
3084
3085 "count" and "event" are used as names for JSON and XML output.  The
3086 "count" field uses the format "%d" and "event" uses the default "%s"
3087 format.  Both are "value" roles, which is the default role.
3088
3089 Since text outside of output fields is passed verbatim, other roles
3090 are less important, but their proper use can help make output more
3091 useful.  The "note" and "label" roles allow HTML output to recognize
3092 the relationship between text and the associated values, allowing
3093 appropriate "hover" and "onclick" behavior.  Using the "units" role
3094 allows the presentation layer to perform conversions when needed.  The
3095 "warning" and "error" roles allows use of color and font to draw
3096 attention to warnings.  The "padding" role makes the use of vital
3097 whitespace more clear (^padding-role^).
3098
3099 The "title" role indicates the headings of table and sections.  This
3100 allows HTML output to use CSS to make this relationship more obvious.
3101
3102     printf("Statistics:\n");
3103     xo_emit("{T:Statistics}:\n");
3104
3105 The "color" roles controls foreground and background colors, as well
3106 as effects like bold and underline (see ^color-role^).
3107
3108     xo_emit("{C:bold}required{C:}\n");
3109
3110 Finally, the start- and stop-anchor roles allow justification and
3111 padding over multiple fields (see ^anchor-role^).
3112
3113     snprintf(buf, sizeof(buf), "(%u/%u/%u)", min, ave, max);
3114     printf("%30s", buf);
3115    
3116     xo_emit("{[:30}({:minimum/%u}/{:average/%u}/{:maximum/%u}{]:}",
3117             min, ave, max);
3118
3119 *** Creating Hierarchy
3120
3121 Text output doesn't have any sort of hierarchy, but XML and JSON
3122 require this.  Typically applications use indentation to represent
3123 these relationship:
3124
3125     printf("table %d\n", tnum);
3126     for (i = 0; i < tmax; i++) {
3127         printf("    %s %d\n", table[i].name, table[i].size);
3128     }
3129
3130     xo_emit("{T:/table %d}\n", tnum);
3131     xo_open_list("table");
3132     for (i = 0; i < tmax; i++) {
3133         xo_open_instance("table");
3134         xo_emit("{P:    }{k:name} {:size/%d}\n",
3135                 table[i].name, table[i].size);
3136         xo_close_instance("table");
3137     }
3138     xo_close_list("table");
3139
3140 The open and close list functions are used before and after the list,
3141 and the open and close instance functions are used before and after
3142 each instance with in the list.
3143
3144 Typically these developer looks for a "for" loop as an indication of
3145 where to put these calls.
3146
3147 In addition, the open and close container functions allow for
3148 organization levels of hierarchy.
3149
3150     printf("Paging information:\n");
3151     printf("    Free:      %lu\n", free);
3152     printf("    Active:    %lu\n", active);
3153     printf("    Inactive:  %lu\n", inactive);
3154
3155     xo_open_container("paging-information");
3156     xo_emit("{P:    }{L:Free:      }{:free/%lu}\n", free);
3157     xo_emit("{P:    }{L:Active:    }{:active/%lu}\n", active);
3158     xo_emit("{P:    }{L:Inactive:  }{:inactive/%lu}\n", inactive);
3159     xo_close_container("paging-information");
3160
3161 *** Converting Error Functions
3162
3163 libxo provides variants of the standard error and warning functions,
3164 err(3) and warn(3).  There are two variants, one for putting the
3165 errors on standard error, and the other writes the errors and warnings
3166 to the handle using the appropriate encoding style:
3167
3168     err(1, "cannot open output file: %s", file);
3169
3170     xo_err(1, "cannot open output file: %s", file);
3171     xo_emit_err(1, "cannot open output file: {:filename}", file);
3172
3173 ** Howto: Use "xo" in Shell Scripts
3174
3175 ** Howto: Internationalization (i18n) @howto-i18n@
3176
3177     How do I use libxo to support internationalization?
3178
3179 libxo allows format and field strings to be used a keys into message
3180 catalogs to enable translation into a user's native language by
3181 invoking the standard gettext(3) functions.
3182
3183 gettext setup is a bit complicated: text strings are extracted from
3184 source files into "portable object template" (.pot) files using the
3185 "xgettext" command.  For each language, this template file is used as
3186 the source for a message catalog in the "portable object" (.po)
3187 format, which are translated by hand and compiled into "machine
3188 object" (.mo) files using the "msgfmt" command.  The .mo files are
3189 then typically installed in the /usr/share/locale or
3190 /opt/local/share/locale directories.  At run time, the user's language
3191 settings are used to select a .mo file which is searched for matching
3192 messages.  Text strings in the source code are used as keys to look up
3193 the native language strings in the .mo file.
3194
3195 Since the xo_emit format string is used as the key into the message
3196 catalog, libxo removes unimportant field formatting and modifiers from
3197 the format string before use so that minor formatting changes will not
3198 impact the expensive translation process.  We don't want a developer
3199 change such as changing "/%06d" to "/%08d" to force hand inspection of
3200 all .po files.  The simplified version can be generated for a single
3201 message using the "xopo -s <text>" command, or an entire .pot can be
3202 translated using the "xopo -f <input> -o <output>" command.
3203
3204     EXAMPLE:
3205         % xopo -s "There are {:count/%u} {:event/%.6s} events\n"
3206         There are {:count} {:event} events\n
3207
3208     Recommended workflow:
3209         # Extract text messages
3210         xgettext --default-domain=foo --no-wrap \
3211             --add-comments --keyword=xo_emit --keyword=xo_emit_h \
3212             --keyword=xo_emit_warn -C -E -n --foreign-user \
3213             -o foo.pot.raw foo.c
3214
3215         # Simplify format strings for libxo
3216         xopo -f foo.pot.raw -o foo.pot
3217
3218         # For a new language, just copy the file
3219         cp foo.pot po/LC/my_lang/foo.po
3220
3221         # For an existing language:
3222         msgmerge --no-wrap po/LC/my_lang/foo.po \
3223                 foo.pot -o po/LC/my_lang/foo.po.new
3224
3225         # Now the hard part: translate foo.po using tools
3226         # like poedit or emacs' po-mode
3227
3228         # Compile the finished file; Use of msgfmt's "-v" option is
3229         # strongly encouraged, so that "fuzzy" entries are reported.
3230         msgfmt -v -o po/my_lang/LC_MESSAGES/foo.mo po/my_lang/foo.po
3231
3232         # Install the .mo file
3233         sudo cp po/my_lang/LC_MESSAGES/foo.mo \
3234                 /opt/local/share/locale/my_lang/LC_MESSAGE/
3235
3236 Once these steps are complete, you can use the "gettext" command to
3237 test the message catalog:
3238
3239     gettext -d foo -e "some text"
3240
3241 *** i18n and xo_emit
3242
3243 There are three features used in libxo used to support i18n:
3244
3245 - The "{G:}" role looks for a translation of the format string.
3246 - The "{g:}" modifier looks for a translation of the field.
3247 - The "{p:}" modifier looks for a pluralized version of the field.
3248
3249 Together these three flags allows a single function call to give
3250 native language support, as well as libxo's normal XML, JSON, and HTML
3251 support.
3252
3253     printf(gettext("Received %zu %s from {g:server} server\n"),
3254            counter, ngettext("byte", "bytes", counter),
3255            gettext("web"));
3256
3257     xo_emit("{G:}Received {:received/%zu} {Ngp:byte,bytes} "
3258             "from {g:server} server\n", counter, "web");
3259
3260 libxo will see the "{G:}" role and will first simplify the format
3261 string, removing field formats and modifiers.
3262
3263     "Received {:received} {N:byte,bytes} from {:server} server\n"
3264
3265 libxo calls gettext(3) with that string to get a localized version.
3266 If your language were Pig Latin, the result might look like:
3267
3268     "Eceivedray {:received} {N:byte,bytes} omfray "
3269                "{:server} erversay\n"
3270
3271 Note the field names do not change and they should not be translated.
3272 The contents of the note ("byte,bytes") should also not be translated,
3273 since the "g" modifier will need the untranslated value as the key for
3274 the message catalog.
3275
3276 The field "{g:server}" requests the rendered value of the field be
3277 translated using gettext(3).  In this example, "web" would be used.
3278
3279 The field "{Ngp:byte,bytes}" shows an example of plural form using the
3280 "p" modifier with the "g" modifier.  The base singular and plural
3281 forms appear inside the field, separated by a comma.  At run time,
3282 libxo uses the previous field's numeric value to decide which form to
3283 use by calling ngettext(3).
3284
3285 If a domain name is needed, it can be supplied as the content of the
3286 {G:} role.  Domain names remain in use throughout the format string
3287 until cleared with another domain name.
3288
3289     printf(dgettext("dns", "Host %s not found: %d(%s)\n"),
3290         name, errno, dgettext("strerror", strerror(errno)));
3291
3292     xo_emit("{G:dns}Host {:hostname} not found: "
3293             "%d({G:strerror}{g:%m})\n", name, errno);
3294
3295 * Examples
3296
3297 ** Unit Test
3298
3299 Here is the unit test example:
3300
3301     int
3302     main (int argc, char **argv)
3303     {
3304         static char base_grocery[] = "GRO";
3305         static char base_hardware[] = "HRD";
3306         struct item {
3307             const char *i_title;
3308             int i_sold;
3309             int i_instock;
3310             int i_onorder;
3311             const char *i_sku_base;
3312             int i_sku_num;
3313         };
3314         struct item list[] = {
3315             { "gum", 1412, 54, 10, base_grocery, 415 },
3316             { "rope", 85, 4, 2, base_hardware, 212 },
3317             { "ladder", 0, 2, 1, base_hardware, 517 },
3318             { "bolt", 4123, 144, 42, base_hardware, 632 },
3319             { "water", 17, 14, 2, base_grocery, 2331 },
3320             { NULL, 0, 0, 0, NULL, 0 }
3321         };
3322         struct item list2[] = {
3323             { "fish", 1321, 45, 1, base_grocery, 533 },
3324         };
3325         struct item *ip;
3326         xo_info_t info[] = {
3327             { "in-stock", "number", "Number of items in stock" },
3328             { "name", "string", "Name of the item" },
3329             { "on-order", "number", "Number of items on order" },
3330             { "sku", "string", "Stock Keeping Unit" },
3331             { "sold", "number", "Number of items sold" },
3332             { NULL, NULL, NULL },
3333         };
3334         int info_count = (sizeof(info) / sizeof(info[0])) - 1;
3335         
3336         argc = xo_parse_args(argc, argv);
3337         if (argc < 0)
3338             exit(EXIT_FAILURE);
3339     
3340         xo_set_info(NULL, info, info_count);
3341     
3342         xo_open_container_h(NULL, "top");
3343     
3344         xo_open_container("data");
3345         xo_open_list("item");
3346     
3347         for (ip = list; ip->i_title; ip++) {
3348             xo_open_instance("item");
3349     
3350             xo_emit("{L:Item} '{k:name/%s}':\n", ip->i_title);
3351             xo_emit("{P:   }{L:Total sold}: {n:sold/%u%s}\n",
3352                     ip->i_sold, ip->i_sold ? ".0" : "");
3353             xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n", 
3354                     ip->i_instock);
3355             xo_emit("{P:   }{Lwc:On order}{:on-order/%u}\n", 
3356                     ip->i_onorder);
3357             xo_emit("{P:   }{L:SKU}: {q:sku/%s-000-%u}\n",
3358                     ip->i_sku_base, ip->i_sku_num);
3359     
3360             xo_close_instance("item");
3361         }
3362     
3363         xo_close_list("item");
3364         xo_close_container("data");
3365     
3366         xo_open_container("data");
3367         xo_open_list("item");
3368     
3369         for (ip = list2; ip->i_title; ip++) {
3370             xo_open_instance("item");
3371     
3372             xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title);
3373             xo_emit("{P:   }{L:Total sold}: {n:sold/%u%s}\n",
3374                     ip->i_sold, ip->i_sold ? ".0" : "");
3375             xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n", 
3376                     ip->i_instock);
3377             xo_emit("{P:   }{Lwc:On order}{:on-order/%u}\n", 
3378                     ip->i_onorder);
3379             xo_emit("{P:   }{L:SKU}: {q:sku/%s-000-%u}\n",
3380                     ip->i_sku_base, ip->i_sku_num);
3381     
3382             xo_close_instance("item");
3383         }
3384     
3385         xo_close_list("item");
3386         xo_close_container("data");
3387     
3388         xo_close_container_h(NULL, "top");
3389     
3390         return 0;
3391     }
3392
3393 Text output:
3394
3395     % ./testxo --libxo text
3396     Item 'gum':
3397        Total sold: 1412.0
3398        In stock: 54
3399        On order: 10
3400        SKU: GRO-000-415
3401     Item 'rope':
3402        Total sold: 85.0
3403        In stock: 4
3404        On order: 2
3405        SKU: HRD-000-212
3406     Item 'ladder':
3407        Total sold: 0
3408        In stock: 2
3409        On order: 1
3410        SKU: HRD-000-517
3411     Item 'bolt':
3412        Total sold: 4123.0
3413        In stock: 144
3414        On order: 42
3415        SKU: HRD-000-632
3416     Item 'water':
3417        Total sold: 17.0
3418        In stock: 14
3419        On order: 2
3420        SKU: GRO-000-2331
3421     Item 'fish':
3422        Total sold: 1321.0
3423        In stock: 45
3424        On order: 1
3425        SKU: GRO-000-533
3426
3427 JSON output:
3428
3429     % ./testxo --libxo json,pretty
3430     "top": {
3431       "data": {
3432         "item": [
3433           {
3434             "name": "gum",
3435             "sold": 1412.0,
3436             "in-stock": 54,
3437             "on-order": 10,
3438             "sku": "GRO-000-415"
3439           },
3440           {
3441             "name": "rope",
3442             "sold": 85.0,
3443             "in-stock": 4,
3444             "on-order": 2,
3445             "sku": "HRD-000-212"
3446           },
3447           {
3448             "name": "ladder",
3449             "sold": 0,
3450             "in-stock": 2,
3451             "on-order": 1,
3452             "sku": "HRD-000-517"
3453           },
3454           {
3455             "name": "bolt",
3456             "sold": 4123.0,
3457             "in-stock": 144,
3458             "on-order": 42,
3459             "sku": "HRD-000-632"
3460           },
3461           {
3462             "name": "water",
3463             "sold": 17.0,
3464             "in-stock": 14,
3465             "on-order": 2,
3466             "sku": "GRO-000-2331"
3467           }
3468         ]
3469       },
3470       "data": {
3471         "item": [
3472           {
3473             "name": "fish",
3474             "sold": 1321.0,
3475             "in-stock": 45,
3476             "on-order": 1,
3477             "sku": "GRO-000-533"
3478           }
3479         ]
3480       }
3481     }
3482
3483 XML output:
3484
3485     % ./testxo --libxo pretty,xml
3486     <top>
3487       <data>
3488         <item>
3489           <name>gum</name>
3490           <sold>1412.0</sold>
3491           <in-stock>54</in-stock>
3492           <on-order>10</on-order>
3493           <sku>GRO-000-415</sku>
3494         </item>
3495         <item>
3496           <name>rope</name>
3497           <sold>85.0</sold>
3498           <in-stock>4</in-stock>
3499           <on-order>2</on-order>
3500           <sku>HRD-000-212</sku>
3501         </item>
3502         <item>
3503           <name>ladder</name>
3504           <sold>0</sold>
3505           <in-stock>2</in-stock>
3506           <on-order>1</on-order>
3507           <sku>HRD-000-517</sku>
3508         </item>
3509         <item>
3510           <name>bolt</name>
3511           <sold>4123.0</sold>
3512           <in-stock>144</in-stock>
3513           <on-order>42</on-order>
3514           <sku>HRD-000-632</sku>
3515         </item>
3516         <item>
3517           <name>water</name>
3518           <sold>17.0</sold>
3519           <in-stock>14</in-stock>
3520           <on-order>2</on-order>
3521           <sku>GRO-000-2331</sku>
3522         </item>
3523       </data>
3524       <data>
3525         <item>
3526           <name>fish</name>
3527           <sold>1321.0</sold>
3528           <in-stock>45</in-stock>
3529           <on-order>1</on-order>
3530           <sku>GRO-000-533</sku>
3531         </item>
3532       </data>
3533     </top>
3534
3535 HMTL output:
3536
3537     % ./testxo --libxo pretty,html
3538     <div class="line">
3539       <div class="label">Item</div>
3540       <div class="text"> '</div>
3541       <div class="data" data-tag="name">gum</div>
3542       <div class="text">':</div>
3543     </div>
3544     <div class="line">
3545       <div class="padding">   </div>
3546       <div class="label">Total sold</div>
3547       <div class="text">: </div>
3548       <div class="data" data-tag="sold">1412.0</div>
3549     </div>
3550     <div class="line">
3551       <div class="padding">   </div>
3552       <div class="label">In stock</div>
3553       <div class="decoration">:</div>
3554       <div class="padding"> </div>
3555       <div class="data" data-tag="in-stock">54</div>
3556     </div>
3557     <div class="line">
3558       <div class="padding">   </div>
3559       <div class="label">On order</div>
3560       <div class="decoration">:</div>
3561       <div class="padding"> </div>
3562       <div class="data" data-tag="on-order">10</div>
3563     </div>
3564     <div class="line">
3565       <div class="padding">   </div>
3566       <div class="label">SKU</div>
3567       <div class="text">: </div>
3568       <div class="data" data-tag="sku">GRO-000-415</div>
3569     </div>
3570     <div class="line">
3571       <div class="label">Item</div>
3572       <div class="text"> '</div>
3573       <div class="data" data-tag="name">rope</div>
3574       <div class="text">':</div>
3575     </div>
3576     <div class="line">
3577       <div class="padding">   </div>
3578       <div class="label">Total sold</div>
3579       <div class="text">: </div>
3580       <div class="data" data-tag="sold">85.0</div>
3581     </div>
3582     <div class="line">
3583       <div class="padding">   </div>
3584       <div class="label">In stock</div>
3585       <div class="decoration">:</div>
3586       <div class="padding"> </div>
3587       <div class="data" data-tag="in-stock">4</div>
3588     </div>
3589     <div class="line">
3590       <div class="padding">   </div>
3591       <div class="label">On order</div>
3592       <div class="decoration">:</div>
3593       <div class="padding"> </div>
3594       <div class="data" data-tag="on-order">2</div>
3595     </div>
3596     <div class="line">
3597       <div class="padding">   </div>
3598       <div class="label">SKU</div>
3599       <div class="text">: </div>
3600       <div class="data" data-tag="sku">HRD-000-212</div>
3601     </div>
3602     <div class="line">
3603       <div class="label">Item</div>
3604       <div class="text"> '</div>
3605       <div class="data" data-tag="name">ladder</div>
3606       <div class="text">':</div>
3607     </div>
3608     <div class="line">
3609       <div class="padding">   </div>
3610       <div class="label">Total sold</div>
3611       <div class="text">: </div>
3612       <div class="data" data-tag="sold">0</div>
3613     </div>
3614     <div class="line">
3615       <div class="padding">   </div>
3616       <div class="label">In stock</div>
3617       <div class="decoration">:</div>
3618       <div class="padding"> </div>
3619       <div class="data" data-tag="in-stock">2</div>
3620     </div>
3621     <div class="line">
3622       <div class="padding">   </div>
3623       <div class="label">On order</div>
3624       <div class="decoration">:</div>
3625       <div class="padding"> </div>
3626       <div class="data" data-tag="on-order">1</div>
3627     </div>
3628     <div class="line">
3629       <div class="padding">   </div>
3630       <div class="label">SKU</div>
3631       <div class="text">: </div>
3632       <div class="data" data-tag="sku">HRD-000-517</div>
3633     </div>
3634     <div class="line">
3635       <div class="label">Item</div>
3636       <div class="text"> '</div>
3637       <div class="data" data-tag="name">bolt</div>
3638       <div class="text">':</div>
3639     </div>
3640     <div class="line">
3641       <div class="padding">   </div>
3642       <div class="label">Total sold</div>
3643       <div class="text">: </div>
3644       <div class="data" data-tag="sold">4123.0</div>
3645     </div>
3646     <div class="line">
3647       <div class="padding">   </div>
3648       <div class="label">In stock</div>
3649       <div class="decoration">:</div>
3650       <div class="padding"> </div>
3651       <div class="data" data-tag="in-stock">144</div>
3652     </div>
3653     <div class="line">
3654       <div class="padding">   </div>
3655       <div class="label">On order</div>
3656       <div class="decoration">:</div>
3657       <div class="padding"> </div>
3658       <div class="data" data-tag="on-order">42</div>
3659     </div>
3660     <div class="line">
3661       <div class="padding">   </div>
3662       <div class="label">SKU</div>
3663       <div class="text">: </div>
3664       <div class="data" data-tag="sku">HRD-000-632</div>
3665     </div>
3666     <div class="line">
3667       <div class="label">Item</div>
3668       <div class="text"> '</div>
3669       <div class="data" data-tag="name">water</div>
3670       <div class="text">':</div>
3671     </div>
3672     <div class="line">
3673       <div class="padding">   </div>
3674       <div class="label">Total sold</div>
3675       <div class="text">: </div>
3676       <div class="data" data-tag="sold">17.0</div>
3677     </div>
3678     <div class="line">
3679       <div class="padding">   </div>
3680       <div class="label">In stock</div>
3681       <div class="decoration">:</div>
3682       <div class="padding"> </div>
3683       <div class="data" data-tag="in-stock">14</div>
3684     </div>
3685     <div class="line">
3686       <div class="padding">   </div>
3687       <div class="label">On order</div>
3688       <div class="decoration">:</div>
3689       <div class="padding"> </div>
3690       <div class="data" data-tag="on-order">2</div>
3691     </div>
3692     <div class="line">
3693       <div class="padding">   </div>
3694       <div class="label">SKU</div>
3695       <div class="text">: </div>
3696       <div class="data" data-tag="sku">GRO-000-2331</div>
3697     </div>
3698     <div class="line">
3699       <div class="label">Item</div>
3700       <div class="text"> '</div>
3701       <div class="data" data-tag="name">fish</div>
3702       <div class="text">':</div>
3703     </div>
3704     <div class="line">
3705       <div class="padding">   </div>
3706       <div class="label">Total sold</div>
3707       <div class="text">: </div>
3708       <div class="data" data-tag="sold">1321.0</div>
3709     </div>
3710     <div class="line">
3711       <div class="padding">   </div>
3712       <div class="label">In stock</div>
3713       <div class="decoration">:</div>
3714       <div class="padding"> </div>
3715       <div class="data" data-tag="in-stock">45</div>
3716     </div>
3717     <div class="line">
3718       <div class="padding">   </div>
3719       <div class="label">On order</div>
3720       <div class="decoration">:</div>
3721       <div class="padding"> </div>
3722       <div class="data" data-tag="on-order">1</div>
3723     </div>
3724     <div class="line">
3725       <div class="padding">   </div>
3726       <div class="label">SKU</div>
3727       <div class="text">: </div>
3728       <div class="data" data-tag="sku">GRO-000-533</div>
3729     </div>
3730
3731 HTML output with xpath and info flags:
3732
3733     % ./testxo --libxo pretty,html,xpath,info
3734     <div class="line">
3735       <div class="label">Item</div>
3736       <div class="text"> '</div>
3737       <div class="data" data-tag="name"
3738            data-xpath="/top/data/item/name" data-type="string"
3739            data-help="Name of the item">gum</div>
3740       <div class="text">':</div>
3741     </div>
3742     <div class="line">
3743       <div class="padding">   </div>
3744       <div class="label">Total sold</div>
3745       <div class="text">: </div>
3746       <div class="data" data-tag="sold"
3747            data-xpath="/top/data/item/sold" data-type="number"
3748            data-help="Number of items sold">1412.0</div>
3749     </div>
3750     <div class="line">
3751       <div class="padding">   </div>
3752       <div class="label">In stock</div>
3753       <div class="decoration">:</div>
3754       <div class="padding"> </div>
3755       <div class="data" data-tag="in-stock"
3756            data-xpath="/top/data/item/in-stock" data-type="number"
3757            data-help="Number of items in stock">54</div>
3758     </div>
3759     <div class="line">
3760       <div class="padding">   </div>
3761       <div class="label">On order</div>
3762       <div class="decoration">:</div>
3763       <div class="padding"> </div>
3764       <div class="data" data-tag="on-order"
3765            data-xpath="/top/data/item/on-order" data-type="number"
3766            data-help="Number of items on order">10</div>
3767     </div>
3768     <div class="line">
3769       <div class="padding">   </div>
3770       <div class="label">SKU</div>
3771       <div class="text">: </div>
3772       <div class="data" data-tag="sku"
3773            data-xpath="/top/data/item/sku" data-type="string"
3774            data-help="Stock Keeping Unit">GRO-000-415</div>
3775     </div>
3776     <div class="line">
3777       <div class="label">Item</div>
3778       <div class="text"> '</div>
3779       <div class="data" data-tag="name"
3780            data-xpath="/top/data/item/name" data-type="string"
3781            data-help="Name of the item">rope</div>
3782       <div class="text">':</div>
3783     </div>
3784     <div class="line">
3785       <div class="padding">   </div>
3786       <div class="label">Total sold</div>
3787       <div class="text">: </div>
3788       <div class="data" data-tag="sold"
3789            data-xpath="/top/data/item/sold" data-type="number"
3790            data-help="Number of items sold">85.0</div>
3791     </div>
3792     <div class="line">
3793       <div class="padding">   </div>
3794       <div class="label">In stock</div>
3795       <div class="decoration">:</div>
3796       <div class="padding"> </div>
3797       <div class="data" data-tag="in-stock"
3798            data-xpath="/top/data/item/in-stock" data-type="number"
3799            data-help="Number of items in stock">4</div>
3800     </div>
3801     <div class="line">
3802       <div class="padding">   </div>
3803       <div class="label">On order</div>
3804       <div class="decoration">:</div>
3805       <div class="padding"> </div>
3806       <div class="data" data-tag="on-order"
3807            data-xpath="/top/data/item/on-order" data-type="number"
3808            data-help="Number of items on order">2</div>
3809     </div>
3810     <div class="line">
3811       <div class="padding">   </div>
3812       <div class="label">SKU</div>
3813       <div class="text">: </div>
3814       <div class="data" data-tag="sku"
3815            data-xpath="/top/data/item/sku" data-type="string"
3816            data-help="Stock Keeping Unit">HRD-000-212</div>
3817     </div>
3818     <div class="line">
3819       <div class="label">Item</div>
3820       <div class="text"> '</div>
3821       <div class="data" data-tag="name"
3822            data-xpath="/top/data/item/name" data-type="string"
3823            data-help="Name of the item">ladder</div>
3824       <div class="text">':</div>
3825     </div>
3826     <div class="line">
3827       <div class="padding">   </div>
3828       <div class="label">Total sold</div>
3829       <div class="text">: </div>
3830       <div class="data" data-tag="sold"
3831            data-xpath="/top/data/item/sold" data-type="number"
3832            data-help="Number of items sold">0</div>
3833     </div>
3834     <div class="line">
3835       <div class="padding">   </div>
3836       <div class="label">In stock</div>
3837       <div class="decoration">:</div>
3838       <div class="padding"> </div>
3839       <div class="data" data-tag="in-stock"
3840            data-xpath="/top/data/item/in-stock" data-type="number"
3841            data-help="Number of items in stock">2</div>
3842     </div>
3843     <div class="line">
3844       <div class="padding">   </div>
3845       <div class="label">On order</div>
3846       <div class="decoration">:</div>
3847       <div class="padding"> </div>
3848       <div class="data" data-tag="on-order"
3849            data-xpath="/top/data/item/on-order" data-type="number"
3850            data-help="Number of items on order">1</div>
3851     </div>
3852     <div class="line">
3853       <div class="padding">   </div>
3854       <div class="label">SKU</div>
3855       <div class="text">: </div>
3856       <div class="data" data-tag="sku"
3857            data-xpath="/top/data/item/sku" data-type="string"
3858            data-help="Stock Keeping Unit">HRD-000-517</div>
3859     </div>
3860     <div class="line">
3861       <div class="label">Item</div>
3862       <div class="text"> '</div>
3863       <div class="data" data-tag="name"
3864            data-xpath="/top/data/item/name" data-type="string"
3865            data-help="Name of the item">bolt</div>
3866       <div class="text">':</div>
3867     </div>
3868     <div class="line">
3869       <div class="padding">   </div>
3870       <div class="label">Total sold</div>
3871       <div class="text">: </div>
3872       <div class="data" data-tag="sold"
3873            data-xpath="/top/data/item/sold" data-type="number"
3874            data-help="Number of items sold">4123.0</div>
3875     </div>
3876     <div class="line">
3877       <div class="padding">   </div>
3878       <div class="label">In stock</div>
3879       <div class="decoration">:</div>
3880       <div class="padding"> </div>
3881       <div class="data" data-tag="in-stock"
3882            data-xpath="/top/data/item/in-stock" data-type="number"
3883            data-help="Number of items in stock">144</div>
3884     </div>
3885     <div class="line">
3886       <div class="padding">   </div>
3887       <div class="label">On order</div>
3888       <div class="decoration">:</div>
3889       <div class="padding"> </div>
3890       <div class="data" data-tag="on-order"
3891            data-xpath="/top/data/item/on-order" data-type="number"
3892            data-help="Number of items on order">42</div>
3893     </div>
3894     <div class="line">
3895       <div class="padding">   </div>
3896       <div class="label">SKU</div>
3897       <div class="text">: </div>
3898       <div class="data" data-tag="sku"
3899            data-xpath="/top/data/item/sku" data-type="string"
3900            data-help="Stock Keeping Unit">HRD-000-632</div>
3901     </div>
3902     <div class="line">
3903       <div class="label">Item</div>
3904       <div class="text"> '</div>
3905       <div class="data" data-tag="name"
3906            data-xpath="/top/data/item/name" data-type="string"
3907            data-help="Name of the item">water</div>
3908       <div class="text">':</div>
3909     </div>
3910     <div class="line">
3911       <div class="padding">   </div>
3912       <div class="label">Total sold</div>
3913       <div class="text">: </div>
3914       <div class="data" data-tag="sold"
3915            data-xpath="/top/data/item/sold" data-type="number"
3916            data-help="Number of items sold">17.0</div>
3917     </div>
3918     <div class="line">
3919       <div class="padding">   </div>
3920       <div class="label">In stock</div>
3921       <div class="decoration">:</div>
3922       <div class="padding"> </div>
3923       <div class="data" data-tag="in-stock"
3924            data-xpath="/top/data/item/in-stock" data-type="number"
3925            data-help="Number of items in stock">14</div>
3926     </div>
3927     <div class="line">
3928       <div class="padding">   </div>
3929       <div class="label">On order</div>
3930       <div class="decoration">:</div>
3931       <div class="padding"> </div>
3932       <div class="data" data-tag="on-order"
3933            data-xpath="/top/data/item/on-order" data-type="number"
3934            data-help="Number of items on order">2</div>
3935     </div>
3936     <div class="line">
3937       <div class="padding">   </div>
3938       <div class="label">SKU</div>
3939       <div class="text">: </div>
3940       <div class="data" data-tag="sku"
3941            data-xpath="/top/data/item/sku" data-type="string"
3942            data-help="Stock Keeping Unit">GRO-000-2331</div>
3943     </div>
3944     <div class="line">
3945       <div class="label">Item</div>
3946       <div class="text"> '</div>
3947       <div class="data" data-tag="name"
3948            data-xpath="/top/data/item/name" data-type="string"
3949            data-help="Name of the item">fish</div>
3950       <div class="text">':</div>
3951     </div>
3952     <div class="line">
3953       <div class="padding">   </div>
3954       <div class="label">Total sold</div>
3955       <div class="text">: </div>
3956       <div class="data" data-tag="sold"
3957            data-xpath="/top/data/item/sold" data-type="number"
3958            data-help="Number of items sold">1321.0</div>
3959     </div>
3960     <div class="line">
3961       <div class="padding">   </div>
3962       <div class="label">In stock</div>
3963       <div class="decoration">:</div>
3964       <div class="padding"> </div>
3965       <div class="data" data-tag="in-stock"
3966            data-xpath="/top/data/item/in-stock" data-type="number"
3967            data-help="Number of items in stock">45</div>
3968     </div>
3969     <div class="line">
3970       <div class="padding">   </div>
3971       <div class="label">On order</div>
3972       <div class="decoration">:</div>
3973       <div class="padding"> </div>
3974       <div class="data" data-tag="on-order"
3975            data-xpath="/top/data/item/on-order" data-type="number"
3976            data-help="Number of items on order">1</div>
3977     </div>
3978     <div class="line">
3979       <div class="padding">   </div>
3980       <div class="label">SKU</div>
3981       <div class="text">: </div>
3982       <div class="data" data-tag="sku"
3983            data-xpath="/top/data/item/sku" data-type="string"
3984            data-help="Stock Keeping Unit">GRO-000-533</div>
3985     </div>
3986
3987 {{document:
3988     name libxo-manual;
3989     private "The libxo Project";
3990     ipr none;
3991     category exp;
3992     abbreviation LIBXO-MANUAL;
3993     title "libxo: The Easy Way to Generate text, XML, JSON, and HTML output";
3994     contributor "author:Phil Shafer:Juniper Networks:phil@juniper.net";
3995 }}