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