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