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