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