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