add namespace to some names
[pspp] / src / language / stats / ctables.c
index d3a00312a93a670f8d0159363f567ca73e0b39d9..5df2435b7b17f7eb785a4800a68738e525905613 100644 (file)
@@ -21,6 +21,7 @@
 
 #include "data/casereader.h"
 #include "data/casewriter.h"
+#include "data/data-in.h"
 #include "data/data-out.h"
 #include "data/dataset.h"
 #include "data/dictionary.h"
@@ -30,6 +31,7 @@
 #include "language/command.h"
 #include "language/lexer/format-parser.h"
 #include "language/lexer/lexer.h"
+#include "language/lexer/token.h"
 #include "language/lexer/variable-parser.h"
 #include "libpspp/array.h"
 #include "libpspp/assertion.h"
@@ -313,8 +315,8 @@ struct ctables_pcexpr
         /* CTPO_CAT_NUMBER. */
         double number;
 
-        /* CTPO_CAT_STRING. */
-        char *string;
+        /* CTPO_CAT_STRING, in dictionary encoding. */
+        struct substring string;
 
         /* CTPO_CAT_RANGE. */
         double range[2];
@@ -351,6 +353,12 @@ struct ctables_summary_spec_set
        (VALIDN and TOTALN act differently for summarizing scale and categorical
        variables.) */
     bool is_scale;
+
+    /* If any of these optional additional scale variables are missing, then
+       treat 'var' as if it's missing too.  This is for implementing
+       SMISSING=LISTWISE. */
+    struct variable **listwise_vars;
+    size_t n_listwise_vars;
   };
 
 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
@@ -365,6 +373,7 @@ struct ctables_nest
     size_t scale_idx;
     size_t *domains[N_CTDTS];
     size_t n_domains[N_CTDTS];
+    size_t group_head;
 
     struct ctables_summary_spec_set specs[N_CSVS];
   };
@@ -442,30 +451,6 @@ struct ctables_table
     struct ctables_pairwise *pairwise;
   };
 
-struct ctables_var
-  {
-    bool is_mrset;
-    union
-      {
-        struct variable *var;
-        const struct mrset *mrset;
-      };
-  };
-
-static const struct fmt_spec *
-ctables_var_get_print_format (const struct ctables_var *var)
-{
-  return (var->is_mrset
-          ? var_get_print_format (var->mrset->vars[0])
-          : var_get_print_format (var->var));
-}
-
-static const char *
-ctables_var_name (const struct ctables_var *var)
-{
-  return var->is_mrset ? var->mrset->name : var_get_name (var->var);
-}
-
 struct ctables_categories
   {
     size_t n_refs;
@@ -481,7 +466,8 @@ struct ctables_category
         /* Explicit category lists. */
         CCT_NUMBER,
         CCT_STRING,
-        CCT_RANGE,
+        CCT_NRANGE,             /* Numerical range. */
+        CCT_SRANGE,             /* String range. */
         CCT_MISSING,
         CCT_OTHERNM,
         CCT_POSTCOMPUTE,
@@ -506,9 +492,10 @@ struct ctables_category
 
     union
       {
-        double number;          /* CCT_NUMBER. */
-        char *string;           /* CCT_STRING. */
-        double range[2];        /* CCT_RANGE. */
+        double number;           /* CCT_NUMBER. */
+        struct substring string; /* CCT_STRING, in dictionary encoding. */
+        double nrange[2];        /* CCT_NRANGE. */
+        struct substring srange[2]; /* CCT_SRANGE. */
 
         struct
           {
@@ -545,14 +532,19 @@ ctables_category_uninit (struct ctables_category *cat)
   switch (cat->type)
     {
     case CCT_NUMBER:
-    case CCT_RANGE:
+    case CCT_NRANGE:
     case CCT_MISSING:
     case CCT_OTHERNM:
     case CCT_POSTCOMPUTE:
       break;
 
     case CCT_STRING:
-      free (cat->string);
+      ss_dealloc (&cat->string);
+      break;
+
+    case CCT_SRANGE:
+      ss_dealloc (&cat->srange[0]);
+      ss_dealloc (&cat->srange[1]);
       break;
 
     case CCT_SUBTOTAL:
@@ -570,6 +562,13 @@ ctables_category_uninit (struct ctables_category *cat)
     }
 }
 
+static bool
+nullable_substring_equal (const struct substring *a,
+                          const struct substring *b)
+{
+  return !a->string ? !b->string : b->string && ss_equals (*a, *b);
+}
+
 static bool
 ctables_category_equal (const struct ctables_category *a,
                         const struct ctables_category *b)
@@ -583,10 +582,14 @@ ctables_category_equal (const struct ctables_category *a,
       return a->number == b->number;
 
     case CCT_STRING:
-      return strcmp (a->string, b->string);
+      return ss_equals (a->string, b->string);
+
+    case CCT_NRANGE:
+      return a->nrange[0] == b->nrange[0] && a->nrange[1] == b->nrange[1];
 
-    case CCT_RANGE:
-      return a->range[0] == b->range[0] && a->range[1] == b->range[1];
+    case CCT_SRANGE:
+      return (nullable_substring_equal (&a->srange[0], &b->srange[0])
+              && nullable_substring_equal (&a->srange[1], &b->srange[1]));
 
     case CCT_MISSING:
     case CCT_OTHERNM:
@@ -685,7 +688,7 @@ struct ctables_axis
         /* Terminals. */
         struct
           {
-            struct ctables_var var;
+            struct variable *var;
             bool scale;
             struct ctables_summary_spec_set specs[N_CSVS];
           };
@@ -730,7 +733,7 @@ ctables_summary_spec_clone (struct ctables_summary_spec *dst,
                             const struct ctables_summary_spec *src)
 {
   *dst = *src;
-  dst->label = xstrdup (src->label);
+  dst->label = xstrdup_if_nonnull (src->label);
 }
 
 static void
@@ -956,7 +959,7 @@ struct ctables_axis_parse_ctx
 
 static struct fmt_spec
 ctables_summary_default_format (enum ctables_summary_function function,
-                                const struct ctables_var *var)
+                                const struct variable *var)
 {
   static const enum ctables_format default_formats[] = {
 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
@@ -972,7 +975,7 @@ ctables_summary_default_format (enum ctables_summary_function function,
       return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
 
     case CTF_GENERAL:
-      return *ctables_var_get_print_format (var);
+      return *var_get_print_format (var);
 
     default:
       NOT_REACHED ();
@@ -1015,19 +1018,15 @@ add_summary_spec (struct ctables_axis *axis,
   if (axis->op == CTAO_VAR)
     {
       const char *function_name = ctables_summary_function_name (function);
-      const char *var_name = ctables_var_name (&axis->var);
+      const char *var_name = var_get_name (axis->var);
       switch (ctables_function_availability (function))
         {
         case CTFA_MRSETS:
-          if (!axis->var.is_mrset)
-            {
-              msg_at (SE, loc, _("Summary function %s applies only to multiple "
-                                 "response sets."), function_name);
-              msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
-                      var_name);
-              return false;
-            }
-          break;
+          msg_at (SE, loc, _("Summary function %s applies only to multiple "
+                             "response sets."), function_name);
+          msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
+                  var_name);
+          return false;
 
         case CTFA_SCALE:
 #if 0
@@ -1058,7 +1057,7 @@ add_summary_spec (struct ctables_axis *axis,
         .percentile = percentile,
         .label = xstrdup (label),
         .format = (format ? *format
-                   : ctables_summary_default_format (function, &axis->var)),
+                   : ctables_summary_default_format (function, axis->var)),
         .is_ctables_format = is_ctables_format,
       };
       return true;
@@ -1076,35 +1075,6 @@ add_summary_spec (struct ctables_axis *axis,
 static struct ctables_axis *ctables_axis_parse_stack (
   struct ctables_axis_parse_ctx *);
 
-static bool
-ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
-                   struct ctables_var *var)
-{
-  if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
-    {
-      *var = (struct ctables_var) {
-        .is_mrset = true,
-        .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
-      };
-      if (!var->mrset)
-        {
-          lex_error (lexer, _("'%s' does not name a multiple-response set "
-                              "in the active file dictionary."),
-                     lex_tokcstr (lexer));
-          return false;
-        }
-      lex_get (lexer);
-      return true;
-    }
-  else
-    {
-      *var = (struct ctables_var) {
-        .is_mrset = false,
-        .var = parse_variable (lexer, dict),
-      };
-      return var->var != NULL;
-    }
-}
 
 static struct ctables_axis *
 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
@@ -1124,20 +1094,28 @@ ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
     return NULL;
 
   int start_ofs = lex_ofs (ctx->lexer);
-  struct ctables_var var;
-  if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
+  struct variable *var = parse_variable (ctx->lexer, ctx->dict);
+  if (!var)
     return NULL;
 
   struct ctables_axis *axis = xmalloc (sizeof *axis);
   *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
 
   /* XXX should figure out default measures by reading data */
-  axis->scale = (var.is_mrset ? false
-                 : lex_match_phrase (ctx->lexer, "[S]") ? true
+  axis->scale = (lex_match_phrase (ctx->lexer, "[S]") ? true
                  : lex_match_phrase (ctx->lexer, "[C]") ? false
-                 : var_get_measure (var.var) == MEASURE_SCALE);
+                 : var_get_measure (var) == MEASURE_SCALE);
   axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
                                 lex_ofs (ctx->lexer) - 1);
+  if (axis->scale && var_is_alpha (var))
+    {
+      msg_at (SE, axis->loc, _("Cannot use string variable %s as a scale "
+                               "variable."),
+              var_get_name (var));
+      ctables_axis_destroy (axis);
+      return NULL;
+    }
+
   return axis;
 }
 
@@ -1277,15 +1255,7 @@ find_scale (const struct ctables_axis *axis)
   if (!axis)
     return NULL;
   else if (axis->op == CTAO_VAR)
-    {
-      if (axis->scale)
-        {
-          assert (!axis->var.is_mrset);
-          return axis;
-        }
-      else
-        return NULL;
-    }
+    return axis->scale ? axis : NULL;
   else
     {
       for (size_t i = 0; i < 2; i++)
@@ -1455,11 +1425,20 @@ ctables_destroy (struct ctables *ct)
 }
 
 static struct ctables_category
-cct_range (double low, double high)
+cct_nrange (double low, double high)
+{
+  return (struct ctables_category) {
+    .type = CCT_NRANGE,
+    .nrange = { low, high }
+  };
+}
+
+static struct ctables_category
+cct_srange (struct substring low, struct substring high)
 {
   return (struct ctables_category) {
-    .type = CCT_RANGE,
-    .range = { low, high }
+    .type = CCT_SRANGE,
+    .srange = { low, high }
   };
 }
 
@@ -1487,8 +1466,20 @@ ctables_table_parse_subtotal (struct lexer *lexer, bool hide_subcategories,
   return true;
 }
 
+static struct substring
+parse_substring (struct lexer *lexer, struct dictionary *dict)
+{
+  struct substring s = recode_substring_pool (
+    dict_get_encoding (dict), "UTF-8", lex_tokss (lexer), NULL);
+  ss_rtrim (&s, ss_cstr (" "));
+  lex_get (lexer);
+  return s;
+}
+
 static bool
-ctables_table_parse_explicit_category (struct lexer *lexer, struct ctables *ct,
+ctables_table_parse_explicit_category (struct lexer *lexer,
+                                       struct dictionary *dict,
+                                       struct ctables *ct,
                                        struct ctables_category *cat)
 {
   if (lex_match_id (lexer, "OTHERNM"))
@@ -1501,10 +1492,21 @@ ctables_table_parse_explicit_category (struct lexer *lexer, struct ctables *ct,
     return ctables_table_parse_subtotal (lexer, true, cat);
   else if (lex_match_id (lexer, "LO"))
     {
-      if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
+      if (!lex_force_match_id (lexer, "THRU"))
+        return false;
+      if (lex_is_string (lexer))
+        {
+          struct substring sr0 = { .string = NULL };
+          struct substring sr1 = parse_substring (lexer, dict);
+          *cat = cct_srange (sr0, sr1);
+        }
+      else if (lex_force_num (lexer))
+        {
+          *cat = cct_nrange (-DBL_MAX, lex_number (lexer));
+          lex_get (lexer);
+        }
+      else
         return false;
-      *cat = cct_range (-DBL_MAX, lex_number (lexer));
-      lex_get (lexer);
     }
   else if (lex_is_number (lexer))
     {
@@ -1513,12 +1515,12 @@ ctables_table_parse_explicit_category (struct lexer *lexer, struct ctables *ct,
       if (lex_match_id (lexer, "THRU"))
         {
           if (lex_match_id (lexer, "HI"))
-            *cat = cct_range (number, DBL_MAX);
+            *cat = cct_nrange (number, DBL_MAX);
           else
             {
               if (!lex_force_num (lexer))
                 return false;
-              *cat = cct_range (number, lex_number (lexer));
+              *cat = cct_nrange (number, lex_number (lexer));
               lex_get (lexer);
             }
         }
@@ -1530,11 +1532,24 @@ ctables_table_parse_explicit_category (struct lexer *lexer, struct ctables *ct,
     }
   else if (lex_is_string (lexer))
     {
-      *cat = (struct ctables_category) {
-        .type = CCT_STRING,
-        .string = ss_xstrdup (lex_tokss (lexer)),
-      };
-      lex_get (lexer);
+      struct substring s = parse_substring (lexer, dict);
+      if (lex_match_id (lexer, "THRU"))
+        {
+          if (lex_match_id (lexer, "HI"))
+            {
+              struct substring sr1 = { .string = NULL };
+              *cat = cct_srange (s, sr1);
+            }
+          else
+            {
+              if (!lex_force_string (lexer))
+                return false;
+              struct substring sr1 = parse_substring (lexer, dict);
+              *cat = cct_srange (s, sr1);
+            }
+        }
+      else
+        *cat = (struct ctables_category) { .type = CCT_STRING, .string = s };
     }
   else if (lex_match (lexer, T_AND))
     {
@@ -1580,14 +1595,14 @@ ctables_find_category_for_postcompute (const struct ctables_categories *cats,
           break;
 
         case CTPO_CAT_STRING:
-          if (cat->type == CCT_STRING && !strcmp (cat->string, e->string))
+          if (cat->type == CCT_STRING && ss_equals (cat->string, e->string))
             best = cat;
           break;
 
         case CTPO_CAT_RANGE:
-          if (cat->type == CCT_RANGE
-              && cat->range[0] == e->range[0]
-              && cat->range[1] == e->range[1])
+          if (cat->type == CCT_NRANGE
+              && cat->nrange[0] == e->range[0]
+              && cat->nrange[1] == e->range[1])
             best = cat;
           break;
 
@@ -1711,6 +1726,44 @@ ctables_recursive_check_postcompute (const struct ctables_pcexpr *e,
     }
 }
 
+static bool
+parse_category_string (const struct ctables_category *cat,
+                       struct substring s, struct dictionary *dict,
+                       enum fmt_type format, double *n)
+{
+  union value v;
+  char *error = data_in (s, dict_get_encoding (dict), format,
+                         settings_get_fmt_settings (), &v, 0, NULL);
+  if (error)
+    {
+      msg_at (SE, cat->location,
+              _("Failed to parse category specification as format %s: %s."),
+              fmt_name (format), error);
+      free (error);
+      return false;
+    }
+
+  *n = v.f;
+  return true;
+}
+
+static bool
+all_strings (struct variable **vars, size_t n_vars,
+             const struct ctables_category *cat)
+{
+  for (size_t j = 0; j < n_vars; j++)
+    if (var_is_numeric (vars[j]))
+      {
+        msg_at (SE, cat->location,
+                _("This category specification may be applied only to string "
+                  "variables, but this subcommand tries to apply it to "
+                  "numeric variable %s."),
+                var_get_name (vars[j]));
+        return false;
+      }
+  return true;
+}
+
 static bool
 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
                                 struct ctables *ct, struct ctables_table *t)
@@ -1724,6 +1777,21 @@ ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
   if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
     return false;
 
+  const struct fmt_spec *common_format = var_get_print_format (vars[0]);
+  for (size_t i = 1; i < n_vars; i++)
+    {
+      const struct fmt_spec *f = var_get_print_format (vars[i]);
+      if (f->type != common_format->type)
+        {
+          common_format = NULL;
+          break;
+        }
+    }
+  bool parse_strings
+    = (common_format
+       && (fmt_get_category (common_format->type)
+           & (FMT_CAT_DATE | FMT_CAT_TIME | FMT_CAT_DATE_COMPONENT)));
+
   struct ctables_categories *c = xmalloc (sizeof *c);
   *c = (struct ctables_categories) { .n_refs = n_vars, .show_empty = true };
   for (size_t i = 0; i < n_vars; i++)
@@ -1733,7 +1801,6 @@ ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
       ctables_categories_unref (*cp);
       *cp = c;
     }
-  free (vars);
 
   size_t allocated_cats = 0;
   if (lex_match (lexer, T_LBRACK))
@@ -1746,7 +1813,7 @@ ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
 
           int start_ofs = lex_ofs (lexer);
           struct ctables_category *cat = &c->cats[c->n_cats];
-          if (!ctables_table_parse_explicit_category (lexer, ct, cat))
+          if (!ctables_table_parse_explicit_category (lexer, dict, ct, cat))
             return false;
           cat->location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
           c->n_cats++;
@@ -1760,10 +1827,84 @@ ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
       for (size_t i = 0; i < c->n_cats; i++)
         {
           struct ctables_category *cat = &c->cats[i];
-          if (cat->type == CCT_POSTCOMPUTE
-              && !ctables_recursive_check_postcompute (cat->pc->expr, cat,
-                                                       c, cats_location))
-            return false;
+          switch (cat->type)
+            {
+            case CCT_POSTCOMPUTE:
+              if (!ctables_recursive_check_postcompute (cat->pc->expr, cat,
+                                                        c, cats_location))
+                return false;
+              break;
+
+            case CCT_NUMBER:
+            case CCT_NRANGE:
+              for (size_t j = 0; j < n_vars; j++)
+                if (var_is_alpha (vars[j]))
+                  {
+                    msg_at (SE, cat->location,
+                            _("This category specification may be applied "
+                              "only to numeric variables, but this "
+                              "subcommand tries to apply it to string "
+                              "variable %s."),
+                            var_get_name (vars[j]));
+                    return false;
+                  }
+              break;
+
+            case CCT_STRING:
+              if (parse_strings)
+                {
+                  double n;
+                  if (!parse_category_string (cat, cat->string, dict,
+                                              common_format->type, &n))
+                    return false;
+
+                  ss_dealloc (&cat->string);
+
+                  cat->type = CCT_NUMBER;
+                  cat->number = n;
+                }
+              else if (!all_strings (vars, n_vars, cat))
+                return false;
+              break;
+
+            case CCT_SRANGE:
+              if (parse_strings)
+                {
+                  double n[2];
+
+                  if (!cat->srange[0].string)
+                    n[0] = -DBL_MAX;
+                  else if (!parse_category_string (cat, cat->srange[0], dict,
+                                                   common_format->type, &n[0]))
+                    return false;
+
+                  if (!cat->srange[1].string)
+                    n[1] = DBL_MAX;
+                  else if (!parse_category_string (cat, cat->srange[1], dict,
+                                                   common_format->type, &n[1]))
+                    return false;
+
+                  ss_dealloc (&cat->srange[0]);
+                  ss_dealloc (&cat->srange[1]);
+
+                  cat->type = CCT_NRANGE;
+                  cat->nrange[0] = n[0];
+                  cat->nrange[1] = n[1];
+                }
+              else if (!all_strings (vars, n_vars, cat))
+                return false;
+              break;
+
+            case CCT_MISSING:
+            case CCT_OTHERNM:
+            case CCT_SUBTOTAL:
+            case CCT_TOTAL:
+            case CCT_VALUE:
+            case CCT_LABEL:
+            case CCT_FUNCTION:
+            case CCT_EXCLUDED_MISSING:
+              break;
+            }
         }
     }
 
@@ -1932,7 +2073,8 @@ ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
         {
         case CCT_NUMBER:
         case CCT_STRING:
-        case CCT_RANGE:
+        case CCT_NRANGE:
+        case CCT_SRANGE:
         case CCT_MISSING:
         case CCT_OTHERNM:
           cat->subtotal = subtotal;
@@ -2031,13 +2173,39 @@ stack_fts (struct ctables_stack s0, struct ctables_stack s1)
   for (size_t i = 0; i < s0.n; i++)
     stack.nests[stack.n++] = s0.nests[i];
   for (size_t i = 0; i < s1.n; i++)
-    stack.nests[stack.n++] = s1.nests[i];
+    {
+      stack.nests[stack.n] = s1.nests[i];
+      stack.nests[stack.n].group_head += s0.n;
+      stack.n++;
+    }
   assert (stack.n == s0.n + s1.n);
   free (s0.nests);
   free (s1.nests);
   return stack;
 }
 
+static struct ctables_stack
+var_fts (const struct ctables_axis *a)
+{
+  struct variable **vars = xmalloc (sizeof *vars);
+  *vars = a->var;
+
+  struct ctables_nest *nest = xmalloc (sizeof *nest);
+  *nest = (struct ctables_nest) {
+    .vars = vars,
+    .n = 1,
+    .scale_idx = a->scale ? 0 : SIZE_MAX,
+  };
+  if (a->specs[CSV_CELL].n || a->scale)
+    for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
+      {
+        ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
+        nest->specs[sv].var = a->var;
+        nest->specs[sv].is_scale = a->scale;
+      }
+  return (struct ctables_stack) { .nests = nest, .n = 1 };
+}
+
 static struct ctables_stack
 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
 {
@@ -2047,31 +2215,15 @@ enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
   switch (a->op)
     {
     case CTAO_VAR:
-      assert (!a->var.is_mrset);
-
-      struct variable **vars = xmalloc (sizeof *vars);
-      *vars = a->var.var;
-
-      struct ctables_nest *nest = xmalloc (sizeof *nest);
-      *nest = (struct ctables_nest) {
-        .vars = vars,
-        .n = 1,
-        .scale_idx = a->scale ? 0 : SIZE_MAX,
-      };
-      if (a->specs[CSV_CELL].n || a->scale)
-        for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
-          {
-            ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
-            nest->specs[sv].var = a->var.var;
-            nest->specs[sv].is_scale = a->scale;
-          }
-      return (struct ctables_stack) { .nests = nest, .n = 1 };
+      return var_fts (a);
 
     case CTAO_STACK:
       return stack_fts (enumerate_fts (axis_type, a->subs[0]),
                         enumerate_fts (axis_type, a->subs[1]));
 
     case CTAO_NEST:
+      /* This should consider any of the scale variables found in the result to
+         be linked to each other listwise for SMISSING=LISTWISE. */
       return nest_fts (enumerate_fts (axis_type, a->subs[0]),
                        enumerate_fts (axis_type, a->subs[1]));
     }
@@ -2252,7 +2404,8 @@ static void
 ctables_summary_add (union ctables_summary *s,
                      const struct ctables_summary_spec *ss,
                      const struct variable *var, const union value *value,
-                     bool is_scale, bool is_missing, bool excluded_missing,
+                     bool is_scale, bool is_scale_missing,
+                     bool is_missing, bool excluded_missing,
                      double d_weight, double e_weight)
 {
   /* To determine whether a case is included in a given table for a particular
@@ -2307,7 +2460,7 @@ ctables_summary_add (union ctables_summary *s,
     case CTSF_LAYERROWPCT_VALIDN:
     case CTSF_LAYERCOLPCT_VALIDN:
       if (is_scale
-          ? !var_is_value_missing (var, value)
+          ? !is_scale_missing
           : !is_missing)
         s->count += d_weight;
       break;
@@ -2324,7 +2477,7 @@ ctables_summary_add (union ctables_summary *s,
 
     case CTSF_EVALIDN:
       if (is_scale
-          ? !var_is_value_missing (var, value)
+          ? !is_scale_missing
           : !is_missing)
         s->count += e_weight;
       break;
@@ -2336,7 +2489,7 @@ ctables_summary_add (union ctables_summary *s,
     case CTSF_MAXIMUM:
     case CTSF_MINIMUM:
     case CTSF_RANGE:
-      if (!var_is_value_missing (var, value))
+      if (!is_scale_missing)
         {
           assert (!var_is_alpha (var)); /* XXX? */
           if (s->min == SYSMIS || value->f < s->min)
@@ -2358,14 +2511,14 @@ ctables_summary_add (union ctables_summary *s,
     case CTSF_LAYERPCT_SUM:
     case CTSF_LAYERROWPCT_SUM:
     case CTSF_LAYERCOLPCT_SUM:
-      if (!var_is_value_missing (var, value))
+      if (!is_scale_missing)
         moments1_add (s->moments, value->f, e_weight);
       break;
 
     case CTSF_MEDIAN:
     case CTSF_MODE:
     case CTSF_PTILE:
-      if (var_is_value_missing (var, value))
+      if (!is_scale_missing)
         {
           s->ovalid += e_weight;
 
@@ -2640,7 +2793,8 @@ ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
             /* Must be equal. */
             continue;
 
-          case CCT_RANGE:
+          case CCT_NRANGE:
+          case CCT_SRANGE:
           case CCT_MISSING:
           case CCT_OTHERNM:
             {
@@ -2749,6 +2903,24 @@ ctables_domain_insert (struct ctables_section *s, struct ctables_cell *cell,
   return d;
 }
 
+static struct substring
+rtrim_value (const union value *v, const struct variable *var)
+{
+  struct substring s = ss_buffer (CHAR_CAST (char *, v->s),
+                                  var_get_width (var));
+  ss_rtrim (&s, ss_cstr (" "));
+  return s;
+}
+
+static bool
+in_string_range (const union value *v, const struct variable *var,
+                 const struct substring *srange)
+{
+  struct substring s = rtrim_value (v, var);
+  return ((!srange[0].string || ss_compare (s, srange[0]) >= 0)
+          && (!srange[1].string || ss_compare (s, srange[1]) <= 0));
+}
+
 static const struct ctables_category *
 ctables_categories_match (const struct ctables_categories *c,
                           const union value *v, const struct variable *var)
@@ -2768,11 +2940,18 @@ ctables_categories_match (const struct ctables_categories *c,
           break;
 
         case CCT_STRING:
-          NOT_REACHED ();
+          if (ss_equals (cat->string, rtrim_value (v, var)))
+            return cat;
+          break;
 
-        case CCT_RANGE:
-          if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
-              && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
+        case CCT_NRANGE:
+          if ((cat->nrange[0] == -DBL_MAX || v->f >= cat->nrange[0])
+              && (cat->nrange[1] == DBL_MAX || v->f <= cat->nrange[1]))
+            return cat;
+          break;
+
+        case CCT_SRANGE:
+          if (in_string_range (v, var, cat->srange))
             return cat;
           break;
 
@@ -2954,6 +3133,26 @@ ctables_cell_insert__ (struct ctables_section *s, const struct ccase *c,
   return cell;
 }
 
+static bool
+is_scale_missing (const struct ctables_summary_spec_set *specs,
+                  const struct ccase *c)
+{
+  if (!specs->is_scale)
+    return false;
+
+  if (var_is_num_missing (specs->var, case_num (c, specs->var)))
+    return true;
+
+  for (size_t i = 0; i < specs->n_listwise_vars; i++)
+    {
+      const struct variable *var = specs->listwise_vars[i];
+      if (var_is_num_missing (var, case_num (c, var)))
+        return true;
+    }
+
+  return false;
+}
+
 static void
 ctables_cell_add__ (struct ctables_section *s, const struct ccase *c,
                     const struct ctables_category *cats[PIVOT_N_AXES][10],
@@ -2964,10 +3163,13 @@ ctables_cell_add__ (struct ctables_section *s, const struct ccase *c,
   const struct ctables_nest *ss = s->nests[s->table->summary_axis];
 
   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
+
+  bool scale_missing = is_scale_missing (specs, c);
   for (size_t i = 0; i < specs->n; i++)
     ctables_summary_add (&cell->summaries[i], &specs->specs[i],
                          specs->var, case_data (c, specs->var), specs->is_scale,
-                         is_missing, excluded_missing, d_weight, e_weight);
+                         scale_missing, is_missing, excluded_missing,
+                         d_weight, e_weight);
   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
     if (!(cell->omit_domains && (1u << dt)))
       {
@@ -3161,17 +3363,75 @@ merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
 }
 
 static struct pivot_value *
-ctables_category_create_label (const struct ctables_category *cat,
-                               const struct variable *var,
-                               const union value *value)
+ctables_category_create_label__ (const struct ctables_category *cat,
+                                 const struct variable *var,
+                                 const union value *value)
 {
   return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL
           ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
-          : cat->type == CCT_POSTCOMPUTE && cat->pc->label
-          ? pivot_value_new_user_text (cat->pc->label, SIZE_MAX)
           : pivot_value_new_var_value (var, value));
 }
 
+static struct pivot_value *
+ctables_postcompute_label (const struct ctables_categories *cats,
+                           const struct ctables_category *cat,
+                           const struct variable *var,
+                           const union value *value)
+{
+  struct substring in = ss_cstr (cat->pc->label);
+  struct substring target = ss_cstr (")LABEL[");
+
+  struct string out = DS_EMPTY_INITIALIZER;
+  for (;;)
+    {
+      size_t chunk = ss_find_substring (in, target);
+      if (chunk == SIZE_MAX)
+        {
+          if (ds_is_empty (&out))
+            return pivot_value_new_user_text (in.string, in.length);
+          else
+            {
+              ds_put_substring (&out, in);
+              return pivot_value_new_user_text_nocopy (ds_steal_cstr (&out));
+            }
+        }
+
+      ds_put_substring (&out, ss_head (in, chunk));
+      ss_advance (&in, chunk + target.length);
+
+      struct substring idx_s;
+      if (!ss_get_until (&in, ']', &idx_s))
+        goto error;
+      char *tail;
+      long int idx = strtol (idx_s.string, &tail, 10);
+      if (idx < 1 || idx > cats->n_cats || tail != ss_end (idx_s))
+        goto error;
+
+      struct ctables_category *cat2 = &cats->cats[idx - 1];
+      struct pivot_value *label2
+        = ctables_category_create_label__ (cat2, var, value);
+      char *label2_s = pivot_value_to_string_defaults (label2);
+      ds_put_cstr (&out, label2_s);
+      free (label2_s);
+      pivot_value_destroy (label2);
+    }
+
+error:
+  ds_destroy (&out);
+  return pivot_value_new_user_text (cat->pc->label, SIZE_MAX);
+}
+
+static struct pivot_value *
+ctables_category_create_label (const struct ctables_categories *cats,
+                               const struct ctables_category *cat,
+                               const struct variable *var,
+                               const union value *value)
+{
+  return (cat->type == CCT_POSTCOMPUTE && cat->pc->label
+          ? ctables_postcompute_label (cats, cat, var, value)
+          : ctables_category_create_label__ (cat, var, value));
+}
+
 static struct ctables_value *
 ctables_value_find__ (struct ctables_table *t, const union value *value,
                       int width, unsigned int hash)
@@ -3286,6 +3546,7 @@ struct ctables_pcexpr_evaluate_ctx
     const struct ctables_categories *cats;
     enum pivot_axis_type pc_a;
     size_t pc_a_idx;
+    size_t summary_idx;
   };
 
 static double ctables_pcexpr_evaluate (
@@ -3366,8 +3627,8 @@ found: ;
   const struct ctables_table *t = s->table;
   const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
   const struct ctables_summary_spec_set *specs = &specs_nest->specs[tc->sv];
-  size_t j = 0 /* XXX */;
-  return ctables_summary_value (tc, &tc->summaries[j], &specs->specs[j]);
+  return ctables_summary_value (tc, &tc->summaries[ctx->summary_idx],
+                                &specs->specs[ctx->summary_idx]);
 }
 
 static double
@@ -3437,27 +3698,61 @@ ctables_pcexpr_evaluate (const struct ctables_pcexpr_evaluate_ctx *ctx,
   NOT_REACHED ();
 }
 
+/* XXX what if there is a postcompute in more than one dimension?? */
+static const struct ctables_postcompute *
+ctables_cell_postcompute (const struct ctables_section *s,
+                          const struct ctables_cell *cell,
+                          enum pivot_axis_type *pc_a_p,
+                          size_t *pc_a_idx_p)
+{
+  assert (cell->postcompute);
+  for (enum pivot_axis_type pc_a = 0; ; pc_a++)
+    {
+      assert (pc_a < PIVOT_N_AXES);
+      for (size_t pc_a_idx = 0; pc_a_idx < s->nests[pc_a]->n; pc_a_idx++)
+        {
+          const struct ctables_cell_value *cv = &cell->axes[pc_a].cvs[pc_a_idx];
+          if (cv->category->type == CCT_POSTCOMPUTE)
+            {
+              if (pc_a_p)
+                *pc_a_p = pc_a;
+              if (pc_a_idx_p)
+                *pc_a_idx_p = pc_a_idx;
+              return cv->category->pc;
+            }
+        }
+    }
+
+  NOT_REACHED ();
+}
+
 static double
 ctables_cell_calculate_postcompute (const struct ctables_section *s,
-                                    const struct ctables_cell *cell)
+                                    const struct ctables_cell *cell,
+                                    const struct ctables_summary_spec *ss,
+                                    struct fmt_spec *format,
+                                    bool *is_ctables_format,
+                                    size_t summary_idx)
 {
   enum pivot_axis_type pc_a;
   size_t pc_a_idx;
-  const struct ctables_postcompute *pc;
-  for (pc_a = 0; ; pc_a++)
+  const struct ctables_postcompute *pc = ctables_cell_postcompute (
+    s, cell, &pc_a, &pc_a_idx);
+
+  if (pc->specs)
     {
-      assert (pc_a < PIVOT_N_AXES);
-      for (pc_a_idx = 0; pc_a_idx < s->nests[pc_a]->n; pc_a_idx++)
+      for (size_t i = 0; i < pc->specs->n; i++)
         {
-          const struct ctables_cell_value *cv = &cell->axes[pc_a].cvs[pc_a_idx];
-          if (cv->category->type == CCT_POSTCOMPUTE)
+          const struct ctables_summary_spec *ss2 = &pc->specs->specs[i];
+          if (ss->function == ss2->function
+              && ss->percentile == ss2->percentile)
             {
-              pc = cv->category->pc;
-              goto found;
+              *format = ss2->format;
+              *is_ctables_format = ss2->is_ctables_format;
+              break;
             }
         }
     }
-found: ;
 
   const struct variable *var = s->nests[pc_a]->vars[pc_a_idx];
   const struct ctables_categories *cats = s->table->categories[
@@ -3468,6 +3763,7 @@ found: ;
     .cats = cats,
     .pc_a = pc_a,
     .pc_a_idx = pc_a_idx,
+    .summary_idx = summary_idx,
   };
   return ctables_pcexpr_evaluate (&ctx, pc->expr);
 }
@@ -3484,7 +3780,7 @@ ctables_table_output (struct ctables *ct, struct ctables_table *t)
     pivot_table_set_caption (
       pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
   if (t->corner)
-    pivot_table_set_caption (
+    pivot_table_set_corner_text (
       pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
 
   bool summary_dimension = (t->summary_axis != t->slabels_axis
@@ -3518,7 +3814,8 @@ ctables_table_output (struct ctables *ct, struct ctables_table *t)
           const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
           assert (cat != NULL);
           pivot_category_create_leaf (d->root, ctables_category_create_label (
-                                        cat, t->clabels_example, &value->value));
+                                        c, cat, t->clabels_example,
+                                        &value->value));
         }
     }
 
@@ -3710,8 +4007,9 @@ ctables_table_output (struct ctables *ct, struct ctables_table *t)
                       else if (level->type == CTL_CATEGORY)
                         {
                           const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
-                          label = ctables_category_create_label (cv->category,
-                                                                 var, &cv->value);
+                          label = ctables_category_create_label (
+                            t->categories[var_get_dict_index (var)],
+                            cv->category, var, &cv->value);
                         }
                       else
                         NOT_REACHED ();
@@ -3772,15 +4070,18 @@ ctables_table_output (struct ctables *ct, struct ctables_table *t)
 
               const struct ctables_summary_spec *ss = &specs->specs[j];
 
+              struct fmt_spec format = specs->specs[j].format;
+              bool is_ctables_format = ss->is_ctables_format;
               double d = (cell->postcompute
-                          ? ctables_cell_calculate_postcompute (s, cell)
-                          : ctables_summary_value (cell, &cell->summaries[j], ss));
+                          ? ctables_cell_calculate_postcompute (
+                            s, cell, ss, &format, &is_ctables_format, j)
+                          : ctables_summary_value (cell, &cell->summaries[j],
+                                                   ss));
+
               struct pivot_value *value;
               if (ct->hide_threshold != 0
                   && d < ct->hide_threshold
-                  && (cell->postcompute
-                      ? false /* XXX */
-                      : ctables_summary_function_is_count (ss->function)))
+                  && ctables_summary_function_is_count (ss->function))
                 {
                   value = pivot_value_new_user_text_nocopy (
                     xasprintf ("<%d", ct->hide_threshold));
@@ -3789,18 +4090,17 @@ ctables_table_output (struct ctables *ct, struct ctables_table *t)
                 value = pivot_value_new_user_text (ct->zero, SIZE_MAX);
               else if (d == SYSMIS && ct->missing)
                 value = pivot_value_new_user_text (ct->missing, SIZE_MAX);
-              else if (specs->specs[j].is_ctables_format)
+              else if (is_ctables_format)
                 {
                   char *s = data_out_stretchy (&(union value) { .f = d },
-                                               "UTF-8",
-                                               &specs->specs[j].format,
+                                               "UTF-8", &format,
                                                &ct->ctables_formats, NULL);
                   value = pivot_value_new_user_text_nocopy (s);
                 }
               else
                 {
                   value = pivot_value_new_number (d);
-                  value->numeric.format = specs->specs[j].format;
+                  value->numeric.format = format;
                 }
               pivot_table_put (pt, dindexes, n_dindexes, value);
             }
@@ -3977,11 +4277,10 @@ ctables_prepare_table (struct ctables_table *t)
 
           enum ctables_summary_function function
             = specs->is_scale ? CTSF_MEAN : CTSF_COUNT;
-          struct ctables_var var = { .is_mrset = false, .var = specs->var };
 
           *specs->specs = (struct ctables_summary_spec) {
             .function = function,
-            .format = ctables_summary_default_format (function, &var),
+            .format = ctables_summary_default_format (function, specs->var),
             .label = ctables_summary_default_label (function, 0),
           };
           if (!specs->var)
@@ -3993,6 +4292,33 @@ ctables_prepare_table (struct ctables_table *t)
       else if (!nest->specs[CSV_TOTAL].n)
         ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
                                         &nest->specs[CSV_CELL]);
+
+      if (t->ctables->smissing_listwise)
+        {
+          struct variable **listwise_vars = NULL;
+          size_t n = 0;
+          size_t allocated = 0;
+
+          for (size_t j = nest->group_head; j < stack->n; j++)
+            {
+              const struct ctables_nest *other_nest = &stack->nests[j];
+              if (other_nest->group_head != nest->group_head)
+                break;
+
+              if (nest != other_nest && other_nest->scale_idx < other_nest->n)
+                {
+                  if (n >= allocated)
+                    listwise_vars = x2nrealloc (listwise_vars, &allocated,
+                                                sizeof *listwise_vars);
+                  listwise_vars[n++] = other_nest->vars[other_nest->scale_idx];
+                }
+            }
+          for (size_t j = 0; j < N_CSVS; j++)
+            {
+              nest->specs[j].listwise_vars = listwise_vars;
+              nest->specs[j].n_listwise_vars = n;
+            }
+        }
     }
 
   struct ctables_summary_spec_set *merged = &t->summary_specs;
@@ -4138,13 +4464,31 @@ ctables_add_category_occurrences (const struct variable *var,
           break;
 
         case CCT_STRING:
-          abort ();             /* XXX */
+          {
+            int width = var_get_width (var);
+            union value value;
+            value_init (&value, width);
+            value_copy_buf_rpad (&value, width,
+                                 CHAR_CAST (uint8_t *, c->string.string),
+                                 c->string.length, ' ');
+            ctables_add_occurrence (var, &value, occurrences);
+            value_destroy (&value, width);
+          }
+          break;
 
-        case CCT_RANGE:
+        case CCT_NRANGE:
           assert (var_is_numeric (var));
           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
                vl = val_labs_next (val_labs, vl))
-            if (vl->value.f >= c->range[0] && vl->value.f <= c->range[1])
+            if (vl->value.f >= c->nrange[0] && vl->value.f <= c->nrange[1])
+              ctables_add_occurrence (var, &vl->value, occurrences);
+          break;
+
+        case CCT_SRANGE:
+          assert (var_is_alpha (var));
+          for (const struct val_lab *vl = val_labs_first (val_labs); vl;
+               vl = val_labs_next (val_labs, vl))
+            if (in_string_range (&vl->value, var, c->srange))
               ctables_add_occurrence (var, &vl->value, occurrences);
           break;
 
@@ -4308,7 +4652,8 @@ ctables_execute (struct dataset *ds, struct ctables *ct)
 \f
 /* Postcomputes. */
 
-typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *);
+typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *,
+                                                       struct dictionary *);
 
 static void
 ctables_pcexpr_destroy (struct ctables_pcexpr *e)
@@ -4318,7 +4663,7 @@ ctables_pcexpr_destroy (struct ctables_pcexpr *e)
       switch (e->op)
         {
         case CTPO_CAT_STRING:
-          free (e->string);
+          ss_dealloc (&e->string);
           break;
 
         case CTPO_ADD:
@@ -4368,7 +4713,8 @@ struct operator
   };
 
 static const struct operator *
-match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
+ctable_pcexpr_match_operator (struct lexer *lexer,
+                              const struct operator ops[], size_t n_ops)
 {
   for (const struct operator *op = ops; op < ops + n_ops; op++)
     if (lex_token (lexer) == op->token)
@@ -4383,15 +4729,16 @@ match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
 }
 
 static struct ctables_pcexpr *
-parse_binary_operators__ (struct lexer *lexer,
-                          const struct operator ops[], size_t n_ops,
-                          parse_recursively_func *parse_next_level,
-                          const char *chain_warning,
-                          struct ctables_pcexpr *lhs)
+ctable_pcexpr_parse_binary_operators__ (
+  struct lexer *lexer, struct dictionary *dict,
+  const struct operator ops[], size_t n_ops,
+  parse_recursively_func *parse_next_level,
+  const char *chain_warning, struct ctables_pcexpr *lhs)
 {
   for (int op_count = 0; ; op_count++)
     {
-      const struct operator *op = match_operator (lexer, ops, n_ops);
+      const struct operator *op
+        = ctable_pcexpr_match_operator (lexer, ops, n_ops);
       if (!op)
         {
           if (op_count > 1 && chain_warning)
@@ -4400,7 +4747,7 @@ parse_binary_operators__ (struct lexer *lexer,
           return lhs;
         }
 
-      struct ctables_pcexpr *rhs = parse_next_level (lexer);
+      struct ctables_pcexpr *rhs = parse_next_level (lexer, dict);
       if (!rhs)
         {
           ctables_pcexpr_destroy (lhs);
@@ -4412,20 +4759,23 @@ parse_binary_operators__ (struct lexer *lexer,
 }
 
 static struct ctables_pcexpr *
-parse_binary_operators (struct lexer *lexer,
-                        const struct operator ops[], size_t n_ops,
-                        parse_recursively_func *parse_next_level,
-                        const char *chain_warning)
+ctable_pcexpr_parse_binary_operators (struct lexer *lexer,
+                                      struct dictionary *dict,
+                                      const struct operator ops[], size_t n_ops,
+                                      parse_recursively_func *parse_next_level,
+                                      const char *chain_warning)
 {
-  struct ctables_pcexpr *lhs = parse_next_level (lexer);
+  struct ctables_pcexpr *lhs = parse_next_level (lexer, dict);
   if (!lhs)
     return NULL;
 
-  return parse_binary_operators__ (lexer, ops, n_ops, parse_next_level,
-                                   chain_warning, lhs);
+  return ctable_pcexpr_parse_binary_operators__ (lexer, dict, ops, n_ops,
+                                                 parse_next_level,
+                                                 chain_warning, lhs);
 }
 
-static struct ctables_pcexpr *parse_add (struct lexer *);
+static struct ctables_pcexpr *ctable_pcexpr_parse_add (struct lexer *,
+                                                       struct dictionary *);
 
 static struct ctables_pcexpr
 ctpo_cat_range (double low, double high)
@@ -4437,7 +4787,7 @@ ctpo_cat_range (double low, double high)
 }
 
 static struct ctables_pcexpr *
-parse_primary (struct lexer *lexer)
+ctable_pcexpr_parse_primary (struct lexer *lexer, struct dictionary *dict)
 {
   int start_ofs = lex_ofs (lexer);
   struct ctables_pcexpr e;
@@ -4499,10 +4849,11 @@ parse_primary (struct lexer *lexer)
         }
       else if (lex_is_string (lexer))
         {
-          e = (struct ctables_pcexpr) {
-            .op = CTPO_CAT_STRING,
-            .string = ss_xstrdup (lex_tokss (lexer)),
-          };
+          struct substring s = recode_substring_pool (
+            dict_get_encoding (dict), "UTF-8", lex_tokss (lexer), NULL);
+          ss_rtrim (&s, ss_cstr (" "));
+
+          e = (struct ctables_pcexpr) { .op = CTPO_CAT_STRING, .string = s };
           lex_get (lexer);
         }
       else
@@ -4514,13 +4865,13 @@ parse_primary (struct lexer *lexer)
       if (!lex_force_match (lexer, T_RBRACK))
         {
           if (e.op == CTPO_CAT_STRING)
-            free (e.string);
+            ss_dealloc (&e.string);
           return NULL;
         }
     }
   else if (lex_match (lexer, T_LPAREN))
     {
-      struct ctables_pcexpr *ep = parse_add (lexer);
+      struct ctables_pcexpr *ep = ctable_pcexpr_parse_add (lexer, dict);
       if (!ep)
         return NULL;
       if (!lex_force_match (lexer, T_RPAREN))
@@ -4554,7 +4905,7 @@ ctables_pcexpr_allocate_neg (struct ctables_pcexpr *sub,
 }
 
 static struct ctables_pcexpr *
-parse_exp (struct lexer *lexer)
+ctable_pcexpr_parse_exp (struct lexer *lexer, struct dictionary *dict)
 {
   static const struct operator op = { T_EXP, CTPO_POW };
 
@@ -4564,8 +4915,9 @@ parse_exp (struct lexer *lexer)
       "To disable this warning, insert parentheses.");
 
   if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
-    return parse_binary_operators (lexer, &op, 1,
-                                   parse_primary, chain_warning);
+    return ctable_pcexpr_parse_binary_operators (lexer, dict, &op, 1,
+                                                 ctable_pcexpr_parse_primary,
+                                                 chain_warning);
 
   /* Special case for situations like "-5**6", which must be parsed as
      -(5**6). */
@@ -4579,8 +4931,9 @@ parse_exp (struct lexer *lexer)
   };
   lex_get (lexer);
 
-  struct ctables_pcexpr *node = parse_binary_operators__ (
-    lexer, &op, 1, parse_primary, chain_warning, lhs);
+  struct ctables_pcexpr *node = ctable_pcexpr_parse_binary_operators__ (
+    lexer, dict, &op, 1,
+    ctable_pcexpr_parse_primary, chain_warning, lhs);
   if (!node)
     return NULL;
 
@@ -4589,13 +4942,13 @@ parse_exp (struct lexer *lexer)
 
 /* Parses the unary minus level. */
 static struct ctables_pcexpr *
-parse_neg (struct lexer *lexer)
+ctable_pcexpr_parse_neg (struct lexer *lexer, struct dictionary *dict)
 {
   int start_ofs = lex_ofs (lexer);
   if (!lex_match (lexer, T_DASH))
-    return parse_exp (lexer);
+    return ctable_pcexpr_parse_exp (lexer, dict);
 
-  struct ctables_pcexpr *inner = parse_neg (lexer);
+  struct ctables_pcexpr *inner = ctable_pcexpr_parse_neg (lexer, dict);
   if (!inner)
     return NULL;
 
@@ -4604,7 +4957,7 @@ parse_neg (struct lexer *lexer)
 
 /* Parses the multiplication and division level. */
 static struct ctables_pcexpr *
-parse_mul (struct lexer *lexer)
+ctable_pcexpr_parse_mul (struct lexer *lexer, struct dictionary *dict)
 {
   static const struct operator ops[] =
     {
@@ -4612,13 +4965,14 @@ parse_mul (struct lexer *lexer)
       { T_SLASH, CTPO_DIV },
     };
 
-  return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
-                                 parse_neg, NULL);
+  return ctable_pcexpr_parse_binary_operators (lexer, dict, ops,
+                                               sizeof ops / sizeof *ops,
+                                               ctable_pcexpr_parse_neg, NULL);
 }
 
 /* Parses the addition and subtraction level. */
 static struct ctables_pcexpr *
-parse_add (struct lexer *lexer)
+ctable_pcexpr_parse_add (struct lexer *lexer, struct dictionary *dict)
 {
   static const struct operator ops[] =
     {
@@ -4627,8 +4981,9 @@ parse_add (struct lexer *lexer)
       { T_NEG_NUM, CTPO_ADD },
     };
 
-  return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
-                                 parse_mul, NULL);
+  return ctable_pcexpr_parse_binary_operators (lexer, dict,
+                                               ops, sizeof ops / sizeof *ops,
+                                               ctable_pcexpr_parse_mul, NULL);
 }
 
 static struct ctables_postcompute *
@@ -4643,7 +4998,8 @@ ctables_find_postcompute (struct ctables *ct, const char *name)
 }
 
 static bool
-ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
+ctables_parse_pcompute (struct lexer *lexer, struct dictionary *dict,
+                        struct ctables *ct)
 {
   int pcompute_start = lex_ofs (lexer) - 1;
 
@@ -4662,7 +5018,7 @@ ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
     }
 
   int expr_start = lex_ofs (lexer);
-  struct ctables_pcexpr *expr = parse_add (lexer);
+  struct ctables_pcexpr *expr = ctable_pcexpr_parse_add (lexer, dict);
   int expr_end = lex_ofs (lexer) - 1;
   if (!expr || !lex_force_match (lexer, T_RPAREN))
     {
@@ -4729,9 +5085,8 @@ ctables_parse_pproperties_format (struct lexer *lexer,
 
       /* Parse format. */
       struct fmt_spec format;
-      if (!parse_format_specifier (lexer, &format)
-          || !fmt_check_output (&format)
-          || !fmt_check_type_compat (&format, VAL_NUMERIC))
+      bool is_ctables_format;
+      if (!parse_ctables_format_specifier (lexer, &format, &is_ctables_format))
         goto error;
 
       if (sss->n >= sss->allocated)
@@ -4741,6 +5096,7 @@ ctables_parse_pproperties_format (struct lexer *lexer,
         .function = function,
         .percentile = percentile,
         .format = format,
+        .is_ctables_format = is_ctables_format,
       };
     }
   return true;
@@ -4832,6 +5188,92 @@ error:
   return false;
 }
 
+static void
+put_strftime (struct string *out, time_t now, const char *format)
+{
+  const struct tm *tm = localtime (&now);
+  char value[128];
+  strftime (value, sizeof value, format, tm);
+  ds_put_cstr (out, value);
+}
+
+static bool
+skip_prefix (struct substring *s, struct substring prefix)
+{
+  if (ss_starts_with (*s, prefix))
+    {
+      ss_advance (s, prefix.length);
+      return true;
+    }
+  else
+    return false;
+}
+
+static void
+put_table_expression (struct string *out, struct lexer *lexer,
+                      struct dictionary *dict, int expr_start, int expr_end)
+{
+  size_t nest = 0;
+  for (int ofs = expr_start; ofs < expr_end; ofs++)
+    {
+      const struct token *t = lex_ofs_token (lexer, ofs);
+      if (t->type == T_LBRACK)
+        nest++;
+      else if (t->type == T_RBRACK && nest > 0)
+        nest--;
+      else if (nest > 0)
+        {
+          /* Nothing. */
+        }
+      else if (t->type == T_ID)
+        {
+          const struct variable *var
+            = dict_lookup_var (dict, t->string.string);
+          const char *label = var ? var_get_label (var) : NULL;
+          ds_put_cstr (out, label ? label : t->string.string);
+        }
+      else
+        {
+          if (ofs != expr_start && t->type != T_RPAREN && ds_last (out) != ' ')
+            ds_put_byte (out, ' ');
+
+          char *repr = lex_ofs_representation (lexer, ofs, ofs);
+          ds_put_cstr (out, repr);
+          free (repr);
+
+          if (ofs + 1 != expr_end && t->type != T_LPAREN)
+            ds_put_byte (out, ' ');
+        }
+    }
+}
+
+static void
+put_title_text (struct string *out, struct substring in, time_t now,
+                struct lexer *lexer, struct dictionary *dict,
+                int expr_start, int expr_end)
+{
+  for (;;)
+    {
+      size_t chunk = ss_find_byte (in, ')');
+      ds_put_substring (out, ss_head (in, chunk));
+      ss_advance (&in, chunk);
+      if (ss_is_empty (in))
+        return;
+
+      if (skip_prefix (&in, ss_cstr (")DATE")))
+        put_strftime (out, now, "%x");
+      else if (skip_prefix (&in, ss_cstr (")TIME")))
+        put_strftime (out, now, "%X");
+      else if (skip_prefix (&in, ss_cstr (")TABLE")))
+        put_table_expression (out, lexer, dict, expr_start, expr_end);
+      else
+        {
+          ds_put_byte (out, ')');
+          ss_advance (&in, 1);
+        }
+    }
+}
+
 int
 cmd_ctables (struct lexer *lexer, struct dataset *ds)
 {
@@ -4854,6 +5296,8 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
     .postcomputes = HMAP_INITIALIZER (ct->postcomputes),
   };
 
+  time_t now = time (NULL);
+
   struct ctf
     {
       enum fmt_type type;
@@ -5031,7 +5475,7 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
         }
       else if (lex_match_id (lexer, "PCOMPUTE"))
         {
-          if (!ctables_parse_pcompute (lexer, ct))
+          if (!ctables_parse_pcompute (lexer, dataset_dict (ds), ct))
             goto error;
         }
       else if (lex_match_id (lexer, "PPROPERTIES"))
@@ -5121,6 +5565,7 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
       ct->tables[ct->n_tables++] = t;
 
       lex_match (lexer, T_EQUALS);
+      int expr_start = lex_ofs (lexer);
       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
         goto error;
       if (lex_match (lexer, T_BY))
@@ -5136,6 +5581,7 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
                 goto error;
             }
         }
+      int expr_end = lex_ofs (lexer);
 
       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
           && !t->axes[PIVOT_AXIS_LAYER])
@@ -5324,7 +5770,9 @@ cmd_ctables (struct lexer *lexer, struct dataset *ds)
                     {
                       if (!ds_is_empty (&s))
                         ds_put_byte (&s, ' ');
-                      ds_put_substring (&s, lex_tokss (lexer));
+                      put_title_text (&s, lex_tokss (lexer), now,
+                                      lexer, dataset_dict (ds),
+                                      expr_start, expr_end);
                       lex_get (lexer);
                     }
                   free (*textp);