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.
17 #ifdef HAVE_SYS_PARAM_H
18 # include <sys/param.h>
21 static struct swit switches[] = {
23 { "datefield field", 0 },
25 { "textfield field", 0 },
49 static struct smsg *smsgs;
52 char *subjsort = NULL; /* sort on subject if != 0 */
54 int submajor = 0; /* if true, sort on subject-major */
57 /* This keeps compiler happy on calls to qsort */
58 typedef int (*qsort_comp) (const void *, const void *);
63 static int read_hdrs(struct msgs *, char *);
64 static int get_fields(char *, int, struct smsg *);
65 static int dsort(struct smsg **, struct smsg **);
66 static int subsort(struct smsg **, struct smsg **);
67 static int txtsort(struct smsg **, struct smsg **);
68 static void rename_chain(struct msgs *, struct smsg **, int, int);
69 static void rename_msgs(struct msgs *, struct smsg **);
73 main(int argc, char **argv)
77 char *maildir, *datesw = NULL;
78 char *folder = NULL, buf[BUFSIZ], **argp;
80 struct msgs_array msgs = { 0, 0, NULL };
84 setlocale(LC_ALL, "");
85 invo_name = mhbasename(argv[0]);
87 /* read user profile/context */
90 arguments = getarguments(invo_name, argc, argv, 1);
96 while ((cp = *argp++)) {
98 switch (smatch(++cp, switches)) {
100 ambigsw(cp, switches);
103 adios(NULL, "-%s unknown", cp);
106 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
107 print_help(buf, switches, 1);
110 print_version(invo_name);
115 adios(NULL, "only one date field at a time");
116 if (!(datesw = *argp++) || *datesw == '-')
117 adios(NULL, "missing argument to %s",
123 adios(NULL, "only one text field at a time");
124 if (!(subjsort = *argp++) || *subjsort == '-')
125 adios(NULL, "missing argument to %s",
134 if (!(cp = *argp++) || *cp == '-')
135 adios(NULL, "missing argument to %s", argp[-2]);
137 cp++; /* skip any leading zeros */
138 if (!*cp) { /* hit end of string */
139 submajor++; /* sort subject-major */
142 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
143 adios(NULL, "impossible limit %s", cp);
144 datelimit *= 60*60*24;
147 submajor = 0; /* use date-major, but */
148 datelimit = 0; /* use no limit */
159 if (*cp == '+' || *cp == '@') {
161 adios(NULL, "only one folder at a time!");
163 folder = getcpy(expandfol(cp));
165 app_msgarg(&msgs, cp);
169 app_msgarg(&msgs, seq_all);
173 folder = getcurfol();
174 maildir = toabsdir(folder);
176 if (chdir(maildir) == NOTOK)
177 adios(maildir, "unable to change directory to");
179 /* read folder and create message structure */
180 if (!(mp = folder_read(folder)))
181 adios(NULL, "unable to read folder %s", folder);
183 /* check for empty folder */
185 adios(NULL, "no messages in %s", folder);
187 /* parse all the message ranges/sequences and set SELECTED */
188 for (msgnum = 0; msgnum < msgs.size; msgnum++)
189 if (!m_convert(mp, msgs.msgs[msgnum]))
191 seq_setprev(mp); /* set the previous sequence */
193 if ((nmsgs = read_hdrs(mp, datesw)) <= 0)
194 adios(NULL, "no messages to sort");
197 ** sort a list of pointers to our "messages to be sorted".
199 dlist = (struct smsg **) mh_xmalloc((nmsgs+1) * sizeof(*dlist));
200 for (i = 0; i < nmsgs; i++)
201 dlist[i] = &smsgs[i];
204 if (verbose) { /* announce what we're doing */
206 printf("sorting by %s-major %s-minor\n",
207 submajor ? subjsort : datesw,
208 submajor ? datesw : subjsort);
210 printf("sorting by datefield %s\n", datesw);
213 /* first sort by date, or by subject-major, date-minor */
214 qsort((char *) dlist, nmsgs, sizeof(*dlist),
215 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
218 ** if we're sorting on subject, we need another list
219 ** in subject order, then a merge pass to collate the
222 if (!submajor && subjsort) { /* already date sorted */
223 struct smsg **slist, **flist;
224 register struct smsg ***il, **fp, **dp;
226 slist = (struct smsg **)
227 mh_xmalloc((nmsgs+1) * sizeof(*slist));
228 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
229 qsort((char *)slist, nmsgs, sizeof(*slist),
230 (qsort_comp) subsort);
233 ** make an inversion list so we can quickly find
234 ** the collection of messages with the same subj
235 ** given a message number.
237 il = (struct smsg ***) calloc(mp->hghsel+1, sizeof(*il));
239 adios(NULL, "couldn't allocate msg list");
240 for (i = 0; i < nmsgs; i++)
241 il[slist[i]->s_msg] = &slist[i];
243 ** make up the final list, chronological but with
244 ** all the same subjects grouped together.
246 flist = (struct smsg **)
247 mh_xmalloc((nmsgs+1) * sizeof(*flist));
249 for (dp = dlist; *dp;) {
250 register struct smsg **s = il[(*dp++)->s_msg];
252 /* see if we already did this guy */
258 ** take the next message(s) if there is one,
259 ** its subject isn't null and its subject
260 ** is the same as this one and it's not too
263 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)) {
275 ** At this point, dlist is a sorted array of pointers to smsg
276 ** structures, each of which contains a message number.
279 rename_msgs(mp, dlist);
281 context_replace(curfolder, folder); /* update current folder */
282 seq_save(mp); /* synchronize message sequences */
283 context_save(); /* save the context file */
284 folder_free(mp); /* free folder/message structure */
289 read_hdrs(struct msgs *mp, char *datesw)
293 register struct smsg *s;
295 twscopy(&tb, dlocaltimenow());
297 smsgs = (struct smsg *) calloc((size_t) (mp->hghsel - mp->lowsel + 2),
300 adios(NULL, "unable to allocate sort storage");
303 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
304 if (is_selected(mp, msgnum)) {
305 if (get_fields(datesw, msgnum, s)) {
317 ** Parse the message and get the data or subject field,
322 get_fields(char *datesw, int msg, struct smsg *smsg)
326 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
327 register struct tws *tw;
328 register char *datecomp = NULL, *subjcomp = NULL;
331 if ((in = fopen(msgnam = m_name(msg), "r")) == NULL) {
332 admonish(msgnam, "unable to read message");
335 for (compnum = 1, state = FLD;;) {
336 switch (state = m_getfld(state, nam, buf, sizeof(buf), in)) {
341 if (!mh_strcasecmp(nam, datesw)) {
342 datecomp = add(buf, datecomp);
343 while (state == FLDPLUS) {
344 state = m_getfld(state, nam, buf,
346 datecomp = add(buf, datecomp);
348 if (!subjsort || subjcomp)
350 } else if (subjsort && !mh_strcasecmp(nam, subjsort)) {
351 subjcomp = add(buf, subjcomp);
352 while (state == FLDPLUS) {
353 state = m_getfld(state, nam, buf,
355 subjcomp = add(buf, subjcomp);
360 /* just flush this guy */
361 while (state == FLDPLUS)
362 state = m_getfld(state, nam, buf,
374 if (state == LENERR || state == FMTERR)
375 admonish(NULL, "format error in message %d (header #%d)", msg, compnum);
384 adios(NULL, "internal error -- you lose");
390 ** If no date component, then use the modification
391 ** time of the file as its date
393 if (!datecomp || (tw = dparsetime(datecomp)) == NULL) {
396 admonish(NULL, "can't parse %s field in message %d",
398 fstat(fileno(in), &st);
399 smsg->s_clock = st.st_mtime;
401 smsg->s_clock = dmktime(tw);
407 ** try to make the subject "canonical": delete
408 ** leading "re:", everything but letters & smash
409 ** letters to lower case.
411 register char *cp, *cp2;
412 register unsigned char c;
416 if (strcmp(subjsort, "subject") == 0) {
428 while ((c = *cp++)) {
430 *cp2++ = isupper(c) ? tolower(c) : c;
437 smsg->s_subj = subjcomp;
450 dsort(struct smsg **a, struct smsg **b)
452 if ((*a)->s_clock < (*b)->s_clock)
454 else if ((*a)->s_clock > (*b)->s_clock)
456 else if ((*a)->s_msg < (*b)->s_msg)
466 subsort(struct smsg **a, struct smsg **b)
470 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
473 return (dsort(a, b));
477 txtsort(struct smsg **a, struct smsg **b)
481 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
483 else if ((*a)->s_msg < (*b)->s_msg)
490 rename_chain(struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
493 char *newname, oldname[BUFSIZ];
494 char newbuf[MAXPATHLEN + 1];
497 nxt = mlist[msg] - smsgs; /* mlist[msg] is a ptr into smsgs */
498 mlist[msg] = (struct smsg *)0;
499 old = smsgs[nxt].s_msg;
500 new = smsgs[msg].s_msg;
501 strncpy(oldname, m_name(old), sizeof(oldname));
502 newname = m_name(new);
504 printf("message %d becomes message %d\n", old, new);
506 snprintf(oldname, sizeof (oldname), "%s/%d",
508 snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
509 ext_hook("ref-hook", oldname, newbuf);
511 if (rename(oldname, newname) == NOTOK)
512 adios(newname, "unable to rename %s to", oldname);
514 copy_msg_flags(mp, new, old);
515 if (mp->curmsg == old)
523 /* if (nxt != endmsg); */
524 /* rename_chain(mp, mlist, nxt, endmsg); */
528 rename_msgs(struct msgs *mp, struct smsg **mlist)
532 char f1[BUFSIZ], tmpfil[BUFSIZ];
533 char newbuf[MAXPATHLEN + 1];
536 strncpy(tmpfil, m_name(mp->hghmsg + 1), sizeof(tmpfil));
538 for (i = 0; i < nmsgs; i++) {
539 if (! (sp = mlist[i]))
540 continue; /* did this one */
544 continue; /* this one doesn't move */
547 ** the guy that was msg j is about to become msg i.
548 ** rename 'j' to make a hole, then recursively rename
549 ** guys to fill up the hole.
551 old = smsgs[j].s_msg;
552 new = smsgs[i].s_msg;
553 strncpy(f1, m_name(old), sizeof(f1));
556 printf("renaming message chain from %d to %d\n",
560 ** Run the external hook to refile the old message as the
561 ** temporary message number that is off of the end of the
562 ** messages in the folder.
565 snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
566 snprintf(newbuf, sizeof (newbuf), "%s/%d",
567 mp->foldpath, mp->hghmsg + 1);
568 ext_hook("ref-hook", f1, newbuf);
570 if (rename(f1, tmpfil) == NOTOK)
571 adios(tmpfil, "unable to rename %s to ", f1);
573 get_msg_flags(mp, &tmpset, old);
575 rename_chain(mp, mlist, j, i);
578 ** Run the external hook to refile the temorary message number
579 ** to the real place.
582 snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
583 ext_hook("ref-hook", newbuf, f1);
585 if (rename(tmpfil, m_name(new)) == NOTOK)
586 adios(m_name(new), "unable to rename %s to", tmpfil);
588 set_msg_flags(mp, &tmpset, new);
589 mp->msgflags |= SEQMOD;