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