+static void
+flush_deferred_text (struct output_engine *e)
+{
+ struct output_item *deferred_text = e->deferred_text;
+ if (deferred_text)
+ {
+ e->deferred_text = NULL;
+ output_submit__ (e, deferred_text);
+ }
+}
+
+static bool
+defer_text (struct output_engine *e, struct output_item *item)
+{
+ if (item->type != OUTPUT_ITEM_TEXT)
+ return false;
+
+ if (!e->deferred_text)
+ e->deferred_text = output_item_unshare (item);
+ else if (text_item_append (e->deferred_text, item))
+ output_item_unref (item);
+ else
+ {
+ flush_deferred_text (e);
+ e->deferred_text = output_item_unshare (item);
+ }
+ return true;
+}
+
+/* Submits ITEM to the configured output drivers, and transfers ownership to
+ the output subsystem. */
+void
+output_submit (struct output_item *item)
+{
+ struct output_engine *e = engine_stack_top ();
+
+ if (e == NULL)
+ return;
+
+ if (item == NULL)
+ return;
+
+ if (defer_text (e, item))
+ return;
+ flush_deferred_text (e);
+
+ switch (item->type)
+ {
+ case OUTPUT_ITEM_GROUP_OPEN:
+ if (e->n_groups >= e->allocated_groups)
+ e->groups = x2nrealloc (e->groups, &e->allocated_groups,
+ sizeof *e->groups);
+ e->groups[e->n_groups] = xstrdup_if_nonnull (item->command_name);
+ e->n_groups++;
+ break;
+
+ case OUTPUT_ITEM_GROUP_CLOSE:
+ assert (e->n_groups > 0);
+
+ size_t idx = --e->n_groups;
+ free (e->groups[idx]);
+
+ char *key = xasprintf ("Head%zu", idx);
+ free (string_map_find_and_delete (&e->heading_vars, key));
+ free (key);
+ break;
+
+ case OUTPUT_ITEM_TEXT:
+ {
+ enum text_item_subtype st = item->text.subtype;
+ char *key = (st == TEXT_ITEM_TITLE ? xasprintf ("Head%zu", e->n_groups)
+ : st == TEXT_ITEM_PAGE_TITLE ? xstrdup ("PageTitle")
+ : NULL);
+ if (key)
+ string_map_replace_nocopy (&e->heading_vars, key,
+ text_item_get_plain_text (item));
+ }
+ break;
+
+ case OUTPUT_ITEM_CHART:
+ case OUTPUT_ITEM_IMAGE:
+ case OUTPUT_ITEM_MESSAGE:
+ case OUTPUT_ITEM_PAGE_BREAK:
+ case OUTPUT_ITEM_PAGE_SETUP:
+ case OUTPUT_ITEM_TABLE:
+ break;
+ }
+
+ output_submit__ (e, item);
+}
+
+/* Returns the name of the command currently being parsed, or NULL if no
+ command is being parsed. */
+const char *
+output_get_command_name (void)
+{
+ struct output_engine *e = engine_stack_top ();
+ if (e == NULL)
+ return NULL;
+
+ for (size_t i = e->n_groups; i-- > 0;)
+ if (e->groups[i])
+ return e->groups[i];
+
+ return NULL;
+}
+
+char *
+output_get_uppercase_command_name (void)
+{
+ const char *command_name = output_get_command_name ();
+ return command_name ? utf8_to_upper (command_name) : NULL;
+}
+