Index: vendor/Juniper/libxo/0.8.2/doc/libxo-manual.html =================================================================== --- vendor/Juniper/libxo/0.8.2/doc/libxo-manual.html (nonexistent) +++ vendor/Juniper/libxo/0.8.2/doc/libxo-manual.html (revision 319998) @@ -0,0 +1,27436 @@ + + + + +libxo: The Easy Way to Generate text, XML, JSON, and HTML output + + + + + + + + + + + + + + + + + + + + + +
+ +

libxo: The Easy Way to Generate text, XML, JSON, and HTML output
libxo-manual

+
+

Table of Contents

+ +
+
+
+

+
+1_ 
+Overview +

+

libxo - A Library for Generating Text, XML, JSON, and HTML Output

+

You want to prepare for the future, but you need to live in the present. You'd love a flying car, but need to get to work today. You want to support features like XML, JSON, and HTML rendering to allow integration with NETCONF, REST, and web browsers, but you need to make text output for command line users.

+

And you don't want multiple code paths that can't help but get out of sync:

+
+    /* None of this "if (xml) {... } else {...}"  logic */
+    if (xml) {
+        /* some code to make xml*/
+    } else {
+        /* other code to make text */
+        /* oops forgot to add something on both clauses! */
+    }
+
+    /* And ifdefs are right out. */
+    #ifdef MAKE_XML
+        /* icky */
+    #else
+        /* pooh */
+    #endif
+	    

But you'd really, really like all the fancy features that modern encoding formats can provide. libxo can help.

+

The libxo library allows an application to generate text, XML, JSON, and HTML output using a common set of function calls. The application decides at run time which output style should be produced. The application calls a function "xo_emit" to product output that is described in a format string. A "field descriptor" tells libxo what the field is and what it means. Each field descriptor is placed in braces with a printf-like format string (Section 3.2):

+
+    xo_emit(" {:lines/%7ju} {:words/%7ju} "
+            "{:characters/%7ju} {d:filename/%s}\n",
+            linect, wordct, charct, file);
+	    

Each field can have a role, with the 'value' role being the default, and the role tells libxo how and when to render that field (see Section 3.2.1 for details). Modifiers change how the field is rendered in different output styles (see Section 3.2.2 for details. Output can then be generated in various style, using the "‑‑libxo" option:

+
+    % wc /etc/motd
+          25     165    1140 /etc/motd
+    % wc --libxo xml,pretty,warn /etc/motd
+    <wc>
+      <file>
+        <lines>25</lines>
+        <words>165</words>
+        <characters>1140</characters>
+        <filename>/etc/motd</filename>
+      </file>
+    </wc>
+    % wc --libxo json,pretty,warn /etc/motd
+    {
+      "wc": {
+        "file": [
+          {
+            "lines": 25,
+            "words": 165,
+            "characters": 1140,
+            "filename": "/etc/motd"
+          }
+        ]
+      }
+    }
+    % wc --libxo html,pretty,warn /etc/motd
+    <div class="line">
+      <div class="text"> </div>
+      <div class="data" data-tag="lines">     25</div>
+      <div class="text"> </div>
+      <div class="data" data-tag="words">    165</div>
+      <div class="text"> </div>
+      <div class="data" data-tag="characters">   1140</div>
+      <div class="text"> </div>
+      <div class="data" data-tag="filename">/etc/motd</div>
+    </div>
+	    

Same code path, same format strings, same information, but it's rendered in distinct styles based on run-time flags.

+
+
+
+

+
+2_ 
+Getting libxo +

+

libxo now ships as part of the FreeBSD Operating System (as of -11).

+

libxo lives on github as:

+

https://github.com/Juniper/libxo

+

The latest release of libxo is available at:

+

https://github.com/Juniper/libxo/releases

+

We are following the branching scheme from http://nvie.com/posts/a-successful-git-branching-model/ which means we will do development under the "develop" branch, and release from the "master" branch. To clone a developer tree, run the following command:

+
+  git clone https://github.com/Juniper/libxo.git -b develop
+	    

We're using semantic release numbering, as defined in http://semver.org/spec/v2.0.0.html.

+

libxo is open source, distributed under the BSD license. It shipped as part of the FreeBSD operating system starting with release 11.0.

+

Issues, problems, and bugs should be directly to the issues page on our github site.

+

Section Contents:

+ +
+

+
+2.1 
+Downloading libxo Source Code +

+

You can retrieve the source for libxo in two ways:

+

A) Use a "distfile" for a specific release. We use github to maintain our releases. Visit github release page (https://github.com/Juniper/libxo/releases) to see the list of releases. To download the latest, look for the release with the green "Latest release" button and the green "libxo‑RELEASE.tar.gz" button under that section.

+

After downloading that release's distfile, untar it as follows:

+
+    tar -zxf libxo-RELEASE.tar.gz
+    cd libxo-RELEASE
+	    

[Note: for Solaris users, your "tar" command lacks the "‑z" flag, so you'll need to substitute "gzip -dc "file" | tar xf -" instead of "tar -zxf "file"".]

+

B) Use the current build from github. This gives you the most recent source code, which might be less stable than a specific release. To build libxo from the git repo:

+
+    git clone https://github.com/Juniper/libxo.git
+    cd libxo
+	    

_BE AWARE_: The github repository does _not_ contain the files generated by "autoreconf", with the notable exception of the "m4" directory. Since these files (depcomp, configure, missing, install-sh, etc) are generated files, we keep them out of the source code repository.

+

This means that if you download the a release distfile, these files will be ready and you'll just need to run "configure", but if you download the source code from svn, then you'll need to run "autoreconf" by hand. This step is done for you by the "setup.sh" script, described in the next section.

+
+
+

+
+2.2 
+Building libxo +

+

To build libxo, you'll need to set up the build, run the "configure" script, run the "make" command, and run the regression tests.

+

The following is a summary of the commands needed. These commands are explained in detail in the rest of this section.

+
+    sh bin/setup.sh
+    cd build
+    ../configure
+    make
+    make test
+    sudo make install
+	    

The following sections will walk through each of these steps with additional details and options, but the above directions should be all that's needed.

+

Section Contents:

+ +
+

+
+2.2.1 
+Setting up the build +

+

[If you downloaded a distfile, you can skip this step.]

+

Run the "setup.sh" script to set up the build. This script runs the "autoreconf" command to generate the "configure" script and other generated files.

+
+    sh bin/setup.sh
+	    

Note: We're are currently using autoreconf version 2.69.

+
+
+

+
+2.2.2 
+Running the "configure" Script +

+

Configure (and autoconf in general) provides a means of building software in diverse environments. Our configure script supports a set of options that can be used to adjust to your operating environment. Use "configure --help" to view these options.

+

We use the "build" directory to keep object files and generated files away from the source tree.

+

To run the configure script, change into the "build" directory, and run the "configure" script. Add any required options to the "../configure" command line.

+
+    cd build
+    ../configure
+	    

Expect to see the "configure" script generate the following error:

+
+    /usr/bin/rm: cannot remove `libtoolT': No such file or directory
+	    

This error is harmless and can be safely ignored.

+

By default, libxo installs architecture-independent files, including extension library files, in the /usr/local directories. To specify an installation prefix other than /usr/local for all installation files, include the --prefix=prefix option and specify an alternate location. To install just the extension library files in a different, user-defined location, include the --with-extensions-dir=dir option and specify the location where the extension libraries will live.

+
+    cd build
+    ../configure [OPTION]... [VAR=VALUE]...
+	    

Section Contents:

+ +
+

+ +Running the "make" command +

+

Once the "configure" script is run, build the images using the "make" command:

+
+    make
+	    
+
+

+ +Running the Regression Tests +

+

libxo includes a set of regression tests that can be run to ensure the software is working properly. These test are optional, but will help determine if there are any issues running libxo on your machine. To run the regression tests:

+
+    make test
+	    
+
+
+

+
+2.2.3 
+Installing libxo +

+

Once the software is built, you'll need to install libxo using the "make install" command. If you are the root user, or the owner of the installation directory, simply issue the command:

+
+    make install
+	    

If you are not the "root" user and are using the "sudo" package, use:

+
+    sudo make install
+	    

Verify the installation by viewing the output of "xo --version":

+
+    % xo --version
+    libxo version 0.3.5-git-develop
+    xo version 0.3.5-git-develop
+	    
+
+
+
+
+

+
+3_ 
+Formatting with libxo +

+

Most unix commands emit text output aimed at humans. It is designed to be parsed and understood by a user. Humans are gifted at extracting details and pattern matching in such output. Often programmers need to extract information from this human-oriented output. Programmers use tools like grep, awk, and regular expressions to ferret out the pieces of information they need. Such solutions are fragile and require maintenance when output contents change or evolve, along with testing and validation.

+

Modern tool developers favor encoding schemes like XML and JSON, which allow trivial parsing and extraction of data. Such formats are simple, well understood, hierarchical, easily parsed, and often integrate easier with common tools and environments. Changes to content can be done in ways that do not break existing users of the data, which can reduce maintenance costs and increase feature velocity.

+

In addition, modern reality means that more output ends up in web browsers than in terminals, making HTML output valuable.

+

libxo allows a single set of function calls in source code to generate traditional text output, as well as XML and JSON formatted data. HTML can also be generated; "<div>" elements surround the traditional text output, with attributes that detail how to render the data.

+

A single libxo function call in source code is all that's required:

+
+    xo_emit("Connecting to {:host}.{:domain}...\n", host, domain);
+
+    TEXT:
+      Connecting to my-box.example.com...
+    XML:
+      <host>my-box</host>
+      <domain>example.com</domain>
+    JSON:
+      "host": "my-box",
+      "domain": "example.com"
+    HTML:
+       <div class="line">
+         <div class="text">Connecting to </div>
+         <div class="data" data-tag="host" 
+              data-xpath="/top/host">my-box</div>
+         <div class="text">.</div>
+         <div class="data" data-tag="domain"
+              data-xpath="/top/domain">example.com</div>
+         <div class="text">...</div>
+       </div>
+	    

Section Contents:

+ +
+

+
+3.1 
+Encoding Styles +

+

There are four encoding styles supported by libxo:

+

+ +

In general, XML and JSON are suitable for encoding data, while TEXT is suited for terminal output and HTML is suited for display in a web browser (see Section 8).

+

Section Contents:

+ +
+

+
+3.1.1 
+Text Output +

+

Most traditional programs generate text output on standard output, with contents like:

+
+    36      ./src
+    40      ./bin
+    90      .
+	    

In this example (taken from du source code), the code to generate this data might look like:

+
+    printf("%d\t%s\n", num_blocks, path);
+	    

Simple, direct, obvious. But it's only making text output. Imagine using a single code path to make TEXT, XML, JSON or HTML, deciding at run time which to generate.

+

libxo expands on the idea of printf format strings to make a single format containing instructions for creating multiple output styles:

+
+    xo_emit("{:blocks/%d}\t{:path/%s}\n", num_blocks, path);
+	    

This line will generate the same text output as the earlier printf call, but also has enough information to generate XML, JSON, and HTML.

+

The following sections introduce the other formats.

+
+
+

+
+3.1.2 
+XML Output +

+

XML output consists of a hierarchical set of elements, each encoded with a start tag and an end tag. The element should be named for data value that it is encoding:

+
+    <item>
+      <blocks>36</blocks>
+      <path>./src</path>
+    </item>
+    <item>
+      <blocks>40</blocks>
+      <path>./bin</path>
+    </item>
+    <item>
+      <blocks>90</blocks>
+      <path>.</path>
+    </item>
+	    

XML is a W3C standard for encoding data. See w3c.org/TR/xml for additional information.

+
+
+

+
+3.1.3 
+JSON Output +

+

JSON output consists of a hierarchical set of objects and lists, each encoded with a quoted name, a colon, and a value. If the value is a string, it must be quoted, but numbers are not quoted. Objects are encoded using braces; lists are encoded using square brackets. Data inside objects and lists is separated using commas:

+
+    items: [
+        { "blocks": 36, "path" : "./src" },
+        { "blocks": 40, "path" : "./bin" },
+        { "blocks": 90, "path" : "./" }
+    ]
+	    
+
+

+
+3.1.4 
+HTML Output +

+

HTML output is designed to allow the output to be rendered in a web browser with minimal effort. Each piece of output data is rendered inside a <div> element, with a class name related to the role of the data. By using a small set of class attribute values, a CSS stylesheet can render the HTML into rich text that mirrors the traditional text content.

+

Additional attributes can be enabled to provide more details about the data, including data type, description, and an XPath location.

+
+    <div class="line">
+      <div class="data" data-tag="blocks">36</div>
+      <div class="padding">      </div>
+      <div class="data" data-tag="path">./src</div>
+    </div>
+    <div class="line">
+      <div class="data" data-tag="blocks">40</div>
+      <div class="padding">      </div>
+      <div class="data" data-tag="path">./bin</div>
+    </div>
+    <div class="line">
+      <div class="data" data-tag="blocks">90</div>
+      <div class="padding">      </div>
+      <div class="data" data-tag="path">./</div>
+    </div>
+	    
+
+
+

+
+3.2 
+Format Strings +

+

libxo uses format strings to control the rendering of data into the various output styles. Each format string contains a set of zero or more field descriptions, which describe independent data fields. Each field description contains a set of modifiers, a content string, and zero, one, or two format descriptors. The modifiers tell libxo what the field is and how to treat it, while the format descriptors are formatting instructions using printf-style format strings, telling libxo how to format the field. The field description is placed inside a set of braces, with a colon (":") after the modifiers and a slash ("/") before each format descriptors. Text may be intermixed with field descriptions within the format string.

+

The field description is given as follows:

+
+    '{' [ role | modifier ]* [',' long-names ]* ':' [ content ]
+            [ '/' field-format [ '/' encoding-format ]] '}'
+	    

The role describes the function of the field, while the modifiers enable optional behaviors. The contents, field-format, and encoding-format are used in varying ways, based on the role. These are described in the following sections.

+

In the following example, three field descriptors appear. The first is a padding field containing three spaces of padding, the second is a label ("In stock"), and the third is a value field ("in‑stock"). The in-stock field has a "%u" format that will parse the next argument passed to the xo_emit function as an unsigned integer.

+
+    xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n", 65);
+	    

This single line of code can generate text (" In stock: 65\n"), XML ("<in‑stock>65</in‑stock>"), JSON ('"in‑stock": 6'), or HTML (too lengthy to be listed here).

+

While roles and modifiers typically use single character for brevity, there are alternative names for each which allow more verbose formatting strings. These names must be preceded by a comma, and may follow any single-character values:

+
+    xo_emit("{L,white,colon:In stock}{,key:in-stock/%u}\n", 65);
+	    

Section Contents:

+ +
+

+
+3.2.1 
+Field Roles +

+

Field roles are optional, and indicate the role and formatting of the content. The roles are listed below; only one role is permitted:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RNameDescription
CcolorField has color and effect controls
DdecorationField is non-text (e.g., colon, comma)
EerrorField is an error message
GgettextCall gettext(3) on the format string
LlabelField is text that prefixes a value
NnoteField is text that follows a value
PpaddingField is spaces needed for vertical alignment
TtitleField is a title value for headings
UunitsField is the units for the previous value field
VvalueField is the name of field (the default)
WwarningField is a warning message
[start-anchorBegin a section of anchored variable-width text
]stop-anchorEnd a section of anchored variable-width text
+
+    EXAMPLE:
+        xo_emit("{L:Free}{D::}{P:   }{:free/%u} {U:Blocks}\n",
+                free_blocks);
+	    

When a role is not provided, the "value" role is used as the default.

+

Roles and modifiers can also use more verbose names, when preceded by a comma:

+
+    EXAMPLE:
+        xo_emit("{,label:Free}{,decoration::}{,padding:   }"
+                "{,value:free/%u} {,units:Blocks}\n",
+                free_blocks);
+	    

Section Contents:

+ +
+

+ +The Color Role ({C:}) +

+

Colors and effects control how text values are displayed; they are used for display styles (TEXT and HTML).

+
+    xo_emit("{C:bold}{:value}{C:no-bold}\n", value);
+	    

Colors and effects remain in effect until modified by other "C"-role fields.

+
+    xo_emit("{C:bold}{C:inverse}both{C:no-bold}only inverse\n");
+	    

If the content is empty, the "reset" action is performed.

+
+    xo_emit("{C:both,underline}{:value}{C:}\n", value);
+	    

The content should be a comma-separated list of zero or more colors or display effects.

+
+    xo_emit("{C:bold,inverse}Ugly{C:no-bold,no-inverse}\n");
+	    

The color content can be either static, when placed directly within the field descriptor, or a printf-style format descriptor can be used, if preceded by a slash ("/"):

+
+   xo_emit("{C:/%s%s}{:value}{C:}", need_bold ? "bold" : "",
+           need_underline ? "underline" : "", value);
+	    

Color names are prefixed with either "fg‑" or "bg‑" to change the foreground and background colors, respectively.

+
+    xo_emit("{C:/fg-%s,bg-%s}{Lwc:Cost}{:cost/%u}{C:reset}\n",
+            fg_color, bg_color, cost);
+	    

The following table lists the supported effects:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDescription
bg-XXXXXChange background color
boldStart bold text effect
fg-XXXXXChange foreground color
inverseStart inverse (aka reverse) text effect
no-boldStop bold text effect
no-inverseStop inverse (aka reverse) text effect
no-underlineStop underline text effect
normalReset effects (only)
resetReset colors and effects (restore defaults)
underlineStart underline text effect
+

The following color names are supported:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDescription
black
blue
cyan
defaultDefault color for foreground or background
green
magenta
red
white
yellow
+

When using colors, the developer should remember that users will change the foreground and background colors of terminal session according to their own tastes, so assuming that "blue" looks nice is never safe, and is a constant annoyance to your dear author. In addition, a significant percentage of users (1 in 12) will be color blind. Depending on color to convey critical information is not a good idea. Color should enhance output, but should not be used as the sole means of encoding information.

+
+
+

+ +The Decoration Role ({D:}) +

+

Decorations are typically punctuation marks such as colons, semi-colons, and commas used to decorate the text and make it simpler for human readers. By marking these distinctly, HTML usage scenarios can use CSS to direct their display parameters.

+
+    xo_emit("{D:((}{:name}{D:))}\n", name);
+	    
+
+

+ +The Gettext Role ({G:}) +

+

libxo supports internationalization (i18n) through its use of gettext(3). Use the "{G:}" role to request that the remaining part of the format string, following the "{G:}" field, be handled using gettext().

+

Since gettext() uses the string as the key into the message catalog, libxo uses a simplified version of the format string that removes unimportant field formatting and modifiers, stopping minor formatting changes from impacting the expensive translation process. A developer change such as changing "/%06d" to "/%08d" should not force hand inspection of all .po files.

+

The simplified version can be generated for a single message using the "xopo -s <text>" command, or an entire .pot can be translated using the "xopo -f <input> -o <output>" command.

+
+   xo_emit("{G:}Invalid token\n");
+	    

The {G:} role allows a domain name to be set. gettext calls will continue to use that domain name until the current format string processing is complete, enabling a library function to emit strings using it's own catalog. The domain name can be either static as the content of the field, or a format can be used to get the domain name from the arguments.

+
+   xo_emit("{G:libc}Service unavailable in restricted mode\n");
+	    

See Section 11.5 for additional details.

+
+
+

+ +The Label Role ({L:}) +

+

Labels are text that appears before a value.

+
+    xo_emit("{Lwc:Cost}{:cost/%u}\n", cost);
+	    
+
+

+ +The Note Role ({N:}) +

+

Notes are text that appears after a value.

+
+    xo_emit("{:cost/%u} {N:per year}\n", cost);
+	    
+
+

+ +The Padding Role ({P:}) +

+

Padding represents whitespace used before and between fields.

+

The padding content can be either static, when placed directly within the field descriptor, or a printf-style format descriptor can be used, if preceded by a slash ("/"):

+
+    xo_emit("{P:        }{Lwc:Cost}{:cost/%u}\n", cost);
+    xo_emit("{P:/%30s}{Lwc:Cost}{:cost/%u}\n", "", cost);
+	    
+
+

+ +The Title Role ({T:}) +

+

Title are heading or column headers that are meant to be displayed to the user. The title can be either static, when placed directly within the field descriptor, or a printf-style format descriptor can be used, if preceded by a slash ("/"):

+
+    xo_emit("{T:Interface Statistics}\n");
+    xo_emit("{T:/%20.20s}{T:/%6.6s}\n", "Item Name", "Cost");
+	    

Title fields have an extra convenience feature; if both content and format are specified, instead of looking to the argument list for a value, the content is used, allowing a mixture of format and content within the field descriptor:

+
+    xo_emit("{T:Name/%20s}{T:Count/%6s}\n");
+	    

Since the incoming argument is a string, the format must be "%s" or something suitable.

+
+
+

+ +The Units Role ({U:}) +

+

Units are the dimension by which values are measured, such as degrees, miles, bytes, and decibels. The units field carries this information for the previous value field.

+
+    xo_emit("{Lwc:Distance}{:distance/%u}{Uw:miles}\n", miles);
+	    

Note that the sense of the 'w' modifier is reversed for units; a blank is added before the contents, rather than after it.

+

When the XOF_UNITS flag is set, units are rendered in XML as the "units" attribute:

+
+    <distance units="miles">50</distance>
+	    

Units can also be rendered in HTML as the "data‑units" attribute:

+
+    <div class="data" data-tag="distance" data-units="miles"
+         data-xpath="/top/data/distance">50</div>
+	    
+
+

+ +The Value Role ({V:} and {:}) +

+

The value role is used to represent the a data value that is interesting for the non-display output styles (XML and JSON). Value is the default role; if no other role designation is given, the field is a value. The field name must appear within the field descriptor, followed by one or two format descriptors. The first format descriptor is used for display styles (TEXT and HTML), while the second one is used for encoding styles (XML and JSON). If no second format is given, the encoding format defaults to the first format, with any minimum width removed. If no first format is given, both format descriptors default to "%s".

+
+    xo_emit("{:length/%02u}x{:width/%02u}x{:height/%02u}\n",
+            length, width, height);
+    xo_emit("{:author} wrote \"{:poem}\" in {:year/%4d}\n,
+            author, poem, year);
+	    
+
+

+ +The Anchor Roles ({[:} and {]:}) +

+

The anchor roles allow a set of strings by be padded as a group, but still be visible to xo_emit as distinct fields. Either the start or stop anchor can give a field width and it can be either directly in the descriptor or passed as an argument. Any fields between the start and stop anchor are padded to meet the minimum width given.

+

To give a width directly, encode it as the content of the anchor tag:

+
+    xo_emit("({[:10}{:min/%d}/{:max/%d}{]:})\n", min, max);
+	    

To pass a width as an argument, use "%d" as the format, which must appear after the "/". Note that only "%d" is supported for widths. Using any other value could ruin your day.

+
+    xo_emit("({[:/%d}{:min/%d}/{:max/%d}{]:})\n", width, min, max);
+	    

If the width is negative, padding will be added on the right, suitable for left justification. Otherwise the padding will be added to the left of the fields between the start and stop anchors, suitable for right justification. If the width is zero, nothing happens. If the number of columns of output between the start and stop anchors is less than the absolute value of the given width, nothing happens.

+

Widths over 8k are considered probable errors and not supported. If XOF_WARN is set, a warning will be generated.

+
+
+
+

+
+3.2.2 
+Field Modifiers +

+

Field modifiers are flags which modify the way content emitted for particular output styles:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MNameDescription
aargumentThe content appears as a 'const char *' argument
ccolonA colon (":") is appended after the label
ddisplayOnly emit field for display styles (text/HTML)
eencodingOnly emit for encoding styles (XML/JSON)
ggettextCall gettext on field's render content
hhumanize (hn)Format large numbers in human-readable style
hn-spaceHumanize: Place space between numeric and unit
hn-decimalHumanize: Add a decimal digit, if number < 10
hn-1000Humanize: Use 1000 as divisor instead of 1024
kkeyField is a key, suitable for XPath predicates
lleaf-listField is a leaf-list
nno-quotesDo not quote the field when using JSON style
ppluralGettext: Use comma-separated plural form
qquotesQuote the field when using JSON style
ttrimTrim leading and trailing whitespace
wwhiteA blank (" ") is appended after the label
+

Roles and modifiers can also use more verbose names, when preceded by a comma. For example, the modifier string "Lwc" (or "L,white,colon") means the field has a label role (text that describes the next field) and should be followed by a colon ('c') and a space ('w'). The modifier string "Vkq" (or ":key,quote") means the field has a value role (the default role), that it is a key for the current instance, and that the value should be quoted when encoded for JSON.

+

Section Contents:

+ +
+

+ +The Argument Modifier ({a:}) +

+

The argument modifier indicates that the content of the field descriptor will be placed as a UTF-8 string (const char *) argument within the xo_emit parameters.

+
+    EXAMPLE:
+      xo_emit("{La:} {a:}\n", "Label text", "label", "value");
+    TEXT:
+      Label text value
+    JSON:
+      "label": "value"
+    XML:
+      <label>value</label>
+	    

The argument modifier allows field names for value fields to be passed on the stack, avoiding the need to build a field descriptor using snprintf. For many field roles, the argument modifier is not needed, since those roles have specific mechanisms for arguments, such as "{C:fg‑%s}".

+
+
+

+ +The Colon Modifier ({c:}) +

+

The colon modifier appends a single colon to the data value:

+
+    EXAMPLE:
+      xo_emit("{Lc:Name}{:name}\n", "phil");
+    TEXT:
+      Name:phil
+	    

The colon modifier is only used for the TEXT and HTML output styles. It is commonly combined with the space modifier ('{w:}'). It is purely a convenience feature.

+
+
+

+ +The Display Modifier ({d:}) +

+

The display modifier indicated the field should only be generated for the display output styles, TEXT and HTML.

+
+    EXAMPLE:
+      xo_emit("{Lcw:Name}{d:name} {:id/%d}\n", "phil", 1);
+    TEXT:
+      Name: phil 1
+    XML:
+      <id>1</id>
+	    

The display modifier is the opposite of the encoding modifier, and they are often used to give to distinct views of the underlying data.

+
+
+

+ +The Encoding Modifier ({e:}) +

+

The display modifier indicated the field should only be generated for the display output styles, TEXT and HTML.

+
+    EXAMPLE:
+      xo_emit("{Lcw:Name}{:name} {e:id/%d}\n", "phil", 1);
+    TEXT:
+      Name: phil
+    XML:
+      <name>phil</name><id>1</id>
+	    

The encoding modifier is the opposite of the display modifier, and they are often used to give to distinct views of the underlying data.

+
+
+

+ +The Gettext Modifier ({g:}) +

+

The gettext modifier is used to translate individual fields using the gettext domain (typically set using the "{G:}" role) and current language settings. Once libxo renders the field value, it is passed to gettext(3), where it is used as a key to find the native language translation.

+

In the following example, the strings "State" and "full" are passed to gettext() to find locale-based translated strings.

+
+    xo_emit("{Lgwc:State}{g:state}\n", "full");
+	    

See Section 3.2.1.3, Section 3.2.2.10, and Section 11.5 for additional details.

+
+
+

+ +The Humanize Modifier ({h:}) +

+

The humanize modifier is used to render large numbers as in a human-readable format. While numbers like "44470272" are completely readable to computers and savants, humans will generally find "44M" more meaningful.

+

"hn" can be used as an alias for "humanize".

+

The humanize modifier only affects display styles (TEXT and HMTL). The "no‑humanize" option (See Section 4) will block the function of the humanize modifier.

+

There are a number of modifiers that affect details of humanization. These are only available in as full names, not single characters. The "hn‑space" modifier places a space between the number and any multiplier symbol, such as "M" or "K" (ex: "44 K"). The "hn‑decimal" modifier will add a decimal point and a single tenths digit when the number is less than 10 (ex: "4.4K"). The "hn‑1000" modifier will use 1000 as divisor instead of 1024, following the JEDEC-standard instead of the more natural binary powers-of-two tradition.

+
+    EXAMPLE:
+        xo_emit("{h:input/%u}, {h,hn-space:output/%u}, "
+            "{h,hn-decimal:errors/%u}, {h,hn-1000:capacity/%u}, "
+            "{h,hn-decimal:remaining/%u}\n",
+            input, output, errors, capacity, remaining);
+    TEXT:
+        21, 57 K, 96M, 44M, 1.2G
+	    

In the HTML style, the original numeric value is rendered in the "data‑number" attribute on the <div> element:

+
+    <div class="data" data-tag="errors"
+         data-number="100663296">96M</div>
+	    
+
+

+ +The Key Modifier ({k:}) +

+

The key modifier is used to indicate that a particular field helps uniquely identify an instance of list data.

+
+    EXAMPLE:
+        xo_open_list("user");
+        for (i = 0; i < num_users; i++) {
+            xo_open_instance("user");
+            xo_emit("User {k:name} has {:count} tickets\n",
+               user[i].u_name, user[i].u_tickets);
+            xo_close_instance("user");
+        }
+        xo_close_list("user");
+	    

Currently the key modifier is only used when generating XPath value for the HTML output style when XOF_XPATH is set, but other uses are likely in the near future.

+
+
+

+ +The Leaf-List Modifier ({l:}) +

+

The leaf-list modifier is used to distinguish lists where each instance consists of only a single value. In XML, these are rendered as single elements, where JSON renders them as arrays.

+
+    EXAMPLE:
+        for (i = 0; i < num_users; i++) {
+            xo_emit("Member {l:user}\n", user[i].u_name);
+        }
+    XML:
+        <user>phil</user>
+        <user>pallavi</user>
+    JSON:
+        "user": [ "phil", "pallavi" ]
+	    

The name of the field must match the name of the leaf list.

+
+
+

+ +The No-Quotes Modifier ({n:}) +

+

The no-quotes modifier (and its twin, the 'quotes' modifier) affect the quoting of values in the JSON output style. JSON uses quotes for string value, but no quotes for numeric, boolean, and null data. xo_emit applies a simple heuristic to determine whether quotes are needed, but often this needs to be controlled by the caller.

+
+    EXAMPLE:
+      const char *bool = is_true ? "true" : "false";
+      xo_emit("{n:fancy/%s}", bool);
+    JSON:
+      "fancy": true
+	    
+
+

+ +The Plural Modifier ({p:}) +

+

The plural modifier selects the appropriate plural form of an expression based on the most recent number emitted and the current language settings. The contents of the field should be the singular and plural English values, separated by a comma:

+
+    xo_emit("{:bytes} {Ngp:byte,bytes}\n", bytes);
+	    

The plural modifier is meant to work with the gettext modifier ({g:}) but can work independently. See Section 3.2.2.5.

+

When used without the gettext modifier or when the message does not appear in the message catalog, the first token is chosen when the last numeric value is equal to 1; otherwise the second value is used, mimicking the simple pluralization rules of English.

+

When used with the gettext modifier, the ngettext(3) function is called to handle the heavy lifting, using the message catalog to convert the singular and plural forms into the native language.

+
+
+

+ +The Quotes Modifier ({q:}) +

+

The quotes modifier (and its twin, the 'no‑quotes' modifier) affect the quoting of values in the JSON output style. JSON uses quotes for string value, but no quotes for numeric, boolean, and null data. xo_emit applies a simple heuristic to determine whether quotes are needed, but often this needs to be controlled by the caller.

+
+    EXAMPLE:
+      xo_emit("{q:time/%d}", 2014);
+    JSON:
+      "year": "2014"
+	    

The heuristic is based on the format; if the format uses any of the following conversion specifiers, then no quotes are used:

+
+    d i o u x X D O U e E f F g G a A c C p
+	    
+
+

+ +The Trim Modifier ({t:}) +

+

The trim modifier removes any leading or trailing whitespace from the value.

+
+    EXAMPLE:
+      xo_emit("{t:description}", "   some  input   ");
+    JSON:
+      "description": "some input"
+	    
+
+

+ +The White Space Modifier ({w:}) +

+

The white space modifier appends a single space to the data value:

+
+    EXAMPLE:
+      xo_emit("{Lw:Name}{:name}\n", "phil");
+    TEXT:
+      Name phil
+	    

The white space modifier is only used for the TEXT and HTML output styles. It is commonly combined with the colon modifier ('{c:}'). It is purely a convenience feature.

+

Note that the sense of the 'w' modifier is reversed for the units role ({Uw:}); a blank is added before the contents, rather than after it.

+
+
+
+

+
+3.2.3 
+Field Formatting +

+

The field format is similar to the format string for printf(3). Its use varies based on the role of the field, but generally is used to format the field's contents.

+

If the format string is not provided for a value field, it defaults to "%s".

+

Note a field definition can contain zero or more printf-style 'directives', which are sequences that start with a '%' and end with one of following characters: "diouxXDOUeEfFgGaAcCsSp". Each directive is matched by one of more arguments to the xo_emit function.

+

The format string has the form:

+
+  '%' format-modifier * format-character
+	    

The format- modifier can be:

+

+
    +
  • a '#' character, indicating the output value should be prefixed with '0x', typically to indicate a base 16 (hex) value.
  • +
  • a minus sign ('‑'), indicating the output value should be padded on the right instead of the left.
  • +
  • a leading zero ('0') indicating the output value should be padded on the left with zeroes instead of spaces (' ').
  • +
  • one or more digits ('0' - '9') indicating the minimum width of the argument. If the width in columns of the output value is less than the minimum width, the value will be padded to reach the minimum.
  • +
  • a period followed by one or more digits indicating the maximum number of bytes which will be examined for a string argument, or the maximum width for a non-string argument. When handling ASCII strings this functions as the field width but for multi-byte characters, a single character may be composed of multiple bytes. xo_emit will never dereference memory beyond the given number of bytes.
  • +
  • a second period followed by one or more digits indicating the maximum width for a string argument. This modifier cannot be given for non-string arguments.
  • +
  • one or more 'h' characters, indicating shorter input data.
  • +
  • one or more 'l' characters, indicating longer input data.
  • +
  • a 'z' character, indicating a 'size_t' argument.
  • +
  • a 't' character, indicating a 'ptrdiff_t' argument.
  • +
  • a ' ' character, indicating a space should be emitted before positive numbers.
  • +
  • a '+' character, indicating sign should emitted before any number.
  • +
+

Note that 'q', 'D', 'O', and 'U' are considered deprecated and will be removed eventually.

+

The format character is described in the following table:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
LtrArgument TypeFormat
dintbase 10 (decimal)
iintbase 10 (decimal)
ointbase 8 (octal)
uunsignedbase 10 (decimal)
xunsignedbase 16 (hex)
Xunsigned longbase 16 (hex)
Dlongbase 10 (decimal)
Ounsigned longbase 8 (octal)
Uunsigned longbase 10 (decimal)
edouble[-]d.ddde+-dd
Edouble[-]d.dddE+-dd
fdouble[-]ddd.ddd
Fdouble[-]ddd.ddd
gdoubleas 'e' or 'f'
Gdoubleas 'E' or 'F'
adouble[-]0xh.hhhp[+-]d
Adouble[-]0Xh.hhhp[+-]d
cunsigned chara character
Cwint_ta character
schar *a UTF-8 string
Swchar_t *a unicode/WCS string
pvoid *'%#lx'
+

The 'h' and 'l' modifiers affect the size and treatment of the argument:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Modd, io, u, x, X
hhsigned charunsigned char
hshortunsigned short
llongunsigned long
lllong longunsigned long long
jintmax_tuintmax_t
tptrdiff_tptrdiff_t
zsize_tsize_t
qquad_tu_quad_t
+
+
+

+
+3.2.4 
+UTF-8 and Locale Strings +

+

For strings, the 'h' and 'l' modifiers affect the interpretation of the bytes pointed to argument. The default '%s' string is a 'char *' pointer to a string encoded as UTF-8. Since UTF-8 is compatible with ASCII data, a normal 7-bit ASCII string can be used. '%ls' expects a 'wchar_t *' pointer to a wide-character string, encoded as a 32-bit Unicode values. '%hs' expects a 'char *' pointer to a multi-byte string encoded with the current locale, as given by the LC_CTYPE, LANG, or LC_ALL environment varibles. The first of this list of variables is used and if none of the variables are set, the locale defaults to "UTF‑8".

+

libxo will convert these arguments as needed to either UTF-8 (for XML, JSON, and HTML styles) or locale-based strings for display in text style.

+
+   xo_emit("All strings are utf-8 content {:tag/%ls}",
+           L"except for wide strings");
+	    

"%S" is equivalent to "%ls".

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FormatArgument TypeArgument Contents
%sconst char *UTF-8 string
%Sconst char *UTF-8 string (alias for '%s')
%lsconst wchar_t *Wide character UNICODE string
%hsconst char *locale-based string
+

For example, a function is passed a locale-base name, a hat size, and a time value. The hat size is formatted in a UTF-8 (ASCII) string, and the time value is formatted into a wchar_t string.

+
+    void print_order (const char *name, int size,
+                      struct tm *timep) {
+        char buf[32];
+        const char *size_val = "unknown";
+
+        if (size > 0)
+            snprintf(buf, sizeof(buf), "%d", size);
+            size_val = buf;
+        }
+
+        wchar_t when[32];
+        wcsftime(when, sizeof(when), L"%d%b%y", timep);
+
+        xo_emit("The hat for {:name/%hs} is {:size/%s}.\n",
+                name, size_val);
+        xo_emit("It was ordered on {:order-time/%ls}.\n",
+                when);
+    }
+	    

It is important to note that xo_emit will perform the conversion required to make appropriate output. Text style output uses the current locale (as described above), while XML, JSON, and HTML use UTF-8.

+

UTF-8 and locale-encoded strings can use multiple bytes to encode one column of data. The traditional "precision'" (aka "max‑width") value for "%s" printf formatting becomes overloaded since it specifies both the number of bytes that can be safely referenced and the maximum number of columns to emit. xo_emit uses the precision as the former, and adds a third value for specifying the maximum number of columns.

+

In this example, the name field is printed with a minimum of 3 columns and a maximum of 6. Up to ten bytes of data at the location given by 'name' are in used in filling those columns.

+
+    xo_emit("{:name/%3.10.6s}", name);
+	    
+
+

+
+3.2.5 
+Characters Outside of Field Definitions +

+

Characters in the format string that are not part of a field definition are copied to the output for the TEXT style, and are ignored for the JSON and XML styles. For HTML, these characters are placed in a <div> with class "text".

+
+  EXAMPLE:
+      xo_emit("The hat is {:size/%s}.\n", size_val);
+  TEXT:
+      The hat is extra small.
+  XML:
+      <size>extra small</size>
+  JSON:
+      "size": "extra small"
+  HTML:
+      <div class="text">The hat is </div>
+      <div class="data" data-tag="size">extra small</div>
+      <div class="text">.</div>
+	    
+
+

+
+3.2.6 
+"%m" Is Supported +

+

libxo supports the '%m' directive, which formats the error message associated with the current value of "errno". It is the equivalent of "%s" with the argument strerror(errno).

+
+    xo_emit("{:filename} cannot be opened: {:error/%m}", filename);
+    xo_emit("{:filename} cannot be opened: {:error/%s}",
+            filename, strerror(errno));
+	    
+
+

+
+3.2.7 
+"%n" Is Not Supported +

+

libxo does not support the '%n' directive. It's a bad idea and we just don't do it.

+
+
+

+
+3.2.8 
+The Encoding Format (eformat) +

+

The "eformat" string is the format string used when encoding the field for JSON and XML. If not provided, it defaults to the primary format with any minimum width removed. If the primary is not given, both default to "%s".

+
+
+

+
+3.2.9 
+Content Strings +

+

For padding and labels, the content string is considered the content, unless a format is given.

+
+
+

+
+3.2.10 
+Argument Validation +

+

Many compilers and tool chains support validation of printf-like arguments. When the format string fails to match the argument list, a warning is generated. This is a valuable feature and while the formatting strings for libxo differ considerably from printf, many of these checks can still provide build-time protection against bugs.

+

libxo provide variants of functions that provide this ability, if the "‑‑enable‑printflike" option is passed to the "configure" script. These functions use the "_p" suffix, like "xo_emit_p()", xo_emit_hp()", etc.

+

The following are features of libxo formatting strings that are incompatible with printf-like testing:

+

+
    +
  • implicit formats, where "{:tag}" has an implicit "%s";
  • +
  • the "max" parameter for strings, where "{:tag/%4.10.6s}" means up to ten bytes of data can be inspected to fill a minimum of 4 columns and a maximum of 6;
  • +
  • percent signs in strings, where "{:filled}%" makes a single, trailing percent sign;
  • +
  • the "l" and "h" modifiers for strings, where "{:tag/%hs}" means locale-based string and "{:tag/%ls}" means a wide character string;
  • +
  • distinct encoding formats, where "{:tag/#%s/%s}" means the display styles (text and HTML) will use "#%s" where other styles use "%s";
  • +
+

If none of these features are in use by your code, then using the "_p" variants might be wise.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Functionprintf-like Equivalent
xo_emit_hvxo_emit_hvp
xo_emit_hxo_emit_hp
xo_emitxo_emit_p
xo_emit_warn_hcvxo_emit_warn_hcvp
xo_emit_warn_hcxo_emit_warn_hcp
xo_emit_warn_cxo_emit_warn_cp
xo_emit_warnxo_emit_warn_p
xo_emit_warnx_xo_emit_warnx_p
xo_emit_errxo_emit_err_p
xo_emit_errxxo_emit_errx_p
xo_emit_errcxo_emit_errc_p
+
+
+

+
+3.2.11 
+Retaining Parsed Format Information +

+

libxo can retain the parsed internal information related to the given format string, allowing subsequent xo_emit calls, the retained information is used, avoiding repetitive parsing of the format string.

+
+    SYNTAX:
+      int xo_emit_f(xo_emit_flags_t flags, const char fmt, ...);
+    EXAMPLE:
+      xo_emit_f(XOEF_RETAIN, "{:some/%02d}{:thing/%-6s}{:fancy}\n",
+                     some, thing, fancy);
+	    

To retain parsed format information, use the XOEF_RETAIN flag to the xo_emit_f() function. A complete set of xo_emit_f functions exist to match all the xo_emit function signatures (with handles, varadic argument, and printf-like flags):

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunctionFlags Equivalent
xo_emit_hvxo_emit_hvf
xo_emit_hxo_emit_hf
xo_emitxo_emit_f
xo_emit_hvpxo_emit_hvfp
xo_emit_hpxo_emit_hfp
xo_emit_pxo_emit_fp
+

The format string must be immutable across multiple calls to xo_emit_f(), since the library retains the string. Typically this is done by using static constant strings, such as string literals. If the string is not immutable, the XOEF_RETAIN flag must not be used.

+

The functions xo_retain_clear() and xo_retain_clear_all() release internal information on either a single format string or all format strings, respectively. Neither is required, but the library will retain this information until it is cleared or the process exits.

+
+    const char *fmt = "{:name}  {:count/%d}\n";
+    for (i = 0; i < 1000; i++) {
+        xo_open_instance("item");
+        xo_emit_f(XOEF_RETAIN, fmt, name[i], count[i]);
+    }
+    xo_retain_clear(fmt);
+	    

The retained information is kept as thread-specific data.

+
+
+

+
+3.2.12 
+Example +

+

In this example, the value for the number of items in stock is emitted:

+
+        xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n",
+                instock);
+	    

This call will generate the following output:

+
+  TEXT: 
+       In stock: 144
+  XML:
+      <in-stock>144</in-stock>
+  JSON:
+      "in-stock": 144,
+  HTML:
+      <div class="line">
+        <div class="padding">   </div>
+        <div class="label">In stock</div>
+        <div class="decoration">:</div>
+        <div class="padding"> </div>
+        <div class="data" data-tag="in-stock">144</div>
+      </div>
+	    

Clearly HTML wins the verbosity award, and this output does not include XOF_XPATH or XOF_INFO data, which would expand the penultimate line to:

+
+       <div class="data" data-tag="in-stock"
+          data-xpath="/top/data/item/in-stock"
+          data-type="number"
+          data-help="Number of items in stock">144</div>
+	    
+
+
+

+
+3.3 
+Representing Hierarchy +

+

For XML and JSON, individual fields appear inside hierarchies which provide context and meaning to the fields. Unfortunately, these encoding have a basic disconnect between how lists is similar objects are represented.

+

XML encodes lists as set of sequential elements:

+
+    <user>phil</user>
+    <user>pallavi</user>
+    <user>sjg</user>
+	    

JSON encodes lists using a single name and square brackets:

+
+    "user": [ "phil", "pallavi", "sjg" ]
+	    

This means libxo needs three distinct indications of hierarchy: one for containers of hierarchy appear only once for any specific parent, one for lists, and one for each item in a list.

+

Section Contents:

+ +
+

+
+3.3.1 
+Containers +

+

A "container" is an element of a hierarchy that appears only once under any specific parent. The container has no value, but serves to contain other nodes.

+

To open a container, call xo_open_container() or xo_open_container_h(). The former uses the default handle and the latter accepts a specific handle.

+
+    int xo_open_container_h (xo_handle_t *xop, const char *name);
+    int xo_open_container (const char *name);
+	    

To close a level, use the xo_close_container() or xo_close_container_h() functions:

+
+    int xo_close_container_h (xo_handle_t *xop, const char *name);
+    int xo_close_container (const char *name);
+	    

Each open call must have a matching close call. If the XOF_WARN flag is set and the name given does not match the name of the currently open container, a warning will be generated.

+
+    Example:
+
+        xo_open_container("top");
+        xo_open_container("system");
+        xo_emit("{:host-name/%s%s%s", hostname,
+                domainname ? "." : "", domainname ?: "");
+        xo_close_container("system");
+        xo_close_container("top");
+
+    Sample Output:
+      Text:
+        my-host.example.org
+      XML:
+        <top>
+          <system>
+              <host-name>my-host.example.org</host-name>
+          </system>
+        </top>
+      JSON:
+        "top" : {
+          "system" : {
+              "host-name": "my-host.example.org"
+          }
+        }
+      HTML:
+        <div class="data"
+             data-tag="host-name">my-host.example.org</div>
+	    
+
+

+
+3.3.2 
+Lists and Instances +

+

A list is set of one or more instances that appear under the same parent. The instances contain details about a specific object. One can think of instances as objects or records. A call is needed to open and close the list, while a distinct call is needed to open and close each instance of the list:

+
+    xo_open_list("item");
+
+    for (ip = list; ip->i_title; ip++) {
+        xo_open_instance("item");
+        xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title);
+        xo_close_instance("item");
+    }
+
+    xo_close_list("item");
+	    

Getting the list and instance calls correct is critical to the proper generation of XML and JSON data.

+
+
+

+
+3.3.3 
+DTRT Mode +

+

Some users may find tracking the names of open containers, lists, and instances inconvenient. libxo offers a "Do The Right Thing" mode, where libxo will track the names of open containers, lists, and instances so the close function can be called without a name. To enable DTRT mode, turn on the XOF_DTRT flag prior to making any other libxo output.

+
+    xo_set_flags(NULL, XOF_DTRT);
+	    

Each open and close function has a version with the suffix "_d", which will close the open container, list, or instance:

+
+    xo_open_container("top");
+    ...
+    xo_close_container_d();
+	    

This also works for lists and instances:

+
+    xo_open_list("item");
+    for (...) {
+        xo_open_instance("item");
+        xo_emit(...);
+        xo_close_instance_d();
+    }
+    xo_close_list_d();
+	    

Note that the XOF_WARN flag will also cause libxo to track open containers, lists, and instances. A warning is generated when the name given to the close function and the name recorded do not match.

+
+
+

+
+3.3.4 
+Markers +

+

Markers are used to protect and restore the state of open constructs. While a marker is open, no other open constructs can be closed. When a marker is closed, all constructs open since the marker was opened will be closed.

+

Markers use names which are not user-visible, allowing the caller to choose appropriate internal names.

+

In this example, the code whiffles through a list of fish, calling a function to emit details about each fish. The marker "fish‑guts" is used to ensure that any constructs opened by the function are closed properly.

+
+    for (i = 0; fish[i]; i++) {
+        xo_open_instance("fish");
+        xo_open_marker("fish-guts");
+        dump_fish_details(i);
+        xo_close_marker("fish-guts");
+    }
+	    
+
+
+
+
+

+
+4_ 
+Command-line Arguments +

+

libxo uses command line options to trigger rendering behavior. The following options are recognised:

+

+ +

The following invocations are all identical in outcome:

+
+  my-app --libxo warn,pretty arg1
+  my-app --libxo=warn,pretty arg1
+  my-app --libxo:WP arg1
+	    

Programs using libxo are expecting to call the xo_parse_args function to parse these arguments. See Section 5.4.1 for details.

+

Section Contents:

+ +
+

+
+4.1 
+Option keywords +

+

Options is a comma-separated list of tokens that correspond to output styles, flags, or features:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TokenAction
colorEnable colors/effects for display styles (TEXT, HTML)
colors=xxxxAdjust color output values
dtrtEnable "Do The Right Thing" mode
flushFlush after every libxo function call
flush-lineFlush after every line (line-buffered)
htmlEmit HTML output
indent=xxSet the indentation level
infoAdd info attributes (HTML)
jsonEmit JSON output
keysEmit the key attribute for keys (XML)
log-gettextLog (via stderr) each gettext(3) string lookup
log-syslogLog (via stderr) each syslog message (via xo_syslog)
no-humanizeIgnore the {h:} modifier (TEXT, HTML)
no-localeDo not initialize the locale setting
no-retainPrevent retaining formatting information
no-topDo not emit a top set of braces (JSON)
not-firstPretend the 1st output item was not 1st (JSON)
prettyEmit pretty-printed output
retainForce retaining formatting information
textEmit TEXT output
underscoresReplace XML-friendly "-"s with JSON friendly "_"s
unitsAdd the 'units' (XML) or 'data-units (HTML) attribute
warnEmit warnings when libxo detects bad calls
warn-xmlEmit warnings in XML
xmlEmit XML output
xpathAdd XPath expressions (HTML)
+

Most of these option are simple and direct, but some require additional details:

+

+ +
+
+

+
+4.2 
+Brief Options +

+

The brief options are simple single-letter aliases to the normal keywords, as detailed below:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionAction
cEnable color/effects for TEXT/HTML
FForce line-buffered flushing
HEnable HTML output (XO_STYLE_HTML)
IEnable info output (XOF_INFO)
i<num>Indent by <number>
JEnable JSON output (XO_STYLE_JSON)
kAdd keys to XPATH expressions in HTML
nDisable humanization (TEXT, HTML)
PEnable pretty-printed output (XOF_PRETTY)
TEnable text output (XO_STYLE_TEXT)
UAdd units to HTML output
uChange "-"s to "_"s in element names (JSON)
WEnable warnings (XOF_WARN)
XEnable XML output (XO_STYLE_XML)
xEnable XPath data (XOF_XPATH)
+
+
+

+
+4.3 
+Color Mapping +

+

The "colors" option takes a value that is a set of mappings from the pre-defined set of colors to new foreground and background colors. The value is a series of "fg/bg" values, separated by a "+". Each pair of "fg/bg" values gives the colors to which a basic color is mapped when used as a foreground or background color. The order is the mappings is:

+

+ +

Pairs may be skipped, leaving them mapped as normal, as are missing pairs or single colors.

+

For example consider the following xo_emit call:

+
+    xo_emit("{C:fg-red,bg-green}Merry XMas!!{C:}\n");
+	    

To turn all colored output to red-on-blue, use eight pairs of "red/blue" mappings separated by "+"s:

+
+    --libxo colors=red/blue+red/blue+red/blue+red/blue+\
+                   red/blue+red/blue+red/blue+red/blue
+	    

To turn the red-on-green text to magenta-on-cyan, give a "magenta" foreground value for red (the second mapping) and a "cyan" background to green (the third mapping):

+
+    --libxo colors=+magenta+/cyan
+	    

Consider the common situation where blue output looks unreadable on a terminal session with a black background. To turn both "blue" foreground and background output to "yellow", give only the fifth mapping, skipping the first four mappings with bare "+"s:

+
+    --libxo colors=++++yellow/yellow
+	    
+
+
+
+

+
+5_ 
+The libxo API +

+

This section gives details about the functions in libxo, how to call them, and the actions they perform.

+

Section Contents:

+ +
+

+
+5.1 
+Handles +

+

libxo uses "handles" to control its rendering functionality. The handle contains state and buffered data, as well as callback functions to process data.

+

Handles give an abstraction for libxo that encapsulates the state of a stream of output. Handles have the data type "xo_handle_t" and are opaque to the caller.

+

The library has a default handle that is automatically initialized. By default, this handle will send text style output (XO_STYLE_TEXT) to standard output. The xo_set_style and xo_set_flags functions can be used to change this behavior.

+

For the typical command that is generating output on standard output, there is no need to create an explicit handle, but they are available when needed, e.g., for daemons that generate multiple streams of output.

+

Many libxo functions take a handle as their first parameter; most that do not use the default handle. Any function taking a handle can be passed NULL to access the default handle. For the convenience of callers, the libxo library includes handle-less functions that implicitly use the default handle.

+

For example, the following are equivalent:

+
+    xo_emit("test");
+    xo_emit_h(NULL, "test");
+	    

Handles are created using xo_create() and destroy using xo_destroy().

+

Section Contents:

+ +
+

+
+5.1.1 
+xo_create +

+

A handle can be allocated using the xo_create() function:

+
+    xo_handle_t *xo_create (unsigned style, unsigned flags);
+
+  Example:
+    xo_handle_t *xop = xo_create(XO_STYLE_JSON, XOF_WARN);
+    ....
+    xo_emit_h(xop, "testing\n");
+	    

See also Section 5.1.5.1 and Section 5.1.6.1.

+
+
+

+
+5.1.2 
+xo_create_to_file +

+

By default, libxo writes output to standard output. A convenience function is provided for situations when output should be written to a different file:

+
+    xo_handle_t *xo_create_to_file (FILE *fp, unsigned style,
+                                    unsigned flags);
+	    

Use the XOF_CLOSE_FP flag to trigger a call to fclose() for the FILE pointer when the handle is destroyed.

+
+
+

+
+5.1.3 
+xo_set_writer +

+

The xo_set_writer function allows custom 'write' functions which can tailor how libxo writes data. An opaque argument is recorded and passed back to the write function, allowing the function to acquire context information. The 'close' function can release this opaque data and any other resources as needed. The flush function can flush buffered data associated with the opaque object.

+
+    void xo_set_writer (xo_handle_t *xop, void *opaque,
+                        xo_write_func_t write_func,
+                        xo_close_func_t close_func);
+                        xo_flush_func_t flush_func);
+	    
+
+

+
+5.1.4 
+xo_set_style +

+

To set the style, use the xo_set_style() function:

+
+    void xo_set_style(xo_handle_t *xop, unsigned style);
+	    

To use the default handle, pass a NULL handle:

+
+    xo_set_style(NULL, XO_STYLE_XML);
+	    
+
+

+
+5.1.5 
+xo_get_style +

+

To find the current style, use the xo_get_style() function:

+
+    xo_style_t xo_get_style(xo_handle_t *xop);
+	    

To use the default handle, pass a NULL handle:

+
+    style = xo_get_style(NULL);
+	    

Section Contents:

+ +
+

+ +Output Styles (XO_STYLE_*) +

+

The libxo functions accept a set of output styles:

+
+ + + + + + + + + + + + + + + + + + + + + + +
FlagDescription
XO_STYLE_TEXTTraditional text output
XO_STYLE_XMLXML encoded data
XO_STYLE_JSONJSON encoded data
XO_STYLE_HTMLHTML encoded data
+
+
+

+ +xo_set_style_name +

+

The xo_set_style_name() can be used to set the style based on a name encoded as a string:

+
+    int xo_set_style_name (xo_handle_t *xop, const char *style);
+	    

The name can be any of the styles: "text", "xml", "json", or "html".

+
+    EXAMPLE:
+        xo_set_style_name(NULL, "html");
+	    
+
+
+

+
+5.1.6 
+xo_set_flags +

+

To set the flags, use the xo_set_flags() function:

+
+    void xo_set_flags(xo_handle_t *xop, unsigned flags);
+	    

To use the default handle, pass a NULL handle:

+
+    xo_set_style(NULL, XO_STYLE_XML);
+	    

Section Contents:

+ +
+

+ +Flags (XOF_*) +

+

The set of valid flags include:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FlagDescription
XOF_CLOSE_FPClose file pointer on xo_destroy()
XOF_COLOREnable color and effects in output
XOF_COLOR_ALLOWEDAllow color/effect for terminal output
XOF_DTRTEnable "do the right thing" mode
XOF_INFODisplay info data attributes (HTML)
XOF_KEYSEmit the key attribute (XML)
XOF_NO_ENVDo not use the LIBXO_OPTIONS env var
XOF_NO_HUMANIZEDisplay humanization (TEXT, HTML)
XOF_PRETTYMake 'pretty printed' output
XOF_UNDERSCORESReplaces hyphens with underscores
XOF_UNITSDisplay units (XML, HMTL)
XOF_WARNGenerate warnings for broken calls
XOF_WARN_XMLGenerate warnings in XML on stdout
XOF_XPATHEmit XPath expressions (HTML)
XOF_COLUMNSForce xo_emit to return columns used
XOF_FLUSHFlush output after each xo_emit call
+

The XOF_CLOSE_FP flag will trigger the call of the close_func (provided via xo_set_writer()) when the handle is destroyed.

+

The XOF_COLOR flag enables color and effects in output regardless of output device, while the XOF_COLOR_ALLOWED flag allows color and effects only if the output device is a terminal.

+

The XOF_PRETTY flag requests 'pretty printing', which will trigger the addition of indentation and newlines to enhance the readability of XML, JSON, and HTML output. Text output is not affected.

+

The XOF_WARN flag requests that warnings will trigger diagnostic output (on standard error) when the library notices errors during operations, or with arguments to functions. Without warnings enabled, such conditions are ignored.

+

Warnings allow developers to debug their interaction with libxo. The function "xo_failure" can used as a breakpoint for a debugger, regardless of whether warnings are enabled.

+

If the style is XO_STYLE_HTML, the following additional flags can be used:

+
+ + + + + + + + + + + + + + +
FlagDescription
XOF_XPATHEmit "data-xpath" attributes
XOF_INFOEmit additional info fields
+

The XOF_XPATH flag enables the emission of XPath expressions detailing the hierarchy of XML elements used to encode the data field, if the XPATH style of output were requested.

+

The XOF_INFO flag encodes additional informational fields for HTML output. See Section 5.4.4 for details.

+

If the style is XO_STYLE_XML, the following additional flags can be used:

+
+ + + + + + + + +
FlagDescription
XOF_KEYSFlag 'key' fields for xml
+

The XOF_KEYS flag adds 'key' attribute to the XML encoding for field definitions that use the 'k' modifier. The key attribute has the value "key":

+
+    xo_emit("{k:name}", item);
+
+  XML:
+      <name key="key">truck</name>
+	    
+
+

+ +xo_clear_flags +

+

The xo_clear_flags() function turns off the given flags in a specific handle.

+
+    void xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags);
+	    
+
+

+ +xo_set_options +

+

The xo_set_options() function accepts a comma-separated list of styles and flags and enables them for a specific handle.

+
+    int xo_set_options (xo_handle_t *xop, const char *input);
+	    

The options are identical to those listed in Section 4.

+
+
+
+

+
+5.1.7 
+xo_destroy +

+

The xo_destroy function releases a handle and any resources it is using. Calling xo_destroy with a NULL handle will release any resources associated with the default handle.

+
+    void xo_destroy(xo_handle_t *xop);
+	    
+
+
+

+
+5.2 
+Emitting Content (xo_emit) +

+

The following functions are used to emit output:

+
+    int xo_emit (const char *fmt, ...);
+    int xo_emit_h (xo_handle_t *xop, const char *fmt, ...);
+    int xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap);
+	    

The "fmt" argument is a string containing field descriptors as specified in Section 3.2. The use of a handle is optional and NULL can be passed to access the internal 'default' handle. See Section 5.1.

+

The remaining arguments to xo_emit() and xo_emit_h() are a set of arguments corresponding to the fields in the format string. Care must be taken to ensure the argument types match the fields in the format string, since an inappropriate cast can ruin your day. The vap argument to xo_emit_hv() points to a variable argument list that can be used to retrieve arguments via va_arg().

+

Section Contents:

+ +
+

+
+5.2.1 
+Single Field Emitting Functions (xo_emit_field) +

+

The following functions can also make output, but only make a single field at a time:

+
+    int xo_emit_field_hv (xo_handle_t *xop, const char *rolmod,
+                  const char *contents, const char *fmt, 
+                  const char *efmt, va_list vap);
+
+    int xo_emit_field_h (xo_handle_t *xop, const char *rolmod, 
+                 const char *contents, const char *fmt,
+                 const char *efmt, ...);
+
+    int xo_emit_field (const char *rolmod, const char *contents,
+                 const char *fmt, const char *efmt, ...);
+	    

These functions are intended to avoid the scenario where one would otherwise need to compose a format descriptors using snprintf(). The individual parts of the format descriptor are passed in distinctly.

+
+    xo_emit("T", "Host name is ", NULL, NULL);
+    xo_emit("V", "host-name", NULL, NULL, host-name);
+	    
+
+

+
+5.2.2 
+Attributes (xo_attr) +

+

The xo_attr() function emits attributes for the XML output style.

+
+    int xo_attr (const char *name, const char *fmt, ...);
+    int xo_attr_h (xo_handle_t *xop, const char *name, 
+                   const char *fmt, ...);
+    int xo_attr_hv (xo_handle_t *xop, const char *name, 
+                   const char *fmt, va_list vap);
+	    

The name parameter give the name of the attribute to be encoded. The fmt parameter gives a printf-style format string used to format the value of the attribute using any remaining arguments, or the vap parameter passed to xo_attr_hv().

+
+    EXAMPLE:
+      xo_attr("seconds", "%ld", (unsigned long) login_time);
+      struct tm *tmp = localtime(login_time);
+      strftime(buf, sizeof(buf), "%R", tmp);
+      xo_emit("Logged in at {:login-time}\n", buf);
+    XML:
+        <login-time seconds="1408336270">00:14</login-time>
+	    

xo_attr is placed on the next container, instance, leaf, or leaf list that is emitted.

+

Since attributes are only emitted in XML, their use should be limited to meta-data and additional or redundant representations of data already emitted in other form.

+
+
+

+
+5.2.3 
+Flushing Output (xo_flush) +

+

libxo buffers data, both for performance and consistency, but also to allow some advanced features to work properly. At various times, the caller may wish to flush any data buffered within the library. The xo_flush() call is used for this:

+
+    void xo_flush (void);
+    void xo_flush_h (xo_handle_t *xop);
+	    

Calling xo_flush also triggers the flush function associated with the handle. For the default handle, this is equivalent to "fflush(stdio);".

+
+
+

+
+5.2.4 
+Finishing Output (xo_finish) +

+

When the program is ready to exit or close a handle, a call to xo_finish() is required. This flushes any buffered data, closes open libxo constructs, and completes any pending operations.

+
+    int xo_finish (void);
+    int xo_finish_h (xo_handle_t *xop);
+    void xo_finish_atexit (void);
+	    

Calling this function is vital to the proper operation of libxo, especially for the non-TEXT output styles.

+

xo_finish_atexit is suitable for use with atexit(3).

+
+
+
+

+
+5.3 
+Emitting Hierarchy +

+

libxo represents to types of hierarchy: containers and lists. A container appears once under a given parent where a list contains instances that can appear multiple times. A container is used to hold related fields and to give the data organization and scope.

+

To create a container, use the xo_open_container and xo_close_container functions:

+
+    int xo_open_container (const char *name);
+    int xo_open_container_h (xo_handle_t *xop, const char *name);
+    int xo_open_container_hd (xo_handle_t *xop, const char *name);
+    int xo_open_container_d (const char *name);
+
+    int xo_close_container (const char *name);
+    int xo_close_container_h (xo_handle_t *xop, const char *name);
+    int xo_close_container_hd (xo_handle_t *xop);
+    int xo_close_container_d (void);
+	    

The name parameter gives the name of the container, encoded in UTF-8. Since ASCII is a proper subset of UTF-8, traditional C strings can be used directly.

+

The close functions with the "_d" suffix are used in "Do The Right Thing" mode, where the name of the open containers, lists, and instances are maintained internally by libxo to allow the caller to avoid keeping track of the open container name.

+

Use the XOF_WARN flag to generate a warning if the name given on the close does not match the current open container.

+

For TEXT and HTML output, containers are not rendered into output text, though for HTML they are used when the XOF_XPATH flag is set.

+
+    EXAMPLE:
+       xo_open_container("system");
+       xo_emit("The host name is {:host-name}\n", hn);
+       xo_close_container("system");
+    XML:
+       <system><host-name>foo</host-name></system>
+	    

Section Contents:

+ +
+

+
+5.3.1 
+Lists and Instances +

+

Lists are sequences of instances of homogeneous data objects. Two distinct levels of calls are needed to represent them in our output styles. Calls must be made to open and close a list, and for each instance of data in that list, calls must be make to open and close that instance.

+

The name given to all calls must be identical, and it is strongly suggested that the name be singular, not plural, as a matter of style and usage expectations.

+
+    EXAMPLE:
+        xo_open_list("user");
+        for (i = 0; i < num_users; i++) {
+            xo_open_instance("user");
+            xo_emit("{k:name}:{:uid/%u}:{:gid/%u}:{:home}\n",
+                    pw[i].pw_name, pw[i].pw_uid,
+                    pw[i].pw_gid, pw[i].pw_dir);
+            xo_close_instance("user");
+        }
+        xo_close_list("user");
+    TEXT:
+        phil:1001:1001:/home/phil
+        pallavi:1002:1002:/home/pallavi
+    XML:
+        <user>
+            <name>phil</name>
+            <uid>1001</uid>
+            <gid>1001</gid>
+            <home>/home/phil</home>
+        </user>
+        <user>
+            <name>pallavi</name>
+            <uid>1002</uid>
+            <gid>1002</gid>
+            <home>/home/pallavi</home>
+        </user>
+    JSON:
+        user: [
+            {
+                "name": "phil",
+                "uid": 1001,
+                "gid": 1001,
+                "home": "/home/phil",
+            },
+            {
+                "name": "pallavi",
+                "uid": 1002,
+                "gid": 1002,
+                "home": "/home/pallavi",
+            }
+        ]
+	    
+
+
+

+
+5.4 
+Support Functions +

+

Section Contents:

+ +
+

+
+5.4.1 
+Parsing Command-line Arguments (xo_parse_args) +

+

The xo_parse_args() function is used to process a program's arguments. libxo-specific options are processed and removed from the argument list so the calling application does not need to process them. If successful, a new value for argc is returned. On failure, a message it emitted and -1 is returned.

+
+    argc = xo_parse_args(argc, argv);
+    if (argc < 0)
+        exit(EXIT_FAILURE);
+	    

Following the call to xo_parse_args, the application can process the remaining arguments in a normal manner. See Section 4 for a description of valid arguments.

+
+
+

+
+5.4.2 
+xo_set_program +

+

The xo_set_program function sets name of the program as reported by functions like xo_failure, xo_warn, xo_err, etc. The program name is initialized by xo_parse_args, but subsequent calls to xo_set_program can override this value.

+
+    xo_set_program(argv[0]);
+	    

Note that the value is not copied, so the memory passed to xo_set_program (and xo_parse_args) must be maintained by the caller.

+
+
+

+
+5.4.3 
+xo_set_version +

+

The xo_set_version function records a version number to be emitted as part of the data for encoding styles (XML and JSON). This version number is suitable for tracking changes in the content, allowing a user of the data to discern which version of the data model is in use.

+
+     void xo_set_version (const char *version);
+     void xo_set_version_h (xo_handle_t *xop, const char *version);
+	    
+
+

+
+5.4.4 
+Field Information (xo_info_t) +

+

HTML data can include additional information in attributes that begin with "data‑". To enable this, three things must occur:

+

First the application must build an array of xo_info_t structures, one per tag. The array must be sorted by name, since libxo uses a binary search to find the entry that matches names from format instructions.

+

Second, the application must inform libxo about this information using the xo_set_info() call:

+
+    typedef struct xo_info_s {
+        const char *xi_name;    /* Name of the element */
+        const char *xi_type;    /* Type of field */
+        const char *xi_help;    /* Description of field */
+    } xo_info_t;
+
+    void xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count);
+	    

Like other libxo calls, passing NULL for the handle tells libxo to use the default handle.

+

If the count is -1, libxo will count the elements of infop, but there must be an empty element at the end. More typically, the number is known to the application:

+
+    xo_info_t info[] = {
+        { "in-stock", "number", "Number of items in stock" },
+        { "name", "string", "Name of the item" },
+        { "on-order", "number", "Number of items on order" },
+        { "sku", "string", "Stock Keeping Unit" },
+        { "sold", "number", "Number of items sold" },
+    };
+    int info_count = (sizeof(info) / sizeof(info[0]));
+    ...
+    xo_set_info(NULL, info, info_count);
+	    

Third, the emission of info must be triggered with the XOF_INFO flag using either the xo_set_flags() function or the "‑‑libxo=info" command line argument.

+

The type and help values, if present, are emitted as the "data‑type" and "data‑help" attributes:

+
+  <div class="data" data-tag="sku" data-type="string" 
+       data-help="Stock Keeping Unit">GRO-000-533</div>
+	    
+
+

+
+5.4.5 
+Memory Allocation +

+

The xo_set_allocator function allows libxo to be used in environments where the standard realloc() and free() functions are not available.

+
+    void xo_set_allocator (xo_realloc_func_t realloc_func,
+                           xo_free_func_t free_func);
+	    

realloc_func should expect the same arguments as realloc(3) and return a pointer to memory following the same convention. free_func will receive the same argument as free(3) and should release it, as appropriate for the environment.

+

By default, the standard realloc() and free() functions are used.

+
+
+

+
+5.4.6 
+LIBXO_OPTIONS +

+

The environment variable "LIBXO_OPTIONS" can be set to a subset of libxo options, including:

+

+
    +
  • color
  • +
  • flush
  • +
  • flush-line
  • +
  • no-color
  • +
  • no-humanize
  • +
  • no-locale
  • +
  • no-retain
  • +
  • pretty
  • +
  • retain
  • +
  • underscores
  • +
  • warn
  • +
+

For example, warnings can be enabled by:

+
+    % env LIBXO_OPTIONS=warn my-app
+	    

Since environment variables are inherited, child processes will have the same options, which may be undesirable, making the use of the "‑‑libxo" option is preferable in most situations.

+
+
+

+
+5.4.7 
+Errors, Warnings, and Messages +

+

Many programs make use of the standard library functions err() and warn() to generate errors and warnings for the user. libxo wants to pass that information via the current output style, and provides compatible functions to allow this:

+
+    void xo_warn (const char *fmt, ...);
+    void xo_warnx (const char *fmt, ...);
+    void xo_warn_c (int code, const char *fmt, ...);
+    void xo_warn_hc (xo_handle_t *xop, int code,
+                     const char *fmt, ...);
+    void xo_err (int eval, const char *fmt, ...);
+    void xo_errc (int eval, int code, const char *fmt, ...);
+    void xo_errx (int eval, const char *fmt, ...);
+    void xo_message (const char *fmt, ...);
+    void xo_message_c (int code, const char *fmt, ...);
+    void xo_message_hc (xo_handle_t *xop, int code,
+                        const char *fmt, ...);
+    void xo_message_hcv (xo_handle_t *xop, int code, 
+                         const char *fmt, va_list vap);
+	    

These functions display the program name, a colon, a formatted message based on the arguments, and then optionally a colon and an error message associated with either "errno" or the "code" parameter.

+
+    EXAMPLE:
+        if (open(filename, O_RDONLY) < 0)
+            xo_err(1, "cannot open file '%s'", filename);
+	    
+
+

+
+5.4.8 
+xo_error +

+

The xo_error function can be used for generic errors that should be reported over the handle, rather than to stderr. The xo_error function behaves like xo_err for TEXT and HTML output styles, but puts the error into XML or JSON elements:

+
+    EXAMPLE::
+        xo_error("Does not %s", "compute");
+    XML::
+        <error><message>Does not compute</message></error>
+    JSON::
+        "error": { "message": "Does not compute" }
+	    
+
+

+
+5.4.9 
+xo_no_setlocale +

+

libxo automatically initializes the locale based on setting of the environment variables LC_CTYPE, LANG, and LC_ALL. The first of this list of variables is used and if none of the variables, the locale defaults to "UTF‑8". The caller may wish to avoid this behavior, and can do so by calling the xo_no_setlocale() function.

+
+    void xo_no_setlocale (void);
+	    
+
+
+

+
+5.5 
+Emitting syslog Messages +

+

syslog is the system logging facility used throughout the unix world. Messages are sent from commands, applications, and daemons to a hierarchy of servers, where they are filtered, saved, and forwarded based on configuration behaviors.

+

syslog is an older protocol, originally documented only in source code. By the time RFC 3164 published, variation and mutation left the leading "<pri>" string as only common content. RFC 5424 defines a new version (version 1) of syslog and introduces structured data into the messages. Structured data is a set of name/value pairs transmitted distinctly alongside the traditional text message, allowing filtering on precise values instead of regular expressions.

+

These name/value pairs are scoped by a two-part identifier; an enterprise identifier names the party responsible for the message catalog and a name identifying that message. Enterprise IDs are defined by IANA, the Internet Assigned Numbers Authority:

+

https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers

+

Use the Section 5.5.3.5() function to set the Enterprise ID, as needed.

+

The message name should follow the conventions in Section 10.1.3, as should the fields within the message.

+
+    /* Both of these calls are optional */
+    xo_set_syslog_enterprise_id(32473);
+    xo_open_log("my-program", 0, LOG_DAEMON);
+
+    /* Generate a syslog message */
+    xo_syslog(LOG_ERR, "upload-failed",
+              "error <%d> uploading file '{:filename}' "
+              "as '{:target/%s:%s}'",
+              code, filename, protocol, remote);
+
+    xo_syslog(LOG_INFO, "poofd-invalid-state",
+              "state {:current/%u} is invalid {:connection/%u}",
+              state, conn);
+	    

The developer should be aware that the message name may be used in the future to allow access to further information, including documentation. Care should be taken to choose quality, descriptive names.

+

Section Contents:

+ +
+

+
+5.5.1 
+Priority, Facility, and Flags +

+

The xo_syslog, xo_vsyslog, and xo_open_log functions accept a set of flags which provide the priority of the message, the source facility, and some additional features. These values are OR'd together to create a single integer argument:

+
+    xo_syslog(LOG_ERR | LOG_AUTH, "login-failed",
+             "Login failed; user '{:user}' from host '{:address}'",
+             user, addr);
+	    

These values are defined in <syslog.h>.

+

The priority value indicates the importance and potential impact of each message.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PriorityDescription
LOG_EMERGA panic condition, normally broadcast to all users
LOG_ALERTA condition that should be corrected immediately
LOG_CRITCritical conditions
LOG_ERRGeneric errors
LOG_WARNINGWarning messages
LOG_NOTICENon-error conditions that might need special handling
LOG_INFOInformational messages
LOG_DEBUGDeveloper-oriented messages
+

The facility value indicates the source of message, in fairly generic terms.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FacilityDescription
LOG_AUTHThe authorization system (e.g. login(1))
LOG_AUTHPRIVAs LOG_AUTH, but logged to a privileged file
LOG_CRONThe cron daemon: cron(8)
LOG_DAEMONSystem daemons, not otherwise explicitly listed
LOG_FTPThe file transfer protocol daemons
LOG_KERNMessages generated by the kernel
LOG_LPRThe line printer spooling system
LOG_MAILThe mail system
LOG_NEWSThe network news system
LOG_SECURITYSecurity subsystems, such as ipfw(4)
LOG_SYSLOGMessages generated internally by syslogd(8)
LOG_USERMessages generated by user processes (default)
LOG_UUCPThe uucp system
LOG_LOCAL0..7Reserved for local use
+

In addition to the values listed above, xo_open_log accepts a set of addition flags requesting specific behaviors.

+
+ + + + + + + + + + + + + + + + + + + + + + +
FlagDescription
LOG_CONSIf syslogd fails, attempt to write to /dev/console
LOG_NDELAYOpen the connection to syslogd(8) immediately
LOG_PERRORWrite the message also to standard error output
LOG_PIDLog the process id with each message
+
+
+

+
+5.5.2 
+xo_syslog +

+

Use the xo_syslog function to generate syslog messages by calling it with a log priority and facility, a message name, a format string, and a set of arguments. The priority/facility argument are discussed above, as is the message name.

+

The format string follows the same conventions as xo_emit's format string, with each field being rendered as an SD-PARAM pair.

+
+    xo_syslog(LOG_ERR, "poofd-missing-file",
+              "'{:filename}' not found: {:error/%m}", filename);
+
+    ... [poofd-missing-file@32473 filename="/etc/poofd.conf"
+          error="Permission denied"] '/etc/poofd.conf' not
+          found: Permission denied
+	    
+
+

+
+5.5.3 
+Support functions +

+

Section Contents:

+ +
+

+ +xo_vsyslog +

+

xo_vsyslog is identical in function to xo_syslog, but takes the set of arguments using a va_list.

+
+    void my_log (const char *name, const char *fmt, ...)
+    {
+        va_list vap;
+        va_start(vap, fmt);
+        xo_vsyslog(LOG_ERR, name, fmt, vap);
+        va_end(vap);
+    }
+	    
+
+

+ +xo_open_log +

+

xo_open_log functions similar to openlog(3), allowing customization of the program name, the log facility number, and the additional option flags described in Section 5.5.1.

+
+    void
+    xo_open_log (const char *ident, int logopt, int facility);
+	    
+
+

+ +xo_close_log +

+

xo_close_log functions similar to closelog(3), closing the log file and releasing any associated resources.

+
+    void
+    xo_close_log (void);
+	    
+
+

+ +xo_set_logmask +

+

xo_set_logmask function similar to setlogmask(3), restricting the set of generated log event to those whose associated bit is set in maskpri. Use LOG_MASK(pri) to find the appropriate bit, or LOG_UPTO(toppri) to create a mask for all priorities up to and including toppri.

+
+    int
+    xo_set_logmask (int maskpri);
+
+  Example:
+    setlogmask(LOG_UPTO(LOG_WARN));
+	    
+
+

+ +xo_set_syslog_enterprise_id +

+

Use the xo_set_syslog_enterprise_id to supply a platform- or application-specific enterprise id. This value is used in any future syslog messages.

+

Ideally, the operating system should supply a default value via the "kern.syslog.enterprise_id" sysctl value. Lacking that, the application should provide a suitable value.

+
+    void
+    xo_set_syslog_enterprise_id (unsigned short eid);
+	    

Enterprise IDs are administered by IANA, the Internet Assigned Number Authority. The complete list is EIDs on their web site:

+

https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers

+

New EIDs can be requested from IANA using the following page:

+

http://pen.iana.org/pen/PenApplication.page

+

Each software development organization that defines a set of syslog messages should register their own EID and use that value in their software to ensure that messages can be uniquely identified by the combination of EID + message name.

+
+
+
+
+

+
+5.6 
+Creating Custom Encoders +

+

The number of encoding schemes in current use is staggering, with new and distinct schemes appearing daily. While libxo provide XML, JSON, HMTL, and text natively, there are requirements for other encodings.

+

Rather than bake support for all possible encoders into libxo, the API allows them to be defined externally. libxo can then interfaces with these encoding modules using a simplistic API. libxo processes all functions calls, handles state transitions, performs all formatting, and then passes the results as operations to a customized encoding function, which implements specific encoding logic as required. This means your encoder doesn't need to detect errors with unbalanced open/close operations but can rely on libxo to pass correct data.

+

By making a simple API, libxo internals are not exposed, insulating the encoder and the library from future or internal changes.

+

The three elements of the API are:

+

+ +

The following sections provide details about these topics.

+

libxo source contain an encoder for Concise Binary Object Representation, aka CBOR (RFC 7049) which can be used as used as an example for the API.

+

Section Contents:

+ +
+

+
+5.6.1 
+Loading Encoders +

+

Encoders can be registered statically or discovered dynamically. Applications can choose to call the xo_encoder_register() function to explicitly register encoders, but more typically they are built as shared libraries, placed in the libxo/extensions directory, and loaded based on name. libxo looks for a file with the name of the encoder and an extension of ".enc". This can be a file or a symlink to the shared library file that supports the encoder.

+
+    % ls -1 lib/libxo/extensions/*.enc
+    lib/libxo/extensions/cbor.enc
+    lib/libxo/extensions/test.enc
+	    
+
+

+
+5.6.2 
+Encoder Initialization +

+

Each encoder must export a symbol used to access the library, which must have the following signature:

+
+    int xo_encoder_library_init (XO_ENCODER_INIT_ARGS);
+	    

XO_ENCODER_INIT_ARGS is a macro defined in xo_encoder.h that defines an argument called "arg", a pointer of the type xo_encoder_init_args_t. This structure contains two fields:

+

+
    +
  • xei_version is the version number of the API as implemented within libxo. This version is currently as 1 using XO_ENCODER_VERSION. This number can be checked to ensure compatibility. The working assumption is that all versions should be backward compatible, but each side may need to accurately know the version supported by the other side. xo_encoder_library_init can optionally check this value, and must then set it to the version number used by the encoder, allowing libxo to detect version differences and react accordingly. For example, if version 2 adds new operations, then libxo will know that an encoding library that set xei_version to 1 cannot be expected to handle those new operations.
  • +
  • xei_handler must be set to a pointer to a function of type xo_encoder_func_t, as defined in xo_encoder.h. This function takes a set of parameters: -- xop is a pointer to the opaque xo_handle_t structure -- op is an integer representing the current operation -- name is a string whose meaning differs by operation -- value is a string whose meaning differs by operation -- private is an opaque structure provided by the encoder
  • +
+

Additional arguments may be added in the future, so handler functions should use the XO_ENCODER_HANDLER_ARGS macro. An appropriate "extern" declaration is provided to help catch errors.

+

Once the encoder initialization function has completed processing, it should return zero to indicate that no error has occurred. A non-zero return code will cause the handle initialization to fail.

+
+
+

+
+5.6.3 
+Operations +

+

The encoder API defines a set of operations representing the processing model of libxo. Content is formatted within libxo, and callbacks are made to the encoder's handler function when data is ready to be processed.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperationMeaning (Base function)
XO_OP_CREATECalled when the handle is created
XO_OP_OPEN_CONTAINERContainer opened (xo_open_container)
XO_OP_CLOSE_CONTAINERContainer closed (xo_close_container)
XO_OP_OPEN_LISTList opened (xo_open_list)
XO_OP_CLOSE_LISTList closed (xo_close_list)
XO_OP_OPEN_LEAF_LISTLeaf list opened (xo_open_leaf_list)
XO_OP_CLOSE_LEAF_LISTLeaf list closed (xo_close_leaf_list)
XO_OP_OPEN_INSTANCEInstance opened (xo_open_instance)
XO_OP_CLOSE_INSTANCEInstance closed (xo_close_instance)
XO_OP_STRINGField with Quoted UTF-8 string
XO_OP_CONTENTField with content
XO_OP_FINISHFinish any pending output
XO_OP_FLUSHFlush any buffered output
XO_OP_DESTROYClean up resources
XO_OP_ATTRIBUTEAn attribute name/value pair
XO_OP_VERSIONA version string
+

For all the open and close operations, the name parameter holds the name of the construct. For string, content, and attribute operations, the name parameter is the name of the field and the value parameter is the value. "string" are differentiated from "content" to allow differing treatment of true, false, null, and numbers from real strings, though content values are formatted as strings before the handler is called. For version operations, the value parameter contains the version.

+

All strings are encoded in UTF-8.

+
+
+
+
+
+

+
+6_ 
+The "xo" Utility +

+

The "xo" utility allows command line access to the functionality of the libxo library. Using "xo", shell scripts can emit XML, JSON, and HTML using the same commands that emit text output.

+

The style of output can be selected using a specific option: "‑X" for XML, "‑J" for JSON, "‑H" for HTML, or "‑T" for TEXT, which is the default. The "--style <style>" option can also be used. The standard set of "‑‑libxo" options are available (see Section 4), as well as the LIBXO_OPTIONS environment variable (see Section 5.4.6).

+

The "xo" utility accepts a format string suitable for xo_emit() and a set of zero or more arguments used to supply data for that string.

+
+    xo "The {k:name} weighs {:weight/%d} pounds.\n" fish 6
+
+  TEXT:
+    The fish weighs 6 pounds.
+  XML:
+    <name>fish</name>
+    <weight>6</weight>
+  JSON:
+    "name": "fish",
+    "weight": 6
+  HTML:
+    <div class="line">
+      <div class="text">The </div>
+      <div class="data" data-tag="name">fish</div>
+      <div class="text"> weighs </div>
+      <div class="data" data-tag="weight">6</div>
+      <div class="text"> pounds.</div>
+    </div>
+	    

The "--wrap <path>" option can be used to wrap emitted content in a specific hierarchy. The path is a set of hierarchical names separated by the '/' character.

+
+    xo --wrap top/a/b/c '{:tag}' value
+
+  XML:
+    <top>
+      <a>
+        <b>
+          <c>
+            <tag>value</tag>
+          </c>
+        </b>
+      </a>
+    </top>
+  JSON:
+    "top": {
+      "a": {
+        "b": {
+          "c": {
+            "tag": "value"
+          }
+        }
+      }
+    }
+	    

The "--open <path>" and "--close <path>" can be used to emit hierarchical information without the matching close and open tag. This allows a shell script to emit open tags, data, and then close tags. The "‑‑depth" option may be used to set the depth for indentation. The "‑‑leading‑xpath" may be used to prepend data to the XPath values used for HTML output style.

+
+    #!/bin/sh
+    xo --open top/data
+    xo --depth 2 '{tag}' value
+    xo --close top/data
+  XML:
+    <top>
+      <data>
+        <tag>value</tag>
+      </data>
+    </top>
+  JSON:
+    "top": {
+      "data": {
+        "tag": "value"
+      }
+    }
+	    

Section Contents:

+ +
+

+
+6.1 
+Command Line Options +

+

Usage: xo [options] format [fields]

+
+  --close <path>        Close tags for the given path
+  --depth <num>         Set the depth for pretty printing
+  --help                Display this help text
+  --html OR -H          Generate HTML output
+  --json OR -J          Generate JSON output
+  --leading-xpath <path> Add a prefix to generated XPaths (HTML)
+  --open <path>         Open tags for the given path
+  --pretty OR -p        Make 'pretty' output (add indent, newlines)
+  --style <style>       Generate given style (xml, json, text, html)
+  --text OR -T          Generate text output (the default style)
+  --version             Display version information
+  --warn OR -W          Display warnings in text on stderr
+  --warn-xml            Display warnings in xml on stdout
+  --wrap <path>         Wrap output in a set of containers
+  --xml OR -X           Generate XML output
+  --xpath               Add XPath data to HTML output);
+	    
+
+

+
+6.2 
+Example +

+
+  % xo 'The {:product} is {:status}\n' stereo "in route"
+  The stereo is in route
+  % ./xo/xo -p -X 'The {:product} is {:status}\n' stereo "in route"
+  <product>stereo</product>
+  <status>in route</status>
+	    
+
+
+
+

+
+7_ 
+xolint +

+

xolint is a tool for reporting common mistakes in format strings in source code that invokes xo_emit(). It allows these errors to be diagnosed at build time, rather than waiting until runtime.

+

xolint takes the one or more C files as arguments, and reports and errors, warning, or informational messages as needed.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionMeaning
-cInvoke 'cpp' against the input file
-C <flags>Flags that are passed to 'cpp
-dEnable debug output
-DGenerate documentation for all xolint messages
-IGenerate info table code
-pPrint the offending lines after the message
-VPrint vocabulary of all field names
-XExtract samples from xolint, suitable for testing
+

The output message will contain the source filename and line number, the class of the message, the message, and, if -p is given, the line that contains the error:

+
+    % xolint.pl -t xolint.c
+    xolint.c: 16: error: anchor format should be "%d"
+    16         xo_emit("{[:/%s}");
+	    

The "‑I" option will generate a table of xo_info_t structures ,

+

The "‑V" option does not report errors, but prints a complete list of all field names, sorted alphabetically. The output can help spot inconsistencies and spelling errors.

+
+
+
+

+
+8_ 
+xohtml +

+

xohtml is a tool for turning the output of libxo-enabled commands into html files suitable for display in modern HTML web browsers. It can be used to test and debug HTML output, as well as to make the user ache to escape the world of 70s terminal devices.

+

xohtml is given a command, either on the command line or via the "‑c" option. If not command is given, standard input is used. The command's output is wrapped in HTML tags, with references to supporting CSS and Javascript files, and written to standard output or the file given in the "‑f" option. The "‑b" option can be used to provide an alternative base path for the support files.

+
+ + + + + + + + + + + + + + + + + + +
OptionMeaning
-b <base>Base path for finding css/javascript files
-c <command>Command to execute
-f <file>Output file name
+

The "‑c" option takes a full command with arguments, including any libxo options needed to generate html ("‑‑libxo=html"). This value must be quoted if it consists of multiple tokens.

+
+
+
+

+
+9_ 
+xopo +

+

The "xopo" utility filters ".pot" files generated by the "xgettext" utility to remove formatting information suitable for use with the "{G:}" modifier. This means that when the developer changes the formatting portion of the field definitions, or the fields modifiers, the string passed to gettext(3) is unchanged, avoiding the expense of updating any existing translation files (".po" files).

+

The syntax for the xopo command is one of two forms; it can be used as a filter for processing a .po or .pot file, rewriting the "msgid" strings with a simplified message string. In this mode, the input is either standard input or a file given by the "‑f" option, and the output is either standard output or a file given by the "‑o" option.

+

In the second mode, a simple message given using the "‑s" option on the command, and the simplified version of that message is printed on stdout.

+
+ + + + + + + + + + + + + + + + + + +
OptionMeaning
-o <file>Output file name
-f <file>Use the given .po file as input
-s <text>Simplify a format string
+
+    EXAMPLE:
+        % xopo -s "There are {:count/%u} {:event/%.6s} events\n"
+        There are {:count} {:event} events\n
+
+        % xgettext --default-domain=foo --no-wrap \
+            --add-comments --keyword=xo_emit --keyword=xo_emit_h \
+            --keyword=xo_emit_warn -C -E -n --foreign-user \
+            -o foo.pot.raw foo.c
+        % xopo -f foo.pot.raw -o foo.pot
+	    

Use of the "‑‑no‑wrap" option for xgettext is required to ensure that incoming msgid strings are not wrapped across multiple lines.

+
+
+
+

+
+10_ 
+FAQs +

+

This section contains the set of questions that users typically ask, along with answers that might be helpful.

+

Section Contents:

+ +

Section Contents:

+ +
+

+
+10.1 
+General +

+

Section Contents:

+ +
+

+
+10.1.1 
+Can you share the history of libxo? +

+

In 2001, we added an XML API to the JUNOS operating system, which is built on top of FreeBSD. Eventually this API became standardized as the NETCONF API (RFC 6241). As part of this effort, we modified many FreeBSD utilities to emit XML, typically via a "‑X" switch. The results were mixed. The cost of maintaining this code, updating it, and carrying it were non-trivial, and contributed to our expense (and the associated delay) with upgrading the version of FreeBSD on which each release of JUNOS is based.

+

A recent (2014) effort within JUNOS aims at removing our modifications to the underlying FreeBSD code as a means of reducing the expense and delay in tracking HEAD. JUNOS is structured to have system components generate XML that is rendered by the CLI (think: login shell) into human-readable text. This allows the API to use the same plumbing as the CLI, and ensures that all components emit XML, and that it is emitted with knowledge of the consumer of that XML, yielding an API that have no incremental cost or feature delay.

+

libxo is an effort to mix the best aspects of the JUNOS strategy into FreeBSD in a seemless way, allowing commands to make printf-like output calls with a single code path.

+
+
+

+
+10.1.2 
+Did the complex semantics of format strings evolve over time? +

+

The history is both long and short: libxo's functionality is based on what JUNOS does in a data modeling language called ODL (output definition language). In JUNOS, all subcomponents generate XML, which is feed to the CLI, where data from the ODL files tell is how to render that XML into text. ODL might had a set of tags like:

+
+     tag docsis-state {
+         help "State of the DOCSIS interface";
+         type string;
+     }
+
+     tag docsis-mode {
+         help "DOCSIS mode (2.0/3.0) of the DOCSIS interface";
+         type string;
+     }
+
+     tag docsis-upstream-speed {
+         help "Operational upstream speed of the interface";
+         type string;
+     }
+
+     tag downstream-scanning {
+         help "Result of scanning in downstream direction";
+         type string;
+     }
+
+     tag ranging {
+         help "Result of ranging action";
+         type string;
+     }
+
+     tag signal-to-noise-ratio {
+         help "Signal to noise ratio for all channels";
+         type string;
+     }
+
+     tag power {
+         help "Operational power of the signal on all channels";
+         type string;
+     }
+
+     format docsis-status-format {
+         picture "
+   State   : @, Mode: @, Upstream speed: @
+   Downstream scanning: @, Ranging: @
+   Signal to noise ratio: @
+   Power: @
+";
+         line {
+             field docsis-state;
+             field docsis-mode;
+             field docsis-upstream-speed;
+             field downstream-scanning;
+             field ranging;
+             field signal-to-noise-ratio;
+             field power;
+         }
+     }
+	    

These tag definitions are compiled into field definitions that are triggered when matching XML elements are seen. ODL also supports other means of defining output.

+

The roles and modifiers describe these details.

+

In moving these ideas to bsd, two things had to happen: the formatting had to happen at the source since BSD won't have a JUNOS-like CLI to do the rendering, and we can't depend on external data models like ODL, which was seen as too hard a sell to the BSD community.

+

The results were that the xo_emit strings are used to encode the roles, modifiers, names, and formats. They are dense and a bit cryptic, but not so unlike printf format strings that developers will be lost.

+

libxo is a new implementation of these ideas and is distinct from the previous implementation in JUNOS.

+
+
+

+
+10.1.3 
+What makes a good field name? +

+

To make useful, consistent field names, follow these guidelines:

+

+
+
Use lower case, even for TLAs
+
Lower case is more civilized. Even TLAs should be lower case to avoid scenarios where the differences between "XPath" and "Xpath" drive your users crazy. Using "xpath" is simpler and better.
+
Use hyphens, not underscores
+
Use of hyphens is traditional in XML, and the XOF_UNDERSCORES flag can be used to generate underscores in JSON, if desired. But the raw field name should use hyphens.
+
Use full words
+
Don't abbreviate especially when the abbreviation is not obvious or not widely used. Use "data‑size", not "dsz" or "dsize". Use "interface" instead of "ifname", "if‑name", "iface", "if", or "intf".
+
Use <verb>-<units>
+
Using the form <verb>-<units> or <verb>-<classifier>-<units> helps in making consistent, useful names, avoiding the situation where one app uses "sent‑packet" and another "packets‑sent" and another "packets‑we‑have‑sent". The <units> can be dropped when it is obvious, as can obvious words in the classification. Use "receive‑after‑window‑packets" instead of "received‑packets‑of‑data‑after‑window".
+
Reuse existing field names
+
Nothing's worse than writing expressions like:
+
+
+    if ($src1/process[pid == $pid]/name == 
+        $src2/proc-table/proc-list
+                   /proc-entry[process-id == $pid]/proc-name) {
+        ...
+    }
+	    

Find someone else who is expressing similar data and follow their fields and hierarchy. Remember the quote is not "Consistency is the hobgoblin of little minds", but "A foolish consistency is the hobgoblin of little minds".

+

+
+
Use containment as scoping
+
In the previous example, all the names are prefixed with "proc‑", which is redundant given that they are nested under the process table.
+
Think about your users
+
Have empathy for your users, choosing clear and useful fields that contain clear and useful data. You may need to augment the display content with xo_attr() calls (Section 5.2.2) or "{e:}" fields (Section 3.2.2.4) to make the data useful.
+
Don't use an arbitrary number postfix
+
What does "errors2" mean? No one will know. "errors‑after‑restart" would be a better choice. Think of your users, and think of the future. If you make "errors2", the next guy will happily make "errors3" and before you know it, someone will be asking what's the difference between errors37 and errors63.
+
Be consistent, uniform, unsurprising, and predictable
+
Think of your field vocabulary as an API. You want it useful, expressive, meaningful, direct, and obvious. You want the client application's programmer to move between without the need to understand a variety of opinions on how fields are named. They should see the system as a single cohesive whole, not a sack of cats.
+
+

Field names constitute the means by which client programmers interact with our system. By choosing wise names now, you are making their lives better.

+

After using "xolint" to find errors in your field descriptors, use "xolint -V" to spell check your field names and to detect different names for the same data. "dropped‑short" and "dropped‑too‑short" are both reasonable names, but using them both will lead users to ask the difference between the two fields. If there is no difference, use only one of the field names. If there is a difference, change the names to make that difference more obvious.

+
+
+
+

+
+10.2 
+What does this message mean? +

+

Section Contents:

+ +
+

+
+10.2.1 
+'A percent sign appearing in text is a literal' +

+

The message "A percent sign appearing in text is a literal" can be caused by code like:

+
+    xo_emit("cost: %d", cost);
+	    

This code should be replaced with code like:

+
+    xo_emit("{L:cost}: {:cost/%d}", cost);
+	    

This can be a bit surprising and could be a field that was not properly converted to a libxo-style format string.

+
+
+

+
+10.2.2 
+'Unknown long name for role/modifier' +

+

The message "Unknown long name for role/modifier" can be caused by code like:

+
+    xo_emit("{,humanization:value}", value);
+	    

This code should be replaced with code like:

+
+    xo_emit("{,humanize:value}", value);
+	    

The hn-* modifiers (hn-decimal, hn-space, hn-1000) are only valid for fields with the {h:} modifier.

+
+
+

+
+10.2.3 
+'Last character before field definition is a field type' +

+

The message "Last character before field definition is a field type" can be caused by code like:

+

A common typo:

+
+    xo_emit("{T:Min} T{:Max}");
+	    

This code should be replaced with code like:

+
+    xo_emit("{T:Min} {T:Max}");
+	    

Twiddling the "{" and the field role is a common typo.

+
+
+

+
+10.2.4 
+'Encoding format uses different number of arguments' +

+

The message "Encoding format uses different number of arguments" can be caused by code like:

+
+    xo_emit("{:name/%6.6s %%04d/%s}", name, number);
+	    

This code should be replaced with code like:

+
+    xo_emit("{:name/%6.6s %04d/%s-%d}", name, number);
+	    

Both format should consume the same number of arguments off the stack

+
+
+

+
+10.2.5 
+'Only one field role can be used' +

+

The message "Only one field role can be used" can be caused by code like:

+
+    xo_emit("{LT:Max}");
+	    

This code should be replaced with code like:

+
+    xo_emit("{T:Max}");
+	    
+
+

+
+10.2.6 
+'Potential missing slash after C, D, N, L, or T with format' +

+

The message "Potential missing slash after C, D, N, L, or T with format" can be caused by code like:

+
+    xo_emit("{T:%6.6s}\n", "Max");
+	    

This code should be replaced with code like:

+
+    xo_emit("{T:/%6.6s}\n", "Max");
+	    

The "%6.6s" will be a literal, not a field format. While it's possibly valid, it's likely a missing "/".

+
+
+

+
+10.2.7 
+'An encoding format cannot be given (roles: DNLT)' +

+

The message "An encoding format cannot be given (roles: DNLT)" can be caused by code like:

+
+    xo_emit("{T:Max//%s}", "Max");
+	    

Fields with the C, D, N, L, and T roles are not emitted in the 'encoding' style (JSON, XML), so an encoding format would make no sense.

+
+
+

+
+10.2.8 
+'Format cannot be given when content is present (roles: CDLN)' +

+

The message "Format cannot be given when content is present (roles: CDLN)" can be caused by code like:

+
+    xo_emit("{N:Max/%6.6s}", "Max");
+	    

Fields with the C, D, L, or N roles can't have both static literal content ("{L:Label}") and a format ("{L:/%s}"). This error will also occur when the content has a backslash in it, like "{N:Type of I/O}"; backslashes should be escaped, like "{N:Type of I\\/O}". Note the double backslash, one for handling 'C' strings, and one for libxo.

+
+
+

+
+10.2.9 
+'Field has color without fg- or bg- (role: C)' +

+

The message "Field has color without fg- or bg- (role: C)" can be caused by code like:

+
+    xo_emit("{C:green}{:foo}{C:}", x);
+	    

This code should be replaced with code like:

+
+    xo_emit("{C:fg-green}{:foo}{C:}", x);
+	    

Colors must be prefixed by either "fg‑" or "bg‑".

+
+
+

+ +'Field has invalid color or effect (role: C)' +

+

The message "Field has invalid color or effect (role: C)" can be caused by code like:

+
+    xo_emit("{C:fg-purple,bold}{:foo}{C:gween}", x);
+	    

This code should be replaced with code like:

+
+    xo_emit("{C:fg-red,bold}{:foo}{C:fg-green}", x);
+	    

The list of colors and effects are limited. The set of colors includes default, black, red, green, yellow, blue, magenta, cyan, and white, which must be prefixed by either "fg‑" or "bg‑". Effects are limited to bold, no-bold, underline, no-underline, inverse, no-inverse, normal, and reset. Values must be separated by commas.

+
+
+

+ +'Field has humanize modifier but no format string' +

+

The message "Field has humanize modifier but no format string" can be caused by code like:

+
+    xo_emit("{h:value}", value);
+	    

This code should be replaced with code like:

+
+    xo_emit("{h:value/%d}", value);
+	    

Humanization is only value for numbers, which are not likely to use the default format ("%s").

+
+
+

+ +'Field has hn-* modifier but not 'h' modifier' +

+

The message "Field has hn-* modifier but not 'h' modifier" can be caused by code like:

+
+    xo_emit("{,hn-1000:value}", value);
+	    

This code should be replaced with code like:

+
+    xo_emit("{h,hn-1000:value}", value);
+	    

The hn-* modifiers (hn-decimal, hn-space, hn-1000) are only valid for fields with the {h:} modifier.

+
+
+

+ +'Value field must have a name (as content)")' +

+

The message "Value field must have a name (as content)")" can be caused by code like:

+
+    xo_emit("{:/%s}", "value");
+	    

This code should be replaced with code like:

+
+    xo_emit("{:tag-name/%s}", "value");
+	    

The field name is used for XML and JSON encodings. These tags names are static and must appear directly in the field descriptor.

+
+
+

+ +'Use hyphens, not underscores, for value field name' +

+

The message "Use hyphens, not underscores, for value field name" can be caused by code like:

+
+    xo_emit("{:no_under_scores}", "bad");
+	    

This code should be replaced with code like:

+
+    xo_emit("{:no-under-scores}", "bad");
+	    

Use of hyphens is traditional in XML, and the XOF_UNDERSCORES flag can be used to generate underscores in JSON, if desired. But the raw field name should use hyphens.

+
+
+

+ +'Value field name cannot start with digit' +

+

The message "Value field name cannot start with digit" can be caused by code like:

+
+    xo_emit("{:10-gig/}");
+	    

This code should be replaced with code like:

+
+    xo_emit("{:ten-gig/}");
+	    

XML element names cannot start with a digit.

+
+
+

+ +'Value field name should be lower case' +

+

The message "Value field name should be lower case" can be caused by code like:

+
+    xo_emit("{:WHY-ARE-YOU-SHOUTING}", "NO REASON");
+	    

This code should be replaced with code like:

+
+    xo_emit("{:why-are-you-shouting}", "no reason");
+	    

Lower case is more civilized. Even TLAs should be lower case to avoid scenarios where the differences between "XPath" and "Xpath" drive your users crazy. Lower case rules the seas.

+
+
+

+ +'Value field name should be longer than two characters' +

+

The message "Value field name should be longer than two characters" can be caused by code like:

+
+    xo_emit("{:x}", "mumble");
+	    

This code should be replaced with code like:

+
+    xo_emit("{:something-meaningful}", "mumble");
+	    

Field names should be descriptive, and it's hard to be descriptive in less than two characters. Consider your users and try to make something more useful. Note that this error often occurs when the field type is placed after the colon ("{:T/%20s}"), instead of before it ("{T:/20s}").

+
+
+

+ +'Value field name contains invalid character' +

+

The message "Value field name contains invalid character" can be caused by code like:

+
+    xo_emit("{:cost-in-$$/%u}", 15);
+	    

This code should be replaced with code like:

+
+    xo_emit("{:cost-in-dollars/%u}", 15);
+	    

An invalid character is often a sign of a typo, like "{:]}" instead of "{]:}". Field names are restricted to lower-case characters, digits, and hyphens.

+
+
+

+ +'decoration field contains invalid character' +

+

The message "decoration field contains invalid character" can be caused by code like:

+
+    xo_emit("{D:not good}");
+	    

This code should be replaced with code like:

+
+    xo_emit("{D:((}{:good}{D:))}", "yes");
+	    

This is minor, but fields should use proper roles. Decoration fields are meant to hold punctuation and other characters used to decorate the content, typically to make it more readable to human readers.

+
+
+

+ +'Anchor content should be decimal width' +

+

The message "Anchor content should be decimal width" can be caused by code like:

+
+    xo_emit("{[:mumble}");
+	    

This code should be replaced with code like:

+
+    xo_emit("{[:32}");
+	    

Anchors need an integer value to specify the width of the set of anchored fields. The value can be positive (for left padding/right justification) or negative (for right padding/left justification) and can appear in either the start or stop anchor field descriptor.

+
+
+

+ +'Anchor format should be "%d"' +

+

The message "Anchor format should be "%d"" can be caused by code like:

+
+    xo_emit("{[:/%s}");
+	    

This code should be replaced with code like:

+
+    xo_emit("{[:/%d}");
+	    

Anchors only grok integer values, and if the value is not static, if must be in an 'int' argument, represented by the "%d" format. Anything else is an error.

+
+
+

+ +'Anchor cannot have both format and encoding format")' +

+

The message "Anchor cannot have both format and encoding format")" can be caused by code like:

+
+    xo_emit("{[:32/%d}");
+	    

This code should be replaced with code like:

+
+    xo_emit("{[:32}");
+	    

Anchors can have a static value or argument for the width, but cannot have both.

+
+
+

+ +'Max width only valid for strings' +

+

The message "Max width only valid for strings" can be caused by code like:

+
+    xo_emit("{:tag/%2.4.6d}", 55);
+	    

This code should be replaced with code like:

+
+    xo_emit("{:tag/%2.6d}", 55);
+	    

libxo allows a true 'max width' in addition to the traditional printf-style 'max number of bytes to use for input'. But this is supported only for string values, since it makes no sense for non-strings. This error may occur from a typo, like "{:tag/%6..6d}" where only one period should be used.

+
+
+
+
+
+

+
+11_ 
+Howtos: Focused Directions +

+

This section provides task-oriented instructions for selected tasks. If you have a task that needs instructions, please open a request as an enhancement issue on github.

+

Section Contents:

+ +
+

+
+11.1 
+Howto: Report bugs +

+

libxo uses github to track bugs or request enhancements. Please use the following URL:

+

https://github.com/Juniper/libxo/issues

+
+
+

+
+11.2 
+Howto: Install libxo +

+

libxo is open source, under a new BSD license. Source code is available on github, as are recent releases. To get the most current release, please visit:

+

https://github.com/Juniper/libxo/releases

+

After downloading and untarring the source code, building involves the following steps:

+
+    sh bin/setup.sh
+    cd build
+    ../configure
+    make
+    make test
+    sudo make install
+	    

libxo uses a distinct "build" directory to keep generated files separated from source files.

+

Use "../configure --help" to display available configuration options, which include the following:

+
+  --enable-warnings      Turn on compiler warnings
+  --enable-debug         Turn on debugging
+  --enable-text-only     Turn on text-only rendering
+  --enable-printflike    Enable use of GCC __printflike attribute
+  --disable-libxo-options  Turn off support for LIBXO_OPTIONS
+  --with-gettext=PFX     Specify location of gettext installation
+  --with-libslax-prefix=PFX  Specify location of libslax config
+	    

Compiler warnings are a very good thing, but recent compiler version have added some very pedantic checks. While every attempt is made to keep libxo code warning-free, warnings are now optional. If you are doing development work on libxo, it is required that you use --enable-warnings to keep the code warning free, but most users need not use this option.

+

libxo provides the --enable-text-only option to reduce the footprint of the library for smaller installations. XML, JSON, and HTML rendering logic is removed.

+

The gettext library does not provide a simple means of learning its location, but libxo will look for it in /usr and /opt/local. If installed elsewhere, the installer will need to provide this information using the --with-gettext=/dir/path option.

+

libslax is not required by libxo; it contains the "oxtradoc" program used to format documentation.

+

For additional information, see Section 2.2.

+
+
+

+
+11.3 
+Howto: Convert command line applications +

+
+    How do I convert an existing command line application?
+	    

There are three basic steps for converting command line application to use libxo.

+

+ +

Section Contents:

+ +
+

+
+11.3.1 
+Setting up the context +

+

To use libxo, you'll need to include the "xo.h" header file in your source code files:

+
+    #include <libxo/xo.h>
+	    

In your main() function, you'll need to call xo_parse_args to handling argument parsing (Section 5.4.1). This function removes libxo-specific arguments the program's argv and returns either the number of remaining arguments or -1 to indicate an error.

+
+    int main (int argc, char **argv)
+    {
+        argc = xo_parse_args(argc, argv);
+        if (argc < 0)
+            return argc;
+        ....
+    }
+	    

At the bottom of your main(), you'll need to call xo_finish() to complete output processing for the default handle (Section 5.1). libxo provides the xo_finish_atexit function that is suitable for use with the atexit(3) function.

+
+    atexit(xo_finish_atexit);
+	    
+
+

+
+11.3.2 
+Converting printf Calls +

+

The second task is inspecting code for printf(3) calls and replacing them with xo_emit() calls. The format strings are similar in task, but libxo format strings wrap output fields in braces. The following two calls produce identical text output:

+
+    printf("There are %d %s events\n", count, etype);
+    xo_emit("There are {:count/%d} {:event} events\n", count, etype);
+	    

"count" and "event" are used as names for JSON and XML output. The "count" field uses the format "%d" and "event" uses the default "%s" format. Both are "value" roles, which is the default role.

+

Since text outside of output fields is passed verbatim, other roles are less important, but their proper use can help make output more useful. The "note" and "label" roles allow HTML output to recognize the relationship between text and the associated values, allowing appropriate "hover" and "onclick" behavior. Using the "units" role allows the presentation layer to perform conversions when needed. The "warning" and "error" roles allows use of color and font to draw attention to warnings. The "padding" role makes the use of vital whitespace more clear (Section 3.2.1.6).

+

The "title" role indicates the headings of table and sections. This allows HTML output to use CSS to make this relationship more obvious.

+
+    printf("Statistics:\n");
+    xo_emit("{T:Statistics}:\n");
+	    

The "color" roles controls foreground and background colors, as well as effects like bold and underline (see Section 3.2.1.1).

+
+    xo_emit("{C:bold}required{C:}\n");
+	    

Finally, the start- and stop-anchor roles allow justification and padding over multiple fields (see Section 3.2.1.10).

+
+    snprintf(buf, sizeof(buf), "(%u/%u/%u)", min, ave, max);
+    printf("%30s", buf);
+
+    xo_emit("{[:30}({:minimum/%u}/{:average/%u}/{:maximum/%u}{]:}",
+            min, ave, max);
+	    
+
+

+
+11.3.3 
+Creating Hierarchy +

+

Text output doesn't have any sort of hierarchy, but XML and JSON require this. Typically applications use indentation to represent these relationship:

+
+    printf("table %d\n", tnum);
+    for (i = 0; i < tmax; i++) {
+        printf("    %s %d\n", table[i].name, table[i].size);
+    }
+
+    xo_emit("{T:/table %d}\n", tnum);
+    xo_open_list("table");
+    for (i = 0; i < tmax; i++) {
+        xo_open_instance("table");
+        xo_emit("{P:    }{k:name} {:size/%d}\n",
+                table[i].name, table[i].size);
+        xo_close_instance("table");
+    }
+    xo_close_list("table");
+	    

The open and close list functions are used before and after the list, and the open and close instance functions are used before and after each instance with in the list.

+

Typically these developer looks for a "for" loop as an indication of where to put these calls.

+

In addition, the open and close container functions allow for organization levels of hierarchy.

+
+    printf("Paging information:\n");
+    printf("    Free:      %lu\n", free);
+    printf("    Active:    %lu\n", active);
+    printf("    Inactive:  %lu\n", inactive);
+
+    xo_open_container("paging-information");
+    xo_emit("{P:    }{L:Free:      }{:free/%lu}\n", free);
+    xo_emit("{P:    }{L:Active:    }{:active/%lu}\n", active);
+    xo_emit("{P:    }{L:Inactive:  }{:inactive/%lu}\n", inactive);
+    xo_close_container("paging-information");
+	    
+
+

+
+11.3.4 
+Converting Error Functions +

+

libxo provides variants of the standard error and warning functions, err(3) and warn(3). There are two variants, one for putting the errors on standard error, and the other writes the errors and warnings to the handle using the appropriate encoding style:

+
+    err(1, "cannot open output file: %s", file);
+
+    xo_err(1, "cannot open output file: %s", file);
+    xo_emit_err(1, "cannot open output file: {:filename}", file);
+	    
+
+

+
+11.4 
+Howto: Use "xo" in Shell Scripts +

+
+

+
+11.5 
+Howto: Internationalization (i18n) +

+
+    How do I use libxo to support internationalization?
+	    

libxo allows format and field strings to be used a keys into message catalogs to enable translation into a user's native language by invoking the standard gettext(3) functions.

+

gettext setup is a bit complicated: text strings are extracted from source files into "portable object template" (.pot) files using the "xgettext" command. For each language, this template file is used as the source for a message catalog in the "portable object" (.po) format, which are translated by hand and compiled into "machine object" (.mo) files using the "msgfmt" command. The .mo files are then typically installed in the /usr/share/locale or /opt/local/share/locale directories. At run time, the user's language settings are used to select a .mo file which is searched for matching messages. Text strings in the source code are used as keys to look up the native language strings in the .mo file.

+

Since the xo_emit format string is used as the key into the message catalog, libxo removes unimportant field formatting and modifiers from the format string before use so that minor formatting changes will not impact the expensive translation process. We don't want a developer change such as changing "/%06d" to "/%08d" to force hand inspection of all .po files. The simplified version can be generated for a single message using the "xopo -s <text>" command, or an entire .pot can be translated using the "xopo -f <input> -o <output>" command.

+
+    EXAMPLE:
+        % xopo -s "There are {:count/%u} {:event/%.6s} events\n"
+        There are {:count} {:event} events\n
+
+    Recommended workflow:
+        # Extract text messages
+        xgettext --default-domain=foo --no-wrap \
+            --add-comments --keyword=xo_emit --keyword=xo_emit_h \
+            --keyword=xo_emit_warn -C -E -n --foreign-user \
+            -o foo.pot.raw foo.c
+
+        # Simplify format strings for libxo
+        xopo -f foo.pot.raw -o foo.pot
+
+        # For a new language, just copy the file
+        cp foo.pot po/LC/my_lang/foo.po
+
+        # For an existing language:
+        msgmerge --no-wrap po/LC/my_lang/foo.po \
+                foo.pot -o po/LC/my_lang/foo.po.new
+
+        # Now the hard part: translate foo.po using tools
+        # like poedit or emacs' po-mode
+
+        # Compile the finished file; Use of msgfmt's "-v" option is
+        # strongly encouraged, so that "fuzzy" entries are reported.
+        msgfmt -v -o po/my_lang/LC_MESSAGES/foo.mo po/my_lang/foo.po
+
+        # Install the .mo file
+        sudo cp po/my_lang/LC_MESSAGES/foo.mo \
+                /opt/local/share/locale/my_lang/LC_MESSAGE/
+	    

Once these steps are complete, you can use the "gettext" command to test the message catalog:

+
+    gettext -d foo -e "some text"
+	    

Section Contents:

+ +
+

+
+11.5.1 
+i18n and xo_emit +

+

There are three features used in libxo used to support i18n:

+

+
    +
  • The "{G:}" role looks for a translation of the format string.
  • +
  • The "{g:}" modifier looks for a translation of the field.
  • +
  • The "{p:}" modifier looks for a pluralized version of the field.
  • +
+

Together these three flags allows a single function call to give native language support, as well as libxo's normal XML, JSON, and HTML support.

+
+    printf(gettext("Received %zu %s from {g:server} server\n"),
+           counter, ngettext("byte", "bytes", counter),
+           gettext("web"));
+
+    xo_emit("{G:}Received {:received/%zu} {Ngp:byte,bytes} "
+            "from {g:server} server\n", counter, "web");
+	    

libxo will see the "{G:}" role and will first simplify the format string, removing field formats and modifiers.

+
+    "Received {:received} {N:byte,bytes} from {:server} server\n"
+	    

libxo calls gettext(3) with that string to get a localized version. If your language were Pig Latin, the result might look like:

+
+    "Eceivedray {:received} {N:byte,bytes} omfray "
+               "{:server} erversay\n"
+	    

Note the field names do not change and they should not be translated. The contents of the note ("byte,bytes") should also not be translated, since the "g" modifier will need the untranslated value as the key for the message catalog.

+

The field "{g:server}" requests the rendered value of the field be translated using gettext(3). In this example, "web" would be used.

+

The field "{Ngp:byte,bytes}" shows an example of plural form using the "p" modifier with the "g" modifier. The base singular and plural forms appear inside the field, separated by a comma. At run time, libxo uses the previous field's numeric value to decide which form to use by calling ngettext(3).

+

If a domain name is needed, it can be supplied as the content of the {G:} role. Domain names remain in use throughout the format string until cleared with another domain name.

+
+    printf(dgettext("dns", "Host %s not found: %d(%s)\n"),
+        name, errno, dgettext("strerror", strerror(errno)));
+
+    xo_emit("{G:dns}Host {:hostname} not found: "
+            "%d({G:strerror}{g:%m})\n", name, errno);
+	    
+
+
+
+
+

+
+12_ 
+Examples +

+

Section Contents:

+ +
+

+
+12.1 
+Unit Test +

+

Here is the unit test example:

+
+    int
+    main (int argc, char **argv)
+    {
+        static char base_grocery[] = "GRO";
+        static char base_hardware[] = "HRD";
+        struct item {
+            const char *i_title;
+            int i_sold;
+            int i_instock;
+            int i_onorder;
+            const char *i_sku_base;
+            int i_sku_num;
+        };
+        struct item list[] = {
+            { "gum", 1412, 54, 10, base_grocery, 415 },
+            { "rope", 85, 4, 2, base_hardware, 212 },
+            { "ladder", 0, 2, 1, base_hardware, 517 },
+            { "bolt", 4123, 144, 42, base_hardware, 632 },
+            { "water", 17, 14, 2, base_grocery, 2331 },
+            { NULL, 0, 0, 0, NULL, 0 }
+        };
+        struct item list2[] = {
+            { "fish", 1321, 45, 1, base_grocery, 533 },
+        };
+        struct item *ip;
+        xo_info_t info[] = {
+            { "in-stock", "number", "Number of items in stock" },
+            { "name", "string", "Name of the item" },
+            { "on-order", "number", "Number of items on order" },
+            { "sku", "string", "Stock Keeping Unit" },
+            { "sold", "number", "Number of items sold" },
+            { NULL, NULL, NULL },
+        };
+        int info_count = (sizeof(info) / sizeof(info[0])) - 1;
+
+        argc = xo_parse_args(argc, argv);
+        if (argc < 0)
+            exit(EXIT_FAILURE);
+
+        xo_set_info(NULL, info, info_count);
+
+        xo_open_container_h(NULL, "top");
+
+        xo_open_container("data");
+        xo_open_list("item");
+
+        for (ip = list; ip->i_title; ip++) {
+            xo_open_instance("item");
+
+            xo_emit("{L:Item} '{k:name/%s}':\n", ip->i_title);
+            xo_emit("{P:   }{L:Total sold}: {n:sold/%u%s}\n",
+                    ip->i_sold, ip->i_sold ? ".0" : "");
+            xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n", 
+                    ip->i_instock);
+            xo_emit("{P:   }{Lwc:On order}{:on-order/%u}\n", 
+                    ip->i_onorder);
+            xo_emit("{P:   }{L:SKU}: {q:sku/%s-000-%u}\n",
+                    ip->i_sku_base, ip->i_sku_num);
+
+            xo_close_instance("item");
+        }
+
+        xo_close_list("item");
+        xo_close_container("data");
+
+        xo_open_container("data");
+        xo_open_list("item");
+
+        for (ip = list2; ip->i_title; ip++) {
+            xo_open_instance("item");
+
+            xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title);
+            xo_emit("{P:   }{L:Total sold}: {n:sold/%u%s}\n",
+                    ip->i_sold, ip->i_sold ? ".0" : "");
+            xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n", 
+                    ip->i_instock);
+            xo_emit("{P:   }{Lwc:On order}{:on-order/%u}\n", 
+                    ip->i_onorder);
+            xo_emit("{P:   }{L:SKU}: {q:sku/%s-000-%u}\n",
+                    ip->i_sku_base, ip->i_sku_num);
+
+            xo_close_instance("item");
+        }
+
+        xo_close_list("item");
+        xo_close_container("data");
+
+        xo_close_container_h(NULL, "top");
+
+        return 0;
+    }
+	    

Text output:

+
+    % ./testxo --libxo text
+    Item 'gum':
+       Total sold: 1412.0
+       In stock: 54
+       On order: 10
+       SKU: GRO-000-415
+    Item 'rope':
+       Total sold: 85.0
+       In stock: 4
+       On order: 2
+       SKU: HRD-000-212
+    Item 'ladder':
+       Total sold: 0
+       In stock: 2
+       On order: 1
+       SKU: HRD-000-517
+    Item 'bolt':
+       Total sold: 4123.0
+       In stock: 144
+       On order: 42
+       SKU: HRD-000-632
+    Item 'water':
+       Total sold: 17.0
+       In stock: 14
+       On order: 2
+       SKU: GRO-000-2331
+    Item 'fish':
+       Total sold: 1321.0
+       In stock: 45
+       On order: 1
+       SKU: GRO-000-533
+	    

JSON output:

+
+    % ./testxo --libxo json,pretty
+    "top": {
+      "data": {
+        "item": [
+          {
+            "name": "gum",
+            "sold": 1412.0,
+            "in-stock": 54,
+            "on-order": 10,
+            "sku": "GRO-000-415"
+          },
+          {
+            "name": "rope",
+            "sold": 85.0,
+            "in-stock": 4,
+            "on-order": 2,
+            "sku": "HRD-000-212"
+          },
+          {
+            "name": "ladder",
+            "sold": 0,
+            "in-stock": 2,
+            "on-order": 1,
+            "sku": "HRD-000-517"
+          },
+          {
+            "name": "bolt",
+            "sold": 4123.0,
+            "in-stock": 144,
+            "on-order": 42,
+            "sku": "HRD-000-632"
+          },
+          {
+            "name": "water",
+            "sold": 17.0,
+            "in-stock": 14,
+            "on-order": 2,
+            "sku": "GRO-000-2331"
+          }
+        ]
+      },
+      "data": {
+        "item": [
+          {
+            "name": "fish",
+            "sold": 1321.0,
+            "in-stock": 45,
+            "on-order": 1,
+            "sku": "GRO-000-533"
+          }
+        ]
+      }
+    }
+	    

XML output:

+
+    % ./testxo --libxo pretty,xml
+    <top>
+      <data>
+        <item>
+          <name>gum</name>
+          <sold>1412.0</sold>
+          <in-stock>54</in-stock>
+          <on-order>10</on-order>
+          <sku>GRO-000-415</sku>
+        </item>
+        <item>
+          <name>rope</name>
+          <sold>85.0</sold>
+          <in-stock>4</in-stock>
+          <on-order>2</on-order>
+          <sku>HRD-000-212</sku>
+        </item>
+        <item>
+          <name>ladder</name>
+          <sold>0</sold>
+          <in-stock>2</in-stock>
+          <on-order>1</on-order>
+          <sku>HRD-000-517</sku>
+        </item>
+        <item>
+          <name>bolt</name>
+          <sold>4123.0</sold>
+          <in-stock>144</in-stock>
+          <on-order>42</on-order>
+          <sku>HRD-000-632</sku>
+        </item>
+        <item>
+          <name>water</name>
+          <sold>17.0</sold>
+          <in-stock>14</in-stock>
+          <on-order>2</on-order>
+          <sku>GRO-000-2331</sku>
+        </item>
+      </data>
+      <data>
+        <item>
+          <name>fish</name>
+          <sold>1321.0</sold>
+          <in-stock>45</in-stock>
+          <on-order>1</on-order>
+          <sku>GRO-000-533</sku>
+        </item>
+      </data>
+    </top>
+	    

HMTL output:

+
+    % ./testxo --libxo pretty,html
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name">gum</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold">1412.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock">54</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order">10</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku">GRO-000-415</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name">rope</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold">85.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock">4</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order">2</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku">HRD-000-212</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name">ladder</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold">0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock">2</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order">1</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku">HRD-000-517</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name">bolt</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold">4123.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock">144</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order">42</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku">HRD-000-632</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name">water</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold">17.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock">14</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order">2</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku">GRO-000-2331</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name">fish</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold">1321.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock">45</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order">1</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku">GRO-000-533</div>
+    </div>
+	    

HTML output with xpath and info flags:

+
+    % ./testxo --libxo pretty,html,xpath,info
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name"
+           data-xpath="/top/data/item/name" data-type="string"
+           data-help="Name of the item">gum</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold"
+           data-xpath="/top/data/item/sold" data-type="number"
+           data-help="Number of items sold">1412.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock"
+           data-xpath="/top/data/item/in-stock" data-type="number"
+           data-help="Number of items in stock">54</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order"
+           data-xpath="/top/data/item/on-order" data-type="number"
+           data-help="Number of items on order">10</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku"
+           data-xpath="/top/data/item/sku" data-type="string"
+           data-help="Stock Keeping Unit">GRO-000-415</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name"
+           data-xpath="/top/data/item/name" data-type="string"
+           data-help="Name of the item">rope</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold"
+           data-xpath="/top/data/item/sold" data-type="number"
+           data-help="Number of items sold">85.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock"
+           data-xpath="/top/data/item/in-stock" data-type="number"
+           data-help="Number of items in stock">4</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order"
+           data-xpath="/top/data/item/on-order" data-type="number"
+           data-help="Number of items on order">2</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku"
+           data-xpath="/top/data/item/sku" data-type="string"
+           data-help="Stock Keeping Unit">HRD-000-212</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name"
+           data-xpath="/top/data/item/name" data-type="string"
+           data-help="Name of the item">ladder</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold"
+           data-xpath="/top/data/item/sold" data-type="number"
+           data-help="Number of items sold">0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock"
+           data-xpath="/top/data/item/in-stock" data-type="number"
+           data-help="Number of items in stock">2</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order"
+           data-xpath="/top/data/item/on-order" data-type="number"
+           data-help="Number of items on order">1</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku"
+           data-xpath="/top/data/item/sku" data-type="string"
+           data-help="Stock Keeping Unit">HRD-000-517</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name"
+           data-xpath="/top/data/item/name" data-type="string"
+           data-help="Name of the item">bolt</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold"
+           data-xpath="/top/data/item/sold" data-type="number"
+           data-help="Number of items sold">4123.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock"
+           data-xpath="/top/data/item/in-stock" data-type="number"
+           data-help="Number of items in stock">144</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order"
+           data-xpath="/top/data/item/on-order" data-type="number"
+           data-help="Number of items on order">42</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku"
+           data-xpath="/top/data/item/sku" data-type="string"
+           data-help="Stock Keeping Unit">HRD-000-632</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name"
+           data-xpath="/top/data/item/name" data-type="string"
+           data-help="Name of the item">water</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold"
+           data-xpath="/top/data/item/sold" data-type="number"
+           data-help="Number of items sold">17.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock"
+           data-xpath="/top/data/item/in-stock" data-type="number"
+           data-help="Number of items in stock">14</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order"
+           data-xpath="/top/data/item/on-order" data-type="number"
+           data-help="Number of items on order">2</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku"
+           data-xpath="/top/data/item/sku" data-type="string"
+           data-help="Stock Keeping Unit">GRO-000-2331</div>
+    </div>
+    <div class="line">
+      <div class="label">Item</div>
+      <div class="text"> '</div>
+      <div class="data" data-tag="name"
+           data-xpath="/top/data/item/name" data-type="string"
+           data-help="Name of the item">fish</div>
+      <div class="text">':</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">Total sold</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sold"
+           data-xpath="/top/data/item/sold" data-type="number"
+           data-help="Number of items sold">1321.0</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">In stock</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="in-stock"
+           data-xpath="/top/data/item/in-stock" data-type="number"
+           data-help="Number of items in stock">45</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">On order</div>
+      <div class="decoration">:</div>
+      <div class="padding"> </div>
+      <div class="data" data-tag="on-order"
+           data-xpath="/top/data/item/on-order" data-type="number"
+           data-help="Number of items on order">1</div>
+    </div>
+    <div class="line">
+      <div class="padding">   </div>
+      <div class="label">SKU</div>
+      <div class="text">: </div>
+      <div class="data" data-tag="sku"
+           data-xpath="/top/data/item/sku" data-type="string"
+           data-help="Stock Keeping Unit">GRO-000-533</div>
+    </div>
+	    
+
+
+
+
+

Author's Address

+
+Phil ShaferJuniper NetworksEMail: +
+
+ + Property changes on: vendor/Juniper/libxo/0.8.2/doc/libxo-manual.html ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/html \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/doc/libxo.txt =================================================================== --- vendor/Juniper/libxo/0.8.2/doc/libxo.txt (nonexistent) +++ vendor/Juniper/libxo/0.8.2/doc/libxo.txt (revision 319998) @@ -0,0 +1,3995 @@ +# +# Copyright (c) 2014, Juniper Networks, Inc. +# All rights reserved. +# This SOFTWARE is licensed under the LICENSE provided in the +# ../Copyright file. By downloading, installing, copying, or +# using the SOFTWARE, you agree to be bound by the terms of that +# LICENSE. +# Phil Shafer, July 2014 +# + +* Overview + +libxo - A Library for Generating Text, XML, JSON, and HTML Output + +You want to prepare for the future, but you need to live in the +present. You'd love a flying car, but need to get to work today. You +want to support features like XML, JSON, and HTML rendering to allow +integration with NETCONF, REST, and web browsers, but you need to make +text output for command line users. + +And you don't want multiple code paths that can't help but get out of +sync: + + /* None of this "if (xml) {... } else {...}" logic */ + if (xml) { + /* some code to make xml*/ + } else { + /* other code to make text */ + /* oops forgot to add something on both clauses! */ + } + + /* And ifdefs are right out. */ + #ifdef MAKE_XML + /* icky */ + #else + /* pooh */ + #endif + +But you'd really, really like all the fancy features that modern +encoding formats can provide. libxo can help. + +The libxo library allows an application to generate text, XML, JSON, +and HTML output using a common set of function calls. The application +decides at run time which output style should be produced. The +application calls a function "xo_emit" to product output that is +described in a format string. A "field descriptor" tells libxo what +the field is and what it means. Each field descriptor is placed in +braces with a printf-like format string (^format-strings^): + + xo_emit(" {:lines/%7ju} {:words/%7ju} " + "{:characters/%7ju} {d:filename/%s}\n", + linect, wordct, charct, file); + +Each field can have a role, with the 'value' role being the default, +and the role tells libxo how and when to render that field (see +^field-roles^ for details). Modifiers change how the field is +rendered in different output styles (see ^field-modifiers^ for +details. Output can then be generated in various style, using the +"--libxo" option: + + % wc /etc/motd + 25 165 1140 /etc/motd + % wc --libxo xml,pretty,warn /etc/motd + + + 25 + 165 + 1140 + /etc/motd + + + % wc --libxo json,pretty,warn /etc/motd + { + "wc": { + "file": [ + { + "lines": 25, + "words": 165, + "characters": 1140, + "filename": "/etc/motd" + } + ] + } + } + % wc --libxo html,pretty,warn /etc/motd +
+
+
25
+
+
165
+
+
1140
+
+
/etc/motd
+
+ +Same code path, same format strings, same information, but it's +rendered in distinct styles based on run-time flags. + +* Getting libxo + +libxo now ships as part of the FreeBSD Operating System (as of -11). + +libxo lives on github as: + + https://github.com/Juniper/libxo + +The latest release of libxo is available at: + + https://github.com/Juniper/libxo/releases + +We are following the branching scheme from +^http://nvie.com/posts/a-successful-git-branching-model/^ which means +we will do development under the "develop" branch, and release from +the "master" branch. To clone a developer tree, run the following +command: + + git clone https://github.com/Juniper/libxo.git -b develop + +We're using semantic release numbering, as defined in +^http://semver.org/spec/v2.0.0.html^. + +libxo is open source, distributed under the BSD license. It shipped +as part of the FreeBSD operating system starting with release 11.0. + +Issues, problems, and bugs should be directly to the issues page on +our github site. + +** Downloading libxo Source Code + +You can retrieve the source for libxo in two ways: + +A) Use a "distfile" for a specific release. We use +github to maintain our releases. Visit +github release page (^https://github.com/Juniper/libxo/releases^) +to see the list of releases. To download the latest, look for the +release with the green "Latest release" button and the green +"libxo-RELEASE.tar.gz" button under that section. + +After downloading that release's distfile, untar it as follows: + + tar -zxf libxo-RELEASE.tar.gz + cd libxo-RELEASE + +[Note: for Solaris users, your "tar" command lacks the "-z" flag, +so you'll need to substitute "gzip -dc "file" | tar xf -" instead of +"tar -zxf "file"".] + +B) Use the current build from github. This gives you the most recent +source code, which might be less stable than a specific release. To +build libxo from the git repo: + + git clone https://github.com/Juniper/libxo.git + cd libxo + +_BE AWARE_: The github repository does _not_ contain the files +generated by "autoreconf", with the notable exception of the "m4" +directory. Since these files (depcomp, configure, missing, +install-sh, etc) are generated files, we keep them out of the source +code repository. + +This means that if you download the a release distfile, these files +will be ready and you'll just need to run "configure", but if you +download the source code from svn, then you'll need to run +"autoreconf" by hand. This step is done for you by the "setup.sh" +script, described in the next section. + +** Building libxo + +To build libxo, you'll need to set up the build, run the "configure" +script, run the "make" command, and run the regression tests. + +The following is a summary of the commands needed. These commands are +explained in detail in the rest of this section. + + sh bin/setup.sh + cd build + ../configure + make + make test + sudo make install + +The following sections will walk through each of these steps with +additional details and options, but the above directions should be all +that's needed. + +*** Setting up the build + +[If you downloaded a distfile, you can skip this step.] + +Run the "setup.sh" script to set up the build. This script runs the +"autoreconf" command to generate the "configure" script and other +generated files. + + sh bin/setup.sh + +Note: We're are currently using autoreconf version 2.69. + +*** Running the "configure" Script + +Configure (and autoconf in general) provides a means of building +software in diverse environments. Our configure script supports +a set of options that can be used to adjust to your operating +environment. Use "configure --help" to view these options. + +We use the "build" directory to keep object files and generated files +away from the source tree. + +To run the configure script, change into the "build" directory, and +run the "configure" script. Add any required options to the +"../configure" command line. + + cd build + ../configure + +Expect to see the "configure" script generate the following error: + + /usr/bin/rm: cannot remove `libtoolT': No such file or directory + +This error is harmless and can be safely ignored. + +By default, libxo installs architecture-independent files, including +extension library files, in the /usr/local directories. To specify an +installation prefix other than /usr/local for all installation files, +include the --prefix=prefix option and specify an alternate +location. To install just the extension library files in a different, +user-defined location, include the --with-extensions-dir=dir option +and specify the location where the extension libraries will live. + + cd build + ../configure [OPTION]... [VAR=VALUE]... + +**** Running the "make" command + +Once the "configure" script is run, build the images using the "make" +command: + + make + +**** Running the Regression Tests + +libxo includes a set of regression tests that can be run to ensure +the software is working properly. These test are optional, but will +help determine if there are any issues running libxo on your +machine. To run the regression tests: + + make test + +*** Installing libxo + +Once the software is built, you'll need to install libxo using the +"make install" command. If you are the root user, or the owner of the +installation directory, simply issue the command: + + make install + +If you are not the "root" user and are using the "sudo" package, use: + + sudo make install + +Verify the installation by viewing the output of "xo --version": + + % xo --version + libxo version 0.3.5-git-develop + xo version 0.3.5-git-develop + +* Formatting with libxo + +Most unix commands emit text output aimed at humans. It is designed +to be parsed and understood by a user. Humans are gifted at +extracting details and pattern matching in such output. Often +programmers need to extract information from this human-oriented +output. Programmers use tools like grep, awk, and regular expressions +to ferret out the pieces of information they need. Such solutions are +fragile and require maintenance when output contents change or evolve, +along with testing and validation. + +Modern tool developers favor encoding schemes like XML and JSON, +which allow trivial parsing and extraction of data. Such formats are +simple, well understood, hierarchical, easily parsed, and often +integrate easier with common tools and environments. Changes to +content can be done in ways that do not break existing users of the +data, which can reduce maintenance costs and increase feature velocity. + +In addition, modern reality means that more output ends up in web +browsers than in terminals, making HTML output valuable. + +libxo allows a single set of function calls in source code to generate +traditional text output, as well as XML and JSON formatted data. HTML +can also be generated; "
" elements surround the traditional text +output, with attributes that detail how to render the data. + +A single libxo function call in source code is all that's required: + + xo_emit("Connecting to {:host}.{:domain}...\n", host, domain); + + TEXT: + Connecting to my-box.example.com... + XML: + my-box + example.com + JSON: + "host": "my-box", + "domain": "example.com" + HTML: +
+
Connecting to
+
my-box
+
.
+
example.com
+
...
+
+ +** Encoding Styles + +There are four encoding styles supported by libxo: + +- TEXT output can be display on a terminal session, allowing +compatibility with traditional command line usage. +- XML output is suitable for tools like XPath and protocols like +NETCONF. +- JSON output can be used for RESTful APIs and integration with +languages like Javascript and Python. +- HTML can be matched with a small CSS file to permit rendering in any +HTML5 browser. + +In general, XML and JSON are suitable for encoding data, while TEXT is +suited for terminal output and HTML is suited for display in a web +browser (see ^xohtml^). + +*** Text Output + +Most traditional programs generate text output on standard output, +with contents like: + + 36 ./src + 40 ./bin + 90 . + +In this example (taken from du source code), the code to generate this +data might look like: + + printf("%d\t%s\n", num_blocks, path); + +Simple, direct, obvious. But it's only making text output. Imagine +using a single code path to make TEXT, XML, JSON or HTML, deciding at +run time which to generate. + +libxo expands on the idea of printf format strings to make a single +format containing instructions for creating multiple output styles: + + xo_emit("{:blocks/%d}\t{:path/%s}\n", num_blocks, path); + +This line will generate the same text output as the earlier printf +call, but also has enough information to generate XML, JSON, and HTML. + +The following sections introduce the other formats. + +*** XML Output + +XML output consists of a hierarchical set of elements, each encoded +with a start tag and an end tag. The element should be named for data +value that it is encoding: + + + 36 + ./src + + + 40 + ./bin + + + 90 + . + + +XML is a W3C standard for encoding data. See w3c.org/TR/xml for +additional information. + +*** JSON Output + +JSON output consists of a hierarchical set of objects and lists, each +encoded with a quoted name, a colon, and a value. If the value is a +string, it must be quoted, but numbers are not quoted. Objects are +encoded using braces; lists are encoded using square brackets. +Data inside objects and lists is separated using commas: + + items: [ + { "blocks": 36, "path" : "./src" }, + { "blocks": 40, "path" : "./bin" }, + { "blocks": 90, "path" : "./" } + ] + +*** HTML Output + +HTML output is designed to allow the output to be rendered in a web +browser with minimal effort. Each piece of output data is rendered +inside a
element, with a class name related to the role of the +data. By using a small set of class attribute values, a CSS +stylesheet can render the HTML into rich text that mirrors the +traditional text content. + +Additional attributes can be enabled to provide more details about the +data, including data type, description, and an XPath location. + +
+
36
+
+
./src
+
+
+
40
+
+
./bin
+
+
+
90
+
+
./
+
+ +** Format Strings @format-strings@ + +libxo uses format strings to control the rendering of data into the +various output styles. Each format string contains a set of zero or +more field descriptions, which describe independent data fields. Each +field description contains a set of modifiers, a content string, and +zero, one, or two format descriptors. The modifiers tell libxo what +the field is and how to treat it, while the format descriptors are +formatting instructions using printf-style format strings, telling +libxo how to format the field. The field description is placed inside +a set of braces, with a colon (":") after the modifiers and a slash +("/") before each format descriptors. Text may be intermixed with +field descriptions within the format string. + +The field description is given as follows: + + '{' [ role | modifier ]* [',' long-names ]* ':' [ content ] + [ '/' field-format [ '/' encoding-format ]] '}' + +The role describes the function of the field, while the modifiers +enable optional behaviors. The contents, field-format, and +encoding-format are used in varying ways, based on the role. These +are described in the following sections. + +In the following example, three field descriptors appear. The first +is a padding field containing three spaces of padding, the second is a +label ("In stock"), and the third is a value field ("in-stock"). The +in-stock field has a "%u" format that will parse the next argument +passed to the xo_emit function as an unsigned integer. + + xo_emit("{P: }{Lwc:In stock}{:in-stock/%u}\n", 65); + +This single line of code can generate text (" In stock: 65\n"), XML +("65"), JSON ('"in-stock": 6'), or HTML (too +lengthy to be listed here). + +While roles and modifiers typically use single character for brevity, +there are alternative names for each which allow more verbose +formatting strings. These names must be preceded by a comma, and may +follow any single-character values: + + xo_emit("{L,white,colon:In stock}{,key:in-stock/%u}\n", 65); + +*** Field Roles + +Field roles are optional, and indicate the role and formatting of the +content. The roles are listed below; only one role is permitted: + +|---+--------------+-------------------------------------------------| +| R | Name | Description | +|---+--------------+-------------------------------------------------| +| C | color | Field has color and effect controls | +| D | decoration | Field is non-text (e.g., colon, comma) | +| E | error | Field is an error message | +| G | gettext | Call gettext(3) on the format string | +| L | label | Field is text that prefixes a value | +| N | note | Field is text that follows a value | +| P | padding | Field is spaces needed for vertical alignment | +| T | title | Field is a title value for headings | +| U | units | Field is the units for the previous value field | +| V | value | Field is the name of field (the default) | +| W | warning | Field is a warning message | +| [ | start-anchor | Begin a section of anchored variable-width text | +| ] | stop-anchor | End a section of anchored variable-width text | +|---+--------------+-------------------------------------------------| + + EXAMPLE: + xo_emit("{L:Free}{D::}{P: }{:free/%u} {U:Blocks}\n", + free_blocks); + +When a role is not provided, the "value" role is used as the default. + +Roles and modifiers can also use more verbose names, when preceded by +a comma: + + EXAMPLE: + xo_emit("{,label:Free}{,decoration::}{,padding: }" + "{,value:free/%u} {,units:Blocks}\n", + free_blocks); + +**** The Color Role ({C:}) @color-role@ + +Colors and effects control how text values are displayed; they are +used for display styles (TEXT and HTML). + + xo_emit("{C:bold}{:value}{C:no-bold}\n", value); + +Colors and effects remain in effect until modified by other "C"-role +fields. + + xo_emit("{C:bold}{C:inverse}both{C:no-bold}only inverse\n"); + +If the content is empty, the "reset" action is performed. + + xo_emit("{C:both,underline}{:value}{C:}\n", value); + +The content should be a comma-separated list of zero or more colors or +display effects. + + xo_emit("{C:bold,inverse}Ugly{C:no-bold,no-inverse}\n"); + +The color content can be either static, when placed directly within +the field descriptor, or a printf-style format descriptor can be used, +if preceded by a slash ("/"): + + xo_emit("{C:/%s%s}{:value}{C:}", need_bold ? "bold" : "", + need_underline ? "underline" : "", value); + +Color names are prefixed with either "fg-" or "bg-" to change the +foreground and background colors, respectively. + + xo_emit("{C:/fg-%s,bg-%s}{Lwc:Cost}{:cost/%u}{C:reset}\n", + fg_color, bg_color, cost); + +The following table lists the supported effects: + +|---------------+-------------------------------------------------| +| Name | Description | +|---------------+-------------------------------------------------| +| bg-XXXXX | Change background color | +| bold | Start bold text effect | +| fg-XXXXX | Change foreground color | +| inverse | Start inverse (aka reverse) text effect | +| no-bold | Stop bold text effect | +| no-inverse | Stop inverse (aka reverse) text effect | +| no-underline | Stop underline text effect | +| normal | Reset effects (only) | +| reset | Reset colors and effects (restore defaults) | +| underline | Start underline text effect | +|---------------+-------------------------------------------------| + +The following color names are supported: + +|---------+--------------------------------------------| +| Name | Description | +|---------+--------------------------------------------| +| black | | +| blue | | +| cyan | | +| default | Default color for foreground or background | +| green | | +| magenta | | +| red | | +| white | | +| yellow | | +|---------+--------------------------------------------| + +When using colors, the developer should remember that users will +change the foreground and background colors of terminal session +according to their own tastes, so assuming that "blue" looks nice is +never safe, and is a constant annoyance to your dear author. In +addition, a significant percentage of users (1 in 12) will be color +blind. Depending on color to convey critical information is not a +good idea. Color should enhance output, but should not be used as the +sole means of encoding information. + +**** The Decoration Role ({D:}) + +Decorations are typically punctuation marks such as colons, +semi-colons, and commas used to decorate the text and make it simpler +for human readers. By marking these distinctly, HTML usage scenarios +can use CSS to direct their display parameters. + + xo_emit("{D:((}{:name}{D:))}\n", name); + +**** The Gettext Role ({G:}) @gettext-role@ + +libxo supports internationalization (i18n) through its use of +gettext(3). Use the "{G:}" role to request that the remaining part of +the format string, following the "{G:}" field, be handled using +gettext(). + +Since gettext() uses the string as the key into the message catalog, +libxo uses a simplified version of the format string that removes +unimportant field formatting and modifiers, stopping minor formatting +changes from impacting the expensive translation process. A developer +change such as changing "/%06d" to "/%08d" should not force hand +inspection of all .po files. + +The simplified version can be generated for a single message using the +"xopo -s " command, or an entire .pot can be translated using +the "xopo -f -o " command. + + xo_emit("{G:}Invalid token\n"); + +The {G:} role allows a domain name to be set. gettext calls will +continue to use that domain name until the current format string +processing is complete, enabling a library function to emit strings +using it's own catalog. The domain name can be either static as the +content of the field, or a format can be used to get the domain name +from the arguments. + + xo_emit("{G:libc}Service unavailable in restricted mode\n"); + +See ^howto-i18n^ for additional details. + +**** The Label Role ({L:}) + +Labels are text that appears before a value. + + xo_emit("{Lwc:Cost}{:cost/%u}\n", cost); + +**** The Note Role ({N:}) + +Notes are text that appears after a value. + + xo_emit("{:cost/%u} {N:per year}\n", cost); + +**** The Padding Role ({P:}) @padding-role@ + +Padding represents whitespace used before and between fields. + +The padding content can be either static, when placed directly within +the field descriptor, or a printf-style format descriptor can be used, +if preceded by a slash ("/"): + + xo_emit("{P: }{Lwc:Cost}{:cost/%u}\n", cost); + xo_emit("{P:/%30s}{Lwc:Cost}{:cost/%u}\n", "", cost); + +**** The Title Role ({T:}) + +Title are heading or column headers that are meant to be displayed to +the user. The title can be either static, when placed directly within +the field descriptor, or a printf-style format descriptor can be used, +if preceded by a slash ("/"): + + xo_emit("{T:Interface Statistics}\n"); + xo_emit("{T:/%20.20s}{T:/%6.6s}\n", "Item Name", "Cost"); + +Title fields have an extra convenience feature; if both content and +format are specified, instead of looking to the argument list for a +value, the content is used, allowing a mixture of format and content +within the field descriptor: + + xo_emit("{T:Name/%20s}{T:Count/%6s}\n"); + +Since the incoming argument is a string, the format must be "%s" or +something suitable. + +**** The Units Role ({U:}) + +Units are the dimension by which values are measured, such as degrees, +miles, bytes, and decibels. The units field carries this information +for the previous value field. + + xo_emit("{Lwc:Distance}{:distance/%u}{Uw:miles}\n", miles); + +Note that the sense of the 'w' modifier is reversed for units; +a blank is added before the contents, rather than after it. + +When the XOF_UNITS flag is set, units are rendered in XML as the +"units" attribute: + + 50 + +Units can also be rendered in HTML as the "data-units" attribute: + +
50
+ +**** The Value Role ({V:} and {:}) + +The value role is used to represent the a data value that is +interesting for the non-display output styles (XML and JSON). Value +is the default role; if no other role designation is given, the field +is a value. The field name must appear within the field descriptor, +followed by one or two format descriptors. The first format +descriptor is used for display styles (TEXT and HTML), while the +second one is used for encoding styles (XML and JSON). If no second +format is given, the encoding format defaults to the first format, +with any minimum width removed. If no first format is given, both +format descriptors default to "%s". + + xo_emit("{:length/%02u}x{:width/%02u}x{:height/%02u}\n", + length, width, height); + xo_emit("{:author} wrote \"{:poem}\" in {:year/%4d}\n, + author, poem, year); + +**** The Anchor Roles ({[:} and {]:}) @anchor-role@ + +The anchor roles allow a set of strings by be padded as a group, +but still be visible to xo_emit as distinct fields. Either the start +or stop anchor can give a field width and it can be either directly in +the descriptor or passed as an argument. Any fields between the start +and stop anchor are padded to meet the minimum width given. + +To give a width directly, encode it as the content of the anchor tag: + + xo_emit("({[:10}{:min/%d}/{:max/%d}{]:})\n", min, max); + +To pass a width as an argument, use "%d" as the format, which must +appear after the "/". Note that only "%d" is supported for widths. +Using any other value could ruin your day. + + xo_emit("({[:/%d}{:min/%d}/{:max/%d}{]:})\n", width, min, max); + +If the width is negative, padding will be added on the right, suitable +for left justification. Otherwise the padding will be added to the +left of the fields between the start and stop anchors, suitable for +right justification. If the width is zero, nothing happens. If the +number of columns of output between the start and stop anchors is less +than the absolute value of the given width, nothing happens. + +Widths over 8k are considered probable errors and not supported. If +XOF_WARN is set, a warning will be generated. + +*** Field Modifiers + +Field modifiers are flags which modify the way content emitted for +particular output styles: + +|---+---------------+--------------------------------------------------| +| M | Name | Description | +|---+---------------+--------------------------------------------------| +| a | argument | The content appears as a 'const char *' argument | +| c | colon | A colon (":") is appended after the label | +| d | display | Only emit field for display styles (text/HTML) | +| e | encoding | Only emit for encoding styles (XML/JSON) | +| g | gettext | Call gettext on field's render content | +| h | humanize (hn) | Format large numbers in human-readable style | +| | hn-space | Humanize: Place space between numeric and unit | +| | hn-decimal | Humanize: Add a decimal digit, if number < 10 | +| | hn-1000 | Humanize: Use 1000 as divisor instead of 1024 | +| k | key | Field is a key, suitable for XPath predicates | +| l | leaf-list | Field is a leaf-list | +| n | no-quotes | Do not quote the field when using JSON style | +| p | plural | Gettext: Use comma-separated plural form | +| q | quotes | Quote the field when using JSON style | +| t | trim | Trim leading and trailing whitespace | +| w | white | A blank (" ") is appended after the label | +|---+---------------+--------------------------------------------------| + +Roles and modifiers can also use more verbose names, when preceded by +a comma. For example, the modifier string "Lwc" (or "L,white,colon") +means the field has a label role (text that describes the next field) +and should be followed by a colon ('c') and a space ('w'). The +modifier string "Vkq" (or ":key,quote") means the field has a value +role (the default role), that it is a key for the current instance, +and that the value should be quoted when encoded for JSON. + +**** The Argument Modifier ({a:}) + +The argument modifier indicates that the content of the field +descriptor will be placed as a UTF-8 string (const char *) argument +within the xo_emit parameters. + + EXAMPLE: + xo_emit("{La:} {a:}\n", "Label text", "label", "value"); + TEXT: + Label text value + JSON: + "label": "value" + XML: + + +The argument modifier allows field names for value fields to be passed +on the stack, avoiding the need to build a field descriptor using +snprintf. For many field roles, the argument modifier is not needed, +since those roles have specific mechanisms for arguments, such as +"{C:fg-%s}". + +**** The Colon Modifier ({c:}) + +The colon modifier appends a single colon to the data value: + + EXAMPLE: + xo_emit("{Lc:Name}{:name}\n", "phil"); + TEXT: + Name:phil + +The colon modifier is only used for the TEXT and HTML output +styles. It is commonly combined with the space modifier ('{w:}'). +It is purely a convenience feature. + +**** The Display Modifier ({d:}) + +The display modifier indicated the field should only be generated for +the display output styles, TEXT and HTML. + + EXAMPLE: + xo_emit("{Lcw:Name}{d:name} {:id/%d}\n", "phil", 1); + TEXT: + Name: phil 1 + XML: + 1 + +The display modifier is the opposite of the encoding modifier, and +they are often used to give to distinct views of the underlying data. + +**** The Encoding Modifier ({e:}) @e-modifier@ + +The display modifier indicated the field should only be generated for +the display output styles, TEXT and HTML. + + EXAMPLE: + xo_emit("{Lcw:Name}{:name} {e:id/%d}\n", "phil", 1); + TEXT: + Name: phil + XML: + phil1 + +The encoding modifier is the opposite of the display modifier, and +they are often used to give to distinct views of the underlying data. + +**** The Gettext Modifier ({g:}) @gettext-modifier@ + +The gettext modifier is used to translate individual fields using the +gettext domain (typically set using the "{G:}" role) and current +language settings. Once libxo renders the field value, it is passed +to gettext(3), where it is used as a key to find the native language +translation. + +In the following example, the strings "State" and "full" are passed +to gettext() to find locale-based translated strings. + + xo_emit("{Lgwc:State}{g:state}\n", "full"); + +See ^gettext-role^, ^plural-modifier^, and ^howto-i18n^ for additional +details. + +**** The Humanize Modifier ({h:}) + +The humanize modifier is used to render large numbers as in a +human-readable format. While numbers like "44470272" are completely +readable to computers and savants, humans will generally find "44M" +more meaningful. + +"hn" can be used as an alias for "humanize". + +The humanize modifier only affects display styles (TEXT and HMTL). +The "no-humanize" option (See ^options^) will block the function of +the humanize modifier. + +There are a number of modifiers that affect details of humanization. +These are only available in as full names, not single characters. The +"hn-space" modifier places a space between the number and any +multiplier symbol, such as "M" or "K" (ex: "44 K"). The "hn-decimal" +modifier will add a decimal point and a single tenths digit when the number is +less than 10 (ex: "4.4K"). The "hn-1000" modifier will use 1000 as divisor +instead of 1024, following the JEDEC-standard instead of the more +natural binary powers-of-two tradition. + + EXAMPLE: + xo_emit("{h:input/%u}, {h,hn-space:output/%u}, " + "{h,hn-decimal:errors/%u}, {h,hn-1000:capacity/%u}, " + "{h,hn-decimal:remaining/%u}\n", + input, output, errors, capacity, remaining); + TEXT: + 21, 57 K, 96M, 44M, 1.2G + +In the HTML style, the original numeric value is rendered in the +"data-number" attribute on the
element: + +
96M
+ +**** The Key Modifier ({k:}) + +The key modifier is used to indicate that a particular field helps +uniquely identify an instance of list data. + + EXAMPLE: + xo_open_list("user"); + for (i = 0; i < num_users; i++) { + xo_open_instance("user"); + xo_emit("User {k:name} has {:count} tickets\n", + user[i].u_name, user[i].u_tickets); + xo_close_instance("user"); + } + xo_close_list("user"); + +Currently the key modifier is only used when generating XPath value +for the HTML output style when XOF_XPATH is set, but other uses are +likely in the near future. + +**** The Leaf-List Modifier ({l:}) + +The leaf-list modifier is used to distinguish lists where each +instance consists of only a single value. In XML, these are +rendered as single elements, where JSON renders them as arrays. + + EXAMPLE: + for (i = 0; i < num_users; i++) { + xo_emit("Member {l:user}\n", user[i].u_name); + } + XML: + phil + pallavi + JSON: + "user": [ "phil", "pallavi" ] + +The name of the field must match the name of the leaf list. + +**** The No-Quotes Modifier ({n:}) + +The no-quotes modifier (and its twin, the 'quotes' modifier) affect +the quoting of values in the JSON output style. JSON uses quotes for +string value, but no quotes for numeric, boolean, and null data. +xo_emit applies a simple heuristic to determine whether quotes are +needed, but often this needs to be controlled by the caller. + + EXAMPLE: + const char *bool = is_true ? "true" : "false"; + xo_emit("{n:fancy/%s}", bool); + JSON: + "fancy": true + +**** The Plural Modifier ({p:}) @plural-modifier@ + +The plural modifier selects the appropriate plural form of an +expression based on the most recent number emitted and the current +language settings. The contents of the field should be the singular +and plural English values, separated by a comma: + + xo_emit("{:bytes} {Ngp:byte,bytes}\n", bytes); + +The plural modifier is meant to work with the gettext modifier ({g:}) +but can work independently. See ^gettext-modifier^. + +When used without the gettext modifier or when the message does not +appear in the message catalog, the first token is chosen when the last +numeric value is equal to 1; otherwise the second value is used, +mimicking the simple pluralization rules of English. + +When used with the gettext modifier, the ngettext(3) function is +called to handle the heavy lifting, using the message catalog to +convert the singular and plural forms into the native language. + +**** The Quotes Modifier ({q:}) + +The quotes modifier (and its twin, the 'no-quotes' modifier) affect +the quoting of values in the JSON output style. JSON uses quotes for +string value, but no quotes for numeric, boolean, and null data. +xo_emit applies a simple heuristic to determine whether quotes are +needed, but often this needs to be controlled by the caller. + + EXAMPLE: + xo_emit("{q:time/%d}", 2014); + JSON: + "year": "2014" + +The heuristic is based on the format; if the format uses any of the +following conversion specifiers, then no quotes are used: + + d i o u x X D O U e E f F g G a A c C p + +**** The Trim Modifier ({t:}) + +The trim modifier removes any leading or trailing whitespace from +the value. + + EXAMPLE: + xo_emit("{t:description}", " some input "); + JSON: + "description": "some input" + +**** The White Space Modifier ({w:}) + +The white space modifier appends a single space to the data value: + + EXAMPLE: + xo_emit("{Lw:Name}{:name}\n", "phil"); + TEXT: + Name phil + +The white space modifier is only used for the TEXT and HTML output +styles. It is commonly combined with the colon modifier ('{c:}'). +It is purely a convenience feature. + +Note that the sense of the 'w' modifier is reversed for the units role +({Uw:}); a blank is added before the contents, rather than after it. + +*** Field Formatting + +The field format is similar to the format string for printf(3). Its +use varies based on the role of the field, but generally is used to +format the field's contents. + +If the format string is not provided for a value field, it defaults to +"%s". + +Note a field definition can contain zero or more printf-style +'directives', which are sequences that start with a '%' and end with +one of following characters: "diouxXDOUeEfFgGaAcCsSp". Each directive +is matched by one of more arguments to the xo_emit function. + +The format string has the form: + + '%' format-modifier * format-character + +The format- modifier can be: +- a '#' character, indicating the output value should be prefixed with +'0x', typically to indicate a base 16 (hex) value. +- a minus sign ('-'), indicating the output value should be padded on +the right instead of the left. +- a leading zero ('0') indicating the output value should be padded on the +left with zeroes instead of spaces (' '). +- one or more digits ('0' - '9') indicating the minimum width of the +argument. If the width in columns of the output value is less than +the minimum width, the value will be padded to reach the minimum. +- a period followed by one or more digits indicating the maximum +number of bytes which will be examined for a string argument, or the maximum +width for a non-string argument. When handling ASCII strings this +functions as the field width but for multi-byte characters, a single +character may be composed of multiple bytes. +xo_emit will never dereference memory beyond the given number of bytes. +- a second period followed by one or more digits indicating the maximum +width for a string argument. This modifier cannot be given for non-string +arguments. +- one or more 'h' characters, indicating shorter input data. +- one or more 'l' characters, indicating longer input data. +- a 'z' character, indicating a 'size_t' argument. +- a 't' character, indicating a 'ptrdiff_t' argument. +- a ' ' character, indicating a space should be emitted before +positive numbers. +- a '+' character, indicating sign should emitted before any number. + +Note that 'q', 'D', 'O', and 'U' are considered deprecated and will be +removed eventually. + +The format character is described in the following table: + +|-----+-----------------+----------------------| +| Ltr | Argument Type | Format | +|-----+-----------------+----------------------| +| d | int | base 10 (decimal) | +| i | int | base 10 (decimal) | +| o | int | base 8 (octal) | +| u | unsigned | base 10 (decimal) | +| x | unsigned | base 16 (hex) | +| X | unsigned long | base 16 (hex) | +| D | long | base 10 (decimal) | +| O | unsigned long | base 8 (octal) | +| U | unsigned long | base 10 (decimal) | +| e | double | [-]d.ddde+-dd | +| E | double | [-]d.dddE+-dd | +| f | double | [-]ddd.ddd | +| F | double | [-]ddd.ddd | +| g | double | as 'e' or 'f' | +| G | double | as 'E' or 'F' | +| a | double | [-]0xh.hhhp[+-]d | +| A | double | [-]0Xh.hhhp[+-]d | +| c | unsigned char | a character | +| C | wint_t | a character | +| s | char * | a UTF-8 string | +| S | wchar_t * | a unicode/WCS string | +| p | void * | '%#lx' | +|-----+-----------------+----------------------| + +The 'h' and 'l' modifiers affect the size and treatment of the +argument: + +|-----+-------------+--------------------| +| Mod | d, i | o, u, x, X | +|-----+-------------+--------------------| +| hh | signed char | unsigned char | +| h | short | unsigned short | +| l | long | unsigned long | +| ll | long long | unsigned long long | +| j | intmax_t | uintmax_t | +| t | ptrdiff_t | ptrdiff_t | +| z | size_t | size_t | +| q | quad_t | u_quad_t | +|-----+-------------+--------------------| + +*** UTF-8 and Locale Strings + +For strings, the 'h' and 'l' modifiers affect the interpretation of +the bytes pointed to argument. The default '%s' string is a 'char *' +pointer to a string encoded as UTF-8. Since UTF-8 is compatible with +ASCII data, a normal 7-bit ASCII string can be used. '%ls' expects a +'wchar_t *' pointer to a wide-character string, encoded as a 32-bit +Unicode values. '%hs' expects a 'char *' pointer to a multi-byte +string encoded with the current locale, as given by the LC_CTYPE, +LANG, or LC_ALL environment varibles. The first of this list of +variables is used and if none of the variables are set, the locale +defaults to "UTF-8". + +libxo will convert these arguments as needed to either UTF-8 (for XML, +JSON, and HTML styles) or locale-based strings for display in text +style. + + xo_emit("All strings are utf-8 content {:tag/%ls}", + L"except for wide strings"); + +"%S" is equivalent to "%ls". + +|--------+-----------------+-------------------------------| +| Format | Argument Type | Argument Contents | +|--------+-----------------+-------------------------------| +| %s | const char * | UTF-8 string | +| %S | const char * | UTF-8 string (alias for '%s') | +| %ls | const wchar_t * | Wide character UNICODE string | +| %hs | const char * | locale-based string | +|--------+-----------------+-------------------------------| + +For example, a function is passed a locale-base name, a hat size, +and a time value. The hat size is formatted in a UTF-8 (ASCII) +string, and the time value is formatted into a wchar_t string. + + void print_order (const char *name, int size, + struct tm *timep) { + char buf[32]; + const char *size_val = "unknown"; + + if (size > 0) + snprintf(buf, sizeof(buf), "%d", size); + size_val = buf; + } + + wchar_t when[32]; + wcsftime(when, sizeof(when), L"%d%b%y", timep); + + xo_emit("The hat for {:name/%hs} is {:size/%s}.\n", + name, size_val); + xo_emit("It was ordered on {:order-time/%ls}.\n", + when); + } + +It is important to note that xo_emit will perform the conversion +required to make appropriate output. Text style output uses the +current locale (as described above), while XML, JSON, and HTML use +UTF-8. + +UTF-8 and locale-encoded strings can use multiple bytes to encode one +column of data. The traditional "precision'" (aka "max-width") value +for "%s" printf formatting becomes overloaded since it specifies both +the number of bytes that can be safely referenced and the maximum +number of columns to emit. xo_emit uses the precision as the former, +and adds a third value for specifying the maximum number of columns. + +In this example, the name field is printed with a minimum of 3 columns +and a maximum of 6. Up to ten bytes of data at the location given by +'name' are in used in filling those columns. + + xo_emit("{:name/%3.10.6s}", name); + +*** Characters Outside of Field Definitions + +Characters in the format string that are not part of a field +definition are copied to the output for the TEXT style, and are +ignored for the JSON and XML styles. For HTML, these characters are +placed in a
with class "text". + + EXAMPLE: + xo_emit("The hat is {:size/%s}.\n", size_val); + TEXT: + The hat is extra small. + XML: + extra small + JSON: + "size": "extra small" + HTML: +
The hat is
+
extra small
+
.
+ +*** "%m" Is Supported + +libxo supports the '%m' directive, which formats the error message +associated with the current value of "errno". It is the equivalent +of "%s" with the argument strerror(errno). + + xo_emit("{:filename} cannot be opened: {:error/%m}", filename); + xo_emit("{:filename} cannot be opened: {:error/%s}", + filename, strerror(errno)); + +*** "%n" Is Not Supported + +libxo does not support the '%n' directive. It's a bad idea and we +just don't do it. + +*** The Encoding Format (eformat) + +The "eformat" string is the format string used when encoding the field +for JSON and XML. If not provided, it defaults to the primary format +with any minimum width removed. If the primary is not given, both +default to "%s". + +*** Content Strings + +For padding and labels, the content string is considered the content, +unless a format is given. + +*** Argument Validation @printf-like@ + +Many compilers and tool chains support validation of printf-like +arguments. When the format string fails to match the argument list, +a warning is generated. This is a valuable feature and while the +formatting strings for libxo differ considerably from printf, many of +these checks can still provide build-time protection against bugs. + +libxo provide variants of functions that provide this ability, if the +"--enable-printflike" option is passed to the "configure" script. +These functions use the "_p" suffix, like "xo_emit_p()", +xo_emit_hp()", etc. + +The following are features of libxo formatting strings that are +incompatible with printf-like testing: + +- implicit formats, where "{:tag}" has an implicit "%s"; +- the "max" parameter for strings, where "{:tag/%4.10.6s}" means up to +ten bytes of data can be inspected to fill a minimum of 4 columns and +a maximum of 6; +- percent signs in strings, where "{:filled}%" makes a single, +trailing percent sign; +- the "l" and "h" modifiers for strings, where "{:tag/%hs}" means +locale-based string and "{:tag/%ls}" means a wide character string; +- distinct encoding formats, where "{:tag/#%s/%s}" means the display +styles (text and HTML) will use "#%s" where other styles use "%s"; + +If none of these features are in use by your code, then using the "_p" +variants might be wise. + +|------------------+------------------------| +| Function | printf-like Equivalent | +|------------------+------------------------| +| xo_emit_hv | xo_emit_hvp | +| xo_emit_h | xo_emit_hp | +| xo_emit | xo_emit_p | +| xo_emit_warn_hcv | xo_emit_warn_hcvp | +| xo_emit_warn_hc | xo_emit_warn_hcp | +| xo_emit_warn_c | xo_emit_warn_cp | +| xo_emit_warn | xo_emit_warn_p | +| xo_emit_warnx_ | xo_emit_warnx_p | +| xo_emit_err | xo_emit_err_p | +| xo_emit_errx | xo_emit_errx_p | +| xo_emit_errc | xo_emit_errc_p | +|------------------+------------------------| + +*** Retaining Parsed Format Information @retain@ + +libxo can retain the parsed internal information related to the given +format string, allowing subsequent xo_emit calls, the retained +information is used, avoiding repetitive parsing of the format string. + + SYNTAX: + int xo_emit_f(xo_emit_flags_t flags, const char fmt, ...); + EXAMPLE: + xo_emit_f(XOEF_RETAIN, "{:some/%02d}{:thing/%-6s}{:fancy}\n", + some, thing, fancy); + +To retain parsed format information, use the XOEF_RETAIN flag to the +xo_emit_f() function. A complete set of xo_emit_f functions exist to +match all the xo_emit function signatures (with handles, varadic +argument, and printf-like flags): + +|------------------+------------------------| +| Function | Flags Equivalent | +|------------------+------------------------| +| xo_emit_hv | xo_emit_hvf | +| xo_emit_h | xo_emit_hf | +| xo_emit | xo_emit_f | +| xo_emit_hvp | xo_emit_hvfp | +| xo_emit_hp | xo_emit_hfp | +| xo_emit_p | xo_emit_fp | +|------------------+------------------------| + +The format string must be immutable across multiple calls to xo_emit_f(), +since the library retains the string. Typically this is done by using +static constant strings, such as string literals. If the string is not +immutable, the XOEF_RETAIN flag must not be used. + +The functions xo_retain_clear() and xo_retain_clear_all() release +internal information on either a single format string or all format +strings, respectively. Neither is required, but the library will +retain this information until it is cleared or the process exits. + + const char *fmt = "{:name} {:count/%d}\n"; + for (i = 0; i < 1000; i++) { + xo_open_instance("item"); + xo_emit_f(XOEF_RETAIN, fmt, name[i], count[i]); + } + xo_retain_clear(fmt); + +The retained information is kept as thread-specific data. + +*** Example + +In this example, the value for the number of items in stock is emitted: + + xo_emit("{P: }{Lwc:In stock}{:in-stock/%u}\n", + instock); + +This call will generate the following output: + + TEXT: + In stock: 144 + XML: + 144 + JSON: + "in-stock": 144, + HTML: +
+
+
In stock
+
:
+
+
144
+
+ +Clearly HTML wins the verbosity award, and this output does +not include XOF_XPATH or XOF_INFO data, which would expand the +penultimate line to: + +
144
+ +** Representing Hierarchy + +For XML and JSON, individual fields appear inside hierarchies which +provide context and meaning to the fields. Unfortunately, these +encoding have a basic disconnect between how lists is similar objects +are represented. + +XML encodes lists as set of sequential elements: + + phil + pallavi + sjg + +JSON encodes lists using a single name and square brackets: + + "user": [ "phil", "pallavi", "sjg" ] + +This means libxo needs three distinct indications of hierarchy: one +for containers of hierarchy appear only once for any specific parent, +one for lists, and one for each item in a list. + +*** Containers + +A "container" is an element of a hierarchy that appears only once +under any specific parent. The container has no value, but serves to +contain other nodes. + +To open a container, call xo_open_container() or +xo_open_container_h(). The former uses the default handle and +the latter accepts a specific handle. + + int xo_open_container_h (xo_handle_t *xop, const char *name); + int xo_open_container (const char *name); + +To close a level, use the xo_close_container() or +xo_close_container_h() functions: + + int xo_close_container_h (xo_handle_t *xop, const char *name); + int xo_close_container (const char *name); + +Each open call must have a matching close call. If the XOF_WARN flag +is set and the name given does not match the name of the currently open +container, a warning will be generated. + + Example: + + xo_open_container("top"); + xo_open_container("system"); + xo_emit("{:host-name/%s%s%s", hostname, + domainname ? "." : "", domainname ?: ""); + xo_close_container("system"); + xo_close_container("top"); + + Sample Output: + Text: + my-host.example.org + XML: + + + my-host.example.org + + + JSON: + "top" : { + "system" : { + "host-name": "my-host.example.org" + } + } + HTML: +
my-host.example.org
+ +*** Lists and Instances + +A list is set of one or more instances that appear under the same +parent. The instances contain details about a specific object. One +can think of instances as objects or records. A call is needed to +open and close the list, while a distinct call is needed to open and +close each instance of the list: + + xo_open_list("item"); + + for (ip = list; ip->i_title; ip++) { + xo_open_instance("item"); + xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title); + xo_close_instance("item"); + } + + xo_close_list("item"); + +Getting the list and instance calls correct is critical to the proper +generation of XML and JSON data. + +*** DTRT Mode + +Some users may find tracking the names of open containers, lists, and +instances inconvenient. libxo offers a "Do The Right Thing" mode, where +libxo will track the names of open containers, lists, and instances so +the close function can be called without a name. To enable DTRT mode, +turn on the XOF_DTRT flag prior to making any other libxo output. + + xo_set_flags(NULL, XOF_DTRT); + +Each open and close function has a version with the suffix "_d", which +will close the open container, list, or instance: + + xo_open_container("top"); + ... + xo_close_container_d(); + +This also works for lists and instances: + + xo_open_list("item"); + for (...) { + xo_open_instance("item"); + xo_emit(...); + xo_close_instance_d(); + } + xo_close_list_d(); + +Note that the XOF_WARN flag will also cause libxo to track open +containers, lists, and instances. A warning is generated when the +name given to the close function and the name recorded do not match. + +*** Markers + +Markers are used to protect and restore the state of open constructs. +While a marker is open, no other open constructs can be closed. When +a marker is closed, all constructs open since the marker was opened +will be closed. + +Markers use names which are not user-visible, allowing the caller to +choose appropriate internal names. + +In this example, the code whiffles through a list of fish, calling a +function to emit details about each fish. The marker "fish-guts" is +used to ensure that any constructs opened by the function are closed +properly. + + for (i = 0; fish[i]; i++) { + xo_open_instance("fish"); + xo_open_marker("fish-guts"); + dump_fish_details(i); + xo_close_marker("fish-guts"); + } + +* Command-line Arguments @options@ + +libxo uses command line options to trigger rendering behavior. The +following options are recognised: + +- --libxo +- --libxo= +- --libxo: + +The following invocations are all identical in outcome: + + my-app --libxo warn,pretty arg1 + my-app --libxo=warn,pretty arg1 + my-app --libxo:WP arg1 + +Programs using libxo are expecting to call the xo_parse_args function +to parse these arguments. See ^xo_parse_args^ for details. + +** Option keywords + +Options is a comma-separated list of tokens that correspond to output +styles, flags, or features: + +|-------------+-------------------------------------------------------| +| Token | Action | +|-------------+-------------------------------------------------------| +| color | Enable colors/effects for display styles (TEXT, HTML) | +| colors=xxxx | Adjust color output values | +| dtrt | Enable "Do The Right Thing" mode | +| flush | Flush after every libxo function call | +| flush-line | Flush after every line (line-buffered) | +| html | Emit HTML output | +| indent=xx | Set the indentation level | +| info | Add info attributes (HTML) | +| json | Emit JSON output | +| keys | Emit the key attribute for keys (XML) | +| log-gettext | Log (via stderr) each gettext(3) string lookup | +| log-syslog | Log (via stderr) each syslog message (via xo_syslog) | +| no-humanize | Ignore the {h:} modifier (TEXT, HTML) | +| no-locale | Do not initialize the locale setting | +| no-retain | Prevent retaining formatting information | +| no-top | Do not emit a top set of braces (JSON) | +| not-first | Pretend the 1st output item was not 1st (JSON) | +| pretty | Emit pretty-printed output | +| retain | Force retaining formatting information | +| text | Emit TEXT output | +| underscores | Replace XML-friendly "-"s with JSON friendly "_"s | +| units | Add the 'units' (XML) or 'data-units (HTML) attribute | +| warn | Emit warnings when libxo detects bad calls | +| warn-xml | Emit warnings in XML | +| xml | Emit XML output | +| xpath | Add XPath expressions (HTML) | +|-------------+-------------------------------------------------------| + +Most of these option are simple and direct, but some require +additional details: + +- "colors" is described in ^color-mapping^. +- "flush-line" performs line buffering, even when the output is not +directed to a TTY device. +- "info" generates additional data for HTML, encoded in attributes +using names that state with "data-". +- "keys" adds a "key" attribute for XML output to indicate that a leaf +is an identifier for the list member. +- "no-humanize"avoids "humanizing" numeric output (see +humanize_number(3) for details). +- "no-locale" instructs libxo to avoid translating output to the +current locale. +- "no-retain" disables the ability of libxo to internally retain +"compiled" information about formatting strings. +- "underscores" can be used with JSON output to change XML-friendly +names with dashes into JSON-friendly name with underscores. +- "warn" allows libxo to emit warnings on stderr when application code +make incorrect calls. +- "warn-xml" causes those warnings to be placed in XML inside the +output. + +** Brief Options + +The brief options are simple single-letter aliases to the normal +keywords, as detailed below: + +|--------+---------------------------------------------| +| Option | Action | +|--------+---------------------------------------------| +| c | Enable color/effects for TEXT/HTML | +| F | Force line-buffered flushing | +| H | Enable HTML output (XO_STYLE_HTML) | +| I | Enable info output (XOF_INFO) | +| i | Indent by | +| J | Enable JSON output (XO_STYLE_JSON) | +| k | Add keys to XPATH expressions in HTML | +| n | Disable humanization (TEXT, HTML) | +| P | Enable pretty-printed output (XOF_PRETTY) | +| T | Enable text output (XO_STYLE_TEXT) | +| U | Add units to HTML output | +| u | Change "-"s to "_"s in element names (JSON) | +| W | Enable warnings (XOF_WARN) | +| X | Enable XML output (XO_STYLE_XML) | +| x | Enable XPath data (XOF_XPATH) | +|--------+---------------------------------------------| + +** Color Mapping +The "colors" option takes a value that is a set of mappings from the +pre-defined set of colors to new foreground and background colors. +The value is a series of "fg/bg" values, separated by a "+". Each +pair of "fg/bg" values gives the colors to which a basic color is +mapped when used as a foreground or background color. The order is +the mappings is: + +- black +- red +- green +- yellow +- blue +- magenta +- cyan +- white + +Pairs may be skipped, leaving them mapped as normal, as are missing +pairs or single colors. + +For example consider the following xo_emit call: + + xo_emit("{C:fg-red,bg-green}Merry XMas!!{C:}\n"); + +To turn all colored output to red-on-blue, use eight pairs of +"red/blue" mappings separated by "+"s: + + --libxo colors=red/blue+red/blue+red/blue+red/blue+\ + red/blue+red/blue+red/blue+red/blue + +To turn the red-on-green text to magenta-on-cyan, give a "magenta" +foreground value for red (the second mapping) and a "cyan" background +to green (the third mapping): + + --libxo colors=+magenta+/cyan + +Consider the common situation where blue output looks unreadable on a +terminal session with a black background. To turn both "blue" +foreground and background output to "yellow", give only the fifth +mapping, skipping the first four mappings with bare "+"s: + + --libxo colors=++++yellow/yellow + +* The libxo API + +This section gives details about the functions in libxo, how to call +them, and the actions they perform. + +** Handles @handles@ + +libxo uses "handles" to control its rendering functionality. The +handle contains state and buffered data, as well as callback functions +to process data. + +Handles give an abstraction for libxo that encapsulates the state of a +stream of output. Handles have the data type "xo_handle_t" and are +opaque to the caller. + +The library has a default handle that is automatically initialized. +By default, this handle will send text style output (XO_STYLE_TEXT) to +standard output. The xo_set_style and xo_set_flags functions can be +used to change this behavior. + +For the typical command that is generating output on standard output, +there is no need to create an explicit handle, but they are available +when needed, e.g., for daemons that generate multiple streams of +output. + +Many libxo functions take a handle as their first parameter; most that +do not use the default handle. Any function taking a handle can be +passed NULL to access the default handle. For the convenience of +callers, the libxo library includes handle-less functions that +implicitly use the default handle. + +For example, the following are equivalent: + + xo_emit("test"); + xo_emit_h(NULL, "test"); + +Handles are created using xo_create() and destroy using xo_destroy(). + +*** xo_create + +A handle can be allocated using the xo_create() function: + + xo_handle_t *xo_create (unsigned style, unsigned flags); + + Example: + xo_handle_t *xop = xo_create(XO_STYLE_JSON, XOF_WARN); + .... + xo_emit_h(xop, "testing\n"); + +See also ^styles^ and ^flags^. + +*** xo_create_to_file + +By default, libxo writes output to standard output. A convenience +function is provided for situations when output should be written to +a different file: + + xo_handle_t *xo_create_to_file (FILE *fp, unsigned style, + unsigned flags); + +Use the XOF_CLOSE_FP flag to trigger a call to fclose() for +the FILE pointer when the handle is destroyed. + +*** xo_set_writer + +The xo_set_writer function allows custom 'write' functions +which can tailor how libxo writes data. An opaque argument is +recorded and passed back to the write function, allowing the function +to acquire context information. The 'close' function can +release this opaque data and any other resources as needed. +The flush function can flush buffered data associated with the opaque +object. + + void xo_set_writer (xo_handle_t *xop, void *opaque, + xo_write_func_t write_func, + xo_close_func_t close_func); + xo_flush_func_t flush_func); + +*** xo_set_style + +To set the style, use the xo_set_style() function: + + void xo_set_style(xo_handle_t *xop, unsigned style); + +To use the default handle, pass a NULL handle: + + xo_set_style(NULL, XO_STYLE_XML); + +*** xo_get_style + +To find the current style, use the xo_get_style() function: + + xo_style_t xo_get_style(xo_handle_t *xop); + +To use the default handle, pass a NULL handle: + + style = xo_get_style(NULL); + +**** Output Styles (XO_STYLE_*) @styles@ + +The libxo functions accept a set of output styles: + +|---------------+-------------------------| +| Flag | Description | +|---------------+-------------------------| +| XO_STYLE_TEXT | Traditional text output | +| XO_STYLE_XML | XML encoded data | +| XO_STYLE_JSON | JSON encoded data | +| XO_STYLE_HTML | HTML encoded data | +|---------------+-------------------------| + +**** xo_set_style_name + +The xo_set_style_name() can be used to set the style based on a name +encoded as a string: + + int xo_set_style_name (xo_handle_t *xop, const char *style); + +The name can be any of the styles: "text", "xml", "json", or "html". + + EXAMPLE: + xo_set_style_name(NULL, "html"); + +*** xo_set_flags + +To set the flags, use the xo_set_flags() function: + + void xo_set_flags(xo_handle_t *xop, unsigned flags); + +To use the default handle, pass a NULL handle: + + xo_set_style(NULL, XO_STYLE_XML); + +**** Flags (XOF_*) @flags@ + +The set of valid flags include: + +|-------------------+----------------------------------------| +| Flag | Description | +|-------------------+----------------------------------------| +| XOF_CLOSE_FP | Close file pointer on xo_destroy() | +| XOF_COLOR | Enable color and effects in output | +| XOF_COLOR_ALLOWED | Allow color/effect for terminal output | +| XOF_DTRT | Enable "do the right thing" mode | +| XOF_INFO | Display info data attributes (HTML) | +| XOF_KEYS | Emit the key attribute (XML) | +| XOF_NO_ENV | Do not use the LIBXO_OPTIONS env var | +| XOF_NO_HUMANIZE | Display humanization (TEXT, HTML) | +| XOF_PRETTY | Make 'pretty printed' output | +| XOF_UNDERSCORES | Replaces hyphens with underscores | +| XOF_UNITS | Display units (XML, HMTL) | +| XOF_WARN | Generate warnings for broken calls | +| XOF_WARN_XML | Generate warnings in XML on stdout | +| XOF_XPATH | Emit XPath expressions (HTML) | +| XOF_COLUMNS | Force xo_emit to return columns used | +| XOF_FLUSH | Flush output after each xo_emit call | +|-------------------+----------------------------------------| + +The XOF_CLOSE_FP flag will trigger the call of the close_func +(provided via xo_set_writer()) when the handle is destroyed. + +The XOF_COLOR flag enables color and effects in output regardless of +output device, while the XOF_COLOR_ALLOWED flag allows color and +effects only if the output device is a terminal. + +The XOF_PRETTY flag requests 'pretty printing', which will trigger the +addition of indentation and newlines to enhance the readability of +XML, JSON, and HTML output. Text output is not affected. + +The XOF_WARN flag requests that warnings will trigger diagnostic +output (on standard error) when the library notices errors during +operations, or with arguments to functions. Without warnings enabled, +such conditions are ignored. + +Warnings allow developers to debug their interaction with libxo. +The function "xo_failure" can used as a breakpoint for a debugger, +regardless of whether warnings are enabled. + +If the style is XO_STYLE_HTML, the following additional flags can be +used: + +|---------------+-----------------------------------------| +| Flag | Description | +|---------------+-----------------------------------------| +| XOF_XPATH | Emit "data-xpath" attributes | +| XOF_INFO | Emit additional info fields | +|---------------+-----------------------------------------| + +The XOF_XPATH flag enables the emission of XPath expressions detailing +the hierarchy of XML elements used to encode the data field, if the +XPATH style of output were requested. + +The XOF_INFO flag encodes additional informational fields for HTML +output. See ^info^ for details. + +If the style is XO_STYLE_XML, the following additional flags can be +used: + +|---------------+-----------------------------------------| +| Flag | Description | +|---------------+-----------------------------------------| +| XOF_KEYS | Flag 'key' fields for xml | +|---------------+-----------------------------------------| + +The XOF_KEYS flag adds 'key' attribute to the XML encoding for +field definitions that use the 'k' modifier. The key attribute has +the value "key": + + xo_emit("{k:name}", item); + + XML: + truck + +**** xo_clear_flags + +The xo_clear_flags() function turns off the given flags in a specific +handle. + + void xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags); + +**** xo_set_options + +The xo_set_options() function accepts a comma-separated list of styles +and flags and enables them for a specific handle. + + int xo_set_options (xo_handle_t *xop, const char *input); + +The options are identical to those listed in ^options^. + +*** xo_destroy + +The xo_destroy function releases a handle and any resources it is +using. Calling xo_destroy with a NULL handle will release any +resources associated with the default handle. + + void xo_destroy(xo_handle_t *xop); + +** Emitting Content (xo_emit) + +The following functions are used to emit output: + + int xo_emit (const char *fmt, ...); + int xo_emit_h (xo_handle_t *xop, const char *fmt, ...); + int xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap); + +The "fmt" argument is a string containing field descriptors as +specified in ^format-strings^. The use of a handle is optional and +NULL can be passed to access the internal 'default' handle. See +^handles^. + +The remaining arguments to xo_emit() and xo_emit_h() are a set of +arguments corresponding to the fields in the format string. Care must +be taken to ensure the argument types match the fields in the format +string, since an inappropriate cast can ruin your day. The vap +argument to xo_emit_hv() points to a variable argument list that can +be used to retrieve arguments via va_arg(). + +*** Single Field Emitting Functions (xo_emit_field) @xo_emit_field@ + +The following functions can also make output, but only make a single +field at a time: + + int xo_emit_field_hv (xo_handle_t *xop, const char *rolmod, + const char *contents, const char *fmt, + const char *efmt, va_list vap); + + int xo_emit_field_h (xo_handle_t *xop, const char *rolmod, + const char *contents, const char *fmt, + const char *efmt, ...); + + int xo_emit_field (const char *rolmod, const char *contents, + const char *fmt, const char *efmt, ...); + +These functions are intended to avoid the scenario where one +would otherwise need to compose a format descriptors using +snprintf(). The individual parts of the format descriptor are +passed in distinctly. + + xo_emit("T", "Host name is ", NULL, NULL); + xo_emit("V", "host-name", NULL, NULL, host-name); + +*** Attributes (xo_attr) @xo_attr@ + +The xo_attr() function emits attributes for the XML output style. + + int xo_attr (const char *name, const char *fmt, ...); + int xo_attr_h (xo_handle_t *xop, const char *name, + const char *fmt, ...); + int xo_attr_hv (xo_handle_t *xop, const char *name, + const char *fmt, va_list vap); + +The name parameter give the name of the attribute to be encoded. The +fmt parameter gives a printf-style format string used to format the +value of the attribute using any remaining arguments, or the vap +parameter passed to xo_attr_hv(). + + EXAMPLE: + xo_attr("seconds", "%ld", (unsigned long) login_time); + struct tm *tmp = localtime(login_time); + strftime(buf, sizeof(buf), "%R", tmp); + xo_emit("Logged in at {:login-time}\n", buf); + XML: + 00:14 + +xo_attr is placed on the next container, instance, leaf, or leaf list +that is emitted. + +Since attributes are only emitted in XML, their use should be limited +to meta-data and additional or redundant representations of data +already emitted in other form. + +*** Flushing Output (xo_flush) + +libxo buffers data, both for performance and consistency, but also to +allow some advanced features to work properly. At various times, the +caller may wish to flush any data buffered within the library. The +xo_flush() call is used for this: + + void xo_flush (void); + void xo_flush_h (xo_handle_t *xop); + +Calling xo_flush also triggers the flush function associated with the +handle. For the default handle, this is equivalent to +"fflush(stdio);". + +*** Finishing Output (xo_finish) + +When the program is ready to exit or close a handle, a call to +xo_finish() is required. This flushes any buffered data, closes +open libxo constructs, and completes any pending operations. + + int xo_finish (void); + int xo_finish_h (xo_handle_t *xop); + void xo_finish_atexit (void); + +Calling this function is vital to the proper operation of libxo, +especially for the non-TEXT output styles. + +xo_finish_atexit is suitable for use with atexit(3). + +** Emitting Hierarchy + +libxo represents to types of hierarchy: containers and lists. A +container appears once under a given parent where a list contains +instances that can appear multiple times. A container is used to hold +related fields and to give the data organization and scope. + +To create a container, use the xo_open_container and +xo_close_container functions: + + int xo_open_container (const char *name); + int xo_open_container_h (xo_handle_t *xop, const char *name); + int xo_open_container_hd (xo_handle_t *xop, const char *name); + int xo_open_container_d (const char *name); + + int xo_close_container (const char *name); + int xo_close_container_h (xo_handle_t *xop, const char *name); + int xo_close_container_hd (xo_handle_t *xop); + int xo_close_container_d (void); + +The name parameter gives the name of the container, encoded in UTF-8. +Since ASCII is a proper subset of UTF-8, traditional C strings can be +used directly. + +The close functions with the "_d" suffix are used in "Do The Right +Thing" mode, where the name of the open containers, lists, and +instances are maintained internally by libxo to allow the caller to +avoid keeping track of the open container name. + +Use the XOF_WARN flag to generate a warning if the name given on the +close does not match the current open container. + +For TEXT and HTML output, containers are not rendered into output +text, though for HTML they are used when the XOF_XPATH flag is set. + + EXAMPLE: + xo_open_container("system"); + xo_emit("The host name is {:host-name}\n", hn); + xo_close_container("system"); + XML: + foo + +*** Lists and Instances + +Lists are sequences of instances of homogeneous data objects. Two +distinct levels of calls are needed to represent them in our output +styles. Calls must be made to open and close a list, and for each +instance of data in that list, calls must be make to open and close +that instance. + +The name given to all calls must be identical, and it is strongly +suggested that the name be singular, not plural, as a matter of +style and usage expectations. + + EXAMPLE: + xo_open_list("user"); + for (i = 0; i < num_users; i++) { + xo_open_instance("user"); + xo_emit("{k:name}:{:uid/%u}:{:gid/%u}:{:home}\n", + pw[i].pw_name, pw[i].pw_uid, + pw[i].pw_gid, pw[i].pw_dir); + xo_close_instance("user"); + } + xo_close_list("user"); + TEXT: + phil:1001:1001:/home/phil + pallavi:1002:1002:/home/pallavi + XML: + + phil + 1001 + 1001 + /home/phil + + + pallavi + 1002 + 1002 + /home/pallavi + + JSON: + user: [ + { + "name": "phil", + "uid": 1001, + "gid": 1001, + "home": "/home/phil", + }, + { + "name": "pallavi", + "uid": 1002, + "gid": 1002, + "home": "/home/pallavi", + } + ] + +** Support Functions + +*** Parsing Command-line Arguments (xo_parse_args) @xo_parse_args@ + +The xo_parse_args() function is used to process a program's +arguments. libxo-specific options are processed and removed +from the argument list so the calling application does not +need to process them. If successful, a new value for argc +is returned. On failure, a message it emitted and -1 is returned. + + argc = xo_parse_args(argc, argv); + if (argc < 0) + exit(EXIT_FAILURE); + +Following the call to xo_parse_args, the application can process the +remaining arguments in a normal manner. See ^options^ +for a description of valid arguments. + +*** xo_set_program + +The xo_set_program function sets name of the program as reported by +functions like xo_failure, xo_warn, xo_err, etc. The program name is +initialized by xo_parse_args, but subsequent calls to xo_set_program +can override this value. + + xo_set_program(argv[0]); + +Note that the value is not copied, so the memory passed to +xo_set_program (and xo_parse_args) must be maintained by the caller. + +*** xo_set_version + +The xo_set_version function records a version number to be emitted as +part of the data for encoding styles (XML and JSON). This version +number is suitable for tracking changes in the content, allowing a +user of the data to discern which version of the data model is in use. + + void xo_set_version (const char *version); + void xo_set_version_h (xo_handle_t *xop, const char *version); + +*** Field Information (xo_info_t) @info@ + +HTML data can include additional information in attributes that +begin with "data-". To enable this, three things must occur: + +First the application must build an array of xo_info_t structures, +one per tag. The array must be sorted by name, since libxo uses a +binary search to find the entry that matches names from format +instructions. + +Second, the application must inform libxo about this information using +the xo_set_info() call: + + typedef struct xo_info_s { + const char *xi_name; /* Name of the element */ + const char *xi_type; /* Type of field */ + const char *xi_help; /* Description of field */ + } xo_info_t; + + void xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count); + +Like other libxo calls, passing NULL for the handle tells libxo to use +the default handle. + +If the count is -1, libxo will count the elements of infop, but there +must be an empty element at the end. More typically, the number is +known to the application: + + xo_info_t info[] = { + { "in-stock", "number", "Number of items in stock" }, + { "name", "string", "Name of the item" }, + { "on-order", "number", "Number of items on order" }, + { "sku", "string", "Stock Keeping Unit" }, + { "sold", "number", "Number of items sold" }, + }; + int info_count = (sizeof(info) / sizeof(info[0])); + ... + xo_set_info(NULL, info, info_count); + +Third, the emission of info must be triggered with the XOF_INFO flag +using either the xo_set_flags() function or the "--libxo=info" command +line argument. + +The type and help values, if present, are emitted as the "data-type" +and "data-help" attributes: + +
GRO-000-533
+ +*** Memory Allocation + +The xo_set_allocator function allows libxo to be used in environments +where the standard realloc() and free() functions are not available. + + void xo_set_allocator (xo_realloc_func_t realloc_func, + xo_free_func_t free_func); + +realloc_func should expect the same arguments as realloc(3) and return +a pointer to memory following the same convention. free_func will +receive the same argument as free(3) and should release it, as +appropriate for the environment. + +By default, the standard realloc() and free() functions are used. + +*** LIBXO_OPTIONS @LIBXO_OPTIONS@ + +The environment variable "LIBXO_OPTIONS" can be set to a subset of +libxo options, including: + +- color +- flush +- flush-line +- no-color +- no-humanize +- no-locale +- no-retain +- pretty +- retain +- underscores +- warn + +For example, warnings can be enabled by: + + % env LIBXO_OPTIONS=warn my-app + +Since environment variables are inherited, child processes will have +the same options, which may be undesirable, making the use of the +"--libxo" option is preferable in most situations. + +*** Errors, Warnings, and Messages + +Many programs make use of the standard library functions err() and +warn() to generate errors and warnings for the user. libxo wants to +pass that information via the current output style, and provides +compatible functions to allow this: + + void xo_warn (const char *fmt, ...); + void xo_warnx (const char *fmt, ...); + void xo_warn_c (int code, const char *fmt, ...); + void xo_warn_hc (xo_handle_t *xop, int code, + const char *fmt, ...); + void xo_err (int eval, const char *fmt, ...); + void xo_errc (int eval, int code, const char *fmt, ...); + void xo_errx (int eval, const char *fmt, ...); + void xo_message (const char *fmt, ...); + void xo_message_c (int code, const char *fmt, ...); + void xo_message_hc (xo_handle_t *xop, int code, + const char *fmt, ...); + void xo_message_hcv (xo_handle_t *xop, int code, + const char *fmt, va_list vap); + +These functions display the program name, a colon, a formatted message +based on the arguments, and then optionally a colon and an error +message associated with either "errno" or the "code" parameter. + + EXAMPLE: + if (open(filename, O_RDONLY) < 0) + xo_err(1, "cannot open file '%s'", filename); + +*** xo_error + +The xo_error function can be used for generic errors that should be +reported over the handle, rather than to stderr. The xo_error +function behaves like xo_err for TEXT and HTML output styles, but puts +the error into XML or JSON elements: + + EXAMPLE:: + xo_error("Does not %s", "compute"); + XML:: + Does not compute + JSON:: + "error": { "message": "Does not compute" } + +*** xo_no_setlocale + +libxo automatically initializes the locale based on setting of the +environment variables LC_CTYPE, LANG, and LC_ALL. The first of this +list of variables is used and if none of the variables, the locale +defaults to "UTF-8". The caller may wish to avoid this behavior, and +can do so by calling the xo_no_setlocale() function. + + void xo_no_setlocale (void); + +** Emitting syslog Messages + +syslog is the system logging facility used throughout the unix world. +Messages are sent from commands, applications, and daemons to a +hierarchy of servers, where they are filtered, saved, and forwarded +based on configuration behaviors. + +syslog is an older protocol, originally documented only in source +code. By the time RFC 3164 published, variation and mutation left the +leading "" string as only common content. RFC 5424 defines a new +version (version 1) of syslog and introduces structured data into the +messages. Structured data is a set of name/value pairs transmitted +distinctly alongside the traditional text message, allowing filtering +on precise values instead of regular expressions. + +These name/value pairs are scoped by a two-part identifier; an +enterprise identifier names the party responsible for the message +catalog and a name identifying that message. Enterprise IDs are +defined by IANA, the Internet Assigned Numbers Authority: + +https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers + +Use the ^xo_set_syslog_enterprise_id^() function to set the Enterprise +ID, as needed. + +The message name should follow the conventions in ^good-field-names^, +as should the fields within the message. + + /* Both of these calls are optional */ + xo_set_syslog_enterprise_id(32473); + xo_open_log("my-program", 0, LOG_DAEMON); + + /* Generate a syslog message */ + xo_syslog(LOG_ERR, "upload-failed", + "error <%d> uploading file '{:filename}' " + "as '{:target/%s:%s}'", + code, filename, protocol, remote); + + xo_syslog(LOG_INFO, "poofd-invalid-state", + "state {:current/%u} is invalid {:connection/%u}", + state, conn); + +The developer should be aware that the message name may be used in the +future to allow access to further information, including +documentation. Care should be taken to choose quality, descriptive +names. + +*** Priority, Facility, and Flags @priority@ + +The xo_syslog, xo_vsyslog, and xo_open_log functions accept a set of +flags which provide the priority of the message, the source facility, +and some additional features. These values are OR'd together to +create a single integer argument: + + xo_syslog(LOG_ERR | LOG_AUTH, "login-failed", + "Login failed; user '{:user}' from host '{:address}'", + user, addr); + +These values are defined in . + +The priority value indicates the importance and potential impact of +each message. + +|-------------+-------------------------------------------------------| +| Priority | Description | +|-------------+-------------------------------------------------------| +| LOG_EMERG | A panic condition, normally broadcast to all users | +| LOG_ALERT | A condition that should be corrected immediately | +| LOG_CRIT | Critical conditions | +| LOG_ERR | Generic errors | +| LOG_WARNING | Warning messages | +| LOG_NOTICE | Non-error conditions that might need special handling | +| LOG_INFO | Informational messages | +| LOG_DEBUG | Developer-oriented messages | +|-------------+-------------------------------------------------------| + +The facility value indicates the source of message, in fairly generic +terms. + +|---------------+-------------------------------------------------| +| Facility | Description | +|---------------+-------------------------------------------------| +| LOG_AUTH | The authorization system (e.g. login(1)) | +| LOG_AUTHPRIV | As LOG_AUTH, but logged to a privileged file | +| LOG_CRON | The cron daemon: cron(8) | +| LOG_DAEMON | System daemons, not otherwise explicitly listed | +| LOG_FTP | The file transfer protocol daemons | +| LOG_KERN | Messages generated by the kernel | +| LOG_LPR | The line printer spooling system | +| LOG_MAIL | The mail system | +| LOG_NEWS | The network news system | +| LOG_SECURITY | Security subsystems, such as ipfw(4) | +| LOG_SYSLOG | Messages generated internally by syslogd(8) | +| LOG_USER | Messages generated by user processes (default) | +| LOG_UUCP | The uucp system | +| LOG_LOCAL0..7 | Reserved for local use | +|---------------+-------------------------------------------------| + +In addition to the values listed above, xo_open_log accepts a set of +addition flags requesting specific behaviors. + +|------------+----------------------------------------------------| +| Flag | Description | +|------------+----------------------------------------------------| +| LOG_CONS | If syslogd fails, attempt to write to /dev/console | +| LOG_NDELAY | Open the connection to syslogd(8) immediately | +| LOG_PERROR | Write the message also to standard error output | +| LOG_PID | Log the process id with each message | +|------------+----------------------------------------------------| + +*** xo_syslog + +Use the xo_syslog function to generate syslog messages by calling it +with a log priority and facility, a message name, a format string, and +a set of arguments. The priority/facility argument are discussed +above, as is the message name. + +The format string follows the same conventions as xo_emit's format +string, with each field being rendered as an SD-PARAM pair. + + xo_syslog(LOG_ERR, "poofd-missing-file", + "'{:filename}' not found: {:error/%m}", filename); + + ... [poofd-missing-file@32473 filename="/etc/poofd.conf" + error="Permission denied"] '/etc/poofd.conf' not + found: Permission denied + +*** Support functions + +**** xo_vsyslog + +xo_vsyslog is identical in function to xo_syslog, but takes the set of +arguments using a va_list. + + void my_log (const char *name, const char *fmt, ...) + { + va_list vap; + va_start(vap, fmt); + xo_vsyslog(LOG_ERR, name, fmt, vap); + va_end(vap); + } + +**** xo_open_log + +xo_open_log functions similar to openlog(3), allowing customization of +the program name, the log facility number, and the additional option +flags described in ^priority^. + + void + xo_open_log (const char *ident, int logopt, int facility); + +**** xo_close_log + +xo_close_log functions similar to closelog(3), closing the log file +and releasing any associated resources. + + void + xo_close_log (void); + +**** xo_set_logmask + +xo_set_logmask function similar to setlogmask(3), restricting the set +of generated log event to those whose associated bit is set in +maskpri. Use LOG_MASK(pri) to find the appropriate bit, or +LOG_UPTO(toppri) to create a mask for all priorities up to and +including toppri. + + int + xo_set_logmask (int maskpri); + + Example: + setlogmask(LOG_UPTO(LOG_WARN)); + +**** xo_set_syslog_enterprise_id + +Use the xo_set_syslog_enterprise_id to supply a platform- or +application-specific enterprise id. This value is used in any +future syslog messages. + +Ideally, the operating system should supply a default value via the +"kern.syslog.enterprise_id" sysctl value. Lacking that, the +application should provide a suitable value. + + void + xo_set_syslog_enterprise_id (unsigned short eid); + +Enterprise IDs are administered by IANA, the Internet Assigned Number +Authority. The complete list is EIDs on their web site: + + https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers + +New EIDs can be requested from IANA using the following page: + + http://pen.iana.org/pen/PenApplication.page + +Each software development organization that defines a set of syslog +messages should register their own EID and use that value in their +software to ensure that messages can be uniquely identified by the +combination of EID + message name. + +** Creating Custom Encoders + +The number of encoding schemes in current use is staggering, with new +and distinct schemes appearing daily. While libxo provide XML, JSON, +HMTL, and text natively, there are requirements for other encodings. + +Rather than bake support for all possible encoders into libxo, the API +allows them to be defined externally. libxo can then interfaces with +these encoding modules using a simplistic API. libxo processes all +functions calls, handles state transitions, performs all formatting, +and then passes the results as operations to a customized encoding +function, which implements specific encoding logic as required. This +means your encoder doesn't need to detect errors with unbalanced +open/close operations but can rely on libxo to pass correct data. + +By making a simple API, libxo internals are not exposed, insulating the +encoder and the library from future or internal changes. + +The three elements of the API are: +- loading +- initialization +- operations + +The following sections provide details about these topics. + +libxo source contain an encoder for Concise Binary Object +Representation, aka CBOR (RFC 7049) which can be used as used as an +example for the API. + +*** Loading Encoders + +Encoders can be registered statically or discovered dynamically. +Applications can choose to call the xo_encoder_register() +function to explicitly register encoders, but more typically they are +built as shared libraries, placed in the libxo/extensions directory, +and loaded based on name. libxo looks for a file with the name of the encoder +and an extension of ".enc". This can be a file or a symlink to the +shared library file that supports the encoder. + + % ls -1 lib/libxo/extensions/*.enc + lib/libxo/extensions/cbor.enc + lib/libxo/extensions/test.enc + +*** Encoder Initialization + +Each encoder must export a symbol used to access the library, which +must have the following signature: + + int xo_encoder_library_init (XO_ENCODER_INIT_ARGS); + +XO_ENCODER_INIT_ARGS is a macro defined in xo_encoder.h that defines +an argument called "arg", a pointer of the type +xo_encoder_init_args_t. This structure contains two fields: + +- xei_version is the version number of the API as implemented within +libxo. This version is currently as 1 using XO_ENCODER_VERSION. This +number can be checked to ensure compatibility. The working assumption +is that all versions should be backward compatible, but each side may +need to accurately know the version supported by the other side. +xo_encoder_library_init can optionally check this value, and must then +set it to the version number used by the encoder, allowing libxo to +detect version differences and react accordingly. For example, if +version 2 adds new operations, then libxo will know that an encoding +library that set xei_version to 1 cannot be expected to handle those +new operations. + +- xei_handler must be set to a pointer to a function of type +xo_encoder_func_t, as defined in xo_encoder.h. This function +takes a set of parameters: +-- xop is a pointer to the opaque xo_handle_t structure +-- op is an integer representing the current operation +-- name is a string whose meaning differs by operation +-- value is a string whose meaning differs by operation +-- private is an opaque structure provided by the encoder + +Additional arguments may be added in the future, so handler functions +should use the XO_ENCODER_HANDLER_ARGS macro. An appropriate +"extern" declaration is provided to help catch errors. + +Once the encoder initialization function has completed processing, it +should return zero to indicate that no error has occurred. A non-zero +return code will cause the handle initialization to fail. + +*** Operations + +The encoder API defines a set of operations representing the +processing model of libxo. Content is formatted within libxo, and +callbacks are made to the encoder's handler function when data is +ready to be processed. + +|-----------------------+---------------------------------------| +| Operation | Meaning (Base function) | +|-----------------------+---------------------------------------| +| XO_OP_CREATE | Called when the handle is created | +| XO_OP_OPEN_CONTAINER | Container opened (xo_open_container) | +| XO_OP_CLOSE_CONTAINER | Container closed (xo_close_container) | +| XO_OP_OPEN_LIST | List opened (xo_open_list) | +| XO_OP_CLOSE_LIST | List closed (xo_close_list) | +| XO_OP_OPEN_LEAF_LIST | Leaf list opened (xo_open_leaf_list) | +| XO_OP_CLOSE_LEAF_LIST | Leaf list closed (xo_close_leaf_list) | +| XO_OP_OPEN_INSTANCE | Instance opened (xo_open_instance) | +| XO_OP_CLOSE_INSTANCE | Instance closed (xo_close_instance) | +| XO_OP_STRING | Field with Quoted UTF-8 string | +| XO_OP_CONTENT | Field with content | +| XO_OP_FINISH | Finish any pending output | +| XO_OP_FLUSH | Flush any buffered output | +| XO_OP_DESTROY | Clean up resources | +| XO_OP_ATTRIBUTE | An attribute name/value pair | +| XO_OP_VERSION | A version string | +|-----------------------+---------------------------------------| + +For all the open and close operations, the name parameter holds the +name of the construct. For string, content, and attribute operations, +the name parameter is the name of the field and the value parameter is +the value. "string" are differentiated from "content" to allow differing +treatment of true, false, null, and numbers from real strings, though +content values are formatted as strings before the handler is called. +For version operations, the value parameter contains the version. + +All strings are encoded in UTF-8. + +* The "xo" Utility + +The "xo" utility allows command line access to the functionality of +the libxo library. Using "xo", shell scripts can emit XML, JSON, and +HTML using the same commands that emit text output. + +The style of output can be selected using a specific option: "-X" for +XML, "-J" for JSON, "-H" for HTML, or "-T" for TEXT, which is the +default. The "--style ardinalyayammetersgrayErmissionpay eniedday6otuslay-oyay-eltayay \ No newline at end of file Index: vendor/Juniper/libxo/0.8.2/tests/gettext/saved/gt_01.XP.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/gettext/saved/gt_01.XP.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/gettext/saved/gt_01.XP.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/gettext/saved/gt_01.XP.out (revision 319998) @@ -0,0 +1,49 @@ + + amingflay + ordsway + urningbay + ymay + ouchcay + amingflay + ordsway + urningbay + ymay + ouchcay + 0 + 1 + 2 + 3 + 4 + 1234 + 1234 + foop + 4321 + + 1234 + foop + 4321 + + 1234 + foop + 4321 + + 3 + 1.2.3 + Tue Jun 23 18:47:09 UTC 2015 + <__warning> + gt_01.test + Nableuay otay ectulatobjay orwardfay elocipingvay + ectulatobjay + Ermissionpay eniedday + + <__warning> + gt_01.test + automaticyay ynchronizationsay ofyay ardinalyay ammetersgray ailedfay + + ardinalyay + ammetersgray + Ermissionpay eniedday + + 6 + otuslay-oyay-eltayay + Index: vendor/Juniper/libxo/0.8.2/tests/gettext/strerror.pot =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/gettext/strerror.pot (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/gettext/strerror.pot (revision 319998) @@ -0,0 +1,468 @@ +# +# Copyright (c) 1982, 1985, 1993 +# The Regents of the University of California. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of the University nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +# SUCH DAMAGE. +# +# List of system errors ala strerror() and sys_errlist +# Phil Shafer , 2015. +# +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2015-07-01 16:15-0400\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=CHARSET\n" +"Content-Transfer-Encoding: 8bit\n" + +msgid "Received {:received} {N:byte,bytes} from {:from}#{:port} in {:time} ms\n" +msgstr "" + +# 0 - ENOERROR +msgid "No error: 0" +msgstr "" + +# 1 - EPERM +msgid "Operation not permitted" +msgstr "" + +# 2 - ENOENT +msgid "No such file or directory" +msgstr "" + +# 3 - ESRCH +msgid "No such process" +msgstr "" + +# 4 - EINTR +msgid "Interrupted system call" +msgstr "" + +# 5 - EIO +msgid "Input/output error" +msgstr "" + +# 6 - ENXIO +msgid "Device not configured" +msgstr "" + +# 7 - E2BIG +msgid "Argument list too long" +msgstr "" + +# 8 - ENOEXEC +msgid "Exec format error" +msgstr "" + +# 9 - EBADF +msgid "Bad file descriptor" +msgstr "" + +# 10 - ECHILD +msgid "No child processes" +msgstr "" + +# 11 - EDEADLK +msgid "Resource deadlock avoided" +msgstr "" + +# 12 - ENOMEM +msgid "Cannot allocate memory" +msgstr "" + +# 13 - EACCES +msgid "Permission denied" +msgstr "" + +# 14 - EFAULT +msgid "Bad address" +msgstr "" + +# 15 - ENOTBLK +msgid "Block device required" +msgstr "" + +# 16 - EBUSY +msgid "Device busy" +msgstr "" + +# 17 - EEXIST +msgid "File exists" +msgstr "" + +# 18 - EXDEV +msgid "Cross-device link" +msgstr "" + +# 19 - ENODEV +msgid "Operation not supported by device" +msgstr "" + +# 20 - ENOTDIR +msgid "Not a directory" +msgstr "" + +# 21 - EISDIR +msgid "Is a directory" +msgstr "" + +# 22 - EINVAL +msgid "Invalid argument" +msgstr "" + +# 23 - ENFILE +msgid "Too many open files in system" +msgstr "" + +# 24 - EMFILE +msgid "Too many open files" +msgstr "" + +# 25 - ENOTTY +msgid "Inappropriate ioctl for device" +msgstr "" + +# 26 - ETXTBSY +msgid "Text file busy" +msgstr "" + +# 27 - EFBIG +msgid "File too large" +msgstr "" + +# 28 - ENOSPC +msgid "No space left on device" +msgstr "" + +# 29 - ESPIPE +msgid "Illegal seek" +msgstr "" + +# 30 - EROFS +msgid "Read-only file system" +msgstr "" + +# 31 - EMLINK +msgid "Too many links" +msgstr "" + +# 32 - EPIPE +msgid "Broken pipe" +msgstr "" + +# +# math software +# + +# 33 - EDOM +msgid "Numerical argument out of domain" +msgstr "" + +# 34 - ERANGE +msgid "Result too large" +msgstr "" + +# +# non-blocking and interrupt i/o +# + +# 35 - EAGAIN +# 35 - EWOULDBLOCK +msgid "Resource temporarily unavailable" +msgstr "" + +# 36 - EINPROGRESS +msgid "Operation now in progress" +msgstr "" + +# 37 - EALREADY +msgid "Operation already in progress" +msgstr "" + + +# +# ipc/network software -- argument errors +# + +# 38 - ENOTSOCK +msgid "Socket operation on non-socket" +msgstr "" + +# 39 - EDESTADDRREQ +msgid "Destination address required" +msgstr "" + +# 40 - EMSGSIZE +msgid "Message too long" +msgstr "" + +# 41 - EPROTOTYPE +msgid "Protocol wrong type for socket" +msgstr "" + +# 42 - ENOPROTOOPT +msgid "Protocol not available" +msgstr "" + +# 43 - EPROTONOSUPPORT +msgid "Protocol not supported" +msgstr "" + +# 44 - ESOCKTNOSUPPORT +msgid "Socket type not supported" +msgstr "" + +# 45 - EOPNOTSUPP +msgid "Operation not supported" +msgstr "" + +# 46 - EPFNOSUPPORT +msgid "Protocol family not supported" +msgstr "" + +# 47 - EAFNOSUPPORT +msgid "Address family not supported by protocol family" +msgstr "" + +# 48 - EADDRINUSE +msgid "Address already in use" +msgstr "" + +# 49 - EADDRNOTAVAIL +msgid "Can't assign requested address" +msgstr "" + +# +# ipc/network software -- operational errors +# + +# 50 - ENETDOWN +msgid "Network is down" +msgstr "" + +# 51 - ENETUNREACH +msgid "Network is unreachable" +msgstr "" + +# 52 - ENETRESET +msgid "Network dropped connection on reset" +msgstr "" + +# 53 - ECONNABORTED +msgid "Software caused connection abort" +msgstr "" + +# 54 - ECONNRESET +msgid "Connection reset by peer" +msgstr "" + +# 55 - ENOBUFS +msgid "No buffer space available" +msgstr "" + +# 56 - EISCONN +msgid "Socket is already connected" +msgstr "" + +# 57 - ENOTCONN +msgid "Socket is not connected" +msgstr "" + +# 58 - ESHUTDOWN +msgid "Can't send after socket shutdown" +msgstr "" + +# 59 - ETOOMANYREFS +msgid "Too many references: can't splice" +msgstr "" + +# 60 - ETIMEDOUT +msgid "Operation timed out" +msgstr "" + +# 61 - ECONNREFUSED +msgid "Connection refused" +msgstr "" + +# 62 - ELOOP +msgid "Too many levels of symbolic links" +msgstr "" + +# 63 - ENAMETOOLONG +msgid "File name too long" +msgstr "" + +# +# should be rearranged +# + +# 64 - EHOSTDOWN +msgid "Host is down" +msgstr "" + +# 65 - EHOSTUNREACH +msgid "No route to host" +msgstr "" + +# 66 - ENOTEMPTY +msgid "Directory not empty" +msgstr "" + +# +# quotas & mush +# + +# 67 - EPROCLIM +msgid "Too many processes" +msgstr "" + +# 68 - EUSERS +msgid "Too many users" +msgstr "" + +# 69 - EDQUOT +msgid "Disc quota exceeded" +msgstr "" + +# +# Network File System +# + +# 70 - ESTALE +msgid "Stale NFS file handle" +msgstr "" + +# 71 - EREMOTE +msgid "Too many levels of remote in path" +msgstr "" + +# 72 - EBADRPC +msgid "RPC struct is bad" +msgstr "" + +# 73 - ERPCMISMATCH +msgid "RPC version wrong" +msgstr "" + +# 74 - EPROGUNAVAIL +msgid "RPC prog. not avail" +msgstr "" + +# 75 - EPROGMISMATCH +msgid "Program version wrong" +msgstr "" + +# 76 - EPROCUNAVAIL +msgid "Bad procedure for program" +msgstr "" + +# 77 - ENOLCK +msgid "No locks available" +msgstr "" + +# 78 - ENOSYS +msgid "Function not implemented" +msgstr "" + +# 79 - EFTYPE +msgid "Inappropriate file type or format" +msgstr "" + +# 80 - EAUTH +msgid "Authentication error" +msgstr "" + +# 81 - ENEEDAUTH +msgid "Need authenticator" +msgstr "" + +# 82 - EIDRM +msgid "Identifier removed" +msgstr "" + +# 83 - ENOMSG +msgid "No message of desired type" +msgstr "" + +# 84 - EOVERFLOW +msgid "Value too large to be stored in data type" +msgstr "" + +# 85 - ECANCELED +msgid "Operation canceled" +msgstr "" + +# 86 - EILSEQ +msgid "Illegal byte sequence" +msgstr "" + +# 87 - ENOATTR +msgid "Attribute not found" +msgstr "" + +# +# General +# + +# 88 - EDOOFUS +msgid "Programming error" +msgstr "" + +# 89 - EBADMSG +msgid "Bad message" +msgstr "" + +# 90 - EMULTIHOP +msgid "Multihop attempted" +msgstr "" + +# 91 - ENOLINK +msgid "Link has been severed" +msgstr "" + +# 92 - EPROTO +msgid "Protocol error" +msgstr "" + +# 93 - ENOTCAPABLE +msgid "Capabilities insufficient" +msgstr "" + +# 94 - ECAPMODE +msgid "Not permitted in capability mode" +msgstr "" + +# 95 - ENOTRECOVERABLE +msgid "State not recoverable" +msgstr "" + +# 96 - EOWNERDEAD +msgid "Previous owner died" +msgstr "" Index: vendor/Juniper/libxo/0.8.2/tests/gettext/gt_01.c =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/gettext/gt_01.c (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/gettext/gt_01.c (revision 319998) @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2015, Juniper Networks, Inc. + * All rights reserved. + * This SOFTWARE is licensed under the LICENSE provided in the + * ../Copyright file. By downloading, installing, copying, or otherwise + * using the SOFTWARE, you agree to be bound by the terms of that + * LICENSE. + * Phil Shafer, June 2015 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "xo.h" + +int +main (int argc, char **argv) +{ + static char domainname[] = "gt_01"; + static char path[MAXPATHLEN]; + const char *tzone = "EST"; + const char *lang = "pig_latin"; + + argc = xo_parse_args(argc, argv); + if (argc < 0) + return 1; + + for (argc = 1; argv[argc]; argc++) { + if (strcmp(argv[argc], "tz") == 0) + tzone = argv[++argc]; + else if (strcmp(argv[argc], "lang") == 0) + lang = argv[++argc]; + else if (strcmp(argv[argc], "po") == 0) + strlcpy(path, argv[++argc], sizeof(path)); + } + + setenv("LANG", lang, 1); + setenv("TZ", tzone, 1); + + if (path[0] == 0) { + getcwd(path, sizeof(path)); + strlcat(path, "/po", sizeof(path)); + } + + setlocale(LC_ALL, ""); + bindtextdomain(domainname, path); + bindtextdomain("ldns", path); + bindtextdomain("strerror", path); + textdomain(domainname); + tzset(); + + xo_open_container("top"); + + xo_emit("{G:}Your {qg:adjective} {g:noun} is {g:verb} {qg:owner} {g:target}\n", + "flaming", "sword", "burning", "my", "couch"); + + xo_emit("{G:}The {qg:adjective} {g:noun} was {g:verb} {qg:owner} {g:target}\n", + "flaming", "sword", "burning", "my", "couch"); + + + int i; + for (i = 0; i < 5; i++) + xo_emit("{lw:bytes/%d}{Ngp:byte,bytes}\n", i); + + xo_emit("{G:}{L:total} {:total/%u}\n", 1234); + + xo_emit("{G:ldns}Received {:received/%zu} {Ngp:byte,bytes} " + "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", + (size_t) 1234, "foop", 4321, 32); + + xo_emit("{G:}Received {:received/%zu} {Ngp:byte,bytes} " + "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", + (size_t) 1234, "foop", 4321, 32); + + xo_emit("{G:/%s}Received {:received/%zu} {Ngp:byte,bytes} " + "from {:from/%s}#{:port/%d} in {:time/%d} ms\n", + "ldns", (size_t) 1234, "foop", 4321, 32); + + struct timeval tv; + tv.tv_sec = 1435085229; + tv.tv_usec = 123456; + + struct tm tm; + (void) gmtime_r(&tv.tv_sec, &tm); + + char date[64]; + strftime(date, sizeof(date), "%+", &tm); + + xo_emit("{G:}Only {:marzlevanes/%d} {Ngp:marzlevane,marzlevanes} " + "are functioning correctly\n", 3); + + xo_emit("{G:}Version {:version} {:date}\n", "1.2.3", date); + + errno = EACCES; + xo_emit_warn("{G:}Unable to {g:verb/objectulate} forward velociping"); + xo_emit_warn("{G:}{g:style/automatic} synchronization of {g:type/cardinal} " + "{g:target/grammeters} failed"); + xo_emit("{G:}{Lwcg:hydrocoptic marzlevanes}{:marzlevanes/%d}\n", 6); + + xo_emit("{G:}{Lwcg:Windings}{g:windings}\n", "lotus-o-delta"); + + xo_close_container("top"); + xo_finish(); + + return 0; +} Property changes on: vendor/Juniper/libxo/0.8.2/tests/gettext/gt_01.c ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/tests/gettext/gt_01.pot =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/gettext/gt_01.pot (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/gettext/gt_01.pot (revision 319998) @@ -0,0 +1,105 @@ +# SOME DESCRIPTIVE TITLE. +# This file is put in the public domain. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2015-07-01 16:15-0400\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=CHARSET\n" +"Content-Transfer-Encoding: 8bit\n" + +#: gt_01.c:42 +#, c-format +msgid "{:bytes}{N:byte,bytes}\n" +msgstr "" + +#: gt_01.c:44 +#, c-format +msgid "{L:total} {:total}\n" +msgstr "" + +#: gt_01.c:60 +#, c-format +msgid "Only {:marzlevanes} {N:marzlevane,marzlevanes} are functioning correctly\n" +msgstr "" + +#: gt_01.c:63 +msgid "Version {:version} {:date}\n" +msgstr "" + +#: gt_01.c:66 +msgid "Unable to {:verb} forward velociping" +msgstr "" + +#: gt_01.c:67 +msgid "{:style} synchronization of {:type} {:target} failed" +msgstr "" + +#: gt_01.c:69 +#, c-format +msgid "{L:hydrocoptic marzlevanes}{:marzlevanes}\n" +msgstr "" + +#: gt_01.c:71 +msgid "{L:Windings}{:windings}\n" +msgstr "" + +msgid "byte" +msgid_plural "bytes" +msgstr[0] "" +msgstr[1] "" + +msgid "marzlevane" +msgid_plural "marzlevanes" +msgstr[0] "" +msgstr[1] "" + +msgid "lotus-o-delta" +msgstr "" + +msgid "cardinal" +msgstr "" + +msgid "automatic" +msgstr "" + +msgid "grammeters" +msgstr "" + +msgid "objectulate" +msgstr "" + +msgid "hydrocoptic marzlevanes" +msgstr "" + +msgid "Windings" +msgstr "" + +msgid "Your {:adjective} {:noun} is {:verb} {:owner} {:target}\n" +msgstr "" + +msgid "The {:adjective} {:noun} was {:verb} {:owner} {:target}\n" +msgstr "" + +msgid "flaming" +msgstr "" + +msgid "sword" +msgstr "" + +msgid "burning" +msgstr "" + +msgid "my" +msgstr "" + +msgid "couch" +msgstr "" Index: vendor/Juniper/libxo/0.8.2/tests/gettext/ldns.pot =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/gettext/ldns.pot (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/gettext/ldns.pot (revision 319998) @@ -0,0 +1,28 @@ +# SOME DESCRIPTIVE TITLE. +# This file is put in the public domain. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2015-07-01 16:15-0400\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=CHARSET\n" +"Content-Transfer-Encoding: 8bit\n" + +#: gt_01.c:46 +#, c-format +msgid "Received {:received} {N:byte,bytes} from {:from}#{:port} in {:time} ms\n" +msgstr "" + +msgid "byte" +msgid_plural "bytes" +msgstr[0] "" +msgstr[1] "" + Index: vendor/Juniper/libxo/0.8.2/tests/gettext =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/gettext (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/gettext (revision 319998) Property changes on: vendor/Juniper/libxo/0.8.2/tests/gettext ___________________________________________________________________ Added: svn:ignore ## -0,0 +1 ## +Makefile.in Index: vendor/Juniper/libxo/0.8.2/tests/xo/Makefile.am =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/Makefile.am (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/Makefile.am (revision 319998) @@ -0,0 +1,89 @@ +# +# $Id$ +# +# Copyright 2014, Juniper Networks, Inc. +# All rights reserved. +# This SOFTWARE is licensed under the LICENSE provided in the +# ../Copyright file. By downloading, installing, copying, or otherwise +# using the SOFTWARE, you agree to be bound by the terms of that +# LICENSE. + +AM_CFLAGS = -I${top_srcdir} -I${top_srcdir}/libxo + +# Ick: maintained by hand! +TEST_CASES = \ +xo_01.sh + +X=\ +xo_02.sh \ +xo_03.sh \ +xo_04.sh \ +xo_05.sh \ +xo_06.sh + +# TEST_CASES := $(shell cd ${srcdir} ; echo *.c ) + +EXTRA_DIST = \ + ${TEST_CASES} \ + ${addprefix saved/, ${TEST_CASES:.sh=.T.err}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.T.out}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.XP.err}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.XP.out}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.JP.err}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.JP.out}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.HP.err}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.HP.out}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.X.err}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.X.out}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.J.err}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.J.out}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.H.err}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.H.out}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.HIPx.err}} \ + ${addprefix saved/, ${TEST_CASES:.sh=.HIPx.out}} + +S2O = | ${SED} '1,/@@/d' + +all: + +#TEST_TRACE = set -x ; + +XO=../../xo/xo + +TEST_ONE = \ + ${CHECKER} sh ${srcdir}/$$base.sh "${XO} --libxo:W$$fmt" ${TEST_OPTS} \ + > out/$$base.$$fmt.out 2> out/$$base.$$fmt.err ; \ + ${DIFF} -Nu ${srcdir}/saved/$$base.$$fmt.out out/$$base.$$fmt.out ${S2O} ; \ + ${DIFF} -Nu ${srcdir}/saved/$$base.$$fmt.err out/$$base.$$fmt.err ${S2O} + +TEST_FORMATS = T XP JP HP X J H HIPx + +test tests: ${bin_PROGRAMS} + @${MKDIR} -p out + -@ ${TEST_TRACE} (for test in ${TEST_CASES} ; do \ + base=`${BASENAME} $$test .sh` ; \ + (for fmt in ${TEST_FORMATS}; do \ + echo "... $$test ... $$fmt ..."; \ + ${TEST_ONE}; \ + true; \ + done) \ + done) + +one: + -@(test=${TEST_CASE}; data=${TEST_DATA}; ${TEST_ONE} ; true) + +accept: + -@(for test in ${TEST_CASES} ; do \ + base=`${BASENAME} $$test .sh` ; \ + (for fmt in ${TEST_FORMATS}; do \ + echo "... $$test ... $$fmt ..."; \ + ${CP} out/$$base.$$fmt.out ${srcdir}/saved/$$base.$$fmt.out ; \ + ${CP} out/$$base.$$fmt.err ${srcdir}/saved/$$base.$$fmt.err ; \ + done) \ + done) + +CLEANFILES = +CLEANDIRS = out + +clean-local: + rm -rf ${CLEANDIRS} Property changes on: vendor/Juniper/libxo/0.8.2/tests/xo/Makefile.am ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.H.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.H.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.H.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.H.out (revision 319998) @@ -0,0 +1 @@ +
Item
one
is
number
001
,
color
:
red
Item
two
is
number
002
,
color
:
blue
Item
three
is
number
003
,
color
:
green
Item
four
is
number
004
,
color
:
yellow
\ No newline at end of file Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.HIPx.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.HIPx.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.HIPx.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.HIPx.out (revision 319998) @@ -0,0 +1,52 @@ +
+
Item
+
one
+
is
+
number
+
+
001
+
,
+
color
+
:
+
+
red
+
+
+
Item
+
two
+
is
+
number
+
+
002
+
,
+
color
+
:
+
+
blue
+
+
+
Item
+
three
+
is
+
number
+
+
003
+
,
+
color
+
:
+
+
green
+
+
+
Item
+
four
+
is
+
number
+
+
004
+
,
+
color
+
:
+
+
yellow
+
Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.HP.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.HP.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.HP.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.HP.out (revision 319998) @@ -0,0 +1,52 @@ +
+
Item
+
one
+
is
+
number
+
+
001
+
,
+
color
+
:
+
+
red
+
+
+
Item
+
two
+
is
+
number
+
+
002
+
,
+
color
+
:
+
+
blue
+
+
+
Item
+
three
+
is
+
number
+
+
003
+
,
+
color
+
:
+
+
green
+
+
+
Item
+
four
+
is
+
number
+
+
004
+
,
+
color
+
:
+
+
yellow
+
Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.J.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.J.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.J.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.J.out (revision 319998) @@ -0,0 +1 @@ +"top": {"item": {"name":"one","value":1,"color":"red"}, "item": {"name":"two","value":2,"color":"blue"}, "item": {"name":"three","value":3,"color":"green"}, "item": {"name":"four","value":4,"color":"yellow"}} Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.JP.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.JP.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.JP.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.JP.out (revision 319998) @@ -0,0 +1,22 @@ +"top": { + "item": { + "name": "one", + "value": 1, + "color": "red" + }, + "item": { + "name": "two", + "value": 2, + "color": "blue" + }, + "item": { + "name": "three", + "value": 3, + "color": "green" + }, + "item": { + "name": "four", + "value": 4, + "color": "yellow" + } +} Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.T.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.T.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.T.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.T.out (revision 319998) @@ -0,0 +1,4 @@ +Item one is number 001, color: red +Item two is number 002, color: blue +Item three is number 003, color: green +Item four is number 004, color: yellow Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.X.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.X.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.X.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.X.out (revision 319998) @@ -0,0 +1 @@ +one1redtwo2bluethree3greenfour4yellow \ No newline at end of file Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.XP.err =================================================================== Index: vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.XP.out =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.XP.out (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/saved/xo_01.XP.out (revision 319998) @@ -0,0 +1,22 @@ + + + one + 1 + red + + + two + 2 + blue + + + three + 3 + green + + + four + 4 + yellow + + Index: vendor/Juniper/libxo/0.8.2/tests/xo/xo_01.sh =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo/xo_01.sh (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo/xo_01.sh (revision 319998) @@ -0,0 +1,27 @@ +# +# $Id$ +# +# Copyright 2014, Juniper Networks, Inc. +# All rights reserved. +# This SOFTWARE is licensed under the LICENSE provided in the +# ../Copyright file. By downloading, installing, copying, or otherwise +# using the SOFTWARE, you agree to be bound by the terms of that +# LICENSE. + +XO=$1 +shift + +XOP="${XO} --warn --depth 1 --leading-xpath /top" + +${XO} --open top + +NF= +for i in one:1:red two:2:blue three:3:green four:4:yellow ; do + set `echo $i | sed 's/:/ /g'` + ${XOP} ${NF} --wrap item \ + 'Item {k:name} is {Lw:number}{:value/%03d/%d}, {Lwc:color}{:color}\n' \ + $1 $2 $3 + NF=--not-first +done + +${XO} --close top \ No newline at end of file Property changes on: vendor/Juniper/libxo/0.8.2/tests/xo/xo_01.sh ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:executable ## -0,0 +1 ## +* \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/tests/xo =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/xo (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/xo (revision 319998) Property changes on: vendor/Juniper/libxo/0.8.2/tests/xo ___________________________________________________________________ Added: svn:ignore ## -0,0 +1 ## +Makefile.in Index: vendor/Juniper/libxo/0.8.2/tests/Makefile.am =================================================================== --- vendor/Juniper/libxo/0.8.2/tests/Makefile.am (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests/Makefile.am (revision 319998) @@ -0,0 +1,32 @@ +# +# Copyright 2014, Juniper Networks, Inc. +# All rights reserved. +# This SOFTWARE is licensed under the LICENSE provided in the +# ../Copyright file. By downloading, installing, copying, or otherwise +# using the SOFTWARE, you agree to be bound by the terms of that +# LICENSE. + +SUBDIRS = core xo + +if HAVE_GETTEXT +SUBDIRS += gettext +endif + +test tests: + @(cur=`pwd` ; for dir in $(SUBDIRS) ; do \ + cd $$dir ; \ + $(MAKE) tests ; \ + cd $$cur ; \ + done) + +accept: + @(cur=`pwd` ; for dir in $(SUBDIRS) ; do \ + cd $$dir ; \ + $(MAKE) accept ; \ + cd $$cur ; \ + done) + +valgrind: + @echo '## Running the regression tests under Valgrind' + @echo '## Go get a cup of coffee it is gonna take a while ...' + ${MAKE} VALGRIND='valgrind -q' tests Property changes on: vendor/Juniper/libxo/0.8.2/tests/Makefile.am ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/tests =================================================================== --- vendor/Juniper/libxo/0.8.2/tests (nonexistent) +++ vendor/Juniper/libxo/0.8.2/tests (revision 319998) Property changes on: vendor/Juniper/libxo/0.8.2/tests ___________________________________________________________________ Added: svn:ignore ## -0,0 +1 ## +Makefile.in Index: vendor/Juniper/libxo/0.8.2/xohtml/xohtml.css =================================================================== --- vendor/Juniper/libxo/0.8.2/xohtml/xohtml.css (nonexistent) +++ vendor/Juniper/libxo/0.8.2/xohtml/xohtml.css (revision 319998) @@ -0,0 +1,1040 @@ +/* + * $Id$ + * + * Copyright 2000, All rights reserved + * See ../Copyright for more information + */ + +#content-wrapper { + margin: 0 4px; +} + +#target-history .empty { + color: #d0d0d0; + text-align:center; +} + +#command-history .empty { + color: grey; + padding-left: 20px; +} + +#prefs { + font-size: 70%; +} + +div[data-key] { + color: red; +} + +div.decoration, div.default, div.header-line { + color: #505050; + font-family: monospace; + white-space: pre-wrap; +} + +div.line:first-child { + padding-top: 10px; +} + +div.padding { + white-space: pre-wrap; + font-family: monospace; + display: inline; +} + +div.label, div.note, div.text { + font-family: monospace; + white-space: pre-wrap; + display: inline; + vertical-align: middle; +/* + * font-weight: bold; + * color: #606060; + */ +} + +div.blank-line { + padding-top: 40px; +} + +div.title { + border-bottom: 2px solid black; + border-top: 2px solid #f0f0ff; + border-radius: 3px; + margin-top: 10px; + color: #1010a0; + background-color: #e0e0ff; + font-family: monospace; + display: inline; + vertical-align: middle; + white-space: pre-wrap; +} + +div.data { + font-family: monospace; +} + +div.line { + display: block; +} + +div.indented { + display: inline; +} + +div.indent { + display: inline; +} + +/* BEGIN LINES */ +div.line { + border: none; +} + +div.item { + border: none; +} + +div.pad { + border: none; +} + +div.blank-line { + border: 1px inset; +} + +div.item { + white-space: pre; +} +/* END LINES */ + +div.muxer-prompt { + padding: 2em; +} + +div.muxer-message, div.muxer-prompt form { + white-space: pre; + display: inline-block; + vertical-align: middle; +} + +div.muxer-buttons { + display: inline-block; + padding: 20px; +} + +div.text, div.decoration, div.data, div.header, div.pad, div.item, div.units { + font-family: monospace; + display: inline; + vertical-align: middle; + white-space: pre-wrap; +} + +div.blank-line { + margin: 5px; +} + +div.indentxxx { + padding-left: 2em; +} + +div.output, configuration-output, configuration-information { + font-family: monospace; + white-space: pre-wrap; +} + +div.header-line { + color: #ffffff; + background: none repeat scroll 0 0 #0D5995; + margin-top: 4px; + padding-top: 4px; + border-top-left-radius: 4px; + border-top-right-radius: 4px; +} + +div.header-line-empty { + color: #ffffff; + background: none repeat scroll 0 0 #0D5995; + padding-top: 4px; + padding-bottom: 2px; +} + + +/* + * juise rendering + */ + +div.hidden, +img.hidden, +button.hidden { + display: none; +} + +div.keeper-active div.icon-box img.keeper { + border: 1px solid #966535; + border-radius: 4px; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; +} + +div.icon-box img.keeper { + border: 1px solid #ffffff; + border-radius: 4px; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; +} + +div#debug-container { + background-color: #ccc; + border: 1px solid #d0d0ff; + bottom: 0; + color: blue; + display: none; + font-size: 70%; + position: fixed; + width: 100%; +} + +div#debug-log { + background-color: #ffffff; + max-height: 200px; + overflow-y: auto; + padding: 0 5px; + white-space: pre-wrap; +} + +div#header { + height: 30px; + padding: 0px 0px 40px 30px ; +} + +div#header-logo { + display: inline-block; + background: url(/images/logo.png) no-repeat; + height: 60px; + width: 150px; +} + +div#header-info { + display: table-cell; + height: 60px; + width: 60%; + background-color: #ffffff; + font-size: 80%; + padding-left: 10px; +} + +.prefsbtn { + background: rgb(230, 230, 230) url(/images/gear.png) no-repeat center; + margin-top: 5px; + min-height: 40px; + width: 40px; + border-radius: 2px; + cursor: pointer; + float: right; + box-shadow: 0 1px 1px #fff, + 0 -1px 1px #666, + inset 0 -1px 1px rgba(0,0,0,0.5), + inset 0 1px 1px rgba(255,255,255,0.8); +} + +.prefsbtn:hover { + background-color: #dde; +} + +div#header-actions { + height: 60px; + width: 200px; + display: table-cell; + padding-left: 10px; +} + +xdiv#header-actions div, +xdiv#header-info div { + display: inline-block; +} + +div#target-list { + display: none; + clear: both; +} + +div#target-title { + display: table-cell; + padding: 6px 1px 6px 0px; +} + +div#target-history { + border: 1px solid #659635; + position: absolute; + width: 25%; + padding-left: 0px; + padding-right: 0px; +} + +form#target-history-form { + margin-bottom: 0px; +} + +input#target-history-submit { + background: url(none); + margin-left: 2px; +} + +div.target-history-name { + display: inline-block; +} + +div.target-history-entry-parent:hover { + background: #659635; +} + +div.target-history-entry-parent:first-child { + border-top: 0px none; +} + +div.target-history-entry-parent { + border-top: 1px solid #659635; + padding-left: 8px; + padding-right: 8px; +} +div.target-history-entry { + display: inline-block; +} + +div.target-info { + display: inline-block; + font-family: Helvetica, Arial, sans-serif; + font-weight: bold; + font-size: 12px; + margin-right: 10px; + margin-left: 10px; + padding: 5px 10px 5px 10px; +} + +div#target-contents, +div#target-contents-none { + display: table-cell; + font-family: Verdana, Arial, Helvetica, sans-serif ; +} + +div#target-contents-none { + padding-left: 10px; + font-size: 70%; +} + +div.target { + display: inline-block; + margin-left: 2px; + margin-right: 2px; +} + +div#command-history { + border: 1px solid #c0c0ff; + position: absolute; + width: 60em; + font-family: Verdana, Arial, Helvetica, sans-serif ; + font-family: monospace; + font-size: 12px; + background: #e0e0ff; + padding-left: 0px; + padding-right: 0px; +} + +div.command-history-entry:hover { + background: #c0c0ff; +} + +div.command-history-entry:first-child { + border-top: 0px none; +} + +div.command-history-entry { + border-top: 1px solid #c0c0ff; + padding-left: 8px; + padding-right: 8px; +} + +div#footer { + padding-top: 100px; + clear: both; + display: block; + height: 100px; + width: 100%; + font-size: 8; + text-align: center; +} + +div#input-history { + display: inline-block; + float: left; + margin-right: 5px; + position: relative; + width: 70%; +} + +div#input-top { + display: block; + height: 70px; + padding: 10px; + margin-bottom: 10px; + background-color: rgb(245, 245, 245); + border-bottom: rgb(200, 200, 200) solid 1px; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); +} + +div#input-history .pulldown { + border: solid 1px rgb(180, 180, 200); + max-height: 300px; + overflow-y: auto; + padding: 0px; + width: 100%; +} + +div#mru-pulldown { + margin-top: 40px; + position: absolute; + width: 100%; + z-index: 9999; +} + +div#mru-pulldown .mru-item { + padding: 5px; +} + +div#mru-pulldown .mru-item:hover { + background: rgb(242, 244, 255); + cursor: pointer; + font-weight: 700; +} + +div#recent-devices { + margin-top: 10px; +} + +div#recent-devices a { + color: rgb(0, 50, 112); + cursor: pointer; + text-decoration: underline; +} + +div#input-top .logo { + float: left; + margin: 0px 10px 0px 10px; +} + +form#target-input-form, +form#command-input-form { + display: inline-block; +} + +div#target-top, +div#command-top { + display: inline-block; + float: left; + margin: 10px 5px 0px 0px; + width: 100%; +} + +div#command-top .input-box { + height: 32px; + min-width: 500px; + padding: 1px; + background-color: #fff; + width: 100%; +} + +div#command-top .focus-off { + border: solid 1px rgb(180, 180, 200); +} + +div#command-top .focus-on { + border: solid 1px rgb(180, 180, 200); + box-shadow: 0px 0px 8px rgba(100, 100, 200, 0.5); +} + +div#input-top .input-enter { + margin: 10px 0px 10px 0px; + float: left; +} + +input.command-input { + font-family: Verdana, Arial, Helvetica, sans-serif ; + font-family: monospace; + font-size: 12px; +} + +div#output-top { + margin-bottom: 20px; +} + +div.output-wrapper { +/* border: 1px solid blue; */ + margin-top: 5px; + background: white; + padding: 0px; +} + +div.output-header button { + margin-right: 4px; +} + +div.output-header { + padding: 4px; +} + +div.output-header div.target-value { + margin-left: 4px; +} + +div.output-header div.command-value { + margin-right: 4px; +} + +div.output-header div.target-value, +div.output-header div.command-value { + font-weight: normal; + font-size: 12px; +} + +div.target-value, +input.target-value { + display: inline-block; + font-size: 12px; + font-family: Verdana, Arial, Helvetica, sans-serif ; +} + +div.label, div.note { + display: inline; +/* + padding-left: 3px; + padding-right: 3px; +*/ + font-size: 12px; +} + +div.command-value, +input.command-value { + display: inline-block; + font-size: 14px; +} + +div.command-number { + display: inline-block; + font-size: 70%; + float: right; +} + +div#ember-view .output-content { + float: left; + position: relative; +} + +div.output-content { + display: block; + font-size: 12px; + padding: 10px; +} + +div.icon-box { + display: inline-block; + margin-right: 5px; +} + +div#debug-title { + display: inline-block; +} + +img.icon { + height: 16px; + vertical-align: middle; +} + +.buttonish { + text-align: center; + text-decoration: none; + text-shadow: -1px -1px 2px #777777; + text-shadow: rgba(10, 10, 10, 0.5) 1px 2px 2px; +} + +input.text-entry { + border: 0; + outline: 0; + height: 20px; + width: 100%; +} + +.rounded { + border: 1px solid #659635; + background: #99ca28; + padding: 2px 8px 2px 8px; + + border-radius: 5px; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; +} + +.green { + color: #ffffff; + background: linear-gradient(top, + #5da331 0%, #659635 2%, #9bcb2a 97%, #cfe782 100%); + background: -moz-linear-gradient(top, + #5da331 0%, #659635 2%, #9bcb2a 97%, #cfe782 100%); + background: -webkit-linear-gradient(top, + #5da331 0%, #659635 2%, #9bcb2a 97%, #cfe782 100%); + filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, + startColorstr='#659635', endColorstr='#9bcb2a'); +} + +.blue { + color: #0c0c0c; +/* + background: linear-gradient(top, + #a0a0ff 0%, #c8c8ff 10%, #d8d8ff 90%, #f0f0ff 100%); + background: -moz-linear-gradient(top, + #a0a0ff 0%, #c8c8ff 10%, #d8d8ff 90%, #f0f0ff 100%); + background: -webkit-linear-gradient(top, + #a0a0ff 0%, #c8c8ff 10%, #d8d8ff 90%, #f0f0ff 100%); + filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, + startColorstr='#a0a0ff', endColorstr='#f0f0ff'); +*/ +} + +.jquery-checkbox { + line-height: 24px; +} + +ul.setupgrid { + padding: 0; + list-style: none; + margin: 0 auto; +} + +ul.setupgrid li { + float: left; + padding: 10px; + border: 1px solid #cbcad0; + margin: 0 5px 10px 5px; +} + +div.setupgrid { + font-family: 'GraublauWeb', arial, serif; + text-align: center; +} + +.setupgrid a { + height: 32px; + width: 64px; + display: block; + padding-top: 32px; + text-decoration: none; +} + +.setupgrid a#prefs-devices { + background: url(/images/prefs-devices.png) no-repeat center top; +} + +.setupgrid a#prefs-groups { + background: url(/images/prefs-groups.png) no-repeat center top; +} + +.setupgrid a#prefs-general { + background: url(/images/prefs-general.png) no-repeat center top; +} + +div.input { + background: #e0e0ff; + padding: 10px; +} + +div.parse { + background: #b0b0b0; + border: 1px solid black; +} + +div.input-debug { + background: #ffe0e0; + border-bottom: 1px solid black; + padding: 10px; + font-weight: bold; +} + +div.possibility-debug { + background: #ffe0e0; + padding: 10px; + border-bottom: 1px dotted red; +} + +div.match-debug { + display: inline-block; + padding: 5px; +} + +div.command-token, +div.command-token div { + display: inline-block; +} + +div.parse-details { +/* display: none; */ +} + +div.command-line { + font-weight: bold; +} + +div.match-details { + display: inline-block; +} + +div.possibility { +/* background: #ffe0e0; */ + padding: 10px; + border-bottom: 1px dotted red; +} + +div.parse-implicit-keyword, +div.parse-token, +div.parse-trailing, +div.parse-missing { + display: inline-block; +} + +div.parse-implicit-keyword, +div.parse-trailing, +div.parse-missing { + font-style: italic; + font-weight: normal; +} + +div.parse-token { + font-weight: bold; +} + +div.parse-mandatory { + color: red; + display: inline-block; +} + +div.parse-mandatory-value { + color: red; + font-style: italic; + display: inline-block; +} + +div.output-content div.parse:first-of-type { + display: none; +} + +div.command-help { + font-size: smaller; + font-style: italic; + padding-left: 20px; + padding-bottom: 5px; +} + +img.rendered { + float: left; + margin-right: 5px; + max-width: 16px; + vertical-align: middle; +} + +div.map-small { + width: 300px; + height: 200px; +} + +div.inline-dialog { + box-shadow: none; + margin-left: 20px; + position: relative; +} + +.inline-dialog .ui-dialog-titlebar-close { + display: none; +} + +div#prefs-title { + font-size: 120%; + font-weight: 600; +} + +div.prefs-item, +div.ui-yf-item { + display: table-row; +} + +div.prefs-item label, +div.ui-yf-item label { + padding-left: 10px; + padding-right: 5px; +} + +div.prefs-item label, +div.prefs-item input, +div.prefs-item div, +div.ui-yf-item label, +div.ui-yf-item input, +div.ui-yf-item div { + display: table-cell; +} + +div.dyn-form { + padding: 5px; + width: auto; +} + +div.dyn-form-wrapper { + display: inline-block; + border: 1px solid #ccc; + min-width: 400px; +} + +div.dyn-form-title { + background-color: #1478dc; + padding: 10px; + color: white; + font-size: 1.1em; +} + +div.dyn-form-item { + display: inline-block; + text-align: center; + padding: 2px 10px 2px 10px; +} + +div.dyn-form-message { + text-align: left; + padding: 5px 10px 5px 10px; +} + +div.dyn-form-item label { + float: left; + padding-left: 10px; + padding-right: 5px; +} + +div.dyn-form-buttons { + text-align: center; + padding: 5px 10px 10px 10px; +} + +div.dyn-form-item label, +div.dyn-form-item input, +div.dyn-form-item select, +div.dyn-form-item div { + float: left; + line-height: 20px; + margin-top: 5px; + min-width: 100px; + text-align: left; +} + +div.dyn-form-item input, +div.dyn-form-item select { + border: solid 1px #CCC; + margin-top: 5px; + width: auto; +} + +div.dyn-form-item .mandatory { + border-color: rgb(213, 119, 0); +} + +div.dyn-form-item .is-error { + border-color: rgb(213, 11, 0); +} + +div.dyn-form-item .is-error:focus { + border-color: rgb(213, 11, 0); +} + +div.dyn-form-item input:focus { + border: solid 1px rgb(180, 180, 200); + box-shadow: 0px 0px 3px rgba(100, 100, 200, 0.8); +} + +div.dyn-form-boolean { + margin-left: -40px; + text-align: left; + vertical-align: middle; +} + +div.dyn-form-item .dyn-radio-button { + margin-left: -30px; + margin-right: -40px; +} + +div.dyn-radiogroup { + border-bottom: 1px solid rgb(230, 230, 230); + border-top: 1px solid rgb(230, 230, 230); + padding: 5px; +} + +.dyn-dropdown-item { + max-height: 200px; + overflow-y: auto; +} + +.history-element .command { + font-size: 16px; +} + +.history-element .date { + color: rgb(130, 130, 130); + font-style: italic; +} + +.node { + stroke: #fff; + stroke-width: 1.5px; +} + +.link { + stroke: #444; + stroke-opacity: 0.6; + stroke-width: 2px; +} + +g.node text { + pointer-events: none; + font: 8px; + stroke: #000080; +} + +some.day { + background: -moz-linear-gradient(center top , #4B90C3, #0D63A3) + repeat scroll 0 0 transparent; +} + +.ui-autocomplete-divider { + border-bottom: 1px solid black; +} + +.ui-autocomplete { + max-height: 400px; + overflow-y: auto; + overflow-x: hidden; + padding-right: 20px; + width: 650px; +} + +ul.ui-autocomplete li.ui-menu-item { + font-family: monospace; +} + +ul.ui-autocomplete li.ui-menu-item a.label { + float: left; + font-weight: bold; +} + +ul.ui-autocomplete li.ui-menu-item a.help { + float: right; +} + +a.xpath-link { + text-decoration: none; +} + +div.xpath-wrapper { + margin-top: 8px; + padding-top: 5px; + border-top: solid 1px #c8c8c8; +} + +div.xpath { + display: none; + margin-top: 8px; +} + +/* + * Additional styles for messages + */ +.ui-state-info { + color: rgb(0, 94, 196); +} + +.ui-state-info .ui-icon { + background-image:url(/themes/clira/images/ui-icons_ffcf29_256x240.png); +} + +.ui-state-success { + color: rgb(45, 126, 0); +} + +.ui-state-success .ui-icon { + background-image:url(/themes/clira/images/ui-icons_ffcf29_256x240.png); +} + +.ui-state-warning { + color: rgb(179, 146, 14); +} + +.ui-state-warning .ui-icon { + background-image:url(/themes/clira/images/ui-icons_ffcf29_256x240.png); +} + +.stop_button { + background-color: #f24537; + background: -moz-linear-gradient( center top, #f24537 5%, #c62d1f 100% ); + background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f24537), color-stop(1, #c62d1f) ); + border: 1px solid #d02718; + border-bottom-left-radius: 6px; + border-bottom-right-radius: 6px; + border-top-left-radius: 6px; + border-top-right-radius: 6px; + box-shadow: inset 0px 1px 0px 0px #f5978e; + color: #ffffff; + display: inline-block; + filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f24537', endColorstr='#c62d1f'); + font-family: Courier New; + font-size: 10px; + font-style: normal; + font-weight: bold; + height: 16px; + line-height: 16px; + margin-left: 5px; + text-align: center; + text-decoration: none; + text-indent: 0.4px; + text-shadow: 1px 1px 0px #810e05; + width: 37px; +} + +.stop_button:hover { + background-color: #c62d1f; + background: -moz-linear-gradient( center top, #c62d1f 5%, #f24537 100% ); + background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #c62d1f), color-stop(1, #f24537) ); + filter:progid: DXImageTransform.Microsoft.gradient(startColorstr='#c62d1f', endColorstr='#f24537'); +} + +.stop_button:active { + position: relative; + top: 1px; +} + +div.color-fg-black { color: black; } +div.color-fg-red { color: red; } +div.color-fg-green { color: green; } +div.color-fg-yellow { color: yellow; } +div.color-fg-blue { color: blue; } +div.color-fg-magenta { color: magenta; } +div.color-fg-cyan { color: cyan; } +div.color-fg-white { color: white; } + +div.color-bg-black { background-color: black; } +div.color-bg-red { background-color: red; } +div.color-bg-green { background-color: green; } +div.color-bg-yellow { background-color: yellow; } +div.color-bg-blue { background-color: blue; } +div.color-bg-magenta { background-color: magenta; } +div.color-bg-cyan { background-color: cyan; } +div.color-bg-white { background-color: white; } + +div.color-fg-inverse { color: white; } +div.color-bg-inverse { background-color: black; } + +div.effect-bold { font-weight:bold; } +div.effect-underline { text-decoration: underline; } Property changes on: vendor/Juniper/libxo/0.8.2/xohtml/xohtml.css ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/css \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/xohtml/xohtml.sh.in =================================================================== --- vendor/Juniper/libxo/0.8.2/xohtml/xohtml.sh.in (nonexistent) +++ vendor/Juniper/libxo/0.8.2/xohtml/xohtml.sh.in (revision 319998) @@ -0,0 +1,78 @@ +#!/bin/sh +# +# Copyright (c) 2014, Juniper Networks, Inc. +# All rights reserved. +# This SOFTWARE is licensed under the LICENSE provided in the +# ../Copyright file. By downloading, installing, copying, or otherwise +# using the SOFTWARE, you agree to be bound by the terms of that +# LICENSE. +# Phil Shafer, July 2014 +# + +BASE=@XO_SHAREDIR@ +CMD=cat +DONE= + +do_help () { + echo "xohtml: wrap libxo-enabled output in HTML" + echo "Usage: xohtml [options] [command [arguments]]" + echo "Valid options are:" + echo " -b | --base " + echo " -c | --command " + echo " -f | --file " + exit 1 +} + +while [ -z "$DONE" -a ! -z "$1" ]; do + case "$1" in + -b|--base) + shift; + BASE="$1"; + shift; + ;; + -c|--command) + shift; + CMD="$1"; + shift; + ;; + -f|--file) + shift; + FILE="$1"; + shift; + exec > "$FILE"; + ;; + -*) + do_help + ;; + *) + DONE=1; + XX=$1; + shift; + CMD="$XX --libxo=html $@" + ;; + esac +done + +if [ "$CMD" = "cat" -a -t 0 ]; then + do_help +fi + +echo '' +echo '' +echo '' +echo '' +echo '' +echo '' +echo '' +echo '' +echo '' +echo '' +echo '' + +$CMD + +echo '' +echo '' + +exit 0 Property changes on: vendor/Juniper/libxo/0.8.2/xohtml/xohtml.sh.in ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/xohtml/xohtml.1 =================================================================== --- vendor/Juniper/libxo/0.8.2/xohtml/xohtml.1 (nonexistent) +++ vendor/Juniper/libxo/0.8.2/xohtml/xohtml.1 (revision 319998) @@ -0,0 +1,96 @@ +.\" # +.\" # Copyright (c) 2015, Juniper Networks, Inc. +.\" # All rights reserved. +.\" # This SOFTWARE is licensed under the LICENSE provided in the +.\" # ../Copyright file. By downloading, installing, copying, or +.\" # using the SOFTWARE, you agree to be bound by the terms of that +.\" # LICENSE. +.\" # Phil Shafer, July 2014 +.\" +.Dd December 4, 2014 +.Dt XOHTML 1 +.Os +.Sh NAME +.Nm xohtml +.Nd display libxo html output +.Xr xo_emit 3 +.Sh SYNOPSIS +.Nm xohtml +.Op Fl "b " +.Op Fl "c" " +.Op Fl "f" +.Op Ar command argument... +.Sh DESCRIPTION +.Nm +is a tool for preparing +.Xr libxo 3 +HTML output for display in modern HTML web browsers. +.Nm +can operate in two modes. +If command is provided +either with the +.Fl c +option or as argument(s) to the +.Nm +command, that command is executed and the resulting output is processed. +If no command is given, the +standard input is used. +.Pp +.Nm +is typically used to wrap +.Nm libxo +output with sufficient HTML content to allow display in a web browser. +This includes parent HTML tags as well as +.Nm CSS +stylesheets and +.Nm Javascript +files. +.Pp +If the command is given directly on the command line, +.Nm +will add the "--libxo=html" option needed to generate HTML output +from +.Nm libxo "-enabled" +applications. See +.Xr xo_options 7 +for details. +.Pp +The following options are available: +.Bl -tag -width indent +.It Ic -b Ar base | Ic --base Ar base +Supplies a source path for the CSS and Javascript files referenced in +the output of +.Nm xohtml . +.It Ic -c Ar command | Ic --command Ar command +Use the given command instead of one on the command line. +This command should be quoted if it consists of multiple tokens, and +should contain the "--libxo=html" option or equivalent, since the +command is used directly. +.It Ic -f Ar file | Ic --file Ar file +Output is saved to the given file, rather than to the standard output +descriptor. +.El +.Pp +.Sh EXAMPLES +The following command line will run "du --libxo=html ~/src" and save +the output to /tmp/src.html: +.Bd -literal -offset indent + xohtml du ~/src > /tmp/src.html +.Ed +.Pp +The following command line will run "du --libxo=html,warn ~/src" and save +the output to /tmp/src.html: +.Bd -literal -offset indent + du --libxo=html,warn ~/src | xohtml -f /tmp/src.html +.Ed +.Pp +The following command line will run "du --libxo=html,warn ~/src" and save +the output to /tmp/src.html: +.Bd -literal -offset indent + xohtml -c "du --libxo=html,warn ~/src" -f /tmp/src.html +.Ed +.Pp +.Sh SEE ALSO +.Xr libxo 3 , +.Xr xo_emit 3 , +.Xr xo_options 7 Property changes on: vendor/Juniper/libxo/0.8.2/xohtml/xohtml.1 ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/xohtml/Makefile.am =================================================================== --- vendor/Juniper/libxo/0.8.2/xohtml/Makefile.am (nonexistent) +++ vendor/Juniper/libxo/0.8.2/xohtml/Makefile.am (revision 319998) @@ -0,0 +1,42 @@ +# +# Copyright 2015, Juniper Networks, Inc. +# All rights reserved. +# This SOFTWARE is licensed under the LICENSE provided in the +# ../Copyright file. By downloading, installing, copying, or otherwise +# using the SOFTWARE, you agree to be bound by the terms of that +# LICENSE. + +man_MANS = xohtml.1 + +EXTERNAL_FILES = \ + external/jquery.js \ + external/jquery.qtip.css \ + external/jquery.qtip.js + +INTERNAL_FILES = \ + xohtml.js \ + xohtml.css + +EXTRA_DIST = \ + xohtml.1 \ + xohtml.sh.in \ + ${INTERNAL_FILES} \ + ${EXTERNAL_FILES} + +install-exec-hook: + install xohtml.sh ${DESTDIR}${bindir}/xohtml + mkdir -p ${DESTDIR}${XO_SHAREDIR}/external + for file in ${INTERNAL_FILES}; do \ + install ${srcdir}/$$file ${DESTDIR}${XO_SHAREDIR} ; done + for file in ${EXTERNAL_FILES}; do \ + install ${srcdir}/$$file ${DESTDIR}${XO_SHAREDIR}/external ; done + +uninstall-hook: + for file in ${INTERNAL_FILES} ${EXTERNAL_FILES}; do \ + rm ${DESTDIR}${XO_SHAREDIR}/$$file ; done + rmdir ${DESTDIR}${XO_SHAREDIR}/external + rm -f ${DESTDIR}${bindir}/xohtml + +install-data-hook: + for file in ${man_MANS}; do \ + cat ../libxo/add.man >> ${DESTDIR}${man1dir}/$$file ; done Property changes on: vendor/Juniper/libxo/0.8.2/xohtml/Makefile.am ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/Juniper/libxo/0.8.2/xohtml/external/jquery.js =================================================================== --- vendor/Juniper/libxo/0.8.2/xohtml/external/jquery.js (nonexistent) +++ vendor/Juniper/libxo/0.8.2/xohtml/external/jquery.js (revision 319998) @@ -0,0 +1,9300 @@ +/*! + * jQuery JavaScript Library v1.7 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Thu Nov 3 16:18:21 2011 -0400 + */ +(function( window, undefined ) { + +// Use the correct document accordingly with window argument (sandbox) +var document = window.document, + navigator = window.navigator, + location = window.location; +var jQuery = (function() { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Check for digits + rdigit = /\d/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Matches dashed string for camelizing + rdashAlpha = /-([a-z]|[0-9])/ig, + rmsPrefix = /^-ms-/, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // The deferred used on DOM ready + readyList, + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = quickExpr.exec( selector ); + } + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context ? context.ownerDocument || context : document ); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.7", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.add( fn ); + + return this; + }, + + eq: function( i ) { + return i === -1 ? + this.slice( i ) : + this.slice( i, +i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + // Either a released hold or an DOMready/load event and not yet ready + if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.fireWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).unbind( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyList ) { + return; + } + + readyList = jQuery.Callbacks( "once memory" ); + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNumeric: function( obj ) { + return obj != null && rdigit.test( obj ) && !isNaN( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw msg; + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction( object ); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + break; + } + } + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // The extra typeof function check is to prevent crashes + // in Safari 2 (See: #3039) + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type( array ); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array, i ) { + var len; + + if ( array ) { + if ( indexOf ) { + return indexOf.call( array, elem, i ); + } + + len = array.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in array && array[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + if ( typeof context === "string" ) { + var tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + var args = slice.call( arguments, 2 ), + proxy = function() { + return fn.apply( context, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can optionally be executed if it's a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return ( new Date() ).getTime(); + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; + }, + + browser: {} +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +// Expose jQuery as an AMD module, but only for AMD loaders that +// understand the issues with loading multiple versions of jQuery +// in a page that all might call define(). The loader will indicate +// they have special allowances for multiple jQuery versions by +// specifying define.amd.jQuery = true. Register as a named module, +// since jQuery can be concatenated with other files that may use define, +// but not use a proper concatenation script that understands anonymous +// AMD modules. A named AMD is safest and most robust way to register. +// Lowercase jquery is used because AMD module names are derived from +// file names, and jQuery is normally delivered in a lowercase file name. +if ( typeof define === "function" && define.amd && define.amd.jQuery ) { + define( "jquery", [], function () { return jQuery; } ); +} + +return jQuery; + +})(); + + +// String to Object flags format cache +var flagsCache = {}; + +// Convert String-formatted flags into Object-formatted ones and store in cache +function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; +} + +/* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( flags ) { + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Add one or several callbacks to the list + add = function( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // Add if not in unique mode and callback is not in + if ( !flags.unique || !self.has( elem ) ) { + list.push( elem ); + } + } + } + }, + // Fire callbacks + fire = function( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + self.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + self.disable(); + } else { + list = []; + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + var length = list.length; + add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { + firingStart = length; + fire( memory[ 0 ], memory[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength ; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } + } + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique ) { + break; + } + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory || memory === true ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( stack ) { + if ( firing ) { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { + fire( context, args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!memory; + } + }; + + return self; +}; + + + + +var // Static reference to slice + sliceDeferred = [].slice; + +jQuery.extend({ + + Deferred: function( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + state = "pending", + lists = { + resolve: doneList, + reject: failList, + notify: progressList + }, + promise = { + done: doneList.add, + fail: failList.add, + progress: progressList.add, + + state: function() { + return state; + }, + + // Deprecated + isResolved: doneList.fired, + isRejected: failList.fired, + + then: function( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always: function() { + return deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); + }, + pipe: function( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ], + progress: [ fnProgress, "notify" ] + }, function( handler, data ) { + var fn = data[ 0 ], + action = data[ 1 ], + returned; + if ( jQuery.isFunction( fn ) ) { + deferred[ handler ](function() { + returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + }); + } else { + deferred[ handler ]( newDefer[ action ] ); + } + }); + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + if ( obj == null ) { + obj = promise; + } else { + for ( var key in promise ) { + obj[ key ] = promise[ key ]; + } + } + return obj; + } + }, + deferred = promise.promise({}), + key; + + for ( key in lists ) { + deferred[ key ] = lists[ key ].fire; + deferred[ key + "With" ] = lists[ key ].fireWith; + } + + // Handle state + deferred.done( function() { + state = "resolved"; + }, failList.disable, progressList.lock ).fail( function() { + state = "rejected"; + }, doneList.disable, progressList.lock ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( firstParam ) { + var args = sliceDeferred.call( arguments, 0 ), + i = 0, + length = args.length, + pValues = new Array( length ), + count = length, + pCount = length, + deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? + firstParam : + jQuery.Deferred(), + promise = deferred.promise(); + function resolveFunc( i ) { + return function( value ) { + args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.resolveWith( deferred, args ); + } + }; + } + function progressFunc( i ) { + return function( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + deferred.notifyWith( promise, pValues ); + }; + } + if ( length > 1 ) { + for ( ; i < length; i++ ) { + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( deferred, args ); + } + } else if ( deferred !== firstParam ) { + deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); + } + return promise; + } +}); + + + + +jQuery.support = (function() { + + var div = document.createElement( "div" ), + documentElement = document.documentElement, + all, + a, + select, + opt, + input, + marginDiv, + support, + fragment, + body, + testElementParent, + testElement, + testElementStyle, + tds, + events, + eventName, + i, + isSupported; + + // Preliminary tests + div.setAttribute("className", "t"); + div.innerHTML = "
a"; + + + all = div.getElementsByTagName( "*" ); + a = div.getElementsByTagName( "a" )[ 0 ]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement( "select" ); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName( "input" )[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName( "tbody" ).length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName( "link" ).length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure unknown elements (like HTML5 elems) are handled appropriately + unknownElems: !!div.getElementsByTagName( "nav" ).length, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype: !!document.createElement("form").enctype, + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent( "onclick" ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute("type", "radio"); + support.radioValue = input.value === "t"; + + input.setAttribute("checked", "checked"); + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + div.innerHTML = ""; + + // Figure out if the W3C box model works as expected + div.style.width = div.style.paddingLeft = "1px"; + + // We don't want to do body-related feature tests on frameset + // documents, which lack a body. So we use + // document.getElementsByTagName("body")[0], which is undefined in + // frameset documents, while document.body isn’t. (7398) + body = document.getElementsByTagName("body")[ 0 ]; + // We use our own, invisible, body unless the body is already present + // in which case we use a div (#9239) + testElement = document.createElement( body ? "div" : "body" ); + testElementStyle = { + visibility: "hidden", + width: 0, + height: 0, + border: 0, + margin: 0, + background: "none" + }; + if ( body ) { + jQuery.extend( testElementStyle, { + position: "absolute", + left: "-999px", + top: "-999px" + }); + } + for ( i in testElementStyle ) { + testElement.style[ i ] = testElementStyle[ i ]; + } + testElement.appendChild( div ); + testElementParent = body || documentElement; + testElementParent.insertBefore( testElement, testElementParent.firstChild ); + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + support.boxModel = div.offsetWidth === 2; + + if ( "zoom" in div.style ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "
"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); + } + + div.innerHTML = "
t
"; + tds = div.getElementsByTagName( "td" ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE < 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + div.innerHTML = ""; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + if ( document.defaultView && document.defaultView.getComputedStyle ) { + marginDiv = document.createElement( "div" ); + marginDiv.style.width = "0"; + marginDiv.style.marginRight = "0"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; + } + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for( i in { + submit: 1, + change: 1, + focusin: 1 + } ) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + // Run fixed position tests at doc ready to avoid a crash + // related to the invisible body in IE8 + jQuery(function() { + var container, outer, inner, table, td, offsetSupport, + conMarginTop = 1, + ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;", + vb = "visibility:hidden;border:0;", + style = "style='" + ptlm + "border:5px solid #000;padding:0;'", + html = "
" + + "" + + "
"; + + // Reconstruct a container + body = document.getElementsByTagName("body")[0]; + if ( !body ) { + // Return for frameset docs that don't have a body + // These tests cannot be done + return; + } + + container = document.createElement("div"); + container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; + body.insertBefore( container, body.firstChild ); + + // Construct a test element + testElement = document.createElement("div"); + testElement.style.cssText = ptlm + vb; + + testElement.innerHTML = html; + container.appendChild( testElement ); + outer = testElement.firstChild; + inner = outer.firstChild; + td = outer.nextSibling.firstChild.firstChild; + + offsetSupport = { + doesNotAddBorder: ( inner.offsetTop !== 5 ), + doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) + }; + + inner.style.position = "fixed"; + inner.style.top = "20px"; + + // safari subtracts parent border width here which is 5px + offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); + inner.style.position = inner.style.top = ""; + + outer.style.overflow = "hidden"; + outer.style.position = "relative"; + + offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); + offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + + body.removeChild( container ); + testElement = container = null; + + jQuery.extend( support, offsetSupport ); + }); + + testElement.innerHTML = ""; + testElementParent.removeChild( testElement ); + + // Null connected elements to avoid leaks in IE + testElement = fragment = select = opt = body = marginDiv = div = input = null; + + return support; +})(); + +// Keep track of boxModel +jQuery.boxModel = jQuery.support.boxModel; + + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var privateCache, thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando, + isEvents = name === "events"; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ jQuery.expando ] = id = ++jQuery.uuid; + } else { + id = jQuery.expando; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + privateCache = thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Users should not attempt to inspect the internal events object using jQuery.data, + // it is undocumented and subject to change. But does anyone listen? No. + if ( isEvents && !thisCache[ name ] ) { + return privateCache.events; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + // Reference to internal data cache key + internalKey = jQuery.expando, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support space separated names + if ( jQuery.isArray( name ) ) { + name = name; + } else if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split( " " ); + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject(cache[ id ]) ) { + return; + } + } + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + // Ensure that `cache` is not a window object #10080 + if ( jQuery.support.deleteExpando || !cache.setInterval ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the cache and need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ jQuery.expando ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( jQuery.expando ); + } else { + elem[ jQuery.expando ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, attr, name, + data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { + attr = this[0].attributes; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( this[0], name, data[ name ] ); + } + } + jQuery._data( this[0], "parsedAttrs", true ); + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var $this = jQuery( this ), + args = [ parts[0], value ]; + + $this.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + $this.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + jQuery.isNumeric( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + for ( var name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + + + + +function handleQueueMarkDefer( elem, type, src ) { + var deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + defer = jQuery._data( elem, deferDataKey ); + if ( defer && + ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && + ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { + // Give room for hard-coded callbacks to fire first + // and eventually mark/queue something else on the element + setTimeout( function() { + if ( !jQuery._data( elem, queueDataKey ) && + !jQuery._data( elem, markDataKey ) ) { + jQuery.removeData( elem, deferDataKey, true ); + defer.fire(); + } + }, 0 ); + } +} + +jQuery.extend({ + + _mark: function( elem, type ) { + if ( elem ) { + type = ( type || "fx" ) + "mark"; + jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); + } + }, + + _unmark: function( force, elem, type ) { + if ( force !== true ) { + type = elem; + elem = force; + force = false; + } + if ( elem ) { + type = type || "fx"; + var key = type + "mark", + count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); + if ( count ) { + jQuery._data( elem, key, count ); + } else { + jQuery.removeData( elem, key, true ); + handleQueueMarkDefer( elem, type, "mark" ); + } + } + }, + + queue: function( elem, type, data ) { + var q; + if ( elem ) { + type = ( type || "fx" ) + "queue"; + q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !q || jQuery.isArray(data) ) { + q = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + q.push( data ); + } + } + return q || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(), + hooks = {}; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + jQuery._data( elem, type + ".run", hooks ); + fn.call( elem, function() { + jQuery.dequeue( elem, type ); + }, hooks ); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue " + type + ".run", true ); + handleQueueMarkDefer( elem, type, "queue" ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function() { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, object ) { + if ( typeof type !== "string" ) { + object = type; + type = undefined; + } + type = type || "fx"; + var defer = jQuery.Deferred(), + elements = this, + i = elements.length, + count = 1, + deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + tmp; + function resolve() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + } + while( i-- ) { + if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || + ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || + jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { + count++; + tmp.add( resolve ); + } + } + resolve(); + return defer.promise(); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspace = /\s+/, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + nodeHook, boolHook, fixSpecified; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.prop ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + classNames = ( value || "" ).split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[ c ] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return undefined; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var self = jQuery(this), val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return undefined; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( !("getAttribute" in elem) ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return undefined; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, l, + i = 0; + + if ( elem.nodeType === 1 ) { + attrNames = ( value || "" ).split( rspace ); + l = attrNames.length; + + for ( ; i < l; i++ ) { + name = attrNames[ i ].toLowerCase(); + propName = jQuery.propFix[ name ] || name; + + // See #9699 for explanation of this approach (setting first, then removal) + jQuery.attr( elem, name, "" ); + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( rboolean.test( name ) && propName in elem ) { + elem[ propName ] = false; + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return undefined; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) +jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? + ret.nodeValue : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.nodeValue = value + "" ); + } + }; + + // Apply the nodeHook to tabindex + jQuery.attrHooks.tabindex.set = nodeHook.set; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = "" + value ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); + + + + +var rnamespaces = /\.(.*)$/, + rformElems = /^(?:textarea|input|select)$/i, + rperiod = /\./g, + rspaces = / /g, + rescape = /[^\w\s.|`]/g, + rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, + rhoverHack = /\bhover(\.\S+)?/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, + quickParse = function( selector ) { + var quick = rquickIs.exec( selector ); + if ( quick ) { + // 0 1 2 3 + // [ _, tag, id, class ] + quick[1] = ( quick[1] || "" ).toLowerCase(); + quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); + } + return quick; + }, + quickIs = function( elem, m ) { + return ( + (!m[1] || elem.nodeName.toLowerCase() === m[1]) && + (!m[2] || elem.id === m[2]) && + (!m[3] || m[3].test( elem.className )) + ); + }, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, quick, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = hoverHack(types).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + namespace: namespaces.join(".") + }, handleObjIn ); + + // Delegated event; pre-analyze selector so it's processed quickly on event dispatch + if ( selector ) { + handleObj.quick = quickParse( selector ); + if ( !handleObj.quick && jQuery.expr.match.POS.test( selector ) ) { + handleObj.isPositional = true; + } + } + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector ) { + + var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + t, tns, type, namespaces, origCount, + j, events, special, handle, eventType, handleObj; + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = hoverHack( types || "" ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + namespaces = namespaces? "." + namespaces : ""; + for ( j in events ) { + jQuery.event.remove( elem, j + namespaces, handler, selector ); + } + return; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + + // Only need to loop for special events or selective removal + if ( handler || namespaces || selector || special.remove ) { + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( !handler || handler.guid === handleObj.guid ) { + if ( !namespaces || namespaces.test( handleObj.namespace ) ) { + if ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + } + } + } else { + // Removing all events + eventType.length = 0; + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, [ "events", "handle" ], true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var type = event.type || event, + namespaces = [], + cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // triggerHandler() and global events don't bubble or run the default action + if ( onlyHandlers || !elem ) { + event.preventDefault(); + } + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + old = null; + for ( cur = elem.parentNode; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old && old === elem.ownerDocument ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length; i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) ) { + handle.apply( cur, data ); + } + + if ( event.isPropagationStopped() ) { + break; + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = [].slice.call( arguments, 0 ), + run_all = !event.exclusive && !event.namespace, + specialHandle = ( jQuery.event.special[ event.type ] || {} ).handle, + handlerQueue = [], + i, j, cur, ret, selMatch, matched, matches, handleObj, sel, hit, related; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Determine handlers that should run if there are delegated events + // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + selMatch = {}; + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + hit = selMatch[ sel ]; + + if ( handleObj.isPositional ) { + // Since .is() does not work for positionals; see http://jsfiddle.net/eJ4yd/3/ + hit = ( hit || (selMatch[ sel ] = jQuery( sel )) ).index( cur ) >= 0; + } else if ( hit === undefined ) { + hit = selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jQuery( cur ).is( sel ) ); + } + if ( hit ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement wheelDelta".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) + if ( event.metaKey === undefined ) { + event.metaKey = event.ctrlKey; + } + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady + }, + + focus: { + delegateType: "focusin", + noBubble: true + }, + blur: { + delegateType: "focusout", + noBubble: true + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = jQuery.event.special[ fix ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector, + oldType, ret; + + // For a real mouseover/out, always call the handler; for + // mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || handleObj.origType === event.type || (related !== target && !jQuery.contains( target, related )) ) { + oldType = event.type; + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = oldType; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !form._submit_attached ) { + jQuery.event.add( form, "submit._submit", function( event ) { + // Form was submitted, bubble the event up the tree + if ( this.parentNode ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + }); + form._submit_attached = true; + } + }); + // return undefined since we don't need an event listener + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed ) { + this._just_changed = false; + jQuery.event.simulate( "change", this, event, true ); + } + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + elem._change_attached = true; + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on.call( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + var handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( var type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.bind( name, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); + + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + expando = "sizcache" + (Math.random() + '').replace('.', ''), + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rReturn = /\r\n/g, + rNonWord = /\W/; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context, seed ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set, seed ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set, i, len, match, type, left; + + if ( !expr ) { + return []; + } + + for ( i = 0, len = Expr.order.length; i < len; i++ ) { + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + type, found, item, filter, left, + i, pass, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + filter = Expr.filter[ type ]; + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + pass = not ^ found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw "Syntax error, unrecognized expression: " + msg; +}; + +/** + * Utility function for retreiving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +var getText = Sizzle.getText = function( elem ) { + var i, node, + nodeType = elem.nodeType, + ret = ""; + + if ( nodeType ) { + if ( nodeType === 1 ) { + // Use textContent || innerText for elements + if ( typeof elem.textContent === 'string' ) { + return elem.textContent; + } else if ( typeof elem.innerText === 'string' ) { + // Replace IE's carriage returns + return elem.innerText.replace( rReturn, '' ); + } else { + // Traverse it's children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + } else { + + // If no nodeType, this is expected to be an array + for ( i = 0; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + if ( node.nodeType !== 8 ) { + ret += getText( node ); + } + } + } + return ret; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + }, + type: function( elem ) { + return elem.getAttribute( "type" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace( rBackslash, "" ); + }, + + TAG: function( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + var attr = elem.getAttribute( "type" ), type = elem.type; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); + }, + + radio: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; + }, + + checkbox: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; + }, + + file: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; + }, + + password: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; + }, + + submit: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "submit" === elem.type; + }, + + image: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; + }, + + reset: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "reset" === elem.type; + }, + + button: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && "button" === elem.type || name === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + }, + + focus: function( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var first, last, + doneName, parent, cache, + count, diff, + type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + first = match[2]; + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + doneName = match[0]; + parent = elem.parentNode; + + if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { + count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent[ expando ] = doneName; + } + + diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Sizzle.attr ? + Sizzle.attr( elem, name ) : + Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + !type && Sizzle.attr ? + result != null : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = ""; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "

"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; + + if ( matches ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9 fails this) + var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + var ret = matches.call( node, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || !disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9, so check for that + node.document && node.document.nodeType !== 11 ) { + return ret; + } + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "
"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context, seed ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet, seed ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +Sizzle.selectors.attrMap = {}; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var self = this, + i, l; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + var ret = this.pushStack( "", "find", selector ), + length, n, r; + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + POS.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + // Array (deprecated as of jQuery 1.7) + if ( jQuery.isArray( selectors ) ) { + var level = 1; + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( i = 0; i < selectors.length; i++ ) { + + if ( jQuery( cur ).is( selectors[ i ] ) ) { + ret.push({ selector: selectors[ i ], elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + + return ret; + } + + // String + var pos = POS.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ), + // The variable 'args' was introduced in + // https://github.com/jquery/jquery/commit/52a0238 + // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. + // http://code.google.com/p/v8/issues/detail?id=1050 + args = slice.call(arguments); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, args.join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} + + + + +function createSafeFragment( document ) { + var list = nodeNames.split( " " ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr article aside audio canvas datalist details figcaption figure footer " + + "header hgroup mark meter nav output progress section summary time video", + rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /", "" ], + legend: [ 1, "
", "
" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + col: [ 2, "", "
" ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize and