@kaynooo/cli-pick 0.9.2 → 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 +443 -75
  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));
@@ -451,7 +483,7 @@ class Completing {
451
483
  }
452
484
  var completion = { active: false };
453
485
  var OUTPUT_OPTIONS = {
454
- 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" },
455
487
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
456
488
  };
457
489
  function applyOutput(color, plain, env = process9.env) {
@@ -655,13 +687,91 @@ 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/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
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
+ }
659
769
 
660
770
  // ../kit/src/usage.ts
661
771
  import { appendFileSync, mkdirSync } from "fs";
662
772
  import { homedir as homedir3 } from "os";
663
773
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
664
- import process11 from "process";
774
+ import process12 from "process";
665
775
 
666
776
  // ../kit/src/logs.ts
667
777
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -675,14 +785,14 @@ var usageError;
675
785
  function noteUsageError(message) {
676
786
  usageError = message;
677
787
  }
678
- function stateHome(env = process11.env) {
788
+ function stateHome(env = process12.env) {
679
789
  const dir = env.XDG_STATE_HOME;
680
790
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
681
791
  }
682
- function usagePath(env = process11.env) {
792
+ function usagePath(env = process12.env) {
683
793
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
684
794
  }
685
- function usageRecorded(env = process11.env) {
795
+ function usageRecorded(env = process12.env) {
686
796
  const off = env.KAYNOOO_CLI_NO_USAGE;
687
797
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
688
798
  }
@@ -696,7 +806,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
696
806
  usageError = undefined;
697
807
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
698
808
  }
699
- function recordUsage(entry, env = process11.env) {
809
+ function recordUsage(entry, env = process12.env) {
700
810
  if (!usageRecorded(env))
701
811
  return;
702
812
  try {
@@ -712,10 +822,14 @@ var LEVEL_OPTIONS = {
712
822
  ...OUTPUT_OPTIONS,
713
823
  help: { type: "boolean", short: "h", description: "show this help" }
714
824
  };
715
- 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
+ };
716
830
  function printError(prefix, message, hint, cause) {
717
- const colors = paint(process12.stderr);
718
- const styled = takesControlCodes(process12.stderr);
831
+ const colors = paint(process13.stderr);
832
+ const styled = takesControlCodes(process13.stderr);
719
833
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
720
834
  const under = (label, text, tint) => text === undefined ? "" : `
721
835
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -792,6 +906,19 @@ async function leafCandidates(run, words) {
792
906
  const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
793
907
  return values === undefined ? [FILES] : values.map(candidateLine);
794
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
+ }
795
922
  async function printCandidates(found) {
796
923
  for (const line of await found)
797
924
  console.log(line);
@@ -815,16 +942,20 @@ function packageVersion(entry = Bun.main) {
815
942
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
816
943
  if (argv[0] === COMPLETE)
817
944
  return printCandidates(leafCandidates(run, argv.slice(1)));
945
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
946
+ return printCompletionScript(name, flagValue(argv));
818
947
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
819
948
  console.log(version ?? packageVersion());
820
949
  return 0;
821
950
  }
822
951
  let code;
952
+ const started = performance.now();
823
953
  try {
824
954
  code = await run(argv);
825
955
  } catch (error) {
826
956
  code = reportThrown(name, error, redact, wantsJson(argv));
827
957
  }
958
+ notifyEnd(name, code, performance.now() - started);
828
959
  if (usage !== false) {
829
960
  try {
830
961
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -840,6 +971,119 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
840
971
  var {Glob } = globalThis.Bun;
841
972
  var SESSION_FILES = new Glob("*.json");
842
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
+
843
1087
  // ../kit/src/picker/score.ts
844
1088
  var MATCH = 16;
845
1089
  var CONSECUTIVE = 12;
@@ -924,7 +1168,6 @@ function rank(query, lines) {
924
1168
  }
925
1169
 
926
1170
  // ../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
1171
  var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
929
1172
  var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
930
1173
  var SGR = /^\x1B\[[0-9;]*m$/;
@@ -932,7 +1175,6 @@ var RESET = /^\x1B\[0?m$/;
932
1175
  var COLUMN_GAP = 2;
933
1176
  var PASTE_START = "\x1B[200~";
934
1177
  var PASTE_END = "\x1B[201~";
935
- var LAST_WORD = /\S*\s*$/;
936
1178
  var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
937
1179
  var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
938
1180
  var WHEEL_LINES = 3;
@@ -955,10 +1197,29 @@ var KEYS = {
955
1197
  "\n": "enter",
956
1198
  "\x03": "cancel",
957
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",
958
1212
  "\x7F": "erase",
959
- "\b": "erase",
1213
+ "\x1B[3~": "delete",
1214
+ "\b": "killword",
1215
+ "\x1B\x7F": "killword",
1216
+ "\x1B[3;5~": "killnext",
1217
+ "\x1Bd": "killnext",
960
1218
  "\x15": "clear",
1219
+ "\v": "killend",
961
1220
  "\x17": "word",
1221
+ "\x19": "yank",
1222
+ "\x1A": "suspend",
962
1223
  "\t": "tab",
963
1224
  "\x1F": "help",
964
1225
  "\x1BOP": "help",
@@ -979,7 +1240,7 @@ function styled(line) {
979
1240
  colored ||= active !== "" && flat !== "";
980
1241
  styles.push(...repeat(active, flat.length));
981
1242
  }
982
- for (const found of line.matchAll(ANSI2)) {
1243
+ for (const found of line.matchAll(ANSI)) {
983
1244
  add(line.slice(last, found.index));
984
1245
  last = found.index + found[0].length;
985
1246
  if (SGR.test(found[0]))
@@ -991,7 +1252,7 @@ function styled(line) {
991
1252
  function lay(rows, searched) {
992
1253
  const parsed = rows.map((row) => row.cells.map(styled));
993
1254
  const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
994
- return parsed.map((cells) => {
1255
+ return parsed.map((cells, at) => {
995
1256
  let text = "";
996
1257
  const styles = [];
997
1258
  let colored = false;
@@ -1010,7 +1271,7 @@ function lay(rows, searched) {
1010
1271
  styles.push(...repeat("", pad));
1011
1272
  }
1012
1273
  }
1013
- 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) };
1014
1275
  });
1015
1276
  }
1016
1277
  function parseKeys(input, paste = { active: false }, ctrls = []) {
@@ -1034,7 +1295,7 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1034
1295
  });
1035
1296
  }
1036
1297
  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 };
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 };
1038
1299
  return withRows(state, rows);
1039
1300
  }
1040
1301
  function withRows(state, rows, header = state.header) {
@@ -1044,8 +1305,9 @@ function withRows(state, rows, header = state.header) {
1044
1305
  const matches = rank(state.query, searchable);
1045
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 };
1046
1307
  }
1047
- function withQuery(state, query) {
1048
- 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 };
1049
1311
  }
1050
1312
  function move(state, by) {
1051
1313
  return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
@@ -1056,13 +1318,17 @@ function highlighted(state) {
1056
1318
  function press(state, key) {
1057
1319
  if (state.done !== undefined)
1058
1320
  return state;
1321
+ if (state.chained && endsKills(key))
1322
+ state = { ...state, chained: false };
1059
1323
  if (state.help)
1060
1324
  return { ...state, help: false };
1061
1325
  if (typeof key === "object") {
1062
1326
  if ("text" in key)
1063
- return withQuery(state, state.query + key.text);
1327
+ return withQuery(state, key);
1064
1328
  return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1065
1329
  }
1330
+ if (isEditKey(key))
1331
+ return withQuery(state, key);
1066
1332
  switch (key) {
1067
1333
  case "up":
1068
1334
  return move(state, -1);
@@ -1080,12 +1346,8 @@ function press(state, key) {
1080
1346
  return { ...state, done: "cancel" };
1081
1347
  case "help":
1082
1348
  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, ""));
1349
+ case "suspend":
1350
+ return state;
1089
1351
  case "enter":
1090
1352
  return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1091
1353
  case "tab": {
@@ -1108,11 +1370,25 @@ function chosen(state) {
1108
1370
 
1109
1371
  // ../kit/src/picker/terminal.ts
1110
1372
  import { openSync } from "fs";
1111
- import process15 from "process";
1373
+ import process17 from "process";
1112
1374
  import tty from "tty";
1113
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
+
1114
1390
  // ../kit/src/picker/preview.ts
1115
- import process14 from "process";
1391
+ import process16 from "process";
1116
1392
 
1117
1393
  // ../kit/src/shell.ts
1118
1394
  var SEPARATORS = new Set([`
@@ -1181,7 +1457,7 @@ async function runPreview(template, line, signal, hidden = []) {
1181
1457
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1182
1458
  const stop = () => {
1183
1459
  try {
1184
- process14.kill(-proc.pid, "SIGKILL");
1460
+ process16.kill(-proc.pid, "SIGKILL");
1185
1461
  } catch {
1186
1462
  proc.kill();
1187
1463
  }
@@ -1257,13 +1533,20 @@ function fitStyled(line, width, plain = identity) {
1257
1533
  const { text, styles } = styled(line);
1258
1534
  return fit(text, width, plain, plain, new Set, styles);
1259
1535
  }
1260
- function caretColumn(state, layout) {
1261
- 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 ?? " " };
1262
1542
  }
1263
1543
  function helpLines(state, layout, theme) {
1264
1544
  const lines = [
1265
1545
  "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`,
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`,
1267
1550
  ...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
1268
1551
  ];
1269
1552
  const title = "keys, any key closes this help";
@@ -1279,7 +1562,9 @@ function listLines(state, layout, theme) {
1279
1562
  const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
1280
1563
  const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
1281
1564
  const promptWidth = Bun.stringWidth(state.prompt);
1282
- 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) };
1283
1568
  const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
1284
1569
  const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
1285
1570
  const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
@@ -1312,7 +1597,8 @@ var ESCAPE_WAIT_MS = 30;
1312
1597
  var OPEN = { ctrl: "open" };
1313
1598
  var HIDE_CURSOR = "\x1B[?25l";
1314
1599
  var SHOW_CURSOR = "\x1B[?25h";
1315
- var CARET = "\x1B[7m \x1B[27m";
1600
+ var REVERSE = "\x1B[7m";
1601
+ var REVERSE_END = "\x1B[27m";
1316
1602
  var PASTE_ON = "\x1B[?2004h";
1317
1603
  var PASTE_OFF = "\x1B[?2004l";
1318
1604
  var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
@@ -1330,7 +1616,7 @@ function openTerminal() {
1330
1616
  return fail("no terminal to read keys from (/dev/tty)");
1331
1617
  }
1332
1618
  const keys = Bun.file("/dev/tty").stream().getReader();
1333
- const out = process15.stderr;
1619
+ const out = process17.stderr;
1334
1620
  let resize;
1335
1621
  async function read(onChunk) {
1336
1622
  const decoder = new TextDecoder;
@@ -1356,6 +1642,11 @@ function openTerminal() {
1356
1642
  out.on("resize", onResize);
1357
1643
  read(onChunk);
1358
1644
  },
1645
+ suspend() {
1646
+ mode.setRawMode(false);
1647
+ stopJob();
1648
+ mode.setRawMode(true);
1649
+ },
1359
1650
  close() {
1360
1651
  if (resize !== undefined)
1361
1652
  out.off("resize", resize);
@@ -1383,14 +1674,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1383
1674
  if (restored)
1384
1675
  return;
1385
1676
  const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1386
- let frame = HIDE_CURSOR;
1677
+ let frame = SYNC_START + HIDE_CURSOR;
1387
1678
  if (reserved !== layout.height || clear) {
1388
1679
  frame += CLEAR_BELOW + `
1389
1680
  `.repeat(layout.height - 1) + up(layout.height - 1);
1390
1681
  reserved = layout.height;
1391
1682
  }
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`;
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}`;
1394
1685
  terminal.write(frame);
1395
1686
  }
1396
1687
  function pageSize() {
@@ -1432,6 +1723,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1432
1723
  terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1433
1724
  terminal.close();
1434
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
+ }
1435
1734
  const stop = () => {
1436
1735
  state = { ...state, done: "cancel" };
1437
1736
  finish?.();
@@ -1465,6 +1764,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1465
1764
  for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
1466
1765
  if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
1467
1766
  await reloadRows();
1767
+ else if (key === "suspend")
1768
+ suspend();
1468
1769
  else
1469
1770
  state = press({ ...state, page: pageSize() }, key);
1470
1771
  }
@@ -1504,9 +1805,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1504
1805
  const ended = new Promise((resolve) => {
1505
1806
  finish = resolve;
1506
1807
  });
1507
- process15.once("exit", restore);
1808
+ process17.once("exit", restore);
1508
1809
  for (const signal of SIGNALS)
1509
- process15.once(signal, stop);
1810
+ process17.once(signal, stop);
1510
1811
  try {
1511
1812
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1512
1813
  terminal.listen(onChunk, () => draw(true));
@@ -1519,8 +1820,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1519
1820
  await ended;
1520
1821
  } finally {
1521
1822
  for (const signal of SIGNALS)
1522
- process15.off(signal, stop);
1523
- process15.off("exit", restore);
1823
+ process17.off(signal, stop);
1824
+ process17.off("exit", restore);
1524
1825
  restore();
1525
1826
  }
1526
1827
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1532,60 +1833,127 @@ async function previewOf(preview, hidden, signal) {
1532
1833
  return [error instanceof Error ? error.message : String(error)];
1533
1834
  }
1534
1835
  }
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]);
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("");
1538
1872
  }
1873
+
1539
1874
  // src/pick.ts
1540
1875
  var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
1541
1876
 
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.
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.
1543
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).
1544
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.
1545
1880
 
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"]];
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.
1883
+
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"]];
1548
1886
  var OPTIONS = {
1549
1887
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
1550
1888
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
1551
1889
  query: { type: "string", short: "q", description: "the query to start with" },
1552
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" },
1553
1900
  height: { type: "string", description: "lines or a percentage of the terminal to draw in (100%)" },
1554
1901
  json: jsonOption("{picked: [lines]}, the choice or the marked lines in input order")
1555
1902
  };
1556
- function print(chosen, json) {
1903
+ function print(chosen, json, end) {
1557
1904
  if (json)
1558
1905
  printJson({ picked: chosen });
1559
1906
  else
1560
- process16.stdout.write(`${chosen.join(`
1561
- `)}
1562
- `);
1907
+ process18.stdout.write(chosen.map((line) => line + end).join(""));
1563
1908
  }
1564
1909
  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 {}'"] });
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"] });
1566
1911
  if (positionals.length > 0)
1567
1912
  badUsage("pick takes its lines on stdin, not as arguments");
1568
1913
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1569
1914
  if (height === undefined)
1570
1915
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1571
- if (process16.stdin.isTTY)
1916
+ if (process18.stdin.isTTY)
1572
1917
  badUsage("pipe the lines to pick on stdin");
1573
- 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" : `
1574
1933
  `).filter((line) => line !== "");
1575
1934
  if (lines.length === 0)
1576
1935
  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);
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);
1946
+ return 0;
1947
+ }
1948
+ if (values["select-1"] === true && matching.length === 1) {
1949
+ print(matching, json, end);
1583
1950
  return 0;
1584
1951
  }
1585
- const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
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 });
1586
1954
  if (picked === undefined)
1587
- return 1;
1588
- print(picked, values.json === true);
1955
+ return 130;
1956
+ print(picked.rows.map((row) => row.hidden[0]), json, end);
1589
1957
  return 0;
1590
1958
  }
1591
- process16.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.2",
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.38.3"
38
+ "@kaynooo/cli-kit": "0.41.0"
39
39
  }
40
40
  }