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