2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #include "telescope.h"
26 * There's a simple text wrapping algorithm.
28 * 1. if it's a line in a pre-formatted block:
31 * 2. otherwise advance the line char by char.
32 * 3. when ending the space, split the line at the last occurrence of
33 * a "word separator" (i.e. " \t-") or at point if none.
39 push_line(struct window *window, const struct line *l, const char *buf, size_t len, int cont)
45 if ((vl = calloc(1, sizeof(*vl))) == NULL)
48 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
55 memcpy(vl->line, buf, len);
58 if (TAILQ_EMPTY(&window->head))
59 TAILQ_INSERT_HEAD(&window->head, vl, vlines);
61 TAILQ_INSERT_TAIL(&window->head, vl, vlines);
66 * Build a list of visual line by wrapping the given line, assuming
67 * that when printed will have a leading prefix prfx.
70 wrap_text(struct window *window, const char *prfx, struct line *l, size_t width)
72 const char *separators = " \t-";
73 const char *start, *end, *line, *lastsep, *lastchar;
74 uint32_t cp = 0, state = 0;
75 size_t cur, prfxwidth, w;
78 if ((line = l->line) == NULL)
79 return push_line(window, l, NULL, 0, 0);
81 prfxwidth = utf8_swidth(prfx);
87 for (; *line; line++) {
88 if (utf8_decode(&state, &cp, *line))
91 if (cur + w >= width -1) {
93 ? utf8_next_cp((char*)lastchar)
94 : utf8_next_cp((char*)lastsep);
95 if (!push_line(window, l, start, end - start, cont))
99 cur = prfxwidth + utf8_swidth_between(start, lastchar);
101 if (strchr(separators, *line) != NULL)
105 lastchar = utf8_prev_cp(line, l->line);
109 return push_line(window, l, start, line - start, cont);
113 hardwrap_text(struct window *window, struct line *l, size_t width)
115 const char *line, *start, *lastchar;
117 uint32_t state = 0, cp = 0;
120 if ((line = l->line) == NULL)
121 return push_line(window, l, NULL, 0, 0);
127 for (; *line; line++) {
128 if (utf8_decode(&state, &cp, *line))
130 w = utf8_chwidth(cp);
131 if (cur + w >= width) {
132 if (!push_line(window, l, start, lastchar - start, cont))
139 lastchar = utf8_prev_cp(line, l->line);
143 return push_line(window, l, start, line - start, cont);