Home | History | Annotate | Line # | Download | only in mail
thread.c revision 1.4.6.1
      1 /*	$NetBSD: thread.c,v 1.4.6.1 2008/05/18 12:36:06 yamt 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.4.6.1 2008/05/18 12:36:06 yamt 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 	int 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 	int 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, int beg, int end)
    798 {
    799 	int 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 		int 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;
    934 	int i;
    935 
    936 	assert(mp == current_thread.t_head);
    937 
    938 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
    939 
    940 	mcount = get_msgCount();
    941 
    942 	if (mcount < 2)	/* it's hard to thread so few messages! */
    943 		goto done;
    944 
    945 	marray = csalloc(mcount + 1, sizeof(*marray));
    946 
    947 	/*
    948 	 * Load up the array (skin where necessary).
    949 	 *
    950 	 * With a 40K message file, most of the time is spent here,
    951 	 * not in the search loop below.
    952 	 */
    953 	for (i = 0; i < mcount; i++) {
    954 		marray[i].mp = mp;
    955 		marray[i].message_id = skin(hfield("message-id", mp));
    956 		marray[i].parent_id = get_parent_id(mp);
    957 		mp = next_message(mp);
    958 	}
    959 
    960 	/*
    961 	 * Save the old parent.
    962 	 */
    963 	parent = marray[0].mp->m_plink;
    964 
    965 	/*
    966 	 * flatten the array.
    967 	 */
    968 	marray[0].mp->m_clink = NULL;
    969 	for (i = 1; i < mcount; i++) {
    970 		marray[i].mp->m_depth = marray[0].mp->m_depth;
    971 		marray[i].mp->m_plink = marray[0].mp->m_plink;
    972 		marray[i].mp->m_clink = NULL;
    973 		marray[i].mp->m_blink = marray[i - 1].mp;
    974 		marray[i - 1].mp->m_flink = marray[i].mp;
    975 	}
    976 	marray[i - 1].mp->m_flink = NULL;
    977 
    978 	/*
    979 	 * Walk the array hooking up the replies with their parents.
    980 	 */
    981 	for (i = 0; i < mcount; i++) {
    982 		struct message *child;
    983 		char *parent_id;
    984 		int j;
    985 
    986 		if ((parent_id = marray[i].parent_id) == NULL)
    987 			continue;
    988 
    989 		child = marray[i].mp;
    990 
    991 		/*
    992 		 * Look for the parent message and link this one in
    993 		 * appropriately.
    994 		 *
    995 		 * XXX - This will not scale nicely, though it does
    996 		 * not appear to be the dominant loop even with 40K
    997 		 * messages.  If this becomes a problem, implement a
    998 		 * binary search.
    999 		 */
   1000 		for (j = 0; j < mcount; j++) {
   1001 			/* message_id will be NULL on mbox files */
   1002 			if (marray[i].message_id == NULL)
   1003 				continue;
   1004 
   1005 			if (equal(marray[j].message_id, parent_id)) {
   1006 				/*
   1007 				 * The child is at the top level.  If
   1008 				 * it is being adopted and it was top
   1009 				 * left (current_thread.t_head), then
   1010 				 * its right sibling is the new top
   1011 				 * left (current_thread.t_head).
   1012 				 */
   1013 				if (current_thread.t_head == child) {
   1014 					current_thread.t_head = child->m_flink;
   1015 					assert(current_thread.t_head != NULL);
   1016 				}
   1017 				adopt_child(marray[j].mp, child);
   1018 				break;
   1019 			}
   1020 		}
   1021 	}
   1022 
   1023 	if (parent)
   1024 		parent->m_clink = current_thread.t_head;
   1025 	/*
   1026 	 * If the old state is not exposed, reset the dot to the head
   1027 	 * of the thread it lived in, so it will be in a valid spot
   1028 	 * when things are re-hidden.
   1029 	 */
   1030 	if (!S_IS_EXPOSE(oldstate))
   1031 		dot = thread_top(dot);
   1032  done:
   1033 	restore_state(oldstate);
   1034 }
   1035 
   1036 /************************************************************************/
   1037 /*
   1038  * Tagging commands.
   1039  */
   1040 static int
   1041 tag1(int *msgvec, int and_bits, int xor_bits)
   1042 {
   1043 	int *ip;
   1044 
   1045 	for (ip = msgvec; *ip != 0; ip++)
   1046 		(void)set_m_flag(*ip, and_bits, xor_bits);
   1047 
   1048 	reindex(&current_thread);
   1049 /*	thread_announce(v); */
   1050 	return 0;
   1051 }
   1052 
   1053 /*
   1054  * Tag the current message dot or a message list.
   1055  */
   1056 PUBLIC int
   1057 tagcmd(void *v)
   1058 {
   1059 	return tag1(v, ~MTAGGED, MTAGGED);
   1060 }
   1061 
   1062 /*
   1063  * Untag the current message dot or a message list.
   1064  */
   1065 PUBLIC int
   1066 untagcmd(void *v)
   1067 {
   1068 	return tag1(v, ~MTAGGED, 0);
   1069 }
   1070 
   1071 /*
   1072  * Invert all tags in the message list.
   1073  */
   1074 PUBLIC int
   1075 invtagscmd(void *v)
   1076 {
   1077 	return tag1(v, ~0, MTAGGED);
   1078 }
   1079 
   1080 /*
   1081  * Tag all messages below the current dot or below a specified
   1082  * message.
   1083  */
   1084 PUBLIC int
   1085 tagbelowcmd(void *v)
   1086 {
   1087 	int *msgvec;
   1088 	struct message *mp;
   1089 	state_t oldstate;
   1090 	int depth;
   1091 
   1092 	msgvec = v;
   1093 
   1094 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
   1095 	mp = get_message(*msgvec);
   1096 	if (mp) {
   1097 		depth = mp->m_depth;
   1098 		for (mp = first_message(current_thread.t_head); mp; mp = next_message(mp))
   1099 			if (mp->m_depth > depth ) {
   1100 				mp->m_flag |= MTAGGED;
   1101 				touch(mp);
   1102 			}
   1103 	}
   1104 	/* dot is OK */
   1105 	restore_state(oldstate);
   1106 /*	thread_announce(v); */
   1107 	return 0;
   1108 }
   1109 
   1110 /*
   1111  * Do not display the tagged messages.
   1112  */
   1113 PUBLIC int
   1114 hidetagscmd(void *v)
   1115 {
   1116 	(void)set_state(~S_RESTRICT, S_RESTRICT);	/* restrict on */
   1117 	dot = first_visible_message(dot);
   1118 	thread_announce(v);
   1119 	return 0;
   1120 }
   1121 
   1122 /*
   1123  * Display the tagged messages.
   1124  */
   1125 PUBLIC int
   1126 showtagscmd(void *v)
   1127 {
   1128 	(void)set_state(~S_RESTRICT, 0);		/* restrict off */
   1129 	dot = first_visible_message(dot);
   1130 	thread_announce(v);
   1131 	return 0;
   1132 }
   1133 
   1134 /************************************************************************/
   1135 /*
   1136  * Basic threading commands.
   1137  */
   1138 /*
   1139  * Show the threads.
   1140  */
   1141 PUBLIC int
   1142 exposecmd(void *v)
   1143 {
   1144 	(void)set_state(~S_EXPOSE, S_EXPOSE);	/* expose on */
   1145 	dot = first_visible_message(dot);
   1146 	thread_announce(v);
   1147 	return 0;
   1148 }
   1149 
   1150 /*
   1151  * Hide the threads.
   1152  */
   1153 PUBLIC int
   1154 hidecmd(void *v)
   1155 {
   1156 	dot = thread_top(dot);
   1157 	(void)set_state(~S_EXPOSE, 0);		/* expose off */
   1158 	dot = first_visible_message(dot);
   1159 	thread_announce(v);
   1160 	return 0;
   1161 }
   1162 
   1163 /*
   1164  * Up one level in the thread tree.  Go up multiple levels if given an
   1165  * argument.
   1166  */
   1167 PUBLIC int
   1168 upcmd(void *v)
   1169 {
   1170 	char *str;
   1171 	int upcnt;
   1172 	int upone;
   1173 
   1174 	str = v;
   1175 	str = skip_WSP(str);
   1176 	if (*str == '\0')
   1177 		upcnt = 1;
   1178 	else
   1179 		upcnt = atoi(str);
   1180 
   1181 	if (upcnt < 1) {
   1182 		(void)printf("Sorry, argument must be > 0.\n");
   1183 		return 0;
   1184 	}
   1185 	if (dot == NULL) {
   1186 		(void)printf("No applicable messages\n");
   1187 		return 0;
   1188 	}
   1189 	if (dot->m_plink == NULL) {
   1190 		(void)printf("top thread\n");
   1191 		return 0;
   1192 	}
   1193 	upone = 0;
   1194 	while (upcnt-- > 0) {
   1195 		struct message *parent;
   1196 		parent = current_thread.t_head->m_plink;
   1197 		if (parent == NULL) {
   1198 			(void)printf("top thread\n");
   1199 			break;
   1200 		}
   1201 		else {
   1202 			struct message *mp;
   1203 			assert(current_thread.t_head->m_depth > 0);
   1204 			for (mp = parent; mp && mp->m_blink; mp = mp->m_blink)
   1205 				continue;
   1206 			current_thread.t_head = mp;
   1207 			dot = parent;
   1208 			upone = 1;
   1209 		}
   1210 	}
   1211 	if (upone) {
   1212 		reindex(&current_thread);
   1213 		thread_announce(v);
   1214 	}
   1215 	return 0;
   1216 }
   1217 
   1218 /*
   1219  * Go down one level in the thread tree from the current dot or a
   1220  * given message number if given.
   1221  */
   1222 PUBLIC int
   1223 downcmd(void *v)
   1224 {
   1225 	struct message *child;
   1226 	struct message *mp;
   1227 	int *msgvec = v;
   1228 
   1229 	if ((mp = get_message(*msgvec)) == NULL ||
   1230 	    (child = mp->m_clink) == NULL)
   1231 		(void)printf("no sub-thread\n");
   1232 	else {
   1233 		current_thread.t_head = child;
   1234 		dot = child;
   1235 		reindex(&current_thread);
   1236 		thread_announce(v);
   1237 	}
   1238 	return 0;
   1239 }
   1240 
   1241 /*
   1242  * Set the current thread level to the current dot or to the message
   1243  * if given.
   1244  */
   1245 PUBLIC int
   1246 tsetcmd(void *v)
   1247 {
   1248 	struct message *mp;
   1249 	int *msgvec = v;
   1250 
   1251 	if ((mp = get_message(*msgvec)) == NULL)
   1252 		(void)printf("invalid message\n");
   1253 	else {
   1254 		for (/*EMPTY*/; mp->m_blink; mp = mp->m_blink)
   1255 			continue;
   1256 		current_thread.t_head = mp;
   1257 		reindex(&current_thread);
   1258 		thread_announce(v);
   1259 	}
   1260 	return 0;
   1261 }
   1262 
   1263 /*
   1264  * Reverse the current thread order.  If threaded, it only operates on
   1265  * the heads.
   1266  */
   1267 static void
   1268 reversecmd_core(struct thread_s *tp)
   1269 {
   1270 	struct message *thread_start;
   1271 	struct message *mp;
   1272 	struct message *lastmp;
   1273 	struct message *old_flink;
   1274 
   1275 	thread_start = tp->t_head;
   1276 
   1277 	assert(thread_start->m_blink == NULL);
   1278 
   1279 	lastmp = NULL;
   1280 	for (mp = thread_start; mp; mp = old_flink) {
   1281 		old_flink = mp->m_flink;
   1282 		mp->m_flink = mp->m_blink;
   1283 		mp->m_blink = old_flink;
   1284 		lastmp = mp;
   1285 	}
   1286 	if (thread_start->m_plink)
   1287 		thread_start->m_plink->m_clink = lastmp;
   1288 
   1289 	current_thread.t_head = lastmp;
   1290 	reindex(tp);
   1291 }
   1292 
   1293 PUBLIC int
   1294 reversecmd(void *v)
   1295 {
   1296 	reversecmd_core(&current_thread);
   1297 	thread_announce(v);
   1298 	return 0;
   1299 }
   1300 
   1301 
   1302 /*
   1303  * Get threading and sorting modifiers.
   1304  */
   1305 #define MF_IGNCASE	1	/* ignore case when sorting */
   1306 #define MF_REVERSE	2	/* reverse sort direction */
   1307 #define MF_SKIN		4	/* "skin" the field to remove comments */
   1308 static int
   1309 get_modifiers(char **str)
   1310 {
   1311 	int modflags;
   1312 	char *p;
   1313 
   1314 	modflags = 0;
   1315 	for (p = *str; p && *p; p++) {
   1316 		switch (*p) {
   1317 		case '!':
   1318 			modflags |= MF_REVERSE;
   1319 			break;
   1320 		case '^':
   1321 			modflags |= MF_IGNCASE;
   1322 			break;
   1323 		case '-':
   1324 			modflags |= MF_SKIN;
   1325 			break;
   1326 		case ' ':
   1327 		case '\t':
   1328 			break;
   1329 		default:
   1330 			goto done;
   1331 		}
   1332 	}
   1333  done:
   1334 	*str = p;
   1335 	return modflags;
   1336 }
   1337 
   1338 /************************************************************************/
   1339 /*
   1340  * The key_sort_s compare routines.
   1341  */
   1342 
   1343 static int
   1344 keystrcmp(const void *left, const void *right)
   1345 {
   1346 	const struct key_sort_s *lp = left;
   1347 	const struct key_sort_s *rp = right;
   1348 
   1349 	lp = left;
   1350 	rp = right;
   1351 
   1352 	if (rp->key.str == NULL && lp->key.str == NULL)
   1353 		return 0;
   1354 	else if (rp->key.str == NULL)
   1355 		return -1;
   1356 	else if (lp->key.str == NULL)
   1357 		return 1;
   1358 	else
   1359 		return strcmp(lp->key.str, rp->key.str);
   1360 }
   1361 
   1362 static int
   1363 keystrcasecmp(const void *left, const void *right)
   1364 {
   1365 	const struct key_sort_s *lp = left;
   1366 	const struct key_sort_s *rp = right;
   1367 
   1368 	if (rp->key.str == NULL && lp->key.str == NULL)
   1369 		return 0;
   1370 	else if (rp->key.str == NULL)
   1371 		return -1;
   1372 	else if (lp->key.str == NULL)
   1373 		return 1;
   1374 	else
   1375 		return strcasecmp(lp->key.str, rp->key.str);
   1376 }
   1377 
   1378 static int
   1379 keylongcmp(const void *left, const void *right)
   1380 {
   1381 	const struct key_sort_s *lp = left;
   1382 	const struct key_sort_s *rp = right;
   1383 
   1384 	if (lp->key.lines > rp->key.lines)
   1385 		return 1;
   1386 
   1387 	if (lp->key.lines < rp->key.lines)
   1388 		return -1;
   1389 
   1390 	return 0;
   1391 }
   1392 
   1393 static int
   1394 keyoffcmp(const void *left, const void *right)
   1395 {
   1396 	const struct key_sort_s *lp = left;
   1397 	const struct key_sort_s *rp = right;
   1398 
   1399 	if (lp->key.size > rp->key.size)
   1400 		return 1;
   1401 
   1402 	if (lp->key.size < rp->key.size)
   1403 		return -1;
   1404 
   1405 	return 0;
   1406 }
   1407 
   1408 static int
   1409 keytimecmp(const void *left, const void *right)
   1410 {
   1411 	double delta;
   1412 	const struct key_sort_s *lp = left;
   1413 	const struct key_sort_s *rp = right;
   1414 
   1415 	delta = difftime(lp->key.time, rp->key.time);
   1416 	if (delta > 0)
   1417 		return 1;
   1418 
   1419 	if (delta < 0)
   1420 		return -1;
   1421 
   1422 	return 0;
   1423 }
   1424 
   1425 /************************************************************************
   1426  * key_sort_s loading routines.
   1427  */
   1428 static void
   1429 field_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
   1430     const char *key, int skin_it)
   1431 {
   1432 	int i;
   1433 	for (i = 0; i < mcount; i++) {
   1434 		marray[i].mp = mp;
   1435 		marray[i].key.str =
   1436 		    skin_it ? skin(hfield(key, mp)) : hfield(key, mp);
   1437 		marray[i].index = mp->m_index;
   1438 		mp = next_message(mp);
   1439 	}
   1440 }
   1441 
   1442 static void
   1443 subj_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
   1444     const char *key __unused, int flags __unused)
   1445 {
   1446 	int i;
   1447 #ifdef __lint__
   1448 	flags = flags;
   1449 	key = key;
   1450 #endif
   1451 	for (i = 0; i < mcount; i++) {
   1452 		char *subj = hfield(key, mp);
   1453 		while( strncasecmp(subj, "Re:", 3) == 0 )
   1454 			subj = skip_WSP(subj + 3);
   1455 		marray[i].mp = mp;
   1456 		marray[i].key.str = subj;
   1457 		marray[i].index = mp->m_index;
   1458 		mp = next_message(mp);
   1459 	}
   1460 }
   1461 
   1462 
   1463 static void
   1464 lines_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
   1465     const char *key __unused, int flags)
   1466 {
   1467 	int i;
   1468 	int use_blines;
   1469 	int use_hlines;
   1470 #ifdef __lint__
   1471 	key = key;
   1472 #endif
   1473 #define HLINES	1
   1474 #define BLINES	2
   1475 #define TLINES	3
   1476 	use_hlines = flags == HLINES;
   1477 	use_blines = flags == BLINES;
   1478 
   1479 	for (i = 0; i < mcount; i++) {
   1480 		marray[i].mp = mp;
   1481 		marray[i].key.lines = use_hlines ? mp->m_lines - mp->m_blines :
   1482 		    use_blines ? mp->m_blines : mp->m_lines;
   1483 		marray[i].index = mp->m_index;
   1484 		mp = next_message(mp);
   1485 	}
   1486 }
   1487 
   1488 static void
   1489 size_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
   1490     const char *key __unused, int flags __unused)
   1491 {
   1492 	int i;
   1493 #ifdef __lint__
   1494 	flags = flags;
   1495 	key = key;
   1496 #endif
   1497 	for (i = 0; i < mcount; i++) {
   1498 		marray[i].mp = mp;
   1499 		marray[i].key.size = mp->m_size;
   1500 		marray[i].index = mp->m_index;
   1501 		mp = next_message(mp);
   1502 	}
   1503 }
   1504 
   1505 static void __unused
   1506 date_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
   1507     const char *key __unused, int flags)
   1508 {
   1509 	int i;
   1510 	int use_hl_date;
   1511 	int zero_hour_min_sec;
   1512 #ifdef __lint__
   1513 	key = key;
   1514 #endif
   1515 #define RDAY 1
   1516 #define SDAY 2
   1517 #define RDATE 3
   1518 #define SDATE 4
   1519 	use_hl_date       = (flags == RDAY || flags == RDATE);
   1520 	zero_hour_min_sec = (flags == RDAY || flags == SDAY);
   1521 
   1522 	for (i = 0; i < mcount; i++) {
   1523 		struct tm tm;
   1524 		(void)dateof(&tm, mp, use_hl_date);
   1525 		if (zero_hour_min_sec) {
   1526 			tm.tm_sec = 0;
   1527 			tm.tm_min = 0;
   1528 			tm.tm_hour = 0;
   1529 		}
   1530 		marray[i].mp = mp;
   1531 		marray[i].key.time = mktime(&tm);
   1532 		marray[i].index = mp->m_index;
   1533 		mp = next_message(mp);
   1534 	}
   1535 }
   1536 
   1537 static void
   1538 from_load(struct key_sort_s *marray, size_t mcount, struct message *mp,
   1539     const char *key __unused, int flags __unused)
   1540 {
   1541 	int i;
   1542 #ifdef __lint__
   1543 	flags = flags;
   1544 	key = key;
   1545 #endif
   1546 	for (i = 0; i < mcount; i++) {
   1547 		marray[i].mp = mp;
   1548 		marray[i].key.str = nameof(mp, 0);
   1549 		marray[i].index = mp->m_index;
   1550 		mp = next_message(mp);
   1551 	}
   1552 }
   1553 
   1554 /************************************************************************
   1555  * The master table that controls all sorting and threading.
   1556  */
   1557 static const struct key_tbl_s {
   1558 	const char *key;
   1559 	void (*loadfn)(struct key_sort_s *, size_t, struct message *, const char *, int);
   1560 	int flags;
   1561 	int (*cmpfn)(const void*, const void*);
   1562 	int (*casecmpfn)(const void*, const void*);
   1563 } key_tbl[] = {
   1564 	{"blines",	lines_load,	BLINES,	keylongcmp,	keylongcmp},
   1565 	{"hlines",	lines_load,	HLINES,	keylongcmp,	keylongcmp},
   1566 	{"tlines",	lines_load,	TLINES,	keylongcmp,	keylongcmp},
   1567 	{"size",	size_load,	0,	keyoffcmp,	keyoffcmp},
   1568 	{"sday",	date_load,	SDAY,	keytimecmp,	keytimecmp},
   1569 	{"rday",	date_load,	RDAY,	keytimecmp,	keytimecmp},
   1570 	{"sdate",	date_load,	SDATE,	keytimecmp,	keytimecmp},
   1571 	{"rdate",	date_load,	RDATE,	keytimecmp,	keytimecmp},
   1572 	{"from",	from_load,	0,	keystrcasecmp,	keystrcasecmp},
   1573 	{"subject",	subj_load,	0,	keystrcmp,	keystrcasecmp},
   1574 	{NULL,		field_load,	0,	keystrcmp,	keystrcasecmp},
   1575 };
   1576 
   1577 #ifdef USE_EDITLINE
   1578 /*
   1579  * This is for use in complete.c to get the list of threading key
   1580  * names without exposing the key_tbl[].  The first name is returned
   1581  * if called with a pointer to a NULL pointer.  Subsequent calls with
   1582  * the same cookie give successive names.  A NULL return indicates the
   1583  * end of the list.
   1584  */
   1585 PUBLIC const char *
   1586 thread_next_key_name(const void **cookie)
   1587 {
   1588 	const struct key_tbl_s *kp;
   1589 
   1590 	kp = *cookie;
   1591 	if (kp == NULL)
   1592 		kp = key_tbl;
   1593 
   1594 	*cookie = kp->key ? &kp[1] : NULL;
   1595 
   1596 	return kp->key;
   1597 }
   1598 #endif /* USE_EDITLINE */
   1599 
   1600 static const struct key_tbl_s *
   1601 get_key(const char *key)
   1602 {
   1603 	const struct key_tbl_s *kp;
   1604 	for (kp = key_tbl; kp->key != NULL; kp++)
   1605 		if (strcmp(kp->key, key) == 0)
   1606 			return kp;
   1607 	return kp;
   1608 }
   1609 
   1610 static int (*
   1611 get_cmpfn(const struct key_tbl_s *kp, int ignorecase)
   1612 )(const void*, const void*)
   1613 {
   1614 	if (ignorecase)
   1615 		return kp->casecmpfn;
   1616 	else
   1617 		return kp->cmpfn;
   1618 }
   1619 
   1620 static void
   1621 thread_current_on(char *str, int modflags, int cutit)
   1622 {
   1623 	const struct key_tbl_s *kp;
   1624 	struct key_sort_s *marray;
   1625 	size_t mcount;
   1626 	state_t oldstate;
   1627 
   1628 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), cutit ? S_EXPOSE : 0);
   1629 
   1630 	kp = get_key(str);
   1631 	mcount = get_msgCount();
   1632 	marray = csalloc(mcount + 1, sizeof(*marray));
   1633 	kp->loadfn(marray, mcount, current_thread.t_head, str,
   1634 	    kp->flags ? kp->flags : modflags & MF_SKIN);
   1635 	cmp.fn = get_cmpfn(kp, modflags & MF_IGNCASE);
   1636 	cmp.inv = modflags & MF_REVERSE;
   1637 	thread_array(marray, mcount, cutit);
   1638 
   1639 	if (!S_IS_EXPOSE(oldstate))
   1640 		dot = thread_top(dot);
   1641 	restore_state(oldstate);
   1642 }
   1643 
   1644 /*
   1645  * The thread command.  Thread the current thread on its references or
   1646  * on a specified field.
   1647  */
   1648 PUBLIC int
   1649 threadcmd(void *v)
   1650 {
   1651 	char *str;
   1652 
   1653 	str = v;
   1654 	if (*str == '\0')
   1655 		thread_on_reference(current_thread.t_head);
   1656 	else {
   1657 		int modflags;
   1658 		modflags = get_modifiers(&str);
   1659 		thread_current_on(str, modflags, 1);
   1660 	}
   1661 	thread_announce(v);
   1662 	return 0;
   1663 }
   1664 
   1665 /*
   1666  * Remove all threading information, reverting to the startup state.
   1667  */
   1668 PUBLIC int
   1669 unthreadcmd(void *v)
   1670 {
   1671 	thread_fix_new_links(message_array.t_head, 0, message_array.t_msgCount);
   1672 	thread_announce(v);
   1673 	return 0;
   1674 }
   1675 
   1676 /*
   1677  * The sort command.
   1678  */
   1679 PUBLIC int
   1680 sortcmd(void *v)
   1681 {
   1682 	int modflags;
   1683 	char *str;
   1684 
   1685 	str = v;
   1686 	modflags = get_modifiers(&str);
   1687 	if (*str != '\0')
   1688 		thread_current_on(str, modflags, 0);
   1689 	else {
   1690 		if (modflags & MF_REVERSE)
   1691 			reversecmd_core(&current_thread);
   1692 		else {
   1693 			(void)printf("sort on what?\n");
   1694 			return 0;
   1695 		}
   1696 	}
   1697 	thread_announce(v);
   1698 	return 0;
   1699 }
   1700 
   1701 
   1702 /*
   1703  * Delete duplicate messages (based on their "Message-Id" field).
   1704  */
   1705 /*ARGSUSED*/
   1706 PUBLIC int
   1707 deldupscmd(void *v __unused)
   1708 {
   1709 	struct message *mp;
   1710 	int depth;
   1711 	state_t oldstate;
   1712 
   1713 	oldstate = set_state(~(S_RESTRICT | S_EXPOSE), S_EXPOSE); /* restrict off, expose on */
   1714 
   1715 	thread_current_on(__UNCONST("Message-Id"), 0, 1);
   1716 	reindex(&current_thread);
   1717 	redepth(&current_thread);
   1718 	depth = current_thread.t_head->m_depth;
   1719 	for (mp = first_message(current_thread.t_head); mp; mp = next_message(mp)) {
   1720 		if (mp->m_depth > depth ) {
   1721 			mp->m_flag &= ~(MPRESERVE | MSAVED | MBOX);
   1722 			mp->m_flag |= MDELETED | MTOUCH;
   1723 			touch(mp);
   1724 		}
   1725 	}
   1726 	dot = thread_top(dot);	/* do this irrespective of the oldstate */
   1727 	restore_state(oldstate);
   1728 /*	thread_announce(v); */
   1729 	return 0;
   1730 }
   1731 
   1732 #endif /* THREAD_SUPPORT */
   1733