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