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