+static void
+_notmuch_message_ensure_message_file (notmuch_message_t *message)
+{
+ const char *filename;
+
+ if (message->message_file)
+ return;
+
+ filename = notmuch_message_get_filename (message);
+ if (unlikely (filename == NULL))
+ return;
+
+ message->message_file = _notmuch_message_file_open_ctx (message, filename);
+}
+
+const char *
+notmuch_message_get_header (notmuch_message_t *message, const char *header)
+{
+ _notmuch_message_ensure_message_file (message);
+ if (message->message_file == NULL)
+ return NULL;
+
+ return notmuch_message_file_get_header (message->message_file, header);
+}
+
+const char *
+notmuch_message_get_all_headers (notmuch_message_t *message)
+{
+ _notmuch_message_ensure_message_file (message);
+ if (message->message_file == NULL)
+ return NULL;
+
+ return notmuch_message_file_get_all_headers (message->message_file);
+}
+
+size_t
+notmuch_message_get_header_size (notmuch_message_t *message)
+{
+ _notmuch_message_ensure_message_file (message);
+ if (message->message_file == NULL)
+ return 0;
+
+ return notmuch_message_file_get_header_size (message->message_file);
+
+}
+
+const char *
+notmuch_message_get_thread_id (notmuch_message_t *message)
+{
+ Xapian::TermIterator i;
+
+ if (message->thread_id)
+ return message->thread_id;
+
+ i = message->doc.termlist_begin ();
+ i.skip_to (_find_prefix ("thread"));
+
+ if (i == message->doc.termlist_end ())
+ INTERNAL_ERROR ("Message with document ID of %d has no thread ID.\n",
+ message->doc_id);
+
+ message->thread_id = talloc_strdup (message, (*i).c_str () + 1);
+
+#if DEBUG_DATABASE_SANITY
+ i++;
+
+ if (i != message->doc.termlist_end () &&
+ strncmp ((*i).c_str (), _find_prefix ("thread"),
+ strlen (_find_prefix ("thread"))) == 0)
+ {
+ INTERNAL_ERROR ("Message %s has duplicate thread IDs: %s and %s\n",
+ notmuch_message_get_message_id (message),
+ message->thread_id,
+ (*i).c_str () + 1);
+ }
+#endif
+
+ return message->thread_id;
+}
+
+/* Set the filename for 'message' to 'filename'.
+ *
+ * XXX: We should still figure out if we think it's important to store
+ * multiple filenames for email messages with identical message IDs.
+ *
+ * This change will not be reflected in the database until the next
+ * call to _notmuch_message_set_sync. */
+void
+_notmuch_message_set_filename (notmuch_message_t *message,
+ const char *filename)
+{
+ const char *s;
+ const char *db_path;
+ unsigned int db_path_len;
+
+ if (message->filename) {
+ talloc_free (message->filename);
+ message->filename = NULL;
+ }
+
+ if (filename == NULL)
+ INTERNAL_ERROR ("Message filename cannot be NULL.");
+
+ s = filename;
+
+ db_path = notmuch_database_get_path (message->notmuch);
+ db_path_len = strlen (db_path);
+
+ if (*s == '/' && strncmp (s, db_path, db_path_len) == 0
+ && strlen (s) > db_path_len)
+ {
+ s += db_path_len + 1;
+ }
+
+ message->doc.set_data (s);
+}
+