xref: /netbsd-src/usr.bin/mail/thread.c (revision c8a35b6227034951e874c2def577388e79ede4a5)
1 /*	$NetBSD: thread.c,v 1.7 2009/01/18 01:29:57 lukem Exp $	*/
2 
3 /*-
4  * Copyright (c) 2006 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Anon Ymous.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * This module contains the threading and sorting routines.
34  */
35 
36 #ifdef THREAD_SUPPORT
37 
38 #include <sys/cdefs.h>
39 #ifndef __lint__
40 __RCSID("$NetBSD: thread.c,v 1.7 2009/01/18 01:29:57 lukem Exp $");
41 #endif /* not __lint__ */
42 
43 #include <assert.h>
44 #include <ctype.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <util.h>
48 
49 #include "def.h"
50 #include "glob.h"
51 #include "extern.h"
52 #include "format.h"
53 #include "thread.h"
54 
55 
56 struct thread_s {
57 	struct message *t_head;		/* head of the thread */
58 	struct message **t_msgtbl;	/* message array indexed by msgnum */
59 	int t_msgCount;			/* count of messages in thread */
60 };
61 #define THREAD_INIT	{NULL, NULL, 0}
62 
63 typedef int state_t;
64 #define S_STATE_INIT	0
65 #define S_EXPOSE	1	/* flag to expose the thread */
66 #define S_RESTRICT	2	/* flag to restrict to tagged messages */
67 #define S_IS_EXPOSE(a)		((a) & S_EXPOSE)
68 #define S_IS_RESTRICT(a)	((a) & S_RESTRICT)
69 
70 /* XXX - this isn't really a thread */
71 static struct thread_s message_array  = THREAD_INIT;	/* the basic message array */
72 static struct thread_s current_thread = THREAD_INIT;	/* the current thread */
73 
74 static state_t state = S_STATE_INIT;	/* the current state */
75 
76 /*
77  * A state hook used by the format module.
78  */
79 PUBLIC int
80 thread_hidden(void)
81 {
82 	return !S_IS_EXPOSE(state);
83 }
84 
85 /************************************************************************
86  * Debugging stuff that should evaporate eventually.
87  */
88 #ifdef THREAD_DEBUG
89 static void
90 show_msg(struct message *mp)
91 {
92 	if (mp == NULL)
93 		return;
94 	/*
95 	 * Arg!  '%p' doesn't like the '0' modifier.
96 	 */
97 	(void)printf("%3d (%p):"
98 	    " flink=%p blink=%p clink=%p plink=%p"
99 	    " depth=%d flags=0x%03x\n",
100 	    mp->m_index, mp,
101 	    mp->m_flink, mp->m_blink, mp->m_clink, mp->m_plink,
102 	    mp->m_depth, mp->m_flag);
103 }
104 
105 #ifndef __lint__
106 __unused
107 static void
108 show_thread(struct message *mp)
109 {
110 	(void)printf("current_thread.t_head=%p\n", current_thread.t_head);
111 	for (/*EMPTY*/; mp; mp = next_message(mp))
112 		show_msg(mp);
113 }
114 #endif
115 
116 PUBLIC int
117 thread_showcmd(void *v)
118 {
119 	int *ip;
120 
121 	(void)printf("current_thread.t_head=%p\n", current_thread.t_head);
122 	for (ip = v; *ip; ip++)
123 		show_msg(get_message(*ip));
124 
125 	return 0;
126 }
127 #endif /* THREAD_DEBUG */
128 
129 /*************************************************************************
130  * tag/restrict routines
131  */
132 
133 /*
134  * Return TRUE iff all messages forward or below this one are tagged.
135  */
136 static int
137 is_tagged_core(struct message *mp)
138 {
139 	if (S_IS_EXPOSE(state))
140 		return 1;
141 
142 	for (/*EMPTY*/; mp; mp = mp->m_flink)
143 		if ((mp->m_flag & MTAGGED) == 0 ||
144 		    is_tagged_core(mp->m_clink) == 0)
145 			return 0;
146 	return 1;
147 }
148 
149 static int
150 is_tagged(struct message *mp)
151 {
152 	return mp->m_flag & MTAGGED && is_tagged_core(mp->m_clink);
153 }
154 
155 /************************************************************************
156  * These are the core routines to access messages via the links used
157  * everywhere outside this module and fio.c.
158  */
159 
160 static int
161 has_parent(struct message *mp)
162 {
163 	return mp->m_plink != NULL &&
164 	    mp->m_plink->m_clink != current_thread.t_head;
165 }
166 
167 static struct message *
168 next_message1(struct message *mp)
169 {
170 	if (mp == NULL)
171 		return NULL;
172 
173 	if (S_IS_EXPOSE(state) == 0)
174 		return mp->m_flink;
175 
176 	if (mp->m_clink)
177 		return mp->m_clink;
178 
179 	while (mp->m_flink == NULL && has_parent(mp))
180 		mp = mp->m_plink;
181 
182 	return mp->m_flink;
183 }
184 
185 static struct message *
186 prev_message1(struct message *mp)
187 {
188 	if (mp == NULL)
189 		return NULL;
190 
191 	if (S_IS_EXPOSE(state) && mp->m_blink == NULL && has_parent(mp))
192 		return mp->m_plink;
193 
194 	return mp->m_blink;
195 }
196 
197 PUBLIC struct message *
198 next_message(struct message *mp)
199 {
200 	if (S_IS_RESTRICT(state) == 0)
201 		return next_message1(mp);
202 
203 	while ((mp = next_message1(mp)) != NULL && is_tagged(mp))
204 		continue;
205 
206 	return mp;
207 }
208 
209 PUBLIC struct message *
210 prev_message(struct message *mp)
211 {
212 	if (S_IS_RESTRICT(state) == 0)
213 		return prev_message1(mp);
214 
215 	while ((mp = prev_message1(mp)) != NULL && is_tagged(mp))
216 		continue;
217 
218 	return mp;
219 }
220 
221 static struct message *
222 first_message(struct message *mp)
223 {
224 	if (S_IS_RESTRICT(state) && is_tagged(mp))
225 		mp = next_message(mp);
226 	return mp;
227 }
228 
229 PUBLIC struct message *
230 get_message(int msgnum)
231 {
232 	struct message *mp;
233 
234 	if (msgnum < 1 || msgnum > current_thread.t_msgCount)
235 		return NULL;
236 	mp = current_thread.t_msgtbl[msgnum - 1];
237 	assert(mp->m_index == msgnum);
238 	return mp;
239 }
240 
241 PUBLIC int
242 get_msgnum(struct message *mp)
243 {
244 	return mp ? mp->m_index : 0;
245 }
246 
247 PUBLIC int
248 get_msgCount(void)
249 {
250 	return current_thread.t_msgCount;
251 }
252 
253 PUBLIC int
254 get_abs_msgCount(void)
255 {
256 	return message_array.t_msgCount;
257 }
258 
259 PUBLIC struct message *
260 get_abs_message(int msgnum)
261 {
262 	if (msgnum < 1 || msgnum > message_array.t_msgCount)
263 		return NULL;
264 
265 	return &message_array.t_head[msgnum - 1];
266 }
267 
268 PUBLIC struct message *
269 next_abs_message(struct message *mp)
270 {
271 	int i;
272 
273 	i = (int)(mp - message_array.t_head);
274 
275 	if (i < 0 || i + 1 >= message_array.t_msgCount)
276 		return NULL;
277 
278 	return &message_array.t_head[i + 1];
279 }
280 
281 /************************************************************************/
282 /*
283  * routines to handle the recursion of commands.
284  */
285 PUBLIC int
286 do_recursion(void)
287 {
288 	return S_IS_EXPOSE(state) == 0 && value(ENAME_RECURSIVE_CMDS) != NULL;
289 }
290 
291 static int
292 thread_recursion_flist(struct message *mp, int (*fn)(struct message *, void *), void *args)
293 {
294 	int retval;
295 	for (/*EMPTY*/; mp; mp = mp->m_flink) {
296 		if (S_IS_RESTRICT(state) && is_tagged(mp))
297 			continue;
298 		if ((retval = fn(mp, args)) != 0 ||
299 		    (retval = thread_recursion_flist(mp->m_clink, fn, args)) != 0)
300 			return retval;
301 	}
302 
303 	return 0;
304 }
305 
306 PUBLIC int
307 thread_recursion(struct message *mp, int (*fn)(struct message *, void *), void *args)
308 {
309 	int retval;
310 
311 	assert(mp != NULL);
312 
313 	if ((retval = fn(mp, args)) != 0)
314 		return retval;
315 
316 	if (do_recursion() &&
317 	    (retval = thread_recursion_flist(mp->m_clink, fn, args)) != 0)
318 		return retval;
319 
320 	return 0;
321 }
322 
323 /************************************************************************
324  * A hook for sfmtfield() in format.c.  It is the only place outside
325  * this module that the m_depth is known.
326  */
327 PUBLIC int
328 thread_depth(void)
329 {
330 	return current_thread.t_head ? current_thread.t_head->m_depth : 0;
331 }
332 
333 /************************************************************************/
334 
335 static int
336 reindex_core(struct message *mp)
337 {
338 	int i;
339 	assert(mp->m_blink == NULL);
340 
341 	i = 0;
342 	for (mp = first_message(mp); mp; mp = mp->m_flink) {
343 		assert(mp->m_flink == NULL || mp == mp->m_flink->m_blink);
344 		assert(mp->m_blink == NULL || mp == mp->m_blink->m_flink);
345 
346 		assert(mp->m_size != 0);
347 
348 		if (S_IS_RESTRICT(state) == 0 || !is_tagged(mp))
349 			mp->m_index = ++i;
350 
351 		if (mp->m_clink)
352 			(void)reindex_core(mp->m_clink);
353 	}
354 	return i;
355 }
356 
357 
358 static void
359 reindex(struct thread_s *tp)
360 {
361 	struct message *mp;
362 	int i;
363 
364 	assert(tp != NULL);
365 
366 	if ((mp = tp->t_head) == NULL || mp->m_size == 0)
367 		return;
368 
369 	assert(mp->m_blink == NULL);
370 
371 	if (S_IS_EXPOSE(state) == 0) {
372 		/*
373 		 * We special case this so that all the hidden
374 		 * sub-threads get indexed, not just the current one.
375 		 */
376 		i = reindex_core(tp->t_head);
377 	}
378 	else {
379 		i = 0;
380 		for (mp = first_message(tp->t_head); mp; mp = next_message(mp))
381 			mp->m_index = ++i;
382 	}
383 
384 	assert(i <= message_array.t_msgCount);
385 
386 	tp->t_msgCount = i;
387 	i = 0;
388 	for (mp = first_message(tp->t_head); mp; mp = next_message(mp))
389 		tp->t_msgtbl[i++] = mp;
390 }
391 
392 static void
393 redepth_core(struct message *mp, int depth, struct message *parent)
394 {
395 	assert(mp->m_blink == NULL);
396 	assert((parent == NULL && depth == 0) ||
397 	       (parent != NULL && depth != 0 && depth == parent->m_depth + 1));
398 
399 	for (/*EMPTY*/; mp; mp = mp->m_flink) {
400 		assert(mp->m_plink == parent);
401 		assert(mp->m_flink == NULL || mp == mp->m_flink->m_blink);
402 		assert(mp->m_blink == NULL || mp == mp->m_blink->m_flink);
403 		assert(mp->m_size != 0);
404 
405 		mp->m_depth = depth;
406 		if (mp->m_clink)
407 			redepth_core(mp->m_clink, depth + 1, mp);
408 	}
409 }
410 
411 static void
412 redepth(struct thread_s *thread)
413 {
414 	int depth;
415 	struct message *mp;
416 
417 	assert(thread != NULL);
418 
419 	if ((mp = thread->t_head) == NULL || mp->m_size == 0)
420 		return;
421 
422 	depth = mp->m_plink ? mp->m_plink->m_depth + 1 : 0;
423 
424 #ifndef NDEBUG	/* a sanity check if asserts are active */
425 	{
426 		struct message *tp;
427 		int i;
428 		i = 0;
429 		for (tp = mp->m_plink; tp; tp = tp->m_plink)
430 			i++;
431 		assert(i == depth);
432 	}
433 #endif
434 
435 	redepth_core(mp, depth, mp->m_plink);
436 }
437 
438 /************************************************************************
439  * To be called after reallocating the main message list.  It is here
440  * as it needs access to current_thread.t_head.
441  */
442 PUBLIC void
443 thread_fix_old_links(struct message *nmessage, struct message *message, int omsgCount)
444 {
445 	int i;
446 	if (nmessage == message)
447 		return;
448 
449 #ifndef NDEBUG
450 	message_array.t_head = nmessage; /* for assert check in thread_fix_new_links */
451 #endif
452 
453 # define FIX_LINK(p)	do { if (p) p = nmessage + (p - message); } while(/*CONSTCOND*/0)
454 	FIX_LINK(current_thread.t_head);
455 	for (i = 0; i < omsgCount; i++) {
456 		FIX_LINK(nmessage[i].m_blink);
457 		FIX_LINK(nmessage[i].m_flink);
458 		FIX_LINK(nmessage[i].m_clink);
459 		FIX_LINK(nmessage[i].m_plink);
460 	}
461 	for (i = 0; i < current_thread.t_msgCount; i++ )
462 		FIX_LINK(current_thread.t_msgtbl[i]);
463 
464 # undef FIX_LINK
465 }
466 
467 static void
468 thread_init(struct thread_s *tp, struct message *mp, int msgCount)
469 {
470 	int i;
471 
472 	if (tp->t_msgtbl == NULL || msgCount > tp->t_msgCount) {
473 		if (tp->t_msgtbl)
474 			free(tp->t_msgtbl);
475 		tp->t_msgtbl = ecalloc((size_t)msgCount, sizeof(tp->t_msgtbl[0]));
476 	}
477 	tp->t_head = mp;
478 	tp->t_msgCount = msgCount;
479 	for (i = 0; i < msgCount; i++)
480 		tp->t_msgtbl[i] = &mp[i];
481 }
482 
483 /*
484  * To be called after reading in the new message structures.
485  * It is here as it needs access to current_thread.t_head.
486  */
487 PUBLIC void
488 thread_fix_new_links(struct message *message, int omsgCount, int msgCount)
489 {
490 	int i;
491 	struct message *lastmp;
492 
493 	/* This should only be called at the top level if omsgCount != 0! */
494 	assert(omsgCount == 0 || message->m_plink == NULL);
495 	assert(omsgCount == 0 || message_array.t_msgCount == omsgCount);
496 	assert(message_array.t_head == message);
497 
498 	message_array.t_head = message;
499 	message_array.t_msgCount = msgCount;
500 	assert(message_array.t_msgtbl == NULL);	/* never used */
501 
502 	lastmp = NULL;
503 	if (omsgCount) {
504 		/*
505 		 * Find the end of the toplevel thread.
506 		 */
507 		for (i = 0; i < omsgCount; i++) {
508 			if (message_array.t_head[i].m_depth == 0 &&
509 			    message_array.t_head[i].m_flink == NULL) {
510 				lastmp = &message_array.t_head[i];
511 				break;
512 			}
513 		}
514 #ifndef NDEBUG
515 		/*
516 		 * lastmp better be unique!!!
517 		 */
518 		for (i++; i < omsgCount; i++)
519 			assert(message_array.t_head[i].m_depth != 0 ||
520 			    message_array.t_head[i].m_flink != NULL);
521 		assert(lastmp != NULL);
522 #endif /* NDEBUG */
523 	}
524 	/*
525 	 * Link and index the new messages linearly at depth 0.
526 	 */
527 	for (i = omsgCount; i < msgCount; i++) {
528 		message[i].m_index = i + 1;
529 		message[i].m_depth = 0;
530 		message[i].m_blink = lastmp;
531 		message[i].m_flink = NULL;
532 		message[i].m_clink = NULL;
533 		message[i].m_plink = NULL;
534 		if (lastmp)
535 			lastmp->m_flink = &message[i];
536 		lastmp = &message[i];
537 	}
538 
539 	/*
540 	 * Make sure the current thread is setup correctly.
541 	 */
542 	if (omsgCount == 0) {
543 		thread_init(&current_thread, message, msgCount);
544 	}
545 	else {
546 		/*
547 		 * Make sure current_thread.t_msgtbl is always large
548 		 * enough.
549 		 */
550 		current_thread.t_msgtbl =
551 		    erealloc(current_thread.t_msgtbl,
552 			msgCount * sizeof(*current_thread.t_msgtbl));
553 
554 		assert(current_thread.t_head != NULL);
555 		if (current_thread.t_head->m_depth == 0)
556 			reindex(&current_thread);
557 	}
558 }
559 
560 /************************************************************************/
561 /*
562  * All state changes should go through here!!!
563  */
564 
565 /*
566  * NOTE: It is the caller's responsibility to ensure that the "dot"
567  * will be valid after a state change.  For example, when changing
568  * from exposed to hidden threads, it is necessary to move the dot to
569  * the head of the thread or it will not be seen.  Use thread_top()
570  * for this.  Likewise, use first_visible_message() to locate the
571  * first visible message after a state change.
572  */
573 
574 static state_t
575 set_state(int and_bits, int xor_bits)
576 {
577 	state_t old_state;
578 	old_state = state;
579 	state &= and_bits;
580 	state ^= xor_bits;
581 	reindex(&current_thread);
582 	redepth(&current_thread);
583 	return old_state;
584 }
585 
586 static struct message *
587 first_visible_message(struct message *mp)
588 {
589 	struct message *oldmp;
590 
591 	if (mp == NULL)
592 		mp = current_thread.t_head;
593 
594 	oldmp = mp;
595 	if ((S_IS_RESTRICT(state) && is_tagged(mp)) || mp->m_flag & MDELETED)
596 		mp = next_message(mp);
597 
598 	if (mp == NULL) {
599 		mp = oldmp;
600 		if ((S_IS_RESTRICT(state) && is_tagged(mp)) || mp->m_flag & MDELETED)
601 			mp = prev_message(mp);
602 	}
603 	if (mp == NULL)
604 		mp = current_thread.t_head;
605 
606 	return mp;
607 }
608 
609 static void
610 restore_state(state_t new_state)
611 {
612 	state = new_state;
613 	reindex(&current_thread);
614 	redepth(&current_thread);
615 	dot = first_visible_message(dot);
616 }
617 
618 static struct message *
619 thread_top(struct message *mp)
620 {
621 	while (mp && mp->m_plink) {
622 		if (mp->m_plink->m_clink == current_thread.t_head)
623 			break;
624 		mp = mp->m_plink;
625 	}
626 	return mp;
627 }
628 
629 /************************************************************************/
630 /*
631  * Possibly show the message list.
632  */
633 static void
634 thread_announce(void *v)
635 {
636 	int vec[2];
637 
638 	if (v == NULL)	/* check this here to avoid it before each call */
639 	    return;
640 
641 	if (dot == NULL) {
642 		(void)printf("No applicable messages\n");
643 		return;
644 	}
645 	vec[0] = get_msgnum(dot);
646 	vec[1] = 0;
647 	if (get_msgCount() > 0 && value(ENAME_NOHEADER) == NULL)
648 		(void)headers(vec);
649 	sawcom = 0;	/* so next will print the first message */
650 }
651 
652 /************************************************************************/
653 
654 /*
655  * Flatten out the portion of the thread starting with the given
656  * message.
657  */
658 static void
659 flattencmd_core(struct message *mp)
660 {
661 	struct message **marray;
662 	size_t mcount;
663 	struct message *tp;
664 	struct message *nextmp;
665 	size_t i;
666 
667 	if (mp == NULL)
668 		return;
669 
670 	mcount = 1;
671 	for (tp = next_message(mp); tp && tp->m_depth > mp->m_depth; tp = next_message(tp))
672 		mcount++;
673 
674 	if (tp && tp->m_depth < mp->m_depth)
675 		nextmp = NULL;
676 	else
677 		nextmp = tp;
678 
679 	if (mcount == 1)
680 		return;
681 
682 	marray = csalloc(mcount, sizeof(*marray));
683 	tp = mp;
684 	for (i = 0; i < mcount; i++) {
685 		marray[i] = tp;
686 		tp = next_message(tp);
687 	}
688 	mp->m_clink = NULL;
689 	for (i = 1; i < mcount; i++) {
690 		marray[i]->m_depth = mp->m_depth;
691 		marray[i]->m_plink = mp->m_plink;
692 		marray[i]->m_clink = NULL;
693 		marray[i]->m_blink = marray[i - 1];
694 		marray[i - 1]->m_flink = marray[i];
695 	}
696 	marray[i - 1]->m_flink = nextmp;
697 	if (nextmp)
698 		nextmp->m_blink = marray[i - 1];
699 }
700 
701 /*
702  * Flatten out all thread parts given in the message list, or the
703  * current thread, if none given.
704  */
705 PUBLIC int
706 flattencmd(void *v)
707 {
708 	int *msgvec;
709 	int *ip;
710 
711 	msgvec = v;
712 
713 	if (*msgvec) { /* a message was supplied */
714 		for (ip = msgvec; *ip; ip++) {
715 			struct message *mp;
716 			mp = get_message(*ip);
717 			if (mp != NULL)
718 				flattencmd_core(mp);
719 		}
720 	}
721 	else { /* no message given - flatten current thread */
722 		struct message *mp;
723 		for (mp = first_message(current_thread.t_head);
724 		     mp; mp = next_message(mp))
725 			flattencmd_core(mp);
726 	}
727 	redepth(&current_thread);
728 	thread_announce(v);
729 	return 0;
730 }
731 
732 
733 /************************************************************************/
734 /*
735  * The basic sort structure.  For each message the index and key
736  * fields are set.  The key field is used for the basic sort and the
737  * index is used to ensure that the order from the current thread is
738  * maintained when the key compare is equal.
739  */
740 struct key_sort_s {
741 	struct message *mp; /* the message the following refer to */
742 	union {
743 		char   *str;	/* string sort key (typically a field or address) */
744 		long   lines;	/* a long sort key (typically a message line count) */
745 		off_t  size;	/* a size sort key (typically the message size) */
746 		time_t time;	/* a time sort key (typically from date or headline) */
747 	} key;
748 	int    index;	/* index from of the current thread before sorting */
749 	/* XXX - do we really want index?  It is always set to mp->m_index */
750 };
751 
752 /*
753  * This is the compare function obtained from the key_tbl[].  It is
754  * used by thread_array() to identify the end of the thread and by
755  * qsort_cmpfn() to do the basic sort.
756  */
757 static struct {
758 	int inv;
759 	int (*fn)(const void *, const void *);
760 } cmp;
761 
762 /*
763  * The routine passed to qsort.  Note that cmpfn must be set first!
764  */
765 static int
766 qsort_cmpfn(const void *left, const void *right)
767 {
768 	int delta;
769 	const struct key_sort_s *lp = left;
770 	const struct key_sort_s *rp = right;
771 
772 	delta = cmp.fn(left, right);
773 	return delta ? cmp.inv ? - delta : delta : lp->index - rp->index;
774 }
775 
776 static void
777 link_array(struct key_sort_s *marray, size_t mcount)
778 {
779 	size_t i;
780 	struct message *lastmp;
781 	lastmp = NULL;
782 	for (i = 0; i < mcount; i++) {
783 		marray[i].mp->m_index = i + 1;
784 		marray[i].mp->m_blink = lastmp;
785 		marray[i].mp->m_flink = NULL;
786 		if (lastmp)
787 			lastmp->m_flink = marray[i].mp;
788 		lastmp = marray[i].mp;
789 	}
790 	if (current_thread.t_head->m_plink)
791 		current_thread.t_head->m_plink->m_clink = marray[0].mp;
792 
793 	current_thread.t_head = marray[0].mp;
794 }
795 
796 static void
797 cut_array(struct key_sort_s *marray, size_t beg, size_t end)
798 {
799 	size_t i;
800 
801 	if (beg + 1 < end) {
802 		assert(marray[beg].mp->m_clink == NULL);
803 
804 		marray[beg].mp->m_clink = marray[beg + 1].mp;
805 		marray[beg + 1].mp->m_blink = NULL;
806 
807 		marray[beg].mp->m_flink = marray[end].mp;
808 		if (marray[end].mp)
809 			marray[end].mp->m_blink = marray[beg].mp;
810 
811 		marray[end - 1].mp->m_flink = NULL;
812 
813 		for (i = beg + 1; i < end; i++)
814 			marray[i].mp->m_plink = marray[beg].mp;
815 	}
816 }
817 
818 static void
819 thread_array(struct key_sort_s *marray, size_t mcount, int cutit)
820 {
821 	struct message *parent;
822 
823 	parent = marray[0].mp->m_plink;
824 	qsort(marray, mcount, sizeof(*marray), qsort_cmpfn);
825 	link_array(marray, mcount);
826 
827 	if (cutit) {
828 		size_t i, j;
829 		/*
830 		 * Flatten out the array.
831 		 */
832 		for (i = 0; i < mcount; i++) {
833 			marray[i].mp->m_plink = parent;
834 			marray[i].mp->m_clink = NULL;
835 		}
836 
837 		/*
838 		 * Now chop it up.  There is really only one level here.
839 		 */
840 		i = 0;
841 		for (j = 1; j < mcount; j++) {
842 			if (cmp.fn(&marray[i], &marray[j]) != 0) {
843 				cut_array(marray, i, j);
844 				i = j;
845 			}
846 		}
847 		cut_array(marray, i, j);
848 	}
849 }
850 
851 /************************************************************************/
852 /*
853  * thread_on_reference() is the core reference threading routine.  It
854  * is not a command itself by called by threadcmd().
855  */
856 
857 static void
858 adopt_child(struct message *parent, struct message *child)
859 {
860 	/*
861 	 * Unhook the child from its current location.
862 	 */
863 	if (child->m_blink != NULL) {
864 		child->m_blink->m_flink = child->m_flink;
865 	}
866 	if (child->m_flink != NULL) {
867 		child->m_flink->m_blink = child->m_blink;
868 	}
869 
870 	/*
871 	 * Link the child to the parent.
872 	 */
873 	if (parent->m_clink == NULL) { /* parent has no child */
874 		parent->m_clink = child;
875 		child->m_blink = NULL;
876 	}
877 	else { /* add message to end of parent's child's flist */
878 		struct message *t;
879 		for (t = parent->m_clink; t && t->m_flink; t = t->m_flink)
880 			continue;
881 		t->m_flink = child;
882 		child->m_blink = t;
883 	}
884 	child->m_flink = NULL;
885 	child->m_plink = parent;
886 }
887 
888 /*
889  * Get the parent ID for a message (if there is one).
890  *
891  * See RFC 2822, sec 3.6.4.
892  *
893  * Many mailers seem to screw up the In-Reply-To: and/or
894  * References: fields, generally by omitting one or both.
895  *
896  * We give preference to the "References" field.  If it does
897  * not exist, try the "In-Reply-To" field.  If neither exist,
898  * then the message is either not a reply or someone isn't
899  * adding the necessary fields, so skip it.
900  */
901 static char *
902 get_parent_id(struct message *mp)
903 {
904 	struct name *refs;
905 
906 	if ((refs = extract(hfield("references", mp), 0)) != NULL) {
907 		char *id;
908 		while (refs->n_flink)
909 			refs = refs->n_flink;
910 
911 		id = skin(refs->n_name);
912 		if (*id != '\0')
913 			return id;
914 	}
915 
916 	return skin(hfield("in-reply-to", mp));
917 }
918 
919 /*
920  * Thread on the "In-Reply-To" and "Reference" fields.  This is the
921  * normal way to thread.
922  */
923 static void
924 thread_on_reference(struct message *mp)
925 {
926 	struct {
927 		struct message *mp;
928 		char *message_id;
929 		char *parent_id;
930 	} *marray;
931 	struct message *parent;
932 	state_t oldstate;
933 	size_t mcount, i;
934 
935 	assert(mp == current_thread.t_head);
936 
937 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
938 
939 	mcount = get_msgCount();
940 
941 	if (mcount < 2)	/* it's hard to thread so few messages! */
942 		goto done;
943 
944 	marray = csalloc(mcount + 1, sizeof(*marray));
945 
946 	/*
947 	 * Load up the array (skin where necessary).
948 	 *
949 	 * With a 40K message file, most of the time is spent here,
950 	 * not in the search loop below.
951 	 */
952 	for (i = 0; i < mcount; i++) {
953 		marray[i].mp = mp;
954 		marray[i].message_id = skin(hfield("message-id", mp));
955 		marray[i].parent_id = get_parent_id(mp);
956 		mp = next_message(mp);
957 	}
958 
959 	/*
960 	 * Save the old parent.
961 	 */
962 	parent = marray[0].mp->m_plink;
963 
964 	/*
965 	 * flatten the array.
966 	 */
967 	marray[0].mp->m_clink = NULL;
968 	for (i = 1; i < mcount; i++) {
969 		marray[i].mp->m_depth = marray[0].mp->m_depth;
970 		marray[i].mp->m_plink = marray[0].mp->m_plink;
971 		marray[i].mp->m_clink = NULL;
972 		marray[i].mp->m_blink = marray[i - 1].mp;
973 		marray[i - 1].mp->m_flink = marray[i].mp;
974 	}
975 	marray[i - 1].mp->m_flink = NULL;
976 
977 	/*
978 	 * Walk the array hooking up the replies with their parents.
979 	 */
980 	for (i = 0; i < mcount; i++) {
981 		struct message *child;
982 		char *parent_id;
983 		size_t j;
984 
985 		if ((parent_id = marray[i].parent_id) == NULL)
986 			continue;
987 
988 		child = marray[i].mp;
989 
990 		/*
991 		 * Look for the parent message and link this one in
992 		 * appropriately.
993 		 *
994 		 * XXX - This will not scale nicely, though it does
995 		 * not appear to be the dominant loop even with 40K
996 		 * messages.  If this becomes a problem, implement a
997 		 * binary search.
998 		 */
999 		for (j = 0; j < mcount; j++) {
1000 			/* message_id will be NULL on mbox files */
1001 			if (marray[i].message_id == NULL)
1002 				continue;
1003 
1004 			if (equal(marray[j].message_id, parent_id)) {
1005 				/*
1006 				 * The child is at the top level.  If
1007 				 * it is being adopted and it was top
1008 				 * left (current_thread.t_head), then
1009 				 * its right sibling is the new top
1010 				 * left (current_thread.t_head).
1011 				 */
1012 				if (current_thread.t_head == child) {
1013 					current_thread.t_head = child->m_flink;
1014 					assert(current_thread.t_head != NULL);
1015 				}
1016 				adopt_child(marray[j].mp, child);
1017 				break;
1018 			}
1019 		}
1020 	}
1021 
1022 	if (parent)
1023 		parent->m_clink = current_thread.t_head;
1024 	/*
1025 	 * If the old state is not exposed, reset the dot to the head
1026 	 * of the thread it lived in, so it will be in a valid spot
1027 	 * when things are re-hidden.
1028 	 */
1029 	if (!S_IS_EXPOSE(oldstate))
1030 		dot = thread_top(dot);
1031  done:
1032 	restore_state(oldstate);
1033 }
1034 
1035 /************************************************************************/
1036 /*
1037  * Tagging commands.
1038  */
1039 static int
1040 tag1(int *msgvec, int and_bits, int xor_bits)
1041 {
1042 	int *ip;
1043 
1044 	for (ip = msgvec; *ip != 0; ip++)
1045 		(void)set_m_flag(*ip, and_bits, xor_bits);
1046 
1047 	reindex(&current_thread);
1048 /*	thread_announce(v); */
1049 	return 0;
1050 }
1051 
1052 /*
1053  * Tag the current message dot or a message list.
1054  */
1055 PUBLIC int
1056 tagcmd(void *v)
1057 {
1058 	return tag1(v, ~MTAGGED, MTAGGED);
1059 }
1060 
1061 /*
1062  * Untag the current message dot or a message list.
1063  */
1064 PUBLIC int
1065 untagcmd(void *v)
1066 {
1067 	return tag1(v, ~MTAGGED, 0);
1068 }
1069 
1070 /*
1071  * Invert all tags in the message list.
1072  */
1073 PUBLIC int
1074 invtagscmd(void *v)
1075 {
1076 	return tag1(v, ~0, MTAGGED);
1077 }
1078 
1079 /*
1080  * Tag all messages below the current dot or below a specified
1081  * message.
1082  */
1083 PUBLIC int
1084 tagbelowcmd(void *v)
1085 {
1086 	int *msgvec;
1087 	struct message *mp;
1088 	state_t oldstate;
1089 	int depth;
1090 
1091 	msgvec = v;
1092 
1093 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
1094 	mp = get_message(*msgvec);
1095 	if (mp) {
1096 		depth = mp->m_depth;
1097 		for (mp = first_message(current_thread.t_head); mp; mp = next_message(mp))
1098 			if (mp->m_depth > depth ) {
1099 				mp->m_flag |= MTAGGED;
1100 				touch(mp);
1101 			}
1102 	}
1103 	/* dot is OK */
1104 	restore_state(oldstate);
1105 /*	thread_announce(v); */
1106 	return 0;
1107 }
1108 
1109 /*
1110  * Do not display the tagged messages.
1111  */
1112 PUBLIC int
1113 hidetagscmd(void *v)
1114 {
1115 	(void)set_state(~S_RESTRICT, S_RESTRICT);	/* restrict on */
1116 	dot = first_visible_message(dot);
1117 	thread_announce(v);
1118 	return 0;
1119 }
1120 
1121 /*
1122  * Display the tagged messages.
1123  */
1124 PUBLIC int
1125 showtagscmd(void *v)
1126 {
1127 	(void)set_state(~S_RESTRICT, 0);		/* restrict off */
1128 	dot = first_visible_message(dot);
1129 	thread_announce(v);
1130 	return 0;
1131 }
1132 
1133 /************************************************************************/
1134 /*
1135  * Basic threading commands.
1136  */
1137 /*
1138  * Show the threads.
1139  */
1140 PUBLIC int
1141 exposecmd(void *v)
1142 {
1143 	(void)set_state(~S_EXPOSE, S_EXPOSE);	/* expose on */
1144 	dot = first_visible_message(dot);
1145 	thread_announce(v);
1146 	return 0;
1147 }
1148 
1149 /*
1150  * Hide the threads.
1151  */
1152 PUBLIC int
1153 hidecmd(void *v)
1154 {
1155 	dot = thread_top(dot);
1156 	(void)set_state(~S_EXPOSE, 0);		/* expose off */
1157 	dot = first_visible_message(dot);
1158 	thread_announce(v);
1159 	return 0;
1160 }
1161 
1162 /*
1163  * Up one level in the thread tree.  Go up multiple levels if given an
1164  * argument.
1165  */
1166 PUBLIC int
1167 upcmd(void *v)
1168 {
1169 	char *str;
1170 	int upcnt;
1171 	int upone;
1172 
1173 	str = v;
1174 	str = skip_WSP(str);
1175 	if (*str == '\0')
1176 		upcnt = 1;
1177 	else
1178 		upcnt = atoi(str);
1179 
1180 	if (upcnt < 1) {
1181 		(void)printf("Sorry, argument must be > 0.\n");
1182 		return 0;
1183 	}
1184 	if (dot == NULL) {
1185 		(void)printf("No applicable messages\n");
1186 		return 0;
1187 	}
1188 	if (dot->m_plink == NULL) {
1189 		(void)printf("top thread\n");
1190 		return 0;
1191 	}
1192 	upone = 0;
1193 	while (upcnt-- > 0) {
1194 		struct message *parent;
1195 		parent = current_thread.t_head->m_plink;
1196 		if (parent == NULL) {
1197 			(void)printf("top thread\n");
1198 			break;
1199 		}
1200 		else {
1201 			struct message *mp;
1202 			assert(current_thread.t_head->m_depth > 0);
1203 			for (mp = parent; mp && mp->m_blink; mp = mp->m_blink)
1204 				continue;
1205 			current_thread.t_head = mp;
1206 			dot = parent;
1207 			upone = 1;
1208 		}
1209 	}
1210 	if (upone) {
1211 		reindex(&current_thread);
1212 		thread_announce(v);
1213 	}
1214 	return 0;
1215 }
1216 
1217 /*
1218  * Go down one level in the thread tree from the current dot or a
1219  * given message number if given.
1220  */
1221 PUBLIC int
1222 downcmd(void *v)
1223 {
1224 	struct message *child;
1225 	struct message *mp;
1226 	int *msgvec = v;
1227 
1228 	if ((mp = get_message(*msgvec)) == NULL ||
1229 	    (child = mp->m_clink) == NULL)
1230 		(void)printf("no sub-thread\n");
1231 	else {
1232 		current_thread.t_head = child;
1233 		dot = child;
1234 		reindex(&current_thread);
1235 		thread_announce(v);
1236 	}
1237 	return 0;
1238 }
1239 
1240 /*
1241  * Set the current thread level to the current dot or to the message
1242  * if given.
1243  */
1244 PUBLIC int
1245 tsetcmd(void *v)
1246 {
1247 	struct message *mp;
1248 	int *msgvec = v;
1249 
1250 	if ((mp = get_message(*msgvec)) == NULL)
1251 		(void)printf("invalid message\n");
1252 	else {
1253 		for (/*EMPTY*/; mp->m_blink; mp = mp->m_blink)
1254 			continue;
1255 		current_thread.t_head = mp;
1256 		reindex(&current_thread);
1257 		thread_announce(v);
1258 	}
1259 	return 0;
1260 }
1261 
1262 /*
1263  * Reverse the current thread order.  If threaded, it only operates on
1264  * the heads.
1265  */
1266 static void
1267 reversecmd_core(struct thread_s *tp)
1268 {
1269 	struct message *thread_start;
1270 	struct message *mp;
1271 	struct message *lastmp;
1272 	struct message *old_flink;
1273 
1274 	thread_start = tp->t_head;
1275 
1276 	assert(thread_start->m_blink == NULL);
1277 
1278 	lastmp = NULL;
1279 	for (mp = thread_start; mp; mp = old_flink) {
1280 		old_flink = mp->m_flink;
1281 		mp->m_flink = mp->m_blink;
1282 		mp->m_blink = old_flink;
1283 		lastmp = mp;
1284 	}
1285 	if (thread_start->m_plink)
1286 		thread_start->m_plink->m_clink = lastmp;
1287 
1288 	current_thread.t_head = lastmp;
1289 	reindex(tp);
1290 }
1291 
1292 PUBLIC int
1293 reversecmd(void *v)
1294 {
1295 	reversecmd_core(&current_thread);
1296 	thread_announce(v);
1297 	return 0;
1298 }
1299 
1300 
1301 /*
1302  * Get threading and sorting modifiers.
1303  */
1304 #define MF_IGNCASE	1	/* ignore case when sorting */
1305 #define MF_REVERSE	2	/* reverse sort direction */
1306 #define MF_SKIN		4	/* "skin" the field to remove comments */
1307 static int
1308 get_modifiers(char **str)
1309 {
1310 	int modflags;
1311 	char *p;
1312 
1313 	modflags = 0;
1314 	for (p = *str; p && *p; p++) {
1315 		switch (*p) {
1316 		case '!':
1317 			modflags |= MF_REVERSE;
1318 			break;
1319 		case '^':
1320 			modflags |= MF_IGNCASE;
1321 			break;
1322 		case '-':
1323 			modflags |= MF_SKIN;
1324 			break;
1325 		case ' ':
1326 		case '\t':
1327 			break;
1328 		default:
1329 			goto done;
1330 		}
1331 	}
1332  done:
1333 	*str = p;
1334 	return modflags;
1335 }
1336 
1337 /************************************************************************/
1338 /*
1339  * The key_sort_s compare routines.
1340  */
1341 
1342 static int
1343 keystrcmp(const void *left, const void *right)
1344 {
1345 	const struct key_sort_s *lp = left;
1346 	const struct key_sort_s *rp = right;
1347 
1348 	lp = left;
1349 	rp = right;
1350 
1351 	if (rp->key.str == NULL && lp->key.str == NULL)
1352 		return 0;
1353 	else if (rp->key.str == NULL)
1354 		return -1;
1355 	else if (lp->key.str == NULL)
1356 		return 1;
1357 	else
1358 		return strcmp(lp->key.str, rp->key.str);
1359 }
1360 
1361 static int
1362 keystrcasecmp(const void *left, const void *right)
1363 {
1364 	const struct key_sort_s *lp = left;
1365 	const struct key_sort_s *rp = right;
1366 
1367 	if (rp->key.str == NULL && lp->key.str == NULL)
1368 		return 0;
1369 	else if (rp->key.str == NULL)
1370 		return -1;
1371 	else if (lp->key.str == NULL)
1372 		return 1;
1373 	else
1374 		return strcasecmp(lp->key.str, rp->key.str);
1375 }
1376 
1377 static int
1378 keylongcmp(const void *left, const void *right)
1379 {
1380 	const struct key_sort_s *lp = left;
1381 	const struct key_sort_s *rp = right;
1382 
1383 	if (lp->key.lines > rp->key.lines)
1384 		return 1;
1385 
1386 	if (lp->key.lines < rp->key.lines)
1387 		return -1;
1388 
1389 	return 0;
1390 }
1391 
1392 static int
1393 keyoffcmp(const void *left, const void *right)
1394 {
1395 	const struct key_sort_s *lp = left;
1396 	const struct key_sort_s *rp = right;
1397 
1398 	if (lp->key.size > rp->key.size)
1399 		return 1;
1400 
1401 	if (lp->key.size < rp->key.size)
1402 		return -1;
1403 
1404 	return 0;
1405 }
1406 
1407 static int
1408 keytimecmp(const void *left, const void *right)
1409 {
1410 	double delta;
1411 	const struct key_sort_s *lp = left;
1412 	const struct key_sort_s *rp = right;
1413 
1414 	delta = difftime(lp->key.time, rp->key.time);
1415 	if (delta > 0)
1416 		return 1;
1417 
1418 	if (delta < 0)
1419 		return -1;
1420 
1421 	return 0;
1422 }
1423 
1424 /************************************************************************
1425  * key_sort_s loading routines.
1426  */
1427 static void
1428 field_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1429     const char *key, int skin_it)
1430 {
1431 	size_t i;
1432 	for (i = 0; i < mcount; i++) {
1433 		marray[i].mp = mp;
1434 		marray[i].key.str =
1435 		    skin_it ? skin(hfield(key, mp)) : hfield(key, mp);
1436 		marray[i].index = mp->m_index;
1437 		mp = next_message(mp);
1438 	}
1439 }
1440 
1441 static void
1442 subj_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1443     const char *key __unused, int flags __unused)
1444 {
1445 	size_t i;
1446 #ifdef __lint__
1447 	flags = flags;
1448 	key = key;
1449 #endif
1450 	for (i = 0; i < mcount; i++) {
1451 		char *subj = hfield(key, mp);
1452 		while( strncasecmp(subj, "Re:", 3) == 0 )
1453 			subj = skip_WSP(subj + 3);
1454 		marray[i].mp = mp;
1455 		marray[i].key.str = subj;
1456 		marray[i].index = mp->m_index;
1457 		mp = next_message(mp);
1458 	}
1459 }
1460 
1461 
1462 static void
1463 lines_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1464     const char *key __unused, int flags)
1465 {
1466 	size_t i;
1467 	int use_blines;
1468 	int use_hlines;
1469 #ifdef __lint__
1470 	key = key;
1471 #endif
1472 #define HLINES	1
1473 #define BLINES	2
1474 #define TLINES	3
1475 	use_hlines = flags == HLINES;
1476 	use_blines = flags == BLINES;
1477 
1478 	for (i = 0; i < mcount; i++) {
1479 		marray[i].mp = mp;
1480 		marray[i].key.lines = use_hlines ? mp->m_lines - mp->m_blines :
1481 		    use_blines ? mp->m_blines : mp->m_lines;
1482 		marray[i].index = mp->m_index;
1483 		mp = next_message(mp);
1484 	}
1485 }
1486 
1487 static void
1488 size_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1489     const char *key __unused, int flags __unused)
1490 {
1491 	size_t i;
1492 #ifdef __lint__
1493 	flags = flags;
1494 	key = key;
1495 #endif
1496 	for (i = 0; i < mcount; i++) {
1497 		marray[i].mp = mp;
1498 		marray[i].key.size = mp->m_size;
1499 		marray[i].index = mp->m_index;
1500 		mp = next_message(mp);
1501 	}
1502 }
1503 
1504 static void __unused
1505 date_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1506     const char *key __unused, int flags)
1507 {
1508 	size_t i;
1509 	int use_hl_date;
1510 	int zero_hour_min_sec;
1511 #ifdef __lint__
1512 	key = key;
1513 #endif
1514 #define RDAY 1
1515 #define SDAY 2
1516 #define RDATE 3
1517 #define SDATE 4
1518 	use_hl_date       = (flags == RDAY || flags == RDATE);
1519 	zero_hour_min_sec = (flags == RDAY || flags == SDAY);
1520 
1521 	for (i = 0; i < mcount; i++) {
1522 		struct tm tm;
1523 		(void)dateof(&tm, mp, use_hl_date);
1524 		if (zero_hour_min_sec) {
1525 			tm.tm_sec = 0;
1526 			tm.tm_min = 0;
1527 			tm.tm_hour = 0;
1528 		}
1529 		marray[i].mp = mp;
1530 		marray[i].key.time = mktime(&tm);
1531 		marray[i].index = mp->m_index;
1532 		mp = next_message(mp);
1533 	}
1534 }
1535 
1536 static void
1537 from_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1538     const char *key __unused, int flags __unused)
1539 {
1540 	size_t i;
1541 #ifdef __lint__
1542 	flags = flags;
1543 	key = key;
1544 #endif
1545 	for (i = 0; i < mcount; i++) {
1546 		marray[i].mp = mp;
1547 		marray[i].key.str = nameof(mp, 0);
1548 		marray[i].index = mp->m_index;
1549 		mp = next_message(mp);
1550 	}
1551 }
1552 
1553 /************************************************************************
1554  * The master table that controls all sorting and threading.
1555  */
1556 static const struct key_tbl_s {
1557 	const char *key;
1558 	void (*loadfn)(struct key_sort_s *, size_t, struct message *, const char *, int);
1559 	int flags;
1560 	int (*cmpfn)(const void*, const void*);
1561 	int (*casecmpfn)(const void*, const void*);
1562 } key_tbl[] = {
1563 	{"blines",	lines_load,	BLINES,	keylongcmp,	keylongcmp},
1564 	{"hlines",	lines_load,	HLINES,	keylongcmp,	keylongcmp},
1565 	{"tlines",	lines_load,	TLINES,	keylongcmp,	keylongcmp},
1566 	{"size",	size_load,	0,	keyoffcmp,	keyoffcmp},
1567 	{"sday",	date_load,	SDAY,	keytimecmp,	keytimecmp},
1568 	{"rday",	date_load,	RDAY,	keytimecmp,	keytimecmp},
1569 	{"sdate",	date_load,	SDATE,	keytimecmp,	keytimecmp},
1570 	{"rdate",	date_load,	RDATE,	keytimecmp,	keytimecmp},
1571 	{"from",	from_load,	0,	keystrcasecmp,	keystrcasecmp},
1572 	{"subject",	subj_load,	0,	keystrcmp,	keystrcasecmp},
1573 	{NULL,		field_load,	0,	keystrcmp,	keystrcasecmp},
1574 };
1575 
1576 #ifdef USE_EDITLINE
1577 /*
1578  * This is for use in complete.c to get the list of threading key
1579  * names without exposing the key_tbl[].  The first name is returned
1580  * if called with a pointer to a NULL pointer.  Subsequent calls with
1581  * the same cookie give successive names.  A NULL return indicates the
1582  * end of the list.
1583  */
1584 PUBLIC const char *
1585 thread_next_key_name(const void **cookie)
1586 {
1587 	const struct key_tbl_s *kp;
1588 
1589 	kp = *cookie;
1590 	if (kp == NULL)
1591 		kp = key_tbl;
1592 
1593 	*cookie = kp->key ? &kp[1] : NULL;
1594 
1595 	return kp->key;
1596 }
1597 #endif /* USE_EDITLINE */
1598 
1599 static const struct key_tbl_s *
1600 get_key(const char *key)
1601 {
1602 	const struct key_tbl_s *kp;
1603 	for (kp = key_tbl; kp->key != NULL; kp++)
1604 		if (strcmp(kp->key, key) == 0)
1605 			return kp;
1606 	return kp;
1607 }
1608 
1609 static int (*
1610 get_cmpfn(const struct key_tbl_s *kp, int ignorecase)
1611 )(const void*, const void*)
1612 {
1613 	if (ignorecase)
1614 		return kp->casecmpfn;
1615 	else
1616 		return kp->cmpfn;
1617 }
1618 
1619 static void
1620 thread_current_on(char *str, int modflags, int cutit)
1621 {
1622 	const struct key_tbl_s *kp;
1623 	struct key_sort_s *marray;
1624 	size_t mcount;
1625 	state_t oldstate;
1626 
1627 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), cutit ? S_EXPOSE : 0);
1628 
1629 	kp = get_key(str);
1630 	mcount = get_msgCount();
1631 	marray = csalloc(mcount + 1, sizeof(*marray));
1632 	kp->loadfn(marray, mcount, current_thread.t_head, str,
1633 	    kp->flags ? kp->flags : modflags & MF_SKIN);
1634 	cmp.fn = get_cmpfn(kp, modflags & MF_IGNCASE);
1635 	cmp.inv = modflags & MF_REVERSE;
1636 	thread_array(marray, mcount, cutit);
1637 
1638 	if (!S_IS_EXPOSE(oldstate))
1639 		dot = thread_top(dot);
1640 	restore_state(oldstate);
1641 }
1642 
1643 /*
1644  * The thread command.  Thread the current thread on its references or
1645  * on a specified field.
1646  */
1647 PUBLIC int
1648 threadcmd(void *v)
1649 {
1650 	char *str;
1651 
1652 	str = v;
1653 	if (*str == '\0')
1654 		thread_on_reference(current_thread.t_head);
1655 	else {
1656 		int modflags;
1657 		modflags = get_modifiers(&str);
1658 		thread_current_on(str, modflags, 1);
1659 	}
1660 	thread_announce(v);
1661 	return 0;
1662 }
1663 
1664 /*
1665  * Remove all threading information, reverting to the startup state.
1666  */
1667 PUBLIC int
1668 unthreadcmd(void *v)
1669 {
1670 	thread_fix_new_links(message_array.t_head, 0, message_array.t_msgCount);
1671 	thread_announce(v);
1672 	return 0;
1673 }
1674 
1675 /*
1676  * The sort command.
1677  */
1678 PUBLIC int
1679 sortcmd(void *v)
1680 {
1681 	int modflags;
1682 	char *str;
1683 
1684 	str = v;
1685 	modflags = get_modifiers(&str);
1686 	if (*str != '\0')
1687 		thread_current_on(str, modflags, 0);
1688 	else {
1689 		if (modflags & MF_REVERSE)
1690 			reversecmd_core(&current_thread);
1691 		else {
1692 			(void)printf("sort on what?\n");
1693 			return 0;
1694 		}
1695 	}
1696 	thread_announce(v);
1697 	return 0;
1698 }
1699 
1700 
1701 /*
1702  * Delete duplicate messages (based on their "Message-Id" field).
1703  */
1704 /*ARGSUSED*/
1705 PUBLIC int
1706 deldupscmd(void *v __unused)
1707 {
1708 	struct message *mp;
1709 	int depth;
1710 	state_t oldstate;
1711 
1712 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
1713 
1714 	thread_current_on(__UNCONST("Message-Id"), 0, 1);
1715 	reindex(&current_thread);
1716 	redepth(&current_thread);
1717 	depth = current_thread.t_head->m_depth;
1718 	for (mp = first_message(current_thread.t_head); mp; mp = next_message(mp)) {
1719 		if (mp->m_depth > depth ) {
1720 			mp->m_flag &= ~(MPRESERVE | MSAVED | MBOX);
1721 			mp->m_flag |= MDELETED | MTOUCH;
1722 			touch(mp);
1723 		}
1724 	}
1725 	dot = thread_top(dot);	/* do this irrespective of the oldstate */
1726 	restore_state(oldstate);
1727 /*	thread_announce(v); */
1728 	return 0;
1729 }
1730 
1731 #endif /* THREAD_SUPPORT */
1732