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