move pop into lib-mx.
[apps/madmutt.git] / pager.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
4  *
5  * Parts were written/modified by:
6  * Nico Golde <nico@ngolde.de>
7  * Andreas Krennmair <ak@synflood.at>
8  *
9  * This file is part of mutt-ng, see http://www.muttng.org/.
10  * It's licensed under the GNU General Public License,
11  * please see the file GPL in the top level source directory.
12  */
13
14 #include <lib-lib/lib-lib.h>
15
16 #include <lib-ui/lib-ui.h>
17 #include <lib-ui/menu.h>
18 #include <lib-ui/madtty.h>
19 #include <lib-mx/mx.h>
20
21 #include "mutt.h"
22 #include "crypt.h"
23 #include "alias.h"
24 #include "keymap.h"
25 #include "sort.h"
26 #include "pager.h"
27 #include "attach.h"
28 #include "recvattach.h"
29 #include "charset.h"
30 #include "buffy.h"
31
32 #include <imap/imap_private.h>
33
34 #define ISHEADER(x) ((x) == MT_COLOR_HEADER || (x) == MT_COLOR_HDEFAULT)
35
36 #define IsAttach(x)      (x && (x)->bdy)
37 #define IsRecvAttach(x)  (x && (x)->bdy && (x)->fp)
38 #define IsSendAttach(x)  (x && (x)->bdy && !(x)->fp)
39 #define IsMsgAttach(x)   (x && (x)->fp && (x)->bdy && (x)->bdy->hdr)
40 #define IsHeader(x)      (x && (x)->hdr && !(x)->bdy)
41
42 /* hack to return to position when returning from index to same message */
43 static int TopLine = 0;
44 static HEADER *OldHdr = NULL;
45
46 #define CHECK_MODE(x) \
47     if (!(x)) {                                         \
48         mutt_flushinp();                                \
49         mutt_error _("Not available in this menu.");    \
50         break;                                          \
51     }
52
53 #define CHECK_READONLY \
54     if (Context->readonly) {                            \
55         mutt_flushinp();                                \
56         mutt_error _("Mailbox is read-only.");          \
57         break;                                          \
58     }
59
60 #define CHECK_ATTACH \
61     if (option(OPTATTACHMSG)) {                         \
62         mutt_flushinp();                                \
63         mutt_error _("Function not permitted in attach-message mode."); \
64         break;                                          \
65     }
66
67 struct q_class_t {
68   int length;
69   int index;
70   int color;
71   char *prefix;
72   struct q_class_t *next, *prev;
73   struct q_class_t *down, *up;
74 };
75
76 struct syntax_t {
77   int color;
78   int first;
79   int last;
80 };
81
82 struct line_t {
83   off_t offset;
84   short type;
85   short continuation;
86   short chunks;
87   short search_cnt;
88   struct syntax_t *syntax;
89   struct syntax_t *search;
90   struct q_class_t *quote;
91 };
92
93 #define ANSI_OFF       (1<<0)
94 #define ANSI_BLINK     (1<<1)
95 #define ANSI_BOLD      (1<<2)
96 #define ANSI_UNDERLINE (1<<3)
97 #define ANSI_REVERSE   (1<<4)
98 #define ANSI_COLOR     (1<<5)
99
100 typedef struct _ansi_attr {
101   int attr;
102   int fg;
103   int bg;
104   int pair;
105 } ansi_attr;
106
107 static short InHelp = 0;
108
109 static struct resize {
110   int line;
111   int SearchCompiled;
112   int SearchBack;
113 } *Resize = NULL;
114
115 #define NumSigLines 4
116
117 static int check_sig(const char *s, struct line_t *info, int n)
118 {
119     int count = 0;
120
121     while (n > 0 && count <= NumSigLines) {
122         if (info[n].type != MT_COLOR_SIGNATURE)
123             break;
124         count++;
125         n--;
126     }
127
128     if (count == 0)
129         return -1;
130
131     if (count > NumSigLines) {
132         /* check for a blank line */
133         s = skipspaces(s);
134         return *s ? -1 : 0;
135     }
136
137     return 0;
138 }
139
140 static void
141 resolve_color (struct line_t *lineInfo, int n, int cnt, int flags,
142                int special, ansi_attr * a)
143 {
144   int def_color;                /* color without syntax hilight */
145   int color;                    /* final color */
146   static int last_color;        /* last color set */
147   int search = 0, i, m;
148
149   if (!cnt)
150     last_color = -1;            /* force wattrset(main_w) */
151
152   if (lineInfo[n].continuation) {
153     if (!cnt && option (OPTMARKERS)) {
154       SETCOLOR(main_w, MT_COLOR_MARKERS);
155       waddch(main_w, '+');
156       last_color = ColorDefs[MT_COLOR_MARKERS];
157     }
158     m = (lineInfo[n].syntax)[0].first;
159     cnt += (lineInfo[n].syntax)[0].last;
160   } else {
161     m = n;
162   }
163
164   if (!(flags & M_SHOWCOLOR))
165     def_color = ColorDefs[MT_COLOR_NORMAL];
166   else if (lineInfo[m].type == MT_COLOR_HEADER)
167     def_color = (lineInfo[m].syntax)[0].color;
168   else
169     def_color = ColorDefs[lineInfo[m].type];
170
171   if ((flags & M_SHOWCOLOR) && lineInfo[m].type == MT_COLOR_QUOTED) {
172     struct q_class_t *class = lineInfo[m].quote;
173
174     if (class) {
175       def_color = class->color;
176
177       while (class && class->length > cnt) {
178         def_color = class->color;
179         class = class->up;
180       }
181     }
182   }
183
184   color = def_color;
185   if (flags & M_SHOWCOLOR) {
186     for (i = 0; i < lineInfo[m].chunks; i++) {
187       /* we assume the chunks are sorted */
188       if (cnt > (lineInfo[m].syntax)[i].last)
189         continue;
190       if (cnt < (lineInfo[m].syntax)[i].first)
191         break;
192       if (cnt != (lineInfo[m].syntax)[i].last) {
193         color = (lineInfo[m].syntax)[i].color;
194         break;
195       }
196       /* don't break here, as cnt might be in the next chunk as well */
197     }
198   }
199
200   if (flags & M_SEARCH) {
201     for (i = 0; i < lineInfo[m].search_cnt; i++) {
202       if (cnt > (lineInfo[m].search)[i].last)
203         continue;
204       if (cnt < (lineInfo[m].search)[i].first)
205         break;
206       if (cnt != (lineInfo[m].search)[i].last) {
207         color = ColorDefs[MT_COLOR_SEARCH];
208         search = 1;
209         break;
210       }
211     }
212   }
213
214   /* handle "special" bold & underlined characters */
215   if (special || a->attr) {
216     if ((a->attr & ANSI_COLOR)) {
217       if (a->pair == -1)
218         a->pair = madtty_color_pair(a->fg, a->bg);
219       color = a->pair;
220       if (a->attr & ANSI_BOLD)
221         color |= A_BOLD;
222     } else
223     if ((special & A_BOLD) || (a->attr & ANSI_BOLD)) {
224       if (ColorDefs[MT_COLOR_BOLD] && !search)
225         color = ColorDefs[MT_COLOR_BOLD];
226       else
227         color ^= A_BOLD;
228     }
229     if ((special & A_UNDERLINE) || (a->attr & ANSI_UNDERLINE)) {
230       if (ColorDefs[MT_COLOR_UNDERLINE] && !search)
231         color = ColorDefs[MT_COLOR_UNDERLINE];
232       else
233         color ^= A_UNDERLINE;
234     }
235     else if (a->attr & ANSI_REVERSE) {
236       color ^= A_REVERSE;
237     }
238     else if (a->attr & ANSI_BLINK) {
239       color ^= A_BLINK;
240     }
241     else if (a->attr & ANSI_OFF) {
242       a->attr = 0;
243     }
244   }
245
246   if (color != last_color) {
247     wattrset(main_w, color);
248     last_color = color;
249   }
250 }
251
252 static void append_line (struct line_t *lineInfo, int n, int cnt)
253 {
254   int m;
255
256   lineInfo[n + 1].type = lineInfo[n].type;
257   lineInfo[n + 1].syntax[0].color = lineInfo[n].syntax[0].color;
258   lineInfo[n + 1].continuation = 1;
259
260   /* find the real start of the line */
261   for (m = n; m >= 0; m--)
262       if (lineInfo[m].continuation == 0)
263           break;
264
265   (lineInfo[n + 1].syntax)[0].first = m;
266   (lineInfo[n + 1].syntax)[0].last = (lineInfo[n].continuation) ?
267       cnt + (lineInfo[n].syntax)[0].last : cnt;
268 }
269
270 static void new_class_color (struct q_class_t *class, int *q_level)
271 {
272     class->index = (*q_level)++;
273     class->color = ColorQuote[class->index % ColorQuoteUsed];
274 }
275
276 static void
277 shift_class_colors (struct q_class_t *QuoteList, struct q_class_t *new_class,
278                     int lindex, int *q_level)
279 {
280     struct q_class_t *q_list;
281
282     q_list = QuoteList;
283     new_class->index = -1;
284
285     while (q_list) {
286         if (q_list->index >= lindex) {
287             q_list->index++;
288             q_list->color = ColorQuote[q_list->index % ColorQuoteUsed];
289         }
290         if (q_list->down)
291             q_list = q_list->down;
292         else if (q_list->next)
293             q_list = q_list->next;
294         else {
295             while (!q_list->next) {
296                 q_list = q_list->up;
297                 if (q_list == NULL)
298                     break;
299             }
300             if (q_list)
301                 q_list = q_list->next;
302         }
303     }
304
305     new_class->index = lindex;
306     new_class->color = ColorQuote[lindex % ColorQuoteUsed];
307     (*q_level)++;
308 }
309
310 static void cleanup_quote(struct q_class_t **QuoteList)
311 {
312     while (*QuoteList) {
313         struct q_class_t *ptr = (*QuoteList)->next;
314         cleanup_quote(&(*QuoteList)->down);
315         p_delete(&(*QuoteList)->prefix);
316         p_delete(QuoteList);
317         *QuoteList = ptr;
318     }
319 }
320
321 static struct q_class_t *classify_quote (struct q_class_t **QuoteList,
322                                          const char *qptr, int length,
323                                          int *force_redraw, int *q_level)
324 {
325     struct q_class_t *q_list = *QuoteList;
326     struct q_class_t *class = NULL, *tmp = NULL, *ptr, *save;
327     char *tail_qptr;
328     int offset, tail_lng;
329     int lindex = -1;
330
331     if (ColorQuoteUsed <= 1) {
332         /* not much point in classifying quotes... */
333
334         if (*QuoteList == NULL) {
335             class = p_new(struct q_class_t, 1);
336             class->color = ColorQuote[0];
337             *QuoteList = class;
338         }
339         return *QuoteList;
340     }
341
342     /* Did I mention how much I like emulating Lisp in C? */
343
344     /* classify quoting prefix */
345     while (q_list) {
346         if (length <= q_list->length) {
347             /* case 1: check the top level nodes */
348
349             if (m_strncmp(qptr, q_list->prefix, length) == 0) {
350                 if (length == q_list->length)
351                     return q_list;        /* same prefix: return the current class */
352
353                 /* found shorter prefix */
354                 if (tmp == NULL) {
355                     /* add a node above q_list */
356                     tmp = p_new(struct q_class_t, 1);
357                     tmp->prefix = p_dupstr(qptr, length);
358                     tmp->length = length;
359
360                     /* replace q_list by tmp in the top level list */
361                     if (q_list->next) {
362                         tmp->next = q_list->next;
363                         q_list->next->prev = tmp;
364                     }
365                     if (q_list->prev) {
366                         tmp->prev = q_list->prev;
367                         q_list->prev->next = tmp;
368                     }
369
370                     /* make q_list a child of tmp */
371                     tmp->down = q_list;
372                     q_list->up = tmp;
373
374                     /* q_list has no siblings for now */
375                     q_list->next = NULL;
376                     q_list->prev = NULL;
377
378                     /* update the root if necessary */
379                     if (q_list == *QuoteList)
380                         *QuoteList = tmp;
381
382                     lindex = q_list->index;
383
384                     /* tmp should be the return class too */
385                     class = tmp;
386
387                     /* next class to test; if tmp is a shorter prefix for another
388                      * node, that node can only be in the top level list, so don't
389                      * go down after this point
390                      */
391                     q_list = tmp->next;
392                 } else {
393                     /* found another branch for which tmp is a shorter prefix */
394
395                     /* save the next sibling for later */
396                     save = q_list->next;
397
398                     /* unlink q_list from the top level list */
399                     if (q_list->next)
400                         q_list->next->prev = q_list->prev;
401                     if (q_list->prev)
402                         q_list->prev->next = q_list->next;
403
404                     /* at this point, we have a tmp->down; link q_list to it */
405                     ptr = tmp->down;
406                     /* sibling order is important here, q_list should be linked last */
407                     while (ptr->next)
408                         ptr = ptr->next;
409                     ptr->next = q_list;
410                     q_list->next = NULL;
411                     q_list->prev = ptr;
412                     q_list->up = tmp;
413
414                     lindex = q_list->index;
415
416                     /* next class to test; as above, we shouldn't go down */
417                     q_list = save;
418                 }
419
420                 /* we found a shorter prefix, so certain quotes have changed classes */
421                 *force_redraw = 1;
422                 continue;
423             } else {
424                 /* shorter, but not a substring of the current class: try next */
425                 q_list = q_list->next;
426                 continue;
427             }
428         } else {
429             /* case 2: try subclassing the current top level node */
430
431             /* tmp != NULL means we already found a shorter prefix at case 1 */
432             if (tmp == NULL
433                 && m_strncmp(qptr, q_list->prefix, q_list->length) == 0) {
434                 /* ok, it's a subclass somewhere on this branch */
435
436                 ptr = q_list;
437                 offset = q_list->length;
438
439                 q_list = q_list->down;
440                 tail_lng = length - offset;
441                 tail_qptr = (char *) qptr + offset;
442
443                 while (q_list) {
444                     if (length <= q_list->length) {
445                         if (m_strncmp(tail_qptr, (q_list->prefix) + offset, tail_lng)
446                             == 0) {
447                             /* same prefix: return the current class */
448                             if (length == q_list->length)
449                                 return q_list;
450
451                             /* found shorter common prefix */
452                             if (tmp == NULL) {
453                                 /* add a node above q_list */
454                                 tmp = p_new(struct q_class_t, 1);
455                                 tmp->prefix = p_dupstr(qptr, length);
456                                 tmp->length = length;
457
458                                 /* replace q_list by tmp */
459                                 if (q_list->next) {
460                                     tmp->next = q_list->next;
461                                     q_list->next->prev = tmp;
462                                 }
463                                 if (q_list->prev) {
464                                     tmp->prev = q_list->prev;
465                                     q_list->prev->next = tmp;
466                                 }
467
468                                 /* make q_list a child of tmp */
469                                 tmp->down = q_list;
470                                 tmp->up = q_list->up;
471                                 q_list->up = tmp;
472                                 if (tmp->up->down == q_list)
473                                     tmp->up->down = tmp;
474
475                                 /* q_list has no siblings */
476                                 q_list->next = NULL;
477                                 q_list->prev = NULL;
478
479                                 lindex = q_list->index;
480
481                                 /* tmp should be the return class too */
482                                 class = tmp;
483
484                                 /* next class to test */
485                                 q_list = tmp->next;
486                             } else {
487                                 /* found another branch for which tmp is a shorter prefix */
488
489                                 /* save the next sibling for later */
490                                 save = q_list->next;
491
492                                 /* unlink q_list from the top level list */
493                                 if (q_list->next)
494                                     q_list->next->prev = q_list->prev;
495                                 if (q_list->prev)
496                                     q_list->prev->next = q_list->next;
497
498                                 /* at this point, we have a tmp->down; link q_list to it */
499                                 ptr = tmp->down;
500                                 while (ptr->next)
501                                     ptr = ptr->next;
502                                 ptr->next = q_list;
503                                 q_list->next = NULL;
504                                 q_list->prev = ptr;
505                                 q_list->up = tmp;
506
507                                 lindex = q_list->index;
508
509                                 /* next class to test */
510                                 q_list = save;
511                             }
512
513                             /* we found a shorter prefix, so we need a redraw */
514                             *force_redraw = 1;
515                             continue;
516                         } else {
517                             q_list = q_list->next;
518                             continue;
519                         }
520                     } else {
521                         /* longer than the current prefix: try subclassing it */
522                         if (tmp == NULL
523                             && m_strncmp(tail_qptr, (q_list->prefix) + offset,
524                                          q_list->length - offset) == 0) {
525                             /* still a subclass: go down one level */
526                             ptr = q_list;
527                             offset = q_list->length;
528
529                             q_list = q_list->down;
530                             tail_lng = length - offset;
531                             tail_qptr = (char *) qptr + offset;
532
533                             continue;
534                         } else {
535                             /* nope, try the next prefix */
536                             q_list = q_list->next;
537                             continue;
538                         }
539                     }
540                 }
541
542                 /* still not found so far: add it as a sibling to the current node */
543                 if (class == NULL) {
544                     tmp = p_new(struct q_class_t, 1);
545                     tmp->prefix = p_dupstr(qptr, length);
546                     tmp->length = length;
547
548                     if (ptr->down) {
549                         tmp->next = ptr->down;
550                         ptr->down->prev = tmp;
551                     }
552                     ptr->down = tmp;
553                     tmp->up = ptr;
554
555                     new_class_color (tmp, q_level);
556
557                     return tmp;
558                 } else {
559                     if (lindex != -1)
560                         shift_class_colors (*QuoteList, tmp, lindex, q_level);
561
562                     return class;
563                 }
564             } else {
565                 /* nope, try the next prefix */
566                 q_list = q_list->next;
567                 continue;
568             }
569         }
570     }
571
572     if (class == NULL) {
573         /* not found so far: add it as a top level class */
574         class = p_new(struct q_class_t, 1);
575         class->prefix = p_dupstr(qptr, length);
576         class->length = length;
577         new_class_color (class, q_level);
578
579         if (*QuoteList) {
580             class->next = *QuoteList;
581             (*QuoteList)->prev = class;
582         }
583         *QuoteList = class;
584     }
585
586     if (lindex != -1)
587         shift_class_colors (*QuoteList, tmp, lindex, q_level);
588
589     return class;
590 }
591
592 static int check_attachment_marker (char *);
593
594 static void
595 resolve_types (char *buf, char *rawbuf, struct line_t *lineInfo, int n, int last,
596                struct q_class_t **QuoteList, int *q_level, int *force_redraw,
597                int q_classify)
598 {
599     COLOR_LINE *color_line;
600     regmatch_t pmatch[1], smatch[1];
601     int found, offset, null_rx, i;
602
603     if (n == 0 || ISHEADER (lineInfo[n - 1].type)) {
604         if (buf[0] == '\n') {
605             lineInfo[n].type = MT_COLOR_NORMAL;
606         }
607         else if (n > 0 && (buf[0] == ' ' || buf[0] == '\t')) {
608             lineInfo[n].type = lineInfo[n - 1].type;  /* wrapped line */
609             (lineInfo[n].syntax)[0].color = (lineInfo[n - 1].syntax)[0].color;
610         } else {
611             lineInfo[n].type = MT_COLOR_HDEFAULT;
612             color_line = ColorHdrList;
613             while (color_line) {
614                 if (REGEXEC (&color_line->rx, buf) == 0) {
615                     lineInfo[n].type = MT_COLOR_HEADER;
616                     lineInfo[n].syntax[0].color = color_line->pair;
617                     break;
618                 }
619                 color_line = color_line->next;
620             }
621         }
622     }
623     else if (m_strncmp("\033[0m", rawbuf, 4) == 0)       /* a little hack... */
624         lineInfo[n].type = MT_COLOR_NORMAL;
625     else if (check_attachment_marker ((char *) rawbuf) == 0)
626         lineInfo[n].type = MT_COLOR_ATTACHMENT;
627     else if (m_strcmp("-- \n", buf) == 0
628              || m_strcmp("-- \r\n", buf) == 0) {
629         i = n + 1;
630
631         lineInfo[n].type = MT_COLOR_SIGNATURE;
632         while (i < last && check_sig(buf, lineInfo, i - 1) == 0 &&
633                (lineInfo[i].type == MT_COLOR_NORMAL ||
634                 lineInfo[i].type == MT_COLOR_QUOTED ||
635                 lineInfo[i].type == MT_COLOR_HEADER)) {
636             /* oops... */
637             if (lineInfo[i].chunks) {
638                 lineInfo[i].chunks = 0;
639                 p_realloc(&(lineInfo[n].syntax), 1);
640             }
641             lineInfo[i++].type = MT_COLOR_SIGNATURE;
642         }
643     }
644     else if (check_sig(buf, lineInfo, n - 1) == 0)
645         lineInfo[n].type = MT_COLOR_SIGNATURE;
646     else if (regexec ((regex_t *) QuoteRegexp.rx, buf, 1, pmatch, 0) == 0) {
647         if (regexec ((regex_t *) Smileys.rx, buf, 1, smatch, 0) == 0) {
648             if (smatch[0].rm_so > 0) {
649                 char c;
650
651                 /* hack to avoid making an extra copy of buf */
652                 c = buf[smatch[0].rm_so];
653                 buf[smatch[0].rm_so] = 0;
654
655                 if (regexec ((regex_t *) QuoteRegexp.rx, buf, 1, pmatch, 0) == 0) {
656                     if (q_classify && lineInfo[n].quote == NULL)
657                         lineInfo[n].quote = classify_quote (QuoteList,
658                                                             buf + pmatch[0].rm_so,
659                                                             pmatch[0].rm_eo -
660                                                             pmatch[0].rm_so, force_redraw,
661                                                             q_level);
662                     lineInfo[n].type = MT_COLOR_QUOTED;
663                 } else {
664                     lineInfo[n].type = MT_COLOR_NORMAL;
665                 }
666
667                 buf[smatch[0].rm_so] = c;
668             } else {
669                 lineInfo[n].type = MT_COLOR_NORMAL;
670             }
671         } else {
672             if (q_classify && lineInfo[n].quote == NULL)
673                 lineInfo[n].quote = classify_quote (QuoteList, buf + pmatch[0].rm_so,
674                                                     pmatch[0].rm_eo - pmatch[0].rm_so,
675                                                     force_redraw, q_level);
676             lineInfo[n].type = MT_COLOR_QUOTED;
677         }
678     } else {
679         lineInfo[n].type = MT_COLOR_NORMAL;
680     }
681
682     /* body patterns */
683     if (lineInfo[n].type == MT_COLOR_NORMAL ||
684         lineInfo[n].type == MT_COLOR_QUOTED) {
685         i = 0;
686
687         offset = 0;
688         lineInfo[n].chunks = 0;
689         do {
690             if (!buf[offset])
691                 break;
692
693             found = 0;
694             null_rx = 0;
695             color_line = ColorBodyList;
696             while (color_line) {
697                 if (regexec (&color_line->rx, buf + offset, 1, pmatch,
698                              (offset ? REG_NOTBOL : 0)) == 0) {
699                     if (pmatch[0].rm_eo != pmatch[0].rm_so) {
700                         if (!found) {
701                             if (++(lineInfo[n].chunks) > 1)
702                                 p_realloc(&(lineInfo[n].syntax), lineInfo[n].chunks);
703                         }
704                         i = lineInfo[n].chunks - 1;
705                         pmatch[0].rm_so += offset;
706                         pmatch[0].rm_eo += offset;
707                         if (!found ||
708                             pmatch[0].rm_so < (lineInfo[n].syntax)[i].first ||
709                             (pmatch[0].rm_so == (lineInfo[n].syntax)[i].first &&
710                              pmatch[0].rm_eo > (lineInfo[n].syntax)[i].last)) {
711                             (lineInfo[n].syntax)[i].color = color_line->pair;
712                             (lineInfo[n].syntax)[i].first = pmatch[0].rm_so;
713                             (lineInfo[n].syntax)[i].last = pmatch[0].rm_eo;
714                         }
715                         found = 1;
716                         null_rx = 0;
717                     } else {
718                         null_rx = 1;        /* empty regexp; don't add it, but keep looking */
719                     }
720                 }
721                 color_line = color_line->next;
722             }
723
724             if (null_rx)
725                 offset++;               /* avoid degenerate cases */
726             else
727                 offset = lineInfo[n].syntax[i].last;
728         } while (found || null_rx);
729     }
730 }
731
732 static int is_ansi(unsigned char *buf)
733 {
734     while (isdigit(*buf) || *buf == ';')
735         buf++;
736     return *buf == 'm';
737 }
738
739 static int check_attachment_marker(char *p)
740 {
741     char *q = AttachmentMarker;
742
743     for (; *p == *q && *q && *p && *q != '\a' && *p != '\a'; p++, q++);
744     return (int)(*p - *q);
745 }
746
747 /* trim tail of buf so that it contains complete multibyte characters */
748 static int trim_incomplete_mbyte(unsigned char *buf, size_t len) {
749     mbstate_t mbstate;
750     ssize_t k;
751
752     p_clear(&mbstate, 1);
753     for (; len > 0; buf += k, len -= k) {
754         k = mbrtowc (NULL, (char *) buf, len, &mbstate);
755         if (k == -2)
756             break;
757         if (k == -1 || k == 0)
758             k = 1;
759     }
760     *buf = '\0';
761
762     return len;
763 }
764
765 static int
766 fill_buffer (FILE * f, off_t *last_pos, off_t offset, unsigned char *buf,
767              unsigned char *fmt, ssize_t blen, int *buf_ready)
768 {
769     unsigned char *p;
770     static int b_read = 0;
771
772     if (*buf_ready == 0) {
773         buf[blen - 1] = 0;
774         if (offset != *last_pos)
775             fseeko (f, offset, 0);
776         if (fgets ((char *) buf, blen - 1, f) == NULL) {
777             fmt[0] = 0;
778             return -1;
779         }
780         *last_pos = ftello (f);
781         b_read = (int) (*last_pos - offset);
782         *buf_ready = 1;
783
784         /* incomplete mbyte characters trigger a segfault in regex processing for
785          * certain versions of glibc. Trim them if necessary. */
786         if (b_read == blen - 2)
787             b_read -= trim_incomplete_mbyte(buf, b_read);
788
789         /* copy "buf" to "fmt", but without bold and underline controls */
790         p = buf;
791         while (*p) {
792             if (*p == '\010' && (p > buf)) {
793                 if (*(p + 1) == '_')    /* underline */
794                     p += 2;
795                 else if (*(p + 1)) {    /* bold or overstrike */
796                     *(fmt - 1) = *(p + 1);
797                     p += 2;
798                 } else {                  /* ^H */
799                     *fmt++ = *p++;
800                 }
801             }
802             else if (*p == '\033' && *(p + 1) == '[' && is_ansi (p + 2)) {
803                 while (*p++ != 'm')     /* skip ANSI sequence */
804                     ;
805             }
806             else if (*p == '\033' && *(p + 1) == ']'
807                      && check_attachment_marker ((char *) p) == 0) {
808                 while (*p++ != '\a')    /* skip pseudo-ANSI sequence */
809                     ;
810             } else {
811                 *fmt++ = *p++;
812             }
813         }
814         *fmt = 0;
815     }
816     return b_read;
817 }
818
819 static int format_line (struct line_t **lineInfo, int n, unsigned char *buf,
820                         int flags, ansi_attr * pa, int cnt,
821                         int *pspace, int *pvch, int *pcol, int *pspecial)
822 {
823   int space = -1;               /* index of the last space or TAB */
824   int col = option (OPTMARKERS) ? (*lineInfo)[n].continuation : 0;
825   int ch, vch, k, last_special = -1, special = 0, t;
826   wchar_t wc;
827   mbstate_t mbstate;
828
829   int wrap_cols = getmaxx(main_w);
830
831   if (!(flags & (M_SHOWFLAT)))
832     wrap_cols -= WrapMargin;
833
834   if (wrap_cols <= 0)
835     wrap_cols = getmaxx(main_w);
836
837   /* FIXME: this should come from lineInfo */
838   p_clear(&mbstate, 1);
839
840   for (ch = 0, vch = 0; ch < cnt; ch += k, vch += k) {
841     /* Handle ANSI sequences */
842     while (cnt - ch >= 2 && buf[ch] == '\033' && buf[ch + 1] == '[' &&
843            is_ansi (buf + ch + 2)) {
844       while (isdigit(buf[ch]) || buf[ch] == ';')
845         ch++;
846     }
847
848     while (cnt - ch >= 2 && buf[ch] == '\033' && buf[ch + 1] == ']' &&
849            check_attachment_marker ((char *) buf + ch) == 0) {
850       while (buf[ch++] != '\a')
851         if (ch >= cnt)
852           break;
853     }
854
855     /* is anything left to do? */
856     if (ch >= cnt)
857       break;
858
859     k = mbrtowc (&wc, (char *) buf + ch, cnt - ch, &mbstate);
860     if (k == -2 || k == -1) {
861       if (col + 4 > wrap_cols)
862         break;
863       col += 4;
864       if (pa)
865         wprintw(main_w, "\\%03o", buf[ch]);
866       k = 1;
867       continue;
868     }
869     if (k == 0)
870       k = 1;
871
872     /* Handle backspace */
873     special = 0;
874     if (iswprint(wc)) {
875       wchar_t wc1;
876       mbstate_t mbstate1;
877       int k1, k2;
878
879       while ((wc1 = 0, mbstate1 = mbstate,
880               k1 =
881               k + mbrtowc (&wc1, (char *) buf + ch + k, cnt - ch - k,
882                            &mbstate1), k1 - k > 0 && wc1 == '\b')
883              && (wc1 = 0, k2 =
884                  mbrtowc (&wc1, (char *) buf + ch + k1, cnt - ch - k1,
885                           &mbstate1), k2 > 0 && iswprint(wc1))) {
886         if (wc == wc1) {
887           special |= (wc == '_' && special & A_UNDERLINE)
888             ? A_UNDERLINE : A_BOLD;
889         }
890         else if (wc == '_' || wc1 == '_') {
891           special |= A_UNDERLINE;
892           wc = (wc1 == '_') ? wc : wc1;
893         } else {
894           /* special = 0; / * overstrike: nothing to do! */
895           wc = wc1;
896         }
897         ch += k1;
898         k = k2;
899         mbstate = mbstate1;
900       }
901     }
902
903     if (pa &&
904         ((flags & (M_SHOWCOLOR | M_SEARCH | M_PAGER_MARKER)) ||
905          special || last_special || pa->attr)) {
906       resolve_color (*lineInfo, n, vch, flags, special, pa);
907       last_special = special;
908     }
909
910     if (iswprint(wc)) {
911       if (wc == ' ')
912         space = ch;
913       t = wcwidth (wc);
914       if (col + t > wrap_cols)
915         break;
916       col += t;
917       if (pa)
918         waddwch(main_w, wc);
919     }
920     else if (wc == '\n')
921       break;
922     else if (wc == '\t') {
923       space = ch;
924       t = (col & ~7) + 8;
925       if (t > wrap_cols)
926         break;
927       if (pa)
928         for (; col < t; col++)
929           waddch(main_w, ' ');
930       else
931         col = t;
932     }
933     else if (wc < 0x20 || wc == 0x7f) {
934       if (col + 2 > wrap_cols)
935         break;
936       col += 2;
937       if (pa)
938         wprintw(main_w, "^%c", ('@' + wc) & 0x7f);
939     }
940     else if (wc < 0x100) {
941       if (col + 4 > wrap_cols)
942         break;
943       col += 4;
944       if (pa)
945         wprintw(main_w, "\\%03o", wc);
946     } else {
947       if (col + 1 > wrap_cols)
948         break;
949       ++col;
950       if (pa)
951         waddch(main_w, CharsetReplacement);
952     }
953   }
954   *pspace = space;
955   *pcol = col;
956   *pvch = vch;
957   *pspecial = special;
958   return ch;
959 }
960
961 /*
962  * Args:
963  *      flags   M_SHOWFLAT, show characters (used for displaying help)
964  *              M_SHOWCOLOR, show characters in color
965  *                      otherwise don't show characters
966  *              M_HIDE, don't show quoted text
967  *              M_SEARCH, resolve search patterns
968  *              M_TYPES, compute line's type
969  *              M_PAGER_NSKIP, keeps leading whitespace
970  *              M_PAGER_MARKER, eventually show markers
971  *
972  * Return values:
973  *      -1      EOF was reached
974  *      0       normal exit, line was not displayed
975  *      >0      normal exit, line was displayed
976  */
977 static int
978 display_line (FILE * f, off_t *last_pos, struct line_t **lineInfo, int n,
979               int *last, int *max, int flags, struct q_class_t **QuoteList,
980               int *q_level, int *force_redraw, regex_t * SearchRE)
981 {
982   unsigned char buf[LONG_STRING], fmt[LONG_STRING];
983   unsigned char *buf_ptr = buf;
984   int ch, vch, col, cnt, b_read;
985   int buf_ready = 0, change_last = 0;
986   int special;
987   int offset;
988   int def_color;
989   int m;
990   ansi_attr a = { 0, 0, 0, -1 };
991   regmatch_t pmatch[1];
992
993   if (n == *last) {
994     (*last)++;
995     change_last = 1;
996   }
997
998   if (*last == *max) {
999     p_realloc(lineInfo, *max += LINES);
1000     for (ch = *last; ch < *max; ch++) {
1001       p_clear(&(*lineInfo)[ch], 1);
1002       (*lineInfo)[ch].type = -1;
1003       (*lineInfo)[ch].search_cnt = -1;
1004       (*lineInfo)[ch].syntax = p_new(struct syntax_t, 1);
1005       ((*lineInfo)[ch].syntax)[0].first = ((*lineInfo)[ch].syntax)[0].last =
1006         -1;
1007     }
1008   }
1009
1010   /* only do color hiliting if we are viewing a message */
1011   if (flags & (M_SHOWCOLOR | M_TYPES)) {
1012     if ((*lineInfo)[n].type == -1) {
1013       /* determine the line class */
1014       if (fill_buffer
1015           (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1016            &buf_ready) < 0) {
1017         if (change_last)
1018           (*last)--;
1019         return -1;
1020       }
1021
1022       resolve_types ((char *) fmt, (char *) buf, *lineInfo, n, *last,
1023                      QuoteList, q_level, force_redraw, flags & M_SHOWCOLOR);
1024
1025       /* avoid race condition for continuation lines when scrolling up */
1026       for (m = n + 1;
1027            m < *last && (*lineInfo)[m].offset && (*lineInfo)[m].continuation;
1028            m++)
1029         (*lineInfo)[m].type = (*lineInfo)[n].type;
1030     }
1031
1032     /* this also prevents searching through the hidden lines */
1033     if ((flags & M_HIDE) && (*lineInfo)[n].type == MT_COLOR_QUOTED)
1034       flags = 0;                /* M_NOSHOW */
1035   }
1036
1037   /* At this point, (*lineInfo[n]).quote may still be undefined. We 
1038    * don't want to compute it every time M_TYPES is set, since this
1039    * would slow down the "bottom" function unacceptably. A compromise
1040    * solution is hence to call regexec() again, just to find out the
1041    * length of the quote prefix.
1042    */
1043   if ((flags & M_SHOWCOLOR) && !(*lineInfo)[n].continuation &&
1044       (*lineInfo)[n].type == MT_COLOR_QUOTED && (*lineInfo)[n].quote == NULL)
1045   {
1046     if (fill_buffer
1047         (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1048          &buf_ready) < 0) {
1049       if (change_last)
1050         (*last)--;
1051       return -1;
1052     }
1053     regexec ((regex_t *) QuoteRegexp.rx, (char *) fmt, 1, pmatch, 0);
1054     (*lineInfo)[n].quote = classify_quote (QuoteList,
1055                                            (char *) fmt + pmatch[0].rm_so,
1056                                            pmatch[0].rm_eo - pmatch[0].rm_so,
1057                                            force_redraw, q_level);
1058   }
1059
1060   if ((flags & M_SEARCH) && !(*lineInfo)[n].continuation
1061       && (*lineInfo)[n].search_cnt == -1) {
1062     if (fill_buffer
1063         (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1064          &buf_ready) < 0) {
1065       if (change_last)
1066         (*last)--;
1067       return -1;
1068     }
1069
1070     offset = 0;
1071     (*lineInfo)[n].search_cnt = 0;
1072     while (regexec
1073            (SearchRE, (char *) fmt + offset, 1, pmatch,
1074             (offset ? REG_NOTBOL : 0)) == 0) {
1075       if (++((*lineInfo)[n].search_cnt) > 1)
1076         p_realloc(&(*lineInfo)[n].search, (*lineInfo)[n].search_cnt);
1077       else
1078         (*lineInfo)[n].search = p_new(struct syntax_t, 1);
1079       pmatch[0].rm_so += offset;
1080       pmatch[0].rm_eo += offset;
1081       ((*lineInfo)[n].search)[(*lineInfo)[n].search_cnt - 1].first =
1082         pmatch[0].rm_so;
1083       ((*lineInfo)[n].search)[(*lineInfo)[n].search_cnt - 1].last =
1084         pmatch[0].rm_eo;
1085
1086       if (pmatch[0].rm_eo == pmatch[0].rm_so)
1087         offset++;               /* avoid degenerate cases */
1088       else
1089         offset = pmatch[0].rm_eo;
1090       if (!fmt[offset])
1091         break;
1092     }
1093   }
1094
1095   if (!(flags & M_SHOW) && (*lineInfo)[n + 1].offset > 0) {
1096     /* we've already scanned this line, so just exit */
1097     return 0;
1098   }
1099   if ((flags & M_SHOWCOLOR) && *force_redraw && (*lineInfo)[n + 1].offset > 0) {
1100     /* no need to try to display this line... */
1101     return 1;                 /* fake display */
1102   }
1103
1104   if ((b_read = fill_buffer (f, last_pos, (*lineInfo)[n].offset, buf, fmt,
1105                              sizeof (buf), &buf_ready)) < 0) {
1106     if (change_last)
1107       (*last)--;
1108     return -1;
1109   }
1110
1111   /* now chose a good place to break the line */
1112   cnt = format_line(lineInfo, n, buf, flags, 0, b_read, &ch, &vch, &col,
1113                     &special);
1114   buf_ptr = buf + cnt;
1115
1116   /* move the break point only if smart_wrap is set */
1117   if (option (OPTWRAP)) {
1118     if (cnt < b_read) {
1119       if (ch != -1 && buf[cnt] != ' ' && buf[cnt] != '\t' && buf[cnt] != '\n'
1120           && buf[cnt] != '\r') {
1121         buf_ptr = buf + ch;
1122         /* skip trailing blanks */
1123         while (ch && (buf[ch] == ' ' || buf[ch] == '\t' || buf[ch] == '\r'))
1124           ch--;
1125         /* a very long word with leading spaces causes infinite wrapping */
1126         if ((!ch) && (flags & M_PAGER_NSKIP))
1127           buf_ptr = buf + cnt;
1128         else
1129           cnt = ch + 1;
1130       } else {
1131         buf_ptr = buf + cnt;    /* a very long word... */
1132       }
1133     }
1134     if (!(flags & M_PAGER_NSKIP))
1135       /* skip leading blanks on the next line too */
1136       while (*buf_ptr == ' ' || *buf_ptr == '\t')
1137         buf_ptr++;
1138   }
1139
1140   if (*buf_ptr == '\r')
1141     buf_ptr++;
1142   if (*buf_ptr == '\n')
1143     buf_ptr++;
1144
1145   if ((int) (buf_ptr - buf) < b_read && !(*lineInfo)[n + 1].continuation)
1146     append_line (*lineInfo, n, (int) (buf_ptr - buf));
1147   (*lineInfo)[n + 1].offset = (*lineInfo)[n].offset + (long) (buf_ptr - buf);
1148
1149   /* if we don't need to display the line we are done */
1150   if (!(flags & M_SHOW))
1151     return 0;
1152
1153   /* display the line */
1154   format_line (lineInfo, n, buf, flags, &a, cnt, &ch, &vch, &col, &special);
1155
1156   /* end the last color pattern (needed by S-Lang) */
1157   if (special || (col != getmaxx(main_w) && (flags & (M_SHOWCOLOR | M_SEARCH))))
1158     resolve_color(*lineInfo, n, vch, flags, 0, &a);
1159
1160   /*
1161    * Fill the blank space at the end of the line with the prevailing color.
1162    * ncurses does an implicit wclrtoeol(main_w) when you do waddch(main_w,
1163    * '\n') so we have to make sure to reset the color *after* that
1164    */
1165   if (flags & M_SHOWCOLOR) {
1166     m = ((*lineInfo)[n].continuation) ? ((*lineInfo)[n].syntax)[0].first : n;
1167     if ((*lineInfo)[m].type == MT_COLOR_HEADER)
1168       def_color = ((*lineInfo)[m].syntax)[0].color;
1169     else
1170       def_color = ColorDefs[(*lineInfo)[m].type];
1171
1172     wattrset(main_w, def_color);
1173     wbkgdset(main_w, def_color | ' ');
1174   }
1175   waddch(main_w, '\n');
1176
1177   /*
1178    * reset the color back to normal.  This *must* come after the
1179    * waddch(main_w, '\n'), otherwise the color for this line will not be
1180    * filled to the right margin.
1181    */
1182   if (flags & M_SHOWCOLOR) {
1183     SETCOLOR(main_w, MT_COLOR_NORMAL);
1184     BKGDSET(main_w, MT_COLOR_NORMAL);
1185   }
1186
1187   /* build a return code */
1188   if (!(flags & M_SHOW))
1189     flags = 0;
1190
1191   return flags;
1192 }
1193
1194 static int upNLines (int nlines, struct line_t *info, int cur, int hiding)
1195 {
1196   while (cur > 0 && nlines > 0) {
1197     cur--;
1198     if (!hiding || info[cur].type != MT_COLOR_QUOTED)
1199       nlines--;
1200   }
1201
1202   return cur;
1203 }
1204
1205 /* This pager is actually not so simple as it once was.  It now operates in
1206    two modes: one for viewing messages and the other for viewing help.  These
1207    can be distinguished by whether or not ``hdr'' is NULL.  The ``hdr'' arg
1208    is there so that we can do operations on the current message without the
1209    need to pop back out to the main-menu.  */
1210 int
1211 mutt_pager (const char *banner, const char *fname, int flags, pager_t * extra)
1212 {
1213   static char searchbuf[STRING];
1214   char buffer[LONG_STRING];
1215   int maxLine, lastLine = 0;
1216   struct line_t *lineInfo;
1217   struct q_class_t *QuoteList = NULL;
1218   int i, j, ch = 0, rc = -1, hideQuoted = 0, q_level = 0, force_redraw = 0;
1219   int lines = 0, curline = 0, topline = 0, oldtopline = 0, err, first = 1;
1220   int r = -1;
1221   int redraw = REDRAW_FULL;
1222   FILE *fp = NULL;
1223   off_t last_pos = 0, last_offset = 0;
1224   int old_smart_wrap, old_markers;
1225   struct stat sb;
1226   regex_t SearchRE;
1227   int SearchCompiled = 0, SearchFlag = 0, SearchBack = 0;
1228   int has_types = (IsHeader (extra) || (flags & M_SHOWCOLOR)) ? M_TYPES : 0;    /* main message or rfc822 attachment */
1229
1230   int bodyoffset = 1;           /* offset of first line of real text */
1231   int statusoffset = 0;         /* offset for the status bar */
1232   int bodylen = LINES - 2 - bodyoffset; /* length of displayable area */
1233
1234   MUTTMENU *pager_index = NULL;       /* the Pager Index (PI) */
1235   int indexlen = PagerIndexLines;     /* indexlen not always == PIL */
1236   int indicator = indexlen / 3; /* the indicator line of the PI */
1237   int old_PagerIndexLines;      /* some people want to resize it
1238                                  * while inside the pager... */
1239
1240   if (!(flags & M_SHOWCOLOR))
1241     flags |= M_SHOWFLAT;
1242
1243   if ((fp = fopen (fname, "r")) == NULL) {
1244     mutt_perror (fname);
1245     return -1;
1246   }
1247
1248   if (stat (fname, &sb) != 0) {
1249     mutt_perror (fname);
1250     m_fclose(&fp);
1251     return -1;
1252   }
1253   unlink (fname);
1254
1255   /* Initialize variables */
1256
1257   if (IsHeader (extra) && !extra->hdr->read) {
1258     Context->msgnotreadyet = extra->hdr->msgno;
1259     mutt_set_flag (Context, extra->hdr, M_READ, 1);
1260   }
1261
1262   lineInfo = p_new(struct line_t, maxLine = LINES);
1263   for (i = 0; i < maxLine; i++) {
1264     p_clear(&lineInfo[i], 1);
1265     lineInfo[i].type = -1;
1266     lineInfo[i].search_cnt = -1;
1267     lineInfo[i].syntax = p_new(struct syntax_t, 1);
1268     (lineInfo[i].syntax)[0].first = (lineInfo[i].syntax)[0].last = -1;
1269   }
1270
1271   while (ch != -1) {
1272     mutt_curs_set (0);
1273     imap_keepalive ();
1274
1275     if (redraw & REDRAW_FULL) {
1276       SETCOLOR(main_w, MT_COLOR_NORMAL);
1277       werase(main_w);
1278
1279       if (IsHeader (extra) && Context->vcount + 1 < PagerIndexLines)
1280         indexlen = Context->vcount + 1;
1281       else
1282         indexlen = PagerIndexLines;
1283
1284       indicator = indexlen / 3;
1285
1286       statusoffset = IsHeader (extra) ? indexlen : 0;
1287       bodyoffset   = statusoffset + 1;
1288       bodylen      = LINES - 2 - bodyoffset;
1289
1290       SETCOLOR(main_w, MT_COLOR_SIDEBAR);
1291       mvwhline(main_w, LINES - 2, 0, ACS_HLINE, getmaxx(main_w));
1292       SETCOLOR(main_w, MT_COLOR_NORMAL);
1293
1294       if (Resize != NULL) {
1295         if ((SearchCompiled = Resize->SearchCompiled)) {
1296           REGCOMP
1297             (&SearchRE, searchbuf, REG_NEWLINE | mutt_which_case (searchbuf));
1298           SearchFlag = M_SEARCH;
1299           SearchBack = Resize->SearchBack;
1300         }
1301         lines = Resize->line;
1302         redraw |= REDRAW_SIGWINCH;
1303
1304         p_delete(&Resize);
1305       }
1306
1307       if (IsHeader (extra) && PagerIndexLines) {
1308         if (pager_index == NULL) {
1309           /* only allocate the space if/when we need the index.
1310              Initialise the menu as per the main index */
1311           pager_index = mutt_new_menu ();
1312           pager_index->menu = MENU_MAIN;
1313           pager_index->make_entry = index_make_entry;
1314           pager_index->color = index_color;
1315           pager_index->max = Context->vcount;
1316           pager_index->current = extra->hdr->virtual;
1317         }
1318
1319         SETCOLOR(main_w, MT_COLOR_NORMAL);
1320         pager_index->offset  = 1;
1321         pager_index->pagelen = indexlen - 1;
1322
1323         /* some fudge to work out where abouts the indicator should go */
1324         if (pager_index->current - indicator < 0)
1325           pager_index->top = 0;
1326         else if (pager_index->max - pager_index->current < pager_index->pagelen - indicator)
1327           pager_index->top = pager_index->max - pager_index->pagelen;
1328         else
1329           pager_index->top = pager_index->current - indicator;
1330
1331         menu_redraw_index (pager_index);
1332       }
1333
1334       redraw |= REDRAW_BODY | REDRAW_INDEX | REDRAW_STATUS;
1335       mutt_show_error ();
1336     }
1337
1338     if (redraw & REDRAW_SIGWINCH) {
1339       i = -1;
1340       j = -1;
1341       while (display_line (fp, &last_pos, &lineInfo, ++i, &lastLine, &maxLine,
1342                            has_types | SearchFlag, &QuoteList, &q_level,
1343                            &force_redraw, &SearchRE) == 0) {
1344         if (!lineInfo[i].continuation && ++j == lines) {
1345           topline = i;
1346           if (!SearchFlag)
1347             break;
1348         }
1349         redraw |= REDRAW_SIDEBAR;
1350       }                         /* while */
1351     }
1352
1353     if ((redraw & REDRAW_BODY) || topline != oldtopline) {
1354       do {
1355         wmove(main_w, bodyoffset, 0);
1356         curline = oldtopline = topline;
1357         lines = 0;
1358         force_redraw = 0;
1359
1360         while (lines < bodylen && lineInfo[curline].offset <= sb.st_size - 1) {
1361           if (display_line (fp, &last_pos, &lineInfo, curline, &lastLine,
1362                             &maxLine,
1363                             (flags & M_DISPLAYFLAGS) | hideQuoted |
1364                             SearchFlag, &QuoteList, &q_level, &force_redraw,
1365                             &SearchRE) > 0)
1366             lines++;
1367           curline++;
1368           wmove(main_w, lines + bodyoffset, 0);
1369           redraw |= REDRAW_SIDEBAR;
1370         }
1371         last_offset = lineInfo[curline].offset;
1372       } while (force_redraw);
1373
1374       SETCOLOR(main_w, MT_COLOR_TILDE);
1375       BKGDSET(main_w, MT_COLOR_TILDE);
1376       while (lines < bodylen) {
1377         wclrtoeol(main_w);
1378         if (option (OPTTILDE))
1379           waddch(main_w, '~');
1380         waddch(main_w, '\n');
1381         lines++;
1382         wmove(main_w, lines + bodyoffset, 0);
1383       }
1384       /* We are going to update the pager status bar, so it isn't
1385        * necessary to reset to normal color now. */
1386
1387       redraw |= REDRAW_STATUS;  /* need to update the % seen */
1388     }
1389
1390     if (redraw & REDRAW_STATUS) {
1391       /* print out the pager status bar */
1392       SETCOLOR(main_w, MT_COLOR_STATUS);
1393       BKGDSET(main_w, MT_COLOR_STATUS);
1394       wmove(main_w, statusoffset, 0);
1395       wclrtoeol(main_w);
1396       if (IsHeader (extra)) {
1397         size_t l1 = (getmaxx(main_w) - 9) * MB_LEN_MAX;
1398         size_t l2 = sizeof (buffer);
1399
1400         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1401                            Context, extra->hdr, M_FORMAT_MAKEPRINT);
1402       }
1403       else if (IsMsgAttach (extra)) {
1404         size_t l1 = (getmaxx(main_w) - 9) * MB_LEN_MAX;
1405         size_t l2 = sizeof (buffer);
1406
1407         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1408                            Context, extra->bdy->hdr, M_FORMAT_MAKEPRINT);
1409       }
1410       wmove(main_w, statusoffset, 0);
1411       mutt_paddstr(main_w, getmaxx(main_w) - 10,
1412                    IsHeader(extra) || IsMsgAttach(extra) ? buffer : banner);
1413
1414       waddstr(main_w, " -- (");
1415       if (last_pos < sb.st_size - 1)
1416         wprintw(main_w, "%d%%)", (int) (100 * last_offset / sb.st_size));
1417       else
1418         waddstr(main_w, topline == 0 ? "all)" : "end)");
1419       BKGDSET(main_w, MT_COLOR_NORMAL);
1420       SETCOLOR(main_w, MT_COLOR_NORMAL);
1421     }
1422
1423     if (redraw & REDRAW_SIDEBAR)
1424       sidebar_draw ();
1425
1426     if ((redraw & REDRAW_INDEX) && pager_index) {
1427       /* redraw the pager_index indicator, because the
1428        * flags for this message might have changed. */
1429       menu_redraw_current (pager_index);
1430       sidebar_draw ();
1431       /* print out the pager_index status bar */
1432       menu_status_line (buffer, sizeof (buffer), pager_index, NONULL (Status));
1433       wmove(main_w, 0, 0);
1434       SETCOLOR(main_w, MT_COLOR_STATUS);
1435       BKGDSET(main_w, MT_COLOR_STATUS);
1436       mutt_paddstr(main_w, getmaxx(main_w), buffer);
1437       SETCOLOR(main_w, MT_COLOR_NORMAL);
1438       BKGDSET(main_w, MT_COLOR_NORMAL);
1439     }
1440
1441     sidebar_draw ();
1442     redraw = 0;
1443     mutt_refresh();
1444
1445     if (IsHeader (extra) && OldHdr == extra->hdr && TopLine != topline
1446         && lineInfo[curline].offset < sb.st_size-1) {
1447       if (TopLine - topline > lines)
1448         topline += lines;
1449       else
1450         topline = TopLine;
1451       continue;
1452     } else {
1453       OldHdr = NULL;
1454     }
1455
1456     ch = km_dokey (MENU_PAGER);
1457     if (ch != -1)
1458       mutt_clear_error ();
1459     mutt_curs_set (1);
1460
1461     if (SigInt) {
1462       mutt_query_exit ();
1463       continue;
1464     }
1465
1466     if (SigWinch) {
1467       ui_layout_resize();
1468
1469       /* Store current position. */
1470       lines = -1;
1471       for (i = 0; i <= topline; i++)
1472         if (!lineInfo[i].continuation)
1473           lines++;
1474
1475       if (flags & M_PAGER_RETWINCH) {
1476         Resize = p_new(struct resize, 1);
1477
1478         Resize->line = lines;
1479         Resize->SearchCompiled = SearchCompiled;
1480         Resize->SearchBack = SearchBack;
1481
1482         ch = -1;
1483         rc = OP_REFORMAT_WINCH;
1484       } else {
1485         for (i = 0; i < maxLine; i++) {
1486           lineInfo[i].offset = 0;
1487           lineInfo[i].type = -1;
1488           lineInfo[i].continuation = 0;
1489           lineInfo[i].chunks = 0;
1490           lineInfo[i].search_cnt = -1;
1491           lineInfo[i].quote = NULL;
1492
1493           p_realloc(&lineInfo[i].syntax, 1);
1494           if (SearchCompiled)
1495             p_delete(&lineInfo[i].search);
1496         }
1497
1498         lastLine = 0;
1499         topline = 0;
1500
1501         redraw = REDRAW_FULL | REDRAW_SIGWINCH;
1502         ch = 0;
1503       }
1504       continue;
1505     }
1506
1507     if (ch == -1) {
1508       ch = 0;
1509       continue;
1510     }
1511
1512     rc = ch;
1513
1514     switch (ch) {
1515     case OP_EXIT:
1516       rc = -1;
1517       ch = -1;
1518       break;
1519
1520     case OP_NEXT_PAGE:
1521       if (lineInfo[curline].offset < sb.st_size - 1) {
1522         topline = upNLines (PagerContext, lineInfo, curline, hideQuoted);
1523       }
1524       else if (option (OPTPAGERSTOP)) {
1525         /* emulate "less -q" and don't go on to the next message. */
1526         mutt_error _("Bottom of message is shown.");
1527       } else {
1528         /* end of the current message, so display the next message. */
1529         rc = OP_MAIN_NEXT_UNDELETED;
1530         ch = -1;
1531       }
1532       break;
1533
1534     case OP_PREV_PAGE:
1535       if (topline != 0) {
1536         topline =
1537           upNLines (bodylen - PagerContext, lineInfo, topline, hideQuoted);
1538       }
1539       else
1540         mutt_error _("Top of message is shown.");
1541       break;
1542
1543     case OP_NEXT_LINE:
1544       if (lineInfo[curline].offset < sb.st_size - 1) {
1545         topline++;
1546         if (hideQuoted) {
1547           while (lineInfo[topline].type == MT_COLOR_QUOTED &&
1548                  topline < lastLine)
1549             topline++;
1550         }
1551       }
1552       else
1553         mutt_error _("Bottom of message is shown.");
1554       break;
1555
1556     case OP_PREV_LINE:
1557       if (topline)
1558         topline = upNLines (1, lineInfo, topline, hideQuoted);
1559       else
1560         mutt_error _("Top of message is shown.");
1561       break;
1562
1563     case OP_PAGER_TOP:
1564       if (topline)
1565         topline = 0;
1566       else
1567         mutt_error _("Top of message is shown.");
1568       break;
1569
1570     case OP_HALF_UP:
1571       if (topline)
1572         topline = upNLines (bodylen / 2, lineInfo, topline, hideQuoted);
1573       else
1574         mutt_error _("Top of message is shown.");
1575       break;
1576
1577     case OP_HALF_DOWN:
1578       if (lineInfo[curline].offset < sb.st_size - 1) {
1579         topline = upNLines (bodylen / 2, lineInfo, curline, hideQuoted);
1580       }
1581       else if (option (OPTPAGERSTOP)) {
1582         /* emulate "less -q" and don't go on to the next message. */
1583         mutt_error _("Bottom of message is shown.");
1584       } else {
1585         /* end of the current message, so display the next message. */
1586         rc = OP_MAIN_NEXT_UNDELETED;
1587         ch = -1;
1588       }
1589       break;
1590
1591     case OP_SEARCH_NEXT:
1592     case OP_SEARCH_OPPOSITE:
1593       if (SearchCompiled) {
1594       search_next:
1595         if ((!SearchBack && ch == OP_SEARCH_NEXT) ||
1596             (SearchBack && ch == OP_SEARCH_OPPOSITE)) {
1597           /* searching forward */
1598           for (i = topline + 1; i < lastLine; i++) {
1599             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1600                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1601               break;
1602           }
1603
1604           if (i < lastLine)
1605             topline = i;
1606           else
1607             mutt_error _("Not found.");
1608         }
1609         else {
1610           /* searching backward */
1611           for (i = topline - 1; i >= 0; i--) {
1612             if ((!hideQuoted || (has_types &&
1613                                  lineInfo[i].type != MT_COLOR_QUOTED)) &&
1614                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1615               break;
1616           }
1617
1618           if (i >= 0)
1619             topline = i;
1620           else
1621             mutt_error _("Not found.");
1622         }
1623
1624         if (lineInfo[topline].search_cnt > 0)
1625           SearchFlag = M_SEARCH;
1626
1627         break;
1628       }
1629       /* no previous search pattern, so fall through to search */
1630
1631     case OP_SEARCH:
1632     case OP_SEARCH_REVERSE:
1633       m_strcpy(buffer, sizeof(buffer), searchbuf);
1634       if (mutt_get_field ((SearchBack ? _("Reverse search: ") :
1635                            _("Search: ")), buffer, sizeof (buffer),
1636                           M_CLEAR) != 0)
1637         break;
1638
1639       if (!m_strcmp (buffer, searchbuf)) {
1640         if (SearchCompiled) {
1641           /* do an implicit search-next */
1642           if (ch == OP_SEARCH)
1643             ch = OP_SEARCH_NEXT;
1644           else
1645             ch = OP_SEARCH_OPPOSITE;
1646
1647           goto search_next;
1648         }
1649       }
1650
1651       if (!buffer[0])
1652         break;
1653
1654       m_strcpy(searchbuf, sizeof(searchbuf), buffer);
1655
1656       /* leave SearchBack alone if ch == OP_SEARCH_NEXT */
1657       if (ch == OP_SEARCH)
1658         SearchBack = 0;
1659       else if (ch == OP_SEARCH_REVERSE)
1660         SearchBack = 1;
1661
1662       if (SearchCompiled) {
1663         regfree (&SearchRE);
1664         for (i = 0; i < lastLine; i++) {
1665           p_delete(&lineInfo[i].search);
1666           lineInfo[i].search_cnt = -1;
1667         }
1668       }
1669
1670       if ((err =
1671            REGCOMP (&SearchRE, searchbuf,
1672                     REG_NEWLINE | mutt_which_case (searchbuf))) != 0) {
1673         regerror (err, &SearchRE, buffer, sizeof (buffer));
1674         mutt_error ("%s", buffer);
1675         regfree (&SearchRE);
1676         for (i = 0; i < maxLine; i++) {
1677           /* cleanup */
1678           p_delete(&lineInfo[i].search);
1679           lineInfo[i].search_cnt = -1;
1680         }
1681         SearchFlag = 0;
1682         SearchCompiled = 0;
1683       }
1684       else {
1685         SearchCompiled = 1;
1686         /* update the search pointers */
1687         i = 0;
1688         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
1689                              &maxLine, M_SEARCH | (flags & M_PAGER_NSKIP),
1690                              &QuoteList, &q_level,
1691                              &force_redraw, &SearchRE) == 0) {
1692           i++;
1693           redraw |= REDRAW_SIDEBAR;
1694         }
1695
1696         if (!SearchBack) {
1697           /* searching forward */
1698           for (i = topline; i < lastLine; i++) {
1699             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1700                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1701               break;
1702           }
1703
1704           if (i < lastLine)
1705             topline = i;
1706         }
1707         else {
1708           /* searching backward */
1709           for (i = topline; i >= 0; i--) {
1710             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1711                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1712               break;
1713           }
1714
1715           if (i >= 0)
1716             topline = i;
1717         }
1718
1719         if (lineInfo[topline].search_cnt == 0) {
1720           SearchFlag = 0;
1721           mutt_error _("Not found.");
1722         }
1723         else
1724           SearchFlag = M_SEARCH;
1725       }
1726       redraw = REDRAW_BODY;
1727       break;
1728
1729     case OP_SEARCH_TOGGLE:
1730       if (SearchCompiled) {
1731         SearchFlag ^= M_SEARCH;
1732         redraw = REDRAW_BODY;
1733       }
1734       break;
1735
1736     case OP_HELP:
1737       /* don't let the user enter the help-menu from the help screen! */
1738       if (!InHelp) {
1739         InHelp = 1;
1740         mutt_help (MENU_PAGER);
1741         redraw = REDRAW_FULL;
1742         InHelp = 0;
1743       }
1744       else
1745         mutt_error _("Help is currently being shown.");
1746       break;
1747
1748     case OP_PAGER_HIDE_QUOTED:
1749       if (has_types) {
1750         hideQuoted ^= M_HIDE;
1751         if (hideQuoted && lineInfo[topline].type == MT_COLOR_QUOTED)
1752           topline = upNLines (1, lineInfo, topline, hideQuoted);
1753         else
1754           redraw = REDRAW_BODY;
1755       }
1756       break;
1757
1758     case OP_PAGER_SKIP_QUOTED:
1759       if (has_types) {
1760         int dretval = 0;
1761         int new_topline = topline;
1762
1763         while ((new_topline < lastLine ||
1764                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
1765                                                new_topline, &lastLine,
1766                                                &maxLine, M_TYPES, &QuoteList,
1767                                                &q_level, &force_redraw,
1768                                                &SearchRE))))
1769                && lineInfo[new_topline].type != MT_COLOR_QUOTED) {
1770           redraw |= REDRAW_SIDEBAR;
1771           new_topline++;
1772         }
1773
1774         if (dretval < 0) {
1775           mutt_error _("No more quoted text.");
1776
1777           break;
1778         }
1779
1780         while ((new_topline < lastLine ||
1781                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
1782                                                new_topline, &lastLine,
1783                                                &maxLine, M_TYPES, &QuoteList,
1784                                                &q_level, &force_redraw,
1785                                                &SearchRE))))
1786                && lineInfo[new_topline].type == MT_COLOR_QUOTED) {
1787           new_topline++;
1788           redraw |= REDRAW_SIDEBAR;
1789         }
1790
1791         if (dretval < 0) {
1792           mutt_error _("No more unquoted text after quoted text.");
1793
1794           break;
1795         }
1796         topline = new_topline;
1797       }
1798       break;
1799
1800     case OP_PAGER_BOTTOM:      /* move to the end of the file */
1801       if (lineInfo[curline].offset < sb.st_size - 1) {
1802         i = curline;
1803         /* make sure the types are defined to the end of file */
1804         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
1805                              &maxLine, has_types,
1806                              &QuoteList, &q_level, &force_redraw,
1807                              &SearchRE) == 0) {
1808           i++;
1809           redraw |= REDRAW_SIDEBAR;
1810         }
1811         topline = upNLines (bodylen, lineInfo, lastLine, hideQuoted);
1812       }
1813       else
1814         mutt_error _("Bottom of message is shown.");
1815       break;
1816
1817     case OP_REDRAW:
1818       clearok(main_w, TRUE);
1819       redraw = REDRAW_FULL;
1820       break;
1821
1822     case OP_NULL:
1823       km_error_key (MENU_PAGER);
1824       break;
1825
1826       /* --------------------------------------------------------------------
1827        * The following are operations on the current message rather than
1828        * adjusting the view of the message.
1829        */
1830
1831     case OP_BOUNCE_MESSAGE:
1832       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
1833         CHECK_ATTACH;
1834       if (IsMsgAttach (extra))
1835         mutt_attach_bounce (extra->fp, extra->hdr,
1836                             extra->idx, extra->idxlen, extra->bdy);
1837       else
1838         ci_bounce_message (extra->hdr, &redraw);
1839       break;
1840
1841     case OP_RESEND:
1842       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
1843         CHECK_ATTACH;
1844       if (IsMsgAttach (extra))
1845         mutt_attach_resend (extra->fp, extra->hdr,
1846                             extra->idx, extra->idxlen, extra->bdy);
1847       else
1848         mutt_resend_message (NULL, extra->ctx, extra->hdr);
1849       redraw = REDRAW_FULL;
1850       break;
1851
1852     case OP_CHECK_TRADITIONAL:
1853       CHECK_MODE (IsHeader (extra));
1854       if (!(extra->hdr->security & PGP_TRADITIONAL_CHECKED)) {
1855         ch = -1;
1856         rc = OP_CHECK_TRADITIONAL;
1857       }
1858       break;
1859
1860     case OP_CREATE_ALIAS:
1861       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
1862       if (IsMsgAttach (extra))
1863         mutt_create_alias (extra->bdy->hdr->env, NULL);
1864       else
1865         mutt_create_alias (extra->hdr->env, NULL);
1866       MAYBE_REDRAW (redraw);
1867       break;
1868
1869     case OP_PURGE_MESSAGE:
1870     case OP_DELETE:
1871       CHECK_MODE (IsHeader (extra));
1872       CHECK_READONLY;
1873
1874       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
1875
1876       mutt_set_flag (Context, extra->hdr, M_DELETE, 1);
1877       mutt_set_flag (Context, extra->hdr, M_PURGED,
1878                      ch != OP_PURGE_MESSAGE ? 0 : 1);
1879       if (option (OPTDELETEUNTAG))
1880         mutt_set_flag (Context, extra->hdr, M_TAG, 0);
1881       redraw = REDRAW_STATUS | REDRAW_INDEX;
1882       if (option (OPTRESOLVE)) {
1883         ch = -1;
1884         rc = OP_MAIN_NEXT_UNDELETED;
1885       }
1886       break;
1887
1888     case OP_DELETE_THREAD:
1889     case OP_DELETE_SUBTHREAD:
1890       CHECK_MODE (IsHeader (extra));
1891       CHECK_READONLY;
1892
1893       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
1894
1895       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 1,
1896                                 ch == OP_DELETE_THREAD ? 0 : 1);
1897
1898       if (r != -1) {
1899         if (option (OPTDELETEUNTAG))
1900           mutt_thread_set_flag (extra->hdr, M_TAG, 0,
1901                                 ch == OP_DELETE_THREAD ? 0 : 1);
1902         if (option (OPTRESOLVE)) {
1903           rc = OP_MAIN_NEXT_UNDELETED;
1904           ch = -1;
1905         }
1906
1907         if (!option (OPTRESOLVE) && PagerIndexLines)
1908           redraw = REDRAW_FULL;
1909         else
1910           redraw = REDRAW_STATUS | REDRAW_INDEX;
1911       }
1912       break;
1913
1914     case OP_DISPLAY_ADDRESS:
1915       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
1916       if (IsMsgAttach (extra))
1917         mutt_display_address (extra->bdy->hdr->env);
1918       else
1919         mutt_display_address (extra->hdr->env);
1920       break;
1921
1922     case OP_ENTER_COMMAND:
1923       old_smart_wrap = option (OPTWRAP);
1924       old_markers = option (OPTMARKERS);
1925       old_PagerIndexLines = PagerIndexLines;
1926
1927       CurrentMenu = MENU_PAGER;
1928       mutt_enter_command ();
1929
1930       if (option (OPTNEEDRESORT)) {
1931         unset_option (OPTNEEDRESORT);
1932         CHECK_MODE (IsHeader (extra));
1933         set_option (OPTNEEDRESORT);
1934       }
1935
1936       if (old_PagerIndexLines != PagerIndexLines) {
1937         if (pager_index)
1938           mutt_menuDestroy (&pager_index);
1939         pager_index = NULL;
1940       }
1941
1942       if (option (OPTWRAP) != old_smart_wrap ||
1943           option (OPTMARKERS) != old_markers) {
1944         if (flags & M_PAGER_RETWINCH) {
1945           ch = -1;
1946           rc = OP_REFORMAT_WINCH;
1947           continue;
1948         }
1949
1950         /* count the real lines above */
1951         j = 0;
1952         for (i = 0; i <= topline; i++) {
1953           if (!lineInfo[i].continuation)
1954             j++;
1955         }
1956
1957         /* we need to restart the whole thing */
1958         for (i = 0; i < maxLine; i++) {
1959           lineInfo[i].offset = 0;
1960           lineInfo[i].type = -1;
1961           lineInfo[i].continuation = 0;
1962           lineInfo[i].chunks = 0;
1963           lineInfo[i].search_cnt = -1;
1964           lineInfo[i].quote = NULL;
1965
1966           p_realloc(&(lineInfo[i].syntax), 1);
1967           if (SearchCompiled)
1968             p_delete(&lineInfo[i].search);
1969         }
1970
1971         if (SearchCompiled) {
1972           regfree (&SearchRE);
1973           SearchCompiled = 0;
1974         }
1975         SearchFlag = 0;
1976
1977         /* try to keep the old position */
1978         topline = 0;
1979         lastLine = 0;
1980         while (j > 0 && display_line (fp, &last_pos, &lineInfo, topline,
1981                                       &lastLine, &maxLine,
1982                                       (has_types ? M_TYPES : 0),
1983                                       &QuoteList, &q_level, &force_redraw,
1984                                       &SearchRE) == 0) {
1985           redraw |= REDRAW_SIDEBAR;
1986           if (!lineInfo[topline].continuation)
1987             j--;
1988           if (j > 0)
1989             topline++;
1990         }
1991
1992         ch = 0;
1993       }
1994
1995       if (option (OPTFORCEREDRAWPAGER))
1996         redraw = REDRAW_FULL;
1997       unset_option (OPTFORCEREDRAWINDEX);
1998       unset_option (OPTFORCEREDRAWPAGER);
1999       break;
2000
2001     case OP_FLAG_MESSAGE:
2002       CHECK_MODE (IsHeader (extra));
2003       CHECK_READONLY;
2004
2005       CHECK_MX_ACL (Context, ACL_WRITE, _("Flagging"));
2006
2007       mutt_set_flag (Context, extra->hdr, M_FLAG, !extra->hdr->flagged);
2008       redraw = REDRAW_STATUS | REDRAW_INDEX;
2009       if (option (OPTRESOLVE)) {
2010         ch = -1;
2011         rc = OP_MAIN_NEXT_UNDELETED;
2012       }
2013       break;
2014
2015     case OP_PIPE:
2016       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2017       if (IsAttach (extra))
2018         mutt_pipe_attachment_list (extra->fp, 0, extra->bdy, 0);
2019       else
2020         mutt_pipe_message (extra->hdr);
2021       MAYBE_REDRAW (redraw);
2022       break;
2023
2024     case OP_PRINT:
2025       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2026       if (IsAttach (extra))
2027         mutt_print_attachment_list (extra->fp, 0, extra->bdy);
2028       else
2029         mutt_print_message (extra->hdr);
2030       break;
2031
2032     case OP_MAIL:
2033       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2034       CHECK_ATTACH;
2035       ci_send_message (0, NULL, NULL, extra->ctx, NULL);
2036       redraw = REDRAW_FULL;
2037       break;
2038
2039     case OP_REPLY:
2040       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2041       CHECK_ATTACH;
2042       if (IsMsgAttach (extra))
2043         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2044                            extra->idxlen, extra->bdy, SENDREPLY);
2045       else
2046         ci_send_message (SENDREPLY, NULL, NULL, extra->ctx, extra->hdr);
2047       redraw = REDRAW_FULL;
2048       break;
2049
2050     case OP_RECALL_MESSAGE:
2051       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2052       CHECK_ATTACH;
2053       ci_send_message (SENDPOSTPONED, NULL, NULL, extra->ctx, extra->hdr);
2054       redraw = REDRAW_FULL;
2055       break;
2056
2057     case OP_GROUP_REPLY:
2058       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2059       CHECK_ATTACH;
2060       if (IsMsgAttach (extra))
2061         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2062                            extra->idxlen, extra->bdy,
2063                            SENDREPLY | SENDGROUPREPLY);
2064       else
2065         ci_send_message (SENDREPLY | SENDGROUPREPLY, NULL, NULL, extra->ctx,
2066                          extra->hdr);
2067       redraw = REDRAW_FULL;
2068       break;
2069
2070     case OP_LIST_REPLY:
2071       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2072       CHECK_ATTACH;
2073       if (IsMsgAttach (extra))
2074         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2075                            extra->idxlen, extra->bdy,
2076                            SENDREPLY | SENDLISTREPLY);
2077       else
2078         ci_send_message (SENDREPLY | SENDLISTREPLY, NULL, NULL, extra->ctx,
2079                          extra->hdr);
2080       redraw = REDRAW_FULL;
2081       break;
2082
2083     case OP_FORWARD_MESSAGE:
2084       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2085       CHECK_ATTACH;
2086       if (IsMsgAttach (extra))
2087         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2088                              extra->idxlen, extra->bdy, 0);
2089       else
2090         ci_send_message (SENDFORWARD, NULL, NULL, extra->ctx, extra->hdr);
2091       redraw = REDRAW_FULL;
2092       break;
2093
2094     case OP_DECRYPT_SAVE:
2095     case OP_SAVE:
2096       if (IsAttach (extra)) {
2097         mutt_save_attachment_list (extra->fp, 0, extra->bdy, extra->hdr,
2098                                    NULL);
2099         break;
2100       }
2101       /* fall through */
2102     case OP_COPY_MESSAGE:
2103     case OP_DECODE_SAVE:
2104     case OP_DECODE_COPY:
2105     case OP_DECRYPT_COPY:
2106       CHECK_MODE (IsHeader (extra));
2107       if (mutt_save_message (extra->hdr,
2108                              (ch == OP_DECRYPT_SAVE) ||
2109                              (ch == OP_SAVE) || (ch == OP_DECODE_SAVE),
2110                              (ch == OP_DECODE_SAVE) || (ch == OP_DECODE_COPY),
2111                              (ch == OP_DECRYPT_SAVE)
2112                              || (ch == OP_DECRYPT_COPY) || 0, &redraw) == 0
2113           && (ch == OP_SAVE || ch == OP_DECODE_SAVE
2114               || ch == OP_DECRYPT_SAVE)) {
2115         if (option (OPTRESOLVE)) {
2116           ch = -1;
2117           rc = OP_MAIN_NEXT_UNDELETED;
2118         }
2119         else
2120           redraw |= REDRAW_STATUS | REDRAW_INDEX;
2121       }
2122       MAYBE_REDRAW (redraw);
2123       break;
2124
2125     case OP_SHELL_ESCAPE:
2126       mutt_shell_escape ();
2127       MAYBE_REDRAW (redraw);
2128       break;
2129
2130     case OP_TAG:
2131       CHECK_MODE (IsHeader (extra));
2132       mutt_set_flag (Context, extra->hdr, M_TAG, !extra->hdr->tagged);
2133
2134       Context->last_tag = extra->hdr->tagged ? extra->hdr :
2135         ((Context->last_tag == extra->hdr && !extra->hdr->tagged)
2136          ? NULL : Context->last_tag);
2137
2138       redraw = REDRAW_STATUS | REDRAW_INDEX;
2139       if (option (OPTRESOLVE)) {
2140         ch = -1;
2141         rc = OP_NEXT_ENTRY;
2142       }
2143       break;
2144
2145     case OP_TOGGLE_NEW:
2146       CHECK_MODE (IsHeader (extra));
2147       CHECK_READONLY;
2148
2149       CHECK_MX_ACL (Context, ACL_SEEN, _("Toggling"));
2150
2151       if (extra->hdr->read || extra->hdr->old)
2152         mutt_set_flag (Context, extra->hdr, M_NEW, 1);
2153       else if (!first)
2154         mutt_set_flag (Context, extra->hdr, M_READ, 1);
2155       first = 0;
2156       Context->msgnotreadyet = -1;
2157       redraw = REDRAW_STATUS | REDRAW_INDEX;
2158       if (option (OPTRESOLVE)) {
2159         ch = -1;
2160         rc = OP_MAIN_NEXT_UNDELETED;
2161       }
2162       break;
2163
2164     case OP_UNDELETE:
2165       CHECK_MODE (IsHeader (extra));
2166       CHECK_READONLY;
2167
2168       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2169
2170       mutt_set_flag (Context, extra->hdr, M_DELETE, 0);
2171       mutt_set_flag (Context, extra->hdr, M_PURGED, 0);
2172       redraw = REDRAW_STATUS | REDRAW_INDEX;
2173       if (option (OPTRESOLVE)) {
2174         ch = -1;
2175         rc = OP_NEXT_ENTRY;
2176       }
2177       break;
2178
2179     case OP_UNDELETE_THREAD:
2180     case OP_UNDELETE_SUBTHREAD:
2181       CHECK_MODE (IsHeader (extra));
2182       CHECK_READONLY;
2183
2184       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2185
2186       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 0,
2187                                 ch == OP_UNDELETE_THREAD ? 0 : 1)
2188         + mutt_thread_set_flag (extra->hdr, M_PURGED, 0,
2189                                 ch == OP_UNDELETE_THREAD ? 0 : 1);
2190
2191       if (r > -1) {
2192         if (option (OPTRESOLVE)) {
2193           rc = (ch == OP_DELETE_THREAD) ?
2194             OP_MAIN_NEXT_THREAD : OP_MAIN_NEXT_SUBTHREAD;
2195           ch = -1;
2196         }
2197
2198         if (!option (OPTRESOLVE) && PagerIndexLines)
2199           redraw = REDRAW_FULL;
2200         else
2201           redraw = REDRAW_STATUS | REDRAW_INDEX;
2202       }
2203       break;
2204
2205     case OP_BUFFY_LIST:
2206       if (option (OPTFORCEBUFFYCHECK))
2207         buffy_check (1);
2208       buffy_list ();
2209       redraw |= REDRAW_SIDEBAR;
2210       break;
2211
2212     case OP_VIEW_ATTACHMENTS:
2213       if (flags & M_PAGER_ATTACHMENT) {
2214         ch = -1;
2215         rc = OP_ATTACH_COLLAPSE;
2216         break;
2217       }
2218       CHECK_MODE (IsHeader (extra));
2219       mutt_view_attachments (extra->hdr);
2220       if (extra->hdr->attach_del)
2221         Context->changed = 1;
2222       redraw = REDRAW_FULL;
2223       break;
2224
2225     case OP_EXTRACT_KEYS:
2226       CHECK_MODE (IsHeader (extra));
2227       crypt_extract_keys_from_messages (extra->hdr);
2228       redraw = REDRAW_FULL;
2229       break;
2230
2231     case OP_SIDEBAR_SCROLL_UP:
2232     case OP_SIDEBAR_SCROLL_DOWN:
2233     case OP_SIDEBAR_NEXT:
2234     case OP_SIDEBAR_NEXT_NEW:
2235     case OP_SIDEBAR_PREV:
2236     case OP_SIDEBAR_PREV_NEW:
2237       sidebar_scroll (ch);
2238       break;
2239     default:
2240       ch = -1;
2241       break;
2242     }
2243   }
2244
2245   m_fclose(&fp);
2246   if (IsHeader (extra)) {
2247     Context->msgnotreadyet = -1;
2248     if (rc == -1)
2249       OldHdr = NULL;
2250     else {
2251       TopLine = topline;
2252       OldHdr = extra->hdr;
2253     }
2254   }
2255
2256   cleanup_quote(&QuoteList);
2257
2258   for (i = 0; i < maxLine; i++) {
2259     p_delete(&lineInfo[i].syntax);
2260     if (SearchCompiled)
2261       p_delete(&lineInfo[i].search);
2262   }
2263   if (SearchCompiled) {
2264     regfree (&SearchRE);
2265     SearchCompiled = 0;
2266   }
2267   p_delete(&lineInfo);
2268   if (pager_index)
2269     mutt_menuDestroy (&pager_index);
2270   return rc != -1 ? rc : 0;
2271 }
2272
2273 #undef CHECK_ATTACH
2274 #undef CHECK_READONLY
2275 #undef CHECK_MODE