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