+ 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;
+}
+
+/* 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)
+{