3 * Copyright (C) 1984-2012 Mark Nudelman
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Less License, as specified in the README file.
8 * For more information, see the README file.
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.
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) */
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 public POSITION highest_hilite; /* Pos of last hilite in file found so far */
32 static int curr; /* Index into linebuf */
33 static int column; /* Printable length, accounting for
35 static int overstrike; /* Next char should overstrike previous char */
36 static int last_overstrike = AT_NORMAL;
37 static int is_null_line; /* There is no current line */
38 static int lmargin; /* Left margin */
40 static POSITION pendpos;
41 static char *end_ansi_chars;
42 static char *mid_ansi_chars;
44 static int attr_swidth();
45 static int attr_ewidth();
46 static int do_append();
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;
62 extern POSITION start_attnpos;
63 extern POSITION end_attnpos;
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;
71 * Initialize from environment variables.
76 end_ansi_chars = lgetenv("LESSANSIENDCHARS");
77 if (end_ansi_chars == NULL || *end_ansi_chars == '\0')
80 mid_ansi_chars = lgetenv("LESSANSIMIDCHARS");
81 if (mid_ansi_chars == NULL || *mid_ansi_chars == '\0')
82 mid_ansi_chars = "0123456789;[?!\"'#%()*+ ";
84 linebuf = (char *) ecalloc(LINEBUF_SIZE, sizeof(char));
85 attr = (char *) ecalloc(LINEBUF_SIZE, sizeof(char));
86 size_linebuf = LINEBUF_SIZE;
90 * Expand the line buffer.
95 /* Double the size of the line buffer. */
96 int new_size = size_linebuf * 2;
98 /* Just realloc to expand the buffer, if we can. */
100 char *new_buf = (char *) realloc(linebuf, new_size);
101 char *new_attr = (char *) realloc(attr, new_size);
103 char *new_buf = (char *) calloc(new_size, sizeof(char));
104 char *new_attr = (char *) calloc(new_size, sizeof(char));
106 if (new_buf == NULL || new_attr == NULL)
108 if (new_attr != NULL)
116 * We realloc'd the buffers; they already have the old contents.
119 memset(new_buf + size_linebuf, 0, new_size - size_linebuf);
120 memset(new_attr + size_linebuf, 0, new_size - size_linebuf);
124 * We just calloc'd the buffers; copy the old contents.
126 memcpy(new_buf, linebuf, size_linebuf * sizeof(char));
127 memcpy(new_attr, attr, size_linebuf * sizeof(char));
133 size_linebuf = new_size;
138 * Is a character ASCII?
148 * Rewind the line buffer.
157 last_overstrike = AT_NORMAL;
167 * Insert the line number (of the given position) into the line buffer.
173 register LINENUM linenum = 0;
176 if (linenums == OPT_ONPLUS)
179 * Get the line number and put it in the current line.
180 * {{ Note: since find_linenum calls forw_raw_line,
181 * it may seek in the input file, requiring the caller
182 * of plinenum to re-seek if necessary. }}
183 * {{ Since forw_raw_line modifies linebuf, we must
184 * do this first, before storing anything in linebuf. }}
186 linenum = find_linenum(pos);
190 * Display a status column if the -J option is set.
195 if (start_attnpos != NULL_POSITION &&
196 pos >= start_attnpos && pos < end_attnpos)
197 attr[curr] = AT_NORMAL|AT_HILITE;
199 attr[curr] = AT_NORMAL;
204 * Display the line number at the start of each line
205 * if the -N option is set.
207 if (linenums == OPT_ONPLUS)
209 char buf[INT_STRLEN_BOUND(pos) + 2];
212 linenumtoa(linenum, buf);
214 if (n < MIN_LINENUM_WIDTH)
215 n = MIN_LINENUM_WIDTH;
216 sprintf(linebuf+curr, "%*s ", n, buf);
217 n++; /* One space after the line number. */
218 for (i = 0; i < n; i++)
219 attr[curr+i] = AT_NORMAL;
226 * Append enough spaces to bring us to the lmargin.
228 while (column < lmargin)
231 attr[curr++] = AT_NORMAL;
237 * Shift the input line left.
238 * This means discarding N printable chars at the start of the buffer.
254 if (shift > column - lmargin)
255 shift = column - lmargin;
256 if (shift > curr - lmargin)
257 shift = curr - lmargin;
261 * We keep on going when shifted == shift
262 * to get all combining chars.
264 while (shifted <= shift && from < curr)
267 if (ctldisp == OPT_ONPLUS && IS_CSI_START(c))
269 /* Keep cumulative effect. */
271 attr[to++] = attr[from++];
272 while (from < curr && linebuf[from])
274 linebuf[to] = linebuf[from];
275 attr[to++] = attr[from];
276 if (!is_ansi_middle(linebuf[from++]))
284 if (!IS_ASCII_OCTET(c) && utf_mode)
286 /* Assumes well-formedness validation already done. */
290 if (from + len > curr)
292 ch = get_wchar(linebuf + from);
293 if (!is_composing_char(ch) && !is_combining_char(prev_ch, ch))
294 width = is_wide_char(ch) ? 2 : 1;
300 /* XXX - Incorrect if several '\b' in a row. */
301 width = (utf_mode && is_wide_char(prev_ch)) ? -2 : -1;
302 else if (!control_char(c))
307 if (width == 2 && shift - shifted == 1) {
308 /* Should never happen when called by pshift_all(). */
309 attr[to] = attr[from];
311 * Assume a wide_char will never be the first half of a
312 * combining_char pair, so reset prev_ch in case we're
313 * followed by a '\b'.
315 prev_ch = linebuf[to++] = ' ';
321 /* Adjust width for magic cookies. */
322 prev_attr = (to > 0) ? attr[to-1] : AT_NORMAL;
323 next_attr = (from + len < curr) ? attr[from + len] : prev_attr;
324 if (!is_at_equiv(attr[from], prev_attr) &&
325 !is_at_equiv(attr[from], next_attr))
327 width += attr_swidth(attr[from]);
328 if (from + len < curr)
329 width += attr_ewidth(attr[from]);
330 if (is_at_equiv(prev_attr, next_attr))
332 width += attr_ewidth(prev_attr);
333 if (from + len < curr)
334 width += attr_swidth(next_attr);
338 if (shift - shifted < width)
347 linebuf[to] = linebuf[from];
348 attr[to++] = attr[from++];
365 * Return the printing width of the start (enter) sequence
366 * for a given character attribute.
374 a = apply_at_specials(a);
376 if (a & AT_UNDERLINE)
389 * Return the printing width of the end (exit) sequence
390 * for a given character attribute.
398 a = apply_at_specials(a);
400 if (a & AT_UNDERLINE)
413 * Return the printing width of a given character and attribute,
414 * if the character were added to the current position in the line buffer.
415 * Adding a character with a given attribute may cause an enter or exit
416 * attribute sequence to be inserted, so this must be taken into account.
419 pwidth(ch, a, prev_ch)
428 * Backspace moves backwards one or two positions.
429 * XXX - Incorrect if several '\b' in a row.
431 return (utf_mode && is_wide_char(prev_ch)) ? -2 : -1;
433 if (!utf_mode || is_ascii_char(ch))
435 if (control_char((char)ch))
438 * Control characters do unpredictable things,
439 * so we don't even try to guess; say it doesn't move.
440 * This can only happen if the -r flag is in effect.
446 if (is_composing_char(ch) || is_combining_char(prev_ch, ch))
449 * Composing and combining chars take up no space.
451 * Some terminals, upon failure to compose a
452 * composing character with the character(s) that
453 * precede(s) it will actually take up one column
454 * for the composing character; there isn't much
455 * we could do short of testing the (complex)
456 * composition process ourselves and printing
457 * a binary representation when it fails.
464 * Other characters take one or two columns,
465 * plus the width of any attribute enter/exit sequence.
468 if (is_wide_char(ch))
470 if (curr > 0 && !is_at_equiv(attr[curr-1], a))
471 w += attr_ewidth(attr[curr-1]);
472 if ((apply_at_specials(a) != AT_NORMAL) &&
473 (curr == 0 || !is_at_equiv(attr[curr-1], a)))
479 * Delete to the previous base character in the line buffer.
480 * Return 1 if one is found.
486 char *p = linebuf + curr;
487 LWCHAR ch = step_char(&p, -1, linebuf + lmargin);
490 /* This assumes that there is no '\b' in linebuf. */
491 while ( curr > lmargin
493 && (!(attr[curr - 1] & (AT_ANSI|AT_BINARY))))
496 prev_ch = step_char(&p, -1, linebuf + lmargin);
497 width = pwidth(ch, attr[curr], prev_ch);
508 * Are we currently within a recognized ANSI escape sequence?
516 * Search backwards for either an ESC (which means we ARE in a seq);
517 * or an end char (which means we're NOT in a seq).
519 for (p = &linebuf[curr]; p > linebuf; )
521 LWCHAR ch = step_char(&p, -1, linebuf);
522 if (IS_CSI_START(ch))
524 if (!is_ansi_middle(ch))
531 * Is a character the end of an ANSI escape sequence?
537 if (!is_ascii_char(ch))
539 return (strchr(end_ansi_chars, (char) ch) != NULL);
549 if (!is_ascii_char(ch))
553 return (strchr(mid_ansi_chars, (char) ch) != NULL);
557 * Append a character and attribute to the line buffer.
559 #define STORE_CHAR(ch,a,rep,pos) \
561 if (store_char((ch),(a),(rep),(pos))) return (1); \
565 store_char(ch, a, rep, pos)
575 w = (a & (AT_UNDERLINE|AT_BOLD)); /* Pre-use w. */
582 if (is_hilited(pos, pos+1, 0, &matches))
585 * This character should be highlighted.
586 * Override the attribute passed in.
590 if (highest_hilite != NULL_POSITION &&
591 pos > highest_hilite)
592 highest_hilite = pos;
599 if (ctldisp == OPT_ONPLUS && in_ansi_esc_seq())
601 if (!is_ansi_end(ch) && !is_ansi_middle(ch)) {
602 /* Remove whole unrecognized sequence. */
603 char *p = &linebuf[curr];
606 bch = step_char(&p, -1, linebuf);
607 } while (p > linebuf && !IS_CSI_START(bch));
611 a = AT_ANSI; /* Will force re-AT_'ing around it. */
614 else if (ctldisp == OPT_ONPLUS && IS_CSI_START(ch))
616 a = AT_ANSI; /* Will force re-AT_'ing around it. */
621 char *p = &linebuf[curr];
622 LWCHAR prev_ch = step_char(&p, -1, linebuf);
623 w = pwidth(ch, a, prev_ch);
626 if (ctldisp != OPT_ON && column + w + attr_ewidth(a) > sc_width)
628 * Won't fit on screen.
639 replen = utf_len(rep[0]);
641 if (curr + replen >= size_linebuf-6)
644 * Won't fit in line buffer.
647 if (expand_linebuf())
653 linebuf[curr] = *rep++;
662 * Append a tab to the line buffer.
663 * Store spaces to represent the tab.
665 #define STORE_TAB(a,pos) \
666 do { if (store_tab((a),(pos))) return (1); } while (0)
673 int to_tab = column + cshift - lmargin;
676 if (ntabstops < 2 || to_tab >= tabstops[ntabstops-1])
677 to_tab = tabdefault -
678 ((to_tab - tabstops[ntabstops-1]) % tabdefault);
681 for (i = ntabstops - 2; i >= 0; i--)
682 if (to_tab >= tabstops[i])
684 to_tab = tabstops[i+1] - to_tab;
687 if (column + to_tab - 1 + pwidth(' ', attr, 0) + attr_ewidth(attr) > sc_width)
691 STORE_CHAR(' ', attr, " ", pos);
692 } while (--to_tab > 0);
696 #define STORE_PRCHAR(c, pos) \
697 do { if (store_prchar((c), (pos))) return 1; } while (0)
707 * Convert to printable representation.
712 * Make sure we can get the entire representation
713 * of the character on this line.
715 if (column + (int) strlen(s) - 1 +
716 pwidth(' ', binattr, 0) + attr_ewidth(binattr) > sc_width)
719 for ( ; *s != 0; s++)
720 STORE_CHAR(*s, AT_BINARY, NULL, pos);
731 for (i = 0; i < mbc_buf_index; i++)
732 if (store_prchar(mbc_buf[i], pos))
733 return mbc_buf_index - i;
739 * Append a character to the line buffer.
740 * Expand tabs into spaces, handle underlining, boldfacing, etc.
741 * Returns 0 if ok, 1 if couldn't fit in buffer.
752 if (do_append(pendc, NULL, pendpos))
754 * Oops. We've probably lost the char which
755 * was in pendc, since caller won't back up.
761 if (c == '\r' && bs_mode == BS_SPECIAL)
763 if (mbc_buf_len > 0) /* utf_mode must be on. */
765 /* Flush incomplete (truncated) sequence. */
766 r = flush_mbc_buf(mbc_pos);
767 mbc_buf_index = r + 1;
770 return (mbc_buf_index);
774 * Don't put the CR into the buffer until we see
775 * the next char. If the next char is a newline,
785 r = do_append((LWCHAR) c, NULL, pos);
788 /* Perform strict validation in all possible cases. */
789 if (mbc_buf_len == 0)
794 if (IS_ASCII_OCTET(c))
795 r = do_append((LWCHAR) c, NULL, pos);
796 else if (IS_UTF8_LEAD(c))
798 mbc_buf_len = utf_len(c);
802 /* UTF8_INVALID or stray UTF8_TRAIL */
803 r = flush_mbc_buf(pos);
804 } else if (IS_UTF8_TRAIL(c))
806 mbc_buf[mbc_buf_index++] = c;
807 if (mbc_buf_index < mbc_buf_len)
809 if (is_utf8_well_formed(mbc_buf))
810 r = do_append(get_wchar(mbc_buf), mbc_buf, mbc_pos);
812 /* Complete, but not shortest form, sequence. */
813 mbc_buf_index = r = flush_mbc_buf(mbc_pos);
817 /* Flush incomplete (truncated) sequence. */
818 r = flush_mbc_buf(mbc_pos);
819 mbc_buf_index = r + 1;
821 /* Handle new char. */
828 * If we need to shift the line, do it.
829 * But wait until we get to at least the middle of the screen,
830 * so shifting it doesn't affect the chars we're currently
831 * pappending. (Bold & underline can get messed up otherwise.)
833 if (cshift < hshift && column > sc_width / 2)
835 linebuf[curr] = '\0';
836 pshift(hshift - cshift);
840 /* How many chars should caller back up? */
841 r = (!utf_mode) ? 1 : mbc_buf_index;
847 do_append(ch, rep, pos)
859 if (bs_mode == BS_CONTROL)
860 goto do_control_char;
863 * A better test is needed here so we don't
864 * backspace over part of the printed
865 * representation of a binary character.
869 || (attr[curr - 1] & (AT_ANSI|AT_BINARY)))
870 STORE_PRCHAR('\b', pos);
871 else if (bs_mode == BS_NORMAL)
872 STORE_CHAR(ch, AT_NORMAL, NULL, pos);
873 else if (bs_mode == BS_SPECIAL)
874 overstrike = backc();
882 * Overstrike the character at the current position
883 * in the line buffer. This will cause either
884 * underline (if a "_" is overstruck),
885 * bold (if an identical character is overstruck),
886 * or just deletion of the character in the buffer.
888 overstrike = utf_mode ? -1 : 0;
889 /* To be correct, this must be a base character. */
890 prev_ch = get_wchar(linebuf + curr);
895 * Overstriking a char with itself means make it bold.
896 * But overstriking an underscore with itself is
897 * ambiguous. It could mean make it bold, or
898 * it could mean make it underlined.
899 * Use the previous overstrike to resolve it.
903 if ((a & (AT_BOLD|AT_UNDERLINE)) != AT_NORMAL)
904 a |= (AT_BOLD|AT_UNDERLINE);
905 else if (last_overstrike != AT_NORMAL)
906 a |= last_overstrike;
911 } else if (ch == '_')
915 rep = linebuf + curr;
916 } else if (prev_ch == '_')
920 /* Else we replace prev_ch, but we keep its attributes. */
921 } else if (overstrike < 0)
923 if ( is_composing_char(ch)
924 || is_combining_char(get_wchar(linebuf + curr), ch))
925 /* Continuation of the same overstrike. */
934 * Expand a tab into spaces.
939 goto do_control_char;
945 } else if ((!utf_mode || is_ascii_char(ch)) && control_char((char)ch))
948 if (ctldisp == OPT_ON || (ctldisp == OPT_ONPLUS && IS_CSI_START(ch)))
951 * Output as a normal character.
953 STORE_CHAR(ch, AT_NORMAL, rep, pos);
956 STORE_PRCHAR((char) ch, pos);
958 } else if (utf_mode && ctldisp != OPT_ON && is_ubin_char(ch))
964 if (column + (int) strlen(s) - 1 +
965 pwidth(' ', binattr, 0) + attr_ewidth(binattr) > sc_width)
968 for ( ; *s != 0; s++)
969 STORE_CHAR(*s, AT_BINARY, NULL, pos);
972 STORE_CHAR(ch, a, rep, pos);
987 /* Flush incomplete (truncated) sequence. */
988 r = flush_mbc_buf(mbc_pos);
995 * Terminate the line in the line buffer.
1004 if (pendc && (pendc != '\r' || !endline))
1006 * If we had a pending character, put it in the buffer.
1007 * But discard a pending CR if we are at end of line
1008 * (that is, discard the CR in a CR/LF sequence).
1010 (void) do_append(pendc, NULL, pendpos);
1013 * Make sure we've shifted the line, if we need to.
1015 if (cshift < hshift)
1016 pshift(hshift - cshift);
1018 if (ctldisp == OPT_ONPLUS && is_ansi_end('m'))
1020 /* Switch to normal attribute at end of line. */
1022 for ( ; *p != '\0'; p++)
1025 attr[curr++] = AT_ANSI;
1030 * Add a newline if necessary,
1031 * and append a '\0' to the end of the line.
1032 * We output a newline if we're not at the right edge of the screen,
1033 * or if the terminal doesn't auto wrap,
1034 * or if this is really the end of the line AND the terminal ignores
1035 * a newline at the right edge.
1036 * (In the last case we don't want to output a newline if the terminal
1037 * doesn't ignore it since that would produce an extra blank line.
1038 * But we do want to output a newline if the terminal ignores it in case
1039 * the next line is blank. In that case the single newline output for
1040 * that blank line would be ignored!)
1042 if (column < sc_width || !auto_wrap || (endline && ignaw) || ctldisp == OPT_ON)
1044 linebuf[curr] = '\n';
1045 attr[curr] = AT_NORMAL;
1048 else if (ignaw && column >= sc_width && forw)
1051 * Terminals with "ignaw" don't wrap until they *really* need
1052 * to, i.e. when the character *after* the last one to fit on a
1053 * line is output. But they are too hard to deal with when they
1054 * get in the state where a full screen width of characters
1055 * have been output but the cursor is sitting on the right edge
1056 * instead of at the start of the next line.
1057 * So we nudge them into wrapping by outputting a space
1058 * character plus a backspace. But do this only if moving
1059 * forward; if we're moving backward and drawing this line at
1060 * the top of the screen, the space would overwrite the first
1061 * char on the next line. We don't need to do this "nudge"
1062 * at the top of the screen anyway.
1064 linebuf[curr] = ' ';
1065 attr[curr++] = AT_NORMAL;
1066 linebuf[curr] = '\b';
1067 attr[curr++] = AT_NORMAL;
1069 linebuf[curr] = '\0';
1070 attr[curr] = AT_NORMAL;
1081 attr[0] = AT_NORMAL|AT_HILITE;
1085 * Get a character from the current line.
1086 * Return the character as the function return value,
1087 * and the character attribute in *ap.
1097 * If there is no current line, we pretend the line is
1098 * either "~" or "", depending on the "twiddle" flag.
1109 /* Make sure we're back to AT_NORMAL before the '\n'. */
1111 return i ? '\0' : '\n';
1115 return (linebuf[i] & 0xFF);
1119 * Indicate that there is no current line.
1129 * Analogous to forw_line(), but deals with "raw lines":
1130 * lines which are not split for screen width.
1131 * {{ This is supposed to be more efficient than forw_line(). }}
1134 forw_raw_line(curr_pos, linep, line_lenp)
1143 if (curr_pos == NULL_POSITION || ch_seek(curr_pos) ||
1144 (c = ch_forw_get()) == EOI)
1145 return (NULL_POSITION);
1150 if (c == '\n' || c == EOI || ABORT_SIGS())
1152 new_pos = ch_tell();
1155 if (n >= size_linebuf-1)
1157 if (expand_linebuf())
1160 * Overflowed the input buffer.
1161 * Pretend the line ended here.
1163 new_pos = ch_tell() - 1;
1173 if (line_lenp != NULL)
1179 * Analogous to back_line(), but deals with "raw lines".
1180 * {{ This is supposed to be more efficient than back_line(). }}
1183 back_raw_line(curr_pos, linep, line_lenp)
1192 if (curr_pos == NULL_POSITION || curr_pos <= ch_zero() ||
1193 ch_seek(curr_pos-1))
1194 return (NULL_POSITION);
1197 linebuf[--n] = '\0';
1201 if (c == '\n' || ABORT_SIGS())
1204 * This is the newline ending the previous line.
1205 * We have hit the beginning of the line.
1207 new_pos = ch_tell() + 1;
1213 * We have hit the beginning of the file.
1214 * This must be the first line in the file.
1215 * This must, of course, be the beginning of the line.
1217 new_pos = ch_zero();
1222 int old_size_linebuf = size_linebuf;
1225 if (expand_linebuf())
1228 * Overflowed the input buffer.
1229 * Pretend the line ended here.
1231 new_pos = ch_tell() + 1;
1235 * Shift the data to the end of the new linebuf.
1237 for (fm = linebuf + old_size_linebuf - 1,
1238 to = linebuf + size_linebuf - 1;
1239 fm >= linebuf; fm--, to--)
1241 n = size_linebuf - old_size_linebuf;
1246 *linep = &linebuf[n];
1247 if (line_lenp != NULL)
1248 *line_lenp = size_linebuf - 1 - n;