2 * Copyright (C) 1984-2005 Mark Nudelman
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.
7 * For more information about less, or for information on how to
8 * contact the author, 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 */
31 static int curr; /* Index into linebuf */
32 static int column; /* Printable length, accounting for
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 */
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;
170 * Insert the line number (of the given position) into the line buffer.
176 register LINENUM linenum = 0;
179 if (linenums == OPT_ONPLUS)
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. }}
189 linenum = find_linenum(pos);
193 * Display a status column if the -J option is set.
198 if (start_attnpos != NULL_POSITION &&
199 pos >= start_attnpos && pos < end_attnpos)
200 attr[curr] = AT_NORMAL|AT_HILITE;
202 attr[curr] = AT_NORMAL;
207 * Display the line number at the start of each line
208 * if the -N option is set.
210 if (linenums == OPT_ONPLUS)
212 char buf[INT_STRLEN_BOUND(pos) + 2];
215 linenumtoa(linenum, 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;
229 * Append enough spaces to bring us to the lmargin.
231 while (column < lmargin)
234 attr[curr++] = AT_NORMAL;
240 * Shift the input line left.
241 * This means discarding N printable chars at the start of the buffer.
257 if (shift > column - lmargin)
258 shift = column - lmargin;
259 if (shift > curr - lmargin)
260 shift = curr - lmargin;
264 * We keep on going when shifted == shift
265 * to get all combining chars.
267 while (shifted <= shift && from < curr)
270 if (c == ESC && ctldisp == OPT_ONPLUS)
272 /* Keep cumulative effect. */
274 attr[to++] = attr[from++];
275 while (from < curr && linebuf[from])
277 linebuf[to] = linebuf[from];
278 attr[to++] = attr[from];
279 if (!is_ansi_middle(linebuf[from++]))
287 if (!IS_ASCII_OCTET(c) && utf_mode)
289 /* Assumes well-formedness validation already done. */
293 if (from + len > curr)
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;
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))
310 if (width == 2 && shift - shifted == 1) {
311 /* Should never happen when called by pshift_all(). */
312 attr[to] = attr[from];
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'.
318 prev_ch = linebuf[to++] = ' ';
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))
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))
335 width += attr_ewidth(prev_attr);
336 if (from + len < curr)
337 width += attr_swidth(next_attr);
341 if (shift - shifted < width)
350 linebuf[to] = linebuf[from];
351 attr[to++] = attr[from++];
368 * Return the printing width of the start (enter) sequence
369 * for a given character attribute.
377 a = apply_at_specials(a);
379 if (a & AT_UNDERLINE)
392 * Return the printing width of the end (exit) sequence
393 * for a given character attribute.
401 a = apply_at_specials(a);
403 if (a & AT_UNDERLINE)
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.
422 pwidth(ch, a, prev_ch)
431 * Backspace moves backwards one or two positions.
432 * XXX - Incorrect if several '\b' in a row.
434 return (utf_mode && is_wide_char(prev_ch)) ? -2 : -1;
436 if (!utf_mode || is_ascii_char(ch))
438 if (control_char((char)ch))
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.
449 if (is_composing_char(ch) || is_combining_char(prev_ch, ch))
452 * Composing and combining chars take up no space.
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.
467 * Other characters take one or two columns,
468 * plus the width of any attribute enter/exit sequence.
471 if (is_wide_char(ch))
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)))
482 * Delete to the previous base character in the line buffer.
483 * Return 1 if one is found.
489 char *p = linebuf + curr;
490 LWCHAR ch = step_char(&p, -1, linebuf + lmargin);
493 /* This assumes that there is no '\b' in linebuf. */
494 while ( curr > lmargin
496 && (!(attr[curr - 1] & (AT_ANSI|AT_BINARY))))
499 prev_ch = step_char(&p, -1, linebuf + lmargin);
500 width = pwidth(ch, attr[curr], prev_ch);
511 * Are we currently within a recognized ANSI escape sequence?
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).
522 for (p = &linebuf[curr]; p > linebuf; )
524 LWCHAR ch = step_char(&p, -1, linebuf);
527 if (!is_ansi_middle(ch))
534 * Is a character the end of an ANSI escape sequence?
540 if (!is_ascii_char(ch))
542 return (strchr(end_ansi_chars, (char) ch) != NULL);
552 if (!is_ascii_char(ch))
556 return (strchr(mid_ansi_chars, (char) ch) != NULL);
560 * Append a character and attribute to the line buffer.
562 #define STORE_CHAR(ch,a,rep,pos) \
564 if (store_char((ch),(a),(rep),(pos))) return (1); \
568 store_char(ch, a, rep, pos)
578 w = (a & (AT_UNDERLINE|AT_BOLD)); /* Pre-use w. */
585 if (is_hilited(pos, pos+1, 0, &matches))
588 * This character should be highlighted.
589 * Override the attribute passed in.
594 line_matches += matches;
598 if (ctldisp == OPT_ONPLUS && in_ansi_esc_seq())
600 if (!is_ansi_end(ch) && !is_ansi_middle(ch)) {
601 /* Remove whole unrecognized sequence. */
604 } while (linebuf[curr] != ESC);
607 a = AT_ANSI; /* Will force re-AT_'ing around it. */
610 else if (ctldisp == OPT_ONPLUS && ch == ESC)
612 a = AT_ANSI; /* Will force re-AT_'ing around it. */
617 char *p = &linebuf[curr];
618 LWCHAR prev_ch = step_char(&p, -1, linebuf);
619 w = pwidth(ch, a, prev_ch);
622 if (ctldisp != OPT_ON && column + w + attr_ewidth(a) > sc_width)
624 * Won't fit on screen.
635 replen = utf_len(rep[0]);
637 if (curr + replen >= size_linebuf-6)
640 * Won't fit in line buffer.
643 if (expand_linebuf())
649 linebuf[curr] = *rep++;
658 * Append a tab to the line buffer.
659 * Store spaces to represent the tab.
661 #define STORE_TAB(a,pos) \
662 do { if (store_tab((a),(pos))) return (1); } while (0)
669 int to_tab = column + cshift - lmargin;
672 if (ntabstops < 2 || to_tab >= tabstops[ntabstops-1])
673 to_tab = tabdefault -
674 ((to_tab - tabstops[ntabstops-1]) % tabdefault);
677 for (i = ntabstops - 2; i >= 0; i--)
678 if (to_tab >= tabstops[i])
680 to_tab = tabstops[i+1] - to_tab;
683 if (column + to_tab - 1 + pwidth(' ', attr, 0) + attr_ewidth(attr) > sc_width)
687 STORE_CHAR(' ', attr, " ", pos);
688 } while (--to_tab > 0);
692 #define STORE_PRCHAR(c, pos) \
693 do { if (store_prchar((c), (pos))) return 1; } while (0)
703 * Convert to printable representation.
708 * Make sure we can get the entire representation
709 * of the character on this line.
711 if (column + (int) strlen(s) - 1 +
712 pwidth(' ', binattr, 0) + attr_ewidth(binattr) > sc_width)
715 for ( ; *s != 0; s++)
716 STORE_CHAR(*s, AT_BINARY, NULL, pos);
727 for (i = 0; i < mbc_buf_index; i++)
728 if (store_prchar(mbc_buf[i], pos))
729 return mbc_buf_index - i;
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.
748 if (do_append(pendc, NULL, pendpos))
750 * Oops. We've probably lost the char which
751 * was in pendc, since caller won't back up.
757 if (c == '\r' && bs_mode == BS_SPECIAL)
759 if (mbc_buf_len > 0) /* utf_mode must be on. */
761 /* Flush incomplete (truncated) sequence. */
762 r = flush_mbc_buf(mbc_pos);
763 mbc_buf_index = r + 1;
766 return (mbc_buf_index);
770 * Don't put the CR into the buffer until we see
771 * the next char. If the next char is a newline,
781 r = do_append((LWCHAR) c, NULL, pos);
784 /* Perform strict validation in all possible cases. */
785 if (mbc_buf_len == 0)
790 if (IS_ASCII_OCTET(c))
791 r = do_append((LWCHAR) c, NULL, pos);
792 else if (IS_UTF8_LEAD(c))
794 mbc_buf_len = utf_len(c);
798 /* UTF8_INVALID or stray UTF8_TRAIL */
799 r = flush_mbc_buf(pos);
800 } else if (IS_UTF8_TRAIL(c))
802 mbc_buf[mbc_buf_index++] = c;
803 if (mbc_buf_index < mbc_buf_len)
805 if (is_utf8_well_formed(mbc_buf))
806 r = do_append(get_wchar(mbc_buf), mbc_buf, mbc_pos);
808 /* Complete, but not shortest form, sequence. */
809 mbc_buf_index = r = flush_mbc_buf(mbc_pos);
813 /* Flush incomplete (truncated) sequence. */
814 r = flush_mbc_buf(mbc_pos);
815 mbc_buf_index = r + 1;
817 /* Handle new char. */
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.)
829 if (cshift < hshift && column > sc_width / 2)
831 linebuf[curr] = '\0';
832 pshift(hshift - cshift);
836 /* How many chars should caller back up? */
837 r = (!utf_mode) ? 1 : mbc_buf_index;
843 do_append(ch, rep, pos)
855 if (bs_mode == BS_CONTROL)
856 goto do_control_char;
859 * A better test is needed here so we don't
860 * backspace over part of the printed
861 * representation of a binary character.
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();
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.
884 overstrike = utf_mode ? -1 : 0;
885 /* To be correct, this must be a base character. */
886 prev_ch = get_wchar(linebuf + curr);
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.
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;
907 } else if (ch == '_')
911 rep = linebuf + curr;
912 } else if (prev_ch == '_')
916 /* Else we replace prev_ch, but we keep its attributes. */
917 } else if (overstrike < 0)
919 if ( is_composing_char(ch)
920 || is_combining_char(get_wchar(linebuf + curr), ch))
921 /* Continuation of the same overstrike. */
930 * Expand a tab into spaces.
935 goto do_control_char;
941 } else if ((!utf_mode || is_ascii_char(ch)) && control_char((char)ch))
944 if (ctldisp == OPT_ON || (ctldisp == OPT_ONPLUS && ch == ESC))
947 * Output as a normal character.
949 STORE_CHAR(ch, AT_NORMAL, rep, pos);
952 STORE_PRCHAR((char) ch, pos);
954 } else if (utf_mode && ctldisp != OPT_ON && is_ubin_char(ch))
960 if (column + (int) strlen(s) - 1 +
961 pwidth(' ', binattr, 0) + attr_ewidth(binattr) > sc_width)
964 for ( ; *s != 0; s++)
965 STORE_CHAR(*s, AT_BINARY, NULL, pos);
968 STORE_CHAR(ch, a, rep, pos);
983 /* Flush incomplete (truncated) sequence. */
984 r = flush_mbc_buf(mbc_pos);
991 * Terminate the line in the line buffer.
999 if (pendc && (pendc != '\r' || !endline))
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).
1005 (void) do_append(pendc, NULL, pendpos);
1008 * Make sure we've shifted the line, if we need to.
1010 if (cshift < hshift)
1011 pshift(hshift - cshift);
1013 if (ctldisp == OPT_ONPLUS && is_ansi_end('m'))
1015 /* Switch to normal attribute at end of line. */
1017 for ( ; *p != '\0'; p++)
1020 attr[curr++] = AT_ANSI;
1025 * Add a newline if necessary,
1026 * and append a '\0' to the end of the line.
1028 if (column < sc_width || !auto_wrap || ignaw || ctldisp == OPT_ON)
1030 linebuf[curr] = '\n';
1031 attr[curr] = AT_NORMAL;
1034 linebuf[curr] = '\0';
1035 attr[curr] = AT_NORMAL;
1038 if (status_col && line_matches > 0)
1041 attr[0] = AT_NORMAL|AT_HILITE;
1047 * Get a character from the current line.
1048 * Return the character as the function return value,
1049 * and the character attribute in *ap.
1059 * If there is no current line, we pretend the line is
1060 * either "~" or "", depending on the "twiddle" flag.
1071 /* Make sure we're back to AT_NORMAL before the '\n'. */
1073 return i ? '\0' : '\n';
1077 return (linebuf[i] & 0xFF);
1081 * Indicate that there is no current line.
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(). }}
1096 forw_raw_line(curr_pos, linep)
1104 if (curr_pos == NULL_POSITION || ch_seek(curr_pos) ||
1105 (c = ch_forw_get()) == EOI)
1106 return (NULL_POSITION);
1111 if (c == '\n' || c == EOI || ABORT_SIGS())
1113 new_pos = ch_tell();
1116 if (n >= size_linebuf-1)
1118 if (expand_linebuf())
1121 * Overflowed the input buffer.
1122 * Pretend the line ended here.
1124 new_pos = ch_tell() - 1;
1138 * Analogous to back_line(), but deals with "raw lines".
1139 * {{ This is supposed to be more efficient than back_line(). }}
1142 back_raw_line(curr_pos, linep)
1150 if (curr_pos == NULL_POSITION || curr_pos <= ch_zero() ||
1151 ch_seek(curr_pos-1))
1152 return (NULL_POSITION);
1155 linebuf[--n] = '\0';
1159 if (c == '\n' || ABORT_SIGS())
1162 * This is the newline ending the previous line.
1163 * We have hit the beginning of the line.
1165 new_pos = ch_tell() + 1;
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.
1175 new_pos = ch_zero();
1180 int old_size_linebuf = size_linebuf;
1183 if (expand_linebuf())
1186 * Overflowed the input buffer.
1187 * Pretend the line ended here.
1189 new_pos = ch_tell() + 1;
1193 * Shift the data to the end of the new linebuf.
1195 for (fm = linebuf + old_size_linebuf - 1,
1196 to = linebuf + size_linebuf - 1;
1197 fm >= linebuf; fm--, to--)
1199 n = size_linebuf - old_size_linebuf;
1204 *linep = &linebuf[n];