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