Remove useless imap_cmd_running()
[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
21 #include "mutt.h"
22 #include "alias.h"
23 #include "keymap.h"
24 #include "sort.h"
25 #include "pager.h"
26 #include "attach.h"
27 #include "recvattach.h"
28 #include "charset.h"
29 #include "buffy.h"
30
31 #include "mx.h"
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 "mx.h"
941 #include "nntp.h"
942 #endif
943
944
945 static int format_line (struct line_t **lineInfo, int n, unsigned char *buf,
946                         int flags, ansi_attr * pa, int cnt,
947                         int *pspace, int *pvch, int *pcol, int *pspecial)
948 {
949   int space = -1;               /* index of the last space or TAB */
950   int col = option (OPTMARKERS) ? (*lineInfo)[n].continuation : 0;
951   int ch, vch, k, last_special = -1, special = 0, t;
952   wchar_t wc;
953   mbstate_t mbstate;
954
955   int wrap_cols = COLS;
956
957   if (!(flags & (M_SHOWFLAT)))
958     wrap_cols -= WrapMargin;
959   wrap_cols -= SW;
960
961   if (wrap_cols <= 0)
962     wrap_cols = COLS;
963
964   /* FIXME: this should come from lineInfo */
965   p_clear(&mbstate, 1);
966
967   for (ch = 0, vch = 0; ch < cnt; ch += k, vch += k) {
968     /* Handle ANSI sequences */
969     while (cnt - ch >= 2 && buf[ch] == '\033' && buf[ch + 1] == '[' &&
970            is_ansi (buf + ch + 2))
971       ch = grok_ansi (buf, ch + 2, pa) + 1;
972
973     while (cnt - ch >= 2 && buf[ch] == '\033' && buf[ch + 1] == ']' &&
974            check_attachment_marker ((char *) buf + ch) == 0) {
975       while (buf[ch++] != '\a')
976         if (ch >= cnt)
977           break;
978     }
979
980     /* is anything left to do? */
981     if (ch >= cnt)
982       break;
983
984     k = mbrtowc (&wc, (char *) buf + ch, cnt - ch, &mbstate);
985     if (k == -2 || k == -1) {
986       if (col + 4 > wrap_cols)
987         break;
988       col += 4;
989       if (pa)
990         printw ("\\%03o", buf[ch]);
991       k = 1;
992       continue;
993     }
994     if (k == 0)
995       k = 1;
996
997     /* Handle backspace */
998     special = 0;
999     if (iswprint(wc)) {
1000       wchar_t wc1;
1001       mbstate_t mbstate1;
1002       int k1, k2;
1003
1004       while ((wc1 = 0, mbstate1 = mbstate,
1005               k1 =
1006               k + mbrtowc (&wc1, (char *) buf + ch + k, cnt - ch - k,
1007                            &mbstate1), k1 - k > 0 && wc1 == '\b')
1008              && (wc1 = 0, k2 =
1009                  mbrtowc (&wc1, (char *) buf + ch + k1, cnt - ch - k1,
1010                           &mbstate1), k2 > 0 && iswprint(wc1))) {
1011         if (wc == wc1) {
1012           special |= (wc == '_' && special & A_UNDERLINE)
1013             ? A_UNDERLINE : A_BOLD;
1014         }
1015         else if (wc == '_' || wc1 == '_') {
1016           special |= A_UNDERLINE;
1017           wc = (wc1 == '_') ? wc : wc1;
1018         }
1019         else {
1020           /* special = 0; / * overstrike: nothing to do! */
1021           wc = wc1;
1022         }
1023         ch += k1;
1024         k = k2;
1025         mbstate = mbstate1;
1026       }
1027     }
1028
1029     if (pa &&
1030         ((flags & (M_SHOWCOLOR | M_SEARCH | M_PAGER_MARKER)) ||
1031          special || last_special || pa->attr)) {
1032       resolve_color (*lineInfo, n, vch, flags, special, pa);
1033       last_special = special;
1034     }
1035
1036     if (iswprint(wc)) {
1037       if (wc == ' ')
1038         space = ch;
1039       t = wcwidth (wc);
1040       if (col + t > wrap_cols)
1041         break;
1042       col += t;
1043       if (pa)
1044         mutt_addwch (wc);
1045     }
1046     else if (wc == '\n')
1047       break;
1048     else if (wc == '\t') {
1049       space = ch;
1050       t = (col & ~7) + 8;
1051       if (t > wrap_cols)
1052         break;
1053       if (pa)
1054         for (; col < t; col++)
1055           addch (' ');
1056       else
1057         col = t;
1058     }
1059     else if (wc < 0x20 || wc == 0x7f) {
1060       if (col + 2 > wrap_cols)
1061         break;
1062       col += 2;
1063       if (pa)
1064         printw ("^%c", ('@' + wc) & 0x7f);
1065     }
1066     else if (wc < 0x100) {
1067       if (col + 4 > wrap_cols)
1068         break;
1069       col += 4;
1070       if (pa)
1071         printw ("\\%03o", wc);
1072     }
1073     else {
1074       if (col + 1 > wrap_cols)
1075         break;
1076       ++col;
1077       if (pa)
1078         addch (CharsetReplacement);
1079     }
1080   }
1081   *pspace = space;
1082   *pcol = col;
1083   *pvch = vch;
1084   *pspecial = special;
1085   return ch;
1086 }
1087
1088 /*
1089  * Args:
1090  *      flags   M_SHOWFLAT, show characters (used for displaying help)
1091  *              M_SHOWCOLOR, show characters in color
1092  *                      otherwise don't show characters
1093  *              M_HIDE, don't show quoted text
1094  *              M_SEARCH, resolve search patterns
1095  *              M_TYPES, compute line's type
1096  *              M_PAGER_NSKIP, keeps leading whitespace
1097  *              M_PAGER_MARKER, eventually show markers
1098  *
1099  * Return values:
1100  *      -1      EOF was reached
1101  *      0       normal exit, line was not displayed
1102  *      >0      normal exit, line was displayed
1103  */
1104
1105 static int
1106 display_line (FILE * f, off_t *last_pos, struct line_t **lineInfo, int n,
1107               int *last, int *max, int flags, struct q_class_t **QuoteList,
1108               int *q_level, int *force_redraw, regex_t * SearchRE)
1109 {
1110   unsigned char buf[LONG_STRING], fmt[LONG_STRING];
1111   unsigned char *buf_ptr = buf;
1112   int ch, vch, col, cnt, b_read;
1113   int buf_ready = 0, change_last = 0;
1114   int special;
1115   int offset;
1116   int def_color;
1117   int m;
1118   ansi_attr a = { 0, 0, 0, -1 };
1119   regmatch_t pmatch[1];
1120
1121   if (n == *last) {
1122     (*last)++;
1123     change_last = 1;
1124   }
1125
1126   if (*last == *max) {
1127     p_realloc(lineInfo, *max += LINES);
1128     for (ch = *last; ch < *max; ch++) {
1129       p_clear(&(*lineInfo)[ch], 1);
1130       (*lineInfo)[ch].type = -1;
1131       (*lineInfo)[ch].search_cnt = -1;
1132       (*lineInfo)[ch].syntax = p_new(struct syntax_t, 1);
1133       ((*lineInfo)[ch].syntax)[0].first = ((*lineInfo)[ch].syntax)[0].last =
1134         -1;
1135     }
1136   }
1137
1138   /* only do color hiliting if we are viewing a message */
1139   if (flags & (M_SHOWCOLOR | M_TYPES)) {
1140     if ((*lineInfo)[n].type == -1) {
1141       /* determine the line class */
1142       if (fill_buffer
1143           (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1144            &buf_ready) < 0) {
1145         if (change_last)
1146           (*last)--;
1147         return (-1);
1148       }
1149
1150       resolve_types ((char *) fmt, (char *) buf, *lineInfo, n, *last,
1151                      QuoteList, q_level, force_redraw, flags & M_SHOWCOLOR);
1152
1153       /* avoid race condition for continuation lines when scrolling up */
1154       for (m = n + 1;
1155            m < *last && (*lineInfo)[m].offset && (*lineInfo)[m].continuation;
1156            m++)
1157         (*lineInfo)[m].type = (*lineInfo)[n].type;
1158     }
1159
1160     /* this also prevents searching through the hidden lines */
1161     if ((flags & M_HIDE) && (*lineInfo)[n].type == MT_COLOR_QUOTED)
1162       flags = 0;                /* M_NOSHOW */
1163   }
1164
1165   /* At this point, (*lineInfo[n]).quote may still be undefined. We 
1166    * don't want to compute it every time M_TYPES is set, since this
1167    * would slow down the "bottom" function unacceptably. A compromise
1168    * solution is hence to call regexec() again, just to find out the
1169    * length of the quote prefix.
1170    */
1171   if ((flags & M_SHOWCOLOR) && !(*lineInfo)[n].continuation &&
1172       (*lineInfo)[n].type == MT_COLOR_QUOTED && (*lineInfo)[n].quote == NULL)
1173   {
1174     if (fill_buffer
1175         (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1176          &buf_ready) < 0) {
1177       if (change_last)
1178         (*last)--;
1179       return (-1);
1180     }
1181     regexec ((regex_t *) QuoteRegexp.rx, (char *) fmt, 1, pmatch, 0);
1182     (*lineInfo)[n].quote = classify_quote (QuoteList,
1183                                            (char *) fmt + pmatch[0].rm_so,
1184                                            pmatch[0].rm_eo - pmatch[0].rm_so,
1185                                            force_redraw, q_level);
1186   }
1187
1188   if ((flags & M_SEARCH) && !(*lineInfo)[n].continuation
1189       && (*lineInfo)[n].search_cnt == -1) {
1190     if (fill_buffer
1191         (f, last_pos, (*lineInfo)[n].offset, buf, fmt, sizeof (buf),
1192          &buf_ready) < 0) {
1193       if (change_last)
1194         (*last)--;
1195       return (-1);
1196     }
1197
1198     offset = 0;
1199     (*lineInfo)[n].search_cnt = 0;
1200     while (regexec
1201            (SearchRE, (char *) fmt + offset, 1, pmatch,
1202             (offset ? REG_NOTBOL : 0)) == 0) {
1203       if (++((*lineInfo)[n].search_cnt) > 1)
1204         p_realloc(&(*lineInfo)[n].search, (*lineInfo)[n].search_cnt);
1205       else
1206         (*lineInfo)[n].search = p_new(struct syntax_t, 1);
1207       pmatch[0].rm_so += offset;
1208       pmatch[0].rm_eo += offset;
1209       ((*lineInfo)[n].search)[(*lineInfo)[n].search_cnt - 1].first =
1210         pmatch[0].rm_so;
1211       ((*lineInfo)[n].search)[(*lineInfo)[n].search_cnt - 1].last =
1212         pmatch[0].rm_eo;
1213
1214       if (pmatch[0].rm_eo == pmatch[0].rm_so)
1215         offset++;               /* avoid degenerate cases */
1216       else
1217         offset = pmatch[0].rm_eo;
1218       if (!fmt[offset])
1219         break;
1220     }
1221   }
1222
1223   if (!(flags & M_SHOW) && (*lineInfo)[n + 1].offset > 0) {
1224     /* we've already scanned this line, so just exit */
1225     return (0);
1226   }
1227   if ((flags & M_SHOWCOLOR) && *force_redraw && (*lineInfo)[n + 1].offset > 0) {
1228     /* no need to try to display this line... */
1229     return (1);                 /* fake display */
1230   }
1231
1232   if ((b_read = fill_buffer (f, last_pos, (*lineInfo)[n].offset, buf, fmt,
1233                              sizeof (buf), &buf_ready)) < 0) {
1234     if (change_last)
1235       (*last)--;
1236     return (-1);
1237   }
1238
1239   /* now chose a good place to break the line */
1240   cnt =
1241     format_line (lineInfo, n, buf, flags, 0, b_read, &ch, &vch, &col,
1242                  &special);
1243   buf_ptr = buf + cnt;
1244
1245   /* move the break point only if smart_wrap is set */
1246   if (option (OPTWRAP)) {
1247     if (cnt < b_read) {
1248       if (ch != -1 && buf[cnt] != ' ' && buf[cnt] != '\t' && buf[cnt] != '\n'
1249           && buf[cnt] != '\r') {
1250         buf_ptr = buf + ch;
1251         /* skip trailing blanks */
1252         while (ch && (buf[ch] == ' ' || buf[ch] == '\t' || buf[ch] == '\r'))
1253           ch--;
1254         /* a very long word with leading spaces causes infinite wrapping */
1255         if ((!ch) && (flags & M_PAGER_NSKIP))
1256           buf_ptr = buf + cnt;
1257         else
1258           cnt = ch + 1;
1259       }
1260       else
1261         buf_ptr = buf + cnt;    /* a very long word... */
1262     }
1263     if (!(flags & M_PAGER_NSKIP))
1264       /* skip leading blanks on the next line too */
1265       while (*buf_ptr == ' ' || *buf_ptr == '\t')
1266         buf_ptr++;
1267   }
1268
1269   if (*buf_ptr == '\r')
1270     buf_ptr++;
1271   if (*buf_ptr == '\n')
1272     buf_ptr++;
1273
1274   if ((int) (buf_ptr - buf) < b_read && !(*lineInfo)[n + 1].continuation)
1275     append_line (*lineInfo, n, (int) (buf_ptr - buf));
1276   (*lineInfo)[n + 1].offset = (*lineInfo)[n].offset + (long) (buf_ptr - buf);
1277
1278   /* if we don't need to display the line we are done */
1279   if (!(flags & M_SHOW))
1280     return 0;
1281
1282   /* display the line */
1283   format_line (lineInfo, n, buf, flags, &a, cnt, &ch, &vch, &col, &special);
1284
1285   /* avoid a bug in ncurses... */
1286 #ifndef USE_SLANG_CURSES
1287   if (col == 0) {
1288     SETCOLOR (MT_COLOR_NORMAL);
1289     addch (' ');
1290   }
1291 #endif
1292
1293   /* end the last color pattern (needed by S-Lang) */
1294   if (special || (col != COLS && (flags & (M_SHOWCOLOR | M_SEARCH))))
1295     resolve_color (*lineInfo, n, vch, flags, 0, &a);
1296
1297   /*
1298    * Fill the blank space at the end of the line with the prevailing color.
1299    * ncurses does an implicit clrtoeol() when you do addch('\n') so we have
1300    * to make sure to reset the color *after* that
1301    */
1302   if (flags & M_SHOWCOLOR) {
1303     m = ((*lineInfo)[n].continuation) ? ((*lineInfo)[n].syntax)[0].first : n;
1304     if ((*lineInfo)[m].type == MT_COLOR_HEADER)
1305       def_color = ((*lineInfo)[m].syntax)[0].color;
1306     else
1307       def_color = ColorDefs[(*lineInfo)[m].type];
1308
1309     attrset (def_color);
1310 #ifdef HAVE_BKGDSET
1311     bkgdset (def_color | ' ');
1312 #endif
1313   }
1314
1315   /* ncurses always wraps lines when you get to the right side of the
1316    * screen, but S-Lang seems to only wrap if the next character is *not*
1317    * a newline (grr!).
1318    */
1319 #ifndef USE_SLANG_CURSES
1320   if (col < COLS)
1321 #endif
1322     addch ('\n');
1323
1324   /*
1325    * reset the color back to normal.  This *must* come after the
1326    * addch('\n'), otherwise the color for this line will not be
1327    * filled to the right margin.
1328    */
1329   if (flags & M_SHOWCOLOR) {
1330     SETCOLOR (MT_COLOR_NORMAL);
1331     BKGDSET (MT_COLOR_NORMAL);
1332   }
1333
1334   /* build a return code */
1335   if (!(flags & M_SHOW))
1336     flags = 0;
1337
1338   return (flags);
1339 }
1340
1341 static int upNLines (int nlines, struct line_t *info, int cur, int hiding)
1342 {
1343   while (cur > 0 && nlines > 0) {
1344     cur--;
1345     if (!hiding || info[cur].type != MT_COLOR_QUOTED)
1346       nlines--;
1347   }
1348
1349   return cur;
1350 }
1351
1352 static struct mapping_t PagerHelp[] = {
1353   {N_("Exit"), OP_EXIT},
1354   {N_("PrevPg"), OP_PREV_PAGE},
1355   {N_("NextPg"), OP_NEXT_PAGE},
1356   {NULL, 0}
1357 };
1358 static struct mapping_t PagerHelpExtra[] = {
1359   {N_("View Attachm."), OP_VIEW_ATTACHMENTS},
1360   {N_("Del"), OP_DELETE},
1361   {N_("Reply"), OP_REPLY},
1362   {N_("Next"), OP_MAIN_NEXT_UNDELETED},
1363   {NULL, 0}
1364 };
1365
1366 #ifdef USE_NNTP
1367 static struct mapping_t PagerNewsHelpExtra[] = {
1368   {N_("Post"), OP_POST},
1369   {N_("Followup"), OP_FOLLOWUP},
1370   {N_("Del"), OP_DELETE},
1371   {N_("Next"), OP_MAIN_NEXT_UNDELETED},
1372   {NULL, 0}
1373 };
1374 #endif
1375
1376
1377
1378 /* This pager is actually not so simple as it once was.  It now operates in
1379    two modes: one for viewing messages and the other for viewing help.  These
1380    can be distinguished by whether or not ``hdr'' is NULL.  The ``hdr'' arg
1381    is there so that we can do operations on the current message without the
1382    need to pop back out to the main-menu.  */
1383 int
1384 mutt_pager (const char *banner, const char *fname, int flags, pager_t * extra)
1385 {
1386   static char searchbuf[STRING];
1387   char buffer[LONG_STRING];
1388   char helpstr[SHORT_STRING * 2];
1389   char tmphelp[SHORT_STRING * 2];
1390   int maxLine, lastLine = 0;
1391   struct line_t *lineInfo;
1392   struct q_class_t *QuoteList = NULL;
1393   int i, j, ch = 0, rc = -1, hideQuoted = 0, q_level = 0, force_redraw = 0;
1394   int lines = 0, curline = 0, topline = 0, oldtopline = 0, err, first = 1;
1395   int r = -1;
1396   int redraw = REDRAW_FULL;
1397   FILE *fp = NULL;
1398   off_t last_pos = 0, last_offset = 0;
1399   int old_smart_wrap, old_markers;
1400   struct stat sb;
1401   regex_t SearchRE;
1402   int SearchCompiled = 0, SearchFlag = 0, SearchBack = 0;
1403   int has_types = (IsHeader (extra) || (flags & M_SHOWCOLOR)) ? M_TYPES : 0;    /* main message or rfc822 attachment */
1404
1405   int bodyoffset = 1;           /* offset of first line of real text */
1406   int statusoffset = 0;         /* offset for the status bar */
1407   int helpoffset = LINES - 2;   /* offset for the help bar. */
1408   int bodylen = LINES - 2 - bodyoffset; /* length of displayable area */
1409
1410   MUTTMENU *pager_index = NULL;       /* the Pager Index (PI) */
1411   int indexoffset = 0;          /* offset for the PI */
1412   int indexlen = PagerIndexLines;       /* indexlen not always == PIL */
1413   int indicator = indexlen / 3; /* the indicator line of the PI */
1414   int old_PagerIndexLines;      /* some people want to resize it
1415                                  * while inside the pager... */
1416
1417 #ifdef USE_NNTP
1418   char *followup_to;
1419 #endif
1420
1421   if (!(flags & M_SHOWCOLOR))
1422     flags |= M_SHOWFLAT;
1423
1424   if ((fp = fopen (fname, "r")) == NULL) {
1425     mutt_perror (fname);
1426     return (-1);
1427   }
1428
1429   if (stat (fname, &sb) != 0) {
1430     mutt_perror (fname);
1431     fclose (fp);
1432     return (-1);
1433   }
1434   unlink (fname);
1435
1436   /* Initialize variables */
1437
1438   if (IsHeader (extra) && !extra->hdr->read) {
1439     Context->msgnotreadyet = extra->hdr->msgno;
1440     mutt_set_flag (Context, extra->hdr, M_READ, 1);
1441   }
1442
1443   lineInfo = p_new(struct line_t, maxLine = LINES);
1444   for (i = 0; i < maxLine; i++) {
1445     p_clear(&lineInfo[i], 1);
1446     lineInfo[i].type = -1;
1447     lineInfo[i].search_cnt = -1;
1448     lineInfo[i].syntax = p_new(struct syntax_t, 1);
1449     (lineInfo[i].syntax)[0].first = (lineInfo[i].syntax)[0].last = -1;
1450   }
1451
1452   mutt_compile_help (helpstr, sizeof (helpstr), MENU_PAGER, PagerHelp);
1453   if (IsHeader (extra)) {
1454     m_strcpy(tmphelp, sizeof(tmphelp), helpstr);
1455     mutt_compile_help (buffer, sizeof (buffer), MENU_PAGER,
1456 #ifdef USE_NNTP
1457                        (Context
1458                         && (Context->magic == M_NNTP)) ? PagerNewsHelpExtra :
1459 #endif
1460                        PagerHelpExtra);
1461     snprintf (helpstr, sizeof (helpstr), "%s %s", tmphelp, buffer);
1462   }
1463   if (!InHelp) {
1464     m_strcpy(tmphelp, sizeof(tmphelp), helpstr);
1465     mutt_make_help (buffer, sizeof (buffer), _("Help"), MENU_PAGER, OP_HELP);
1466     snprintf (helpstr, sizeof (helpstr), "%s %s", tmphelp, buffer);
1467   }
1468
1469   while (ch != -1) {
1470     mutt_curs_set (0);
1471     imap_keepalive ();
1472
1473     if (redraw & REDRAW_FULL) {
1474       SETCOLOR (MT_COLOR_NORMAL);
1475       /* clear() doesn't optimize screen redraws */
1476       move (0, 0);
1477       clrtobot ();
1478
1479       if (IsHeader (extra) && Context->vcount + 1 < PagerIndexLines)
1480         indexlen = Context->vcount + 1;
1481       else
1482         indexlen = PagerIndexLines;
1483
1484       indicator = indexlen / 3;
1485
1486       if (option (OPTSTATUSONTOP)) {
1487         indexoffset = 0;
1488         statusoffset = IsHeader (extra) ? indexlen : 0;
1489         bodyoffset = statusoffset + 1;
1490         helpoffset = LINES - 2;
1491         bodylen = helpoffset - bodyoffset;
1492         if (!option (OPTHELP))
1493           bodylen++;
1494       }
1495       else {
1496         helpoffset = 0;
1497         indexoffset = 1;
1498         statusoffset = LINES - 2;
1499         if (!option (OPTHELP))
1500           indexoffset = 0;
1501         bodyoffset = indexoffset + (IsHeader (extra) ? indexlen : 0);
1502         bodylen = statusoffset - bodyoffset;
1503       }
1504
1505       if (option (OPTHELP)) {
1506         SETCOLOR (MT_COLOR_STATUS);
1507         move (helpoffset, SW);
1508         mutt_paddstr (COLS-SW, helpstr);
1509         SETCOLOR (MT_COLOR_NORMAL);
1510       }
1511
1512 #if defined (USE_SLANG_CURSES) || defined (HAVE_RESIZETERM)
1513       if (Resize != NULL) {
1514         if ((SearchCompiled = Resize->SearchCompiled)) {
1515           REGCOMP
1516             (&SearchRE, searchbuf, REG_NEWLINE | mutt_which_case (searchbuf));
1517           SearchFlag = M_SEARCH;
1518           SearchBack = Resize->SearchBack;
1519         }
1520         lines = Resize->line;
1521         redraw |= REDRAW_SIGWINCH;
1522
1523         p_delete(&Resize);
1524       }
1525 #endif
1526
1527       if (IsHeader (extra) && PagerIndexLines) {
1528         if (pager_index == NULL) {
1529           /* only allocate the space if/when we need the index.
1530              Initialise the menu as per the main index */
1531           pager_index = mutt_new_menu ();
1532           pager_index->menu = MENU_MAIN;
1533           pager_index->make_entry = index_make_entry;
1534           pager_index->color = index_color;
1535           pager_index->max = Context->vcount;
1536           pager_index->current = extra->hdr->virtual;
1537         }
1538
1539         SETCOLOR (MT_COLOR_NORMAL);
1540         pager_index->offset = indexoffset + (option (OPTSTATUSONTOP) ? 1 : 0);
1541
1542         pager_index->pagelen = indexlen - 1;
1543
1544         /* some fudge to work out where abouts the indicator should go */
1545         if (pager_index->current - indicator < 0)
1546           pager_index->top = 0;
1547         else if (pager_index->max - pager_index->current < pager_index->pagelen - indicator)
1548           pager_index->top = pager_index->max - pager_index->pagelen;
1549         else
1550           pager_index->top = pager_index->current - indicator;
1551
1552         menu_redraw_index (pager_index);
1553       }
1554
1555       redraw |= REDRAW_BODY | REDRAW_INDEX | REDRAW_STATUS;
1556       mutt_show_error ();
1557     }
1558
1559     if (redraw & REDRAW_SIGWINCH) {
1560       i = -1;
1561       j = -1;
1562       while (display_line (fp, &last_pos, &lineInfo, ++i, &lastLine, &maxLine,
1563                            has_types | SearchFlag, &QuoteList, &q_level,
1564                            &force_redraw, &SearchRE) == 0) {
1565         if (!lineInfo[i].continuation && ++j == lines) {
1566           topline = i;
1567           if (!SearchFlag)
1568             break;
1569         }
1570         redraw |= REDRAW_SIDEBAR;
1571       }                         /* while */
1572     }
1573
1574     if ((redraw & REDRAW_BODY) || topline != oldtopline) {
1575       do {
1576         move (bodyoffset, SW);
1577         curline = oldtopline = topline;
1578         lines = 0;
1579         force_redraw = 0;
1580
1581         while (lines < bodylen && lineInfo[curline].offset <= sb.st_size - 1) {
1582           if (display_line (fp, &last_pos, &lineInfo, curline, &lastLine,
1583                             &maxLine,
1584                             (flags & M_DISPLAYFLAGS) | hideQuoted |
1585                             SearchFlag, &QuoteList, &q_level, &force_redraw,
1586                             &SearchRE) > 0)
1587             lines++;
1588           curline++;
1589           move (lines + bodyoffset, SW);
1590           redraw |= REDRAW_SIDEBAR;
1591         }
1592         last_offset = lineInfo[curline].offset;
1593       } while (force_redraw);
1594
1595       SETCOLOR (MT_COLOR_TILDE);
1596       BKGDSET (MT_COLOR_TILDE);
1597       while (lines < bodylen) {
1598         clrtoeol ();
1599         if (option (OPTTILDE))
1600           addch ('~');
1601         addch ('\n');
1602         lines++;
1603         move (lines + bodyoffset, SW);
1604       }
1605       /* We are going to update the pager status bar, so it isn't
1606        * necessary to reset to normal color now. */
1607
1608       redraw |= REDRAW_STATUS;  /* need to update the % seen */
1609     }
1610
1611     if (redraw & REDRAW_STATUS) {
1612       /* print out the pager status bar */
1613       SETCOLOR (MT_COLOR_STATUS);
1614       BKGDSET (MT_COLOR_STATUS);
1615       CLEARLINE_WIN (statusoffset);
1616       if (IsHeader (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->hdr, M_FORMAT_MAKEPRINT);
1622       }
1623       else if (IsMsgAttach (extra)) {
1624         size_t l1 = (COLS - 9) * MB_LEN_MAX;
1625         size_t l2 = sizeof (buffer);
1626
1627         _mutt_make_string (buffer, l1 < l2 ? l1 : l2, NONULL (PagerFmt),
1628                            Context, extra->bdy->hdr, M_FORMAT_MAKEPRINT);
1629       }
1630       move(statusoffset,SW);
1631       mutt_paddstr (COLS - 10 - SW, IsHeader (extra) || 
1632                     IsMsgAttach (extra) ? buffer : banner);
1633
1634       addstr (" -- (");
1635       if (last_pos < sb.st_size - 1)
1636         printw ("%d%%)", (int) (100 * last_offset / sb.st_size));
1637       else
1638         addstr (topline == 0 ? "all)" : "end)");
1639       BKGDSET (MT_COLOR_NORMAL);
1640       SETCOLOR (MT_COLOR_NORMAL);
1641     }
1642
1643     if (redraw & REDRAW_SIDEBAR)
1644       sidebar_draw (MENU_PAGER);
1645
1646     if ((redraw & REDRAW_INDEX) && pager_index) {
1647       /* redraw the pager_index indicator, because the
1648        * flags for this message might have changed. */
1649       menu_redraw_current (pager_index);
1650       sidebar_draw (MENU_PAGER);
1651       /* print out the pager_index status bar */
1652       menu_status_line (buffer, sizeof (buffer), pager_index, NONULL (Status));
1653       move (indexoffset + (option (OPTSTATUSONTOP) ? 0 : (indexlen - 1)), SW);
1654       SETCOLOR (MT_COLOR_STATUS);
1655       BKGDSET (MT_COLOR_STATUS);
1656       mutt_paddstr (COLS-SW, buffer);
1657       SETCOLOR (MT_COLOR_NORMAL);
1658       BKGDSET (MT_COLOR_NORMAL);
1659     }
1660     /* if we're not using the index, update every time */
1661     if (index == 0)
1662       sidebar_draw (MENU_PAGER);
1663
1664     redraw = 0;
1665
1666     if (option(OPTBRAILLEFRIENDLY)) {
1667       if (brailleLine!=-1) {
1668         move(brailleLine+1, 0);
1669         brailleLine = -1;
1670       }
1671     } else
1672       move (statusoffset, COLS-1);
1673     mutt_refresh ();
1674
1675     if (IsHeader (extra) && OldHdr == extra->hdr && TopLine != topline
1676         && lineInfo[curline].offset < sb.st_size-1) {
1677       if (TopLine - topline > lines)
1678         topline += lines;
1679       else
1680         topline = TopLine;
1681       continue;
1682     }
1683     else
1684       OldHdr = NULL;
1685
1686     ch = km_dokey (MENU_PAGER);
1687     if (ch != -1)
1688       mutt_clear_error ();
1689     mutt_curs_set (1);
1690
1691     if (SigInt) {
1692       mutt_query_exit ();
1693       continue;
1694     }
1695 #if defined (USE_SLANG_CURSES) || defined (HAVE_RESIZETERM)
1696     else if (SigWinch) {
1697       mutt_resize_screen ();
1698
1699       /* Store current position. */
1700       lines = -1;
1701       for (i = 0; i <= topline; i++)
1702         if (!lineInfo[i].continuation)
1703           lines++;
1704
1705       if (flags & M_PAGER_RETWINCH) {
1706         Resize = p_new(struct resize, 1);
1707
1708         Resize->line = lines;
1709         Resize->SearchCompiled = SearchCompiled;
1710         Resize->SearchBack = SearchBack;
1711
1712         ch = -1;
1713         rc = OP_REFORMAT_WINCH;
1714       }
1715       else {
1716         for (i = 0; i < maxLine; i++) {
1717           lineInfo[i].offset = 0;
1718           lineInfo[i].type = -1;
1719           lineInfo[i].continuation = 0;
1720           lineInfo[i].chunks = 0;
1721           lineInfo[i].search_cnt = -1;
1722           lineInfo[i].quote = NULL;
1723
1724           p_realloc(&lineInfo[i].syntax, 1);
1725           if (SearchCompiled && lineInfo[i].search)
1726             p_delete(&(lineInfo[i].search));
1727         }
1728
1729         lastLine = 0;
1730         topline = 0;
1731
1732         redraw = REDRAW_FULL | REDRAW_SIGWINCH;
1733         ch = 0;
1734       }
1735
1736       SigWinch = 0;
1737       clearok (stdscr, TRUE);   /*force complete redraw */
1738       continue;
1739     }
1740 #endif
1741     else if (ch == -1) {
1742       ch = 0;
1743       continue;
1744     }
1745
1746     rc = ch;
1747
1748     switch (ch) {
1749     case OP_EXIT:
1750       rc = -1;
1751       ch = -1;
1752       break;
1753
1754     case OP_NEXT_PAGE:
1755       if (lineInfo[curline].offset < sb.st_size - 1) {
1756         topline = upNLines (PagerContext, lineInfo, curline, hideQuoted);
1757       }
1758       else if (option (OPTPAGERSTOP)) {
1759         /* emulate "less -q" and don't go on to the next message. */
1760         mutt_error _("Bottom of message is shown.");
1761       }
1762       else {
1763         /* end of the current message, so display the next message. */
1764         rc = OP_MAIN_NEXT_UNDELETED;
1765         ch = -1;
1766       }
1767       break;
1768
1769     case OP_PREV_PAGE:
1770       if (topline != 0) {
1771         topline =
1772           upNLines (bodylen - PagerContext, lineInfo, topline, hideQuoted);
1773       }
1774       else
1775         mutt_error _("Top of message is shown.");
1776       break;
1777
1778     case OP_NEXT_LINE:
1779       if (lineInfo[curline].offset < sb.st_size - 1) {
1780         topline++;
1781         if (hideQuoted) {
1782           while (lineInfo[topline].type == MT_COLOR_QUOTED &&
1783                  topline < lastLine)
1784             topline++;
1785         }
1786       }
1787       else
1788         mutt_error _("Bottom of message is shown.");
1789       break;
1790
1791     case OP_PREV_LINE:
1792       if (topline)
1793         topline = upNLines (1, lineInfo, topline, hideQuoted);
1794       else
1795         mutt_error _("Top of message is shown.");
1796       break;
1797
1798     case OP_PAGER_TOP:
1799       if (topline)
1800         topline = 0;
1801       else
1802         mutt_error _("Top of message is shown.");
1803       break;
1804
1805     case OP_HALF_UP:
1806       if (topline)
1807         topline = upNLines (bodylen / 2, lineInfo, topline, hideQuoted);
1808       else
1809         mutt_error _("Top of message is shown.");
1810       break;
1811
1812     case OP_HALF_DOWN:
1813       if (lineInfo[curline].offset < sb.st_size - 1) {
1814         topline = upNLines (bodylen / 2, lineInfo, curline, hideQuoted);
1815       }
1816       else if (option (OPTPAGERSTOP)) {
1817         /* emulate "less -q" and don't go on to the next message. */
1818         mutt_error _("Bottom of message is shown.");
1819       }
1820       else {
1821         /* end of the current message, so display the next message. */
1822         rc = OP_MAIN_NEXT_UNDELETED;
1823         ch = -1;
1824       }
1825       break;
1826
1827     case OP_SEARCH_NEXT:
1828     case OP_SEARCH_OPPOSITE:
1829       if (SearchCompiled) {
1830       search_next:
1831         if ((!SearchBack && ch == OP_SEARCH_NEXT) ||
1832             (SearchBack && ch == OP_SEARCH_OPPOSITE)) {
1833           /* searching forward */
1834           for (i = topline + 1; i < lastLine; i++) {
1835             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1836                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1837               break;
1838           }
1839
1840           if (i < lastLine)
1841             topline = i;
1842           else
1843             mutt_error _("Not found.");
1844         }
1845         else {
1846           /* searching backward */
1847           for (i = topline - 1; i >= 0; i--) {
1848             if ((!hideQuoted || (has_types &&
1849                                  lineInfo[i].type != MT_COLOR_QUOTED)) &&
1850                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1851               break;
1852           }
1853
1854           if (i >= 0)
1855             topline = i;
1856           else
1857             mutt_error _("Not found.");
1858         }
1859
1860         if (lineInfo[topline].search_cnt > 0)
1861           SearchFlag = M_SEARCH;
1862
1863         break;
1864       }
1865       /* no previous search pattern, so fall through to search */
1866
1867     case OP_SEARCH:
1868     case OP_SEARCH_REVERSE:
1869       m_strcpy(buffer, sizeof(buffer), searchbuf);
1870       if (mutt_get_field ((SearchBack ? _("Reverse search: ") :
1871                            _("Search: ")), buffer, sizeof (buffer),
1872                           M_CLEAR) != 0)
1873         break;
1874
1875       if (!strcmp (buffer, searchbuf)) {
1876         if (SearchCompiled) {
1877           /* do an implicit search-next */
1878           if (ch == OP_SEARCH)
1879             ch = OP_SEARCH_NEXT;
1880           else
1881             ch = OP_SEARCH_OPPOSITE;
1882
1883           goto search_next;
1884         }
1885       }
1886
1887       if (!buffer[0])
1888         break;
1889
1890       m_strcpy(searchbuf, sizeof(searchbuf), buffer);
1891
1892       /* leave SearchBack alone if ch == OP_SEARCH_NEXT */
1893       if (ch == OP_SEARCH)
1894         SearchBack = 0;
1895       else if (ch == OP_SEARCH_REVERSE)
1896         SearchBack = 1;
1897
1898       if (SearchCompiled) {
1899         regfree (&SearchRE);
1900         for (i = 0; i < lastLine; i++) {
1901           if (lineInfo[i].search)
1902             p_delete(&(lineInfo[i].search));
1903           lineInfo[i].search_cnt = -1;
1904         }
1905       }
1906
1907       if ((err =
1908            REGCOMP (&SearchRE, searchbuf,
1909                     REG_NEWLINE | mutt_which_case (searchbuf))) != 0) {
1910         regerror (err, &SearchRE, buffer, sizeof (buffer));
1911         mutt_error ("%s", buffer);
1912         regfree (&SearchRE);
1913         for (i = 0; i < maxLine; i++) {
1914           /* cleanup */
1915           if (lineInfo[i].search)
1916             p_delete(&(lineInfo[i].search));
1917           lineInfo[i].search_cnt = -1;
1918         }
1919         SearchFlag = 0;
1920         SearchCompiled = 0;
1921       }
1922       else {
1923         SearchCompiled = 1;
1924         /* update the search pointers */
1925         i = 0;
1926         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
1927                              &maxLine, M_SEARCH | (flags & M_PAGER_NSKIP),
1928                              &QuoteList, &q_level,
1929                              &force_redraw, &SearchRE) == 0) {
1930           i++;
1931           redraw |= REDRAW_SIDEBAR;
1932         }
1933
1934         if (!SearchBack) {
1935           /* searching forward */
1936           for (i = topline; i < lastLine; i++) {
1937             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1938                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1939               break;
1940           }
1941
1942           if (i < lastLine)
1943             topline = i;
1944         }
1945         else {
1946           /* searching backward */
1947           for (i = topline; i >= 0; i--) {
1948             if ((!hideQuoted || lineInfo[i].type != MT_COLOR_QUOTED) &&
1949                 !lineInfo[i].continuation && lineInfo[i].search_cnt > 0)
1950               break;
1951           }
1952
1953           if (i >= 0)
1954             topline = i;
1955         }
1956
1957         if (lineInfo[topline].search_cnt == 0) {
1958           SearchFlag = 0;
1959           mutt_error _("Not found.");
1960         }
1961         else
1962           SearchFlag = M_SEARCH;
1963       }
1964       redraw = REDRAW_BODY;
1965       break;
1966
1967     case OP_SEARCH_TOGGLE:
1968       if (SearchCompiled) {
1969         SearchFlag ^= M_SEARCH;
1970         redraw = REDRAW_BODY;
1971       }
1972       break;
1973
1974     case OP_HELP:
1975       /* don't let the user enter the help-menu from the help screen! */
1976       if (!InHelp) {
1977         InHelp = 1;
1978         mutt_help (MENU_PAGER);
1979         redraw = REDRAW_FULL;
1980         InHelp = 0;
1981       }
1982       else
1983         mutt_error _("Help is currently being shown.");
1984       break;
1985
1986     case OP_PAGER_HIDE_QUOTED:
1987       if (has_types) {
1988         hideQuoted ^= M_HIDE;
1989         if (hideQuoted && lineInfo[topline].type == MT_COLOR_QUOTED)
1990           topline = upNLines (1, lineInfo, topline, hideQuoted);
1991         else
1992           redraw = REDRAW_BODY;
1993       }
1994       break;
1995
1996     case OP_PAGER_SKIP_QUOTED:
1997       if (has_types) {
1998         int dretval = 0;
1999         int new_topline = topline;
2000
2001         while ((new_topline < lastLine ||
2002                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
2003                                                new_topline, &lastLine,
2004                                                &maxLine, M_TYPES, &QuoteList,
2005                                                &q_level, &force_redraw,
2006                                                &SearchRE))))
2007                && lineInfo[new_topline].type != MT_COLOR_QUOTED) {
2008           redraw |= REDRAW_SIDEBAR;
2009           new_topline++;
2010         }
2011
2012         if (dretval < 0) {
2013           mutt_error _("No more quoted text.");
2014
2015           break;
2016         }
2017
2018         while ((new_topline < lastLine ||
2019                 (0 == (dretval = display_line (fp, &last_pos, &lineInfo,
2020                                                new_topline, &lastLine,
2021                                                &maxLine, M_TYPES, &QuoteList,
2022                                                &q_level, &force_redraw,
2023                                                &SearchRE))))
2024                && lineInfo[new_topline].type == MT_COLOR_QUOTED) {
2025           new_topline++;
2026           redraw |= REDRAW_SIDEBAR;
2027         }
2028
2029         if (dretval < 0) {
2030           mutt_error _("No more unquoted text after quoted text.");
2031
2032           break;
2033         }
2034         topline = new_topline;
2035       }
2036       break;
2037
2038     case OP_PAGER_BOTTOM:      /* move to the end of the file */
2039       if (lineInfo[curline].offset < sb.st_size - 1) {
2040         i = curline;
2041         /* make sure the types are defined to the end of file */
2042         while (display_line (fp, &last_pos, &lineInfo, i, &lastLine,
2043                              &maxLine, has_types,
2044                              &QuoteList, &q_level, &force_redraw,
2045                              &SearchRE) == 0) {
2046           i++;
2047           redraw |= REDRAW_SIDEBAR;
2048         }
2049         topline = upNLines (bodylen, lineInfo, lastLine, hideQuoted);
2050       }
2051       else
2052         mutt_error _("Bottom of message is shown.");
2053       break;
2054
2055     case OP_REDRAW:
2056       clearok (stdscr, TRUE);
2057       redraw = REDRAW_FULL;
2058       break;
2059
2060     case OP_NULL:
2061       km_error_key (MENU_PAGER);
2062       break;
2063
2064       /* --------------------------------------------------------------------
2065        * The following are operations on the current message rather than
2066        * adjusting the view of the message.
2067        */
2068
2069     case OP_BOUNCE_MESSAGE:
2070       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
2071         CHECK_ATTACH;
2072       if (IsMsgAttach (extra))
2073         mutt_attach_bounce (extra->fp, extra->hdr,
2074                             extra->idx, extra->idxlen, extra->bdy);
2075       else
2076         ci_bounce_message (extra->hdr, &redraw);
2077       break;
2078
2079     case OP_RESEND:
2080       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra))
2081         CHECK_ATTACH;
2082       if (IsMsgAttach (extra))
2083         mutt_attach_resend (extra->fp, extra->hdr,
2084                             extra->idx, extra->idxlen, extra->bdy);
2085       else
2086         mutt_resend_message (NULL, extra->ctx, extra->hdr);
2087       redraw = REDRAW_FULL;
2088       break;
2089
2090     case OP_CHECK_TRADITIONAL:
2091       CHECK_MODE (IsHeader (extra));
2092       if (!(extra->hdr->security & PGP_TRADITIONAL_CHECKED)) {
2093         ch = -1;
2094         rc = OP_CHECK_TRADITIONAL;
2095       }
2096       break;
2097
2098     case OP_CREATE_ALIAS:
2099       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2100       if (IsMsgAttach (extra))
2101         mutt_create_alias (extra->bdy->hdr->env, NULL);
2102       else
2103         mutt_create_alias (extra->hdr->env, NULL);
2104       MAYBE_REDRAW (redraw);
2105       break;
2106
2107     case OP_PURGE_MESSAGE:
2108     case OP_DELETE:
2109       CHECK_MODE (IsHeader (extra));
2110       CHECK_READONLY;
2111
2112       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
2113
2114       mutt_set_flag (Context, extra->hdr, M_DELETE, 1);
2115       mutt_set_flag (Context, extra->hdr, M_PURGED,
2116                      ch != OP_PURGE_MESSAGE ? 0 : 1);
2117       if (option (OPTDELETEUNTAG))
2118         mutt_set_flag (Context, extra->hdr, M_TAG, 0);
2119       redraw = REDRAW_STATUS | REDRAW_INDEX;
2120       if (option (OPTRESOLVE)) {
2121         ch = -1;
2122         rc = OP_MAIN_NEXT_UNDELETED;
2123       }
2124       break;
2125
2126     case OP_DELETE_THREAD:
2127     case OP_DELETE_SUBTHREAD:
2128       CHECK_MODE (IsHeader (extra));
2129       CHECK_READONLY;
2130
2131       CHECK_MX_ACL (Context, ACL_DELETE, _("Deletion"));
2132
2133       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 1,
2134                                 ch == OP_DELETE_THREAD ? 0 : 1);
2135
2136       if (r != -1) {
2137         if (option (OPTDELETEUNTAG))
2138           mutt_thread_set_flag (extra->hdr, M_TAG, 0,
2139                                 ch == OP_DELETE_THREAD ? 0 : 1);
2140         if (option (OPTRESOLVE)) {
2141           rc = OP_MAIN_NEXT_UNDELETED;
2142           ch = -1;
2143         }
2144
2145         if (!option (OPTRESOLVE) && PagerIndexLines)
2146           redraw = REDRAW_FULL;
2147         else
2148           redraw = REDRAW_STATUS | REDRAW_INDEX;
2149       }
2150       break;
2151
2152     case OP_DISPLAY_ADDRESS:
2153       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2154       if (IsMsgAttach (extra))
2155         mutt_display_address (extra->bdy->hdr->env);
2156       else
2157         mutt_display_address (extra->hdr->env);
2158       break;
2159
2160     case OP_ENTER_COMMAND:
2161       old_smart_wrap = option (OPTWRAP);
2162       old_markers = option (OPTMARKERS);
2163       old_PagerIndexLines = PagerIndexLines;
2164
2165       CurrentMenu = MENU_PAGER;
2166       mutt_enter_command ();
2167
2168       if (option (OPTNEEDRESORT)) {
2169         unset_option (OPTNEEDRESORT);
2170         CHECK_MODE (IsHeader (extra));
2171         set_option (OPTNEEDRESORT);
2172       }
2173
2174       if (old_PagerIndexLines != PagerIndexLines) {
2175         if (pager_index)
2176           mutt_menuDestroy (&pager_index);
2177         pager_index = NULL;
2178       }
2179
2180       if (option (OPTWRAP) != old_smart_wrap ||
2181           option (OPTMARKERS) != old_markers) {
2182         if (flags & M_PAGER_RETWINCH) {
2183           ch = -1;
2184           rc = OP_REFORMAT_WINCH;
2185           continue;
2186         }
2187
2188         /* count the real lines above */
2189         j = 0;
2190         for (i = 0; i <= topline; i++) {
2191           if (!lineInfo[i].continuation)
2192             j++;
2193         }
2194
2195         /* we need to restart the whole thing */
2196         for (i = 0; i < maxLine; i++) {
2197           lineInfo[i].offset = 0;
2198           lineInfo[i].type = -1;
2199           lineInfo[i].continuation = 0;
2200           lineInfo[i].chunks = 0;
2201           lineInfo[i].search_cnt = -1;
2202           lineInfo[i].quote = NULL;
2203
2204           p_realloc(&(lineInfo[i].syntax), 1);
2205           if (SearchCompiled && lineInfo[i].search)
2206             p_delete(&(lineInfo[i].search));
2207         }
2208
2209         if (SearchCompiled) {
2210           regfree (&SearchRE);
2211           SearchCompiled = 0;
2212         }
2213         SearchFlag = 0;
2214
2215         /* try to keep the old position */
2216         topline = 0;
2217         lastLine = 0;
2218         while (j > 0 && display_line (fp, &last_pos, &lineInfo, topline,
2219                                       &lastLine, &maxLine,
2220                                       (has_types ? M_TYPES : 0),
2221                                       &QuoteList, &q_level, &force_redraw,
2222                                       &SearchRE) == 0) {
2223           redraw |= REDRAW_SIDEBAR;
2224           if (!lineInfo[topline].continuation)
2225             j--;
2226           if (j > 0)
2227             topline++;
2228         }
2229
2230         ch = 0;
2231       }
2232
2233       if (option (OPTFORCEREDRAWPAGER))
2234         redraw = REDRAW_FULL;
2235       unset_option (OPTFORCEREDRAWINDEX);
2236       unset_option (OPTFORCEREDRAWPAGER);
2237       break;
2238
2239     case OP_FLAG_MESSAGE:
2240       CHECK_MODE (IsHeader (extra));
2241       CHECK_READONLY;
2242
2243       CHECK_MX_ACL (Context, ACL_WRITE, _("Flagging"));
2244
2245       mutt_set_flag (Context, extra->hdr, M_FLAG, !extra->hdr->flagged);
2246       redraw = REDRAW_STATUS | REDRAW_INDEX;
2247       if (option (OPTRESOLVE)) {
2248         ch = -1;
2249         rc = OP_MAIN_NEXT_UNDELETED;
2250       }
2251       break;
2252
2253     case OP_PIPE:
2254       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2255       if (IsAttach (extra))
2256         mutt_pipe_attachment_list (extra->fp, 0, extra->bdy, 0);
2257       else
2258         mutt_pipe_message (extra->hdr);
2259       MAYBE_REDRAW (redraw);
2260       break;
2261
2262     case OP_PRINT:
2263       CHECK_MODE (IsHeader (extra) || IsAttach (extra));
2264       if (IsAttach (extra))
2265         mutt_print_attachment_list (extra->fp, 0, extra->bdy);
2266       else
2267         mutt_print_message (extra->hdr);
2268       break;
2269
2270     case OP_MAIL:
2271       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2272       CHECK_ATTACH;
2273       ci_send_message (0, NULL, NULL, extra->ctx, NULL);
2274       redraw = REDRAW_FULL;
2275       break;
2276
2277 #ifdef USE_NNTP
2278     case OP_POST:
2279       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2280       CHECK_ATTACH;
2281       if (extra->ctx && extra->ctx->magic == M_NNTP &&
2282           !((NNTP_DATA *) extra->ctx->data)->allowed &&
2283           query_quadoption (OPT_TOMODERATED,
2284                             _
2285                             ("Posting to this group not allowed, may be moderated. Continue?"))
2286           != M_YES)
2287         break;
2288       ci_send_message (SENDNEWS, NULL, NULL, extra->ctx, NULL);
2289       redraw = REDRAW_FULL;
2290       break;
2291
2292     case OP_FORWARD_TO_GROUP:
2293       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2294       CHECK_ATTACH;
2295       if (extra->ctx && extra->ctx->magic == M_NNTP &&
2296           !((NNTP_DATA *) extra->ctx->data)->allowed &&
2297           query_quadoption (OPT_TOMODERATED,
2298                             _
2299                             ("Posting to this group not allowed, may be moderated. Continue?"))
2300           != M_YES)
2301         break;
2302       if (IsMsgAttach (extra))
2303         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2304                              extra->idxlen, extra->bdy, SENDNEWS);
2305       else
2306         ci_send_message (SENDNEWS | SENDFORWARD, NULL, NULL, extra->ctx,
2307                          extra->hdr);
2308       redraw = REDRAW_FULL;
2309       break;
2310
2311     case OP_FOLLOWUP:
2312       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2313       CHECK_ATTACH;
2314
2315       if (IsMsgAttach (extra))
2316         followup_to = extra->bdy->hdr->env->followup_to;
2317       else
2318         followup_to = extra->hdr->env->followup_to;
2319
2320       if (!followup_to || m_strcasecmp(followup_to, "poster") ||
2321           query_quadoption (OPT_FOLLOWUPTOPOSTER,
2322                             _("Reply by mail as poster prefers?")) != M_YES) {
2323         if (extra->ctx && extra->ctx->magic == M_NNTP
2324             && !((NNTP_DATA *) extra->ctx->data)->allowed
2325             && query_quadoption (OPT_TOMODERATED,
2326                                  _
2327                                  ("Posting to this group not allowed, may be moderated. Continue?"))
2328             != M_YES)
2329           break;
2330         if (IsMsgAttach (extra))
2331           mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2332                              extra->idxlen, extra->bdy, SENDNEWS | SENDREPLY);
2333         else
2334           ci_send_message (SENDNEWS | SENDREPLY, NULL, NULL,
2335                            extra->ctx, extra->hdr);
2336         redraw = REDRAW_FULL;
2337         break;
2338       }
2339 #endif
2340
2341     case OP_REPLY:
2342       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2343       CHECK_ATTACH;
2344       if (IsMsgAttach (extra))
2345         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2346                            extra->idxlen, extra->bdy, SENDREPLY);
2347       else
2348         ci_send_message (SENDREPLY, NULL, NULL, extra->ctx, extra->hdr);
2349       redraw = REDRAW_FULL;
2350       break;
2351
2352     case OP_RECALL_MESSAGE:
2353       CHECK_MODE (IsHeader (extra) && !IsAttach (extra));
2354       CHECK_ATTACH;
2355       ci_send_message (SENDPOSTPONED, NULL, NULL, extra->ctx, extra->hdr);
2356       redraw = REDRAW_FULL;
2357       break;
2358
2359     case OP_GROUP_REPLY:
2360       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2361       CHECK_ATTACH;
2362       if (IsMsgAttach (extra))
2363         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2364                            extra->idxlen, extra->bdy,
2365                            SENDREPLY | SENDGROUPREPLY);
2366       else
2367         ci_send_message (SENDREPLY | SENDGROUPREPLY, NULL, NULL, extra->ctx,
2368                          extra->hdr);
2369       redraw = REDRAW_FULL;
2370       break;
2371
2372     case OP_LIST_REPLY:
2373       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2374       CHECK_ATTACH;
2375       if (IsMsgAttach (extra))
2376         mutt_attach_reply (extra->fp, extra->hdr, extra->idx,
2377                            extra->idxlen, extra->bdy,
2378                            SENDREPLY | SENDLISTREPLY);
2379       else
2380         ci_send_message (SENDREPLY | SENDLISTREPLY, NULL, NULL, extra->ctx,
2381                          extra->hdr);
2382       redraw = REDRAW_FULL;
2383       break;
2384
2385     case OP_FORWARD_MESSAGE:
2386       CHECK_MODE (IsHeader (extra) || IsMsgAttach (extra));
2387       CHECK_ATTACH;
2388       if (IsMsgAttach (extra))
2389         mutt_attach_forward (extra->fp, extra->hdr, extra->idx,
2390                              extra->idxlen, extra->bdy, 0);
2391       else
2392         ci_send_message (SENDFORWARD, NULL, NULL, extra->ctx, extra->hdr);
2393       redraw = REDRAW_FULL;
2394       break;
2395
2396     case OP_DECRYPT_SAVE:
2397     case OP_SAVE:
2398       if (IsAttach (extra)) {
2399         mutt_save_attachment_list (extra->fp, 0, extra->bdy, extra->hdr,
2400                                    NULL);
2401         break;
2402       }
2403       /* fall through */
2404     case OP_COPY_MESSAGE:
2405     case OP_DECODE_SAVE:
2406     case OP_DECODE_COPY:
2407     case OP_DECRYPT_COPY:
2408       CHECK_MODE (IsHeader (extra));
2409       if (mutt_save_message (extra->hdr,
2410                              (ch == OP_DECRYPT_SAVE) ||
2411                              (ch == OP_SAVE) || (ch == OP_DECODE_SAVE),
2412                              (ch == OP_DECODE_SAVE) || (ch == OP_DECODE_COPY),
2413                              (ch == OP_DECRYPT_SAVE)
2414                              || (ch == OP_DECRYPT_COPY) || 0, &redraw) == 0
2415           && (ch == OP_SAVE || ch == OP_DECODE_SAVE
2416               || ch == OP_DECRYPT_SAVE)) {
2417         if (option (OPTRESOLVE)) {
2418           ch = -1;
2419           rc = OP_MAIN_NEXT_UNDELETED;
2420         }
2421         else
2422           redraw |= REDRAW_STATUS | REDRAW_INDEX;
2423       }
2424       MAYBE_REDRAW (redraw);
2425       break;
2426
2427     case OP_SHELL_ESCAPE:
2428       mutt_shell_escape ();
2429       MAYBE_REDRAW (redraw);
2430       break;
2431
2432     case OP_TAG:
2433       CHECK_MODE (IsHeader (extra));
2434       mutt_set_flag (Context, extra->hdr, M_TAG, !extra->hdr->tagged);
2435
2436       Context->last_tag = extra->hdr->tagged ? extra->hdr :
2437         ((Context->last_tag == extra->hdr && !extra->hdr->tagged)
2438          ? NULL : Context->last_tag);
2439
2440       redraw = REDRAW_STATUS | REDRAW_INDEX;
2441       if (option (OPTRESOLVE)) {
2442         ch = -1;
2443         rc = OP_NEXT_ENTRY;
2444       }
2445       break;
2446
2447     case OP_TOGGLE_NEW:
2448       CHECK_MODE (IsHeader (extra));
2449       CHECK_READONLY;
2450
2451       CHECK_MX_ACL (Context, ACL_SEEN, _("Toggling"));
2452
2453       if (extra->hdr->read || extra->hdr->old)
2454         mutt_set_flag (Context, extra->hdr, M_NEW, 1);
2455       else if (!first)
2456         mutt_set_flag (Context, extra->hdr, M_READ, 1);
2457       first = 0;
2458       Context->msgnotreadyet = -1;
2459       redraw = REDRAW_STATUS | REDRAW_INDEX;
2460       if (option (OPTRESOLVE)) {
2461         ch = -1;
2462         rc = OP_MAIN_NEXT_UNDELETED;
2463       }
2464       break;
2465
2466     case OP_UNDELETE:
2467       CHECK_MODE (IsHeader (extra));
2468       CHECK_READONLY;
2469
2470       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2471
2472       mutt_set_flag (Context, extra->hdr, M_DELETE, 0);
2473       mutt_set_flag (Context, extra->hdr, M_PURGED, 0);
2474       redraw = REDRAW_STATUS | REDRAW_INDEX;
2475       if (option (OPTRESOLVE)) {
2476         ch = -1;
2477         rc = OP_NEXT_ENTRY;
2478       }
2479       break;
2480
2481     case OP_UNDELETE_THREAD:
2482     case OP_UNDELETE_SUBTHREAD:
2483       CHECK_MODE (IsHeader (extra));
2484       CHECK_READONLY;
2485
2486       CHECK_MX_ACL (Context, ACL_DELETE, _("Undeletion"));
2487
2488       r = mutt_thread_set_flag (extra->hdr, M_DELETE, 0,
2489                                 ch == OP_UNDELETE_THREAD ? 0 : 1)
2490         + mutt_thread_set_flag (extra->hdr, M_PURGED, 0,
2491                                 ch == OP_UNDELETE_THREAD ? 0 : 1);
2492
2493       if (r > -1) {
2494         if (option (OPTRESOLVE)) {
2495           rc = (ch == OP_DELETE_THREAD) ?
2496             OP_MAIN_NEXT_THREAD : OP_MAIN_NEXT_SUBTHREAD;
2497           ch = -1;
2498         }
2499
2500         if (!option (OPTRESOLVE) && PagerIndexLines)
2501           redraw = REDRAW_FULL;
2502         else
2503           redraw = REDRAW_STATUS | REDRAW_INDEX;
2504       }
2505       break;
2506
2507     case OP_VERSION:
2508       mutt_version ();
2509       break;
2510
2511     case OP_BUFFY_LIST:
2512       if (option (OPTFORCEBUFFYCHECK))
2513         buffy_check (1);
2514       buffy_list ();
2515       redraw |= REDRAW_SIDEBAR;
2516       break;
2517
2518     case OP_VIEW_ATTACHMENTS:
2519       if (flags & M_PAGER_ATTACHMENT) {
2520         ch = -1;
2521         rc = OP_ATTACH_COLLAPSE;
2522         break;
2523       }
2524       CHECK_MODE (IsHeader (extra));
2525       mutt_view_attachments (extra->hdr);
2526       if (extra->hdr->attach_del)
2527         Context->changed = 1;
2528       redraw = REDRAW_FULL;
2529       break;
2530
2531
2532     case OP_MAIL_KEY:
2533       CHECK_MODE (IsHeader (extra));
2534       CHECK_ATTACH;
2535       ci_send_message (SENDKEY, NULL, NULL, extra->ctx, extra->hdr);
2536       redraw = REDRAW_FULL;
2537       break;
2538
2539
2540     case OP_FORGET_PASSPHRASE:
2541       crypt_forget_passphrase ();
2542       break;
2543
2544     case OP_EXTRACT_KEYS:
2545       CHECK_MODE (IsHeader (extra));
2546       crypt_extract_keys_from_messages (extra->hdr);
2547       redraw = REDRAW_FULL;
2548       break;
2549
2550     case OP_SIDEBAR_SCROLL_UP:
2551     case OP_SIDEBAR_SCROLL_DOWN:
2552     case OP_SIDEBAR_NEXT:
2553     case OP_SIDEBAR_NEXT_NEW:
2554     case OP_SIDEBAR_PREV:
2555     case OP_SIDEBAR_PREV_NEW:
2556       sidebar_scroll (ch, MENU_PAGER);
2557       break;
2558     default:
2559       ch = -1;
2560       break;
2561     }
2562   }
2563
2564   fclose (fp);
2565   if (IsHeader (extra)) {
2566     Context->msgnotreadyet = -1;
2567     if (rc == -1)
2568       OldHdr = NULL;
2569     else {
2570       TopLine = topline;
2571       OldHdr = extra->hdr;
2572     }
2573   }
2574
2575   cleanup_quote (&QuoteList);
2576
2577   for (i = 0; i < maxLine; i++) {
2578     p_delete(&(lineInfo[i].syntax));
2579     if (SearchCompiled && lineInfo[i].search)
2580       p_delete(&(lineInfo[i].search));
2581   }
2582   if (SearchCompiled) {
2583     regfree (&SearchRE);
2584     SearchCompiled = 0;
2585   }
2586   p_delete(&lineInfo);
2587   if (pager_index)
2588     mutt_menuDestroy (&pager_index);
2589   return (rc != -1 ? rc : 0);
2590 }