@kaynooo/cli-pick 0.9.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/pick.js +362 -73
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -14,7 +14,7 @@ bun add -g @kaynooo/cli-pick
14
14
  | `ls \| pick --preview 'head -20 {}'` | a pane on the right (terminal at least 80 columns) shows the command run for the highlighted line, `{}` shell-quoted |
15
15
  | `--height 12`, `--height 60%` | lines or a share of the terminal to draw in (100%) |
16
16
 
17
- Keys: type to filter, up and down or ctrl-p and ctrl-n to move, enter to pick, esc or ctrl-c to cancel (exit 1, nothing printed), ctrl-u clears the query, ctrl-w deletes a word, ctrl-/ or f1 opens a legend of the keys until the next key. The count line ends in a `ctrl-/ keys` hint, and the characters a query matched are underlined.
17
+ Keys: type to filter, up and down or ctrl-p and ctrl-n to move, enter to pick, esc or ctrl-c to cancel (exit 1, nothing printed), left and right (with ctrl or alt, by a word), ctrl-a and ctrl-e move the caret in the query, ctrl-w or ctrl-backspace deletes a word before it, ctrl-u and ctrl-k erase back to the start and on to the end, delete the character under it, ctrl-y puts back what they erased, ctrl-z suspends the pick to the shell until `fg`, ctrl-/ or f1 opens a legend of the keys until the next key. The count line ends in a `ctrl-/ keys` hint, and the characters a query matched are underlined.
18
18
 
19
19
  The query matches as a subsequence, best first: a word start, a run of consecutive characters or a prefix scores higher, a lowercase query ignores case and an uppercase letter makes it exact. Keys come from `/dev/tty` and the selector is drawn on stderr, so a pipe or a command substitution takes only the choice. Without a terminal on stderr it exits 2.
20
20
 
package/dist/pick.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/pick.ts
5
- import process16 from "process";
5
+ import process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -321,11 +321,31 @@ var STATUS_WORDS = {
321
321
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
322
322
 
323
323
  // ../kit/src/format.ts
324
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
325
+ function formatSeconds(total) {
326
+ let rest = Math.max(0, Math.round(total));
327
+ const amounts = UNITS.map(([unit, size]) => {
328
+ const amount = Math.floor(rest / size);
329
+ rest -= amount * size;
330
+ return `${amount}${unit}`;
331
+ });
332
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
333
+ if (first === -1)
334
+ return "0s";
335
+ const next = amounts[first + 1];
336
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
337
+ }
338
+ function formatDuration(ms) {
339
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
340
+ }
324
341
  function upTo(text, separator) {
325
342
  const end = text.indexOf(separator);
326
343
  return end === -1 ? text : text.slice(0, end);
327
344
  }
328
345
  var ESCAPE = String.fromCharCode(27);
346
+ function textWidth(text) {
347
+ return Bun.stringWidth(text);
348
+ }
329
349
  function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
330
350
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
331
351
  }
@@ -335,7 +355,7 @@ function printJson(value) {
335
355
 
336
356
  // ../kit/src/help.ts
337
357
  import process8 from "process";
338
- var OPTIONAL = /\[[^\]]+\]/g;
358
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
339
359
  var USAGE_PREFIX = /^usage:\s*/i;
340
360
  var FULL_STOP = /\.$/;
341
361
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -374,29 +394,41 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
374
394
  return [];
375
395
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
376
396
  }
397
+ var MAX_INLINE_CHOICES = 24;
377
398
  function optionRows(options, colors = paint(process8.stdout)) {
378
399
  const rows = Object.entries(options).map(([name, option]) => {
379
400
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
380
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
401
+ const choices = option.choices?.join("|");
402
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
403
+ const named = inline ? `<${choices}>` : "<value>";
381
404
  const placeholder = option.optional === undefined ? named : `[${named}]`;
382
405
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
383
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
406
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
407
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
384
408
  });
385
409
  const width = Math.max(0, ...rows.map((row) => row.width));
386
410
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
387
411
  }
388
412
 
389
413
  // ../kit/src/text.ts
390
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
414
+ var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
391
415
  function distance(a, b) {
392
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
393
- for (const [i, left] of [...a].entries()) {
416
+ const left = [...a];
417
+ const right = [...b];
418
+ let before = [];
419
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
420
+ for (const [i, x] of left.entries()) {
394
421
  const current = [i + 1];
395
- for (const [j, right] of [...b].entries())
396
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
422
+ for (const [j, y] of right.entries()) {
423
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
424
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
425
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
426
+ current.push(cost);
427
+ }
428
+ before = previous;
397
429
  previous = current;
398
430
  }
399
- return previous[b.length] ?? 0;
431
+ return previous[right.length] ?? 0;
400
432
  }
401
433
  function closest(name, names) {
402
434
  const started = names.find((known) => known.startsWith(name));
@@ -655,13 +687,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
655
687
  // ../kit/src/cli.ts
656
688
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
657
689
  import { dirname as dirname3, join as join5 } from "path";
658
- import process12 from "process";
690
+ import process13 from "process";
691
+
692
+ // ../kit/src/notify.ts
693
+ import process11 from "process";
694
+ var NOTIFY_AFTER_MS = 1e4;
695
+ var CANCELLED = 130;
696
+ function base64(text) {
697
+ return Buffer.from(text).toString("base64");
698
+ }
699
+ function notification(title, body, env = process11.env) {
700
+ const id = `kit${process11.pid}`;
701
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
702
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
703
+ }
704
+ function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
705
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
706
+ return;
707
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
708
+ }
659
709
 
660
710
  // ../kit/src/usage.ts
661
711
  import { appendFileSync, mkdirSync } from "fs";
662
712
  import { homedir as homedir3 } from "os";
663
713
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
664
- import process11 from "process";
714
+ import process12 from "process";
665
715
 
666
716
  // ../kit/src/logs.ts
667
717
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -675,14 +725,14 @@ var usageError;
675
725
  function noteUsageError(message) {
676
726
  usageError = message;
677
727
  }
678
- function stateHome(env = process11.env) {
728
+ function stateHome(env = process12.env) {
679
729
  const dir = env.XDG_STATE_HOME;
680
730
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
681
731
  }
682
- function usagePath(env = process11.env) {
732
+ function usagePath(env = process12.env) {
683
733
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
684
734
  }
685
- function usageRecorded(env = process11.env) {
735
+ function usageRecorded(env = process12.env) {
686
736
  const off = env.KAYNOOO_CLI_NO_USAGE;
687
737
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
688
738
  }
@@ -696,7 +746,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
696
746
  usageError = undefined;
697
747
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
698
748
  }
699
- function recordUsage(entry, env = process11.env) {
749
+ function recordUsage(entry, env = process12.env) {
700
750
  if (!usageRecorded(env))
701
751
  return;
702
752
  try {
@@ -714,8 +764,8 @@ var LEVEL_OPTIONS = {
714
764
  };
715
765
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
716
766
  function printError(prefix, message, hint, cause) {
717
- const colors = paint(process12.stderr);
718
- const styled = takesControlCodes(process12.stderr);
767
+ const colors = paint(process13.stderr);
768
+ const styled = takesControlCodes(process13.stderr);
719
769
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
720
770
  const under = (label, text, tint) => text === undefined ? "" : `
721
771
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -820,11 +870,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
820
870
  return 0;
821
871
  }
822
872
  let code;
873
+ const started = performance.now();
823
874
  try {
824
875
  code = await run(argv);
825
876
  } catch (error) {
826
877
  code = reportThrown(name, error, redact, wantsJson(argv));
827
878
  }
879
+ notifyEnd(name, code, performance.now() - started);
828
880
  if (usage !== false) {
829
881
  try {
830
882
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -840,6 +892,119 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
840
892
  var {Glob } = globalThis.Bun;
841
893
  var SESSION_FILES = new Glob("*.json");
842
894
  var ACCOUNT_DIRS = new Glob("*/sessions");
895
+ // ../kit/src/picker/line.ts
896
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
897
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
898
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
899
+ function isEditKey(key) {
900
+ return EDIT_KEYS.has(key);
901
+ }
902
+ function endsKills(key) {
903
+ return typeof key !== "object" && !isEditKey(key);
904
+ }
905
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
906
+ var SPACE = /\s/;
907
+ function isWord(char) {
908
+ return char !== undefined && WORD_CHARACTER.test(char);
909
+ }
910
+ function wordStart(chars, from) {
911
+ let at = from;
912
+ while (at > 0 && !isWord(chars[at - 1]))
913
+ at--;
914
+ while (at > 0 && isWord(chars[at - 1]))
915
+ at--;
916
+ return at;
917
+ }
918
+ function wordEnd(chars, from) {
919
+ let at = from;
920
+ while (at < chars.length && !isWord(chars[at]))
921
+ at++;
922
+ while (at < chars.length && isWord(chars[at]))
923
+ at++;
924
+ return at;
925
+ }
926
+ function spacedStart(chars, from) {
927
+ let at = from;
928
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
929
+ at--;
930
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
931
+ at--;
932
+ return at;
933
+ }
934
+ function cut(chars, from, to) {
935
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
936
+ }
937
+ function insert(chars, at, text) {
938
+ const typed = [...text];
939
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
940
+ }
941
+ function editLine(line, key) {
942
+ const { killed = "", chained = false } = line;
943
+ const chars = [...line.text];
944
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
945
+ const edited = edit(chars, at, key, killed);
946
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
947
+ return line.killed === undefined ? edited : { ...edited, killed };
948
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
949
+ if (taken === "")
950
+ return { ...edited, killed, chained };
951
+ if (!chained)
952
+ return { ...edited, killed: taken, chained: true };
953
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
954
+ }
955
+ function edit(chars, at, key, killed) {
956
+ const text = chars.join("");
957
+ if (typeof key === "object")
958
+ return insert(chars, at, key.text);
959
+ switch (key) {
960
+ case "left":
961
+ return { text, caret: Math.max(at - 1, 0) };
962
+ case "right":
963
+ return { text, caret: Math.min(at + 1, chars.length) };
964
+ case "wordleft":
965
+ return { text, caret: wordStart(chars, at) };
966
+ case "wordright":
967
+ return { text, caret: wordEnd(chars, at) };
968
+ case "linestart":
969
+ return { text, caret: 0 };
970
+ case "lineend":
971
+ return { text, caret: chars.length };
972
+ case "erase":
973
+ return cut(chars, Math.max(at - 1, 0), at);
974
+ case "delete":
975
+ return cut(chars, at, Math.min(at + 1, chars.length));
976
+ case "word":
977
+ return cut(chars, spacedStart(chars, at), at);
978
+ case "killword":
979
+ return cut(chars, wordStart(chars, at), at);
980
+ case "killnext":
981
+ return cut(chars, at, wordEnd(chars, at));
982
+ case "clear":
983
+ return cut(chars, 0, at);
984
+ case "killend":
985
+ return cut(chars, at, chars.length);
986
+ case "yank":
987
+ return insert(chars, at, killed);
988
+ }
989
+ }
990
+ function visible({ text, caret }, room) {
991
+ const chars = [...text];
992
+ const at = Math.min(Math.max(caret, 0), chars.length);
993
+ const cells = at === chars.length ? [...chars, " "] : chars;
994
+ const widths = cells.map((char) => Bun.stringWidth(char));
995
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
996
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
997
+ let start = at;
998
+ let end = at + 1;
999
+ while (start > 0 && fits(start - 1, end))
1000
+ start--;
1001
+ while (end < cells.length && fits(start, end + 1))
1002
+ end++;
1003
+ const left = start > 0 ? "\u2026" : "";
1004
+ const right = end < cells.length ? "\u2026" : "";
1005
+ return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
1006
+ }
1007
+
843
1008
  // ../kit/src/picker/score.ts
844
1009
  var MATCH = 16;
845
1010
  var CONSECUTIVE = 12;
@@ -924,7 +1089,6 @@ function rank(query, lines) {
924
1089
  }
925
1090
 
926
1091
  // ../kit/src/picker/state.ts
927
- var ANSI2 = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
928
1092
  var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
929
1093
  var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
930
1094
  var SGR = /^\x1B\[[0-9;]*m$/;
@@ -932,7 +1096,6 @@ var RESET = /^\x1B\[0?m$/;
932
1096
  var COLUMN_GAP = 2;
933
1097
  var PASTE_START = "\x1B[200~";
934
1098
  var PASTE_END = "\x1B[201~";
935
- var LAST_WORD = /\S*\s*$/;
936
1099
  var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
937
1100
  var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
938
1101
  var WHEEL_LINES = 3;
@@ -955,10 +1118,29 @@ var KEYS = {
955
1118
  "\n": "enter",
956
1119
  "\x03": "cancel",
957
1120
  "\x1B": "cancel",
1121
+ "\x1B[D": "left",
1122
+ "\x1BOD": "left",
1123
+ "\x1B[C": "right",
1124
+ "\x1BOC": "right",
1125
+ "\x1B[1;5D": "wordleft",
1126
+ "\x1B[1;3D": "wordleft",
1127
+ "\x1Bb": "wordleft",
1128
+ "\x1B[1;5C": "wordright",
1129
+ "\x1B[1;3C": "wordright",
1130
+ "\x1Bf": "wordright",
1131
+ "\x01": "linestart",
1132
+ "\x05": "lineend",
958
1133
  "\x7F": "erase",
959
- "\b": "erase",
1134
+ "\x1B[3~": "delete",
1135
+ "\b": "killword",
1136
+ "\x1B\x7F": "killword",
1137
+ "\x1B[3;5~": "killnext",
1138
+ "\x1Bd": "killnext",
960
1139
  "\x15": "clear",
1140
+ "\v": "killend",
961
1141
  "\x17": "word",
1142
+ "\x19": "yank",
1143
+ "\x1A": "suspend",
962
1144
  "\t": "tab",
963
1145
  "\x1F": "help",
964
1146
  "\x1BOP": "help",
@@ -979,7 +1161,7 @@ function styled(line) {
979
1161
  colored ||= active !== "" && flat !== "";
980
1162
  styles.push(...repeat(active, flat.length));
981
1163
  }
982
- for (const found of line.matchAll(ANSI2)) {
1164
+ for (const found of line.matchAll(ANSI)) {
983
1165
  add(line.slice(last, found.index));
984
1166
  last = found.index + found[0].length;
985
1167
  if (SGR.test(found[0]))
@@ -991,7 +1173,7 @@ function styled(line) {
991
1173
  function lay(rows, searched) {
992
1174
  const parsed = rows.map((row) => row.cells.map(styled));
993
1175
  const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
994
- return parsed.map((cells) => {
1176
+ return parsed.map((cells, at) => {
995
1177
  let text = "";
996
1178
  const styles = [];
997
1179
  let colored = false;
@@ -1010,7 +1192,7 @@ function lay(rows, searched) {
1010
1192
  styles.push(...repeat("", pad));
1011
1193
  }
1012
1194
  }
1013
- return { text, styles: colored ? styles : undefined, searchable: text.slice(0, searchEnd) };
1195
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1014
1196
  });
1015
1197
  }
1016
1198
  function parseKeys(input, paste = { active: false }, ctrls = []) {
@@ -1034,7 +1216,7 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1034
1216
  });
1035
1217
  }
1036
1218
  function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1037
- const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1219
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1038
1220
  return withRows(state, rows);
1039
1221
  }
1040
1222
  function withRows(state, rows, header = state.header) {
@@ -1044,8 +1226,9 @@ function withRows(state, rows, header = state.header) {
1044
1226
  const matches = rank(state.query, searchable);
1045
1227
  return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1046
1228
  }
1047
- function withQuery(state, query) {
1048
- return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
1229
+ function withQuery(state, key) {
1230
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1231
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1049
1232
  }
1050
1233
  function move(state, by) {
1051
1234
  return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
@@ -1056,13 +1239,17 @@ function highlighted(state) {
1056
1239
  function press(state, key) {
1057
1240
  if (state.done !== undefined)
1058
1241
  return state;
1242
+ if (state.chained && endsKills(key))
1243
+ state = { ...state, chained: false };
1059
1244
  if (state.help)
1060
1245
  return { ...state, help: false };
1061
1246
  if (typeof key === "object") {
1062
1247
  if ("text" in key)
1063
- return withQuery(state, state.query + key.text);
1248
+ return withQuery(state, key);
1064
1249
  return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1065
1250
  }
1251
+ if (isEditKey(key))
1252
+ return withQuery(state, key);
1066
1253
  switch (key) {
1067
1254
  case "up":
1068
1255
  return move(state, -1);
@@ -1080,12 +1267,8 @@ function press(state, key) {
1080
1267
  return { ...state, done: "cancel" };
1081
1268
  case "help":
1082
1269
  return { ...state, help: true };
1083
- case "erase":
1084
- return withQuery(state, [...state.query].slice(0, -1).join(""));
1085
- case "clear":
1086
- return withQuery(state, "");
1087
- case "word":
1088
- return withQuery(state, state.query.replace(LAST_WORD, ""));
1270
+ case "suspend":
1271
+ return state;
1089
1272
  case "enter":
1090
1273
  return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1091
1274
  case "tab": {
@@ -1108,11 +1291,25 @@ function chosen(state) {
1108
1291
 
1109
1292
  // ../kit/src/picker/terminal.ts
1110
1293
  import { openSync } from "fs";
1111
- import process15 from "process";
1294
+ import process17 from "process";
1112
1295
  import tty from "tty";
1113
1296
 
1297
+ // ../kit/src/job.ts
1298
+ import process15 from "process";
1299
+ function stopJob() {
1300
+ process15.kill(0, "SIGTSTP");
1301
+ }
1302
+
1303
+ // ../kit/src/redraw.ts
1304
+ var SYNC_START = "\x1B[?2026h";
1305
+ var SYNC_END = "\x1B[?2026l";
1306
+ function overwrite(lines, columns) {
1307
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1308
+ `);
1309
+ }
1310
+
1114
1311
  // ../kit/src/picker/preview.ts
1115
- import process14 from "process";
1312
+ import process16 from "process";
1116
1313
 
1117
1314
  // ../kit/src/shell.ts
1118
1315
  var SEPARATORS = new Set([`
@@ -1181,7 +1378,7 @@ async function runPreview(template, line, signal, hidden = []) {
1181
1378
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1182
1379
  const stop = () => {
1183
1380
  try {
1184
- process14.kill(-proc.pid, "SIGKILL");
1381
+ process16.kill(-proc.pid, "SIGKILL");
1185
1382
  } catch {
1186
1383
  proc.kill();
1187
1384
  }
@@ -1257,13 +1454,20 @@ function fitStyled(line, width, plain = identity) {
1257
1454
  const { text, styles } = styled(line);
1258
1455
  return fit(text, width, plain, plain, new Set, styles);
1259
1456
  }
1260
- function caretColumn(state, layout) {
1261
- return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
1457
+ function queryShown(state, layout) {
1458
+ return visible({ text: state.query, caret: state.caret }, Math.max(1, layout.listWidth - Bun.stringWidth(state.prompt)));
1459
+ }
1460
+ function caretCell(state, layout) {
1461
+ const shown = queryShown(state, layout);
1462
+ return { column: Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + shown.column + 1), char: shown.at ?? " " };
1262
1463
  }
1263
1464
  function helpLines(state, layout, theme) {
1264
1465
  const lines = [
1265
1466
  "type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move",
1266
- `enter picks${state.multi ? ", tab marks" : ""}, ctrl-u clears the query, ctrl-w a word, esc or ctrl-c cancels`,
1467
+ "left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word",
1468
+ "ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead",
1469
+ "ctrl-y puts back what they erased, ctrl-z suspends to the shell",
1470
+ `enter picks${state.multi ? ", tab marks" : ""}, esc or ctrl-c cancels`,
1267
1471
  ...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
1268
1472
  ];
1269
1473
  const title = "keys, any key closes this help";
@@ -1279,7 +1483,9 @@ function listLines(state, layout, theme) {
1279
1483
  const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
1280
1484
  const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
1281
1485
  const promptWidth = Bun.stringWidth(state.prompt);
1282
- const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
1486
+ const shown = queryShown(state, layout);
1487
+ const text = `${shown.before}${shown.at ?? ""}${shown.after}`;
1488
+ const query = { text, width: Bun.stringWidth(text) };
1283
1489
  const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
1284
1490
  const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
1285
1491
  const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
@@ -1312,7 +1518,8 @@ var ESCAPE_WAIT_MS = 30;
1312
1518
  var OPEN = { ctrl: "open" };
1313
1519
  var HIDE_CURSOR = "\x1B[?25l";
1314
1520
  var SHOW_CURSOR = "\x1B[?25h";
1315
- var CARET = "\x1B[7m \x1B[27m";
1521
+ var REVERSE = "\x1B[7m";
1522
+ var REVERSE_END = "\x1B[27m";
1316
1523
  var PASTE_ON = "\x1B[?2004h";
1317
1524
  var PASTE_OFF = "\x1B[?2004l";
1318
1525
  var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
@@ -1330,7 +1537,7 @@ function openTerminal() {
1330
1537
  return fail("no terminal to read keys from (/dev/tty)");
1331
1538
  }
1332
1539
  const keys = Bun.file("/dev/tty").stream().getReader();
1333
- const out = process15.stderr;
1540
+ const out = process17.stderr;
1334
1541
  let resize;
1335
1542
  async function read(onChunk) {
1336
1543
  const decoder = new TextDecoder;
@@ -1356,6 +1563,11 @@ function openTerminal() {
1356
1563
  out.on("resize", onResize);
1357
1564
  read(onChunk);
1358
1565
  },
1566
+ suspend() {
1567
+ mode.setRawMode(false);
1568
+ stopJob();
1569
+ mode.setRawMode(true);
1570
+ },
1359
1571
  close() {
1360
1572
  if (resize !== undefined)
1361
1573
  out.off("resize", resize);
@@ -1383,14 +1595,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1383
1595
  if (restored)
1384
1596
  return;
1385
1597
  const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1386
- let frame = HIDE_CURSOR;
1598
+ let frame = SYNC_START + HIDE_CURSOR;
1387
1599
  if (reserved !== layout.height || clear) {
1388
1600
  frame += CLEAR_BELOW + `
1389
1601
  `.repeat(layout.height - 1) + up(layout.height - 1);
1390
1602
  reserved = layout.height;
1391
1603
  }
1392
- frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
1393
- `)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${CARET}\r`;
1604
+ const caret = caretCell(state, layout);
1605
+ frame += `\r${overwrite(render(state, layout, theme, preview), terminal.columns)}${up(layout.height - 1)}\r\x1B[${caret.column}G${REVERSE}${caret.char}${REVERSE_END}\r${SYNC_END}`;
1394
1606
  terminal.write(frame);
1395
1607
  }
1396
1608
  function pageSize() {
@@ -1432,6 +1644,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1432
1644
  terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1433
1645
  terminal.close();
1434
1646
  }
1647
+ function suspend() {
1648
+ if (terminal.suspend === undefined)
1649
+ return;
1650
+ terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1651
+ terminal.suspend();
1652
+ terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1653
+ draw(true);
1654
+ }
1435
1655
  const stop = () => {
1436
1656
  state = { ...state, done: "cancel" };
1437
1657
  finish?.();
@@ -1465,6 +1685,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1465
1685
  for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
1466
1686
  if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
1467
1687
  await reloadRows();
1688
+ else if (key === "suspend")
1689
+ suspend();
1468
1690
  else
1469
1691
  state = press({ ...state, page: pageSize() }, key);
1470
1692
  }
@@ -1504,9 +1726,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1504
1726
  const ended = new Promise((resolve) => {
1505
1727
  finish = resolve;
1506
1728
  });
1507
- process15.once("exit", restore);
1729
+ process17.once("exit", restore);
1508
1730
  for (const signal of SIGNALS)
1509
- process15.once(signal, stop);
1731
+ process17.once(signal, stop);
1510
1732
  try {
1511
1733
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1512
1734
  terminal.listen(onChunk, () => draw(true));
@@ -1519,8 +1741,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1519
1741
  await ended;
1520
1742
  } finally {
1521
1743
  for (const signal of SIGNALS)
1522
- process15.off(signal, stop);
1523
- process15.off("exit", restore);
1744
+ process17.off(signal, stop);
1745
+ process17.off("exit", restore);
1524
1746
  restore();
1525
1747
  }
1526
1748
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1532,60 +1754,127 @@ async function previewOf(preview, hidden, signal) {
1532
1754
  return [error instanceof Error ? error.message : String(error)];
1533
1755
  }
1534
1756
  }
1535
- async function choose(lines, settings) {
1536
- const picked = await select(lines.map((line) => ({ hidden: [], cells: [line] })), settings);
1537
- return picked?.rows.map((row) => row.cells[0]);
1757
+ // src/fields.ts
1758
+ var INDEX = /^-?\d+$/;
1759
+ function splitFields(line, delimiter) {
1760
+ if (delimiter === undefined)
1761
+ return line.match(/\s*\S+\s*/g) ?? [];
1762
+ const fields = [];
1763
+ let from = 0;
1764
+ for (const match of line.matchAll(new RegExp(delimiter, `${delimiter.flags}g`))) {
1765
+ if (match[0] === "")
1766
+ continue;
1767
+ fields.push(line.slice(from, match.index + match[0].length));
1768
+ from = match.index + match[0].length;
1769
+ }
1770
+ fields.push(line.slice(from));
1771
+ return fields;
1772
+ }
1773
+ function parseFields(expression) {
1774
+ const spans = [];
1775
+ for (const part of expression.split(",")) {
1776
+ const dots = part.indexOf("..");
1777
+ const from = dots === -1 ? part : part.slice(0, dots);
1778
+ const to = dots === -1 ? from : part.slice(dots + 2);
1779
+ if (part === "0" || part === "" || from !== "" && !INDEX.test(from) || to !== "" && !INDEX.test(to))
1780
+ return;
1781
+ const resolve = (n, count) => n < 0 ? count + n : n - 1;
1782
+ spans.push((count) => {
1783
+ const first = from === "" ? 0 : resolve(Number(from), count);
1784
+ const last = to === "" ? count - 1 : resolve(Number(to), count);
1785
+ return Array.from({ length: Math.max(0, last - first + 1) }, (_, i) => first + i).filter((i) => i >= 0 && i < count);
1786
+ });
1787
+ }
1788
+ return (count) => spans.flatMap((span) => span(count));
1789
+ }
1790
+ function pickFields(line, select, delimiter) {
1791
+ const fields = splitFields(line, delimiter);
1792
+ return select(fields.length).map((i) => fields[i]).join("");
1538
1793
  }
1794
+
1539
1795
  // src/pick.ts
1540
1796
  var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
1541
1797
 
1542
- Type to filter: the query matches as a subsequence, best matches first (a word start, a run of characters or a prefix scores higher; a lowercase query ignores case, an uppercase letter makes it exact). Up and down or ctrl-p and ctrl-n move, enter picks, esc and ctrl-c cancel, ctrl-u clears the query, ctrl-/ or f1 shows the keys.
1798
+ Type to filter: the query matches as a subsequence, best matches first (a word start, a run of characters or a prefix scores higher; a lowercase query ignores case, an uppercase letter makes it exact). Up and down or ctrl-p and ctrl-n move, enter picks, esc and ctrl-c cancel, left, right, ctrl-a and ctrl-e move in the query (ctrl or alt for a word), ctrl-u and ctrl-k erase back to its start and on to its end, ctrl-y puts back what they erased, ctrl-z suspends, ctrl-/ or f1 shows the keys.
1543
1799
  The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks the highlighted line and enter prints the marked lines in input order (the highlighted one when none is marked).
1544
1800
  --preview runs a command for the highlighted line, \`{}\` standing for it shell-quoted, in a pane on the right when the terminal is at least 80 columns wide; its output is cut at 64 KiB and 200 lines.
1545
1801
 
1546
- Without a terminal on stderr there is nobody to choose: it prints the first line containing the query (case-insensitive), every one with --multi.`;
1547
- var EXITS = [[0, "it printed a choice"], [1, "cancelled, nothing matches or there are no lines"], [2, "a usage error"]];
1802
+ --delimiter splits each line into fields (a regex, whitespace by default), --nth names the fields the query is matched against and --with-nth the ones shown, in fzf's syntax: 1-based, \`-1\` the last, \`2..\`, \`..3\`, \`2..4\`, comma-separated. The printed line is always the whole input line. --read0 reads NUL-separated lines and --print0 ends each printed one with NUL.
1803
+ --filter takes the query and prints every match best first with no terminal; --select-1 prints the only match without opening the selector, --exit-0 exits 1 at once when nothing matches.
1804
+
1805
+ Without a terminal on stderr there is nobody to choose: it prints the best line the query matches, as the selector would rank it, or every match best first with --multi.`;
1806
+ var EXITS = [[0, "it printed a choice"], [1, "nothing matches or there are no lines"], [2, "a usage error"], [130, "cancelled"]];
1548
1807
  var OPTIONS = {
1549
1808
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
1550
1809
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
1551
1810
  query: { type: "string", short: "q", description: "the query to start with" },
1552
1811
  preview: { type: "string", description: "a command shown for the highlighted line, {} standing for it" },
1812
+ header: { type: "string", description: "a line of text shown above the list" },
1813
+ filter: { type: "string", short: "f", description: "print every line the query matches, best first, with no terminal" },
1814
+ "select-1": { type: "boolean", short: "1", description: "print the only match without opening the selector" },
1815
+ "exit-0": { type: "boolean", short: "0", description: "exit 1 at once when nothing matches" },
1816
+ delimiter: { type: "string", short: "d", description: "a regex splitting a line into fields (whitespace)" },
1817
+ nth: { type: "string", description: "the fields the query is matched against, 2, -1, 2.., 1..3, 1,3" },
1818
+ "with-nth": { type: "string", description: "the fields shown, the printed line stays whole" },
1819
+ read0: { type: "boolean", description: "lines on stdin end with NUL" },
1820
+ print0: { type: "boolean", description: "end each printed line with NUL" },
1553
1821
  height: { type: "string", description: "lines or a percentage of the terminal to draw in (100%)" },
1554
1822
  json: jsonOption("{picked: [lines]}, the choice or the marked lines in input order")
1555
1823
  };
1556
- function print(chosen, json) {
1824
+ function print(chosen, json, end) {
1557
1825
  if (json)
1558
1826
  printJson({ picked: chosen });
1559
1827
  else
1560
- process16.stdout.write(`${chosen.join(`
1561
- `)}
1562
- `);
1828
+ process18.stdout.write(chosen.map((line) => line + end).join(""));
1563
1829
  }
1564
1830
  async function main(args) {
1565
- const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'"] });
1831
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'", "git branch | pick --filter main # every match, best first, no terminal", "ps aux | pick --with-nth 2,11.. --nth 11.. # show some fields, search others"] });
1566
1832
  if (positionals.length > 0)
1567
1833
  badUsage("pick takes its lines on stdin, not as arguments");
1568
1834
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1569
1835
  if (height === undefined)
1570
1836
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1571
- if (process16.stdin.isTTY)
1837
+ if (process18.stdin.isTTY)
1572
1838
  badUsage("pipe the lines to pick on stdin");
1573
- const lines = (await Bun.stdin.text()).split(`
1839
+ const fieldsOf = (name) => {
1840
+ const text = values[name];
1841
+ if (text === undefined)
1842
+ return;
1843
+ return parseFields(text) ?? badUsage(`--${name} takes fields such as 2, -1, 2.., 1..3 or 1,3, not ${text}`);
1844
+ };
1845
+ const nth = fieldsOf("nth");
1846
+ const withNth = fieldsOf("with-nth");
1847
+ let delimiter;
1848
+ try {
1849
+ delimiter = values.delimiter === undefined ? undefined : new RegExp(values.delimiter);
1850
+ } catch {
1851
+ badUsage(`--delimiter is a regex, not ${values.delimiter}`);
1852
+ }
1853
+ const lines = (await Bun.stdin.text()).split(values.read0 === true ? "\x00" : `
1574
1854
  `).filter((line) => line !== "");
1575
1855
  if (lines.length === 0)
1576
1856
  fail("nothing to pick from", 1);
1577
- if (!process16.stderr.isTTY) {
1578
- const query = (values.query ?? "").toLowerCase();
1579
- const matching = lines.filter((line) => line.toLowerCase().includes(query));
1580
- if (matching.length === 0)
1581
- return 1;
1582
- print(values.multi === true ? matching : matching.slice(0, 1), values.json === true);
1857
+ const query = values.filter ?? values.query ?? "";
1858
+ const end = values.print0 === true ? "\x00" : `
1859
+ `;
1860
+ const json = values.json === true;
1861
+ const searched = lines.map((line) => nth === undefined ? line : pickFields(line, nth, delimiter));
1862
+ const matching = rank(query, searched).map(({ index }) => lines[index]);
1863
+ if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process18.stderr.isTTY))
1864
+ return 1;
1865
+ if (values.filter !== undefined || !process18.stderr.isTTY) {
1866
+ print(values.multi === true || values.filter !== undefined ? matching : matching.slice(0, 1), json, end);
1583
1867
  return 0;
1584
1868
  }
1585
- const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
1869
+ if (values["select-1"] === true && matching.length === 1) {
1870
+ print(matching, json, end);
1871
+ return 0;
1872
+ }
1873
+ const rows = lines.map((line, index) => ({ hidden: [line], cells: [withNth === undefined ? line : pickFields(line, withNth, delimiter).trimEnd()], ...nth === undefined ? {} : { search: searched[index] } }));
1874
+ const picked = await select(rows, { multi: values.multi === true, prompt: values.prompt ?? "> ", query, height, preview: values.preview, header: values.header });
1586
1875
  if (picked === undefined)
1587
- return 1;
1588
- print(picked, values.json === true);
1876
+ return 130;
1877
+ print(picked.rows.map((row) => row.hidden[0]), json, end);
1589
1878
  return 0;
1590
1879
  }
1591
- process16.exitCode = await runMain({ name: "pick", run: main });
1880
+ process18.exitCode = await runMain({ name: "pick", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-pick",
3
3
  "type": "module",
4
- "version": "0.9.2",
4
+ "version": "0.11.0",
5
5
  "description": "pick: a themed fuzzy selector, lines on stdin, the chosen one on stdout.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "pick": "$npm_execpath src/pick.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.38.3"
38
+ "@kaynooo/cli-kit": "0.40.0"
39
39
  }
40
40
  }