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