2 ** sortm.c -- sort messages in a folder by date/time
4 ** This code is Copyright (c) 2002, by the authors of nmh. See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
13 static struct swit switches[] = {
15 { "datefield field", 0 },
17 { "textfield field", 0 },
41 static struct smsg *smsgs;
44 char *subjsort = NULL; /* sort on subject if != 0 */
46 int submajor = 0; /* if true, sort on subject-major */
49 /* This keeps compiler happy on calls to qsort */
50 typedef int (*qsort_comp) (const void *, const void *);
55 static int read_hdrs(struct msgs *, char *);
56 static int get_fields(char *, int, struct smsg *);
57 static int dsort(struct smsg **, struct smsg **);
58 static int subsort(struct smsg **, struct smsg **);
59 static int txtsort(struct smsg **, struct smsg **);
60 static void rename_chain(struct msgs *, struct smsg **, int, int);
61 static void rename_msgs(struct msgs *, struct smsg **);
65 main(int argc, char **argv)
69 char *maildir, *datesw = NULL;
70 char *folder = NULL, buf[BUFSIZ], **argp;
72 struct msgs_array msgs = { 0, 0, NULL };
76 setlocale(LC_ALL, "");
77 invo_name = mhbasename(argv[0]);
79 /* read user profile/context */
82 arguments = getarguments(invo_name, argc, argv, 1);
88 while ((cp = *argp++)) {
90 switch (smatch(++cp, switches)) {
92 ambigsw(cp, switches);
95 adios(NULL, "-%s unknown", cp);
98 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
99 print_help(buf, switches, 1);
102 print_version(invo_name);
107 adios(NULL, "only one date field at a time");
108 if (!(datesw = *argp++) || *datesw == '-')
109 adios(NULL, "missing argument to %s",
115 adios(NULL, "only one text field at a time");
116 if (!(subjsort = *argp++) || *subjsort == '-')
117 adios(NULL, "missing argument to %s",
126 if (!(cp = *argp++) || *cp == '-')
127 adios(NULL, "missing argument to %s", argp[-2]);
129 cp++; /* skip any leading zeros */
130 if (!*cp) { /* hit end of string */
131 submajor++; /* sort subject-major */
134 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
135 adios(NULL, "impossible limit %s", cp);
136 datelimit *= 60*60*24;
139 submajor = 0; /* use date-major, but */
140 datelimit = 0; /* use no limit */
151 if (*cp == '+' || *cp == '@') {
153 adios(NULL, "only one folder at a time!");
155 folder = getcpy(expandfol(cp));
157 app_msgarg(&msgs, cp);
161 app_msgarg(&msgs, seq_all);
165 folder = getcurfol();
166 maildir = toabsdir(folder);
168 if (chdir(maildir) == NOTOK)
169 adios(maildir, "unable to change directory to");
171 /* read folder and create message structure */
172 if (!(mp = folder_read(folder)))
173 adios(NULL, "unable to read folder %s", folder);
175 /* check for empty folder */
177 adios(NULL, "no messages in %s", folder);
179 /* parse all the message ranges/sequences and set SELECTED */
180 for (msgnum = 0; msgnum < msgs.size; msgnum++)
181 if (!m_convert(mp, msgs.msgs[msgnum]))
183 seq_setprev(mp); /* set the previous sequence */
185 if ((nmsgs = read_hdrs(mp, datesw)) <= 0)
186 adios(NULL, "no messages to sort");
189 ** sort a list of pointers to our "messages to be sorted".
191 dlist = (struct smsg **) mh_xmalloc((nmsgs+1) * sizeof(*dlist));
192 for (i = 0; i < nmsgs; i++)
193 dlist[i] = &smsgs[i];
196 if (verbose) { /* announce what we're doing */
198 printf("sorting by %s-major %s-minor\n",
199 submajor ? subjsort : datesw,
200 submajor ? datesw : subjsort);
202 printf("sorting by datefield %s\n", datesw);
205 /* first sort by date, or by subject-major, date-minor */
206 qsort((char *) dlist, nmsgs, sizeof(*dlist),
207 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
210 ** if we're sorting on subject, we need another list
211 ** in subject order, then a merge pass to collate the
214 if (!submajor && subjsort) { /* already date sorted */
215 struct smsg **slist, **flist;
216 register struct smsg ***il, **fp, **dp;
218 slist = (struct smsg **)
219 mh_xmalloc((nmsgs+1) * sizeof(*slist));
220 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
221 qsort((char *)slist, nmsgs, sizeof(*slist),
222 (qsort_comp) subsort);
225 ** make an inversion list so we can quickly find
226 ** the collection of messages with the same subj
227 ** given a message number.
229 il = (struct smsg ***) calloc(mp->hghsel+1, sizeof(*il));
231 adios(NULL, "couldn't allocate msg list");
232 for (i = 0; i < nmsgs; i++)
233 il[slist[i]->s_msg] = &slist[i];
235 ** make up the final list, chronological but with
236 ** all the same subjects grouped together.
238 flist = (struct smsg **)
239 mh_xmalloc((nmsgs+1) * sizeof(*flist));
241 for (dp = dlist; *dp;) {
242 register struct smsg **s = il[(*dp++)->s_msg];
244 /* see if we already did this guy */
250 ** take the next message(s) if there is one,
251 ** its subject isn't null and its subject
252 ** is the same as this one and it's not too
255 while (*s && (*s)->s_subj[0] && strcmp((*s)->s_subj, s[-1]->s_subj) == 0 && (datelimit == 0 || (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
267 ** At this point, dlist is a sorted array of pointers to smsg
268 ** structures, each of which contains a message number.
271 rename_msgs(mp, dlist);
273 context_replace(curfolder, folder); /* update current folder */
274 seq_save(mp); /* synchronize message sequences */
275 context_save(); /* save the context file */
276 folder_free(mp); /* free folder/message structure */
281 read_hdrs(struct msgs *mp, char *datesw)
285 register struct smsg *s;
287 twscopy(&tb, dlocaltimenow());
289 smsgs = (struct smsg *) calloc((size_t) (mp->hghsel - mp->lowsel + 2),
292 adios(NULL, "unable to allocate sort storage");
295 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
296 if (is_selected(mp, msgnum)) {
297 if (get_fields(datesw, msgnum, s)) {
309 ** Parse the message and get the data or subject field,
314 get_fields(char *datesw, int msg, struct smsg *smsg)
318 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
319 register struct tws *tw;
320 register char *datecomp = NULL, *subjcomp = NULL;
323 if ((in = fopen(msgnam = m_name(msg), "r")) == NULL) {
324 admonish(msgnam, "unable to read message");
327 for (compnum = 1, state = FLD;;) {
328 switch (state = m_getfld(state, nam, buf, sizeof(buf), in)) {
333 if (!mh_strcasecmp(nam, datesw)) {
334 datecomp = add(buf, datecomp);
335 while (state == FLDPLUS) {
336 state = m_getfld(state, nam, buf,
338 datecomp = add(buf, datecomp);
340 if (!subjsort || subjcomp)
342 } else if (subjsort && !mh_strcasecmp(nam, subjsort)) {
343 subjcomp = add(buf, subjcomp);
344 while (state == FLDPLUS) {
345 state = m_getfld(state, nam, buf,
347 subjcomp = add(buf, subjcomp);
352 /* just flush this guy */
353 while (state == FLDPLUS)
354 state = m_getfld(state, nam, buf,
366 if (state == LENERR || state == FMTERR)
367 admonish(NULL, "format error in message %d (header #%d)", msg, compnum);
376 adios(NULL, "internal error -- you lose");
382 ** If no date component, then use the modification
383 ** time of the file as its date
385 if (!datecomp || (tw = dparsetime(datecomp)) == NULL) {
388 admonish(NULL, "can't parse %s field in message %d",
390 fstat(fileno(in), &st);
391 smsg->s_clock = st.st_mtime;
393 smsg->s_clock = dmktime(tw);
399 ** try to make the subject "canonical": delete
400 ** leading "re:", everything but letters & smash
401 ** letters to lower case.
403 register char *cp, *cp2;
404 register unsigned char c;
408 if (strcmp(subjsort, "subject") == 0) {
420 while ((c = *cp++)) {
422 *cp2++ = isupper(c) ? tolower(c) : c;
429 smsg->s_subj = subjcomp;
442 dsort(struct smsg **a, struct smsg **b)
444 if ((*a)->s_clock < (*b)->s_clock)
446 else if ((*a)->s_clock > (*b)->s_clock)
448 else if ((*a)->s_msg < (*b)->s_msg)
458 subsort(struct smsg **a, struct smsg **b)
462 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
465 return (dsort(a, b));
469 txtsort(struct smsg **a, struct smsg **b)
473 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
475 else if ((*a)->s_msg < (*b)->s_msg)
482 rename_chain(struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
485 char *newname, oldname[BUFSIZ];
486 char newbuf[MAXPATHLEN + 1];
489 nxt = mlist[msg] - smsgs; /* mlist[msg] is a ptr into smsgs */
490 mlist[msg] = (struct smsg *)0;
491 old = smsgs[nxt].s_msg;
492 new = smsgs[msg].s_msg;
493 strncpy(oldname, m_name(old), sizeof(oldname));
494 newname = m_name(new);
496 printf("message %d becomes message %d\n", old, new);
498 snprintf(oldname, sizeof (oldname), "%s/%d",
500 snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
501 ext_hook("ref-hook", oldname, newbuf);
503 if (rename(oldname, newname) == NOTOK)
504 adios(newname, "unable to rename %s to", oldname);
506 copy_msg_flags(mp, new, old);
507 if (mp->curmsg == old)
515 /* if (nxt != endmsg); */
516 /* rename_chain(mp, mlist, nxt, endmsg); */
520 rename_msgs(struct msgs *mp, struct smsg **mlist)
524 char f1[BUFSIZ], tmpfil[BUFSIZ];
525 char newbuf[MAXPATHLEN + 1];
528 strncpy(tmpfil, m_name(mp->hghmsg + 1), sizeof(tmpfil));
530 for (i = 0; i < nmsgs; i++) {
531 if (! (sp = mlist[i]))
532 continue; /* did this one */
536 continue; /* this one doesn't move */
539 ** the guy that was msg j is about to become msg i.
540 ** rename 'j' to make a hole, then recursively rename
541 ** guys to fill up the hole.
543 old = smsgs[j].s_msg;
544 new = smsgs[i].s_msg;
545 strncpy(f1, m_name(old), sizeof(f1));
548 printf("renaming message chain from %d to %d\n",
552 ** Run the external hook to refile the old message as the
553 ** temporary message number that is off of the end of the
554 ** messages in the folder.
557 snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
558 snprintf(newbuf, sizeof (newbuf), "%s/%d",
559 mp->foldpath, mp->hghmsg + 1);
560 ext_hook("ref-hook", f1, newbuf);
562 if (rename(f1, tmpfil) == NOTOK)
563 adios(tmpfil, "unable to rename %s to ", f1);
565 get_msg_flags(mp, &tmpset, old);
567 rename_chain(mp, mlist, j, i);
570 ** Run the external hook to refile the temorary message number
571 ** to the real place.
574 snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
575 ext_hook("ref-hook", newbuf, f1);
577 if (rename(tmpfil, m_name(new)) == NOTOK)
578 adios(m_name(new), "unable to rename %s to", tmpfil);
580 set_msg_flags(mp, &tmpset, new);
581 mp->msgflags |= SEQMOD;