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