]> git.notmuchmail.org Git - notmuch/blob - notmuch.c
show: Pass notmuch_message_t instead of path to show_message_body.
[notmuch] / notmuch.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  * Copyright © 2009 Keith Packard
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see http://www.gnu.org/licenses/ .
18  *
19  * Authors: Carl Worth <cworth@cworth.org>
20  *          Keith Packard <keithp@keithp.com>
21  */
22
23 #include "notmuch-client.h"
24
25 typedef int (*command_function_t) (void *ctx, int argc, char *argv[]);
26
27 typedef struct command {
28     const char *name;
29     command_function_t function;
30     const char *arguments;
31     const char *summary;
32     const char *documentation;
33 } command_t;
34
35 #define MAX_ALIAS_SUBSTITUTIONS 3
36
37 typedef struct alias {
38     const char *name;
39     const char *substitutions[MAX_ALIAS_SUBSTITUTIONS];
40 } alias_t;
41
42 alias_t aliases[] = {
43     { "part", { "show", "--format=raw"}},
44     { "search-tags", {"search", "--output=tags", "*"}}
45 };
46
47 static int
48 notmuch_help_command (void *ctx, int argc, char *argv[]);
49
50 static const char search_terms_help[] =
51     "\tSeveral notmuch commands accept a common syntax for search\n"
52     "\tterms.\n"
53     "\n"
54     "\tThe search terms can consist of free-form text (and quoted\n"
55     "\tphrases) which will match all messages that contain all of\n"
56     "\tthe given terms/phrases in the body, the subject, or any of\n"
57     "\tthe sender or recipient headers.\n"
58     "\n"
59     "\tAs a special case, a search string consisting of exactly a\n"
60     "\tsingle asterisk (\"*\") will match all messages.\n"
61     "\n"
62     "\tIn addition to free text, the following prefixes can be used\n"
63     "\tto force terms to match against specific portions of an email,\n"
64     "\t(where <brackets> indicate user-supplied values):\n"
65     "\n"
66     "\t\tfrom:<name-or-address>\n"
67     "\t\tto:<name-or-address>\n"
68     "\t\tsubject:<word-or-quoted-phrase>\n"
69     "\t\tattachment:<word>\n"
70     "\t\ttag:<tag> (or is:<tag>)\n"
71     "\t\tid:<message-id>\n"
72     "\t\tthread:<thread-id>\n"
73     "\t\tfolder:<directory-path>\n"
74     "\n"
75     "\tThe from: prefix is used to match the name or address of\n"
76     "\tthe sender of an email message.\n"
77     "\n"
78     "\tThe to: prefix is used to match the names or addresses of\n"
79     "\tany recipient of an email message, (whether To, Cc, or Bcc).\n"
80     "\n"
81     "\tAny term prefixed with subject: will match only text from\n"
82     "\tthe subject of an email. Quoted phrases are supported when\n"
83     "\tsearching with: subject:\"this is a phrase\".\n"
84     "\n"
85     "\tFor tag: and is:, valid tag values include \"inbox\" and \"unread\"\n"
86     "\tby default for new messages added by \"notmuch new\" as well\n"
87     "\tas any other tag values added manually with \"notmuch tag\".\n"
88     "\n"
89     "\tFor id:, message ID values are the literal contents of the\n"
90     "\tMessage-ID: header of email messages, but without the '<','>'\n"
91     "\tdelimiters.\n"
92     "\n"
93     "\tThe thread: prefix can be used with the thread ID values that\n"
94     "\tare generated internally by notmuch (and do not appear in email\n"
95     "\tmessages). These thread ID values can be seen in the first\n"
96     "\tcolumn of output from \"notmuch search\".\n"
97     "\n"
98     "\tThe folder: prefix can be used to search for email message\n"
99     "\tfiles that are contained within particular directories within\n"
100     "\tthe mail store. Only the directory components below the top-level\n"
101     "\tmail database path are available to be searched.\n"
102     "\n"
103     "\tIn addition to individual terms, multiple terms can be\n"
104     "\tcombined with Boolean operators (\"and\", \"or\", \"not\", etc.).\n"
105     "\tEach term in the query will be implicitly connected by a\n"
106     "\tlogical AND if no explicit operator is provided, (except\n"
107     "\tthat terms with a common prefix will be implicitly combined\n"
108     "\twith OR until we get Xapian defect #402 fixed).\n"
109     "\n"
110     "\tParentheses can also be used to control the combination of\n"
111     "\tthe Boolean operators, but will have to be protected from\n"
112     "\tinterpretation by the shell, (such as by putting quotation\n"
113     "\tmarks around any parenthesized expression).\n"
114     "\n"
115     "\tFinally, results can be restricted to only messages within a\n"
116     "\tparticular time range, (based on the Date: header) with:\n"
117     "\n"
118     "\t\t<intial-timestamp>..<final-timestamp>\n"
119     "\n"
120     "\tEach timestamp is a number representing the number of seconds\n"
121     "\tsince 1970-01-01 00:00:00 UTC. This is not the most convenient\n"
122     "\tmeans of expressing date ranges, but until notmuch is fixed to\n"
123     "\taccept a more convenient form, one can use the date program to\n"
124     "\tconstruct timestamps. For example, with the bash shell the\n"
125     "\tfollowing syntax would specify a date range to return messages\n"
126     "\tfrom 2009-10-01 until the current time:\n"
127     "\n"
128     "\t\t$(date +%%s -d 2009-10-01)..$(date +%%s)\n\n";
129
130 static const char hooks_help[] =
131     "\tHooks are scripts (or arbitrary executables or symlinks to such) that\n"
132     "\tnotmuch invokes before and after certain actions. These scripts reside\n"
133     "\tin the .notmuch/hooks directory within the database directory and must\n"
134     "\thave executable permissions.\n"
135     "\n"
136     "\tThe currently available hooks are described below.\n"
137     "\n"
138     "\tpre-new\n"
139     "\t\tThis hook is invoked by the new command before scanning or\n"
140     "\t\timporting new messages into the database. If this hook exits\n"
141     "\t\twith a non-zero status, notmuch will abort further processing\n"
142     "\t\tof the new command.\n"
143     "\n"
144     "\t\tTypically this hook is used for fetching or delivering new\n"
145     "\t\tmail to be imported into the database.\n"
146     "\n"
147     "\tpost-new\n"
148     "\t\tThis hook is invoked by the new command after new messages\n"
149     "\t\thave been imported into the database and initial tags have\n"
150     "\t\tbeen applied. The hook will not be run if there have been any\n"
151     "\t\terrors during the scan or import.\n"
152     "\n"
153     "\t\tTypically this hook is used to perform additional query-based\n"
154     "\t\ttagging on the imported messages.\n\n";
155
156 static command_t commands[] = {
157     { "setup", notmuch_setup_command,
158       NULL,
159       "Interactively setup notmuch for first use.",
160       "\tThe setup command will prompt for your full name, your primary\n"
161       "\temail address, any alternate email addresses you use, and the\n"
162       "\tdirectory containing your email archives. Your answers will be\n"
163       "\twritten to a configuration file in ${NOTMUCH_CONFIG} (if set)\n"
164       "\tor ${HOME}/.notmuch-config.\n"
165       "\n"
166       "\tThis configuration file will be created with descriptive\n"
167       "\tcomments, making it easy to edit by hand later to change the\n"
168       "\tconfiguration. Or you can run \"notmuch setup\" again.\n"
169       "\n"
170       "\tInvoking notmuch with no command argument will run setup if\n"
171       "\tthe setup command has not previously been completed." },
172     { "new", notmuch_new_command,
173       "[options...]",
174       "Find and import new messages to the notmuch database.",
175       "\tScans all sub-directories of the mail directory, performing\n"
176       "\tfull-text indexing on new messages that are found. Each new\n"
177       "\tmessage will be tagged as both \"inbox\" and \"unread\".\n"
178       "\n"
179       "\tYou should run \"notmuch new\" once after first running\n"
180       "\t\"notmuch setup\" to create the initial database. The first\n"
181       "\trun may take a long time if you have a significant amount of\n"
182       "\tmail (several hundred thousand messages or more).\n"
183       "\n"
184       "\tSubsequently, you should run \"notmuch new\" whenever new mail\n"
185       "\tis delivered and you wish to incorporate it into the database.\n"
186       "\tThese subsequent runs will be much quicker than the initial run.\n"
187       "\n"
188       "\tThe new command supports hooks. See \"notmuch help hooks\" for\n"
189       "\tmore details on hooks.\n"
190       "\n"
191       "\tSupported options for new include:\n"
192       "\n"
193       "\t--no-hooks\n"
194       "\n"
195       "\t\tPrevent hooks from being run.\n"
196       "\n"
197       "\t--verbose\n"
198       "\n"
199       "\t\tVerbose operation. Shows paths of message files as\n"
200       "\t\tthey are being indexed.\n"
201       "\n"
202       "\tInvoking notmuch with no command argument will run new if\n"
203       "\tthe setup command has previously been completed, but new has\n"
204       "\tnot previously been run." },
205     { "search", notmuch_search_command,
206       "[options...] <search-terms> [...]",
207       "Search for messages matching the given search terms.",
208       "\tNote that the individual mail messages will be matched\n"
209       "\tagainst the search terms, but the results will be the\n"
210       "\tthreads (one per line) containing the matched messages.\n"
211       "\n"
212       "\tSupported options for search include:\n"
213       "\n"
214       "\t--format=(json|text)\n"
215       "\n"
216       "\t\tPresents the results in either JSON or\n"
217       "\t\tplain-text (default)\n"
218       "\n"
219       "\t--output=(summary|threads|messages|files|tags)\n"
220       "\n"
221       "\t\tsummary (default)\n"
222       "\n"
223       "\t\tOutput a summary of each thread with any message matching the\n"
224       "\t\tsearch terms. The summary includes the thread ID, date, the\n"
225       "\t\tnumber of messages in the thread (both the number matched and\n"
226       "\t\tthe total number), the authors of the thread and the subject.\n"
227       "\n"
228       "\t\tthreads\n"
229       "\n"
230       "\t\tOutput the thread IDs of all threads with any message matching\n"
231       "\t\tthe search terms, either one per line (--format=text) or as a\n"
232       "\t\tJSON array (--format=json).\n"
233       "\n"
234       "\t\tmessages\n"
235       "\n"
236       "\t\tOutput the message IDs of all messages matching the search\n"
237       "\t\tterms, either one per line (--format=text) or as a JSON array\n"
238       "\t\t(--format=json).\n"
239       "\n"
240       "\t\tfiles\n"
241       "\n"
242       "\t\tOutput the filenames of all messages matching the search\n"
243       "\t\tterms, either one per line (--format=text) or as a JSON array\n"
244       "\t\t(--format=json).\n"
245       "\n"
246       "\t\ttags\n"
247       "\n"
248       "\t\tOutput all tags that appear on any message matching the search\n"
249       "\t\tterms, either one per line (--format=text) or as a JSON array\n"
250       "\t\t(--format=json).\n"
251       "\n"
252       "\t--sort=(newest-first|oldest-first)\n"
253       "\n"
254       "\t\tPresent results in either chronological order\n"
255       "\t\t(oldest-first) or reverse chronological order\n"
256       "\t\t(newest-first), which is the default.\n"
257       "\n"
258       "\t--offset=[-]N\n"
259       "\n"
260       "\t\tSkip displaying the first N results. With the leading '-',\n"
261       "\t\tstart at the Nth result from the end.\n"
262       "\n"
263       "\t--limit=N\n"
264       "\n"
265       "\t\tLimit the number of displayed results to N.\n"
266       "\n"
267       "\tSee \"notmuch help search-terms\" for details of the search\n"
268       "\tterms syntax." },
269     { "show", notmuch_show_command,
270       "<search-terms> [...]",
271       "Show all messages matching the search terms.",
272       "\tThe messages are grouped and sorted based on the threading\n"
273       "\t(all replies to a particular message appear immediately\n"
274       "\tafter that message in date order).\n"
275       "\n"
276       "\tSupported options for show include:\n"
277       "\n"
278       "\t--entire-thread\n"
279       "\n"
280       "\t\tBy default only those messages that match the\n"
281       "\t\tsearch terms will be displayed. With this option,\n"
282       "\t\tall messages in the same thread as any matched\n"
283       "\t\tmessage will be displayed.\n"
284       "\n"
285       "\t--format=(text|json|mbox|raw)\n"
286       "\n"
287       "\t\ttext (default for messages)\n"
288       "\n"
289       "\t\tThe default plain-text format has all text-content MIME parts\n"
290       "\t\tdecoded. Various components in the output, ('message', 'header',\n"
291       "\t\t'body', 'attachment', and MIME 'part') are delimited by\n"
292       "\t\teasily-parsed markers. Each marker consists of a Control-L\n"
293       "\t\tcharacter (ASCII decimal 12), the name of the marker, and\n"
294       "\t\tthen either an opening or closing brace, '{' or '}' to\n"
295       "\t\teither open or close the component. For a multipart MIME\n"
296       "\t\tmessage, these parts will be nested.\n"
297       "\n"
298       "\t\tjson\n"
299       "\n"
300       "\t\tThe output is formatted with Javascript Object Notation\n"
301       "\t\t(JSON). This format is more robust than the text format\n"
302       "\t\tfor automated processing. The nested structure of multipart\n"
303       "\t\tMIME messages is reflected in nested JSON output. JSON\n"
304       "\t\toutput always includes all messages in a matching thread;\n"
305       "\t\tin effect '--format=json' implies '--entire-thread'\n"
306       "\n"
307       "\t\tmbox\n"
308       "\n"
309       "\t\tAll matching messages are output in the traditional, Unix\n"
310       "\t\tmbox format with each message being prefixed by a line\n"
311       "\t\tbeginning with 'From ' and a blank line separating each\n"
312       "\t\tmessage. Lines in the message content beginning with 'From '\n"
313       "\t\t(preceded by zero or more '>' characters) have an additional\n"
314       "\t\t'>' character added. This reversible escaping is termed\n"
315       "\t\t\"mboxrd\" format and described in detail here:\n"
316       "\n"
317       "\t\thttp://homepage.ntlworld.com/jonathan.deboynepollard/FGA/mail-mbox-formats.html\n"
318       "\n"
319       "\t\traw (default for a single part, see --part)\n"
320       "\n"
321       "\t\tFor a message, the original, raw content of the email\n"
322       "\t\tmessage is output. Consumers of this format should\n"
323       "\t\texpect to implement MIME decoding and similar functions.\n"
324       "\n"
325       "\t\tFor a single part (--part) the raw part content is output\n"
326       "\t\tafter performing any necessary MIME decoding.\n"
327       "\n"
328       "\t\tThe raw format must only be used with search terms matching\n"
329       "\t\tsingle message.\n"
330       "\n"
331       "\t--part=N\n"
332       "\n"
333       "\t\tOutput the single decoded MIME part N of a single message.\n"
334       "\t\tThe search terms must match only a single message.\n"
335       "\t\tMessage parts are numbered in a depth-first walk of the\n"
336       "\t\tmessage MIME structure, and are identified in the 'json' or\n"
337       "\t\t'text' output formats.\n"
338       "\n"
339       "\t--verify\n"
340       "\n"
341       "\t\tCompute and report the validity of any MIME cryptographic\n"
342       "\t\tsignatures found in the selected content (ie.\n"
343       "\t\t\"multipart/signed\" parts). Status of the signature will be\n"
344       "\t\treported (currently only supported with --format=json) and\n"
345       "\t\tthe multipart/signed part will be replaced by the signed data.\n"
346       "\n"
347       "\t--decrypt\n"
348       "\n"
349       "\t\tDecrypt any MIME encrypted parts found in the selected content\n"
350       "\t\t(ie. \"multipart/encrypted\" parts). Status of the decryption\n"
351       "\t\twill be reported (currently only supported with --format=json)\n"
352       "\t\tand the multipart/encrypted part will be replaced by the\n"
353       "\t\tdecrypted content.\n"
354       "\n"
355       "\n"
356       "\tA common use of \"notmuch show\" is to display a single\n"
357       "\tthread of email messages. For this, use a search term of\n"
358       "\t\"thread:<thread-id>\" as can be seen in the first column\n"
359       "\tof output from the \"notmuch search\" command.\n"
360       "\n"
361       "\tSee \"notmuch help search-terms\" for details of the search\n"
362       "\tterms syntax." },
363     { "count", notmuch_count_command,
364       "[options...] <search-terms> [...]",
365       "Count messages matching the search terms.",
366       "\tThe number of matching messages (or threads) is output to stdout.\n"
367       "\n"
368       "\tWith no search terms, a count of all messages (or threads) in\n"
369       "\tthe database will be displayed.\n"
370       "\n"
371       "\tSupported options for count include:\n"
372       "\n"
373       "\t--output=(messages|threads)\n"
374       "\n"
375       "\t\tmessages (default)\n"
376       "\n"
377       "\t\tOutput the number of matching messages.\n"
378       "\n"
379       "\t\tthreads\n"
380       "\n"
381       "\t\tOutput the number of matching threads.\n"
382       "\n"
383       "\tSee \"notmuch help search-terms\" for details of the search\n"
384       "\tterms syntax." },
385     { "reply", notmuch_reply_command,
386       "[options...] <search-terms> [...]",
387       "Construct a reply template for a set of messages.",
388       "\tConstructs a new message as a reply to a set of existing\n"
389       "\tmessages. The Reply-To: header (if any, otherwise From:) is\n"
390       "\tused for the To: address. The To: and Cc: headers are copied,\n"
391       "\tbut not including any of the user's configured addresses.\n"
392       "\n"
393       "\tA suitable subject is constructed. The In-Reply-to: and\n"
394       "\tReferences: headers are set appropriately, and the content\n"
395       "\tof the original messages is quoted and included in the body\n"
396       "\t(unless --format=headers-only is given).\n"
397       "\n"
398       "\tThe resulting message template is output to stdout.\n"
399       "\n"
400       "\tSupported options for reply include:\n"
401       "\n"
402       "\t--format=(default|headers-only)\n"
403       "\n"
404       "\t\tdefault:\n"
405       "\t\t\tIncludes subject and quoted message body.\n"
406       "\n"
407       "\t\theaders-only:\n"
408       "\t\t\tOnly produces In-Reply-To, References, To\n"
409       "\t\t\tCc, and Bcc headers.\n"
410       "\n"
411       "\tSee \"notmuch help search-terms\" for details of the search\n"
412       "\tterms syntax." },
413     { "tag", notmuch_tag_command,
414       "+<tag>|-<tag> [...] [--] <search-terms> [...]",
415       "Add/remove tags for all messages matching the search terms.",
416       "\tThe search terms are handled exactly as in 'search' so one\n"
417       "\tcan use that command first to see what will be modified.\n"
418       "\n"
419       "\tTags prefixed by '+' are added while those prefixed by\n"
420       "\t'-' are removed. For each message, tag removal is performed\n"
421       "\tbefore tag addition.\n"
422       "\n"
423       "\tThe beginning of <search-terms> is recognized by the first\n"
424       "\targument that begins with neither '+' nor '-'. Support for\n"
425       "\tan initial search term beginning with '+' or '-' is provided\n"
426       "\tby allowing the user to specify a \"--\" argument to separate\n"
427       "\tthe tags from the search terms.\n"
428       "\n"
429       "\tSee \"notmuch help search-terms\" for details of the search\n"
430       "\tterms syntax." },
431     { "dump", notmuch_dump_command,
432       "[<filename>] [--] [<search-terms>]",
433       "Create a plain-text dump of the tags for each message.",
434       "\tOutput is to the given filename, if any, or to stdout.\n"
435       "\tNote that using the filename argument is deprecated.\n"
436       "\n"
437       "\tThese tags are the only data in the notmuch database\n"
438       "\tthat can't be recreated from the messages themselves.\n"
439       "\tThe output of notmuch dump is therefore the only\n"
440       "\tcritical thing to backup (and much more friendly to\n"
441       "\tincremental backup than the native database files.)\n" 
442       "\n"
443       "\tWith no search terms, a dump of all messages in the\n"
444       "\tdatabase will be generated. A \"--\" argument instructs\n"
445       "\tnotmuch that the remaining arguments are search terms.\n"
446       "\n"
447       "\tSee \"notmuch help search-terms\" for the search-term syntax.\n"      
448  },
449     { "restore", notmuch_restore_command,
450       "[--accumulate] [<filename>]",
451       "Restore the tags from the given dump file (see 'dump').",
452       "\tInput is read from the given filename, if any, or from stdin.\n"
453       "\tNote: The dump file format is specifically chosen to be\n"
454       "\tcompatible with the format of files produced by sup-dump.\n"
455       "\tSo if you've previously been using sup for mail, then the\n"
456       "\t\"notmuch restore\" command provides you a way to import\n"
457       "\tall of your tags (or labels as sup calls them).\n"
458       "\tThe --accumulate switch causes the union of the existing and new\n"
459       "\ttags to be applied, instead of replacing each message's tags as\n"
460       "\tthey are read in from the dump file."},
461     { "config", notmuch_config_command,
462       "[get|set] <section>.<item> [value ...]",
463       "Get or set settings in the notmuch configuration file.",
464       "    config get <section>.<item>\n"
465       "\n"
466       "\tThe value of the specified configuration item is printed\n"
467       "\tto stdout. If the item has multiple values, each value\n"
468       "\tis separated by a newline character.\n"
469       "\n"
470       "\tAvailable configuration items include at least\n"
471       "\n"
472       "\t\tdatabase.path\n"
473       "\t\tuser.name\n"
474       "\t\tuser.primary_email\n"
475       "\t\tuser.other_email\n"
476       "\t\tnew.tags\n"
477       "\n"
478       "    config set <section>.<item> [value ...]\n"
479       "\n"
480       "\tThe specified configuration item is set to the given value.\n"
481       "\tTo specify a multiple-value item, provide each value as\n"
482       "\ta separate command-line argument.\n"
483       "\n"
484       "\tIf no values are provided, the specified configuration item\n"
485       "\twill be removed from the configuration file." },
486     { "help", notmuch_help_command,
487       "[<command>]",
488       "This message, or more detailed help for the named command.",
489       "\tExcept in this case, where there's not much more detailed\n"
490       "\thelp available." }
491 };
492
493 static void
494 usage (FILE *out)
495 {
496     command_t *command;
497     unsigned int i;
498
499     fprintf (out,
500              "Usage: notmuch --help\n"
501              "       notmuch --version\n"
502              "       notmuch <command> [args...]\n");
503     fprintf (out, "\n");
504     fprintf (out, "The available commands are as follows:\n");
505     fprintf (out, "\n");
506
507     for (i = 0; i < ARRAY_SIZE (commands); i++) {
508         command = &commands[i];
509
510         fprintf (out, "  %-11s  %s\n",
511                  command->name, command->summary);
512     }
513
514     fprintf (out, "\n");
515     fprintf (out,
516     "Use \"notmuch help <command>\" for more details on each command\n"
517     "and \"notmuch help search-terms\" for the common search-terms syntax.\n\n");
518 }
519
520 static int
521 notmuch_help_command (unused (void *ctx), int argc, char *argv[])
522 {
523     command_t *command;
524     unsigned int i;
525
526     argc--; argv++; /* Ignore "help" */
527
528     if (argc == 0) {
529         printf ("The notmuch mail system.\n\n");
530         usage (stdout);
531         return 0;
532     }
533
534     for (i = 0; i < ARRAY_SIZE (commands); i++) {
535         command = &commands[i];
536
537         if (strcmp (argv[0], command->name) == 0) {
538             printf ("Help for \"notmuch %s\":\n\n", argv[0]);
539             if (command->arguments)
540                 printf ("%s %s\n\n\t%s\n\n%s\n\n",
541                         command->name, command->arguments,
542                         command->summary, command->documentation);
543             else
544                 printf ("%s\t%s\n\n%s\n\n", command->name,
545                         command->summary, command->documentation);
546             return 0;
547         }
548     }
549
550     if (strcmp (argv[0], "search-terms") == 0) {
551         printf ("Help for <%s>\n\n", argv[0]);
552         for (i = 0; i < ARRAY_SIZE (commands); i++) {
553             command = &commands[i];
554
555             if (command->arguments &&
556                 strstr (command->arguments, "search-terms"))
557             {
558                 printf ("\t%s\t%s\n",
559                         command->name, command->arguments);
560             }
561         }
562         printf ("\n");
563         printf (search_terms_help);
564         return 0;
565     } else if (strcmp (argv[0], "hooks") == 0) {
566         printf ("Help for <%s>\n\n", argv[0]);
567         printf (hooks_help);
568         return 0;
569     }
570
571     fprintf (stderr,
572              "\nSorry, %s is not a known command. There's not much I can do to help.\n\n",
573              argv[0]);
574     return 1;
575 }
576
577 /* Handle the case of "notmuch" being invoked with no command
578  * argument. For now we just call notmuch_setup_command, but we plan
579  * to be more clever about this in the future.
580  */
581 static int
582 notmuch (void *ctx)
583 {
584     notmuch_config_t *config;
585     notmuch_bool_t is_new;
586     char *db_path;
587     struct stat st;
588
589     config = notmuch_config_open (ctx, NULL, &is_new);
590
591     /* If the user has never configured notmuch, then run
592      * notmuch_setup_command which will give a nice welcome message,
593      * and interactively guide the user through the configuration. */
594     if (is_new) {
595         notmuch_config_close (config);
596         return notmuch_setup_command (ctx, 0, NULL);
597     }
598
599     /* Notmuch is already configured, but is there a database? */
600     db_path = talloc_asprintf (ctx, "%s/%s",
601                                notmuch_config_get_database_path (config),
602                                ".notmuch");
603     if (stat (db_path, &st)) {
604         notmuch_config_close (config);
605         if (errno != ENOENT) {
606             fprintf (stderr, "Error looking for notmuch database at %s: %s\n",
607                      db_path, strerror (errno));
608             return 1;
609         }
610         printf ("Notmuch is configured, but there's not yet a database at\n\n\t%s\n\n",
611                 db_path);
612         printf ("You probably want to run \"notmuch new\" now to create that database.\n\n"
613                 "Note that the first run of \"notmuch new\" can take a very long time\n"
614                 "and that the resulting database will use roughly the same amount of\n"
615                 "storage space as the email being indexed.\n\n");
616         return 0;
617     }
618
619     printf ("Notmuch is configured and appears to have a database. Excellent!\n\n"
620             "At this point you can start exploring the functionality of notmuch by\n"
621             "using commands such as:\n\n"
622             "\tnotmuch search tag:inbox\n\n"
623             "\tnotmuch search to:\"%s\"\n\n"
624             "\tnotmuch search from:\"%s\"\n\n"
625             "\tnotmuch search subject:\"my favorite things\"\n\n"
626             "See \"notmuch help search\" for more details.\n\n"
627             "You can also use \"notmuch show\" with any of the thread IDs resulting\n"
628             "from a search. Finally, you may want to explore using a more sophisticated\n"
629             "interface to notmuch such as the emacs interface implemented in notmuch.el\n"
630             "or any other interface described at http://notmuchmail.org\n\n"
631             "And don't forget to run \"notmuch new\" whenever new mail arrives.\n\n"
632             "Have fun, and may your inbox never have much mail.\n\n",
633             notmuch_config_get_user_name (config),
634             notmuch_config_get_user_primary_email (config));
635
636     notmuch_config_close (config);
637
638     return 0;
639 }
640
641 int
642 main (int argc, char *argv[])
643 {
644     void *local;
645     command_t *command;
646     alias_t *alias;
647     unsigned int i, j;
648     const char **argv_local;
649
650     talloc_enable_null_tracking ();
651
652     local = talloc_new (NULL);
653
654     g_mime_init (0);
655     g_type_init ();
656
657     if (argc == 1)
658         return notmuch (local);
659
660     if (STRNCMP_LITERAL (argv[1], "--help") == 0)
661         return notmuch_help_command (NULL, argc - 1, &argv[1]);
662
663     if (STRNCMP_LITERAL (argv[1], "--version") == 0) {
664         printf ("notmuch " STRINGIFY(NOTMUCH_VERSION) "\n");
665         return 0;
666     }
667
668     for (i = 0; i < ARRAY_SIZE (aliases); i++) {
669         alias = &aliases[i];
670
671         if (strcmp (argv[1], alias->name) == 0)
672         {
673             int substitutions;
674
675             argv_local = talloc_size (local, sizeof (char *) *
676                                       (argc + MAX_ALIAS_SUBSTITUTIONS - 1));
677             if (argv_local == NULL) {
678                 fprintf (stderr, "Out of memory.\n");
679                 return 1;
680             }
681
682             /* Copy all substution arguments from the alias. */
683             argv_local[0] = argv[0];
684             for (j = 0; j < MAX_ALIAS_SUBSTITUTIONS; j++) {
685                 if (alias->substitutions[j] == NULL)
686                     break;
687                 argv_local[j+1] = alias->substitutions[j];
688             }
689             substitutions = j;
690
691             /* And copy all original arguments (skipping the argument
692              * that matched the alias of course. */
693             for (j = 2; j < (unsigned) argc; j++) {
694                 argv_local[substitutions+j-1] = argv[j];
695             }
696
697             argc += substitutions - 1;
698             argv = (char **) argv_local;
699         }
700     }
701
702     for (i = 0; i < ARRAY_SIZE (commands); i++) {
703         command = &commands[i];
704
705         if (strcmp (argv[1], command->name) == 0)
706             return (command->function) (local, argc - 1, &argv[1]);
707     }
708
709     fprintf (stderr, "Error: Unknown command '%s' (see \"notmuch help\")\n",
710              argv[1]);
711
712     talloc_free (local);
713
714     return 1;
715 }