xref: /netbsd-src/usr.bin/mail/thread.c (revision 865c57e0098351fba0d2d2a97b33e7e0270e62c6)
1 /*	$NetBSD: thread.c,v 1.15 2023/08/10 20:36:28 mrg 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.15 2023/08/10 20:36:28 mrg 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, ptrdiff_t off, int omsgCount)
444 {
445 	int i;
446 	if (off == 0)
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 {\
454 	p = nmessage + off;\
455   } while (0)
456 
457 	FIX_LINK(current_thread.t_head);
458 	for (i = 0; i < omsgCount; i++) {
459 		FIX_LINK(nmessage[i].m_blink);
460 		FIX_LINK(nmessage[i].m_flink);
461 		FIX_LINK(nmessage[i].m_clink);
462 		FIX_LINK(nmessage[i].m_plink);
463 	}
464 	for (i = 0; i < current_thread.t_msgCount; i++)
465 		FIX_LINK(current_thread.t_msgtbl[i]);
466 
467 # undef FIX_LINK
468 }
469 
470 static void
471 thread_init(struct thread_s *tp, struct message *mp, int msgCount)
472 {
473 	int i;
474 
475 	if (tp->t_msgtbl == NULL || msgCount > tp->t_msgCount) {
476 		if (tp->t_msgtbl)
477 			free(tp->t_msgtbl);
478 		tp->t_msgtbl = ecalloc((size_t)msgCount, sizeof(tp->t_msgtbl[0]));
479 	}
480 	tp->t_head = mp;
481 	tp->t_msgCount = msgCount;
482 	for (i = 0; i < msgCount; i++)
483 		tp->t_msgtbl[i] = &mp[i];
484 }
485 
486 /*
487  * To be called after reading in the new message structures.
488  * It is here as it needs access to current_thread.t_head.
489  */
490 PUBLIC void
491 thread_fix_new_links(struct message *message, int omsgCount, int msgCount)
492 {
493 	int i;
494 	struct message *lastmp;
495 
496 	/* This should only be called at the top level if omsgCount != 0! */
497 	assert(omsgCount == 0 || message->m_plink == NULL);
498 	assert(omsgCount == 0 || message_array.t_msgCount == omsgCount);
499 	assert(message_array.t_head == message);
500 
501 	message_array.t_head = message;
502 	message_array.t_msgCount = msgCount;
503 	assert(message_array.t_msgtbl == NULL);	/* never used */
504 
505 	lastmp = NULL;
506 	if (omsgCount) {
507 		/*
508 		 * Find the end of the toplevel thread.
509 		 */
510 		for (i = 0; i < omsgCount; i++) {
511 			if (message_array.t_head[i].m_depth == 0 &&
512 			    message_array.t_head[i].m_flink == NULL) {
513 				lastmp = &message_array.t_head[i];
514 				break;
515 			}
516 		}
517 #ifndef NDEBUG
518 		/*
519 		 * lastmp better be unique!!!
520 		 */
521 		for (i++; i < omsgCount; i++)
522 			assert(message_array.t_head[i].m_depth != 0 ||
523 			    message_array.t_head[i].m_flink != NULL);
524 		assert(lastmp != NULL);
525 #endif /* NDEBUG */
526 	}
527 	/*
528 	 * Link and index the new messages linearly at depth 0.
529 	 */
530 	for (i = omsgCount; i < msgCount; i++) {
531 		message[i].m_index = i + 1;
532 		message[i].m_depth = 0;
533 		message[i].m_blink = lastmp;
534 		message[i].m_flink = NULL;
535 		message[i].m_clink = NULL;
536 		message[i].m_plink = NULL;
537 		if (lastmp)
538 			lastmp->m_flink = &message[i];
539 		lastmp = &message[i];
540 	}
541 
542 	/*
543 	 * Make sure the current thread is setup correctly.
544 	 */
545 	if (omsgCount == 0) {
546 		thread_init(&current_thread, message, msgCount);
547 	}
548 	else {
549 		/*
550 		 * Make sure current_thread.t_msgtbl is always large
551 		 * enough.
552 		 */
553 		current_thread.t_msgtbl =
554 		    erealloc(current_thread.t_msgtbl,
555 			msgCount * sizeof(*current_thread.t_msgtbl));
556 
557 		assert(current_thread.t_head != NULL);
558 		if (current_thread.t_head->m_depth == 0)
559 			reindex(&current_thread);
560 	}
561 }
562 
563 /************************************************************************/
564 /*
565  * All state changes should go through here!!!
566  */
567 
568 /*
569  * NOTE: It is the caller's responsibility to ensure that the "dot"
570  * will be valid after a state change.  For example, when changing
571  * from exposed to hidden threads, it is necessary to move the dot to
572  * the head of the thread or it will not be seen.  Use thread_top()
573  * for this.  Likewise, use first_visible_message() to locate the
574  * first visible message after a state change.
575  */
576 
577 static state_t
578 set_state(int and_bits, int xor_bits)
579 {
580 	state_t old_state;
581 	old_state = state;
582 	state &= and_bits;
583 	state ^= xor_bits;
584 	reindex(&current_thread);
585 	redepth(&current_thread);
586 	return old_state;
587 }
588 
589 static struct message *
590 first_visible_message(struct message *mp)
591 {
592 	struct message *oldmp;
593 
594 	if (mp == NULL)
595 		mp = current_thread.t_head;
596 
597 	if (mp == NULL)
598 		return NULL;
599 
600 	oldmp = mp;
601 	if ((S_IS_RESTRICT(state) && is_tagged(mp)) || mp->m_flag & MDELETED)
602 		mp = next_message(mp);
603 
604 	if (mp == NULL) {
605 		mp = oldmp;
606 		if ((S_IS_RESTRICT(state) && is_tagged(mp)) || mp->m_flag & MDELETED)
607 			mp = prev_message(mp);
608 	}
609 	if (mp == NULL)
610 		mp = current_thread.t_head;
611 
612 	return mp;
613 }
614 
615 static void
616 restore_state(state_t new_state)
617 {
618 	state = new_state;
619 	reindex(&current_thread);
620 	redepth(&current_thread);
621 	dot = first_visible_message(dot);
622 }
623 
624 static struct message *
625 thread_top(struct message *mp)
626 {
627 	while (mp && mp->m_plink) {
628 		if (mp->m_plink->m_clink == current_thread.t_head)
629 			break;
630 		mp = mp->m_plink;
631 	}
632 	return mp;
633 }
634 
635 /************************************************************************/
636 /*
637  * Possibly show the message list.
638  */
639 static void
640 thread_announce(void *v)
641 {
642 	int vec[2];
643 
644 	if (v == NULL)	/* check this here to avoid it before each call */
645 	    return;
646 
647 	if (dot == NULL) {
648 		(void)printf("No applicable messages\n");
649 		return;
650 	}
651 	vec[0] = get_msgnum(dot);
652 	vec[1] = 0;
653 	if (get_msgCount() > 0 && value(ENAME_NOHEADER) == NULL)
654 		(void)headers(vec);
655 	sawcom = 0;	/* so next will print the first message */
656 }
657 
658 /************************************************************************/
659 
660 /*
661  * Flatten out the portion of the thread starting with the given
662  * message.
663  */
664 static void
665 flattencmd_core(struct message *mp)
666 {
667 	struct message **marray;
668 	size_t mcount;
669 	struct message *tp;
670 	struct message *nextmp;
671 	size_t i;
672 
673 	if (mp == NULL)
674 		return;
675 
676 	mcount = 1;
677 	for (tp = next_message(mp); tp && tp->m_depth > mp->m_depth; tp = next_message(tp))
678 		mcount++;
679 
680 	if (tp && tp->m_depth < mp->m_depth)
681 		nextmp = NULL;
682 	else
683 		nextmp = tp;
684 
685 	if (mcount == 1)
686 		return;
687 
688 	marray = csalloc(mcount, sizeof(*marray));
689 	tp = mp;
690 	for (i = 0; i < mcount; i++) {
691 		marray[i] = tp;
692 		tp = next_message(tp);
693 	}
694 	mp->m_clink = NULL;
695 	for (i = 1; i < mcount; i++) {
696 		marray[i]->m_depth = mp->m_depth;
697 		marray[i]->m_plink = mp->m_plink;
698 		marray[i]->m_clink = NULL;
699 		marray[i]->m_blink = marray[i - 1];
700 		marray[i - 1]->m_flink = marray[i];
701 	}
702 	marray[i - 1]->m_flink = nextmp;
703 	if (nextmp)
704 		nextmp->m_blink = marray[i - 1];
705 }
706 
707 /*
708  * Flatten out all thread parts given in the message list, or the
709  * current thread, if none given.
710  */
711 PUBLIC int
712 flattencmd(void *v)
713 {
714 	int *msgvec;
715 	int *ip;
716 
717 	msgvec = v;
718 
719 	if (*msgvec) { /* a message was supplied */
720 		for (ip = msgvec; *ip; ip++) {
721 			struct message *mp;
722 			mp = get_message(*ip);
723 			if (mp != NULL)
724 				flattencmd_core(mp);
725 		}
726 	}
727 	else { /* no message given - flatten current thread */
728 		struct message *mp;
729 		for (mp = first_message(current_thread.t_head);
730 		     mp; mp = next_message(mp))
731 			flattencmd_core(mp);
732 	}
733 	redepth(&current_thread);
734 	thread_announce(v);
735 	return 0;
736 }
737 
738 
739 /************************************************************************/
740 /*
741  * The basic sort structure.  For each message the index and key
742  * fields are set.  The key field is used for the basic sort and the
743  * index is used to ensure that the order from the current thread is
744  * maintained when the key compare is equal.
745  */
746 struct key_sort_s {
747 	struct message *mp; /* the message the following refer to */
748 	union {
749 		char   *str;	/* string sort key (typically a field or address) */
750 		long   lines;	/* a long sort key (typically a message line count) */
751 		off_t  size;	/* a size sort key (typically the message size) */
752 		time_t time;	/* a time sort key (typically from date or headline) */
753 	} key;
754 	int    index;	/* index from of the current thread before sorting */
755 	/* XXX - do we really want index?  It is always set to mp->m_index */
756 };
757 
758 /*
759  * This is the compare function obtained from the key_tbl[].  It is
760  * used by thread_array() to identify the end of the thread and by
761  * qsort_cmpfn() to do the basic sort.
762  */
763 static struct {
764 	int inv;
765 	int (*fn)(const void *, const void *);
766 } cmp;
767 
768 /*
769  * The routine passed to qsort.  Note that cmpfn must be set first!
770  */
771 static int
772 qsort_cmpfn(const void *left, const void *right)
773 {
774 	int delta;
775 	const struct key_sort_s *lp = left;
776 	const struct key_sort_s *rp = right;
777 
778 	delta = cmp.fn(left, right);
779 	return delta ? cmp.inv ? - delta : delta : lp->index - rp->index;
780 }
781 
782 static void
783 link_array(struct key_sort_s *marray, size_t mcount)
784 {
785 	size_t i;
786 	struct message *lastmp;
787 	lastmp = NULL;
788 	for (i = 0; i < mcount; i++) {
789 		marray[i].mp->m_index = (int)i + 1;
790 		marray[i].mp->m_blink = lastmp;
791 		marray[i].mp->m_flink = NULL;
792 		if (lastmp)
793 			lastmp->m_flink = marray[i].mp;
794 		lastmp = marray[i].mp;
795 	}
796 	if (current_thread.t_head->m_plink)
797 		current_thread.t_head->m_plink->m_clink = marray[0].mp;
798 
799 	current_thread.t_head = marray[0].mp;
800 }
801 
802 static void
803 cut_array(struct key_sort_s *marray, size_t beg, size_t end)
804 {
805 	size_t i;
806 
807 	if (beg + 1 < end) {
808 		assert(marray[beg].mp->m_clink == NULL);
809 
810 		marray[beg].mp->m_clink = marray[beg + 1].mp;
811 		marray[beg + 1].mp->m_blink = NULL;
812 
813 		marray[beg].mp->m_flink = marray[end].mp;
814 		if (marray[end].mp)
815 			marray[end].mp->m_blink = marray[beg].mp;
816 
817 		marray[end - 1].mp->m_flink = NULL;
818 
819 		for (i = beg + 1; i < end; i++)
820 			marray[i].mp->m_plink = marray[beg].mp;
821 	}
822 }
823 
824 static void
825 thread_array(struct key_sort_s *marray, size_t mcount, int cutit)
826 {
827 	struct message *parent;
828 
829 	if (mcount == 0)
830 		return;
831 
832 	parent = marray[0].mp->m_plink;
833 	qsort(marray, mcount, sizeof(*marray), qsort_cmpfn);
834 	link_array(marray, mcount);
835 
836 	if (cutit) {
837 		size_t i, j;
838 		/*
839 		 * Flatten out the array.
840 		 */
841 		for (i = 0; i < mcount; i++) {
842 			marray[i].mp->m_plink = parent;
843 			marray[i].mp->m_clink = NULL;
844 		}
845 
846 		/*
847 		 * Now chop it up.  There is really only one level here.
848 		 */
849 		i = 0;
850 		for (j = 1; j < mcount; j++) {
851 			if (cmp.fn(&marray[i], &marray[j]) != 0) {
852 				cut_array(marray, i, j);
853 				i = j;
854 			}
855 		}
856 		cut_array(marray, i, j);
857 	}
858 }
859 
860 /************************************************************************/
861 /*
862  * thread_on_reference() is the core reference threading routine.  It
863  * is not a command itself by called by threadcmd().
864  */
865 
866 static void
867 adopt_child(struct message *parent, struct message *child)
868 {
869 	/*
870 	 * Unhook the child from its current location.
871 	 */
872 	if (child->m_blink != NULL) {
873 		child->m_blink->m_flink = child->m_flink;
874 	}
875 	if (child->m_flink != NULL) {
876 		child->m_flink->m_blink = child->m_blink;
877 	}
878 
879 	/*
880 	 * Link the child to the parent.
881 	 */
882 	if (parent->m_clink == NULL) { /* parent has no child */
883 		parent->m_clink = child;
884 		child->m_blink = NULL;
885 	}
886 	else { /* add message to end of parent's child's flist */
887 		struct message *t;
888 		for (t = parent->m_clink; t && t->m_flink; t = t->m_flink)
889 			continue;
890 		t->m_flink = child;
891 		child->m_blink = t;
892 	}
893 	child->m_flink = NULL;
894 	child->m_plink = parent;
895 }
896 
897 /*
898  * Get the parent ID for a message (if there is one).
899  *
900  * See RFC 2822, sec 3.6.4.
901  *
902  * Many mailers seem to screw up the In-Reply-To: and/or
903  * References: fields, generally by omitting one or both.
904  *
905  * We give preference to the "References" field.  If it does
906  * not exist, try the "In-Reply-To" field.  If neither exist,
907  * then the message is either not a reply or someone isn't
908  * adding the necessary fields, so skip it.
909  */
910 static char *
911 get_parent_id(struct message *mp)
912 {
913 	struct name *refs;
914 
915 	if ((refs = extract(hfield("references", mp), 0)) != NULL) {
916 		char *id;
917 		while (refs->n_flink)
918 			refs = refs->n_flink;
919 
920 		id = skin(refs->n_name);
921 		if (*id != '\0')
922 			return id;
923 	}
924 
925 	return skin(hfield("in-reply-to", mp));
926 }
927 
928 /*
929  * Thread on the "In-Reply-To" and "Reference" fields.  This is the
930  * normal way to thread.
931  */
932 static void
933 thread_on_reference(struct message *mp)
934 {
935 	struct {
936 		struct message *mp;
937 		char *message_id;
938 		char *parent_id;
939 	} *marray;
940 	struct message *parent;
941 	state_t oldstate;
942 	size_t mcount, i;
943 
944 	assert(mp == current_thread.t_head);
945 
946 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
947 
948 	mcount = get_msgCount();
949 
950 	if (mcount < 2)	/* it's hard to thread so few messages! */
951 		goto done;
952 
953 	marray = csalloc(mcount + 1, sizeof(*marray));
954 
955 	/*
956 	 * Load up the array (skin where necessary).
957 	 *
958 	 * With a 40K message file, most of the time is spent here,
959 	 * not in the search loop below.
960 	 */
961 	for (i = 0; i < mcount; i++) {
962 		marray[i].mp = mp;
963 		marray[i].message_id = skin(hfield("message-id", mp));
964 		marray[i].parent_id = get_parent_id(mp);
965 		mp = next_message(mp);
966 	}
967 
968 	/*
969 	 * Save the old parent.
970 	 */
971 	parent = marray[0].mp->m_plink;
972 
973 	/*
974 	 * flatten the array.
975 	 */
976 	marray[0].mp->m_clink = NULL;
977 	for (i = 1; i < mcount; i++) {
978 		marray[i].mp->m_depth = marray[0].mp->m_depth;
979 		marray[i].mp->m_plink = marray[0].mp->m_plink;
980 		marray[i].mp->m_clink = NULL;
981 		marray[i].mp->m_blink = marray[i - 1].mp;
982 		marray[i - 1].mp->m_flink = marray[i].mp;
983 	}
984 	marray[i - 1].mp->m_flink = NULL;
985 
986 	/*
987 	 * Walk the array hooking up the replies with their parents.
988 	 */
989 	for (i = 0; i < mcount; i++) {
990 		struct message *child;
991 		char *parent_id;
992 		size_t j;
993 
994 		if ((parent_id = marray[i].parent_id) == NULL)
995 			continue;
996 
997 		child = marray[i].mp;
998 
999 		/*
1000 		 * Look for the parent message and link this one in
1001 		 * appropriately.
1002 		 *
1003 		 * XXX - This will not scale nicely, though it does
1004 		 * not appear to be the dominant loop even with 40K
1005 		 * messages.  If this becomes a problem, implement a
1006 		 * binary search.
1007 		 */
1008 		for (j = 0; j < mcount; j++) {
1009 			/* message_id will be NULL on mbox files */
1010 			if (marray[j].message_id == NULL)
1011 				continue;
1012 
1013 			if (equal(marray[j].message_id, parent_id)) {
1014 				/*
1015 				 * The child is at the top level.  If
1016 				 * it is being adopted and it was top
1017 				 * left (current_thread.t_head), then
1018 				 * its right sibling is the new top
1019 				 * left (current_thread.t_head).
1020 				 */
1021 				if (current_thread.t_head == child) {
1022 					current_thread.t_head = child->m_flink;
1023 					assert(current_thread.t_head != NULL);
1024 				}
1025 				adopt_child(marray[j].mp, child);
1026 				break;
1027 			}
1028 		}
1029 	}
1030 
1031 	if (parent)
1032 		parent->m_clink = current_thread.t_head;
1033 	/*
1034 	 * If the old state is not exposed, reset the dot to the head
1035 	 * of the thread it lived in, so it will be in a valid spot
1036 	 * when things are re-hidden.
1037 	 */
1038 	if (!S_IS_EXPOSE(oldstate))
1039 		dot = thread_top(dot);
1040  done:
1041 	restore_state(oldstate);
1042 }
1043 
1044 /************************************************************************/
1045 /*
1046  * Tagging commands.
1047  */
1048 static int
1049 tag1(int *msgvec, int and_bits, int xor_bits)
1050 {
1051 	int *ip;
1052 
1053 	for (ip = msgvec; *ip != 0; ip++)
1054 		(void)set_m_flag(*ip, and_bits, xor_bits);
1055 
1056 	reindex(&current_thread);
1057 /*	thread_announce(v); */
1058 	return 0;
1059 }
1060 
1061 /*
1062  * Tag the current message dot or a message list.
1063  */
1064 PUBLIC int
1065 tagcmd(void *v)
1066 {
1067 	return tag1(v, ~MTAGGED, MTAGGED);
1068 }
1069 
1070 /*
1071  * Untag the current message dot or a message list.
1072  */
1073 PUBLIC int
1074 untagcmd(void *v)
1075 {
1076 	return tag1(v, ~MTAGGED, 0);
1077 }
1078 
1079 /*
1080  * Invert all tags in the message list.
1081  */
1082 PUBLIC int
1083 invtagscmd(void *v)
1084 {
1085 	return tag1(v, ~0, MTAGGED);
1086 }
1087 
1088 /*
1089  * Tag all messages below the current dot or below a specified
1090  * message.
1091  */
1092 PUBLIC int
1093 tagbelowcmd(void *v)
1094 {
1095 	int *msgvec;
1096 	struct message *mp;
1097 	state_t oldstate;
1098 	int depth;
1099 
1100 	msgvec = v;
1101 
1102 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
1103 	mp = get_message(*msgvec);
1104 	if (mp) {
1105 		depth = mp->m_depth;
1106 		for (mp = first_message(current_thread.t_head); mp; mp = next_message(mp))
1107 			if (mp->m_depth > depth) {
1108 				mp->m_flag |= MTAGGED;
1109 				touch(mp);
1110 			}
1111 	}
1112 	/* dot is OK */
1113 	restore_state(oldstate);
1114 /*	thread_announce(v); */
1115 	return 0;
1116 }
1117 
1118 /*
1119  * Do not display the tagged messages.
1120  */
1121 PUBLIC int
1122 hidetagscmd(void *v)
1123 {
1124 	(void)set_state(~S_RESTRICT, S_RESTRICT);	/* restrict on */
1125 	dot = first_visible_message(dot);
1126 	thread_announce(v);
1127 	return 0;
1128 }
1129 
1130 /*
1131  * Display the tagged messages.
1132  */
1133 PUBLIC int
1134 showtagscmd(void *v)
1135 {
1136 	(void)set_state(~S_RESTRICT, 0);		/* restrict off */
1137 	dot = first_visible_message(dot);
1138 	thread_announce(v);
1139 	return 0;
1140 }
1141 
1142 /************************************************************************/
1143 /*
1144  * Basic threading commands.
1145  */
1146 /*
1147  * Show the threads.
1148  */
1149 PUBLIC int
1150 exposecmd(void *v)
1151 {
1152 	(void)set_state(~S_EXPOSE, S_EXPOSE);	/* expose on */
1153 	dot = first_visible_message(dot);
1154 	thread_announce(v);
1155 	return 0;
1156 }
1157 
1158 /*
1159  * Hide the threads.
1160  */
1161 PUBLIC int
1162 hidecmd(void *v)
1163 {
1164 	dot = thread_top(dot);
1165 	(void)set_state(~S_EXPOSE, 0);		/* expose off */
1166 	dot = first_visible_message(dot);
1167 	thread_announce(v);
1168 	return 0;
1169 }
1170 
1171 /*
1172  * Up one level in the thread tree.  Go up multiple levels if given an
1173  * argument.
1174  */
1175 PUBLIC int
1176 upcmd(void *v)
1177 {
1178 	char *str;
1179 	int upcnt;
1180 	int upone;
1181 
1182 	str = v;
1183 	str = skip_WSP(str);
1184 	if (*str == '\0')
1185 		upcnt = 1;
1186 	else
1187 		upcnt = atoi(str);
1188 
1189 	if (upcnt < 1) {
1190 		(void)printf("Sorry, argument must be > 0.\n");
1191 		return 0;
1192 	}
1193 	if (dot == NULL) {
1194 		(void)printf("No applicable messages\n");
1195 		return 0;
1196 	}
1197 	if (dot->m_plink == NULL) {
1198 		(void)printf("top thread\n");
1199 		return 0;
1200 	}
1201 	upone = 0;
1202 	while (upcnt-- > 0) {
1203 		struct message *parent;
1204 		parent = current_thread.t_head->m_plink;
1205 		if (parent == NULL) {
1206 			(void)printf("top thread\n");
1207 			break;
1208 		}
1209 		else {
1210 			struct message *mp;
1211 			assert(current_thread.t_head->m_depth > 0);
1212 			for (mp = parent; mp && mp->m_blink; mp = mp->m_blink)
1213 				continue;
1214 			current_thread.t_head = mp;
1215 			dot = parent;
1216 			upone = 1;
1217 		}
1218 	}
1219 	if (upone) {
1220 		reindex(&current_thread);
1221 		thread_announce(v);
1222 	}
1223 	return 0;
1224 }
1225 
1226 /*
1227  * Go down one level in the thread tree from the current dot or a
1228  * given message number if given.
1229  */
1230 PUBLIC int
1231 downcmd(void *v)
1232 {
1233 	struct message *child;
1234 	struct message *mp;
1235 	int *msgvec = v;
1236 
1237 	if ((mp = get_message(*msgvec)) == NULL ||
1238 	    (child = mp->m_clink) == NULL)
1239 		(void)printf("no sub-thread\n");
1240 	else {
1241 		current_thread.t_head = child;
1242 		dot = child;
1243 		reindex(&current_thread);
1244 		thread_announce(v);
1245 	}
1246 	return 0;
1247 }
1248 
1249 /*
1250  * Set the current thread level to the current dot or to the message
1251  * if given.
1252  */
1253 PUBLIC int
1254 tsetcmd(void *v)
1255 {
1256 	struct message *mp;
1257 	int *msgvec = v;
1258 
1259 	if ((mp = get_message(*msgvec)) == NULL)
1260 		(void)printf("invalid message\n");
1261 	else {
1262 		for (/*EMPTY*/; mp->m_blink; mp = mp->m_blink)
1263 			continue;
1264 		current_thread.t_head = mp;
1265 		reindex(&current_thread);
1266 		thread_announce(v);
1267 	}
1268 	return 0;
1269 }
1270 
1271 /*
1272  * Reverse the current thread order.  If threaded, it only operates on
1273  * the heads.
1274  */
1275 static void
1276 reversecmd_core(struct thread_s *tp)
1277 {
1278 	struct message *thread_start;
1279 	struct message *mp;
1280 	struct message *lastmp;
1281 	struct message *old_flink;
1282 
1283 	thread_start = tp->t_head;
1284 
1285 	assert(thread_start->m_blink == NULL);
1286 
1287 	lastmp = NULL;
1288 	for (mp = thread_start; mp; mp = old_flink) {
1289 		old_flink = mp->m_flink;
1290 		mp->m_flink = mp->m_blink;
1291 		mp->m_blink = old_flink;
1292 		lastmp = mp;
1293 	}
1294 	if (thread_start->m_plink)
1295 		thread_start->m_plink->m_clink = lastmp;
1296 
1297 	current_thread.t_head = lastmp;
1298 	reindex(tp);
1299 }
1300 
1301 PUBLIC int
1302 reversecmd(void *v)
1303 {
1304 	reversecmd_core(&current_thread);
1305 	thread_announce(v);
1306 	return 0;
1307 }
1308 
1309 
1310 /*
1311  * Get threading and sorting modifiers.
1312  */
1313 #define MF_IGNCASE	1	/* ignore case when sorting */
1314 #define MF_REVERSE	2	/* reverse sort direction */
1315 #define MF_SKIN		4	/* "skin" the field to remove comments */
1316 static int
1317 get_modifiers(char **str)
1318 {
1319 	int modflags;
1320 	char *p;
1321 
1322 	modflags = 0;
1323 	for (p = *str; p && *p; p++) {
1324 		switch (*p) {
1325 		case '!':
1326 			modflags |= MF_REVERSE;
1327 			break;
1328 		case '^':
1329 			modflags |= MF_IGNCASE;
1330 			break;
1331 		case '-':
1332 			modflags |= MF_SKIN;
1333 			break;
1334 		case ' ':
1335 		case '\t':
1336 			break;
1337 		default:
1338 			goto done;
1339 		}
1340 	}
1341  done:
1342 	*str = p;
1343 	return modflags;
1344 }
1345 
1346 /************************************************************************/
1347 /*
1348  * The key_sort_s compare routines.
1349  */
1350 
1351 static int
1352 keystrcmp(const void *left, const void *right)
1353 {
1354 	const struct key_sort_s *lp = left;
1355 	const struct key_sort_s *rp = right;
1356 
1357 	lp = left;
1358 	rp = right;
1359 
1360 	if (rp->key.str == NULL && lp->key.str == NULL)
1361 		return 0;
1362 	else if (rp->key.str == NULL)
1363 		return -1;
1364 	else if (lp->key.str == NULL)
1365 		return 1;
1366 	else
1367 		return strcmp(lp->key.str, rp->key.str);
1368 }
1369 
1370 static int
1371 keystrcasecmp(const void *left, const void *right)
1372 {
1373 	const struct key_sort_s *lp = left;
1374 	const struct key_sort_s *rp = right;
1375 
1376 	if (rp->key.str == NULL && lp->key.str == NULL)
1377 		return 0;
1378 	else if (rp->key.str == NULL)
1379 		return -1;
1380 	else if (lp->key.str == NULL)
1381 		return 1;
1382 	else
1383 		return strcasecmp(lp->key.str, rp->key.str);
1384 }
1385 
1386 static int
1387 keylongcmp(const void *left, const void *right)
1388 {
1389 	const struct key_sort_s *lp = left;
1390 	const struct key_sort_s *rp = right;
1391 
1392 	if (lp->key.lines > rp->key.lines)
1393 		return 1;
1394 
1395 	if (lp->key.lines < rp->key.lines)
1396 		return -1;
1397 
1398 	return 0;
1399 }
1400 
1401 static int
1402 keyoffcmp(const void *left, const void *right)
1403 {
1404 	const struct key_sort_s *lp = left;
1405 	const struct key_sort_s *rp = right;
1406 
1407 	if (lp->key.size > rp->key.size)
1408 		return 1;
1409 
1410 	if (lp->key.size < rp->key.size)
1411 		return -1;
1412 
1413 	return 0;
1414 }
1415 
1416 static int
1417 keytimecmp(const void *left, const void *right)
1418 {
1419 	double delta;
1420 	const struct key_sort_s *lp = left;
1421 	const struct key_sort_s *rp = right;
1422 
1423 	delta = difftime(lp->key.time, rp->key.time);
1424 	if (delta > 0)
1425 		return 1;
1426 
1427 	if (delta < 0)
1428 		return -1;
1429 
1430 	return 0;
1431 }
1432 
1433 /************************************************************************
1434  * key_sort_s loading routines.
1435  */
1436 static void
1437 field_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1438     const char *key, int skin_it)
1439 {
1440 	size_t i;
1441 	for (i = 0; i < mcount; i++) {
1442 		marray[i].mp = mp;
1443 		marray[i].key.str =
1444 		    skin_it ? skin(hfield(key, mp)) : hfield(key, mp);
1445 		marray[i].index = mp->m_index;
1446 		mp = next_message(mp);
1447 	}
1448 }
1449 
1450 static void
1451 subj_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1452     const char *key __unused, int flags __unused)
1453 {
1454 	size_t i;
1455 #ifdef __lint__
1456 	flags = flags;
1457 	key = key;
1458 #endif
1459 	for (i = 0; i < mcount; i++) {
1460 		char *subj = hfield(key, mp);
1461 		while (strncasecmp(subj, "Re:", 3) == 0)
1462 			subj = skip_WSP(subj + 3);
1463 		marray[i].mp = mp;
1464 		marray[i].key.str = subj;
1465 		marray[i].index = mp->m_index;
1466 		mp = next_message(mp);
1467 	}
1468 }
1469 
1470 
1471 static void
1472 lines_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1473     const char *key __unused, int flags)
1474 {
1475 	size_t i;
1476 	int use_blines;
1477 	int use_hlines;
1478 #ifdef __lint__
1479 	key = key;
1480 #endif
1481 #define HLINES	1
1482 #define BLINES	2
1483 #define TLINES	3
1484 	use_hlines = flags == HLINES;
1485 	use_blines = flags == BLINES;
1486 
1487 	for (i = 0; i < mcount; i++) {
1488 		marray[i].mp = mp;
1489 		marray[i].key.lines = use_hlines ? mp->m_lines - mp->m_blines :
1490 		    use_blines ? mp->m_blines : mp->m_lines;
1491 		marray[i].index = mp->m_index;
1492 		mp = next_message(mp);
1493 	}
1494 }
1495 
1496 static void
1497 size_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1498     const char *key __unused, int flags __unused)
1499 {
1500 	size_t i;
1501 #ifdef __lint__
1502 	flags = flags;
1503 	key = key;
1504 #endif
1505 	for (i = 0; i < mcount; i++) {
1506 		marray[i].mp = mp;
1507 		marray[i].key.size = mp->m_size;
1508 		marray[i].index = mp->m_index;
1509 		mp = next_message(mp);
1510 	}
1511 }
1512 
1513 static void __unused
1514 date_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1515     const char *key __unused, int flags)
1516 {
1517 	size_t i;
1518 	int use_hl_date;
1519 	int zero_hour_min_sec;
1520 #ifdef __lint__
1521 	key = key;
1522 #endif
1523 #define RDAY 1
1524 #define SDAY 2
1525 #define RDATE 3
1526 #define SDATE 4
1527 	use_hl_date       = (flags == RDAY || flags == RDATE);
1528 	zero_hour_min_sec = (flags == RDAY || flags == SDAY);
1529 
1530 	for (i = 0; i < mcount; i++) {
1531 		struct tm tm;
1532 		(void)dateof(&tm, mp, use_hl_date);
1533 		if (zero_hour_min_sec) {
1534 			tm.tm_sec = 0;
1535 			tm.tm_min = 0;
1536 			tm.tm_hour = 0;
1537 		}
1538 		marray[i].mp = mp;
1539 		marray[i].key.time = mktime(&tm);
1540 		marray[i].index = mp->m_index;
1541 		mp = next_message(mp);
1542 	}
1543 }
1544 
1545 static void
1546 from_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
1547     const char *key __unused, int flags __unused)
1548 {
1549 	size_t i;
1550 #ifdef __lint__
1551 	flags = flags;
1552 	key = key;
1553 #endif
1554 	for (i = 0; i < mcount; i++) {
1555 		marray[i].mp = mp;
1556 		marray[i].key.str = nameof(mp, 0);
1557 		marray[i].index = mp->m_index;
1558 		mp = next_message(mp);
1559 	}
1560 }
1561 
1562 /************************************************************************
1563  * The master table that controls all sorting and threading.
1564  */
1565 static const struct key_tbl_s {
1566 	const char *key;
1567 	void (*loadfn)(struct key_sort_s *, size_t, struct message *, const char *, int);
1568 	int flags;
1569 	int (*cmpfn)(const void*, const void*);
1570 	int (*casecmpfn)(const void*, const void*);
1571 } key_tbl[] = {
1572 	{"blines",	lines_load,	BLINES,	keylongcmp,	keylongcmp},
1573 	{"hlines",	lines_load,	HLINES,	keylongcmp,	keylongcmp},
1574 	{"tlines",	lines_load,	TLINES,	keylongcmp,	keylongcmp},
1575 	{"size",	size_load,	0,	keyoffcmp,	keyoffcmp},
1576 	{"sday",	date_load,	SDAY,	keytimecmp,	keytimecmp},
1577 	{"rday",	date_load,	RDAY,	keytimecmp,	keytimecmp},
1578 	{"sdate",	date_load,	SDATE,	keytimecmp,	keytimecmp},
1579 	{"rdate",	date_load,	RDATE,	keytimecmp,	keytimecmp},
1580 	{"from",	from_load,	0,	keystrcasecmp,	keystrcasecmp},
1581 	{"subject",	subj_load,	0,	keystrcmp,	keystrcasecmp},
1582 	{NULL,		field_load,	0,	keystrcmp,	keystrcasecmp},
1583 };
1584 
1585 #ifdef USE_EDITLINE
1586 /*
1587  * This is for use in complete.c to get the list of threading key
1588  * names without exposing the key_tbl[].  The first name is returned
1589  * if called with a pointer to a NULL pointer.  Subsequent calls with
1590  * the same cookie give successive names.  A NULL return indicates the
1591  * end of the list.
1592  */
1593 PUBLIC const char *
1594 thread_next_key_name(const void **cookie)
1595 {
1596 	const struct key_tbl_s *kp;
1597 
1598 	kp = *cookie;
1599 	if (kp == NULL)
1600 		kp = key_tbl;
1601 
1602 	*cookie = kp->key ? &kp[1] : NULL;
1603 
1604 	return kp->key;
1605 }
1606 #endif /* USE_EDITLINE */
1607 
1608 static const struct key_tbl_s *
1609 get_key(const char *key)
1610 {
1611 	const struct key_tbl_s *kp;
1612 	for (kp = key_tbl; kp->key != NULL; kp++)
1613 		if (strcmp(kp->key, key) == 0)
1614 			return kp;
1615 	return kp;
1616 }
1617 
1618 static int (*
1619 get_cmpfn(const struct key_tbl_s *kp, int ignorecase)
1620 )(const void*, const void*)
1621 {
1622 	if (ignorecase)
1623 		return kp->casecmpfn;
1624 	else
1625 		return kp->cmpfn;
1626 }
1627 
1628 static void
1629 thread_current_on(char *str, int modflags, int cutit)
1630 {
1631 	const struct key_tbl_s *kp;
1632 	struct key_sort_s *marray;
1633 	size_t mcount;
1634 	state_t oldstate;
1635 
1636 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), cutit ? S_EXPOSE : 0);
1637 
1638 	kp = get_key(str);
1639 	mcount = get_msgCount();
1640 	marray = csalloc(mcount + 1, sizeof(*marray));
1641 	kp->loadfn(marray, mcount, current_thread.t_head, str,
1642 	    kp->flags ? kp->flags : modflags & MF_SKIN);
1643 	cmp.fn = get_cmpfn(kp, modflags & MF_IGNCASE);
1644 	cmp.inv = modflags & MF_REVERSE;
1645 	thread_array(marray, mcount, cutit);
1646 
1647 	if (!S_IS_EXPOSE(oldstate))
1648 		dot = thread_top(dot);
1649 	restore_state(oldstate);
1650 }
1651 
1652 /*
1653  * The thread command.  Thread the current thread on its references or
1654  * on a specified field.
1655  */
1656 PUBLIC int
1657 threadcmd(void *v)
1658 {
1659 	char *str;
1660 
1661 	str = v;
1662 	if (*str == '\0')
1663 		thread_on_reference(current_thread.t_head);
1664 	else {
1665 		int modflags;
1666 		modflags = get_modifiers(&str);
1667 		thread_current_on(str, modflags, 1);
1668 	}
1669 	thread_announce(v);
1670 	return 0;
1671 }
1672 
1673 /*
1674  * Remove all threading information, reverting to the startup state.
1675  */
1676 PUBLIC int
1677 unthreadcmd(void *v)
1678 {
1679 	thread_fix_new_links(message_array.t_head, 0, message_array.t_msgCount);
1680 	thread_announce(v);
1681 	return 0;
1682 }
1683 
1684 /*
1685  * The sort command.
1686  */
1687 PUBLIC int
1688 sortcmd(void *v)
1689 {
1690 	int modflags;
1691 	char *str;
1692 
1693 	str = v;
1694 	modflags = get_modifiers(&str);
1695 	if (*str != '\0')
1696 		thread_current_on(str, modflags, 0);
1697 	else {
1698 		if (modflags & MF_REVERSE)
1699 			reversecmd_core(&current_thread);
1700 		else {
1701 			(void)printf("sort on what?\n");
1702 			return 0;
1703 		}
1704 	}
1705 	thread_announce(v);
1706 	return 0;
1707 }
1708 
1709 
1710 /*
1711  * Delete duplicate messages (based on their "Message-Id" field).
1712  */
1713 /*ARGSUSED*/
1714 PUBLIC int
1715 deldupscmd(void *v __unused)
1716 {
1717 	struct message *mp;
1718 	int depth;
1719 	state_t oldstate;
1720 
1721 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
1722 
1723 	thread_current_on(__UNCONST("Message-Id"), 0, 1);
1724 	reindex(&current_thread);
1725 	redepth(&current_thread);
1726 	depth = current_thread.t_head->m_depth;
1727 	for (mp = first_message(current_thread.t_head); mp; mp = next_message(mp)) {
1728 		if (mp->m_depth > depth) {
1729 			mp->m_flag &= ~(MPRESERVE | MSAVED | MBOX);
1730 			mp->m_flag |= MDELETED | MTOUCH;
1731 			touch(mp);
1732 		}
1733 	}
1734 	dot = thread_top(dot);	/* do this irrespective of the oldstate */
1735 	restore_state(oldstate);
1736 /*	thread_announce(v); */
1737 	return 0;
1738 }
1739 
1740 #endif /* THREAD_SUPPORT */
1741