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