]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/libxo/doc/libxo.txt
Import to 0.6.1
[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 thru 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 preceeded 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 preceeded 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 that
990 the minumum 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("Alll 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 | html        | Emit HTML output                                      |
1468 | indent=xx   | Set the indentation level                             |
1469 | info        | Add info attributes (HTML)                            |
1470 | json        | Emit JSON output                                      |
1471 | keys        | Emit the key attribute for keys (XML)                 |
1472 | log-gettext | Log (via stderr) each gettext(3) string lookup        |
1473 | log-syslog  | Log (via stderr) each syslog message (via xo_syslog)  |
1474 | no-humanize | Ignore the {h:} modifier (TEXT, HTML)                 |
1475 | no-locale   | Do not initialize the locale setting                  |
1476 | no-retain   | Prevent retaining formatting information              |
1477 | no-top      | Do not emit a top set of braces (JSON)                |
1478 | not-first   | Pretend the 1st output item was not 1st (JSON)        |
1479 | pretty      | Emit pretty-printed output                            |
1480 | retain      | Force retaining formatting information                |
1481 | text        | Emit TEXT output                                      |
1482 | underscores | Replace XML-friendly "-"s with JSON friendly "_"s e   |
1483 | units       | Add the 'units' (XML) or 'data-units (HTML) attribute |
1484 | warn        | Emit warnings when libxo detects bad calls            |
1485 | warn-xml    | Emit warnings in XML                                  |
1486 | xml         | Emit XML output                                       |
1487 | xpath       | Add XPath expressions (HTML)                          |
1488 |-------------+-------------------------------------------------------|
1489
1490 The brief options are detailed in ^LIBXO_OPTIONS^.
1491
1492 * The libxo API
1493
1494 This section gives details about the functions in libxo, how to call
1495 them, and the actions they perform.
1496
1497 ** Handles @handles@
1498
1499 libxo uses "handles" to control its rendering functionality.  The
1500 handle contains state and buffered data, as well as callback functions
1501 to process data.
1502
1503 Handles give an abstraction for libxo that encapsulates the state of a
1504 stream of output.  Handles have the data type "xo_handle_t" and are
1505 opaque to the caller.
1506
1507 The library has a default handle that is automatically initialized.
1508 By default, this handle will send text style output (XO_STYLE_TEXT) to
1509 standard output.  The xo_set_style and xo_set_flags functions can be
1510 used to change this behavior.
1511
1512 For the typical command that is generating output on standard output,
1513 there is no need to create an explicit handle, but they are available
1514 when needed, e.g., for daemons that generate multiple streams of
1515 output.
1516
1517 Many libxo functions take a handle as their first parameter; most that
1518 do not use the default handle.  Any function taking a handle can be
1519 passed NULL to access the default handle.  For the convenience of
1520 callers, the libxo library includes handle-less functions that
1521 implicitly use the default handle.
1522
1523 For example, the following are equivalent:
1524
1525     xo_emit("test");
1526     xo_emit_h(NULL, "test");
1527
1528 Handles are created using xo_create() and destroy using xo_destroy().
1529
1530 *** xo_create
1531
1532 A handle can be allocated using the xo_create() function:
1533
1534     xo_handle_t *xo_create (unsigned style, unsigned flags);
1535
1536   Example:
1537     xo_handle_t *xop = xo_create(XO_STYLE_JSON, XOF_WARN);
1538     ....
1539     xo_emit_h(xop, "testing\n");
1540
1541 See also ^styles^ and ^flags^.
1542
1543 *** xo_create_to_file
1544
1545 By default, libxo writes output to standard output.  A convenience
1546 function is provided for situations when output should be written to
1547 a different file:
1548
1549     xo_handle_t *xo_create_to_file (FILE *fp, unsigned style,
1550                                     unsigned flags);
1551
1552 Use the XOF_CLOSE_FP flag to trigger a call to fclose() for
1553 the FILE pointer when the handle is destroyed.
1554
1555 *** xo_set_writer
1556
1557 The xo_set_writer function allows custom 'write' functions
1558 which can tailor how libxo writes data.  An opaque argument is
1559 recorded and passed back to the write function, allowing the function
1560 to acquire context information. The 'close' function can
1561 release this opaque data and any other resources as needed.
1562 The flush function can flush buffered data associated with the opaque
1563 object.
1564
1565     void xo_set_writer (xo_handle_t *xop, void *opaque,
1566                         xo_write_func_t write_func,
1567                         xo_close_func_t close_func);
1568                         xo_flush_func_t flush_func);
1569
1570 *** xo_set_style
1571
1572 To set the style, use the xo_set_style() function:
1573
1574     void xo_set_style(xo_handle_t *xop, unsigned style);
1575
1576 To use the default handle, pass a NULL handle:
1577
1578     xo_set_style(NULL, XO_STYLE_XML);
1579
1580 **** Output Styles (XO_STYLE_*) @styles@
1581
1582 The libxo functions accept a set of output styles:
1583
1584 |---------------+-------------------------|
1585 | Flag          | Description             |
1586 |---------------+-------------------------|
1587 | XO_STYLE_TEXT | Traditional text output |
1588 | XO_STYLE_XML  | XML encoded data        |
1589 | XO_STYLE_JSON | JSON encoded data       |
1590 | XO_STYLE_HTML | HTML encoded data       |
1591 |---------------+-------------------------|
1592
1593 **** xo_set_style_name
1594
1595 The xo_set_style_name() can be used to set the style based on a name
1596 encoded as a string:
1597
1598     int xo_set_style_name (xo_handle_t *xop, const char *style);
1599
1600 The name can be any of the styles: "text", "xml", "json", or "html".
1601
1602     EXAMPLE:
1603         xo_set_style_name(NULL, "html");
1604
1605 *** xo_set_flags
1606
1607 To set the flags, use the xo_set_flags() function:
1608
1609     void xo_set_flags(xo_handle_t *xop, unsigned flags);
1610
1611 To use the default handle, pass a NULL handle:
1612
1613     xo_set_style(NULL, XO_STYLE_XML);
1614
1615 **** Flags (XOF_*) @flags@
1616
1617 The set of valid flags include:
1618
1619 |-------------------+----------------------------------------|
1620 | Flag              | Description                            |
1621 |-------------------+----------------------------------------|
1622 | XOF_CLOSE_FP      | Close file pointer on xo_destroy()     |
1623 | XOF_COLOR         | Enable color and effects in output     |
1624 | XOF_COLOR_ALLOWED | Allow color/effect for terminal output |
1625 | XOF_DTRT          | Enable "do the right thing" mode       |
1626 | XOF_INFO          | Display info data attributes (HTML)    |
1627 | XOF_KEYS          | Emit the key attribute (XML)           |
1628 | XOF_NO_ENV        | Do not use the LIBXO_OPTIONS env var   |
1629 | XOF_NO_HUMANIZE   | Display humanization (TEXT, HTML)      |
1630 | XOF_PRETTY        | Make 'pretty printed' output           |
1631 | XOF_UNDERSCORES   | Replaces hyphens with underscores      |
1632 | XOF_UNITS         | Display units (XML, HMTL)              |
1633 | XOF_WARN          | Generate warnings for broken calls     |
1634 | XOF_WARN_XML      | Generate warnings in XML on stdout     |
1635 | XOF_XPATH         | Emit XPath expressions (HTML)          |
1636 | XOF_COLUMNS       | Force xo_emit to return columns used   |
1637 | XOF_FLUSH         | Flush output after each xo_emit call   |
1638 |-------------------+----------------------------------------|
1639
1640 The XOF_CLOSE_FP flag will trigger the call of the close_func
1641 (provided via xo_set_writer()) when the handle is destroyed.
1642
1643 The XOF_COLOR flag enables color and effects in output regardless of
1644 output device, while the XOF_COLOR_ALLOWED flag allows color and
1645 effects only if the output device is a terminal.
1646
1647 The XOF_PRETTY flag requests 'pretty printing', which will trigger the
1648 addition of indentation and newlines to enhance the readability of
1649 XML, JSON, and HTML output.  Text output is not affected.
1650
1651 The XOF_WARN flag requests that warnings will trigger diagnostic
1652 output (on standard error) when the library notices errors during
1653 operations, or with arguments to functions.  Without warnings enabled,
1654 such conditions are ignored.
1655
1656 Warnings allow developers to debug their interaction with libxo.
1657 The function "xo_failure" can used as a breakpoint for a debugger,
1658 regardless of whether warnings are enabled.
1659
1660 If the style is XO_STYLE_HTML, the following additional flags can be
1661 used:
1662
1663 |---------------+-----------------------------------------|
1664 | Flag          | Description                             |
1665 |---------------+-----------------------------------------|
1666 | XOF_XPATH     | Emit "data-xpath" attributes            |
1667 | XOF_INFO      | Emit additional info fields             |
1668 |---------------+-----------------------------------------|
1669
1670 The XOF_XPATH flag enables the emission of XPath expressions detailing
1671 the hierarchy of XML elements used to encode the data field, if the
1672 XPATH style of output were requested.
1673
1674 The XOF_INFO flag encodes additional informational fields for HTML
1675 output.  See ^info^ for details.
1676
1677 If the style is XO_STYLE_XML, the following additional flags can be
1678 used:
1679
1680 |---------------+-----------------------------------------|
1681 | Flag          | Description                             |
1682 |---------------+-----------------------------------------|
1683 | XOF_KEYS      | Flag 'key' fields for xml               |
1684 |---------------+-----------------------------------------|
1685
1686 The XOF_KEYS flag adds 'key' attribute to the XML encoding for
1687 field definitions that use the 'k' modifier.  The key attribute has
1688 the value "key":
1689
1690     xo_emit("{k:name}", item);
1691
1692   XML:
1693       <name key="key">truck</name>
1694
1695 **** xo_clear_flags
1696
1697 The xo_clear_flags() function turns off the given flags in a specific
1698 handle. 
1699
1700     void xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags);
1701
1702 **** xo_set_options
1703
1704 The xo_set_options() function accepts a comma-separated list of styles
1705 and flags and enables them for a specific handle.
1706
1707     int xo_set_options (xo_handle_t *xop, const char *input);
1708
1709 The options are identical to those listed in ^command-line-arguments^.
1710
1711 *** xo_destroy
1712
1713 The xo_destroy function releases a handle and any resources it is
1714 using.  Calling xo_destroy with a NULL handle will release any
1715 resources associated with the default handle.
1716
1717     void xo_destroy(xo_handle_t *xop);
1718
1719 ** Emitting Content (xo_emit)
1720
1721 The following functions are used to emit output:
1722
1723     int xo_emit (const char *fmt, ...);
1724     int xo_emit_h (xo_handle_t *xop, const char *fmt, ...);
1725     int xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap);
1726
1727 The "fmt" argument is a string containing field descriptors as
1728 specified in ^format-strings^.  The use of a handle is optional and
1729 NULL can be passed to access the internal 'default' handle.  See
1730 ^handles^.
1731
1732 The remaining arguments to xo_emit() and xo_emit_h() are a set of
1733 arguments corresponding to the fields in the format string.  Care must
1734 be taken to ensure the argument types match the fields in the format
1735 string, since an inappropriate cast can ruin your day.  The vap
1736 argument to xo_emit_hv() points to a variable argument list that can
1737 be used to retrieve arguments via va_arg().
1738
1739 *** Single Field Emitting Functions (xo_emit_field) @xo_emit_field@
1740
1741 The following functions can also make output, but only make a single
1742 field at a time:
1743
1744     int xo_emit_field_hv (xo_handle_t *xop, const char *rolmod,
1745                   const char *contents, const char *fmt, 
1746                   const char *efmt, va_list vap);
1747
1748     int xo_emit_field_h (xo_handle_t *xop, const char *rolmod, 
1749                  const char *contents, const char *fmt,
1750                  const char *efmt, ...);
1751
1752     int xo_emit_field (const char *rolmod, const char *contents,
1753                  const char *fmt, const char *efmt, ...);
1754
1755 These functions are intended to avoid the scenario where one
1756 would otherwise need to compose a format descriptors using
1757 snprintf().  The individual parts of the format descriptor are
1758 passed in distinctly.
1759
1760     xo_emit("T", "Host name is ", NULL, NULL);
1761     xo_emit("V", "host-name", NULL, NULL, host-name);
1762
1763 *** Attributes (xo_attr) @xo_attr@
1764
1765 The xo_attr() function emits attributes for the XML output style.
1766
1767     int xo_attr (const char *name, const char *fmt, ...);
1768     int xo_attr_h (xo_handle_t *xop, const char *name, 
1769                    const char *fmt, ...);
1770     int xo_attr_hv (xo_handle_t *xop, const char *name, 
1771                    const char *fmt, va_list vap);
1772
1773 The name parameter give the name of the attribute to be encoded.  The
1774 fmt parameter gives a printf-style format string used to format the
1775 value of the attribute using any remaining arguments, or the vap
1776 parameter passed to xo_attr_hv().
1777
1778     EXAMPLE:
1779       xo_attr("seconds", "%ld", (unsigned long) login_time);
1780       struct tm *tmp = localtime(login_time);
1781       strftime(buf, sizeof(buf), "%R", tmp);
1782       xo_emit("Logged in at {:login-time}\n", buf);
1783     XML:
1784         <login-time seconds="1408336270">00:14</login-time>
1785
1786 xo_attr is placed on the next container, instance, leaf, or leaf list
1787 that is emitted.
1788
1789 Since attributes are only emitted in XML, their use should be limited
1790 to meta-data and additional or redundant representations of data
1791 already emitted in other form.
1792
1793 *** Flushing Output (xo_flush)
1794
1795 libxo buffers data, both for performance and consistency, but also to
1796 allow some advanced features to work properly.  At various times, the
1797 caller may wish to flush any data buffered within the library.  The
1798 xo_flush() call is used for this:
1799
1800     void xo_flush (void);
1801     void xo_flush_h (xo_handle_t *xop);
1802
1803 Calling xo_flush also triggers the flush function associated with the
1804 handle.  For the default handle, this is equivalent to
1805 "fflush(stdio);". 
1806
1807 *** Finishing Output (xo_finish)
1808
1809 When the program is ready to exit or close a handle, a call to
1810 xo_finish() is required.  This flushes any buffered data, closes
1811 open libxo constructs, and completes any pending operations.
1812
1813     int xo_finish (void);
1814     int xo_finish_h (xo_handle_t *xop);
1815     void xo_finish_atexit (void);
1816
1817 Calling this function is vital to the proper operation of libxo,
1818 especially for the non-TEXT output styles.
1819
1820 xo_finish_atexit is suitable for use with atexit(3).
1821
1822 ** Emitting Hierarchy
1823
1824 libxo represents to types of hierarchy: containers and lists.  A
1825 container appears once under a given parent where a list contains
1826 instances that can appear multiple times.  A container is used to hold
1827 related fields and to give the data organization and scope.
1828
1829 To create a container, use the xo_open_container and
1830 xo_close_container functions:
1831
1832     int xo_open_container (const char *name);
1833     int xo_open_container_h (xo_handle_t *xop, const char *name);
1834     int xo_open_container_hd (xo_handle_t *xop, const char *name);
1835     int xo_open_container_d (const char *name);
1836
1837     int xo_close_container (const char *name);
1838     int xo_close_container_h (xo_handle_t *xop, const char *name);
1839     int xo_close_container_hd (xo_handle_t *xop);
1840     int xo_close_container_d (void);
1841
1842 The name parameter gives the name of the container, encoded in UTF-8.
1843 Since ASCII is a proper subset of UTF-8, traditional C strings can be
1844 used directly.
1845
1846 The close functions with the "_d" suffix are used in "Do The Right
1847 Thing" mode, where the name of the open containers, lists, and
1848 instances are maintained internally by libxo to allow the caller to
1849 avoid keeping track of the open container name.
1850
1851 Use the XOF_WARN flag to generate a warning if the name given on the
1852 close does not match the current open container.
1853
1854 For TEXT and HTML output, containers are not rendered into output
1855 text, though for HTML they are used when the XOF_XPATH flag is set.
1856
1857     EXAMPLE:
1858        xo_open_container("system");
1859        xo_emit("The host name is {:host-name}\n", hn);
1860        xo_close_container("system");
1861     XML:
1862        <system><host-name>foo</host-name></system>
1863
1864 *** Lists and Instances
1865
1866 Lists are sequences of instances of homogeneous data objects.  Two
1867 distinct levels of calls are needed to represent them in our output
1868 styles.  Calls must be made to open and close a list, and for each
1869 instance of data in that list, calls must be make to open and close
1870 that instance.
1871
1872 The name given to all calls must be identical, and it is strongly
1873 suggested that the name be singular, not plural, as a matter of
1874 style and usage expectations.
1875
1876     EXAMPLE:
1877         xo_open_list("user");
1878         for (i = 0; i < num_users; i++) {
1879             xo_open_instance("user");
1880             xo_emit("{k:name}:{:uid/%u}:{:gid/%u}:{:home}\n",
1881                     pw[i].pw_name, pw[i].pw_uid,
1882                     pw[i].pw_gid, pw[i].pw_dir);
1883             xo_close_instance("user");
1884         }
1885         xo_close_list("user");
1886     TEXT:
1887         phil:1001:1001:/home/phil
1888         pallavi:1002:1002:/home/pallavi
1889     XML:
1890         <user>
1891             <name>phil</name>
1892             <uid>1001</uid>
1893             <gid>1001</gid>
1894             <home>/home/phil</home>
1895         </user>
1896         <user>
1897             <name>pallavi</name>
1898             <uid>1002</uid>
1899             <gid>1002</gid>
1900             <home>/home/pallavi</home>
1901         </user>
1902     JSON:
1903         user: [
1904             {
1905                 "name": "phil",
1906                 "uid": 1001,
1907                 "gid": 1001,
1908                 "home": "/home/phil",
1909             },
1910             {
1911                 "name": "pallavi",
1912                 "uid": 1002,
1913                 "gid": 1002,
1914                 "home": "/home/pallavi",
1915             }
1916         ]
1917
1918 ** Support Functions
1919
1920 *** Parsing Command-line Arguments (xo_parse_args) @xo_parse_args@
1921
1922 The xo_parse_args() function is used to process a program's
1923 arguments.  libxo-specific options are processed and removed
1924 from the argument list so the calling application does not
1925 need to process them.  If successful, a new value for argc
1926 is returned.  On failure, a message it emitted and -1 is returned.
1927
1928     argc = xo_parse_args(argc, argv);
1929     if (argc < 0)
1930         exit(EXIT_FAILURE);
1931
1932 Following the call to xo_parse_args, the application can process the
1933 remaining arguments in a normal manner.  See ^command-line-arguments^
1934 for a description of valid arguments.
1935
1936 *** xo_set_program
1937
1938 The xo_set_program function sets name of the program as reported by
1939 functions like xo_failure, xo_warn, xo_err, etc.  The program name is
1940 initialized by xo_parse_args, but subsequent calls to xo_set_program
1941 can override this value.
1942
1943     xo_set_program(argv[0]);
1944
1945 Note that the value is not copied, so the memory passed to
1946 xo_set_program (and xo_parse_args) must be maintained by the caller.
1947
1948 *** xo_set_version
1949
1950 The xo_set_version function records a version number to be emitted as
1951 part of the data for encoding styles (XML and JSON).  This version
1952 number is suitable for tracking changes in the content, allowing a
1953 user of the data to discern which version of the data model is in use.
1954
1955      void xo_set_version (const char *version);
1956      void xo_set_version_h (xo_handle_t *xop, const char *version);
1957
1958 *** Field Information (xo_info_t) @info@
1959
1960 HTML data can include additional information in attributes that
1961 begin with "data-".  To enable this, three things must occur:
1962
1963 First the application must build an array of xo_info_t structures,
1964 one per tag.  The array must be sorted by name, since libxo uses a
1965 binary search to find the entry that matches names from format
1966 instructions.
1967
1968 Second, the application must inform libxo about this information using
1969 the xo_set_info() call:
1970
1971     typedef struct xo_info_s {
1972         const char *xi_name;    /* Name of the element */
1973         const char *xi_type;    /* Type of field */
1974         const char *xi_help;    /* Description of field */
1975     } xo_info_t;
1976
1977     void xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count);
1978
1979 Like other libxo calls, passing NULL for the handle tells libxo to use
1980 the default handle.
1981
1982 If the count is -1, libxo will count the elements of infop, but there
1983 must be an empty element at the end.  More typically, the number is
1984 known to the application:
1985
1986     xo_info_t info[] = {
1987         { "in-stock", "number", "Number of items in stock" },
1988         { "name", "string", "Name of the item" },
1989         { "on-order", "number", "Number of items on order" },
1990         { "sku", "string", "Stock Keeping Unit" },
1991         { "sold", "number", "Number of items sold" },
1992     };
1993     int info_count = (sizeof(info) / sizeof(info[0]));
1994     ...
1995     xo_set_info(NULL, info, info_count);
1996
1997 Third, the emission of info must be triggered with the XOF_INFO flag
1998 using either the xo_set_flags() function or the "--libxo=info" command
1999 line argument.
2000
2001 The type and help values, if present, are emitted as the "data-type"
2002 and "data-help" attributes:
2003
2004   <div class="data" data-tag="sku" data-type="string" 
2005        data-help="Stock Keeping Unit">GRO-000-533</div>
2006
2007 *** Memory Allocation
2008
2009 The xo_set_allocator function allows libxo to be used in environments
2010 where the standard realloc() and free() functions are not available.
2011
2012     void xo_set_allocator (xo_realloc_func_t realloc_func,
2013                            xo_free_func_t free_func);
2014
2015 realloc_func should expect the same arguments as realloc(3) and return
2016 a pointer to memory following the same convention.  free_func will
2017 receive the same argument as free(3) and should release it, as
2018 appropriate for the environment.
2019
2020 By default, the standard realloc() and free() functions are used.
2021
2022 *** LIBXO_OPTIONS @LIBXO_OPTIONS@
2023
2024 The environment variable "LIBXO_OPTIONS" can be set to a string of
2025 options:
2026
2027 |--------+---------------------------------------------|
2028 | Option | Action                                      |
2029 |--------+---------------------------------------------|
2030 | c      | Enable color/effects for TEXT/HTML          |
2031 | F      | Force line-buffered flushing                |
2032 | H      | Enable HTML output (XO_STYLE_HTML)          |
2033 | I      | Enable info output (XOF_INFO)               |
2034 | i<num> | Indent by <number>                          |
2035 | J      | Enable JSON output (XO_STYLE_JSON)          |
2036 | k      | Add keys to XPATH expressions in HTML       |
2037 | n      | Disable humanization (TEXT, HTML)           |
2038 | P      | Enable pretty-printed output (XOF_PRETTY)   |
2039 | T      | Enable text output (XO_STYLE_TEXT)          |
2040 | U      | Add units to HTML output                    |
2041 | u      | Change "-"s to "_"s in element names (JSON) |
2042 | W      | Enable warnings (XOF_WARN)                  |
2043 | X      | Enable XML output (XO_STYLE_XML)            |
2044 | x      | Enable XPath data (XOF_XPATH)               |
2045 |--------+---------------------------------------------|
2046
2047 For example, warnings can be enabled by:
2048
2049     % env LIBXO_OPTIONS=W my-app
2050
2051 Complete HTML output can be generated with:
2052
2053     % env LIBXO_OPTIONS=HXI my-app
2054
2055 Since environment variables are inherited, child processes will have
2056 the same options, which may be undesirable, making the use of the
2057 "--libxo" option is preferable in most situations.
2058
2059 *** Errors, Warnings, and Messages
2060
2061 Many programs make use of the standard library functions err() and
2062 warn() to generate errors and warnings for the user.  libxo wants to
2063 pass that information via the current output style, and provides
2064 compatible functions to allow this:
2065
2066     void xo_warn (const char *fmt, ...);
2067     void xo_warnx (const char *fmt, ...);
2068     void xo_warn_c (int code, const char *fmt, ...);
2069     void xo_warn_hc (xo_handle_t *xop, int code,
2070                      const char *fmt, ...);
2071     void xo_err (int eval, const char *fmt, ...);
2072     void xo_errc (int eval, int code, const char *fmt, ...);
2073     void xo_errx (int eval, const char *fmt, ...);
2074     void xo_message (const char *fmt, ...);
2075     void xo_message_c (int code, const char *fmt, ...);
2076     void xo_message_hc (xo_handle_t *xop, int code,
2077                         const char *fmt, ...);
2078     void xo_message_hcv (xo_handle_t *xop, int code, 
2079                          const char *fmt, va_list vap);
2080
2081 These functions display the program name, a colon, a formatted message
2082 based on the arguments, and then optionally a colon and an error
2083 message associated with either "errno" or the "code" parameter.
2084
2085     EXAMPLE:
2086         if (open(filename, O_RDONLY) < 0)
2087             xo_err(1, "cannot open file '%s'", filename);
2088
2089 *** xo_error
2090
2091 The xo_error function can be used for generic errors that should be
2092 reported over the handle, rather than to stderr.  The xo_error
2093 function behaves like xo_err for TEXT and HTML output styles, but puts
2094 the error into XML or JSON elements:
2095
2096     EXAMPLE::
2097         xo_error("Does not %s", "compute");
2098     XML::
2099         <error><message>Does not compute</message></error>
2100     JSON::
2101         "error": { "message": "Does not compute" }
2102
2103 *** xo_no_setlocale
2104
2105 libxo automatically initializes the locale based on setting of the
2106 environment variables LC_CTYPE, LANG, and LC_ALL.  The first of this
2107 list of variables is used and if none of the variables, the locale
2108 defaults to "UTF-8".  The caller may wish to avoid this behavior, and
2109 can do so by calling the xo_no_setlocale() function.
2110
2111     void xo_no_setlocale (void);
2112
2113 ** Emitting syslog Messages
2114
2115 syslog is the system logging facility used throughout the unix world.
2116 Messages are sent from commands, applications, and daemons to a
2117 hierarchy of servers, where they are filtered, saved, and forwarded
2118 based on configuration behaviors.
2119
2120 syslog is an older protocol, originally documented only in source
2121 code.  By the time RFC 3164 published, variation and mutation left the
2122 leading "<pri>" string as only common content.  RFC 5424 defines a new
2123 version (version 1) of syslog and introduces structured data into the
2124 messages.  Structured data is a set of name/value pairs transmitted
2125 distinctly alongside the traditional text message, allowing filtering
2126 on precise values instead of regular expressions.
2127
2128 These name/value pairs are scoped by a two-part identifier; an
2129 enterprise identifier names the party responsible for the message
2130 catalog and a name identifying that message.  Enterprise IDs are
2131 defined by IANA, the Internet Assigned Numbers Authority:
2132
2133 https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
2134
2135 Use the ^xo_set_syslog_enterprise_id^() function to set the Enterprise
2136 ID, as needed.
2137
2138 The message name should follow the conventions in ^good-field-names^,
2139 as should the fields within the message.
2140
2141     /* Both of these calls are optional */
2142     xo_set_syslog_enterprise_id(32473);
2143     xo_open_log("my-program", 0, LOG_DAEMON);
2144
2145     /* Generate a syslog message */
2146     xo_syslog(LOG_ERR, "upload-failed",
2147               "error <%d> uploading file '{:filename}' "
2148               "as '{:target/%s:%s}'",
2149               code, filename, protocol, remote);
2150
2151     xo_syslog(LOG_INFO, "poofd-invalid-state",
2152               "state {:current/%u} is invalid {:connection/%u}",
2153               state, conn);
2154
2155 The developer should be aware that the message name may be used in the
2156 future to allow access to further information, including
2157 documentation.  Care should be taken to choose quality, descriptive
2158 names.
2159
2160 *** Priority, Facility, and Flags @priority@
2161
2162 The xo_syslog, xo_vsyslog, and xo_open_log functions accept a set of
2163 flags which provide the priority of the message, the source facility,
2164 and some additional features.  These values are OR'd together to
2165 create a single integer argument:
2166
2167     xo_syslog(LOG_ERR | LOG_AUTH, "login-failed",
2168              "Login failed; user '{:user}' from host '{:address}'",
2169              user, addr);
2170
2171 These values are defined in <syslog.h>.
2172
2173 The priority value indicates the importance and potential impact of
2174 each message.
2175
2176 |-------------+-------------------------------------------------------|
2177 | Priority    | Description                                           |
2178 |-------------+-------------------------------------------------------|
2179 | LOG_EMERG   | A panic condition, normally broadcast to all users    |
2180 | LOG_ALERT   | A condition that should be corrected immediately      |
2181 | LOG_CRIT    | Critical conditions                                   |
2182 | LOG_ERR     | Generic errors                                        |
2183 | LOG_WARNING | Warning messages                                      |
2184 | LOG_NOTICE  | Non-error conditions that might need special handling |
2185 | LOG_INFO    | Informational messages                                |
2186 | LOG_DEBUG   | Developer-oriented messages                           |
2187 |-------------+-------------------------------------------------------|
2188
2189 The facility value indicates the source of message, in fairly generic
2190 terms. 
2191
2192 |---------------+-------------------------------------------------|
2193 | Facility      | Description                                     |
2194 |---------------+-------------------------------------------------|
2195 | LOG_AUTH      | The authorization system (e.g. login(1))        |
2196 | LOG_AUTHPRIV  | As LOG_AUTH, but logged to a privileged file    |
2197 | LOG_CRON      | The cron daemon: cron(8)                        |
2198 | LOG_DAEMON    | System daemons, not otherwise explicitly listed |
2199 | LOG_FTP       | The file transfer protocol daemons              |
2200 | LOG_KERN      | Messages generated by the kernel                |
2201 | LOG_LPR       | The line printer spooling system                |
2202 | LOG_MAIL      | The mail system                                 |
2203 | LOG_NEWS      | The network news system                         |
2204 | LOG_SECURITY  | Security subsystems, such as ipfw(4)            |
2205 | LOG_SYSLOG    | Messages generated internally by syslogd(8)     |
2206 | LOG_USER      | Messages generated by user processes (default)  |
2207 | LOG_UUCP      | The uucp system                                 |
2208 | LOG_LOCAL0..7 | Reserved for local use                          |
2209 |---------------+-------------------------------------------------|
2210
2211 In addition to the values listed above, xo_open_log accepts a set of
2212 addition flags requesting specific behaviors.
2213
2214 |------------+----------------------------------------------------|
2215 | Flag       | Description                                        |
2216 |------------+----------------------------------------------------|
2217 | LOG_CONS   | If syslogd fails, attempt to write to /dev/console |
2218 | LOG_NDELAY | Open the connection to syslogd(8) immediately      |
2219 | LOG_PERROR | Write the message also to standard error output    |
2220 | LOG_PID    | Log the process id with each message               |
2221 |------------+----------------------------------------------------|
2222
2223 *** xo_syslog
2224
2225 Use the xo_syslog function to generate syslog messages by calling it
2226 with a log priority and facility, a message name, a format string, and
2227 a set of arguments.  The priority/facility argument are discussed
2228 above, as is the message name.
2229
2230 The format string follows the same conventions as xo_emit's format
2231 string, with each field being rendered as an SD-PARAM pair.
2232
2233     xo_syslog(LOG_ERR, "poofd-missing-file",
2234               "'{:filename}' not found: {:error/%m}", filename);
2235
2236     ... [poofd-missing-file@32473 filename="/etc/poofd.conf"
2237           error="Permission denied"] '/etc/poofd.conf' not
2238           found: Permission denied
2239
2240 *** Support functions
2241
2242 **** xo_vsyslog
2243
2244 xo_vsyslog is identical in function to xo_syslog, but takes the set of
2245 arguments using a va_list.
2246
2247     void my_log (const char *name, const char *fmt, ...)
2248     {
2249         va_list vap;
2250         va_start(vap, fmt);
2251         xo_vsyslog(LOG_ERR, name, fmt, vap);
2252         va_end(vap);
2253     }
2254
2255 **** xo_open_log
2256
2257 xo_open_log functions similar to openlog(3), allowing customization of
2258 the program name, the log facility number, and the additional option
2259 flags described in ^priority^.
2260
2261     void
2262     xo_open_log (const char *ident, int logopt, int facility);
2263
2264 **** xo_close_log
2265
2266 xo_close_log functions similar to closelog(3), closing the log file
2267 and releasing any associated resources.
2268
2269     void
2270     xo_close_log (void);
2271
2272 **** xo_set_logmask
2273
2274 xo_set_logmask function similar to setlogmask(3), restricting the set
2275 of generated log event to those whose associated bit is set in
2276 maskpri.  Use LOG_MASK(pri) to find the appropriate bit, or
2277 LOG_UPTO(toppri) to create a mask for all priorities up to and
2278 including toppri.
2279
2280     int
2281     xo_set_logmask (int maskpri);
2282
2283   Example:
2284     setlogmask(LOG_UPTO(LOG_WARN));
2285
2286 **** xo_set_syslog_enterprise_id
2287
2288 Use the xo_set_syslog_enterprise_id to supply a platform- or
2289 application-specific enterprise id.  This value is used in any
2290 future syslog messages.
2291
2292 Ideally, the operating system should supply a default value via the
2293 "kern.syslog.enterprise_id" sysctl value.  Lacking that, the
2294 application should provide a suitable value.
2295
2296     void
2297     xo_set_syslog_enterprise_id (unsigned short eid);
2298
2299 Enterprise IDs are administered by IANA, the Internet Assigned Number
2300 Authority.  The complete list is EIDs on their web site:
2301
2302     https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
2303
2304 New EIDs can be requested from IANA using the following page:
2305
2306     http://pen.iana.org/pen/PenApplication.page
2307
2308 Each software development organization that defines a set of syslog
2309 messages should register their own EID and use that value in their
2310 software to ensure that messages can be uniquely identified by the
2311 combination of EID + message name.
2312
2313 ** Creating Custom Encoders
2314
2315 The number of encoding schemes in current use is staggering, with new
2316 and distinct schemes appearing daily.  While libxo provide XML, JSON,
2317 HMTL, and text natively, there are requirements for other encodings.
2318
2319 Rather than bake support for all possible encoders into libxo, the API
2320 allows them to be defined externally.  libxo can then interfaces with
2321 these encoding modules using a simplistic API.  libxo processes all
2322 functions calls, handles state transitions, performs all formatting,
2323 and then passes the results as operations to a customized encoding
2324 function, which implements specific encoding logic as required.  This
2325 means your encoder doesn't need to detect errors with unbalanced
2326 open/close operations but can rely on libxo to pass correct data.
2327
2328 By making a simple API, libxo internals are not exposed, insulating the
2329 encoder and the library from future or internal changes.
2330
2331 The three elements of the API are:
2332 - loading
2333 - initialization
2334 - operations
2335
2336 The following sections provide details about these topics.
2337
2338 libxo source contain an encoder for Concise Binary Object
2339 Representation, aka CBOR (RFC 7049) which can be used as used as an
2340 example for the API.
2341
2342 *** Loading Encoders
2343
2344 Encoders can be registered statically or discovered dynamically.
2345 Applications can choose to call the xo_encoder_register()
2346 function to explicitly register encoders, but more typically they are
2347 built as shared libraries, placed in the libxo/extensions directory,
2348 and loaded based on name.  libxo looks for a file with the name of the encoder
2349 and an extension of ".enc".  This can be a file or a symlink to the
2350 shared library file that supports the encoder.
2351
2352     % ls -1 lib/libxo/extensions/*.enc
2353     lib/libxo/extensions/cbor.enc
2354     lib/libxo/extensions/test.enc
2355
2356 *** Encoder Initialization
2357
2358 Each encoder must export a symbol used to access the library, which
2359 must have the following signature:
2360
2361     int xo_encoder_library_init (XO_ENCODER_INIT_ARGS);
2362
2363 XO_ENCODER_INIT_ARGS is a macro defined in xo_encoder.h that defines
2364 an argument called "arg", a pointer of the type
2365 xo_encoder_init_args_t.  This structure contains two fields:
2366
2367 - xei_version is the version number of the API as implemented within
2368 libxo.  This version is currently as 1 using XO_ENCODER_VERSION.  This
2369 number can be checked to ensure compatibility.  The working assumption
2370 is that all versions should be backward compatible, but each side may
2371 need to accurately know the version supported by the other side.  
2372 xo_encoder_library_init can optionally check this value, and must then
2373 set it to the version number used by the encoder, allowing libxo to
2374 detect version differences and react accordingly.  For example, if
2375 version 2 adds new operations, then libxo will know that an encoding
2376 library that set xei_version to 1 cannot be expected to handle those
2377 new operations.
2378
2379 - xei_handler must be set to a pointer to a function of type
2380 xo_encoder_func_t, as defined in xo_encoder.h.  This function
2381 takes a set of parameters:
2382 -- xop is a pointer to the opaque xo_handle_t structure
2383 -- op is an integer representing the current operation
2384 -- name is a string whose meaning differs by operation
2385 -- value is a string whose meaning differs by operation
2386 -- private is an opaque structure provided by the encoder
2387
2388 Additional arguments may be added in the future, so handler functions
2389 should use the XO_ENCODER_HANDLER_ARGS macro.  An appropriate
2390 "extern" declaration is provided to help catch errors.
2391
2392 Once the encoder initialization function has completed processing, it
2393 should return zero to indicate that no error has occurred.  A non-zero
2394 return code will cause the handle initialization to fail.
2395
2396 *** Operations
2397
2398 The encoder API defines a set of operations representing the
2399 processing model of libxo.  Content is formatted within libxo, and
2400 callbacks are made to the encoder's handler function when data is
2401 ready to be processed.
2402
2403 |-----------------------+---------------------------------------|
2404 | Operation             | Meaning  (Base function)              |
2405 |-----------------------+---------------------------------------|
2406 | XO_OP_CREATE          | Called when the handle is created     |
2407 | XO_OP_OPEN_CONTAINER  | Container opened (xo_open_container)  |
2408 | XO_OP_CLOSE_CONTAINER | Container closed (xo_close_container) |
2409 | XO_OP_OPEN_LIST       | List opened (xo_open_list)            |
2410 | XO_OP_CLOSE_LIST      | List closed (xo_close_list)           |
2411 | XO_OP_OPEN_LEAF_LIST  | Leaf list opened (xo_open_leaf_list)  |
2412 | XO_OP_CLOSE_LEAF_LIST | Leaf list closed (xo_close_leaf_list) |
2413 | XO_OP_OPEN_INSTANCE   | Instance opened (xo_open_instance)    |
2414 | XO_OP_CLOSE_INSTANCE  | Instance closed (xo_close_instance)   |
2415 | XO_OP_STRING          | Field with Quoted UTF-8 string        |
2416 | XO_OP_CONTENT         | Field with content                    |
2417 | XO_OP_FINISH          | Finish any pending output             |
2418 | XO_OP_FLUSH           | Flush any buffered output             |
2419 | XO_OP_DESTROY         | Clean up resources                    |
2420 | XO_OP_ATTRIBUTE       | An attribute name/value pair          |
2421 | XO_OP_VERSION         | A version string                      |
2422 |-----------------------+---------------------------------------|
2423
2424 For all the open and close operations, the name parameter holds the
2425 name of the construct.  For string, content, and attribute operations,
2426 the name parameter is the name of the field and the value parameter is
2427 the value.  "string" are differentiated from "content" to allow differing
2428 treatment of true, false, null, and numbers from real strings, though
2429 content values are formatted as strings before the handler is called.
2430 For version operations, the value parameter contains the version.
2431
2432 All strings are encoded in UTF-8.
2433
2434 * The "xo" Utility
2435
2436 The "xo" utility allows command line access to the functionality of
2437 the libxo library.  Using "xo", shell scripts can emit XML, JSON, and
2438 HTML using the same commands that emit text output.
2439
2440 The style of output can be selected using a specific option: "-X" for
2441 XML, "-J" for JSON, "-H" for HTML, or "-T" for TEXT, which is the
2442 default.  The "--style <style>" option can also be used.  The
2443 LIBXO_OPTIONS environment variable can also be used to set the style,
2444 as well as other flags.
2445
2446 The "xo" utility accepts a format string suitable for xo_emit() and a
2447 set of zero or more arguments used to supply data for that string.
2448
2449     xo "The {k:name} weighs {:weight/%d} pounds.\n" fish 6
2450
2451   TEXT:
2452     The fish weighs 6 pounds.
2453   XML:
2454     <name>fish</name>
2455     <weight>6</weight>
2456   JSON:
2457     "name": "fish",
2458     "weight": 6
2459   HTML:
2460     <div class="line">
2461       <div class="text">The </div>
2462       <div class="data" data-tag="name">fish</div>
2463       <div class="text"> weighs </div>
2464       <div class="data" data-tag="weight">6</div>
2465       <div class="text"> pounds.</div>
2466     </div>
2467
2468 The "--wrap <path>" option can be used to wrap emitted content in a
2469 specific hierarchy.  The path is a set of hierarchical names separated
2470 by the '/' character.
2471
2472     xo --wrap top/a/b/c '{:tag}' value
2473
2474   XML:
2475     <top>
2476       <a>
2477         <b>
2478           <c>
2479             <tag>value</tag>
2480           </c>
2481         </b>
2482       </a>
2483     </top>
2484   JSON:
2485     "top": {
2486       "a": {
2487         "b": {
2488           "c": {
2489             "tag": "value"
2490           }
2491         }
2492       }
2493     }
2494
2495 The "--open <path>" and "--close <path>" can be used to emit
2496 hierarchical information without the matching close and open
2497 tag.  This allows a shell script to emit open tags, data, and
2498 then close tags.  The "--depth" option may be used to set the
2499 depth for indentation.  The "--leading-xpath" may be used to
2500 prepend data to the XPath values used for HTML output style.
2501
2502     #!/bin/sh
2503     xo --open top/data
2504     xo --depth 2 '{tag}' value
2505     xo --close top/data
2506   XML:
2507     <top>
2508       <data>
2509         <tag>value</tag>
2510       </data>
2511     </top>
2512   JSON:
2513     "top": {
2514       "data": {
2515         "tag": "value"
2516       }
2517     }
2518
2519 ** Command Line Options
2520
2521 Usage: xo [options] format [fields]
2522   --close <path>        Close tags for the given path
2523   --depth <num>         Set the depth for pretty printing
2524   --help                Display this help text
2525   --html OR -H          Generate HTML output
2526   --json OR -J          Generate JSON output
2527   --leading-xpath <path> Add a prefix to generated XPaths (HTML)
2528   --open <path>         Open tags for the given path
2529   --pretty OR -p        Make 'pretty' output (add indent, newlines)
2530   --style <style>       Generate given style (xml, json, text, html)
2531   --text OR -T          Generate text output (the default style)
2532   --version             Display version information
2533   --warn OR -W          Display warnings in text on stderr
2534   --warn-xml            Display warnings in xml on stdout
2535   --wrap <path>         Wrap output in a set of containers
2536   --xml OR -X           Generate XML output
2537   --xpath               Add XPath data to HTML output);
2538
2539 ** Example
2540
2541   % xo 'The {:product} is {:status}\n' stereo "in route"
2542   The stereo is in route
2543   % ./xo/xo -p -X 'The {:product} is {:status}\n' stereo "in route"
2544   <product>stereo</product>
2545   <status>in route</status>
2546
2547 * xolint
2548
2549 xolint is a tool for reporting common mistakes in format strings
2550 in source code that invokes xo_emit().  It allows these errors
2551 to be diagnosed at build time, rather than waiting until runtime.
2552
2553 xolint takes the one or more C files as arguments, and reports
2554 and errors, warning, or informational messages as needed.
2555
2556 |------------+---------------------------------------------------|
2557 | Option     | Meaning                                           |
2558 |------------+---------------------------------------------------|
2559 | -c         | Invoke 'cpp' against the input file               |
2560 | -C <flags> | Flags that are passed to 'cpp                     |
2561 | -d         | Enable debug output                               |
2562 | -D         | Generate documentation for all xolint messages    |
2563 | -I         | Generate info table code                          |
2564 | -p         | Print the offending lines after the message       |
2565 | -V         | Print vocabulary of all field names               |
2566 | -X         | Extract samples from xolint, suitable for testing |
2567 |------------+---------------------------------------------------|
2568
2569 The output message will contain the source filename and line number, the
2570 class of the message, the message, and, if -p is given, the
2571 line that contains the error:
2572
2573     % xolint.pl -t xolint.c
2574     xolint.c: 16: error: anchor format should be "%d"
2575     16         xo_emit("{[:/%s}");
2576
2577 The "-I" option will generate a table of xo_info_t structures , 
2578
2579 The "-V" option does not report errors, but prints a complete list of
2580 all field names, sorted alphabetically.  The output can help spot
2581 inconsistencies and spelling errors.
2582
2583 * xohtml @xohtml@
2584
2585 xohtml is a tool for turning the output of libxo-enabled commands into
2586 html files suitable for display in modern HTML web browsers.  It can
2587 be used to test and debug HTML output, as well as to make the user
2588 ache to escape the world of 70s terminal devices.
2589
2590 xohtml is given a command, either on the command line or via the "-c"
2591 option.  If not command is given, standard input is used.  The
2592 command's output is wrapped in HTML tags, with references to
2593 supporting CSS and Javascript files, and written to standard output or
2594 the file given in the "-f" option.  The "-b" option can be used to
2595 provide an alternative base path for the support files.
2596
2597 |--------------+---------------------------------------------------|
2598 | Option       | Meaning                                           |
2599 |--------------+---------------------------------------------------|
2600 | -b <base>    | Base path for finding css/javascript files        |
2601 | -c <command> | Command to execute                                |
2602 | -f <file>    | Output file name                                  |
2603 |--------------+---------------------------------------------------|
2604
2605 The "-c" option takes a full command with arguments, including
2606 any libxo options needed to generate html ("--libxo=html").  This
2607 value must be quoted if it consists of multiple tokens.
2608
2609 * xopo
2610
2611 The "xopo" utility filters ".pot" files generated by the "xgettext"
2612 utility to remove formatting information suitable for use with
2613 the "{G:}" modifier.  This means that when the developer changes the
2614 formatting portion of the field definitions, or the fields modifiers,
2615 the string passed to gettext(3) is unchanged, avoiding the expense of
2616 updating any existing translation files (".po" files).
2617
2618 The syntax for the xopo command is one of two forms; it can be used as
2619 a filter for processing a .po or .pot file, rewriting the "msgid"
2620 strings with a simplified message string.  In this mode, the input is
2621 either standard input or a file given by the "-f" option, and the
2622 output is either standard output or a file given by the "-o" option.
2623
2624 In the second mode, a simple message given using the "-s" option on
2625 the command, and the simplified version of that message is printed on
2626 stdout.
2627
2628 |-----------+---------------------------------|
2629 | Option    | Meaning                         |
2630 |-----------+---------------------------------|
2631 | -o <file> | Output file name                |
2632 | -f <file> | Use the given .po file as input |
2633 | -s <text> | Simplify a format string        |
2634 |-----------+---------------------------------|
2635
2636     EXAMPLE:
2637         % xopo -s "There are {:count/%u} {:event/%.6s} events\n"
2638         There are {:count} {:event} events\n
2639
2640         % xgettext --default-domain=foo --no-wrap \
2641             --add-comments --keyword=xo_emit --keyword=xo_emit_h \
2642             --keyword=xo_emit_warn -C -E -n --foreign-user \
2643             -o foo.pot.raw foo.c
2644         % xopo -f foo.pot.raw -o foo.pot
2645
2646 Use of the "--no-wrap" option for xgettext is required to ensure that
2647 incoming msgid strings are not wrapped across multiple lines.
2648
2649 * FAQs
2650
2651 This section contains the set of questions that users typically ask,
2652 along with answers that might be helpful.
2653
2654 !! list-sections
2655
2656 ** General
2657
2658 *** Can you share the history of libxo?
2659
2660 In 2001, we added an XML API to the JUNOS operating system, which is
2661 built on top of FreeBSD.  Eventually this API became standardized as
2662 the NETCONF API (RFC 6241).  As part of this effort, we modified many
2663 FreeBSD utilities to emit XML, typically via a "-X" switch.  The
2664 results were mixed.  The cost of maintaining this code, updating it,
2665 and carrying it were non-trivial, and contributed to our expense (and
2666 the associated delay) with upgrading the version of FreeBSD on which
2667 each release of JUNOS is based.
2668
2669 A recent (2014) effort within JUNOS aims at removing our modifications
2670 to the underlying FreeBSD code as a means of reducing the expense and
2671 delay in tracking HEAD.  JUNOS is structured to have system components
2672 generate XML that is rendered by the CLI (think: login shell) into
2673 human-readable text.  This allows the API to use the same plumbing as
2674 the CLI, and ensures that all components emit XML, and that it is
2675 emitted with knowledge of the consumer of that XML, yielding an API
2676 that have no incremental cost or feature delay.
2677
2678 libxo is an effort to mix the best aspects of the JUNOS strategy into
2679 FreeBSD in a seemless way, allowing commands to make printf-like
2680 output calls with a single code path.
2681
2682 *** Did the complex semantics of format strings evolve over time?
2683
2684 The history is both long and short: libxo's functionality is based
2685 on what JUNOS does in a data modeling language called ODL (output
2686 definition language).  In JUNOS, all subcomponents generate XML,
2687 which is feed to the CLI, where data from the ODL files tell is
2688 how to render that XML into text.  ODL might had a set of tags
2689 like:
2690
2691      tag docsis-state {
2692          help "State of the DOCSIS interface";
2693          type string;
2694      }
2695
2696      tag docsis-mode {
2697          help "DOCSIS mode (2.0/3.0) of the DOCSIS interface";
2698          type string;
2699      }
2700
2701      tag docsis-upstream-speed {
2702          help "Operational upstream speed of the interface";
2703          type string;
2704      }
2705
2706      tag downstream-scanning {
2707          help "Result of scanning in downstream direction";
2708          type string;
2709      }
2710
2711      tag ranging {
2712          help "Result of ranging action";
2713          type string;
2714      }
2715
2716      tag signal-to-noise-ratio {
2717          help "Signal to noise ratio for all channels";
2718          type string;
2719      }
2720
2721      tag power {
2722          help "Operational power of the signal on all channels";
2723          type string;
2724      }
2725
2726      format docsis-status-format {
2727          picture "
2728    State   : @, Mode: @, Upstream speed: @
2729    Downstream scanning: @, Ranging: @
2730    Signal to noise ratio: @
2731    Power: @
2732 ";
2733          line {
2734              field docsis-state;
2735              field docsis-mode;
2736              field docsis-upstream-speed;
2737              field downstream-scanning;
2738              field ranging;
2739              field signal-to-noise-ratio;
2740              field power;
2741          }
2742      }
2743
2744 These tag definitions are compiled into field definitions
2745 that are triggered when matching XML elements are seen.  ODL
2746 also supports other means of defining output.
2747
2748 The roles and modifiers describe these details.
2749
2750 In moving these ideas to bsd, two things had to happen: the
2751 formatting had to happen at the source since BSD won't have
2752 a JUNOS-like CLI to do the rendering, and we can't depend on
2753 external data models like ODL, which was seen as too hard a
2754 sell to the BSD community.
2755
2756 The results were that the xo_emit strings are used to encode the
2757 roles, modifiers, names, and formats.  They are dense and a bit
2758 cryptic, but not so unlike printf format strings that developers will
2759 be lost.
2760
2761 libxo is a new implementation of these ideas and is distinct from
2762 the previous implementation in JUNOS.
2763
2764 *** What makes a good field name? @good-field-names@
2765
2766 To make useful, consistent field names, follow these guidelines:
2767
2768 = Use lower case, even for TLAs
2769 Lower case is more civilized.  Even TLAs should be lower case
2770 to avoid scenarios where the differences between "XPath" and
2771 "Xpath" drive your users crazy.  Using "xpath" is simpler and better.
2772 = Use hyphens, not underscores
2773 Use of hyphens is traditional in XML, and the XOF_UNDERSCORES
2774 flag can be used to generate underscores in JSON, if desired.
2775 But the raw field name should use hyphens.
2776 = Use full words
2777 Don't abbreviate especially when the abbreviation is not obvious or
2778 not widely used.  Use "data-size", not "dsz" or "dsize".  Use
2779 "interface" instead of "ifname", "if-name", "iface", "if", or "intf".
2780 = Use <verb>-<units>
2781 Using the form <verb>-<units> or <verb>-<classifier>-<units> helps in
2782 making consistent, useful names, avoiding the situation where one app
2783 uses "sent-packet" and another "packets-sent" and another
2784 "packets-we-have-sent".  The <units> can be dropped when it is
2785 obvious, as can obvious words in the classification.
2786 Use "receive-after-window-packets" instead of
2787 "received-packets-of-data-after-window".
2788 = Reuse existing field names
2789 Nothing's worse than writing expressions like:
2790
2791     if ($src1/process[pid == $pid]/name == 
2792         $src2/proc-table/proc-list
2793                    /proc-entry[process-id == $pid]/proc-name) {
2794         ...
2795     }
2796
2797 Find someone else who is expressing similar data and follow their
2798 fields and hierarchy.  Remember the quote is not "Consistency is the
2799 hobgoblin of little minds", but "A foolish consistency is the
2800 hobgoblin of little minds".
2801 = Use containment as scoping
2802 In the previous example, all the names are prefixed with "proc-",
2803 which is redundant given that they are nested under the process table.
2804 = Think about your users
2805 Have empathy for your users, choosing clear and useful fields that
2806 contain clear and useful data.  You may need to augment the display
2807 content with xo_attr() calls (^xo_attr^) or "{e:}" fields
2808 (^e-modifier^) to make the data useful.
2809 = Don't use an arbitrary number postfix
2810 What does "errors2" mean?  No one will know.  "errors-after-restart"
2811 would be a better choice.  Think of your users, and think of the
2812 future.  If you make "errors2", the next guy will happily make
2813 "errors3" and before you know it, someone will be asking what's the
2814 difference between errors37 and errors63.
2815 = Be consistent, uniform, unsurprising, and predictable
2816 Think of your field vocabulary as an API.  You want it useful,
2817 expressive, meaningful, direct, and obvious.  You want the client
2818 application's programmer to move between without the need to
2819 understand a variety of opinions on how fields are named.  They should
2820 see the system as a single cohesive whole, not a sack of cats.
2821
2822 Field names constitute the means by which client programmers interact
2823 with our system.  By choosing wise names now, you are making their
2824 lives better.
2825
2826 After using "xolint" to find errors in your field descriptors, use
2827 "xolint -V" to spell check your field names and to detect different
2828 names for the same data.  "dropped-short" and "dropped-too-short" are
2829 both reasonable names, but using them both will lead users to ask the
2830 difference between the two fields.  If there is no difference,
2831 use only one of the field names.  If there is a difference, change the
2832 names to make that difference more obvious.
2833
2834 ** What does this message mean?
2835
2836 !!include-file xolint.txt
2837
2838 * Howtos: Focused Directions
2839
2840 This section provides task-oriented instructions for selected tasks.
2841 If you have a task that needs instructions, please open a request as
2842 an enhancement issue on github.
2843
2844 ** Howto: Report bugs
2845
2846 libxo uses github to track bugs or request enhancements.  Please use
2847 the following URL:
2848
2849   https://github.com/Juniper/libxo/issues
2850
2851 ** Howto: Install libxo
2852
2853 libxo is open source, under a new BSD license.  Source code is
2854 available on github, as are recent releases.  To get the most
2855 current release, please visit:
2856
2857   https://github.com/Juniper/libxo/releases
2858
2859 After downloading and untarring the source code, building involves the
2860 following steps:
2861
2862     sh bin/setup.sh
2863     cd build
2864     ../configure
2865     make
2866     make test
2867     sudo make install
2868
2869 libxo uses a distinct "build" directory to keep generated files
2870 separated from source files.
2871
2872 Use "../configure --help" to display available configuration options,
2873 which include the following:
2874
2875   --enable-warnings      Turn on compiler warnings
2876   --enable-debug         Turn on debugging
2877   --enable-text-only     Turn on text-only rendering
2878   --enable-printflike    Enable use of GCC __printflike attribute
2879   --disable-libxo-options  Turn off support for LIBXO_OPTIONS
2880   --with-gettext=PFX     Specify location of gettext installation
2881   --with-libslax-prefix=PFX  Specify location of libslax config
2882
2883 Compiler warnings are a very good thing, but recent compiler version
2884 have added some very pedantic checks.  While every attempt is made to
2885 keep libxo code warning-free, warnings are now optional.  If you are
2886 doing development work on libxo, it is required that you use
2887 --enable-warnings to keep the code warning free, but most users need
2888 not use this option.
2889
2890 libxo provides the --enable-text-only option to reduce the footprint
2891 of the library for smaller installations.  XML, JSON, and HTML
2892 rendering logic is removed.
2893
2894 The gettext library does not provide a simple means of learning its
2895 location, but libxo will look for it in /usr and /opt/local.  If
2896 installed elsewhere, the installer will need to provide this
2897 information using the --with-gettext=/dir/path option.
2898
2899 libslax is not required by libxo; it contains the "oxtradoc" program
2900 used to format documentation.
2901
2902 For additional information, see ^building-libxo^.
2903
2904 ** Howto: Convert command line applications
2905
2906     How do I convert an existing command line application?
2907
2908 There are three basic steps for converting command line application to
2909 use libxo.
2910
2911 - Setting up the context
2912 - Converting printf calls
2913 - Creating hierarchy
2914 - Converting error functions
2915
2916 *** Setting up the context
2917
2918 To use libxo, you'll need to include the "xo.h" header file in your
2919 source code files:
2920
2921     #include <libxo/xo.h>
2922
2923 In your main() function, you'll need to call xo_parse_args to handling
2924 argument parsing (^xo_parse_args^).  This function removes
2925 libxo-specific arguments the program's argv and returns either the
2926 number of remaining arguments or -1 to indicate an error.
2927
2928     int main (int argc, char **argv)
2929     {
2930         argc = xo_parse_args(argc, argv);
2931         if (argc < 0)
2932             return argc;
2933         ....
2934     }
2935
2936 At the bottom of your main(), you'll need to call xo_finish() to
2937 complete output processing for the default handle (^handles^).  libxo
2938 provides the xo_finish_atexit function that is suitable for use with
2939 the atexit(3) function.
2940
2941     atexit(xo_finish_atexit);
2942
2943 *** Converting printf Calls
2944
2945 The second task is inspecting code for printf(3) calls and replacing
2946 them with xo_emit() calls.  The format strings are similar in task,
2947 but libxo format strings wrap output fields in braces.  The following
2948 two calls produce identical text output:
2949
2950     printf("There are %d %s events\n", count, etype);
2951     xo_emit("There are {:count/%d} {:event} events\n", count, etype);
2952
2953 "count" and "event" are used as names for JSON and XML output.  The
2954 "count" field uses the format "%d" and "event" uses the default "%s"
2955 format.  Both are "value" roles, which is the default role.
2956
2957 Since text outside of output fields is passed verbatim, other roles
2958 are less important, but their proper use can help make output more
2959 useful.  The "note" and "label" roles allow HTML output to recognize
2960 the relationship between text and the associated values, allowing
2961 appropriate "hover" and "onclick" behavior.  Using the "units" role
2962 allows the presentation layer to perform conversions when needed.  The
2963 "warning" and "error" roles allows use of color and font to draw
2964 attention to warnings.  The "padding" role makes the use of vital
2965 whitespace more clear (^padding-role^).
2966
2967 The "title" role indicates the headings of table and sections.  This
2968 allows HTML output to use CSS to make this relationship more obvious.
2969
2970     printf("Statistics:\n");
2971     xo_emit("{T:Statistics}:\n");
2972
2973 The "color" roles controls foreground and background colors, as well
2974 as effects like bold and underline (see ^color-role^).
2975
2976     xo_emit("{C:bold}required{C:}\n");
2977
2978 Finally, the start- and stop-anchor roles allow justification and
2979 padding over multiple fields (see ^anchor-role^).
2980
2981     snprintf(buf, sizeof(buf), "(%u/%u/%u)", min, ave, max);
2982     printf("%30s", buf);
2983    
2984     xo_emit("{[:30}({:minimum/%u}/{:average/%u}/{:maximum/%u}{]:}",
2985             min, ave, max);
2986
2987 *** Creating Hierarchy
2988
2989 Text output doesn't have any sort of hierarchy, but XML and JSON
2990 require this.  Typically applications use indentation to represent
2991 these relationship:
2992
2993     printf("table %d\n", tnum);
2994     for (i = 0; i < tmax; i++) {
2995         printf("    %s %d\n", table[i].name, table[i].size);
2996     }
2997
2998     xo_emit("{T:/table %d}\n", tnum);
2999     xo_open_list("table");
3000     for (i = 0; i < tmax; i++) {
3001         xo_open_instance("table");
3002         xo_emit("{P:    }{k:name} {:size/%d}\n",
3003                 table[i].name, table[i].size);
3004         xo_close_instance("table");
3005     }
3006     xo_close_list("table");
3007
3008 The open and close list functions are used before and after the list,
3009 and the open and close instance functions are used before and after
3010 each instance with in the list.
3011
3012 Typically these developer looks for a "for" loop as an indication of
3013 where to put these calls.
3014
3015 In addition, the open and close container functions allow for
3016 organization levels of hierarchy.
3017
3018     printf("Paging information:\n");
3019     printf("    Free:      %lu\n", free);
3020     printf("    Active:    %lu\n", active);
3021     printf("    Inactive:  %lu\n", inactive);
3022
3023     xo_open_container("paging-information");
3024     xo_emit("{P:    }{L:Free:      }{:free/%lu}\n", free);
3025     xo_emit("{P:    }{L:Active:    }{:active/%lu}\n", active);
3026     xo_emit("{P:    }{L:Inactive:  }{:inactive/%lu}\n", inactive);
3027     xo_close_container("paging-information");
3028
3029 *** Converting Error Functions
3030
3031 libxo provides variants of the standard error and warning functions,
3032 err(3) and warn(3).  There are two variants, one for putting the
3033 errors on standard error, and the other writes the errors and warnings
3034 to the handle using the appropriate encoding style:
3035
3036     err(1, "cannot open output file: %s", file);
3037
3038     xo_err(1, "cannot open output file: %s", file);
3039     xo_emit_err(1, "cannot open output file: {:filename}", file);
3040
3041 ** Howto: Use "xo" in Shell Scripts
3042
3043 ** Howto: Internationalization (i18n) @howto-i18n@
3044
3045     How do I use libxo to support internationalization?
3046
3047 libxo allows format and field strings to be used a keys into message
3048 catalogs to enable translation into a user's native language by
3049 invoking the standard gettext(3) functions.
3050
3051 gettext setup is a bit complicated: text strings are extracted from
3052 source files into "portable object template" (.pot) files using the
3053 "xgettext" command.  For each language, this template file is used as
3054 the source for a message catalog in the "portable object" (.po)
3055 format, which are translated by hand and compiled into "machine
3056 object" (.mo) files using the "msgfmt" command.  The .mo files are
3057 then typically installed in the /usr/share/locale or
3058 /opt/local/share/locale directories.  At run time, the user's language
3059 settings are used to select a .mo file which is searched for matching
3060 messages.  Text strings in the source code are used as keys to look up
3061 the native language strings in the .mo file.
3062
3063 Since the xo_emit format string is used as the key into the message
3064 catalog, libxo removes unimportant field formatting and modifiers from
3065 the format string before use so that minor formatting changes will not
3066 impact the expensive translation process.  We don't want a developer
3067 change such as changing "/%06d" to "/%08d" to force hand inspection of
3068 all .po files.  The simplified version can be generated for a single
3069 message using the "xopo -s <text>" command, or an entire .pot can be
3070 translated using the "xopo -f <input> -o <output>" command.
3071
3072     EXAMPLE:
3073         % xopo -s "There are {:count/%u} {:event/%.6s} events\n"
3074         There are {:count} {:event} events\n
3075
3076     Recommended workflow:
3077         # Extract text messages
3078         xgettext --default-domain=foo --no-wrap \
3079             --add-comments --keyword=xo_emit --keyword=xo_emit_h \
3080             --keyword=xo_emit_warn -C -E -n --foreign-user \
3081             -o foo.pot.raw foo.c
3082
3083         # Simplify format strings for libxo
3084         xopo -f foo.pot.raw -o foo.pot
3085
3086         # For a new language, just copy the file
3087         cp foo.pot po/LC/my_lang/foo.po
3088
3089         # For an existing language:
3090         msgmerge --no-wrap po/LC/my_lang/foo.po \
3091                 foo.pot -o po/LC/my_lang/foo.po.new
3092
3093         # Now the hard part: translate foo.po using tools
3094         # like poedit or emacs' po-mode
3095
3096         # Compile the finished file; Use of msgfmt's "-v" option is
3097         # strongly encouraged, so that "fuzzy" entries are reported.
3098         msgfmt -v -o po/my_lang/LC_MESSAGES/foo.mo po/my_lang/foo.po
3099
3100         # Install the .mo file
3101         sudo cp po/my_lang/LC_MESSAGES/foo.mo \
3102                 /opt/local/share/locale/my_lang/LC_MESSAGE/
3103
3104 Once these steps are complete, you can use the "gettext" command to
3105 test the message catalog:
3106
3107     gettext -d foo -e "some text"
3108
3109 *** i18n and xo_emit
3110
3111 There are three features used in libxo used to support i18n:
3112
3113 - The "{G:}" role looks for a translation of the format string.
3114 - The "{g:}" modifier looks for a translation of the field.
3115 - The "{p:}" modifier looks for a pluralized version of the field.
3116
3117 Together these three flags allows a single function call to give
3118 native language support, as well as libxo's normal XML, JSON, and HTML
3119 support.
3120
3121     printf(gettext("Received %zu %s from {g:server} server\n"),
3122            counter, ngettext("byte", "bytes", counter),
3123            gettext("web"));
3124
3125     xo_emit("{G:}Received {:received/%zu} {Ngp:byte,bytes} "
3126             "from {g:server} server\n", counter, "web");
3127
3128 libxo will see the "{G:}" role and will first simplify the format
3129 string, removing field formats and modifiers.
3130
3131     "Received {:received} {N:byte,bytes} from {:server} server\n"
3132
3133 libxo calls gettext(3) with that string to get a localized version.
3134 If your language were Pig Latin, the result might look like:
3135
3136     "Eceivedray {:received} {N:byte,bytes} omfray "
3137                "{:server} erversay\n"
3138
3139 Note the field names do not change and they should not be translated.
3140 The contents of the note ("byte,bytes") should also not be translated,
3141 since the "g" modifier will need the untranslated value as the key for
3142 the message catalog.
3143
3144 The field "{g:server}" requests the rendered value of the field be
3145 translated using gettext(3).  In this example, "web" would be used.
3146
3147 The field "{Ngp:byte,bytes}" shows an example of plural form using the
3148 "p" modifier with the "g" modifier.  The base singular and plural
3149 forms appear inside the field, separated by a comma.  At run time,
3150 libxo uses the previous field's numeric value to decide which form to
3151 use by calling ngettext(3).
3152
3153 If a domain name is needed, it can be supplied as the content of the
3154 {G:} role.  Domain names remain in use throughout the format string
3155 until cleared with another domain name.
3156
3157     printf(dgettext("dns", "Host %s not found: %d(%s)\n"),
3158         name, errno, dgettext("strerror", strerror(errno)));
3159
3160     xo_emit("{G:dns}Host {:hostname} not found: "
3161             "%d({G:strerror}{g:%m})\n", name, errno);
3162
3163 * Examples
3164
3165 ** Unit Test
3166
3167 Here is the unit test example:
3168
3169     int
3170     main (int argc, char **argv)
3171     {
3172         static char base_grocery[] = "GRO";
3173         static char base_hardware[] = "HRD";
3174         struct item {
3175             const char *i_title;
3176             int i_sold;
3177             int i_instock;
3178             int i_onorder;
3179             const char *i_sku_base;
3180             int i_sku_num;
3181         };
3182         struct item list[] = {
3183             { "gum", 1412, 54, 10, base_grocery, 415 },
3184             { "rope", 85, 4, 2, base_hardware, 212 },
3185             { "ladder", 0, 2, 1, base_hardware, 517 },
3186             { "bolt", 4123, 144, 42, base_hardware, 632 },
3187             { "water", 17, 14, 2, base_grocery, 2331 },
3188             { NULL, 0, 0, 0, NULL, 0 }
3189         };
3190         struct item list2[] = {
3191             { "fish", 1321, 45, 1, base_grocery, 533 },
3192         };
3193         struct item *ip;
3194         xo_info_t info[] = {
3195             { "in-stock", "number", "Number of items in stock" },
3196             { "name", "string", "Name of the item" },
3197             { "on-order", "number", "Number of items on order" },
3198             { "sku", "string", "Stock Keeping Unit" },
3199             { "sold", "number", "Number of items sold" },
3200             { NULL, NULL, NULL },
3201         };
3202         int info_count = (sizeof(info) / sizeof(info[0])) - 1;
3203         
3204         argc = xo_parse_args(argc, argv);
3205         if (argc < 0)
3206             exit(EXIT_FAILURE);
3207     
3208         xo_set_info(NULL, info, info_count);
3209     
3210         xo_open_container_h(NULL, "top");
3211     
3212         xo_open_container("data");
3213         xo_open_list("item");
3214     
3215         for (ip = list; ip->i_title; ip++) {
3216             xo_open_instance("item");
3217     
3218             xo_emit("{L:Item} '{k:name/%s}':\n", ip->i_title);
3219             xo_emit("{P:   }{L:Total sold}: {n:sold/%u%s}\n",
3220                     ip->i_sold, ip->i_sold ? ".0" : "");
3221             xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n", 
3222                     ip->i_instock);
3223             xo_emit("{P:   }{Lwc:On order}{:on-order/%u}\n", 
3224                     ip->i_onorder);
3225             xo_emit("{P:   }{L:SKU}: {q:sku/%s-000-%u}\n",
3226                     ip->i_sku_base, ip->i_sku_num);
3227     
3228             xo_close_instance("item");
3229         }
3230     
3231         xo_close_list("item");
3232         xo_close_container("data");
3233     
3234         xo_open_container("data");
3235         xo_open_list("item");
3236     
3237         for (ip = list2; ip->i_title; ip++) {
3238             xo_open_instance("item");
3239     
3240             xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title);
3241             xo_emit("{P:   }{L:Total sold}: {n:sold/%u%s}\n",
3242                     ip->i_sold, ip->i_sold ? ".0" : "");
3243             xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n", 
3244                     ip->i_instock);
3245             xo_emit("{P:   }{Lwc:On order}{:on-order/%u}\n", 
3246                     ip->i_onorder);
3247             xo_emit("{P:   }{L:SKU}: {q:sku/%s-000-%u}\n",
3248                     ip->i_sku_base, ip->i_sku_num);
3249     
3250             xo_close_instance("item");
3251         }
3252     
3253         xo_close_list("item");
3254         xo_close_container("data");
3255     
3256         xo_close_container_h(NULL, "top");
3257     
3258         return 0;
3259     }
3260
3261 Text output:
3262
3263     % ./testxo --libxo text
3264     Item 'gum':
3265        Total sold: 1412.0
3266        In stock: 54
3267        On order: 10
3268        SKU: GRO-000-415
3269     Item 'rope':
3270        Total sold: 85.0
3271        In stock: 4
3272        On order: 2
3273        SKU: HRD-000-212
3274     Item 'ladder':
3275        Total sold: 0
3276        In stock: 2
3277        On order: 1
3278        SKU: HRD-000-517
3279     Item 'bolt':
3280        Total sold: 4123.0
3281        In stock: 144
3282        On order: 42
3283        SKU: HRD-000-632
3284     Item 'water':
3285        Total sold: 17.0
3286        In stock: 14
3287        On order: 2
3288        SKU: GRO-000-2331
3289     Item 'fish':
3290        Total sold: 1321.0
3291        In stock: 45
3292        On order: 1
3293        SKU: GRO-000-533
3294
3295 JSON output:
3296
3297     % ./testxo --libxo json,pretty
3298     "top": {
3299       "data": {
3300         "item": [
3301           {
3302             "name": "gum",
3303             "sold": 1412.0,
3304             "in-stock": 54,
3305             "on-order": 10,
3306             "sku": "GRO-000-415"
3307           },
3308           {
3309             "name": "rope",
3310             "sold": 85.0,
3311             "in-stock": 4,
3312             "on-order": 2,
3313             "sku": "HRD-000-212"
3314           },
3315           {
3316             "name": "ladder",
3317             "sold": 0,
3318             "in-stock": 2,
3319             "on-order": 1,
3320             "sku": "HRD-000-517"
3321           },
3322           {
3323             "name": "bolt",
3324             "sold": 4123.0,
3325             "in-stock": 144,
3326             "on-order": 42,
3327             "sku": "HRD-000-632"
3328           },
3329           {
3330             "name": "water",
3331             "sold": 17.0,
3332             "in-stock": 14,
3333             "on-order": 2,
3334             "sku": "GRO-000-2331"
3335           }
3336         ]
3337       },
3338       "data": {
3339         "item": [
3340           {
3341             "name": "fish",
3342             "sold": 1321.0,
3343             "in-stock": 45,
3344             "on-order": 1,
3345             "sku": "GRO-000-533"
3346           }
3347         ]
3348       }
3349     }
3350
3351 XML output:
3352
3353     % ./testxo --libxo pretty,xml
3354     <top>
3355       <data>
3356         <item>
3357           <name>gum</name>
3358           <sold>1412.0</sold>
3359           <in-stock>54</in-stock>
3360           <on-order>10</on-order>
3361           <sku>GRO-000-415</sku>
3362         </item>
3363         <item>
3364           <name>rope</name>
3365           <sold>85.0</sold>
3366           <in-stock>4</in-stock>
3367           <on-order>2</on-order>
3368           <sku>HRD-000-212</sku>
3369         </item>
3370         <item>
3371           <name>ladder</name>
3372           <sold>0</sold>
3373           <in-stock>2</in-stock>
3374           <on-order>1</on-order>
3375           <sku>HRD-000-517</sku>
3376         </item>
3377         <item>
3378           <name>bolt</name>
3379           <sold>4123.0</sold>
3380           <in-stock>144</in-stock>
3381           <on-order>42</on-order>
3382           <sku>HRD-000-632</sku>
3383         </item>
3384         <item>
3385           <name>water</name>
3386           <sold>17.0</sold>
3387           <in-stock>14</in-stock>
3388           <on-order>2</on-order>
3389           <sku>GRO-000-2331</sku>
3390         </item>
3391       </data>
3392       <data>
3393         <item>
3394           <name>fish</name>
3395           <sold>1321.0</sold>
3396           <in-stock>45</in-stock>
3397           <on-order>1</on-order>
3398           <sku>GRO-000-533</sku>
3399         </item>
3400       </data>
3401     </top>
3402
3403 HMTL output:
3404
3405     % ./testxo --libxo pretty,html
3406     <div class="line">
3407       <div class="label">Item</div>
3408       <div class="text"> '</div>
3409       <div class="data" data-tag="name">gum</div>
3410       <div class="text">':</div>
3411     </div>
3412     <div class="line">
3413       <div class="padding">   </div>
3414       <div class="label">Total sold</div>
3415       <div class="text">: </div>
3416       <div class="data" data-tag="sold">1412.0</div>
3417     </div>
3418     <div class="line">
3419       <div class="padding">   </div>
3420       <div class="label">In stock</div>
3421       <div class="decoration">:</div>
3422       <div class="padding"> </div>
3423       <div class="data" data-tag="in-stock">54</div>
3424     </div>
3425     <div class="line">
3426       <div class="padding">   </div>
3427       <div class="label">On order</div>
3428       <div class="decoration">:</div>
3429       <div class="padding"> </div>
3430       <div class="data" data-tag="on-order">10</div>
3431     </div>
3432     <div class="line">
3433       <div class="padding">   </div>
3434       <div class="label">SKU</div>
3435       <div class="text">: </div>
3436       <div class="data" data-tag="sku">GRO-000-415</div>
3437     </div>
3438     <div class="line">
3439       <div class="label">Item</div>
3440       <div class="text"> '</div>
3441       <div class="data" data-tag="name">rope</div>
3442       <div class="text">':</div>
3443     </div>
3444     <div class="line">
3445       <div class="padding">   </div>
3446       <div class="label">Total sold</div>
3447       <div class="text">: </div>
3448       <div class="data" data-tag="sold">85.0</div>
3449     </div>
3450     <div class="line">
3451       <div class="padding">   </div>
3452       <div class="label">In stock</div>
3453       <div class="decoration">:</div>
3454       <div class="padding"> </div>
3455       <div class="data" data-tag="in-stock">4</div>
3456     </div>
3457     <div class="line">
3458       <div class="padding">   </div>
3459       <div class="label">On order</div>
3460       <div class="decoration">:</div>
3461       <div class="padding"> </div>
3462       <div class="data" data-tag="on-order">2</div>
3463     </div>
3464     <div class="line">
3465       <div class="padding">   </div>
3466       <div class="label">SKU</div>
3467       <div class="text">: </div>
3468       <div class="data" data-tag="sku">HRD-000-212</div>
3469     </div>
3470     <div class="line">
3471       <div class="label">Item</div>
3472       <div class="text"> '</div>
3473       <div class="data" data-tag="name">ladder</div>
3474       <div class="text">':</div>
3475     </div>
3476     <div class="line">
3477       <div class="padding">   </div>
3478       <div class="label">Total sold</div>
3479       <div class="text">: </div>
3480       <div class="data" data-tag="sold">0</div>
3481     </div>
3482     <div class="line">
3483       <div class="padding">   </div>
3484       <div class="label">In stock</div>
3485       <div class="decoration">:</div>
3486       <div class="padding"> </div>
3487       <div class="data" data-tag="in-stock">2</div>
3488     </div>
3489     <div class="line">
3490       <div class="padding">   </div>
3491       <div class="label">On order</div>
3492       <div class="decoration">:</div>
3493       <div class="padding"> </div>
3494       <div class="data" data-tag="on-order">1</div>
3495     </div>
3496     <div class="line">
3497       <div class="padding">   </div>
3498       <div class="label">SKU</div>
3499       <div class="text">: </div>
3500       <div class="data" data-tag="sku">HRD-000-517</div>
3501     </div>
3502     <div class="line">
3503       <div class="label">Item</div>
3504       <div class="text"> '</div>
3505       <div class="data" data-tag="name">bolt</div>
3506       <div class="text">':</div>
3507     </div>
3508     <div class="line">
3509       <div class="padding">   </div>
3510       <div class="label">Total sold</div>
3511       <div class="text">: </div>
3512       <div class="data" data-tag="sold">4123.0</div>
3513     </div>
3514     <div class="line">
3515       <div class="padding">   </div>
3516       <div class="label">In stock</div>
3517       <div class="decoration">:</div>
3518       <div class="padding"> </div>
3519       <div class="data" data-tag="in-stock">144</div>
3520     </div>
3521     <div class="line">
3522       <div class="padding">   </div>
3523       <div class="label">On order</div>
3524       <div class="decoration">:</div>
3525       <div class="padding"> </div>
3526       <div class="data" data-tag="on-order">42</div>
3527     </div>
3528     <div class="line">
3529       <div class="padding">   </div>
3530       <div class="label">SKU</div>
3531       <div class="text">: </div>
3532       <div class="data" data-tag="sku">HRD-000-632</div>
3533     </div>
3534     <div class="line">
3535       <div class="label">Item</div>
3536       <div class="text"> '</div>
3537       <div class="data" data-tag="name">water</div>
3538       <div class="text">':</div>
3539     </div>
3540     <div class="line">
3541       <div class="padding">   </div>
3542       <div class="label">Total sold</div>
3543       <div class="text">: </div>
3544       <div class="data" data-tag="sold">17.0</div>
3545     </div>
3546     <div class="line">
3547       <div class="padding">   </div>
3548       <div class="label">In stock</div>
3549       <div class="decoration">:</div>
3550       <div class="padding"> </div>
3551       <div class="data" data-tag="in-stock">14</div>
3552     </div>
3553     <div class="line">
3554       <div class="padding">   </div>
3555       <div class="label">On order</div>
3556       <div class="decoration">:</div>
3557       <div class="padding"> </div>
3558       <div class="data" data-tag="on-order">2</div>
3559     </div>
3560     <div class="line">
3561       <div class="padding">   </div>
3562       <div class="label">SKU</div>
3563       <div class="text">: </div>
3564       <div class="data" data-tag="sku">GRO-000-2331</div>
3565     </div>
3566     <div class="line">
3567       <div class="label">Item</div>
3568       <div class="text"> '</div>
3569       <div class="data" data-tag="name">fish</div>
3570       <div class="text">':</div>
3571     </div>
3572     <div class="line">
3573       <div class="padding">   </div>
3574       <div class="label">Total sold</div>
3575       <div class="text">: </div>
3576       <div class="data" data-tag="sold">1321.0</div>
3577     </div>
3578     <div class="line">
3579       <div class="padding">   </div>
3580       <div class="label">In stock</div>
3581       <div class="decoration">:</div>
3582       <div class="padding"> </div>
3583       <div class="data" data-tag="in-stock">45</div>
3584     </div>
3585     <div class="line">
3586       <div class="padding">   </div>
3587       <div class="label">On order</div>
3588       <div class="decoration">:</div>
3589       <div class="padding"> </div>
3590       <div class="data" data-tag="on-order">1</div>
3591     </div>
3592     <div class="line">
3593       <div class="padding">   </div>
3594       <div class="label">SKU</div>
3595       <div class="text">: </div>
3596       <div class="data" data-tag="sku">GRO-000-533</div>
3597     </div>
3598
3599 HTML output with xpath and info flags:
3600
3601     % ./testxo --libxo pretty,html,xpath,info
3602     <div class="line">
3603       <div class="label">Item</div>
3604       <div class="text"> '</div>
3605       <div class="data" data-tag="name"
3606            data-xpath="/top/data/item/name" data-type="string"
3607            data-help="Name of the item">gum</div>
3608       <div class="text">':</div>
3609     </div>
3610     <div class="line">
3611       <div class="padding">   </div>
3612       <div class="label">Total sold</div>
3613       <div class="text">: </div>
3614       <div class="data" data-tag="sold"
3615            data-xpath="/top/data/item/sold" data-type="number"
3616            data-help="Number of items sold">1412.0</div>
3617     </div>
3618     <div class="line">
3619       <div class="padding">   </div>
3620       <div class="label">In stock</div>
3621       <div class="decoration">:</div>
3622       <div class="padding"> </div>
3623       <div class="data" data-tag="in-stock"
3624            data-xpath="/top/data/item/in-stock" data-type="number"
3625            data-help="Number of items in stock">54</div>
3626     </div>
3627     <div class="line">
3628       <div class="padding">   </div>
3629       <div class="label">On order</div>
3630       <div class="decoration">:</div>
3631       <div class="padding"> </div>
3632       <div class="data" data-tag="on-order"
3633            data-xpath="/top/data/item/on-order" data-type="number"
3634            data-help="Number of items on order">10</div>
3635     </div>
3636     <div class="line">
3637       <div class="padding">   </div>
3638       <div class="label">SKU</div>
3639       <div class="text">: </div>
3640       <div class="data" data-tag="sku"
3641            data-xpath="/top/data/item/sku" data-type="string"
3642            data-help="Stock Keeping Unit">GRO-000-415</div>
3643     </div>
3644     <div class="line">
3645       <div class="label">Item</div>
3646       <div class="text"> '</div>
3647       <div class="data" data-tag="name"
3648            data-xpath="/top/data/item/name" data-type="string"
3649            data-help="Name of the item">rope</div>
3650       <div class="text">':</div>
3651     </div>
3652     <div class="line">
3653       <div class="padding">   </div>
3654       <div class="label">Total sold</div>
3655       <div class="text">: </div>
3656       <div class="data" data-tag="sold"
3657            data-xpath="/top/data/item/sold" data-type="number"
3658            data-help="Number of items sold">85.0</div>
3659     </div>
3660     <div class="line">
3661       <div class="padding">   </div>
3662       <div class="label">In stock</div>
3663       <div class="decoration">:</div>
3664       <div class="padding"> </div>
3665       <div class="data" data-tag="in-stock"
3666            data-xpath="/top/data/item/in-stock" data-type="number"
3667            data-help="Number of items in stock">4</div>
3668     </div>
3669     <div class="line">
3670       <div class="padding">   </div>
3671       <div class="label">On order</div>
3672       <div class="decoration">:</div>
3673       <div class="padding"> </div>
3674       <div class="data" data-tag="on-order"
3675            data-xpath="/top/data/item/on-order" data-type="number"
3676            data-help="Number of items on order">2</div>
3677     </div>
3678     <div class="line">
3679       <div class="padding">   </div>
3680       <div class="label">SKU</div>
3681       <div class="text">: </div>
3682       <div class="data" data-tag="sku"
3683            data-xpath="/top/data/item/sku" data-type="string"
3684            data-help="Stock Keeping Unit">HRD-000-212</div>
3685     </div>
3686     <div class="line">
3687       <div class="label">Item</div>
3688       <div class="text"> '</div>
3689       <div class="data" data-tag="name"
3690            data-xpath="/top/data/item/name" data-type="string"
3691            data-help="Name of the item">ladder</div>
3692       <div class="text">':</div>
3693     </div>
3694     <div class="line">
3695       <div class="padding">   </div>
3696       <div class="label">Total sold</div>
3697       <div class="text">: </div>
3698       <div class="data" data-tag="sold"
3699            data-xpath="/top/data/item/sold" data-type="number"
3700            data-help="Number of items sold">0</div>
3701     </div>
3702     <div class="line">
3703       <div class="padding">   </div>
3704       <div class="label">In stock</div>
3705       <div class="decoration">:</div>
3706       <div class="padding"> </div>
3707       <div class="data" data-tag="in-stock"
3708            data-xpath="/top/data/item/in-stock" data-type="number"
3709            data-help="Number of items in stock">2</div>
3710     </div>
3711     <div class="line">
3712       <div class="padding">   </div>
3713       <div class="label">On order</div>
3714       <div class="decoration">:</div>
3715       <div class="padding"> </div>
3716       <div class="data" data-tag="on-order"
3717            data-xpath="/top/data/item/on-order" data-type="number"
3718            data-help="Number of items on order">1</div>
3719     </div>
3720     <div class="line">
3721       <div class="padding">   </div>
3722       <div class="label">SKU</div>
3723       <div class="text">: </div>
3724       <div class="data" data-tag="sku"
3725            data-xpath="/top/data/item/sku" data-type="string"
3726            data-help="Stock Keeping Unit">HRD-000-517</div>
3727     </div>
3728     <div class="line">
3729       <div class="label">Item</div>
3730       <div class="text"> '</div>
3731       <div class="data" data-tag="name"
3732            data-xpath="/top/data/item/name" data-type="string"
3733            data-help="Name of the item">bolt</div>
3734       <div class="text">':</div>
3735     </div>
3736     <div class="line">
3737       <div class="padding">   </div>
3738       <div class="label">Total sold</div>
3739       <div class="text">: </div>
3740       <div class="data" data-tag="sold"
3741            data-xpath="/top/data/item/sold" data-type="number"
3742            data-help="Number of items sold">4123.0</div>
3743     </div>
3744     <div class="line">
3745       <div class="padding">   </div>
3746       <div class="label">In stock</div>
3747       <div class="decoration">:</div>
3748       <div class="padding"> </div>
3749       <div class="data" data-tag="in-stock"
3750            data-xpath="/top/data/item/in-stock" data-type="number"
3751            data-help="Number of items in stock">144</div>
3752     </div>
3753     <div class="line">
3754       <div class="padding">   </div>
3755       <div class="label">On order</div>
3756       <div class="decoration">:</div>
3757       <div class="padding"> </div>
3758       <div class="data" data-tag="on-order"
3759            data-xpath="/top/data/item/on-order" data-type="number"
3760            data-help="Number of items on order">42</div>
3761     </div>
3762     <div class="line">
3763       <div class="padding">   </div>
3764       <div class="label">SKU</div>
3765       <div class="text">: </div>
3766       <div class="data" data-tag="sku"
3767            data-xpath="/top/data/item/sku" data-type="string"
3768            data-help="Stock Keeping Unit">HRD-000-632</div>
3769     </div>
3770     <div class="line">
3771       <div class="label">Item</div>
3772       <div class="text"> '</div>
3773       <div class="data" data-tag="name"
3774            data-xpath="/top/data/item/name" data-type="string"
3775            data-help="Name of the item">water</div>
3776       <div class="text">':</div>
3777     </div>
3778     <div class="line">
3779       <div class="padding">   </div>
3780       <div class="label">Total sold</div>
3781       <div class="text">: </div>
3782       <div class="data" data-tag="sold"
3783            data-xpath="/top/data/item/sold" data-type="number"
3784            data-help="Number of items sold">17.0</div>
3785     </div>
3786     <div class="line">
3787       <div class="padding">   </div>
3788       <div class="label">In stock</div>
3789       <div class="decoration">:</div>
3790       <div class="padding"> </div>
3791       <div class="data" data-tag="in-stock"
3792            data-xpath="/top/data/item/in-stock" data-type="number"
3793            data-help="Number of items in stock">14</div>
3794     </div>
3795     <div class="line">
3796       <div class="padding">   </div>
3797       <div class="label">On order</div>
3798       <div class="decoration">:</div>
3799       <div class="padding"> </div>
3800       <div class="data" data-tag="on-order"
3801            data-xpath="/top/data/item/on-order" data-type="number"
3802            data-help="Number of items on order">2</div>
3803     </div>
3804     <div class="line">
3805       <div class="padding">   </div>
3806       <div class="label">SKU</div>
3807       <div class="text">: </div>
3808       <div class="data" data-tag="sku"
3809            data-xpath="/top/data/item/sku" data-type="string"
3810            data-help="Stock Keeping Unit">GRO-000-2331</div>
3811     </div>
3812     <div class="line">
3813       <div class="label">Item</div>
3814       <div class="text"> '</div>
3815       <div class="data" data-tag="name"
3816            data-xpath="/top/data/item/name" data-type="string"
3817            data-help="Name of the item">fish</div>
3818       <div class="text">':</div>
3819     </div>
3820     <div class="line">
3821       <div class="padding">   </div>
3822       <div class="label">Total sold</div>
3823       <div class="text">: </div>
3824       <div class="data" data-tag="sold"
3825            data-xpath="/top/data/item/sold" data-type="number"
3826            data-help="Number of items sold">1321.0</div>
3827     </div>
3828     <div class="line">
3829       <div class="padding">   </div>
3830       <div class="label">In stock</div>
3831       <div class="decoration">:</div>
3832       <div class="padding"> </div>
3833       <div class="data" data-tag="in-stock"
3834            data-xpath="/top/data/item/in-stock" data-type="number"
3835            data-help="Number of items in stock">45</div>
3836     </div>
3837     <div class="line">
3838       <div class="padding">   </div>
3839       <div class="label">On order</div>
3840       <div class="decoration">:</div>
3841       <div class="padding"> </div>
3842       <div class="data" data-tag="on-order"
3843            data-xpath="/top/data/item/on-order" data-type="number"
3844            data-help="Number of items on order">1</div>
3845     </div>
3846     <div class="line">
3847       <div class="padding">   </div>
3848       <div class="label">SKU</div>
3849       <div class="text">: </div>
3850       <div class="data" data-tag="sku"
3851            data-xpath="/top/data/item/sku" data-type="string"
3852            data-help="Stock Keeping Unit">GRO-000-533</div>
3853     </div>
3854
3855 {{document:
3856     name libxo-manual;
3857     private "The libxo Project";
3858     ipr none;
3859     category exp;
3860     abbreviation LIBXO-MANUAL;
3861     title "libxo: The Easy Way to Generate text, XML, JSON, and HTML output";
3862     contributor "author:Phil Shafer:Juniper Networks:phil@juniper.net";
3863 }}