Rocco Rutte:
[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 static int
882 fill_buffer (FILE * f, long *last_pos, long offset, unsigned char *buf,
883              unsigned char *fmt, size_t blen, int *buf_ready)
884 {
885   unsigned char *p;
886   static int b_read = 0;
887
888   if (*buf_ready == 0) {
889     buf[blen - 1] = 0;
890     if (offset != *last_pos)
891       fseek (f, offset, 0);
892     if (fgets ((char *) buf, blen - 1, f) == NULL) {
893       fmt[0] = 0;
894       return (-1);
895     }
896     *last_pos = ftell (f);
897     b_read = (int) (*last_pos - offset);
898     *buf_ready = 1;
899
900     /* copy "buf" to "fmt", but without bold and underline controls */
901     p = buf;
902     while (*p) {
903       if (*p == '\010' && (p > buf)) {
904         if (*(p + 1) == '_')    /* underline */
905           p += 2;
906         else if (*(p + 1)) {    /* bold or overstrike */
907           *(fmt - 1) = *(p + 1);
908           p += 2;
909         }
910         else                    /* ^H */
911           *fmt++ = *p++;
912       }
913       else if (*p == '\033' && *(p + 1) == '[' && is_ansi (p + 2)) {
914         while (*p++ != 'm')     /* skip ANSI sequence */
915           ;
916       }
917       else if (*p == '\033' && *(p + 1) == ']'
918                && check_attachment_marker ((char *) p) == 0) {
919         debug_print (2, ("seen attachment marker.\n"));
920         while (*p++ != '\a')    /* skip pseudo-ANSI sequence */
921           ;
922       }
923       else
924         *fmt++ = *p++;
925     }
926     *fmt = 0;
927   }
928   return b_read;
929 }
930
931 #ifdef USE_NNTP
932 #include "mx.h"
933 #include "nntp.h"
934 #endif
935
936
937 static int format_line (struct line_t **lineInfo, int n, unsigned char *buf,
938                         int flags, ansi_attr * pa, int cnt,
939                         int *pspace, int *pvch, int *pcol, int *pspecial)
940 {
941   int space = -1;               /* index of the last space or TAB */
942   int col = option (OPTMARKERS) ? (*lineInfo)[n].continuation : 0;
943   int ch, vch, k, last_special = -1, special = 0, t;
944   wchar_t wc;
945   mbstate_t mbstate;
946
947   int wrap_cols = COLS;
948
949   if (!(flags & (M_SHOWFLAT)))
950     wrap_cols -= WrapMargin;
951   wrap_cols -= SidebarWidth;
952
953   if (wrap_cols <= 0)
954     wrap_cols = COLS;
955
956   /* FIXME: this should come from lineInfo */
957   memset (&mbstate, 0, sizeof (mbstate));
958
959   for (ch = 0, vch = 0; ch < cnt; ch += k, vch += k) {
960     /* Handle ANSI sequences */
961     while (cnt - ch >= 2 && buf[ch] == '\033' && buf[ch + 1] == '[' &&
962            is_ansi (buf + ch + 2))
963       ch = grok_ansi (buf, ch + 2, pa) + 1;
964
965     while (cnt - ch >= 2 && buf[ch] == '\033' && buf[ch + 1] == ']' &&
966            check_attachment_marker ((char *) buf + ch) == 0) {
967       while (buf[ch++] != '\a')
968         if (ch >= cnt)
969           break;
970     }
971
972     /* is anything left to do? */
973     if (ch >= cnt)
974       break;
975
976     k = mbrtowc (&wc, (char *) buf + ch, cnt - ch, &mbstate);
977     if (k == -2 || k == -1) {
978       debug_print (1, ("mbrtowc returned %d; errno = %d.\n", k, errno));
979       if (col + 4 > wrap_cols)
980         break;
981       col += 4;
982       if (pa)
983         printw ("\\%03o", buf[ch]);
984       k = 1;
985       continue;
986     }
987     if (k == 0)
988       k = 1;
989
990     /* Handle backspace */
991     special = 0;
992     if (IsWPrint (wc)) {
993       wchar_t wc1;
994       mbstate_t mbstate1;
995       int k1, k2;
996
997       while ((wc1 = 0, mbstate1 = mbstate,
998               k1 =
999               k + mbrtowc (&wc1, (char *) buf + ch + k, cnt - ch - k,
1000                            &mbstate1), k1 - k > 0 && wc1 == '\b')
1001              && (wc1 = 0, k2 =
1002                  mbrtowc (&wc1, (char *) buf + ch + k1, cnt - ch - k1,
1003                           &mbstate1), k2 > 0 && IsWPrint (wc1))) {
1004         if (wc == wc1) {
1005           special |= (wc == '_' && special & A_UNDERLINE)
1006             ? A_UNDERLINE : A_BOLD;
1007         }
1008         else if (wc == '_' || wc1 == '_') {
1009           special |= A_UNDERLINE;
1010           wc = (wc1 == '_') ? wc : wc1;
1011         }
1012         else {
1013           /* special = 0; / * overstrike: nothing to do! */
1014           wc = wc1;
1015         }
1016         ch += k1;
1017         k = k2;
1018         mbstate = mbstate1;
1019       }
1020     }
1021
1022     if (pa &&
1023         ((flags & (M_SHOWCOLOR | M_SEARCH | M_PAGER_MARKER)) ||
1024          special || last_special || pa->attr)) {
1025       resolve_color (*lineInfo, n, vch, flags, special, pa);
1026       last_special = special;
1027     }
1028
1029     if (IsWPrint (wc)) {
1030       if (wc == ' ')
1031         space = ch;
1032       t = wcwidth (wc);
1033       if (col + t > wrap_cols)
1034         break;
1035       col += t;
1036       if (pa)
1037         mutt_addwch (wc);
1038     }
1039     else if (wc == '\n')
1040       break;
1041     else if (wc == '\t') {
1042       space = ch;
1043       t = (col & ~7) + 8;
1044       if (t > wrap_cols)
1045         break;
1046       if (pa)
1047         for (; col < t; col++)
1048           addch (' ');
1049       else
1050         col = t;
1051     }
1052     else if (wc < 0x20 || wc == 0x7f) {
1053       if (col + 2 > wrap_cols)
1054         break;
1055       col += 2;
1056       if (pa)
1057         printw ("^%c", ('@' + wc) & 0x7f);
1058     }
1059     else if (wc < 0x100) {
1060       if (col + 4 > wrap_cols)
1061         break;
1062       col += 4;
1063       if (pa)
1064         printw ("\\%03o", wc);
1065     }
1066     else {
1067       if (col + 1 > wrap_cols)
1068         break;
1069       ++col;
1070       if (pa)
1071         addch (replacement_char ());
1072     }
1073   }
1074   *pspace = space;
1075   *pcol = col;
1076   *pvch = vch;
1077   *pspecial = special;
1078   return ch;
1079 }
1080
1081 /*
1082  * Args:
1083  *      flags   M_SHOWFLAT, show characters (used for displaying help)
1084  *              M_SHOWCOLOR, show characters in color
1085  *                      otherwise don't show characters
1086  *              M_HIDE, don't show quoted text
1087  *              M_SEARCH, resolve search patterns
1088  *              M_TYPES, compute line's type
1089  *              M_PAGER_NSKIP, keeps leading whitespace
1090  *              M_PAGER_MARKER, eventually show markers
1091  *
1092  * Return values:
1093  *      -1      EOF was reached
1094  *      0       normal exit, line was not displayed
1095  *      >0      normal exit, line was displayed
1096  */
1097
1098 static int
1099 display_line (FILE * f, long *last_pos, struct line_t **lineInfo, int n,
1100               int *last, int *max, int flags, struct q_class_t **QuoteList,
1101               int *q_level, int *force_redraw, regex_t * SearchRE)
1102 {
1103   unsigned char buf[LONG_STRING], fmt[LONG_STRING];
1104   unsigned char *buf_ptr = buf;
1105   int ch, vch, col, cnt, b_read;
1106   int buf_ready = 0, change_last = 0;
1107   int special;
1108   int offset;
1109   int def_color;
1110   int m;
1111   ansi_attr a = { 0, 0, 0, -1 };
1112   regmatch_t pmatch[1];
1113
1114   if (n == *last) {
1115     (*last)++;
1116     change_last = 1;
1117   }
1118
1119   if (*last == *max) {
1120     safe_realloc (lineInfo, sizeof (struct line_t) * (*max += LINES));
1121     for (ch = *last; ch < *max; ch++) {
1122       memset (&((*lineInfo)[ch]), 0, sizeof (struct line_t));
1123       (*lineInfo)[ch].type = -1;
1124       (*lineInfo)[ch].search_cnt = -1;
1125       (*lineInfo)[ch].syntax = safe_malloc (sizeof (struct syntax_t));
1126       ((*lineInfo)[ch].syntax)[0].first = ((*lineInfo)[ch].syntax)[0].last =
1127         -1;
1128     }
1129   }
1130
1131   /* only do color hiliting if we are viewing a message */
1132   if (flags & (M_SHOWCOLOR | M_TYPES)) {
1133     if ((*lineInfo)[n].type == -1) {
1134       /* determine the line class */
1135       if (fill_buffer
1136           (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1137            &buf_ready) < 0) {
1138         if (change_last)
1139           (*last)--;
1140         return (-1);
1141       }
1142
1143       resolve_types ((char *) fmt, (char *) buf, *lineInfo, n, *last,
1144                      QuoteList, q_level, force_redraw, flags & M_SHOWCOLOR);
1145
1146       /* avoid race condition for continuation lines when scrolling up */
1147       for (m = n + 1;
1148            m < *last && (*lineInfo)[m].offset && (*lineInfo)[m].continuation;
1149            m++)
1150         (*lineInfo)[m].type = (*lineInfo)[n].type;
1151     }
1152
1153     /* this also prevents searching through the hidden lines */
1154     if ((flags & M_HIDE) && (*lineInfo)[n].type == MT_COLOR_QUOTED)
1155       flags = 0;                /* M_NOSHOW */
1156   }
1157
1158   /* At this point, (*lineInfo[n]).quote may still be undefined. We 
1159    * don't want to compute it every time M_TYPES is set, since this
1160    * would slow down the "bottom" function unacceptably. A compromise
1161    * solution is hence to call regexec() again, just to find out the
1162    * length of the quote prefix.
1163    */
1164   if ((flags & M_SHOWCOLOR) && !(*lineInfo)[n].continuation &&
1165       (*lineInfo)[n].type == MT_COLOR_QUOTED && (*lineInfo)[n].quote == NULL)
1166   {
1167     if (fill_buffer
1168         (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1169          &buf_ready) < 0) {
1170       if (change_last)
1171         (*last)--;
1172       return (-1);
1173     }
1174     regexec ((regex_t *) QuoteRegexp.rx, (char *) fmt, 1, pmatch, 0);
1175     (*lineInfo)[n].quote = classify_quote (QuoteList,
1176                                            (char *) fmt + pmatch[0].rm_so,
1177                                            pmatch[0].rm_eo - pmatch[0].rm_so,
1178                                            force_redraw, q_level);
1179   }
1180
1181   if ((flags & M_SEARCH) && !(*lineInfo)[n].continuation
1182       && (*lineInfo)[n].search_cnt == -1) {
1183     if (fill_buffer
1184         (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1185          &buf_ready) < 0) {
1186       if (change_last)
1187         (*last)--;
1188       return (-1);
1189     }
1190
1191     offset = 0;
1192     (*lineInfo)[n].search_cnt = 0;
1193     while (regexec
1194            (SearchRE, (char *) fmt + offset, 1, pmatch,
1195             (offset ? REG_NOTBOL : 0)) == 0) {
1196       if (++((*lineInfo)[n].search_cnt) > 1)
1197         safe_realloc (&((*lineInfo)[n].search),
1198                       ((*lineInfo)[n].search_cnt) * sizeof (struct syntax_t));
1199       else
1200         (*lineInfo)[n].search = safe_malloc (sizeof (struct syntax_t));
1201       pmatch[0].rm_so += offset;
1202       pmatch[0].rm_eo += offset;
1203       ((*lineInfo)[n].search)[(*lineInfo)[n].search_cnt - 1].first =
1204         pmatch[0].rm_so;
1205       ((*lineInfo)[n].search)[(*lineInfo)[n].search_cnt - 1].last =
1206         pmatch[0].rm_eo;
1207
1208       if (pmatch[0].rm_eo == pmatch[0].rm_so)
1209         offset++;               /* avoid degenerate cases */
1210       else
1211         offset = pmatch[0].rm_eo;
1212       if (!fmt[offset])
1213         break;
1214     }
1215   }
1216
1217   if (!(flags & M_SHOW) && (*lineInfo)[n + 1].offset > 0) {
1218     /* we've already scanned this line, so just exit */
1219     return (0);
1220   }
1221   if ((flags & M_SHOWCOLOR) && *force_redraw && (*lineInfo)[n + 1].offset > 0) {
1222     /* no need to try to display this line... */
1223     return (1);                 /* fake display */
1224   }
1225
1226   if ((b_read = fill_buffer (f, last_pos, (*lineInfo)[n].offset, buf, fmt,
1227                              sizeof (buf), &buf_ready)) < 0) {
1228     if (change_last)
1229       (*last)--;
1230     return (-1);
1231   }
1232
1233   /* now chose a good place to break the line */
1234   cnt =
1235     format_line (lineInfo, n, buf, flags, 0, b_read, &ch, &vch, &col,
1236                  &special);
1237   buf_ptr = buf + cnt;
1238
1239   /* move the break point only if smart_wrap is set */
1240   if (option (OPTWRAP)) {
1241     if (cnt < b_read) {
1242       if (ch != -1 && buf[cnt] != ' ' && buf[cnt] != '\t' && buf[cnt] != '\n'
1243           && buf[cnt] != '\r') {
1244         buf_ptr = buf + ch;
1245         /* skip trailing blanks */
1246         while (ch && (buf[ch] == ' ' || buf[ch] == '\t' || buf[ch] == '\r'))
1247           ch--;
1248         /* a very long word with leading spaces causes infinite wrapping */
1249         if ((!ch) && (flags & M_PAGER_NSKIP))
1250           buf_ptr = buf + cnt;
1251         else
1252           cnt = ch + 1;
1253       }
1254       else
1255         buf_ptr = buf + cnt;    /* a very long word... */
1256     }
1257     if (!(flags & M_PAGER_NSKIP))
1258       /* skip leading blanks on the next line too */
1259       while (*buf_ptr == ' ' || *buf_ptr == '\t')
1260         buf_ptr++;
1261   }
1262
1263   if (*buf_ptr == '\r')
1264     buf_ptr++;
1265   if (*buf_ptr == '\n')
1266     buf_ptr++;
1267
1268   if ((int) (buf_ptr - buf) < b_read && !(*lineInfo)[n + 1].continuation)
1269     append_line (*lineInfo, n, (int) (buf_ptr - buf));
1270   (*lineInfo)[n + 1].offset = (*lineInfo)[n].offset + (long) (buf_ptr - buf);
1271
1272   /* if we don't need to display the line we are done */
1273   if (!(flags & M_SHOW))
1274     return 0;
1275
1276   /* display the line */
1277   format_line (lineInfo, n, buf, flags, &a, cnt, &ch, &vch, &col, &special);
1278
1279   /* avoid a bug in ncurses... */
1280 #ifndef USE_SLANG_CURSES
1281   if (col == 0) {
1282     SETCOLOR (MT_COLOR_NORMAL);
1283     addch (' ');
1284   }
1285 #endif
1286
1287   /* end the last color pattern (needed by S-Lang) */
1288   if (special || (col != COLS && (flags & (M_SHOWCOLOR | M_SEARCH))))
1289     resolve_color (*lineInfo, n, vch, flags, 0, &a);
1290
1291   /*
1292    * Fill the blank space at the end of the line with the prevailing color.
1293    * ncurses does an implicit clrtoeol() when you do addch('\n') so we have
1294    * to make sure to reset the color *after* that
1295    */
1296   if (flags & M_SHOWCOLOR) {
1297     m = ((*lineInfo)[n].continuation) ? ((*lineInfo)[n].syntax)[0].first : n;
1298     if ((*lineInfo)[m].type == MT_COLOR_HEADER)
1299       def_color = ((*lineInfo)[m].syntax)[0].color;
1300     else
1301       def_color = ColorDefs[(*lineInfo)[m].type];
1302
1303     attrset (def_color);
1304 #ifdef HAVE_BKGDSET
1305     bkgdset (def_color | ' ');
1306 #endif
1307   }
1308
1309   /* ncurses always wraps lines when you get to the right side of the
1310    * screen, but S-Lang seems to only wrap if the next character is *not*
1311    * a newline (grr!).
1312    */
1313 #ifndef USE_SLANG_CURSES
1314   if (col < COLS)
1315 #endif
1316     addch ('\n');
1317
1318   /*
1319    * reset the color back to normal.  This *must* come after the
1320    * addch('\n'), otherwise the color for this line will not be
1321    * filled to the right margin.
1322    */
1323   if (flags & M_SHOWCOLOR) {
1324     SETCOLOR (MT_COLOR_NORMAL);
1325     BKGDSET (MT_COLOR_NORMAL);
1326   }
1327
1328   /* build a return code */
1329   if (!(flags & M_SHOW))
1330     flags = 0;
1331
1332   return (flags);
1333 }
1334
1335 static int upNLines (int nlines, struct line_t *info, int cur, int hiding)
1336 {
1337   while (cur > 0 && nlines > 0) {
1338     cur--;
1339     if (!hiding || info[cur].type != MT_COLOR_QUOTED)
1340       nlines--;
1341   }
1342
1343   return cur;
1344 }
1345
1346 static struct mapping_t PagerHelp[] = {
1347   {N_("Exit"), OP_EXIT},
1348   {N_("PrevPg"), OP_PREV_PAGE},
1349   {N_("NextPg"), OP_NEXT_PAGE},
1350   {NULL, 0}
1351 };
1352 static struct mapping_t PagerHelpExtra[] = {
1353   {N_("View Attachm."), OP_VIEW_ATTACHMENTS},
1354   {N_("Del"), OP_DELETE},
1355   {N_("Reply"), OP_REPLY},
1356   {N_("Next"), OP_MAIN_NEXT_UNDELETED},
1357   {NULL, 0}
1358 };
1359
1360 #ifdef USE_NNTP
1361 static struct mapping_t PagerNewsHelpExtra[] = {
1362   {N_("Post"), OP_POST},
1363   {N_("Followup"), OP_FOLLOWUP},
1364   {N_("Del"), OP_DELETE},
1365   {N_("Next"), OP_MAIN_NEXT_UNDELETED},
1366   {NULL, 0}
1367 };
1368 #endif
1369
1370
1371
1372 /* This pager is actually not so simple as it once was.  It now operates in
1373    two modes: one for viewing messages and the other for viewing help.  These
1374    can be distinguished by whether or not ``hdr'' is NULL.  The ``hdr'' arg
1375    is there so that we can do operations on the current message without the
1376    need to pop back out to the main-menu.  */
1377 int
1378 mutt_pager (const char *banner, const char *fname, int flags, pager_t * extra)
1379 {
1380   static char searchbuf[STRING];
1381   char buffer[LONG_STRING];
1382   char helpstr[SHORT_STRING * 2];
1383   char tmphelp[SHORT_STRING * 2];
1384   int maxLine, lastLine = 0;
1385   struct line_t *lineInfo;
1386   struct q_class_t *QuoteList = NULL;
1387   int i, j, ch = 0, rc = -1, hideQuoted = 0, q_level = 0, force_redraw = 0;
1388   int lines = 0, curline = 0, topline = 0, oldtopline = 0, err, first = 1;
1389   int r = -1;
1390   int redraw = REDRAW_FULL;
1391   FILE *fp = NULL;
1392   long last_pos = 0, last_offset = 0;
1393   int old_smart_wrap, old_markers;
1394   struct stat sb;
1395   regex_t SearchRE;
1396   int SearchCompiled = 0, SearchFlag = 0, SearchBack = 0;
1397   int has_types = (IsHeader (extra) || (flags & M_SHOWCOLOR)) ? M_TYPES : 0;    /* main message or rfc822 attachment */
1398
1399   int bodyoffset = 1;           /* offset of first line of real text */
1400   int statusoffset = 0;         /* offset for the status bar */
1401   int helpoffset = LINES - 2;   /* offset for the help bar. */
1402   int bodylen = LINES - 2 - bodyoffset; /* length of displayable area */
1403
1404   MUTTMENU *index = NULL;       /* the Pager Index (PI) */
1405   int indexoffset = 0;          /* offset for the PI */
1406   int indexlen = PagerIndexLines;       /* indexlen not always == PIL */
1407   int indicator = indexlen / 3; /* the indicator line of the PI */
1408   int old_PagerIndexLines;      /* some people want to resize it
1409                                  * while inside the pager... */
1410
1411 #ifdef USE_NNTP
1412   char *followup_to;
1413 #endif
1414
1415   if (!(flags & M_SHOWCOLOR))
1416     flags |= M_SHOWFLAT;
1417
1418   if ((fp = fopen (fname, "r")) == NULL) {
1419     mutt_perror (fname);
1420     return (-1);
1421   }
1422
1423   if (stat (fname, &sb) != 0) {
1424     mutt_perror (fname);
1425     fclose (fp);
1426     return (-1);
1427   }
1428   unlink (fname);
1429
1430   /* Initialize variables */
1431
1432   if (IsHeader (extra) && !extra->hdr->read) {
1433     Context->msgnotreadyet = extra->hdr->msgno;
1434     mutt_set_flag (Context, extra->hdr, M_READ, 1);
1435   }
1436
1437   lineInfo = safe_malloc (sizeof (struct line_t) * (maxLine = LINES));
1438   for (i = 0; i < maxLine; i++) {
1439     memset (&lineInfo[i], 0, sizeof (struct line_t));
1440     lineInfo[i].type = -1;
1441     lineInfo[i].search_cnt = -1;
1442     lineInfo[i].syntax = safe_malloc (sizeof (struct syntax_t));
1443     (lineInfo[i].syntax)[0].first = (lineInfo[i].syntax)[0].last = -1;
1444   }
1445
1446   mutt_compile_help (helpstr, sizeof (helpstr), MENU_PAGER, PagerHelp);
1447   if (IsHeader (extra)) {
1448     strfcpy (tmphelp, helpstr, sizeof (tmphelp));
1449     mutt_compile_help (buffer, sizeof (buffer), MENU_PAGER,
1450 #ifdef USE_NNTP
1451                        (Context
1452                         && (Context->magic == M_NNTP)) ? PagerNewsHelpExtra :
1453 #endif
1454                        PagerHelpExtra);
1455     snprintf (helpstr, sizeof (helpstr), "%s %s", tmphelp, buffer);
1456   }
1457   if (!InHelp) {
1458     strfcpy (tmphelp, helpstr, sizeof (tmphelp));
1459     mutt_make_help (buffer, sizeof (buffer), _("Help"), MENU_PAGER, OP_HELP);
1460     snprintf (helpstr, sizeof (helpstr), "%s %s", tmphelp, buffer);
1461   }
1462
1463   while (ch != -1) {
1464     mutt_curs_set (0);
1465
1466 #ifdef USE_IMAP
1467     imap_keepalive ();
1468 #endif
1469
1470     if (redraw & REDRAW_FULL) {
1471       SETCOLOR (MT_COLOR_NORMAL);
1472       /* clear() doesn't optimize screen redraws */
1473       move (0, 0);
1474       clrtobot ();
1475
1476       if (IsHeader (extra) && Context->vcount + 1 < PagerIndexLines)
1477         indexlen = Context->vcount + 1;
1478       else
1479         indexlen = PagerIndexLines;
1480
1481       indicator = indexlen / 3;
1482
1483       if (option (OPTSTATUSONTOP)) {
1484         indexoffset = 0;
1485         statusoffset = IsHeader (extra) ? indexlen : 0;
1486         bodyoffset = statusoffset + 1;
1487         helpoffset = LINES - 2;
1488         bodylen = helpoffset - bodyoffset;
1489         if (!option (OPTHELP))
1490           bodylen++;
1491       }
1492       else {
1493         helpoffset = 0;
1494         indexoffset = 1;
1495         statusoffset = LINES - 2;
1496         if (!option (OPTHELP))
1497           indexoffset = 0;
1498         bodyoffset = indexoffset + (IsHeader (extra) ? indexlen : 0);
1499         bodylen = statusoffset - bodyoffset;
1500       }
1501
1502       if (option (OPTHELP)) {
1503         SETCOLOR (MT_COLOR_STATUS);
1504         move (helpoffset, 0);
1505         mutt_paddstr (COLS, helpstr);
1506         SETCOLOR (MT_COLOR_NORMAL);
1507       }
1508
1509 #if defined (USE_SLANG_CURSES) || defined (HAVE_RESIZETERM)
1510       if (Resize != NULL) {
1511         if ((SearchCompiled = Resize->SearchCompiled)) {
1512           REGCOMP
1513             (&SearchRE, searchbuf, REG_NEWLINE | mutt_which_case (searchbuf));
1514           SearchFlag = M_SEARCH;
1515           SearchBack = Resize->SearchBack;
1516         }
1517         lines = Resize->line;
1518         redraw |= REDRAW_SIGWINCH;
1519
1520         FREE (&Resize);
1521       }
1522 #endif
1523
1524       if (IsHeader (extra) && PagerIndexLines) {
1525         if (index == NULL) {
1526           /* only allocate the space if/when we need the index.
1527              Initialise the menu as per the main index */
1528           index = mutt_new_menu ();
1529           index->menu = MENU_MAIN;
1530           index->make_entry = index_make_entry;
1531           index->color = index_color;
1532           index->max = Context->vcount;
1533           index->current = extra->hdr->virtual;
1534         }
1535
1536         SETCOLOR (MT_COLOR_NORMAL);
1537         index->offset = indexoffset + (option (OPTSTATUSONTOP) ? 1 : 0);
1538
1539         index->pagelen = indexlen - 1;
1540
1541         /* some fudge to work out where abouts the indicator should go */
1542         if (index->current - indicator < 0)
1543           index->top = 0;
1544         else if (index->max - index->current < index->pagelen - indicator)
1545           index->top = index->max - index->pagelen;
1546         else
1547           index->top = index->current - indicator;
1548
1549         menu_redraw_index (index);
1550       }
1551
1552       redraw |= REDRAW_BODY | REDRAW_INDEX | REDRAW_STATUS;
1553       mutt_show_error ();
1554     }
1555
1556     if (redraw & REDRAW_SIGWINCH) {
1557       i = -1;
1558       j = -1;
1559       while (display_line (fp, &last_pos, &lineInfo, ++i, &lastLine, &maxLine,
1560                            has_types | SearchFlag, &QuoteList, &q_level,
1561                            &force_redraw, &SearchRE) == 0) {
1562         if (!lineInfo[i].continuation && ++j == lines) {
1563           topline = i;
1564           if (!SearchFlag)
1565             break;
1566         }
1567         redraw |= REDRAW_SIDEBAR;
1568       }                         /* while */
1569     }
1570
1571     if ((redraw & REDRAW_BODY) || topline != oldtopline) {
1572       do {
1573         move (bodyoffset, SidebarWidth);
1574         curline = oldtopline = topline;
1575         lines = 0;
1576         force_redraw = 0;
1577
1578         while (lines < bodylen && lineInfo[curline].offset <= sb.st_size - 1) {
1579           if (display_line (fp, &last_pos, &lineInfo, curline, &lastLine,
1580                             &maxLine,
1581                             (flags & M_DISPLAYFLAGS) | hideQuoted |
1582                             SearchFlag, &QuoteList, &q_level, &force_redraw,
1583                             &SearchRE) > 0)
1584             lines++;
1585           curline++;
1586           move (lines + bodyoffset, SidebarWidth);
1587           redraw |= REDRAW_SIDEBAR;
1588         }
1589         last_offset = lineInfo[curline].offset;
1590       } while (force_redraw);
1591
1592       SETCOLOR (MT_COLOR_TILDE);
1593       BKGDSET (MT_COLOR_TILDE);
1594       while (lines < bodylen) {
1595         clrtoeol ();
1596         if (option (OPTTILDE))
1597           addch ('~');
1598         addch ('\n');
1599         lines++;
1600         move (lines + bodyoffset, SidebarWidth);
1601       }
1602       /* We are going to update the pager status bar, so it isn't
1603        * necessary to reset to normal color now. */
1604
1605       redraw |= REDRAW_STATUS;  /* need to update the % seen */
1606     }
1607
1608     if (redraw & REDRAW_STATUS) {
1609       /* print out the pager status bar */
1610       SETCOLOR (MT_COLOR_STATUS);
1611       BKGDSET (MT_COLOR_STATUS);
1612       CLEARLINE_WIN (statusoffset);
1613       if (IsHeader (extra)) {
1614         size_t l1 = (COLS - 9) * MB_LEN_MAX;
1615         size_t l2 = sizeof (buffer);
1616
1617         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1618                            Context, extra->hdr, M_FORMAT_MAKEPRINT);
1619       }
1620       else if (IsMsgAttach (extra)) {
1621         size_t l1 = (COLS - 9) * MB_LEN_MAX;
1622         size_t l2 = sizeof (buffer);
1623
1624         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1625                            Context, extra->bdy->hdr, M_FORMAT_MAKEPRINT);
1626       }
1627       if (option(OPTSTATUSONTOP)) {
1628         move(0,0);
1629       }
1630       /*move (indexoffset + (option (OPTSTATUSONTOP) ? 0 : (InHelp?(LINES-2):(indexlen - 1))),
1631             option (OPTSTATUSONTOP) ? 0 : SidebarWidth);*/
1632       mutt_paddstr (COLS - 10 - (option(OPTSTATUSONTOP)?0:SidebarWidth), IsHeader (extra)
1633                     || IsMsgAttach (extra) ? buffer : banner);
1634
1635       addstr (" -- (");
1636       if (last_pos < sb.st_size - 1)
1637         printw ("%d%%)", (int) (100 * last_offset / sb.st_size));
1638       else
1639         addstr (topline == 0 ? "all)" : "end)");
1640       BKGDSET (MT_COLOR_NORMAL);
1641       SETCOLOR (MT_COLOR_NORMAL);
1642     }
1643
1644     if (redraw & REDRAW_SIDEBAR)
1645       sidebar_draw (MENU_PAGER);
1646
1647     if ((redraw & REDRAW_INDEX) && index) {
1648       /* redraw the pager_index indicator, because the
1649        * flags for this message might have changed. */
1650       menu_redraw_current (index);
1651       sidebar_draw (MENU_PAGER);
1652       /* print out the index status bar */
1653       menu_status_line (buffer, sizeof (buffer), index, NONULL (Status));
1654       move (indexoffset + (option (OPTSTATUSONTOP) ? 0 : (indexlen - 1)),
1655             option (OPTSTATUSONTOP) ? 0 : SidebarWidth);
1656       SETCOLOR (MT_COLOR_STATUS);
1657       BKGDSET (MT_COLOR_STATUS);
1658       mutt_paddstr (COLS - (option (OPTSTATUSONTOP) ? 0 : SidebarWidth),
1659                     buffer);
1660       SETCOLOR (MT_COLOR_NORMAL);
1661       BKGDSET (MT_COLOR_NORMAL);
1662     }
1663     /* if we're not using the index, update every time */
1664     if (index == 0)
1665       sidebar_draw (MENU_PAGER);
1666
1667     redraw = 0;
1668
1669     move (statusoffset, COLS - 1);
1670     mutt_refresh ();
1671     ch = km_dokey (MENU_PAGER);
1672     if (ch != -1)
1673       mutt_clear_error ();
1674     mutt_curs_set (1);
1675
1676     if (SigInt) {
1677       mutt_query_exit ();
1678       continue;
1679     }
1680 #if defined (USE_SLANG_CURSES) || defined (HAVE_RESIZETERM)
1681     else if (SigWinch) {
1682       mutt_resize_screen ();
1683
1684       /* Store current position. */
1685       lines = -1;
1686       for (i = 0; i <= topline; i++)
1687         if (!lineInfo[i].continuation)
1688           lines++;
1689
1690       if (flags & M_PAGER_RETWINCH) {
1691         Resize = safe_malloc (sizeof (struct resize));
1692
1693         Resize->line = lines;
1694         Resize->SearchCompiled = SearchCompiled;
1695         Resize->SearchBack = SearchBack;
1696
1697         ch = -1;
1698         rc = OP_REFORMAT_WINCH;
1699       }
1700       else {
1701         for (i = 0; i < maxLine; i++) {
1702           lineInfo[i].offset = 0;
1703           lineInfo[i].type = -1;
1704           lineInfo[i].continuation = 0;
1705           lineInfo[i].chunks = 0;
1706           lineInfo[i].search_cnt = -1;
1707           lineInfo[i].quote = NULL;
1708
1709           safe_realloc (&(lineInfo[i].syntax), sizeof (struct syntax_t));
1710           if (SearchCompiled && lineInfo[i].search)
1711             FREE (&(lineInfo[i].search));
1712         }
1713
1714         lastLine = 0;
1715         topline = 0;
1716
1717         redraw = REDRAW_FULL | REDRAW_SIGWINCH;
1718         ch = 0;
1719       }
1720
1721       SigWinch = 0;
1722       clearok (stdscr, TRUE);   /*force complete redraw */
1723       continue;
1724     }
1725 #endif
1726     else if (ch == -1) {
1727       ch = 0;
1728       continue;
1729     }
1730
1731     rc = ch;
1732
1733     switch (ch) {
1734     case OP_EXIT:
1735       rc = -1;
1736       ch = -1;
1737       break;
1738
1739     case OP_NEXT_PAGE:
1740       if (lineInfo[curline].offset < sb.st_size - 1) {
1741         topline = upNLines (PagerContext, lineInfo, curline, hideQuoted);
1742       }
1743       else if (option (OPTPAGERSTOP)) {
1744         /* emulate "less -q" and don't go on to the next message. */
1745         mutt_error _("Bottom of message is shown.");
1746       }
1747       else {
1748         /* end of the current message, so display the next message. */
1749         rc = OP_MAIN_NEXT_UNDELETED;
1750         ch = -1;
1751       }
1752       break;
1753
1754     case OP_PREV_PAGE:
1755       if (topline != 0) {
1756         topline =
1757           upNLines (bodylen - PagerContext, lineInfo, topline, hideQuoted);
1758       }
1759       else
1760         mutt_error _("Top of message is shown.");
1761       break;
1762
1763     case OP_NEXT_LINE:
1764       if (lineInfo[curline].offset < sb.st_size - 1) {
1765         topline++;
1766         if (hideQuoted) {
1767           while (lineInfo[topline].type == MT_COLOR_QUOTED &&
1768                  topline < lastLine)
1769             topline++;
1770         }
1771       }
1772       else
1773         mutt_error _("Bottom of message is shown.");
1774       break;
1775
1776     case OP_PREV_LINE:
1777       if (topline)
1778         topline = upNLines (1, lineInfo, topline, hideQuoted);
1779       else
1780         mutt_error _("Top of message is shown.");
1781       break;
1782
1783     case OP_PAGER_TOP:
1784       if (topline)
1785         topline = 0;
1786       else
1787         mutt_error _("Top of message is shown.");
1788       break;
1789
1790     case OP_HALF_UP:
1791       if (topline)
1792         topline = upNLines (bodylen / 2, lineInfo, topline, hideQuoted);
1793       else
1794         mutt_error _("Top of message is shown.");
1795       break;
1796
1797     case OP_HALF_DOWN:
1798       if (lineInfo[curline].offset < sb.st_size - 1) {
1799         topline = upNLines (bodylen / 2, lineInfo, curline, hideQuoted);
1800       }
1801       else if (option (OPTPAGERSTOP)) {
1802         /* emulate "less -q" and don't go on to the next message. */
1803         mutt_error _("Bottom of message is shown.");
1804       }
1805       else {
1806         /* end of the current message, so display the next message. */
1807         rc = OP_MAIN_NEXT_UNDELETED;
1808         ch = -1;
1809       }
1810       break;
1811
1812     case OP_SEARCH_NEXT:
1813     case OP_SEARCH_OPPOSITE:
1814       if (SearchCompiled) {
1815       search_next:
1816         if ((!SearchBack && ch == OP_SEARCH_NEXT) ||
1817             (SearchBack && ch == OP_SEARCH_OPPOSITE)) {
1818           /* searching forward */
1819           for (i = topline + 1; i < lastLine; i++) {
1820             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1821                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1822               break;
1823           }
1824
1825           if (i < lastLine)
1826             topline = i;
1827           else
1828             mutt_error _("Not found.");
1829         }
1830         else {
1831           /* searching backward */
1832           for (i = topline - 1; i >= 0; i--) {
1833             if ((!hideQuoted || (has_types &&
1834                                  lineInfo[i].type != MT_COLOR_QUOTED)) &&
1835                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1836               break;
1837           }
1838
1839           if (i >= 0)
1840             topline = i;
1841           else
1842             mutt_error _("Not found.");
1843         }
1844
1845         if (lineInfo[topline].search_cnt > 0)
1846           SearchFlag = M_SEARCH;
1847
1848         break;
1849       }
1850       /* no previous search pattern, so fall through to search */
1851
1852     case OP_SEARCH:
1853     case OP_SEARCH_REVERSE:
1854       strfcpy (buffer, searchbuf, sizeof (buffer));
1855       if (mutt_get_field ((SearchBack ? _("Reverse search: ") :
1856                            _("Search: ")), buffer, sizeof (buffer),
1857                           M_CLEAR) != 0)
1858         break;
1859
1860       if (!strcmp (buffer, searchbuf)) {
1861         if (SearchCompiled) {
1862           /* do an implicit search-next */
1863           if (ch == OP_SEARCH)
1864             ch = OP_SEARCH_NEXT;
1865           else
1866             ch = OP_SEARCH_OPPOSITE;
1867
1868           goto search_next;
1869         }
1870       }
1871
1872       if (!buffer[0])
1873         break;
1874
1875       strfcpy (searchbuf, buffer, sizeof (searchbuf));
1876
1877       /* leave SearchBack alone if ch == OP_SEARCH_NEXT */
1878       if (ch == OP_SEARCH)
1879         SearchBack = 0;
1880       else if (ch == OP_SEARCH_REVERSE)
1881         SearchBack = 1;
1882
1883       if (SearchCompiled) {
1884         regfree (&SearchRE);
1885         for (i = 0; i < lastLine; i++) {
1886           if (lineInfo[i].search)
1887             FREE (&(lineInfo[i].search));
1888           lineInfo[i].search_cnt = -1;
1889         }
1890       }
1891
1892       if ((err =
1893            REGCOMP (&SearchRE, searchbuf,
1894                     REG_NEWLINE | mutt_which_case (searchbuf))) != 0) {
1895         regerror (err, &SearchRE, buffer, sizeof (buffer));
1896         mutt_error ("%s", buffer);
1897         regfree (&SearchRE);
1898         for (i = 0; i < maxLine; i++) {
1899           /* cleanup */
1900           if (lineInfo[i].search)
1901             FREE (&(lineInfo[i].search));
1902           lineInfo[i].search_cnt = -1;
1903         }
1904         SearchFlag = 0;
1905         SearchCompiled = 0;
1906       }
1907       else {
1908         SearchCompiled = 1;
1909         /* update the search pointers */
1910         i = 0;
1911         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
1912                              &maxLine, M_SEARCH | (flags & M_PAGER_NSKIP),
1913                              &QuoteList, &q_level,
1914                              &force_redraw, &SearchRE) == 0) {
1915           i++;
1916           redraw |= REDRAW_SIDEBAR;
1917         }
1918
1919         if (!SearchBack) {
1920           /* searching forward */
1921           for (i = topline; i < lastLine; i++) {
1922             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1923                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1924               break;
1925           }
1926
1927           if (i < lastLine)
1928             topline = i;
1929         }
1930         else {
1931           /* searching backward */
1932           for (i = topline; i >= 0; i--) {
1933             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1934                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1935               break;
1936           }
1937
1938           if (i >= 0)
1939             topline = i;
1940         }
1941
1942         if (lineInfo[topline].search_cnt == 0) {
1943           SearchFlag = 0;
1944           mutt_error _("Not found.");
1945         }
1946         else
1947           SearchFlag = M_SEARCH;
1948       }
1949       redraw = REDRAW_BODY;
1950       break;
1951
1952     case OP_SEARCH_TOGGLE:
1953       if (SearchCompiled) {
1954         SearchFlag ^= M_SEARCH;
1955         redraw = REDRAW_BODY;
1956       }
1957       break;
1958
1959     case OP_HELP:
1960       /* don't let the user enter the help-menu from the help screen! */
1961       if (!InHelp) {
1962         InHelp = 1;
1963         mutt_help (MENU_PAGER);
1964         redraw = REDRAW_FULL;
1965         InHelp = 0;
1966       }
1967       else
1968         mutt_error _("Help is currently being shown.");
1969       break;
1970
1971     case OP_PAGER_HIDE_QUOTED:
1972       if (has_types) {
1973         hideQuoted ^= M_HIDE;
1974         if (hideQuoted && lineInfo[topline].type == MT_COLOR_QUOTED)
1975           topline = upNLines (1, lineInfo, topline, hideQuoted);
1976         else
1977           redraw = REDRAW_BODY;
1978       }
1979       break;
1980
1981     case OP_PAGER_SKIP_QUOTED:
1982       if (has_types) {
1983         int dretval = 0;
1984         int new_topline = topline;
1985
1986         while ((new_topline < lastLine ||
1987                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
1988                                                new_topline, &lastLine,
1989                                                &maxLine, M_TYPES, &QuoteList,
1990                                                &q_level, &force_redraw,
1991                                                &SearchRE))))
1992                && lineInfo[new_topline].type != MT_COLOR_QUOTED) {
1993           redraw |= REDRAW_SIDEBAR;
1994           new_topline++;
1995         }
1996
1997         if (dretval < 0) {
1998           mutt_error _("No more quoted text.");
1999
2000           break;
2001         }
2002
2003         while ((new_topline < lastLine ||
2004                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
2005                                                new_topline, &lastLine,
2006                                                &maxLine, M_TYPES, &QuoteList,
2007                                                &q_level, &force_redraw,
2008                                                &SearchRE))))
2009                && lineInfo[new_topline].type == MT_COLOR_QUOTED) {
2010           new_topline++;
2011           redraw |= REDRAW_SIDEBAR;
2012         }
2013
2014         if (dretval < 0) {
2015           mutt_error _("No more unquoted text after quoted text.");
2016
2017           break;
2018         }
2019         topline = new_topline;
2020       }
2021       break;
2022
2023     case OP_PAGER_BOTTOM:      /* move to the end of the file */
2024       if (lineInfo[curline].offset < sb.st_size - 1) {
2025         i = curline;
2026         /* make sure the types are defined to the end of file */
2027         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
2028                              &maxLine, has_types,
2029                              &QuoteList, &q_level, &force_redraw,
2030                              &SearchRE) == 0) {
2031           i++;
2032           redraw |= REDRAW_SIDEBAR;
2033         }
2034         topline = upNLines (bodylen, lineInfo, lastLine, hideQuoted);
2035       }
2036       else
2037         mutt_error _("Bottom of message is shown.");
2038       break;
2039
2040     case OP_REDRAW:
2041       clearok (stdscr, TRUE);
2042       redraw = REDRAW_FULL;
2043       break;
2044
2045     case OP_NULL:
2046       km_error_key (MENU_PAGER);
2047       break;
2048
2049       /* --------------------------------------------------------------------
2050        * The following are operations on the current message rather than
2051        * adjusting the view of the message.
2052        */
2053
2054     case OP_BOUNCE_MESSAGE:
2055       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
2056         CHECK_ATTACH;
2057       if (IsMsgAttach (extra))
2058         mutt_attach_bounce (extra->fp, extra->hdr,
2059                             extra->idx, extra->idxlen, extra->bdy);
2060       else
2061         ci_bounce_message (extra->hdr, &redraw);
2062       break;
2063
2064     case OP_RESEND:
2065       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
2066         CHECK_ATTACH;
2067       if (IsMsgAttach (extra))
2068         mutt_attach_resend (extra->fp, extra->hdr,
2069                             extra->idx, extra->idxlen, extra->bdy);
2070       else
2071         mutt_resend_message (NULL, extra->ctx, extra->hdr);
2072       redraw = REDRAW_FULL;
2073       break;
2074
2075     case OP_CHECK_TRADITIONAL:
2076       CHECK_MODE (IsHeader (extra));
2077       if (!(WithCrypto & APPLICATION_PGP))
2078         break;
2079       if (!(extra->hdr->security & PGP_TRADITIONAL_CHECKED)) {
2080         ch = -1;
2081         rc = OP_CHECK_TRADITIONAL;
2082       }
2083       break;
2084
2085     case OP_CREATE_ALIAS:
2086       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2087       if (IsMsgAttach (extra))
2088         mutt_create_alias (extra->bdy->hdr->env, NULL);
2089       else
2090         mutt_create_alias (extra->hdr->env, NULL);
2091       MAYBE_REDRAW (redraw);
2092       break;
2093
2094     case OP_PURGE_MESSAGE:
2095     case OP_DELETE:
2096       CHECK_MODE (IsHeader (extra));
2097       CHECK_READONLY;
2098
2099       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
2100
2101       mutt_set_flag (Context, extra->hdr, M_DELETE, 1);
2102       mutt_set_flag (Context, extra->hdr, M_PURGED,
2103                      ch != OP_PURGE_MESSAGE ? 0 : 1);
2104       if (option (OPTDELETEUNTAG))
2105         mutt_set_flag (Context, extra->hdr, M_TAG, 0);
2106       redraw = REDRAW_STATUS | REDRAW_INDEX;
2107       if (option (OPTRESOLVE)) {
2108         ch = -1;
2109         rc = OP_MAIN_NEXT_UNDELETED;
2110       }
2111       break;
2112
2113     case OP_DELETE_THREAD:
2114     case OP_DELETE_SUBTHREAD:
2115       CHECK_MODE (IsHeader (extra));
2116       CHECK_READONLY;
2117
2118       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
2119
2120       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 1,
2121                                 ch == OP_DELETE_THREAD ? 0 : 1);
2122
2123       if (r != -1) {
2124         if (option (OPTDELETEUNTAG))
2125           mutt_thread_set_flag (extra->hdr, M_TAG, 0,
2126                                 ch == OP_DELETE_THREAD ? 0 : 1);
2127         if (option (OPTRESOLVE)) {
2128           rc = OP_MAIN_NEXT_UNDELETED;
2129           ch = -1;
2130         }
2131
2132         if (!option (OPTRESOLVE) && PagerIndexLines)
2133           redraw = REDRAW_FULL;
2134         else
2135           redraw = REDRAW_STATUS | REDRAW_INDEX;
2136       }
2137       break;
2138
2139     case OP_DISPLAY_ADDRESS:
2140       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2141       if (IsMsgAttach (extra))
2142         mutt_display_address (extra->bdy->hdr->env);
2143       else
2144         mutt_display_address (extra->hdr->env);
2145       break;
2146
2147     case OP_ENTER_COMMAND:
2148       old_smart_wrap = option (OPTWRAP);
2149       old_markers = option (OPTMARKERS);
2150       old_PagerIndexLines = PagerIndexLines;
2151
2152       CurrentMenu = MENU_PAGER;
2153       mutt_enter_command ();
2154
2155       if (option (OPTNEEDRESORT)) {
2156         unset_option (OPTNEEDRESORT);
2157         CHECK_MODE (IsHeader (extra));
2158         set_option (OPTNEEDRESORT);
2159       }
2160
2161       if (old_PagerIndexLines != PagerIndexLines) {
2162         if (index)
2163           mutt_menuDestroy (&index);
2164         index = NULL;
2165       }
2166
2167       if (option (OPTWRAP) != old_smart_wrap ||
2168           option (OPTMARKERS) != old_markers) {
2169         if (flags & M_PAGER_RETWINCH) {
2170           ch = -1;
2171           rc = OP_REFORMAT_WINCH;
2172           continue;
2173         }
2174
2175         /* count the real lines above */
2176         j = 0;
2177         for (i = 0; i <= topline; i++) {
2178           if (!lineInfo[i].continuation)
2179             j++;
2180         }
2181
2182         /* we need to restart the whole thing */
2183         for (i = 0; i < maxLine; i++) {
2184           lineInfo[i].offset = 0;
2185           lineInfo[i].type = -1;
2186           lineInfo[i].continuation = 0;
2187           lineInfo[i].chunks = 0;
2188           lineInfo[i].search_cnt = -1;
2189           lineInfo[i].quote = NULL;
2190
2191           safe_realloc (&(lineInfo[i].syntax), sizeof (struct syntax_t));
2192           if (SearchCompiled && lineInfo[i].search)
2193             FREE (&(lineInfo[i].search));
2194         }
2195
2196         if (SearchCompiled) {
2197           regfree (&SearchRE);
2198           SearchCompiled = 0;
2199         }
2200         SearchFlag = 0;
2201
2202         /* try to keep the old position */
2203         topline = 0;
2204         lastLine = 0;
2205         while (j > 0 && display_line (fp, &last_pos, &lineInfo, topline,
2206                                       &lastLine, &maxLine,
2207                                       (has_types ? M_TYPES : 0),
2208                                       &QuoteList, &q_level, &force_redraw,
2209                                       &SearchRE) == 0) {
2210           redraw |= REDRAW_SIDEBAR;
2211           if (!lineInfo[topline].continuation)
2212             j--;
2213           if (j > 0)
2214             topline++;
2215         }
2216
2217         ch = 0;
2218       }
2219
2220       if (option (OPTFORCEREDRAWPAGER))
2221         redraw = REDRAW_FULL;
2222       unset_option (OPTFORCEREDRAWINDEX);
2223       unset_option (OPTFORCEREDRAWPAGER);
2224       break;
2225
2226     case OP_FLAG_MESSAGE:
2227       CHECK_MODE (IsHeader (extra));
2228       CHECK_READONLY;
2229
2230       CHECK_MX_ACL (Context, ACL_WRITE, _("Flagging"));
2231
2232       mutt_set_flag (Context, extra->hdr, M_FLAG, !extra->hdr->flagged);
2233       redraw = REDRAW_STATUS | REDRAW_INDEX;
2234       if (option (OPTRESOLVE)) {
2235         ch = -1;
2236         rc = OP_MAIN_NEXT_UNDELETED;
2237       }
2238       break;
2239
2240     case OP_PIPE:
2241       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2242       if (IsAttach (extra))
2243         mutt_pipe_attachment_list (extra->fp, 0, extra->bdy, 0);
2244       else
2245         mutt_pipe_message (extra->hdr);
2246       MAYBE_REDRAW (redraw);
2247       break;
2248
2249     case OP_PRINT:
2250       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2251       if (IsAttach (extra))
2252         mutt_print_attachment_list (extra->fp, 0, extra->bdy);
2253       else
2254         mutt_print_message (extra->hdr);
2255       break;
2256
2257     case OP_MAIL:
2258       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2259       CHECK_ATTACH;
2260       ci_send_message (0, NULL, NULL, extra->ctx, NULL);
2261       redraw = REDRAW_FULL;
2262       break;
2263
2264 #ifdef USE_NNTP
2265     case OP_POST:
2266       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2267       CHECK_ATTACH;
2268       if (extra->ctx && extra->ctx->magic == M_NNTP &&
2269           !((NNTP_DATA *) extra->ctx->data)->allowed &&
2270           query_quadoption (OPT_TOMODERATED,
2271                             _
2272                             ("Posting to this group not allowed, may be moderated. Continue?"))
2273           != M_YES)
2274         break;
2275       ci_send_message (SENDNEWS, NULL, NULL, extra->ctx, NULL);
2276       redraw = REDRAW_FULL;
2277       break;
2278
2279     case OP_FORWARD_TO_GROUP:
2280       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2281       CHECK_ATTACH;
2282       if (extra->ctx && extra->ctx->magic == M_NNTP &&
2283           !((NNTP_DATA *) extra->ctx->data)->allowed &&
2284           query_quadoption (OPT_TOMODERATED,
2285                             _
2286                             ("Posting to this group not allowed, may be moderated. Continue?"))
2287           != M_YES)
2288         break;
2289       if (IsMsgAttach (extra))
2290         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2291                              extra->idxlen, extra->bdy, SENDNEWS);
2292       else
2293         ci_send_message (SENDNEWS | SENDFORWARD, NULL, NULL, extra->ctx,
2294                          extra->hdr);
2295       redraw = REDRAW_FULL;
2296       break;
2297
2298     case OP_FOLLOWUP:
2299       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2300       CHECK_ATTACH;
2301
2302       if (IsMsgAttach (extra))
2303         followup_to = extra->bdy->hdr->env->followup_to;
2304       else
2305         followup_to = extra->hdr->env->followup_to;
2306
2307       if (!followup_to || safe_strcasecmp (followup_to, "poster") ||
2308           query_quadoption (OPT_FOLLOWUPTOPOSTER,
2309                             _("Reply by mail as poster prefers?")) != M_YES) {
2310         if (extra->ctx && extra->ctx->magic == M_NNTP
2311             && !((NNTP_DATA *) extra->ctx->data)->allowed
2312             && query_quadoption (OPT_TOMODERATED,
2313                                  _
2314                                  ("Posting to this group not allowed, may be moderated. Continue?"))
2315             != M_YES)
2316           break;
2317         if (IsMsgAttach (extra))
2318           mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2319                              extra->idxlen, extra->bdy, SENDNEWS | SENDREPLY);
2320         else
2321           ci_send_message (SENDNEWS | SENDREPLY, NULL, NULL,
2322                            extra->ctx, extra->hdr);
2323         redraw = REDRAW_FULL;
2324         break;
2325       }
2326 #endif
2327
2328     case OP_REPLY:
2329       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2330       CHECK_ATTACH;
2331       if (IsMsgAttach (extra))
2332         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2333                            extra->idxlen, extra->bdy, SENDREPLY);
2334       else
2335         ci_send_message (SENDREPLY, NULL, NULL, extra->ctx, extra->hdr);
2336       redraw = REDRAW_FULL;
2337       break;
2338
2339     case OP_RECALL_MESSAGE:
2340       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2341       CHECK_ATTACH;
2342       ci_send_message (SENDPOSTPONED, NULL, NULL, extra->ctx, extra->hdr);
2343       redraw = REDRAW_FULL;
2344       break;
2345
2346     case OP_GROUP_REPLY:
2347       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2348       CHECK_ATTACH;
2349       if (IsMsgAttach (extra))
2350         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2351                            extra->idxlen, extra->bdy,
2352                            SENDREPLY | SENDGROUPREPLY);
2353       else
2354         ci_send_message (SENDREPLY | SENDGROUPREPLY, NULL, NULL, extra->ctx,
2355                          extra->hdr);
2356       redraw = REDRAW_FULL;
2357       break;
2358
2359     case OP_LIST_REPLY:
2360       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2361       CHECK_ATTACH;
2362       if (IsMsgAttach (extra))
2363         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2364                            extra->idxlen, extra->bdy,
2365                            SENDREPLY | SENDLISTREPLY);
2366       else
2367         ci_send_message (SENDREPLY | SENDLISTREPLY, NULL, NULL, extra->ctx,
2368                          extra->hdr);
2369       redraw = REDRAW_FULL;
2370       break;
2371
2372     case OP_FORWARD_MESSAGE:
2373       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2374       CHECK_ATTACH;
2375       if (IsMsgAttach (extra))
2376         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2377                              extra->idxlen, extra->bdy, 0);
2378       else
2379         ci_send_message (SENDFORWARD, NULL, NULL, extra->ctx, extra->hdr);
2380       redraw = REDRAW_FULL;
2381       break;
2382
2383     case OP_DECRYPT_SAVE:
2384       if (!WithCrypto) {
2385         ch = -1;
2386         break;
2387       }
2388       /* fall through */
2389     case OP_SAVE:
2390       if (IsAttach (extra)) {
2391         mutt_save_attachment_list (extra->fp, 0, extra->bdy, extra->hdr,
2392                                    NULL);
2393         break;
2394       }
2395       /* fall through */
2396     case OP_COPY_MESSAGE:
2397     case OP_DECODE_SAVE:
2398     case OP_DECODE_COPY:
2399     case OP_DECRYPT_COPY:
2400       if (!WithCrypto && ch == OP_DECRYPT_COPY) {
2401         ch = -1;
2402         break;
2403       }
2404       CHECK_MODE (IsHeader (extra));
2405       if (mutt_save_message (extra->hdr,
2406                              (ch == OP_DECRYPT_SAVE) ||
2407                              (ch == OP_SAVE) || (ch == OP_DECODE_SAVE),
2408                              (ch == OP_DECODE_SAVE) || (ch == OP_DECODE_COPY),
2409                              (ch == OP_DECRYPT_SAVE)
2410                              || (ch == OP_DECRYPT_COPY) || 0, &redraw) == 0
2411           && (ch == OP_SAVE || ch == OP_DECODE_SAVE
2412               || ch == OP_DECRYPT_SAVE)) {
2413         if (option (OPTRESOLVE)) {
2414           ch = -1;
2415           rc = OP_MAIN_NEXT_UNDELETED;
2416         }
2417         else
2418           redraw |= REDRAW_STATUS | REDRAW_INDEX;
2419       }
2420       MAYBE_REDRAW (redraw);
2421       break;
2422
2423     case OP_SHELL_ESCAPE:
2424       mutt_shell_escape ();
2425       MAYBE_REDRAW (redraw);
2426       break;
2427
2428     case OP_TAG:
2429       CHECK_MODE (IsHeader (extra));
2430       mutt_set_flag (Context, extra->hdr, M_TAG, !extra->hdr->tagged);
2431
2432       Context->last_tag = extra->hdr->tagged ? extra->hdr :
2433         ((Context->last_tag == extra->hdr && !extra->hdr->tagged)
2434          ? NULL : Context->last_tag);
2435
2436       redraw = REDRAW_STATUS | REDRAW_INDEX;
2437       if (option (OPTRESOLVE)) {
2438         ch = -1;
2439         rc = OP_NEXT_ENTRY;
2440       }
2441       break;
2442
2443     case OP_TOGGLE_NEW:
2444       CHECK_MODE (IsHeader (extra));
2445       CHECK_READONLY;
2446
2447       CHECK_MX_ACL (Context, ACL_SEEN, _("Toggling"));
2448
2449       if (extra->hdr->read || extra->hdr->old)
2450         mutt_set_flag (Context, extra->hdr, M_NEW, 1);
2451       else if (!first)
2452         mutt_set_flag (Context, extra->hdr, M_READ, 1);
2453       first = 0;
2454       Context->msgnotreadyet = -1;
2455       redraw = REDRAW_STATUS | REDRAW_INDEX;
2456       if (option (OPTRESOLVE)) {
2457         ch = -1;
2458         rc = OP_MAIN_NEXT_UNDELETED;
2459       }
2460       break;
2461
2462     case OP_UNDELETE:
2463       CHECK_MODE (IsHeader (extra));
2464       CHECK_READONLY;
2465
2466       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2467
2468       mutt_set_flag (Context, extra->hdr, M_DELETE, 0);
2469       mutt_set_flag (Context, extra->hdr, M_PURGED, 0);
2470       redraw = REDRAW_STATUS | REDRAW_INDEX;
2471       if (option (OPTRESOLVE)) {
2472         ch = -1;
2473         rc = OP_NEXT_ENTRY;
2474       }
2475       break;
2476
2477     case OP_UNDELETE_THREAD:
2478     case OP_UNDELETE_SUBTHREAD:
2479       CHECK_MODE (IsHeader (extra));
2480       CHECK_READONLY;
2481
2482       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2483
2484       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 0,
2485                                 ch == OP_UNDELETE_THREAD ? 0 : 1)
2486         + mutt_thread_set_flag (extra->hdr, M_PURGED, 0,
2487                                 ch == OP_UNDELETE_THREAD ? 0 : 1);
2488
2489       if (r > -1) {
2490         if (option (OPTRESOLVE)) {
2491           rc = (ch == OP_DELETE_THREAD) ?
2492             OP_MAIN_NEXT_THREAD : OP_MAIN_NEXT_SUBTHREAD;
2493           ch = -1;
2494         }
2495
2496         if (!option (OPTRESOLVE) && PagerIndexLines)
2497           redraw = REDRAW_FULL;
2498         else
2499           redraw = REDRAW_STATUS | REDRAW_INDEX;
2500       }
2501       break;
2502
2503     case OP_VERSION:
2504       mutt_version ();
2505       break;
2506
2507     case OP_BUFFY_LIST:
2508       buffy_list ();
2509       redraw |= REDRAW_SIDEBAR;
2510       break;
2511
2512     case OP_VIEW_ATTACHMENTS:
2513       if (flags & M_PAGER_ATTACHMENT) {
2514         ch = -1;
2515         rc = OP_ATTACH_COLLAPSE;
2516         break;
2517       }
2518       CHECK_MODE (IsHeader (extra));
2519       mutt_view_attachments (extra->hdr);
2520       if (extra->hdr->attach_del)
2521         Context->changed = 1;
2522       redraw = REDRAW_FULL;
2523       break;
2524
2525
2526     case OP_MAIL_KEY:
2527       if (!(WithCrypto & APPLICATION_PGP)) {
2528         ch = -1;
2529         break;
2530       }
2531       CHECK_MODE (IsHeader (extra));
2532       CHECK_ATTACH;
2533       ci_send_message (SENDKEY, NULL, NULL, extra->ctx, extra->hdr);
2534       redraw = REDRAW_FULL;
2535       break;
2536
2537
2538     case OP_FORGET_PASSPHRASE:
2539       crypt_forget_passphrase ();
2540       break;
2541
2542     case OP_EXTRACT_KEYS:
2543       if (!WithCrypto) {
2544         ch = -1;
2545         break;
2546       }
2547       CHECK_MODE (IsHeader (extra));
2548       crypt_extract_keys_from_messages (extra->hdr);
2549       redraw = REDRAW_FULL;
2550       break;
2551
2552     case OP_SIDEBAR_SCROLL_UP:
2553     case OP_SIDEBAR_SCROLL_DOWN:
2554     case OP_SIDEBAR_NEXT:
2555     case OP_SIDEBAR_NEXT_NEW:
2556     case OP_SIDEBAR_PREV:
2557     case OP_SIDEBAR_PREV_NEW:
2558       sidebar_scroll (ch, MENU_PAGER);
2559       break;
2560     default:
2561       ch = -1;
2562       break;
2563     }
2564   }
2565
2566   fclose (fp);
2567   if (IsHeader (extra))
2568     Context->msgnotreadyet = -1;
2569
2570   cleanup_quote (&QuoteList);
2571
2572   for (i = 0; i < maxLine; i++) {
2573     FREE (&(lineInfo[i].syntax));
2574     if (SearchCompiled && lineInfo[i].search)
2575       FREE (&(lineInfo[i].search));
2576   }
2577   if (SearchCompiled) {
2578     regfree (&SearchRE);
2579     SearchCompiled = 0;
2580   }
2581   FREE (&lineInfo);
2582   if (index)
2583     mutt_menuDestroy (&index);
2584   return (rc != -1 ? rc : 0);
2585 }