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