Add manpage for stge(4)
[dragonfly.git] / contrib / less-394 / line.c
1 /*
2  * Copyright (C) 1984-2005  Mark Nudelman
3  *
4  * You may distribute under the terms of either the GNU General Public
5  * License or the Less License, as specified in the README file.
6  *
7  * For more information about less, or for information on how to 
8  * contact the author, see the README file.
9  */
10
11
12 /*
13  * Routines to manipulate the "line buffer".
14  * The line buffer holds a line of output as it is being built
15  * in preparation for output to the screen.
16  */
17
18 #include "less.h"
19 #include "charset.h"
20
21 static char *linebuf = NULL;    /* Buffer which holds the current output line */
22 static char *attr = NULL;       /* Extension of linebuf to hold attributes */
23 public int size_linebuf = 0;    /* Size of line buffer (and attr buffer) */
24
25 static int cshift;              /* Current left-shift of output line buffer */
26 public int hshift;              /* Desired left-shift of output line buffer */
27 public int tabstops[TABSTOP_MAX] = { 0 }; /* Custom tabstops */
28 public int ntabstops = 1;       /* Number of tabstops */
29 public int tabdefault = 8;      /* Default repeated tabstops */
30
31 static int curr;                /* Index into linebuf */
32 static int column;              /* Printable length, accounting for
33                                    backspaces, etc. */
34 static int overstrike;          /* Next char should overstrike previous char */
35 static int last_overstrike = AT_NORMAL;
36 static int is_null_line;        /* There is no current line */
37 static int lmargin;             /* Left margin */
38 static int line_matches;        /* Number of search matches in this line */
39 static char pendc;
40 static POSITION pendpos;
41 static char *end_ansi_chars;
42 static char *mid_ansi_chars;
43
44 static int attr_swidth();
45 static int attr_ewidth();
46 static int do_append();
47
48 extern int sigs;
49 extern int bs_mode;
50 extern int linenums;
51 extern int ctldisp;
52 extern int twiddle;
53 extern int binattr;
54 extern int status_col;
55 extern int auto_wrap, ignaw;
56 extern int bo_s_width, bo_e_width;
57 extern int ul_s_width, ul_e_width;
58 extern int bl_s_width, bl_e_width;
59 extern int so_s_width, so_e_width;
60 extern int sc_width, sc_height;
61 extern int utf_mode;
62 extern POSITION start_attnpos;
63 extern POSITION end_attnpos;
64
65 static char mbc_buf[MAX_UTF_CHAR_LEN];
66 static int mbc_buf_len = 0;
67 static int mbc_buf_index = 0;
68 static POSITION mbc_pos;
69
70 /*
71  * Initialize from environment variables.
72  */
73         public void
74 init_line()
75 {
76         end_ansi_chars = lgetenv("LESSANSIENDCHARS");
77         if (end_ansi_chars == NULL || *end_ansi_chars == '\0')
78                 end_ansi_chars = "m";
79
80         mid_ansi_chars = lgetenv("LESSANSIMIDCHARS");
81         if (mid_ansi_chars == NULL || *mid_ansi_chars == '\0')
82                 mid_ansi_chars = "0123456789;[?!\"'#%()*+ ";
83
84         linebuf = (char *) ecalloc(LINEBUF_SIZE, sizeof(char));
85         attr = (char *) ecalloc(LINEBUF_SIZE, sizeof(char));
86         size_linebuf = LINEBUF_SIZE;
87 }
88
89 /*
90  * Expand the line buffer.
91  */
92         static int
93 expand_linebuf()
94 {
95         /* Double the size of the line buffer. */
96         int new_size = size_linebuf * 2;
97
98         /* Just realloc to expand the buffer, if we can. */
99 #if HAVE_REALLOC
100         char *new_buf = (char *) realloc(linebuf, new_size);
101         char *new_attr = (char *) realloc(attr, new_size);
102 #else
103         char *new_buf = (char *) calloc(new_size, sizeof(char));
104         char *new_attr = (char *) calloc(new_size, sizeof(char));
105 #endif
106         if (new_buf == NULL || new_attr == NULL)
107         {
108                 if (new_attr != NULL)
109                         free(new_attr);
110                 if (new_buf != NULL)
111                         free(new_buf);
112                 return 1;
113         }
114 #if HAVE_REALLOC
115         /*
116          * We realloc'd the buffers; they already have the old contents.
117          */
118         #if 0
119         memset(new_buf + size_linebuf, 0, new_size - size_linebuf);
120         memset(new_attr + size_linebuf, 0, new_size - size_linebuf);
121         #endif
122 #else
123         /*
124          * We just calloc'd the buffers; copy the old contents.
125          */
126         memcpy(new_buf, linebuf, size_linebuf * sizeof(char));
127         memcpy(new_attr, attr, size_linebuf * sizeof(char));
128         free(attr);
129         free(linebuf);
130 #endif
131         linebuf = new_buf;
132         attr = new_attr;
133         size_linebuf = new_size;
134         return 0;
135 }
136
137 /*
138  * Is a character ASCII?
139  */
140         public int
141 is_ascii_char(ch)
142         LWCHAR ch;
143 {
144         return (ch <= 0x7F);
145 }
146
147 /*
148  * Rewind the line buffer.
149  */
150         public void
151 prewind()
152 {
153         curr = 0;
154         column = 0;
155         cshift = 0;
156         overstrike = 0;
157         last_overstrike = AT_NORMAL;
158         mbc_buf_len = 0;
159         is_null_line = 0;
160         pendc = '\0';
161         lmargin = 0;
162         if (status_col)
163                 lmargin += 1;
164 #if HILITE_SEARCH
165         line_matches = 0;
166 #endif
167 }
168
169 /*
170  * Insert the line number (of the given position) into the line buffer.
171  */
172         public void
173 plinenum(pos)
174         POSITION pos;
175 {
176         register LINENUM linenum = 0;
177         register int i;
178
179         if (linenums == OPT_ONPLUS)
180         {
181                 /*
182                  * Get the line number and put it in the current line.
183                  * {{ Note: since find_linenum calls forw_raw_line,
184                  *    it may seek in the input file, requiring the caller 
185                  *    of plinenum to re-seek if necessary. }}
186                  * {{ Since forw_raw_line modifies linebuf, we must
187                  *    do this first, before storing anything in linebuf. }}
188                  */
189                 linenum = find_linenum(pos);
190         }
191
192         /*
193          * Display a status column if the -J option is set.
194          */
195         if (status_col)
196         {
197                 linebuf[curr] = ' ';
198                 if (start_attnpos != NULL_POSITION &&
199                     pos >= start_attnpos && pos < end_attnpos)
200                         attr[curr] = AT_NORMAL|AT_HILITE;
201                 else
202                         attr[curr] = AT_NORMAL;
203                 curr++;
204                 column++;
205         }
206         /*
207          * Display the line number at the start of each line
208          * if the -N option is set.
209          */
210         if (linenums == OPT_ONPLUS)
211         {
212                 char buf[INT_STRLEN_BOUND(pos) + 2];
213                 int n;
214
215                 linenumtoa(linenum, buf);
216                 n = strlen(buf);
217                 if (n < MIN_LINENUM_WIDTH)
218                         n = MIN_LINENUM_WIDTH;
219                 sprintf(linebuf+curr, "%*s ", n, buf);
220                 n++;  /* One space after the line number. */
221                 for (i = 0; i < n; i++)
222                         attr[curr+i] = AT_NORMAL;
223                 curr += n;
224                 column += n;
225                 lmargin += n;
226         }
227
228         /*
229          * Append enough spaces to bring us to the lmargin.
230          */
231         while (column < lmargin)
232         {
233                 linebuf[curr] = ' ';
234                 attr[curr++] = AT_NORMAL;
235                 column++;
236         }
237 }
238
239 /*
240  * Shift the input line left.
241  * This means discarding N printable chars at the start of the buffer.
242  */
243         static void
244 pshift(shift)
245         int shift;
246 {
247         LWCHAR prev_ch = 0;
248         unsigned char c;
249         int shifted = 0;
250         int to;
251         int from;
252         int len;
253         int width;
254         int prev_attr;
255         int next_attr;
256
257         if (shift > column - lmargin)
258                 shift = column - lmargin;
259         if (shift > curr - lmargin)
260                 shift = curr - lmargin;
261
262         to = from = lmargin;
263         /*
264          * We keep on going when shifted == shift
265          * to get all combining chars.
266          */
267         while (shifted <= shift && from < curr)
268         {
269                 c = linebuf[from];
270                 if (c == ESC && ctldisp == OPT_ONPLUS)
271                 {
272                         /* Keep cumulative effect.  */
273                         linebuf[to] = c;
274                         attr[to++] = attr[from++];
275                         while (from < curr && linebuf[from])
276                         {
277                                 linebuf[to] = linebuf[from];
278                                 attr[to++] = attr[from];
279                                 if (!is_ansi_middle(linebuf[from++]))
280                                         break;
281                         } 
282                         continue;
283                 }
284
285                 width = 0;
286
287                 if (!IS_ASCII_OCTET(c) && utf_mode)
288                 {
289                         /* Assumes well-formedness validation already done.  */
290                         LWCHAR ch;
291
292                         len = utf_len(c);
293                         if (from + len > curr)
294                                 break;
295                         ch = get_wchar(linebuf + from);
296                         if (!is_composing_char(ch) && !is_combining_char(prev_ch, ch))
297                                 width = is_wide_char(ch) ? 2 : 1;
298                         prev_ch = ch;
299                 } else
300                 {
301                         len = 1;
302                         if (c == '\b')
303                                 /* XXX - Incorrect if several '\b' in a row.  */
304                                 width = (utf_mode && is_wide_char(prev_ch)) ? -2 : -1;
305                         else if (!control_char(c))
306                                 width = 1;
307                         prev_ch = 0;
308                 }
309
310                 if (width == 2 && shift - shifted == 1) {
311                         /* Should never happen when called by pshift_all().  */
312                         attr[to] = attr[from];
313                         /*
314                          * Assume a wide_char will never be the first half of a
315                          * combining_char pair, so reset prev_ch in case we're
316                          * followed by a '\b'.
317                          */
318                         prev_ch = linebuf[to++] = ' ';
319                         from += len;
320                         shifted++;
321                         continue;
322                 }
323
324                 /* Adjust width for magic cookies. */
325                 prev_attr = (to > 0) ? attr[to-1] : AT_NORMAL;
326                 next_attr = (from + len < curr) ? attr[from + len] : prev_attr;
327                 if (!is_at_equiv(attr[from], prev_attr) && 
328                         !is_at_equiv(attr[from], next_attr))
329                 {
330                         width += attr_swidth(attr[from]);
331                         if (from + len < curr)
332                                 width += attr_ewidth(attr[from]);
333                         if (is_at_equiv(prev_attr, next_attr))
334                         {
335                                 width += attr_ewidth(prev_attr);
336                                 if (from + len < curr)
337                                         width += attr_swidth(next_attr);
338                         }
339                 }
340
341                 if (shift - shifted < width)
342                         break;
343                 from += len;
344                 shifted += width;
345                 if (shifted < 0)
346                         shifted = 0;
347         }
348         while (from < curr)
349         {
350                 linebuf[to] = linebuf[from];
351                 attr[to++] = attr[from++];
352         }
353         curr = to;
354         column -= shifted;
355         cshift += shifted;
356 }
357
358 /*
359  *
360  */
361         public void
362 pshift_all()
363 {
364         pshift(column);
365 }
366
367 /*
368  * Return the printing width of the start (enter) sequence
369  * for a given character attribute.
370  */
371         static int
372 attr_swidth(a)
373         int a;
374 {
375         int w = 0;
376
377         a = apply_at_specials(a);
378
379         if (a & AT_UNDERLINE)
380                 w += ul_s_width;
381         if (a & AT_BOLD)
382                 w += bo_s_width;
383         if (a & AT_BLINK)
384                 w += bl_s_width;
385         if (a & AT_STANDOUT)
386                 w += so_s_width;
387
388         return w;
389 }
390
391 /*
392  * Return the printing width of the end (exit) sequence
393  * for a given character attribute.
394  */
395         static int
396 attr_ewidth(a)
397         int a;
398 {
399         int w = 0;
400
401         a = apply_at_specials(a);
402
403         if (a & AT_UNDERLINE)
404                 w += ul_e_width;
405         if (a & AT_BOLD)
406                 w += bo_e_width;
407         if (a & AT_BLINK)
408                 w += bl_e_width;
409         if (a & AT_STANDOUT)
410                 w += so_e_width;
411
412         return w;
413 }
414
415 /*
416  * Return the printing width of a given character and attribute,
417  * if the character were added to the current position in the line buffer.
418  * Adding a character with a given attribute may cause an enter or exit
419  * attribute sequence to be inserted, so this must be taken into account.
420  */
421         static int
422 pwidth(ch, a, prev_ch)
423         LWCHAR ch;
424         int a;
425         LWCHAR prev_ch;
426 {
427         int w;
428
429         if (ch == '\b')
430                 /*
431                  * Backspace moves backwards one or two positions.
432                  * XXX - Incorrect if several '\b' in a row.
433                  */
434                 return (utf_mode && is_wide_char(prev_ch)) ? -2 : -1;
435
436         if (!utf_mode || is_ascii_char(ch))
437         {
438                 if (control_char((char)ch))
439                 {
440                         /*
441                          * Control characters do unpredictable things,
442                          * so we don't even try to guess; say it doesn't move.
443                          * This can only happen if the -r flag is in effect.
444                          */
445                         return (0);
446                 }
447         } else
448         {
449                 if (is_composing_char(ch) || is_combining_char(prev_ch, ch))
450                 {
451                         /*
452                          * Composing and combining chars take up no space.
453                          *
454                          * Some terminals, upon failure to compose a
455                          * composing character with the character(s) that
456                          * precede(s) it will actually take up one column
457                          * for the composing character; there isn't much
458                          * we could do short of testing the (complex)
459                          * composition process ourselves and printing
460                          * a binary representation when it fails.
461                          */
462                         return (0);
463                 }
464         }
465
466         /*
467          * Other characters take one or two columns,
468          * plus the width of any attribute enter/exit sequence.
469          */
470         w = 1;
471         if (is_wide_char(ch))
472                 w++;
473         if (curr > 0 && !is_at_equiv(attr[curr-1], a))
474                 w += attr_ewidth(attr[curr-1]);
475         if ((apply_at_specials(a) != AT_NORMAL) &&
476             (curr == 0 || !is_at_equiv(attr[curr-1], a)))
477                 w += attr_swidth(a);
478         return (w);
479 }
480
481 /*
482  * Delete to the previous base character in the line buffer.
483  * Return 1 if one is found.
484  */
485         static int
486 backc()
487 {
488         LWCHAR prev_ch;
489         char *p = linebuf + curr;
490         LWCHAR ch = step_char(&p, -1, linebuf + lmargin);
491         int width;
492
493         /* This assumes that there is no '\b' in linebuf.  */
494         while (   curr > lmargin
495                && column > lmargin
496                && (!(attr[curr - 1] & (AT_ANSI|AT_BINARY))))
497         {
498                 curr = p - linebuf;
499                 prev_ch = step_char(&p, -1, linebuf + lmargin);
500                 width = pwidth(ch, attr[curr], prev_ch);
501                 column -= width;
502                 if (width > 0)
503                         return 1;
504                 ch = prev_ch;
505         }
506
507         return 0;
508 }
509
510 /*
511  * Are we currently within a recognized ANSI escape sequence?
512  */
513         static int
514 in_ansi_esc_seq()
515 {
516         char *p;
517
518         /*
519          * Search backwards for either an ESC (which means we ARE in a seq);
520          * or an end char (which means we're NOT in a seq).
521          */
522         for (p = &linebuf[curr];  p > linebuf; )
523         {
524                 LWCHAR ch = step_char(&p, -1, linebuf);
525                 if (ch == ESC)
526                         return (1);
527                 if (!is_ansi_middle(ch))
528                         return (0);
529         }
530         return (0);
531 }
532
533 /*
534  * Is a character the end of an ANSI escape sequence?
535  */
536         public int
537 is_ansi_end(ch)
538         LWCHAR ch;
539 {
540         if (!is_ascii_char(ch))
541                 return (0);
542         return (strchr(end_ansi_chars, (char) ch) != NULL);
543 }
544
545 /*
546  *
547  */
548         public int
549 is_ansi_middle(ch)
550         LWCHAR ch;
551 {
552         if (!is_ascii_char(ch))
553                 return (0);
554         if (is_ansi_end(ch))
555                 return (0);
556         return (strchr(mid_ansi_chars, (char) ch) != NULL);
557 }
558
559 /*
560  * Append a character and attribute to the line buffer.
561  */
562 #define STORE_CHAR(ch,a,rep,pos) \
563         do { \
564                 if (store_char((ch),(a),(rep),(pos))) return (1); \
565         } while (0)
566
567         static int
568 store_char(ch, a, rep, pos)
569         LWCHAR ch;
570         int a;
571         char *rep;
572         POSITION pos;
573 {
574         int w;
575         int replen;
576         char cs;
577
578         w = (a & (AT_UNDERLINE|AT_BOLD));       /* Pre-use w.  */
579         if (w != AT_NORMAL)
580                 last_overstrike = w;
581
582 #if HILITE_SEARCH
583         {
584                 int matches;
585                 if (is_hilited(pos, pos+1, 0, &matches))
586                 {
587                         /*
588                          * This character should be highlighted.
589                          * Override the attribute passed in.
590                          */
591                         if (a != AT_ANSI)
592                                 a |= AT_HILITE;
593                 }
594                 line_matches += matches;
595         }
596 #endif
597
598         if (ctldisp == OPT_ONPLUS && in_ansi_esc_seq())
599         {
600                 if (!is_ansi_end(ch) && !is_ansi_middle(ch)) {
601                         /* Remove whole unrecognized sequence.  */
602                         do {
603                                 --curr;
604                         } while (linebuf[curr] != ESC);
605                         return 0;
606                 }
607                 a = AT_ANSI;    /* Will force re-AT_'ing around it.  */
608                 w = 0;
609         }
610         else if (ctldisp == OPT_ONPLUS && ch == ESC)
611         {
612                 a = AT_ANSI;    /* Will force re-AT_'ing around it.  */
613                 w = 0;
614         }
615         else
616         {
617                 char *p = &linebuf[curr];
618                 LWCHAR prev_ch = step_char(&p, -1, linebuf);
619                 w = pwidth(ch, a, prev_ch);
620         }
621
622         if (ctldisp != OPT_ON && column + w + attr_ewidth(a) > sc_width)
623                 /*
624                  * Won't fit on screen.
625                  */
626                 return (1);
627
628         if (rep == NULL)
629         {
630                 cs = (char) ch;
631                 rep = &cs;
632                 replen = 1;
633         } else
634         {
635                 replen = utf_len(rep[0]);
636         }
637         if (curr + replen >= size_linebuf-6)
638         {
639                 /*
640                  * Won't fit in line buffer.
641                  * Try to expand it.
642                  */
643                 if (expand_linebuf())
644                         return (1);
645         }
646
647         while (replen-- > 0)
648         {
649                 linebuf[curr] = *rep++;
650                 attr[curr] = a;
651                 curr++;
652         }
653         column += w;
654         return (0);
655 }
656
657 /*
658  * Append a tab to the line buffer.
659  * Store spaces to represent the tab.
660  */
661 #define STORE_TAB(a,pos) \
662         do { if (store_tab((a),(pos))) return (1); } while (0)
663
664         static int
665 store_tab(attr, pos)
666         int attr;
667         POSITION pos;
668 {
669         int to_tab = column + cshift - lmargin;
670         int i;
671
672         if (ntabstops < 2 || to_tab >= tabstops[ntabstops-1])
673                 to_tab = tabdefault -
674                      ((to_tab - tabstops[ntabstops-1]) % tabdefault);
675         else
676         {
677                 for (i = ntabstops - 2;  i >= 0;  i--)
678                         if (to_tab >= tabstops[i])
679                                 break;
680                 to_tab = tabstops[i+1] - to_tab;
681         }
682
683         if (column + to_tab - 1 + pwidth(' ', attr, 0) + attr_ewidth(attr) > sc_width)
684                 return 1;
685
686         do {
687                 STORE_CHAR(' ', attr, " ", pos);
688         } while (--to_tab > 0);
689         return 0;
690 }
691
692 #define STORE_PRCHAR(c, pos) \
693         do { if (store_prchar((c), (pos))) return 1; } while (0)
694
695         static int
696 store_prchar(c, pos)
697         char c;
698         POSITION pos;
699 {
700         char *s;
701
702         /*
703          * Convert to printable representation.
704          */
705         s = prchar(c);
706
707         /*
708          * Make sure we can get the entire representation
709          * of the character on this line.
710          */
711         if (column + (int) strlen(s) - 1 +
712             pwidth(' ', binattr, 0) + attr_ewidth(binattr) > sc_width)
713                 return 1;
714
715         for ( ;  *s != 0;  s++)
716                 STORE_CHAR(*s, AT_BINARY, NULL, pos);
717
718         return 0;
719 }
720
721         static int
722 flush_mbc_buf(pos)
723         POSITION pos;
724 {
725         int i;
726
727         for (i = 0; i < mbc_buf_index; i++)
728                 if (store_prchar(mbc_buf[i], pos))
729                         return mbc_buf_index - i;
730
731         return 0;
732 }
733
734 /*
735  * Append a character to the line buffer.
736  * Expand tabs into spaces, handle underlining, boldfacing, etc.
737  * Returns 0 if ok, 1 if couldn't fit in buffer.
738  */
739         public int
740 pappend(c, pos)
741         char c;
742         POSITION pos;
743 {
744         int r;
745
746         if (pendc)
747         {
748                 if (do_append(pendc, NULL, pendpos))
749                         /*
750                          * Oops.  We've probably lost the char which
751                          * was in pendc, since caller won't back up.
752                          */
753                         return (1);
754                 pendc = '\0';
755         }
756
757         if (c == '\r' && bs_mode == BS_SPECIAL)
758         {
759                 if (mbc_buf_len > 0)  /* utf_mode must be on. */
760                 {
761                         /* Flush incomplete (truncated) sequence. */
762                         r = flush_mbc_buf(mbc_pos);
763                         mbc_buf_index = r + 1;
764                         mbc_buf_len = 0;
765                         if (r)
766                                 return (mbc_buf_index);
767                 }
768
769                 /*
770                  * Don't put the CR into the buffer until we see 
771                  * the next char.  If the next char is a newline,
772                  * discard the CR.
773                  */
774                 pendc = c;
775                 pendpos = pos;
776                 return (0);
777         }
778
779         if (!utf_mode)
780         {
781                 r = do_append((LWCHAR) c, NULL, pos);
782         } else
783         {
784                 /* Perform strict validation in all possible cases. */
785                 if (mbc_buf_len == 0)
786                 {
787                 retry:
788                         mbc_buf_index = 1;
789                         *mbc_buf = c;
790                         if (IS_ASCII_OCTET(c))
791                                 r = do_append((LWCHAR) c, NULL, pos);
792                         else if (IS_UTF8_LEAD(c))
793                         {
794                                 mbc_buf_len = utf_len(c);
795                                 mbc_pos = pos;
796                                 return (0);
797                         } else
798                                 /* UTF8_INVALID or stray UTF8_TRAIL */
799                                 r = flush_mbc_buf(pos);
800                 } else if (IS_UTF8_TRAIL(c))
801                 {
802                         mbc_buf[mbc_buf_index++] = c;
803                         if (mbc_buf_index < mbc_buf_len)
804                                 return (0);
805                         if (is_utf8_well_formed(mbc_buf))
806                                 r = do_append(get_wchar(mbc_buf), mbc_buf, mbc_pos);
807                         else
808                                 /* Complete, but not shortest form, sequence. */
809                                 mbc_buf_index = r = flush_mbc_buf(mbc_pos);
810                         mbc_buf_len = 0;
811                 } else
812                 {
813                         /* Flush incomplete (truncated) sequence.  */
814                         r = flush_mbc_buf(mbc_pos);
815                         mbc_buf_index = r + 1;
816                         mbc_buf_len = 0;
817                         /* Handle new char.  */
818                         if (!r)
819                                 goto retry;
820                 }
821         }
822
823         /*
824          * If we need to shift the line, do it.
825          * But wait until we get to at least the middle of the screen,
826          * so shifting it doesn't affect the chars we're currently
827          * pappending.  (Bold & underline can get messed up otherwise.)
828          */
829         if (cshift < hshift && column > sc_width / 2)
830         {
831                 linebuf[curr] = '\0';
832                 pshift(hshift - cshift);
833         }
834         if (r)
835         {
836                 /* How many chars should caller back up? */
837                 r = (!utf_mode) ? 1 : mbc_buf_index;
838         }
839         return (r);
840 }
841
842         static int
843 do_append(ch, rep, pos)
844         LWCHAR ch;
845         char *rep;
846         POSITION pos;
847 {
848         register int a;
849         LWCHAR prev_ch;
850
851         a = AT_NORMAL;
852
853         if (ch == '\b')
854         {
855                 if (bs_mode == BS_CONTROL)
856                         goto do_control_char;
857
858                 /*
859                  * A better test is needed here so we don't
860                  * backspace over part of the printed
861                  * representation of a binary character.
862                  */
863                 if (   curr <= lmargin
864                     || column <= lmargin
865                     || (attr[curr - 1] & (AT_ANSI|AT_BINARY)))
866                         STORE_PRCHAR('\b', pos);
867                 else if (bs_mode == BS_NORMAL)
868                         STORE_CHAR(ch, AT_NORMAL, NULL, pos);
869                 else if (bs_mode == BS_SPECIAL)
870                         overstrike = backc();
871
872                 return 0;
873         }
874
875         if (overstrike > 0)
876         {
877                 /*
878                  * Overstrike the character at the current position
879                  * in the line buffer.  This will cause either 
880                  * underline (if a "_" is overstruck), 
881                  * bold (if an identical character is overstruck),
882                  * or just deletion of the character in the buffer.
883                  */
884                 overstrike = utf_mode ? -1 : 0;
885                 /* To be correct, this must be a base character.  */
886                 prev_ch = get_wchar(linebuf + curr);
887                 a = attr[curr];
888                 if (ch == prev_ch)
889                 {
890                         /*
891                          * Overstriking a char with itself means make it bold.
892                          * But overstriking an underscore with itself is
893                          * ambiguous.  It could mean make it bold, or
894                          * it could mean make it underlined.
895                          * Use the previous overstrike to resolve it.
896                          */
897                         if (ch == '_')
898                         {
899                                 if ((a & (AT_BOLD|AT_UNDERLINE)) != AT_NORMAL)
900                                         a |= (AT_BOLD|AT_UNDERLINE);
901                                 else if (last_overstrike != AT_NORMAL)
902                                         a |= last_overstrike;
903                                 else
904                                         a |= AT_BOLD;
905                         } else
906                                 a |= AT_BOLD;
907                 } else if (ch == '_')
908                 {
909                         a |= AT_UNDERLINE;
910                         ch = prev_ch;
911                         rep = linebuf + curr;
912                 } else if (prev_ch == '_')
913                 {
914                         a |= AT_UNDERLINE;
915                 }
916                 /* Else we replace prev_ch, but we keep its attributes.  */
917         } else if (overstrike < 0)
918         {
919                 if (   is_composing_char(ch)
920                     || is_combining_char(get_wchar(linebuf + curr), ch))
921                         /* Continuation of the same overstrike.  */
922                         a = last_overstrike;
923                 else
924                         overstrike = 0;
925         }
926
927         if (ch == '\t') 
928         {
929                 /*
930                  * Expand a tab into spaces.
931                  */
932                 switch (bs_mode)
933                 {
934                 case BS_CONTROL:
935                         goto do_control_char;
936                 case BS_NORMAL:
937                 case BS_SPECIAL:
938                         STORE_TAB(a, pos);
939                         break;
940                 }
941         } else if ((!utf_mode || is_ascii_char(ch)) && control_char((char)ch))
942         {
943         do_control_char:
944                 if (ctldisp == OPT_ON || (ctldisp == OPT_ONPLUS && ch == ESC))
945                 {
946                         /*
947                          * Output as a normal character.
948                          */
949                         STORE_CHAR(ch, AT_NORMAL, rep, pos);
950                 } else 
951                 {
952                         STORE_PRCHAR((char) ch, pos);
953                 }
954         } else if (utf_mode && ctldisp != OPT_ON && is_ubin_char(ch))
955         {
956                 char *s;
957
958                 s = prutfchar(ch);
959
960                 if (column + (int) strlen(s) - 1 +
961                     pwidth(' ', binattr, 0) + attr_ewidth(binattr) > sc_width)
962                         return (1);
963
964                 for ( ;  *s != 0;  s++)
965                         STORE_CHAR(*s, AT_BINARY, NULL, pos);
966         } else
967         {
968                 STORE_CHAR(ch, a, rep, pos);
969         }
970         return (0);
971 }
972
973 /*
974  *
975  */
976         public int
977 pflushmbc()
978 {
979         int r = 0;
980
981         if (mbc_buf_len > 0)
982         {
983                 /* Flush incomplete (truncated) sequence.  */
984                 r = flush_mbc_buf(mbc_pos);
985                 mbc_buf_len = 0;
986         }
987         return r;
988 }
989
990 /*
991  * Terminate the line in the line buffer.
992  */
993         public void
994 pdone(endline)
995         int endline;
996 {
997         (void) pflushmbc();
998
999         if (pendc && (pendc != '\r' || !endline))
1000                 /*
1001                  * If we had a pending character, put it in the buffer.
1002                  * But discard a pending CR if we are at end of line
1003                  * (that is, discard the CR in a CR/LF sequence).
1004                  */
1005                 (void) do_append(pendc, NULL, pendpos);
1006
1007         /*
1008          * Make sure we've shifted the line, if we need to.
1009          */
1010         if (cshift < hshift)
1011                 pshift(hshift - cshift);
1012
1013         if (ctldisp == OPT_ONPLUS && is_ansi_end('m'))
1014         {
1015                 /* Switch to normal attribute at end of line. */
1016                 char *p = "\033[m";
1017                 for ( ;  *p != '\0';  p++)
1018                 {
1019                         linebuf[curr] = *p;
1020                         attr[curr++] = AT_ANSI;
1021                 }
1022         }
1023
1024         /*
1025          * Add a newline if necessary,
1026          * and append a '\0' to the end of the line.
1027          */
1028         if (column < sc_width || !auto_wrap || ignaw || ctldisp == OPT_ON)
1029         {
1030                 linebuf[curr] = '\n';
1031                 attr[curr] = AT_NORMAL;
1032                 curr++;
1033         }
1034         linebuf[curr] = '\0';
1035         attr[curr] = AT_NORMAL;
1036
1037 #if HILITE_SEARCH
1038         if (status_col && line_matches > 0)
1039         {
1040                 linebuf[0] = '*';
1041                 attr[0] = AT_NORMAL|AT_HILITE;
1042         }
1043 #endif
1044 }
1045
1046 /*
1047  * Get a character from the current line.
1048  * Return the character as the function return value,
1049  * and the character attribute in *ap.
1050  */
1051         public int
1052 gline(i, ap)
1053         register int i;
1054         register int *ap;
1055 {
1056         if (is_null_line)
1057         {
1058                 /*
1059                  * If there is no current line, we pretend the line is
1060                  * either "~" or "", depending on the "twiddle" flag.
1061                  */
1062                 if (twiddle)
1063                 {
1064                         if (i == 0)
1065                         {
1066                                 *ap = AT_BOLD;
1067                                 return '~';
1068                         }
1069                         --i;
1070                 }
1071                 /* Make sure we're back to AT_NORMAL before the '\n'.  */
1072                 *ap = AT_NORMAL;
1073                 return i ? '\0' : '\n';
1074         }
1075
1076         *ap = attr[i];
1077         return (linebuf[i] & 0xFF);
1078 }
1079
1080 /*
1081  * Indicate that there is no current line.
1082  */
1083         public void
1084 null_line()
1085 {
1086         is_null_line = 1;
1087         cshift = 0;
1088 }
1089
1090 /*
1091  * Analogous to forw_line(), but deals with "raw lines":
1092  * lines which are not split for screen width.
1093  * {{ This is supposed to be more efficient than forw_line(). }}
1094  */
1095         public POSITION
1096 forw_raw_line(curr_pos, linep)
1097         POSITION curr_pos;
1098         char **linep;
1099 {
1100         register int n;
1101         register int c;
1102         POSITION new_pos;
1103
1104         if (curr_pos == NULL_POSITION || ch_seek(curr_pos) ||
1105                 (c = ch_forw_get()) == EOI)
1106                 return (NULL_POSITION);
1107
1108         n = 0;
1109         for (;;)
1110         {
1111                 if (c == '\n' || c == EOI || ABORT_SIGS())
1112                 {
1113                         new_pos = ch_tell();
1114                         break;
1115                 }
1116                 if (n >= size_linebuf-1)
1117                 {
1118                         if (expand_linebuf())
1119                         {
1120                                 /*
1121                                  * Overflowed the input buffer.
1122                                  * Pretend the line ended here.
1123                                  */
1124                                 new_pos = ch_tell() - 1;
1125                                 break;
1126                         }
1127                 }
1128                 linebuf[n++] = c;
1129                 c = ch_forw_get();
1130         }
1131         linebuf[n] = '\0';
1132         if (linep != NULL)
1133                 *linep = linebuf;
1134         return (new_pos);
1135 }
1136
1137 /*
1138  * Analogous to back_line(), but deals with "raw lines".
1139  * {{ This is supposed to be more efficient than back_line(). }}
1140  */
1141         public POSITION
1142 back_raw_line(curr_pos, linep)
1143         POSITION curr_pos;
1144         char **linep;
1145 {
1146         register int n;
1147         register int c;
1148         POSITION new_pos;
1149
1150         if (curr_pos == NULL_POSITION || curr_pos <= ch_zero() ||
1151                 ch_seek(curr_pos-1))
1152                 return (NULL_POSITION);
1153
1154         n = size_linebuf;
1155         linebuf[--n] = '\0';
1156         for (;;)
1157         {
1158                 c = ch_back_get();
1159                 if (c == '\n' || ABORT_SIGS())
1160                 {
1161                         /*
1162                          * This is the newline ending the previous line.
1163                          * We have hit the beginning of the line.
1164                          */
1165                         new_pos = ch_tell() + 1;
1166                         break;
1167                 }
1168                 if (c == EOI)
1169                 {
1170                         /*
1171                          * We have hit the beginning of the file.
1172                          * This must be the first line in the file.
1173                          * This must, of course, be the beginning of the line.
1174                          */
1175                         new_pos = ch_zero();
1176                         break;
1177                 }
1178                 if (n <= 0)
1179                 {
1180                         int old_size_linebuf = size_linebuf;
1181                         char *fm;
1182                         char *to;
1183                         if (expand_linebuf())
1184                         {
1185                                 /*
1186                                  * Overflowed the input buffer.
1187                                  * Pretend the line ended here.
1188                                  */
1189                                 new_pos = ch_tell() + 1;
1190                                 break;
1191                         }
1192                         /*
1193                          * Shift the data to the end of the new linebuf.
1194                          */
1195                         for (fm = linebuf + old_size_linebuf - 1,
1196                               to = linebuf + size_linebuf - 1;
1197                              fm >= linebuf;  fm--, to--)
1198                                 *to = *fm;
1199                         n = size_linebuf - old_size_linebuf;
1200                 }
1201                 linebuf[--n] = c;
1202         }
1203         if (linep != NULL)
1204                 *linep = &linebuf[n];
1205         return (new_pos);
1206 }