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