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