+ const char *join = "";
+ size_t i;
+
+ /* Don't optimize if there are no tag changes. */
+ if (tag_op_list_size (list) == 0)
+ return talloc_strdup (ctx, orig_query_string);
+
+ /* Build the new query string */
+ if (strcmp (orig_query_string, "*") == 0)
+ query_string = talloc_strdup (ctx, "(");
+ else
+ query_string = talloc_asprintf (ctx, "( %s ) and (", orig_query_string);
+
+ for (i = 0; i < tag_op_list_size (list) && query_string; i++) {
+ /* XXX in case of OOM, query_string will be deallocated when
+ * ctx is, which might be at shutdown */
+ if (make_boolean_term (ctx,
+ "tag", tag_op_list_tag (list, i),
+ &escaped, &escaped_len))
+ return NULL;
+
+ query_string = talloc_asprintf_append_buffer (
+ query_string, "%s%s%s", join,
+ tag_op_list_isremove (list, i) ? "" : "not ",
+ escaped);
+ join = " or ";
+ }
+
+ if (query_string)
+ query_string = talloc_strdup_append_buffer (query_string, ")");
+
+ talloc_free (escaped);
+ return query_string;
+}
+
+static char *
+_optimize_tag_query (void *ctx, const char *orig_query_string,
+ notmuch_query_syntax_t stx,
+ const tag_op_list_t *list)
+{
+ char *query_string;
+
+ if (stx == NOTMUCH_QUERY_SYNTAX_XAPIAN)
+ return _optimize_tag_query_infix (ctx, orig_query_string, list);
+
+ /* Don't optimize if there are no tag changes. */
+ if (tag_op_list_size (list) == 0)
+ return talloc_strdup (ctx, orig_query_string);
+
+ query_string = talloc_asprintf (ctx, "(and %s", orig_query_string);
+ for (size_t i = 0; i < tag_op_list_size (list) && query_string; i++) {
+ query_string = talloc_asprintf_append_buffer (
+ query_string, tag_op_list_isremove (list, i) ? " (tag \"%s\")" : " (not (tag \"%s\"))",
+ tag_op_list_tag (list, i));
+ }
+
+ if (query_string)
+ query_string = talloc_strdup_append_buffer (query_string, ")");
+
+ return query_string;
+}
+
+/* Tag messages matching 'query_string' according to 'tag_ops'
+ */
+static int
+tag_query (void *ctx, notmuch_database_t *notmuch, const char *query_string,
+ tag_op_list_t *tag_ops, tag_op_flag_t flags)
+{