3 * Copyright (C) 1984-2007 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 about less, or for information on how to
9 * contact the author, see the README file.
14 * Routines to manipulate the "line buffer".
15 * The line buffer holds a line of output as it is being built
16 * in preparation for output to the screen.
22 static char *linebuf = NULL; /* Buffer which holds the current output line */
23 static char *attr = NULL; /* Extension of linebuf to hold attributes */
24 public int size_linebuf = 0; /* Size of line buffer (and attr buffer) */
26 static int cshift; /* Current left-shift of output line buffer */
27 public int hshift; /* Desired left-shift of output line buffer */
28 public int tabstops[TABSTOP_MAX] = { 0 }; /* Custom tabstops */
29 public int ntabstops = 1; /* Number of tabstops */
30 public int tabdefault = 8; /* Default repeated tabstops */
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 */
39 static int line_matches; /* Number of search matches in this line */
41 static POSITION pendpos;
42 static char *end_ansi_chars;
43 static char *mid_ansi_chars;
45 static int attr_swidth();
46 static int attr_ewidth();
47 static int do_append();
55 extern int status_col;
56 extern int auto_wrap, ignaw;
57 extern int bo_s_width, bo_e_width;
58 extern int ul_s_width, ul_e_width;
59 extern int bl_s_width, bl_e_width;
60 extern int so_s_width, so_e_width;
61 extern int sc_width, sc_height;
64 extern POSITION start_attnpos;
65 extern POSITION end_attnpos;
67 static char mbc_buf[MAX_UTF_CHAR_LEN];
68 static int mbc_buf_len = 0;
69 static int mbc_buf_index = 0;
70 static POSITION mbc_pos;
73 * Initialize from environment variables.
78 end_ansi_chars = lgetenv("LESSANSIENDCHARS");
79 if (end_ansi_chars == NULL || *end_ansi_chars == '\0')
82 mid_ansi_chars = lgetenv("LESSANSIMIDCHARS");
83 if (mid_ansi_chars == NULL || *mid_ansi_chars == '\0')
84 mid_ansi_chars = "0123456789;[?!\"'#%()*+ ";
86 linebuf = (char *) ecalloc(LINEBUF_SIZE, sizeof(char));
87 attr = (char *) ecalloc(LINEBUF_SIZE, sizeof(char));
88 size_linebuf = LINEBUF_SIZE;
92 * Expand the line buffer.
97 /* Double the size of the line buffer. */
98 int new_size = size_linebuf * 2;
100 /* Just realloc to expand the buffer, if we can. */
102 char *new_buf = (char *) realloc(linebuf, new_size);
103 char *new_attr = (char *) realloc(attr, new_size);
105 char *new_buf = (char *) calloc(new_size, sizeof(char));
106 char *new_attr = (char *) calloc(new_size, sizeof(char));
108 if (new_buf == NULL || new_attr == NULL)
110 if (new_attr != NULL)
118 * We realloc'd the buffers; they already have the old contents.
121 memset(new_buf + size_linebuf, 0, new_size - size_linebuf);
122 memset(new_attr + size_linebuf, 0, new_size - size_linebuf);
126 * We just calloc'd the buffers; copy the old contents.
128 memcpy(new_buf, linebuf, size_linebuf * sizeof(char));
129 memcpy(new_attr, attr, size_linebuf * sizeof(char));
135 size_linebuf = new_size;
140 * Is a character ASCII?
150 * Rewind the line buffer.
159 last_overstrike = AT_NORMAL;
172 * Insert the line number (of the given position) into the line buffer.
178 register LINENUM linenum = 0;
181 if (linenums == OPT_ONPLUS)
184 * Get the line number and put it in the current line.
185 * {{ Note: since find_linenum calls forw_raw_line,
186 * it may seek in the input file, requiring the caller
187 * of plinenum to re-seek if necessary. }}
188 * {{ Since forw_raw_line modifies linebuf, we must
189 * do this first, before storing anything in linebuf. }}
191 linenum = find_linenum(pos);
195 * Display a status column if the -J option is set.
200 if (start_attnpos != NULL_POSITION &&
201 pos >= start_attnpos && pos < end_attnpos)
202 attr[curr] = AT_NORMAL|AT_HILITE;
204 attr[curr] = AT_NORMAL;
209 * Display the line number at the start of each line
210 * if the -N option is set.
212 if (linenums == OPT_ONPLUS)
214 char buf[INT_STRLEN_BOUND(pos) + 2];
217 linenumtoa(linenum, buf);
219 if (n < MIN_LINENUM_WIDTH)
220 n = MIN_LINENUM_WIDTH;
221 sprintf(linebuf+curr, "%*s ", n, buf);
222 n++; /* One space after the line number. */
223 for (i = 0; i < n; i++)
224 attr[curr+i] = AT_NORMAL;
231 * Append enough spaces to bring us to the lmargin.
233 while (column < lmargin)
236 attr[curr++] = AT_NORMAL;
242 * Shift the input line left.
243 * This means discarding N printable chars at the start of the buffer.
259 if (shift > column - lmargin)
260 shift = column - lmargin;
261 if (shift > curr - lmargin)
262 shift = curr - lmargin;
266 * We keep on going when shifted == shift
267 * to get all combining chars.
269 while (shifted <= shift && from < curr)
272 if (ctldisp == OPT_ONPLUS && IS_CSI_START(c))
274 /* Keep cumulative effect. */
276 attr[to++] = attr[from++];
277 while (from < curr && linebuf[from])
279 linebuf[to] = linebuf[from];
280 attr[to++] = attr[from];
281 if (!is_ansi_middle(linebuf[from++]))
289 if (!IS_ASCII_OCTET(c) && utf_mode)
291 /* Assumes well-formedness validation already done. */
295 if (from + len > curr)
297 ch = get_wchar(linebuf + from);
298 if (!is_composing_char(ch) && !is_combining_char(prev_ch, ch))
299 width = is_wide_char(ch) ? 2 : 1;
305 /* XXX - Incorrect if several '\b' in a row. */
306 width = (utf_mode && is_wide_char(prev_ch)) ? -2 : -1;
307 else if (!control_char(c))
312 if (width == 2 && shift - shifted == 1) {
313 /* Should never happen when called by pshift_all(). */
314 attr[to] = attr[from];
316 * Assume a wide_char will never be the first half of a
317 * combining_char pair, so reset prev_ch in case we're
318 * followed by a '\b'.
320 prev_ch = linebuf[to++] = ' ';
326 /* Adjust width for magic cookies. */
327 prev_attr = (to > 0) ? attr[to-1] : AT_NORMAL;
328 next_attr = (from + len < curr) ? attr[from + len] : prev_attr;
329 if (!is_at_equiv(attr[from], prev_attr) &&
330 !is_at_equiv(attr[from], next_attr))
332 width += attr_swidth(attr[from]);
333 if (from + len < curr)
334 width += attr_ewidth(attr[from]);
335 if (is_at_equiv(prev_attr, next_attr))
337 width += attr_ewidth(prev_attr);
338 if (from + len < curr)
339 width += attr_swidth(next_attr);
343 if (shift - shifted < width)
352 linebuf[to] = linebuf[from];
353 attr[to++] = attr[from++];
370 * Return the printing width of the start (enter) sequence
371 * for a given character attribute.
379 a = apply_at_specials(a);
381 if (a & AT_UNDERLINE)
394 * Return the printing width of the end (exit) sequence
395 * for a given character attribute.
403 a = apply_at_specials(a);
405 if (a & AT_UNDERLINE)
418 * Return the printing width of a given character and attribute,
419 * if the character were added to the current position in the line buffer.
420 * Adding a character with a given attribute may cause an enter or exit
421 * attribute sequence to be inserted, so this must be taken into account.
424 pwidth(ch, a, prev_ch)
433 * Backspace moves backwards one or two positions.
434 * XXX - Incorrect if several '\b' in a row.
436 return (utf_mode && is_wide_char(prev_ch)) ? -2 : -1;
438 if (!utf_mode || is_ascii_char(ch))
440 if (control_char((char)ch))
443 * Control characters do unpredictable things,
444 * so we don't even try to guess; say it doesn't move.
445 * This can only happen if the -r flag is in effect.
451 if (is_composing_char(ch) || is_combining_char(prev_ch, ch))
454 * Composing and combining chars take up no space.
456 * Some terminals, upon failure to compose a
457 * composing character with the character(s) that
458 * precede(s) it will actually take up one column
459 * for the composing character; there isn't much
460 * we could do short of testing the (complex)
461 * composition process ourselves and printing
462 * a binary representation when it fails.
469 * Other characters take one or two columns,
470 * plus the width of any attribute enter/exit sequence.
473 if (is_wide_char(ch))
475 if (curr > 0 && !is_at_equiv(attr[curr-1], a))
476 w += attr_ewidth(attr[curr-1]);
477 if ((apply_at_specials(a) != AT_NORMAL) &&
478 (curr == 0 || !is_at_equiv(attr[curr-1], a)))
484 * Delete to the previous base character in the line buffer.
485 * Return 1 if one is found.
491 char *p = linebuf + curr;
492 LWCHAR ch = step_char(&p, -1, linebuf + lmargin);
495 /* This assumes that there is no '\b' in linebuf. */
496 while ( curr > lmargin
498 && (!(attr[curr - 1] & (AT_ANSI|AT_BINARY))))
501 prev_ch = step_char(&p, -1, linebuf + lmargin);
502 width = pwidth(ch, attr[curr], prev_ch);
513 * Are we currently within a recognized ANSI escape sequence?
521 * Search backwards for either an ESC (which means we ARE in a seq);
522 * or an end char (which means we're NOT in a seq).
524 for (p = &linebuf[curr]; p > linebuf; )
526 LWCHAR ch = step_char(&p, -1, linebuf);
527 if (IS_CSI_START(ch))
529 if (!is_ansi_middle(ch))
536 * Is a character the end of an ANSI escape sequence?
542 if (!is_ascii_char(ch))
544 return (strchr(end_ansi_chars, (char) ch) != NULL);
554 if (!is_ascii_char(ch))
558 return (strchr(mid_ansi_chars, (char) ch) != NULL);
562 * Append a character and attribute to the line buffer.
564 #define STORE_CHAR(ch,a,rep,pos) \
566 if (store_char((ch),(a),(rep),(pos))) return (1); \
570 store_char(ch, a, rep, pos)
580 w = (a & (AT_UNDERLINE|AT_BOLD)); /* Pre-use w. */
587 if (is_hilited(pos, pos+1, 0, &matches))
590 * This character should be highlighted.
591 * Override the attribute passed in.
596 line_matches += matches;
600 if (ctldisp == OPT_ONPLUS && in_ansi_esc_seq())
602 if (!is_ansi_end(ch) && !is_ansi_middle(ch)) {
603 /* Remove whole unrecognized sequence. */
606 } while (!IS_CSI_START(linebuf[curr]));
609 a = AT_ANSI; /* Will force re-AT_'ing around it. */
612 else if (ctldisp == OPT_ONPLUS && IS_CSI_START(ch))
614 a = AT_ANSI; /* Will force re-AT_'ing around it. */
619 char *p = &linebuf[curr];
620 LWCHAR prev_ch = step_char(&p, -1, linebuf);
621 w = pwidth(ch, a, prev_ch);
624 if (ctldisp != OPT_ON && column + w + attr_ewidth(a) > sc_width)
626 * Won't fit on screen.
637 replen = utf_len(rep[0]);
639 if (curr + replen >= size_linebuf-6)
642 * Won't fit in line buffer.
645 if (expand_linebuf())
651 linebuf[curr] = *rep++;
660 * Append a tab to the line buffer.
661 * Store spaces to represent the tab.
663 #define STORE_TAB(a,pos) \
664 do { if (store_tab((a),(pos))) return (1); } while (0)
671 int to_tab = column + cshift - lmargin;
674 if (ntabstops < 2 || to_tab >= tabstops[ntabstops-1])
675 to_tab = tabdefault -
676 ((to_tab - tabstops[ntabstops-1]) % tabdefault);
679 for (i = ntabstops - 2; i >= 0; i--)
680 if (to_tab >= tabstops[i])
682 to_tab = tabstops[i+1] - to_tab;
685 if (column + to_tab - 1 + pwidth(' ', attr, 0) + attr_ewidth(attr) > sc_width)
689 STORE_CHAR(' ', attr, " ", pos);
690 } while (--to_tab > 0);
694 #define STORE_PRCHAR(c, pos) \
695 do { if (store_prchar((c), (pos))) return 1; } while (0)
705 * Convert to printable representation.
710 * Make sure we can get the entire representation
711 * of the character on this line.
713 if (column + (int) strlen(s) - 1 +
714 pwidth(' ', binattr, 0) + attr_ewidth(binattr) > sc_width)
717 for ( ; *s != 0; s++)
718 STORE_CHAR(*s, AT_BINARY, NULL, pos);
729 for (i = 0; i < mbc_buf_index; i++)
730 if (store_prchar(mbc_buf[i], pos))
731 return mbc_buf_index - i;
737 * Append a character to the line buffer.
738 * Expand tabs into spaces, handle underlining, boldfacing, etc.
739 * Returns 0 if ok, 1 if couldn't fit in buffer.
750 if (do_append(pendc, NULL, pendpos))
752 * Oops. We've probably lost the char which
753 * was in pendc, since caller won't back up.
759 if (c == '\r' && bs_mode == BS_SPECIAL)
761 if (mbc_buf_len > 0) /* utf_mode must be on. */
763 /* Flush incomplete (truncated) sequence. */
764 r = flush_mbc_buf(mbc_pos);
765 mbc_buf_index = r + 1;
768 return (mbc_buf_index);
772 * Don't put the CR into the buffer until we see
773 * the next char. If the next char is a newline,
783 r = do_append((LWCHAR) c, NULL, pos);
786 /* Perform strict validation in all possible cases. */
787 if (mbc_buf_len == 0)
792 if (IS_ASCII_OCTET(c))
793 r = do_append((LWCHAR) c, NULL, pos);
794 else if (IS_UTF8_LEAD(c))
796 mbc_buf_len = utf_len(c);
800 /* UTF8_INVALID or stray UTF8_TRAIL */
801 r = flush_mbc_buf(pos);
802 } else if (IS_UTF8_TRAIL(c))
804 mbc_buf[mbc_buf_index++] = c;
805 if (mbc_buf_index < mbc_buf_len)
807 if (is_utf8_well_formed(mbc_buf))
808 r = do_append(get_wchar(mbc_buf), mbc_buf, mbc_pos);
810 /* Complete, but not shortest form, sequence. */
811 mbc_buf_index = r = flush_mbc_buf(mbc_pos);
815 /* Flush incomplete (truncated) sequence. */
816 r = flush_mbc_buf(mbc_pos);
817 mbc_buf_index = r + 1;
819 /* Handle new char. */
826 * If we need to shift the line, do it.
827 * But wait until we get to at least the middle of the screen,
828 * so shifting it doesn't affect the chars we're currently
829 * pappending. (Bold & underline can get messed up otherwise.)
831 if (cshift < hshift && column > sc_width / 2)
833 linebuf[curr] = '\0';
834 pshift(hshift - cshift);
838 /* How many chars should caller back up? */
839 r = (!utf_mode) ? 1 : mbc_buf_index;
845 do_append(ch, rep, pos)
857 if (bs_mode == BS_CONTROL)
858 goto do_control_char;
861 * A better test is needed here so we don't
862 * backspace over part of the printed
863 * representation of a binary character.
867 || (attr[curr - 1] & (AT_ANSI|AT_BINARY)))
868 STORE_PRCHAR('\b', pos);
869 else if (bs_mode == BS_NORMAL)
870 STORE_CHAR(ch, AT_NORMAL, NULL, pos);
871 else if (bs_mode == BS_SPECIAL)
872 overstrike = backc();
880 * Overstrike the character at the current position
881 * in the line buffer. This will cause either
882 * underline (if a "_" is overstruck),
883 * bold (if an identical character is overstruck),
884 * or just deletion of the character in the buffer.
886 overstrike = utf_mode ? -1 : 0;
887 /* To be correct, this must be a base character. */
888 prev_ch = get_wchar(linebuf + curr);
893 * Overstriking a char with itself means make it bold.
894 * But overstriking an underscore with itself is
895 * ambiguous. It could mean make it bold, or
896 * it could mean make it underlined.
897 * Use the previous overstrike to resolve it.
901 if ((a & (AT_BOLD|AT_UNDERLINE)) != AT_NORMAL)
902 a |= (AT_BOLD|AT_UNDERLINE);
903 else if (last_overstrike != AT_NORMAL)
904 a |= last_overstrike;
909 } else if (ch == '_')
913 rep = linebuf + curr;
914 } else if (prev_ch == '_')
918 /* Else we replace prev_ch, but we keep its attributes. */
919 } else if (overstrike < 0)
921 if ( is_composing_char(ch)
922 || is_combining_char(get_wchar(linebuf + curr), ch))
923 /* Continuation of the same overstrike. */
932 * Expand a tab into spaces.
937 goto do_control_char;
943 } else if ((!utf_mode || is_ascii_char(ch)) && control_char((char)ch))
946 if (ctldisp == OPT_ON || (ctldisp == OPT_ONPLUS && IS_CSI_START(ch)))
949 * Output as a normal character.
951 STORE_CHAR(ch, AT_NORMAL, rep, pos);
954 STORE_PRCHAR((char) ch, pos);
956 } else if (utf_mode && ctldisp != OPT_ON && is_ubin_char(ch))
962 if (column + (int) strlen(s) - 1 +
963 pwidth(' ', binattr, 0) + attr_ewidth(binattr) > sc_width)
966 for ( ; *s != 0; s++)
967 STORE_CHAR(*s, AT_BINARY, NULL, pos);
970 STORE_CHAR(ch, a, rep, pos);
985 /* Flush incomplete (truncated) sequence. */
986 r = flush_mbc_buf(mbc_pos);
993 * Terminate the line in the line buffer.
1003 if (pendc && (pendc != '\r' || !endline))
1005 * If we had a pending character, put it in the buffer.
1006 * But discard a pending CR if we are at end of line
1007 * (that is, discard the CR in a CR/LF sequence).
1009 (void) do_append(pendc, NULL, pendpos);
1012 * Make sure we've shifted the line, if we need to.
1014 if (cshift < hshift)
1015 pshift(hshift - cshift);
1017 if (ctldisp == OPT_ONPLUS && is_ansi_end('m'))
1019 /* Switch to normal attribute at end of line. */
1021 for ( ; *p != '\0'; p++)
1024 attr[curr++] = AT_ANSI;
1029 * Add a newline if necessary,
1030 * and append a '\0' to the end of the line.
1031 * We output a newline if we're not at the right edge of the screen,
1032 * or if the terminal doesn't auto wrap,
1033 * or if this is really the end of the line AND the terminal ignores
1034 * a newline at the right edge.
1035 * (In the last case we don't want to output a newline if the terminal
1036 * doesn't ignore it since that would produce an extra blank line.
1037 * But we do want to output a newline if the terminal ignores it in case
1038 * the next line is blank. In that case the single newline output for
1039 * that blank line would be ignored!)
1042 nl = (column < sc_width || !auto_wrap || (endline && ignaw) || ctldisp == OPT_ON);
1044 nl = (column < sc_width || !auto_wrap || ignaw || ctldisp == OPT_ON);
1047 linebuf[curr] = '\n';
1048 attr[curr] = AT_NORMAL;
1051 else if (ignaw && !auto_wrap && column >= sc_width)
1054 * Big horrible kludge.
1055 * No-wrap terminals are too hard to deal with when they get in
1056 * the state where a full screen width of characters have been
1057 * output but the cursor is sitting on the right edge instead
1058 * of at the start of the next line.
1059 * So after we output a full line, we output an extra
1060 * space and backspace to force the cursor to the
1061 * beginning of the next line, like a sane terminal.
1063 linebuf[curr] = ' ';
1064 attr[curr++] = AT_NORMAL;
1065 linebuf[curr] = '\b';
1066 attr[curr++] = AT_NORMAL;
1068 linebuf[curr] = '\0';
1069 attr[curr] = AT_NORMAL;
1072 if (status_col && line_matches > 0)
1075 attr[0] = AT_NORMAL|AT_HILITE;
1081 * Get a character from the current line.
1082 * Return the character as the function return value,
1083 * and the character attribute in *ap.
1093 * If there is no current line, we pretend the line is
1094 * either "~" or "", depending on the "twiddle" flag.
1105 /* Make sure we're back to AT_NORMAL before the '\n'. */
1107 return i ? '\0' : '\n';
1111 return (linebuf[i] & 0xFF);
1115 * Indicate that there is no current line.
1125 * Analogous to forw_line(), but deals with "raw lines":
1126 * lines which are not split for screen width.
1127 * {{ This is supposed to be more efficient than forw_line(). }}
1130 forw_raw_line(curr_pos, linep, line_lenp)
1139 if (curr_pos == NULL_POSITION || ch_seek(curr_pos) ||
1140 (c = ch_forw_get()) == EOI)
1141 return (NULL_POSITION);
1146 if (c == '\n' || c == EOI || ABORT_SIGS())
1148 new_pos = ch_tell();
1151 if (n >= size_linebuf-1)
1153 if (expand_linebuf())
1156 * Overflowed the input buffer.
1157 * Pretend the line ended here.
1159 new_pos = ch_tell() - 1;
1169 if (line_lenp != NULL)
1175 * Analogous to back_line(), but deals with "raw lines".
1176 * {{ This is supposed to be more efficient than back_line(). }}
1179 back_raw_line(curr_pos, linep, line_lenp)
1188 if (curr_pos == NULL_POSITION || curr_pos <= ch_zero() ||
1189 ch_seek(curr_pos-1))
1190 return (NULL_POSITION);
1193 linebuf[--n] = '\0';
1197 if (c == '\n' || ABORT_SIGS())
1200 * This is the newline ending the previous line.
1201 * We have hit the beginning of the line.
1203 new_pos = ch_tell() + 1;
1209 * We have hit the beginning of the file.
1210 * This must be the first line in the file.
1211 * This must, of course, be the beginning of the line.
1213 new_pos = ch_zero();
1218 int old_size_linebuf = size_linebuf;
1221 if (expand_linebuf())
1224 * Overflowed the input buffer.
1225 * Pretend the line ended here.
1227 new_pos = ch_tell() + 1;
1231 * Shift the data to the end of the new linebuf.
1233 for (fm = linebuf + old_size_linebuf - 1,
1234 to = linebuf + size_linebuf - 1;
1235 fm >= linebuf; fm--, to--)
1237 n = size_linebuf - old_size_linebuf;
1242 *linep = &linebuf[n];
1243 if (line_lenp != NULL)
1244 *line_lenp = size_linebuf - 1 - n;