Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

feat(plugins): wrap a text into the lines its box holds

RoversX2ec9bd117f13
diff --git a/docs/thinkterm/plugins.md b/docs/thinkterm/plugins.md
index dd8c2615..bf4b17a6 100644
--- a/docs/thinkterm/plugins.md
+++ b/docs/thinkterm/plugins.md
@@ -204,7 +204,7 @@ the rest are drawn.
| Item | Fields |
|----------|----------------------------------------------------------------------------------------------------------|
| `rect` | `x`, `y`, `w`, `h`; `fill`; `radius` (0); `border` (a one-unit line inside the edge) |
-| `text` | `x`, `y`, `w`, `h`, `text`; `color` (`text`); `font` (`ui` or `mono`); `size` (`small`, `body`, `title`: the `ui` font's); `bold`; `align` (`left`, `center`, `right`) |
+| `text` | `x`, `y`, `w`, `h`, `text`; `color` (`text`); `font` (`ui` or `mono`); `size` (`small`, `body`, `title`: the `ui` font's); `bold`; `align` (`left`, `center`, `right`); `wrap` |
| `line` | `points` (x, y, x, y ...), `color`; `width` (1) |
| `area` | `points` (left to right), `base`, `color`; `fade` (thins to nothing at `base`): the fill under a chart |
| `hit` | `id`, `x`, `y`, `w`, `h`; `hover` (a colour to tint it with while the pointer is over it); `radius` (0, the tint's corners); `cursor` (`pointer`, `arrow`) |
@@ -216,6 +216,16 @@ the rest are drawn.
an ellipsis in the `ui` font, at the edge in the `mono` font, whose
columns a plugin lines up itself -- the environment says how wide one is,
and a character most scripts write in one column takes two in CJK.
+- With `wrap`, text is broken into lines that fit its box's width -- after
+ a space, between the characters of a script written without spaces, at
+ its own line breaks, or else where a word overflows -- set from the
+ box's top, a `line` of its font each, as many as the box's height holds.
+ Where text is left over, the last ends in an ellipsis in the `ui` font;
+ one cut at the most characters a text holds (see [Limits](#limits)) ends
+ in `...` in either.
+ A box a whole number of lines tall holds that many, so a plugin sizes it
+ from the environment's `line` and never needs to measure text. A client
+ whose environment does not say `wrap` shows one line.
- A hit's tint is painted where the hit is in the list: put the hit before
what it should be under. Where hits overlap, the last one answers: a row
can take clicks across its whole width and be tinted only in a rounded
@@ -274,7 +284,8 @@ panel](#the-terminal-beside-a-panel)); `can_extend` (see [The extended
view](#the-extended-view)); and `features`, what the client does besides
drawing and sending clicks: `fields` when it shows fields, `keys` when it
gives a panel the keyboard on the user's key (see [Fields and the
-keyboard](#fields-and-the-keyboard)). It comes with `open` and again when any of it
+keyboard](#fields-and-the-keyboard)), `wrap` when it breaks a text into
+lines. It comes with `open` and again when any of it
changes -- no more than ten times a second while a window is resized, the
last always -- and the `rows` asked for after it are drawn for it. A click's
`x` and `y` are within the hit. A `version` or a `layout` of 0, and a
diff --git a/thinkterm-plugin-panel/src/player.rs b/thinkterm-plugin-panel/src/player.rs
index 5c572871..a3512974 100644
--- a/thinkterm-plugin-panel/src/player.rs
+++ b/thinkterm-plugin-panel/src/player.rs
@@ -156,6 +156,7 @@ pub enum Op {
size: Size,
bold: bool,
align: Align,
+ wrap: bool,
},
/// Through `points`, x, y and so on.
Line {
@@ -1065,6 +1066,7 @@ impl Player {
size: text.size,
bold: text.bold,
align: text.align,
+ wrap: text.wrap,
},
Drawn::Line(line) => Op::Line {
clip,
@@ -1526,6 +1528,13 @@ fn keep(items: &mut Vec<Item>, budget: &mut usize, nested: bool) {
Item::Text(text) => {
if let Some((cut, _)) = text.text.char_indices().nth(TEXT_LIMIT) {
text.text.truncate(cut);
+ // Whole in a box with room to spare, a text asked to wrap
+ // would stop as if it were done: it ends in an ellipsis.
+ if text.wrap {
+ let marked = text.text.char_indices().nth(TEXT_LIMIT - 3);
+ text.text.truncate(marked.map_or(0, |(at, _)| at));
+ text.text.push_str("...");
+ }
}
}
Item::Field(field) => {
@@ -1763,6 +1772,7 @@ mod tests {
size: Default::default(),
bold: false,
align: Default::default(),
+ wrap: false,
}),
]
}
@@ -2412,6 +2422,7 @@ mod tests {
size: Default::default(),
bold: false,
align: Default::default(),
+ wrap: false,
}));
player.frame(Frame {
items,
@@ -2443,7 +2454,20 @@ mod tests {
size: Default::default(),
bold: false,
align: Default::default(),
+ wrap: false,
+ });
+ player.frame(Frame {
+ items: vec![long],
+ ..Frame::default()
});
+ let Item::Text(text) = &player.frame.items[0] else {
+ panic!()
+ };
+ assert_eq!(text.text.chars().count(), TEXT_LIMIT);
+
+ // One asked to wrap says it was cut.
+ let long =
+ Item::Text(Text::new(0.0, 0.0, 1.0, 1.0, "\u{4e2d}".repeat(TEXT_LIMIT + 1)).wrap());
player.frame(Frame {
items: vec![long],
..Frame::default()
@@ -2452,6 +2476,7 @@ mod tests {
panic!()
};
assert_eq!(text.text.chars().count(), TEXT_LIMIT);
+ assert!(text.text.ends_with("\u{4e2d}..."));
}
#[test]
diff --git a/thinkterm-plugin-panel/src/scene.rs b/thinkterm-plugin-panel/src/scene.rs
index 6c1abc5e..01ab08d6 100644
--- a/thinkterm-plugin-panel/src/scene.rs
+++ b/thinkterm-plugin-panel/src/scene.rs
@@ -84,10 +84,10 @@ pub struct Rect {
pub border: Option<Color>,
}
-/// One line of text in a box: centred in its height, placed across its
-/// width as `align` says, and cut to fit -- with an ellipsis in the
-/// interface font, at the box's edge in the monospaced one, whose columns a
-/// plugin lines up itself.
+/// Text in a box: one line, centred in its height, placed across its width
+/// as `align` says, and cut to fit -- with an ellipsis in the interface
+/// font, at the box's edge in the monospaced one, whose columns a plugin
+/// lines up itself. Or, asked to `wrap`, as many lines as the box holds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Text {
pub x: f32,
@@ -106,6 +106,17 @@ pub struct Text {
pub bold: bool,
#[serde(default, skip_serializing_if = "is_default")]
pub align: Align,
+ /// Broken into lines that fit the box's width -- after a space, between
+ /// the characters of a script written without spaces, at the text's own
+ /// line breaks -- set from its top, each a line of its font tall
+ /// ([`TextMetrics::line`]), as many as its height holds and at least
+ /// one. Where text is left over, the last ends in an ellipsis in the
+ /// interface font. A client without [`feature::WRAP`] shows one line.
+ ///
+ /// [`TextMetrics::line`]: crate::wire::TextMetrics::line
+ /// [`feature::WRAP`]: crate::wire::feature::WRAP
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub wrap: bool,
}
/// A line through `points`, given as x, y, x, y and so on.
@@ -530,6 +541,7 @@ impl Text {
size: Size::Body,
bold: false,
align: Align::Left,
+ wrap: false,
}
}
@@ -557,6 +569,12 @@ impl Text {
self.align = align;
self
}
+
+ /// Breaks it into as many lines as its box holds.
+ pub fn wrap(mut self) -> Self {
+ self.wrap = true;
+ self
+ }
}
impl Line {
diff --git a/thinkterm-plugin-panel/src/wire.rs b/thinkterm-plugin-panel/src/wire.rs
index a710d9b7..25c04894 100644
--- a/thinkterm-plugin-panel/src/wire.rs
+++ b/thinkterm-plugin-panel/src/wire.rs
@@ -70,6 +70,10 @@ pub mod feature {
/// It gives a panel the keyboard when the user asks, and sends the keys
/// the panel takes.
pub const KEYS: &str = "keys";
+ /// It breaks a text that asks for it into lines ([`Text::wrap`]).
+ ///
+ /// [`Text::wrap`]: crate::scene::Text::wrap
+ pub const WRAP: &str = "wrap";
}
impl Env {
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index 284ee28f..8dbcea2f 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -4928,7 +4928,10 @@ impl<P: Platform, L: Link> App<P, L> {
env.terminal = Self::focused_terminal(inner);
// Its fields are the page's own; the keyboard comes to a panel
// through them, and no key of the page's gives it.
- env.features = vec![thinkterm_plugin_panel::feature::FIELDS.to_string()];
+ env.features = vec![
+ thinkterm_plugin_panel::feature::FIELDS.to_string(),
+ thinkterm_plugin_panel::feature::WRAP.to_string(),
+ ];
if extended {
env.can_extend = false;
inner.plugin_extended_env = Some(env.clone());
diff --git a/thinkterm-web/ui/src/PluginPanel.svelte b/thinkterm-web/ui/src/PluginPanel.svelte
index c1488c2a..64628ed4 100644
--- a/thinkterm-web/ui/src/PluginPanel.svelte
+++ b/thinkterm-web/ui/src/PluginPanel.svelte
@@ -20,6 +20,7 @@
import { focusTerminal } from './mobile.svelte';
import type { PanelOp, PanelView, Painting } from './model';
import { onMac } from './palette.svelte';
+ import { breakLines } from './wrap';
let { extended = false }: { extended?: boolean } = $props();
@@ -183,6 +184,48 @@
return result;
}
+ // A text asked to wrap, as the lines its box holds -- `rows` of them at
+ // most -- and how wide each is, remembered as a cut is: where text is
+ // left over, the last ends in an ellipsis in the interface font.
+ const wraps = new Map<string, Cut[]>();
+
+ function wrap(ctx: CanvasRenderingContext2D, text: string, room: number, rows: number, ellipsize: boolean): Cut[] {
+ const key = `${ctx.font}\u0000${room}\u0000${rows}\u0000${text}`;
+ const known = wraps.get(key);
+ if (known !== undefined) return known;
+ const { lines, leftOver } = breakLines(text, room, rows, (part) => ctx.measureText(part).width);
+ const laid = lines.map((shown) => ({ shown, wide: ctx.measureText(shown).width }));
+ const last = laid.length - 1;
+ if (leftOver && ellipsize && last >= 0) laid[last] = cut(ctx, laid[last].shown + ELLIPSIS, room, true);
+ if (wraps.size >= CUTS) wraps.clear();
+ wraps.set(key, laid);
+ return laid;
+ }
+
+ /** One line of a text op, its middle at `middle`: placed across the
+ op's box as it says, and cut at its edge if it is wider still. */
+ function textLine(ctx: CanvasRenderingContext2D, op: Extract<PanelOp, { op: 'text' }>, { shown, wide }: Cut, middle: number) {
+ if (shown === '') return;
+ const left = Math.max(
+ op.x,
+ op.align === 'center' ? op.x + (op.w - wide) / 2 : op.align === 'right' ? op.x + op.w - wide : op.x,
+ );
+ // The monospaced font is cut at its box's edge, not ellipsized: a
+ // plugin lines its columns up itself. So is a line of either that is
+ // wider than its box all the same -- one character in a box narrower
+ // than it.
+ if (wide > op.w) {
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(op.x, op.y, op.w, op.h);
+ ctx.clip();
+ ctx.fillText(shown, left, middle);
+ ctx.restore();
+ } else {
+ ctx.fillText(shown, left, middle);
+ }
+ }
+
function paint(painting: Painting | null) {
const ctx = canvas?.getContext('2d');
if (!ctx) return;
@@ -233,24 +276,17 @@
ctx.font = font(op, family);
ctx.fillStyle = css(rgba(op.color));
ctx.textBaseline = 'middle';
- const { shown, wide } = cut(ctx, op.text, op.w, op.font === 'ui');
- const left = Math.max(
- op.x,
- op.align === 'center' ? op.x + (op.w - wide) / 2 : op.align === 'right' ? op.x + op.w - wide : op.x,
- );
- const middle = op.y + op.h / 2;
- // The monospaced font is cut at its box's edge, not ellipsized: a
- // plugin lines its columns up itself.
- if (op.font === 'mono' && wide > op.w) {
- ctx.save();
- ctx.beginPath();
- ctx.rect(op.x, op.y, op.w, op.h);
- ctx.clip();
- ctx.fillText(shown, left, middle);
- ctx.restore();
- } else {
- ctx.fillText(shown, left, middle);
+ if (op.wrap) {
+ // From the box's top, a line of the font each, as many as the
+ // box holds: one made a whole number of lines tall holds them all.
+ const line = op.font === 'mono' ? MONO.line : TEXT[op.size].line;
+ const rows = Math.max(1, Math.floor((op.h + 0.5) / line));
+ wrap(ctx, op.text, op.w, rows, op.font === 'ui').forEach((laid, row) =>
+ textLine(ctx, op, laid, op.y + row * line + line / 2),
+ );
+ return;
}
+ textLine(ctx, op, cut(ctx, op.text, op.w, op.font === 'ui'), op.y + op.h / 2);
return;
}
case 'line': {
@@ -585,6 +621,7 @@
document.fonts.add(face);
face.load().then(() => {
cuts.clear();
+ wraps.clear();
sendEnv();
refresh(true);
}, () => {});
diff --git a/thinkterm-web/ui/src/model.ts b/thinkterm-web/ui/src/model.ts
index bfc11da5..e28abe65 100644
--- a/thinkterm-web/ui/src/model.ts
+++ b/thinkterm-web/ui/src/model.ts
@@ -302,6 +302,7 @@ export type PanelOp =
size: 'small' | 'body' | 'title';
bold: boolean;
align: 'left' | 'center' | 'right';
+ wrap: boolean;
}
| { op: 'line'; clip: number; points: number[]; width: number; color: string }
| { op: 'area'; clip: number; points: number[]; base: number; color: string; fade: boolean }
diff --git a/thinkterm-web/ui/src/wrap.ts b/thinkterm-web/ui/src/wrap.ts
new file mode 100644
index 00000000..0282d9ec
--- /dev/null
+++ b/thinkterm-web/ui/src/wrap.ts
@@ -0,0 +1,99 @@
+// A plugin panel's text broken into lines (thinkterm-plugin-panel
+// `Text::wrap`), by the rules the desktop breaks them by
+// (plugin_panel/field.rs `wrap_line`), measured with whatever the caller
+// measures in.
+
+// Punctuation that closes a phrase of a script written without spaces: a
+// line does not start with it.
+const CLOSING = new Set(['、', '。', ',', '.', ':', ';', '!', '?', ')', '」', '』', '】', '〉', '》', '〕', 'ー', '…']);
+
+// Chinese, Japanese, Korean, and their punctuation: scripts written
+// without spaces between their words.
+const UNSPACED: [number, number][] = [
+ [0x2e80, 0x2fff],
+ [0x3000, 0x303f],
+ [0x3040, 0x30ff],
+ [0x3100, 0x31ff],
+ [0x3400, 0x4dbf],
+ [0x4e00, 0x9fff],
+ [0xac00, 0xd7af],
+ [0xf900, 0xfaff],
+ [0xff00, 0xffef],
+ [0x20000, 0x3ffff],
+];
+
+// What a line may not be broken inside: a letter and its accents, an
+// emoji's parts. Code points where the browser cannot say.
+const segmenter = typeof Intl !== 'undefined' && 'Segmenter' in Intl
+ ? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
+ : null;
+
+function graphemes(text: string): string[] {
+ return segmenter ? Array.from(segmenter.segment(text), (part) => part.segment) : Array.from(text);
+}
+
+function unspaced(ch: string): boolean {
+ const code = ch.codePointAt(0) ?? 0;
+ return UNSPACED.some(([from, to]) => code >= from && code <= to);
+}
+
+/** Whether a line may break before character `at` of `chars` -- whole
+ characters, as `graphemes` makes them: after a space, or where the
+ characters on either side are of a script written without spaces --
+ but not before the punctuation that closes one. */
+function breaksBefore(chars: string[], at: number): boolean {
+ const before = chars[at - 1];
+ const after = chars[at];
+ if (before === undefined || after === undefined) return false;
+ if (/\s/u.test(before)) return true;
+ return (unspaced(before) || unspaced(after)) && !/\s/u.test(after) && !CLOSING.has(after);
+}
+
+/** `text` as at most `rows` lines no wider than `room` -- broken at the
+ last place that keeps one within it, or else where it overflows, and
+ at its own line breaks -- and whether text is left over. */
+export function breakLines(
+ text: string,
+ room: number,
+ rows: number,
+ measure: (text: string) => number,
+): { lines: string[]; leftOver: boolean } {
+ const lines: string[] = [];
+ const paragraphs = text.split(/\r?\n/);
+ if (paragraphs.length > 1 && paragraphs[paragraphs.length - 1] === '') paragraphs.pop();
+ for (const paragraph of paragraphs) {
+ if (lines.length === rows) return { lines, leftOver: true };
+ const chars = graphemes(paragraph);
+ if (chars.length === 0) {
+ lines.push('');
+ continue;
+ }
+ let start = 0;
+ while (start < chars.length) {
+ if (lines.length === rows) return { lines, leftOver: true };
+ // The most characters from `start` that fit, and at least one, the
+ // spaces after them hanging past the edge; then back to the last
+ // place the line may break, if it has one.
+ let low = start + 1;
+ let high = chars.length;
+ while (low < high) {
+ const mid = Math.ceil((low + high) / 2);
+ if (measure(chars.slice(start, mid).join('')) <= room) low = mid;
+ else high = mid - 1;
+ }
+ let end = low;
+ while (end < chars.length && /\s/u.test(chars[end])) end++;
+ if (end < chars.length) {
+ for (let at = end; at > start; at--) {
+ if (breaksBefore(chars, at)) {
+ end = at;
+ break;
+ }
+ }
+ }
+ lines.push(chars.slice(start, end).join('').trimEnd());
+ start = end;
+ }
+ }
+ return { lines, leftOver: false };
+}
diff --git a/thinkterm-web/ui/tests/wrap.test.mjs b/thinkterm-web/ui/tests/wrap.test.mjs
new file mode 100644
index 00000000..19378c0c
--- /dev/null
+++ b/thinkterm-web/ui/tests/wrap.test.mjs
@@ -0,0 +1,43 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import ts from 'typescript';
+
+// The module as the page runs it, measured with a ruler of its own: a
+// column a character, two for one of a script written without spaces.
+const path = new URL('../src/wrap.ts', import.meta.url);
+const plain = ts.transpileModule(readFileSync(path, 'utf8'), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
+}).outputText;
+const { breakLines } = await import(`data:text/javascript,${encodeURIComponent(plain)}`);
+
+const columns = (text) => Array.from(text).reduce((sum, ch) => sum + (ch.codePointAt(0) >= 0x2e80 ? 2 : 1), 0);
+const lay = (text, room, rows = 99) => breakLines(text, room, rows, columns);
+
+test('lines break after a space, and a word too long for one where it overflows', () => {
+ assert.deepEqual(lay('the quick brown fox', 10), { lines: ['the quick', 'brown fox'], leftOver: false });
+ assert.deepEqual(lay('abcdefghijkl', 5).lines, ['abcde', 'fghij', 'kl']);
+});
+
+test('a script written without spaces breaks between its characters, not before closing punctuation', () => {
+ assert.deepEqual(lay('中文的句子很长', 6).lines, ['中文的', '句子很', '长']);
+ assert.deepEqual(lay('中文。句子', 4).lines, ['中', '文。', '句子']);
+});
+
+test('a letter keeps its accent, and an emoji its parts', () => {
+ const marks = (text) => Array.from(text).filter((ch) => !/\p{M}|\u200d/u.test(ch)).length;
+ assert.deepEqual(breakLines('ab\u0301c', 1, 99, marks).lines, ['a', 'b\u0301', 'c']);
+ const family = '\u{1f468}\u200d\u{1f469}\u200d\u{1f467}';
+ // Wider than the box, it is not split to fit.
+ assert.deepEqual(breakLines(`${family}x`, 2, 99, marks).lines, [family, 'x']);
+});
+
+test('the text breaks at its own line breaks, and keeps its empty lines', () => {
+ assert.deepEqual(lay('one\r\n\ntwo\n', 10).lines, ['one', '', 'two']);
+});
+
+test('what does not fit in the rows is left over', () => {
+ assert.deepEqual(lay('a b c d e f', 3, 2), { lines: ['a b', 'c d'], leftOver: true });
+ assert.deepEqual(lay('one\ntwo', 10, 1), { lines: ['one'], leftOver: true });
+ assert.deepEqual(lay('one\ntwo', 10, 2), { lines: ['one', 'two'], leftOver: false });
+});
diff --git a/wezterm-gui/src/termwindow/ui/plugin_panel.rs b/wezterm-gui/src/termwindow/ui/plugin_panel.rs
index b7f75847..81028ffc 100644
--- a/wezterm-gui/src/termwindow/ui/plugin_panel.rs
+++ b/wezterm-gui/src/termwindow/ui/plugin_panel.rs
@@ -1735,9 +1735,10 @@ impl TermWindow {
Ok(())
}
- /// One line of text in its box: centred in its height, placed across
- /// it as asked, and cut to it -- with an ellipsis in the interface
- /// font, at the edge in the monospaced one.
+ /// Text in its box: one line, centred in its height -- or, asked to
+ /// wrap, as many as the box holds, from its top -- each placed across
+ /// it as asked and cut to it: with an ellipsis in the interface font,
+ /// at the edge in the monospaced one.
/// Only the glyphs within `across`, the draw's left and right edges, are
/// laid: a line far wider than a list scrolled sideways costs what shows.
#[allow(clippy::too_many_arguments)]
@@ -1756,20 +1757,103 @@ impl TermWindow {
return Ok(());
}
let (font, metrics) = fonts.of(text);
+ let across = (clip_left, clip_right);
+ let mut line = |shown: &str, top: f32, budget: &mut usize| {
+ let at = (area, top);
+ self.paint_panel_text_line(
+ layers, text.align, shown, font, metrics, at, color, across, budget,
+ )
+ };
+ if text.wrap {
+ let line_height = metrics.cell_size.height as f32;
+ let lines = self.panel_text_lines(text, font, metrics, area)?;
+ for (row, shown) in lines.iter().enumerate() {
+ line(shown, area.min_y() + row as f32 * line_height, budget)?;
+ }
+ return Ok(());
+ }
let top = area.min_y() + (area.height() - metrics.cell_size.height as f32) / 2.0;
let shown = match text.font {
Font::Ui => self.ellipsize_ui_text(font, &text.text, area.width() as usize)?,
Font::Mono => std::borrow::Cow::Borrowed(text.text.as_str()),
};
+ line(&shown, top, budget)
+ }
+
+ /// `text` broken into the lines its box holds ([`Text::wrap`]), as they
+ /// show: where text is left over, the last ends in an ellipsis in the
+ /// interface font.
+ fn panel_text_lines(
+ &self,
+ text: &Text,
+ font: &Rc<LoadedFont>,
+ metrics: &RenderMetrics,
+ area: RectF,
+ ) -> anyhow::Result<Vec<String>> {
+ const ELLIPSIS: &str = "...";
+ let line_height = (metrics.cell_size.height as f32).max(1.0);
+ // A box made a whole number of lines tall holds them all, whatever
+ // its pixels round to.
+ let room = ((area.height() + 1.0) / line_height).floor().max(1.0) as usize;
+ let mut lines = Vec::new();
+ let mut left_over = false;
+ let width = area.width();
+ 'text: for paragraph in text.text.lines() {
+ if lines.len() == room {
+ left_over = true;
+ break;
+ }
+ let xs = self.boundaries(font, metrics, paragraph)?;
+ let chars: Vec<char> = paragraph.chars().collect();
+ let at: Vec<usize> = paragraph
+ .char_indices()
+ .map(|(at, _)| at)
+ .chain(std::iter::once(paragraph.len()))
+ .collect();
+ for line in break_text(&chars, &xs, width) {
+ if lines.len() == room {
+ left_over = true;
+ break 'text;
+ }
+ let shown = &paragraph[at[line.start]..at[line.end]];
+ lines.push(shown.trim_end().to_string());
+ }
+ }
+ if left_over && text.font == Font::Ui {
+ if let Some(last) = lines.last_mut() {
+ let ended = format!("{last}{ELLIPSIS}");
+ *last = self
+ .ellipsize_ui_text(font, &ended, area.width() as usize)?
+ .into_owned();
+ }
+ }
+ Ok(lines)
+ }
+
+ /// One line of a panel's text, `shown`, its top at `top` and placed
+ /// across `area` as `align` says.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_panel_text_line(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ align: Align,
+ shown: &str,
+ font: &Rc<LoadedFont>,
+ metrics: &RenderMetrics,
+ (area, top): (RectF, f32),
+ color: LinearRgba,
+ (clip_left, clip_right): (f32, f32),
+ budget: &mut usize,
+ ) -> anyhow::Result<()> {
if shown.is_empty() {
return Ok(());
}
- let (shaped, _) = self.cached_ui_shape(font, metrics, &shown)?;
+ let (shaped, _) = self.cached_ui_shape(font, metrics, shown)?;
let width: f32 = shaped
.iter()
.map(|info| info.glyph.x_advance.get() as f32)
.sum();
- let left = match text.align {
+ let left = match align {
Align::Left => area.min_x(),
Align::Center => area.min_x() + (area.width() - width) / 2.0,
Align::Right => area.max_x() - width,
@@ -1975,6 +2059,47 @@ fn local_path(url: &Url) -> Option<String> {
(!path.is_empty()).then(|| path.to_string())
}
+/// Where `chars`, whose boundaries are at `xs` -- as many as it has
+/// characters, and one -- break into lines no wider than `width`: at the
+/// last place that keeps one within it, after a space or between the
+/// characters of a script written without spaces, or else where it
+/// overflows. Only between whole clusters -- a letter and its accents, an
+/// emoji's parts, which `xs` gives the cluster's start -- and a line's
+/// spaces stay at its end, hanging past the edge.
+fn break_text(chars: &[char], xs: &[f32], width: f32) -> Vec<std::ops::Range<usize>> {
+ let count = chars.len();
+ let bounds: Vec<usize> = (0..=count)
+ .filter(|&at| at == 0 || at == count || xs[at] > xs[at - 1])
+ .collect();
+ let mut lines = Vec::new();
+ let mut from = 0;
+ loop {
+ let start = bounds[from];
+ // A cluster at least, then as many more as fit.
+ let mut to = (from + 1).min(bounds.len() - 1);
+ while let Some(&next) = bounds.get(to + 1) {
+ let hangs = chars[bounds[to]..next].iter().all(|c| c.is_whitespace());
+ if !hangs && xs[next] - xs[start] > width {
+ break;
+ }
+ to += 1;
+ }
+ if bounds[to] < count {
+ if let Some(found) = (from + 1..=to)
+ .rev()
+ .find(|&at| field::breaks_before(chars, bounds[at]))
+ {
+ to = found;
+ }
+ }
+ lines.push(start..bounds[to]);
+ from = to;
+ if bounds[from] >= count {
+ return lines;
+ }
+ }
+}
+
/// Pane `pane` as `thinkterm cli` reaches it. One the session server keeps
/// for this machine, by its number there and the server's socket: as the
/// programs in it reach it. Any other by its number here and the socket
@@ -2023,7 +2148,11 @@ fn panel_env(fonts: &PanelFonts, chrome: &UiPalette, width: f32, height: f32, sc
terminal: None,
can_extend: false,
close: None,
- features: vec![feature::FIELDS.to_string(), feature::KEYS.to_string()],
+ features: vec![
+ feature::FIELDS.to_string(),
+ feature::KEYS.to_string(),
+ feature::WRAP.to_string(),
+ ],
}
}
@@ -2217,6 +2346,47 @@ mod tests {
assert_eq!(host_name("fe80::1"), "fe80::1");
}
+ #[test]
+ fn text_breaks_after_a_space_between_unspaced_characters_or_where_it_overflows() {
+ // A column a character, two for Chinese.
+ let lines = |text: &str, width: f32| {
+ let chars: Vec<char> = text.chars().collect();
+ let mut xs = vec![0.0];
+ for ch in &chars {
+ let wide = if (*ch as u32) >= 0x2E80 { 2.0 } else { 1.0 };
+ xs.push(xs.last().unwrap() + wide);
+ }
+ super::break_text(&chars, &xs, width)
+ .into_iter()
+ .map(|line| {
+ chars[line]
+ .iter()
+ .collect::<String>()
+ .trim_end()
+ .to_string()
+ })
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(
+ lines("the quick brown fox", 10.0),
+ ["the quick", "brown fox"]
+ );
+ assert_eq!(
+ lines("a b c d", 3.0),
+ ["a b", "c d"],
+ "a space hangs past the edge"
+ );
+ assert_eq!(lines("abcdefghijkl", 5.0), ["abcde", "fghij", "kl"]);
+ assert_eq!(lines("中文的句子很长", 6.0), ["中文的", "句子很", "长"]);
+ assert_eq!(lines("中文。句子", 4.0), ["中", "文。", "句子"]);
+ assert_eq!(lines("", 4.0), [""]);
+
+ // A letter and its accent are one cluster: its start is theirs.
+ let chars: Vec<char> = "ab\u{301}c".chars().collect();
+ let broken = super::break_text(&chars, &[0.0, 10.0, 10.0, 20.0, 30.0], 10.0);
+ assert_eq!(broken, [0..1, 1..3, 3..4]);
+ }
+
#[test]
fn a_unit_is_a_point() {
let retina = if cfg!(target_os = "macos") { 144 } else { 192 };
diff --git a/wezterm-gui/src/termwindow/ui/plugin_panel/field.rs b/wezterm-gui/src/termwindow/ui/plugin_panel/field.rs
index 02bb3fe7..1525c322 100644
--- a/wezterm-gui/src/termwindow/ui/plugin_panel/field.rs
+++ b/wezterm-gui/src/termwindow/ui/plugin_panel/field.rs
@@ -1034,7 +1034,7 @@ impl TermWindow {
/// set on one line, from its left: as many as it has characters, and
/// one. The characters inside a cluster -- a ligature's -- share the
/// cluster's start.
- fn boundaries(
+ pub(super) fn boundaries(
&self,
font: &Rc<LoadedFont>,
metrics: &RenderMetrics,
@@ -1480,7 +1480,7 @@ fn wrap_line(
/// Whether a line may break before character `at` of `chars`: after a
/// space, or where the characters on either side are of a script written
/// without spaces -- but not before the punctuation that closes one.
-fn breaks_before(chars: &[char], at: usize) -> bool {
+pub(super) fn breaks_before(chars: &[char], at: usize) -> bool {
let (Some(before), Some(after)) = (chars.get(at.wrapping_sub(1)), chars.get(at)) else {
return false;
};