@kaynooo/cli-pick 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/pick.js +404 -92
  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));
@@ -627,21 +655,63 @@ 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/notify.ts
638
693
  import process11 from "process";
694
+ var NOTIFY_AFTER_MS = 1e4;
695
+ var CANCELLED = 130;
696
+ function base64(text) {
697
+ return Buffer.from(text).toString("base64");
698
+ }
699
+ function notification(title, body, env = process11.env) {
700
+ const id = `kit${process11.pid}`;
701
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
702
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
703
+ }
704
+ function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
705
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
706
+ return;
707
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
708
+ }
639
709
 
640
710
  // ../kit/src/usage.ts
641
711
  import { appendFileSync, mkdirSync } from "fs";
642
712
  import { homedir as homedir3 } from "os";
643
713
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
644
- import process10 from "process";
714
+ import process12 from "process";
645
715
 
646
716
  // ../kit/src/logs.ts
647
717
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -655,14 +725,14 @@ var usageError;
655
725
  function noteUsageError(message) {
656
726
  usageError = message;
657
727
  }
658
- function stateHome(env = process10.env) {
728
+ function stateHome(env = process12.env) {
659
729
  const dir = env.XDG_STATE_HOME;
660
730
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
661
731
  }
662
- function usagePath(env = process10.env) {
732
+ function usagePath(env = process12.env) {
663
733
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
664
734
  }
665
- function usageRecorded(env = process10.env) {
735
+ function usageRecorded(env = process12.env) {
666
736
  const off = env.KAYNOOO_CLI_NO_USAGE;
667
737
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
668
738
  }
@@ -676,7 +746,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
676
746
  usageError = undefined;
677
747
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
678
748
  }
679
- function recordUsage(entry, env = process10.env) {
749
+ function recordUsage(entry, env = process12.env) {
680
750
  if (!usageRecorded(env))
681
751
  return;
682
752
  try {
@@ -694,8 +764,8 @@ var LEVEL_OPTIONS = {
694
764
  };
695
765
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
696
766
  function printError(prefix, message, hint, cause) {
697
- const colors = paint(process11.stderr);
698
- const styled = takesControlCodes(process11.stderr);
767
+ const colors = paint(process13.stderr);
768
+ const styled = takesControlCodes(process13.stderr);
699
769
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
700
770
  const under = (label, text, tint) => text === undefined ? "" : `
701
771
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -739,24 +809,24 @@ function candidateLine(candidate) {
739
809
  }
740
810
  function positionalBeingTyped(before, { options, positionals }) {
741
811
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
742
- let index = 0;
812
+ const typed = [];
743
813
  let at = 0;
744
814
  while (at < before.length) {
745
815
  const word = before[at];
746
816
  if (word === "--") {
747
- index += before.length - at - 1;
817
+ typed.push(...before.slice(at + 1));
748
818
  break;
749
819
  }
750
820
  if (!word.startsWith("-"))
751
- index++;
821
+ typed.push(word);
752
822
  else if (takesValue(word))
753
823
  at++;
754
824
  at++;
755
825
  }
756
826
  const last = positionals.at(-1);
757
- if (index < positionals.length)
758
- return positionals[index];
759
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
827
+ if (typed.length < positionals.length)
828
+ return { name: positionals[typed.length], typed };
829
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
760
830
  }
761
831
  async function leafCandidates(run, words) {
762
832
  const completing = await completingOf(run);
@@ -764,12 +834,12 @@ async function leafCandidates(run, words) {
764
834
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
765
835
  const flag = words.at(-2);
766
836
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
837
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
767
838
  if (option?.type === "string") {
768
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
839
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
769
840
  return values === undefined ? [FILES] : values.map(candidateLine);
770
841
  }
771
- const name = positionalBeingTyped(words.slice(0, -1), completing);
772
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
842
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
773
843
  return values === undefined ? [FILES] : values.map(candidateLine);
774
844
  }
775
845
  async function printCandidates(found) {
@@ -778,9 +848,13 @@ async function printCandidates(found) {
778
848
  return 0;
779
849
  }
780
850
  function packageVersion(entry = Bun.main) {
781
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
851
+ let resolved = entry;
852
+ try {
853
+ resolved = realpathSync2(entry);
854
+ } catch {}
855
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
782
856
  try {
783
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
857
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
784
858
  if (typeof version === "string")
785
859
  return version;
786
860
  } catch {}
@@ -788,7 +862,7 @@ function packageVersion(entry = Bun.main) {
788
862
  return "0.0.0";
789
863
  }
790
864
  }
791
- async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
865
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
792
866
  if (argv[0] === COMPLETE)
793
867
  return printCandidates(leafCandidates(run, argv.slice(1)));
794
868
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -796,11 +870,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process11.a
796
870
  return 0;
797
871
  }
798
872
  let code;
873
+ const started = performance.now();
799
874
  try {
800
875
  code = await run(argv);
801
876
  } catch (error) {
802
877
  code = reportThrown(name, error, redact, wantsJson(argv));
803
878
  }
879
+ notifyEnd(name, code, performance.now() - started);
804
880
  if (usage !== false) {
805
881
  try {
806
882
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -816,6 +892,119 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
816
892
  var {Glob } = globalThis.Bun;
817
893
  var SESSION_FILES = new Glob("*.json");
818
894
  var ACCOUNT_DIRS = new Glob("*/sessions");
895
+ // ../kit/src/picker/line.ts
896
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
897
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
898
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
899
+ function isEditKey(key) {
900
+ return EDIT_KEYS.has(key);
901
+ }
902
+ function endsKills(key) {
903
+ return typeof key !== "object" && !isEditKey(key);
904
+ }
905
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
906
+ var SPACE = /\s/;
907
+ function isWord(char) {
908
+ return char !== undefined && WORD_CHARACTER.test(char);
909
+ }
910
+ function wordStart(chars, from) {
911
+ let at = from;
912
+ while (at > 0 && !isWord(chars[at - 1]))
913
+ at--;
914
+ while (at > 0 && isWord(chars[at - 1]))
915
+ at--;
916
+ return at;
917
+ }
918
+ function wordEnd(chars, from) {
919
+ let at = from;
920
+ while (at < chars.length && !isWord(chars[at]))
921
+ at++;
922
+ while (at < chars.length && isWord(chars[at]))
923
+ at++;
924
+ return at;
925
+ }
926
+ function spacedStart(chars, from) {
927
+ let at = from;
928
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
929
+ at--;
930
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
931
+ at--;
932
+ return at;
933
+ }
934
+ function cut(chars, from, to) {
935
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
936
+ }
937
+ function insert(chars, at, text) {
938
+ const typed = [...text];
939
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
940
+ }
941
+ function editLine(line, key) {
942
+ const { killed = "", chained = false } = line;
943
+ const chars = [...line.text];
944
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
945
+ const edited = edit(chars, at, key, killed);
946
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
947
+ return line.killed === undefined ? edited : { ...edited, killed };
948
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
949
+ if (taken === "")
950
+ return { ...edited, killed, chained };
951
+ if (!chained)
952
+ return { ...edited, killed: taken, chained: true };
953
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
954
+ }
955
+ function edit(chars, at, key, killed) {
956
+ const text = chars.join("");
957
+ if (typeof key === "object")
958
+ return insert(chars, at, key.text);
959
+ switch (key) {
960
+ case "left":
961
+ return { text, caret: Math.max(at - 1, 0) };
962
+ case "right":
963
+ return { text, caret: Math.min(at + 1, chars.length) };
964
+ case "wordleft":
965
+ return { text, caret: wordStart(chars, at) };
966
+ case "wordright":
967
+ return { text, caret: wordEnd(chars, at) };
968
+ case "linestart":
969
+ return { text, caret: 0 };
970
+ case "lineend":
971
+ return { text, caret: chars.length };
972
+ case "erase":
973
+ return cut(chars, Math.max(at - 1, 0), at);
974
+ case "delete":
975
+ return cut(chars, at, Math.min(at + 1, chars.length));
976
+ case "word":
977
+ return cut(chars, spacedStart(chars, at), at);
978
+ case "killword":
979
+ return cut(chars, wordStart(chars, at), at);
980
+ case "killnext":
981
+ return cut(chars, at, wordEnd(chars, at));
982
+ case "clear":
983
+ return cut(chars, 0, at);
984
+ case "killend":
985
+ return cut(chars, at, chars.length);
986
+ case "yank":
987
+ return insert(chars, at, killed);
988
+ }
989
+ }
990
+ function visible({ text, caret }, room) {
991
+ const chars = [...text];
992
+ const at = Math.min(Math.max(caret, 0), chars.length);
993
+ const cells = at === chars.length ? [...chars, " "] : chars;
994
+ const widths = cells.map((char) => Bun.stringWidth(char));
995
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
996
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
997
+ let start = at;
998
+ let end = at + 1;
999
+ while (start > 0 && fits(start - 1, end))
1000
+ start--;
1001
+ while (end < cells.length && fits(start, end + 1))
1002
+ end++;
1003
+ const left = start > 0 ? "\u2026" : "";
1004
+ const right = end < cells.length ? "\u2026" : "";
1005
+ return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
1006
+ }
1007
+
819
1008
  // ../kit/src/picker/score.ts
820
1009
  var MATCH = 16;
821
1010
  var CONSECUTIVE = 12;
@@ -900,7 +1089,6 @@ function rank(query, lines) {
900
1089
  }
901
1090
 
902
1091
  // ../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
1092
  var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
905
1093
  var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
906
1094
  var SGR = /^\x1B\[[0-9;]*m$/;
@@ -908,7 +1096,6 @@ var RESET = /^\x1B\[0?m$/;
908
1096
  var COLUMN_GAP = 2;
909
1097
  var PASTE_START = "\x1B[200~";
910
1098
  var PASTE_END = "\x1B[201~";
911
- var LAST_WORD = /\S*\s*$/;
912
1099
  var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
913
1100
  var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
914
1101
  var WHEEL_LINES = 3;
@@ -931,10 +1118,29 @@ var KEYS = {
931
1118
  "\n": "enter",
932
1119
  "\x03": "cancel",
933
1120
  "\x1B": "cancel",
1121
+ "\x1B[D": "left",
1122
+ "\x1BOD": "left",
1123
+ "\x1B[C": "right",
1124
+ "\x1BOC": "right",
1125
+ "\x1B[1;5D": "wordleft",
1126
+ "\x1B[1;3D": "wordleft",
1127
+ "\x1Bb": "wordleft",
1128
+ "\x1B[1;5C": "wordright",
1129
+ "\x1B[1;3C": "wordright",
1130
+ "\x1Bf": "wordright",
1131
+ "\x01": "linestart",
1132
+ "\x05": "lineend",
934
1133
  "\x7F": "erase",
935
- "\b": "erase",
1134
+ "\x1B[3~": "delete",
1135
+ "\b": "killword",
1136
+ "\x1B\x7F": "killword",
1137
+ "\x1B[3;5~": "killnext",
1138
+ "\x1Bd": "killnext",
936
1139
  "\x15": "clear",
1140
+ "\v": "killend",
937
1141
  "\x17": "word",
1142
+ "\x19": "yank",
1143
+ "\x1A": "suspend",
938
1144
  "\t": "tab",
939
1145
  "\x1F": "help",
940
1146
  "\x1BOP": "help",
@@ -955,7 +1161,7 @@ function styled(line) {
955
1161
  colored ||= active !== "" && flat !== "";
956
1162
  styles.push(...repeat(active, flat.length));
957
1163
  }
958
- for (const found of line.matchAll(ANSI2)) {
1164
+ for (const found of line.matchAll(ANSI)) {
959
1165
  add(line.slice(last, found.index));
960
1166
  last = found.index + found[0].length;
961
1167
  if (SGR.test(found[0]))
@@ -967,7 +1173,7 @@ function styled(line) {
967
1173
  function lay(rows, searched) {
968
1174
  const parsed = rows.map((row) => row.cells.map(styled));
969
1175
  const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
970
- return parsed.map((cells) => {
1176
+ return parsed.map((cells, at) => {
971
1177
  let text = "";
972
1178
  const styles = [];
973
1179
  let colored = false;
@@ -986,7 +1192,7 @@ function lay(rows, searched) {
986
1192
  styles.push(...repeat("", pad));
987
1193
  }
988
1194
  }
989
- return { text, styles: colored ? styles : undefined, searchable: text.slice(0, searchEnd) };
1195
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
990
1196
  });
991
1197
  }
992
1198
  function parseKeys(input, paste = { active: false }, ctrls = []) {
@@ -1010,7 +1216,7 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1010
1216
  });
1011
1217
  }
1012
1218
  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 };
1219
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1014
1220
  return withRows(state, rows);
1015
1221
  }
1016
1222
  function withRows(state, rows, header = state.header) {
@@ -1020,8 +1226,9 @@ function withRows(state, rows, header = state.header) {
1020
1226
  const matches = rank(state.query, searchable);
1021
1227
  return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1022
1228
  }
1023
- function withQuery(state, query) {
1024
- return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
1229
+ function withQuery(state, key) {
1230
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1231
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1025
1232
  }
1026
1233
  function move(state, by) {
1027
1234
  return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
@@ -1032,13 +1239,17 @@ function highlighted(state) {
1032
1239
  function press(state, key) {
1033
1240
  if (state.done !== undefined)
1034
1241
  return state;
1242
+ if (state.chained && endsKills(key))
1243
+ state = { ...state, chained: false };
1035
1244
  if (state.help)
1036
1245
  return { ...state, help: false };
1037
1246
  if (typeof key === "object") {
1038
1247
  if ("text" in key)
1039
- return withQuery(state, state.query + key.text);
1248
+ return withQuery(state, key);
1040
1249
  return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1041
1250
  }
1251
+ if (isEditKey(key))
1252
+ return withQuery(state, key);
1042
1253
  switch (key) {
1043
1254
  case "up":
1044
1255
  return move(state, -1);
@@ -1056,12 +1267,8 @@ function press(state, key) {
1056
1267
  return { ...state, done: "cancel" };
1057
1268
  case "help":
1058
1269
  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, ""));
1270
+ case "suspend":
1271
+ return state;
1065
1272
  case "enter":
1066
1273
  return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1067
1274
  case "tab": {
@@ -1084,11 +1291,25 @@ function chosen(state) {
1084
1291
 
1085
1292
  // ../kit/src/picker/terminal.ts
1086
1293
  import { openSync } from "fs";
1087
- import process14 from "process";
1294
+ import process17 from "process";
1088
1295
  import tty from "tty";
1089
1296
 
1297
+ // ../kit/src/job.ts
1298
+ import process15 from "process";
1299
+ function stopJob() {
1300
+ process15.kill(0, "SIGTSTP");
1301
+ }
1302
+
1303
+ // ../kit/src/redraw.ts
1304
+ var SYNC_START = "\x1B[?2026h";
1305
+ var SYNC_END = "\x1B[?2026l";
1306
+ function overwrite(lines, columns) {
1307
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1308
+ `);
1309
+ }
1310
+
1090
1311
  // ../kit/src/picker/preview.ts
1091
- import process13 from "process";
1312
+ import process16 from "process";
1092
1313
 
1093
1314
  // ../kit/src/shell.ts
1094
1315
  var SEPARATORS = new Set([`
@@ -1157,7 +1378,7 @@ async function runPreview(template, line, signal, hidden = []) {
1157
1378
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1158
1379
  const stop = () => {
1159
1380
  try {
1160
- process13.kill(-proc.pid, "SIGKILL");
1381
+ process16.kill(-proc.pid, "SIGKILL");
1161
1382
  } catch {
1162
1383
  proc.kill();
1163
1384
  }
@@ -1233,13 +1454,20 @@ function fitStyled(line, width, plain = identity) {
1233
1454
  const { text, styles } = styled(line);
1234
1455
  return fit(text, width, plain, plain, new Set, styles);
1235
1456
  }
1236
- function caretColumn(state, layout) {
1237
- return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
1457
+ function queryShown(state, layout) {
1458
+ return visible({ text: state.query, caret: state.caret }, Math.max(1, layout.listWidth - Bun.stringWidth(state.prompt)));
1459
+ }
1460
+ function caretCell(state, layout) {
1461
+ const shown = queryShown(state, layout);
1462
+ return { column: Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + shown.column + 1), char: shown.at ?? " " };
1238
1463
  }
1239
1464
  function helpLines(state, layout, theme) {
1240
1465
  const lines = [
1241
1466
  "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`,
1467
+ "left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word",
1468
+ "ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead",
1469
+ "ctrl-y puts back what they erased, ctrl-z suspends to the shell",
1470
+ `enter picks${state.multi ? ", tab marks" : ""}, esc or ctrl-c cancels`,
1243
1471
  ...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
1244
1472
  ];
1245
1473
  const title = "keys, any key closes this help";
@@ -1255,7 +1483,9 @@ function listLines(state, layout, theme) {
1255
1483
  const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
1256
1484
  const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
1257
1485
  const promptWidth = Bun.stringWidth(state.prompt);
1258
- const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
1486
+ const shown = queryShown(state, layout);
1487
+ const text = `${shown.before}${shown.at ?? ""}${shown.after}`;
1488
+ const query = { text, width: Bun.stringWidth(text) };
1259
1489
  const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
1260
1490
  const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
1261
1491
  const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
@@ -1288,7 +1518,8 @@ var ESCAPE_WAIT_MS = 30;
1288
1518
  var OPEN = { ctrl: "open" };
1289
1519
  var HIDE_CURSOR = "\x1B[?25l";
1290
1520
  var SHOW_CURSOR = "\x1B[?25h";
1291
- var CARET = "\x1B[7m \x1B[27m";
1521
+ var REVERSE = "\x1B[7m";
1522
+ var REVERSE_END = "\x1B[27m";
1292
1523
  var PASTE_ON = "\x1B[?2004h";
1293
1524
  var PASTE_OFF = "\x1B[?2004l";
1294
1525
  var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
@@ -1306,7 +1537,7 @@ function openTerminal() {
1306
1537
  return fail("no terminal to read keys from (/dev/tty)");
1307
1538
  }
1308
1539
  const keys = Bun.file("/dev/tty").stream().getReader();
1309
- const out = process14.stderr;
1540
+ const out = process17.stderr;
1310
1541
  let resize;
1311
1542
  async function read(onChunk) {
1312
1543
  const decoder = new TextDecoder;
@@ -1332,6 +1563,11 @@ function openTerminal() {
1332
1563
  out.on("resize", onResize);
1333
1564
  read(onChunk);
1334
1565
  },
1566
+ suspend() {
1567
+ mode.setRawMode(false);
1568
+ stopJob();
1569
+ mode.setRawMode(true);
1570
+ },
1335
1571
  close() {
1336
1572
  if (resize !== undefined)
1337
1573
  out.off("resize", resize);
@@ -1359,14 +1595,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1359
1595
  if (restored)
1360
1596
  return;
1361
1597
  const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1362
- let frame = HIDE_CURSOR;
1598
+ let frame = SYNC_START + HIDE_CURSOR;
1363
1599
  if (reserved !== layout.height || clear) {
1364
1600
  frame += CLEAR_BELOW + `
1365
1601
  `.repeat(layout.height - 1) + up(layout.height - 1);
1366
1602
  reserved = layout.height;
1367
1603
  }
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`;
1604
+ const caret = caretCell(state, layout);
1605
+ frame += `\r${overwrite(render(state, layout, theme, preview), terminal.columns)}${up(layout.height - 1)}\r\x1B[${caret.column}G${REVERSE}${caret.char}${REVERSE_END}\r${SYNC_END}`;
1370
1606
  terminal.write(frame);
1371
1607
  }
1372
1608
  function pageSize() {
@@ -1408,6 +1644,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1408
1644
  terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1409
1645
  terminal.close();
1410
1646
  }
1647
+ function suspend() {
1648
+ if (terminal.suspend === undefined)
1649
+ return;
1650
+ terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1651
+ terminal.suspend();
1652
+ terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1653
+ draw(true);
1654
+ }
1411
1655
  const stop = () => {
1412
1656
  state = { ...state, done: "cancel" };
1413
1657
  finish?.();
@@ -1441,6 +1685,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1441
1685
  for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
1442
1686
  if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
1443
1687
  await reloadRows();
1688
+ else if (key === "suspend")
1689
+ suspend();
1444
1690
  else
1445
1691
  state = press({ ...state, page: pageSize() }, key);
1446
1692
  }
@@ -1480,9 +1726,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1480
1726
  const ended = new Promise((resolve) => {
1481
1727
  finish = resolve;
1482
1728
  });
1483
- process14.once("exit", restore);
1729
+ process17.once("exit", restore);
1484
1730
  for (const signal of SIGNALS)
1485
- process14.once(signal, stop);
1731
+ process17.once(signal, stop);
1486
1732
  try {
1487
1733
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1488
1734
  terminal.listen(onChunk, () => draw(true));
@@ -1495,8 +1741,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1495
1741
  await ended;
1496
1742
  } finally {
1497
1743
  for (const signal of SIGNALS)
1498
- process14.off(signal, stop);
1499
- process14.off("exit", restore);
1744
+ process17.off(signal, stop);
1745
+ process17.off("exit", restore);
1500
1746
  restore();
1501
1747
  }
1502
1748
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1508,61 +1754,127 @@ async function previewOf(preview, hidden, signal) {
1508
1754
  return [error instanceof Error ? error.message : String(error)];
1509
1755
  }
1510
1756
  }
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]);
1757
+ // src/fields.ts
1758
+ var INDEX = /^-?\d+$/;
1759
+ function splitFields(line, delimiter) {
1760
+ if (delimiter === undefined)
1761
+ return line.match(/\s*\S+\s*/g) ?? [];
1762
+ const fields = [];
1763
+ let from = 0;
1764
+ for (const match of line.matchAll(new RegExp(delimiter, `${delimiter.flags}g`))) {
1765
+ if (match[0] === "")
1766
+ continue;
1767
+ fields.push(line.slice(from, match.index + match[0].length));
1768
+ from = match.index + match[0].length;
1769
+ }
1770
+ fields.push(line.slice(from));
1771
+ return fields;
1772
+ }
1773
+ function parseFields(expression) {
1774
+ const spans = [];
1775
+ for (const part of expression.split(",")) {
1776
+ const dots = part.indexOf("..");
1777
+ const from = dots === -1 ? part : part.slice(0, dots);
1778
+ const to = dots === -1 ? from : part.slice(dots + 2);
1779
+ if (part === "0" || part === "" || from !== "" && !INDEX.test(from) || to !== "" && !INDEX.test(to))
1780
+ return;
1781
+ const resolve = (n, count) => n < 0 ? count + n : n - 1;
1782
+ spans.push((count) => {
1783
+ const first = from === "" ? 0 : resolve(Number(from), count);
1784
+ const last = to === "" ? count - 1 : resolve(Number(to), count);
1785
+ return Array.from({ length: Math.max(0, last - first + 1) }, (_, i) => first + i).filter((i) => i >= 0 && i < count);
1786
+ });
1787
+ }
1788
+ return (count) => spans.flatMap((span) => span(count));
1789
+ }
1790
+ function pickFields(line, select, delimiter) {
1791
+ const fields = splitFields(line, delimiter);
1792
+ return select(fields.length).map((i) => fields[i]).join("");
1514
1793
  }
1794
+
1515
1795
  // src/pick.ts
1516
1796
  var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
1517
1797
 
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.
1798
+ Type to filter: the query matches as a subsequence, best matches first (a word start, a run of characters or a prefix scores higher; a lowercase query ignores case, an uppercase letter makes it exact). Up and down or ctrl-p and ctrl-n move, enter picks, esc and ctrl-c cancel, left, right, ctrl-a and ctrl-e move in the query (ctrl or alt for a word), ctrl-u and ctrl-k erase back to its start and on to its end, ctrl-y puts back what they erased, ctrl-z suspends, ctrl-/ or f1 shows the keys.
1519
1799
  The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks the highlighted line and enter prints the marked lines in input order (the highlighted one when none is marked).
1520
1800
  --preview runs a command for the highlighted line, \`{}\` standing for it shell-quoted, in a pane on the right when the terminal is at least 80 columns wide; its output is cut at 64 KiB and 200 lines.
1521
1801
 
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.
1802
+ --delimiter splits each line into fields (a regex, whitespace by default), --nth names the fields the query is matched against and --with-nth the ones shown, in fzf's syntax: 1-based, \`-1\` the last, \`2..\`, \`..3\`, \`2..4\`, comma-separated. The printed line is always the whole input line. --read0 reads NUL-separated lines and --print0 ends each printed one with NUL.
1803
+ --filter takes the query and prints every match best first with no terminal; --select-1 prints the only match without opening the selector, --exit-0 exits 1 at once when nothing matches.
1523
1804
 
1524
- Exits 0 when it printed a choice, 1 when cancelled, nothing matches or there are no lines, 2 on a usage error.`;
1805
+ Without a terminal on stderr there is nobody to choose: it prints the best line the query matches, as the selector would rank it, or every match best first with --multi.`;
1806
+ var EXITS = [[0, "it printed a choice"], [1, "nothing matches or there are no lines"], [2, "a usage error"], [130, "cancelled"]];
1525
1807
  var OPTIONS = {
1526
1808
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
1527
1809
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
1528
1810
  query: { type: "string", short: "q", description: "the query to start with" },
1529
1811
  preview: { type: "string", description: "a command shown for the highlighted line, {} standing for it" },
1812
+ header: { type: "string", description: "a line of text shown above the list" },
1813
+ filter: { type: "string", short: "f", description: "print every line the query matches, best first, with no terminal" },
1814
+ "select-1": { type: "boolean", short: "1", description: "print the only match without opening the selector" },
1815
+ "exit-0": { type: "boolean", short: "0", description: "exit 1 at once when nothing matches" },
1816
+ delimiter: { type: "string", short: "d", description: "a regex splitting a line into fields (whitespace)" },
1817
+ nth: { type: "string", description: "the fields the query is matched against, 2, -1, 2.., 1..3, 1,3" },
1818
+ "with-nth": { type: "string", description: "the fields shown, the printed line stays whole" },
1819
+ read0: { type: "boolean", description: "lines on stdin end with NUL" },
1820
+ print0: { type: "boolean", description: "end each printed line with NUL" },
1530
1821
  height: { type: "string", description: "lines or a percentage of the terminal to draw in (100%)" },
1531
1822
  json: jsonOption("{picked: [lines]}, the choice or the marked lines in input order")
1532
1823
  };
1533
- function print(chosen, json) {
1824
+ function print(chosen, json, end) {
1534
1825
  if (json)
1535
1826
  printJson({ picked: chosen });
1536
1827
  else
1537
- process15.stdout.write(`${chosen.join(`
1538
- `)}
1539
- `);
1828
+ process18.stdout.write(chosen.map((line) => line + end).join(""));
1540
1829
  }
1541
1830
  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 {}'"] });
1831
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'", "git branch | pick --filter main # every match, best first, no terminal", "ps aux | pick --with-nth 2,11.. --nth 11.. # show some fields, search others"] });
1543
1832
  if (positionals.length > 0)
1544
1833
  badUsage("pick takes its lines on stdin, not as arguments");
1545
1834
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1546
1835
  if (height === undefined)
1547
1836
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1548
- if (process15.stdin.isTTY)
1837
+ if (process18.stdin.isTTY)
1549
1838
  badUsage("pipe the lines to pick on stdin");
1550
- const lines = (await Bun.stdin.text()).split(`
1839
+ const fieldsOf = (name) => {
1840
+ const text = values[name];
1841
+ if (text === undefined)
1842
+ return;
1843
+ return parseFields(text) ?? badUsage(`--${name} takes fields such as 2, -1, 2.., 1..3 or 1,3, not ${text}`);
1844
+ };
1845
+ const nth = fieldsOf("nth");
1846
+ const withNth = fieldsOf("with-nth");
1847
+ let delimiter;
1848
+ try {
1849
+ delimiter = values.delimiter === undefined ? undefined : new RegExp(values.delimiter);
1850
+ } catch {
1851
+ badUsage(`--delimiter is a regex, not ${values.delimiter}`);
1852
+ }
1853
+ const lines = (await Bun.stdin.text()).split(values.read0 === true ? "\x00" : `
1551
1854
  `).filter((line) => line !== "");
1552
1855
  if (lines.length === 0)
1553
1856
  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);
1857
+ const query = values.filter ?? values.query ?? "";
1858
+ const end = values.print0 === true ? "\x00" : `
1859
+ `;
1860
+ const json = values.json === true;
1861
+ const searched = lines.map((line) => nth === undefined ? line : pickFields(line, nth, delimiter));
1862
+ const matching = rank(query, searched).map(({ index }) => lines[index]);
1863
+ if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process18.stderr.isTTY))
1864
+ return 1;
1865
+ if (values.filter !== undefined || !process18.stderr.isTTY) {
1866
+ print(values.multi === true || values.filter !== undefined ? matching : matching.slice(0, 1), json, end);
1867
+ return 0;
1868
+ }
1869
+ if (values["select-1"] === true && matching.length === 1) {
1870
+ print(matching, json, end);
1560
1871
  return 0;
1561
1872
  }
1562
- const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
1873
+ const rows = lines.map((line, index) => ({ hidden: [line], cells: [withNth === undefined ? line : pickFields(line, withNth, delimiter).trimEnd()], ...nth === undefined ? {} : { search: searched[index] } }));
1874
+ const picked = await select(rows, { multi: values.multi === true, prompt: values.prompt ?? "> ", query, height, preview: values.preview, header: values.header });
1563
1875
  if (picked === undefined)
1564
- return 1;
1565
- print(picked, values.json === true);
1876
+ return 130;
1877
+ print(picked.rows.map((row) => row.hidden[0]), json, end);
1566
1878
  return 0;
1567
1879
  }
1568
- process15.exitCode = await runMain({ name: "pick", run: main });
1880
+ process18.exitCode = await runMain({ name: "pick", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-pick",
3
3
  "type": "module",
4
- "version": "0.9.1",
4
+ "version": "0.11.0",
5
5
  "description": "pick: a themed fuzzy selector, lines on stdin, the chosen one on stdout.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "pick": "$npm_execpath src/pick.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.37.0"
38
+ "@kaynooo/cli-kit": "0.40.0"
39
39
  }
40
40
  }