move history in lib-ui
[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 #if HAVE_CONFIG_H
12 # include "config.h"
13 #endif
14
15 #include <string.h>
16 #include <ctype.h>
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <sys/wait.h>
20 #include <errno.h>
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 #include <time.h>
24 #include <sys/types.h>
25 #include <utime.h>
26
27 #include <lib-lib/mem.h>
28 #include <lib-lib/ascii.h>
29 #include <lib-lib/str.h>
30 #include <lib-lib/macros.h>
31 #include <lib-lib/buffer.h>
32 #include <lib-lib/file.h>
33 #include <lib-lib/debug.h>
34
35 #include <lib-mime/mime.h>
36
37 #include <lib-ui/curses.h>
38 #include <lib-ui/enter.h>
39
40 #include "mutt.h"
41 #include "mx.h"
42 #include "url.h"
43 #include "attach.h"
44
45 #include "version.h"
46
47 #include <imap/imap.h>
48 #include <imap/mx_imap.h>
49
50 #include <lib-crypt/crypt.h>
51
52 #define SW              (option(OPTMBOXPANE)?SidebarWidth:0)
53
54 BODY *mutt_new_body (void)
55 {
56   BODY *p = p_new(BODY, 1);
57
58   p->disposition = DISPATTACH;
59   p->use_disp = 1;
60   return (p);
61 }
62
63
64 /* Modified by blong to accept a "suggestion" for file name.  If
65  * that file exists, then construct one with unique name but 
66  * keep any extension.  This might fail, I guess.
67  * Renamed to mutt_adv_mktemp so I only have to change where it's
68  * called, and not all possible cases.
69  */
70 void mutt_adv_mktemp (const char* dir, char *s, size_t l)
71 {
72   char buf[_POSIX_PATH_MAX];
73   char tmp[_POSIX_PATH_MAX];
74   char *period;
75   size_t sl;
76   struct stat sb;
77
78   m_strcpy(buf, sizeof(buf), m_strisempty(dir) ? NONULL(Tempdir) : dir);
79   mutt_expand_path (buf, sizeof (buf));
80   if (s[0] == '\0') {
81     snprintf (s, l, "%s/muttXXXXXX", buf);
82     mktemp (s);
83   }
84   else {
85     m_strcpy(tmp, sizeof(tmp), s);
86     mutt_sanitize_filename (tmp, 1);
87     snprintf (s, l, "%s/%s", buf, tmp);
88     if (lstat (s, &sb) == -1 && errno == ENOENT)
89       return;
90     if ((period = strrchr (tmp, '.')) != NULL)
91       *period = 0;
92     snprintf (s, l, "%s/%s.XXXXXX", buf, tmp);
93     mktemp (s);
94     if (period != NULL) {
95       *period = '.';
96       sl = m_strlen(s);
97       m_strcpy(s + sl, l - sl, period);
98     }
99   }
100 }
101
102 /* create a send-mode duplicate from a receive-mode body */
103
104 int mutt_copy_body (FILE * fp, BODY ** tgt, BODY * src)
105 {
106   char tmp[_POSIX_PATH_MAX];
107   BODY *b;
108
109   PARAMETER *par, **ppar;
110
111   short use_disp;
112
113   if (src->filename) {
114     use_disp = 1;
115     m_strcpy(tmp, sizeof(tmp), src->filename);
116   }
117   else {
118     use_disp = 0;
119     tmp[0] = '\0';
120   }
121
122   mutt_adv_mktemp (NULL, tmp, sizeof (tmp));
123   if (mutt_save_attachment (fp, src, tmp, 0, NULL) == -1)
124     return -1;
125
126   *tgt = mutt_new_body ();
127   b = *tgt;
128
129   memcpy (b, src, sizeof (BODY));
130   b->parts = NULL;
131   b->next = NULL;
132
133   b->filename = m_strdup(tmp);
134   b->use_disp = use_disp;
135   b->unlink = 1;
136
137   if (mutt_is_text_part (b))
138     b->noconv = 1;
139
140   b->xtype = m_strdup(b->xtype);
141   b->subtype = m_strdup(b->subtype);
142   b->form_name = m_strdup(b->form_name);
143   b->filename = m_strdup(b->filename);
144   b->d_filename = m_strdup(b->d_filename);
145   b->description = m_strdup(b->description);
146
147   /* 
148    * we don't seem to need the HEADER structure currently.
149    * XXX - this may change in the future
150    */
151
152   if (b->hdr)
153     b->hdr = NULL;
154
155   /* copy parameters */
156   for (par = b->parameter, ppar = &b->parameter; par;
157        ppar = &(*ppar)->next, par = par->next) {
158     *ppar = parameter_new();
159     (*ppar)->attribute = m_strdup(par->attribute);
160     (*ppar)->value = m_strdup(par->value);
161   }
162
163   mutt_stamp_attachment (b);
164
165   return 0;
166 }
167
168
169
170 void mutt_free_body (BODY ** p)
171 {
172   BODY *a = *p, *b;
173
174   while (a) {
175     b = a;
176     a = a->next;
177
178     if (b->parameter)
179       parameter_delete(&b->parameter);
180     if (b->unlink && b->filename) {
181       debug_print (1, ("unlinking %s.\n", b->filename));
182       unlink (b->filename);
183     }
184     else if (b->filename)
185       debug_print (1, ("not unlinking %s.\n", b->filename));
186
187     p_delete(&b->filename);
188     p_delete(&b->content);
189     p_delete(&b->xtype);
190     p_delete(&b->subtype);
191     p_delete(&b->description);
192     p_delete(&b->form_name);
193
194     if (b->hdr) {
195       /* Don't free twice (b->hdr->content = b->parts) */
196       b->hdr->content = NULL;
197       header_delete(&b->hdr);
198     }
199
200     if (b->parts)
201       mutt_free_body (&b->parts);
202
203     p_delete(&b);
204   }
205
206   *p = 0;
207 }
208
209 HEADER *mutt_dup_header (HEADER * h)
210 {
211   HEADER *hnew;
212
213   hnew = header_new();
214   memcpy (hnew, h, sizeof (HEADER));
215   return hnew;
216 }
217
218 /* returns true if the header contained in "s" is in list "t" */
219 int mutt_matches_ignore (const char *s, LIST * t)
220 {
221   for (; t; t = t->next) {
222     if (!ascii_strncasecmp (s, t->data, m_strlen(t->data))
223         || *t->data == '*')
224       return 1;
225   }
226   return 0;
227 }
228
229 /* prepend the path part of *path to *lnk */
230 void mutt_expand_link (char *newpath, const char *path, const char *lnk)
231 {
232   const char *lb = NULL;
233   size_t len;
234
235   /* lnk is full path */
236   if (*lnk == '/') {
237     m_strcpy(newpath, _POSIX_PATH_MAX, lnk);
238     return;
239   }
240
241   if ((lb = strrchr (path, '/')) == NULL) {
242     /* no path in lnk */
243     m_strcpy(newpath, _POSIX_PATH_MAX, lnk);
244     return;
245   }
246
247   len = lb - path + 1;
248   memcpy (newpath, path, len);
249   m_strcpy(newpath + len, _POSIX_PATH_MAX - len, lnk);
250 }
251
252 char *mutt_expand_path (char *s, size_t slen)
253 {
254   return _mutt_expand_path (s, slen, 0);
255 }
256
257 char *_mutt_expand_path (char *s, size_t slen, int rx)
258 {
259   char p[_POSIX_PATH_MAX] = "";
260   char q[_POSIX_PATH_MAX] = "";
261   char tmp[_POSIX_PATH_MAX];
262   char *t;
263
264   const char *tail = "";
265
266   int recurse = 0;
267
268   do {
269     recurse = 0;
270
271     switch (*s) {
272     case '~':
273       {
274         if (*(s + 1) == '/' || *(s + 1) == 0) {
275           m_strcpy(p, sizeof(p), NONULL(Homedir));
276           tail = s + 1;
277         }
278         else {
279           struct passwd *pw;
280
281           if ((t = strchr (s + 1, '/')))
282             *t = 0;
283
284           if ((pw = getpwnam (s + 1))) {
285             m_strcpy(p, sizeof(p), pw->pw_dir);
286             if (t) {
287               *t = '/';
288               tail = t;
289             }
290             else
291               tail = "";
292           }
293           else {
294             /* user not found! */
295             if (t)
296               *t = '/';
297             *p = '\0';
298             tail = s;
299           }
300         }
301       }
302       break;
303
304     case '=':
305     case '+':
306       {
307         /* if folder = imap[s]://host/: don't append slash */
308         if (imap_is_magic (NONULL (Maildir), NULL) == M_IMAP && 
309             Maildir[m_strlen(Maildir) - 1] == '/')
310           m_strcpy(p, sizeof(p), NONULL(Maildir));
311         else
312           snprintf (p, sizeof (p), "%s/", NONULL (Maildir));
313
314         tail = s + 1;
315       }
316       break;
317
318       /* elm compatibility, @ expands alias to user name */
319
320     case '@':
321       {
322         HEADER *h;
323         address_t *alias;
324
325         if ((alias = mutt_lookup_alias (s + 1))) {
326           h = header_new();
327           h->env = envelope_new();
328           h->env->from = h->env->to = alias;
329           mutt_default_save (p, sizeof (p), h);
330           h->env->from = h->env->to = NULL;
331           header_delete(&h);
332           /* Avoid infinite recursion if the resulting folder starts with '@' */
333           if (*p != '@')
334             recurse = 1;
335
336           tail = "";
337         }
338       }
339       break;
340
341     case '>':
342       {
343         m_strcpy(p, sizeof(p), NONULL(Inbox));
344         tail = s + 1;
345       }
346       break;
347
348     case '<':
349       {
350         m_strcpy(p, sizeof(p), NONULL(Outbox));
351         tail = s + 1;
352       }
353       break;
354
355     case '!':
356       {
357         if (*(s + 1) == '!') {
358           m_strcpy(p, sizeof(p), NONULL(LastFolder));
359           tail = s + 2;
360         }
361         else {
362           m_strcpy(p, sizeof(p), NONULL(Spoolfile));
363           tail = s + 1;
364         }
365       }
366       break;
367
368     case '-':
369       {
370         m_strcpy(p, sizeof(p), NONULL(LastFolder));
371         tail = s + 1;
372       }
373       break;
374
375     case '^':
376       {
377         m_strcpy(p, sizeof(p), NONULL(CurrentFolder));
378         tail = s + 1;
379       }
380       break;
381
382     default:
383       {
384         *p = '\0';
385         tail = s;
386       }
387     }
388
389     if (rx && *p && !recurse) {
390       rx_sanitize_string (q, sizeof (q), p);
391       snprintf (tmp, sizeof (tmp), "%s%s", q, tail);
392     }
393     else
394       snprintf (tmp, sizeof (tmp), "%s%s", p, tail);
395
396     m_strcpy(s, slen, tmp);
397   }
398   while (recurse);
399
400   return (s);
401 }
402
403 char *mutt_get_parameter (const char *s, PARAMETER * p)
404 {
405   for (; p; p = p->next)
406     if (ascii_strcasecmp (s, p->attribute) == 0)
407       return (p->value);
408
409   return NULL;
410 }
411
412 void mutt_set_parameter (const char *attribute, const char *value,
413                          PARAMETER ** p)
414 {
415   PARAMETER *q;
416
417   if (!value) {
418     mutt_delete_parameter (attribute, p);
419     return;
420   }
421
422   for (q = *p; q; q = q->next) {
423     if (ascii_strcasecmp (attribute, q->attribute) == 0) {
424       m_strreplace(&q->value, value);
425       return;
426     }
427   }
428
429   q = parameter_new();
430   q->attribute = m_strdup(attribute);
431   q->value = m_strdup(value);
432   q->next = *p;
433   *p = q;
434 }
435
436 void mutt_delete_parameter (const char *attribute, PARAMETER ** p)
437 {
438   PARAMETER *q;
439
440   for (q = *p; q; p = &q->next, q = q->next) {
441     if (ascii_strcasecmp (attribute, q->attribute) == 0) {
442       *p = q->next;
443       q->next = NULL;
444       parameter_delete(&q);
445       return;
446     }
447   }
448 }
449
450 /* returns 1 if Mutt can't display this type of data, 0 otherwise */
451 int mutt_needs_mailcap (BODY * m)
452 {
453   switch (m->type) {
454   case TYPETEXT:
455
456     if (!ascii_strcasecmp ("plain", m->subtype) ||
457         !ascii_strcasecmp ("rfc822-headers", m->subtype) ||
458         !ascii_strcasecmp ("enriched", m->subtype))
459       return 0;
460     break;
461
462   case TYPEAPPLICATION:
463     if (mutt_is_application_pgp (m))
464       return 0;
465     if (mutt_is_application_smime (m))
466       return 0;
467     break;
468
469   case TYPEMULTIPART:
470   case TYPEMESSAGE:
471     return 0;
472   }
473
474   return 1;
475 }
476
477 int mutt_is_text_part (BODY * b)
478 {
479   int t = b->type;
480   char *s = b->subtype;
481
482   if (mutt_is_application_pgp (b))
483     return 0;
484
485   if (t == TYPETEXT)
486     return 1;
487
488   if (t == TYPEMESSAGE) {
489     if (!ascii_strcasecmp ("delivery-status", s))
490       return 1;
491   }
492
493   if (t == TYPEAPPLICATION) {
494     if (!ascii_strcasecmp ("pgp-keys", s))
495       return 1;
496   }
497
498   return 0;
499 }
500
501 /* move all the headers from extra not present in base into base */
502 void mutt_merge_envelopes(ENVELOPE* base, ENVELOPE** extra)
503 {
504   /* copies each existing element if necessary, and sets the element
505   * to NULL in the source so that envelope_delete doesn't leave us
506   * with dangling pointers. */
507 #define MOVE_ELEM(h) if (!base->h) { base->h = (*extra)->h; (*extra)->h = NULL; }
508   MOVE_ELEM(return_path);
509   MOVE_ELEM(from);
510   MOVE_ELEM(to);
511   MOVE_ELEM(cc);
512   MOVE_ELEM(bcc);
513   MOVE_ELEM(sender);
514   MOVE_ELEM(reply_to);
515   MOVE_ELEM(mail_followup_to);
516   MOVE_ELEM(list_post);
517   MOVE_ELEM(message_id);
518   MOVE_ELEM(supersedes);
519   MOVE_ELEM(date);
520   MOVE_ELEM(x_label);
521   if (!base->refs_changed) {
522     MOVE_ELEM(references);
523   }
524   if (!base->irt_changed) {
525     MOVE_ELEM(in_reply_to);
526   }
527   /* real_subj is subordinate to subject */
528   if (!base->subject) {
529     base->subject = (*extra)->subject;
530     base->real_subj = (*extra)->real_subj;
531     (*extra)->subject = NULL;
532     (*extra)->real_subj = NULL;
533   }
534   /* spam and user headers should never be hashed, and the new envelope may
535    * have better values. Use new versions regardless. */
536   mutt_buffer_free (&base->spam);
537   mutt_free_list (&base->userhdrs);
538   MOVE_ELEM(spam);
539   MOVE_ELEM(userhdrs);
540 #undef MOVE_ELEM
541   
542   envelope_delete(extra);
543 }
544
545 void _mutt_mktemp (char *s, const char *src, int line)
546 {
547
548   snprintf (s, _POSIX_PATH_MAX, "%s/madmutt-%s-%d-%d-%d-%x%x", NONULL (Tempdir),
549             NONULL (Hostname), (int) getuid (), (int) getpid (), Counter++, 
550             (unsigned int) rand(), (unsigned int) rand());
551   debug_print (1, ("%s:%d: mutt_mktemp returns \"%s\".\n", src, line, s));
552   unlink (s);
553 }
554
555 void mutt_free_alias (ALIAS ** p)
556 {
557   ALIAS *t;
558
559   while (*p) {
560     t = *p;
561     *p = (*p)->next;
562     p_delete(&t->name);
563     address_delete (&t->addr);
564     p_delete(&t);
565   }
566 }
567
568 /* collapse the pathname using ~ or = when possible */
569 void mutt_pretty_mailbox (char *s)
570 {
571   char *p = s, *q = s;
572   size_t len;
573   url_scheme_t scheme;
574
575   scheme = url_check_scheme (s);
576
577   if (scheme == U_IMAP || scheme == U_IMAPS) {
578     imap_pretty_mailbox (s);
579     return;
580   }
581
582   /* if s is an url, only collapse path component */
583   if (scheme != U_UNKNOWN) {
584     p = strchr (s, ':') + 1;
585     if (!strncmp (p, "//", 2))
586       q = strchr (p + 2, '/');
587     if (!q)
588       q = strchr (p, '\0');
589     p = q;
590   }
591
592   /* first attempt to collapse the pathname */
593   while (*p) {
594     if (*p == '/' && p[1] == '/') {
595       *q++ = '/';
596       p += 2;
597     }
598     else if (p[0] == '/' && p[1] == '.' && p[2] == '/') {
599       *q++ = '/';
600       p += 3;
601     }
602     else
603       *q++ = *p++;
604   }
605   *q = 0;
606
607   if (m_strncmp(s, Maildir, (len = m_strlen(Maildir))) == 0 &&
608       s[len] == '/') {
609     *s++ = '=';
610     memmove (s, s + len, m_strlen(s + len) + 1);
611   }
612   else if (m_strncmp(s, Homedir, (len = m_strlen(Homedir))) == 0 &&
613            s[len] == '/') {
614     *s++ = '~';
615     memmove (s, s + len - 1, m_strlen(s + len - 1) + 1);
616   }
617 }
618
619 void mutt_pretty_size (char *s, size_t len, long n)
620 {
621   if (n == 0)
622     m_strcpy(s, len, "0K");
623   else if (n < 10189)           /* 0.1K - 9.9K */
624     snprintf (s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
625   else if (n < 1023949) {       /* 10K - 999K */
626     /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
627     snprintf (s, len, "%ldK", (n + 51) / 1024);
628   }
629   else if (n < 10433332)        /* 1.0M - 9.9M */
630     snprintf (s, len, "%3.1fM", n / 1048576.0);
631   else {                        /* 10M+ */
632
633     /* (10433332 + 52428) / 1048576 = 10 */
634     snprintf (s, len, "%ldM", (n + 52428) / 1048576);
635   }
636 }
637
638 void mutt_expand_file_fmt (char *dest, size_t destlen, const char *fmt,
639                            const char *src)
640 {
641   char tmp[LONG_STRING];
642
643   mutt_quote_filename (tmp, sizeof (tmp), src);
644   mutt_expand_fmt (dest, destlen, fmt, tmp);
645 }
646
647 void mutt_expand_fmt (char *dest, size_t destlen, const char *fmt,
648                       const char *src)
649 {
650   const char *p;
651   char *d;
652   size_t slen;
653   int found = 0;
654
655   slen = m_strlen(src);
656   destlen--;
657
658   for (p = fmt, d = dest; destlen && *p; p++) {
659     if (*p == '%') {
660       switch (p[1]) {
661       case '%':
662         *d++ = *p++;
663         destlen--;
664         break;
665       case 's':
666         found = 1;
667         m_strcpy(d, destlen + 1, src);
668         d += destlen > slen ? slen : destlen;
669         destlen -= destlen > slen ? slen : destlen;
670         p++;
671         break;
672       default:
673         *d++ = *p;
674         destlen--;
675         break;
676       }
677     }
678     else {
679       *d++ = *p;
680       destlen--;
681     }
682   }
683
684   *d = '\0';
685
686   if (!found && destlen > 0) {
687     m_strcat(dest, destlen, " ");
688     m_strcat(dest, destlen, src);
689   }
690
691 }
692
693 /* return 0 on success, -1 on abort, 1 on error */
694 int mutt_check_overwrite (const char *attname, const char *path,
695                           char *fname, size_t flen, int *append,
696                           char **directory)
697 {
698   int rc = 0;
699   char tmp[_POSIX_PATH_MAX];
700   struct stat st;
701
702   m_strcpy(fname, flen, path);
703   if (access (fname, F_OK) != 0)
704     return 0;
705   if (stat (fname, &st) != 0)
706     return -1;
707   if (S_ISDIR (st.st_mode)) {
708     if (directory) {
709       switch (mutt_multi_choice
710               (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"),
711                _("yna"))) {
712       case 3:                  /* all */
713         m_strreplace(directory, fname);
714         break;
715       case 1:                  /* yes */
716         p_delete(directory);
717         break;
718       case -1:                 /* abort */
719         p_delete(directory);
720         return -1;
721       case 2:                  /* no */
722         p_delete(directory);
723         return 1;
724       }
725     }
726     else
727       if ((rc =
728            mutt_yesorno (_("File is a directory, save under it?"),
729                          M_YES)) != M_YES)
730       return (rc == M_NO) ? 1 : -1;
731
732     if (!attname || !attname[0]) {
733       tmp[0] = 0;
734       if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
735                           M_FILE | M_CLEAR) != 0 || !tmp[0])
736         return (-1);
737       mutt_concat_path(fname, flen, path, tmp);
738     }
739     else
740       mutt_concat_path(fname, flen, path, mutt_basename(attname));
741   }
742
743   if (*append == 0 && access (fname, F_OK) == 0) {
744     switch (mutt_multi_choice
745             (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
746     {
747     case -1:                   /* abort */
748       return -1;
749     case 3:                    /* cancel */
750       return 1;
751
752     case 2:                    /* append */
753       *append = M_SAVE_APPEND;
754       break;
755     case 1:                    /* overwrite */
756       *append = M_SAVE_OVERWRITE;
757       break;
758     }
759   }
760   return 0;
761 }
762
763 void mutt_save_path (char *d, size_t dsize, address_t * a)
764 {
765   if (a && a->mailbox) {
766     m_strcpy(d, dsize, a->mailbox);
767     if (!option (OPTSAVEADDRESS)) {
768       char *p;
769
770       if ((p = strpbrk (d, "%@")))
771         *p = 0;
772     }
773     m_strtolower(d);
774   }
775   else
776     *d = 0;
777 }
778
779 void mutt_safe_path (char *s, size_t l, address_t * a)
780 {
781   char *p;
782
783   mutt_save_path (s, l, a);
784   for (p = s; *p; p++)
785     if (*p == '/' || ISSPACE (*p) || !IsPrint ((unsigned char) *p))
786       *p = '_';
787 }
788
789 /* counts how many characters in s can be skipped while none of the
790  * characters of c appears */
791 int mutt_skipchars (const char *s, const char *c)
792 {
793   int ret = 0;
794   const char *p = s;
795
796   while (s && *s) {
797     register const char *t = c;
798
799     while (t && *t) {
800       if (*t == *s)
801         return (ret);
802       t++;
803     }
804     ret++;
805     s++;
806   }
807   return (m_strlen(p));
808 }
809
810 void mutt_FormatString (char *dest,     /* output buffer */
811                         ssize_t destlen, /* output buffer len */
812                         const char *src,        /* template string */
813                         format_t * callback,    /* callback for processing */
814                         unsigned long data,     /* callback data */
815                         format_flag flags)
816 {                               /* callback flags */
817   char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
818   char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
819   ssize_t wlen, wid, count, col, len;
820
821   prefix[0] = '\0';
822   destlen--;                    /* save room for the terminal \0 */
823   wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
824   col = wlen;
825
826   while (*src && wlen < destlen) {
827     if (*src == '%') {
828       if (*++src == '%') {
829         *wptr++ = '%';
830         wlen++;
831         col++;
832         src++;
833         continue;
834       }
835
836       if (*src == '?') {
837         flags |= M_FORMAT_OPTIONAL;
838         src++;
839       }
840       else {
841         flags &= ~M_FORMAT_OPTIONAL;
842
843         /* eat the format string */
844         cp = prefix;
845         count = 0;
846         while (count < ssizeof (prefix) &&
847                (isdigit ((unsigned char) *src) || *src == '.' || *src == '-'))
848         {
849           *cp++ = *src++;
850           count++;
851         }
852         *cp = 0;
853       }
854
855       if (!*src)
856         break;                  /* bad format */
857
858       ch = *src++;              /* save the character to switch on */
859
860       if (flags & M_FORMAT_OPTIONAL) {
861         if (*src != '?')
862           break;                /* bad format */
863         src++;
864
865         /* eat the `if' part of the string */
866         cp = ifstring;
867         count = 0;
868         while (count < ssizeof (ifstring) && *src && *src != '?'
869                && *src != '&') {
870           *cp++ = *src++;
871           count++;
872         }
873         *cp = 0;
874
875         /* eat the `else' part of the string (optional) */
876         if (*src == '&')
877           src++;                /* skip the & */
878         cp = elsestring;
879         count = 0;
880         while (count < ssizeof (elsestring) && *src && *src != '?') {
881           *cp++ = *src++;
882           count++;
883         }
884         *cp = 0;
885
886         if (!*src)
887           break;                /* bad format */
888
889         src++;                  /* move past the trailing `?' */
890       }
891
892       /* handle generic cases first */
893       if (ch == '>') {
894         /* right justify to EOL */
895         ch = *src++;            /* pad char */
896         /* calculate space left on line.  if we've already written more data
897            than will fit on the line, ignore the rest of the line */
898         if (DrawFullLine || option (OPTSTATUSONTOP))
899           count = (COLS < destlen ? COLS : destlen);
900         else
901           count = ((COLS - SW) < destlen ? (COLS - SW) : destlen);
902         if (count > col) {
903           count -= col;         /* how many columns left on this line */
904           mutt_FormatString (buf, sizeof (buf), src, callback, data, flags);
905           wid = m_strlen(buf);
906           if (count > wid) {
907             count -= wid;       /* how many chars to pad */
908             memset (wptr, ch, count);
909             wptr += count;
910             col += count;
911           }
912           if (wid + wlen > destlen)
913             len = destlen - wlen;
914           else
915             len = wid;
916           memcpy (wptr, buf, len);
917           wptr += len;
918           wlen += len;
919           col += mutt_strwidth (buf);
920         }
921         break;                  /* skip rest of input */
922       }
923       else if (ch == '|') {
924         /* pad to EOL */
925         ch = *src++;
926         if (destlen > COLS)
927           destlen = COLS;
928         if (destlen > wlen) {
929           count = destlen - wlen;
930           memset (wptr, ch, count);
931           wptr += count;
932         }
933         break;                  /* skip rest of input */
934       }
935       else {
936         short lower = 0;
937         short nodots = 0;
938
939         while (ch == '_' || ch == ':') {
940           if (ch == '_')
941             lower = 1;
942           else if (ch == ':')
943             nodots = 1;
944
945           ch = *src++;
946         }
947
948         /* use callback function to handle this case */
949         src =
950           callback (buf, sizeof (buf), ch, src, prefix, ifstring, elsestring,
951                     data, flags);
952
953         if (lower)
954           m_strtolower(buf);
955         if (nodots) {
956           char *p = buf;
957
958           for (; *p; p++)
959             if (*p == '.')
960               *p = '_';
961         }
962
963         if ((len = m_strlen(buf)) + wlen > destlen)
964           len = (destlen - wlen > 0) ? (destlen - wlen) : 0;
965
966         memcpy (wptr, buf, len);
967         wptr += len;
968         wlen += len;
969         col += mutt_strwidth (buf);
970       }
971     }
972     else if (*src == '\\') {
973       if (!*++src)
974         break;
975       switch (*src) {
976       case 'n':
977         *wptr = '\n';
978         break;
979       case 't':
980         *wptr = '\t';
981         break;
982       case 'r':
983         *wptr = '\r';
984         break;
985       case 'f':
986         *wptr = '\f';
987         break;
988       case 'v':
989         *wptr = '\v';
990         break;
991       default:
992         *wptr = *src;
993         break;
994       }
995       src++;
996       wptr++;
997       wlen++;
998       col++;
999     }
1000     else {
1001       unsigned int bar = mutt_skipchars (src, "%\\");
1002       char *bar2 = p_dupstr(src, bar);
1003
1004       while (bar--) {
1005         *wptr++ = *src++;
1006         wlen++;
1007       }
1008       col += mutt_strwidth (bar2);
1009       p_delete(&bar2);
1010     }
1011   }
1012   *wptr = 0;
1013
1014 #if 0
1015   if (flags & M_FORMAT_MAKEPRINT) {
1016     /* Make sure that the string is printable by changing all non-printable
1017        chars to dots, or spaces for non-printable whitespace */
1018     for (cp = dest; *cp; cp++)
1019       if (!IsPrint (*cp) && !((flags & M_FORMAT_TREE) && (*cp <= M_TREE_MAX)))
1020         *cp = isspace ((unsigned char) *cp) ? ' ' : '.';
1021   }
1022 #endif
1023 }
1024
1025 /* This function allows the user to specify a command to read stdout from in
1026    place of a normal file.  If the last character in the string is a pipe (|),
1027    then we assume it is a commmand to run instead of a normal file. */
1028 FILE *mutt_open_read (const char *path, pid_t * thepid)
1029 {
1030     int len = m_strlen(path);
1031     FILE *f;
1032
1033     if (path[len - 1] == '|') {
1034         char *s = m_strdup(path);
1035
1036         /* read from a pipe */
1037
1038         s[len - 1] = 0;
1039         mutt_endwin (NULL);
1040         *thepid = mutt_create_filter (s, NULL, &f, NULL);
1041         p_delete(&s);
1042     } else {
1043         f = fopen (path, "r");
1044         if (!f)
1045             return NULL;
1046         *thepid = -1;
1047     }
1048
1049     return (f);
1050 }
1051
1052 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
1053 int mutt_save_confirm (const char *s, struct stat *st)
1054 {
1055   char tmp[_POSIX_PATH_MAX];
1056   int ret = 0;
1057   int rc;
1058   int magic = 0;
1059
1060   magic = mx_get_magic (s);
1061
1062   if (magic == M_POP) {
1063     mutt_error _("Can't save message to POP mailbox.");
1064
1065     return 1;
1066   }
1067
1068 #ifdef USE_NNTP
1069   if (magic == M_NNTP) {
1070     mutt_error _("Can't save message to newsserver.");
1071
1072     return 0;
1073   }
1074 #endif
1075
1076   if (magic > 0 && !mx_access (s, W_OK)) {
1077     if (option (OPTCONFIRMAPPEND) &&
1078         (!TrashPath || (m_strcmp(s, TrashPath) != 0))) {
1079       /* if we're appending to the trash, there's no point in asking */
1080       snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
1081       if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1082         ret = 1;
1083       else if (rc == -1)
1084         ret = -1;
1085     }
1086   }
1087
1088   if (stat (s, st) != -1) {
1089     if (magic == -1) {
1090       mutt_error (_("%s is not a mailbox!"), s);
1091       return 1;
1092     }
1093   }
1094   else {
1095     if (magic != M_IMAP)
1096     {
1097       st->st_mtime = 0;
1098       st->st_atime = 0;
1099
1100       if (errno == ENOENT) {
1101         if (option (OPTCONFIRMCREATE)) {
1102           snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
1103           if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1104             ret = 1;
1105           else if (rc == -1)
1106             ret = -1;
1107         }
1108       }
1109       else {
1110         mutt_perror (s);
1111         return 1;
1112       }
1113     }
1114   }
1115
1116   CLEARLINE (LINES - 1);
1117   return (ret);
1118 }
1119
1120 void mutt_display_sanitize (char *s)
1121 {
1122   for (; *s; s++) {
1123     if (!IsPrint (*s))
1124       *s = '?';
1125   }
1126 }
1127
1128 void mutt_sleep (short s)
1129 {
1130   if (SleepTime > s)
1131     sleep (SleepTime);
1132   else if (s)
1133     sleep (s);
1134 }
1135
1136 /* Decrease a file's modification time by 1 second */
1137 time_t mutt_decrease_mtime (const char *f, struct stat *st)
1138 {
1139   struct utimbuf utim;
1140   struct stat _st;
1141   time_t mtime;
1142
1143   if (!st) {
1144     if (stat (f, &_st) == -1)
1145       return -1;
1146     st = &_st;
1147   }
1148
1149   if ((mtime = st->st_mtime) == time (NULL)) {
1150     mtime -= 1;
1151     utim.actime = mtime;
1152     utim.modtime = mtime;
1153     utime (f, &utim);
1154   }
1155
1156   return mtime;
1157 }
1158
1159 /* sets mtime of 'to' to mtime of 'from' */
1160 void mutt_set_mtime (const char* from, const char* to) {
1161   struct utimbuf utim;
1162   struct stat st;
1163
1164   if (stat (from, &st) != -1) {
1165     utim.actime = st.st_mtime;
1166     utim.modtime = st.st_mtime;
1167     utime (to, &utim);
1168   }
1169 }
1170
1171 const char *mutt_make_version (int full)
1172 {
1173   static char vstring[STRING];
1174
1175   if (full)
1176     snprintf (vstring, sizeof (vstring),
1177               "Madmutt/%s-r%s (based on Mutt 1.5.11)",
1178               MUTT_VERSION, MUTT_REVISION);
1179   else
1180     snprintf (vstring, sizeof (vstring), "Madmutt/%s-%s",
1181               MUTT_VERSION, MUTT_REVISION);
1182   return vstring;
1183 }
1184
1185 void mutt_free_spam_list (SPAM_LIST ** list)
1186 {
1187   SPAM_LIST *p;
1188
1189   if (!list)
1190     return;
1191   while (*list) {
1192     p = *list;
1193     *list = (*list)->next;
1194     rx_delete(&p->rx);
1195     p_delete(&p->template);
1196     p_delete(&p);
1197   }
1198 }
1199
1200 int mutt_match_spam_list (const char *s, SPAM_LIST * l, char *text, int x)
1201 {
1202   static regmatch_t *pmatch = NULL;
1203   static int nmatch = 0;
1204   int i, n, tlen;
1205   char *p;
1206
1207   if (!s)
1208     return 0;
1209
1210   tlen = 0;
1211
1212   for (; l; l = l->next) {
1213     /* If this pattern needs more matches, expand pmatch. */
1214     if (l->nmatch > nmatch) {
1215       p_realloc(&pmatch, l->nmatch);
1216       nmatch = l->nmatch;
1217     }
1218
1219     /* Does this pattern match? */
1220     if (regexec
1221         (l->rx->rx, s, (size_t) l->nmatch, (regmatch_t *) pmatch,
1222          (int) 0) == 0) {
1223       debug_print (5, ("%s matches %s\n%d subst", s, l->rx->pattern, l->rx->rx->re_nsub));
1224
1225       /* Copy template into text, with substitutions. */
1226       for (p = l->template; *p;) {
1227         if (*p == '%') {
1228           n = atoi (++p);       /* find pmatch index */
1229           while (isdigit ((unsigned char) *p))
1230             ++p;                /* skip subst token */
1231           for (i = pmatch[n].rm_so; (i < pmatch[n].rm_eo) && (tlen < x); i++)
1232             text[tlen++] = s[i];
1233         }
1234         else {
1235           text[tlen++] = *p++;
1236         }
1237       }
1238       text[tlen] = '\0';
1239       debug_print (5, ("\"%s\"\n", text));
1240       return 1;
1241     }
1242   }
1243
1244   return 0;
1245 }
1246
1247 int mutt_cmp_header (const HEADER * h1, const HEADER * h2) {
1248   if (h1 && h2) {
1249     if (h1->received != h2->received ||
1250         h1->date_sent != h2->date_sent ||
1251         h1->content->length != h2->content->length ||
1252         h1->lines != h2->lines ||
1253         h1->zhours != h2->zhours ||
1254         h1->zminutes != h2->zminutes ||
1255         h1->zoccident != h2->zoccident ||
1256         h1->mime != h2->mime ||
1257         !mutt_cmp_env (h1->env, h2->env) ||
1258         !mutt_cmp_body (h1->content, h2->content))
1259       return (0);
1260     else
1261       return (1);
1262   }
1263   else {
1264     if (h1 == NULL && h2 == NULL)
1265       return (1);
1266     else
1267       return (0);
1268   }
1269 }
1270
1271 /* return 1 if address lists are strictly identical */
1272 int mutt_cmp_addr (const address_t * a, const address_t * b)
1273 {
1274   while (a && b) {
1275     if (m_strcmp(a->mailbox, b->mailbox) ||
1276         m_strcmp(a->personal, b->personal))
1277       return (0);
1278
1279     a = a->next;
1280     b = b->next;
1281   }
1282   if (a || b)
1283     return (0);
1284
1285   return (1);
1286 }
1287
1288 int mutt_cmp_list (const LIST * a, const LIST * b)
1289 {
1290   while (a && b) {
1291     if (m_strcmp(a->data, b->data))
1292       return (0);
1293
1294     a = a->next;
1295     b = b->next;
1296   }
1297   if (a || b)
1298     return (0);
1299
1300   return (1);
1301 }
1302
1303 int mutt_cmp_env (const ENVELOPE * e1, const ENVELOPE * e2)
1304 {
1305   if (e1 && e2) {
1306     if (m_strcmp(e1->message_id, e2->message_id) ||
1307         m_strcmp(e1->subject, e2->subject) ||
1308         !mutt_cmp_list (e1->references, e2->references) ||
1309         !mutt_cmp_addr (e1->from, e2->from) ||
1310         !mutt_cmp_addr (e1->sender, e2->sender) ||
1311         !mutt_cmp_addr (e1->reply_to, e2->reply_to) ||
1312         !mutt_cmp_addr (e1->to, e2->to) ||
1313         !mutt_cmp_addr (e1->cc, e2->cc) ||
1314         !mutt_cmp_addr (e1->return_path, e2->return_path))
1315       return (0);
1316     else
1317       return (1);
1318   }
1319   else {
1320     if (e1 == NULL && e2 == NULL)
1321       return (1);
1322     else
1323       return (0);
1324   }
1325 }
1326
1327 int mutt_cmp_param (const PARAMETER * p1, const PARAMETER * p2)
1328 {
1329   while (p1 && p2) {
1330     if (m_strcmp(p1->attribute, p2->attribute) ||
1331         m_strcmp(p1->value, p2->value))
1332       return (0);
1333
1334     p1 = p1->next;
1335     p2 = p2->next;
1336   }
1337   if (p1 || p2)
1338     return (0);
1339
1340   return (1);
1341 }
1342
1343 int mutt_cmp_body (const BODY * b1, const BODY * b2)
1344 {
1345   if (b1->type != b2->type ||
1346       b1->encoding != b2->encoding ||
1347       m_strcmp(b1->subtype, b2->subtype) ||
1348       m_strcmp(b1->description, b2->description) ||
1349       !mutt_cmp_param (b1->parameter, b2->parameter) ||
1350       b1->length != b2->length)
1351     return (0);
1352   return (1);
1353 }