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         cnt = ch + 1;
1249       }
1250       else
1251         buf_ptr = buf + cnt;    /* a very long word... */
1252     }
1253     if (!(flags & M_PAGER_NSKIP))
1254       /* skip leading blanks on the next line too */
1255       while (*buf_ptr == ' ' || *buf_ptr == '\t')
1256         buf_ptr++;
1257   }
1258
1259   if (*buf_ptr == '\r')
1260     buf_ptr++;
1261   if (*buf_ptr == '\n')
1262     buf_ptr++;
1263
1264   if ((int) (buf_ptr - buf) < b_read && !(*lineInfo)[n + 1].continuation)
1265     append_line (*lineInfo, n, (int) (buf_ptr - buf));
1266   (*lineInfo)[n + 1].offset = (*lineInfo)[n].offset + (long) (buf_ptr - buf);
1267
1268   /* if we don't need to display the line we are done */
1269   if (!(flags & M_SHOW))
1270     return 0;
1271
1272   /* display the line */
1273   format_line (lineInfo, n, buf, flags, &a, cnt, &ch, &vch, &col, &special);
1274
1275   /* avoid a bug in ncurses... */
1276 #ifndef USE_SLANG_CURSES
1277   if (col == 0) {
1278     SETCOLOR (MT_COLOR_NORMAL);
1279     addch (' ');
1280   }
1281 #endif
1282
1283   /* end the last color pattern (needed by S-Lang) */
1284   if (special || (col != COLS && (flags & (M_SHOWCOLOR | M_SEARCH))))
1285     resolve_color (*lineInfo, n, vch, flags, 0, &a);
1286
1287   /*
1288    * Fill the blank space at the end of the line with the prevailing color.
1289    * ncurses does an implicit clrtoeol() when you do addch('\n') so we have
1290    * to make sure to reset the color *after* that
1291    */
1292   if (flags & M_SHOWCOLOR) {
1293     m = ((*lineInfo)[n].continuation) ? ((*lineInfo)[n].syntax)[0].first : n;
1294     if ((*lineInfo)[m].type == MT_COLOR_HEADER)
1295       def_color = ((*lineInfo)[m].syntax)[0].color;
1296     else
1297       def_color = ColorDefs[(*lineInfo)[m].type];
1298
1299     attrset (def_color);
1300 #ifdef HAVE_BKGDSET
1301     bkgdset (def_color | ' ');
1302 #endif
1303   }
1304
1305   /* ncurses always wraps lines when you get to the right side of the
1306    * screen, but S-Lang seems to only wrap if the next character is *not*
1307    * a newline (grr!).
1308    */
1309 #ifndef USE_SLANG_CURSES
1310   if (col < COLS)
1311 #endif
1312     addch ('\n');
1313
1314   /*
1315    * reset the color back to normal.  This *must* come after the
1316    * addch('\n'), otherwise the color for this line will not be
1317    * filled to the right margin.
1318    */
1319   if (flags & M_SHOWCOLOR) {
1320     SETCOLOR (MT_COLOR_NORMAL);
1321     BKGDSET (MT_COLOR_NORMAL);
1322   }
1323
1324   /* build a return code */
1325   if (!(flags & M_SHOW))
1326     flags = 0;
1327
1328   return (flags);
1329 }
1330
1331 static int upNLines (int nlines, struct line_t *info, int cur, int hiding)
1332 {
1333   while (cur > 0 && nlines > 0) {
1334     cur--;
1335     if (!hiding || info[cur].type != MT_COLOR_QUOTED)
1336       nlines--;
1337   }
1338
1339   return cur;
1340 }
1341
1342 static struct mapping_t PagerHelp[] = {
1343   {N_("Exit"), OP_EXIT},
1344   {N_("PrevPg"), OP_PREV_PAGE},
1345   {N_("NextPg"), OP_NEXT_PAGE},
1346   {NULL, 0}
1347 };
1348 static struct mapping_t PagerHelpExtra[] = {
1349   {N_("View Attachm."), OP_VIEW_ATTACHMENTS},
1350   {N_("Del"), OP_DELETE},
1351   {N_("Reply"), OP_REPLY},
1352   {N_("Next"), OP_MAIN_NEXT_UNDELETED},
1353   {NULL, 0}
1354 };
1355
1356 #ifdef USE_NNTP
1357 static struct mapping_t PagerNewsHelpExtra[] = {
1358   {N_("Post"), OP_POST},
1359   {N_("Followup"), OP_FOLLOWUP},
1360   {N_("Del"), OP_DELETE},
1361   {N_("Next"), OP_MAIN_NEXT_UNDELETED},
1362   {NULL, 0}
1363 };
1364 #endif
1365
1366
1367
1368 /* This pager is actually not so simple as it once was.  It now operates in
1369    two modes: one for viewing messages and the other for viewing help.  These
1370    can be distinguished by whether or not ``hdr'' is NULL.  The ``hdr'' arg
1371    is there so that we can do operations on the current message without the
1372    need to pop back out to the main-menu.  */
1373 int
1374 mutt_pager (const char *banner, const char *fname, int flags, pager_t * extra)
1375 {
1376   static char searchbuf[STRING];
1377   char buffer[LONG_STRING];
1378   char helpstr[SHORT_STRING * 2];
1379   char tmphelp[SHORT_STRING * 2];
1380   int maxLine, lastLine = 0;
1381   struct line_t *lineInfo;
1382   struct q_class_t *QuoteList = NULL;
1383   int i, j, ch = 0, rc = -1, hideQuoted = 0, q_level = 0, force_redraw = 0;
1384   int lines = 0, curline = 0, topline = 0, oldtopline = 0, err, first = 1;
1385   int r = -1;
1386   int redraw = REDRAW_FULL;
1387   FILE *fp = NULL;
1388   long last_pos = 0, last_offset = 0;
1389   int old_smart_wrap, old_markers;
1390   struct stat sb;
1391   regex_t SearchRE;
1392   int SearchCompiled = 0, SearchFlag = 0, SearchBack = 0;
1393   int has_types = (IsHeader (extra) || (flags & M_SHOWCOLOR)) ? M_TYPES : 0;    /* main message or rfc822 attachment */
1394
1395   int bodyoffset = 1;           /* offset of first line of real text */
1396   int statusoffset = 0;         /* offset for the status bar */
1397   int helpoffset = LINES - 2;   /* offset for the help bar. */
1398   int bodylen = LINES - 2 - bodyoffset; /* length of displayable area */
1399
1400   MUTTMENU *index = NULL;       /* the Pager Index (PI) */
1401   int indexoffset = 0;          /* offset for the PI */
1402   int indexlen = PagerIndexLines;       /* indexlen not always == PIL */
1403   int indicator = indexlen / 3; /* the indicator line of the PI */
1404   int old_PagerIndexLines;      /* some people want to resize it
1405                                  * while inside the pager... */
1406
1407 #ifdef USE_NNTP
1408   char *followup_to;
1409 #endif
1410
1411   if (!(flags & M_SHOWCOLOR))
1412     flags |= M_SHOWFLAT;
1413
1414   if ((fp = fopen (fname, "r")) == NULL) {
1415     mutt_perror (fname);
1416     return (-1);
1417   }
1418
1419   if (stat (fname, &sb) != 0) {
1420     mutt_perror (fname);
1421     fclose (fp);
1422     return (-1);
1423   }
1424   unlink (fname);
1425
1426   /* Initialize variables */
1427
1428   if (IsHeader (extra) && !extra->hdr->read) {
1429     Context->msgnotreadyet = extra->hdr->msgno;
1430     mutt_set_flag (Context, extra->hdr, M_READ, 1);
1431   }
1432
1433   lineInfo = safe_malloc (sizeof (struct line_t) * (maxLine = LINES));
1434   for (i = 0; i < maxLine; i++) {
1435     memset (&lineInfo[i], 0, sizeof (struct line_t));
1436     lineInfo[i].type = -1;
1437     lineInfo[i].search_cnt = -1;
1438     lineInfo[i].syntax = safe_malloc (sizeof (struct syntax_t));
1439     (lineInfo[i].syntax)[0].first = (lineInfo[i].syntax)[0].last = -1;
1440   }
1441
1442   mutt_compile_help (helpstr, sizeof (helpstr), MENU_PAGER, PagerHelp);
1443   if (IsHeader (extra)) {
1444     strfcpy (tmphelp, helpstr, sizeof (tmphelp));
1445     mutt_compile_help (buffer, sizeof (buffer), MENU_PAGER,
1446 #ifdef USE_NNTP
1447                        (Context
1448                         && (Context->magic == M_NNTP)) ? PagerNewsHelpExtra :
1449 #endif
1450                        PagerHelpExtra);
1451     snprintf (helpstr, sizeof (helpstr), "%s %s", tmphelp, buffer);
1452   }
1453   if (!InHelp) {
1454     strfcpy (tmphelp, helpstr, sizeof (tmphelp));
1455     mutt_make_help (buffer, sizeof (buffer), _("Help"), MENU_PAGER, OP_HELP);
1456     snprintf (helpstr, sizeof (helpstr), "%s %s", tmphelp, buffer);
1457   }
1458
1459   while (ch != -1) {
1460     mutt_curs_set (0);
1461
1462 #ifdef USE_IMAP
1463     imap_keepalive ();
1464 #endif
1465
1466     if (redraw & REDRAW_FULL) {
1467       SETCOLOR (MT_COLOR_NORMAL);
1468       /* clear() doesn't optimize screen redraws */
1469       move (0, 0);
1470       clrtobot ();
1471
1472       if (IsHeader (extra) && Context->vcount + 1 < PagerIndexLines)
1473         indexlen = Context->vcount + 1;
1474       else
1475         indexlen = PagerIndexLines;
1476
1477       indicator = indexlen / 3;
1478
1479       if (option (OPTSTATUSONTOP)) {
1480         indexoffset = 0;
1481         statusoffset = IsHeader (extra) ? indexlen : 0;
1482         bodyoffset = statusoffset + 1;
1483         helpoffset = LINES - 2;
1484         bodylen = helpoffset - bodyoffset;
1485         if (!option (OPTHELP))
1486           bodylen++;
1487       }
1488       else {
1489         helpoffset = 0;
1490         indexoffset = 1;
1491         statusoffset = LINES - 2;
1492         if (!option (OPTHELP))
1493           indexoffset = 0;
1494         bodyoffset = indexoffset + (IsHeader (extra) ? indexlen : 0);
1495         bodylen = statusoffset - bodyoffset;
1496       }
1497
1498       if (option (OPTHELP)) {
1499         SETCOLOR (MT_COLOR_STATUS);
1500         move (helpoffset, 0);
1501         mutt_paddstr (COLS, helpstr);
1502         SETCOLOR (MT_COLOR_NORMAL);
1503       }
1504
1505 #if defined (USE_SLANG_CURSES) || defined (HAVE_RESIZETERM)
1506       if (Resize != NULL) {
1507         if ((SearchCompiled = Resize->SearchCompiled)) {
1508           REGCOMP
1509             (&SearchRE, searchbuf, REG_NEWLINE | mutt_which_case (searchbuf));
1510           SearchFlag = M_SEARCH;
1511           SearchBack = Resize->SearchBack;
1512         }
1513         lines = Resize->line;
1514         redraw |= REDRAW_SIGWINCH;
1515
1516         FREE (&Resize);
1517       }
1518 #endif
1519
1520       if (IsHeader (extra) && PagerIndexLines) {
1521         if (index == NULL) {
1522           /* only allocate the space if/when we need the index.
1523              Initialise the menu as per the main index */
1524           index = mutt_new_menu ();
1525           index->menu = MENU_MAIN;
1526           index->make_entry = index_make_entry;
1527           index->color = index_color;
1528           index->max = Context->vcount;
1529           index->current = extra->hdr->virtual;
1530         }
1531
1532         SETCOLOR (MT_COLOR_NORMAL);
1533         index->offset = indexoffset + (option (OPTSTATUSONTOP) ? 1 : 0);
1534
1535         index->pagelen = indexlen - 1;
1536
1537         /* some fudge to work out where abouts the indicator should go */
1538         if (index->current - indicator < 0)
1539           index->top = 0;
1540         else if (index->max - index->current < index->pagelen - indicator)
1541           index->top = index->max - index->pagelen;
1542         else
1543           index->top = index->current - indicator;
1544
1545         menu_redraw_index (index);
1546       }
1547
1548       redraw |= REDRAW_BODY | REDRAW_INDEX | REDRAW_STATUS;
1549       mutt_show_error ();
1550     }
1551
1552     if (redraw & REDRAW_SIGWINCH) {
1553       i = -1;
1554       j = -1;
1555       while (display_line (fp, &last_pos, &lineInfo, ++i, &lastLine, &maxLine,
1556                            has_types | SearchFlag, &QuoteList, &q_level,
1557                            &force_redraw, &SearchRE) == 0) {
1558         if (!lineInfo[i].continuation && ++j == lines) {
1559           topline = i;
1560           if (!SearchFlag)
1561             break;
1562         }
1563         redraw |= REDRAW_SIDEBAR;
1564       }                         /* while */
1565     }
1566
1567     if ((redraw & REDRAW_BODY) || topline != oldtopline) {
1568       do {
1569         move (bodyoffset, SidebarWidth);
1570         curline = oldtopline = topline;
1571         lines = 0;
1572         force_redraw = 0;
1573
1574         while (lines < bodylen && lineInfo[curline].offset <= sb.st_size - 1) {
1575           if (display_line (fp, &last_pos, &lineInfo, curline, &lastLine,
1576                             &maxLine,
1577                             (flags & M_DISPLAYFLAGS) | hideQuoted |
1578                             SearchFlag, &QuoteList, &q_level, &force_redraw,
1579                             &SearchRE) > 0)
1580             lines++;
1581           curline++;
1582           move (lines + bodyoffset, SidebarWidth);
1583           redraw |= REDRAW_SIDEBAR;
1584         }
1585         last_offset = lineInfo[curline].offset;
1586       } while (force_redraw);
1587
1588       SETCOLOR (MT_COLOR_TILDE);
1589       BKGDSET (MT_COLOR_TILDE);
1590       while (lines < bodylen) {
1591         clrtoeol ();
1592         if (option (OPTTILDE))
1593           addch ('~');
1594         addch ('\n');
1595         lines++;
1596         move (lines + bodyoffset, SidebarWidth);
1597       }
1598       /* We are going to update the pager status bar, so it isn't
1599        * necessary to reset to normal color now. */
1600
1601       redraw |= REDRAW_STATUS;  /* need to update the % seen */
1602     }
1603
1604     if (redraw & REDRAW_STATUS) {
1605       /* print out the pager status bar */
1606       SETCOLOR (MT_COLOR_STATUS);
1607       BKGDSET (MT_COLOR_STATUS);
1608       CLEARLINE_WIN (statusoffset);
1609       if (IsHeader (extra)) {
1610         size_t l1 = (COLS - 9) * MB_LEN_MAX;
1611         size_t l2 = sizeof (buffer);
1612
1613         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1614                            Context, extra->hdr, M_FORMAT_MAKEPRINT);
1615       }
1616       else if (IsMsgAttach (extra)) {
1617         size_t l1 = (COLS - 9) * MB_LEN_MAX;
1618         size_t l2 = sizeof (buffer);
1619
1620         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1621                            Context, extra->bdy->hdr, M_FORMAT_MAKEPRINT);
1622       }
1623       if (option(OPTSTATUSONTOP)) {
1624         move(0,0);
1625       }
1626       /*move (indexoffset + (option (OPTSTATUSONTOP) ? 0 : (InHelp?(LINES-2):(indexlen - 1))),
1627             option (OPTSTATUSONTOP) ? 0 : SidebarWidth);*/
1628       mutt_paddstr (COLS - 10 - (option(OPTSTATUSONTOP)?0:SidebarWidth), IsHeader (extra)
1629                     || IsMsgAttach (extra) ? buffer : banner);
1630
1631       addstr (" -- (");
1632       if (last_pos < sb.st_size - 1)
1633         printw ("%d%%)", (int) (100 * last_offset / sb.st_size));
1634       else
1635         addstr (topline == 0 ? "all)" : "end)");
1636       BKGDSET (MT_COLOR_NORMAL);
1637       SETCOLOR (MT_COLOR_NORMAL);
1638     }
1639
1640     if (redraw & REDRAW_SIDEBAR)
1641       sidebar_draw (MENU_PAGER);
1642
1643     if ((redraw & REDRAW_INDEX) && index) {
1644       /* redraw the pager_index indicator, because the
1645        * flags for this message might have changed. */
1646       menu_redraw_current (index);
1647       sidebar_draw (MENU_PAGER);
1648       /* print out the index status bar */
1649       menu_status_line (buffer, sizeof (buffer), index, NONULL (Status));
1650       move (indexoffset + (option (OPTSTATUSONTOP) ? 0 : (indexlen - 1)),
1651             option (OPTSTATUSONTOP) ? 0 : SidebarWidth);
1652       SETCOLOR (MT_COLOR_STATUS);
1653       mutt_paddstr (COLS - (option (OPTSTATUSONTOP) ? 0 : SidebarWidth),
1654                     buffer);
1655       SETCOLOR (MT_COLOR_NORMAL);
1656     }
1657     /* if we're not using the index, update every time */
1658     if (index == 0)
1659       sidebar_draw (MENU_PAGER);
1660
1661     redraw = 0;
1662
1663     move (statusoffset, COLS - 1);
1664     mutt_refresh ();
1665     ch = km_dokey (MENU_PAGER);
1666     if (ch != -1)
1667       mutt_clear_error ();
1668     mutt_curs_set (1);
1669
1670     if (SigInt) {
1671       mutt_query_exit ();
1672       continue;
1673     }
1674 #if defined (USE_SLANG_CURSES) || defined (HAVE_RESIZETERM)
1675     else if (SigWinch) {
1676       mutt_resize_screen ();
1677
1678       /* Store current position. */
1679       lines = -1;
1680       for (i = 0; i <= topline; i++)
1681         if (!lineInfo[i].continuation)
1682           lines++;
1683
1684       if (flags & M_PAGER_RETWINCH) {
1685         Resize = safe_malloc (sizeof (struct resize));
1686
1687         Resize->line = lines;
1688         Resize->SearchCompiled = SearchCompiled;
1689         Resize->SearchBack = SearchBack;
1690
1691         ch = -1;
1692         rc = OP_REFORMAT_WINCH;
1693       }
1694       else {
1695         for (i = 0; i < maxLine; i++) {
1696           lineInfo[i].offset = 0;
1697           lineInfo[i].type = -1;
1698           lineInfo[i].continuation = 0;
1699           lineInfo[i].chunks = 0;
1700           lineInfo[i].search_cnt = -1;
1701           lineInfo[i].quote = NULL;
1702
1703           safe_realloc (&(lineInfo[i].syntax), sizeof (struct syntax_t));
1704           if (SearchCompiled && lineInfo[i].search)
1705             FREE (&(lineInfo[i].search));
1706         }
1707
1708         lastLine = 0;
1709         topline = 0;
1710
1711         redraw = REDRAW_FULL | REDRAW_SIGWINCH;
1712         ch = 0;
1713       }
1714
1715       SigWinch = 0;
1716       clearok (stdscr, TRUE);   /*force complete redraw */
1717       continue;
1718     }
1719 #endif
1720     else if (ch == -1) {
1721       ch = 0;
1722       continue;
1723     }
1724
1725     rc = ch;
1726
1727     switch (ch) {
1728     case OP_EXIT:
1729       rc = -1;
1730       ch = -1;
1731       break;
1732
1733     case OP_NEXT_PAGE:
1734       if (lineInfo[curline].offset < sb.st_size - 1) {
1735         topline = upNLines (PagerContext, lineInfo, curline, hideQuoted);
1736       }
1737       else if (option (OPTPAGERSTOP)) {
1738         /* emulate "less -q" and don't go on to the next message. */
1739         mutt_error _("Bottom of message is shown.");
1740       }
1741       else {
1742         /* end of the current message, so display the next message. */
1743         rc = OP_MAIN_NEXT_UNDELETED;
1744         ch = -1;
1745       }
1746       break;
1747
1748     case OP_PREV_PAGE:
1749       if (topline != 0) {
1750         topline =
1751           upNLines (bodylen - PagerContext, lineInfo, topline, hideQuoted);
1752       }
1753       else
1754         mutt_error _("Top of message is shown.");
1755       break;
1756
1757     case OP_NEXT_LINE:
1758       if (lineInfo[curline].offset < sb.st_size - 1) {
1759         topline++;
1760         if (hideQuoted) {
1761           while (lineInfo[topline].type == MT_COLOR_QUOTED &&
1762                  topline < lastLine)
1763             topline++;
1764         }
1765       }
1766       else
1767         mutt_error _("Bottom of message is shown.");
1768       break;
1769
1770     case OP_PREV_LINE:
1771       if (topline)
1772         topline = upNLines (1, lineInfo, topline, hideQuoted);
1773       else
1774         mutt_error _("Top of message is shown.");
1775       break;
1776
1777     case OP_PAGER_TOP:
1778       if (topline)
1779         topline = 0;
1780       else
1781         mutt_error _("Top of message is shown.");
1782       break;
1783
1784     case OP_HALF_UP:
1785       if (topline)
1786         topline = upNLines (bodylen / 2, lineInfo, topline, hideQuoted);
1787       else
1788         mutt_error _("Top of message is shown.");
1789       break;
1790
1791     case OP_HALF_DOWN:
1792       if (lineInfo[curline].offset < sb.st_size - 1) {
1793         topline = upNLines (bodylen / 2, lineInfo, curline, hideQuoted);
1794       }
1795       else if (option (OPTPAGERSTOP)) {
1796         /* emulate "less -q" and don't go on to the next message. */
1797         mutt_error _("Bottom of message is shown.");
1798       }
1799       else {
1800         /* end of the current message, so display the next message. */
1801         rc = OP_MAIN_NEXT_UNDELETED;
1802         ch = -1;
1803       }
1804       break;
1805
1806     case OP_SEARCH_NEXT:
1807     case OP_SEARCH_OPPOSITE:
1808       if (SearchCompiled) {
1809       search_next:
1810         if ((!SearchBack && ch == OP_SEARCH_NEXT) ||
1811             (SearchBack && ch == OP_SEARCH_OPPOSITE)) {
1812           /* searching forward */
1813           for (i = topline + 1; i < lastLine; i++) {
1814             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1815                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1816               break;
1817           }
1818
1819           if (i < lastLine)
1820             topline = i;
1821           else
1822             mutt_error _("Not found.");
1823         }
1824         else {
1825           /* searching backward */
1826           for (i = topline - 1; i >= 0; i--) {
1827             if ((!hideQuoted || (has_types &&
1828                                  lineInfo[i].type != MT_COLOR_QUOTED)) &&
1829                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1830               break;
1831           }
1832
1833           if (i >= 0)
1834             topline = i;
1835           else
1836             mutt_error _("Not found.");
1837         }
1838
1839         if (lineInfo[topline].search_cnt > 0)
1840           SearchFlag = M_SEARCH;
1841
1842         break;
1843       }
1844       /* no previous search pattern, so fall through to search */
1845
1846     case OP_SEARCH:
1847     case OP_SEARCH_REVERSE:
1848       strfcpy (buffer, searchbuf, sizeof (buffer));
1849       if (mutt_get_field ((SearchBack ? _("Reverse search: ") :
1850                            _("Search: ")), buffer, sizeof (buffer),
1851                           M_CLEAR) != 0)
1852         break;
1853
1854       if (!strcmp (buffer, searchbuf)) {
1855         if (SearchCompiled) {
1856           /* do an implicit search-next */
1857           if (ch == OP_SEARCH)
1858             ch = OP_SEARCH_NEXT;
1859           else
1860             ch = OP_SEARCH_OPPOSITE;
1861
1862           goto search_next;
1863         }
1864       }
1865
1866       if (!buffer[0])
1867         break;
1868
1869       strfcpy (searchbuf, buffer, sizeof (searchbuf));
1870
1871       /* leave SearchBack alone if ch == OP_SEARCH_NEXT */
1872       if (ch == OP_SEARCH)
1873         SearchBack = 0;
1874       else if (ch == OP_SEARCH_REVERSE)
1875         SearchBack = 1;
1876
1877       if (SearchCompiled) {
1878         regfree (&SearchRE);
1879         for (i = 0; i < lastLine; i++) {
1880           if (lineInfo[i].search)
1881             FREE (&(lineInfo[i].search));
1882           lineInfo[i].search_cnt = -1;
1883         }
1884       }
1885
1886       if ((err =
1887            REGCOMP (&SearchRE, searchbuf,
1888                     REG_NEWLINE | mutt_which_case (searchbuf))) != 0) {
1889         regerror (err, &SearchRE, buffer, sizeof (buffer));
1890         mutt_error ("%s", buffer);
1891         regfree (&SearchRE);
1892         for (i = 0; i < maxLine; i++) {
1893           /* cleanup */
1894           if (lineInfo[i].search)
1895             FREE (&(lineInfo[i].search));
1896           lineInfo[i].search_cnt = -1;
1897         }
1898         SearchFlag = 0;
1899         SearchCompiled = 0;
1900       }
1901       else {
1902         SearchCompiled = 1;
1903         /* update the search pointers */
1904         i = 0;
1905         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
1906                              &maxLine, M_SEARCH | (flags & M_PAGER_NSKIP),
1907                              &QuoteList, &q_level,
1908                              &force_redraw, &SearchRE) == 0) {
1909           i++;
1910           redraw |= REDRAW_SIDEBAR;
1911         }
1912
1913         if (!SearchBack) {
1914           /* searching forward */
1915           for (i = topline; i < lastLine; i++) {
1916             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1917                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1918               break;
1919           }
1920
1921           if (i < lastLine)
1922             topline = i;
1923         }
1924         else {
1925           /* searching backward */
1926           for (i = topline; i >= 0; i--) {
1927             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1928                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1929               break;
1930           }
1931
1932           if (i >= 0)
1933             topline = i;
1934         }
1935
1936         if (lineInfo[topline].search_cnt == 0) {
1937           SearchFlag = 0;
1938           mutt_error _("Not found.");
1939         }
1940         else
1941           SearchFlag = M_SEARCH;
1942       }
1943       redraw = REDRAW_BODY;
1944       break;
1945
1946     case OP_SEARCH_TOGGLE:
1947       if (SearchCompiled) {
1948         SearchFlag ^= M_SEARCH;
1949         redraw = REDRAW_BODY;
1950       }
1951       break;
1952
1953     case OP_HELP:
1954       /* don't let the user enter the help-menu from the help screen! */
1955       if (!InHelp) {
1956         InHelp = 1;
1957         mutt_help (MENU_PAGER);
1958         redraw = REDRAW_FULL;
1959         InHelp = 0;
1960       }
1961       else
1962         mutt_error _("Help is currently being shown.");
1963       break;
1964
1965     case OP_PAGER_HIDE_QUOTED:
1966       if (has_types) {
1967         hideQuoted ^= M_HIDE;
1968         if (hideQuoted && lineInfo[topline].type == MT_COLOR_QUOTED)
1969           topline = upNLines (1, lineInfo, topline, hideQuoted);
1970         else
1971           redraw = REDRAW_BODY;
1972       }
1973       break;
1974
1975     case OP_PAGER_SKIP_QUOTED:
1976       if (has_types) {
1977         int dretval = 0;
1978         int new_topline = topline;
1979
1980         while ((new_topline < lastLine ||
1981                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
1982                                                new_topline, &lastLine,
1983                                                &maxLine, M_TYPES, &QuoteList,
1984                                                &q_level, &force_redraw,
1985                                                &SearchRE))))
1986                && lineInfo[new_topline].type != MT_COLOR_QUOTED) {
1987           redraw |= REDRAW_SIDEBAR;
1988           new_topline++;
1989         }
1990
1991         if (dretval < 0) {
1992           mutt_error _("No more quoted text.");
1993
1994           break;
1995         }
1996
1997         while ((new_topline < lastLine ||
1998                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
1999                                                new_topline, &lastLine,
2000                                                &maxLine, M_TYPES, &QuoteList,
2001                                                &q_level, &force_redraw,
2002                                                &SearchRE))))
2003                && lineInfo[new_topline].type == MT_COLOR_QUOTED) {
2004           new_topline++;
2005           redraw |= REDRAW_SIDEBAR;
2006         }
2007
2008         if (dretval < 0) {
2009           mutt_error _("No more unquoted text after quoted text.");
2010
2011           break;
2012         }
2013         topline = new_topline;
2014       }
2015       break;
2016
2017     case OP_PAGER_BOTTOM:      /* move to the end of the file */
2018       if (lineInfo[curline].offset < sb.st_size - 1) {
2019         i = curline;
2020         /* make sure the types are defined to the end of file */
2021         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
2022                              &maxLine, has_types,
2023                              &QuoteList, &q_level, &force_redraw,
2024                              &SearchRE) == 0) {
2025           i++;
2026           redraw |= REDRAW_SIDEBAR;
2027         }
2028         topline = upNLines (bodylen, lineInfo, lastLine, hideQuoted);
2029       }
2030       else
2031         mutt_error _("Bottom of message is shown.");
2032       break;
2033
2034     case OP_REDRAW:
2035       clearok (stdscr, TRUE);
2036       redraw = REDRAW_FULL;
2037       break;
2038
2039     case OP_NULL:
2040       km_error_key (MENU_PAGER);
2041       break;
2042
2043       /* --------------------------------------------------------------------
2044        * The following are operations on the current message rather than
2045        * adjusting the view of the message.
2046        */
2047
2048     case OP_BOUNCE_MESSAGE:
2049       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
2050         CHECK_ATTACH;
2051       if (IsMsgAttach (extra))
2052         mutt_attach_bounce (extra->fp, extra->hdr,
2053                             extra->idx, extra->idxlen, extra->bdy);
2054       else
2055         ci_bounce_message (extra->hdr, &redraw);
2056       break;
2057
2058     case OP_RESEND:
2059       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
2060         CHECK_ATTACH;
2061       if (IsMsgAttach (extra))
2062         mutt_attach_resend (extra->fp, extra->hdr,
2063                             extra->idx, extra->idxlen, extra->bdy);
2064       else
2065         mutt_resend_message (NULL, extra->ctx, extra->hdr);
2066       redraw = REDRAW_FULL;
2067       break;
2068
2069     case OP_CHECK_TRADITIONAL:
2070       CHECK_MODE (IsHeader (extra));
2071       if (!(WithCrypto & APPLICATION_PGP))
2072         break;
2073       if (!(extra->hdr->security & PGP_TRADITIONAL_CHECKED)) {
2074         ch = -1;
2075         rc = OP_CHECK_TRADITIONAL;
2076       }
2077       break;
2078
2079     case OP_CREATE_ALIAS:
2080       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2081       if (IsMsgAttach (extra))
2082         mutt_create_alias (extra->bdy->hdr->env, NULL);
2083       else
2084         mutt_create_alias (extra->hdr->env, NULL);
2085       MAYBE_REDRAW (redraw);
2086       break;
2087
2088     case OP_PURGE_MESSAGE:
2089     case OP_DELETE:
2090       CHECK_MODE (IsHeader (extra));
2091       CHECK_READONLY;
2092
2093       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
2094
2095       mutt_set_flag (Context, extra->hdr, M_DELETE, 1);
2096       mutt_set_flag (Context, extra->hdr, M_PURGED,
2097                      ch != OP_PURGE_MESSAGE ? 0 : 1);
2098       if (option (OPTDELETEUNTAG))
2099         mutt_set_flag (Context, extra->hdr, M_TAG, 0);
2100       redraw = REDRAW_STATUS | REDRAW_INDEX;
2101       if (option (OPTRESOLVE)) {
2102         ch = -1;
2103         rc = OP_MAIN_NEXT_UNDELETED;
2104       }
2105       break;
2106
2107     case OP_DELETE_THREAD:
2108     case OP_DELETE_SUBTHREAD:
2109       CHECK_MODE (IsHeader (extra));
2110       CHECK_READONLY;
2111
2112       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
2113
2114       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 1,
2115                                 ch == OP_DELETE_THREAD ? 0 : 1);
2116
2117       if (r != -1) {
2118         if (option (OPTDELETEUNTAG))
2119           mutt_thread_set_flag (extra->hdr, M_TAG, 0,
2120                                 ch == OP_DELETE_THREAD ? 0 : 1);
2121         if (option (OPTRESOLVE)) {
2122           rc = OP_MAIN_NEXT_UNDELETED;
2123           ch = -1;
2124         }
2125
2126         if (!option (OPTRESOLVE) && PagerIndexLines)
2127           redraw = REDRAW_FULL;
2128         else
2129           redraw = REDRAW_STATUS | REDRAW_INDEX;
2130       }
2131       break;
2132
2133     case OP_DISPLAY_ADDRESS:
2134       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2135       if (IsMsgAttach (extra))
2136         mutt_display_address (extra->bdy->hdr->env);
2137       else
2138         mutt_display_address (extra->hdr->env);
2139       break;
2140
2141     case OP_ENTER_COMMAND:
2142       old_smart_wrap = option (OPTWRAP);
2143       old_markers = option (OPTMARKERS);
2144       old_PagerIndexLines = PagerIndexLines;
2145
2146       CurrentMenu = MENU_PAGER;
2147       mutt_enter_command ();
2148
2149       if (option (OPTNEEDRESORT)) {
2150         unset_option (OPTNEEDRESORT);
2151         CHECK_MODE (IsHeader (extra));
2152         set_option (OPTNEEDRESORT);
2153       }
2154
2155       if (old_PagerIndexLines != PagerIndexLines) {
2156         if (index)
2157           mutt_menuDestroy (&index);
2158         index = NULL;
2159       }
2160
2161       if (option (OPTWRAP) != old_smart_wrap ||
2162           option (OPTMARKERS) != old_markers) {
2163         if (flags & M_PAGER_RETWINCH) {
2164           ch = -1;
2165           rc = OP_REFORMAT_WINCH;
2166           continue;
2167         }
2168
2169         /* count the real lines above */
2170         j = 0;
2171         for (i = 0; i <= topline; i++) {
2172           if (!lineInfo[i].continuation)
2173             j++;
2174         }
2175
2176         /* we need to restart the whole thing */
2177         for (i = 0; i < maxLine; i++) {
2178           lineInfo[i].offset = 0;
2179           lineInfo[i].type = -1;
2180           lineInfo[i].continuation = 0;
2181           lineInfo[i].chunks = 0;
2182           lineInfo[i].search_cnt = -1;
2183           lineInfo[i].quote = NULL;
2184
2185           safe_realloc (&(lineInfo[i].syntax), sizeof (struct syntax_t));
2186           if (SearchCompiled && lineInfo[i].search)
2187             FREE (&(lineInfo[i].search));
2188         }
2189
2190         if (SearchCompiled) {
2191           regfree (&SearchRE);
2192           SearchCompiled = 0;
2193         }
2194         SearchFlag = 0;
2195
2196         /* try to keep the old position */
2197         topline = 0;
2198         lastLine = 0;
2199         while (j > 0 && display_line (fp, &last_pos, &lineInfo, topline,
2200                                       &lastLine, &maxLine,
2201                                       (has_types ? M_TYPES : 0),
2202                                       &QuoteList, &q_level, &force_redraw,
2203                                       &SearchRE) == 0) {
2204           redraw |= REDRAW_SIDEBAR;
2205           if (!lineInfo[topline].continuation)
2206             j--;
2207           if (j > 0)
2208             topline++;
2209         }
2210
2211         ch = 0;
2212       }
2213
2214       if (option (OPTFORCEREDRAWPAGER))
2215         redraw = REDRAW_FULL;
2216       unset_option (OPTFORCEREDRAWINDEX);
2217       unset_option (OPTFORCEREDRAWPAGER);
2218       break;
2219
2220     case OP_FLAG_MESSAGE:
2221       CHECK_MODE (IsHeader (extra));
2222       CHECK_READONLY;
2223
2224       CHECK_MX_ACL (Context, ACL_WRITE, _("Flagging"));
2225
2226       mutt_set_flag (Context, extra->hdr, M_FLAG, !extra->hdr->flagged);
2227       redraw = REDRAW_STATUS | REDRAW_INDEX;
2228       if (option (OPTRESOLVE)) {
2229         ch = -1;
2230         rc = OP_MAIN_NEXT_UNDELETED;
2231       }
2232       break;
2233
2234     case OP_PIPE:
2235       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2236       if (IsAttach (extra))
2237         mutt_pipe_attachment_list (extra->fp, 0, extra->bdy, 0);
2238       else
2239         mutt_pipe_message (extra->hdr);
2240       MAYBE_REDRAW (redraw);
2241       break;
2242
2243     case OP_PRINT:
2244       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2245       if (IsAttach (extra))
2246         mutt_print_attachment_list (extra->fp, 0, extra->bdy);
2247       else
2248         mutt_print_message (extra->hdr);
2249       break;
2250
2251     case OP_MAIL:
2252       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2253       CHECK_ATTACH;
2254       ci_send_message (0, NULL, NULL, extra->ctx, NULL);
2255       redraw = REDRAW_FULL;
2256       break;
2257
2258 #ifdef USE_NNTP
2259     case OP_POST:
2260       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2261       CHECK_ATTACH;
2262       if (extra->ctx && extra->ctx->magic == M_NNTP &&
2263           !((NNTP_DATA *) extra->ctx->data)->allowed &&
2264           query_quadoption (OPT_TOMODERATED,
2265                             _
2266                             ("Posting to this group not allowed, may be moderated. Continue?"))
2267           != M_YES)
2268         break;
2269       ci_send_message (SENDNEWS, NULL, NULL, extra->ctx, NULL);
2270       redraw = REDRAW_FULL;
2271       break;
2272
2273     case OP_FORWARD_TO_GROUP:
2274       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2275       CHECK_ATTACH;
2276       if (extra->ctx && extra->ctx->magic == M_NNTP &&
2277           !((NNTP_DATA *) extra->ctx->data)->allowed &&
2278           query_quadoption (OPT_TOMODERATED,
2279                             _
2280                             ("Posting to this group not allowed, may be moderated. Continue?"))
2281           != M_YES)
2282         break;
2283       if (IsMsgAttach (extra))
2284         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2285                              extra->idxlen, extra->bdy, SENDNEWS);
2286       else
2287         ci_send_message (SENDNEWS | SENDFORWARD, NULL, NULL, extra->ctx,
2288                          extra->hdr);
2289       redraw = REDRAW_FULL;
2290       break;
2291
2292     case OP_FOLLOWUP:
2293       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2294       CHECK_ATTACH;
2295
2296       if (IsMsgAttach (extra))
2297         followup_to = extra->bdy->hdr->env->followup_to;
2298       else
2299         followup_to = extra->hdr->env->followup_to;
2300
2301       if (!followup_to || safe_strcasecmp (followup_to, "poster") ||
2302           query_quadoption (OPT_FOLLOWUPTOPOSTER,
2303                             _("Reply by mail as poster prefers?")) != M_YES) {
2304         if (extra->ctx && extra->ctx->magic == M_NNTP
2305             && !((NNTP_DATA *) extra->ctx->data)->allowed
2306             && query_quadoption (OPT_TOMODERATED,
2307                                  _
2308                                  ("Posting to this group not allowed, may be moderated. Continue?"))
2309             != M_YES)
2310           break;
2311         if (IsMsgAttach (extra))
2312           mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2313                              extra->idxlen, extra->bdy, SENDNEWS | SENDREPLY);
2314         else
2315           ci_send_message (SENDNEWS | SENDREPLY, NULL, NULL,
2316                            extra->ctx, extra->hdr);
2317         redraw = REDRAW_FULL;
2318         break;
2319       }
2320 #endif
2321
2322     case OP_REPLY:
2323       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2324       CHECK_ATTACH;
2325       if (IsMsgAttach (extra))
2326         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2327                            extra->idxlen, extra->bdy, SENDREPLY);
2328       else
2329         ci_send_message (SENDREPLY, NULL, NULL, extra->ctx, extra->hdr);
2330       redraw = REDRAW_FULL;
2331       break;
2332
2333     case OP_RECALL_MESSAGE:
2334       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2335       CHECK_ATTACH;
2336       ci_send_message (SENDPOSTPONED, NULL, NULL, extra->ctx, extra->hdr);
2337       redraw = REDRAW_FULL;
2338       break;
2339
2340     case OP_GROUP_REPLY:
2341       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2342       CHECK_ATTACH;
2343       if (IsMsgAttach (extra))
2344         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2345                            extra->idxlen, extra->bdy,
2346                            SENDREPLY | SENDGROUPREPLY);
2347       else
2348         ci_send_message (SENDREPLY | SENDGROUPREPLY, NULL, NULL, extra->ctx,
2349                          extra->hdr);
2350       redraw = REDRAW_FULL;
2351       break;
2352
2353     case OP_LIST_REPLY:
2354       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2355       CHECK_ATTACH;
2356       if (IsMsgAttach (extra))
2357         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2358                            extra->idxlen, extra->bdy,
2359                            SENDREPLY | SENDLISTREPLY);
2360       else
2361         ci_send_message (SENDREPLY | SENDLISTREPLY, NULL, NULL, extra->ctx,
2362                          extra->hdr);
2363       redraw = REDRAW_FULL;
2364       break;
2365
2366     case OP_FORWARD_MESSAGE:
2367       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2368       CHECK_ATTACH;
2369       if (IsMsgAttach (extra))
2370         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2371                              extra->idxlen, extra->bdy, 0);
2372       else
2373         ci_send_message (SENDFORWARD, NULL, NULL, extra->ctx, extra->hdr);
2374       redraw = REDRAW_FULL;
2375       break;
2376
2377     case OP_DECRYPT_SAVE:
2378       if (!WithCrypto) {
2379         ch = -1;
2380         break;
2381       }
2382       /* fall through */
2383     case OP_SAVE:
2384       if (IsAttach (extra)) {
2385         mutt_save_attachment_list (extra->fp, 0, extra->bdy, extra->hdr,
2386                                    NULL);
2387         break;
2388       }
2389       /* fall through */
2390     case OP_COPY_MESSAGE:
2391     case OP_DECODE_SAVE:
2392     case OP_DECODE_COPY:
2393     case OP_DECRYPT_COPY:
2394       if (!WithCrypto && ch == OP_DECRYPT_COPY) {
2395         ch = -1;
2396         break;
2397       }
2398       CHECK_MODE (IsHeader (extra));
2399       if (mutt_save_message (extra->hdr,
2400                              (ch == OP_DECRYPT_SAVE) ||
2401                              (ch == OP_SAVE) || (ch == OP_DECODE_SAVE),
2402                              (ch == OP_DECODE_SAVE) || (ch == OP_DECODE_COPY),
2403                              (ch == OP_DECRYPT_SAVE)
2404                              || (ch == OP_DECRYPT_COPY) || 0, &redraw) == 0
2405           && (ch == OP_SAVE || ch == OP_DECODE_SAVE
2406               || ch == OP_DECRYPT_SAVE)) {
2407         if (option (OPTRESOLVE)) {
2408           ch = -1;
2409           rc = OP_MAIN_NEXT_UNDELETED;
2410         }
2411         else
2412           redraw |= REDRAW_STATUS | REDRAW_INDEX;
2413       }
2414       MAYBE_REDRAW (redraw);
2415       break;
2416
2417     case OP_SHELL_ESCAPE:
2418       mutt_shell_escape ();
2419       MAYBE_REDRAW (redraw);
2420       break;
2421
2422     case OP_TAG:
2423       CHECK_MODE (IsHeader (extra));
2424       mutt_set_flag (Context, extra->hdr, M_TAG, !extra->hdr->tagged);
2425
2426       Context->last_tag = extra->hdr->tagged ? extra->hdr :
2427         ((Context->last_tag == extra->hdr && !extra->hdr->tagged)
2428          ? NULL : Context->last_tag);
2429
2430       redraw = REDRAW_STATUS | REDRAW_INDEX;
2431       if (option (OPTRESOLVE)) {
2432         ch = -1;
2433         rc = OP_NEXT_ENTRY;
2434       }
2435       break;
2436
2437     case OP_TOGGLE_NEW:
2438       CHECK_MODE (IsHeader (extra));
2439       CHECK_READONLY;
2440
2441       CHECK_MX_ACL (Context, ACL_SEEN, _("Toggling"));
2442
2443       if (extra->hdr->read || extra->hdr->old)
2444         mutt_set_flag (Context, extra->hdr, M_NEW, 1);
2445       else if (!first)
2446         mutt_set_flag (Context, extra->hdr, M_READ, 1);
2447       first = 0;
2448       Context->msgnotreadyet = -1;
2449       redraw = REDRAW_STATUS | REDRAW_INDEX;
2450       if (option (OPTRESOLVE)) {
2451         ch = -1;
2452         rc = OP_MAIN_NEXT_UNDELETED;
2453       }
2454       break;
2455
2456     case OP_UNDELETE:
2457       CHECK_MODE (IsHeader (extra));
2458       CHECK_READONLY;
2459
2460       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2461
2462       mutt_set_flag (Context, extra->hdr, M_DELETE, 0);
2463       mutt_set_flag (Context, extra->hdr, M_PURGED, 0);
2464       redraw = REDRAW_STATUS | REDRAW_INDEX;
2465       if (option (OPTRESOLVE)) {
2466         ch = -1;
2467         rc = OP_NEXT_ENTRY;
2468       }
2469       break;
2470
2471     case OP_UNDELETE_THREAD:
2472     case OP_UNDELETE_SUBTHREAD:
2473       CHECK_MODE (IsHeader (extra));
2474       CHECK_READONLY;
2475
2476       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2477
2478       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 0,
2479                                 ch == OP_UNDELETE_THREAD ? 0 : 1)
2480         + mutt_thread_set_flag (extra->hdr, M_PURGED, 0,
2481                                 ch == OP_UNDELETE_THREAD ? 0 : 1);
2482
2483       if (r > -1) {
2484         if (option (OPTRESOLVE)) {
2485           rc = (ch == OP_DELETE_THREAD) ?
2486             OP_MAIN_NEXT_THREAD : OP_MAIN_NEXT_SUBTHREAD;
2487           ch = -1;
2488         }
2489
2490         if (!option (OPTRESOLVE) && PagerIndexLines)
2491           redraw = REDRAW_FULL;
2492         else
2493           redraw = REDRAW_STATUS | REDRAW_INDEX;
2494       }
2495       break;
2496
2497     case OP_VERSION:
2498       mutt_version ();
2499       break;
2500
2501     case OP_BUFFY_LIST:
2502       buffy_list ();
2503       redraw |= REDRAW_SIDEBAR;
2504       break;
2505
2506     case OP_VIEW_ATTACHMENTS:
2507       if (flags & M_PAGER_ATTACHMENT) {
2508         ch = -1;
2509         rc = OP_ATTACH_COLLAPSE;
2510         break;
2511       }
2512       CHECK_MODE (IsHeader (extra));
2513       mutt_view_attachments (extra->hdr);
2514       if (extra->hdr->attach_del)
2515         Context->changed = 1;
2516       redraw = REDRAW_FULL;
2517       break;
2518
2519
2520     case OP_MAIL_KEY:
2521       if (!(WithCrypto & APPLICATION_PGP)) {
2522         ch = -1;
2523         break;
2524       }
2525       CHECK_MODE (IsHeader (extra));
2526       CHECK_ATTACH;
2527       ci_send_message (SENDKEY, NULL, NULL, extra->ctx, extra->hdr);
2528       redraw = REDRAW_FULL;
2529       break;
2530
2531
2532     case OP_FORGET_PASSPHRASE:
2533       crypt_forget_passphrase ();
2534       break;
2535
2536     case OP_EXTRACT_KEYS:
2537       if (!WithCrypto) {
2538         ch = -1;
2539         break;
2540       }
2541       CHECK_MODE (IsHeader (extra));
2542       crypt_extract_keys_from_messages (extra->hdr);
2543       redraw = REDRAW_FULL;
2544       break;
2545
2546     case OP_SIDEBAR_SCROLL_UP:
2547     case OP_SIDEBAR_SCROLL_DOWN:
2548     case OP_SIDEBAR_NEXT:
2549     case OP_SIDEBAR_NEXT_NEW:
2550     case OP_SIDEBAR_PREV:
2551     case OP_SIDEBAR_PREV_NEW:
2552       sidebar_scroll (ch, MENU_PAGER);
2553       break;
2554     default:
2555       ch = -1;
2556       break;
2557     }
2558   }
2559
2560   fclose (fp);
2561   if (IsHeader (extra))
2562     Context->msgnotreadyet = -1;
2563
2564   cleanup_quote (&QuoteList);
2565
2566   for (i = 0; i < maxLine; i++) {
2567     FREE (&(lineInfo[i].syntax));
2568     if (SearchCompiled && lineInfo[i].search)
2569       FREE (&(lineInfo[i].search));
2570   }
2571   if (SearchCompiled) {
2572     regfree (&SearchRE);
2573     SearchCompiled = 0;
2574   }
2575   FREE (&lineInfo);
2576   if (index)
2577     mutt_menuDestroy (&index);
2578   return (rc != -1 ? rc : 0);
2579 }