@@ -22992,7 +22998,8 @@ jQuery(function ($) {
@@ -23356,6 +23363,11 @@ jQuery(function ($) {
+a
+argument
+The content appears as a 'const char *' argument
+
+
c
colon
A colon (":") is appended after the label
@@ -23435,87 +23447,107 @@ jQuery(function ($) {
Roles and modifiers can also use more verbose names, when preceeded 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:
-- Section 2.2.2.1
-- Section 2.2.2.2
-- Section 2.2.2.3
-- Section 2.2.2.4
-- Section 2.2.2.5
-- Section 2.2.2.6
-- Section 2.2.2.7
-- Section 2.2.2.8
-- Section 2.2.2.9
-- Section 2.2.2.10
-- Section 2.2.2.11
+- Section 2.2.2.1
+- Section 2.2.2.2
+- Section 2.2.2.3
+- Section 2.2.2.4
+- Section 2.2.2.5
+- Section 2.2.2.6
+- Section 2.2.2.7
+- Section 2.2.2.8
+- Section 2.2.2.9
+- Section 2.2.2.10
+- Section 2.2.2.11
+- Section 2.2.2.12
+- Section 2.2.2.13
-The Colon Modifier ({c:})
+The Argument Modifier ({a:})
-The colon modifier appends a single colon to the data value:
+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("{Lc:Name}{:name}\n", "phil");
+ xo_emit("{La:} {a:}\n", "Label text", "label", "value");
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.
+ 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.
-
+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 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.
-
+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 2.2.1.3, Section 2.2.2.9, and Section 9.5 for additional details.
+ 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 2.2.1.3, Section 2.2.2.10, and Section 9.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 3.4.6) 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.
-
+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 3.4.6) 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}, "
@@ -23523,19 +23555,19 @@ jQuery(function ($) {
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:
-
+
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.
-
+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++) {
@@ -23545,16 +23577,16 @@ jQuery(function ($) {
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.
+
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.
-
+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);
@@ -23564,16 +23596,16 @@ jQuery(function ($) {
<user>pallavi</user>
JSON:
"user": [ "phil", "pallavi" ]
-
The name of the field must match the name of the leaf list.
+
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.
-
+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);
@@ -23581,45 +23613,61 @@ jQuery(function ($) {
"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 2.2.2.4.
-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 Plural Modifier ({p:})
-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.
+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:
- EXAMPLE:
- xo_emit("{q:time/%d}", 2014);
- JSON:
- "year": "2014"
-
+ 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 2.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:
-
+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.
+
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.
@@ -23632,7 +23680,7 @@ jQuery(function ($) {
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:
@@ -23829,8 +23877,42 @@ jQuery(function ($) {
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".
-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.
-
+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("Alll 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];
@@ -23849,10 +23931,10 @@ jQuery(function ($) {
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.
-
+
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);
@@ -23862,7 +23944,7 @@ jQuery(function ($) {
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:
@@ -23883,7 +23965,7 @@ jQuery(function ($) {
"%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));
@@ -23930,7 +24012,7 @@ jQuery(function ($) {
- 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
@@ -23987,14 +24069,71 @@ jQuery(function ($) {
+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):
+
+
+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:
-
+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:
-
+
This call will generate the following output:
+
TEXT:
In stock: 144
XML:
@@ -24009,8 +24148,8 @@ jQuery(function ($) {
<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:
-
+
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"
@@ -24021,17 +24160,148 @@ jQuery(function ($) {
+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:
+
+
+
+
+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>
+
+
+
+
+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");
+ }
+
+
+
+
+
+2.4
Command-line Arguments
-libxo uses command line options to trigger rendering behavior. The following options are recognised:
-
+libxo uses command line options to trigger rendering behavior. The following options are recognised:
+
- --libxo <options>
- --libxo=<options>
- --libxo:<brief‑options>
-Options is a comma-separated list of tokens that correspond to output styles, flags, or features:
-
+Programs using libxo are expecting to call the xo_parse_args function to parse these arguments. See Section 3.4.1 for details.
+Options is a comma-separated list of tokens that correspond to output styles, flags, or features:
+
Token
Action
@@ -24082,6 +24352,10 @@ jQuery(function ($) {
Do not initialize the locale setting
+no-retain
+Prevent retaining formatting information
+
+
no-top
Do not emit a top set of braces (JSON)
@@ -24094,6 +24368,10 @@ jQuery(function ($) {
Emit pretty-printed output
+retain
+Force retaining formatting information
+
+
text
Emit TEXT output
@@ -24123,165 +24401,7 @@ jQuery(function ($) {
-The brief options are detailed in Section 3.4.6.
-
-
-
-
-2.4
-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:
-
-
-
-
-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>
-
-
-
-
-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");
- }
-
-
-
-
-
-2.5
-Handles
-
-libxo uses "handles" to control its rendering functionality. The handle contains state and buffered data, as well as callback functions to process data.
-A default handle is used when a NULL is passed to functions accepting a handle. This handle is initialized to write its data to stdout using the default style of text (XO_STYLE_TEXT).
-For the convenience of callers, the libxo library includes handle-less functions that implicitly use the default handle. Any function that takes a handle will use the default handle is a value of NULL is passed in place of a valid 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().
-
-
-
-
-2.6
-UTF-8
-
-All strings for libxo must be UTF-8. libxo will handle turning them into locale-based strings for display to the user.
-The only exception is argument formatted using the "%ls" format, which require a wide character string (wchar_t *) as input. 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("Alll strings are utf-8 content {:tag/%ls}",
- L"except for wide strings");
-
"%S" is equivalent to "%ls".
+The brief options are detailed in Section 3.4.6.
@@ -24294,7 +24414,7 @@ jQuery(function ($) {
This section gives details about the functions in libxo, how to call them, and the actions they perform.
Section Contents:
-- Section 3.1
+- Section 3.1
- Section 3.2
- Section 3.3
- Section 3.4
@@ -24305,13 +24425,19 @@ jQuery(function ($) {
-Handles
+Handles
-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 to standard output. The xo_set_style and xo_set_flags functions can be used to change this behavior.
-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.
+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.
-Section Contents:
+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:
- Section 3.1.1
- Section 3.1.2
@@ -24327,7 +24453,7 @@ jQuery(function ($) {
xo_create
A handle can be allocated using the xo_create() function:
-
+
xo_handle_t *xo_create (unsigned style, unsigned flags);
Example:
@@ -24343,7 +24469,7 @@ jQuery(function ($) {
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.
@@ -24355,7 +24481,7 @@ jQuery(function ($) {
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);
@@ -24368,10 +24494,10 @@ jQuery(function ($) {
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);
Section Contents:
@@ -24385,7 +24511,7 @@ jQuery(function ($) {
Output Styles (XO_STYLE_*)
The libxo functions accept a set of output styles:
-
+
Flag
Description
@@ -24417,10 +24543,10 @@ jQuery(function ($) {
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");
@@ -24432,10 +24558,10 @@ jQuery(function ($) {
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:
@@ -24450,7 +24576,7 @@ jQuery(function ($) {
Flags (XOF_*)
The set of valid flags include:
-
+
Flag
Description
@@ -24528,7 +24654,7 @@ jQuery(function ($) {
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
@@ -24547,7 +24673,7 @@ jQuery(function ($) {
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 3.4.4 for details.
If the style is XO_STYLE_XML, the following additional flags can be used:
-
+
Flag
Description
@@ -24558,7 +24684,7 @@ jQuery(function ($) {
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:
@@ -24571,7 +24697,7 @@ jQuery(function ($) {
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);
@@ -24581,9 +24707,9 @@ jQuery(function ($) {
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 2.3.
+
The options are identical to those listed in Section 2.4.
@@ -24593,7 +24719,7 @@ jQuery(function ($) {
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);
@@ -24604,33 +24730,57 @@ jQuery(function ($) {
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 2.2. The use of a handle is optional and NULL can be passed to access the internal 'default' handle. See Section 2.5.
+
The "fmt" argument is a string containing field descriptors as specified in Section 2.2. The use of a handle is optional and NULL can be passed to access the internal 'default' handle. See Section 3.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:
-- Section 3.2.1
-- Section 3.2.2
-- Section 3.2.3
+- Section 3.2.1
+- Section 3.2.2
+- Section 3.2.3
+- Section 3.2.4
+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);
+
+
+
+
Attributes (xo_attr)
-The xo_attr() function emits attributes for the XML output style.
-
+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().
-
+
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);
@@ -24638,34 +24788,34 @@ jQuery(function ($) {
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.
-
-
-
-
-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);".
+ 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.
-
+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).
+
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).
@@ -24676,7 +24826,7 @@ jQuery(function ($) {
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);
@@ -24690,7 +24840,7 @@ jQuery(function ($) {
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);
@@ -24707,7 +24857,7 @@ jQuery(function ($) {
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++) {
@@ -24776,11 +24926,11 @@ jQuery(function ($) {
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 2.3 for a description of valid arguments.
+
Following the call to xo_parse_args, the application can process the remaining arguments in a normal manner. See Section 2.4 for a description of valid arguments.
@@ -24789,7 +24939,7 @@ jQuery(function ($) {
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.
@@ -24800,7 +24950,7 @@ jQuery(function ($) {
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);
@@ -24813,7 +24963,7 @@ jQuery(function ($) {
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 */
@@ -24823,7 +24973,7 @@ jQuery(function ($) {
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" },
@@ -24836,7 +24986,7 @@ jQuery(function ($) {
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>
@@ -24847,7 +24997,7 @@ jQuery(function ($) {
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.
@@ -24860,7 +25010,7 @@ jQuery(function ($) {
LIBXO_OPTIONS
The environment variable "LIBXO_OPTIONS" can be set to a string of options:
-
+
Option
Action
@@ -24929,10 +25079,10 @@ jQuery(function ($) {
For example, warnings can be enabled by:
-
+
% env LIBXO_OPTIONS=W my-app
Complete HTML output can be generated with:
-
+
% env LIBXO_OPTIONS=HXI 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.
@@ -24943,7 +25093,7 @@ jQuery(function ($) {
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, ...);
@@ -24959,7 +25109,7 @@ jQuery(function ($) {
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);
@@ -24971,7 +25121,7 @@ jQuery(function ($) {
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::
@@ -24986,7 +25136,7 @@ jQuery(function ($) {
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);
@@ -25002,7 +25152,7 @@ jQuery(function ($) {
https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
Use the Section 3.5.3.5() function to set the Enterprise ID, as needed.
The message name should follow the conventions in Section 8.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);
@@ -25030,13 +25180,13 @@ jQuery(function ($) {
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.
-
+
Priority
Description
@@ -25077,7 +25227,7 @@ jQuery(function ($) {
The facility value indicates the source of message, in fairly generic terms.
-
+
Facility
Description
@@ -25142,7 +25292,7 @@ jQuery(function ($) {
In addition to the values listed above, xo_open_log accepts a set of addition flags requesting specific behaviors.
-
+
Flag
Description
@@ -25175,7 +25325,7 @@ jQuery(function ($) {
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);
@@ -25204,7 +25354,7 @@ jQuery(function ($) {
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;
@@ -25220,7 +25370,7 @@ jQuery(function ($) {
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 3.5.1.
-
+
void
xo_open_log (const char *ident, int logopt, int facility);
@@ -25231,7 +25381,7 @@ jQuery(function ($) {
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);
@@ -25242,7 +25392,7 @@ jQuery(function ($) {
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);
@@ -25257,7 +25407,7 @@ jQuery(function ($) {
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:
@@ -25299,7 +25449,7 @@ jQuery(function ($) {
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
@@ -25311,7 +25461,7 @@ jQuery(function ($) {
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:
@@ -25329,7 +25479,7 @@ jQuery(function ($) {
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)
@@ -25416,7 +25566,7 @@ jQuery(function ($) {
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 LIBXO_OPTIONS environment variable can also be used to set the style, as well as other flags.
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:
@@ -25436,7 +25586,7 @@ jQuery(function ($) {
<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:
@@ -25460,7 +25610,7 @@ jQuery(function ($) {
}
}
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
@@ -25489,7 +25639,7 @@ jQuery(function ($) {
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
@@ -25513,7 +25663,7 @@ jQuery(function ($) {
4.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"
@@ -25530,7 +25680,7 @@ jQuery(function ($) {
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.
-
+
Option
Meaning
@@ -25571,7 +25721,7 @@ jQuery(function ($) {
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}");
@@ -25587,7 +25737,7 @@ jQuery(function ($) {
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.
-
+
Option
Meaning
@@ -25619,7 +25769,7 @@ jQuery(function ($) {
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.
-
+
Option
Meaning
@@ -25639,7 +25789,7 @@ jQuery(function ($) {
-
+
EXAMPLE:
% xopo -s "There are {:count/%u} {:event/%.6s} events\n"
There are {:count} {:event} events\n
@@ -25687,9 +25837,9 @@ jQuery(function ($) {
8.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. 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 without needing to care how the output is rendered.
+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.
@@ -25698,7 +25848,7 @@ jQuery(function ($) {
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;
@@ -25777,7 +25927,7 @@ jQuery(function ($) {
- 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) {
@@ -25789,7 +25939,7 @@ jQuery(function ($) {
- 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 3.2.1) or "{e:}" fields (Section 2.2.2.3) to make the data useful.
+- 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 3.2.2) or "{e:}" fields (Section 2.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
@@ -25838,10 +25988,10 @@ jQuery(function ($) {
'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.
@@ -25852,10 +26002,10 @@ jQuery(function ($) {
'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.
@@ -25867,10 +26017,10 @@ jQuery(function ($) {
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.
@@ -25881,10 +26031,10 @@ jQuery(function ($) {
'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
@@ -25895,10 +26045,10 @@ jQuery(function ($) {
'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}");
@@ -25908,10 +26058,10 @@ jQuery(function ($) {
'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 "/".
@@ -25922,7 +26072,7 @@ jQuery(function ($) {
'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.
@@ -25933,7 +26083,7 @@ jQuery(function ($) {
'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.
@@ -25944,10 +26094,10 @@ jQuery(function ($) {
'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‑".
@@ -25958,10 +26108,10 @@ jQuery(function ($) {
'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.
@@ -25972,10 +26122,10 @@ jQuery(function ($) {
'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").
@@ -25986,10 +26136,10 @@ jQuery(function ($) {
'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.
@@ -26000,10 +26150,10 @@ jQuery(function ($) {
'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.
@@ -26014,10 +26164,10 @@ jQuery(function ($) {
'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.
@@ -26028,10 +26178,10 @@ jQuery(function ($) {
'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.
@@ -26042,10 +26192,10 @@ jQuery(function ($) {
'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.
@@ -26056,10 +26206,10 @@ jQuery(function ($) {
'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}").
@@ -26070,10 +26220,10 @@ jQuery(function ($) {
'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.
@@ -26084,10 +26234,10 @@ jQuery(function ($) {
'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.
@@ -26098,10 +26248,10 @@ jQuery(function ($) {
'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.
@@ -26112,10 +26262,10 @@ jQuery(function ($) {
'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.
@@ -26126,10 +26276,10 @@ jQuery(function ($) {
'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.
@@ -26140,10 +26290,10 @@ jQuery(function ($) {
'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.
@@ -26183,7 +26333,7 @@ jQuery(function ($) {
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
@@ -26192,7 +26342,7 @@ jQuery(function ($) {
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
@@ -26212,7 +26362,7 @@ jQuery(function ($) {
9.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.
@@ -26236,10 +26386,10 @@ jQuery(function ($) {
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 3.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);
@@ -26247,8 +26397,8 @@ jQuery(function ($) {
return argc;
....
}
-
At the bottom of your main(), you'll need to call xo_finish() to complete output processing for the default handle (Section 2.5). libxo provides the xo_finish_atexit function that is suitable for use with the atexit(3) function.
-
+
At the bottom of your main(), you'll need to call xo_finish() to complete output processing for the default handle (Section 3.1). libxo provides the xo_finish_atexit function that is suitable for use with the atexit(3) function.
+
atexit(xo_finish_atexit);
@@ -26258,20 +26408,20 @@ jQuery(function ($) {
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 2.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 2.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 2.2.1.10).
-
+
snprintf(buf, sizeof(buf), "(%u/%u/%u)", min, ave, max);
printf("%30s", buf);
@@ -26285,7 +26435,7 @@ jQuery(function ($) {
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);
@@ -26303,7 +26453,7 @@ jQuery(function ($) {
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);
@@ -26322,7 +26472,7 @@ jQuery(function ($) {
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);
@@ -26340,12 +26490,12 @@ jQuery(function ($) {
9.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
@@ -26378,7 +26528,7 @@ jQuery(function ($) {
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:
@@ -26396,7 +26546,7 @@ jQuery(function ($) {
- 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"));
@@ -26404,17 +26554,17 @@ jQuery(function ($) {
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)));
@@ -26439,7 +26589,7 @@ jQuery(function ($) {
Unit Test
Here is the unit test example:
-
+
int
main (int argc, char **argv)
{
@@ -26532,7 +26682,7 @@ jQuery(function ($) {
return 0;
}
Text output:
-
+
% ./testxo --libxo text
Item 'gum':
Total sold: 1412.0
@@ -26565,7 +26715,7 @@ jQuery(function ($) {
On order: 1
SKU: GRO-000-533
JSON output:
-
+
% ./testxo --libxo json,pretty
"top": {
"data": {
@@ -26620,7 +26770,7 @@ jQuery(function ($) {
}
}
XML output:
-
+
% ./testxo --libxo pretty,xml
<top>
<data>
@@ -26671,7 +26821,7 @@ jQuery(function ($) {
</data>
</top>
HMTL output:
-
+
% ./testxo --libxo pretty,html
<div class="line">
<div class="label">Item</div>
@@ -26866,7 +27016,7 @@ jQuery(function ($) {
<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>
diff --git a/contrib/libxo/doc/libxo.txt b/contrib/libxo/doc/libxo.txt
index 1e7acc7984be..ba63702920c5 100644
--- a/contrib/libxo/doc/libxo.txt
+++ b/contrib/libxo/doc/libxo.txt
@@ -699,25 +699,26 @@ XOF_WARN is set, a warning will be generated.
Field modifiers are flags which modify the way content emitted for
particular output styles:
-|---+---------------+-------------------------------------------------|
-| M | Name | Description |
-|---+---------------+-------------------------------------------------|
-| 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 |
-|---+---------------+-------------------------------------------------|
+|---+---------------+--------------------------------------------------|
+| 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 preceeded by
a comma. For example, the modifier string "Lwc" (or "L,white,colon")
@@ -727,6 +728,27 @@ 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:
@@ -907,6 +929,21 @@ needed, but often this needs to be controlled by the caller.
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:
@@ -1029,6 +1066,24 @@ 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("Alll 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.
@@ -1163,6 +1218,53 @@ variants might be wise.
| 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:
@@ -1196,46 +1298,6 @@ penultimate line to:
data-type="number"
data-help="Number of items in stock">144
-** Command-line Arguments
-
-libxo uses command line options to trigger rendering behavior. The
-following options are recognised:
-
-- --libxo
-- --libxo=
-- --libxo:
-
-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) |
-| dtrt | Enable "Do The Right Thing" mode |
-| 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-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 |
-| text | Emit TEXT output |
-| underscores | Replace XML-friendly "-"s with JSON friendly "_"s e |
-| 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) |
-|-------------+-------------------------------------------------------|
-
-The brief options are detailed in ^LIBXO_OPTIONS^.
-
** Representing Hierarchy
For XML and JSON, individual fields appear inside hierarchies which
@@ -1382,20 +1444,81 @@ properly.
xo_close_marker("fish-guts");
}
+** Command-line Arguments
+
+libxo uses command line options to trigger rendering behavior. The
+following options are recognised:
+
+- --libxo
+- --libxo=
+- --libxo:
+
+Programs using libxo are expecting to call the xo_parse_args function
+to parse these arguments. See ^xo_parse_args^ for details.
+
+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) |
+| dtrt | Enable "Do The Right Thing" mode |
+| 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 e |
+| 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) |
+|-------------+-------------------------------------------------------|
+
+The brief options are detailed in ^LIBXO_OPTIONS^.
+
+* 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.
-A default handle is used when a NULL is passed to functions accepting
-a handle. This handle is initialized to write its data to stdout
-using the default style of text (XO_STYLE_TEXT).
+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.
-For the convenience of callers, the libxo library includes handle-less
-functions that implicitly use the default handle. Any function that
-takes a handle will use the default handle is a value of NULL is
-passed in place of a valid handle.
+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:
@@ -1404,46 +1527,6 @@ For example, the following are equivalent:
Handles are created using xo_create() and destroy using xo_destroy().
-** UTF-8
-
-All strings for libxo must be UTF-8. libxo will handle turning them
-into locale-based strings for display to the user.
-
-The only exception is argument formatted using the "%ls" format, which
-require a wide character string (wchar_t *) as input. 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("Alll strings are utf-8 content {:tag/%ls}",
- L"except for wide strings");
-
-"%S" is equivalent to "%ls".
-
-* The libxo API
-
-This section gives details about the functions in libxo, how to call
-them, and the actions they perform.
-
-** Handles
-
-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 to standard output.
-The xo_set_style and xo_set_flags functions can be used to change this
-behavior.
-
-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 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.
-
*** xo_create
A handle can be allocated using the xo_create() function:
@@ -1653,11 +1736,34 @@ 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, ...);
@@ -2555,23 +2661,23 @@ 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
+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. 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.
+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 without needing to care how the output is rendered.
+output calls with a single code path.
*** Did the complex semantics of format strings evolve over time?
diff --git a/contrib/libxo/encoder/cbor/enc_cbor.c b/contrib/libxo/encoder/cbor/enc_cbor.c
index 513063fb1508..7c0a1d33f932 100644
--- a/contrib/libxo/encoder/cbor/enc_cbor.c
+++ b/contrib/libxo/encoder/cbor/enc_cbor.c
@@ -135,7 +135,7 @@ cbor_encode_uint (xo_buffer_t *xbp, uint64_t minor, unsigned limit)
char *bp = xbp->xb_curp;
int i, m;
- if (minor > (1UL<<32)) {
+ if (minor > (1ULL << 32)) {
*bp++ |= CBOR_LEN64;
m = 64;
diff --git a/contrib/libxo/libxo-config.in b/contrib/libxo/libxo-config.in
index 3dbb7d41a364..f08f2340ecdb 100644
--- a/contrib/libxo/libxo-config.in
+++ b/contrib/libxo/libxo-config.in
@@ -77,34 +77,34 @@ while test $# -gt 0; do
;;
--cflags)
- echo -I@LIBXO_INCLUDEDIR@ @LIBXO_CFLAGS@
+ echo -I@XO_INCLUDEDIR@ @XO_CFLAGS@
;;
--share)
- echo @LIBXO_SHAREDIR@
+ echo @XO_SHAREDIR@
;;
--bindir)
- echo @LIBXO_BINDIR@
+ echo @XO_BINDIR@
;;
--libdir)
- echo @LIBXO_LIBDIR@
+ echo @XO_LIBDIR@
;;
--libs)
if [ "`uname`" = "Linux" ]
then
- if [ "@LIBXO_LIBDIR@" = "-L/usr/lib" -o "@LIBXO_LIBDIR@" = "-L/usr/lib64" ]
+ if [ "@XO_LIBDIR@" = "-L/usr/lib" -o "@XO_LIBDIR@" = "-L/usr/lib64" ]
then
- echo @LIBXO_LIBS@
+ echo @XO_LIBS@
else
- echo -L@LIBXO_LIBDIR@ @LIBXO_LIBS@
+ echo -L@XO_LIBDIR@ @XO_LIBS@
fi
else
- echo -L@LIBXO_LIBDIR@ @LIBXO_LIBS@ @WIN32_EXTRA_LIBADD@
+ echo -L@XO_LIBDIR@ @XO_LIBS@
fi
;;
diff --git a/contrib/libxo/libxo/libxo.c b/contrib/libxo/libxo/libxo.c
index bae810f179c7..194a0962b428 100644
--- a/contrib/libxo/libxo/libxo.c
+++ b/contrib/libxo/libxo/libxo.c
@@ -19,7 +19,8 @@
* http://juniper.github.io/libxo/libxo-manual.html
*
* For first time readers, the core bits of code to start looking at are:
- * - xo_do_emit() -- the central function of the library
+ * - xo_do_emit() -- parse and emit a set of fields
+ * - xo_do_emit_fields -- the central function of the library
* - xo_do_format_field() -- handles formatting a single field
* - xo_transiton() -- the state machine that keeps things sane
* and of course the "xo_handle_t" data structure, which carries all
@@ -120,6 +121,7 @@
const char xo_version[] = LIBXO_VERSION;
const char xo_version_extra[] = LIBXO_VERSION_EXTRA;
+static const char xo_default_format[] = "%s";
#ifndef UNUSED
#define UNUSED __attribute__ ((__unused__))
@@ -338,6 +340,7 @@ typedef unsigned long xo_xff_flags_t;
#define XFF_GT_FIELD (1<<19) /* Call gettext() on a field */
#define XFF_GT_PLURAL (1<<20) /* Call dngettext to find plural form */
+#define XFF_ARGUMENT (1<<21) /* Content provided via argument */
/* Flags to turn off when we don't want i18n processing */
#define XFF_GT_FLAGS (XFF_GT_FIELD | XFF_GT_PLURAL)
@@ -1046,7 +1049,7 @@ xo_is_utf8 (char ch)
return (ch & 0x80);
}
-static int
+static inline int
xo_utf8_to_wc_len (const char *buf)
{
unsigned b = (unsigned char) *buf;
@@ -1105,9 +1108,13 @@ xo_buf_utf8_len (xo_handle_t *xop, const char *buf, int bufsiz)
* bits we pull off the first character is dependent on the length,
* but we put 6 bits off all other bytes.
*/
-static wchar_t
+static inline wchar_t
xo_utf8_char (const char *buf, int len)
{
+ /* Most common case: singleton byte */
+ if (len == 1)
+ return (unsigned char) buf[0];
+
int i;
wchar_t wc;
const unsigned char *cp = (const unsigned char *) buf;
@@ -1281,6 +1288,195 @@ xo_data_escape (xo_handle_t *xop, const char *str, int len)
xo_buf_escape(xop, &xop->xo_data, str, len, 0);
}
+#ifdef LIBXO_NO_RETAIN
+/*
+ * Empty implementations of the retain logic
+ */
+
+void
+xo_retain_clear_all (void)
+{
+ return;
+}
+
+void
+xo_retain_clear (const char *fmt UNUSED)
+{
+ return;
+}
+static void
+xo_retain_add (const char *fmt UNUSED, xo_field_info_t *fields UNUSED,
+ unsigned num_fields UNUSED)
+{
+ return;
+}
+
+static int
+xo_retain_find (const char *fmt UNUSED, xo_field_info_t **valp UNUSED,
+ unsigned *nump UNUSED)
+{
+ return -1;
+}
+
+#else /* !LIBXO_NO_RETAIN */
+/*
+ * Retain: We retain parsed field definitions to enhance performance,
+ * especially inside loops. We depend on the caller treating the format
+ * strings as immutable, so that we can retain pointers into them. We
+ * hold the pointers in a hash table, so allow quick access. Retained
+ * information is retained until xo_retain_clear is called.
+ */
+
+/*
+ * xo_retain_entry_t holds information about one retained set of
+ * parsed fields.
+ */
+typedef struct xo_retain_entry_s {
+ struct xo_retain_entry_s *xre_next; /* Pointer to next (older) entry */
+ unsigned long xre_hits; /* Number of times we've hit */
+ const char *xre_format; /* Pointer to format string */
+ unsigned xre_num_fields; /* Number of fields saved */
+ xo_field_info_t *xre_fields; /* Pointer to fields */
+} xo_retain_entry_t;
+
+/*
+ * xo_retain_t holds a complete set of parsed fields as a hash table.
+ */
+#ifndef XO_RETAIN_SIZE
+#define XO_RETAIN_SIZE 6
+#endif /* XO_RETAIN_SIZE */
+#define RETAIN_HASH_SIZE (1<> 4) & (((1 << 24) - 1)));
+
+ val = (val ^ 61) ^ (val >> 16);
+ val = val + (val << 3);
+ val = val ^ (val >> 4);
+ val = val * 0x3a8f05c5; /* My large prime number */
+ val = val ^ (val >> 15);
+ val &= RETAIN_HASH_SIZE - 1;
+
+ return val;
+}
+
+/*
+ * Walk all buckets, clearing all retained entries
+ */
+void
+xo_retain_clear_all (void)
+{
+ int i;
+ xo_retain_entry_t *xrep, *next;
+
+ for (i = 0; i < RETAIN_HASH_SIZE; i++) {
+ for (xrep = xo_retain.xr_bucket[i]; xrep; xrep = next) {
+ next = xrep->xre_next;
+ xo_free(xrep);
+ }
+ xo_retain.xr_bucket[i] = NULL;
+ }
+ xo_retain_count = 0;
+}
+
+/*
+ * Walk all buckets, clearing all retained entries
+ */
+void
+xo_retain_clear (const char *fmt)
+{
+ xo_retain_entry_t **xrepp;
+ unsigned hash = xo_retain_hash(fmt);
+
+ for (xrepp = &xo_retain.xr_bucket[hash]; *xrepp;
+ xrepp = &(*xrepp)->xre_next) {
+ if ((*xrepp)->xre_format == fmt) {
+ *xrepp = (*xrepp)->xre_next;
+ xo_retain_count -= 1;
+ return;
+ }
+ }
+}
+
+/*
+ * Search the hash for an entry matching 'fmt'; return it's fields.
+ */
+static int
+xo_retain_find (const char *fmt, xo_field_info_t **valp, unsigned *nump)
+{
+ if (xo_retain_count == 0)
+ return -1;
+
+ unsigned hash = xo_retain_hash(fmt);
+ xo_retain_entry_t *xrep;
+
+ for (xrep = xo_retain.xr_bucket[hash]; xrep != NULL;
+ xrep = xrep->xre_next) {
+ if (xrep->xre_format == fmt) {
+ *valp = xrep->xre_fields;
+ *nump = xrep->xre_num_fields;
+ xrep->xre_hits += 1;
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+static void
+xo_retain_add (const char *fmt, xo_field_info_t *fields, unsigned num_fields)
+{
+ unsigned hash = xo_retain_hash(fmt);
+ xo_retain_entry_t *xrep;
+ unsigned sz = sizeof(*xrep) + (num_fields + 1) * sizeof(*fields);
+ xo_field_info_t *xfip;
+
+ xrep = xo_realloc(NULL, sz);
+ if (xrep == NULL)
+ return;
+
+ xfip = (xo_field_info_t *) &xrep[1];
+ memcpy(xfip, fields, num_fields * sizeof(*fields));
+
+ bzero(xrep, sizeof(*xrep));
+
+ xrep->xre_format = fmt;
+ xrep->xre_fields = xfip;
+ xrep->xre_num_fields = num_fields;
+
+ /* Record the field info in the retain bucket */
+ xrep->xre_next = xo_retain.xr_bucket[hash];
+ xo_retain.xr_bucket[hash] = xrep;
+ xo_retain_count += 1;
+}
+
+#endif /* !LIBXO_NO_RETAIN */
+
/*
* Generate a warning. Normally, this is a text message written to
* standard error. If the XOF_WARN_XML flag is set, then we generate
@@ -1574,6 +1770,19 @@ xo_message_hcv (xo_handle_t *xop, int code, const char *fmt, va_list vap)
break;
}
+ switch (xo_style(xop)) {
+ case XO_STYLE_HTML:
+ if (XOIF_ISSET(xop, XOIF_DIV_OPEN)) {
+ static char div_close[] = "";
+ XOIF_CLEAR(xop, XOIF_DIV_OPEN);
+ xo_data_append(xop, div_close, sizeof(div_close) - 1);
+
+ if (XOF_ISSET(xop, XOF_PRETTY))
+ xo_data_append(xop, "\n", 1);
+ }
+ break;
+ }
+
(void) xo_flush_h(xop);
}
@@ -1679,6 +1888,39 @@ xo_create_to_file (FILE *fp, xo_style_t style, xo_xof_flags_t flags)
return xop;
}
+/**
+ * Set the default handler to output to a file.
+ * @xop libxo handle
+ * @fp FILE pointer to use
+ */
+int
+xo_set_file_h (xo_handle_t *xop, FILE *fp)
+{
+ xop = xo_default(xop);
+
+ if (fp == NULL) {
+ xo_failure(xop, "xo_set_file: NULL fp");
+ return -1;
+ }
+
+ xop->xo_opaque = fp;
+ xop->xo_write = xo_write_to_file;
+ xop->xo_close = xo_close_file;
+ xop->xo_flush = xo_flush_file;
+
+ return 0;
+}
+
+/**
+ * Set the default handler to output to a file.
+ * @fp FILE pointer to use
+ */
+int
+xo_set_file (FILE *fp)
+{
+ return xo_set_file_h(NULL, fp);
+}
+
/**
* Release any resources held by the handle.
* @xop XO handle to alter (or NULL for default handle)
@@ -1824,9 +2066,11 @@ static xo_mapping_t xo_xof_names[] = {
{ XOF_LOG_SYSLOG, "log-syslog" },
{ XOF_NO_HUMANIZE, "no-humanize" },
{ XOF_NO_LOCALE, "no-locale" },
+ { XOF_RETAIN_NONE, "no-retain" },
{ XOF_NO_TOP, "no-top" },
{ XOF_NOT_FIRST, "not-first" },
{ XOF_PRETTY, "pretty" },
+ { XOF_RETAIN_ALL, "retain" },
{ XOF_UNDERSCORES, "underscores" },
{ XOF_UNITS, "units" },
{ XOF_WARN, "warn" },
@@ -3613,10 +3857,9 @@ xo_format_text (xo_handle_t *xop, const char *str, int len)
}
static void
-xo_format_title (xo_handle_t *xop, xo_field_info_t *xfip)
+xo_format_title (xo_handle_t *xop, xo_field_info_t *xfip,
+ const char *str, unsigned len)
{
- const char *str = xfip->xfi_content;
- unsigned len = xfip->xfi_clen;
const char *fmt = xfip->xfi_format;
unsigned flen = xfip->xfi_flen;
xo_xff_flags_t flags = xfip->xfi_flags;
@@ -4083,10 +4326,9 @@ xo_format_value (xo_handle_t *xop, const char *name, int nlen,
}
static void
-xo_set_gettext_domain (xo_handle_t *xop, xo_field_info_t *xfip)
+xo_set_gettext_domain (xo_handle_t *xop, xo_field_info_t *xfip,
+ const char *str, unsigned len)
{
- const char *str = xfip->xfi_content;
- unsigned len = xfip->xfi_clen;
const char *fmt = xfip->xfi_format;
unsigned flen = xfip->xfi_flen;
@@ -4335,13 +4577,13 @@ xo_colors_enabled (xo_handle_t *xop UNUSED)
}
static void
-xo_colors_handle_text (xo_handle_t *xop UNUSED, xo_colors_t *newp)
+xo_colors_handle_text (xo_handle_t *xop, xo_colors_t *newp)
{
char buf[BUFSIZ];
char *cp = buf, *ep = buf + sizeof(buf);
unsigned i, bit;
xo_colors_t *oldp = &xop->xo_colors;
- const char *code;
+ const char *code = NULL;
/*
* Start the buffer with an escape. We don't want to add the '['
@@ -4460,10 +4702,9 @@ xo_colors_handle_html (xo_handle_t *xop, xo_colors_t *newp)
}
static void
-xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip)
+xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip,
+ const char *str, unsigned len)
{
- const char *str = xfip->xfi_content;
- unsigned len = xfip->xfi_clen;
const char *fmt = xfip->xfi_format;
unsigned flen = xfip->xfi_flen;
@@ -4534,10 +4775,9 @@ xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip)
}
static void
-xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip)
+xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip,
+ const char *str, unsigned len)
{
- const char *str = xfip->xfi_content;
- unsigned len = xfip->xfi_clen;
const char *fmt = xfip->xfi_format;
unsigned flen = xfip->xfi_flen;
xo_xff_flags_t flags = xfip->xfi_flags;
@@ -4589,10 +4829,9 @@ xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip)
}
static int
-xo_find_width (xo_handle_t *xop, xo_field_info_t *xfip)
+xo_find_width (xo_handle_t *xop, xo_field_info_t *xfip,
+ const char *str, unsigned len)
{
- const char *str = xfip->xfi_content;
- unsigned len = xfip->xfi_clen;
const char *fmt = xfip->xfi_format;
unsigned flen = xfip->xfi_flen;
@@ -4639,7 +4878,8 @@ xo_anchor_clear (xo_handle_t *xop)
* format it when the end anchor tag is seen.
*/
static void
-xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip)
+xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip,
+ const char *str, unsigned len)
{
if (xo_style(xop) != XO_STYLE_TEXT && xo_style(xop) != XO_STYLE_HTML)
return;
@@ -4656,11 +4896,12 @@ xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip)
* Now we find the width, if possible. If it's not there,
* we'll get it on the end anchor.
*/
- xop->xo_anchor_min_width = xo_find_width(xop, xfip);
+ xop->xo_anchor_min_width = xo_find_width(xop, xfip, str, len);
}
static void
-xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip)
+xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip,
+ const char *str, unsigned len)
{
if (xo_style(xop) != XO_STYLE_TEXT && xo_style(xop) != XO_STYLE_HTML)
return;
@@ -4672,7 +4913,7 @@ xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip)
XOIF_CLEAR(xop, XOIF_UNITS_PENDING);
- int width = xo_find_width(xop, xfip);
+ int width = xo_find_width(xop, xfip, str, len);
if (width == 0)
width = xop->xo_anchor_min_width;
@@ -4787,6 +5028,7 @@ static xo_mapping_t xo_role_names[] = {
#define XO_ROLE_NEWLINE '\n'
static xo_mapping_t xo_modifier_names[] = {
+ { XFF_ARGUMENT, "argument" },
{ XFF_COLON, "colon" },
{ XFF_COMMA, "comma" },
{ XFF_DISPLAY_ONLY, "display" },
@@ -4858,6 +5100,7 @@ xo_count_fields (xo_handle_t *xop UNUSED, const char *fmt)
* '[': start a section of anchored text
* ']': end a section of anchored text
* The following modifiers are also supported:
+ * 'a': content is provided via argument (const char *), not descriptor
* 'c': flag: emit a colon after the label
* 'd': field is only emitted for display styles (text and html)
* 'e': field is only emitted for encoding styles (xml and json)
@@ -4884,7 +5127,7 @@ xo_parse_roles (xo_handle_t *xop, const char *fmt,
xo_xff_flags_t flags = 0;
uint8_t fnum = 0;
- for (sp = basep; sp; sp++) {
+ for (sp = basep; sp && *sp; sp++) {
if (*sp == ':' || *sp == '/' || *sp == '}')
break;
@@ -4961,6 +5204,10 @@ xo_parse_roles (xo_handle_t *xop, const char *fmt,
fnum = (fnum * 10) + (*sp - '0');
break;
+ case 'a':
+ flags |= XFF_ARGUMENT;
+ break;
+
case 'c':
flags |= XFF_COLON;
break;
@@ -5133,7 +5380,6 @@ static int
xo_parse_fields (xo_handle_t *xop, xo_field_info_t *fields,
unsigned num_fields, const char *fmt)
{
- static const char default_format[] = "%s";
const char *cp, *sp, *ep, *basep;
unsigned field = 0;
xo_field_info_t *xfip = fields;
@@ -5267,12 +5513,12 @@ xo_parse_fields (xo_handle_t *xop, xo_field_info_t *fields,
xfip->xfi_next = ++sp;
/* If we have content, then we have a default format */
- if (xfip->xfi_clen || format) {
+ if (xfip->xfi_clen || format || (xfip->xfi_flags & XFF_ARGUMENT)) {
if (format) {
xfip->xfi_format = format;
xfip->xfi_flen = flen;
} else if (xo_role_wants_default_format(xfip->xfi_ftype)) {
- xfip->xfi_format = default_format;
+ xfip->xfi_format = xo_default_format;
xfip->xfi_flen = 2;
}
}
@@ -5568,9 +5814,8 @@ xo_gettext_combine_formats (xo_handle_t *xop, const char *fmt UNUSED,
* Summary: i18n aighn't cheap.
*/
static const char *
-xo_gettext_build_format (xo_handle_t *xop UNUSED,
- xo_field_info_t *fields UNUSED,
- int this_field UNUSED,
+xo_gettext_build_format (xo_handle_t *xop,
+ xo_field_info_t *fields, int this_field,
const char *fmt, char **new_fmtp)
{
if (xo_style_is_encoding(xop))
@@ -5686,17 +5931,22 @@ xo_gettext_rebuild_content (xo_handle_t *xop UNUSED,
#endif /* HAVE_GETTEXT */
/*
- * The central function for emitting libxo output.
+ * Emit a set of fields. This is really the core of libxo.
*/
static int
-xo_do_emit (xo_handle_t *xop, const char *fmt)
+xo_do_emit_fields (xo_handle_t *xop, xo_field_info_t *fields,
+ unsigned max_fields, const char *fmt)
{
int gettext_inuse = 0;
int gettext_changed = 0;
int gettext_reordered = 0;
+ unsigned ftype;
+ xo_xff_flags_t flags;
xo_field_info_t *new_fields = NULL;
-
+ xo_field_info_t *xfip;
+ unsigned field;
int rc = 0;
+
int flush = XOF_ISSET(xop, XOF_FLUSH);
int flush_line = XOF_ISSET(xop, XOF_FLUSH_LINE);
char *new_fmt = NULL;
@@ -5704,20 +5954,6 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
if (XOIF_ISSET(xop, XOIF_REORDER) || xo_style(xop) == XO_STYLE_ENCODER)
flush_line = 0;
- xop->xo_columns = 0; /* Always reset it */
- xop->xo_errno = errno; /* Save for "%m" */
-
- unsigned max_fields = xo_count_fields(xop, fmt), field;
- xo_field_info_t fields[max_fields], *xfip;
-
- bzero(fields, max_fields * sizeof(fields[0]));
-
- if (xo_parse_fields(xop, fields, max_fields, fmt))
- return -1; /* Warning already displayed */
-
- unsigned ftype;
- xo_xff_flags_t flags;
-
/*
* Some overhead for gettext; if the fields in the msgstr returned
* by gettext are reordered, then we need to record start and end
@@ -5745,6 +5981,18 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
min_fstart = field;
}
+ const char *content = xfip->xfi_content;
+ int clen = xfip->xfi_clen;
+
+ if (flags & XFF_ARGUMENT) {
+ /*
+ * Argument flag means the content isn't given in the descriptor,
+ * but as a UTF-8 string ('const char *') argument in xo_vap.
+ */
+ content = va_arg(xop->xo_vap, char *);
+ clen = content ? strlen(content) : 0;
+ }
+
if (ftype == XO_ROLE_NEWLINE) {
xo_line_close(xop);
if (flush_line && xo_flush_h(xop) < 0)
@@ -5773,15 +6021,15 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
}
if (ftype == 'V')
- xo_format_value(xop, xfip->xfi_content, xfip->xfi_clen,
+ xo_format_value(xop, content, clen,
xfip->xfi_format, xfip->xfi_flen,
xfip->xfi_encoding, xfip->xfi_elen, flags);
else if (ftype == '[')
- xo_anchor_start(xop, xfip);
+ xo_anchor_start(xop, xfip, content, clen);
else if (ftype == ']')
- xo_anchor_stop(xop, xfip);
+ xo_anchor_stop(xop, xfip, content, clen);
else if (ftype == 'C')
- xo_format_colors(xop, xfip);
+ xo_format_colors(xop, xfip, content, clen);
else if (ftype == 'G') {
/*
@@ -5792,7 +6040,7 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
* Since gettext returns strings in a static buffer, we make
* a copy in new_fmt.
*/
- xo_set_gettext_domain(xop, xfip);
+ xo_set_gettext_domain(xop, xfip, content, clen);
if (!gettext_inuse) { /* Only translate once */
gettext_inuse = 1;
@@ -5843,17 +6091,17 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
}
continue;
- } else if (xfip->xfi_clen || xfip->xfi_format) {
+ } else if (clen || xfip->xfi_format) {
const char *class_name = xo_class_name(ftype);
if (class_name)
xo_format_content(xop, class_name, xo_tag_name(ftype),
- xfip->xfi_content, xfip->xfi_clen,
+ content, clen,
xfip->xfi_format, xfip->xfi_flen, flags);
else if (ftype == 'T')
- xo_format_title(xop, xfip);
+ xo_format_title(xop, xfip, content, clen);
else if (ftype == 'U')
- xo_format_units(xop, xfip);
+ xo_format_units(xop, xfip, content, clen);
else
xo_failure(xop, "unknown field type: '%c'", ftype);
}
@@ -5884,7 +6132,7 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
if (flush && !XOIF_ISSET(xop, XOIF_ANCHOR)) {
if (xo_write(xop) < 0)
rc = -1; /* Report failure */
- else if (xop->xo_flush && xop->xo_flush(xop->xo_opaque) < 0)
+ else if (xo_flush_h(xop) < 0)
rc = -1;
}
@@ -5904,6 +6152,53 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
return (rc < 0) ? rc : (int) xop->xo_columns;
}
+/*
+ * Parse and emit a set of fields
+ */
+static int
+xo_do_emit (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt)
+{
+ xop->xo_columns = 0; /* Always reset it */
+ xop->xo_errno = errno; /* Save for "%m" */
+
+ if (fmt == NULL)
+ return 0;
+
+ unsigned max_fields;
+ xo_field_info_t *fields = NULL;
+
+ /* Adjust XOEF_RETAIN based on global flags */
+ if (XOF_ISSET(xop, XOF_RETAIN_ALL))
+ flags |= XOEF_RETAIN;
+ if (XOF_ISSET(xop, XOF_RETAIN_NONE))
+ flags &= ~XOEF_RETAIN;
+
+ /*
+ * Check for 'retain' flag, telling us to retain the field
+ * information. If we've already saved it, then we can avoid
+ * re-parsing the format string.
+ */
+ if (!(flags & XOEF_RETAIN)
+ || xo_retain_find(fmt, &fields, &max_fields) != 0
+ || fields == NULL) {
+
+ /* Nothing retained; parse the format string */
+ max_fields = xo_count_fields(xop, fmt);
+ fields = alloca(max_fields * sizeof(fields[0]));
+ bzero(fields, max_fields * sizeof(fields[0]));
+
+ if (xo_parse_fields(xop, fields, max_fields, fmt))
+ return -1; /* Warning already displayed */
+
+ if (flags & XOEF_RETAIN) {
+ /* Retain the info */
+ xo_retain_add(fmt, fields, max_fields);
+ }
+ }
+
+ return xo_do_emit_fields(xop, fields, max_fields, fmt);
+}
+
/*
* Rebuild a format string in a gettext-friendly format. This function
* is exposed to tools can perform this function. See xo(1).
@@ -5944,7 +6239,7 @@ xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap)
xop = xo_default(xop);
va_copy(xop->xo_vap, vap);
- rc = xo_do_emit(xop, fmt);
+ rc = xo_do_emit(xop, 0, fmt);
va_end(xop->xo_vap);
bzero(&xop->xo_vap, sizeof(xop->xo_vap));
@@ -5958,7 +6253,7 @@ xo_emit_h (xo_handle_t *xop, const char *fmt, ...)
xop = xo_default(xop);
va_start(xop->xo_vap, fmt);
- rc = xo_do_emit(xop, fmt);
+ rc = xo_do_emit(xop, 0, fmt);
va_end(xop->xo_vap);
bzero(&xop->xo_vap, sizeof(xop->xo_vap));
@@ -5972,13 +6267,137 @@ xo_emit (const char *fmt, ...)
int rc;
va_start(xop->xo_vap, fmt);
- rc = xo_do_emit(xop, fmt);
+ rc = xo_do_emit(xop, 0, fmt);
va_end(xop->xo_vap);
bzero(&xop->xo_vap, sizeof(xop->xo_vap));
return rc;
}
+int
+xo_emit_hvf (xo_handle_t *xop, xo_emit_flags_t flags,
+ const char *fmt, va_list vap)
+{
+ int rc;
+
+ xop = xo_default(xop);
+ va_copy(xop->xo_vap, vap);
+ rc = xo_do_emit(xop, flags, fmt);
+ va_end(xop->xo_vap);
+ bzero(&xop->xo_vap, sizeof(xop->xo_vap));
+
+ return rc;
+}
+
+int
+xo_emit_hf (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...)
+{
+ int rc;
+
+ xop = xo_default(xop);
+ va_start(xop->xo_vap, fmt);
+ rc = xo_do_emit(xop, flags, fmt);
+ va_end(xop->xo_vap);
+ bzero(&xop->xo_vap, sizeof(xop->xo_vap));
+
+ return rc;
+}
+
+int
+xo_emit_f (xo_emit_flags_t flags, const char *fmt, ...)
+{
+ xo_handle_t *xop = xo_default(NULL);
+ int rc;
+
+ va_start(xop->xo_vap, fmt);
+ rc = xo_do_emit(xop, flags, fmt);
+ va_end(xop->xo_vap);
+ bzero(&xop->xo_vap, sizeof(xop->xo_vap));
+
+ return rc;
+}
+
+/*
+ * Emit a single field by providing the info information typically provided
+ * inside the field description (role, modifiers, and formats). This is
+ * a convenience function to avoid callers using snprintf to build field
+ * descriptions.
+ */
+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 rc;
+
+ xop = xo_default(xop);
+
+ if (rolmod == NULL)
+ rolmod = "V";
+
+ xo_field_info_t xfi;
+
+ bzero(&xfi, sizeof(xfi));
+
+ const char *cp;
+ cp = xo_parse_roles(xop, rolmod, rolmod, &xfi);
+ if (cp == NULL)
+ return -1;
+
+ xfi.xfi_start = fmt;
+ xfi.xfi_content = contents;
+ xfi.xfi_format = fmt;
+ xfi.xfi_encoding = efmt;
+ xfi.xfi_clen = contents ? strlen(contents) : 0;
+ xfi.xfi_flen = fmt ? strlen(fmt) : 0;
+ xfi.xfi_elen = efmt ? strlen(efmt) : 0;
+
+ /* If we have content, then we have a default format */
+ if (contents && fmt == NULL
+ && xo_role_wants_default_format(xfi.xfi_ftype)) {
+ xfi.xfi_format = xo_default_format;
+ xfi.xfi_flen = 2;
+ }
+
+
+
+ va_copy(xop->xo_vap, vap);
+
+ rc = xo_do_emit_fields(xop, &xfi, 1, fmt ?: contents ?: "field");
+
+ va_end(xop->xo_vap);
+
+ return rc;
+}
+
+int
+xo_emit_field_h (xo_handle_t *xop, const char *rolmod, const char *contents,
+ const char *fmt, const char *efmt, ...)
+{
+ int rc;
+ va_list vap;
+
+ va_start(vap, efmt);
+ rc = xo_emit_field_hv(xop, rolmod, contents, fmt, efmt, vap);
+ va_end(vap);
+
+ return rc;
+}
+
+int
+xo_emit_field (const char *rolmod, const char *contents,
+ const char *fmt, const char *efmt, ...)
+{
+ int rc;
+ va_list vap;
+
+ va_start(vap, efmt);
+ rc = xo_emit_field_hv(NULL, rolmod, contents, fmt, efmt, vap);
+ va_end(vap);
+
+ return rc;
+}
+
int
xo_attr_hv (xo_handle_t *xop, const char *name, const char *fmt, va_list vap)
{
@@ -6392,7 +6811,7 @@ xo_open_list_hf (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name)
}
int
-xo_open_list_h (xo_handle_t *xop, const char *name UNUSED)
+xo_open_list_h (xo_handle_t *xop, const char *name)
{
return xo_open_list_hf(xop, 0, name);
}
@@ -6404,7 +6823,7 @@ xo_open_list (const char *name)
}
int
-xo_open_list_hd (xo_handle_t *xop, const char *name UNUSED)
+xo_open_list_hd (xo_handle_t *xop, const char *name)
{
return xo_open_list_hf(xop, XOF_DTRT, name);
}
@@ -7113,6 +7532,11 @@ xo_transition (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name,
xsp->xs_state, new_state);
}
+ /* Handle the flush flag */
+ if (rc >= 0 && XOF_ISSET(xop, XOF_FLUSH))
+ if (xo_flush_h(xop))
+ rc = -1;
+
return rc;
marker_prevents_close:
@@ -7179,22 +7603,11 @@ xo_set_allocator (xo_realloc_func_t realloc_func, xo_free_func_t free_func)
int
xo_flush_h (xo_handle_t *xop)
{
- static char div_close[] = "";
int rc;
xop = xo_default(xop);
switch (xo_style(xop)) {
- case XO_STYLE_HTML:
- if (XOIF_ISSET(xop, XOIF_DIV_OPEN)) {
- XOIF_CLEAR(xop, XOIF_DIV_OPEN);
- xo_data_append(xop, div_close, sizeof(div_close) - 1);
-
- if (XOF_ISSET(xop, XOF_PRETTY))
- xo_data_append(xop, "\n", 1);
- }
- break;
-
case XO_STYLE_ENCODER:
xo_encoder_handle(xop, XO_OP_FLUSH, NULL, NULL);
}
@@ -7435,7 +7848,7 @@ xo_set_program (const char *name)
}
void
-xo_set_version_h (xo_handle_t *xop, const char *version UNUSED)
+xo_set_version_h (xo_handle_t *xop, const char *version)
{
xop = xo_default(xop);
diff --git a/contrib/libxo/libxo/xo.h b/contrib/libxo/libxo/xo.h
index 88bcce2999df..310b21cae366 100644
--- a/contrib/libxo/libxo/xo.h
+++ b/contrib/libxo/libxo/xo.h
@@ -94,6 +94,11 @@ typedef unsigned long long xo_xof_flags_t;
#define XOF_LOG_GETTEXT XOF_BIT(28) /** Log (stderr) gettext lookup strings */
#define XOF_UTF8 XOF_BIT(29) /** Force text output to be UTF8 */
+#define XOF_RETAIN_ALL XOF_BIT(30) /** Force use of XOEF_RETAIN */
+#define XOF_RETAIN_NONE XOF_BIT(31) /** Prevent use of XOEF_RETAIN */
+
+typedef unsigned xo_emit_flags_t; /* Flags to xo_emit() and friends */
+#define XOEF_RETAIN (1<<0) /* Retain parsed formatting information */
/*
* The xo_info_t structure provides a mapping between names and
@@ -162,6 +167,12 @@ xo_set_flags (xo_handle_t *xop, xo_xof_flags_t flags);
void
xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags);
+int
+xo_set_file_h (xo_handle_t *xop, FILE *fp);
+
+int
+xo_set_file (FILE *fp);
+
void
xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count);
@@ -180,6 +191,16 @@ xo_emit_h (xo_handle_t *xop, const char *fmt, ...);
int
xo_emit (const char *fmt, ...);
+int
+xo_emit_hvf (xo_handle_t *xop, xo_emit_flags_t flags,
+ const char *fmt, va_list vap);
+
+int
+xo_emit_hf (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...);
+
+int
+xo_emit_f (xo_emit_flags_t flags, const char *fmt, ...);
+
PRINTFLIKE(2, 0)
static inline int
xo_emit_hvp (xo_handle_t *xop, const char *fmt, va_list vap)
@@ -209,6 +230,36 @@ xo_emit_p (const char *fmt, ...)
return rc;
}
+PRINTFLIKE(3, 0)
+static inline int
+xo_emit_hvfp (xo_handle_t *xop, xo_emit_flags_t flags,
+ const char *fmt, va_list vap)
+{
+ return xo_emit_hvf(xop, flags, fmt, vap);
+}
+
+PRINTFLIKE(3, 4)
+static inline int
+xo_emit_hfp (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...)
+{
+ va_list vap;
+ va_start(vap, fmt);
+ int rc = xo_emit_hvf(xop, flags, fmt, vap);
+ va_end(vap);
+ return rc;
+}
+
+PRINTFLIKE(2, 3)
+static inline int
+xo_emit_fp (xo_emit_flags_t flags, const char *fmt, ...)
+{
+ va_list vap;
+ va_start(vap, fmt);
+ int rc = xo_emit_hvf(NULL, flags, fmt, vap);
+ va_end(vap);
+ return rc;
+}
+
int
xo_open_container_h (xo_handle_t *xop, const char *name);
@@ -593,4 +644,23 @@ char *
xo_simplify_format (xo_handle_t *xop, const char *fmt, int with_numbers,
xo_simplify_field_func_t field_cb);
+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, ...);
+
+void
+xo_retain_clear_all (void);
+
+void
+xo_retain_clear (const char *fmt);
+
#endif /* INCLUDE_XO_H */
diff --git a/contrib/libxo/libxo/xo_emit_f.3 b/contrib/libxo/libxo/xo_emit_f.3
new file mode 100644
index 000000000000..087954631516
--- /dev/null
+++ b/contrib/libxo/libxo/xo_emit_f.3
@@ -0,0 +1,111 @@
+.\" #
+.\" # Copyright (c) 2016, 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, April 2016
+.\"
+.Dd April 15, 2016
+.Dt LIBXO 3
+.Os
+.Sh NAME
+.Nm xo_emit_f , xo_emit_hf , xo_emit_hvf
+.Nd emit formatted output based on format string and arguments
+.Sh LIBRARY
+.Lb libxo
+.Sh SYNOPSIS
+.In libxo/xo.h
+.Ft int
+.Fn xo_emit_f "xo_emit_flags_t flags" "const char *fmt" "..."
+.Ft int
+.Fn xo_emit_hf "xo_handle_t *xop" "xo_emit_flags_t flags" "const char *fmt" "..."
+.Ft int
+.Fn xo_emit_hvf "xo_handle_t *xop" "xo_emit_flags_t flags" "const char *fmt" "va_list vap"
+.Ft void
+.Fn xo_retain_clear_all "void"
+.Ft void
+.Fn xo_retain_clear "const char *fmt"
+.Sh DESCRIPTION
+These functions allow callers to pass a set of flags to
+.Nm
+emitting functions. These processing of arguments, except for
+.Fa flags ,
+is identical to the base functions.
+See
+.Xr xo_emit 3
+for additional information.
+.Pp
+The only currently defined flag is
+.Dv XOEF_RETAIN .
+.Nm
+can retain the parsed internal information related to the given
+format string, allowing subsequent
+.Xr xo_emit 3
+calls, the retained
+information is used, avoiding repetitive parsing of the format string.
+To retain parsed format information, use the
+.Dv XOEF_RETAIN
+flag to the
+.Fn xo_emit_f
+function.
+.Pp
+The format string must be immutable across multiple calls to
+.Xn 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
+.Dv XOEF_RETAIN
+flag must not be used.
+.Pp
+The functions
+.Fn xo_retain_clear
+and
+.Fn 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.
+.Pp
+The retained information is kept as thread-specific data.
+.Pp
+Use
+.Fn xo_retain_clear
+and
+.Fn xo_retain_clear_all
+to clear the retained information, clearing the retained information
+for either a specific format string or all format strings, respectively.
+These functions are only needed when the calling application wants to
+clear this information; they are not generally needed.
+.Sh EXAMPLES
+.Pp
+.Bd -literal -offset indent
+ for (i = 0; i < 1000; i++) {
+ xo_open_instance("item");
+ xo_emit_f(XOEF_RETAIN, "{:name} {:count/%d}\n",
+ name[i], count[i]);
+ }
+.Ed
+.Pp
+In this example, the caller desires to clear the retained information.
+.Bd -literal -offset indent
+ 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);
+.Ed
+.Sh RETURN CODE
+The return values for these functions is identical to those of their
+traditional counterparts. See
+.Xr xo_emit 3
+for details.
+.Sh SEE ALSO
+.Xr xo_emit 3 ,
+.Xr xo_open_container 3 ,
+.Xr xo_open_list 3 ,
+.Xr xo_format 5 ,
+.Xr libxo 3
diff --git a/contrib/libxo/libxo/xo_format.5 b/contrib/libxo/libxo/xo_format.5
index 89c010391d51..79af3fa39f3d 100644
--- a/contrib/libxo/libxo/xo_format.5
+++ b/contrib/libxo/libxo/xo_format.5
@@ -51,14 +51,14 @@ field descriptions within the format string.
.Pp
The field description is given as follows:
.Bd -literal -offset indent
- '{' [ role | modifier ]* [',' long-names ]* ':' [ content ]
- [ '/' field-format [ '/' encoding-format ]] '}'
+ \(aq{\(aq [ role | modifier ]* [\(aq,\(aq long\-names ]* \(aq:\(aq [ content ]
+ [ \(aq/\(aq field\-format [ \(aq/\(aq encoding\-format ]] \(aq}\(aq
.Ed
.Pp
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.
+The contents, field\-format, and
+encoding\-format are used in varying ways, based on the role.
These are described in the following sections.
.Pp
Braces can be escaped by using double braces, similar to "%%" in
@@ -68,26 +68,26 @@ The format string "{{braces}}" would emit "{braces}".
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
+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
.Xr xo_emit 3 ,
function as an unsigned integer.
.Bd -literal -offset indent
- xo_emit("{P: }{Lwc:In stock}{:in-stock/%u}\\n", 65);
+ xo_emit("{P: }{Lwc:In stock}{:in\-stock/%u}\\n", 65);
.Ed
.Pp
This single line of code can generate text ("In stock: 65\\n"), XML
-("65 "), JSON ('"in-stock": 65'), or HTML (too
+("65 "), JSON (\(aq"in\-stock": 65\(aq), or HTML (too
lengthy to be listed here).
.Pp
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:
+single\-character values:
.Bd -literal -offset indent
- xo_emit("{L,white,colon:In stock}{,key:in-stock/%u}\n", 65);
+ xo_emit("{L,white,colon:In stock}{,key:in\-stock/%u}\\n", 65);
.Ed
.Ss "Field Roles"
Field roles are optional, and indicate the role and formatting of the
@@ -96,7 +96,7 @@ The roles are listed below; only one role is permitted:
.Bl -column "M" "Name12341234"
.It Sy "M" "Name " "Description"
.It C "color " "Field is a color or effect"
-.It D "decoration " "Field is non-text (e.g. colon, comma)"
+.It D "decoration " "Field is non\-text (e.g. colon, comma)"
.It E "error " "Field is an error message"
.It L "label " "Field is text that prefixes a value"
.It N "note " "Field is text that follows a value"
@@ -105,12 +105,12 @@ The roles are listed below; only one role is permitted:
.It U "units " "Field is the units for the previous value field"
.It V "value " "Field is the name of field (the default)"
.It W "warning " "Field is a warning message"
-.It \&[ "start-anchor" "Begin a section of anchored variable-width text"
-.It \&] "stop-anchor " "End a section of anchored variable-width text"
+.It \&[ "start\-anchor" "Begin a section of anchored variable\-width text"
+.It \&] "stop\-anchor " "End a section of anchored variable\-width text"
.El
.Bd -literal -offset indent
EXAMPLE:
- xo_emit("{L:Free}{D::}{P: }{:free/%u} {U:Blocks}\n",
+ xo_emit("{L:Free}{D::}{P: }{:free/%u} {U:Blocks}\\n",
free_blocks);
.Ed
.Pp
@@ -121,50 +121,50 @@ a comma:
.Bd -literal -offset indent
EXAMPLE:
xo_emit("{,label:Free}{,decoration::}{,padding: }"
- "{,value:free/%u} {,units:Blocks}\n",
+ "{,value:free/%u} {,units:Blocks}\\n",
free_blocks);
.Ed
.Ss "The Color Role ({C:})"
Colors and effects control how text values are displayed; they are
used for display styles (TEXT and HTML).
.Bd -literal -offset indent
- xo_emit("{C:bold}{:value}{C:no-bold}\n", value);
+ xo_emit("{C:bold}{:value}{C:no\-bold}\\n", value);
.Ed
.Pp
-Colors and effects remain in effect until modified by other "C"-role
+Colors and effects remain in effect until modified by other "C"\-role
fields.
.Bd -literal -offset indent
- xo_emit("{C:bold}{C:inverse}both{C:no-bold}only inverse\n");
+ xo_emit("{C:bold}{C:inverse}both{C:no\-bold}only inverse\\n");
.Ed
.Pp
If the content is empty, the "reset" action is performed.
.Bd -literal -offset indent
- xo_emit("{C:both,underline}{:value}{C:}\n", value);
+ xo_emit("{C:both,underline}{:value}{C:}\\n", value);
.Ed
.Pp
-The content should be a comma-separated list of zero or more colors or
+The content should be a comma\-separated list of zero or more colors or
display effects.
.Bd -literal -offset indent
- xo_emit("{C:bold,underline,inverse}All three{C:no-bold,no-inverse}\n");
+ xo_emit("{C:bold,underline,inverse}All three{C:no\-bold,no\-inverse}\\n");
.Ed
.Pp
The color content can be either static, when placed directly within
-the field descriptor, or a printf-style format descriptor can be used,
+the field descriptor, or a printf\-style format descriptor can be used,
if preceded by a slash ("/"):
.Bd -literal -offset indent
xo_emit("{C:/%s%s}{:value}{C:}", need_bold ? "bold" : "",
need_underline ? "underline" : "", value);
.Ed
.Pp
-Color names are prefixed with either "fg-" or "bg-" to change the
+Color names are prefixed with either "fg\-" or "bg\-" to change the
foreground and background colors, respectively.
.Bd -literal -offset indent
- xo_emit("{C:/fg-%s,bg-%s}{Lwc:Cost}{:cost/%u}{C:reset}\n",
+ xo_emit("{C:/fg\-%s,bg\-%s}{Lwc:Cost}{:cost/%u}{C:reset}\\n",
fg_color, bg_color, cost);
.Ed
.Pp
The following table lists the supported effects:
-.Bl -column "no-underline"
+.Bl -column "no\-underline"
.It Sy "Name " "Description"
.It "bg\-xxxxx " "Change background color"
.It "bold " "Start bold text effect"
@@ -179,7 +179,7 @@ The following table lists the supported effects:
.El
.Pp
The following color names are supported:
-.Bl -column "no-underline"
+.Bl -column "no\-underline"
.It Sy "Name"
.It black
.It blue
@@ -193,7 +193,7 @@ The following color names are supported:
.El
.Ss "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
+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.
@@ -219,22 +219,23 @@ change such as changing "/%06d" to "/%08d" should not force hand
inspection of all .po files.
.Pp
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
Roles and modifiers can also use more verbose names, when preceeded 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:
-
-
- Section 2.2.2.1 -
- Section 2.2.2.2 -
- Section 2.2.2.3 -
- Section 2.2.2.4 -
- Section 2.2.2.5 -
- Section 2.2.2.6 -
- Section 2.2.2.7 -
- Section 2.2.2.8 -
- Section 2.2.2.9 -
- Section 2.2.2.10 -
- Section 2.2.2.11 +
- Section 2.2.2.1 +
- Section 2.2.2.2 +
- Section 2.2.2.3 +
- Section 2.2.2.4 +
- Section 2.2.2.5 +
- Section 2.2.2.6 +
- Section 2.2.2.7 +
- Section 2.2.2.8 +
- Section 2.2.2.9 +
- Section 2.2.2.10 +
- Section 2.2.2.11 +
- Section 2.2.2.12 +
- Section 2.2.2.13
-The Colon Modifier ({c:}) +The Argument Modifier ({a:})
-The colon modifier appends a single colon to the data value:
+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("{Lc:Name}{:name}\n", "phil"); + xo_emit("{La:} {a:}\n", "Label text", "label", "value"); 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.
+ 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.
-+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 display modifier is the opposite of the encoding modifier, and they are often used to give to distinct views of the underlying data.
The display modifier indicated the field should only be generated for the display output styles, TEXT and HTML.
-+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 2.2.1.3, Section 2.2.2.9, and Section 9.5 for additional details.
+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 2.2.1.3, Section 2.2.2.10, and Section 9.5 for additional details.
++The Key Modifier ({k:}) -+ 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 3.4.6) 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.
-+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 3.4.6) 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}, " @@ -23523,19 +23555,19 @@ jQuery(function ($) { 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:
-+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 is used to indicate that a particular field helps uniquely identify an instance of list data.
-+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++) { @@ -23545,16 +23577,16 @@ jQuery(function ($) { 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.
+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.
-+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); @@ -23564,16 +23596,16 @@ jQuery(function ($) { <user>pallavi</user> JSON: "user": [ "phil", "pallavi" ] -The name of the field must match the name of the leaf list.
+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.
-+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); @@ -23581,45 +23613,61 @@ jQuery(function ($) { "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 2.2.2.4.
-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.
-+ xo_emit("{:bytes} {Ngp:byte,bytes}\n", bytes); +-The Quotes Modifier ({q:}) +The Plural Modifier ({p:})
-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.
+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:
- EXAMPLE: - xo_emit("{q:time/%d}", 2014); - JSON: - "year": "2014" -The plural modifier is meant to work with the gettext modifier ({g:}) but can work independently. See Section 2.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:
-+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.
+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.
@@ -23632,7 +23680,7 @@ jQuery(function ($) {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-characterThe format- modifier can be:
@@ -23829,8 +23877,42 @@ jQuery(function ($) { 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".
-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.
-+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("Alll 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]; @@ -23849,10 +23931,10 @@ jQuery(function ($) { 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.
-+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);@@ -23862,7 +23944,7 @@ jQuery(function ($) { Characters Outside of Field DefinitionsCharacters 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: @@ -23883,7 +23965,7 @@ jQuery(function ($) { "%m" Is Supportedlibxo 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)); @@ -23930,7 +24012,7 @@ jQuery(function ($) {- 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 @@ -23987,14 +24069,71 @@ jQuery(function ($) {+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):
+++
+ + +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:
-++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:
-+This call will generate the following output:
+TEXT: In stock: 144 XML: @@ -24009,8 +24148,8 @@ jQuery(function ($) { <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:
-+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" @@ -24021,17 +24160,148 @@ jQuery(function ($) {+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:
++++ +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> ++++ +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"); + } +++
-+2.4Command-line Argumentslibxo uses command line options to trigger rendering behavior. The following options are recognised:
-+
libxo uses command line options to trigger rendering behavior. The following options are recognised:
+
-
- --libxo <options>
- --libxo=<options>
- --libxo:<brief‑options>
Options is a comma-separated list of tokens that correspond to output styles, flags, or features:
-+
Programs using libxo are expecting to call the xo_parse_args function to parse these arguments. See Section 3.4.1 for details.
+Options is a comma-separated list of tokens that correspond to output styles, flags, or features:
+-
Token Action @@ -24082,6 +24352,10 @@ jQuery(function ($) {Do not initialize the locale setting + +no-retain +Prevent retaining formatting information +@@ -24094,6 +24368,10 @@ jQuery(function ($) { no-top Do not emit a top set of braces (JSON) Emit pretty-printed output + +retain +Force retaining formatting information +@@ -24123,165 +24401,7 @@ jQuery(function ($) { text Emit TEXT output The brief options are detailed in Section 3.4.6.
- ----
--2.4-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:
- ---- -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> ---- -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"); - } ----
--2.5-Handles -libxo uses "handles" to control its rendering functionality. The handle contains state and buffered data, as well as callback functions to process data.
-A default handle is used when a NULL is passed to functions accepting a handle. This handle is initialized to write its data to stdout using the default style of text (XO_STYLE_TEXT).
-For the convenience of callers, the libxo library includes handle-less functions that implicitly use the default handle. Any function that takes a handle will use the default handle is a value of NULL is passed in place of a valid 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().
--@@ -24294,7 +24414,7 @@ jQuery(function ($) {-
--2.6-UTF-8 -All strings for libxo must be UTF-8. libxo will handle turning them into locale-based strings for display to the user.
-The only exception is argument formatted using the "%ls" format, which require a wide character string (wchar_t *) as input. 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("Alll strings are utf-8 content {:tag/%ls}", - L"except for wide strings"); -"%S" is equivalent to "%ls".
+The brief options are detailed in Section 3.4.6.
This section gives details about the functions in libxo, how to call them, and the actions they perform.
Section Contents:
-
- Section 3.1
+- Section 3.1
- Section 3.2
- Section 3.3
- Section 3.4
@@ -24305,13 +24425,19 @@ jQuery(function ($) {-Handles +Handles
-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 to standard output. The xo_set_style and xo_set_flags functions can be used to change this behavior.
-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.
+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.
-Section Contents:
+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:
- Section 3.1.1
- Section 3.1.2
@@ -24327,7 +24453,7 @@ jQuery(function ($) { xo_createA handle can be allocated using the xo_create() function:
-+xo_handle_t *xo_create (unsigned style, unsigned flags); Example: @@ -24343,7 +24469,7 @@ jQuery(function ($) { xo_create_to_fileBy 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.
@@ -24355,7 +24481,7 @@ jQuery(function ($) { xo_set_writerThe 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); @@ -24368,10 +24494,10 @@ jQuery(function ($) { xo_set_styleTo 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);Section Contents:
@@ -24385,7 +24511,7 @@ jQuery(function ($) { Output Styles (XO_STYLE_*)
The libxo functions accept a set of output styles:
-+
Flag Description @@ -24417,10 +24543,10 @@ jQuery(function ($) { xo_set_style_nameThe 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");@@ -24432,10 +24558,10 @@ jQuery(function ($) { xo_set_flagsTo 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:
@@ -24450,7 +24576,7 @@ jQuery(function ($) { Flags (XOF_*)
The set of valid flags include:
-+
Flag Description @@ -24528,7 +24654,7 @@ jQuery(function ($) {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 @@ -24547,7 +24673,7 @@ jQuery(function ($) {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 3.4.4 for details.
If the style is XO_STYLE_XML, the following additional flags can be used:
-+
Flag Description @@ -24558,7 +24684,7 @@ jQuery(function ($) {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: @@ -24571,7 +24697,7 @@ jQuery(function ($) { xo_clear_flagsThe 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);@@ -24581,9 +24707,9 @@ jQuery(function ($) { xo_set_optionsThe 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 2.3.
+The options are identical to those listed in Section 2.4.
@@ -24593,7 +24719,7 @@ jQuery(function ($) { xo_destroy@@ -24604,33 +24730,57 @@ jQuery(function ($) { Emitting Content (xo_emit)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);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 2.2. The use of a handle is optional and NULL can be passed to access the internal 'default' handle. See Section 2.5.
+The "fmt" argument is a string containing field descriptors as specified in Section 2.2. The use of a handle is optional and NULL can be passed to access the internal 'default' handle. See Section 3.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:
-
- Section 3.2.1
-- Section 3.2.2
-- Section 3.2.3
+- Section 3.2.1
+- Section 3.2.2
+- Section 3.2.3
+- Section 3.2.4
++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); ++-+ Attributes (xo_attr)
-The xo_attr() function emits attributes for the XML output style.
-+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().
-+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); @@ -24638,34 +24788,34 @@ jQuery(function ($) { 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.
--- -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);".
+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.
-+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).
+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).
@@ -24676,7 +24826,7 @@ jQuery(function ($) {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); @@ -24690,7 +24840,7 @@ jQuery(function ($) {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); @@ -24707,7 +24857,7 @@ jQuery(function ($) {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++) { @@ -24776,11 +24926,11 @@ jQuery(function ($) { 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 2.3 for a description of valid arguments.
+Following the call to xo_parse_args, the application can process the remaining arguments in a normal manner. See Section 2.4 for a description of valid arguments.
@@ -24800,7 +24950,7 @@ jQuery(function ($) { xo_set_version@@ -24789,7 +24939,7 @@ jQuery(function ($) { 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.
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);@@ -24813,7 +24963,7 @@ jQuery(function ($) {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 */ @@ -24823,7 +24973,7 @@ jQuery(function ($) { 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" }, @@ -24836,7 +24986,7 @@ jQuery(function ($) { 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>@@ -24847,7 +24997,7 @@ jQuery(function ($) { Memory AllocationThe 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.
@@ -24860,7 +25010,7 @@ jQuery(function ($) { LIBXO_OPTIONSThe environment variable "LIBXO_OPTIONS" can be set to a string of options:
-+
Option Action @@ -24929,10 +25079,10 @@ jQuery(function ($) {For example, warnings can be enabled by:
-+% env LIBXO_OPTIONS=W my-appComplete HTML output can be generated with:
-+% env LIBXO_OPTIONS=HXI my-appSince 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.
@@ -24943,7 +25093,7 @@ jQuery(function ($) { Errors, Warnings, and MessagesMany 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, ...); @@ -24959,7 +25109,7 @@ jQuery(function ($) { 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); @@ -24971,7 +25121,7 @@ jQuery(function ($) { xo_errorThe 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:: @@ -24986,7 +25136,7 @@ jQuery(function ($) { xo_no_setlocalelibxo 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);@@ -25002,7 +25152,7 @@ jQuery(function ($) {https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
Use the Section 3.5.3.5() function to set the Enterprise ID, as needed.
The message name should follow the conventions in Section 8.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); @@ -25030,13 +25180,13 @@ jQuery(function ($) { Priority, Facility, and FlagsThe 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.
-+
Priority Description @@ -25077,7 +25227,7 @@ jQuery(function ($) {The facility value indicates the source of message, in fairly generic terms.
-+
Facility Description @@ -25142,7 +25292,7 @@ jQuery(function ($) {In addition to the values listed above, xo_open_log accepts a set of addition flags requesting specific behaviors.
-+
Flag Description @@ -25175,7 +25325,7 @@ jQuery(function ($) {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); @@ -25204,7 +25354,7 @@ jQuery(function ($) { xo_vsyslogxo_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; @@ -25220,7 +25370,7 @@ jQuery(function ($) { xo_open_logxo_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 3.5.1.
-+void xo_open_log (const char *ident, int logopt, int facility);@@ -25231,7 +25381,7 @@ jQuery(function ($) { xo_close_logxo_close_log functions similar to closelog(3), closing the log file and releasing any associated resources.
-+void xo_close_log (void);@@ -25242,7 +25392,7 @@ jQuery(function ($) { xo_set_logmaskxo_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); @@ -25257,7 +25407,7 @@ jQuery(function ($) {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:
@@ -25299,7 +25449,7 @@ jQuery(function ($) { Loading EncodersEncoders 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 @@ -25311,7 +25461,7 @@ jQuery(function ($) { Encoder InitializationEach 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:
@@ -25329,7 +25479,7 @@ jQuery(function ($) { 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) @@ -25416,7 +25566,7 @@ jQuery(function ($) {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 LIBXO_OPTIONS environment variable can also be used to set the style, as well as other flags.
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: @@ -25436,7 +25586,7 @@ jQuery(function ($) { <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: @@ -25460,7 +25610,7 @@ jQuery(function ($) { } }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 @@ -25489,7 +25639,7 @@ jQuery(function ($) { Command Line OptionsUsage: 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 @@ -25513,7 +25663,7 @@ jQuery(function ($) { 4.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" @@ -25530,7 +25680,7 @@ jQuery(function ($) {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.
-+
Option Meaning @@ -25571,7 +25721,7 @@ jQuery(function ($) {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}"); @@ -25587,7 +25737,7 @@ jQuery(function ($) {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.
-+
Option Meaning @@ -25619,7 +25769,7 @@ jQuery(function ($) {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.
-+
-
Option Meaning @@ -25639,7 +25789,7 @@ jQuery(function ($) {+@@ -26396,7 +26546,7 @@ jQuery(function ($) {EXAMPLE: % xopo -s "There are {:count/%u} {:event/%.6s} events\n" There are {:count} {:event} events\n @@ -25687,9 +25837,9 @@ jQuery(function ($) { 8.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. 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 without needing to care how the output is rendered.
+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.
@@ -25852,10 +26002,10 @@ jQuery(function ($) { 'Unknown long name for role/modifier'@@ -25698,7 +25848,7 @@ jQuery(function ($) { 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; @@ -25777,7 +25927,7 @@ jQuery(function ($) {- 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) { @@ -25789,7 +25939,7 @@ jQuery(function ($) {- 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 3.2.1) or "{e:}" fields (Section 2.2.2.3) to make the data useful.
+- 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 3.2.2) or "{e:}" fields (Section 2.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
@@ -25838,10 +25988,10 @@ jQuery(function ($) { '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.
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.
@@ -25867,10 +26017,10 @@ jQuery(function ($) {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.
@@ -25881,10 +26031,10 @@ jQuery(function ($) { '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
@@ -25895,10 +26045,10 @@ jQuery(function ($) { '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}");@@ -25908,10 +26058,10 @@ jQuery(function ($) { 'Potential missing slash after C, D, N, L, or T with format'@@ -25922,7 +26072,7 @@ jQuery(function ($) { 'An encoding format cannot be given (roles: DNLT)'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 "/".
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.
@@ -25933,7 +26083,7 @@ jQuery(function ($) { '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.
@@ -25944,10 +26094,10 @@ jQuery(function ($) { '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‑".
@@ -25958,10 +26108,10 @@ jQuery(function ($) { '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.
@@ -25972,10 +26122,10 @@ jQuery(function ($) { '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").
@@ -25986,10 +26136,10 @@ jQuery(function ($) { '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.
@@ -26000,10 +26150,10 @@ jQuery(function ($) { '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.
@@ -26014,10 +26164,10 @@ jQuery(function ($) { '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.
@@ -26028,10 +26178,10 @@ jQuery(function ($) { '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.
@@ -26042,10 +26192,10 @@ jQuery(function ($) { '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.
@@ -26056,10 +26206,10 @@ jQuery(function ($) { '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}").
@@ -26070,10 +26220,10 @@ jQuery(function ($) { '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.
@@ -26084,10 +26234,10 @@ jQuery(function ($) { '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.
@@ -26098,10 +26248,10 @@ jQuery(function ($) { '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.
@@ -26112,10 +26262,10 @@ jQuery(function ($) { '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.
@@ -26126,10 +26276,10 @@ jQuery(function ($) { '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.
@@ -26140,10 +26290,10 @@ jQuery(function ($) { '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.
@@ -26183,7 +26333,7 @@ jQuery(function ($) {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 @@ -26192,7 +26342,7 @@ jQuery(function ($) { sudo make installlibxo 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 @@ -26212,7 +26362,7 @@ jQuery(function ($) { 9.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.
@@ -26236,10 +26386,10 @@ jQuery(function ($) { 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 3.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); @@ -26247,8 +26397,8 @@ jQuery(function ($) { return argc; .... } -At the bottom of your main(), you'll need to call xo_finish() to complete output processing for the default handle (Section 2.5). libxo provides the xo_finish_atexit function that is suitable for use with the atexit(3) function.
-+At the bottom of your main(), you'll need to call xo_finish() to complete output processing for the default handle (Section 3.1). libxo provides the xo_finish_atexit function that is suitable for use with the atexit(3) function.
+atexit(xo_finish_atexit);@@ -26258,20 +26408,20 @@ jQuery(function ($) { Converting printf CallsHowto: Internationalization (i18n) -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 2.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 2.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 2.2.1.10).
-+snprintf(buf, sizeof(buf), "(%u/%u/%u)", min, ave, max); printf("%30s", buf); @@ -26285,7 +26435,7 @@ jQuery(function ($) { Creating HierarchyText 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); @@ -26303,7 +26453,7 @@ jQuery(function ($) {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); @@ -26322,7 +26472,7 @@ jQuery(function ($) { Converting Error Functionslibxo 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); @@ -26340,12 +26490,12 @@ jQuery(function ($) { 9.5+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 @@ -26378,7 +26528,7 @@ jQuery(function ($) { 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:
- 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")); @@ -26404,17 +26554,17 @@ jQuery(function ($) { 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))); @@ -26439,7 +26589,7 @@ jQuery(function ($) { Unit TestHere is the unit test example:
-+int main (int argc, char **argv) { @@ -26532,7 +26682,7 @@ jQuery(function ($) { return 0; }Text output:
-+% ./testxo --libxo text Item 'gum': Total sold: 1412.0 @@ -26565,7 +26715,7 @@ jQuery(function ($) { On order: 1 SKU: GRO-000-533JSON output:
-+% ./testxo --libxo json,pretty "top": { "data": { @@ -26620,7 +26770,7 @@ jQuery(function ($) { } }XML output:
-+% ./testxo --libxo pretty,xml <top> <data> @@ -26671,7 +26821,7 @@ jQuery(function ($) { </data> </top>HMTL output:
-+% ./testxo --libxo pretty,html <div class="line"> <div class="label">Item</div> @@ -26866,7 +27016,7 @@ jQuery(function ($) { <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> diff --git a/contrib/libxo/doc/libxo.txt b/contrib/libxo/doc/libxo.txt index 1e7acc7984be..ba63702920c5 100644 --- a/contrib/libxo/doc/libxo.txt +++ b/contrib/libxo/doc/libxo.txt @@ -699,25 +699,26 @@ XOF_WARN is set, a warning will be generated. Field modifiers are flags which modify the way content emitted for particular output styles: -|---+---------------+-------------------------------------------------| -| M | Name | Description | -|---+---------------+-------------------------------------------------| -| 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 | -|---+---------------+-------------------------------------------------| +|---+---------------+--------------------------------------------------| +| 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 preceeded by a comma. For example, the modifier string "Lwc" (or "L,white,colon") @@ -727,6 +728,27 @@ 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: @@ -907,6 +929,21 @@ needed, but often this needs to be controlled by the caller. 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: @@ -1029,6 +1066,24 @@ 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("Alll 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. @@ -1163,6 +1218,53 @@ variants might be wise. | 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: @@ -1196,46 +1298,6 @@ penultimate line to: data-type="number" data-help="Number of items in stock">144 -** Command-line Arguments - -libxo uses command line options to trigger rendering behavior. The -following options are recognised: - -- --libxo-- --libxo= -- --libxo: - -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) | -| dtrt | Enable "Do The Right Thing" mode | -| 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-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 | -| text | Emit TEXT output | -| underscores | Replace XML-friendly "-"s with JSON friendly "_"s e | -| 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) | -|-------------+-------------------------------------------------------| - -The brief options are detailed in ^LIBXO_OPTIONS^. - ** Representing Hierarchy For XML and JSON, individual fields appear inside hierarchies which @@ -1382,20 +1444,81 @@ properly. xo_close_marker("fish-guts"); } +** Command-line Arguments + +libxo uses command line options to trigger rendering behavior. The +following options are recognised: + +- --libxo +- --libxo= +- --libxo: + +Programs using libxo are expecting to call the xo_parse_args function +to parse these arguments. See ^xo_parse_args^ for details. + +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) | +| dtrt | Enable "Do The Right Thing" mode | +| 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 e | +| 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) | +|-------------+-------------------------------------------------------| + +The brief options are detailed in ^LIBXO_OPTIONS^. + +* 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. -A default handle is used when a NULL is passed to functions accepting -a handle. This handle is initialized to write its data to stdout -using the default style of text (XO_STYLE_TEXT). +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. -For the convenience of callers, the libxo library includes handle-less -functions that implicitly use the default handle. Any function that -takes a handle will use the default handle is a value of NULL is -passed in place of a valid handle. +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: @@ -1404,46 +1527,6 @@ For example, the following are equivalent: Handles are created using xo_create() and destroy using xo_destroy(). -** UTF-8 - -All strings for libxo must be UTF-8. libxo will handle turning them -into locale-based strings for display to the user. - -The only exception is argument formatted using the "%ls" format, which -require a wide character string (wchar_t *) as input. 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("Alll strings are utf-8 content {:tag/%ls}", - L"except for wide strings"); - -"%S" is equivalent to "%ls". - -* The libxo API - -This section gives details about the functions in libxo, how to call -them, and the actions they perform. - -** Handles - -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 to standard output. -The xo_set_style and xo_set_flags functions can be used to change this -behavior. - -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 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. - *** xo_create A handle can be allocated using the xo_create() function: @@ -1653,11 +1736,34 @@ 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, ...); @@ -2555,23 +2661,23 @@ 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 +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. 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. +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 without needing to care how the output is rendered. +output calls with a single code path. *** Did the complex semantics of format strings evolve over time? diff --git a/contrib/libxo/encoder/cbor/enc_cbor.c b/contrib/libxo/encoder/cbor/enc_cbor.c index 513063fb1508..7c0a1d33f932 100644 --- a/contrib/libxo/encoder/cbor/enc_cbor.c +++ b/contrib/libxo/encoder/cbor/enc_cbor.c @@ -135,7 +135,7 @@ cbor_encode_uint (xo_buffer_t *xbp, uint64_t minor, unsigned limit) char *bp = xbp->xb_curp; int i, m; - if (minor > (1UL<<32)) { + if (minor > (1ULL << 32)) { *bp++ |= CBOR_LEN64; m = 64; diff --git a/contrib/libxo/libxo-config.in b/contrib/libxo/libxo-config.in index 3dbb7d41a364..f08f2340ecdb 100644 --- a/contrib/libxo/libxo-config.in +++ b/contrib/libxo/libxo-config.in @@ -77,34 +77,34 @@ while test $# -gt 0; do ;; --cflags) - echo -I@LIBXO_INCLUDEDIR@ @LIBXO_CFLAGS@ + echo -I@XO_INCLUDEDIR@ @XO_CFLAGS@ ;; --share) - echo @LIBXO_SHAREDIR@ + echo @XO_SHAREDIR@ ;; --bindir) - echo @LIBXO_BINDIR@ + echo @XO_BINDIR@ ;; --libdir) - echo @LIBXO_LIBDIR@ + echo @XO_LIBDIR@ ;; --libs) if [ "`uname`" = "Linux" ] then - if [ "@LIBXO_LIBDIR@" = "-L/usr/lib" -o "@LIBXO_LIBDIR@" = "-L/usr/lib64" ] + if [ "@XO_LIBDIR@" = "-L/usr/lib" -o "@XO_LIBDIR@" = "-L/usr/lib64" ] then - echo @LIBXO_LIBS@ + echo @XO_LIBS@ else - echo -L@LIBXO_LIBDIR@ @LIBXO_LIBS@ + echo -L@XO_LIBDIR@ @XO_LIBS@ fi else - echo -L@LIBXO_LIBDIR@ @LIBXO_LIBS@ @WIN32_EXTRA_LIBADD@ + echo -L@XO_LIBDIR@ @XO_LIBS@ fi ;; diff --git a/contrib/libxo/libxo/libxo.c b/contrib/libxo/libxo/libxo.c index bae810f179c7..194a0962b428 100644 --- a/contrib/libxo/libxo/libxo.c +++ b/contrib/libxo/libxo/libxo.c @@ -19,7 +19,8 @@ * http://juniper.github.io/libxo/libxo-manual.html * * For first time readers, the core bits of code to start looking at are: - * - xo_do_emit() -- the central function of the library + * - xo_do_emit() -- parse and emit a set of fields + * - xo_do_emit_fields -- the central function of the library * - xo_do_format_field() -- handles formatting a single field * - xo_transiton() -- the state machine that keeps things sane * and of course the "xo_handle_t" data structure, which carries all @@ -120,6 +121,7 @@ const char xo_version[] = LIBXO_VERSION; const char xo_version_extra[] = LIBXO_VERSION_EXTRA; +static const char xo_default_format[] = "%s"; #ifndef UNUSED #define UNUSED __attribute__ ((__unused__)) @@ -338,6 +340,7 @@ typedef unsigned long xo_xff_flags_t; #define XFF_GT_FIELD (1<<19) /* Call gettext() on a field */ #define XFF_GT_PLURAL (1<<20) /* Call dngettext to find plural form */ +#define XFF_ARGUMENT (1<<21) /* Content provided via argument */ /* Flags to turn off when we don't want i18n processing */ #define XFF_GT_FLAGS (XFF_GT_FIELD | XFF_GT_PLURAL) @@ -1046,7 +1049,7 @@ xo_is_utf8 (char ch) return (ch & 0x80); } -static int +static inline int xo_utf8_to_wc_len (const char *buf) { unsigned b = (unsigned char) *buf; @@ -1105,9 +1108,13 @@ xo_buf_utf8_len (xo_handle_t *xop, const char *buf, int bufsiz) * bits we pull off the first character is dependent on the length, * but we put 6 bits off all other bytes. */ -static wchar_t +static inline wchar_t xo_utf8_char (const char *buf, int len) { + /* Most common case: singleton byte */ + if (len == 1) + return (unsigned char) buf[0]; + int i; wchar_t wc; const unsigned char *cp = (const unsigned char *) buf; @@ -1281,6 +1288,195 @@ xo_data_escape (xo_handle_t *xop, const char *str, int len) xo_buf_escape(xop, &xop->xo_data, str, len, 0); } +#ifdef LIBXO_NO_RETAIN +/* + * Empty implementations of the retain logic + */ + +void +xo_retain_clear_all (void) +{ + return; +} + +void +xo_retain_clear (const char *fmt UNUSED) +{ + return; +} +static void +xo_retain_add (const char *fmt UNUSED, xo_field_info_t *fields UNUSED, + unsigned num_fields UNUSED) +{ + return; +} + +static int +xo_retain_find (const char *fmt UNUSED, xo_field_info_t **valp UNUSED, + unsigned *nump UNUSED) +{ + return -1; +} + +#else /* !LIBXO_NO_RETAIN */ +/* + * Retain: We retain parsed field definitions to enhance performance, + * especially inside loops. We depend on the caller treating the format + * strings as immutable, so that we can retain pointers into them. We + * hold the pointers in a hash table, so allow quick access. Retained + * information is retained until xo_retain_clear is called. + */ + +/* + * xo_retain_entry_t holds information about one retained set of + * parsed fields. + */ +typedef struct xo_retain_entry_s { + struct xo_retain_entry_s *xre_next; /* Pointer to next (older) entry */ + unsigned long xre_hits; /* Number of times we've hit */ + const char *xre_format; /* Pointer to format string */ + unsigned xre_num_fields; /* Number of fields saved */ + xo_field_info_t *xre_fields; /* Pointer to fields */ +} xo_retain_entry_t; + +/* + * xo_retain_t holds a complete set of parsed fields as a hash table. + */ +#ifndef XO_RETAIN_SIZE +#define XO_RETAIN_SIZE 6 +#endif /* XO_RETAIN_SIZE */ +#define RETAIN_HASH_SIZE (1< > 4) & (((1 << 24) - 1))); + + val = (val ^ 61) ^ (val >> 16); + val = val + (val << 3); + val = val ^ (val >> 4); + val = val * 0x3a8f05c5; /* My large prime number */ + val = val ^ (val >> 15); + val &= RETAIN_HASH_SIZE - 1; + + return val; +} + +/* + * Walk all buckets, clearing all retained entries + */ +void +xo_retain_clear_all (void) +{ + int i; + xo_retain_entry_t *xrep, *next; + + for (i = 0; i < RETAIN_HASH_SIZE; i++) { + for (xrep = xo_retain.xr_bucket[i]; xrep; xrep = next) { + next = xrep->xre_next; + xo_free(xrep); + } + xo_retain.xr_bucket[i] = NULL; + } + xo_retain_count = 0; +} + +/* + * Walk all buckets, clearing all retained entries + */ +void +xo_retain_clear (const char *fmt) +{ + xo_retain_entry_t **xrepp; + unsigned hash = xo_retain_hash(fmt); + + for (xrepp = &xo_retain.xr_bucket[hash]; *xrepp; + xrepp = &(*xrepp)->xre_next) { + if ((*xrepp)->xre_format == fmt) { + *xrepp = (*xrepp)->xre_next; + xo_retain_count -= 1; + return; + } + } +} + +/* + * Search the hash for an entry matching 'fmt'; return it's fields. + */ +static int +xo_retain_find (const char *fmt, xo_field_info_t **valp, unsigned *nump) +{ + if (xo_retain_count == 0) + return -1; + + unsigned hash = xo_retain_hash(fmt); + xo_retain_entry_t *xrep; + + for (xrep = xo_retain.xr_bucket[hash]; xrep != NULL; + xrep = xrep->xre_next) { + if (xrep->xre_format == fmt) { + *valp = xrep->xre_fields; + *nump = xrep->xre_num_fields; + xrep->xre_hits += 1; + return 0; + } + } + + return -1; +} + +static void +xo_retain_add (const char *fmt, xo_field_info_t *fields, unsigned num_fields) +{ + unsigned hash = xo_retain_hash(fmt); + xo_retain_entry_t *xrep; + unsigned sz = sizeof(*xrep) + (num_fields + 1) * sizeof(*fields); + xo_field_info_t *xfip; + + xrep = xo_realloc(NULL, sz); + if (xrep == NULL) + return; + + xfip = (xo_field_info_t *) &xrep[1]; + memcpy(xfip, fields, num_fields * sizeof(*fields)); + + bzero(xrep, sizeof(*xrep)); + + xrep->xre_format = fmt; + xrep->xre_fields = xfip; + xrep->xre_num_fields = num_fields; + + /* Record the field info in the retain bucket */ + xrep->xre_next = xo_retain.xr_bucket[hash]; + xo_retain.xr_bucket[hash] = xrep; + xo_retain_count += 1; +} + +#endif /* !LIBXO_NO_RETAIN */ + /* * Generate a warning. Normally, this is a text message written to * standard error. If the XOF_WARN_XML flag is set, then we generate @@ -1574,6 +1770,19 @@ xo_message_hcv (xo_handle_t *xop, int code, const char *fmt, va_list vap) break; } + switch (xo_style(xop)) { + case XO_STYLE_HTML: + if (XOIF_ISSET(xop, XOIF_DIV_OPEN)) { + static char div_close[] = ""; + XOIF_CLEAR(xop, XOIF_DIV_OPEN); + xo_data_append(xop, div_close, sizeof(div_close) - 1); + + if (XOF_ISSET(xop, XOF_PRETTY)) + xo_data_append(xop, "\n", 1); + } + break; + } + (void) xo_flush_h(xop); } @@ -1679,6 +1888,39 @@ xo_create_to_file (FILE *fp, xo_style_t style, xo_xof_flags_t flags) return xop; } +/** + * Set the default handler to output to a file. + * @xop libxo handle + * @fp FILE pointer to use + */ +int +xo_set_file_h (xo_handle_t *xop, FILE *fp) +{ + xop = xo_default(xop); + + if (fp == NULL) { + xo_failure(xop, "xo_set_file: NULL fp"); + return -1; + } + + xop->xo_opaque = fp; + xop->xo_write = xo_write_to_file; + xop->xo_close = xo_close_file; + xop->xo_flush = xo_flush_file; + + return 0; +} + +/** + * Set the default handler to output to a file. + * @fp FILE pointer to use + */ +int +xo_set_file (FILE *fp) +{ + return xo_set_file_h(NULL, fp); +} + /** * Release any resources held by the handle. * @xop XO handle to alter (or NULL for default handle) @@ -1824,9 +2066,11 @@ static xo_mapping_t xo_xof_names[] = { { XOF_LOG_SYSLOG, "log-syslog" }, { XOF_NO_HUMANIZE, "no-humanize" }, { XOF_NO_LOCALE, "no-locale" }, + { XOF_RETAIN_NONE, "no-retain" }, { XOF_NO_TOP, "no-top" }, { XOF_NOT_FIRST, "not-first" }, { XOF_PRETTY, "pretty" }, + { XOF_RETAIN_ALL, "retain" }, { XOF_UNDERSCORES, "underscores" }, { XOF_UNITS, "units" }, { XOF_WARN, "warn" }, @@ -3613,10 +3857,9 @@ xo_format_text (xo_handle_t *xop, const char *str, int len) } static void -xo_format_title (xo_handle_t *xop, xo_field_info_t *xfip) +xo_format_title (xo_handle_t *xop, xo_field_info_t *xfip, + const char *str, unsigned len) { - const char *str = xfip->xfi_content; - unsigned len = xfip->xfi_clen; const char *fmt = xfip->xfi_format; unsigned flen = xfip->xfi_flen; xo_xff_flags_t flags = xfip->xfi_flags; @@ -4083,10 +4326,9 @@ xo_format_value (xo_handle_t *xop, const char *name, int nlen, } static void -xo_set_gettext_domain (xo_handle_t *xop, xo_field_info_t *xfip) +xo_set_gettext_domain (xo_handle_t *xop, xo_field_info_t *xfip, + const char *str, unsigned len) { - const char *str = xfip->xfi_content; - unsigned len = xfip->xfi_clen; const char *fmt = xfip->xfi_format; unsigned flen = xfip->xfi_flen; @@ -4335,13 +4577,13 @@ xo_colors_enabled (xo_handle_t *xop UNUSED) } static void -xo_colors_handle_text (xo_handle_t *xop UNUSED, xo_colors_t *newp) +xo_colors_handle_text (xo_handle_t *xop, xo_colors_t *newp) { char buf[BUFSIZ]; char *cp = buf, *ep = buf + sizeof(buf); unsigned i, bit; xo_colors_t *oldp = &xop->xo_colors; - const char *code; + const char *code = NULL; /* * Start the buffer with an escape. We don't want to add the '[' @@ -4460,10 +4702,9 @@ xo_colors_handle_html (xo_handle_t *xop, xo_colors_t *newp) } static void -xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip) +xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip, + const char *str, unsigned len) { - const char *str = xfip->xfi_content; - unsigned len = xfip->xfi_clen; const char *fmt = xfip->xfi_format; unsigned flen = xfip->xfi_flen; @@ -4534,10 +4775,9 @@ xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip) } static void -xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip) +xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip, + const char *str, unsigned len) { - const char *str = xfip->xfi_content; - unsigned len = xfip->xfi_clen; const char *fmt = xfip->xfi_format; unsigned flen = xfip->xfi_flen; xo_xff_flags_t flags = xfip->xfi_flags; @@ -4589,10 +4829,9 @@ xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip) } static int -xo_find_width (xo_handle_t *xop, xo_field_info_t *xfip) +xo_find_width (xo_handle_t *xop, xo_field_info_t *xfip, + const char *str, unsigned len) { - const char *str = xfip->xfi_content; - unsigned len = xfip->xfi_clen; const char *fmt = xfip->xfi_format; unsigned flen = xfip->xfi_flen; @@ -4639,7 +4878,8 @@ xo_anchor_clear (xo_handle_t *xop) * format it when the end anchor tag is seen. */ static void -xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip) +xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip, + const char *str, unsigned len) { if (xo_style(xop) != XO_STYLE_TEXT && xo_style(xop) != XO_STYLE_HTML) return; @@ -4656,11 +4896,12 @@ xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip) * Now we find the width, if possible. If it's not there, * we'll get it on the end anchor. */ - xop->xo_anchor_min_width = xo_find_width(xop, xfip); + xop->xo_anchor_min_width = xo_find_width(xop, xfip, str, len); } static void -xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip) +xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip, + const char *str, unsigned len) { if (xo_style(xop) != XO_STYLE_TEXT && xo_style(xop) != XO_STYLE_HTML) return; @@ -4672,7 +4913,7 @@ xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip) XOIF_CLEAR(xop, XOIF_UNITS_PENDING); - int width = xo_find_width(xop, xfip); + int width = xo_find_width(xop, xfip, str, len); if (width == 0) width = xop->xo_anchor_min_width; @@ -4787,6 +5028,7 @@ static xo_mapping_t xo_role_names[] = { #define XO_ROLE_NEWLINE '\n' static xo_mapping_t xo_modifier_names[] = { + { XFF_ARGUMENT, "argument" }, { XFF_COLON, "colon" }, { XFF_COMMA, "comma" }, { XFF_DISPLAY_ONLY, "display" }, @@ -4858,6 +5100,7 @@ xo_count_fields (xo_handle_t *xop UNUSED, const char *fmt) * '[': start a section of anchored text * ']': end a section of anchored text * The following modifiers are also supported: + * 'a': content is provided via argument (const char *), not descriptor * 'c': flag: emit a colon after the label * 'd': field is only emitted for display styles (text and html) * 'e': field is only emitted for encoding styles (xml and json) @@ -4884,7 +5127,7 @@ xo_parse_roles (xo_handle_t *xop, const char *fmt, xo_xff_flags_t flags = 0; uint8_t fnum = 0; - for (sp = basep; sp; sp++) { + for (sp = basep; sp && *sp; sp++) { if (*sp == ':' || *sp == '/' || *sp == '}') break; @@ -4961,6 +5204,10 @@ xo_parse_roles (xo_handle_t *xop, const char *fmt, fnum = (fnum * 10) + (*sp - '0'); break; + case 'a': + flags |= XFF_ARGUMENT; + break; + case 'c': flags |= XFF_COLON; break; @@ -5133,7 +5380,6 @@ static int xo_parse_fields (xo_handle_t *xop, xo_field_info_t *fields, unsigned num_fields, const char *fmt) { - static const char default_format[] = "%s"; const char *cp, *sp, *ep, *basep; unsigned field = 0; xo_field_info_t *xfip = fields; @@ -5267,12 +5513,12 @@ xo_parse_fields (xo_handle_t *xop, xo_field_info_t *fields, xfip->xfi_next = ++sp; /* If we have content, then we have a default format */ - if (xfip->xfi_clen || format) { + if (xfip->xfi_clen || format || (xfip->xfi_flags & XFF_ARGUMENT)) { if (format) { xfip->xfi_format = format; xfip->xfi_flen = flen; } else if (xo_role_wants_default_format(xfip->xfi_ftype)) { - xfip->xfi_format = default_format; + xfip->xfi_format = xo_default_format; xfip->xfi_flen = 2; } } @@ -5568,9 +5814,8 @@ xo_gettext_combine_formats (xo_handle_t *xop, const char *fmt UNUSED, * Summary: i18n aighn't cheap. */ static const char * -xo_gettext_build_format (xo_handle_t *xop UNUSED, - xo_field_info_t *fields UNUSED, - int this_field UNUSED, +xo_gettext_build_format (xo_handle_t *xop, + xo_field_info_t *fields, int this_field, const char *fmt, char **new_fmtp) { if (xo_style_is_encoding(xop)) @@ -5686,17 +5931,22 @@ xo_gettext_rebuild_content (xo_handle_t *xop UNUSED, #endif /* HAVE_GETTEXT */ /* - * The central function for emitting libxo output. + * Emit a set of fields. This is really the core of libxo. */ static int -xo_do_emit (xo_handle_t *xop, const char *fmt) +xo_do_emit_fields (xo_handle_t *xop, xo_field_info_t *fields, + unsigned max_fields, const char *fmt) { int gettext_inuse = 0; int gettext_changed = 0; int gettext_reordered = 0; + unsigned ftype; + xo_xff_flags_t flags; xo_field_info_t *new_fields = NULL; - + xo_field_info_t *xfip; + unsigned field; int rc = 0; + int flush = XOF_ISSET(xop, XOF_FLUSH); int flush_line = XOF_ISSET(xop, XOF_FLUSH_LINE); char *new_fmt = NULL; @@ -5704,20 +5954,6 @@ xo_do_emit (xo_handle_t *xop, const char *fmt) if (XOIF_ISSET(xop, XOIF_REORDER) || xo_style(xop) == XO_STYLE_ENCODER) flush_line = 0; - xop->xo_columns = 0; /* Always reset it */ - xop->xo_errno = errno; /* Save for "%m" */ - - unsigned max_fields = xo_count_fields(xop, fmt), field; - xo_field_info_t fields[max_fields], *xfip; - - bzero(fields, max_fields * sizeof(fields[0])); - - if (xo_parse_fields(xop, fields, max_fields, fmt)) - return -1; /* Warning already displayed */ - - unsigned ftype; - xo_xff_flags_t flags; - /* * Some overhead for gettext; if the fields in the msgstr returned * by gettext are reordered, then we need to record start and end @@ -5745,6 +5981,18 @@ xo_do_emit (xo_handle_t *xop, const char *fmt) min_fstart = field; } + const char *content = xfip->xfi_content; + int clen = xfip->xfi_clen; + + if (flags & XFF_ARGUMENT) { + /* + * Argument flag means the content isn't given in the descriptor, + * but as a UTF-8 string ('const char *') argument in xo_vap. + */ + content = va_arg(xop->xo_vap, char *); + clen = content ? strlen(content) : 0; + } + if (ftype == XO_ROLE_NEWLINE) { xo_line_close(xop); if (flush_line && xo_flush_h(xop) < 0) @@ -5773,15 +6021,15 @@ xo_do_emit (xo_handle_t *xop, const char *fmt) } if (ftype == 'V') - xo_format_value(xop, xfip->xfi_content, xfip->xfi_clen, + xo_format_value(xop, content, clen, xfip->xfi_format, xfip->xfi_flen, xfip->xfi_encoding, xfip->xfi_elen, flags); else if (ftype == '[') - xo_anchor_start(xop, xfip); + xo_anchor_start(xop, xfip, content, clen); else if (ftype == ']') - xo_anchor_stop(xop, xfip); + xo_anchor_stop(xop, xfip, content, clen); else if (ftype == 'C') - xo_format_colors(xop, xfip); + xo_format_colors(xop, xfip, content, clen); else if (ftype == 'G') { /* @@ -5792,7 +6040,7 @@ xo_do_emit (xo_handle_t *xop, const char *fmt) * Since gettext returns strings in a static buffer, we make * a copy in new_fmt. */ - xo_set_gettext_domain(xop, xfip); + xo_set_gettext_domain(xop, xfip, content, clen); if (!gettext_inuse) { /* Only translate once */ gettext_inuse = 1; @@ -5843,17 +6091,17 @@ xo_do_emit (xo_handle_t *xop, const char *fmt) } continue; - } else if (xfip->xfi_clen || xfip->xfi_format) { + } else if (clen || xfip->xfi_format) { const char *class_name = xo_class_name(ftype); if (class_name) xo_format_content(xop, class_name, xo_tag_name(ftype), - xfip->xfi_content, xfip->xfi_clen, + content, clen, xfip->xfi_format, xfip->xfi_flen, flags); else if (ftype == 'T') - xo_format_title(xop, xfip); + xo_format_title(xop, xfip, content, clen); else if (ftype == 'U') - xo_format_units(xop, xfip); + xo_format_units(xop, xfip, content, clen); else xo_failure(xop, "unknown field type: '%c'", ftype); } @@ -5884,7 +6132,7 @@ xo_do_emit (xo_handle_t *xop, const char *fmt) if (flush && !XOIF_ISSET(xop, XOIF_ANCHOR)) { if (xo_write(xop) < 0) rc = -1; /* Report failure */ - else if (xop->xo_flush && xop->xo_flush(xop->xo_opaque) < 0) + else if (xo_flush_h(xop) < 0) rc = -1; } @@ -5904,6 +6152,53 @@ xo_do_emit (xo_handle_t *xop, const char *fmt) return (rc < 0) ? rc : (int) xop->xo_columns; } +/* + * Parse and emit a set of fields + */ +static int +xo_do_emit (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt) +{ + xop->xo_columns = 0; /* Always reset it */ + xop->xo_errno = errno; /* Save for "%m" */ + + if (fmt == NULL) + return 0; + + unsigned max_fields; + xo_field_info_t *fields = NULL; + + /* Adjust XOEF_RETAIN based on global flags */ + if (XOF_ISSET(xop, XOF_RETAIN_ALL)) + flags |= XOEF_RETAIN; + if (XOF_ISSET(xop, XOF_RETAIN_NONE)) + flags &= ~XOEF_RETAIN; + + /* + * Check for 'retain' flag, telling us to retain the field + * information. If we've already saved it, then we can avoid + * re-parsing the format string. + */ + if (!(flags & XOEF_RETAIN) + || xo_retain_find(fmt, &fields, &max_fields) != 0 + || fields == NULL) { + + /* Nothing retained; parse the format string */ + max_fields = xo_count_fields(xop, fmt); + fields = alloca(max_fields * sizeof(fields[0])); + bzero(fields, max_fields * sizeof(fields[0])); + + if (xo_parse_fields(xop, fields, max_fields, fmt)) + return -1; /* Warning already displayed */ + + if (flags & XOEF_RETAIN) { + /* Retain the info */ + xo_retain_add(fmt, fields, max_fields); + } + } + + return xo_do_emit_fields(xop, fields, max_fields, fmt); +} + /* * Rebuild a format string in a gettext-friendly format. This function * is exposed to tools can perform this function. See xo(1). @@ -5944,7 +6239,7 @@ xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap) xop = xo_default(xop); va_copy(xop->xo_vap, vap); - rc = xo_do_emit(xop, fmt); + rc = xo_do_emit(xop, 0, fmt); va_end(xop->xo_vap); bzero(&xop->xo_vap, sizeof(xop->xo_vap)); @@ -5958,7 +6253,7 @@ xo_emit_h (xo_handle_t *xop, const char *fmt, ...) xop = xo_default(xop); va_start(xop->xo_vap, fmt); - rc = xo_do_emit(xop, fmt); + rc = xo_do_emit(xop, 0, fmt); va_end(xop->xo_vap); bzero(&xop->xo_vap, sizeof(xop->xo_vap)); @@ -5972,13 +6267,137 @@ xo_emit (const char *fmt, ...) int rc; va_start(xop->xo_vap, fmt); - rc = xo_do_emit(xop, fmt); + rc = xo_do_emit(xop, 0, fmt); va_end(xop->xo_vap); bzero(&xop->xo_vap, sizeof(xop->xo_vap)); return rc; } +int +xo_emit_hvf (xo_handle_t *xop, xo_emit_flags_t flags, + const char *fmt, va_list vap) +{ + int rc; + + xop = xo_default(xop); + va_copy(xop->xo_vap, vap); + rc = xo_do_emit(xop, flags, fmt); + va_end(xop->xo_vap); + bzero(&xop->xo_vap, sizeof(xop->xo_vap)); + + return rc; +} + +int +xo_emit_hf (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...) +{ + int rc; + + xop = xo_default(xop); + va_start(xop->xo_vap, fmt); + rc = xo_do_emit(xop, flags, fmt); + va_end(xop->xo_vap); + bzero(&xop->xo_vap, sizeof(xop->xo_vap)); + + return rc; +} + +int +xo_emit_f (xo_emit_flags_t flags, const char *fmt, ...) +{ + xo_handle_t *xop = xo_default(NULL); + int rc; + + va_start(xop->xo_vap, fmt); + rc = xo_do_emit(xop, flags, fmt); + va_end(xop->xo_vap); + bzero(&xop->xo_vap, sizeof(xop->xo_vap)); + + return rc; +} + +/* + * Emit a single field by providing the info information typically provided + * inside the field description (role, modifiers, and formats). This is + * a convenience function to avoid callers using snprintf to build field + * descriptions. + */ +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 rc; + + xop = xo_default(xop); + + if (rolmod == NULL) + rolmod = "V"; + + xo_field_info_t xfi; + + bzero(&xfi, sizeof(xfi)); + + const char *cp; + cp = xo_parse_roles(xop, rolmod, rolmod, &xfi); + if (cp == NULL) + return -1; + + xfi.xfi_start = fmt; + xfi.xfi_content = contents; + xfi.xfi_format = fmt; + xfi.xfi_encoding = efmt; + xfi.xfi_clen = contents ? strlen(contents) : 0; + xfi.xfi_flen = fmt ? strlen(fmt) : 0; + xfi.xfi_elen = efmt ? strlen(efmt) : 0; + + /* If we have content, then we have a default format */ + if (contents && fmt == NULL + && xo_role_wants_default_format(xfi.xfi_ftype)) { + xfi.xfi_format = xo_default_format; + xfi.xfi_flen = 2; + } + + + + va_copy(xop->xo_vap, vap); + + rc = xo_do_emit_fields(xop, &xfi, 1, fmt ?: contents ?: "field"); + + va_end(xop->xo_vap); + + return rc; +} + +int +xo_emit_field_h (xo_handle_t *xop, const char *rolmod, const char *contents, + const char *fmt, const char *efmt, ...) +{ + int rc; + va_list vap; + + va_start(vap, efmt); + rc = xo_emit_field_hv(xop, rolmod, contents, fmt, efmt, vap); + va_end(vap); + + return rc; +} + +int +xo_emit_field (const char *rolmod, const char *contents, + const char *fmt, const char *efmt, ...) +{ + int rc; + va_list vap; + + va_start(vap, efmt); + rc = xo_emit_field_hv(NULL, rolmod, contents, fmt, efmt, vap); + va_end(vap); + + return rc; +} + int xo_attr_hv (xo_handle_t *xop, const char *name, const char *fmt, va_list vap) { @@ -6392,7 +6811,7 @@ xo_open_list_hf (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name) } int -xo_open_list_h (xo_handle_t *xop, const char *name UNUSED) +xo_open_list_h (xo_handle_t *xop, const char *name) { return xo_open_list_hf(xop, 0, name); } @@ -6404,7 +6823,7 @@ xo_open_list (const char *name) } int -xo_open_list_hd (xo_handle_t *xop, const char *name UNUSED) +xo_open_list_hd (xo_handle_t *xop, const char *name) { return xo_open_list_hf(xop, XOF_DTRT, name); } @@ -7113,6 +7532,11 @@ xo_transition (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name, xsp->xs_state, new_state); } + /* Handle the flush flag */ + if (rc >= 0 && XOF_ISSET(xop, XOF_FLUSH)) + if (xo_flush_h(xop)) + rc = -1; + return rc; marker_prevents_close: @@ -7179,22 +7603,11 @@ xo_set_allocator (xo_realloc_func_t realloc_func, xo_free_func_t free_func) int xo_flush_h (xo_handle_t *xop) { - static char div_close[] = ""; int rc; xop = xo_default(xop); switch (xo_style(xop)) { - case XO_STYLE_HTML: - if (XOIF_ISSET(xop, XOIF_DIV_OPEN)) { - XOIF_CLEAR(xop, XOIF_DIV_OPEN); - xo_data_append(xop, div_close, sizeof(div_close) - 1); - - if (XOF_ISSET(xop, XOF_PRETTY)) - xo_data_append(xop, "\n", 1); - } - break; - case XO_STYLE_ENCODER: xo_encoder_handle(xop, XO_OP_FLUSH, NULL, NULL); } @@ -7435,7 +7848,7 @@ xo_set_program (const char *name) } void -xo_set_version_h (xo_handle_t *xop, const char *version UNUSED) +xo_set_version_h (xo_handle_t *xop, const char *version) { xop = xo_default(xop); diff --git a/contrib/libxo/libxo/xo.h b/contrib/libxo/libxo/xo.h index 88bcce2999df..310b21cae366 100644 --- a/contrib/libxo/libxo/xo.h +++ b/contrib/libxo/libxo/xo.h @@ -94,6 +94,11 @@ typedef unsigned long long xo_xof_flags_t; #define XOF_LOG_GETTEXT XOF_BIT(28) /** Log (stderr) gettext lookup strings */ #define XOF_UTF8 XOF_BIT(29) /** Force text output to be UTF8 */ +#define XOF_RETAIN_ALL XOF_BIT(30) /** Force use of XOEF_RETAIN */ +#define XOF_RETAIN_NONE XOF_BIT(31) /** Prevent use of XOEF_RETAIN */ + +typedef unsigned xo_emit_flags_t; /* Flags to xo_emit() and friends */ +#define XOEF_RETAIN (1<<0) /* Retain parsed formatting information */ /* * The xo_info_t structure provides a mapping between names and @@ -162,6 +167,12 @@ xo_set_flags (xo_handle_t *xop, xo_xof_flags_t flags); void xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags); +int +xo_set_file_h (xo_handle_t *xop, FILE *fp); + +int +xo_set_file (FILE *fp); + void xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count); @@ -180,6 +191,16 @@ xo_emit_h (xo_handle_t *xop, const char *fmt, ...); int xo_emit (const char *fmt, ...); +int +xo_emit_hvf (xo_handle_t *xop, xo_emit_flags_t flags, + const char *fmt, va_list vap); + +int +xo_emit_hf (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...); + +int +xo_emit_f (xo_emit_flags_t flags, const char *fmt, ...); + PRINTFLIKE(2, 0) static inline int xo_emit_hvp (xo_handle_t *xop, const char *fmt, va_list vap) @@ -209,6 +230,36 @@ xo_emit_p (const char *fmt, ...) return rc; } +PRINTFLIKE(3, 0) +static inline int +xo_emit_hvfp (xo_handle_t *xop, xo_emit_flags_t flags, + const char *fmt, va_list vap) +{ + return xo_emit_hvf(xop, flags, fmt, vap); +} + +PRINTFLIKE(3, 4) +static inline int +xo_emit_hfp (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...) +{ + va_list vap; + va_start(vap, fmt); + int rc = xo_emit_hvf(xop, flags, fmt, vap); + va_end(vap); + return rc; +} + +PRINTFLIKE(2, 3) +static inline int +xo_emit_fp (xo_emit_flags_t flags, const char *fmt, ...) +{ + va_list vap; + va_start(vap, fmt); + int rc = xo_emit_hvf(NULL, flags, fmt, vap); + va_end(vap); + return rc; +} + int xo_open_container_h (xo_handle_t *xop, const char *name); @@ -593,4 +644,23 @@ char * xo_simplify_format (xo_handle_t *xop, const char *fmt, int with_numbers, xo_simplify_field_func_t field_cb); +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, ...); + +void +xo_retain_clear_all (void); + +void +xo_retain_clear (const char *fmt); + #endif /* INCLUDE_XO_H */ diff --git a/contrib/libxo/libxo/xo_emit_f.3 b/contrib/libxo/libxo/xo_emit_f.3 new file mode 100644 index 000000000000..087954631516 --- /dev/null +++ b/contrib/libxo/libxo/xo_emit_f.3 @@ -0,0 +1,111 @@ +.\" # +.\" # Copyright (c) 2016, 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, April 2016 +.\" +.Dd April 15, 2016 +.Dt LIBXO 3 +.Os +.Sh NAME +.Nm xo_emit_f , xo_emit_hf , xo_emit_hvf +.Nd emit formatted output based on format string and arguments +.Sh LIBRARY +.Lb libxo +.Sh SYNOPSIS +.In libxo/xo.h +.Ft int +.Fn xo_emit_f "xo_emit_flags_t flags" "const char *fmt" "..." +.Ft int +.Fn xo_emit_hf "xo_handle_t *xop" "xo_emit_flags_t flags" "const char *fmt" "..." +.Ft int +.Fn xo_emit_hvf "xo_handle_t *xop" "xo_emit_flags_t flags" "const char *fmt" "va_list vap" +.Ft void +.Fn xo_retain_clear_all "void" +.Ft void +.Fn xo_retain_clear "const char *fmt" +.Sh DESCRIPTION +These functions allow callers to pass a set of flags to +.Nm +emitting functions. These processing of arguments, except for +.Fa flags , +is identical to the base functions. +See +.Xr xo_emit 3 +for additional information. +.Pp +The only currently defined flag is +.Dv XOEF_RETAIN . +.Nm +can retain the parsed internal information related to the given +format string, allowing subsequent +.Xr xo_emit 3 +calls, the retained +information is used, avoiding repetitive parsing of the format string. +To retain parsed format information, use the +.Dv XOEF_RETAIN +flag to the +.Fn xo_emit_f +function. +.Pp +The format string must be immutable across multiple calls to +.Xn 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 +.Dv XOEF_RETAIN +flag must not be used. +.Pp +The functions +.Fn xo_retain_clear +and +.Fn 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. +.Pp +The retained information is kept as thread-specific data. +.Pp +Use +.Fn xo_retain_clear +and +.Fn xo_retain_clear_all +to clear the retained information, clearing the retained information +for either a specific format string or all format strings, respectively. +These functions are only needed when the calling application wants to +clear this information; they are not generally needed. +.Sh EXAMPLES +.Pp +.Bd -literal -offset indent + for (i = 0; i < 1000; i++) { + xo_open_instance("item"); + xo_emit_f(XOEF_RETAIN, "{:name} {:count/%d}\n", + name[i], count[i]); + } +.Ed +.Pp +In this example, the caller desires to clear the retained information. +.Bd -literal -offset indent + 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); +.Ed +.Sh RETURN CODE +The return values for these functions is identical to those of their +traditional counterparts. See +.Xr xo_emit 3 +for details. +.Sh SEE ALSO +.Xr xo_emit 3 , +.Xr xo_open_container 3 , +.Xr xo_open_list 3 , +.Xr xo_format 5 , +.Xr libxo 3 diff --git a/contrib/libxo/libxo/xo_format.5 b/contrib/libxo/libxo/xo_format.5 index 89c010391d51..79af3fa39f3d 100644 --- a/contrib/libxo/libxo/xo_format.5 +++ b/contrib/libxo/libxo/xo_format.5 @@ -51,14 +51,14 @@ field descriptions within the format string. .Pp The field description is given as follows: .Bd -literal -offset indent - '{' [ role | modifier ]* [',' long-names ]* ':' [ content ] - [ '/' field-format [ '/' encoding-format ]] '}' + \(aq{\(aq [ role | modifier ]* [\(aq,\(aq long\-names ]* \(aq:\(aq [ content ] + [ \(aq/\(aq field\-format [ \(aq/\(aq encoding\-format ]] \(aq}\(aq .Ed .Pp 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. +The contents, field\-format, and +encoding\-format are used in varying ways, based on the role. These are described in the following sections. .Pp Braces can be escaped by using double braces, similar to "%%" in @@ -68,26 +68,26 @@ The format string "{{braces}}" would emit "{braces}". 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 +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 .Xr xo_emit 3 , function as an unsigned integer. .Bd -literal -offset indent - xo_emit("{P: }{Lwc:In stock}{:in-stock/%u}\\n", 65); + xo_emit("{P: }{Lwc:In stock}{:in\-stock/%u}\\n", 65); .Ed .Pp This single line of code can generate text ("In stock: 65\\n"), XML -(" 65 "), JSON ('"in-stock": 65'), or HTML (too +("65 "), JSON (\(aq"in\-stock": 65\(aq), or HTML (too lengthy to be listed here). .Pp 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: +single\-character values: .Bd -literal -offset indent - xo_emit("{L,white,colon:In stock}{,key:in-stock/%u}\n", 65); + xo_emit("{L,white,colon:In stock}{,key:in\-stock/%u}\\n", 65); .Ed .Ss "Field Roles" Field roles are optional, and indicate the role and formatting of the @@ -96,7 +96,7 @@ The roles are listed below; only one role is permitted: .Bl -column "M" "Name12341234" .It Sy "M" "Name " "Description" .It C "color " "Field is a color or effect" -.It D "decoration " "Field is non-text (e.g. colon, comma)" +.It D "decoration " "Field is non\-text (e.g. colon, comma)" .It E "error " "Field is an error message" .It L "label " "Field is text that prefixes a value" .It N "note " "Field is text that follows a value" @@ -105,12 +105,12 @@ The roles are listed below; only one role is permitted: .It U "units " "Field is the units for the previous value field" .It V "value " "Field is the name of field (the default)" .It W "warning " "Field is a warning message" -.It \&[ "start-anchor" "Begin a section of anchored variable-width text" -.It \&] "stop-anchor " "End a section of anchored variable-width text" +.It \&[ "start\-anchor" "Begin a section of anchored variable\-width text" +.It \&] "stop\-anchor " "End a section of anchored variable\-width text" .El .Bd -literal -offset indent EXAMPLE: - xo_emit("{L:Free}{D::}{P: }{:free/%u} {U:Blocks}\n", + xo_emit("{L:Free}{D::}{P: }{:free/%u} {U:Blocks}\\n", free_blocks); .Ed .Pp @@ -121,50 +121,50 @@ a comma: .Bd -literal -offset indent EXAMPLE: xo_emit("{,label:Free}{,decoration::}{,padding: }" - "{,value:free/%u} {,units:Blocks}\n", + "{,value:free/%u} {,units:Blocks}\\n", free_blocks); .Ed .Ss "The Color Role ({C:})" Colors and effects control how text values are displayed; they are used for display styles (TEXT and HTML). .Bd -literal -offset indent - xo_emit("{C:bold}{:value}{C:no-bold}\n", value); + xo_emit("{C:bold}{:value}{C:no\-bold}\\n", value); .Ed .Pp -Colors and effects remain in effect until modified by other "C"-role +Colors and effects remain in effect until modified by other "C"\-role fields. .Bd -literal -offset indent - xo_emit("{C:bold}{C:inverse}both{C:no-bold}only inverse\n"); + xo_emit("{C:bold}{C:inverse}both{C:no\-bold}only inverse\\n"); .Ed .Pp If the content is empty, the "reset" action is performed. .Bd -literal -offset indent - xo_emit("{C:both,underline}{:value}{C:}\n", value); + xo_emit("{C:both,underline}{:value}{C:}\\n", value); .Ed .Pp -The content should be a comma-separated list of zero or more colors or +The content should be a comma\-separated list of zero or more colors or display effects. .Bd -literal -offset indent - xo_emit("{C:bold,underline,inverse}All three{C:no-bold,no-inverse}\n"); + xo_emit("{C:bold,underline,inverse}All three{C:no\-bold,no\-inverse}\\n"); .Ed .Pp The color content can be either static, when placed directly within -the field descriptor, or a printf-style format descriptor can be used, +the field descriptor, or a printf\-style format descriptor can be used, if preceded by a slash ("/"): .Bd -literal -offset indent xo_emit("{C:/%s%s}{:value}{C:}", need_bold ? "bold" : "", need_underline ? "underline" : "", value); .Ed .Pp -Color names are prefixed with either "fg-" or "bg-" to change the +Color names are prefixed with either "fg\-" or "bg\-" to change the foreground and background colors, respectively. .Bd -literal -offset indent - xo_emit("{C:/fg-%s,bg-%s}{Lwc:Cost}{:cost/%u}{C:reset}\n", + xo_emit("{C:/fg\-%s,bg\-%s}{Lwc:Cost}{:cost/%u}{C:reset}\\n", fg_color, bg_color, cost); .Ed .Pp The following table lists the supported effects: -.Bl -column "no-underline" +.Bl -column "no\-underline" .It Sy "Name " "Description" .It "bg\-xxxxx " "Change background color" .It "bold " "Start bold text effect" @@ -179,7 +179,7 @@ The following table lists the supported effects: .El .Pp The following color names are supported: -.Bl -column "no-underline" +.Bl -column "no\-underline" .It Sy "Name" .It black .It blue @@ -193,7 +193,7 @@ The following color names are supported: .El .Ss "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 +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. @@ -219,22 +219,23 @@ change such as changing "/%06d" to "/%08d" should not force hand inspection of all .po files. .Pp 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