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