+static const struct output_driver_class journal_class;
+
+/* Journal driver, if journaling is enabled. */
+static struct journal_driver journal;
+
+
+static struct journal_driver *
+journal_driver_cast (struct output_driver *driver)
+{
+ assert (driver->class == &journal_class);
+ return UP_CAST (driver, struct journal_driver, driver);
+}
+
+static void
+journal_close (void)
+{
+ if (journal.file != NULL)
+ {
+ if (fwriteerror (journal.file))
+ msg_error (errno, _("error writing output file `%s'"),
+ journal.file_name);
+
+ }
+ journal.file = NULL;
+}
+
+static void
+journal_destroy (struct output_driver *driver)
+{
+ struct journal_driver *j = journal_driver_cast (driver);
+
+ if (!j->destroyed)
+ journal_close ();
+
+ j->destroyed = true;
+}
+
+static void
+journal_output (struct journal_driver *j, char *s)
+{
+ if (j->file)
+ {
+ fprintf (j->file, "%s\n", s);
+
+ /* Flush the journal in case the syntax we're about to write
+ causes a crash. Having the syntax already written to disk
+ makes postmortem analysis of the problem possible. */
+ fflush (j->file);
+ }
+
+ free (s);
+}
+
+static void
+journal_submit (struct output_driver *driver, const struct output_item *item)
+{
+ struct journal_driver *j = journal_driver_cast (driver);
+
+ switch (item->type)
+ {
+ case OUTPUT_ITEM_MESSAGE:
+ journal_output (j, msg_to_string (item->message));
+ break;
+
+ case OUTPUT_ITEM_TEXT:
+ if (item->text.subtype == TEXT_ITEM_SYNTAX)
+ journal_output (j, text_item_get_plain_text (item));
+ break;
+
+ case OUTPUT_ITEM_GROUP:
+ for (size_t i = 0; i < item->group.n_children; i++)
+ journal_submit (driver, item->group.children[i]);
+ break;
+
+ case OUTPUT_ITEM_CHART:
+ case OUTPUT_ITEM_IMAGE:
+ case OUTPUT_ITEM_PAGE_BREAK:
+ case OUTPUT_ITEM_TABLE:
+ break;
+ }
+}
+
+static const struct output_driver_class journal_class =
+ {
+ .name = "journal",
+ .destroy = journal_destroy,
+ .submit = journal_submit,
+ };
+\f