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