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