]> git.notmuchmail.org Git - notmuch/blob - notmuch.c
vim: cleanup search buffer
[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 static int
36 notmuch_help_command (void *ctx, int argc, char *argv[]);
37
38 static const char search_terms_help[] =
39     "\tSeveral notmuch commands accept a comman syntax for search\n"
40     "\tterms.\n"
41     "\n"
42     "\tThe search terms can consist of free-form text (and quoted\n"
43     "\tphrases) which will match all messages that contain all of\n"
44     "\tthe given terms/phrases in the body, the subject, or any of\n"
45     "\tthe sender or recipient headers.\n"
46     "\n"
47     "\tAs a special case, a search string consisting of exactly a\n"
48     "\tsingle asterisk (\"*\") will match all messages.\n"
49     "\n"
50     "\tIn addition to free text, the following prefixes can be used\n"
51     "\tto force terms to match against specific portions of an email,\n"
52     "\t(where <brackets> indicate user-supplied values):\n"
53     "\n"
54     "\t\tfrom:<name-or-address>\n"
55     "\t\tto:<name-or-address>\n"
56     "\t\tsubject:<word-or-quoted-phrase>\n"
57     "\t\tattachment:<word>\n"
58     "\t\ttag:<tag> (or is:<tag>)\n"
59     "\t\tid:<message-id>\n"
60     "\t\tthread:<thread-id>\n"
61     "\n"
62     "\tThe from: prefix is used to match the name or address of\n"
63     "\tthe sender of an email message.\n"
64     "\n"
65     "\tThe to: prefix is used to match the names or addresses of\n"
66     "\tany recipient of an email message, (whether To, Cc, or Bcc).\n"
67     "\n"
68     "\tAny term prefixed with subject: will match only text from\n"
69     "\tthe subject of an email. Quoted phrases are supported when\n"
70     "\tsearching with: subject:\"this is a phrase\".\n"
71     "\n"
72     "\tFor tag: and is:, valid tag values include \"inbox\" and \"unread\"\n"
73     "\tby default for new messages added by \"notmuch new\" as well\n"
74     "\tas any other tag values added manually with \"notmuch tag\".\n"
75     "\n"
76     "\tFor id:, message ID values are the literal contents of the\n"
77     "\tMessage-ID: header of email messages, but without the '<','>'\n"
78     "\tdelimiters.\n"
79     "\n"
80     "\tThe thread: prefix can be used with the thread ID values that\n"
81     "\tare generated internally by notmuch (and do not appear in email\n"
82     "\tmessages). These thread ID values can be seen in the first\n"
83     "\tcolumn of output from \"notmuch search\".\n"
84     "\n"
85     "\tIn addition to individual terms, multiple terms can be\n"
86     "\tcombined with Boolean operators (\"and\", \"or\", \"not\", etc.).\n"
87     "\tEach term in the query will be implicitly connected by a\n"
88     "\tlogical AND if no explicit operator is provided, (except\n"
89     "\tthat terms with a common prefix will be implicitly combined\n"
90     "\twith OR until we get Xapian defect #402 fixed).\n"
91     "\n"
92     "\tParentheses can also be used to control the combination of\n"
93     "\tthe Boolean operators, but will have to be protected from\n"
94     "\tinterpretation by the shell, (such as by putting quotation\n"
95     "\tmarks around any parenthesized expression).\n"
96     "\n"
97     "\tFinally, results can be restricted to only messages within a\n"
98     "\tparticular time range, (based on the Date: header) with:\n"
99     "\n"
100     "\t\t<intial-timestamp>..<final-timestamp>\n"
101     "\n"
102     "\tEach timestamp is a number representing the number of seconds\n"
103     "\tsince 1970-01-01 00:00:00 UTC. This is not the most convenient\n"
104     "\tmeans of expressing date ranges, but until notmuch is fixed to\n"
105     "\taccept a more convenient form, one can use the date program to\n"
106     "\tconstruct timestamps. For example, with the bash shell the\n"
107     "\tfollowing syntax would specify a date range to return messages\n"
108     "\tfrom 2009-10-01 until the current time:\n"
109     "\n"
110     "\t\t$(date +%%s -d 2009-10-01)..$(date +%%s)\n\n";
111
112 command_t commands[] = {
113     { "setup", notmuch_setup_command,
114       NULL,
115       "Interactively setup notmuch for first use.",
116       "\tThe setup command will prompt for your full name, your primary\n"
117       "\temail address, any alternate email addresses you use, and the\n"
118       "\tdirectory containing your email archives. Your answers will be\n"
119       "\twritten to a configuration file in ${NOTMUCH_CONFIG} (if set)\n"
120       "\tor ${HOME}/.notmuch-config.\n"
121       "\n"
122       "\tThis configuration file will be created with descriptive\n"
123       "\tcomments, making it easy to edit by hand later to change the\n"
124       "\tconfiguration. Or you can run \"notmuch setup\" again.\n"
125       "\n"
126       "\tInvoking notmuch with no command argument will run setup if\n"
127       "\tthe setup command has not previously been completed." },
128     { "new", notmuch_new_command,
129       "[--verbose]",
130       "Find and import new messages to the notmuch database.",
131       "\tScans all sub-directories of the mail directory, performing\n"
132       "\tfull-text indexing on new messages that are found. Each new\n"
133       "\tmessage will be tagged as both \"inbox\" and \"unread\".\n"
134       "\n"
135       "\tYou should run \"notmuch new\" once after first running\n"
136       "\t\"notmuch setup\" to create the initial database. The first\n"
137       "\trun may take a long time if you have a significant amount of\n"
138       "\tmail (several hundred thousand messages or more).\n"
139       "\n"
140       "\tSubsequently, you should run \"notmuch new\" whenever new mail\n"
141       "\tis delivered and you wish to incorporate it into the database.\n"
142       "\tThese subsequent runs will be much quicker than the initial run.\n"
143       "\n"
144       "\tSupported options for new include:\n"
145       "\n"
146       "\t--verbose\n"
147       "\n"
148       "\t\tVerbose operation. Shows paths of message files as\n"
149       "\t\tthey are being indexed.\n"
150       "\n"
151       "\tInvoking notmuch with no command argument will run new if\n"
152       "\tthe setup command has previously been completed, but new has\n"
153       "\tnot previously been run." },
154     { "search", notmuch_search_command,
155       "[options...] <search-terms> [...]",
156       "Search for messages matching the given search terms.",
157       "\tNote that the individual mail messages will be matched\n"
158       "\tagainst the search terms, but the results will be the\n"
159       "\tthreads (one per line) containing the matched messages.\n"
160       "\n"
161       "\tSupported options for search include:\n"
162       "\n"
163       "\t--format=(json|text)\n"
164       "\n"
165       "\t\tPresents the results in either JSON or\n"
166       "\t\tplain-text (default)\n"
167       "\n"
168       "\t--output=(summary|threads|messages|files|tags)\n"
169       "\n"
170       "\t\tsummary (default)\n"
171       "\n"
172       "\t\tOutput a summary of each thread with any message matching the\n"
173       "\t\tsearch terms. The summary includes the thread ID, date, the\n"
174       "\t\tnumber of messages in the thread (both the number matched and\n"
175       "\t\tthe total number), the authors of the thread and the subject.\n"
176       "\n"
177       "\t\tthreads\n"
178       "\n"
179       "\t\tOutput the thread IDs of all threads with any message matching\n"
180       "\t\tthe search terms, either one per line (--format=text) or as a\n"
181       "\t\tJSON array (--format=json).\n"
182       "\n"
183       "\t\tmessages\n"
184       "\n"
185       "\t\tOutput the message IDs of all messages matching the search\n"
186       "\t\tterms, either one per line (--format=text) or as a JSON array\n"
187       "\t\t(--format=json).\n"
188       "\n"
189       "\t\tfiles\n"
190       "\n"
191       "\t\tOutput the filenames of all messages matching the search\n"
192       "\t\tterms, either one per line (--format=text) or as a JSON array\n"
193       "\t\t(--format=json).\n"
194       "\n"
195       "\t\ttags\n"
196       "\n"
197       "\t\tOutput all tags that appear on any message matching the search\n"
198       "\t\tterms, either one per line (--format=text) or as a JSON array\n"
199       "\t\t(--format=json).\n"
200       "\n"
201       "\t--sort=(newest-first|oldest-first)\n"
202       "\n"
203       "\t\tPresent results in either chronological order\n"
204       "\t\t(oldest-first) or reverse chronological order\n"
205       "\t\t(newest-first), which is the default.\n"
206       "\n"
207       "\tSee \"notmuch help search-terms\" for details of the search\n"
208       "\tterms syntax." },
209     { "show", notmuch_show_command,
210       "<search-terms> [...]",
211       "Show all messages matching the search terms.",
212       "\tThe messages are grouped and sorted based on the threading\n"
213       "\t(all replies to a particular message appear immediately\n"
214       "\tafter that message in date order).\n"
215       "\n"
216       "\tSupported options for show include:\n"
217       "\n"
218       "\t--entire-thread\n"
219       "\n"
220       "\t\tBy default only those messages that match the\n"
221       "\t\tsearch terms will be displayed. With this option,\n"
222       "\t\tall messages in the same thread as any matched\n"
223       "\t\tmessage will be displayed.\n"
224       "\n"
225       "\t--format=(text|json|mbox|raw)\n"
226       "\n"
227       "\t\ttext (default)\n"
228       "\n"
229       "\t\tThe default plain-text format has all text-content MIME parts\n"
230       "\t\tdecoded. Various components in the output, ('message', 'header',\n"
231       "\t\t'body', 'attachment', and MIME 'part') are delimited by\n"
232       "\t\teasily-parsed markers. Each marker consists of a Control-L\n"
233       "\t\tcharacter (ASCII decimal 12), the name of the marker, and\n"
234       "\t\tthen either an opening or closing brace, '{' or '}' to\n"
235       "\t\teither open or close the component.\n"
236       "\n"
237       "\t\tjson\n"
238       "\n"
239       "\t\tThe output is formatted with Javascript Object Notation\n"
240       "\t\t(JSON). This format is more robust than the text format\n"
241       "\t\tfor automated processing. JSON output always includes all\n"
242       "\t\tmessages in a matching thread; in effect '--format=json'\n"
243       "\t\timplies '--entire-thread'\n"
244       "\n"
245       "\t\tmbox\n"
246       "\n"
247       "\t\tAll matching messages are output in the traditional, Unix\n"
248       "\t\tmbox format with each message being prefixed by a line\n"
249       "\t\tbeginning with 'From ' and a blank line separating each\n"
250       "\t\tmessage. Lines in the message content beginning with 'From '\n"
251       "\t\t(preceded by zero or more '>' characters) have an additional\n"
252       "\t\t'>' character added. This reversible escaping is termed\n"
253       "\t\t\"mboxrd\" format and described in detail here:\n"
254       "\n"
255       "\t\thttp://homepage.ntlworld.com/jonathan.deboynepollard/FGA/mail-mbox-formats.html\n"
256       "\n"
257       "\t\traw\n"
258       "\n"
259       "\t\tThe original, raw content of the email message is displayed.\n"
260       "\t\tConsumers of this format should expect to implement MIME\n"
261       "\t\tdecoding and similar functions. This format must only\n"
262       "\t\tbe used with search terms matching a single message.\n"
263       "\n"
264       "\tA common use of \"notmuch show\" is to display a single\n"
265       "\tthread of email messages. For this, use a search term of\n"
266       "\t\"thread:<thread-id>\" as can be seen in the first column\n"
267       "\tof output from the \"notmuch search\" command.\n"
268       "\n"
269       "\tSee \"notmuch help search-terms\" for details of the search\n"
270       "\tterms syntax." },
271     { "count", notmuch_count_command,
272       "<search-terms> [...]",
273       "Count messages matching the search terms.",
274       "\tThe number of matching messages is output to stdout.\n"
275       "\n"
276       "\tWith no search terms, a count of all messages in the database\n"
277       "\twill be displayed.\n"
278       "\n"
279       "\tSee \"notmuch help search-terms\" for details of the search\n"
280       "\tterms syntax." },
281     { "reply", notmuch_reply_command,
282       "[options...] <search-terms> [...]",
283       "Construct a reply template for a set of messages.",
284       "\tConstructs a new message as a reply to a set of existing\n"
285       "\tmessages. The Reply-To: header (if any, otherwise From:) is\n"
286       "\tused for the To: address. The To: and Cc: headers are copied,\n"
287       "\tbut not including any of the user's configured addresses.\n"
288       "\n"
289       "\tA suitable subject is constructed. The In-Reply-to: and\n"
290       "\tReferences: headers are set appropriately, and the content\n"
291       "\tof the original messages is quoted and included in the body\n"
292       "\t(unless --format=headers-only is given).\n"
293       "\n"
294       "\tThe resulting message template is output to stdout.\n"
295       "\n"
296       "\tSupported options for reply include:\n"
297       "\n"
298       "\t--format=(default|headers-only)\n"
299       "\n"
300       "\t\tdefault:\n"
301       "\t\t\tIncludes subject and quoted message body.\n"
302       "\n"
303       "\t\theaders-only:\n"
304       "\t\t\tOnly produces In-Reply-To, References, To\n"
305       "\t\t\tCc, and Bcc headers.\n"
306       "\n"
307       "\tSee \"notmuch help search-terms\" for details of the search\n"
308       "\tterms syntax." },
309     { "tag", notmuch_tag_command,
310       "+<tag>|-<tag> [...] [--] <search-terms> [...]",
311       "Add/remove tags for all messages matching the search terms.",
312       "\tThe search terms are handled exactly as in 'search' so one\n"
313       "\tcan use that command first to see what will be modified.\n"
314       "\n"
315       "\tTags prefixed by '+' are added while those prefixed by\n"
316       "\t'-' are removed. For each message, tag removal is performed\n"
317       "\tbefore tag addition.\n"
318       "\n"
319       "\tThe beginning of <search-terms> is recognized by the first\n"
320       "\targument that begins with neither '+' nor '-'. Support for\n"
321       "\tan initial search term beginning with '+' or '-' is provided\n"
322       "\tby allowing the user to specify a \"--\" argument to separate\n"
323       "\tthe tags from the search terms.\n"
324       "\n"
325       "\tSee \"notmuch help search-terms\" for details of the search\n"
326       "\tterms syntax." },
327     { "dump", notmuch_dump_command,
328       "[<filename>]",
329       "Create a plain-text dump of the tags for each message.",
330       "\tOutput is to the given filename, if any, or to stdout.\n"
331       "\tThese tags are the only data in the notmuch database\n"
332       "\tthat can't be recreated from the messages themselves.\n"
333       "\tThe output of notmuch dump is therefore the only\n"
334       "\tcritical thing to backup (and much more friendly to\n"
335       "\tincremental backup than the native database files.)" },
336     { "restore", notmuch_restore_command,
337       "<filename>",
338       "Restore the tags from the given dump file (see 'dump').",
339       "\tNote: The dump file format is specifically chosen to be\n"
340       "\tcompatible with the format of files produced by sup-dump.\n"
341       "\tSo if you've previously been using sup for mail, then the\n"
342       "\t\"notmuch restore\" command provides you a way to import\n"
343       "\tall of your tags (or labels as sup calls them)." },
344     { "search-tags", notmuch_search_tags_command,
345       "[<search-terms> [...] ]",
346       "List all tags found in the database or matching messages.",
347       "\tRun this command without any search-term(s) to obtain a list\n"
348       "\tof all tags found in the database. If you provide one or more\n"
349       "\tsearch-terms as argument(s) then the resulting list will\n"
350       "\tcontain tags only from messages that match the search-term(s).\n"
351       "\n"
352       "\tIn both cases the list will be alphabetically sorted." },
353     { "part", notmuch_part_command,
354       "--part=<num> <search-terms>",
355       "Output a single MIME part of a message.",
356       "\tA single decoded MIME part, with no encoding or framing,\n"
357       "\tis output to stdout. The search terms must match only a single\n"
358       "\tmessage, otherwise this command will fail.\n"
359       "\n"
360       "\tThe part number should match the part \"id\" field output\n"
361       "\tby the \"--format=json\" option of \"notmuch show\". If the\n"
362       "\tmessage specified by the search terms does not include a\n"
363       "\tpart with the specified \"id\" there will be no output." },
364     { "config", notmuch_config_command,
365       "[get|set] <section>.<item> [value ...]",
366       "Get or set settings in the notmuch configuration file.",
367       "    config get <section>.<item>\n"
368       "\n"
369       "\tThe value of the specified configuration item is printed\n"
370       "\tto stdout. If the item has multiple values, each value\n"
371       "\tis separated by a newline character.\n"
372       "\n"
373       "\tAvailable configuration items include at least\n"
374       "\n"
375       "\t\tdatabase.path\n"
376       "\t\tuser.name\n"
377       "\t\tuser.primary_email\n"
378       "\t\tuser.other_email\n"
379       "\t\tnew.tags\n"
380       "\n"
381       "    config set <section>.<item> [value ...]\n"
382       "\n"
383       "\tThe specified configuration item is set to the given value.\n"
384       "\tTo specify a multiple-value item, provide each value as\n"
385       "\ta separate command-line argument.\n"
386       "\n"
387       "\tIf no values are provided, the specified configuration item\n"
388       "\twill be removed from the configuration file." },
389     { "help", notmuch_help_command,
390       "[<command>]",
391       "This message, or more detailed help for the named command.",
392       "\tExcept in this case, where there's not much more detailed\n"
393       "\thelp available." }
394 };
395
396 static void
397 usage (FILE *out)
398 {
399     command_t *command;
400     unsigned int i;
401
402     fprintf (out,
403              "Usage: notmuch --help\n"
404              "       notmuch --version\n"
405              "       notmuch <command> [args...]\n");
406     fprintf (out, "\n");
407     fprintf (out, "The available commands are as follows:\n");
408     fprintf (out, "\n");
409
410     for (i = 0; i < ARRAY_SIZE (commands); i++) {
411         command = &commands[i];
412
413         fprintf (out, "  %-11s  %s\n",
414                  command->name, command->summary);
415     }
416
417     fprintf (out, "\n");
418     fprintf (out,
419     "Use \"notmuch help <command>\" for more details on each command\n"
420     "and \"notmuch help search-terms\" for the common search-terms syntax.\n\n");
421 }
422
423 static int
424 notmuch_help_command (unused (void *ctx), int argc, char *argv[])
425 {
426     command_t *command;
427     unsigned int i;
428
429     if (argc == 0) {
430         printf ("The notmuch mail system.\n\n");
431         usage (stdout);
432         return 0;
433     }
434
435     for (i = 0; i < ARRAY_SIZE (commands); i++) {
436         command = &commands[i];
437
438         if (strcmp (argv[0], command->name) == 0) {
439             printf ("Help for \"notmuch %s\":\n\n", argv[0]);
440             if (command->arguments)
441                 printf ("%s %s\n\n\t%s\n\n%s\n\n",
442                         command->name, command->arguments,
443                         command->summary, command->documentation);
444             else
445                 printf ("%s\t%s\n\n%s\n\n", command->name,
446                         command->summary, command->documentation);
447             return 0;
448         }
449     }
450
451     if (strcmp (argv[0], "search-terms") == 0) {
452         printf ("Help for <%s>\n\n", argv[0]);
453         for (i = 0; i < ARRAY_SIZE (commands); i++) {
454             command = &commands[i];
455
456             if (command->arguments &&
457                 strstr (command->arguments, "search-terms"))
458             {
459                 printf ("\t%s\t%s\n",
460                         command->name, command->arguments);
461             }
462         }
463         printf ("\n");
464         printf (search_terms_help);
465         return 0;
466     }
467
468     fprintf (stderr,
469              "\nSorry, %s is not a known command. There's not much I can do to help.\n\n",
470              argv[0]);
471     return 1;
472 }
473
474 /* Handle the case of "notmuch" being invoked with no command
475  * argument. For now we just call notmuch_setup_command, but we plan
476  * to be more clever about this in the future.
477  */
478 static int
479 notmuch (void *ctx)
480 {
481     notmuch_config_t *config;
482     notmuch_bool_t is_new;
483     char *db_path;
484     struct stat st;
485
486     config = notmuch_config_open (ctx, NULL, &is_new);
487
488     /* If the user has never configured notmuch, then run
489      * notmuch_setup_command which will give a nice welcome message,
490      * and interactively guide the user through the configuration. */
491     if (is_new) {
492         notmuch_config_close (config);
493         return notmuch_setup_command (ctx, 0, NULL);
494     }
495
496     /* Notmuch is already configured, but is there a database? */
497     db_path = talloc_asprintf (ctx, "%s/%s",
498                                notmuch_config_get_database_path (config),
499                                ".notmuch");
500     if (stat (db_path, &st)) {
501         notmuch_config_close (config);
502         if (errno != ENOENT) {
503             fprintf (stderr, "Error looking for notmuch database at %s: %s\n",
504                      db_path, strerror (errno));
505             return 1;
506         }
507         printf ("Notmuch is configured, but there's not yet a database at\n\n\t%s\n\n",
508                 db_path);
509         printf ("You probably want to run \"notmuch new\" now to create that database.\n\n"
510                 "Note that the first run of \"notmuch new\" can take a very long time\n"
511                 "and that the resulting database will use roughly the same amount of\n"
512                 "storage space as the email being indexed.\n\n");
513         return 0;
514     }
515
516     printf ("Notmuch is configured and appears to have a database. Excellent!\n\n"
517             "At this point you can start exploring the functionality of notmuch by\n"
518             "using commands such as:\n\n"
519             "\tnotmuch search tag:inbox\n\n"
520             "\tnotmuch search to:\"%s\"\n\n"
521             "\tnotmuch search from:\"%s\"\n\n"
522             "\tnotmuch search subject:\"my favorite things\"\n\n"
523             "See \"notmuch help search\" for more details.\n\n"
524             "You can also use \"notmuch show\" with any of the thread IDs resulting\n"
525             "from a search. Finally, you may want to explore using a more sophisticated\n"
526             "interface to notmuch such as the emacs interface implemented in notmuch.el\n"
527             "or any other interface described at http://notmuchmail.org\n\n"
528             "And don't forget to run \"notmuch new\" whenever new mail arrives.\n\n"
529             "Have fun, and may your inbox never have much mail.\n\n",
530             notmuch_config_get_user_name (config),
531             notmuch_config_get_user_primary_email (config));
532
533     notmuch_config_close (config);
534
535     return 0;
536 }
537
538 int
539 main (int argc, char *argv[])
540 {
541     void *local;
542     command_t *command;
543     unsigned int i;
544
545     local = talloc_new (NULL);
546
547     g_mime_init (0);
548
549     if (argc == 1)
550         return notmuch (local);
551
552     if (STRNCMP_LITERAL (argv[1], "--help") == 0)
553         return notmuch_help_command (NULL, 0, NULL);
554
555     if (STRNCMP_LITERAL (argv[1], "--version") == 0) {
556         printf ("notmuch " STRINGIFY(NOTMUCH_VERSION) "\n");
557         return 0;
558     }
559
560     for (i = 0; i < ARRAY_SIZE (commands); i++) {
561         command = &commands[i];
562
563         if (strcmp (argv[1], command->name) == 0)
564             return (command->function) (local, argc - 2, &argv[2]);
565     }
566
567     fprintf (stderr, "Error: Unknown command '%s' (see \"notmuch help\")\n",
568              argv[1]);
569
570     talloc_free (local);
571
572     return 1;
573 }