@kaynooo/cli-pick 0.9.1 → 0.11.1

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 +485 -94
  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 process15 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,24 +355,20 @@ 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)) {
342
362
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
363
  }
344
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
345
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
364
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
365
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
366
  `);
347
367
  }
348
368
  function exitRows(exits, colors = paint(process8.stdout)) {
349
369
  if (exits.length === 0)
350
370
  return [];
351
- const width = Math.max(...exits.map(([code]) => String(code).length));
352
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
353
- }
354
- function replacesRows(replaces, colors = paint(process8.stdout)) {
355
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
371
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
356
372
  }
357
373
  function wantsHelpJson(env = process8.env) {
358
374
  return env.KIT_HELP === "json";
@@ -378,29 +394,41 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
378
394
  return [];
379
395
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
380
396
  }
397
+ var MAX_INLINE_CHOICES = 24;
381
398
  function optionRows(options, colors = paint(process8.stdout)) {
382
399
  const rows = Object.entries(options).map(([name, option]) => {
383
400
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
384
- 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>";
385
404
  const placeholder = option.optional === undefined ? named : `[${named}]`;
386
405
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
387
- 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 };
388
408
  });
389
409
  const width = Math.max(0, ...rows.map((row) => row.width));
390
410
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
391
411
  }
392
412
 
393
413
  // ../kit/src/text.ts
394
- 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;
395
415
  function distance(a, b) {
396
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
397
- 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()) {
398
421
  const current = [i + 1];
399
- for (const [j, right] of [...b].entries())
400
- 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;
401
429
  previous = current;
402
430
  }
403
- return previous[b.length] ?? 0;
431
+ return previous[right.length] ?? 0;
404
432
  }
405
433
  function closest(name, names) {
406
434
  const started = names.find((known) => known.startsWith(name));
@@ -455,7 +483,7 @@ class Completing {
455
483
  }
456
484
  var completion = { active: false };
457
485
  var OUTPUT_OPTIONS = {
458
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
486
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
459
487
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
460
488
  };
461
489
  function applyOutput(color, plain, env = process9.env) {
@@ -627,21 +655,123 @@ function nearestOption(message, options, allowNegative) {
627
655
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
628
656
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
629
657
  }
658
+ // ../kit/src/argv.ts
659
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
660
+ import { resolve as resolve3 } from "path";
661
+ import process10 from "process";
662
+ function commandLine() {
663
+ try {
664
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
665
+ } catch {
666
+ return;
667
+ }
668
+ }
669
+ function realPath(word) {
670
+ try {
671
+ return realpathSync(resolve3(word));
672
+ } catch {
673
+ return;
674
+ }
675
+ }
676
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
677
+ const target = script === undefined ? undefined : realPath(script) ?? script;
678
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
679
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
680
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
681
+ }
630
682
  // ../kit/src/progress.ts
631
683
  var ESC = String.fromCharCode(27);
632
684
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
633
685
  var RESET_STYLE = `${ESC}[0m`;
634
686
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
635
687
  // ../kit/src/cli.ts
636
- import { readFileSync as readFileSync2, realpathSync } from "fs";
688
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
637
689
  import { dirname as dirname3, join as join5 } from "path";
690
+ import process13 from "process";
691
+
692
+ // ../kit/src/completions.ts
693
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
694
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
695
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
696
+ set -l current (commandline -ct)
697
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
698
+ if test "$line" = __files__
699
+ __fish_complete_path $current
700
+ else
701
+ echo $line
702
+ end
703
+ end
704
+ end`;
705
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
706
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
707
+ local -a lines
708
+ COMPREPLY=()
709
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
710
+ for line in "\${lines[@]}"; do
711
+ if [[ $line == __files__ ]]; then
712
+ COMPREPLY+=($(compgen -f -- "$cur"))
713
+ else
714
+ words+="\${line%%$'\\t'*}"$'\\n'
715
+ fi
716
+ done
717
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
718
+ }`;
719
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
720
+ local line
721
+ local -a described plain
722
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
723
+ if [[ $line == __files__ ]]; then
724
+ _files
725
+ elif [[ $line == *$'\\t'* ]]; then
726
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
727
+ else
728
+ plain+=("$line")
729
+ fi
730
+ done
731
+ (( \${#described} )) && _describe -V value described
732
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
733
+ return 0
734
+ }`;
735
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
736
+ if (shell === "fish")
737
+ return `${header}
738
+ ${FISH_FUNCTION}
739
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
740
+ `).join("")}`;
741
+ if (shell === "bash")
742
+ return `${header}
743
+ ${BASH_FUNCTION}
744
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
745
+ `;
746
+ return `${header}
747
+ ${ZSH_FUNCTION}
748
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
749
+ `;
750
+ }
751
+
752
+ // ../kit/src/notify.ts
638
753
  import process11 from "process";
754
+ var NOTIFY_AFTER_MS = 1e4;
755
+ var CANCELLED = 130;
756
+ function base64(text) {
757
+ return Buffer.from(text).toString("base64");
758
+ }
759
+ function notification(title, body, env = process11.env) {
760
+ const id = `kit${process11.pid}`;
761
+ 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\\`];
762
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
763
+ }
764
+ function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
765
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
766
+ return;
767
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
768
+ }
639
769
 
640
770
  // ../kit/src/usage.ts
641
771
  import { appendFileSync, mkdirSync } from "fs";
642
772
  import { homedir as homedir3 } from "os";
643
773
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
644
- import process10 from "process";
774
+ import process12 from "process";
645
775
 
646
776
  // ../kit/src/logs.ts
647
777
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -655,14 +785,14 @@ var usageError;
655
785
  function noteUsageError(message) {
656
786
  usageError = message;
657
787
  }
658
- function stateHome(env = process10.env) {
788
+ function stateHome(env = process12.env) {
659
789
  const dir = env.XDG_STATE_HOME;
660
790
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
661
791
  }
662
- function usagePath(env = process10.env) {
792
+ function usagePath(env = process12.env) {
663
793
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
664
794
  }
665
- function usageRecorded(env = process10.env) {
795
+ function usageRecorded(env = process12.env) {
666
796
  const off = env.KAYNOOO_CLI_NO_USAGE;
667
797
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
668
798
  }
@@ -676,7 +806,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
676
806
  usageError = undefined;
677
807
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
678
808
  }
679
- function recordUsage(entry, env = process10.env) {
809
+ function recordUsage(entry, env = process12.env) {
680
810
  if (!usageRecorded(env))
681
811
  return;
682
812
  try {
@@ -692,10 +822,14 @@ var LEVEL_OPTIONS = {
692
822
  ...OUTPUT_OPTIONS,
693
823
  help: { type: "boolean", short: "h", description: "show this help" }
694
824
  };
695
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
825
+ var TOP_OPTIONS = {
826
+ ...LEVEL_OPTIONS,
827
+ version: { type: "boolean", short: "v", description: "print the version" },
828
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
829
+ };
696
830
  function printError(prefix, message, hint, cause) {
697
- const colors = paint(process11.stderr);
698
- const styled = takesControlCodes(process11.stderr);
831
+ const colors = paint(process13.stderr);
832
+ const styled = takesControlCodes(process13.stderr);
699
833
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
700
834
  const under = (label, text, tint) => text === undefined ? "" : `
701
835
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -739,24 +873,24 @@ function candidateLine(candidate) {
739
873
  }
740
874
  function positionalBeingTyped(before, { options, positionals }) {
741
875
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
742
- let index = 0;
876
+ const typed = [];
743
877
  let at = 0;
744
878
  while (at < before.length) {
745
879
  const word = before[at];
746
880
  if (word === "--") {
747
- index += before.length - at - 1;
881
+ typed.push(...before.slice(at + 1));
748
882
  break;
749
883
  }
750
884
  if (!word.startsWith("-"))
751
- index++;
885
+ typed.push(word);
752
886
  else if (takesValue(word))
753
887
  at++;
754
888
  at++;
755
889
  }
756
890
  const last = positionals.at(-1);
757
- if (index < positionals.length)
758
- return positionals[index];
759
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
891
+ if (typed.length < positionals.length)
892
+ return { name: positionals[typed.length], typed };
893
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
760
894
  }
761
895
  async function leafCandidates(run, words) {
762
896
  const completing = await completingOf(run);
@@ -764,23 +898,40 @@ async function leafCandidates(run, words) {
764
898
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
765
899
  const flag = words.at(-2);
766
900
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
901
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
767
902
  if (option?.type === "string") {
768
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
903
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
769
904
  return values === undefined ? [FILES] : values.map(candidateLine);
770
905
  }
771
- const name = positionalBeingTyped(words.slice(0, -1), completing);
772
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
906
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
773
907
  return values === undefined ? [FILES] : values.map(candidateLine);
774
908
  }
909
+ var COMPLETIONS = "--completions";
910
+ function flagValue([flag = "", ...rest]) {
911
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
912
+ }
913
+ function printCompletionScript(name, args) {
914
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
915
+ if (shell === undefined || args.length !== 1) {
916
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
917
+ return 2;
918
+ }
919
+ console.log(completionScript(shell, [name]).trimEnd());
920
+ return 0;
921
+ }
775
922
  async function printCandidates(found) {
776
923
  for (const line of await found)
777
924
  console.log(line);
778
925
  return 0;
779
926
  }
780
927
  function packageVersion(entry = Bun.main) {
781
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
928
+ let resolved = entry;
929
+ try {
930
+ resolved = realpathSync2(entry);
931
+ } catch {}
932
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
782
933
  try {
783
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
934
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
784
935
  if (typeof version === "string")
785
936
  return version;
786
937
  } catch {}
@@ -788,19 +939,23 @@ function packageVersion(entry = Bun.main) {
788
939
  return "0.0.0";
789
940
  }
790
941
  }
791
- async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
942
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
792
943
  if (argv[0] === COMPLETE)
793
944
  return printCandidates(leafCandidates(run, argv.slice(1)));
945
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
946
+ return printCompletionScript(name, flagValue(argv));
794
947
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
795
948
  console.log(version ?? packageVersion());
796
949
  return 0;
797
950
  }
798
951
  let code;
952
+ const started = performance.now();
799
953
  try {
800
954
  code = await run(argv);
801
955
  } catch (error) {
802
956
  code = reportThrown(name, error, redact, wantsJson(argv));
803
957
  }
958
+ notifyEnd(name, code, performance.now() - started);
804
959
  if (usage !== false) {
805
960
  try {
806
961
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -816,6 +971,119 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
816
971
  var {Glob } = globalThis.Bun;
817
972
  var SESSION_FILES = new Glob("*.json");
818
973
  var ACCOUNT_DIRS = new Glob("*/sessions");
974
+ // ../kit/src/picker/line.ts
975
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
976
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
977
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
978
+ function isEditKey(key) {
979
+ return EDIT_KEYS.has(key);
980
+ }
981
+ function endsKills(key) {
982
+ return typeof key !== "object" && !isEditKey(key);
983
+ }
984
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
985
+ var SPACE = /\s/;
986
+ function isWord(char) {
987
+ return char !== undefined && WORD_CHARACTER.test(char);
988
+ }
989
+ function wordStart(chars, from) {
990
+ let at = from;
991
+ while (at > 0 && !isWord(chars[at - 1]))
992
+ at--;
993
+ while (at > 0 && isWord(chars[at - 1]))
994
+ at--;
995
+ return at;
996
+ }
997
+ function wordEnd(chars, from) {
998
+ let at = from;
999
+ while (at < chars.length && !isWord(chars[at]))
1000
+ at++;
1001
+ while (at < chars.length && isWord(chars[at]))
1002
+ at++;
1003
+ return at;
1004
+ }
1005
+ function spacedStart(chars, from) {
1006
+ let at = from;
1007
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1008
+ at--;
1009
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1010
+ at--;
1011
+ return at;
1012
+ }
1013
+ function cut(chars, from, to) {
1014
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1015
+ }
1016
+ function insert(chars, at, text) {
1017
+ const typed = [...text];
1018
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1019
+ }
1020
+ function editLine(line, key) {
1021
+ const { killed = "", chained = false } = line;
1022
+ const chars = [...line.text];
1023
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
1024
+ const edited = edit(chars, at, key, killed);
1025
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1026
+ return line.killed === undefined ? edited : { ...edited, killed };
1027
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1028
+ if (taken === "")
1029
+ return { ...edited, killed, chained };
1030
+ if (!chained)
1031
+ return { ...edited, killed: taken, chained: true };
1032
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1033
+ }
1034
+ function edit(chars, at, key, killed) {
1035
+ const text = chars.join("");
1036
+ if (typeof key === "object")
1037
+ return insert(chars, at, key.text);
1038
+ switch (key) {
1039
+ case "left":
1040
+ return { text, caret: Math.max(at - 1, 0) };
1041
+ case "right":
1042
+ return { text, caret: Math.min(at + 1, chars.length) };
1043
+ case "wordleft":
1044
+ return { text, caret: wordStart(chars, at) };
1045
+ case "wordright":
1046
+ return { text, caret: wordEnd(chars, at) };
1047
+ case "linestart":
1048
+ return { text, caret: 0 };
1049
+ case "lineend":
1050
+ return { text, caret: chars.length };
1051
+ case "erase":
1052
+ return cut(chars, Math.max(at - 1, 0), at);
1053
+ case "delete":
1054
+ return cut(chars, at, Math.min(at + 1, chars.length));
1055
+ case "word":
1056
+ return cut(chars, spacedStart(chars, at), at);
1057
+ case "killword":
1058
+ return cut(chars, wordStart(chars, at), at);
1059
+ case "killnext":
1060
+ return cut(chars, at, wordEnd(chars, at));
1061
+ case "clear":
1062
+ return cut(chars, 0, at);
1063
+ case "killend":
1064
+ return cut(chars, at, chars.length);
1065
+ case "yank":
1066
+ return insert(chars, at, killed);
1067
+ }
1068
+ }
1069
+ function visible({ text, caret }, room) {
1070
+ const chars = [...text];
1071
+ const at = Math.min(Math.max(caret, 0), chars.length);
1072
+ const cells = at === chars.length ? [...chars, " "] : chars;
1073
+ const widths = cells.map((char) => Bun.stringWidth(char));
1074
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1075
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1076
+ let start = at;
1077
+ let end = at + 1;
1078
+ while (start > 0 && fits(start - 1, end))
1079
+ start--;
1080
+ while (end < cells.length && fits(start, end + 1))
1081
+ end++;
1082
+ const left = start > 0 ? "\u2026" : "";
1083
+ const right = end < cells.length ? "\u2026" : "";
1084
+ 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) };
1085
+ }
1086
+
819
1087
  // ../kit/src/picker/score.ts
820
1088
  var MATCH = 16;
821
1089
  var CONSECUTIVE = 12;
@@ -900,7 +1168,6 @@ function rank(query, lines) {
900
1168
  }
901
1169
 
902
1170
  // ../kit/src/picker/state.ts
903
- var ANSI2 = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
904
1171
  var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
905
1172
  var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
906
1173
  var SGR = /^\x1B\[[0-9;]*m$/;
@@ -908,7 +1175,6 @@ var RESET = /^\x1B\[0?m$/;
908
1175
  var COLUMN_GAP = 2;
909
1176
  var PASTE_START = "\x1B[200~";
910
1177
  var PASTE_END = "\x1B[201~";
911
- var LAST_WORD = /\S*\s*$/;
912
1178
  var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
913
1179
  var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
914
1180
  var WHEEL_LINES = 3;
@@ -931,10 +1197,29 @@ var KEYS = {
931
1197
  "\n": "enter",
932
1198
  "\x03": "cancel",
933
1199
  "\x1B": "cancel",
1200
+ "\x1B[D": "left",
1201
+ "\x1BOD": "left",
1202
+ "\x1B[C": "right",
1203
+ "\x1BOC": "right",
1204
+ "\x1B[1;5D": "wordleft",
1205
+ "\x1B[1;3D": "wordleft",
1206
+ "\x1Bb": "wordleft",
1207
+ "\x1B[1;5C": "wordright",
1208
+ "\x1B[1;3C": "wordright",
1209
+ "\x1Bf": "wordright",
1210
+ "\x01": "linestart",
1211
+ "\x05": "lineend",
934
1212
  "\x7F": "erase",
935
- "\b": "erase",
1213
+ "\x1B[3~": "delete",
1214
+ "\b": "killword",
1215
+ "\x1B\x7F": "killword",
1216
+ "\x1B[3;5~": "killnext",
1217
+ "\x1Bd": "killnext",
936
1218
  "\x15": "clear",
1219
+ "\v": "killend",
937
1220
  "\x17": "word",
1221
+ "\x19": "yank",
1222
+ "\x1A": "suspend",
938
1223
  "\t": "tab",
939
1224
  "\x1F": "help",
940
1225
  "\x1BOP": "help",
@@ -955,7 +1240,7 @@ function styled(line) {
955
1240
  colored ||= active !== "" && flat !== "";
956
1241
  styles.push(...repeat(active, flat.length));
957
1242
  }
958
- for (const found of line.matchAll(ANSI2)) {
1243
+ for (const found of line.matchAll(ANSI)) {
959
1244
  add(line.slice(last, found.index));
960
1245
  last = found.index + found[0].length;
961
1246
  if (SGR.test(found[0]))
@@ -967,7 +1252,7 @@ function styled(line) {
967
1252
  function lay(rows, searched) {
968
1253
  const parsed = rows.map((row) => row.cells.map(styled));
969
1254
  const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
970
- return parsed.map((cells) => {
1255
+ return parsed.map((cells, at) => {
971
1256
  let text = "";
972
1257
  const styles = [];
973
1258
  let colored = false;
@@ -986,7 +1271,7 @@ function lay(rows, searched) {
986
1271
  styles.push(...repeat("", pad));
987
1272
  }
988
1273
  }
989
- return { text, styles: colored ? styles : undefined, searchable: text.slice(0, searchEnd) };
1274
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
990
1275
  });
991
1276
  }
992
1277
  function parseKeys(input, paste = { active: false }, ctrls = []) {
@@ -1010,7 +1295,7 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1010
1295
  });
1011
1296
  }
1012
1297
  function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1013
- 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 };
1298
+ 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 };
1014
1299
  return withRows(state, rows);
1015
1300
  }
1016
1301
  function withRows(state, rows, header = state.header) {
@@ -1020,8 +1305,9 @@ function withRows(state, rows, header = state.header) {
1020
1305
  const matches = rank(state.query, searchable);
1021
1306
  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 };
1022
1307
  }
1023
- function withQuery(state, query) {
1024
- return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
1308
+ function withQuery(state, key) {
1309
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1310
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1025
1311
  }
1026
1312
  function move(state, by) {
1027
1313
  return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
@@ -1032,13 +1318,17 @@ function highlighted(state) {
1032
1318
  function press(state, key) {
1033
1319
  if (state.done !== undefined)
1034
1320
  return state;
1321
+ if (state.chained && endsKills(key))
1322
+ state = { ...state, chained: false };
1035
1323
  if (state.help)
1036
1324
  return { ...state, help: false };
1037
1325
  if (typeof key === "object") {
1038
1326
  if ("text" in key)
1039
- return withQuery(state, state.query + key.text);
1327
+ return withQuery(state, key);
1040
1328
  return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1041
1329
  }
1330
+ if (isEditKey(key))
1331
+ return withQuery(state, key);
1042
1332
  switch (key) {
1043
1333
  case "up":
1044
1334
  return move(state, -1);
@@ -1056,12 +1346,8 @@ function press(state, key) {
1056
1346
  return { ...state, done: "cancel" };
1057
1347
  case "help":
1058
1348
  return { ...state, help: true };
1059
- case "erase":
1060
- return withQuery(state, [...state.query].slice(0, -1).join(""));
1061
- case "clear":
1062
- return withQuery(state, "");
1063
- case "word":
1064
- return withQuery(state, state.query.replace(LAST_WORD, ""));
1349
+ case "suspend":
1350
+ return state;
1065
1351
  case "enter":
1066
1352
  return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1067
1353
  case "tab": {
@@ -1084,11 +1370,25 @@ function chosen(state) {
1084
1370
 
1085
1371
  // ../kit/src/picker/terminal.ts
1086
1372
  import { openSync } from "fs";
1087
- import process14 from "process";
1373
+ import process17 from "process";
1088
1374
  import tty from "tty";
1089
1375
 
1376
+ // ../kit/src/job.ts
1377
+ import process15 from "process";
1378
+ function stopJob() {
1379
+ process15.kill(0, "SIGTSTP");
1380
+ }
1381
+
1382
+ // ../kit/src/redraw.ts
1383
+ var SYNC_START = "\x1B[?2026h";
1384
+ var SYNC_END = "\x1B[?2026l";
1385
+ function overwrite(lines, columns) {
1386
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1387
+ `);
1388
+ }
1389
+
1090
1390
  // ../kit/src/picker/preview.ts
1091
- import process13 from "process";
1391
+ import process16 from "process";
1092
1392
 
1093
1393
  // ../kit/src/shell.ts
1094
1394
  var SEPARATORS = new Set([`
@@ -1157,7 +1457,7 @@ async function runPreview(template, line, signal, hidden = []) {
1157
1457
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1158
1458
  const stop = () => {
1159
1459
  try {
1160
- process13.kill(-proc.pid, "SIGKILL");
1460
+ process16.kill(-proc.pid, "SIGKILL");
1161
1461
  } catch {
1162
1462
  proc.kill();
1163
1463
  }
@@ -1233,13 +1533,20 @@ function fitStyled(line, width, plain = identity) {
1233
1533
  const { text, styles } = styled(line);
1234
1534
  return fit(text, width, plain, plain, new Set, styles);
1235
1535
  }
1236
- function caretColumn(state, layout) {
1237
- return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
1536
+ function queryShown(state, layout) {
1537
+ return visible({ text: state.query, caret: state.caret }, Math.max(1, layout.listWidth - Bun.stringWidth(state.prompt)));
1538
+ }
1539
+ function caretCell(state, layout) {
1540
+ const shown = queryShown(state, layout);
1541
+ return { column: Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + shown.column + 1), char: shown.at ?? " " };
1238
1542
  }
1239
1543
  function helpLines(state, layout, theme) {
1240
1544
  const lines = [
1241
1545
  "type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move",
1242
- `enter picks${state.multi ? ", tab marks" : ""}, ctrl-u clears the query, ctrl-w a word, esc or ctrl-c cancels`,
1546
+ "left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word",
1547
+ "ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead",
1548
+ "ctrl-y puts back what they erased, ctrl-z suspends to the shell",
1549
+ `enter picks${state.multi ? ", tab marks" : ""}, esc or ctrl-c cancels`,
1243
1550
  ...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
1244
1551
  ];
1245
1552
  const title = "keys, any key closes this help";
@@ -1255,7 +1562,9 @@ function listLines(state, layout, theme) {
1255
1562
  const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
1256
1563
  const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
1257
1564
  const promptWidth = Bun.stringWidth(state.prompt);
1258
- const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
1565
+ const shown = queryShown(state, layout);
1566
+ const text = `${shown.before}${shown.at ?? ""}${shown.after}`;
1567
+ const query = { text, width: Bun.stringWidth(text) };
1259
1568
  const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
1260
1569
  const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
1261
1570
  const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
@@ -1288,7 +1597,8 @@ var ESCAPE_WAIT_MS = 30;
1288
1597
  var OPEN = { ctrl: "open" };
1289
1598
  var HIDE_CURSOR = "\x1B[?25l";
1290
1599
  var SHOW_CURSOR = "\x1B[?25h";
1291
- var CARET = "\x1B[7m \x1B[27m";
1600
+ var REVERSE = "\x1B[7m";
1601
+ var REVERSE_END = "\x1B[27m";
1292
1602
  var PASTE_ON = "\x1B[?2004h";
1293
1603
  var PASTE_OFF = "\x1B[?2004l";
1294
1604
  var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
@@ -1306,7 +1616,7 @@ function openTerminal() {
1306
1616
  return fail("no terminal to read keys from (/dev/tty)");
1307
1617
  }
1308
1618
  const keys = Bun.file("/dev/tty").stream().getReader();
1309
- const out = process14.stderr;
1619
+ const out = process17.stderr;
1310
1620
  let resize;
1311
1621
  async function read(onChunk) {
1312
1622
  const decoder = new TextDecoder;
@@ -1332,6 +1642,11 @@ function openTerminal() {
1332
1642
  out.on("resize", onResize);
1333
1643
  read(onChunk);
1334
1644
  },
1645
+ suspend() {
1646
+ mode.setRawMode(false);
1647
+ stopJob();
1648
+ mode.setRawMode(true);
1649
+ },
1335
1650
  close() {
1336
1651
  if (resize !== undefined)
1337
1652
  out.off("resize", resize);
@@ -1359,14 +1674,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1359
1674
  if (restored)
1360
1675
  return;
1361
1676
  const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1362
- let frame = HIDE_CURSOR;
1677
+ let frame = SYNC_START + HIDE_CURSOR;
1363
1678
  if (reserved !== layout.height || clear) {
1364
1679
  frame += CLEAR_BELOW + `
1365
1680
  `.repeat(layout.height - 1) + up(layout.height - 1);
1366
1681
  reserved = layout.height;
1367
1682
  }
1368
- frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
1369
- `)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${CARET}\r`;
1683
+ const caret = caretCell(state, layout);
1684
+ 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}`;
1370
1685
  terminal.write(frame);
1371
1686
  }
1372
1687
  function pageSize() {
@@ -1408,6 +1723,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1408
1723
  terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1409
1724
  terminal.close();
1410
1725
  }
1726
+ function suspend() {
1727
+ if (terminal.suspend === undefined)
1728
+ return;
1729
+ terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1730
+ terminal.suspend();
1731
+ terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1732
+ draw(true);
1733
+ }
1411
1734
  const stop = () => {
1412
1735
  state = { ...state, done: "cancel" };
1413
1736
  finish?.();
@@ -1441,6 +1764,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1441
1764
  for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
1442
1765
  if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
1443
1766
  await reloadRows();
1767
+ else if (key === "suspend")
1768
+ suspend();
1444
1769
  else
1445
1770
  state = press({ ...state, page: pageSize() }, key);
1446
1771
  }
@@ -1480,9 +1805,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1480
1805
  const ended = new Promise((resolve) => {
1481
1806
  finish = resolve;
1482
1807
  });
1483
- process14.once("exit", restore);
1808
+ process17.once("exit", restore);
1484
1809
  for (const signal of SIGNALS)
1485
- process14.once(signal, stop);
1810
+ process17.once(signal, stop);
1486
1811
  try {
1487
1812
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1488
1813
  terminal.listen(onChunk, () => draw(true));
@@ -1495,8 +1820,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1495
1820
  await ended;
1496
1821
  } finally {
1497
1822
  for (const signal of SIGNALS)
1498
- process14.off(signal, stop);
1499
- process14.off("exit", restore);
1823
+ process17.off(signal, stop);
1824
+ process17.off("exit", restore);
1500
1825
  restore();
1501
1826
  }
1502
1827
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1508,61 +1833,127 @@ async function previewOf(preview, hidden, signal) {
1508
1833
  return [error instanceof Error ? error.message : String(error)];
1509
1834
  }
1510
1835
  }
1511
- async function choose(lines, settings) {
1512
- const picked = await select(lines.map((line) => ({ hidden: [], cells: [line] })), settings);
1513
- return picked?.rows.map((row) => row.cells[0]);
1836
+ // src/fields.ts
1837
+ var INDEX = /^-?\d+$/;
1838
+ function splitFields(line, delimiter) {
1839
+ if (delimiter === undefined)
1840
+ return line.match(/\s*\S+\s*/g) ?? [];
1841
+ const fields = [];
1842
+ let from = 0;
1843
+ for (const match of line.matchAll(new RegExp(delimiter, `${delimiter.flags}g`))) {
1844
+ if (match[0] === "")
1845
+ continue;
1846
+ fields.push(line.slice(from, match.index + match[0].length));
1847
+ from = match.index + match[0].length;
1848
+ }
1849
+ fields.push(line.slice(from));
1850
+ return fields;
1851
+ }
1852
+ function parseFields(expression) {
1853
+ const spans = [];
1854
+ for (const part of expression.split(",")) {
1855
+ const dots = part.indexOf("..");
1856
+ const from = dots === -1 ? part : part.slice(0, dots);
1857
+ const to = dots === -1 ? from : part.slice(dots + 2);
1858
+ if (part === "0" || part === "" || from !== "" && !INDEX.test(from) || to !== "" && !INDEX.test(to))
1859
+ return;
1860
+ const resolve = (n, count) => n < 0 ? count + n : n - 1;
1861
+ spans.push((count) => {
1862
+ const first = from === "" ? 0 : resolve(Number(from), count);
1863
+ const last = to === "" ? count - 1 : resolve(Number(to), count);
1864
+ return Array.from({ length: Math.max(0, last - first + 1) }, (_, i) => first + i).filter((i) => i >= 0 && i < count);
1865
+ });
1866
+ }
1867
+ return (count) => spans.flatMap((span) => span(count));
1868
+ }
1869
+ function pickFields(line, select, delimiter) {
1870
+ const fields = splitFields(line, delimiter);
1871
+ return select(fields.length).map((i) => fields[i]).join("");
1514
1872
  }
1873
+
1515
1874
  // src/pick.ts
1516
1875
  var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
1517
1876
 
1518
- 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.
1877
+ 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.
1519
1878
  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).
1520
1879
  --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.
1521
1880
 
1522
- Without a terminal on stderr there is nobody to choose: it prints the first line containing the query (case-insensitive), every one with --multi.
1881
+ --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.
1882
+ --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.
1523
1883
 
1524
- Exits 0 when it printed a choice, 1 when cancelled, nothing matches or there are no lines, 2 on a usage error.`;
1884
+ 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.`;
1885
+ var EXITS = [[0, "it printed a choice"], [1, "nothing matches or there are no lines"], [2, "a usage error"], [130, "cancelled"]];
1525
1886
  var OPTIONS = {
1526
1887
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
1527
1888
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
1528
1889
  query: { type: "string", short: "q", description: "the query to start with" },
1529
1890
  preview: { type: "string", description: "a command shown for the highlighted line, {} standing for it" },
1891
+ header: { type: "string", description: "a line of text shown above the list" },
1892
+ filter: { type: "string", short: "f", description: "print every line the query matches, best first, with no terminal" },
1893
+ "select-1": { type: "boolean", short: "1", description: "print the only match without opening the selector" },
1894
+ "exit-0": { type: "boolean", short: "0", description: "exit 1 at once when nothing matches" },
1895
+ delimiter: { type: "string", short: "d", description: "a regex splitting a line into fields (whitespace)" },
1896
+ nth: { type: "string", description: "the fields the query is matched against, 2, -1, 2.., 1..3, 1,3" },
1897
+ "with-nth": { type: "string", description: "the fields shown, the printed line stays whole" },
1898
+ read0: { type: "boolean", description: "lines on stdin end with NUL" },
1899
+ print0: { type: "boolean", description: "end each printed line with NUL" },
1530
1900
  height: { type: "string", description: "lines or a percentage of the terminal to draw in (100%)" },
1531
1901
  json: jsonOption("{picked: [lines]}, the choice or the marked lines in input order")
1532
1902
  };
1533
- function print(chosen, json) {
1903
+ function print(chosen, json, end) {
1534
1904
  if (json)
1535
1905
  printJson({ picked: chosen });
1536
1906
  else
1537
- process15.stdout.write(`${chosen.join(`
1538
- `)}
1539
- `);
1907
+ process18.stdout.write(chosen.map((line) => line + end).join(""));
1540
1908
  }
1541
1909
  async function main(args) {
1542
- const { values, positionals } = parse(args, USAGE, OPTIONS, { 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 {}'"] });
1910
+ 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"] });
1543
1911
  if (positionals.length > 0)
1544
1912
  badUsage("pick takes its lines on stdin, not as arguments");
1545
1913
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1546
1914
  if (height === undefined)
1547
1915
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1548
- if (process15.stdin.isTTY)
1916
+ if (process18.stdin.isTTY)
1549
1917
  badUsage("pipe the lines to pick on stdin");
1550
- const lines = (await Bun.stdin.text()).split(`
1918
+ const fieldsOf = (name) => {
1919
+ const text = values[name];
1920
+ if (text === undefined)
1921
+ return;
1922
+ return parseFields(text) ?? badUsage(`--${name} takes fields such as 2, -1, 2.., 1..3 or 1,3, not ${text}`);
1923
+ };
1924
+ const nth = fieldsOf("nth");
1925
+ const withNth = fieldsOf("with-nth");
1926
+ let delimiter;
1927
+ try {
1928
+ delimiter = values.delimiter === undefined ? undefined : new RegExp(values.delimiter);
1929
+ } catch {
1930
+ badUsage(`--delimiter is a regex, not ${values.delimiter}`);
1931
+ }
1932
+ const lines = (await Bun.stdin.text()).split(values.read0 === true ? "\x00" : `
1551
1933
  `).filter((line) => line !== "");
1552
1934
  if (lines.length === 0)
1553
1935
  fail("nothing to pick from", 1);
1554
- if (!process15.stderr.isTTY) {
1555
- const query = (values.query ?? "").toLowerCase();
1556
- const matching = lines.filter((line) => line.toLowerCase().includes(query));
1557
- if (matching.length === 0)
1558
- return 1;
1559
- print(values.multi === true ? matching : matching.slice(0, 1), values.json === true);
1936
+ const query = values.filter ?? values.query ?? "";
1937
+ const end = values.print0 === true ? "\x00" : `
1938
+ `;
1939
+ const json = values.json === true;
1940
+ const searched = lines.map((line) => nth === undefined ? line : pickFields(line, nth, delimiter));
1941
+ const matching = rank(query, searched).map(({ index }) => lines[index]);
1942
+ if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process18.stderr.isTTY))
1943
+ return 1;
1944
+ if (values.filter !== undefined || !process18.stderr.isTTY) {
1945
+ print(values.multi === true || values.filter !== undefined ? matching : matching.slice(0, 1), json, end);
1560
1946
  return 0;
1561
1947
  }
1562
- const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
1948
+ if (values["select-1"] === true && matching.length === 1) {
1949
+ print(matching, json, end);
1950
+ return 0;
1951
+ }
1952
+ const rows = lines.map((line, index) => ({ hidden: [line], cells: [withNth === undefined ? line : pickFields(line, withNth, delimiter).trimEnd()], ...nth === undefined ? {} : { search: searched[index] } }));
1953
+ const picked = await select(rows, { multi: values.multi === true, prompt: values.prompt ?? "> ", query, height, preview: values.preview, header: values.header });
1563
1954
  if (picked === undefined)
1564
- return 1;
1565
- print(picked, values.json === true);
1955
+ return 130;
1956
+ print(picked.rows.map((row) => row.hidden[0]), json, end);
1566
1957
  return 0;
1567
1958
  }
1568
- process15.exitCode = await runMain({ name: "pick", run: main });
1959
+ 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.1",
4
+ "version": "0.11.1",
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.37.0"
38
+ "@kaynooo/cli-kit": "0.41.0"
39
39
  }
40
40
  }