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