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