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