Skip to content

Commit 6049f26

Browse files
committed
Add widthMode to markdown table and use it
Introduce a WidthMode option to renderMarkdownTable with two modes: "raw" (string length) and "markdown-conceal" (strips/normalizes markdown for visual width). Implement grapheme-aware measurement via Intl.Segmenter (with fallback), improved width calculation that handles escaped pipes and inline code, and update padCell to honor the chosen width mode. Use the new markdown-conceal mode in quota-stats-format to improve TUI table alignment. Also add an LLM Agents install note and anchor to the README.
1 parent 92b457b commit 6049f26

3 files changed

Lines changed: 103 additions & 12 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ Then enable the providers you use:
3636

3737
That's it. Toasts appear automatically after assistant responses.
3838

39+
> **LLM Agents:** Ask your agent to install `https://github.com/slkiser/opencode-quota` with the providers you have enabled. See [LLM Agent Installation Instructions](#llm-agent-installation-instructions) for details.
40+
3941
## Commands
4042

4143
| Command | Description |
@@ -183,7 +185,7 @@ Toast not appearing? Run `/quota_status` to check config and provider availabili
183185

184186
---
185187

186-
<details>
188+
<details id="llm-agent-installation-instructions">
187189
<summary><strong>LLM Agent Installation Instructions</strong></summary>
188190

189191
### For LLM Agents: How to Install and Configure

‎src/lib/markdown-table.ts‎

Lines changed: 91 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,92 @@
11
type Align = "left" | "right" | "center";
22

3-
function padCell(text: string, width: number, align: Align): string {
3+
/**
4+
* Width measurement mode:
5+
* - "raw": Use string length (grapheme count)
6+
* - "markdown-conceal": Strip markdown syntax for width calculation (for TUI concealment mode)
7+
*/
8+
export type WidthMode = "raw" | "markdown-conceal";
9+
10+
/**
11+
* Use Intl.Segmenter for grapheme-aware width measurement when available.
12+
* Falls back to Array.from for code point count.
13+
*/
14+
const GRAPHEME_SEGMENTER =
15+
typeof Intl !== "undefined" && typeof Intl.Segmenter === "function"
16+
? new Intl.Segmenter(undefined, { granularity: "grapheme" })
17+
: null;
18+
19+
/**
20+
* Measure width using grapheme clusters (preferred) or code points (fallback).
21+
*/
22+
function measureWidth(text: string): number {
23+
const s = text ?? "";
24+
if (!s) return 0;
25+
if (GRAPHEME_SEGMENTER) {
26+
let n = 0;
27+
for (const _ of GRAPHEME_SEGMENTER.segment(s)) n++;
28+
return n;
29+
}
30+
return Array.from(s).length;
31+
}
32+
33+
/**
34+
* Convert markdown text to visual representation for width calculation.
35+
* Strips markdown syntax that is hidden in concealment mode.
36+
*/
37+
function toVisualTextForWidth(text: string): string {
38+
// Treat escaped markdown pipes as a single visual char.
39+
let t = (text ?? "").replace(/\\\|/g, "|");
40+
41+
// Protect inline code so markdown inside `code` remains literal.
42+
const codeSpans: string[] = [];
43+
t = t.replace(/`([^`]+?)`/g, (_m, content: string) => {
44+
codeSpans.push(content);
45+
return `\x00CODE${codeSpans.length - 1}\x00`;
46+
});
47+
48+
let prev = "";
49+
while (t !== prev) {
50+
prev = t;
51+
t = t
52+
// ***bold+italic*** -> text
53+
.replace(/\*\*\*(.+?)\*\*\*/g, "$1")
54+
// **bold** -> text
55+
.replace(/\*\*(.+?)\*\*/g, "$1")
56+
// *italic* -> text
57+
.replace(/\*(.+?)\*/g, "$1")
58+
// ~~strikethrough~~ -> text
59+
.replace(/~~(.+?)~~/g, "$1")
60+
// ![alt](url) -> alt
61+
.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, "$1")
62+
// [text](url) -> text (url)
63+
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1 ($2)");
64+
}
65+
66+
// Restore inline code contents (without backticks)
67+
t = t.replace(/\x00CODE(\d+)\x00/g, (_m, idx: string) => {
68+
const i = Number(idx);
69+
return Number.isFinite(i) ? (codeSpans[i] ?? "") : "";
70+
});
71+
72+
return t;
73+
}
74+
75+
/**
76+
* Calculate cell width based on the specified mode.
77+
*/
78+
function cellWidth(text: string, widthMode: WidthMode): number {
79+
if (widthMode === "markdown-conceal") {
80+
return measureWidth(toVisualTextForWidth(text));
81+
}
82+
return measureWidth(text);
83+
}
84+
85+
function padCell(text: string, width: number, align: Align, widthMode: WidthMode): string {
486
const s = text ?? "";
5-
const len = s.length;
6-
if (len >= width) return s;
7-
const pad = width - len;
87+
const w = cellWidth(s, widthMode);
88+
if (w >= width) return s;
89+
const pad = width - w;
890
if (align === "right") return " ".repeat(pad) + s;
991
if (align === "center") {
1092
const left = Math.floor(pad / 2);
@@ -23,8 +105,10 @@ export function renderMarkdownTable(params: {
23105
headers: string[];
24106
rows: string[][];
25107
aligns?: Align[];
108+
widthMode?: WidthMode;
26109
}): string {
27110
const aligns: Align[] = params.aligns ?? params.headers.map(() => "left");
111+
const widthMode: WidthMode = params.widthMode ?? "raw";
28112
const colCount = params.headers.length;
29113

30114
const safeRows = params.rows.map((r) => {
@@ -35,17 +119,15 @@ export function renderMarkdownTable(params: {
35119

36120
const headerCells = params.headers.map((h) => escapeCell(h));
37121

38-
const widths = headerCells.map((h) => Math.max(3, h.length));
122+
const widths = headerCells.map((h) => Math.max(3, cellWidth(h, widthMode)));
39123
for (const row of safeRows) {
40124
for (let i = 0; i < colCount; i++) {
41-
widths[i] = Math.max(widths[i], (row[i] ?? "").length);
125+
widths[i] = Math.max(widths[i], cellWidth(row[i] ?? "", widthMode));
42126
}
43127
}
44128

45129
const fmtRow = (cells: string[]) =>
46-
`| ${cells
47-
.map((c, i) => padCell(c, widths[i], aligns[i] ?? "left"))
48-
.join(" | ")} |`;
130+
`| ${cells.map((c, i) => padCell(c, widths[i], aligns[i] ?? "left", widthMode)).join(" | ")} |`;
49131

50132
const sep = `| ${widths
51133
.map((w, i) => {

‎src/lib/quota-stats-format.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import type { AggregateResult, TokenBuckets } from "./quota-stats.js";
2-
import { renderMarkdownTable } from "./markdown-table.js";
2+
import { renderMarkdownTable, type WidthMode } from "./markdown-table.js";
3+
4+
/** Use markdown-conceal for proper TUI alignment (strips markdown syntax for width calc) */
5+
const TABLE_WIDTH_MODE: WidthMode = "markdown-conceal";
36

47
function fmtUsd(n: number): string {
58
if (!Number.isFinite(n)) return "$0.00";
@@ -115,6 +118,7 @@ export function formatQuotaStatsReport(params: {
115118
renderMarkdownTable({
116119
headers: ["Messages", "Tokens", "Cost"],
117120
aligns: ["right", "right", "right"],
121+
widthMode: TABLE_WIDTH_MODE,
118122
rows: [
119123
[
120124
fmtCompact(r.totals.messageCount),
@@ -129,6 +133,7 @@ export function formatQuotaStatsReport(params: {
129133
renderMarkdownTable({
130134
headers: ["Window", "Messages", "Sessions", "Tokens", "Cost"],
131135
aligns: ["left", "right", "right", "right", "right"],
136+
widthMode: TABLE_WIDTH_MODE,
132137
rows: [
133138
[
134139
fmtWindow(r.window),
@@ -199,7 +204,7 @@ export function formatQuotaStatsReport(params: {
199204
lines.push("");
200205
lines.push(`## Models`);
201206
lines.push("");
202-
lines.push(renderMarkdownTable({ headers, rows, aligns }));
207+
lines.push(renderMarkdownTable({ headers, rows, aligns, widthMode: TABLE_WIDTH_MODE }));
203208
}
204209

205210
// Skip Top Sessions for session-only reports (e.g., /tokens_session)
@@ -241,6 +246,7 @@ export function formatQuotaStatsReport(params: {
241246
renderMarkdownTable({
242247
headers: ["", "Session", "Cost", "Tokens", "Msgs", "Title"],
243248
aligns: ["left", "left", "right", "right", "right", "left"],
249+
widthMode: TABLE_WIDTH_MODE,
244250
rows: sessionRows,
245251
}),
246252
);
@@ -254,6 +260,7 @@ export function formatQuotaStatsReport(params: {
254260
renderMarkdownTable({
255261
headers: ["Source", "Model", "Mapped", "Tokens", "Msgs"],
256262
aligns: ["left", "left", "left", "right", "right"],
263+
widthMode: TABLE_WIDTH_MODE,
257264
rows: r.unknown.slice(0, 20).map((u) => {
258265
const mapped =
259266
u.key.mappedProvider && u.key.mappedModel

0 commit comments

Comments
 (0)