Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/keysmash/src/text.ts

Raw
// Pure text rules for the prompt editor. No Pi imports; everything works on
// plain lines so behavior stays testable and independent of the editor.

export type ItemKind = "bullet" | "ordered" | "task" | "quote";

/** A line that starts with a list or quote marker. */
export interface Item {
	kind: ItemKind;
	/** Leading spaces before the marker. */
	indent: number;
	/** Everything before the content: indent, marker, gaps, task box. */
	prefix: string;
	/** Marker plus following gap, without indent; child items align after it. */
	markerWidth: number;
	/** Text after the prefix. */
	content: string;
	/** Prefix a following item should start with. */
	next: string;
}

const LIST = /^( *)([-*+]|(\d{1,3})([.)]))( +)(?:(\[[ xX]\])( +|$))?(.*)$/;
const QUOTE = /^( *)(>(?: ?>)* )(.*)$/;
const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;

export const MAX_INDENT = 32;
export const INDENT_STEP = 2;

export function parseItem(line: string): Item | undefined {
	const list = LIST.exec(line);
	if (list) {
		const indent = list[1] ?? "";
		const marker = list[2] ?? "";
		const gap = list[5] ?? "";
		const box = list[6];
		const boxGap = list[7] ?? "";
		const content = list[8] ?? "";
		const ordered = list[3] !== undefined;
		const nextMarker = ordered
			? `${Number(list[3]) + 1}${list[4] ?? "."}`
			: marker;
		// A bare "[ ]" with nothing after it still counts as an empty task.
		const prefix = `${indent}${marker}${gap}${box ? `${box}${boxGap}` : ""}`;
		const nextBox = box ? `[ ]${boxGap || " "}` : "";
		return {
			kind: box ? "task" : ordered ? "ordered" : "bullet",
			indent: indent.length,
			prefix,
			markerWidth: marker.length + gap.length,
			content,
			next: `${indent}${nextMarker}${gap}${nextBox}`,
		};
	}
	const quote = QUOTE.exec(line);
	if (quote) {
		const indent = quote[1] ?? "";
		const marker = quote[2] ?? "";
		return {
			kind: "quote",
			indent: indent.length,
			prefix: `${indent}${marker}`,
			markerWidth: marker.length,
			content: quote[3] ?? "",
			next: `${indent}${marker}`,
		};
	}
	return undefined;
}

export function isEmptyItem(item: Item): boolean {
	return item.content.trim() === "";
}

/** True when `lines[index]` sits inside an open fenced code block. */
export function insideFence(lines: readonly string[], index: number): boolean {
	let open: { char: string; length: number } | undefined;
	for (let i = 0; i < index && i < lines.length; i++) {
		const match = FENCE.exec(lines[i] ?? "");
		if (!match) continue;
		const run = match[1] ?? "";
		const rest = match[2] ?? "";
		if (!open) {
			// A backtick fence's info string may not contain backticks.
			if (run.startsWith("`") && rest.includes("`")) continue;
			open = { char: run.charAt(0), length: run.length };
		} else if (
			run.charAt(0) === open.char &&
			run.length >= open.length &&
			rest.trim() === ""
		) {
			open = undefined;
		}
	}
	return open !== undefined;
}

/** Indent a Tab press should give list line `index`, or undefined for none. */
export function indentTarget(
	lines: readonly string[],
	index: number,
): number | undefined {
	const item = parseItem(lines[index] ?? "");
	if (!item || item.kind === "quote") return undefined;
	const above = index > 0 ? parseItem(lines[index - 1] ?? "") : undefined;
	let target = item.indent + INDENT_STEP;
	if (above && above.kind !== "quote" && above.indent <= item.indent)
		target = Math.max(target, above.indent + above.markerWidth);
	return target > MAX_INDENT ? undefined : target;
}

/** Indent a Shift+Tab press should give list line `index`, or undefined for none. */
export function outdentTarget(
	lines: readonly string[],
	index: number,
): number | undefined {
	const item = parseItem(lines[index] ?? "");
	if (!item || item.kind === "quote" || item.indent === 0) return undefined;
	for (let i = index - 1; i >= 0; i--) {
		const parent = parseItem(lines[i] ?? "");
		if (!parent) break;
		if (parent.kind !== "quote" && parent.indent < item.indent)
			return parent.indent;
	}
	return Math.max(0, item.indent - INDENT_STEP);
}

/** Tab on text that looks like a path or mention belongs to completion. */
export function looksCompletable(beforeCursor: string): boolean {
	const token = beforeCursor.split(/\s/u).at(-1) ?? "";
	return /^[@~.]/u.test(token) || token.includes("/");
}

const PAIRS: Readonly<Record<string, string>> = {
	"(": ")",
	"[": "]",
	"{": "}",
	'"': '"',
	"`": "`",
};
const CLOSERS = new Set(Object.values(PAIRS));
const SYMMETRIC = new Set(['"', "`"]);
const WORD = /[\p{L}\p{N}_]/u;

export function closerFor(opener: string): string {
	return PAIRS[opener] ?? opener;
}

export type PairAction = "overtype" | "pair" | undefined;

/** What typing `typed` between `before` and `after` should do. */
export function pairAction(
	typed: string,
	before: string,
	after: string,
): PairAction {
	const next = after.charAt(0);
	if (CLOSERS.has(typed) && next === typed) return "overtype";
	const closer = PAIRS[typed];
	if (closer === undefined) return undefined;
	const prev = before.slice(-1);
	if (prev === "\\") return undefined;
	if (next !== "" && !/\s/u.test(next) && !")]}".includes(next))
		return undefined;
	if (SYMMETRIC.has(typed) && (WORD.test(prev) || prev === typed))
		return undefined;
	// Emoticons such as ":(" are not brackets.
	if (typed === "(" && (prev === ":" || prev === ";")) return undefined;
	return "pair";
}

/** True when Backspace between `before` and `after` should delete a pair. */
export function isEmptyPair(before: string, after: string): boolean {
	const opener = before.slice(-1);
	const closer = PAIRS[opener];
	return closer !== undefined && after.startsWith(closer);
}

export function leadingSpaces(line: string): number {
	return /^ */u.exec(line)?.[0].length ?? 0;
}