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