2 * Copyright (c) 2014-2015, Juniper Networks, Inc.
4 * This SOFTWARE is licensed under the LICENSE provided in the
5 * ../Copyright file. By downloading, installing, copying, or otherwise
6 * using the SOFTWARE, you agree to be bound by the terms of that
8 * Phil Shafer, July 2014
10 * This is the implementation of libxo, the formatting library that
11 * generates multiple styles of output from a single code path.
12 * Command line utilities can have their normal text output while
13 * automation tools can see XML or JSON output, and web tools can use
14 * HTML output that encodes the text output annotated with additional
15 * information. Specialized encoders can be built that allow custom
16 * encoding including binary ones like CBOR, thrift, protobufs, etc.
18 * Full documentation is available in ./doc/libxo.txt or online at:
19 * http://juniper.github.io/libxo/libxo-manual.html
21 * For first time readers, the core bits of code to start looking at are:
22 * - xo_do_emit() -- parse and emit a set of fields
23 * - xo_do_emit_fields -- the central function of the library
24 * - xo_do_format_field() -- handles formatting a single field
25 * - xo_transiton() -- the state machine that keeps things sane
26 * and of course the "xo_handle_t" data structure, which carries all
27 * configuration and state.
37 #include <sys/types.h>
46 #include "xo_config.h"
48 #include "xo_encoder.h"
52 * We ask wcwidth() to do an impossible job, really. It's supposed to
53 * need to tell us the number of columns consumed to display a unicode
54 * character. It returns that number without any sort of context, but
55 * we know they are characters whose glyph differs based on placement
56 * (end of word, middle of word, etc) and many that affect characters
57 * previously emitted. Without content, it can't hope to tell us.
58 * But it's the only standard tool we've got, so we use it. We would
59 * use wcswidth() but it typically just loops through adding the results
60 * of wcwidth() calls in an entirely unhelpful way.
62 * Even then, there are many poor implementations (macosx), so we have
63 * to carry our own. We could have configure.ac test this (with
64 * something like 'assert(wcwidth(0x200d) == 0)'), but it would have
65 * to run a binary, which breaks cross-compilation. Hmm... I could
66 * run this test at init time and make a warning for our dear user.
68 * Anyhow, it remains a best-effort sort of thing. And it's all made
69 * more hopeless because we assume the display code doing the rendering is
70 * playing by the same rules we are. If it display 0x200d as a square
71 * box or a funky question mark, the output will be hosed.
74 #include "xo_wcwidth.h"
75 #else /* LIBXO_WCWIDTH */
76 #define xo_wcwidth(_x) wcwidth(_x)
77 #endif /* LIBXO_WCWIDTH */
79 #ifdef HAVE_STDIO_EXT_H
80 #include <stdio_ext.h>
81 #endif /* HAVE_STDIO_EXT_H */
84 * humanize_number is a great function, unless you don't have it. So
85 * we carry one in our pocket.
87 #ifdef HAVE_HUMANIZE_NUMBER
89 #define xo_humanize_number humanize_number
90 #else /* HAVE_HUMANIZE_NUMBER */
91 #include "xo_humanize.h"
92 #endif /* HAVE_HUMANIZE_NUMBER */
96 #endif /* HAVE_GETTEXT */
99 * Three styles of specifying thread-local variables are supported.
100 * configure.ac has the brains to run each possibility through the
101 * compiler and see what works; we are left to define the THREAD_LOCAL
102 * macro to the right value. Most toolchains (clang, gcc) use
103 * "before", but some (borland) use "after" and I've heard of some
104 * (ms) that use __declspec. Any others out there?
106 #define THREAD_LOCAL_before 1
107 #define THREAD_LOCAL_after 2
108 #define THREAD_LOCAL_declspec 3
110 #ifndef HAVE_THREAD_LOCAL
111 #define THREAD_LOCAL(_x) _x
112 #elif HAVE_THREAD_LOCAL == THREAD_LOCAL_before
113 #define THREAD_LOCAL(_x) __thread _x
114 #elif HAVE_THREAD_LOCAL == THREAD_LOCAL_after
115 #define THREAD_LOCAL(_x) _x __thread
116 #elif HAVE_THREAD_LOCAL == THREAD_LOCAL_declspec
117 #define THREAD_LOCAL(_x) __declspec(_x)
119 #error unknown thread-local setting
120 #endif /* HAVE_THREADS_H */
122 const char xo_version[] = LIBXO_VERSION;
123 const char xo_version_extra[] = LIBXO_VERSION_EXTRA;
124 static const char xo_default_format[] = "%s";
127 #define UNUSED __attribute__ ((__unused__))
130 #define XO_INDENT_BY 2 /* Amount to indent when pretty printing */
131 #define XO_DEPTH 128 /* Default stack depth */
132 #define XO_MAX_ANCHOR_WIDTH (8*1024) /* Anything wider is just sillyb */
134 #define XO_FAILURE_NAME "failure"
136 /* Flags for the stack frame */
137 typedef unsigned xo_xsf_flags_t; /* XSF_* flags */
138 #define XSF_NOT_FIRST (1<<0) /* Not the first element */
139 #define XSF_LIST (1<<1) /* Frame is a list */
140 #define XSF_INSTANCE (1<<2) /* Frame is an instance */
141 #define XSF_DTRT (1<<3) /* Save the name for DTRT mode */
143 #define XSF_CONTENT (1<<4) /* Some content has been emitted */
144 #define XSF_EMIT (1<<5) /* Some field has been emitted */
145 #define XSF_EMIT_KEY (1<<6) /* A key has been emitted */
146 #define XSF_EMIT_LEAF_LIST (1<<7) /* A leaf-list field has been emitted */
148 /* These are the flags we propagate between markers and their parents */
149 #define XSF_MARKER_FLAGS \
150 (XSF_NOT_FIRST | XSF_CONTENT | XSF_EMIT | XSF_EMIT_KEY | XSF_EMIT_LEAF_LIST )
153 * A word about states: We use a finite state machine (FMS) approach
154 * to help remove fragility from the caller's code. Instead of
155 * requiring a specific order of calls, we'll allow the caller more
156 * flexibility and make the library responsible for recovering from
157 * missed steps. The goal is that the library should not be capable
158 * of emitting invalid xml or json, but the developer shouldn't need
159 * to know or understand all the details about these encodings.
161 * You can think of states as either states or events, since they
162 * function rather like both. None of the XO_CLOSE_* events will
163 * persist as states, since the matching stack frame will be popped.
164 * Same is true of XSS_EMIT, which is an event that asks us to
165 * prep for emitting output fields.
168 /* Stack frame states */
169 typedef unsigned xo_state_t;
170 #define XSS_INIT 0 /* Initial stack state */
171 #define XSS_OPEN_CONTAINER 1
172 #define XSS_CLOSE_CONTAINER 2
173 #define XSS_OPEN_LIST 3
174 #define XSS_CLOSE_LIST 4
175 #define XSS_OPEN_INSTANCE 5
176 #define XSS_CLOSE_INSTANCE 6
177 #define XSS_OPEN_LEAF_LIST 7
178 #define XSS_CLOSE_LEAF_LIST 8
179 #define XSS_DISCARDING 9 /* Discarding data until recovered */
180 #define XSS_MARKER 10 /* xo_open_marker's marker */
181 #define XSS_EMIT 11 /* xo_emit has a leaf field */
182 #define XSS_EMIT_LEAF_LIST 12 /* xo_emit has a leaf-list ({l:}) */
183 #define XSS_FINISH 13 /* xo_finish was called */
187 #define XSS_TRANSITION(_old, _new) ((_old) << 8 | (_new))
190 * xo_stack_t: As we open and close containers and levels, we
191 * create a stack of frames to track them. This is needed for
192 * XOF_WARN and XOF_XPATH.
194 typedef struct xo_stack_s {
195 xo_xsf_flags_t xs_flags; /* Flags for this frame */
196 xo_state_t xs_state; /* State for this stack frame */
197 char *xs_name; /* Name (for XPath value) */
198 char *xs_keys; /* XPath predicate for any key fields */
202 * libxo supports colors and effects, for those who like them.
203 * XO_COL_* ("colors") refers to fancy ansi codes, while X__EFF_*
204 * ("effects") are bits since we need to maintain state.
206 typedef uint8_t xo_color_t;
207 #define XO_COL_DEFAULT 0
208 #define XO_COL_BLACK 1
210 #define XO_COL_GREEN 3
211 #define XO_COL_YELLOW 4
212 #define XO_COL_BLUE 5
213 #define XO_COL_MAGENTA 6
214 #define XO_COL_CYAN 7
215 #define XO_COL_WHITE 8
217 #define XO_NUM_COLORS 9
220 * Yes, there's no blink. We're civilized. We like users. Blink
221 * isn't something one does to someone you like. Friends don't let
222 * friends use blink. On friends. You know what I mean. Blink is
223 * like, well, it's like bursting into show tunes at a funeral. It's
224 * just not done. Not something anyone wants. And on those rare
225 * instances where it might actually be appropriate, it's still wrong,
226 * since it's likely done by the wrong person for the wrong reason.
227 * Just like blink. And if I implemented blink, I'd be like a funeral
228 * director who adds "Would you like us to burst into show tunes?" on
229 * the list of questions asked while making funeral arrangements.
230 * It's formalizing wrongness in the wrong way. And we're just too
231 * civilized to do that. Hhhmph!
233 #define XO_EFF_RESET (1<<0)
234 #define XO_EFF_NORMAL (1<<1)
235 #define XO_EFF_BOLD (1<<2)
236 #define XO_EFF_UNDERLINE (1<<3)
237 #define XO_EFF_INVERSE (1<<4)
239 #define XO_EFF_CLEAR_BITS XO_EFF_RESET /* Reset gets reset, surprisingly */
241 typedef uint8_t xo_effect_t;
242 typedef uint8_t xo_color_t;
243 typedef struct xo_colors_s {
244 xo_effect_t xoc_effects; /* Current effect set */
245 xo_color_t xoc_col_fg; /* Foreground color */
246 xo_color_t xoc_col_bg; /* Background color */
250 * xo_handle_t: this is the principle data structure for libxo.
251 * It's used as a store for state, options, content, and all manor
252 * of other information.
255 xo_xof_flags_t xo_flags; /* Flags (XOF_*) from the user*/
256 xo_xof_flags_t xo_iflags; /* Internal flags (XOIF_*) */
257 xo_style_t xo_style; /* XO_STYLE_* value */
258 unsigned short xo_indent; /* Indent level (if pretty) */
259 unsigned short xo_indent_by; /* Indent amount (tab stop) */
260 xo_write_func_t xo_write; /* Write callback */
261 xo_close_func_t xo_close; /* Close callback */
262 xo_flush_func_t xo_flush; /* Flush callback */
263 xo_formatter_t xo_formatter; /* Custom formating function */
264 xo_checkpointer_t xo_checkpointer; /* Custom formating support function */
265 void *xo_opaque; /* Opaque data for write function */
266 xo_buffer_t xo_data; /* Output data */
267 xo_buffer_t xo_fmt; /* Work area for building format strings */
268 xo_buffer_t xo_attrs; /* Work area for building XML attributes */
269 xo_buffer_t xo_predicate; /* Work area for building XPath predicates */
270 xo_stack_t *xo_stack; /* Stack pointer */
271 int xo_depth; /* Depth of stack */
272 int xo_stack_size; /* Size of the stack */
273 xo_info_t *xo_info; /* Info fields for all elements */
274 int xo_info_count; /* Number of info entries */
275 va_list xo_vap; /* Variable arguments (stdargs) */
276 char *xo_leading_xpath; /* A leading XPath expression */
277 mbstate_t xo_mbstate; /* Multi-byte character conversion state */
278 ssize_t xo_anchor_offset; /* Start of anchored text */
279 ssize_t xo_anchor_columns; /* Number of columns since the start anchor */
280 ssize_t xo_anchor_min_width; /* Desired width of anchored text */
281 ssize_t xo_units_offset; /* Start of units insertion point */
282 ssize_t xo_columns; /* Columns emitted during this xo_emit call */
283 #ifndef LIBXO_TEXT_ONLY
284 uint8_t xo_color_map_fg[XO_NUM_COLORS]; /* Foreground color mappings */
285 uint8_t xo_color_map_bg[XO_NUM_COLORS]; /* Background color mappings */
286 #endif /* LIBXO_TEXT_ONLY */
287 xo_colors_t xo_colors; /* Current color and effect values */
288 xo_buffer_t xo_color_buf; /* HTML: buffer of colors and effects */
289 char *xo_version; /* Version string */
290 int xo_errno; /* Saved errno for "%m" */
291 char *xo_gt_domain; /* Gettext domain, suitable for dgettext(3) */
292 xo_encoder_func_t xo_encoder; /* Encoding function */
293 void *xo_private; /* Private data for external encoders */
296 /* Flag operations */
297 #define XOF_BIT_ISSET(_flag, _bit) (((_flag) & (_bit)) ? 1 : 0)
298 #define XOF_BIT_SET(_flag, _bit) do { (_flag) |= (_bit); } while (0)
299 #define XOF_BIT_CLEAR(_flag, _bit) do { (_flag) &= ~(_bit); } while (0)
301 #define XOF_ISSET(_xop, _bit) XOF_BIT_ISSET(_xop->xo_flags, _bit)
302 #define XOF_SET(_xop, _bit) XOF_BIT_SET(_xop->xo_flags, _bit)
303 #define XOF_CLEAR(_xop, _bit) XOF_BIT_CLEAR(_xop->xo_flags, _bit)
305 #define XOIF_ISSET(_xop, _bit) XOF_BIT_ISSET(_xop->xo_iflags, _bit)
306 #define XOIF_SET(_xop, _bit) XOF_BIT_SET(_xop->xo_iflags, _bit)
307 #define XOIF_CLEAR(_xop, _bit) XOF_BIT_CLEAR(_xop->xo_iflags, _bit)
310 #define XOIF_REORDER XOF_BIT(0) /* Reordering fields; record field info */
311 #define XOIF_DIV_OPEN XOF_BIT(1) /* A <div> is open */
312 #define XOIF_TOP_EMITTED XOF_BIT(2) /* The top JSON braces have been emitted */
313 #define XOIF_ANCHOR XOF_BIT(3) /* An anchor is in place */
315 #define XOIF_UNITS_PENDING XOF_BIT(4) /* We have a units-insertion pending */
316 #define XOIF_INIT_IN_PROGRESS XOF_BIT(5) /* Init of handle is in progress */
318 /* Flags for formatting functions */
319 typedef unsigned long xo_xff_flags_t;
320 #define XFF_COLON (1<<0) /* Append a ":" */
321 #define XFF_COMMA (1<<1) /* Append a "," iff there's more output */
322 #define XFF_WS (1<<2) /* Append a blank */
323 #define XFF_ENCODE_ONLY (1<<3) /* Only emit for encoding styles (XML, JSON) */
325 #define XFF_QUOTE (1<<4) /* Force quotes */
326 #define XFF_NOQUOTE (1<<5) /* Force no quotes */
327 #define XFF_DISPLAY_ONLY (1<<6) /* Only emit for display styles (text, html) */
328 #define XFF_KEY (1<<7) /* Field is a key (for XPath) */
330 #define XFF_XML (1<<8) /* Force XML encoding style (for XPath) */
331 #define XFF_ATTR (1<<9) /* Escape value using attribute rules (XML) */
332 #define XFF_BLANK_LINE (1<<10) /* Emit a blank line */
333 #define XFF_NO_OUTPUT (1<<11) /* Do not make any output */
335 #define XFF_TRIM_WS (1<<12) /* Trim whitespace off encoded values */
336 #define XFF_LEAF_LIST (1<<13) /* A leaf-list (list of values) */
337 #define XFF_UNESCAPE (1<<14) /* Need to printf-style unescape the value */
338 #define XFF_HUMANIZE (1<<15) /* Humanize the value (for display styles) */
340 #define XFF_HN_SPACE (1<<16) /* Humanize: put space before suffix */
341 #define XFF_HN_DECIMAL (1<<17) /* Humanize: add one decimal place if <10 */
342 #define XFF_HN_1000 (1<<18) /* Humanize: use 1000, not 1024 */
343 #define XFF_GT_FIELD (1<<19) /* Call gettext() on a field */
345 #define XFF_GT_PLURAL (1<<20) /* Call dngettext to find plural form */
346 #define XFF_ARGUMENT (1<<21) /* Content provided via argument */
348 /* Flags to turn off when we don't want i18n processing */
349 #define XFF_GT_FLAGS (XFF_GT_FIELD | XFF_GT_PLURAL)
352 * Normal printf has width and precision, which for strings operate as
353 * min and max number of columns. But this depends on the idea that
354 * one byte means one column, which UTF-8 and multi-byte characters
355 * pitches on its ear. It may take 40 bytes of data to populate 14
356 * columns, but we can't go off looking at 40 bytes of data without the
357 * caller's permission for fear/knowledge that we'll generate core files.
359 * So we make three values, distinguishing between "max column" and
360 * "number of bytes that we will inspect inspect safely" We call the
361 * later "size", and make the format "%[[<min>].[[<size>].<max>]]s".
363 * Under the "first do no harm" theory, we default "max" to "size".
364 * This is a reasonable assumption for folks that don't grok the
365 * MBS/WCS/UTF-8 world, and while it will be annoying, it will never
368 * For example, xo_emit("{:tag/%-14.14s}", buf) will make 14
369 * columns of output, but will never look at more than 14 bytes of the
370 * input buffer. This is mostly compatible with printf and caller's
373 * In contrast xo_emit("{:tag/%-14..14s}", buf) will look at however
374 * many bytes (or until a NUL is seen) are needed to fill 14 columns
375 * of output. xo_emit("{:tag/%-14.*.14s}", xx, buf) will look at up
376 * to xx bytes (or until a NUL is seen) in order to fill 14 columns
379 * It's fairly amazing how a good idea (handle all languages of the
380 * world) blows such a big hole in the bottom of the fairly weak boat
381 * that is C string handling. The simplicity and completenesss are
382 * sunk in ways we haven't even begun to understand.
384 #define XF_WIDTH_MIN 0 /* Minimal width */
385 #define XF_WIDTH_SIZE 1 /* Maximum number of bytes to examine */
386 #define XF_WIDTH_MAX 2 /* Maximum width */
387 #define XF_WIDTH_NUM 3 /* Numeric fields in printf (min.size.max) */
389 /* Input and output string encodings */
390 #define XF_ENC_WIDE 1 /* Wide characters (wchar_t) */
391 #define XF_ENC_UTF8 2 /* UTF-8 */
392 #define XF_ENC_LOCALE 3 /* Current locale */
395 * A place to parse printf-style format flags for each field
397 typedef struct xo_format_s {
398 unsigned char xf_fc; /* Format character */
399 unsigned char xf_enc; /* Encoding of the string (XF_ENC_*) */
400 unsigned char xf_skip; /* Skip this field */
401 unsigned char xf_lflag; /* 'l' (long) */
402 unsigned char xf_hflag;; /* 'h' (half) */
403 unsigned char xf_jflag; /* 'j' (intmax_t) */
404 unsigned char xf_tflag; /* 't' (ptrdiff_t) */
405 unsigned char xf_zflag; /* 'z' (size_t) */
406 unsigned char xf_qflag; /* 'q' (quad_t) */
407 unsigned char xf_seen_minus; /* Seen a minus */
408 int xf_leading_zero; /* Seen a leading zero (zero fill) */
409 unsigned xf_dots; /* Seen one or more '.'s */
410 int xf_width[XF_WIDTH_NUM]; /* Width/precision/size numeric fields */
411 unsigned xf_stars; /* Seen one or more '*'s */
412 unsigned char xf_star[XF_WIDTH_NUM]; /* Seen one or more '*'s */
416 * This structure represents the parsed field information, suitable for
417 * processing by xo_do_emit and anything else that needs to parse fields.
418 * Note that all pointers point to the main format string.
420 * XXX This is a first step toward compilable or cachable format
421 * strings. We can also cache the results of dgettext when no format
422 * is used, assuming the 'p' modifier has _not_ been set.
424 typedef struct xo_field_info_s {
425 xo_xff_flags_t xfi_flags; /* Flags for this field */
426 unsigned xfi_ftype; /* Field type, as character (e.g. 'V') */
427 const char *xfi_start; /* Start of field in the format string */
428 const char *xfi_content; /* Field's content */
429 const char *xfi_format; /* Field's Format */
430 const char *xfi_encoding; /* Field's encoding format */
431 const char *xfi_next; /* Next character in format string */
432 ssize_t xfi_len; /* Length of field */
433 ssize_t xfi_clen; /* Content length */
434 ssize_t xfi_flen; /* Format length */
435 ssize_t xfi_elen; /* Encoding length */
436 unsigned xfi_fnum; /* Field number (if used; 0 otherwise) */
437 unsigned xfi_renum; /* Reordered number (0 == no renumbering) */
441 * We keep a 'default' handle to allow callers to avoid having to
442 * allocate one. Passing NULL to any of our functions will use
443 * this default handle. Most functions have a variant that doesn't
444 * require a handle at all, since most output is to stdout, which
445 * the default handle handles handily.
447 static THREAD_LOCAL(xo_handle_t) xo_default_handle;
448 static THREAD_LOCAL(int) xo_default_inited;
449 static int xo_locale_inited;
450 static const char *xo_program;
453 * To allow libxo to be used in diverse environment, we allow the
454 * caller to give callbacks for memory allocation.
456 xo_realloc_func_t xo_realloc = realloc;
457 xo_free_func_t xo_free = free;
459 /* Forward declarations */
461 xo_failure (xo_handle_t *xop, const char *fmt, ...);
464 xo_transition (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name,
465 xo_state_t new_state);
468 xo_set_options_simple (xo_handle_t *xop, const char *input);
471 xo_color_find (const char *str);
474 xo_buf_append_div (xo_handle_t *xop, const char *class, xo_xff_flags_t flags,
475 const char *name, ssize_t nlen,
476 const char *value, ssize_t vlen,
477 const char *encoding, ssize_t elen);
480 xo_anchor_clear (xo_handle_t *xop);
483 * xo_style is used to retrieve the current style. When we're built
484 * for "text only" mode, we use this function to drive the removal
485 * of most of the code in libxo. We return a constant and the compiler
486 * happily removes the non-text code that is not longer executed. This
487 * trims our code nicely without needing to trampel perfectly readable
490 static inline xo_style_t
491 xo_style (xo_handle_t *xop UNUSED)
493 #ifdef LIBXO_TEXT_ONLY
494 return XO_STYLE_TEXT;
495 #else /* LIBXO_TEXT_ONLY */
496 return xop->xo_style;
497 #endif /* LIBXO_TEXT_ONLY */
501 * Callback to write data to a FILE pointer
504 xo_write_to_file (void *opaque, const char *data)
506 FILE *fp = (FILE *) opaque;
508 return fprintf(fp, "%s", data);
512 * Callback to close a file
515 xo_close_file (void *opaque)
517 FILE *fp = (FILE *) opaque;
523 * Callback to flush a FILE pointer
526 xo_flush_file (void *opaque)
528 FILE *fp = (FILE *) opaque;
534 * Use a rotating stock of buffers to make a printable string
537 #define XO_SMBUFSZ 128
540 xo_printable (const char *str)
542 static THREAD_LOCAL(char) bufset[XO_NUMBUFS][XO_SMBUFSZ];
543 static THREAD_LOCAL(int) bufnum = 0;
548 if (++bufnum == XO_NUMBUFS)
551 char *res = bufset[bufnum], *cp, *ep;
553 for (cp = res, ep = res + XO_SMBUFSZ - 1; *str && cp < ep; cp++, str++) {
557 } else if (*str == '\r') {
560 } else if (*str == '\"') {
572 xo_depth_check (xo_handle_t *xop, int depth)
576 if (depth >= xop->xo_stack_size) {
577 depth += XO_DEPTH; /* Extra room */
579 xsp = xo_realloc(xop->xo_stack, sizeof(xop->xo_stack[0]) * depth);
581 xo_failure(xop, "xo_depth_check: out of memory (%d)", depth);
585 int count = depth - xop->xo_stack_size;
587 bzero(xsp + xop->xo_stack_size, count * sizeof(*xsp));
588 xop->xo_stack_size = depth;
596 xo_no_setlocale (void)
598 xo_locale_inited = 1; /* Skip initialization */
602 * We need to decide if stdout is line buffered (_IOLBF). Lacking a
603 * standard way to decide this (e.g. getlinebuf()), we have configure
604 * look to find __flbf, which glibc supported. If not, we'll rely on
605 * isatty, with the assumption that terminals are the only thing
606 * that's line buffered. We _could_ test for "steam._flags & _IOLBF",
607 * which is all __flbf does, but that's even tackier. Like a
608 * bedazzled Elvis outfit on an ugly lap dog sort of tacky. Not
609 * something we're willing to do.
612 xo_is_line_buffered (FILE *stream)
617 #else /* HAVE___FLBF */
618 if (isatty(fileno(stream)))
620 #endif /* HAVE___FLBF */
625 * Initialize an xo_handle_t, using both static defaults and
626 * the global settings from the LIBXO_OPTIONS environment
630 xo_init_handle (xo_handle_t *xop)
632 xop->xo_opaque = stdout;
633 xop->xo_write = xo_write_to_file;
634 xop->xo_flush = xo_flush_file;
636 if (xo_is_line_buffered(stdout))
637 XOF_SET(xop, XOF_FLUSH_LINE);
640 * We need to initialize the locale, which isn't really pretty.
641 * Libraries should depend on their caller to set up the
642 * environment. But we really can't count on the caller to do
643 * this, because well, they won't. Trust me.
645 if (!xo_locale_inited) {
646 xo_locale_inited = 1; /* Only do this once */
648 const char *cp = getenv("LC_CTYPE");
652 cp = getenv("LC_ALL");
654 cp = "C"; /* Default for C programs */
655 (void) setlocale(LC_CTYPE, cp);
659 * Initialize only the xo_buffers we know we'll need; the others
660 * can be allocated as needed.
662 xo_buf_init(&xop->xo_data);
663 xo_buf_init(&xop->xo_fmt);
665 if (XOIF_ISSET(xop, XOIF_INIT_IN_PROGRESS))
667 XOIF_SET(xop, XOIF_INIT_IN_PROGRESS);
669 xop->xo_indent_by = XO_INDENT_BY;
670 xo_depth_check(xop, XO_DEPTH);
672 XOIF_CLEAR(xop, XOIF_INIT_IN_PROGRESS);
676 * Initialize the default handle.
679 xo_default_init (void)
681 xo_handle_t *xop = &xo_default_handle;
685 #if !defined(NO_LIBXO_OPTIONS)
686 if (!XOF_ISSET(xop, XOF_NO_ENV)) {
687 char *env = getenv("LIBXO_OPTIONS");
689 xo_set_options_simple(xop, env);
692 #endif /* NO_LIBXO_OPTIONS */
694 xo_default_inited = 1;
698 * Cheap convenience function to return either the argument, or
699 * the internal handle, after it has been initialized. The usage
701 * xop = xo_default(xop);
704 xo_default (xo_handle_t *xop)
707 if (xo_default_inited == 0)
709 xop = &xo_default_handle;
716 * Return the number of spaces we should be indenting. If
717 * we are pretty-printing, this is indent * indent_by.
720 xo_indent (xo_handle_t *xop)
724 xop = xo_default(xop);
726 if (XOF_ISSET(xop, XOF_PRETTY)) {
727 rc = xop->xo_indent * xop->xo_indent_by;
728 if (XOIF_ISSET(xop, XOIF_TOP_EMITTED))
729 rc += xop->xo_indent_by;
732 return (rc > 0) ? rc : 0;
736 xo_buf_indent (xo_handle_t *xop, int indent)
738 xo_buffer_t *xbp = &xop->xo_data;
741 indent = xo_indent(xop);
743 if (!xo_buf_has_room(xbp, indent))
746 memset(xbp->xb_curp, ' ', indent);
747 xbp->xb_curp += indent;
750 static char xo_xml_amp[] = "&";
751 static char xo_xml_lt[] = "<";
752 static char xo_xml_gt[] = ">";
753 static char xo_xml_quot[] = """;
756 xo_escape_xml (xo_buffer_t *xbp, ssize_t len, xo_xff_flags_t flags)
762 int attr = XOF_BIT_ISSET(flags, XFF_ATTR);
764 for (cp = xbp->xb_curp, ep = cp + len; cp < ep; cp++) {
765 /* We're subtracting 2: 1 for the NUL, 1 for the char we replace */
767 delta += sizeof(xo_xml_lt) - 2;
769 delta += sizeof(xo_xml_gt) - 2;
771 delta += sizeof(xo_xml_amp) - 2;
772 else if (attr && *cp == '"')
773 delta += sizeof(xo_xml_quot) - 2;
776 if (delta == 0) /* Nothing to escape; bail */
779 if (!xo_buf_has_room(xbp, delta)) /* No room; bail, but don't append */
795 else if (attr && *cp == '"')
804 memcpy(ip, sp, slen);
806 } while (cp > ep && cp != ip);
812 xo_escape_json (xo_buffer_t *xbp, ssize_t len, xo_xff_flags_t flags UNUSED)
817 for (cp = xbp->xb_curp, ep = cp + len; cp < ep; cp++) {
818 if (*cp == '\\' || *cp == '"')
820 else if (*cp == '\n' || *cp == '\r')
824 if (delta == 0) /* Nothing to escape; bail */
827 if (!xo_buf_has_room(xbp, delta)) /* No room; bail, but don't append */
837 if (*cp == '\\' || *cp == '"') {
840 } else if (*cp == '\n') {
843 } else if (*cp == '\r') {
850 } while (cp > ep && cp != ip);
856 * PARAM-VALUE = UTF-8-STRING ; characters '"', '\' and
857 * ; ']' MUST be escaped.
860 xo_escape_sdparams (xo_buffer_t *xbp, ssize_t len, xo_xff_flags_t flags UNUSED)
865 for (cp = xbp->xb_curp, ep = cp + len; cp < ep; cp++) {
866 if (*cp == '\\' || *cp == '"' || *cp == ']')
870 if (delta == 0) /* Nothing to escape; bail */
873 if (!xo_buf_has_room(xbp, delta)) /* No room; bail, but don't append */
883 if (*cp == '\\' || *cp == '"' || *cp == ']') {
890 } while (cp > ep && cp != ip);
896 xo_buf_escape (xo_handle_t *xop, xo_buffer_t *xbp,
897 const char *str, ssize_t len, xo_xff_flags_t flags)
899 if (!xo_buf_has_room(xbp, len))
902 memcpy(xbp->xb_curp, str, len);
904 switch (xo_style(xop)) {
907 len = xo_escape_xml(xbp, len, flags);
911 len = xo_escape_json(xbp, len, flags);
914 case XO_STYLE_SDPARAMS:
915 len = xo_escape_sdparams(xbp, len, flags);
923 * Write the current contents of the data buffer using the handle's
927 xo_write (xo_handle_t *xop)
930 xo_buffer_t *xbp = &xop->xo_data;
932 if (xbp->xb_curp != xbp->xb_bufp) {
933 xo_buf_append(xbp, "", 1); /* Append ending NUL */
934 xo_anchor_clear(xop);
936 rc = xop->xo_write(xop->xo_opaque, xbp->xb_bufp);
937 xbp->xb_curp = xbp->xb_bufp;
940 /* Turn off the flags that don't survive across writes */
941 XOIF_CLEAR(xop, XOIF_UNITS_PENDING);
947 * Format arguments into our buffer. If a custom formatter has been set,
948 * we use that to do the work; otherwise we vsnprintf().
951 xo_vsnprintf (xo_handle_t *xop, xo_buffer_t *xbp, const char *fmt, va_list vap)
955 ssize_t left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
957 va_copy(va_local, vap);
959 if (xop->xo_formatter)
960 rc = xop->xo_formatter(xop, xbp->xb_curp, left, fmt, va_local);
962 rc = vsnprintf(xbp->xb_curp, left, fmt, va_local);
965 if (!xo_buf_has_room(xbp, rc)) {
971 * After we call vsnprintf(), the stage of vap is not defined.
972 * We need to copy it before we pass. Then we have to do our
973 * own logic below to move it along. This is because the
974 * implementation can have va_list be a pointer (bsd) or a
975 * structure (macosx) or anything in between.
978 va_end(va_local); /* Reset vap to the start */
979 va_copy(va_local, vap);
981 left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
982 if (xop->xo_formatter)
983 rc = xop->xo_formatter(xop, xbp->xb_curp, left, fmt, va_local);
985 rc = vsnprintf(xbp->xb_curp, left, fmt, va_local);
993 * Print some data through the handle.
996 xo_printf_v (xo_handle_t *xop, const char *fmt, va_list vap)
998 xo_buffer_t *xbp = &xop->xo_data;
999 ssize_t left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
1003 va_copy(va_local, vap);
1005 rc = vsnprintf(xbp->xb_curp, left, fmt, va_local);
1008 if (!xo_buf_has_room(xbp, rc)) {
1013 va_end(va_local); /* Reset vap to the start */
1014 va_copy(va_local, vap);
1016 left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
1017 rc = vsnprintf(xbp->xb_curp, left, fmt, va_local);
1029 xo_printf (xo_handle_t *xop, const char *fmt, ...)
1036 rc = xo_printf_v(xop, fmt, vap);
1043 * These next few function are make The Essential UTF-8 Ginsu Knife.
1044 * Identify an input and output character, and convert it.
1046 static uint8_t xo_utf8_data_bits[5] = { 0, 0x7f, 0x1f, 0x0f, 0x07 };
1047 static uint8_t xo_utf8_len_bits[5] = { 0, 0x00, 0xc0, 0xe0, 0xf0 };
1050 * If the byte has a high-bit set, it's UTF-8, not ASCII.
1053 xo_is_utf8 (char ch)
1059 * Look at the high bits of the first byte to determine the length
1060 * of the UTF-8 character.
1062 static inline ssize_t
1063 xo_utf8_to_wc_len (const char *buf)
1065 uint8_t bval = (uint8_t) *buf;
1068 if ((bval & 0x80) == 0x0)
1070 else if ((bval & 0xe0) == 0xc0)
1072 else if ((bval & 0xf0) == 0xe0)
1074 else if ((bval & 0xf8) == 0xf0)
1083 xo_buf_utf8_len (xo_handle_t *xop, const char *buf, ssize_t bufsiz)
1085 unsigned b = (unsigned char) *buf;
1088 len = xo_utf8_to_wc_len(buf);
1090 xo_failure(xop, "invalid UTF-8 data: %02hhx", b);
1095 xo_failure(xop, "invalid UTF-8 data (short): %02hhx (%d/%d)",
1100 for (i = 2; i < len; i++) {
1101 b = (unsigned char ) buf[i];
1102 if ((b & 0xc0) != 0x80) {
1103 xo_failure(xop, "invalid UTF-8 data (byte %d): %x", i, b);
1112 * Build a wide character from the input buffer; the number of
1113 * bits we pull off the first character is dependent on the length,
1114 * but we put 6 bits off all other bytes.
1116 static inline wchar_t
1117 xo_utf8_char (const char *buf, ssize_t len)
1119 /* Most common case: singleton byte */
1121 return (unsigned char) buf[0];
1125 const unsigned char *cp = (const unsigned char *) buf;
1127 wc = *cp & xo_utf8_data_bits[len];
1128 for (i = 1; i < len; i++) {
1129 wc <<= 6; /* Low six bits have data */
1131 if ((cp[i] & 0xc0) != 0x80)
1132 return (wchar_t) -1;
1139 * Determine the number of bytes needed to encode a wide character.
1142 xo_utf8_emit_len (wchar_t wc)
1146 if ((wc & ((1 << 7) - 1)) == wc) /* Simple case */
1148 else if ((wc & ((1 << 11) - 1)) == wc)
1150 else if ((wc & ((1 << 16) - 1)) == wc)
1152 else if ((wc & ((1 << 21) - 1)) == wc)
1155 len = -1; /* Invalid */
1161 * Emit a single wide character into the given buffer
1164 xo_utf8_emit_char (char *buf, ssize_t len, wchar_t wc)
1168 if (len == 1) { /* Simple case */
1173 /* Start with the low bits and insert them, six bits as a time */
1174 for (i = len - 1; i >= 0; i--) {
1175 buf[i] = 0x80 | (wc & 0x3f);
1176 wc >>= 6; /* Drop the low six bits */
1179 /* Finish off the first byte with the length bits */
1180 buf[0] &= xo_utf8_data_bits[len]; /* Clear out the length bits */
1181 buf[0] |= xo_utf8_len_bits[len]; /* Drop in new length bits */
1185 * Append a single UTF-8 character to a buffer, converting it to locale
1186 * encoding. Returns the number of columns consumed by that character,
1187 * as best we can determine it.
1190 xo_buf_append_locale_from_utf8 (xo_handle_t *xop, xo_buffer_t *xbp,
1191 const char *ibuf, ssize_t ilen)
1197 * Build our wide character from the input buffer; the number of
1198 * bits we pull off the first character is dependent on the length,
1199 * but we put 6 bits off all other bytes.
1201 wc = xo_utf8_char(ibuf, ilen);
1202 if (wc == (wchar_t) -1) {
1203 xo_failure(xop, "invalid UTF-8 byte sequence");
1207 if (XOF_ISSET(xop, XOF_NO_LOCALE)) {
1208 if (!xo_buf_has_room(xbp, ilen))
1211 memcpy(xbp->xb_curp, ibuf, ilen);
1212 xbp->xb_curp += ilen;
1215 if (!xo_buf_has_room(xbp, MB_LEN_MAX + 1))
1218 bzero(&xop->xo_mbstate, sizeof(xop->xo_mbstate));
1219 len = wcrtomb(xbp->xb_curp, wc, &xop->xo_mbstate);
1222 xo_failure(xop, "could not convert wide char: %lx",
1223 (unsigned long) wc);
1226 xbp->xb_curp += len;
1229 return xo_wcwidth(wc);
1233 * Append a UTF-8 string to a buffer, converting it into locale encoding
1236 xo_buf_append_locale (xo_handle_t *xop, xo_buffer_t *xbp,
1237 const char *cp, ssize_t len)
1239 const char *sp = cp, *ep = cp + len;
1240 ssize_t save_off = xbp->xb_bufp - xbp->xb_curp;
1244 for ( ; cp < ep; cp++) {
1245 if (!xo_is_utf8(*cp)) {
1251 * We're looking at a non-ascii UTF-8 character.
1252 * First we copy the previous data.
1253 * Then we need find the length and validate it.
1254 * Then we turn it into a wide string.
1255 * Then we turn it into a localized string.
1256 * Then we repeat. Isn't i18n fun?
1259 xo_buf_append(xbp, sp, cp - sp); /* Append previous data */
1261 slen = xo_buf_utf8_len(xop, cp, ep - cp);
1263 /* Bad data; back it all out */
1264 xbp->xb_curp = xbp->xb_bufp + save_off;
1268 cols += xo_buf_append_locale_from_utf8(xop, xbp, cp, slen);
1270 /* Next time through, we'll start at the next character */
1275 /* Update column values */
1276 if (XOF_ISSET(xop, XOF_COLUMNS))
1277 xop->xo_columns += cols;
1278 if (XOIF_ISSET(xop, XOIF_ANCHOR))
1279 xop->xo_anchor_columns += cols;
1281 /* Before we fall into the basic logic below, we need reset len */
1283 if (len != 0) /* Append trailing data */
1284 xo_buf_append(xbp, sp, len);
1288 * Append the given string to the given buffer, without escaping or
1289 * character set conversion. This is the straight copy to the data
1290 * buffer with no fanciness.
1293 xo_data_append (xo_handle_t *xop, const char *str, ssize_t len)
1295 xo_buf_append(&xop->xo_data, str, len);
1299 * Append the given string to the given buffer
1302 xo_data_escape (xo_handle_t *xop, const char *str, ssize_t len)
1304 xo_buf_escape(xop, &xop->xo_data, str, len, 0);
1307 #ifdef LIBXO_NO_RETAIN
1309 * Empty implementations of the retain logic
1313 xo_retain_clear_all (void)
1319 xo_retain_clear (const char *fmt UNUSED)
1324 xo_retain_add (const char *fmt UNUSED, xo_field_info_t *fields UNUSED,
1325 unsigned num_fields UNUSED)
1331 xo_retain_find (const char *fmt UNUSED, xo_field_info_t **valp UNUSED,
1332 unsigned *nump UNUSED)
1337 #else /* !LIBXO_NO_RETAIN */
1339 * Retain: We retain parsed field definitions to enhance performance,
1340 * especially inside loops. We depend on the caller treating the format
1341 * strings as immutable, so that we can retain pointers into them. We
1342 * hold the pointers in a hash table, so allow quick access. Retained
1343 * information is retained until xo_retain_clear is called.
1347 * xo_retain_entry_t holds information about one retained set of
1350 typedef struct xo_retain_entry_s {
1351 struct xo_retain_entry_s *xre_next; /* Pointer to next (older) entry */
1352 unsigned long xre_hits; /* Number of times we've hit */
1353 const char *xre_format; /* Pointer to format string */
1354 unsigned xre_num_fields; /* Number of fields saved */
1355 xo_field_info_t *xre_fields; /* Pointer to fields */
1356 } xo_retain_entry_t;
1359 * xo_retain_t holds a complete set of parsed fields as a hash table.
1361 #ifndef XO_RETAIN_SIZE
1362 #define XO_RETAIN_SIZE 6
1363 #endif /* XO_RETAIN_SIZE */
1364 #define RETAIN_HASH_SIZE (1<<XO_RETAIN_SIZE)
1366 typedef struct xo_retain_s {
1367 xo_retain_entry_t *xr_bucket[RETAIN_HASH_SIZE];
1370 static THREAD_LOCAL(xo_retain_t) xo_retain;
1371 static THREAD_LOCAL(unsigned) xo_retain_count;
1374 * Simple hash function based on Thomas Wang's paper. The original is
1375 * gone, but an archive is available on the Way Back Machine:
1377 * http://web.archive.org/web/20071223173210/\
1378 * http://www.concentric.net/~Ttwang/tech/inthash.htm
1380 * For our purposes, we can assume the low four bits are uninteresting
1381 * since any string less that 16 bytes wouldn't be worthy of
1382 * retaining. We toss the high bits also, since these bits are likely
1383 * to be common among constant format strings. We then run Wang's
1384 * algorithm, and cap the result at RETAIN_HASH_SIZE.
1387 xo_retain_hash (const char *fmt)
1389 volatile uintptr_t iptr = (uintptr_t) (const void *) fmt;
1391 /* Discard low four bits and high bits; they aren't interesting */
1392 uint32_t val = (uint32_t) ((iptr >> 4) & (((1 << 24) - 1)));
1394 val = (val ^ 61) ^ (val >> 16);
1395 val = val + (val << 3);
1396 val = val ^ (val >> 4);
1397 val = val * 0x3a8f05c5; /* My large prime number */
1398 val = val ^ (val >> 15);
1399 val &= RETAIN_HASH_SIZE - 1;
1405 * Walk all buckets, clearing all retained entries
1408 xo_retain_clear_all (void)
1411 xo_retain_entry_t *xrep, *next;
1413 for (i = 0; i < RETAIN_HASH_SIZE; i++) {
1414 for (xrep = xo_retain.xr_bucket[i]; xrep; xrep = next) {
1415 next = xrep->xre_next;
1418 xo_retain.xr_bucket[i] = NULL;
1420 xo_retain_count = 0;
1424 * Walk all buckets, clearing all retained entries
1427 xo_retain_clear (const char *fmt)
1429 xo_retain_entry_t **xrepp;
1430 unsigned hash = xo_retain_hash(fmt);
1432 for (xrepp = &xo_retain.xr_bucket[hash]; *xrepp;
1433 xrepp = &(*xrepp)->xre_next) {
1434 if ((*xrepp)->xre_format == fmt) {
1435 *xrepp = (*xrepp)->xre_next;
1436 xo_retain_count -= 1;
1443 * Search the hash for an entry matching 'fmt'; return it's fields.
1446 xo_retain_find (const char *fmt, xo_field_info_t **valp, unsigned *nump)
1448 if (xo_retain_count == 0)
1451 unsigned hash = xo_retain_hash(fmt);
1452 xo_retain_entry_t *xrep;
1454 for (xrep = xo_retain.xr_bucket[hash]; xrep != NULL;
1455 xrep = xrep->xre_next) {
1456 if (xrep->xre_format == fmt) {
1457 *valp = xrep->xre_fields;
1458 *nump = xrep->xre_num_fields;
1459 xrep->xre_hits += 1;
1468 xo_retain_add (const char *fmt, xo_field_info_t *fields, unsigned num_fields)
1470 unsigned hash = xo_retain_hash(fmt);
1471 xo_retain_entry_t *xrep;
1472 ssize_t sz = sizeof(*xrep) + (num_fields + 1) * sizeof(*fields);
1473 xo_field_info_t *xfip;
1475 xrep = xo_realloc(NULL, sz);
1479 xfip = (xo_field_info_t *) &xrep[1];
1480 memcpy(xfip, fields, num_fields * sizeof(*fields));
1482 bzero(xrep, sizeof(*xrep));
1484 xrep->xre_format = fmt;
1485 xrep->xre_fields = xfip;
1486 xrep->xre_num_fields = num_fields;
1488 /* Record the field info in the retain bucket */
1489 xrep->xre_next = xo_retain.xr_bucket[hash];
1490 xo_retain.xr_bucket[hash] = xrep;
1491 xo_retain_count += 1;
1494 #endif /* !LIBXO_NO_RETAIN */
1497 * Generate a warning. Normally, this is a text message written to
1498 * standard error. If the XOF_WARN_XML flag is set, then we generate
1499 * XMLified content on standard output.
1502 xo_warn_hcv (xo_handle_t *xop, int code, int check_warn,
1503 const char *fmt, va_list vap)
1505 xop = xo_default(xop);
1506 if (check_warn && !XOF_ISSET(xop, XOF_WARN))
1512 ssize_t len = strlen(fmt);
1513 ssize_t plen = xo_program ? strlen(xo_program) : 0;
1514 char *newfmt = alloca(len + 1 + plen + 2); /* NUL, and ": " */
1517 memcpy(newfmt, xo_program, plen);
1518 newfmt[plen++] = ':';
1519 newfmt[plen++] = ' ';
1521 memcpy(newfmt + plen, fmt, len);
1522 newfmt[len + plen] = '\0';
1524 if (XOF_ISSET(xop, XOF_WARN_XML)) {
1525 static char err_open[] = "<error>";
1526 static char err_close[] = "</error>";
1527 static char msg_open[] = "<message>";
1528 static char msg_close[] = "</message>";
1530 xo_buffer_t *xbp = &xop->xo_data;
1532 xo_buf_append(xbp, err_open, sizeof(err_open) - 1);
1533 xo_buf_append(xbp, msg_open, sizeof(msg_open) - 1);
1536 va_copy(va_local, vap);
1538 ssize_t left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
1539 ssize_t rc = vsnprintf(xbp->xb_curp, left, newfmt, vap);
1541 if (!xo_buf_has_room(xbp, rc)) {
1546 va_end(vap); /* Reset vap to the start */
1547 va_copy(vap, va_local);
1549 left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
1550 rc = vsnprintf(xbp->xb_curp, left, fmt, vap);
1554 rc = xo_escape_xml(xbp, rc, 1);
1557 xo_buf_append(xbp, msg_close, sizeof(msg_close) - 1);
1558 xo_buf_append(xbp, err_close, sizeof(err_close) - 1);
1561 const char *msg = strerror(code);
1563 xo_buf_append(xbp, ": ", 2);
1564 xo_buf_append(xbp, msg, strlen(msg));
1568 xo_buf_append(xbp, "\n", 1); /* Append newline and NUL to string */
1569 (void) xo_write(xop);
1572 vfprintf(stderr, newfmt, vap);
1574 const char *msg = strerror(code);
1576 fprintf(stderr, ": %s", msg);
1578 fprintf(stderr, "\n");
1583 xo_warn_hc (xo_handle_t *xop, int code, const char *fmt, ...)
1588 xo_warn_hcv(xop, code, 0, fmt, vap);
1593 xo_warn_c (int code, const char *fmt, ...)
1598 xo_warn_hcv(NULL, code, 0, fmt, vap);
1603 xo_warn (const char *fmt, ...)
1609 xo_warn_hcv(NULL, code, 0, fmt, vap);
1614 xo_warnx (const char *fmt, ...)
1619 xo_warn_hcv(NULL, -1, 0, fmt, vap);
1624 xo_err (int eval, const char *fmt, ...)
1630 xo_warn_hcv(NULL, code, 0, fmt, vap);
1637 xo_errx (int eval, const char *fmt, ...)
1642 xo_warn_hcv(NULL, -1, 0, fmt, vap);
1649 xo_errc (int eval, int code, const char *fmt, ...)
1654 xo_warn_hcv(NULL, code, 0, fmt, vap);
1661 * Generate a warning. Normally, this is a text message written to
1662 * standard error. If the XOF_WARN_XML flag is set, then we generate
1663 * XMLified content on standard output.
1666 xo_message_hcv (xo_handle_t *xop, int code, const char *fmt, va_list vap)
1668 static char msg_open[] = "<message>";
1669 static char msg_close[] = "</message>";
1674 xop = xo_default(xop);
1676 if (fmt == NULL || *fmt == '\0')
1679 int need_nl = (fmt[strlen(fmt) - 1] != '\n');
1681 switch (xo_style(xop)) {
1683 xbp = &xop->xo_data;
1684 if (XOF_ISSET(xop, XOF_PRETTY))
1685 xo_buf_indent(xop, xop->xo_indent_by);
1686 xo_buf_append(xbp, msg_open, sizeof(msg_open) - 1);
1688 va_copy(va_local, vap);
1690 ssize_t left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
1691 rc = vsnprintf(xbp->xb_curp, left, fmt, vap);
1693 if (!xo_buf_has_room(xbp, rc)) {
1698 va_end(vap); /* Reset vap to the start */
1699 va_copy(vap, va_local);
1701 left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
1702 rc = vsnprintf(xbp->xb_curp, left, fmt, vap);
1706 rc = xo_escape_xml(xbp, rc, 0);
1709 if (need_nl && code > 0) {
1710 const char *msg = strerror(code);
1712 xo_buf_append(xbp, ": ", 2);
1713 xo_buf_append(xbp, msg, strlen(msg));
1718 xo_buf_append(xbp, "\n", 1); /* Append newline and NUL to string */
1720 xo_buf_append(xbp, msg_close, sizeof(msg_close) - 1);
1722 if (XOF_ISSET(xop, XOF_PRETTY))
1723 xo_buf_append(xbp, "\n", 1); /* Append newline and NUL to string */
1725 (void) xo_write(xop);
1730 char buf[BUFSIZ], *bp = buf, *cp;
1731 ssize_t bufsiz = sizeof(buf);
1734 va_copy(va_local, vap);
1736 rc = vsnprintf(bp, bufsiz, fmt, va_local);
1738 bufsiz = rc + BUFSIZ;
1739 bp = alloca(bufsiz);
1741 va_copy(va_local, vap);
1742 rc = vsnprintf(bp, bufsiz, fmt, va_local);
1748 rc2 = snprintf(cp, bufsiz - rc, "%s%s\n",
1749 (code > 0) ? ": " : "",
1750 (code > 0) ? strerror(code) : "");
1755 xo_buf_append_div(xop, "message", 0, NULL, 0, bp, rc, NULL, 0);
1760 case XO_STYLE_SDPARAMS:
1761 case XO_STYLE_ENCODER:
1762 /* No means of representing messages */
1766 rc = xo_printf_v(xop, fmt, vap);
1768 * XXX need to handle UTF-8 widths
1771 if (XOF_ISSET(xop, XOF_COLUMNS))
1772 xop->xo_columns += rc;
1773 if (XOIF_ISSET(xop, XOIF_ANCHOR))
1774 xop->xo_anchor_columns += rc;
1777 if (need_nl && code > 0) {
1778 const char *msg = strerror(code);
1780 xo_printf(xop, ": %s", msg);
1784 xo_printf(xop, "\n");
1789 switch (xo_style(xop)) {
1791 if (XOIF_ISSET(xop, XOIF_DIV_OPEN)) {
1792 static char div_close[] = "</div>";
1793 XOIF_CLEAR(xop, XOIF_DIV_OPEN);
1794 xo_data_append(xop, div_close, sizeof(div_close) - 1);
1796 if (XOF_ISSET(xop, XOF_PRETTY))
1797 xo_data_append(xop, "\n", 1);
1802 (void) xo_flush_h(xop);
1806 xo_message_hc (xo_handle_t *xop, int code, const char *fmt, ...)
1811 xo_message_hcv(xop, code, fmt, vap);
1816 xo_message_c (int code, const char *fmt, ...)
1821 xo_message_hcv(NULL, code, fmt, vap);
1826 xo_message_e (const char *fmt, ...)
1832 xo_message_hcv(NULL, code, fmt, vap);
1837 xo_message (const char *fmt, ...)
1842 xo_message_hcv(NULL, 0, fmt, vap);
1847 xo_failure (xo_handle_t *xop, const char *fmt, ...)
1849 if (!XOF_ISSET(xop, XOF_WARN))
1855 xo_warn_hcv(xop, -1, 1, fmt, vap);
1860 * Create a handle for use by later libxo functions.
1862 * Note: normal use of libxo does not require a distinct handle, since
1863 * the default handle (used when NULL is passed) generates text on stdout.
1865 * @param style Style of output desired (XO_STYLE_* value)
1866 * @param flags Set of XOF_* flags in use with this handle
1867 * @return Newly allocated handle
1871 xo_create (xo_style_t style, xo_xof_flags_t flags)
1873 xo_handle_t *xop = xo_realloc(NULL, sizeof(*xop));
1876 bzero(xop, sizeof(*xop));
1878 xop->xo_style = style;
1879 XOF_SET(xop, flags);
1880 xo_init_handle(xop);
1881 xop->xo_style = style; /* Reset style (see LIBXO_OPTIONS) */
1888 * Create a handle that will write to the given file. Use
1889 * the XOF_CLOSE_FP flag to have the file closed on xo_destroy().
1891 * @param fp FILE pointer to use
1892 * @param style Style of output desired (XO_STYLE_* value)
1893 * @param flags Set of XOF_* flags to use with this handle
1894 * @return Newly allocated handle
1898 xo_create_to_file (FILE *fp, xo_style_t style, xo_xof_flags_t flags)
1900 xo_handle_t *xop = xo_create(style, flags);
1903 xop->xo_opaque = fp;
1904 xop->xo_write = xo_write_to_file;
1905 xop->xo_close = xo_close_file;
1906 xop->xo_flush = xo_flush_file;
1913 * Set the default handler to output to a file.
1915 * @param xop libxo handle
1916 * @param fp FILE pointer to use
1917 * @return 0 on success, non-zero on failure
1920 xo_set_file_h (xo_handle_t *xop, FILE *fp)
1922 xop = xo_default(xop);
1925 xo_failure(xop, "xo_set_file: NULL fp");
1929 xop->xo_opaque = fp;
1930 xop->xo_write = xo_write_to_file;
1931 xop->xo_close = xo_close_file;
1932 xop->xo_flush = xo_flush_file;
1938 * Set the default handler to output to a file.
1940 * @param fp FILE pointer to use
1941 * @return 0 on success, non-zero on failure
1944 xo_set_file (FILE *fp)
1946 return xo_set_file_h(NULL, fp);
1950 * Release any resources held by the handle.
1952 * @param xop XO handle to alter (or NULL for default handle)
1955 xo_destroy (xo_handle_t *xop_arg)
1957 xo_handle_t *xop = xo_default(xop_arg);
1961 if (xop->xo_close && XOF_ISSET(xop, XOF_CLOSE_FP))
1962 xop->xo_close(xop->xo_opaque);
1964 xo_free(xop->xo_stack);
1965 xo_buf_cleanup(&xop->xo_data);
1966 xo_buf_cleanup(&xop->xo_fmt);
1967 xo_buf_cleanup(&xop->xo_predicate);
1968 xo_buf_cleanup(&xop->xo_attrs);
1969 xo_buf_cleanup(&xop->xo_color_buf);
1971 if (xop->xo_version)
1972 xo_free(xop->xo_version);
1974 if (xop_arg == NULL) {
1975 bzero(&xo_default_handle, sizeof(xo_default_handle));
1976 xo_default_inited = 0;
1982 * Record a new output style to use for the given handle (or default if
1983 * handle is NULL). This output style will be used for any future output.
1985 * @param xop XO handle to alter (or NULL for default handle)
1986 * @param style new output style (XO_STYLE_*)
1989 xo_set_style (xo_handle_t *xop, xo_style_t style)
1991 xop = xo_default(xop);
1992 xop->xo_style = style;
1996 * Return the current style of a handle
1998 * @param xop XO handle to access
1999 * @return The handle's current style
2002 xo_get_style (xo_handle_t *xop)
2004 xop = xo_default(xop);
2005 return xo_style(xop);
2009 * Return the XO_STYLE_* value matching a given name
2011 * @param name String name of a style
2012 * @return XO_STYLE_* value
2015 xo_name_to_style (const char *name)
2017 if (strcmp(name, "xml") == 0)
2018 return XO_STYLE_XML;
2019 else if (strcmp(name, "json") == 0)
2020 return XO_STYLE_JSON;
2021 else if (strcmp(name, "encoder") == 0)
2022 return XO_STYLE_ENCODER;
2023 else if (strcmp(name, "text") == 0)
2024 return XO_STYLE_TEXT;
2025 else if (strcmp(name, "html") == 0)
2026 return XO_STYLE_HTML;
2027 else if (strcmp(name, "sdparams") == 0)
2028 return XO_STYLE_SDPARAMS;
2034 * Indicate if the style is an "encoding" one as opposed to a "display" one.
2037 xo_style_is_encoding (xo_handle_t *xop)
2039 if (xo_style(xop) == XO_STYLE_JSON
2040 || xo_style(xop) == XO_STYLE_XML
2041 || xo_style(xop) == XO_STYLE_SDPARAMS
2042 || xo_style(xop) == XO_STYLE_ENCODER)
2047 /* Simple name-value mapping */
2048 typedef struct xo_mapping_s {
2049 xo_xff_flags_t xm_value; /* Flag value */
2050 const char *xm_name; /* String name */
2053 static xo_xff_flags_t
2054 xo_name_lookup (xo_mapping_t *map, const char *value, ssize_t len)
2060 len = strlen(value);
2062 while (isspace((int) *value)) {
2067 while (isspace((int) value[len]))
2073 for ( ; map->xm_name; map++)
2074 if (strncmp(map->xm_name, value, len) == 0)
2075 return map->xm_value;
2080 #ifdef NOT_NEEDED_YET
2082 xo_value_lookup (xo_mapping_t *map, xo_xff_flags_t value)
2087 for ( ; map->xm_name; map++)
2088 if (map->xm_value == value)
2089 return map->xm_name;
2093 #endif /* NOT_NEEDED_YET */
2095 static xo_mapping_t xo_xof_names[] = {
2096 { XOF_COLOR_ALLOWED, "color" },
2097 { XOF_COLOR, "color-force" },
2098 { XOF_COLUMNS, "columns" },
2099 { XOF_DTRT, "dtrt" },
2100 { XOF_FLUSH, "flush" },
2101 { XOF_FLUSH_LINE, "flush-line" },
2102 { XOF_IGNORE_CLOSE, "ignore-close" },
2103 { XOF_INFO, "info" },
2104 { XOF_KEYS, "keys" },
2105 { XOF_LOG_GETTEXT, "log-gettext" },
2106 { XOF_LOG_SYSLOG, "log-syslog" },
2107 { XOF_NO_HUMANIZE, "no-humanize" },
2108 { XOF_NO_LOCALE, "no-locale" },
2109 { XOF_RETAIN_NONE, "no-retain" },
2110 { XOF_NO_TOP, "no-top" },
2111 { XOF_NOT_FIRST, "not-first" },
2112 { XOF_PRETTY, "pretty" },
2113 { XOF_RETAIN_ALL, "retain" },
2114 { XOF_UNDERSCORES, "underscores" },
2115 { XOF_UNITS, "units" },
2116 { XOF_WARN, "warn" },
2117 { XOF_WARN_XML, "warn-xml" },
2118 { XOF_XPATH, "xpath" },
2122 /* Options available via the environment variable ($LIBXO_OPTIONS) */
2123 static xo_mapping_t xo_xof_simple_names[] = {
2124 { XOF_COLOR_ALLOWED, "color" },
2125 { XOF_FLUSH, "flush" },
2126 { XOF_FLUSH_LINE, "flush-line" },
2127 { XOF_NO_HUMANIZE, "no-humanize" },
2128 { XOF_NO_LOCALE, "no-locale" },
2129 { XOF_RETAIN_NONE, "no-retain" },
2130 { XOF_PRETTY, "pretty" },
2131 { XOF_RETAIN_ALL, "retain" },
2132 { XOF_UNDERSCORES, "underscores" },
2133 { XOF_WARN, "warn" },
2138 * Convert string name to XOF_* flag value.
2139 * Not all are useful. Or safe. Or sane.
2142 xo_name_to_flag (const char *name)
2144 return (unsigned) xo_name_lookup(xo_xof_names, name, -1);
2148 * Set the style of an libxo handle based on a string name
2150 * @param xop XO handle
2151 * @param name String value of name
2152 * @return 0 on success, non-zero on failure
2155 xo_set_style_name (xo_handle_t *xop, const char *name)
2160 int style = xo_name_to_style(name);
2164 xo_set_style(xop, style);
2169 * Fill in the color map, based on the input string; currently unimplemented
2170 * Look for something like "colors=red/blue+green/yellow" as fg/bg pairs.
2173 xo_set_color_map (xo_handle_t *xop, char *value)
2175 #ifdef LIBXO_TEXT_ONLY
2177 #endif /* LIBXO_TEXT_ONLY */
2179 char *cp, *ep, *vp, *np;
2180 ssize_t len = value ? strlen(value) + 1 : 0;
2181 int num = 1, fg, bg;
2183 for (cp = value, ep = cp + len - 1; cp && *cp && cp < ep; cp = np) {
2184 np = strchr(cp, '+');
2188 vp = strchr(cp, '/');
2192 fg = *cp ? xo_color_find(cp) : -1;
2193 bg = (vp && *vp) ? xo_color_find(vp) : -1;
2195 xop->xo_color_map_fg[num] = (fg < 0) ? num : fg;
2196 xop->xo_color_map_bg[num] = (bg < 0) ? num : bg;
2197 if (++num > XO_NUM_COLORS)
2201 /* If no color initialization happened, then we don't need the map */
2203 XOF_SET(xop, XOF_COLOR_MAP);
2205 XOF_CLEAR(xop, XOF_COLOR_MAP);
2207 /* Fill in the rest of the colors with the defaults */
2208 for ( ; num < XO_NUM_COLORS; num++)
2209 xop->xo_color_map_fg[num] = xop->xo_color_map_bg[num] = num;
2213 xo_set_options_simple (xo_handle_t *xop, const char *input)
2215 xo_xof_flags_t new_flag;
2216 char *cp, *ep, *vp, *np, *bp;
2217 ssize_t len = strlen(input) + 1;
2220 memcpy(bp, input, len);
2222 for (cp = bp, ep = cp + len - 1; cp && cp < ep; cp = np) {
2223 np = strchr(cp, ',');
2227 vp = strchr(cp, '=');
2231 if (strcmp("colors", cp) == 0) {
2232 xo_set_color_map(xop, vp);
2236 new_flag = xo_name_lookup(xo_xof_simple_names, cp, -1);
2237 if (new_flag != 0) {
2238 XOF_SET(xop, new_flag);
2239 } else if (strcmp(cp, "no-color") == 0) {
2240 XOF_CLEAR(xop, XOF_COLOR_ALLOWED);
2242 xo_failure(xop, "unknown simple option: %s", cp);
2251 * Set the options for a handle using a string of options
2252 * passed in. The input is a comma-separated set of names
2253 * and optional values: "xml,pretty,indent=4"
2255 * @param xop XO handle
2256 * @param input Comma-separated set of option values
2257 * @return 0 on success, non-zero on failure
2260 xo_set_options (xo_handle_t *xop, const char *input)
2262 char *cp, *ep, *vp, *np, *bp;
2263 int style = -1, new_style, rc = 0;
2265 xo_xof_flags_t new_flag;
2270 xop = xo_default(xop);
2272 #ifdef LIBXO_COLOR_ON_BY_DEFAULT
2273 /* If the installer used --enable-color-on-by-default, then we allow it */
2274 XOF_SET(xop, XOF_COLOR_ALLOWED);
2275 #endif /* LIBXO_COLOR_ON_BY_DEFAULT */
2278 * We support a simpler, old-school style of giving option
2279 * also, using a single character for each option. It's
2280 * ideal for lazy people, such as myself.
2282 if (*input == ':') {
2285 for (input++ ; *input; input++) {
2288 XOF_SET(xop, XOF_COLOR_ALLOWED);
2292 XOF_SET(xop, XOF_FLUSH);
2296 XOF_SET(xop, XOF_FLUSH_LINE);
2300 XOF_SET(xop, XOF_LOG_GETTEXT);
2304 xop->xo_style = XO_STYLE_HTML;
2308 XOF_SET(xop, XOF_INFO);
2312 sz = strspn(input + 1, "0123456789");
2314 xop->xo_indent_by = atoi(input + 1);
2315 input += sz - 1; /* Skip value */
2320 xop->xo_style = XO_STYLE_JSON;
2324 XOF_SET(xop, XOF_KEYS);
2328 XOF_SET(xop, XOF_NO_HUMANIZE);
2332 XOF_SET(xop, XOF_PRETTY);
2336 xop->xo_style = XO_STYLE_TEXT;
2340 XOF_SET(xop, XOF_UNITS);
2344 XOF_SET(xop, XOF_UNDERSCORES);
2348 XOF_SET(xop, XOF_WARN);
2352 xop->xo_style = XO_STYLE_XML;
2356 XOF_SET(xop, XOF_XPATH);
2363 len = strlen(input) + 1;
2365 memcpy(bp, input, len);
2367 for (cp = bp, ep = cp + len - 1; cp && cp < ep; cp = np) {
2368 np = strchr(cp, ',');
2372 vp = strchr(cp, '=');
2376 if (strcmp("colors", cp) == 0) {
2377 xo_set_color_map(xop, vp);
2382 * For options, we don't allow "encoder" since we want to
2383 * handle it explicitly below as "encoder=xxx".
2385 new_style = xo_name_to_style(cp);
2386 if (new_style >= 0 && new_style != XO_STYLE_ENCODER) {
2388 xo_warnx("ignoring multiple styles: '%s'", cp);
2392 new_flag = xo_name_to_flag(cp);
2394 XOF_SET(xop, new_flag);
2395 else if (strcmp(cp, "no-color") == 0)
2396 XOF_CLEAR(xop, XOF_COLOR_ALLOWED);
2397 else if (strcmp(cp, "indent") == 0) {
2399 xop->xo_indent_by = atoi(vp);
2401 xo_failure(xop, "missing value for indent option");
2402 } else if (strcmp(cp, "encoder") == 0) {
2404 xo_failure(xop, "missing value for encoder option");
2406 if (xo_encoder_init(xop, vp)) {
2407 xo_failure(xop, "encoder not found: %s", vp);
2413 xo_warnx("unknown libxo option value: '%s'", cp);
2420 xop->xo_style= style;
2426 * Set one or more flags for a given handle (or default if handle is NULL).
2427 * These flags will affect future output.
2429 * @param xop XO handle to alter (or NULL for default handle)
2430 * @param flags Flags to be set (XOF_*)
2433 xo_set_flags (xo_handle_t *xop, xo_xof_flags_t flags)
2435 xop = xo_default(xop);
2437 XOF_SET(xop, flags);
2441 * Accessor to return the current set of flags for a handle
2442 * @param xop XO handle
2443 * @return Current set of flags
2446 xo_get_flags (xo_handle_t *xop)
2448 xop = xo_default(xop);
2450 return xop->xo_flags;
2454 * strndup with a twist: len < 0 means len = strlen(str)
2457 xo_strndup (const char *str, ssize_t len)
2462 char *cp = xo_realloc(NULL, len + 1);
2464 memcpy(cp, str, len);
2472 * Record a leading prefix for the XPath we generate. This allows the
2473 * generated data to be placed within an XML hierarchy but still have
2474 * accurate XPath expressions.
2476 * @param xop XO handle to alter (or NULL for default handle)
2477 * @param path The XPath expression
2480 xo_set_leading_xpath (xo_handle_t *xop, const char *path)
2482 xop = xo_default(xop);
2484 if (xop->xo_leading_xpath) {
2485 xo_free(xop->xo_leading_xpath);
2486 xop->xo_leading_xpath = NULL;
2492 xop->xo_leading_xpath = xo_strndup(path, -1);
2496 * Record the info data for a set of tags
2498 * @param xop XO handle to alter (or NULL for default handle)
2499 * @param info Info data (xo_info_t) to be recorded (or NULL) (MUST BE SORTED)
2500 * @pararm count Number of entries in info (or -1 to count them ourselves)
2503 xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count)
2505 xop = xo_default(xop);
2507 if (count < 0 && infop) {
2510 for (xip = infop, count = 0; xip->xi_name; xip++, count++)
2514 xop->xo_info = infop;
2515 xop->xo_info_count = count;
2519 * Set the formatter callback for a handle. The callback should
2520 * return a newly formatting contents of a formatting instruction,
2521 * meaning the bits inside the braces.
2524 xo_set_formatter (xo_handle_t *xop, xo_formatter_t func,
2525 xo_checkpointer_t cfunc)
2527 xop = xo_default(xop);
2529 xop->xo_formatter = func;
2530 xop->xo_checkpointer = cfunc;
2534 * Clear one or more flags for a given handle (or default if handle is NULL).
2535 * These flags will affect future output.
2537 * @param xop XO handle to alter (or NULL for default handle)
2538 * @param flags Flags to be cleared (XOF_*)
2541 xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags)
2543 xop = xo_default(xop);
2545 XOF_CLEAR(xop, flags);
2549 xo_state_name (xo_state_t state)
2551 static const char *names[] = {
2569 if (state < (sizeof(names) / sizeof(names[0])))
2570 return names[state];
2576 xo_line_ensure_open (xo_handle_t *xop, xo_xff_flags_t flags UNUSED)
2578 static char div_open[] = "<div class=\"line\">";
2579 static char div_open_blank[] = "<div class=\"blank-line\">";
2581 if (XOIF_ISSET(xop, XOIF_DIV_OPEN))
2584 if (xo_style(xop) != XO_STYLE_HTML)
2587 XOIF_SET(xop, XOIF_DIV_OPEN);
2588 if (flags & XFF_BLANK_LINE)
2589 xo_data_append(xop, div_open_blank, sizeof(div_open_blank) - 1);
2591 xo_data_append(xop, div_open, sizeof(div_open) - 1);
2593 if (XOF_ISSET(xop, XOF_PRETTY))
2594 xo_data_append(xop, "\n", 1);
2598 xo_line_close (xo_handle_t *xop)
2600 static char div_close[] = "</div>";
2602 switch (xo_style(xop)) {
2604 if (!XOIF_ISSET(xop, XOIF_DIV_OPEN))
2605 xo_line_ensure_open(xop, 0);
2607 XOIF_CLEAR(xop, XOIF_DIV_OPEN);
2608 xo_data_append(xop, div_close, sizeof(div_close) - 1);
2610 if (XOF_ISSET(xop, XOF_PRETTY))
2611 xo_data_append(xop, "\n", 1);
2615 xo_data_append(xop, "\n", 1);
2621 xo_info_compare (const void *key, const void *data)
2623 const char *name = key;
2624 const xo_info_t *xip = data;
2626 return strcmp(name, xip->xi_name);
2631 xo_info_find (xo_handle_t *xop, const char *name, ssize_t nlen)
2634 char *cp = alloca(nlen + 1); /* Need local copy for NUL termination */
2636 memcpy(cp, name, nlen);
2639 xip = bsearch(cp, xop->xo_info, xop->xo_info_count,
2640 sizeof(xop->xo_info[0]), xo_info_compare);
2644 #define CONVERT(_have, _need) (((_have) << 8) | (_need))
2647 * Check to see that the conversion is safe and sane.
2650 xo_check_conversion (xo_handle_t *xop, int have_enc, int need_enc)
2652 switch (CONVERT(have_enc, need_enc)) {
2653 case CONVERT(XF_ENC_UTF8, XF_ENC_UTF8):
2654 case CONVERT(XF_ENC_UTF8, XF_ENC_LOCALE):
2655 case CONVERT(XF_ENC_WIDE, XF_ENC_UTF8):
2656 case CONVERT(XF_ENC_WIDE, XF_ENC_LOCALE):
2657 case CONVERT(XF_ENC_LOCALE, XF_ENC_LOCALE):
2658 case CONVERT(XF_ENC_LOCALE, XF_ENC_UTF8):
2662 xo_failure(xop, "invalid conversion (%c:%c)", have_enc, need_enc);
2668 xo_format_string_direct (xo_handle_t *xop, xo_buffer_t *xbp,
2669 xo_xff_flags_t flags,
2670 const wchar_t *wcp, const char *cp,
2671 ssize_t len, int max,
2672 int need_enc, int have_enc)
2678 int attr = XOF_BIT_ISSET(flags, XFF_ATTR);
2681 if (len > 0 && !xo_buf_has_room(xbp, len))
2691 if ((flags & XFF_UNESCAPE) && (*cp == '\\' || *cp == '%')) {
2697 if (wcp && *wcp == L'\0')
2703 case XF_ENC_WIDE: /* Wide character */
2708 case XF_ENC_UTF8: /* UTF-8 */
2709 ilen = xo_utf8_to_wc_len(cp);
2711 xo_failure(xop, "invalid UTF-8 character: %02hhx", *cp);
2712 return -1; /* Can't continue; we can't find the end */
2715 if (len > 0 && len < ilen) {
2716 len = 0; /* Break out of the loop */
2720 wc = xo_utf8_char(cp, ilen);
2721 if (wc == (wchar_t) -1) {
2722 xo_failure(xop, "invalid UTF-8 character: %02hhx/%d",
2724 return -1; /* Can't continue; we can't find the end */
2729 case XF_ENC_LOCALE: /* Native locale */
2730 ilen = (len > 0) ? len : MB_LEN_MAX;
2731 ilen = mbrtowc(&wc, cp, ilen, &xop->xo_mbstate);
2732 if (ilen < 0) { /* Invalid data; skip */
2733 xo_failure(xop, "invalid mbs char: %02hhx", *cp);
2738 if (ilen == 0) { /* Hit a wide NUL character */
2747 /* Reduce len, but not below zero */
2755 * Find the width-in-columns of this character, which must be done
2756 * in wide characters, since we lack a mbswidth() function. If
2759 width = xo_wcwidth(wc);
2761 width = iswcntrl(wc) ? 0 : 1;
2763 if (xo_style(xop) == XO_STYLE_TEXT || xo_style(xop) == XO_STYLE_HTML) {
2764 if (max > 0 && cols + width > max)
2771 /* Output in UTF-8 needs to be escaped, based on the style */
2772 switch (xo_style(xop)) {
2781 else if (attr && wc == '"')
2786 ssize_t slen = strlen(sp);
2787 if (!xo_buf_has_room(xbp, slen - 1))
2790 memcpy(xbp->xb_curp, sp, slen);
2791 xbp->xb_curp += slen;
2792 goto done_with_encoding; /* Need multi-level 'break' */
2795 if (wc != '\\' && wc != '"' && wc != '\n' && wc != '\r')
2798 if (!xo_buf_has_room(xbp, 2))
2801 *xbp->xb_curp++ = '\\';
2804 else if (wc == '\r')
2806 else wc = wc & 0x7f;
2808 *xbp->xb_curp++ = wc;
2809 goto done_with_encoding;
2811 case XO_STYLE_SDPARAMS:
2812 if (wc != '\\' && wc != '"' && wc != ']')
2815 if (!xo_buf_has_room(xbp, 2))
2818 *xbp->xb_curp++ = '\\';
2820 *xbp->xb_curp++ = wc;
2821 goto done_with_encoding;
2824 olen = xo_utf8_emit_len(wc);
2826 xo_failure(xop, "ignoring bad length");
2830 if (!xo_buf_has_room(xbp, olen))
2833 xo_utf8_emit_char(xbp->xb_curp, olen, wc);
2834 xbp->xb_curp += olen;
2838 if (!xo_buf_has_room(xbp, MB_LEN_MAX + 1))
2841 olen = wcrtomb(xbp->xb_curp, wc, &xop->xo_mbstate);
2843 xo_failure(xop, "could not convert wide char: %lx",
2844 (unsigned long) wc);
2846 *xbp->xb_curp++ = '?';
2848 xbp->xb_curp += olen;
2860 xo_needed_encoding (xo_handle_t *xop)
2862 if (XOF_ISSET(xop, XOF_UTF8)) /* Check the override flag */
2865 if (xo_style(xop) == XO_STYLE_TEXT) /* Text means locale */
2866 return XF_ENC_LOCALE;
2868 return XF_ENC_UTF8; /* Otherwise, we love UTF-8 */
2872 xo_format_string (xo_handle_t *xop, xo_buffer_t *xbp, xo_xff_flags_t flags,
2875 static char null[] = "(null)";
2876 static char null_no_quotes[] = "null";
2879 wchar_t *wcp = NULL;
2881 ssize_t cols = 0, rc = 0;
2882 ssize_t off = xbp->xb_curp - xbp->xb_bufp, off2;
2883 int need_enc = xo_needed_encoding(xop);
2885 if (xo_check_conversion(xop, xfp->xf_enc, need_enc))
2888 len = xfp->xf_width[XF_WIDTH_SIZE];
2890 if (xfp->xf_fc == 'm') {
2891 cp = strerror(xop->xo_errno);
2893 len = cp ? strlen(cp) : 0;
2896 } else if (xfp->xf_enc == XF_ENC_WIDE) {
2897 wcp = va_arg(xop->xo_vap, wchar_t *);
2902 * Dont' deref NULL; use the traditional "(null)" instead
2903 * of the more accurate "who's been a naughty boy, then?".
2907 len = sizeof(null) - 1;
2911 cp = va_arg(xop->xo_vap, char *); /* UTF-8 or native */
2917 /* Echo "Dont' deref NULL" logic */
2919 if ((flags & XFF_NOQUOTE) && xo_style_is_encoding(xop)) {
2920 cp = null_no_quotes;
2921 len = sizeof(null_no_quotes) - 1;
2924 len = sizeof(null) - 1;
2929 * Optimize the most common case, which is "%s". We just
2930 * need to copy the complete string to the output buffer.
2932 if (xfp->xf_enc == need_enc
2933 && xfp->xf_width[XF_WIDTH_MIN] < 0
2934 && xfp->xf_width[XF_WIDTH_SIZE] < 0
2935 && xfp->xf_width[XF_WIDTH_MAX] < 0
2936 && !(XOIF_ISSET(xop, XOIF_ANCHOR)
2937 || XOF_ISSET(xop, XOF_COLUMNS))) {
2939 xo_buf_escape(xop, xbp, cp, len, flags);
2942 * Our caller expects xb_curp left untouched, so we have
2943 * to reset it and return the number of bytes written to
2946 off2 = xbp->xb_curp - xbp->xb_bufp;
2948 xbp->xb_curp = xbp->xb_bufp + off;
2954 cols = xo_format_string_direct(xop, xbp, flags, wcp, cp, len,
2955 xfp->xf_width[XF_WIDTH_MAX],
2956 need_enc, xfp->xf_enc);
2961 * xo_buf_append* will move xb_curp, so we save/restore it.
2963 off2 = xbp->xb_curp - xbp->xb_bufp;
2965 xbp->xb_curp = xbp->xb_bufp + off;
2967 if (cols < xfp->xf_width[XF_WIDTH_MIN]) {
2969 * Find the number of columns needed to display the string.
2970 * If we have the original wide string, we just call wcswidth,
2971 * but if we did the work ourselves, then we need to do it.
2973 int delta = xfp->xf_width[XF_WIDTH_MIN] - cols;
2974 if (!xo_buf_has_room(xbp, xfp->xf_width[XF_WIDTH_MIN]))
2978 * If seen_minus, then pad on the right; otherwise move it so
2979 * we can pad on the left.
2981 if (xfp->xf_seen_minus) {
2982 cp = xbp->xb_curp + rc;
2985 memmove(xbp->xb_curp + delta, xbp->xb_curp, rc);
2988 /* Set the padding */
2989 memset(cp, (xfp->xf_leading_zero > 0) ? '0' : ' ', delta);
2994 if (XOF_ISSET(xop, XOF_COLUMNS))
2995 xop->xo_columns += cols;
2996 if (XOIF_ISSET(xop, XOIF_ANCHOR))
2997 xop->xo_anchor_columns += cols;
3002 xbp->xb_curp = xbp->xb_bufp + off;
3007 * Look backwards in a buffer to find a numeric value
3010 xo_buf_find_last_number (xo_buffer_t *xbp, ssize_t start_offset)
3012 int rc = 0; /* Fail with zero */
3014 char *sp = xbp->xb_bufp;
3015 char *cp = sp + start_offset;
3018 if (isdigit((int) *cp))
3021 for ( ; cp >= sp; cp--) {
3022 if (!isdigit((int) *cp))
3024 rc += (*cp - '0') * digit;
3032 xo_count_utf8_cols (const char *str, ssize_t len)
3037 const char *ep = str + len;
3040 tlen = xo_utf8_to_wc_len(str);
3041 if (tlen < 0) /* Broken input is very bad */
3044 wc = xo_utf8_char(str, tlen);
3045 if (wc == (wchar_t) -1)
3048 /* We only print printable characters */
3049 if (iswprint((wint_t) wc)) {
3051 * Find the width-in-columns of this character, which must be done
3052 * in wide characters, since we lack a mbswidth() function.
3054 ssize_t width = xo_wcwidth(wc);
3056 width = iswcntrl(wc) ? 0 : 1;
3068 static inline const char *
3069 xo_dgettext (xo_handle_t *xop, const char *str)
3071 const char *domainname = xop->xo_gt_domain;
3074 res = dgettext(domainname, str);
3076 if (XOF_ISSET(xop, XOF_LOG_GETTEXT))
3077 fprintf(stderr, "xo: gettext: %s%s%smsgid \"%s\" returns \"%s\"\n",
3078 domainname ? "domain \"" : "", xo_printable(domainname),
3079 domainname ? "\", " : "", xo_printable(str), xo_printable(res));
3084 static inline const char *
3085 xo_dngettext (xo_handle_t *xop, const char *sing, const char *plural,
3086 unsigned long int n)
3088 const char *domainname = xop->xo_gt_domain;
3091 res = dngettext(domainname, sing, plural, n);
3092 if (XOF_ISSET(xop, XOF_LOG_GETTEXT))
3093 fprintf(stderr, "xo: gettext: %s%s%s"
3094 "msgid \"%s\", msgid_plural \"%s\" (%lu) returns \"%s\"\n",
3095 domainname ? "domain \"" : "",
3096 xo_printable(domainname), domainname ? "\", " : "",
3098 xo_printable(plural), n, xo_printable(res));
3102 #else /* HAVE_GETTEXT */
3103 static inline const char *
3104 xo_dgettext (xo_handle_t *xop UNUSED, const char *str)
3109 static inline const char *
3110 xo_dngettext (xo_handle_t *xop UNUSED, const char *singular,
3111 const char *plural, unsigned long int n)
3113 return (n == 1) ? singular : plural;
3115 #endif /* HAVE_GETTEXT */
3118 * This is really _re_formatting, since the normal format code has
3119 * generated a beautiful string into xo_data, starting at
3120 * start_offset. We need to see if it's plural, which means
3121 * comma-separated options, or singular. Then we make the appropriate
3122 * call to d[n]gettext() to get the locale-based version. Note that
3123 * both input and output of gettext() this should be UTF-8.
3126 xo_format_gettext (xo_handle_t *xop, xo_xff_flags_t flags,
3127 ssize_t start_offset, ssize_t cols, int need_enc)
3129 xo_buffer_t *xbp = &xop->xo_data;
3131 if (!xo_buf_has_room(xbp, 1))
3134 xbp->xb_curp[0] = '\0'; /* NUL-terminate the input string */
3136 char *cp = xbp->xb_bufp + start_offset;
3137 ssize_t len = xbp->xb_curp - cp;
3138 const char *newstr = NULL;
3141 * The plural flag asks us to look backwards at the last numeric
3142 * value rendered and disect the string into two pieces.
3144 if (flags & XFF_GT_PLURAL) {
3145 int n = xo_buf_find_last_number(xbp, start_offset);
3146 char *two = memchr(cp, (int) ',', len);
3148 xo_failure(xop, "no comma in plural gettext field: '%s'", cp);
3153 xo_failure(xop, "nothing before comma in plural gettext "
3158 if (two == xbp->xb_curp) {
3159 xo_failure(xop, "nothing after comma in plural gettext "
3165 if (flags & XFF_GT_FIELD) {
3166 newstr = xo_dngettext(xop, cp, two, n);
3168 /* Don't do a gettext() look up, just get the plural form */
3169 newstr = (n == 1) ? cp : two;
3173 * If we returned the first string, optimize a bit by
3174 * backing up over comma
3177 xbp->xb_curp = two - 1; /* One for comma */
3179 * If the caller wanted UTF8, we're done; nothing changed,
3180 * but we need to count the columns used.
3182 if (need_enc == XF_ENC_UTF8)
3183 return xo_count_utf8_cols(cp, xbp->xb_curp - cp);
3187 /* The simple case (singular) */
3188 newstr = xo_dgettext(xop, cp);
3191 /* If the caller wanted UTF8, we're done; nothing changed */
3192 if (need_enc == XF_ENC_UTF8)
3198 * Since the new string string might be in gettext's buffer or
3199 * in the buffer (as the plural form), we make a copy.
3201 ssize_t nlen = strlen(newstr);
3202 char *newcopy = alloca(nlen + 1);
3203 memcpy(newcopy, newstr, nlen + 1);
3205 xbp->xb_curp = xbp->xb_bufp + start_offset; /* Reset the buffer */
3206 return xo_format_string_direct(xop, xbp, flags, NULL, newcopy, nlen, 0,
3207 need_enc, XF_ENC_UTF8);
3211 xo_data_append_content (xo_handle_t *xop, const char *str, ssize_t len,
3212 xo_xff_flags_t flags)
3215 int need_enc = xo_needed_encoding(xop);
3216 ssize_t start_offset = xo_buf_offset(&xop->xo_data);
3218 cols = xo_format_string_direct(xop, &xop->xo_data, XFF_UNESCAPE | flags,
3220 need_enc, XF_ENC_UTF8);
3221 if (flags & XFF_GT_FLAGS)
3222 cols = xo_format_gettext(xop, flags, start_offset, cols, need_enc);
3224 if (XOF_ISSET(xop, XOF_COLUMNS))
3225 xop->xo_columns += cols;
3226 if (XOIF_ISSET(xop, XOIF_ANCHOR))
3227 xop->xo_anchor_columns += cols;
3231 * Bump one of the 'width' values in a format strings (e.g. "%40.50.60s").
3232 * @param xfp Formatting instructions
3233 * @param digit Single digit (0-9) of input
3236 xo_bump_width (xo_format_t *xfp, int digit)
3238 int *ip = &xfp->xf_width[xfp->xf_dots];
3240 *ip = ((*ip > 0) ? *ip : 0) * 10 + digit;
3244 xo_trim_ws (xo_buffer_t *xbp, ssize_t len)
3249 /* First trim leading space */
3250 for (cp = sp = xbp->xb_curp, ep = cp + len; cp < ep; cp++) {
3258 memmove(sp, cp, len);
3261 /* Then trim off the end */
3262 for (cp = xbp->xb_curp, sp = ep = cp + len; cp < ep; ep--) {
3277 * Interface to format a single field. The arguments are in xo_vap,
3278 * and the format is in 'fmt'. If 'xbp' is null, we use xop->xo_data;
3279 * this is the most common case.
3282 xo_do_format_field (xo_handle_t *xop, xo_buffer_t *xbp,
3283 const char *fmt, ssize_t flen, xo_xff_flags_t flags)
3286 const char *cp, *ep, *sp, *xp = NULL;
3288 int style = (flags & XFF_XML) ? XO_STYLE_XML : xo_style(xop);
3289 unsigned make_output = !(flags & XFF_NO_OUTPUT) ? 1 : 0;
3290 int need_enc = xo_needed_encoding(xop);
3291 int real_need_enc = need_enc;
3292 ssize_t old_cols = xop->xo_columns;
3294 /* The gettext interface is UTF-8, so we'll need that for now */
3295 if (flags & XFF_GT_FIELD)
3296 need_enc = XF_ENC_UTF8;
3299 xbp = &xop->xo_data;
3301 ssize_t start_offset = xo_buf_offset(xbp);
3303 for (cp = fmt, ep = fmt + flen; cp < ep; cp++) {
3305 * Since we're starting a new field, save the starting offset.
3306 * We'll need this later for field-related operations.
3314 if (*cp == '\\' && cp[1] != '\0')
3318 } if (cp + 1 < ep && cp[1] == '%') {
3325 cols = xo_format_string_direct(xop, xbp, flags | XFF_UNESCAPE,
3326 NULL, xp, cp - xp, -1,
3327 need_enc, XF_ENC_UTF8);
3328 if (XOF_ISSET(xop, XOF_COLUMNS))
3329 xop->xo_columns += cols;
3330 if (XOIF_ISSET(xop, XOIF_ANCHOR))
3331 xop->xo_anchor_columns += cols;
3337 bzero(&xf, sizeof(xf));
3338 xf.xf_leading_zero = -1;
3339 xf.xf_width[0] = xf.xf_width[1] = xf.xf_width[2] = -1;
3342 * "%@" starts an XO-specific set of flags:
3343 * @X@ - XML-only field; ignored if style isn't XML
3346 for (cp += 2; cp < ep; cp++) {
3352 * '*' means there's a "%*.*s" value in vap that
3355 if (!XOF_ISSET(xop, XOF_NO_VA_ARG))
3356 va_arg(xop->xo_vap, int);
3361 /* Hidden fields are only visible to JSON and XML */
3362 if (XOF_ISSET(xop, XFF_ENCODE_ONLY)) {
3363 if (style != XO_STYLE_XML
3364 && !xo_style_is_encoding(xop))
3366 } else if (XOF_ISSET(xop, XFF_DISPLAY_ONLY)) {
3367 if (style != XO_STYLE_TEXT
3368 && xo_style(xop) != XO_STYLE_HTML)
3376 * Looking at one piece of a format; find the end and
3377 * call snprintf. Then advance xo_vap on our own.
3379 * Note that 'n', 'v', and '$' are not supported.
3381 sp = cp; /* Save start pointer */
3382 for (cp += 1; cp < ep; cp++) {
3385 else if (*cp == 'h')
3387 else if (*cp == 'j')
3389 else if (*cp == 't')
3391 else if (*cp == 'z')
3393 else if (*cp == 'q')
3395 else if (*cp == '.') {
3396 if (++xf.xf_dots >= XF_WIDTH_NUM) {
3397 xo_failure(xop, "Too many dots in format: '%s'", fmt);
3400 } else if (*cp == '-')
3401 xf.xf_seen_minus = 1;
3402 else if (isdigit((int) *cp)) {
3403 if (xf.xf_leading_zero < 0)
3404 xf.xf_leading_zero = (*cp == '0');
3405 xo_bump_width(&xf, *cp - '0');
3406 } else if (*cp == '*') {
3408 xf.xf_star[xf.xf_dots] = 1;
3409 } else if (strchr("diouxXDOUeEfFgGaAcCsSpm", *cp) != NULL)
3411 else if (*cp == 'n' || *cp == 'v') {
3412 xo_failure(xop, "unsupported format: '%s'", fmt);
3418 xo_failure(xop, "field format missing format character: %s",
3423 if (!XOF_ISSET(xop, XOF_NO_VA_ARG)) {
3424 if (*cp == 's' || *cp == 'S') {
3425 /* Handle "%*.*.*s" */
3427 for (s = 0; s < XF_WIDTH_NUM; s++) {
3428 if (xf.xf_star[s]) {
3429 xf.xf_width[s] = va_arg(xop->xo_vap, int);
3431 /* Normalize a negative width value */
3432 if (xf.xf_width[s] < 0) {
3434 xf.xf_width[0] = -xf.xf_width[0];
3435 xf.xf_seen_minus = 1;
3437 xf.xf_width[s] = -1; /* Ignore negative values */
3444 /* If no max is given, it defaults to size */
3445 if (xf.xf_width[XF_WIDTH_MAX] < 0 && xf.xf_width[XF_WIDTH_SIZE] >= 0)
3446 xf.xf_width[XF_WIDTH_MAX] = xf.xf_width[XF_WIDTH_SIZE];
3448 if (xf.xf_fc == 'D' || xf.xf_fc == 'O' || xf.xf_fc == 'U')
3452 xo_buffer_t *fbp = &xop->xo_fmt;
3453 ssize_t len = cp - sp + 1;
3454 if (!xo_buf_has_room(fbp, len + 1))
3457 char *newfmt = fbp->xb_curp;
3458 memcpy(newfmt, sp, len);
3459 newfmt[0] = '%'; /* If we skipped over a "%@...@s" format */
3463 * Bad news: our strings are UTF-8, but the stock printf
3464 * functions won't handle field widths for wide characters
3465 * correctly. So we have to handle this ourselves.
3467 if (xop->xo_formatter == NULL
3468 && (xf.xf_fc == 's' || xf.xf_fc == 'S'
3469 || xf.xf_fc == 'm')) {
3471 xf.xf_enc = (xf.xf_fc == 'm') ? XF_ENC_UTF8
3472 : (xf.xf_lflag || (xf.xf_fc == 'S')) ? XF_ENC_WIDE
3473 : xf.xf_hflag ? XF_ENC_LOCALE : XF_ENC_UTF8;
3475 rc = xo_format_string(xop, xbp, flags, &xf);
3477 if ((flags & XFF_TRIM_WS) && xo_style_is_encoding(xop))
3478 rc = xo_trim_ws(xbp, rc);
3481 ssize_t columns = rc = xo_vsnprintf(xop, xbp, newfmt,
3485 * For XML and HTML, we need "&<>" processing; for JSON,
3486 * it's quotes. Text gets nothing.
3490 if (flags & XFF_TRIM_WS)
3491 columns = rc = xo_trim_ws(xbp, rc);
3494 rc = xo_escape_xml(xbp, rc, (flags & XFF_ATTR));
3498 if (flags & XFF_TRIM_WS)
3499 columns = rc = xo_trim_ws(xbp, rc);
3500 rc = xo_escape_json(xbp, rc, 0);
3503 case XO_STYLE_SDPARAMS:
3504 if (flags & XFF_TRIM_WS)
3505 columns = rc = xo_trim_ws(xbp, rc);
3506 rc = xo_escape_sdparams(xbp, rc, 0);
3509 case XO_STYLE_ENCODER:
3510 if (flags & XFF_TRIM_WS)
3511 columns = rc = xo_trim_ws(xbp, rc);
3516 * We can assume all the non-%s data we've
3517 * added is ASCII, so the columns and bytes are the
3518 * same. xo_format_string handles all the fancy
3519 * string conversions and updates xo_anchor_columns
3522 if (XOF_ISSET(xop, XOF_COLUMNS))
3523 xop->xo_columns += columns;
3524 if (XOIF_ISSET(xop, XOIF_ANCHOR))
3525 xop->xo_anchor_columns += columns;
3532 * Now for the tricky part: we need to move the argument pointer
3533 * along by the amount needed.
3535 if (!XOF_ISSET(xop, XOF_NO_VA_ARG)) {
3537 if (xf.xf_fc == 's' ||xf.xf_fc == 'S') {
3539 * The 'S' and 's' formats are normally handled in
3540 * xo_format_string, but if we skipped it, then we
3544 va_arg(xop->xo_vap, char *);
3546 } else if (xf.xf_fc == 'm') {
3547 /* Nothing on the stack for "%m" */
3551 for (s = 0; s < XF_WIDTH_NUM; s++) {
3553 va_arg(xop->xo_vap, int);
3556 if (strchr("diouxXDOU", xf.xf_fc) != NULL) {
3557 if (xf.xf_hflag > 1) {
3558 va_arg(xop->xo_vap, int);
3560 } else if (xf.xf_hflag > 0) {
3561 va_arg(xop->xo_vap, int);
3563 } else if (xf.xf_lflag > 1) {
3564 va_arg(xop->xo_vap, unsigned long long);
3566 } else if (xf.xf_lflag > 0) {
3567 va_arg(xop->xo_vap, unsigned long);
3569 } else if (xf.xf_jflag > 0) {
3570 va_arg(xop->xo_vap, intmax_t);
3572 } else if (xf.xf_tflag > 0) {
3573 va_arg(xop->xo_vap, ptrdiff_t);
3575 } else if (xf.xf_zflag > 0) {
3576 va_arg(xop->xo_vap, size_t);
3578 } else if (xf.xf_qflag > 0) {
3579 va_arg(xop->xo_vap, quad_t);
3582 va_arg(xop->xo_vap, int);
3584 } else if (strchr("eEfFgGaA", xf.xf_fc) != NULL)
3586 va_arg(xop->xo_vap, long double);
3588 va_arg(xop->xo_vap, double);
3590 else if (xf.xf_fc == 'C' || (xf.xf_fc == 'c' && xf.xf_lflag))
3591 va_arg(xop->xo_vap, wint_t);
3593 else if (xf.xf_fc == 'c')
3594 va_arg(xop->xo_vap, int);
3596 else if (xf.xf_fc == 'p')
3597 va_arg(xop->xo_vap, void *);
3604 cols = xo_format_string_direct(xop, xbp, flags | XFF_UNESCAPE,
3605 NULL, xp, cp - xp, -1,
3606 need_enc, XF_ENC_UTF8);
3608 if (XOF_ISSET(xop, XOF_COLUMNS))
3609 xop->xo_columns += cols;
3610 if (XOIF_ISSET(xop, XOIF_ANCHOR))
3611 xop->xo_anchor_columns += cols;
3617 if (flags & XFF_GT_FLAGS) {
3619 * Handle gettext()ing the field by looking up the value
3620 * and then copying it in, while converting to locale, if
3623 ssize_t new_cols = xo_format_gettext(xop, flags, start_offset,
3624 old_cols, real_need_enc);
3626 if (XOF_ISSET(xop, XOF_COLUMNS))
3627 xop->xo_columns += new_cols - old_cols;
3628 if (XOIF_ISSET(xop, XOIF_ANCHOR))
3629 xop->xo_anchor_columns += new_cols - old_cols;
3636 xo_fix_encoding (xo_handle_t *xop UNUSED, char *encoding)
3638 char *cp = encoding;
3640 if (cp[0] != '%' || !isdigit((int) cp[1]))
3643 for (cp += 2; *cp; cp++) {
3644 if (!isdigit((int) *cp))
3655 xo_color_append_html (xo_handle_t *xop)
3658 * If the color buffer has content, we add it now. It's already
3659 * prebuilt and ready, since we want to add it to every <div>.
3661 if (!xo_buf_is_empty(&xop->xo_color_buf)) {
3662 xo_buffer_t *xbp = &xop->xo_color_buf;
3664 xo_data_append(xop, xbp->xb_bufp, xbp->xb_curp - xbp->xb_bufp);
3669 * A wrapper for humanize_number that autoscales, since the
3670 * HN_AUTOSCALE flag scales as needed based on the size of
3671 * the output buffer, not the size of the value. I also
3672 * wish HN_DECIMAL was more imperative, without the <10
3673 * test. But the boat only goes where we want when we hold
3674 * the rudder, so xo_humanize fixes part of the problem.
3677 xo_humanize (char *buf, ssize_t len, uint64_t value, int flags)
3682 uint64_t left = value;
3684 if (flags & HN_DIVISOR_1000) {
3685 for ( ; left; scale++)
3688 for ( ; left; scale++)
3694 return xo_humanize_number(buf, len, value, "", scale, flags);
3698 * This is an area where we can save information from the handle for
3699 * later restoration. We need to know what data was rendered to know
3700 * what needs cleaned up.
3702 typedef struct xo_humanize_save_s {
3703 ssize_t xhs_offset; /* Saved xo_offset */
3704 ssize_t xhs_columns; /* Saved xo_columns */
3705 ssize_t xhs_anchor_columns; /* Saved xo_anchor_columns */
3706 } xo_humanize_save_t;
3709 * Format a "humanized" value for a numeric, meaning something nice
3710 * like "44M" instead of "44470272". We autoscale, choosing the
3711 * most appropriate value for K/M/G/T/P/E based on the value given.
3714 xo_format_humanize (xo_handle_t *xop, xo_buffer_t *xbp,
3715 xo_humanize_save_t *savep, xo_xff_flags_t flags)
3717 if (XOF_ISSET(xop, XOF_NO_HUMANIZE))
3720 ssize_t end_offset = xbp->xb_curp - xbp->xb_bufp;
3721 if (end_offset == savep->xhs_offset) /* Huh? Nothing to render */
3725 * We have a string that's allegedly a number. We want to
3726 * humanize it, which means turning it back into a number
3727 * and calling xo_humanize_number on it.
3732 xo_buf_append(xbp, "", 1); /* NUL-terminate it */
3734 value = strtoull(xbp->xb_bufp + savep->xhs_offset, &ep, 0);
3735 if (!(value == ULLONG_MAX && errno == ERANGE)
3736 && (ep != xbp->xb_bufp + savep->xhs_offset)) {
3738 * There are few values where humanize_number needs
3739 * more bytes than the original value. I've used
3740 * 10 as a rectal number to cover those scenarios.
3742 if (xo_buf_has_room(xbp, 10)) {
3743 xbp->xb_curp = xbp->xb_bufp + savep->xhs_offset;
3746 ssize_t left = (xbp->xb_bufp + xbp->xb_size) - xbp->xb_curp;
3747 int hn_flags = HN_NOSPACE; /* On by default */
3749 if (flags & XFF_HN_SPACE)
3750 hn_flags &= ~HN_NOSPACE;
3752 if (flags & XFF_HN_DECIMAL)
3753 hn_flags |= HN_DECIMAL;
3755 if (flags & XFF_HN_1000)
3756 hn_flags |= HN_DIVISOR_1000;
3758 rc = xo_humanize(xbp->xb_curp, left, value, hn_flags);
3761 xop->xo_columns = savep->xhs_columns + rc;
3762 xop->xo_anchor_columns = savep->xhs_anchor_columns + rc;
3769 xo_buf_append_div (xo_handle_t *xop, const char *class, xo_xff_flags_t flags,
3770 const char *name, ssize_t nlen,
3771 const char *value, ssize_t vlen,
3772 const char *encoding, ssize_t elen)
3774 static char div_start[] = "<div class=\"";
3775 static char div_tag[] = "\" data-tag=\"";
3776 static char div_xpath[] = "\" data-xpath=\"";
3777 static char div_key[] = "\" data-key=\"key";
3778 static char div_end[] = "\">";
3779 static char div_close[] = "</div>";
3781 /* The encoding format defaults to the normal format */
3782 if (encoding == NULL) {
3783 char *enc = alloca(vlen + 1);
3784 memcpy(enc, value, vlen);
3786 encoding = xo_fix_encoding(xop, enc);
3787 elen = strlen(encoding);
3791 * To build our XPath predicate, we need to save the va_list before
3792 * we format our data, and then restore it before we format the
3794 * Display-only keys implies that we've got an encode-only key
3795 * elsewhere, so we don't use them from making predicates.
3797 int need_predidate =
3798 (name && (flags & XFF_KEY) && !(flags & XFF_DISPLAY_ONLY)
3799 && XOF_ISSET(xop, XOF_XPATH)) ? 1 : 0;
3801 if (need_predidate) {
3804 va_copy(va_local, xop->xo_vap);
3805 if (xop->xo_checkpointer)
3806 xop->xo_checkpointer(xop, xop->xo_vap, 0);
3809 * Build an XPath predicate expression to match this key.
3810 * We use the format buffer.
3812 xo_buffer_t *pbp = &xop->xo_predicate;
3813 pbp->xb_curp = pbp->xb_bufp; /* Restart buffer */
3815 xo_buf_append(pbp, "[", 1);
3816 xo_buf_escape(xop, pbp, name, nlen, 0);
3817 if (XOF_ISSET(xop, XOF_PRETTY))
3818 xo_buf_append(pbp, " = '", 4);
3820 xo_buf_append(pbp, "='", 2);
3822 xo_xff_flags_t pflags = flags | XFF_XML | XFF_ATTR;
3823 pflags &= ~(XFF_NO_OUTPUT | XFF_ENCODE_ONLY);
3824 xo_do_format_field(xop, pbp, encoding, elen, pflags);
3826 xo_buf_append(pbp, "']", 2);
3828 /* Now we record this predicate expression in the stack */
3829 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth];
3830 ssize_t olen = xsp->xs_keys ? strlen(xsp->xs_keys) : 0;
3831 ssize_t dlen = pbp->xb_curp - pbp->xb_bufp;
3833 char *cp = xo_realloc(xsp->xs_keys, olen + dlen + 1);
3835 memcpy(cp + olen, pbp->xb_bufp, dlen);
3836 cp[olen + dlen] = '\0';
3840 /* Now we reset the xo_vap as if we were never here */
3841 va_end(xop->xo_vap);
3842 va_copy(xop->xo_vap, va_local);
3844 if (xop->xo_checkpointer)
3845 xop->xo_checkpointer(xop, xop->xo_vap, 1);
3848 if (flags & XFF_ENCODE_ONLY) {
3850 * Even if this is encode-only, we need to go through the
3851 * work of formatting it to make sure the args are cleared
3854 xo_do_format_field(xop, NULL, encoding, elen,
3855 flags | XFF_NO_OUTPUT);
3859 xo_line_ensure_open(xop, 0);
3861 if (XOF_ISSET(xop, XOF_PRETTY))
3862 xo_buf_indent(xop, xop->xo_indent_by);
3864 xo_data_append(xop, div_start, sizeof(div_start) - 1);
3865 xo_data_append(xop, class, strlen(class));
3868 * If the color buffer has content, we add it now. It's already
3869 * prebuilt and ready, since we want to add it to every <div>.
3871 if (!xo_buf_is_empty(&xop->xo_color_buf)) {
3872 xo_buffer_t *xbp = &xop->xo_color_buf;
3874 xo_data_append(xop, xbp->xb_bufp, xbp->xb_curp - xbp->xb_bufp);
3878 xo_data_append(xop, div_tag, sizeof(div_tag) - 1);
3879 xo_data_escape(xop, name, nlen);
3882 * Save the offset at which we'd place units. See xo_format_units.
3884 if (XOF_ISSET(xop, XOF_UNITS)) {
3885 XOIF_SET(xop, XOIF_UNITS_PENDING);
3887 * Note: We need the '+1' here because we know we've not
3888 * added the closing quote. We add one, knowing the quote
3889 * will be added shortly.
3891 xop->xo_units_offset =
3892 xop->xo_data.xb_curp -xop->xo_data.xb_bufp + 1;
3895 if (XOF_ISSET(xop, XOF_XPATH)) {
3899 xo_data_append(xop, div_xpath, sizeof(div_xpath) - 1);
3900 if (xop->xo_leading_xpath)
3901 xo_data_append(xop, xop->xo_leading_xpath,
3902 strlen(xop->xo_leading_xpath));
3904 for (i = 0; i <= xop->xo_depth; i++) {
3905 xsp = &xop->xo_stack[i];
3906 if (xsp->xs_name == NULL)
3910 * XSS_OPEN_LIST and XSS_OPEN_LEAF_LIST stack frames
3911 * are directly under XSS_OPEN_INSTANCE frames so we
3912 * don't need to put these in our XPath expressions.
3914 if (xsp->xs_state == XSS_OPEN_LIST
3915 || xsp->xs_state == XSS_OPEN_LEAF_LIST)
3918 xo_data_append(xop, "/", 1);
3919 xo_data_escape(xop, xsp->xs_name, strlen(xsp->xs_name));
3921 /* Don't show keys for the key field */
3922 if (i != xop->xo_depth || !(flags & XFF_KEY))
3923 xo_data_append(xop, xsp->xs_keys, strlen(xsp->xs_keys));
3927 xo_data_append(xop, "/", 1);
3928 xo_data_escape(xop, name, nlen);
3931 if (XOF_ISSET(xop, XOF_INFO) && xop->xo_info) {
3932 static char in_type[] = "\" data-type=\"";
3933 static char in_help[] = "\" data-help=\"";
3935 xo_info_t *xip = xo_info_find(xop, name, nlen);
3938 xo_data_append(xop, in_type, sizeof(in_type) - 1);
3939 xo_data_escape(xop, xip->xi_type, strlen(xip->xi_type));
3942 xo_data_append(xop, in_help, sizeof(in_help) - 1);
3943 xo_data_escape(xop, xip->xi_help, strlen(xip->xi_help));
3948 if ((flags & XFF_KEY) && XOF_ISSET(xop, XOF_KEYS))
3949 xo_data_append(xop, div_key, sizeof(div_key) - 1);
3952 xo_buffer_t *xbp = &xop->xo_data;
3953 ssize_t base_offset = xbp->xb_curp - xbp->xb_bufp;
3955 xo_data_append(xop, div_end, sizeof(div_end) - 1);
3957 xo_humanize_save_t save; /* Save values for humanizing logic */
3959 save.xhs_offset = xbp->xb_curp - xbp->xb_bufp;
3960 save.xhs_columns = xop->xo_columns;
3961 save.xhs_anchor_columns = xop->xo_anchor_columns;
3963 xo_do_format_field(xop, NULL, value, vlen, flags);
3965 if (flags & XFF_HUMANIZE) {
3967 * Unlike text style, we want to retain the original value and
3968 * stuff it into the "data-number" attribute.
3970 static const char div_number[] = "\" data-number=\"";
3971 ssize_t div_len = sizeof(div_number) - 1;
3973 ssize_t end_offset = xbp->xb_curp - xbp->xb_bufp;
3974 ssize_t olen = end_offset - save.xhs_offset;
3976 char *cp = alloca(olen + 1);
3977 memcpy(cp, xbp->xb_bufp + save.xhs_offset, olen);
3980 xo_format_humanize(xop, xbp, &save, flags);
3982 if (xo_buf_has_room(xbp, div_len + olen)) {
3983 ssize_t new_offset = xbp->xb_curp - xbp->xb_bufp;
3986 /* Move the humanized string off to the left */
3987 memmove(xbp->xb_bufp + base_offset + div_len + olen,
3988 xbp->xb_bufp + base_offset, new_offset - base_offset);
3990 /* Copy the data_number attribute name */
3991 memcpy(xbp->xb_bufp + base_offset, div_number, div_len);
3993 /* Copy the original long value */
3994 memcpy(xbp->xb_bufp + base_offset + div_len, cp, olen);
3995 xbp->xb_curp += div_len + olen;
3999 xo_data_append(xop, div_close, sizeof(div_close) - 1);
4001 if (XOF_ISSET(xop, XOF_PRETTY))
4002 xo_data_append(xop, "\n", 1);
4006 xo_format_text (xo_handle_t *xop, const char *str, ssize_t len)
4008 switch (xo_style(xop)) {
4010 xo_buf_append_locale(xop, &xop->xo_data, str, len);
4014 xo_buf_append_div(xop, "text", 0, NULL, 0, str, len, NULL, 0);
4020 xo_format_title (xo_handle_t *xop, xo_field_info_t *xfip,
4021 const char *str, ssize_t len)
4023 const char *fmt = xfip->xfi_format;
4024 ssize_t flen = xfip->xfi_flen;
4025 xo_xff_flags_t flags = xfip->xfi_flags;
4027 static char div_open[] = "<div class=\"title";
4028 static char div_middle[] = "\">";
4029 static char div_close[] = "</div>";
4036 switch (xo_style(xop)) {
4039 case XO_STYLE_SDPARAMS:
4040 case XO_STYLE_ENCODER:
4042 * Even though we don't care about text, we need to do
4043 * enough parsing work to skip over the right bits of xo_vap.
4046 xo_do_format_field(xop, NULL, fmt, flen, flags | XFF_NO_OUTPUT);
4050 xo_buffer_t *xbp = &xop->xo_data;
4051 ssize_t start = xbp->xb_curp - xbp->xb_bufp;
4052 ssize_t left = xbp->xb_size - start;
4055 if (xo_style(xop) == XO_STYLE_HTML) {
4056 xo_line_ensure_open(xop, 0);
4057 if (XOF_ISSET(xop, XOF_PRETTY))
4058 xo_buf_indent(xop, xop->xo_indent_by);
4059 xo_buf_append(&xop->xo_data, div_open, sizeof(div_open) - 1);
4060 xo_color_append_html(xop);
4061 xo_buf_append(&xop->xo_data, div_middle, sizeof(div_middle) - 1);
4064 start = xbp->xb_curp - xbp->xb_bufp; /* Reset start */
4066 char *newfmt = alloca(flen + 1);
4067 memcpy(newfmt, fmt, flen);
4068 newfmt[flen] = '\0';
4070 /* If len is non-zero, the format string apply to the name */
4071 char *newstr = alloca(len + 1);
4072 memcpy(newstr, str, len);
4075 if (newstr[len - 1] == 's') {
4078 rc = snprintf(NULL, 0, newfmt, newstr);
4081 * We have to do this the hard way, since we might need
4084 bp = alloca(rc + 1);
4085 rc = snprintf(bp, rc + 1, newfmt, newstr);
4087 xo_data_append_content(xop, bp, rc, flags);
4092 rc = snprintf(xbp->xb_curp, left, newfmt, newstr);
4094 if (!xo_buf_has_room(xbp, rc))
4096 left = xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
4097 rc = snprintf(xbp->xb_curp, left, newfmt, newstr);
4101 if (XOF_ISSET(xop, XOF_COLUMNS))
4102 xop->xo_columns += rc;
4103 if (XOIF_ISSET(xop, XOIF_ANCHOR))
4104 xop->xo_anchor_columns += rc;
4109 xo_do_format_field(xop, NULL, fmt, flen, flags);
4111 /* xo_do_format_field moved curp, so we need to reset it */
4112 rc = xbp->xb_curp - (xbp->xb_bufp + start);
4113 xbp->xb_curp = xbp->xb_bufp + start;
4116 /* If we're styling HTML, then we need to escape it */
4117 if (xo_style(xop) == XO_STYLE_HTML) {
4118 rc = xo_escape_xml(xbp, rc, 0);
4125 if (xo_style(xop) == XO_STYLE_HTML) {
4126 xo_data_append(xop, div_close, sizeof(div_close) - 1);
4127 if (XOF_ISSET(xop, XOF_PRETTY))
4128 xo_data_append(xop, "\n", 1);
4133 xo_format_prep (xo_handle_t *xop, xo_xff_flags_t flags)
4135 if (xop->xo_stack[xop->xo_depth].xs_flags & XSF_NOT_FIRST) {
4136 xo_data_append(xop, ",", 1);
4137 if (!(flags & XFF_LEAF_LIST) && XOF_ISSET(xop, XOF_PRETTY))
4138 xo_data_append(xop, "\n", 1);
4140 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
4144 /* Useful debugging function */
4146 xo_arg (xo_handle_t *xop);
4148 xo_arg (xo_handle_t *xop)
4150 xop = xo_default(xop);
4151 fprintf(stderr, "0x%x", va_arg(xop->xo_vap, unsigned));
4156 xo_format_value (xo_handle_t *xop, const char *name, ssize_t nlen,
4157 const char *format, ssize_t flen,
4158 const char *encoding, ssize_t elen, xo_xff_flags_t flags)
4160 int pretty = XOF_ISSET(xop, XOF_PRETTY);
4164 * Before we emit a value, we need to know that the frame is ready.
4166 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth];
4168 if (flags & XFF_LEAF_LIST) {
4170 * Check if we've already started to emit normal leafs
4171 * or if we're not in a leaf list.
4173 if ((xsp->xs_flags & (XSF_EMIT | XSF_EMIT_KEY))
4174 || !(xsp->xs_flags & XSF_EMIT_LEAF_LIST)) {
4175 char nbuf[nlen + 1];
4176 memcpy(nbuf, name, nlen);
4179 ssize_t rc = xo_transition(xop, 0, nbuf, XSS_EMIT_LEAF_LIST);
4181 flags |= XFF_DISPLAY_ONLY | XFF_ENCODE_ONLY;
4183 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_EMIT_LEAF_LIST;
4186 xsp = &xop->xo_stack[xop->xo_depth];
4188 name = xsp->xs_name;
4189 nlen = strlen(name);
4192 } else if (flags & XFF_KEY) {
4193 /* Emitting a 'k' (key) field */
4194 if ((xsp->xs_flags & XSF_EMIT) && !(flags & XFF_DISPLAY_ONLY)) {
4195 xo_failure(xop, "key field emitted after normal value field: '%.*s'",
4198 } else if (!(xsp->xs_flags & XSF_EMIT_KEY)) {
4199 char nbuf[nlen + 1];
4200 memcpy(nbuf, name, nlen);
4203 ssize_t rc = xo_transition(xop, 0, nbuf, XSS_EMIT);
4205 flags |= XFF_DISPLAY_ONLY | XFF_ENCODE_ONLY;
4207 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_EMIT_KEY;
4209 xsp = &xop->xo_stack[xop->xo_depth];
4210 xsp->xs_flags |= XSF_EMIT_KEY;
4214 /* Emitting a normal value field */
4215 if ((xsp->xs_flags & XSF_EMIT_LEAF_LIST)
4216 || !(xsp->xs_flags & XSF_EMIT)) {
4217 char nbuf[nlen + 1];
4218 memcpy(nbuf, name, nlen);
4221 ssize_t rc = xo_transition(xop, 0, nbuf, XSS_EMIT);
4223 flags |= XFF_DISPLAY_ONLY | XFF_ENCODE_ONLY;
4225 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_EMIT;
4227 xsp = &xop->xo_stack[xop->xo_depth];
4228 xsp->xs_flags |= XSF_EMIT;
4232 xo_buffer_t *xbp = &xop->xo_data;
4233 xo_humanize_save_t save; /* Save values for humanizing logic */
4235 switch (xo_style(xop)) {
4237 if (flags & XFF_ENCODE_ONLY)
4238 flags |= XFF_NO_OUTPUT;
4240 save.xhs_offset = xbp->xb_curp - xbp->xb_bufp;
4241 save.xhs_columns = xop->xo_columns;
4242 save.xhs_anchor_columns = xop->xo_anchor_columns;
4244 xo_do_format_field(xop, NULL, format, flen, flags);
4246 if (flags & XFF_HUMANIZE)
4247 xo_format_humanize(xop, xbp, &save, flags);
4251 if (flags & XFF_ENCODE_ONLY)
4252 flags |= XFF_NO_OUTPUT;
4254 xo_buf_append_div(xop, "data", flags, name, nlen,
4255 format, flen, encoding, elen);
4260 * Even though we're not making output, we still need to
4261 * let the formatting code handle the va_arg popping.
4263 if (flags & XFF_DISPLAY_ONLY) {
4264 flags |= XFF_NO_OUTPUT;
4265 xo_do_format_field(xop, NULL, format, flen, flags);
4273 char *enc = alloca(flen + 1);
4274 memcpy(enc, format, flen);
4276 format = xo_fix_encoding(xop, enc);
4277 flen = strlen(format);
4281 static char missing[] = "missing-field-name";
4282 xo_failure(xop, "missing field name: %s", format);
4284 nlen = sizeof(missing) - 1;
4288 xo_buf_indent(xop, -1);
4289 xo_data_append(xop, "<", 1);
4290 xo_data_escape(xop, name, nlen);
4292 if (xop->xo_attrs.xb_curp != xop->xo_attrs.xb_bufp) {
4293 xo_data_append(xop, xop->xo_attrs.xb_bufp,
4294 xop->xo_attrs.xb_curp - xop->xo_attrs.xb_bufp);
4295 xop->xo_attrs.xb_curp = xop->xo_attrs.xb_bufp;
4299 * We indicate 'key' fields using the 'key' attribute. While
4300 * this is really committing the crime of mixing meta-data with
4301 * data, it's often useful. Especially when format meta-data is
4302 * difficult to come by.
4304 if ((flags & XFF_KEY) && XOF_ISSET(xop, XOF_KEYS)) {
4305 static char attr[] = " key=\"key\"";
4306 xo_data_append(xop, attr, sizeof(attr) - 1);
4310 * Save the offset at which we'd place units. See xo_format_units.
4312 if (XOF_ISSET(xop, XOF_UNITS)) {
4313 XOIF_SET(xop, XOIF_UNITS_PENDING);
4314 xop->xo_units_offset = xop->xo_data.xb_curp -xop->xo_data.xb_bufp;
4317 xo_data_append(xop, ">", 1);
4318 xo_do_format_field(xop, NULL, format, flen, flags);
4319 xo_data_append(xop, "</", 2);
4320 xo_data_escape(xop, name, nlen);
4321 xo_data_append(xop, ">", 1);
4323 xo_data_append(xop, "\n", 1);
4327 if (flags & XFF_DISPLAY_ONLY) {
4328 flags |= XFF_NO_OUTPUT;
4329 xo_do_format_field(xop, NULL, format, flen, flags);
4337 char *enc = alloca(flen + 1);
4338 memcpy(enc, format, flen);
4340 format = xo_fix_encoding(xop, enc);
4341 flen = strlen(format);
4344 int first = (xop->xo_stack[xop->xo_depth].xs_flags & XSF_NOT_FIRST)
4347 xo_format_prep(xop, flags);
4349 if (flags & XFF_QUOTE)
4351 else if (flags & XFF_NOQUOTE)
4353 else if (flen == 0) {
4355 format = "true"; /* JSON encodes empty tags as a boolean true */
4357 } else if (strchr("diouDOUeEfFgG", format[flen - 1]) == NULL)
4363 static char missing[] = "missing-field-name";
4364 xo_failure(xop, "missing field name: %s", format);
4366 nlen = sizeof(missing) - 1;
4369 if (flags & XFF_LEAF_LIST) {
4370 if (!first && pretty)
4371 xo_data_append(xop, "\n", 1);
4373 xo_buf_indent(xop, -1);
4376 xo_buf_indent(xop, -1);
4377 xo_data_append(xop, "\"", 1);
4379 xbp = &xop->xo_data;
4380 ssize_t off = xbp->xb_curp - xbp->xb_bufp;
4382 xo_data_escape(xop, name, nlen);
4384 if (XOF_ISSET(xop, XOF_UNDERSCORES)) {
4385 ssize_t coff = xbp->xb_curp - xbp->xb_bufp;
4386 for ( ; off < coff; off++)
4387 if (xbp->xb_bufp[off] == '-')
4388 xbp->xb_bufp[off] = '_';
4390 xo_data_append(xop, "\":", 2);
4392 xo_data_append(xop, " ", 1);
4396 xo_data_append(xop, "\"", 1);
4398 xo_do_format_field(xop, NULL, format, flen, flags);
4401 xo_data_append(xop, "\"", 1);
4404 case XO_STYLE_SDPARAMS:
4405 if (flags & XFF_DISPLAY_ONLY) {
4406 flags |= XFF_NO_OUTPUT;
4407 xo_do_format_field(xop, NULL, format, flen, flags);
4415 char *enc = alloca(flen + 1);
4416 memcpy(enc, format, flen);
4418 format = xo_fix_encoding(xop, enc);
4419 flen = strlen(format);
4423 static char missing[] = "missing-field-name";
4424 xo_failure(xop, "missing field name: %s", format);
4426 nlen = sizeof(missing) - 1;
4429 xo_data_escape(xop, name, nlen);
4430 xo_data_append(xop, "=\"", 2);
4431 xo_do_format_field(xop, NULL, format, flen, flags);
4432 xo_data_append(xop, "\" ", 2);
4435 case XO_STYLE_ENCODER:
4436 if (flags & XFF_DISPLAY_ONLY) {
4437 flags |= XFF_NO_OUTPUT;
4438 xo_do_format_field(xop, NULL, format, flen, flags);
4442 if (flags & XFF_QUOTE)
4444 else if (flags & XFF_NOQUOTE)
4446 else if (flen == 0) {
4448 format = "true"; /* JSON encodes empty tags as a boolean true */
4450 } else if (strchr("diouxXDOUeEfFgGaAcCp", format[flen - 1]) == NULL)
4459 char *enc = alloca(flen + 1);
4460 memcpy(enc, format, flen);
4462 format = xo_fix_encoding(xop, enc);
4463 flen = strlen(format);
4467 static char missing[] = "missing-field-name";
4468 xo_failure(xop, "missing field name: %s", format);
4470 nlen = sizeof(missing) - 1;
4473 ssize_t name_offset = xo_buf_offset(&xop->xo_data);
4474 xo_data_append(xop, name, nlen);
4475 xo_data_append(xop, "", 1);
4477 ssize_t value_offset = xo_buf_offset(&xop->xo_data);
4478 xo_do_format_field(xop, NULL, format, flen, flags);
4479 xo_data_append(xop, "", 1);
4481 xo_encoder_handle(xop, quote ? XO_OP_STRING : XO_OP_CONTENT,
4482 xo_buf_data(&xop->xo_data, name_offset),
4483 xo_buf_data(&xop->xo_data, value_offset), flags);
4484 xo_buf_reset(&xop->xo_data);
4490 xo_set_gettext_domain (xo_handle_t *xop, xo_field_info_t *xfip,
4491 const char *str, ssize_t len)
4493 const char *fmt = xfip->xfi_format;
4494 ssize_t flen = xfip->xfi_flen;
4496 /* Start by discarding previous domain */
4497 if (xop->xo_gt_domain) {
4498 xo_free(xop->xo_gt_domain);
4499 xop->xo_gt_domain = NULL;
4502 /* An empty {G:} means no domainname */
4503 if (len == 0 && flen == 0)
4506 ssize_t start_offset = -1;
4507 if (len == 0 && flen != 0) {
4508 /* Need to do format the data to get the domainname from args */
4509 start_offset = xop->xo_data.xb_curp - xop->xo_data.xb_bufp;
4510 xo_do_format_field(xop, NULL, fmt, flen, 0);
4512 ssize_t end_offset = xop->xo_data.xb_curp - xop->xo_data.xb_bufp;
4513 len = end_offset - start_offset;
4514 str = xop->xo_data.xb_bufp + start_offset;
4517 xop->xo_gt_domain = xo_strndup(str, len);
4519 /* Reset the current buffer point to avoid emitting the name as output */
4520 if (start_offset >= 0)
4521 xop->xo_data.xb_curp = xop->xo_data.xb_bufp + start_offset;
4525 xo_format_content (xo_handle_t *xop, const char *class_name,
4526 const char *tag_name,
4527 const char *str, ssize_t len, const char *fmt, ssize_t flen,
4528 xo_xff_flags_t flags)
4530 switch (xo_style(xop)) {
4533 xo_data_append_content(xop, str, len, flags);
4535 xo_do_format_field(xop, NULL, fmt, flen, flags);
4544 xo_buf_append_div(xop, class_name, flags, NULL, 0, str, len, NULL, 0);
4549 case XO_STYLE_SDPARAMS:
4556 xo_open_container_h(xop, tag_name);
4557 xo_format_value(xop, "message", 7, str, len, NULL, 0, flags);
4558 xo_close_container_h(xop, tag_name);
4562 * Even though we don't care about labels, we need to do
4563 * enough parsing work to skip over the right bits of xo_vap.
4566 xo_do_format_field(xop, NULL, fmt, flen,
4567 flags | XFF_NO_OUTPUT);
4571 case XO_STYLE_ENCODER:
4573 xo_do_format_field(xop, NULL, fmt, flen,
4574 flags | XFF_NO_OUTPUT);
4579 static const char *xo_color_names[] = {
4580 "default", /* XO_COL_DEFAULT */
4581 "black", /* XO_COL_BLACK */
4582 "red", /* XO_CLOR_RED */
4583 "green", /* XO_COL_GREEN */
4584 "yellow", /* XO_COL_YELLOW */
4585 "blue", /* XO_COL_BLUE */
4586 "magenta", /* XO_COL_MAGENTA */
4587 "cyan", /* XO_COL_CYAN */
4588 "white", /* XO_COL_WHITE */
4593 xo_color_find (const char *str)
4597 for (i = 0; xo_color_names[i]; i++) {
4598 if (strcmp(xo_color_names[i], str) == 0)
4605 static const char *xo_effect_names[] = {
4606 "reset", /* XO_EFF_RESET */
4607 "normal", /* XO_EFF_NORMAL */
4608 "bold", /* XO_EFF_BOLD */
4609 "underline", /* XO_EFF_UNDERLINE */
4610 "inverse", /* XO_EFF_INVERSE */
4614 static const char *xo_effect_on_codes[] = {
4615 "0", /* XO_EFF_RESET */
4616 "0", /* XO_EFF_NORMAL */
4617 "1", /* XO_EFF_BOLD */
4618 "4", /* XO_EFF_UNDERLINE */
4619 "7", /* XO_EFF_INVERSE */
4625 * See comment below re: joy of terminal standards. These can
4626 * be use by just adding:
4627 * + if (newp->xoc_effects & bit)
4628 * code = xo_effect_on_codes[i];
4630 * + code = xo_effect_off_codes[i];
4631 * in xo_color_handle_text.
4633 static const char *xo_effect_off_codes[] = {
4634 "0", /* XO_EFF_RESET */
4635 "0", /* XO_EFF_NORMAL */
4636 "21", /* XO_EFF_BOLD */
4637 "24", /* XO_EFF_UNDERLINE */
4638 "27", /* XO_EFF_INVERSE */
4644 xo_effect_find (const char *str)
4648 for (i = 0; xo_effect_names[i]; i++) {
4649 if (strcmp(xo_effect_names[i], str) == 0)
4657 xo_colors_parse (xo_handle_t *xop, xo_colors_t *xocp, char *str)
4659 #ifdef LIBXO_TEXT_ONLY
4661 #endif /* LIBXO_TEXT_ONLY */
4663 char *cp, *ep, *np, *xp;
4664 ssize_t len = strlen(str);
4668 * Possible tokens: colors, bg-colors, effects, no-effects, "reset".
4670 for (cp = str, ep = cp + len - 1; cp && cp < ep; cp = np) {
4671 /* Trim leading whitespace */
4672 while (isspace((int) *cp))
4675 np = strchr(cp, ',');
4679 /* Trim trailing whitespace */
4680 xp = cp + strlen(cp) - 1;
4681 while (isspace(*xp) && xp > cp)
4684 if (cp[0] == 'f' && cp[1] == 'g' && cp[2] == '-') {
4685 rc = xo_color_find(cp + 3);
4689 xocp->xoc_col_fg = rc;
4691 } else if (cp[0] == 'b' && cp[1] == 'g' && cp[2] == '-') {
4692 rc = xo_color_find(cp + 3);
4695 xocp->xoc_col_bg = rc;
4697 } else if (cp[0] == 'n' && cp[1] == 'o' && cp[2] == '-') {
4698 rc = xo_effect_find(cp + 3);
4701 xocp->xoc_effects &= ~(1 << rc);
4704 rc = xo_effect_find(cp);
4707 xocp->xoc_effects |= 1 << rc;
4711 xocp->xoc_col_fg = xocp->xoc_col_bg = 0;
4712 /* Note: not "|=" since we want to wipe out the old value */
4713 xocp->xoc_effects = XO_EFF_RESET;
4717 xocp->xoc_effects &= ~(XO_EFF_BOLD | XO_EFF_UNDERLINE
4718 | XO_EFF_INVERSE | XO_EFF_NORMAL);
4725 if (XOF_ISSET(xop, XOF_WARN))
4726 xo_failure(xop, "unknown color/effect string detected: '%s'", cp);
4731 xo_colors_enabled (xo_handle_t *xop UNUSED)
4733 #ifdef LIBXO_TEXT_ONLY
4735 #else /* LIBXO_TEXT_ONLY */
4736 return XOF_ISSET(xop, XOF_COLOR);
4737 #endif /* LIBXO_TEXT_ONLY */
4741 * If the color map is in use (--libxo colors=xxxx), then update
4742 * the incoming foreground and background colors from the map.
4745 xo_colors_update (xo_handle_t *xop, xo_colors_t *newp)
4747 #ifdef LIBXO_TEXT_ONLY
4749 #endif /* LIBXO_TEXT_ONLY */
4751 xo_color_t fg = newp->xoc_col_fg;
4752 if (XOF_ISSET(xop, XOF_COLOR_MAP) && fg < XO_NUM_COLORS)
4753 fg = xop->xo_color_map_fg[fg]; /* Fetch from color map */
4754 newp->xoc_col_fg = fg;
4756 xo_color_t bg = newp->xoc_col_bg;
4757 if (XOF_ISSET(xop, XOF_COLOR_MAP) && bg < XO_NUM_COLORS)
4758 bg = xop->xo_color_map_bg[bg]; /* Fetch from color map */
4759 newp->xoc_col_bg = bg;
4763 xo_colors_handle_text (xo_handle_t *xop, xo_colors_t *newp)
4766 char *cp = buf, *ep = buf + sizeof(buf);
4768 xo_colors_t *oldp = &xop->xo_colors;
4769 const char *code = NULL;
4772 * Start the buffer with an escape. We don't want to add the '['
4773 * now, since we let xo_effect_text_add unconditionally add the ';'.
4774 * We'll replace the first ';' with a '[' when we're done.
4776 *cp++ = 0x1b; /* Escape */
4779 * Terminals were designed back in the age before "certainty" was
4780 * invented, when standards were more what you'd call "guidelines"
4781 * than actual rules. Anyway we can't depend on them to operate
4782 * correctly. So when display attributes are changed, we punt,
4783 * reseting them all and turning back on the ones we want to keep.
4784 * Longer, but should be completely reliable. Savvy?
4786 if (oldp->xoc_effects != (newp->xoc_effects & oldp->xoc_effects)) {
4787 newp->xoc_effects |= XO_EFF_RESET;
4788 oldp->xoc_effects = 0;
4791 for (i = 0, bit = 1; xo_effect_names[i]; i++, bit <<= 1) {
4792 if ((newp->xoc_effects & bit) == (oldp->xoc_effects & bit))
4795 code = xo_effect_on_codes[i];
4797 cp += snprintf(cp, ep - cp, ";%s", code);
4799 return; /* Should not occur */
4801 if (bit == XO_EFF_RESET) {
4802 /* Mark up the old value so we can detect current values as new */
4803 oldp->xoc_effects = 0;
4804 oldp->xoc_col_fg = oldp->xoc_col_bg = XO_COL_DEFAULT;
4808 xo_color_t fg = newp->xoc_col_fg;
4809 if (fg != oldp->xoc_col_fg) {
4810 cp += snprintf(cp, ep - cp, ";3%u",
4811 (fg != XO_COL_DEFAULT) ? fg - 1 : 9);
4814 xo_color_t bg = newp->xoc_col_bg;
4815 if (bg != oldp->xoc_col_bg) {
4816 cp += snprintf(cp, ep - cp, ";4%u",
4817 (bg != XO_COL_DEFAULT) ? bg - 1 : 9);
4820 if (cp - buf != 1 && cp < ep - 3) {
4821 buf[1] = '['; /* Overwrite leading ';' */
4824 xo_buf_append(&xop->xo_data, buf, cp - buf);
4829 xo_colors_handle_html (xo_handle_t *xop, xo_colors_t *newp)
4831 xo_colors_t *oldp = &xop->xo_colors;
4834 * HTML colors are mostly trivial: fill in xo_color_buf with
4835 * a set of class tags representing the colors and effects.
4838 /* If nothing changed, then do nothing */
4839 if (oldp->xoc_effects == newp->xoc_effects
4840 && oldp->xoc_col_fg == newp->xoc_col_fg
4841 && oldp->xoc_col_bg == newp->xoc_col_bg)
4845 xo_buffer_t *xbp = &xop->xo_color_buf;
4847 xo_buf_reset(xbp); /* We rebuild content after each change */
4849 for (i = 0, bit = 1; xo_effect_names[i]; i++, bit <<= 1) {
4850 if (!(newp->xoc_effects & bit))
4853 xo_buf_append_str(xbp, " effect-");
4854 xo_buf_append_str(xbp, xo_effect_names[i]);
4857 const char *fg = NULL;
4858 const char *bg = NULL;
4860 if (newp->xoc_col_fg != XO_COL_DEFAULT)
4861 fg = xo_color_names[newp->xoc_col_fg];
4862 if (newp->xoc_col_bg != XO_COL_DEFAULT)
4863 bg = xo_color_names[newp->xoc_col_bg];
4865 if (newp->xoc_effects & XO_EFF_INVERSE) {
4866 const char *tmp = fg;
4877 xo_buf_append_str(xbp, " color-fg-");
4878 xo_buf_append_str(xbp, fg);
4882 xo_buf_append_str(xbp, " color-bg-");
4883 xo_buf_append_str(xbp, bg);
4888 xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip,
4889 const char *str, ssize_t len)
4891 const char *fmt = xfip->xfi_format;
4892 ssize_t flen = xfip->xfi_flen;
4896 /* If the string is static and we've in an encoding style, bail */
4897 if (len != 0 && xo_style_is_encoding(xop))
4903 xo_buf_append(&xb, str, len);
4905 xo_do_format_field(xop, &xb, fmt, flen, 0);
4907 xo_buf_append(&xb, "reset", 6); /* Default if empty */
4909 if (xo_colors_enabled(xop)) {
4910 switch (xo_style(xop)) {
4913 xo_buf_append(&xb, "", 1);
4915 xo_colors_t xoc = xop->xo_colors;
4916 xo_colors_parse(xop, &xoc, xb.xb_bufp);
4917 xo_colors_update(xop, &xoc);
4919 if (xo_style(xop) == XO_STYLE_TEXT) {
4921 * Text mode means emitting the colors as ANSI character
4922 * codes. This will allow people who like colors to have
4923 * colors. The issue is, of course conflicting with the
4924 * user's perfectly reasonable color scheme. Which leads
4925 * to the hell of LSCOLORS, where even app need to have
4926 * customization hooks for adjusting colors. Instead we
4927 * provide a simpler-but-still-annoying answer where one
4928 * can map colors to other colors.
4930 xo_colors_handle_text(xop, &xoc);
4931 xoc.xoc_effects &= ~XO_EFF_RESET; /* After handling it */
4935 * HTML output is wrapped in divs, so the color information
4936 * must appear in every div until cleared. Most pathetic.
4939 xoc.xoc_effects &= ~XO_EFF_RESET; /* Before handling effects */
4940 xo_colors_handle_html(xop, &xoc);
4943 xop->xo_colors = xoc;
4948 case XO_STYLE_SDPARAMS:
4949 case XO_STYLE_ENCODER:
4951 * Nothing to do; we did all that work just to clear the stack of
4952 * formatting arguments.
4958 xo_buf_cleanup(&xb);
4962 xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip,
4963 const char *str, ssize_t len)
4965 const char *fmt = xfip->xfi_format;
4966 ssize_t flen = xfip->xfi_flen;
4967 xo_xff_flags_t flags = xfip->xfi_flags;
4969 static char units_start_xml[] = " units=\"";
4970 static char units_start_html[] = " data-units=\"";
4972 if (!XOIF_ISSET(xop, XOIF_UNITS_PENDING)) {
4973 xo_format_content(xop, "units", NULL, str, len, fmt, flen, flags);
4977 xo_buffer_t *xbp = &xop->xo_data;
4978 ssize_t start = xop->xo_units_offset;
4979 ssize_t stop = xbp->xb_curp - xbp->xb_bufp;
4981 if (xo_style(xop) == XO_STYLE_XML)
4982 xo_buf_append(xbp, units_start_xml, sizeof(units_start_xml) - 1);
4983 else if (xo_style(xop) == XO_STYLE_HTML)
4984 xo_buf_append(xbp, units_start_html, sizeof(units_start_html) - 1);
4989 xo_data_escape(xop, str, len);
4991 xo_do_format_field(xop, NULL, fmt, flen, flags);
4993 xo_buf_append(xbp, "\"", 1);
4995 ssize_t now = xbp->xb_curp - xbp->xb_bufp;
4996 ssize_t delta = now - stop;
4997 if (delta <= 0) { /* Strange; no output to move */
4998 xbp->xb_curp = xbp->xb_bufp + stop; /* Reset buffer to prior state */
5003 * Now we're in it alright. We've need to insert the unit value
5004 * we just created into the right spot. We make a local copy,
5005 * move it and then insert our copy. We know there's room in the
5006 * buffer, since we're just moving this around.
5008 char *buf = alloca(delta);
5010 memcpy(buf, xbp->xb_bufp + stop, delta);
5011 memmove(xbp->xb_bufp + start + delta, xbp->xb_bufp + start, stop - start);
5012 memmove(xbp->xb_bufp + start, buf, delta);
5016 xo_find_width (xo_handle_t *xop, xo_field_info_t *xfip,
5017 const char *str, ssize_t len)
5019 const char *fmt = xfip->xfi_format;
5020 ssize_t flen = xfip->xfi_flen;
5027 bp = alloca(len + 1); /* Make local NUL-terminated copy of str */
5028 memcpy(bp, str, len);
5031 width = strtol(bp, &cp, 0);
5032 if (width == LONG_MIN || width == LONG_MAX
5033 || bp == cp || *cp != '\0' ) {
5035 xo_failure(xop, "invalid width for anchor: '%s'", bp);
5038 if (flen != 2 || strncmp("%d", fmt, flen) != 0)
5039 xo_failure(xop, "invalid width format: '%*.*s'", flen, flen, fmt);
5040 if (!XOF_ISSET(xop, XOF_NO_VA_ARG))
5041 width = va_arg(xop->xo_vap, int);
5048 xo_anchor_clear (xo_handle_t *xop)
5050 XOIF_CLEAR(xop, XOIF_ANCHOR);
5051 xop->xo_anchor_offset = 0;
5052 xop->xo_anchor_columns = 0;
5053 xop->xo_anchor_min_width = 0;
5057 * An anchor is a marker used to delay field width implications.
5058 * Imagine the format string "{[:10}{min:%d}/{cur:%d}/{max:%d}{:]}".
5059 * We are looking for output like " 1/4/5"
5061 * To make this work, we record the anchor and then return to
5062 * format it when the end anchor tag is seen.
5065 xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip,
5066 const char *str, ssize_t len)
5068 if (xo_style(xop) != XO_STYLE_TEXT && xo_style(xop) != XO_STYLE_HTML)
5071 if (XOIF_ISSET(xop, XOIF_ANCHOR))
5072 xo_failure(xop, "the anchor already recording is discarded");
5074 XOIF_SET(xop, XOIF_ANCHOR);
5075 xo_buffer_t *xbp = &xop->xo_data;
5076 xop->xo_anchor_offset = xbp->xb_curp - xbp->xb_bufp;
5077 xop->xo_anchor_columns = 0;
5080 * Now we find the width, if possible. If it's not there,
5081 * we'll get it on the end anchor.
5083 xop->xo_anchor_min_width = xo_find_width(xop, xfip, str, len);
5087 xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip,
5088 const char *str, ssize_t len)
5090 if (xo_style(xop) != XO_STYLE_TEXT && xo_style(xop) != XO_STYLE_HTML)
5093 if (!XOIF_ISSET(xop, XOIF_ANCHOR)) {
5094 xo_failure(xop, "no start anchor");
5098 XOIF_CLEAR(xop, XOIF_UNITS_PENDING);
5100 ssize_t width = xo_find_width(xop, xfip, str, len);
5102 width = xop->xo_anchor_min_width;
5104 if (width == 0) /* No width given; nothing to do */
5107 xo_buffer_t *xbp = &xop->xo_data;
5108 ssize_t start = xop->xo_anchor_offset;
5109 ssize_t stop = xbp->xb_curp - xbp->xb_bufp;
5110 ssize_t abswidth = (width > 0) ? width : -width;
5111 ssize_t blen = abswidth - xop->xo_anchor_columns;
5113 if (blen <= 0) /* Already over width */
5116 if (abswidth > XO_MAX_ANCHOR_WIDTH) {
5117 xo_failure(xop, "width over %u are not supported",
5118 XO_MAX_ANCHOR_WIDTH);
5122 /* Make a suitable padding field and emit it */
5123 char *buf = alloca(blen);
5124 memset(buf, ' ', blen);
5125 xo_format_content(xop, "padding", NULL, buf, blen, NULL, 0, 0);
5127 if (width < 0) /* Already left justified */
5130 ssize_t now = xbp->xb_curp - xbp->xb_bufp;
5131 ssize_t delta = now - stop;
5132 if (delta <= 0) /* Strange; no output to move */
5136 * Now we're in it alright. We've need to insert the padding data
5137 * we just created (which might be an HTML <div> or text) before
5138 * the formatted data. We make a local copy, move it and then
5139 * insert our copy. We know there's room in the buffer, since
5140 * we're just moving this around.
5143 buf = alloca(delta); /* Expand buffer if needed */
5145 memcpy(buf, xbp->xb_bufp + stop, delta);
5146 memmove(xbp->xb_bufp + start + delta, xbp->xb_bufp + start, stop - start);
5147 memmove(xbp->xb_bufp + start, buf, delta);
5150 xo_anchor_clear(xop);
5154 xo_class_name (int ftype)
5157 case 'D': return "decoration";
5158 case 'E': return "error";
5159 case 'L': return "label";
5160 case 'N': return "note";
5161 case 'P': return "padding";
5162 case 'W': return "warning";
5169 xo_tag_name (int ftype)
5172 case 'E': return "__error";
5173 case 'W': return "__warning";
5180 xo_role_wants_default_format (int ftype)
5183 /* These roles can be completely empty and/or without formatting */
5194 static xo_mapping_t xo_role_names[] = {
5196 { 'D', "decoration" },
5205 { '[', "start-anchor" },
5206 { ']', "stop-anchor" },
5210 #define XO_ROLE_EBRACE '{' /* Escaped braces */
5211 #define XO_ROLE_TEXT '+'
5212 #define XO_ROLE_NEWLINE '\n'
5214 static xo_mapping_t xo_modifier_names[] = {
5215 { XFF_ARGUMENT, "argument" },
5216 { XFF_COLON, "colon" },
5217 { XFF_COMMA, "comma" },
5218 { XFF_DISPLAY_ONLY, "display" },
5219 { XFF_ENCODE_ONLY, "encoding" },
5220 { XFF_GT_FIELD, "gettext" },
5221 { XFF_HUMANIZE, "humanize" },
5222 { XFF_HUMANIZE, "hn" },
5223 { XFF_HN_SPACE, "hn-space" },
5224 { XFF_HN_DECIMAL, "hn-decimal" },
5225 { XFF_HN_1000, "hn-1000" },
5227 { XFF_LEAF_LIST, "leaf-list" },
5228 { XFF_LEAF_LIST, "list" },
5229 { XFF_NOQUOTE, "no-quotes" },
5230 { XFF_NOQUOTE, "no-quote" },
5231 { XFF_GT_PLURAL, "plural" },
5232 { XFF_QUOTE, "quotes" },
5233 { XFF_QUOTE, "quote" },
5234 { XFF_TRIM_WS, "trim" },
5235 { XFF_WS, "white" },
5239 #ifdef NOT_NEEDED_YET
5240 static xo_mapping_t xo_modifier_short_names[] = {
5242 { XFF_DISPLAY_ONLY, "d" },
5243 { XFF_ENCODE_ONLY, "e" },
5244 { XFF_GT_FIELD, "g" },
5245 { XFF_HUMANIZE, "h" },
5247 { XFF_LEAF_LIST, "l" },
5248 { XFF_NOQUOTE, "n" },
5249 { XFF_GT_PLURAL, "p" },
5251 { XFF_TRIM_WS, "t" },
5255 #endif /* NOT_NEEDED_YET */
5258 xo_count_fields (xo_handle_t *xop UNUSED, const char *fmt)
5263 for (cp = fmt; *cp; cp++)
5264 if (*cp == '{' || *cp == '\n')
5271 * The field format is:
5272 * '{' modifiers ':' content [ '/' print-fmt [ '/' encode-fmt ]] '}'
5273 * Roles are optional and include the following field types:
5274 * 'D': decoration; something non-text and non-data (colons, commmas)
5275 * 'E': error message
5276 * 'G': gettext() the entire string; optional domainname as content
5277 * 'L': label; text preceding data
5278 * 'N': note; text following data
5279 * 'P': padding; whitespace
5280 * 'T': Title, where 'content' is a column title
5281 * 'U': Units, where 'content' is the unit label
5282 * 'V': value, where 'content' is the name of the field (the default)
5283 * 'W': warning message
5284 * '[': start a section of anchored text
5285 * ']': end a section of anchored text
5286 * The following modifiers are also supported:
5287 * 'a': content is provided via argument (const char *), not descriptor
5288 * 'c': flag: emit a colon after the label
5289 * 'd': field is only emitted for display styles (text and html)
5290 * 'e': field is only emitted for encoding styles (xml and json)
5291 * 'g': gettext() the field
5292 * 'h': humanize a numeric value (only for display styles)
5293 * 'k': this field is a key, suitable for XPath predicates
5294 * 'l': a leaf-list, a simple list of values
5295 * 'n': no quotes around this field
5296 * 'p': the field has plural gettext semantics (ngettext)
5297 * 'q': add quotes around this field
5298 * 't': trim whitespace around the value
5299 * 'w': emit a blank after the label
5300 * The print-fmt and encode-fmt strings is the printf-style formating
5301 * for this data. JSON and XML will use the encoding-fmt, if present.
5302 * If the encode-fmt is not provided, it defaults to the print-fmt.
5303 * If the print-fmt is not provided, it defaults to 's'.
5306 xo_parse_roles (xo_handle_t *xop, const char *fmt,
5307 const char *basep, xo_field_info_t *xfip)
5311 xo_xff_flags_t flags = 0;
5314 for (sp = basep; sp && *sp; sp++) {
5315 if (*sp == ':' || *sp == '/' || *sp == '}')
5319 if (sp[1] == '\0') {
5320 xo_failure(xop, "backslash at the end of string");
5324 /* Anything backslashed is ignored */
5331 for (np = ++sp; *np; np++)
5332 if (*np == ':' || *np == '/' || *np == '}' || *np == ',')
5335 ssize_t slen = np - sp;
5337 xo_xff_flags_t value;
5339 value = xo_name_lookup(xo_role_names, sp, slen);
5343 value = xo_name_lookup(xo_modifier_names, sp, slen);
5347 xo_failure(xop, "unknown keyword ignored: '%.*s'",
5371 xo_failure(xop, "field descriptor uses multiple types: '%s'",
5388 fnum = (fnum * 10) + (*sp - '0');
5392 flags |= XFF_ARGUMENT;
5400 flags |= XFF_DISPLAY_ONLY;
5404 flags |= XFF_ENCODE_ONLY;
5408 flags |= XFF_GT_FIELD;
5412 flags |= XFF_HUMANIZE;
5420 flags |= XFF_LEAF_LIST;
5424 flags |= XFF_NOQUOTE;
5428 flags |= XFF_GT_PLURAL;
5436 flags |= XFF_TRIM_WS;
5444 xo_failure(xop, "field descriptor uses unknown modifier: '%s'",
5447 * No good answer here; a bad format will likely
5448 * mean a core file. We just return and hope
5449 * the caller notices there's no output, and while
5450 * that seems, well, bad, there's nothing better.
5455 if (ftype == 'N' || ftype == 'U') {
5456 if (flags & XFF_COLON) {
5457 xo_failure(xop, "colon modifier on 'N' or 'U' field ignored: "
5458 "'%s'", xo_printable(fmt));
5459 flags &= ~XFF_COLON;
5464 xfip->xfi_flags = flags;
5465 xfip->xfi_ftype = ftype ?: 'V';
5466 xfip->xfi_fnum = fnum;
5472 * Number any remaining fields that need numbers. Note that some
5473 * field types (text, newline, escaped braces) never get numbers.
5476 xo_gettext_finish_numbering_fields (xo_handle_t *xop UNUSED,
5477 const char *fmt UNUSED,
5478 xo_field_info_t *fields)
5480 xo_field_info_t *xfip;
5481 unsigned fnum, max_fields;
5484 /* First make a list of add the explicitly used bits */
5485 for (xfip = fields, fnum = 0; xfip->xfi_ftype; xfip++) {
5486 switch (xfip->xfi_ftype) {
5487 case XO_ROLE_NEWLINE: /* Don't get numbered */
5489 case XO_ROLE_EBRACE:
5499 bits |= 1 << xfip->xfi_fnum;
5504 for (xfip = fields, fnum = 0; xfip->xfi_ftype; xfip++) {
5505 switch (xfip->xfi_ftype) {
5506 case XO_ROLE_NEWLINE: /* Don't get numbered */
5508 case XO_ROLE_EBRACE:
5513 if (xfip->xfi_fnum != 0)
5516 /* Find the next unassigned field */
5517 for (fnum++; bits & (1 << fnum); fnum++)
5520 if (fnum > max_fields)
5523 xfip->xfi_fnum = fnum; /* Mark the field number */
5524 bits |= 1 << fnum; /* Mark it used */
5529 * The format string uses field numbers, so we need to whiffle through it
5530 * and make sure everything's sane and lovely.
5533 xo_parse_field_numbers (xo_handle_t *xop, const char *fmt,
5534 xo_field_info_t *fields, unsigned num_fields)
5536 xo_field_info_t *xfip;
5537 unsigned field, fnum;
5540 for (xfip = fields, field = 0; field < num_fields; xfip++, field++) {
5541 /* Fields default to 1:1 with natural position */
5542 if (xfip->xfi_fnum == 0)
5543 xfip->xfi_fnum = field + 1;
5544 else if (xfip->xfi_fnum > num_fields) {
5545 xo_failure(xop, "field number exceeds number of fields: '%s'", fmt);
5549 fnum = xfip->xfi_fnum - 1; /* Move to zero origin */
5550 if (fnum < 64) { /* Only test what fits */
5551 if (bits & (1 << fnum)) {
5552 xo_failure(xop, "field number %u reused: '%s'",
5553 xfip->xfi_fnum, fmt);
5564 xo_parse_fields (xo_handle_t *xop, xo_field_info_t *fields,
5565 unsigned num_fields, const char *fmt)
5567 const char *cp, *sp, *ep, *basep;
5569 xo_field_info_t *xfip = fields;
5570 unsigned seen_fnum = 0;
5572 for (cp = fmt; *cp && field < num_fields; field++, xfip++) {
5573 xfip->xfi_start = cp;
5576 xfip->xfi_ftype = XO_ROLE_NEWLINE;
5584 for (sp = cp; *sp; sp++) {
5585 if (*sp == '{' || *sp == '\n')
5589 xfip->xfi_ftype = XO_ROLE_TEXT;
5590 xfip->xfi_content = cp;
5591 xfip->xfi_clen = sp - cp;
5592 xfip->xfi_next = sp;
5598 if (cp[1] == '{') { /* Start of {{escaped braces}} */
5599 xfip->xfi_start = cp + 1; /* Start at second brace */
5600 xfip->xfi_ftype = XO_ROLE_EBRACE;
5602 cp += 2; /* Skip over _both_ characters */
5603 for (sp = cp; *sp; sp++) {
5604 if (*sp == '}' && sp[1] == '}')
5608 xo_failure(xop, "missing closing '}}': '%s'",
5613 xfip->xfi_len = sp - xfip->xfi_start + 1;
5615 /* Move along the string, but don't run off the end */
5616 if (*sp == '}' && sp[1] == '}')
5619 xfip->xfi_next = cp;
5623 /* We are looking at the start of a field definition */
5624 xfip->xfi_start = basep = cp + 1;
5626 const char *format = NULL;
5629 /* Looking at roles and modifiers */
5630 sp = xo_parse_roles(xop, fmt, basep, xfip);
5632 /* xo_failure has already been called */
5639 /* Looking at content */
5641 for (ep = ++sp; *sp; sp++) {
5642 if (*sp == '}' || *sp == '/')
5645 if (sp[1] == '\0') {
5646 xo_failure(xop, "backslash at the end of string");
5654 xfip->xfi_clen = sp - ep;
5655 xfip->xfi_content = ep;
5658 xo_failure(xop, "missing content (':'): '%s'", xo_printable(fmt));
5662 /* Looking at main (display) format */
5664 for (ep = ++sp; *sp; sp++) {
5665 if (*sp == '}' || *sp == '/')
5668 if (sp[1] == '\0') {
5669 xo_failure(xop, "backslash at the end of string");
5680 /* Looking at encoding format */
5682 for (ep = ++sp; *sp; sp++) {
5687 xfip->xfi_encoding = ep;
5688 xfip->xfi_elen = sp - ep;
5692 xo_failure(xop, "missing closing '}': %s", xo_printable(fmt));
5696 xfip->xfi_len = sp - xfip->xfi_start;
5697 xfip->xfi_next = ++sp;
5699 /* If we have content, then we have a default format */
5700 if (xfip->xfi_clen || format || (xfip->xfi_flags & XFF_ARGUMENT)) {
5702 xfip->xfi_format = format;
5703 xfip->xfi_flen = flen;
5704 } else if (xo_role_wants_default_format(xfip->xfi_ftype)) {
5705 xfip->xfi_format = xo_default_format;
5716 * If we saw a field number on at least one field, then we need
5717 * to enforce some rules and/or guidelines.
5720 rc = xo_parse_field_numbers(xop, fmt, fields, field);
5726 * We are passed a pointer to a format string just past the "{G:}"
5727 * field. We build a simplified version of the format string.
5730 xo_gettext_simplify_format (xo_handle_t *xop UNUSED,
5732 xo_field_info_t *fields,
5734 const char *fmt UNUSED,
5735 xo_simplify_field_func_t field_cb)
5738 xo_xff_flags_t flags;
5739 int field = this_field + 1;
5740 xo_field_info_t *xfip;
5743 for (xfip = &fields[field]; xfip->xfi_ftype; xfip++, field++) {
5744 ftype = xfip->xfi_ftype;
5745 flags = xfip->xfi_flags;
5747 if ((flags & XFF_GT_FIELD) && xfip->xfi_content && ftype != 'V') {
5749 field_cb(xfip->xfi_content, xfip->xfi_clen,
5750 (flags & XFF_GT_PLURAL) ? 1 : 0);
5755 /* Ignore gettext roles */
5758 case XO_ROLE_NEWLINE:
5759 xo_buf_append(xbp, "\n", 1);
5762 case XO_ROLE_EBRACE:
5763 xo_buf_append(xbp, "{", 1);
5764 xo_buf_append(xbp, xfip->xfi_content, xfip->xfi_clen);
5765 xo_buf_append(xbp, "}", 1);
5769 xo_buf_append(xbp, xfip->xfi_content, xfip->xfi_clen);
5773 xo_buf_append(xbp, "{", 1);
5776 xo_buf_append(xbp, &ch, 1);
5779 unsigned fnum = xfip->xfi_fnum ?: 0;
5782 /* Field numbers are origin 1, not 0, following printf(3) */
5783 snprintf(num, sizeof(num), "%u", fnum);
5784 xo_buf_append(xbp, num, strlen(num));
5787 xo_buf_append(xbp, ":", 1);
5788 xo_buf_append(xbp, xfip->xfi_content, xfip->xfi_clen);
5789 xo_buf_append(xbp, "}", 1);
5793 xo_buf_append(xbp, "", 1);
5798 xo_dump_fields (xo_field_info_t *); /* Fake prototype for debug function */
5800 xo_dump_fields (xo_field_info_t *fields)
5802 xo_field_info_t *xfip;
5804 for (xfip = fields; xfip->xfi_ftype; xfip++) {
5805 printf("%lu(%u): %lx [%c/%u] [%.*s] [%.*s] [%.*s]\n",
5806 (unsigned long) (xfip - fields), xfip->xfi_fnum,
5807 (unsigned long) xfip->xfi_flags,
5808 isprint((int) xfip->xfi_ftype) ? xfip->xfi_ftype : ' ',
5810 (int) xfip->xfi_clen, xfip->xfi_content ?: "",
5811 (int) xfip->xfi_flen, xfip->xfi_format ?: "",
5812 (int) xfip->xfi_elen, xfip->xfi_encoding ?: "");
5818 * Find the field that matches the given field number
5820 static xo_field_info_t *
5821 xo_gettext_find_field (xo_field_info_t *fields, unsigned fnum)
5823 xo_field_info_t *xfip;
5825 for (xfip = fields; xfip->xfi_ftype; xfip++)
5826 if (xfip->xfi_fnum == fnum)
5833 * At this point, we need to consider if the fields have been reordered,
5834 * such as "The {:adjective} {:noun}" to "La {:noun} {:adjective}".
5836 * We need to rewrite the new_fields using the old fields order,
5837 * so that we can render the message using the arguments as they
5838 * appear on the stack. It's a lot of work, but we don't really
5839 * want to (eventually) fall into the standard printf code which
5840 * means using the arguments straight (and in order) from the
5841 * varargs we were originally passed.
5844 xo_gettext_rewrite_fields (xo_handle_t *xop UNUSED,
5845 xo_field_info_t *fields, unsigned max_fields)
5847 xo_field_info_t tmp[max_fields];
5848 bzero(tmp, max_fields * sizeof(tmp[0]));
5851 xo_field_info_t *newp, *outp, *zp;
5852 for (newp = fields, outp = tmp; newp->xfi_ftype; newp++, outp++) {
5853 switch (newp->xfi_ftype) {
5854 case XO_ROLE_NEWLINE: /* Don't get numbered */
5856 case XO_ROLE_EBRACE:
5859 outp->xfi_renum = 0;
5863 zp = xo_gettext_find_field(fields, ++fnum);
5864 if (zp == NULL) { /* Should not occur */
5866 outp->xfi_renum = 0;
5871 outp->xfi_renum = newp->xfi_fnum;
5874 memcpy(fields, tmp, max_fields * sizeof(tmp[0]));
5878 * We've got two lists of fields, the old list from the original
5879 * format string and the new one from the parsed gettext reply. The
5880 * new list has the localized words, where the old list has the
5881 * formatting information. We need to combine them into a single list
5884 * If the list needs to be reordered, then we've got more serious work
5888 xo_gettext_combine_formats (xo_handle_t *xop, const char *fmt UNUSED,
5889 const char *gtfmt, xo_field_info_t *old_fields,
5890 xo_field_info_t *new_fields, unsigned new_max_fields,
5894 xo_field_info_t *newp, *oldp, *startp = old_fields;
5896 xo_gettext_finish_numbering_fields(xop, fmt, old_fields);
5898 for (newp = new_fields; newp->xfi_ftype; newp++) {
5899 switch (newp->xfi_ftype) {
5900 case XO_ROLE_NEWLINE:
5902 case XO_ROLE_EBRACE:
5906 for (oldp = startp; oldp->xfi_ftype; oldp++) {
5907 if (oldp->xfi_ftype != 'V')
5909 if (newp->xfi_clen != oldp->xfi_clen
5910 || strncmp(newp->xfi_content, oldp->xfi_content,
5911 oldp->xfi_clen) != 0) {
5919 /* Didn't find it on the first pass (starting from start) */
5920 if (oldp->xfi_ftype == 0) {
5921 for (oldp = old_fields; oldp < startp; oldp++) {
5922 if (oldp->xfi_ftype != 'V')
5924 if (newp->xfi_clen != oldp->xfi_clen)
5926 if (strncmp(newp->xfi_content, oldp->xfi_content,
5927 oldp->xfi_clen) != 0)
5932 if (oldp == startp) {
5933 /* Field not found */
5934 xo_failure(xop, "post-gettext format can't find field "
5935 "'%.*s' in format '%s'",
5936 newp->xfi_clen, newp->xfi_content,
5937 xo_printable(gtfmt));
5945 * Other fields don't have names for us to use, so if
5946 * the types aren't the same, then we'll have to assume
5947 * the original field is a match.
5949 for (oldp = startp; oldp->xfi_ftype; oldp++) {
5950 if (oldp->xfi_ftype == 'V') /* Can't go past these */
5952 if (oldp->xfi_ftype == newp->xfi_ftype)
5953 goto copy_it; /* Assumably we have a match */
5959 * Found a match; copy over appropriate fields
5962 newp->xfi_flags = oldp->xfi_flags;
5963 newp->xfi_fnum = oldp->xfi_fnum;
5964 newp->xfi_format = oldp->xfi_format;
5965 newp->xfi_flen = oldp->xfi_flen;
5966 newp->xfi_encoding = oldp->xfi_encoding;
5967 newp->xfi_elen = oldp->xfi_elen;
5970 *reorderedp = reordered;
5972 xo_gettext_finish_numbering_fields(xop, fmt, new_fields);
5973 xo_gettext_rewrite_fields(xop, new_fields, new_max_fields);
5980 * We don't want to make gettext() calls here with a complete format
5981 * string, since that means changing a flag would mean a
5982 * labor-intensive re-translation expense. Instead we build a
5983 * simplified form with a reduced level of detail, perform a lookup on
5984 * that string and then re-insert the formating info.
5986 * So something like:
5987 * xo_emit("{G:}close {:fd/%ld} returned {g:error/%m} {:test/%6.6s}\n", ...)
5988 * would have a lookup string of:
5989 * "close {:fd} returned {:error} {:test}\n"
5991 * We also need to handling reordering of fields, where the gettext()
5992 * reply string uses fields in a different order than the original
5994 * "cluse-a {:fd} retoorned {:test}. Bork {:error} Bork. Bork.\n"
5995 * If we have to reorder fields within the message, then things get
5996 * complicated. See xo_gettext_rewrite_fields.
5998 * Summary: i18n aighn't cheap.
6001 xo_gettext_build_format (xo_handle_t *xop,
6002 xo_field_info_t *fields, int this_field,
6003 const char *fmt, char **new_fmtp)
6005 if (xo_style_is_encoding(xop))
6011 if (xo_gettext_simplify_format(xop, &xb, fields,
6012 this_field, fmt, NULL))
6015 const char *gtfmt = xo_dgettext(xop, xb.xb_bufp);
6016 if (gtfmt == NULL || gtfmt == fmt || strcmp(gtfmt, fmt) == 0)
6019 char *new_fmt = xo_strndup(gtfmt, -1);
6020 if (new_fmt == NULL)
6023 xo_buf_cleanup(&xb);
6025 *new_fmtp = new_fmt;
6029 xo_buf_cleanup(&xb);
6036 xo_gettext_rebuild_content (xo_handle_t *xop, xo_field_info_t *fields,
6037 ssize_t *fstart, unsigned min_fstart,
6038 ssize_t *fend, unsigned max_fend)
6040 xo_field_info_t *xfip;
6042 ssize_t base = fstart[min_fstart];
6043 ssize_t blen = fend[max_fend] - base;
6044 xo_buffer_t *xbp = &xop->xo_data;
6049 buf = xo_realloc(NULL, blen);
6053 memcpy(buf, xbp->xb_bufp + fstart[min_fstart], blen); /* Copy our data */
6055 unsigned field = min_fstart, len, fnum;
6056 ssize_t soff, doff = base;
6057 xo_field_info_t *zp;
6060 * Be aware there are two competing views of "field number": we
6061 * want the user to thing in terms of "The {1:size}" where {G:},
6062 * newlines, escaped braces, and text don't have numbers. But is
6063 * also the internal view, where we have an array of
6064 * xo_field_info_t and every field have an index. fnum, fstart[]
6065 * and fend[] are the latter, but xfi_renum is the former.
6067 for (xfip = fields + field; xfip->xfi_ftype; xfip++, field++) {
6069 if (xfip->xfi_renum) {
6070 zp = xo_gettext_find_field(fields, xfip->xfi_renum);
6071 fnum = zp ? zp - fields : field;
6074 soff = fstart[fnum];
6075 len = fend[fnum] - soff;
6079 memcpy(xbp->xb_bufp + doff, buf + soff, len);
6086 #else /* HAVE_GETTEXT */
6088 xo_gettext_build_format (xo_handle_t *xop UNUSED,
6089 xo_field_info_t *fields UNUSED,
6090 int this_field UNUSED,
6091 const char *fmt UNUSED, char **new_fmtp)
6098 xo_gettext_combine_formats (xo_handle_t *xop UNUSED, const char *fmt UNUSED,
6099 const char *gtfmt UNUSED,
6100 xo_field_info_t *old_fields UNUSED,
6101 xo_field_info_t *new_fields UNUSED,
6102 unsigned new_max_fields UNUSED,
6103 int *reorderedp UNUSED)
6109 xo_gettext_rebuild_content (xo_handle_t *xop UNUSED,
6110 xo_field_info_t *fields UNUSED,
6111 ssize_t *fstart UNUSED, unsigned min_fstart UNUSED,
6112 ssize_t *fend UNUSED, unsigned max_fend UNUSED)
6116 #endif /* HAVE_GETTEXT */
6119 * Emit a set of fields. This is really the core of libxo.
6122 xo_do_emit_fields (xo_handle_t *xop, xo_field_info_t *fields,
6123 unsigned max_fields, const char *fmt)
6125 int gettext_inuse = 0;
6126 int gettext_changed = 0;
6127 int gettext_reordered = 0;
6129 xo_xff_flags_t flags;
6130 xo_field_info_t *new_fields = NULL;
6131 xo_field_info_t *xfip;
6135 int flush = XOF_ISSET(xop, XOF_FLUSH);
6136 int flush_line = XOF_ISSET(xop, XOF_FLUSH_LINE);
6137 char *new_fmt = NULL;
6139 if (XOIF_ISSET(xop, XOIF_REORDER) || xo_style(xop) == XO_STYLE_ENCODER)
6143 * Some overhead for gettext; if the fields in the msgstr returned
6144 * by gettext are reordered, then we need to record start and end
6145 * for each field. We'll go ahead and render the fields in the
6146 * normal order, but later we can then reconstruct the reordered
6147 * fields using these fstart/fend values.
6149 unsigned flimit = max_fields * 2; /* Pessimistic limit */
6150 unsigned min_fstart = flimit - 1;
6151 unsigned max_fend = 0; /* Highest recorded fend[] entry */
6152 ssize_t fstart[flimit];
6153 bzero(fstart, flimit * sizeof(fstart[0]));
6154 ssize_t fend[flimit];
6155 bzero(fend, flimit * sizeof(fend[0]));
6157 for (xfip = fields, field = 0; field < max_fields && xfip->xfi_ftype;
6159 ftype = xfip->xfi_ftype;
6160 flags = xfip->xfi_flags;
6162 /* Record field start offset */
6163 if (gettext_reordered) {
6164 fstart[field] = xo_buf_offset(&xop->xo_data);
6165 if (min_fstart > field)
6169 const char *content = xfip->xfi_content;
6170 ssize_t clen = xfip->xfi_clen;
6172 if (flags & XFF_ARGUMENT) {
6174 * Argument flag means the content isn't given in the descriptor,
6175 * but as a UTF-8 string ('const char *') argument in xo_vap.
6177 content = va_arg(xop->xo_vap, char *);
6178 clen = content ? strlen(content) : 0;
6181 if (ftype == XO_ROLE_NEWLINE) {
6183 if (flush_line && xo_flush_h(xop) < 0)
6187 } else if (ftype == XO_ROLE_EBRACE) {
6188 xo_format_text(xop, xfip->xfi_start, xfip->xfi_len);
6191 } else if (ftype == XO_ROLE_TEXT) {
6193 xo_format_text(xop, xfip->xfi_content, xfip->xfi_clen);
6198 * Notes and units need the 'w' flag handled before the content.
6200 if (ftype == 'N' || ftype == 'U') {
6201 if (flags & XFF_WS) {
6202 xo_format_content(xop, "padding", NULL, " ", 1,
6204 flags &= ~XFF_WS; /* Block later handling of this */
6209 xo_format_value(xop, content, clen,
6210 xfip->xfi_format, xfip->xfi_flen,
6211 xfip->xfi_encoding, xfip->xfi_elen, flags);
6212 else if (ftype == '[')
6213 xo_anchor_start(xop, xfip, content, clen);
6214 else if (ftype == ']')
6215 xo_anchor_stop(xop, xfip, content, clen);
6216 else if (ftype == 'C')
6217 xo_format_colors(xop, xfip, content, clen);
6219 else if (ftype == 'G') {
6221 * A {G:domain} field; disect the domain name and translate
6222 * the remaining portion of the input string. If the user
6223 * didn't put the {G:} at the start of the format string, then
6224 * assumably they just want us to translate the rest of it.
6225 * Since gettext returns strings in a static buffer, we make
6226 * a copy in new_fmt.
6228 xo_set_gettext_domain(xop, xfip, content, clen);
6230 if (!gettext_inuse) { /* Only translate once */
6237 xo_gettext_build_format(xop, fields, field,
6238 xfip->xfi_next, &new_fmt);
6240 gettext_changed = 1;
6242 unsigned new_max_fields = xo_count_fields(xop, new_fmt);
6244 if (++new_max_fields < max_fields)
6245 new_max_fields = max_fields;
6247 /* Leave a blank slot at the beginning */
6248 ssize_t sz = (new_max_fields + 1) * sizeof(xo_field_info_t);
6249 new_fields = alloca(sz);
6250 bzero(new_fields, sz);
6252 if (!xo_parse_fields(xop, new_fields + 1,
6253 new_max_fields, new_fmt)) {
6254 gettext_reordered = 0;
6256 if (!xo_gettext_combine_formats(xop, fmt, new_fmt,
6257 fields, new_fields + 1,
6258 new_max_fields, &gettext_reordered)) {
6260 if (gettext_reordered) {
6261 if (XOF_ISSET(xop, XOF_LOG_GETTEXT))
6262 xo_failure(xop, "gettext finds reordered "
6263 "fields in '%s' and '%s'",
6265 xo_printable(new_fmt));
6266 flush_line = 0; /* Must keep at content */
6267 XOIF_SET(xop, XOIF_REORDER);
6270 field = -1; /* Will be incremented at top of loop */
6272 max_fields = new_max_fields;
6279 } else if (clen || xfip->xfi_format) {
6281 const char *class_name = xo_class_name(ftype);
6283 xo_format_content(xop, class_name, xo_tag_name(ftype),
6285 xfip->xfi_format, xfip->xfi_flen, flags);
6286 else if (ftype == 'T')
6287 xo_format_title(xop, xfip, content, clen);
6288 else if (ftype == 'U')
6289 xo_format_units(xop, xfip, content, clen);
6291 xo_failure(xop, "unknown field type: '%c'", ftype);
6294 if (flags & XFF_COLON)
6295 xo_format_content(xop, "decoration", NULL, ":", 1, NULL, 0, 0);
6298 xo_format_content(xop, "padding", NULL, " ", 1, NULL, 0, 0);
6301 /* Record the end-of-field offset */
6302 if (gettext_reordered) {
6303 fend[field] = xo_buf_offset(&xop->xo_data);
6308 if (gettext_changed && gettext_reordered) {
6309 /* Final step: rebuild the content using the rendered fields */
6310 xo_gettext_rebuild_content(xop, new_fields + 1, fstart, min_fstart,
6314 XOIF_CLEAR(xop, XOIF_REORDER);
6317 * If we've got enough data, flush it.
6319 if (xo_buf_offset(&xop->xo_data) > XO_BUF_HIGH_WATER)
6322 /* If we don't have an anchor, write the text out */
6323 if (flush && !XOIF_ISSET(xop, XOIF_ANCHOR)) {
6324 if (xo_write(xop) < 0)
6325 rc = -1; /* Report failure */
6326 else if (xo_flush_h(xop) < 0)
6334 * We've carried the gettext domainname inside our handle just for
6335 * convenience, but we need to ensure it doesn't survive across
6338 if (xop->xo_gt_domain) {
6339 xo_free(xop->xo_gt_domain);
6340 xop->xo_gt_domain = NULL;
6343 return (rc < 0) ? rc : xop->xo_columns;
6347 * Parse and emit a set of fields
6350 xo_do_emit (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt)
6352 xop->xo_columns = 0; /* Always reset it */
6353 xop->xo_errno = errno; /* Save for "%m" */
6358 unsigned max_fields;
6359 xo_field_info_t *fields = NULL;
6361 /* Adjust XOEF_RETAIN based on global flags */
6362 if (XOF_ISSET(xop, XOF_RETAIN_ALL))
6363 flags |= XOEF_RETAIN;
6364 if (XOF_ISSET(xop, XOF_RETAIN_NONE))
6365 flags &= ~XOEF_RETAIN;
6368 * Check for 'retain' flag, telling us to retain the field
6369 * information. If we've already saved it, then we can avoid
6370 * re-parsing the format string.
6372 if (!(flags & XOEF_RETAIN)
6373 || xo_retain_find(fmt, &fields, &max_fields) != 0
6374 || fields == NULL) {
6376 /* Nothing retained; parse the format string */
6377 max_fields = xo_count_fields(xop, fmt);
6378 fields = alloca(max_fields * sizeof(fields[0]));
6379 bzero(fields, max_fields * sizeof(fields[0]));
6381 if (xo_parse_fields(xop, fields, max_fields, fmt))
6382 return -1; /* Warning already displayed */
6384 if (flags & XOEF_RETAIN) {
6385 /* Retain the info */
6386 xo_retain_add(fmt, fields, max_fields);
6390 return xo_do_emit_fields(xop, fields, max_fields, fmt);
6394 * Rebuild a format string in a gettext-friendly format. This function
6395 * is exposed to tools can perform this function. See xo(1).
6398 xo_simplify_format (xo_handle_t *xop, const char *fmt, int with_numbers,
6399 xo_simplify_field_func_t field_cb)
6401 xop = xo_default(xop);
6403 xop->xo_columns = 0; /* Always reset it */
6404 xop->xo_errno = errno; /* Save for "%m" */
6406 unsigned max_fields = xo_count_fields(xop, fmt);
6407 xo_field_info_t fields[max_fields];
6409 bzero(fields, max_fields * sizeof(fields[0]));
6411 if (xo_parse_fields(xop, fields, max_fields, fmt))
6412 return NULL; /* Warning already displayed */
6418 xo_gettext_finish_numbering_fields(xop, fmt, fields);
6420 if (xo_gettext_simplify_format(xop, &xb, fields, -1, fmt, field_cb))
6427 xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap)
6431 xop = xo_default(xop);
6432 va_copy(xop->xo_vap, vap);
6433 rc = xo_do_emit(xop, 0, fmt);
6434 va_end(xop->xo_vap);
6435 bzero(&xop->xo_vap, sizeof(xop->xo_vap));
6441 xo_emit_h (xo_handle_t *xop, const char *fmt, ...)
6445 xop = xo_default(xop);
6446 va_start(xop->xo_vap, fmt);
6447 rc = xo_do_emit(xop, 0, fmt);
6448 va_end(xop->xo_vap);
6449 bzero(&xop->xo_vap, sizeof(xop->xo_vap));
6455 xo_emit (const char *fmt, ...)
6457 xo_handle_t *xop = xo_default(NULL);
6460 va_start(xop->xo_vap, fmt);
6461 rc = xo_do_emit(xop, 0, fmt);
6462 va_end(xop->xo_vap);
6463 bzero(&xop->xo_vap, sizeof(xop->xo_vap));
6469 xo_emit_hvf (xo_handle_t *xop, xo_emit_flags_t flags,
6470 const char *fmt, va_list vap)
6474 xop = xo_default(xop);
6475 va_copy(xop->xo_vap, vap);
6476 rc = xo_do_emit(xop, flags, fmt);
6477 va_end(xop->xo_vap);
6478 bzero(&xop->xo_vap, sizeof(xop->xo_vap));
6484 xo_emit_hf (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...)
6488 xop = xo_default(xop);
6489 va_start(xop->xo_vap, fmt);
6490 rc = xo_do_emit(xop, flags, fmt);
6491 va_end(xop->xo_vap);
6492 bzero(&xop->xo_vap, sizeof(xop->xo_vap));
6498 xo_emit_f (xo_emit_flags_t flags, const char *fmt, ...)
6500 xo_handle_t *xop = xo_default(NULL);
6503 va_start(xop->xo_vap, fmt);
6504 rc = xo_do_emit(xop, flags, fmt);
6505 va_end(xop->xo_vap);
6506 bzero(&xop->xo_vap, sizeof(xop->xo_vap));
6512 * Emit a single field by providing the info information typically provided
6513 * inside the field description (role, modifiers, and formats). This is
6514 * a convenience function to avoid callers using snprintf to build field
6518 xo_emit_field_hv (xo_handle_t *xop, const char *rolmod, const char *contents,
6519 const char *fmt, const char *efmt,
6524 xop = xo_default(xop);
6529 xo_field_info_t xfi;
6531 bzero(&xfi, sizeof(xfi));
6534 cp = xo_parse_roles(xop, rolmod, rolmod, &xfi);
6538 xfi.xfi_start = fmt;
6539 xfi.xfi_content = contents;
6540 xfi.xfi_format = fmt;
6541 xfi.xfi_encoding = efmt;
6542 xfi.xfi_clen = contents ? strlen(contents) : 0;
6543 xfi.xfi_flen = fmt ? strlen(fmt) : 0;
6544 xfi.xfi_elen = efmt ? strlen(efmt) : 0;
6546 /* If we have content, then we have a default format */
6547 if (contents && fmt == NULL
6548 && xo_role_wants_default_format(xfi.xfi_ftype)) {
6549 xfi.xfi_format = xo_default_format;
6553 va_copy(xop->xo_vap, vap);
6555 rc = xo_do_emit_fields(xop, &xfi, 1, fmt ?: contents ?: "field");
6557 va_end(xop->xo_vap);
6563 xo_emit_field_h (xo_handle_t *xop, const char *rolmod, const char *contents,
6564 const char *fmt, const char *efmt, ...)
6569 va_start(vap, efmt);
6570 rc = xo_emit_field_hv(xop, rolmod, contents, fmt, efmt, vap);
6577 xo_emit_field (const char *rolmod, const char *contents,
6578 const char *fmt, const char *efmt, ...)
6583 va_start(vap, efmt);
6584 rc = xo_emit_field_hv(NULL, rolmod, contents, fmt, efmt, vap);
6591 xo_attr_hv (xo_handle_t *xop, const char *name, const char *fmt, va_list vap)
6593 const ssize_t extra = 5; /* space, equals, quote, quote, and nul */
6594 xop = xo_default(xop);
6597 ssize_t nlen = strlen(name);
6598 xo_buffer_t *xbp = &xop->xo_attrs;
6599 ssize_t name_offset, value_offset;
6601 switch (xo_style(xop)) {
6603 if (!xo_buf_has_room(xbp, nlen + extra))
6606 *xbp->xb_curp++ = ' ';
6607 memcpy(xbp->xb_curp, name, nlen);
6608 xbp->xb_curp += nlen;
6609 *xbp->xb_curp++ = '=';
6610 *xbp->xb_curp++ = '"';
6612 rc = xo_vsnprintf(xop, xbp, fmt, vap);
6615 rc = xo_escape_xml(xbp, rc, 1);
6619 if (!xo_buf_has_room(xbp, 2))
6622 *xbp->xb_curp++ = '"';
6623 *xbp->xb_curp = '\0';
6628 case XO_STYLE_ENCODER:
6629 name_offset = xo_buf_offset(xbp);
6630 xo_buf_append(xbp, name, nlen);
6631 xo_buf_append(xbp, "", 1);
6633 value_offset = xo_buf_offset(xbp);
6634 rc = xo_vsnprintf(xop, xbp, fmt, vap);
6637 *xbp->xb_curp = '\0';
6638 rc = xo_encoder_handle(xop, XO_OP_ATTRIBUTE,
6639 xo_buf_data(xbp, name_offset),
6640 xo_buf_data(xbp, value_offset), 0);
6648 xo_attr_h (xo_handle_t *xop, const char *name, const char *fmt, ...)
6654 rc = xo_attr_hv(xop, name, fmt, vap);
6661 xo_attr (const char *name, const char *fmt, ...)
6667 rc = xo_attr_hv(NULL, name, fmt, vap);
6674 xo_stack_set_flags (xo_handle_t *xop)
6676 if (XOF_ISSET(xop, XOF_NOT_FIRST)) {
6677 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth];
6679 xsp->xs_flags |= XSF_NOT_FIRST;
6680 XOF_CLEAR(xop, XOF_NOT_FIRST);
6685 xo_depth_change (xo_handle_t *xop, const char *name,
6686 int delta, int indent, xo_state_t state, xo_xsf_flags_t flags)
6688 if (xo_style(xop) == XO_STYLE_HTML || xo_style(xop) == XO_STYLE_TEXT)
6691 if (XOF_ISSET(xop, XOF_DTRT))
6694 if (delta >= 0) { /* Push operation */
6695 if (xo_depth_check(xop, xop->xo_depth + delta))
6698 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth + delta];
6699 xsp->xs_flags = flags;
6700 xsp->xs_state = state;
6701 xo_stack_set_flags(xop);
6704 name = XO_FAILURE_NAME;
6706 xsp->xs_name = xo_strndup(name, -1);
6708 } else { /* Pop operation */
6709 if (xop->xo_depth == 0) {
6710 if (!XOF_ISSET(xop, XOF_IGNORE_CLOSE))
6711 xo_failure(xop, "close with empty stack: '%s'", name);
6715 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth];
6716 if (XOF_ISSET(xop, XOF_WARN)) {
6717 const char *top = xsp->xs_name;
6718 if (top != NULL && name != NULL && strcmp(name, top) != 0) {
6719 xo_failure(xop, "incorrect close: '%s' .vs. '%s'",
6723 if ((xsp->xs_flags & XSF_LIST) != (flags & XSF_LIST)) {
6724 xo_failure(xop, "list close on list confict: '%s'",
6728 if ((xsp->xs_flags & XSF_INSTANCE) != (flags & XSF_INSTANCE)) {
6729 xo_failure(xop, "list close on instance confict: '%s'",
6736 xo_free(xsp->xs_name);
6737 xsp->xs_name = NULL;
6740 xo_free(xsp->xs_keys);
6741 xsp->xs_keys = NULL;
6745 xop->xo_depth += delta; /* Record new depth */
6746 xop->xo_indent += indent;
6750 xo_set_depth (xo_handle_t *xop, int depth)
6752 xop = xo_default(xop);
6754 if (xo_depth_check(xop, depth))
6757 xop->xo_depth += depth;
6758 xop->xo_indent += depth;
6761 static xo_xsf_flags_t
6762 xo_stack_flags (xo_xof_flags_t xflags)
6764 if (xflags & XOF_DTRT)
6770 xo_emit_top (xo_handle_t *xop, const char *ppn)
6772 xo_printf(xop, "%*s{%s", xo_indent(xop), "", ppn);
6773 XOIF_SET(xop, XOIF_TOP_EMITTED);
6775 if (xop->xo_version) {
6776 xo_printf(xop, "%*s\"__version\": \"%s\", %s",
6777 xo_indent(xop), "", xop->xo_version, ppn);
6778 xo_free(xop->xo_version);
6779 xop->xo_version = NULL;
6784 xo_do_open_container (xo_handle_t *xop, xo_xof_flags_t flags, const char *name)
6787 const char *ppn = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
6788 const char *pre_nl = "";
6791 xo_failure(xop, "NULL passed for container name");
6792 name = XO_FAILURE_NAME;
6795 flags |= xop->xo_flags; /* Pick up handle flags */
6797 switch (xo_style(xop)) {
6799 rc = xo_printf(xop, "%*s<%s", xo_indent(xop), "", name);
6801 if (xop->xo_attrs.xb_curp != xop->xo_attrs.xb_bufp) {
6802 rc += xop->xo_attrs.xb_curp - xop->xo_attrs.xb_bufp;
6803 xo_data_append(xop, xop->xo_attrs.xb_bufp,
6804 xop->xo_attrs.xb_curp - xop->xo_attrs.xb_bufp);
6805 xop->xo_attrs.xb_curp = xop->xo_attrs.xb_bufp;
6808 rc += xo_printf(xop, ">%s", ppn);
6812 xo_stack_set_flags(xop);
6814 if (!XOF_ISSET(xop, XOF_NO_TOP)
6815 && !XOIF_ISSET(xop, XOIF_TOP_EMITTED))
6816 xo_emit_top(xop, ppn);
6818 if (xop->xo_stack[xop->xo_depth].xs_flags & XSF_NOT_FIRST)
6819 pre_nl = XOF_ISSET(xop, XOF_PRETTY) ? ",\n" : ", ";
6820 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
6822 rc = xo_printf(xop, "%s%*s\"%s\": {%s",
6823 pre_nl, xo_indent(xop), "", name, ppn);
6826 case XO_STYLE_SDPARAMS:
6829 case XO_STYLE_ENCODER:
6830 rc = xo_encoder_handle(xop, XO_OP_OPEN_CONTAINER, name, NULL, flags);
6834 xo_depth_change(xop, name, 1, 1, XSS_OPEN_CONTAINER,
6835 xo_stack_flags(flags));
6841 xo_open_container_hf (xo_handle_t *xop, xo_xof_flags_t flags, const char *name)
6843 return xo_transition(xop, flags, name, XSS_OPEN_CONTAINER);
6847 xo_open_container_h (xo_handle_t *xop, const char *name)
6849 return xo_open_container_hf(xop, 0, name);
6853 xo_open_container (const char *name)
6855 return xo_open_container_hf(NULL, 0, name);
6859 xo_open_container_hd (xo_handle_t *xop, const char *name)
6861 return xo_open_container_hf(xop, XOF_DTRT, name);
6865 xo_open_container_d (const char *name)
6867 return xo_open_container_hf(NULL, XOF_DTRT, name);
6871 xo_do_close_container (xo_handle_t *xop, const char *name)
6873 xop = xo_default(xop);
6876 const char *ppn = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
6877 const char *pre_nl = "";
6880 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth];
6882 name = xsp->xs_name;
6884 ssize_t len = strlen(name) + 1;
6885 /* We need to make a local copy; xo_depth_change will free it */
6886 char *cp = alloca(len);
6887 memcpy(cp, name, len);
6889 } else if (!(xsp->xs_flags & XSF_DTRT)) {
6890 xo_failure(xop, "missing name without 'dtrt' mode");
6891 name = XO_FAILURE_NAME;
6895 switch (xo_style(xop)) {
6897 xo_depth_change(xop, name, -1, -1, XSS_CLOSE_CONTAINER, 0);
6898 rc = xo_printf(xop, "%*s</%s>%s", xo_indent(xop), "", name, ppn);
6902 pre_nl = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
6903 ppn = (xop->xo_depth <= 1) ? "\n" : "";
6905 xo_depth_change(xop, name, -1, -1, XSS_CLOSE_CONTAINER, 0);
6906 rc = xo_printf(xop, "%s%*s}%s", pre_nl, xo_indent(xop), "", ppn);
6907 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
6912 xo_depth_change(xop, name, -1, 0, XSS_CLOSE_CONTAINER, 0);
6915 case XO_STYLE_SDPARAMS:
6918 case XO_STYLE_ENCODER:
6919 xo_depth_change(xop, name, -1, 0, XSS_CLOSE_CONTAINER, 0);
6920 rc = xo_encoder_handle(xop, XO_OP_CLOSE_CONTAINER, name, NULL, 0);
6928 xo_close_container_h (xo_handle_t *xop, const char *name)
6930 return xo_transition(xop, 0, name, XSS_CLOSE_CONTAINER);
6934 xo_close_container (const char *name)
6936 return xo_close_container_h(NULL, name);
6940 xo_close_container_hd (xo_handle_t *xop)
6942 return xo_close_container_h(xop, NULL);
6946 xo_close_container_d (void)
6948 return xo_close_container_h(NULL, NULL);
6952 xo_do_open_list (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name)
6957 xop = xo_default(xop);
6959 const char *ppn = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
6960 const char *pre_nl = "";
6962 switch (xo_style(xop)) {
6966 if (!XOF_ISSET(xop, XOF_NO_TOP)
6967 && !XOIF_ISSET(xop, XOIF_TOP_EMITTED))
6968 xo_emit_top(xop, ppn);
6971 xo_failure(xop, "NULL passed for list name");
6972 name = XO_FAILURE_NAME;
6975 xo_stack_set_flags(xop);
6977 if (xop->xo_stack[xop->xo_depth].xs_flags & XSF_NOT_FIRST)
6978 pre_nl = XOF_ISSET(xop, XOF_PRETTY) ? ",\n" : ", ";
6979 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
6981 rc = xo_printf(xop, "%s%*s\"%s\": [%s",
6982 pre_nl, xo_indent(xop), "", name, ppn);
6985 case XO_STYLE_ENCODER:
6986 rc = xo_encoder_handle(xop, XO_OP_OPEN_LIST, name, NULL, flags);
6990 xo_depth_change(xop, name, 1, indent, XSS_OPEN_LIST,
6991 XSF_LIST | xo_stack_flags(flags));
6997 xo_open_list_hf (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name)
6999 return xo_transition(xop, flags, name, XSS_OPEN_LIST);
7003 xo_open_list_h (xo_handle_t *xop, const char *name)
7005 return xo_open_list_hf(xop, 0, name);
7009 xo_open_list (const char *name)
7011 return xo_open_list_hf(NULL, 0, name);
7015 xo_open_list_hd (xo_handle_t *xop, const char *name)
7017 return xo_open_list_hf(xop, XOF_DTRT, name);
7021 xo_open_list_d (const char *name)
7023 return xo_open_list_hf(NULL, XOF_DTRT, name);
7027 xo_do_close_list (xo_handle_t *xop, const char *name)
7030 const char *pre_nl = "";
7033 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth];
7035 name = xsp->xs_name;
7037 ssize_t len = strlen(name) + 1;
7038 /* We need to make a local copy; xo_depth_change will free it */
7039 char *cp = alloca(len);
7040 memcpy(cp, name, len);
7042 } else if (!(xsp->xs_flags & XSF_DTRT)) {
7043 xo_failure(xop, "missing name without 'dtrt' mode");
7044 name = XO_FAILURE_NAME;
7048 switch (xo_style(xop)) {
7050 if (xop->xo_stack[xop->xo_depth].xs_flags & XSF_NOT_FIRST)
7051 pre_nl = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
7052 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7054 xo_depth_change(xop, name, -1, -1, XSS_CLOSE_LIST, XSF_LIST);
7055 rc = xo_printf(xop, "%s%*s]", pre_nl, xo_indent(xop), "");
7056 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7059 case XO_STYLE_ENCODER:
7060 xo_depth_change(xop, name, -1, 0, XSS_CLOSE_LIST, XSF_LIST);
7061 rc = xo_encoder_handle(xop, XO_OP_CLOSE_LIST, name, NULL, 0);
7065 xo_depth_change(xop, name, -1, 0, XSS_CLOSE_LIST, XSF_LIST);
7066 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7074 xo_close_list_h (xo_handle_t *xop, const char *name)
7076 return xo_transition(xop, 0, name, XSS_CLOSE_LIST);
7080 xo_close_list (const char *name)
7082 return xo_close_list_h(NULL, name);
7086 xo_close_list_hd (xo_handle_t *xop)
7088 return xo_close_list_h(xop, NULL);
7092 xo_close_list_d (void)
7094 return xo_close_list_h(NULL, NULL);
7098 xo_do_open_leaf_list (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name)
7103 xop = xo_default(xop);
7105 const char *ppn = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
7106 const char *pre_nl = "";
7108 switch (xo_style(xop)) {
7112 if (!XOF_ISSET(xop, XOF_NO_TOP)) {
7113 if (!XOIF_ISSET(xop, XOIF_TOP_EMITTED)) {
7114 xo_printf(xop, "%*s{%s", xo_indent(xop), "", ppn);
7115 XOIF_SET(xop, XOIF_TOP_EMITTED);
7120 xo_failure(xop, "NULL passed for list name");
7121 name = XO_FAILURE_NAME;
7124 xo_stack_set_flags(xop);
7126 if (xop->xo_stack[xop->xo_depth].xs_flags & XSF_NOT_FIRST)
7127 pre_nl = XOF_ISSET(xop, XOF_PRETTY) ? ",\n" : ", ";
7128 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7130 rc = xo_printf(xop, "%s%*s\"%s\": [%s",
7131 pre_nl, xo_indent(xop), "", name, ppn);
7134 case XO_STYLE_ENCODER:
7135 rc = xo_encoder_handle(xop, XO_OP_OPEN_LEAF_LIST, name, NULL, flags);
7139 xo_depth_change(xop, name, 1, indent, XSS_OPEN_LEAF_LIST,
7140 XSF_LIST | xo_stack_flags(flags));
7146 xo_do_close_leaf_list (xo_handle_t *xop, const char *name)
7149 const char *pre_nl = "";
7152 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth];
7154 name = xsp->xs_name;
7156 ssize_t len = strlen(name) + 1;
7157 /* We need to make a local copy; xo_depth_change will free it */
7158 char *cp = alloca(len);
7159 memcpy(cp, name, len);
7161 } else if (!(xsp->xs_flags & XSF_DTRT)) {
7162 xo_failure(xop, "missing name without 'dtrt' mode");
7163 name = XO_FAILURE_NAME;
7167 switch (xo_style(xop)) {
7169 if (xop->xo_stack[xop->xo_depth].xs_flags & XSF_NOT_FIRST)
7170 pre_nl = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
7171 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7173 xo_depth_change(xop, name, -1, -1, XSS_CLOSE_LEAF_LIST, XSF_LIST);
7174 rc = xo_printf(xop, "%s%*s]", pre_nl, xo_indent(xop), "");
7175 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7178 case XO_STYLE_ENCODER:
7179 rc = xo_encoder_handle(xop, XO_OP_CLOSE_LEAF_LIST, name, NULL, 0);
7183 xo_depth_change(xop, name, -1, 0, XSS_CLOSE_LEAF_LIST, XSF_LIST);
7184 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7192 xo_do_open_instance (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name)
7194 xop = xo_default(xop);
7197 const char *ppn = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
7198 const char *pre_nl = "";
7200 flags |= xop->xo_flags;
7203 xo_failure(xop, "NULL passed for instance name");
7204 name = XO_FAILURE_NAME;
7207 switch (xo_style(xop)) {
7209 rc = xo_printf(xop, "%*s<%s", xo_indent(xop), "", name);
7211 if (xop->xo_attrs.xb_curp != xop->xo_attrs.xb_bufp) {
7212 rc += xop->xo_attrs.xb_curp - xop->xo_attrs.xb_bufp;
7213 xo_data_append(xop, xop->xo_attrs.xb_bufp,
7214 xop->xo_attrs.xb_curp - xop->xo_attrs.xb_bufp);
7215 xop->xo_attrs.xb_curp = xop->xo_attrs.xb_bufp;
7218 rc += xo_printf(xop, ">%s", ppn);
7222 xo_stack_set_flags(xop);
7224 if (xop->xo_stack[xop->xo_depth].xs_flags & XSF_NOT_FIRST)
7225 pre_nl = XOF_ISSET(xop, XOF_PRETTY) ? ",\n" : ", ";
7226 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7228 rc = xo_printf(xop, "%s%*s{%s",
7229 pre_nl, xo_indent(xop), "", ppn);
7232 case XO_STYLE_SDPARAMS:
7235 case XO_STYLE_ENCODER:
7236 rc = xo_encoder_handle(xop, XO_OP_OPEN_INSTANCE, name, NULL, flags);
7240 xo_depth_change(xop, name, 1, 1, XSS_OPEN_INSTANCE, xo_stack_flags(flags));
7246 xo_open_instance_hf (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name)
7248 return xo_transition(xop, flags, name, XSS_OPEN_INSTANCE);
7252 xo_open_instance_h (xo_handle_t *xop, const char *name)
7254 return xo_open_instance_hf(xop, 0, name);
7258 xo_open_instance (const char *name)
7260 return xo_open_instance_hf(NULL, 0, name);
7264 xo_open_instance_hd (xo_handle_t *xop, const char *name)
7266 return xo_open_instance_hf(xop, XOF_DTRT, name);
7270 xo_open_instance_d (const char *name)
7272 return xo_open_instance_hf(NULL, XOF_DTRT, name);
7276 xo_do_close_instance (xo_handle_t *xop, const char *name)
7278 xop = xo_default(xop);
7281 const char *ppn = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
7282 const char *pre_nl = "";
7285 xo_stack_t *xsp = &xop->xo_stack[xop->xo_depth];
7287 name = xsp->xs_name;
7289 ssize_t len = strlen(name) + 1;
7290 /* We need to make a local copy; xo_depth_change will free it */
7291 char *cp = alloca(len);
7292 memcpy(cp, name, len);
7294 } else if (!(xsp->xs_flags & XSF_DTRT)) {
7295 xo_failure(xop, "missing name without 'dtrt' mode");
7296 name = XO_FAILURE_NAME;
7300 switch (xo_style(xop)) {
7302 xo_depth_change(xop, name, -1, -1, XSS_CLOSE_INSTANCE, 0);
7303 rc = xo_printf(xop, "%*s</%s>%s", xo_indent(xop), "", name, ppn);
7307 pre_nl = XOF_ISSET(xop, XOF_PRETTY) ? "\n" : "";
7309 xo_depth_change(xop, name, -1, -1, XSS_CLOSE_INSTANCE, 0);
7310 rc = xo_printf(xop, "%s%*s}", pre_nl, xo_indent(xop), "");
7311 xop->xo_stack[xop->xo_depth].xs_flags |= XSF_NOT_FIRST;
7316 xo_depth_change(xop, name, -1, 0, XSS_CLOSE_INSTANCE, 0);
7319 case XO_STYLE_SDPARAMS:
7322 case XO_STYLE_ENCODER:
7323 xo_depth_change(xop, name, -1, 0, XSS_CLOSE_INSTANCE, 0);
7324 rc = xo_encoder_handle(xop, XO_OP_CLOSE_INSTANCE, name, NULL, 0);
7332 xo_close_instance_h (xo_handle_t *xop, const char *name)
7334 return xo_transition(xop, 0, name, XSS_CLOSE_INSTANCE);
7338 xo_close_instance (const char *name)
7340 return xo_close_instance_h(NULL, name);
7344 xo_close_instance_hd (xo_handle_t *xop)
7346 return xo_close_instance_h(xop, NULL);
7350 xo_close_instance_d (void)
7352 return xo_close_instance_h(NULL, NULL);
7356 xo_do_close_all (xo_handle_t *xop, xo_stack_t *limit)
7360 xo_xsf_flags_t flags;
7362 for (xsp = &xop->xo_stack[xop->xo_depth]; xsp >= limit; xsp--) {
7363 switch (xsp->xs_state) {
7369 case XSS_OPEN_CONTAINER:
7370 rc = xo_do_close_container(xop, NULL);
7374 rc = xo_do_close_list(xop, NULL);
7377 case XSS_OPEN_INSTANCE:
7378 rc = xo_do_close_instance(xop, NULL);
7381 case XSS_OPEN_LEAF_LIST:
7382 rc = xo_do_close_leaf_list(xop, NULL);
7386 flags = xsp->xs_flags & XSF_MARKER_FLAGS;
7387 xo_depth_change(xop, xsp->xs_name, -1, 0, XSS_MARKER, 0);
7388 xop->xo_stack[xop->xo_depth].xs_flags |= flags;
7394 xo_failure(xop, "close %d failed: %d", xsp->xs_state, rc);
7401 * This function is responsible for clearing out whatever is needed
7402 * to get to the desired state, if possible.
7405 xo_do_close (xo_handle_t *xop, const char *name, xo_state_t new_state)
7407 xo_stack_t *xsp, *limit = NULL;
7409 xo_state_t need_state = new_state;
7411 if (new_state == XSS_CLOSE_CONTAINER)
7412 need_state = XSS_OPEN_CONTAINER;
7413 else if (new_state == XSS_CLOSE_LIST)
7414 need_state = XSS_OPEN_LIST;
7415 else if (new_state == XSS_CLOSE_INSTANCE)
7416 need_state = XSS_OPEN_INSTANCE;
7417 else if (new_state == XSS_CLOSE_LEAF_LIST)
7418 need_state = XSS_OPEN_LEAF_LIST;
7419 else if (new_state == XSS_MARKER)
7420 need_state = XSS_MARKER;
7422 return 0; /* Unknown or useless new states are ignored */
7424 for (xsp = &xop->xo_stack[xop->xo_depth]; xsp > xop->xo_stack; xsp--) {
7426 * Marker's normally stop us from going any further, unless
7427 * we are popping a marker (new_state == XSS_MARKER).
7429 if (xsp->xs_state == XSS_MARKER && need_state != XSS_MARKER) {
7431 xo_failure(xop, "close (xo_%s) fails at marker '%s'; "
7433 xo_state_name(new_state),
7434 xsp->xs_name, name);
7439 xo_failure(xop, "close stops at marker '%s'", xsp->xs_name);
7444 if (xsp->xs_state != need_state)
7447 if (name && xsp->xs_name && strcmp(name, xsp->xs_name) != 0)
7454 if (limit == NULL) {
7455 xo_failure(xop, "xo_%s can't find match for '%s'",
7456 xo_state_name(new_state), name);
7460 rc = xo_do_close_all(xop, limit);
7466 * We are in a given state and need to transition to the new state.
7469 xo_transition (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name,
7470 xo_state_t new_state)
7474 int old_state, on_marker;
7476 xop = xo_default(xop);
7478 xsp = &xop->xo_stack[xop->xo_depth];
7479 old_state = xsp->xs_state;
7480 on_marker = (old_state == XSS_MARKER);
7482 /* If there's a marker on top of the stack, we need to find a real state */
7483 while (old_state == XSS_MARKER) {
7484 if (xsp == xop->xo_stack)
7487 old_state = xsp->xs_state;
7491 * At this point, the list of possible states are:
7492 * XSS_INIT, XSS_OPEN_CONTAINER, XSS_OPEN_LIST,
7493 * XSS_OPEN_INSTANCE, XSS_OPEN_LEAF_LIST, XSS_DISCARDING
7495 switch (XSS_TRANSITION(old_state, new_state)) {
7498 case XSS_TRANSITION(XSS_INIT, XSS_OPEN_CONTAINER):
7499 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_OPEN_CONTAINER):
7500 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_OPEN_CONTAINER):
7501 rc = xo_do_open_container(xop, flags, name);
7504 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_OPEN_CONTAINER):
7506 goto marker_prevents_close;
7507 rc = xo_do_close_list(xop, NULL);
7509 goto open_container;
7512 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_OPEN_CONTAINER):
7514 goto marker_prevents_close;
7515 rc = xo_do_close_leaf_list(xop, NULL);
7517 goto open_container;
7520 /*close_container:*/
7521 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_CLOSE_CONTAINER):
7523 goto marker_prevents_close;
7524 rc = xo_do_close(xop, name, new_state);
7527 case XSS_TRANSITION(XSS_INIT, XSS_CLOSE_CONTAINER):
7528 /* This is an exception for "xo --close" */
7529 rc = xo_do_close_container(xop, name);
7532 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_CLOSE_CONTAINER):
7533 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_CLOSE_CONTAINER):
7535 goto marker_prevents_close;
7536 rc = xo_do_close(xop, name, new_state);
7539 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_CLOSE_CONTAINER):
7541 goto marker_prevents_close;
7542 rc = xo_do_close_leaf_list(xop, NULL);
7544 rc = xo_do_close(xop, name, new_state);
7548 case XSS_TRANSITION(XSS_INIT, XSS_OPEN_LIST):
7549 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_OPEN_LIST):
7550 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_OPEN_LIST):
7551 rc = xo_do_open_list(xop, flags, name);
7554 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_OPEN_LIST):
7556 goto marker_prevents_close;
7557 rc = xo_do_close_list(xop, NULL);
7562 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_OPEN_LIST):
7564 goto marker_prevents_close;
7565 rc = xo_do_close_leaf_list(xop, NULL);
7571 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_CLOSE_LIST):
7573 goto marker_prevents_close;
7574 rc = xo_do_close(xop, name, new_state);
7577 case XSS_TRANSITION(XSS_INIT, XSS_CLOSE_LIST):
7578 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_CLOSE_LIST):
7579 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_CLOSE_LIST):
7580 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_CLOSE_LIST):
7581 rc = xo_do_close(xop, name, new_state);
7585 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_OPEN_INSTANCE):
7586 rc = xo_do_open_instance(xop, flags, name);
7589 case XSS_TRANSITION(XSS_INIT, XSS_OPEN_INSTANCE):
7590 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_OPEN_INSTANCE):
7591 rc = xo_do_open_list(xop, flags, name);
7596 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_OPEN_INSTANCE):
7598 rc = xo_do_open_list(xop, flags, name);
7600 rc = xo_do_close_instance(xop, NULL);
7606 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_OPEN_INSTANCE):
7608 goto marker_prevents_close;
7609 rc = xo_do_close_leaf_list(xop, NULL);
7615 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_CLOSE_INSTANCE):
7617 goto marker_prevents_close;
7618 rc = xo_do_close_instance(xop, name);
7621 case XSS_TRANSITION(XSS_INIT, XSS_CLOSE_INSTANCE):
7622 /* This one makes no sense; ignore it */
7623 xo_failure(xop, "xo_close_instance ignored when called from "
7624 "initial state ('%s')", name ?: "(unknown)");
7627 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_CLOSE_INSTANCE):
7628 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_CLOSE_INSTANCE):
7630 goto marker_prevents_close;
7631 rc = xo_do_close(xop, name, new_state);
7634 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_CLOSE_INSTANCE):
7636 goto marker_prevents_close;
7637 rc = xo_do_close_leaf_list(xop, NULL);
7639 rc = xo_do_close(xop, name, new_state);
7643 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_OPEN_LEAF_LIST):
7644 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_OPEN_LEAF_LIST):
7645 case XSS_TRANSITION(XSS_INIT, XSS_OPEN_LEAF_LIST):
7646 rc = xo_do_open_leaf_list(xop, flags, name);
7649 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_OPEN_LEAF_LIST):
7650 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_OPEN_LEAF_LIST):
7652 goto marker_prevents_close;
7653 rc = xo_do_close_list(xop, NULL);
7655 goto open_leaf_list;
7658 /*close_leaf_list:*/
7659 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_CLOSE_LEAF_LIST):
7661 goto marker_prevents_close;
7662 rc = xo_do_close_leaf_list(xop, name);
7665 case XSS_TRANSITION(XSS_INIT, XSS_CLOSE_LEAF_LIST):
7666 /* Makes no sense; ignore */
7667 xo_failure(xop, "xo_close_leaf_list ignored when called from "
7668 "initial state ('%s')", name ?: "(unknown)");
7671 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_CLOSE_LEAF_LIST):
7672 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_CLOSE_LEAF_LIST):
7673 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_CLOSE_LEAF_LIST):
7675 goto marker_prevents_close;
7676 rc = xo_do_close(xop, name, new_state);
7680 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_EMIT):
7681 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_EMIT):
7684 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_EMIT):
7686 goto marker_prevents_close;
7687 rc = xo_do_close(xop, NULL, XSS_CLOSE_LIST);
7690 case XSS_TRANSITION(XSS_INIT, XSS_EMIT):
7693 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_EMIT):
7695 goto marker_prevents_close;
7696 rc = xo_do_close_leaf_list(xop, NULL);
7700 case XSS_TRANSITION(XSS_INIT, XSS_EMIT_LEAF_LIST):
7701 case XSS_TRANSITION(XSS_OPEN_CONTAINER, XSS_EMIT_LEAF_LIST):
7702 case XSS_TRANSITION(XSS_OPEN_INSTANCE, XSS_EMIT_LEAF_LIST):
7703 rc = xo_do_open_leaf_list(xop, flags, name);
7706 case XSS_TRANSITION(XSS_OPEN_LEAF_LIST, XSS_EMIT_LEAF_LIST):
7709 case XSS_TRANSITION(XSS_OPEN_LIST, XSS_EMIT_LEAF_LIST):
7711 * We need to be backward compatible with the pre-xo_open_leaf_list
7712 * API, where both lists and leaf-lists were opened as lists. So
7713 * if we find an open list that hasn't had anything written to it,
7719 xo_failure(xop, "unknown transition: (%u -> %u)",
7720 xsp->xs_state, new_state);
7723 /* Handle the flush flag */
7724 if (rc >= 0 && XOF_ISSET(xop, XOF_FLUSH))
7725 if (xo_flush_h(xop))
7730 marker_prevents_close:
7731 xo_failure(xop, "marker '%s' prevents transition from %s to %s",
7732 xop->xo_stack[xop->xo_depth].xs_name,
7733 xo_state_name(old_state), xo_state_name(new_state));
7738 xo_open_marker_h (xo_handle_t *xop, const char *name)
7740 xop = xo_default(xop);
7742 xo_depth_change(xop, name, 1, 0, XSS_MARKER,
7743 xop->xo_stack[xop->xo_depth].xs_flags & XSF_MARKER_FLAGS);
7749 xo_open_marker (const char *name)
7751 return xo_open_marker_h(NULL, name);
7755 xo_close_marker_h (xo_handle_t *xop, const char *name)
7757 xop = xo_default(xop);
7759 return xo_do_close(xop, name, XSS_MARKER);
7763 xo_close_marker (const char *name)
7765 return xo_close_marker_h(NULL, name);
7769 * Record custom output functions into the xo handle, allowing
7770 * integration with a variety of output frameworks.
7773 xo_set_writer (xo_handle_t *xop, void *opaque, xo_write_func_t write_func,
7774 xo_close_func_t close_func, xo_flush_func_t flush_func)
7776 xop = xo_default(xop);
7778 xop->xo_opaque = opaque;
7779 xop->xo_write = write_func;
7780 xop->xo_close = close_func;
7781 xop->xo_flush = flush_func;
7785 xo_set_allocator (xo_realloc_func_t realloc_func, xo_free_func_t free_func)
7787 xo_realloc = realloc_func;
7788 xo_free = free_func;
7792 xo_flush_h (xo_handle_t *xop)
7796 xop = xo_default(xop);
7798 switch (xo_style(xop)) {
7799 case XO_STYLE_ENCODER:
7800 xo_encoder_handle(xop, XO_OP_FLUSH, NULL, NULL, 0);
7804 if (rc >= 0 && xop->xo_flush)
7805 if (xop->xo_flush(xop->xo_opaque) < 0)
7814 return xo_flush_h(NULL);
7818 xo_finish_h (xo_handle_t *xop)
7820 const char *cp = "";
7821 xop = xo_default(xop);
7823 if (!XOF_ISSET(xop, XOF_NO_CLOSE))
7824 xo_do_close_all(xop, xop->xo_stack);
7826 switch (xo_style(xop)) {
7828 if (!XOF_ISSET(xop, XOF_NO_TOP)) {
7829 if (XOIF_ISSET(xop, XOIF_TOP_EMITTED))
7830 XOIF_CLEAR(xop, XOIF_TOP_EMITTED); /* Turn off before output */
7833 xo_printf(xop, "%*s%s}\n",xo_indent(xop), "", cp);
7837 case XO_STYLE_ENCODER:
7838 xo_encoder_handle(xop, XO_OP_FINISH, NULL, NULL, 0);
7842 return xo_flush_h(xop);
7848 return xo_finish_h(NULL);
7852 * xo_finish_atexit is suitable for atexit() calls, to force clear up
7853 * and finalizing output.
7856 xo_finish_atexit (void)
7858 (void) xo_finish_h(NULL);
7862 * Generate an error message, such as would be displayed on stderr
7865 xo_error_hv (xo_handle_t *xop, const char *fmt, va_list vap)
7867 xop = xo_default(xop);
7870 * If the format string doesn't end with a newline, we pop
7873 ssize_t len = strlen(fmt);
7874 if (len > 0 && fmt[len - 1] != '\n') {
7875 char *newfmt = alloca(len + 2);
7876 memcpy(newfmt, fmt, len);
7882 switch (xo_style(xop)) {
7884 vfprintf(stderr, fmt, vap);
7888 va_copy(xop->xo_vap, vap);
7890 xo_buf_append_div(xop, "error", 0, NULL, 0, fmt, strlen(fmt), NULL, 0);
7892 if (XOIF_ISSET(xop, XOIF_DIV_OPEN))
7897 va_end(xop->xo_vap);
7898 bzero(&xop->xo_vap, sizeof(xop->xo_vap));
7903 va_copy(xop->xo_vap, vap);
7905 xo_open_container_h(xop, "error");
7906 xo_format_value(xop, "message", 7, fmt, strlen(fmt), NULL, 0, 0);
7907 xo_close_container_h(xop, "error");
7909 va_end(xop->xo_vap);
7910 bzero(&xop->xo_vap, sizeof(xop->xo_vap));
7913 case XO_STYLE_SDPARAMS:
7914 case XO_STYLE_ENCODER:
7920 xo_error_h (xo_handle_t *xop, const char *fmt, ...)
7925 xo_error_hv(xop, fmt, vap);
7930 * Generate an error message, such as would be displayed on stderr
7933 xo_error (const char *fmt, ...)
7938 xo_error_hv(NULL, fmt, vap);
7943 * Parse any libxo-specific options from the command line, removing them
7944 * so the main() argument parsing won't see them. We return the new value
7945 * for argc or -1 for error. If an error occurred, the program should
7946 * exit. A suitable error message has already been displayed.
7949 xo_parse_args (int argc, char **argv)
7951 static char libxo_opt[] = "--libxo";
7955 /* Save our program name for xo_err and friends */
7956 xo_program = argv[0];
7957 cp = strrchr(xo_program, '/');
7959 xo_program = cp + 1;
7961 xo_handle_t *xop = xo_default(NULL);
7963 for (save = i = 1; i < argc; i++) {
7965 || strncmp(argv[i], libxo_opt, sizeof(libxo_opt) - 1) != 0) {
7967 argv[save] = argv[i];
7972 cp = argv[i] + sizeof(libxo_opt) - 1;
7976 xo_warnx("missing libxo option");
7980 if (xo_set_options(xop, cp) < 0)
7982 } else if (*cp == ':') {
7983 if (xo_set_options(xop, cp) < 0)
7986 } else if (*cp == '=') {
7987 if (xo_set_options(xop, ++cp) < 0)
7990 } else if (*cp == '-') {
7992 if (strcmp(cp, "check") == 0) {
7996 xo_warnx("unknown libxo option: '%s'", argv[i]);
8000 xo_warnx("unknown libxo option: '%s'", argv[i]);
8006 * We only want to do color output on terminals, but we only want
8007 * to do this if the user has asked for color.
8009 if (XOF_ISSET(xop, XOF_COLOR_ALLOWED) && isatty(1))
8010 XOF_SET(xop, XOF_COLOR);
8017 * Debugging function that dumps the current stack of open libxo constructs,
8018 * suitable for calling from the debugger.
8021 xo_dump_stack (xo_handle_t *xop)
8026 xop = xo_default(xop);
8028 fprintf(stderr, "Stack dump:\n");
8030 xsp = xop->xo_stack;
8031 for (i = 1, xsp++; i <= xop->xo_depth; i++, xsp++) {
8032 fprintf(stderr, " [%d] %s '%s' [%x]\n",
8033 i, xo_state_name(xsp->xs_state),
8034 xsp->xs_name ?: "--", xsp->xs_flags);
8039 * Record the program name used for error messages
8042 xo_set_program (const char *name)
8048 xo_set_version_h (xo_handle_t *xop, const char *version)
8050 xop = xo_default(xop);
8052 if (version == NULL || strchr(version, '"') != NULL)
8055 if (!xo_style_is_encoding(xop))
8058 switch (xo_style(xop)) {
8060 /* For XML, we record this as an attribute for the first tag */
8061 xo_attr_h(xop, "version", "%s", version);
8066 * For JSON, we record the version string in our handle, and emit
8067 * it in xo_emit_top.
8069 xop->xo_version = xo_strndup(version, -1);
8072 case XO_STYLE_ENCODER:
8073 xo_encoder_handle(xop, XO_OP_VERSION, NULL, version, 0);
8079 * Set the version number for the API content being carried through
8083 xo_set_version (const char *version)
8085 xo_set_version_h(NULL, version);
8089 * Generate a warning. Normally, this is a text message written to
8090 * standard error. If the XOF_WARN_XML flag is set, then we generate
8091 * XMLified content on standard output.
8094 xo_emit_warn_hcv (xo_handle_t *xop, int as_warning, int code,
8095 const char *fmt, va_list vap)
8097 xop = xo_default(xop);
8102 xo_open_marker_h(xop, "xo_emit_warn_hcv");
8103 xo_open_container_h(xop, as_warning ? "__warning" : "__error");
8106 xo_emit("{wc:program}", xo_program);
8108 if (xo_style(xop) == XO_STYLE_XML || xo_style(xop) == XO_STYLE_JSON) {
8112 bzero(&temp, sizeof(temp));
8113 temp.xo_style = XO_STYLE_TEXT;
8114 xo_buf_init(&temp.xo_data);
8115 xo_depth_check(&temp, XO_DEPTH);
8118 (void) xo_emit_hv(&temp, fmt, ap);
8121 xo_buffer_t *src = &temp.xo_data;
8122 xo_format_value(xop, "message", 7, src->xb_bufp,
8123 src->xb_curp - src->xb_bufp, NULL, 0, 0);
8125 xo_free(temp.xo_stack);
8126 xo_buf_cleanup(src);
8129 (void) xo_emit_hv(xop, fmt, vap);
8131 ssize_t len = strlen(fmt);
8132 if (len > 0 && fmt[len - 1] != '\n') {
8134 const char *msg = strerror(code);
8136 xo_emit_h(xop, ": {G:strerror}{g:error/%s}", msg);
8141 xo_close_marker_h(xop, "xo_emit_warn_hcv");
8146 xo_emit_warn_hc (xo_handle_t *xop, int code, const char *fmt, ...)
8151 xo_emit_warn_hcv(xop, 1, code, fmt, vap);
8156 xo_emit_warn_c (int code, const char *fmt, ...)
8161 xo_emit_warn_hcv(NULL, 1, code, fmt, vap);
8166 xo_emit_warn (const char *fmt, ...)
8172 xo_emit_warn_hcv(NULL, 1, code, fmt, vap);
8177 xo_emit_warnx (const char *fmt, ...)
8182 xo_emit_warn_hcv(NULL, 1, -1, fmt, vap);
8187 xo_emit_err_v (int eval, int code, const char *fmt, va_list vap)
8189 xo_emit_warn_hcv(NULL, 0, code, fmt, vap);
8195 xo_emit_err (int eval, const char *fmt, ...)
8200 xo_emit_err_v(0, code, fmt, vap);
8206 xo_emit_errx (int eval, const char *fmt, ...)
8211 xo_emit_err_v(0, -1, fmt, vap);
8218 xo_emit_errc (int eval, int code, const char *fmt, ...)
8223 xo_emit_warn_hcv(NULL, 0, code, fmt, vap);
8230 * Get the opaque private pointer for an xo handle
8233 xo_get_private (xo_handle_t *xop)
8235 xop = xo_default(xop);
8236 return xop->xo_private;
8240 * Set the opaque private pointer for an xo handle.
8243 xo_set_private (xo_handle_t *xop, void *opaque)
8245 xop = xo_default(xop);
8246 xop->xo_private = opaque;
8250 * Get the encoder function
8253 xo_get_encoder (xo_handle_t *xop)
8255 xop = xo_default(xop);
8256 return xop->xo_encoder;
8260 * Record an encoder callback function in an xo handle.
8263 xo_set_encoder (xo_handle_t *xop, xo_encoder_func_t encoder)
8265 xop = xo_default(xop);
8267 xop->xo_style = XO_STYLE_ENCODER;
8268 xop->xo_encoder = encoder;