drop mem_alloc and mem_free, use my own hand crafted optmized macros that
[apps/madmutt.git] / pager.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
4  *
5  * Parts were written/modified by:
6  * Nico Golde <nico@ngolde.de>
7  * Andreas Krennmair <ak@synflood.at>
8  *
9  * This file is part of mutt-ng, see http://www.muttng.org/.
10  * It's licensed under the GNU General Public License,
11  * please see the file GPL in the top level source directory.
12  */
13
14 #if HAVE_CONFIG_H
15 # include "config.h"
16 #endif
17
18 #include <lib-lib/mem.h>
19
20 #include "mutt.h"
21 #include "enter.h"
22 #include "mutt_curses.h"
23 #include "keymap.h"
24 #include "mutt_menu.h"
25 #include "mapping.h"
26 #include "sort.h"
27 #include "pager.h"
28 #include "attach.h"
29 #include "recvattach.h"
30 #include "mbyte.h"
31 #include "sidebar.h"
32 #include "buffy.h"
33
34 #include "mx.h"
35
36 #ifdef USE_IMAP
37 #include "imap_private.h"
38 #endif
39
40 #include "mutt_crypt.h"
41
42 #include "lib/mem.h"
43 #include "lib/intl.h"
44 #include "lib/str.h"
45 #include "lib/rx.h"
46 #include "lib/debug.h"
47
48 #include <wchar.h>
49 #include <sys/stat.h>
50 #include <ctype.h>
51 #include <unistd.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <errno.h>
55
56 #define ISHEADER(x) ((x) == MT_COLOR_HEADER || (x) == MT_COLOR_HDEFAULT)
57
58 #define IsAttach(x) (x && (x)->bdy)
59 #define IsRecvAttach(x) (x && (x)->bdy && (x)->fp)
60 #define IsSendAttach(x) (x && (x)->bdy && !(x)->fp)
61 #define IsMsgAttach(x) (x && (x)->fp && (x)->bdy && (x)->bdy->hdr)
62 #define IsHeader(x) (x && (x)->hdr && !(x)->bdy)
63 #define SW              (option(OPTMBOXPANE)?SidebarWidth:0)
64
65 static const char *Not_available_in_this_menu =
66 N_("Not available in this menu.");
67 static const char *Mailbox_is_read_only = N_("Mailbox is read-only.");
68 static const char *Function_not_permitted_in_attach_message_mode =
69 N_("Function not permitted in attach-message mode.");
70
71 /* hack to return to position when returning from index to same message */
72 static int TopLine = 0;
73 static HEADER *OldHdr = NULL;
74
75 #define CHECK_MODE(x)   if (!(x)) \
76                         { \
77                                 mutt_flushinp (); \
78                                 mutt_error _(Not_available_in_this_menu); \
79                                 break; \
80                         }
81
82 #define CHECK_READONLY  if (Context->readonly) \
83                         { \
84                                 mutt_flushinp (); \
85                                 mutt_error _(Mailbox_is_read_only);     \
86                                 break; \
87                         }
88
89 #define CHECK_ATTACH if(option(OPTATTACHMSG)) \
90                      {\
91                         mutt_flushinp (); \
92                         mutt_error _(Function_not_permitted_in_attach_message_mode); \
93                         break; \
94                      }
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   off_t 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       p_delete(&(*QuoteList)->prefix);
359     p_delete(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 *) mem_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 (str_ncmp (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 *) mem_calloc (1, sizeof (struct q_class_t));
403           tmp->prefix = (char *) mem_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           && str_ncmp (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 (str_ncmp (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 *) mem_calloc (1,
505                                                         sizeof (struct
506                                                                 q_class_t));
507                 tmp->prefix = (char *) mem_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                 && str_ncmp (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 *) mem_calloc (1, sizeof (struct q_class_t));
603           tmp->prefix = (char *) mem_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 *) mem_calloc (1, sizeof (struct q_class_t));
636     class->prefix = (char *) mem_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 brailleLine = -1;
655 static int brailleCol = -1;
656
657 static int check_attachment_marker (char *);
658
659 static void
660 resolve_types (char *buf, char *raw, struct line_t *lineInfo, int n, int last,
661                struct q_class_t **QuoteList, int *q_level, int *force_redraw,
662                int q_classify)
663 {
664   COLOR_LINE *color_line;
665   regmatch_t pmatch[1], smatch[1];
666   int found, offset, null_rx, i;
667
668   if (n == 0 || ISHEADER (lineInfo[n - 1].type)) {
669     if (buf[0] == '\n') {
670       lineInfo[n].type = MT_COLOR_NORMAL;
671       getyx(stdscr, brailleLine, brailleCol);
672     }
673     else if (n > 0 && (buf[0] == ' ' || buf[0] == '\t')) {
674       lineInfo[n].type = lineInfo[n - 1].type;  /* wrapped line */
675       (lineInfo[n].syntax)[0].color = (lineInfo[n - 1].syntax)[0].color;
676     }
677     else {
678       lineInfo[n].type = MT_COLOR_HDEFAULT;
679       color_line = ColorHdrList;
680       while (color_line) {
681         if (REGEXEC (&color_line->rx, buf) == 0) {
682           lineInfo[n].type = MT_COLOR_HEADER;
683           lineInfo[n].syntax[0].color = color_line->pair;
684           break;
685         }
686         color_line = color_line->next;
687       }
688     }
689   }
690   else if (str_ncmp ("\033[0m", raw, 4) == 0)       /* a little hack... */
691     lineInfo[n].type = MT_COLOR_NORMAL;
692 #if 0
693   else if (str_ncmp ("[-- ", buf, 4) == 0)
694     lineInfo[n].type = MT_COLOR_ATTACHMENT;
695 #else
696   else if (check_attachment_marker ((char *) raw) == 0)
697     lineInfo[n].type = MT_COLOR_ATTACHMENT;
698 #endif
699   else if (str_cmp ("-- \n", buf) == 0
700            || str_cmp ("-- \r\n", buf) == 0) {
701     i = n + 1;
702
703     lineInfo[n].type = MT_COLOR_SIGNATURE;
704     while (i < last && check_sig (buf, lineInfo, i - 1) == 0 &&
705            (lineInfo[i].type == MT_COLOR_NORMAL ||
706             lineInfo[i].type == MT_COLOR_QUOTED ||
707             lineInfo[i].type == MT_COLOR_HEADER)) {
708       /* oops... */
709       if (lineInfo[i].chunks) {
710         lineInfo[i].chunks = 0;
711         mem_realloc (&(lineInfo[n].syntax), sizeof (struct syntax_t));
712       }
713       lineInfo[i++].type = MT_COLOR_SIGNATURE;
714     }
715   }
716   else if (check_sig (buf, lineInfo, n - 1) == 0)
717     lineInfo[n].type = MT_COLOR_SIGNATURE;
718   else if (regexec ((regex_t *) QuoteRegexp.rx, buf, 1, pmatch, 0) == 0) {
719     if (regexec ((regex_t *) Smileys.rx, buf, 1, smatch, 0) == 0) {
720       if (smatch[0].rm_so > 0) {
721         char c;
722
723         /* hack to avoid making an extra copy of buf */
724         c = buf[smatch[0].rm_so];
725         buf[smatch[0].rm_so] = 0;
726
727         if (regexec ((regex_t *) QuoteRegexp.rx, buf, 1, pmatch, 0) == 0) {
728           if (q_classify && lineInfo[n].quote == NULL)
729             lineInfo[n].quote = classify_quote (QuoteList,
730                                                 buf + pmatch[0].rm_so,
731                                                 pmatch[0].rm_eo -
732                                                 pmatch[0].rm_so, force_redraw,
733                                                 q_level);
734           lineInfo[n].type = MT_COLOR_QUOTED;
735         }
736         else
737           lineInfo[n].type = MT_COLOR_NORMAL;
738
739         buf[smatch[0].rm_so] = c;
740       }
741       else
742         lineInfo[n].type = MT_COLOR_NORMAL;
743     }
744     else {
745       if (q_classify && lineInfo[n].quote == NULL)
746         lineInfo[n].quote = classify_quote (QuoteList, buf + pmatch[0].rm_so,
747                                             pmatch[0].rm_eo - pmatch[0].rm_so,
748                                             force_redraw, q_level);
749       lineInfo[n].type = MT_COLOR_QUOTED;
750     }
751   }
752   else
753     lineInfo[n].type = MT_COLOR_NORMAL;
754
755   /* body patterns */
756   if (lineInfo[n].type == MT_COLOR_NORMAL ||
757       lineInfo[n].type == MT_COLOR_QUOTED) {
758     i = 0;
759
760     offset = 0;
761     lineInfo[n].chunks = 0;
762     do {
763       if (!buf[offset])
764         break;
765
766       found = 0;
767       null_rx = 0;
768       color_line = ColorBodyList;
769       while (color_line) {
770         if (regexec (&color_line->rx, buf + offset, 1, pmatch,
771                      (offset ? REG_NOTBOL : 0)) == 0) {
772           if (pmatch[0].rm_eo != pmatch[0].rm_so) {
773             if (!found) {
774               if (++(lineInfo[n].chunks) > 1)
775                 mem_realloc (&(lineInfo[n].syntax),
776                               (lineInfo[n].chunks) *
777                               sizeof (struct syntax_t));
778             }
779             i = lineInfo[n].chunks - 1;
780             pmatch[0].rm_so += offset;
781             pmatch[0].rm_eo += offset;
782             if (!found ||
783                 pmatch[0].rm_so < (lineInfo[n].syntax)[i].first ||
784                 (pmatch[0].rm_so == (lineInfo[n].syntax)[i].first &&
785                  pmatch[0].rm_eo > (lineInfo[n].syntax)[i].last)) {
786               (lineInfo[n].syntax)[i].color = color_line->pair;
787               (lineInfo[n].syntax)[i].first = pmatch[0].rm_so;
788               (lineInfo[n].syntax)[i].last = pmatch[0].rm_eo;
789             }
790             found = 1;
791             null_rx = 0;
792           }
793           else
794             null_rx = 1;        /* empty regexp; don't add it, but keep looking */
795         }
796         color_line = color_line->next;
797       }
798
799       if (null_rx)
800         offset++;               /* avoid degenerate cases */
801       else
802         offset = (lineInfo[n].syntax)[i].last;
803     } while (found || null_rx);
804   }
805 }
806
807 static int is_ansi (unsigned char *buf)
808 {
809   while (*buf && (isdigit (*buf) || *buf == ';'))
810     buf++;
811   return (*buf == 'm');
812 }
813
814 static int check_attachment_marker (char *p)
815 {
816   char *q = AttachmentMarker;
817
818   for (; *p == *q && *q && *p && *q != '\a' && *p != '\a'; p++, q++);
819   return (int) (*p - *q);
820 }
821
822 static int grok_ansi (unsigned char *buf, int pos, ansi_attr * a)
823 {
824   int x = pos;
825
826   while (isdigit (buf[x]) || buf[x] == ';')
827     x++;
828
829   /* Character Attributes */
830   if (option (OPTALLOWANSI) && a != NULL && buf[x] == 'm') {
831     if (pos == x) {
832 #ifdef HAVE_COLOR
833       if (a->pair != -1)
834         mutt_free_color (a->fg, a->bg);
835 #endif
836       a->attr = ANSI_OFF;
837       a->pair = -1;
838     }
839     a->bg = -2;
840     a->fg = -2;
841     while (pos < x) {
842       if (buf[pos] == '1' && (pos + 1 == x || buf[pos + 1] == ';')) {
843         a->attr |= ANSI_BOLD;
844         pos += 2;
845       }
846       else if (buf[pos] == '4' && (pos + 1 == x || buf[pos + 1] == ';')) {
847         a->attr |= ANSI_UNDERLINE;
848         pos += 2;
849       }
850       else if (buf[pos] == '5' && (pos + 1 == x || buf[pos + 1] == ';')) {
851         a->attr |= ANSI_BLINK;
852         pos += 2;
853       }
854       else if (buf[pos] == '7' && (pos + 1 == x || buf[pos + 1] == ';')) {
855         a->attr |= ANSI_REVERSE;
856         pos += 2;
857       }
858       else if (buf[pos] == '0' && (pos + 1 == x || buf[pos + 1] == ';')) {
859         a->bg = -2;
860         a->fg = -2;
861         pos += 2;
862       }
863       else if (buf[pos] == '3' && isdigit (buf[pos + 1])) {
864 #ifdef HAVE_COLOR
865         if (a->pair != -1)
866           mutt_free_color (a->fg, a->bg);
867 #endif
868         a->pair = -1;
869         a->attr |= ANSI_COLOR;
870         if (buf[pos + 1] != '9')
871           a->fg = buf[pos + 1] - '0';
872         pos += 3;
873       }
874       else if (buf[pos] == '4' && isdigit (buf[pos + 1])) {
875 #ifdef HAVE_COLOR
876         if (a->pair != -1)
877           mutt_free_color (a->fg, a->bg);
878 #endif
879         a->pair = -1;
880         a->attr |= ANSI_COLOR;
881         if (buf[pos + 1] != '9')
882           a->bg = buf[pos + 1] - '0';
883         pos += 3;
884       }
885       else {
886         while (pos < x && buf[pos] != ';')
887           pos++;
888         pos++;
889       }
890     }
891   }
892   pos = x;
893   return pos;
894 }
895
896 /* trim tail of buf so that it contains complete multibyte characters */
897 static int trim_incomplete_mbyte(unsigned char *buf, size_t len) {
898   mbstate_t mbstate;
899   size_t k;
900
901   memset (&mbstate, 0, sizeof (mbstate));
902   for (; len > 0; buf += k, len -= k) {
903     k = mbrtowc (NULL, (char *) buf, len, &mbstate);
904     if (k == -2) 
905       break; 
906     else if (k == -1 || k == 0) 
907       k = 1;
908   }
909   *buf = '\0';
910
911   return len;
912 }
913
914 static int
915 fill_buffer (FILE * f, off_t *last_pos, off_t offset, unsigned char *buf,
916              unsigned char *fmt, size_t blen, int *buf_ready)
917 {
918   unsigned char *p;
919   static int b_read = 0;
920
921   if (*buf_ready == 0) {
922     buf[blen - 1] = 0;
923     if (offset != *last_pos)
924       fseeko (f, offset, 0);
925     if (fgets ((char *) buf, blen - 1, f) == NULL) {
926       fmt[0] = 0;
927       return (-1);
928     }
929     *last_pos = ftello (f);
930     b_read = (int) (*last_pos - offset);
931     *buf_ready = 1;
932
933     /* incomplete mbyte characters trigger a segfault in regex processing for
934      * certain versions of glibc. Trim them if necessary. */
935     if (b_read == blen - 2)
936       b_read -= trim_incomplete_mbyte(buf, b_read);
937
938     /* copy "buf" to "fmt", but without bold and underline controls */
939     p = buf;
940     while (*p) {
941       if (*p == '\010' && (p > buf)) {
942         if (*(p + 1) == '_')    /* underline */
943           p += 2;
944         else if (*(p + 1)) {    /* bold or overstrike */
945           *(fmt - 1) = *(p + 1);
946           p += 2;
947         }
948         else                    /* ^H */
949           *fmt++ = *p++;
950       }
951       else if (*p == '\033' && *(p + 1) == '[' && is_ansi (p + 2)) {
952         while (*p++ != 'm')     /* skip ANSI sequence */
953           ;
954       }
955       else if (*p == '\033' && *(p + 1) == ']'
956                && check_attachment_marker ((char *) p) == 0) {
957         debug_print (2, ("seen attachment marker.\n"));
958         while (*p++ != '\a')    /* skip pseudo-ANSI sequence */
959           ;
960       }
961       else
962         *fmt++ = *p++;
963     }
964     *fmt = 0;
965   }
966   return b_read;
967 }
968
969 #ifdef USE_NNTP
970 #include "mx.h"
971 #include "nntp.h"
972 #endif
973
974
975 static int format_line (struct line_t **lineInfo, int n, unsigned char *buf,
976                         int flags, ansi_attr * pa, int cnt,
977                         int *pspace, int *pvch, int *pcol, int *pspecial)
978 {
979   int space = -1;               /* index of the last space or TAB */
980   int col = option (OPTMARKERS) ? (*lineInfo)[n].continuation : 0;
981   int ch, vch, k, last_special = -1, special = 0, t;
982   wchar_t wc;
983   mbstate_t mbstate;
984
985   int wrap_cols = COLS;
986
987   if (!(flags & (M_SHOWFLAT)))
988     wrap_cols -= WrapMargin;
989   wrap_cols -= SW;
990
991   if (wrap_cols <= 0)
992     wrap_cols = COLS;
993
994   /* FIXME: this should come from lineInfo */
995   memset (&mbstate, 0, sizeof (mbstate));
996
997   for (ch = 0, vch = 0; ch < cnt; ch += k, vch += k) {
998     /* Handle ANSI sequences */
999     while (cnt - ch >= 2 && buf[ch] == '\033' && buf[ch + 1] == '[' &&
1000            is_ansi (buf + ch + 2))
1001       ch = grok_ansi (buf, ch + 2, pa) + 1;
1002
1003     while (cnt - ch >= 2 && buf[ch] == '\033' && buf[ch + 1] == ']' &&
1004            check_attachment_marker ((char *) buf + ch) == 0) {
1005       while (buf[ch++] != '\a')
1006         if (ch >= cnt)
1007           break;
1008     }
1009
1010     /* is anything left to do? */
1011     if (ch >= cnt)
1012       break;
1013
1014     k = mbrtowc (&wc, (char *) buf + ch, cnt - ch, &mbstate);
1015     if (k == -2 || k == -1) {
1016       debug_print (1, ("mbrtowc returned %d; errno = %d.\n", k, errno));
1017       if (col + 4 > wrap_cols)
1018         break;
1019       col += 4;
1020       if (pa)
1021         printw ("\\%03o", buf[ch]);
1022       k = 1;
1023       continue;
1024     }
1025     if (k == 0)
1026       k = 1;
1027
1028     /* Handle backspace */
1029     special = 0;
1030     if (IsWPrint (wc)) {
1031       wchar_t wc1;
1032       mbstate_t mbstate1;
1033       int k1, k2;
1034
1035       while ((wc1 = 0, mbstate1 = mbstate,
1036               k1 =
1037               k + mbrtowc (&wc1, (char *) buf + ch + k, cnt - ch - k,
1038                            &mbstate1), k1 - k > 0 && wc1 == '\b')
1039              && (wc1 = 0, k2 =
1040                  mbrtowc (&wc1, (char *) buf + ch + k1, cnt - ch - k1,
1041                           &mbstate1), k2 > 0 && IsWPrint (wc1))) {
1042         if (wc == wc1) {
1043           special |= (wc == '_' && special & A_UNDERLINE)
1044             ? A_UNDERLINE : A_BOLD;
1045         }
1046         else if (wc == '_' || wc1 == '_') {
1047           special |= A_UNDERLINE;
1048           wc = (wc1 == '_') ? wc : wc1;
1049         }
1050         else {
1051           /* special = 0; / * overstrike: nothing to do! */
1052           wc = wc1;
1053         }
1054         ch += k1;
1055         k = k2;
1056         mbstate = mbstate1;
1057       }
1058     }
1059
1060     if (pa &&
1061         ((flags & (M_SHOWCOLOR | M_SEARCH | M_PAGER_MARKER)) ||
1062          special || last_special || pa->attr)) {
1063       resolve_color (*lineInfo, n, vch, flags, special, pa);
1064       last_special = special;
1065     }
1066
1067     if (IsWPrint (wc)) {
1068       if (wc == ' ')
1069         space = ch;
1070       t = wcwidth (wc);
1071       if (col + t > wrap_cols)
1072         break;
1073       col += t;
1074       if (pa)
1075         mutt_addwch (wc);
1076     }
1077     else if (wc == '\n')
1078       break;
1079     else if (wc == '\t') {
1080       space = ch;
1081       t = (col & ~7) + 8;
1082       if (t > wrap_cols)
1083         break;
1084       if (pa)
1085         for (; col < t; col++)
1086           addch (' ');
1087       else
1088         col = t;
1089     }
1090     else if (wc < 0x20 || wc == 0x7f) {
1091       if (col + 2 > wrap_cols)
1092         break;
1093       col += 2;
1094       if (pa)
1095         printw ("^%c", ('@' + wc) & 0x7f);
1096     }
1097     else if (wc < 0x100) {
1098       if (col + 4 > wrap_cols)
1099         break;
1100       col += 4;
1101       if (pa)
1102         printw ("\\%03o", wc);
1103     }
1104     else {
1105       if (col + 1 > wrap_cols)
1106         break;
1107       ++col;
1108       if (pa)
1109         addch (replacement_char ());
1110     }
1111   }
1112   *pspace = space;
1113   *pcol = col;
1114   *pvch = vch;
1115   *pspecial = special;
1116   return ch;
1117 }
1118
1119 /*
1120  * Args:
1121  *      flags   M_SHOWFLAT, show characters (used for displaying help)
1122  *              M_SHOWCOLOR, show characters in color
1123  *                      otherwise don't show characters
1124  *              M_HIDE, don't show quoted text
1125  *              M_SEARCH, resolve search patterns
1126  *              M_TYPES, compute line's type
1127  *              M_PAGER_NSKIP, keeps leading whitespace
1128  *              M_PAGER_MARKER, eventually show markers
1129  *
1130  * Return values:
1131  *      -1      EOF was reached
1132  *      0       normal exit, line was not displayed
1133  *      >0      normal exit, line was displayed
1134  */
1135
1136 static int
1137 display_line (FILE * f, off_t *last_pos, struct line_t **lineInfo, int n,
1138               int *last, int *max, int flags, struct q_class_t **QuoteList,
1139               int *q_level, int *force_redraw, regex_t * SearchRE)
1140 {
1141   unsigned char buf[LONG_STRING], fmt[LONG_STRING];
1142   unsigned char *buf_ptr = buf;
1143   int ch, vch, col, cnt, b_read;
1144   int buf_ready = 0, change_last = 0;
1145   int special;
1146   int offset;
1147   int def_color;
1148   int m;
1149   ansi_attr a = { 0, 0, 0, -1 };
1150   regmatch_t pmatch[1];
1151
1152   if (n == *last) {
1153     (*last)++;
1154     change_last = 1;
1155   }
1156
1157   if (*last == *max) {
1158     mem_realloc (lineInfo, sizeof (struct line_t) * (*max += LINES));
1159     for (ch = *last; ch < *max; ch++) {
1160       memset (&((*lineInfo)[ch]), 0, sizeof (struct line_t));
1161       (*lineInfo)[ch].type = -1;
1162       (*lineInfo)[ch].search_cnt = -1;
1163       (*lineInfo)[ch].syntax = p_new(struct syntax_t, 1);
1164       ((*lineInfo)[ch].syntax)[0].first = ((*lineInfo)[ch].syntax)[0].last =
1165         -1;
1166     }
1167   }
1168
1169   /* only do color hiliting if we are viewing a message */
1170   if (flags & (M_SHOWCOLOR | M_TYPES)) {
1171     if ((*lineInfo)[n].type == -1) {
1172       /* determine the line class */
1173       if (fill_buffer
1174           (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1175            &buf_ready) < 0) {
1176         if (change_last)
1177           (*last)--;
1178         return (-1);
1179       }
1180
1181       resolve_types ((char *) fmt, (char *) buf, *lineInfo, n, *last,
1182                      QuoteList, q_level, force_redraw, flags & M_SHOWCOLOR);
1183
1184       /* avoid race condition for continuation lines when scrolling up */
1185       for (m = n + 1;
1186            m < *last && (*lineInfo)[m].offset && (*lineInfo)[m].continuation;
1187            m++)
1188         (*lineInfo)[m].type = (*lineInfo)[n].type;
1189     }
1190
1191     /* this also prevents searching through the hidden lines */
1192     if ((flags & M_HIDE) && (*lineInfo)[n].type == MT_COLOR_QUOTED)
1193       flags = 0;                /* M_NOSHOW */
1194   }
1195
1196   /* At this point, (*lineInfo[n]).quote may still be undefined. We 
1197    * don't want to compute it every time M_TYPES is set, since this
1198    * would slow down the "bottom" function unacceptably. A compromise
1199    * solution is hence to call regexec() again, just to find out the
1200    * length of the quote prefix.
1201    */
1202   if ((flags & M_SHOWCOLOR) && !(*lineInfo)[n].continuation &&
1203       (*lineInfo)[n].type == MT_COLOR_QUOTED && (*lineInfo)[n].quote == NULL)
1204   {
1205     if (fill_buffer
1206         (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1207          &buf_ready) < 0) {
1208       if (change_last)
1209         (*last)--;
1210       return (-1);
1211     }
1212     regexec ((regex_t *) QuoteRegexp.rx, (char *) fmt, 1, pmatch, 0);
1213     (*lineInfo)[n].quote = classify_quote (QuoteList,
1214                                            (char *) fmt + pmatch[0].rm_so,
1215                                            pmatch[0].rm_eo - pmatch[0].rm_so,
1216                                            force_redraw, q_level);
1217   }
1218
1219   if ((flags & M_SEARCH) && !(*lineInfo)[n].continuation
1220       && (*lineInfo)[n].search_cnt == -1) {
1221     if (fill_buffer
1222         (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1223          &buf_ready) < 0) {
1224       if (change_last)
1225         (*last)--;
1226       return (-1);
1227     }
1228
1229     offset = 0;
1230     (*lineInfo)[n].search_cnt = 0;
1231     while (regexec
1232            (SearchRE, (char *) fmt + offset, 1, pmatch,
1233             (offset ? REG_NOTBOL : 0)) == 0) {
1234       if (++((*lineInfo)[n].search_cnt) > 1)
1235         mem_realloc (&((*lineInfo)[n].search),
1236                       ((*lineInfo)[n].search_cnt) * sizeof (struct syntax_t));
1237       else
1238         (*lineInfo)[n].search = p_new(struct syntax_t, 1);
1239       pmatch[0].rm_so += offset;
1240       pmatch[0].rm_eo += offset;
1241       ((*lineInfo)[n].search)[(*lineInfo)[n].search_cnt - 1].first =
1242         pmatch[0].rm_so;
1243       ((*lineInfo)[n].search)[(*lineInfo)[n].search_cnt - 1].last =
1244         pmatch[0].rm_eo;
1245
1246       if (pmatch[0].rm_eo == pmatch[0].rm_so)
1247         offset++;               /* avoid degenerate cases */
1248       else
1249         offset = pmatch[0].rm_eo;
1250       if (!fmt[offset])
1251         break;
1252     }
1253   }
1254
1255   if (!(flags & M_SHOW) && (*lineInfo)[n + 1].offset > 0) {
1256     /* we've already scanned this line, so just exit */
1257     return (0);
1258   }
1259   if ((flags & M_SHOWCOLOR) && *force_redraw && (*lineInfo)[n + 1].offset > 0) {
1260     /* no need to try to display this line... */
1261     return (1);                 /* fake display */
1262   }
1263
1264   if ((b_read = fill_buffer (f, last_pos, (*lineInfo)[n].offset, buf, fmt,
1265                              sizeof (buf), &buf_ready)) < 0) {
1266     if (change_last)
1267       (*last)--;
1268     return (-1);
1269   }
1270
1271   /* now chose a good place to break the line */
1272   cnt =
1273     format_line (lineInfo, n, buf, flags, 0, b_read, &ch, &vch, &col,
1274                  &special);
1275   buf_ptr = buf + cnt;
1276
1277   /* move the break point only if smart_wrap is set */
1278   if (option (OPTWRAP)) {
1279     if (cnt < b_read) {
1280       if (ch != -1 && buf[cnt] != ' ' && buf[cnt] != '\t' && buf[cnt] != '\n'
1281           && buf[cnt] != '\r') {
1282         buf_ptr = buf + ch;
1283         /* skip trailing blanks */
1284         while (ch && (buf[ch] == ' ' || buf[ch] == '\t' || buf[ch] == '\r'))
1285           ch--;
1286         /* a very long word with leading spaces causes infinite wrapping */
1287         if ((!ch) && (flags & M_PAGER_NSKIP))
1288           buf_ptr = buf + cnt;
1289         else
1290           cnt = ch + 1;
1291       }
1292       else
1293         buf_ptr = buf + cnt;    /* a very long word... */
1294     }
1295     if (!(flags & M_PAGER_NSKIP))
1296       /* skip leading blanks on the next line too */
1297       while (*buf_ptr == ' ' || *buf_ptr == '\t')
1298         buf_ptr++;
1299   }
1300
1301   if (*buf_ptr == '\r')
1302     buf_ptr++;
1303   if (*buf_ptr == '\n')
1304     buf_ptr++;
1305
1306   if ((int) (buf_ptr - buf) < b_read && !(*lineInfo)[n + 1].continuation)
1307     append_line (*lineInfo, n, (int) (buf_ptr - buf));
1308   (*lineInfo)[n + 1].offset = (*lineInfo)[n].offset + (long) (buf_ptr - buf);
1309
1310   /* if we don't need to display the line we are done */
1311   if (!(flags & M_SHOW))
1312     return 0;
1313
1314   /* display the line */
1315   format_line (lineInfo, n, buf, flags, &a, cnt, &ch, &vch, &col, &special);
1316
1317   /* avoid a bug in ncurses... */
1318 #ifndef USE_SLANG_CURSES
1319   if (col == 0) {
1320     SETCOLOR (MT_COLOR_NORMAL);
1321     addch (' ');
1322   }
1323 #endif
1324
1325   /* end the last color pattern (needed by S-Lang) */
1326   if (special || (col != COLS && (flags & (M_SHOWCOLOR | M_SEARCH))))
1327     resolve_color (*lineInfo, n, vch, flags, 0, &a);
1328
1329   /*
1330    * Fill the blank space at the end of the line with the prevailing color.
1331    * ncurses does an implicit clrtoeol() when you do addch('\n') so we have
1332    * to make sure to reset the color *after* that
1333    */
1334   if (flags & M_SHOWCOLOR) {
1335     m = ((*lineInfo)[n].continuation) ? ((*lineInfo)[n].syntax)[0].first : n;
1336     if ((*lineInfo)[m].type == MT_COLOR_HEADER)
1337       def_color = ((*lineInfo)[m].syntax)[0].color;
1338     else
1339       def_color = ColorDefs[(*lineInfo)[m].type];
1340
1341     attrset (def_color);
1342 #ifdef HAVE_BKGDSET
1343     bkgdset (def_color | ' ');
1344 #endif
1345   }
1346
1347   /* ncurses always wraps lines when you get to the right side of the
1348    * screen, but S-Lang seems to only wrap if the next character is *not*
1349    * a newline (grr!).
1350    */
1351 #ifndef USE_SLANG_CURSES
1352   if (col < COLS)
1353 #endif
1354     addch ('\n');
1355
1356   /*
1357    * reset the color back to normal.  This *must* come after the
1358    * addch('\n'), otherwise the color for this line will not be
1359    * filled to the right margin.
1360    */
1361   if (flags & M_SHOWCOLOR) {
1362     SETCOLOR (MT_COLOR_NORMAL);
1363     BKGDSET (MT_COLOR_NORMAL);
1364   }
1365
1366   /* build a return code */
1367   if (!(flags & M_SHOW))
1368     flags = 0;
1369
1370   return (flags);
1371 }
1372
1373 static int upNLines (int nlines, struct line_t *info, int cur, int hiding)
1374 {
1375   while (cur > 0 && nlines > 0) {
1376     cur--;
1377     if (!hiding || info[cur].type != MT_COLOR_QUOTED)
1378       nlines--;
1379   }
1380
1381   return cur;
1382 }
1383
1384 static struct mapping_t PagerHelp[] = {
1385   {N_("Exit"), OP_EXIT},
1386   {N_("PrevPg"), OP_PREV_PAGE},
1387   {N_("NextPg"), OP_NEXT_PAGE},
1388   {NULL, 0}
1389 };
1390 static struct mapping_t PagerHelpExtra[] = {
1391   {N_("View Attachm."), OP_VIEW_ATTACHMENTS},
1392   {N_("Del"), OP_DELETE},
1393   {N_("Reply"), OP_REPLY},
1394   {N_("Next"), OP_MAIN_NEXT_UNDELETED},
1395   {NULL, 0}
1396 };
1397
1398 #ifdef USE_NNTP
1399 static struct mapping_t PagerNewsHelpExtra[] = {
1400   {N_("Post"), OP_POST},
1401   {N_("Followup"), OP_FOLLOWUP},
1402   {N_("Del"), OP_DELETE},
1403   {N_("Next"), OP_MAIN_NEXT_UNDELETED},
1404   {NULL, 0}
1405 };
1406 #endif
1407
1408
1409
1410 /* This pager is actually not so simple as it once was.  It now operates in
1411    two modes: one for viewing messages and the other for viewing help.  These
1412    can be distinguished by whether or not ``hdr'' is NULL.  The ``hdr'' arg
1413    is there so that we can do operations on the current message without the
1414    need to pop back out to the main-menu.  */
1415 int
1416 mutt_pager (const char *banner, const char *fname, int flags, pager_t * extra)
1417 {
1418   static char searchbuf[STRING];
1419   char buffer[LONG_STRING];
1420   char helpstr[SHORT_STRING * 2];
1421   char tmphelp[SHORT_STRING * 2];
1422   int maxLine, lastLine = 0;
1423   struct line_t *lineInfo;
1424   struct q_class_t *QuoteList = NULL;
1425   int i, j, ch = 0, rc = -1, hideQuoted = 0, q_level = 0, force_redraw = 0;
1426   int lines = 0, curline = 0, topline = 0, oldtopline = 0, err, first = 1;
1427   int r = -1;
1428   int redraw = REDRAW_FULL;
1429   FILE *fp = NULL;
1430   off_t last_pos = 0, last_offset = 0;
1431   int old_smart_wrap, old_markers;
1432   struct stat sb;
1433   regex_t SearchRE;
1434   int SearchCompiled = 0, SearchFlag = 0, SearchBack = 0;
1435   int has_types = (IsHeader (extra) || (flags & M_SHOWCOLOR)) ? M_TYPES : 0;    /* main message or rfc822 attachment */
1436
1437   int bodyoffset = 1;           /* offset of first line of real text */
1438   int statusoffset = 0;         /* offset for the status bar */
1439   int helpoffset = LINES - 2;   /* offset for the help bar. */
1440   int bodylen = LINES - 2 - bodyoffset; /* length of displayable area */
1441
1442   MUTTMENU *index = NULL;       /* the Pager Index (PI) */
1443   int indexoffset = 0;          /* offset for the PI */
1444   int indexlen = PagerIndexLines;       /* indexlen not always == PIL */
1445   int indicator = indexlen / 3; /* the indicator line of the PI */
1446   int old_PagerIndexLines;      /* some people want to resize it
1447                                  * while inside the pager... */
1448
1449 #ifdef USE_NNTP
1450   char *followup_to;
1451 #endif
1452
1453   if (!(flags & M_SHOWCOLOR))
1454     flags |= M_SHOWFLAT;
1455
1456   if ((fp = fopen (fname, "r")) == NULL) {
1457     mutt_perror (fname);
1458     return (-1);
1459   }
1460
1461   if (stat (fname, &sb) != 0) {
1462     mutt_perror (fname);
1463     fclose (fp);
1464     return (-1);
1465   }
1466   unlink (fname);
1467
1468   /* Initialize variables */
1469
1470   if (IsHeader (extra) && !extra->hdr->read) {
1471     Context->msgnotreadyet = extra->hdr->msgno;
1472     mutt_set_flag (Context, extra->hdr, M_READ, 1);
1473   }
1474
1475   lineInfo = p_new(struct line_t, maxLine = LINES);
1476   for (i = 0; i < maxLine; i++) {
1477     memset (&lineInfo[i], 0, sizeof (struct line_t));
1478     lineInfo[i].type = -1;
1479     lineInfo[i].search_cnt = -1;
1480     lineInfo[i].syntax = p_new(struct syntax_t, 1);
1481     (lineInfo[i].syntax)[0].first = (lineInfo[i].syntax)[0].last = -1;
1482   }
1483
1484   mutt_compile_help (helpstr, sizeof (helpstr), MENU_PAGER, PagerHelp);
1485   if (IsHeader (extra)) {
1486     strfcpy (tmphelp, helpstr, sizeof (tmphelp));
1487     mutt_compile_help (buffer, sizeof (buffer), MENU_PAGER,
1488 #ifdef USE_NNTP
1489                        (Context
1490                         && (Context->magic == M_NNTP)) ? PagerNewsHelpExtra :
1491 #endif
1492                        PagerHelpExtra);
1493     snprintf (helpstr, sizeof (helpstr), "%s %s", tmphelp, buffer);
1494   }
1495   if (!InHelp) {
1496     strfcpy (tmphelp, helpstr, sizeof (tmphelp));
1497     mutt_make_help (buffer, sizeof (buffer), _("Help"), MENU_PAGER, OP_HELP);
1498     snprintf (helpstr, sizeof (helpstr), "%s %s", tmphelp, buffer);
1499   }
1500
1501   while (ch != -1) {
1502     mutt_curs_set (0);
1503
1504 #ifdef USE_IMAP
1505     imap_keepalive ();
1506 #endif
1507
1508     if (redraw & REDRAW_FULL) {
1509       SETCOLOR (MT_COLOR_NORMAL);
1510       /* clear() doesn't optimize screen redraws */
1511       move (0, 0);
1512       clrtobot ();
1513
1514       if (IsHeader (extra) && Context->vcount + 1 < PagerIndexLines)
1515         indexlen = Context->vcount + 1;
1516       else
1517         indexlen = PagerIndexLines;
1518
1519       indicator = indexlen / 3;
1520
1521       if (option (OPTSTATUSONTOP)) {
1522         indexoffset = 0;
1523         statusoffset = IsHeader (extra) ? indexlen : 0;
1524         bodyoffset = statusoffset + 1;
1525         helpoffset = LINES - 2;
1526         bodylen = helpoffset - bodyoffset;
1527         if (!option (OPTHELP))
1528           bodylen++;
1529       }
1530       else {
1531         helpoffset = 0;
1532         indexoffset = 1;
1533         statusoffset = LINES - 2;
1534         if (!option (OPTHELP))
1535           indexoffset = 0;
1536         bodyoffset = indexoffset + (IsHeader (extra) ? indexlen : 0);
1537         bodylen = statusoffset - bodyoffset;
1538       }
1539
1540       if (option (OPTHELP)) {
1541         SETCOLOR (MT_COLOR_STATUS);
1542         move (helpoffset, SW);
1543         mutt_paddstr (COLS-SW, helpstr);
1544         SETCOLOR (MT_COLOR_NORMAL);
1545       }
1546
1547 #if defined (USE_SLANG_CURSES) || defined (HAVE_RESIZETERM)
1548       if (Resize != NULL) {
1549         if ((SearchCompiled = Resize->SearchCompiled)) {
1550           REGCOMP
1551             (&SearchRE, searchbuf, REG_NEWLINE | mutt_which_case (searchbuf));
1552           SearchFlag = M_SEARCH;
1553           SearchBack = Resize->SearchBack;
1554         }
1555         lines = Resize->line;
1556         redraw |= REDRAW_SIGWINCH;
1557
1558         p_delete(&Resize);
1559       }
1560 #endif
1561
1562       if (IsHeader (extra) && PagerIndexLines) {
1563         if (index == NULL) {
1564           /* only allocate the space if/when we need the index.
1565              Initialise the menu as per the main index */
1566           index = mutt_new_menu ();
1567           index->menu = MENU_MAIN;
1568           index->make_entry = index_make_entry;
1569           index->color = index_color;
1570           index->max = Context->vcount;
1571           index->current = extra->hdr->virtual;
1572         }
1573
1574         SETCOLOR (MT_COLOR_NORMAL);
1575         index->offset = indexoffset + (option (OPTSTATUSONTOP) ? 1 : 0);
1576
1577         index->pagelen = indexlen - 1;
1578
1579         /* some fudge to work out where abouts the indicator should go */
1580         if (index->current - indicator < 0)
1581           index->top = 0;
1582         else if (index->max - index->current < index->pagelen - indicator)
1583           index->top = index->max - index->pagelen;
1584         else
1585           index->top = index->current - indicator;
1586
1587         menu_redraw_index (index);
1588       }
1589
1590       redraw |= REDRAW_BODY | REDRAW_INDEX | REDRAW_STATUS;
1591       mutt_show_error ();
1592     }
1593
1594     if (redraw & REDRAW_SIGWINCH) {
1595       i = -1;
1596       j = -1;
1597       while (display_line (fp, &last_pos, &lineInfo, ++i, &lastLine, &maxLine,
1598                            has_types | SearchFlag, &QuoteList, &q_level,
1599                            &force_redraw, &SearchRE) == 0) {
1600         if (!lineInfo[i].continuation && ++j == lines) {
1601           topline = i;
1602           if (!SearchFlag)
1603             break;
1604         }
1605         redraw |= REDRAW_SIDEBAR;
1606       }                         /* while */
1607     }
1608
1609     if ((redraw & REDRAW_BODY) || topline != oldtopline) {
1610       do {
1611         move (bodyoffset, SW);
1612         curline = oldtopline = topline;
1613         lines = 0;
1614         force_redraw = 0;
1615
1616         while (lines < bodylen && lineInfo[curline].offset <= sb.st_size - 1) {
1617           if (display_line (fp, &last_pos, &lineInfo, curline, &lastLine,
1618                             &maxLine,
1619                             (flags & M_DISPLAYFLAGS) | hideQuoted |
1620                             SearchFlag, &QuoteList, &q_level, &force_redraw,
1621                             &SearchRE) > 0)
1622             lines++;
1623           curline++;
1624           move (lines + bodyoffset, SW);
1625           redraw |= REDRAW_SIDEBAR;
1626         }
1627         last_offset = lineInfo[curline].offset;
1628       } while (force_redraw);
1629
1630       SETCOLOR (MT_COLOR_TILDE);
1631       BKGDSET (MT_COLOR_TILDE);
1632       while (lines < bodylen) {
1633         clrtoeol ();
1634         if (option (OPTTILDE))
1635           addch ('~');
1636         addch ('\n');
1637         lines++;
1638         move (lines + bodyoffset, SW);
1639       }
1640       /* We are going to update the pager status bar, so it isn't
1641        * necessary to reset to normal color now. */
1642
1643       redraw |= REDRAW_STATUS;  /* need to update the % seen */
1644     }
1645
1646     if (redraw & REDRAW_STATUS) {
1647       /* print out the pager status bar */
1648       SETCOLOR (MT_COLOR_STATUS);
1649       BKGDSET (MT_COLOR_STATUS);
1650       CLEARLINE_WIN (statusoffset);
1651       if (IsHeader (extra)) {
1652         size_t l1 = (COLS - 9) * MB_LEN_MAX;
1653         size_t l2 = sizeof (buffer);
1654
1655         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1656                            Context, extra->hdr, M_FORMAT_MAKEPRINT);
1657       }
1658       else if (IsMsgAttach (extra)) {
1659         size_t l1 = (COLS - 9) * MB_LEN_MAX;
1660         size_t l2 = sizeof (buffer);
1661
1662         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1663                            Context, extra->bdy->hdr, M_FORMAT_MAKEPRINT);
1664       }
1665       move(statusoffset,SW);
1666       mutt_paddstr (COLS - 10 - SW, IsHeader (extra) || 
1667                     IsMsgAttach (extra) ? buffer : banner);
1668
1669       addstr (" -- (");
1670       if (last_pos < sb.st_size - 1)
1671         printw ("%d%%)", (int) (100 * last_offset / sb.st_size));
1672       else
1673         addstr (topline == 0 ? "all)" : "end)");
1674       BKGDSET (MT_COLOR_NORMAL);
1675       SETCOLOR (MT_COLOR_NORMAL);
1676     }
1677
1678     if (redraw & REDRAW_SIDEBAR)
1679       sidebar_draw (MENU_PAGER);
1680
1681     if ((redraw & REDRAW_INDEX) && index) {
1682       /* redraw the pager_index indicator, because the
1683        * flags for this message might have changed. */
1684       menu_redraw_current (index);
1685       sidebar_draw (MENU_PAGER);
1686       /* print out the index status bar */
1687       menu_status_line (buffer, sizeof (buffer), index, NONULL (Status));
1688       move (indexoffset + (option (OPTSTATUSONTOP) ? 0 : (indexlen - 1)), SW);
1689       SETCOLOR (MT_COLOR_STATUS);
1690       BKGDSET (MT_COLOR_STATUS);
1691       mutt_paddstr (COLS-SW, buffer);
1692       SETCOLOR (MT_COLOR_NORMAL);
1693       BKGDSET (MT_COLOR_NORMAL);
1694     }
1695     /* if we're not using the index, update every time */
1696     if (index == 0)
1697       sidebar_draw (MENU_PAGER);
1698
1699     redraw = 0;
1700
1701     if (option(OPTBRAILLEFRIENDLY)) {
1702       if (brailleLine!=-1) {
1703         move(brailleLine+1, 0);
1704         brailleLine = -1;
1705       }
1706     } else
1707       move (statusoffset, COLS-1);
1708     mutt_refresh ();
1709
1710     if (IsHeader (extra) && OldHdr == extra->hdr && TopLine != topline
1711         && lineInfo[curline].offset < sb.st_size-1) {
1712       if (TopLine - topline > lines)
1713         topline += lines;
1714       else
1715         topline = TopLine;
1716       continue;
1717     }
1718     else
1719       OldHdr = NULL;
1720
1721     ch = km_dokey (MENU_PAGER);
1722     if (ch != -1)
1723       mutt_clear_error ();
1724     mutt_curs_set (1);
1725
1726     if (SigInt) {
1727       mutt_query_exit ();
1728       continue;
1729     }
1730 #if defined (USE_SLANG_CURSES) || defined (HAVE_RESIZETERM)
1731     else if (SigWinch) {
1732       mutt_resize_screen ();
1733
1734       /* Store current position. */
1735       lines = -1;
1736       for (i = 0; i <= topline; i++)
1737         if (!lineInfo[i].continuation)
1738           lines++;
1739
1740       if (flags & M_PAGER_RETWINCH) {
1741         Resize = p_new(struct resize, 1);
1742
1743         Resize->line = lines;
1744         Resize->SearchCompiled = SearchCompiled;
1745         Resize->SearchBack = SearchBack;
1746
1747         ch = -1;
1748         rc = OP_REFORMAT_WINCH;
1749       }
1750       else {
1751         for (i = 0; i < maxLine; i++) {
1752           lineInfo[i].offset = 0;
1753           lineInfo[i].type = -1;
1754           lineInfo[i].continuation = 0;
1755           lineInfo[i].chunks = 0;
1756           lineInfo[i].search_cnt = -1;
1757           lineInfo[i].quote = NULL;
1758
1759           mem_realloc (&(lineInfo[i].syntax), sizeof (struct syntax_t));
1760           if (SearchCompiled && lineInfo[i].search)
1761             p_delete(&(lineInfo[i].search));
1762         }
1763
1764         lastLine = 0;
1765         topline = 0;
1766
1767         redraw = REDRAW_FULL | REDRAW_SIGWINCH;
1768         ch = 0;
1769       }
1770
1771       SigWinch = 0;
1772       clearok (stdscr, TRUE);   /*force complete redraw */
1773       continue;
1774     }
1775 #endif
1776     else if (ch == -1) {
1777       ch = 0;
1778       continue;
1779     }
1780
1781     rc = ch;
1782
1783     switch (ch) {
1784     case OP_EXIT:
1785       rc = -1;
1786       ch = -1;
1787       break;
1788
1789     case OP_NEXT_PAGE:
1790       if (lineInfo[curline].offset < sb.st_size - 1) {
1791         topline = upNLines (PagerContext, lineInfo, curline, hideQuoted);
1792       }
1793       else if (option (OPTPAGERSTOP)) {
1794         /* emulate "less -q" and don't go on to the next message. */
1795         mutt_error _("Bottom of message is shown.");
1796       }
1797       else {
1798         /* end of the current message, so display the next message. */
1799         rc = OP_MAIN_NEXT_UNDELETED;
1800         ch = -1;
1801       }
1802       break;
1803
1804     case OP_PREV_PAGE:
1805       if (topline != 0) {
1806         topline =
1807           upNLines (bodylen - PagerContext, lineInfo, topline, hideQuoted);
1808       }
1809       else
1810         mutt_error _("Top of message is shown.");
1811       break;
1812
1813     case OP_NEXT_LINE:
1814       if (lineInfo[curline].offset < sb.st_size - 1) {
1815         topline++;
1816         if (hideQuoted) {
1817           while (lineInfo[topline].type == MT_COLOR_QUOTED &&
1818                  topline < lastLine)
1819             topline++;
1820         }
1821       }
1822       else
1823         mutt_error _("Bottom of message is shown.");
1824       break;
1825
1826     case OP_PREV_LINE:
1827       if (topline)
1828         topline = upNLines (1, lineInfo, topline, hideQuoted);
1829       else
1830         mutt_error _("Top of message is shown.");
1831       break;
1832
1833     case OP_PAGER_TOP:
1834       if (topline)
1835         topline = 0;
1836       else
1837         mutt_error _("Top of message is shown.");
1838       break;
1839
1840     case OP_HALF_UP:
1841       if (topline)
1842         topline = upNLines (bodylen / 2, lineInfo, topline, hideQuoted);
1843       else
1844         mutt_error _("Top of message is shown.");
1845       break;
1846
1847     case OP_HALF_DOWN:
1848       if (lineInfo[curline].offset < sb.st_size - 1) {
1849         topline = upNLines (bodylen / 2, lineInfo, curline, hideQuoted);
1850       }
1851       else if (option (OPTPAGERSTOP)) {
1852         /* emulate "less -q" and don't go on to the next message. */
1853         mutt_error _("Bottom of message is shown.");
1854       }
1855       else {
1856         /* end of the current message, so display the next message. */
1857         rc = OP_MAIN_NEXT_UNDELETED;
1858         ch = -1;
1859       }
1860       break;
1861
1862     case OP_SEARCH_NEXT:
1863     case OP_SEARCH_OPPOSITE:
1864       if (SearchCompiled) {
1865       search_next:
1866         if ((!SearchBack && ch == OP_SEARCH_NEXT) ||
1867             (SearchBack && ch == OP_SEARCH_OPPOSITE)) {
1868           /* searching forward */
1869           for (i = topline + 1; i < lastLine; i++) {
1870             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1871                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1872               break;
1873           }
1874
1875           if (i < lastLine)
1876             topline = i;
1877           else
1878             mutt_error _("Not found.");
1879         }
1880         else {
1881           /* searching backward */
1882           for (i = topline - 1; i >= 0; i--) {
1883             if ((!hideQuoted || (has_types &&
1884                                  lineInfo[i].type != MT_COLOR_QUOTED)) &&
1885                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1886               break;
1887           }
1888
1889           if (i >= 0)
1890             topline = i;
1891           else
1892             mutt_error _("Not found.");
1893         }
1894
1895         if (lineInfo[topline].search_cnt > 0)
1896           SearchFlag = M_SEARCH;
1897
1898         break;
1899       }
1900       /* no previous search pattern, so fall through to search */
1901
1902     case OP_SEARCH:
1903     case OP_SEARCH_REVERSE:
1904       strfcpy (buffer, searchbuf, sizeof (buffer));
1905       if (mutt_get_field ((SearchBack ? _("Reverse search: ") :
1906                            _("Search: ")), buffer, sizeof (buffer),
1907                           M_CLEAR) != 0)
1908         break;
1909
1910       if (!strcmp (buffer, searchbuf)) {
1911         if (SearchCompiled) {
1912           /* do an implicit search-next */
1913           if (ch == OP_SEARCH)
1914             ch = OP_SEARCH_NEXT;
1915           else
1916             ch = OP_SEARCH_OPPOSITE;
1917
1918           goto search_next;
1919         }
1920       }
1921
1922       if (!buffer[0])
1923         break;
1924
1925       strfcpy (searchbuf, buffer, sizeof (searchbuf));
1926
1927       /* leave SearchBack alone if ch == OP_SEARCH_NEXT */
1928       if (ch == OP_SEARCH)
1929         SearchBack = 0;
1930       else if (ch == OP_SEARCH_REVERSE)
1931         SearchBack = 1;
1932
1933       if (SearchCompiled) {
1934         regfree (&SearchRE);
1935         for (i = 0; i < lastLine; i++) {
1936           if (lineInfo[i].search)
1937             p_delete(&(lineInfo[i].search));
1938           lineInfo[i].search_cnt = -1;
1939         }
1940       }
1941
1942       if ((err =
1943            REGCOMP (&SearchRE, searchbuf,
1944                     REG_NEWLINE | mutt_which_case (searchbuf))) != 0) {
1945         regerror (err, &SearchRE, buffer, sizeof (buffer));
1946         mutt_error ("%s", buffer);
1947         regfree (&SearchRE);
1948         for (i = 0; i < maxLine; i++) {
1949           /* cleanup */
1950           if (lineInfo[i].search)
1951             p_delete(&(lineInfo[i].search));
1952           lineInfo[i].search_cnt = -1;
1953         }
1954         SearchFlag = 0;
1955         SearchCompiled = 0;
1956       }
1957       else {
1958         SearchCompiled = 1;
1959         /* update the search pointers */
1960         i = 0;
1961         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
1962                              &maxLine, M_SEARCH | (flags & M_PAGER_NSKIP),
1963                              &QuoteList, &q_level,
1964                              &force_redraw, &SearchRE) == 0) {
1965           i++;
1966           redraw |= REDRAW_SIDEBAR;
1967         }
1968
1969         if (!SearchBack) {
1970           /* searching forward */
1971           for (i = topline; i < lastLine; i++) {
1972             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1973                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1974               break;
1975           }
1976
1977           if (i < lastLine)
1978             topline = i;
1979         }
1980         else {
1981           /* searching backward */
1982           for (i = topline; i >= 0; i--) {
1983             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1984                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1985               break;
1986           }
1987
1988           if (i >= 0)
1989             topline = i;
1990         }
1991
1992         if (lineInfo[topline].search_cnt == 0) {
1993           SearchFlag = 0;
1994           mutt_error _("Not found.");
1995         }
1996         else
1997           SearchFlag = M_SEARCH;
1998       }
1999       redraw = REDRAW_BODY;
2000       break;
2001
2002     case OP_SEARCH_TOGGLE:
2003       if (SearchCompiled) {
2004         SearchFlag ^= M_SEARCH;
2005         redraw = REDRAW_BODY;
2006       }
2007       break;
2008
2009     case OP_HELP:
2010       /* don't let the user enter the help-menu from the help screen! */
2011       if (!InHelp) {
2012         InHelp = 1;
2013         mutt_help (MENU_PAGER);
2014         redraw = REDRAW_FULL;
2015         InHelp = 0;
2016       }
2017       else
2018         mutt_error _("Help is currently being shown.");
2019       break;
2020
2021     case OP_PAGER_HIDE_QUOTED:
2022       if (has_types) {
2023         hideQuoted ^= M_HIDE;
2024         if (hideQuoted && lineInfo[topline].type == MT_COLOR_QUOTED)
2025           topline = upNLines (1, lineInfo, topline, hideQuoted);
2026         else
2027           redraw = REDRAW_BODY;
2028       }
2029       break;
2030
2031     case OP_PAGER_SKIP_QUOTED:
2032       if (has_types) {
2033         int dretval = 0;
2034         int new_topline = topline;
2035
2036         while ((new_topline < lastLine ||
2037                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
2038                                                new_topline, &lastLine,
2039                                                &maxLine, M_TYPES, &QuoteList,
2040                                                &q_level, &force_redraw,
2041                                                &SearchRE))))
2042                && lineInfo[new_topline].type != MT_COLOR_QUOTED) {
2043           redraw |= REDRAW_SIDEBAR;
2044           new_topline++;
2045         }
2046
2047         if (dretval < 0) {
2048           mutt_error _("No more quoted text.");
2049
2050           break;
2051         }
2052
2053         while ((new_topline < lastLine ||
2054                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
2055                                                new_topline, &lastLine,
2056                                                &maxLine, M_TYPES, &QuoteList,
2057                                                &q_level, &force_redraw,
2058                                                &SearchRE))))
2059                && lineInfo[new_topline].type == MT_COLOR_QUOTED) {
2060           new_topline++;
2061           redraw |= REDRAW_SIDEBAR;
2062         }
2063
2064         if (dretval < 0) {
2065           mutt_error _("No more unquoted text after quoted text.");
2066
2067           break;
2068         }
2069         topline = new_topline;
2070       }
2071       break;
2072
2073     case OP_PAGER_BOTTOM:      /* move to the end of the file */
2074       if (lineInfo[curline].offset < sb.st_size - 1) {
2075         i = curline;
2076         /* make sure the types are defined to the end of file */
2077         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
2078                              &maxLine, has_types,
2079                              &QuoteList, &q_level, &force_redraw,
2080                              &SearchRE) == 0) {
2081           i++;
2082           redraw |= REDRAW_SIDEBAR;
2083         }
2084         topline = upNLines (bodylen, lineInfo, lastLine, hideQuoted);
2085       }
2086       else
2087         mutt_error _("Bottom of message is shown.");
2088       break;
2089
2090     case OP_REDRAW:
2091       clearok (stdscr, TRUE);
2092       redraw = REDRAW_FULL;
2093       break;
2094
2095     case OP_NULL:
2096       km_error_key (MENU_PAGER);
2097       break;
2098
2099       /* --------------------------------------------------------------------
2100        * The following are operations on the current message rather than
2101        * adjusting the view of the message.
2102        */
2103
2104     case OP_BOUNCE_MESSAGE:
2105       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
2106         CHECK_ATTACH;
2107       if (IsMsgAttach (extra))
2108         mutt_attach_bounce (extra->fp, extra->hdr,
2109                             extra->idx, extra->idxlen, extra->bdy);
2110       else
2111         ci_bounce_message (extra->hdr, &redraw);
2112       break;
2113
2114     case OP_RESEND:
2115       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
2116         CHECK_ATTACH;
2117       if (IsMsgAttach (extra))
2118         mutt_attach_resend (extra->fp, extra->hdr,
2119                             extra->idx, extra->idxlen, extra->bdy);
2120       else
2121         mutt_resend_message (NULL, extra->ctx, extra->hdr);
2122       redraw = REDRAW_FULL;
2123       break;
2124
2125     case OP_CHECK_TRADITIONAL:
2126       CHECK_MODE (IsHeader (extra));
2127       if (!(WithCrypto & APPLICATION_PGP))
2128         break;
2129       if (!(extra->hdr->security & PGP_TRADITIONAL_CHECKED)) {
2130         ch = -1;
2131         rc = OP_CHECK_TRADITIONAL;
2132       }
2133       break;
2134
2135     case OP_CREATE_ALIAS:
2136       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2137       if (IsMsgAttach (extra))
2138         mutt_create_alias (extra->bdy->hdr->env, NULL);
2139       else
2140         mutt_create_alias (extra->hdr->env, NULL);
2141       MAYBE_REDRAW (redraw);
2142       break;
2143
2144     case OP_PURGE_MESSAGE:
2145     case OP_DELETE:
2146       CHECK_MODE (IsHeader (extra));
2147       CHECK_READONLY;
2148
2149       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
2150
2151       mutt_set_flag (Context, extra->hdr, M_DELETE, 1);
2152       mutt_set_flag (Context, extra->hdr, M_PURGED,
2153                      ch != OP_PURGE_MESSAGE ? 0 : 1);
2154       if (option (OPTDELETEUNTAG))
2155         mutt_set_flag (Context, extra->hdr, M_TAG, 0);
2156       redraw = REDRAW_STATUS | REDRAW_INDEX;
2157       if (option (OPTRESOLVE)) {
2158         ch = -1;
2159         rc = OP_MAIN_NEXT_UNDELETED;
2160       }
2161       break;
2162
2163     case OP_DELETE_THREAD:
2164     case OP_DELETE_SUBTHREAD:
2165       CHECK_MODE (IsHeader (extra));
2166       CHECK_READONLY;
2167
2168       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
2169
2170       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 1,
2171                                 ch == OP_DELETE_THREAD ? 0 : 1);
2172
2173       if (r != -1) {
2174         if (option (OPTDELETEUNTAG))
2175           mutt_thread_set_flag (extra->hdr, M_TAG, 0,
2176                                 ch == OP_DELETE_THREAD ? 0 : 1);
2177         if (option (OPTRESOLVE)) {
2178           rc = OP_MAIN_NEXT_UNDELETED;
2179           ch = -1;
2180         }
2181
2182         if (!option (OPTRESOLVE) && PagerIndexLines)
2183           redraw = REDRAW_FULL;
2184         else
2185           redraw = REDRAW_STATUS | REDRAW_INDEX;
2186       }
2187       break;
2188
2189     case OP_DISPLAY_ADDRESS:
2190       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2191       if (IsMsgAttach (extra))
2192         mutt_display_address (extra->bdy->hdr->env);
2193       else
2194         mutt_display_address (extra->hdr->env);
2195       break;
2196
2197     case OP_ENTER_COMMAND:
2198       old_smart_wrap = option (OPTWRAP);
2199       old_markers = option (OPTMARKERS);
2200       old_PagerIndexLines = PagerIndexLines;
2201
2202       CurrentMenu = MENU_PAGER;
2203       mutt_enter_command ();
2204
2205       if (option (OPTNEEDRESORT)) {
2206         unset_option (OPTNEEDRESORT);
2207         CHECK_MODE (IsHeader (extra));
2208         set_option (OPTNEEDRESORT);
2209       }
2210
2211       if (old_PagerIndexLines != PagerIndexLines) {
2212         if (index)
2213           mutt_menuDestroy (&index);
2214         index = NULL;
2215       }
2216
2217       if (option (OPTWRAP) != old_smart_wrap ||
2218           option (OPTMARKERS) != old_markers) {
2219         if (flags & M_PAGER_RETWINCH) {
2220           ch = -1;
2221           rc = OP_REFORMAT_WINCH;
2222           continue;
2223         }
2224
2225         /* count the real lines above */
2226         j = 0;
2227         for (i = 0; i <= topline; i++) {
2228           if (!lineInfo[i].continuation)
2229             j++;
2230         }
2231
2232         /* we need to restart the whole thing */
2233         for (i = 0; i < maxLine; i++) {
2234           lineInfo[i].offset = 0;
2235           lineInfo[i].type = -1;
2236           lineInfo[i].continuation = 0;
2237           lineInfo[i].chunks = 0;
2238           lineInfo[i].search_cnt = -1;
2239           lineInfo[i].quote = NULL;
2240
2241           mem_realloc (&(lineInfo[i].syntax), sizeof (struct syntax_t));
2242           if (SearchCompiled && lineInfo[i].search)
2243             p_delete(&(lineInfo[i].search));
2244         }
2245
2246         if (SearchCompiled) {
2247           regfree (&SearchRE);
2248           SearchCompiled = 0;
2249         }
2250         SearchFlag = 0;
2251
2252         /* try to keep the old position */
2253         topline = 0;
2254         lastLine = 0;
2255         while (j > 0 && display_line (fp, &last_pos, &lineInfo, topline,
2256                                       &lastLine, &maxLine,
2257                                       (has_types ? M_TYPES : 0),
2258                                       &QuoteList, &q_level, &force_redraw,
2259                                       &SearchRE) == 0) {
2260           redraw |= REDRAW_SIDEBAR;
2261           if (!lineInfo[topline].continuation)
2262             j--;
2263           if (j > 0)
2264             topline++;
2265         }
2266
2267         ch = 0;
2268       }
2269
2270       if (option (OPTFORCEREDRAWPAGER))
2271         redraw = REDRAW_FULL;
2272       unset_option (OPTFORCEREDRAWINDEX);
2273       unset_option (OPTFORCEREDRAWPAGER);
2274       break;
2275
2276     case OP_FLAG_MESSAGE:
2277       CHECK_MODE (IsHeader (extra));
2278       CHECK_READONLY;
2279
2280       CHECK_MX_ACL (Context, ACL_WRITE, _("Flagging"));
2281
2282       mutt_set_flag (Context, extra->hdr, M_FLAG, !extra->hdr->flagged);
2283       redraw = REDRAW_STATUS | REDRAW_INDEX;
2284       if (option (OPTRESOLVE)) {
2285         ch = -1;
2286         rc = OP_MAIN_NEXT_UNDELETED;
2287       }
2288       break;
2289
2290     case OP_PIPE:
2291       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2292       if (IsAttach (extra))
2293         mutt_pipe_attachment_list (extra->fp, 0, extra->bdy, 0);
2294       else
2295         mutt_pipe_message (extra->hdr);
2296       MAYBE_REDRAW (redraw);
2297       break;
2298
2299     case OP_PRINT:
2300       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2301       if (IsAttach (extra))
2302         mutt_print_attachment_list (extra->fp, 0, extra->bdy);
2303       else
2304         mutt_print_message (extra->hdr);
2305       break;
2306
2307     case OP_MAIL:
2308       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2309       CHECK_ATTACH;
2310       ci_send_message (0, NULL, NULL, extra->ctx, NULL);
2311       redraw = REDRAW_FULL;
2312       break;
2313
2314 #ifdef USE_NNTP
2315     case OP_POST:
2316       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2317       CHECK_ATTACH;
2318       if (extra->ctx && extra->ctx->magic == M_NNTP &&
2319           !((NNTP_DATA *) extra->ctx->data)->allowed &&
2320           query_quadoption (OPT_TOMODERATED,
2321                             _
2322                             ("Posting to this group not allowed, may be moderated. Continue?"))
2323           != M_YES)
2324         break;
2325       ci_send_message (SENDNEWS, NULL, NULL, extra->ctx, NULL);
2326       redraw = REDRAW_FULL;
2327       break;
2328
2329     case OP_FORWARD_TO_GROUP:
2330       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2331       CHECK_ATTACH;
2332       if (extra->ctx && extra->ctx->magic == M_NNTP &&
2333           !((NNTP_DATA *) extra->ctx->data)->allowed &&
2334           query_quadoption (OPT_TOMODERATED,
2335                             _
2336                             ("Posting to this group not allowed, may be moderated. Continue?"))
2337           != M_YES)
2338         break;
2339       if (IsMsgAttach (extra))
2340         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2341                              extra->idxlen, extra->bdy, SENDNEWS);
2342       else
2343         ci_send_message (SENDNEWS | SENDFORWARD, NULL, NULL, extra->ctx,
2344                          extra->hdr);
2345       redraw = REDRAW_FULL;
2346       break;
2347
2348     case OP_FOLLOWUP:
2349       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2350       CHECK_ATTACH;
2351
2352       if (IsMsgAttach (extra))
2353         followup_to = extra->bdy->hdr->env->followup_to;
2354       else
2355         followup_to = extra->hdr->env->followup_to;
2356
2357       if (!followup_to || str_casecmp (followup_to, "poster") ||
2358           query_quadoption (OPT_FOLLOWUPTOPOSTER,
2359                             _("Reply by mail as poster prefers?")) != M_YES) {
2360         if (extra->ctx && extra->ctx->magic == M_NNTP
2361             && !((NNTP_DATA *) extra->ctx->data)->allowed
2362             && query_quadoption (OPT_TOMODERATED,
2363                                  _
2364                                  ("Posting to this group not allowed, may be moderated. Continue?"))
2365             != M_YES)
2366           break;
2367         if (IsMsgAttach (extra))
2368           mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2369                              extra->idxlen, extra->bdy, SENDNEWS | SENDREPLY);
2370         else
2371           ci_send_message (SENDNEWS | SENDREPLY, NULL, NULL,
2372                            extra->ctx, extra->hdr);
2373         redraw = REDRAW_FULL;
2374         break;
2375       }
2376 #endif
2377
2378     case OP_REPLY:
2379       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2380       CHECK_ATTACH;
2381       if (IsMsgAttach (extra))
2382         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2383                            extra->idxlen, extra->bdy, SENDREPLY);
2384       else
2385         ci_send_message (SENDREPLY, NULL, NULL, extra->ctx, extra->hdr);
2386       redraw = REDRAW_FULL;
2387       break;
2388
2389     case OP_RECALL_MESSAGE:
2390       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2391       CHECK_ATTACH;
2392       ci_send_message (SENDPOSTPONED, NULL, NULL, extra->ctx, extra->hdr);
2393       redraw = REDRAW_FULL;
2394       break;
2395
2396     case OP_GROUP_REPLY:
2397       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2398       CHECK_ATTACH;
2399       if (IsMsgAttach (extra))
2400         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2401                            extra->idxlen, extra->bdy,
2402                            SENDREPLY | SENDGROUPREPLY);
2403       else
2404         ci_send_message (SENDREPLY | SENDGROUPREPLY, NULL, NULL, extra->ctx,
2405                          extra->hdr);
2406       redraw = REDRAW_FULL;
2407       break;
2408
2409     case OP_LIST_REPLY:
2410       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2411       CHECK_ATTACH;
2412       if (IsMsgAttach (extra))
2413         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2414                            extra->idxlen, extra->bdy,
2415                            SENDREPLY | SENDLISTREPLY);
2416       else
2417         ci_send_message (SENDREPLY | SENDLISTREPLY, NULL, NULL, extra->ctx,
2418                          extra->hdr);
2419       redraw = REDRAW_FULL;
2420       break;
2421
2422     case OP_FORWARD_MESSAGE:
2423       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2424       CHECK_ATTACH;
2425       if (IsMsgAttach (extra))
2426         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2427                              extra->idxlen, extra->bdy, 0);
2428       else
2429         ci_send_message (SENDFORWARD, NULL, NULL, extra->ctx, extra->hdr);
2430       redraw = REDRAW_FULL;
2431       break;
2432
2433     case OP_DECRYPT_SAVE:
2434       if (!WithCrypto) {
2435         ch = -1;
2436         break;
2437       }
2438       /* fall through */
2439     case OP_SAVE:
2440       if (IsAttach (extra)) {
2441         mutt_save_attachment_list (extra->fp, 0, extra->bdy, extra->hdr,
2442                                    NULL);
2443         break;
2444       }
2445       /* fall through */
2446     case OP_COPY_MESSAGE:
2447     case OP_DECODE_SAVE:
2448     case OP_DECODE_COPY:
2449     case OP_DECRYPT_COPY:
2450       if (!WithCrypto && ch == OP_DECRYPT_COPY) {
2451         ch = -1;
2452         break;
2453       }
2454       CHECK_MODE (IsHeader (extra));
2455       if (mutt_save_message (extra->hdr,
2456                              (ch == OP_DECRYPT_SAVE) ||
2457                              (ch == OP_SAVE) || (ch == OP_DECODE_SAVE),
2458                              (ch == OP_DECODE_SAVE) || (ch == OP_DECODE_COPY),
2459                              (ch == OP_DECRYPT_SAVE)
2460                              || (ch == OP_DECRYPT_COPY) || 0, &redraw) == 0
2461           && (ch == OP_SAVE || ch == OP_DECODE_SAVE
2462               || ch == OP_DECRYPT_SAVE)) {
2463         if (option (OPTRESOLVE)) {
2464           ch = -1;
2465           rc = OP_MAIN_NEXT_UNDELETED;
2466         }
2467         else
2468           redraw |= REDRAW_STATUS | REDRAW_INDEX;
2469       }
2470       MAYBE_REDRAW (redraw);
2471       break;
2472
2473     case OP_SHELL_ESCAPE:
2474       mutt_shell_escape ();
2475       MAYBE_REDRAW (redraw);
2476       break;
2477
2478     case OP_TAG:
2479       CHECK_MODE (IsHeader (extra));
2480       mutt_set_flag (Context, extra->hdr, M_TAG, !extra->hdr->tagged);
2481
2482       Context->last_tag = extra->hdr->tagged ? extra->hdr :
2483         ((Context->last_tag == extra->hdr && !extra->hdr->tagged)
2484          ? NULL : Context->last_tag);
2485
2486       redraw = REDRAW_STATUS | REDRAW_INDEX;
2487       if (option (OPTRESOLVE)) {
2488         ch = -1;
2489         rc = OP_NEXT_ENTRY;
2490       }
2491       break;
2492
2493     case OP_TOGGLE_NEW:
2494       CHECK_MODE (IsHeader (extra));
2495       CHECK_READONLY;
2496
2497       CHECK_MX_ACL (Context, ACL_SEEN, _("Toggling"));
2498
2499       if (extra->hdr->read || extra->hdr->old)
2500         mutt_set_flag (Context, extra->hdr, M_NEW, 1);
2501       else if (!first)
2502         mutt_set_flag (Context, extra->hdr, M_READ, 1);
2503       first = 0;
2504       Context->msgnotreadyet = -1;
2505       redraw = REDRAW_STATUS | REDRAW_INDEX;
2506       if (option (OPTRESOLVE)) {
2507         ch = -1;
2508         rc = OP_MAIN_NEXT_UNDELETED;
2509       }
2510       break;
2511
2512     case OP_UNDELETE:
2513       CHECK_MODE (IsHeader (extra));
2514       CHECK_READONLY;
2515
2516       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2517
2518       mutt_set_flag (Context, extra->hdr, M_DELETE, 0);
2519       mutt_set_flag (Context, extra->hdr, M_PURGED, 0);
2520       redraw = REDRAW_STATUS | REDRAW_INDEX;
2521       if (option (OPTRESOLVE)) {
2522         ch = -1;
2523         rc = OP_NEXT_ENTRY;
2524       }
2525       break;
2526
2527     case OP_UNDELETE_THREAD:
2528     case OP_UNDELETE_SUBTHREAD:
2529       CHECK_MODE (IsHeader (extra));
2530       CHECK_READONLY;
2531
2532       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2533
2534       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 0,
2535                                 ch == OP_UNDELETE_THREAD ? 0 : 1)
2536         + mutt_thread_set_flag (extra->hdr, M_PURGED, 0,
2537                                 ch == OP_UNDELETE_THREAD ? 0 : 1);
2538
2539       if (r > -1) {
2540         if (option (OPTRESOLVE)) {
2541           rc = (ch == OP_DELETE_THREAD) ?
2542             OP_MAIN_NEXT_THREAD : OP_MAIN_NEXT_SUBTHREAD;
2543           ch = -1;
2544         }
2545
2546         if (!option (OPTRESOLVE) && PagerIndexLines)
2547           redraw = REDRAW_FULL;
2548         else
2549           redraw = REDRAW_STATUS | REDRAW_INDEX;
2550       }
2551       break;
2552
2553     case OP_VERSION:
2554       mutt_version ();
2555       break;
2556
2557     case OP_BUFFY_LIST:
2558       if (option (OPTFORCEBUFFYCHECK))
2559         buffy_check (1);
2560       buffy_list ();
2561       redraw |= REDRAW_SIDEBAR;
2562       break;
2563
2564     case OP_VIEW_ATTACHMENTS:
2565       if (flags & M_PAGER_ATTACHMENT) {
2566         ch = -1;
2567         rc = OP_ATTACH_COLLAPSE;
2568         break;
2569       }
2570       CHECK_MODE (IsHeader (extra));
2571       mutt_view_attachments (extra->hdr);
2572       if (extra->hdr->attach_del)
2573         Context->changed = 1;
2574       redraw = REDRAW_FULL;
2575       break;
2576
2577
2578     case OP_MAIL_KEY:
2579       if (!(WithCrypto & APPLICATION_PGP)) {
2580         ch = -1;
2581         break;
2582       }
2583       CHECK_MODE (IsHeader (extra));
2584       CHECK_ATTACH;
2585       ci_send_message (SENDKEY, NULL, NULL, extra->ctx, extra->hdr);
2586       redraw = REDRAW_FULL;
2587       break;
2588
2589
2590     case OP_FORGET_PASSPHRASE:
2591       crypt_forget_passphrase ();
2592       break;
2593
2594     case OP_EXTRACT_KEYS:
2595       if (!WithCrypto) {
2596         ch = -1;
2597         break;
2598       }
2599       CHECK_MODE (IsHeader (extra));
2600       crypt_extract_keys_from_messages (extra->hdr);
2601       redraw = REDRAW_FULL;
2602       break;
2603
2604     case OP_SIDEBAR_SCROLL_UP:
2605     case OP_SIDEBAR_SCROLL_DOWN:
2606     case OP_SIDEBAR_NEXT:
2607     case OP_SIDEBAR_NEXT_NEW:
2608     case OP_SIDEBAR_PREV:
2609     case OP_SIDEBAR_PREV_NEW:
2610       sidebar_scroll (ch, MENU_PAGER);
2611       break;
2612     default:
2613       ch = -1;
2614       break;
2615     }
2616   }
2617
2618   fclose (fp);
2619   if (IsHeader (extra)) {
2620     Context->msgnotreadyet = -1;
2621     if (rc == -1)
2622       OldHdr = NULL;
2623     else {
2624       TopLine = topline;
2625       OldHdr = extra->hdr;
2626     }
2627   }
2628
2629   cleanup_quote (&QuoteList);
2630
2631   for (i = 0; i < maxLine; i++) {
2632     p_delete(&(lineInfo[i].syntax));
2633     if (SearchCompiled && lineInfo[i].search)
2634       p_delete(&(lineInfo[i].search));
2635   }
2636   if (SearchCompiled) {
2637     regfree (&SearchRE);
2638     SearchCompiled = 0;
2639   }
2640   p_delete(&lineInfo);
2641   if (index)
2642     mutt_menuDestroy (&index);
2643   return (rc != -1 ? rc : 0);
2644 }