fix regression in mutt_is_application_pgp \o/
[apps/madmutt.git] / muttlib.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #include <lib-lib/lib-lib.h>
12
13 #include <grp.h>
14 #include <pwd.h>
15 #include <utime.h>
16
17 #include <lib-mime/mime.h>
18 #include <lib-ui/curses.h>
19 #include <lib-ui/enter.h>
20 #include <lib-sys/unix.h>
21 #include <lib-mx/mx.h>
22
23 #include "alias.h"
24 #include "mutt.h"
25 #include "attach.h"
26
27 #include "version.h"
28
29 #include <imap/imap.h>
30
31 #include <lib-crypt/crypt.h>
32
33 #define SW              (option(OPTMBOXPANE)?SidebarWidth:0)
34
35 /* Modified by blong to accept a "suggestion" for file name.  If
36  * that file exists, then construct one with unique name but 
37  * keep any extension.  This might fail, I guess.
38  * Renamed to mutt_adv_mktemp so I only have to change where it's
39  * called, and not all possible cases.
40  */
41 void mutt_adv_mktemp (const char* dir, char *s, ssize_t l)
42 {
43   char buf[_POSIX_PATH_MAX];
44   char tmp[_POSIX_PATH_MAX];
45   char *period;
46   ssize_t sl;
47   struct stat sb;
48
49   m_strcpy(buf, sizeof(buf), m_strisempty(dir) ? NONULL(Tempdir) : dir);
50   mutt_expand_path (buf, sizeof (buf));
51   if (s[0] == '\0') {
52     snprintf (s, l, "%s/muttXXXXXX", buf);
53     mktemp (s);
54   }
55   else {
56     m_strcpy(tmp, sizeof(tmp), s);
57     mutt_sanitize_filename (tmp, 1);
58     snprintf (s, l, "%s/%s", buf, tmp);
59     if (lstat (s, &sb) == -1 && errno == ENOENT)
60       return;
61     if ((period = strrchr (tmp, '.')) != NULL)
62       *period = 0;
63     snprintf (s, l, "%s/%s.XXXXXX", buf, tmp);
64     mktemp (s);
65     if (period != NULL) {
66       *period = '.';
67       sl = m_strlen(s);
68       m_strcpy(s + sl, l - sl, period);
69     }
70   }
71 }
72
73 /* returns true if the header contained in "s" is in list "t" */
74 int mutt_matches_ignore (const char *s, string_list_t * t)
75 {
76   for (; t; t = t->next) {
77     if (!ascii_strncasecmp (s, t->data, m_strlen(t->data))
78         || *t->data == '*')
79       return 1;
80   }
81   return 0;
82 }
83
84 ssize_t _mutt_expand_path(char *s, ssize_t slen, int rx)
85 {
86     char p[_POSIX_PATH_MAX] = "";
87     char tmp[_POSIX_PATH_MAX];
88     const char *tail = "";
89
90     do {
91         const address_t *alias;
92
93         switch (*s) {
94           case '~':
95             if (s[1] == '/' || s[1] == '\0') {
96                 m_strcpy(p, sizeof(p), Homedir);
97                 tail = s + 1;
98             } else {
99                 struct passwd *pw;
100                 tail = m_strchrnul(s + 1, '/');
101
102                 m_strncpy(tmp, sizeof(tmp), s + 1, tail - s - 1);
103
104                 if ((pw = getpwnam(tmp))) {
105                     m_strcpy(p, sizeof(p), pw->pw_dir);
106                 } else {
107                     /* user not found! */
108                     tail = s;
109                 }
110             }
111             break;
112
113           case '=':
114           case '+':
115             /* if folder = imap[s]://host/: don't append slash */
116             if (imap_is_magic(NONULL(Maildir), NULL) == M_IMAP
117             &&  Maildir[m_strlen(Maildir) - 1] == '/') {
118                 m_strcpy(p, sizeof(p), Maildir);
119             } else {
120                 snprintf(p, sizeof(p), "%s/", NONULL(Maildir));
121             }
122
123             tail = s + 1;
124             break;
125
126             /* elm compatibility, @ expands alias to user name */
127
128           case '@':
129             if ((alias = alias_lookup(s + 1))) {
130                 HEADER h;
131                 header_init(&h);
132                 h.env = envelope_new();
133                 h.env->from = h.env->to = (address_t *)alias;
134                 mutt_default_save(p, sizeof (p), &h);
135                 h.env->from = h.env->to = NULL;
136                 header_wipe(&h);
137
138                 if (*p != '@') {
139                     /* recurse iff the result do not starts with '@' */
140                     m_strcpy(s, slen, p);
141                     continue;
142                 }
143             }
144             break;
145
146           case '>':
147             m_strcpy(p, sizeof(p), Inbox);
148             tail = s + 1;
149             break;
150
151           case '<':
152             m_strcpy(p, sizeof(p), Outbox);
153             tail = s + 1;
154             break;
155
156           case '!':
157             if (s[1] == '!') {
158                 m_strcpy(p, sizeof(p), LastFolder);
159                 tail = s + 2;
160             } else {
161                 m_strcpy(p, sizeof(p), Spoolfile);
162                 tail = s + 1;
163             }
164             break;
165
166           case '-':
167             m_strcpy(p, sizeof(p), NONULL(LastFolder));
168             tail = s + 1;
169             break;
170
171           case '^':
172             m_strcpy(p, sizeof(p), NONULL(CurrentFolder));
173             tail = s + 1;
174             break;
175
176           default:
177             *p = '\0';
178             tail = s;
179         }
180     } while (0);
181
182     if (rx) {
183         char q[_POSIX_PATH_MAX];
184         rx_sanitize_string(q, sizeof(q), p);
185         snprintf(tmp, sizeof(tmp), "%s%s", q, tail);
186     } else {
187         snprintf(tmp, sizeof(tmp), "%s%s", p, tail);
188     }
189
190     return m_strcpy(s, slen, tmp);
191 }
192
193 void mutt_mktemp (char *s)
194 {
195
196   snprintf (s, _POSIX_PATH_MAX, "%s/madmutt-%s-%d-%d-%d-%x%x", NONULL (Tempdir),
197             NONULL (Hostname), (int) getuid (), (int) getpid (), Counter++, 
198             (unsigned int) rand(), (unsigned int) rand());
199   unlink (s);
200 }
201
202 /* collapse the pathname using ~ or = when possible */
203 void mutt_pretty_mailbox (char *s)
204 {
205   char *p = s, *q = s;
206   ssize_t len;
207   url_scheme_t scheme;
208
209   scheme = url_check_scheme (s);
210
211   if (scheme == U_IMAP || scheme == U_IMAPS) {
212     imap_pretty_mailbox (s);
213     return;
214   }
215
216   /* if s is an url, only collapse path component */
217   if (scheme != U_UNKNOWN) {
218     p = strchr (s, ':') + 1;
219     if (!strncmp (p, "//", 2))
220       q = strchr (p + 2, '/');
221     if (!q)
222       q = strchr (p, '\0');
223     p = q;
224   }
225
226   /* first attempt to collapse the pathname */
227   while (*p) {
228     if (*p == '/' && p[1] == '/') {
229       *q++ = '/';
230       p += 2;
231     }
232     else if (p[0] == '/' && p[1] == '.' && p[2] == '/') {
233       *q++ = '/';
234       p += 3;
235     }
236     else
237       *q++ = *p++;
238   }
239   *q = 0;
240
241   if (m_strncmp(s, Maildir, (len = m_strlen(Maildir))) == 0 &&
242       s[len] == '/') {
243     *s++ = '=';
244     memmove (s, s + len, m_strlen(s + len) + 1);
245   }
246   else if (m_strncmp(s, Homedir, (len = m_strlen(Homedir))) == 0 &&
247            s[len] == '/') {
248     *s++ = '~';
249     memmove (s, s + len - 1, m_strlen(s + len - 1) + 1);
250   }
251 }
252
253 void
254 mutt_expand_file_fmt(char *dst, ssize_t n, const char *fmt, const char *src)
255 {
256     char tmp[LONG_STRING];
257     mutt_quote_filename(tmp, sizeof(tmp), src);
258     m_snsubst(dst, n, fmt, tmp);
259 }
260
261 /* return 0 on success, -1 on abort, 1 on error */
262 int mutt_check_overwrite (const char *attname, const char *path,
263                           char *fname, ssize_t flen, int *append,
264                           char **directory)
265 {
266   int rc = 0;
267   char tmp[_POSIX_PATH_MAX];
268   struct stat st;
269
270   m_strcpy(fname, flen, path);
271   if (access (fname, F_OK) != 0)
272     return 0;
273   if (stat (fname, &st) != 0)
274     return -1;
275   if (S_ISDIR (st.st_mode)) {
276     if (directory) {
277       switch (mutt_multi_choice
278               (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"),
279                _("yna"))) {
280       case 3:                  /* all */
281         m_strreplace(directory, fname);
282         break;
283       case 1:                  /* yes */
284         p_delete(directory);
285         break;
286       case -1:                 /* abort */
287         p_delete(directory);
288         return -1;
289       case 2:                  /* no */
290         p_delete(directory);
291         return 1;
292       }
293     }
294     else
295       if ((rc = mutt_yesorno(_("File is a directory, save under it?"),
296                              M_YES)) != M_YES)
297       return (rc == M_NO) ? 1 : -1;
298
299     if (!attname || !attname[0]) {
300       tmp[0] = 0;
301       if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
302                           M_FILE | M_CLEAR) != 0 || !tmp[0])
303         return (-1);
304       mutt_concat_path(fname, flen, path, tmp);
305     }
306     else
307       mutt_concat_path(fname, flen, path, mutt_basename(attname));
308   }
309
310   if (*append == 0 && access (fname, F_OK) == 0) {
311     switch (mutt_multi_choice
312             (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
313     {
314     case -1:                   /* abort */
315       return -1;
316     case 3:                    /* cancel */
317       return 1;
318
319     case 2:                    /* append */
320       *append = M_SAVE_APPEND;
321       break;
322     case 1:                    /* overwrite */
323       *append = M_SAVE_OVERWRITE;
324       break;
325     }
326   }
327   return 0;
328 }
329
330 void mutt_save_path(char *d, ssize_t dsize, address_t *a)
331 {
332     if (a && a->mailbox) {
333         m_strcpy(d, dsize, a->mailbox);
334
335         if (!option(OPTSAVEADDRESS)) {
336             char *p = strpbrk(d, "%@");
337             if (p)
338                 *p = '\0';
339         }
340         m_strtolower(d);
341     } else {
342         *d = '\0';
343     }
344 }
345
346 void mutt_safe_path(char *s, ssize_t l, address_t *a)
347 {
348     mutt_save_path(s, l, a);
349
350     while (*s) {
351         if (*s == '/' || ISSPACE(*s) || !isprint((unsigned char)*s))
352             *s = '_';
353         s++;
354     }
355 }
356
357 void mutt_FormatString (char *dest,     /* output buffer */
358                         ssize_t destlen, /* output buffer len */
359                         const char *src,        /* template string */
360                         format_t * callback,    /* callback for processing */
361                         unsigned long data,     /* callback data */
362                         format_flag flags)
363 {                               /* callback flags */
364   char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
365   char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
366   ssize_t wlen, wid, count, col, len;
367
368   prefix[0] = '\0';
369   destlen--;                    /* save room for the terminal \0 */
370   wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
371   col = wlen;
372
373   while (*src && wlen < destlen) {
374     if (*src == '%') {
375       if (*++src == '%') {
376         *wptr++ = '%';
377         wlen++;
378         col++;
379         src++;
380         continue;
381       }
382
383       if (*src == '?') {
384         flags |= M_FORMAT_OPTIONAL;
385         src++;
386       }
387       else {
388         flags &= ~M_FORMAT_OPTIONAL;
389
390         /* eat the format string */
391         cp = prefix;
392         count = 0;
393         while (count < ssizeof (prefix) &&
394                (isdigit ((unsigned char) *src) || *src == '.' || *src == '-'))
395         {
396           *cp++ = *src++;
397           count++;
398         }
399         *cp = 0;
400       }
401
402       if (!*src)
403         break;                  /* bad format */
404
405       ch = *src++;              /* save the character to switch on */
406
407       if (flags & M_FORMAT_OPTIONAL) {
408         if (*src != '?')
409           break;                /* bad format */
410         src++;
411
412         /* eat the `if' part of the string */
413         cp = ifstring;
414         count = 0;
415         while (count < ssizeof (ifstring) && *src && *src != '?'
416                && *src != '&') {
417           *cp++ = *src++;
418           count++;
419         }
420         *cp = 0;
421
422         /* eat the `else' part of the string (optional) */
423         if (*src == '&')
424           src++;                /* skip the & */
425         cp = elsestring;
426         count = 0;
427         while (count < ssizeof (elsestring) && *src && *src != '?') {
428           *cp++ = *src++;
429           count++;
430         }
431         *cp = 0;
432
433         if (!*src)
434           break;                /* bad format */
435
436         src++;                  /* move past the trailing `?' */
437       }
438
439       /* handle generic cases first */
440       if (ch == '>') {
441         /* right justify to EOL */
442         ch = *src++;            /* pad char */
443         /* calculate space left on line.  if we've already written more data
444            than will fit on the line, ignore the rest of the line */
445         if (DrawFullLine || option (OPTSTATUSONTOP))
446           count = (COLS < destlen ? COLS : destlen);
447         else
448           count = ((COLS - SW) < destlen ? (COLS - SW) : destlen);
449         if (count > col) {
450           count -= col;         /* how many columns left on this line */
451           mutt_FormatString (buf, sizeof (buf), src, callback, data, flags);
452           wid = m_strlen(buf);
453           if (count > wid) {
454             count -= wid;       /* how many chars to pad */
455             memset (wptr, ch, count);
456             wptr += count;
457             col += count;
458           }
459           if (wid + wlen > destlen)
460             len = destlen - wlen;
461           else
462             len = wid;
463           memcpy (wptr, buf, len);
464           wptr += len;
465           wlen += len;
466           col += mutt_strwidth (buf);
467         }
468         break;                  /* skip rest of input */
469       }
470       else if (ch == '|') {
471         /* pad to EOL */
472         ch = *src++;
473         if (destlen > COLS)
474           destlen = COLS;
475         if (destlen > wlen) {
476           count = destlen - wlen;
477           memset (wptr, ch, count);
478           wptr += count;
479         }
480         break;                  /* skip rest of input */
481       }
482       else {
483         short lower = 0;
484         short nodots = 0;
485
486         while (ch == '_' || ch == ':') {
487           if (ch == '_')
488             lower = 1;
489           else if (ch == ':')
490             nodots = 1;
491
492           ch = *src++;
493         }
494
495         /* use callback function to handle this case */
496         src =
497           callback (buf, sizeof (buf), ch, src, prefix, ifstring, elsestring,
498                     data, flags);
499
500         if (lower)
501           m_strtolower(buf);
502         if (nodots) {
503           char *p = buf;
504
505           for (; *p; p++)
506             if (*p == '.')
507               *p = '_';
508         }
509
510         if ((len = m_strlen(buf)) + wlen > destlen)
511           len = (destlen - wlen > 0) ? (destlen - wlen) : 0;
512
513         memcpy (wptr, buf, len);
514         wptr += len;
515         wlen += len;
516         col += mutt_strwidth (buf);
517       }
518     }
519     else if (*src == '\\') {
520       if (!*++src)
521         break;
522       switch (*src) {
523       case 'n':
524         *wptr = '\n';
525         break;
526       case 't':
527         *wptr = '\t';
528         break;
529       case 'r':
530         *wptr = '\r';
531         break;
532       case 'f':
533         *wptr = '\f';
534         break;
535       case 'v':
536         *wptr = '\v';
537         break;
538       default:
539         *wptr = *src;
540         break;
541       }
542       src++;
543       wptr++;
544       wlen++;
545       col++;
546     }
547     else {
548       unsigned int bar = strcspn(src, "%\\");
549       char *bar2 = p_dupstr(src, bar);
550
551       while (bar--) {
552         *wptr++ = *src++;
553         wlen++;
554       }
555       col += mutt_strwidth (bar2);
556       p_delete(&bar2);
557     }
558   }
559   *wptr = 0;
560 }
561
562 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
563 int mutt_save_confirm (const char *s, struct stat *st)
564 {
565   char tmp[_POSIX_PATH_MAX];
566   int ret = 0;
567   int rc;
568   int magic = 0;
569
570   magic = mx_get_magic (s);
571
572   if (magic == M_POP) {
573     mutt_error _("Can't save message to POP mailbox.");
574
575     return 1;
576   }
577
578 #ifdef USE_NNTP
579   if (magic == M_NNTP) {
580     mutt_error _("Can't save message to newsserver.");
581
582     return 0;
583   }
584 #endif
585
586   if (magic > 0 && !mx_access (s, W_OK)) {
587     if (option (OPTCONFIRMAPPEND) &&
588         (!TrashPath || (m_strcmp(s, TrashPath) != 0))) {
589       /* if we're appending to the trash, there's no point in asking */
590       snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
591       if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
592         ret = 1;
593       else if (rc == -1)
594         ret = -1;
595     }
596   }
597
598   if (stat (s, st) != -1) {
599     if (magic == -1) {
600       mutt_error (_("%s is not a mailbox!"), s);
601       return 1;
602     }
603   } else {
604     if (magic != M_IMAP)
605     {
606       st->st_mtime = 0;
607       st->st_atime = 0;
608
609       if (errno == ENOENT) {
610         if (option (OPTCONFIRMCREATE)) {
611           snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
612           if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
613             ret = 1;
614           else if (rc == -1)
615             ret = -1;
616         }
617       } else {
618         mutt_perror (s);
619         return 1;
620       }
621     }
622   }
623
624   CLEARLINE (LINES - 1);
625   return (ret);
626 }
627
628 void mutt_sleep (short s)
629 {
630     sleep(MAX(s, SleepTime));
631 }
632
633 /* Decrease a file's modification time by 1 second */
634 time_t mutt_decrease_mtime (const char *f, struct stat *st)
635 {
636   struct utimbuf utim;
637   struct stat _st;
638   time_t mtime;
639
640   if (!st) {
641     if (stat (f, &_st) == -1)
642       return -1;
643     st = &_st;
644   }
645
646   if ((mtime = st->st_mtime) == time (NULL)) {
647     mtime -= 1;
648     utim.actime = mtime;
649     utim.modtime = mtime;
650     utime (f, &utim);
651   }
652
653   return mtime;
654 }
655
656 const char *mutt_make_version (int full)
657 {
658   static char vstring[STRING];
659
660   if (full)
661     snprintf (vstring, sizeof (vstring),
662               "Madmutt/%s-r%s (based on Mutt 1.5.11)",
663               MUTT_VERSION, MUTT_REVISION);
664   else
665     snprintf (vstring, sizeof (vstring), "Madmutt/%s-%s",
666               MUTT_VERSION, MUTT_REVISION);
667   return vstring;
668 }
669
670 int mutt_match_spam_list (const char *s, rx_t * l, char *text, int x)
671 {
672   static regmatch_t *pmatch = NULL;
673   static int nmatch = 0;
674   int i, n, tlen;
675   char *p;
676
677   if (!s)
678     return 0;
679
680   tlen = 0;
681
682   for (; l; l = l->next) {
683     /* If this pattern needs more matches, expand pmatch. */
684     if (l->nmatch > nmatch) {
685       p_realloc(&pmatch, l->nmatch);
686       nmatch = l->nmatch;
687     }
688
689     /* Does this pattern match? */
690     if (regexec(l->rx, s, l->nmatch, (regmatch_t *)pmatch, (int) 0) == 0) {
691       /* Copy template into text, with substitutions. */
692       for (p = l->template; *p;) {
693         if (*p == '%') {
694           n = atoi (++p);       /* find pmatch index */
695           while (isdigit ((unsigned char) *p))
696             ++p;                /* skip subst token */
697           for (i = pmatch[n].rm_so; (i < pmatch[n].rm_eo) && (tlen < x); i++)
698             text[tlen++] = s[i];
699         }
700         else {
701           text[tlen++] = *p++;
702         }
703       }
704       text[tlen] = '\0';
705       return 1;
706     }
707   }
708
709   return 0;
710 }
711
712 /* return 1 if address lists are strictly identical */
713 static int mutt_cmp_addr (const address_t * a, const address_t * b)
714 {
715   while (a && b) {
716     if (m_strcmp(a->mailbox, b->mailbox) ||
717         m_strcmp(a->personal, b->personal))
718       return (0);
719
720     a = a->next;
721     b = b->next;
722   }
723   if (a || b)
724     return (0);
725
726   return (1);
727 }
728
729 static int mutt_cmp_list (const string_list_t * a, const string_list_t * b)
730 {
731   while (a && b) {
732     if (m_strcmp(a->data, b->data))
733       return (0);
734
735     a = a->next;
736     b = b->next;
737   }
738   if (a || b)
739     return (0);
740
741   return (1);
742 }
743
744 static int mutt_cmp_env (const ENVELOPE * e1, const ENVELOPE * e2)
745 {
746   if (e1 && e2) {
747     if (m_strcmp(e1->message_id, e2->message_id) ||
748         m_strcmp(e1->subject, e2->subject) ||
749         !mutt_cmp_list (e1->references, e2->references) ||
750         !mutt_cmp_addr (e1->from, e2->from) ||
751         !mutt_cmp_addr (e1->sender, e2->sender) ||
752         !mutt_cmp_addr (e1->reply_to, e2->reply_to) ||
753         !mutt_cmp_addr (e1->to, e2->to) ||
754         !mutt_cmp_addr (e1->cc, e2->cc) ||
755         !mutt_cmp_addr (e1->return_path, e2->return_path))
756       return (0);
757     else
758       return (1);
759   }
760   else {
761     if (e1 == NULL && e2 == NULL)
762       return (1);
763     else
764       return (0);
765   }
766 }
767
768 static int mutt_cmp_body (const BODY * b1, const BODY * b2)
769 {
770   if (b1->type != b2->type ||
771       b1->encoding != b2->encoding ||
772       m_strcmp(b1->subtype, b2->subtype) ||
773       m_strcmp(b1->description, b2->description) ||
774       !parameter_equal(b1->parameter, b2->parameter) ||
775       b1->length != b2->length)
776     return (0);
777   return (1);
778 }
779 int mutt_cmp_header (const HEADER * h1, const HEADER * h2) {
780   if (h1 && h2) {
781     if (h1->received != h2->received ||
782         h1->date_sent != h2->date_sent ||
783         h1->content->length != h2->content->length ||
784         h1->lines != h2->lines ||
785         h1->zhours != h2->zhours ||
786         h1->zminutes != h2->zminutes ||
787         h1->zoccident != h2->zoccident ||
788         h1->mime != h2->mime ||
789         !mutt_cmp_env (h1->env, h2->env) ||
790         !mutt_cmp_body (h1->content, h2->content))
791       return (0);
792     else
793       return (1);
794   }
795   else {
796     if (h1 == NULL && h2 == NULL)
797       return (1);
798     else
799       return (0);
800   }
801 }
802
803
804 int mutt_extract_token(BUFFER *dest, BUFFER *tok, int flags)
805 {
806     char ch;
807     char qc = 0;                  /* quote char */
808     char *pc;
809
810     /* reset the destination pointer to the beginning of the buffer */
811     dest->dptr = dest->data;
812
813     tok->dptr = vskipspaces(tok->dptr);
814     while ((ch = *tok->dptr)) {
815         if (!qc) {
816             if ((ISSPACE(ch) && !(flags & M_TOKEN_SPACE))
817             || (ch == '#' && !(flags & M_TOKEN_COMMENT))
818             || (ch == '=' && (flags & M_TOKEN_EQUAL))
819             || (ch == ';' && !(flags & M_TOKEN_SEMICOLON))
820             || ((flags & M_TOKEN_PATTERN) && strchr("~=!|", ch)))
821             {
822                 break;
823             }
824         }
825
826         tok->dptr++;
827
828         if (ch == qc) {
829             qc = 0;                     /* end of quote */
830         } else
831         if (!qc && (ch == '\'' || ch == '"') && !(flags & M_TOKEN_QUOTE)) {
832             qc = ch;
833         } else
834         if (ch == '\\' && qc != '\'') {
835             if (!*tok->dptr)
836                 return -1;              /* premature end of token */
837
838             switch (ch = *tok->dptr++) {
839               case 'c':
840               case 'C':
841                 if (!*tok->dptr)
842                     return -1;          /* premature end of token */
843                 mutt_buffer_addch(dest,
844                                   (ascii_toupper(*tok->dptr) - 'A' + 1) & 0x7f);
845                 tok->dptr++;
846                 break;
847               case 'r':
848                 mutt_buffer_addch(dest, '\r');
849                 break;
850               case 'n':
851                 mutt_buffer_addch(dest, '\n');
852                 break;
853               case 't':
854                 mutt_buffer_addch(dest, '\t');
855                 break;
856               case 'f':
857                 mutt_buffer_addch(dest, '\f');
858                 break;
859               case 'e':
860                 mutt_buffer_addch(dest, '\033');
861                 break;
862               default:
863                 if (isdigit((unsigned char)ch)
864                 &&  isdigit((unsigned char)*tok->dptr)
865                 &&  isdigit((unsigned char)*(tok->dptr + 1)))
866                 {
867                     mutt_buffer_addch(dest, (ch << 6) + (*tok->dptr << 3) +
868                                             *(tok->dptr + 1) - 3504);
869                     tok->dptr += 2;
870                 } else {
871                     mutt_buffer_addch(dest, ch);
872                 }
873             }
874         } else
875         if (ch == '^' && (flags & M_TOKEN_CONDENSE)) {
876             if (!*tok->dptr)
877                 return -1;              /* premature end of token */
878             ch = *tok->dptr++;
879             if (ch == '^') {
880                 mutt_buffer_addch(dest, ch);
881             } else
882             if (ch == '[') {
883                 mutt_buffer_addch(dest, '\033');
884             } else
885             if (isalpha((unsigned char)ch)) {
886                 mutt_buffer_addch(dest, ascii_toupper(ch) - 'A' + 1);
887             } else {
888                 mutt_buffer_addch(dest, '^');
889                 mutt_buffer_addch(dest, ch);
890             }
891         } else
892         if (ch == '`' && (!qc || qc == '"')) {
893             FILE *fp;
894             pid_t pid;
895             char *cmd, *ptr;
896             ssize_t expnlen;
897             BUFFER expn;
898             int line = 0;
899
900             pc = tok->dptr;
901             do {
902                 if ((pc = strpbrk(pc, "\\`"))) {
903                     /* skip any quoted chars */
904                     if (*pc == '\\')
905                         pc += 2;
906                 }
907             } while (pc && *pc != '`');
908             if (!pc) {
909                 return (-1);
910             }
911
912             cmd = p_dupstr(tok->dptr, pc - tok->dptr);
913             if ((pid = mutt_create_filter(cmd, NULL, &fp, NULL)) < 0) {
914                 p_delete(&cmd);
915                 return -1;
916             }
917             p_delete(&cmd);
918
919             tok->dptr = pc + 1;
920
921             /* read line */
922             p_clear(&expn, 1);
923             expn.data = mutt_read_line(NULL, &expn.dsize, fp, &line);
924             fclose(fp);
925             mutt_wait_filter(pid);
926
927             /* if we got output, make a new string consiting of the shell ouptput
928                plus whatever else was left on the original line */
929             /* BUT: If this is inside a quoted string, directly add output to 
930              * the token */
931             if (expn.data && qc) {
932                 mutt_buffer_addstr(dest, expn.data);
933                 p_delete(&expn.data);
934             } else
935             if (expn.data) {
936                 expnlen = m_strlen(expn.data);
937                 tok->dsize = expnlen + m_strlen(tok->dptr) + 1;
938                 ptr = xmalloc(tok->dsize);
939                 memcpy(ptr, expn.data, expnlen);
940                 strcpy(ptr + expnlen, tok->dptr);      /* __STRCPY_CHECKED__ */
941                 if (tok->destroy)
942                     p_delete(&tok->data);
943                 tok->data = ptr;
944                 tok->dptr = ptr;
945                 tok->destroy = 1;       /* mark that the caller should destroy this data */
946                 ptr = NULL;
947                 p_delete(&expn.data);
948             }
949         } else
950         if (ch == '$' && (!qc || qc == '"')
951         && (*tok->dptr == '{' || isalpha((unsigned char)*tok->dptr)))
952         {
953             char *env = NULL, *var = NULL;
954
955             if (*tok->dptr == '{') {
956                 tok->dptr++;
957                 if ((pc = strchr (tok->dptr, '}'))) {
958                     var = p_dupstr(tok->dptr, pc - tok->dptr);
959                     tok->dptr = pc + 1;
960                 }
961             } else {
962                 for (pc = tok->dptr; isalnum((unsigned char)*pc) || *pc == '_';
963                      pc++);
964                 var = p_dupstr(tok->dptr, pc - tok->dptr);
965                 tok->dptr = pc;
966             }
967             if (var) {
968                 char tmp[STRING];
969                 if ((env = getenv (var))
970                 || (mutt_option_value (var, tmp, sizeof (tmp)) && (env = tmp)))
971                 {
972                     mutt_buffer_addstr (dest, env);
973                 }
974             }
975             p_delete(&var);
976         } else {
977             mutt_buffer_addch(dest, ch);
978         }
979     }
980     mutt_buffer_addch(dest, 0);  /* terminate the string */
981     tok->dptr = vskipspaces(tok->dptr);
982     return 0;
983 }