@kaynooo/cli-pick 0.9.1 → 0.10.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 +213 -66
  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-/ 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 process16 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -326,6 +326,9 @@ function upTo(text, separator) {
326
326
  return end === -1 ? text : text.slice(0, end);
327
327
  }
328
328
  var ESCAPE = String.fromCharCode(27);
329
+ function textWidth(text) {
330
+ return Bun.stringWidth(text);
331
+ }
329
332
  function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
330
333
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
331
334
  }
@@ -341,18 +344,14 @@ var FULL_STOP = /\.$/;
341
344
  function usageLine(usage, colors = paint(process8.stdout)) {
342
345
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
346
  }
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(`
347
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
348
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
349
  `);
347
350
  }
348
351
  function exitRows(exits, colors = paint(process8.stdout)) {
349
352
  if (exits.length === 0)
350
353
  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}`];
354
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
356
355
  }
357
356
  function wantsHelpJson(env = process8.env) {
358
357
  return env.KIT_HELP === "json";
@@ -627,21 +626,45 @@ function nearestOption(message, options, allowNegative) {
627
626
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
628
627
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
629
628
  }
629
+ // ../kit/src/argv.ts
630
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
631
+ import { resolve as resolve3 } from "path";
632
+ import process10 from "process";
633
+ function commandLine() {
634
+ try {
635
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
636
+ } catch {
637
+ return;
638
+ }
639
+ }
640
+ function realPath(word) {
641
+ try {
642
+ return realpathSync(resolve3(word));
643
+ } catch {
644
+ return;
645
+ }
646
+ }
647
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
648
+ const target = script === undefined ? undefined : realPath(script) ?? script;
649
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
650
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
651
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
652
+ }
630
653
  // ../kit/src/progress.ts
631
654
  var ESC = String.fromCharCode(27);
632
655
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
633
656
  var RESET_STYLE = `${ESC}[0m`;
634
657
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
635
658
  // ../kit/src/cli.ts
636
- import { readFileSync as readFileSync2, realpathSync } from "fs";
659
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
637
660
  import { dirname as dirname3, join as join5 } from "path";
638
- import process11 from "process";
661
+ import process12 from "process";
639
662
 
640
663
  // ../kit/src/usage.ts
641
664
  import { appendFileSync, mkdirSync } from "fs";
642
665
  import { homedir as homedir3 } from "os";
643
666
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
644
- import process10 from "process";
667
+ import process11 from "process";
645
668
 
646
669
  // ../kit/src/logs.ts
647
670
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -655,14 +678,14 @@ var usageError;
655
678
  function noteUsageError(message) {
656
679
  usageError = message;
657
680
  }
658
- function stateHome(env = process10.env) {
681
+ function stateHome(env = process11.env) {
659
682
  const dir = env.XDG_STATE_HOME;
660
683
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
661
684
  }
662
- function usagePath(env = process10.env) {
685
+ function usagePath(env = process11.env) {
663
686
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
664
687
  }
665
- function usageRecorded(env = process10.env) {
688
+ function usageRecorded(env = process11.env) {
666
689
  const off = env.KAYNOOO_CLI_NO_USAGE;
667
690
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
668
691
  }
@@ -676,7 +699,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
676
699
  usageError = undefined;
677
700
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
678
701
  }
679
- function recordUsage(entry, env = process10.env) {
702
+ function recordUsage(entry, env = process11.env) {
680
703
  if (!usageRecorded(env))
681
704
  return;
682
705
  try {
@@ -694,8 +717,8 @@ var LEVEL_OPTIONS = {
694
717
  };
695
718
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
696
719
  function printError(prefix, message, hint, cause) {
697
- const colors = paint(process11.stderr);
698
- const styled = takesControlCodes(process11.stderr);
720
+ const colors = paint(process12.stderr);
721
+ const styled = takesControlCodes(process12.stderr);
699
722
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
700
723
  const under = (label, text, tint) => text === undefined ? "" : `
701
724
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -739,24 +762,24 @@ function candidateLine(candidate) {
739
762
  }
740
763
  function positionalBeingTyped(before, { options, positionals }) {
741
764
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
742
- let index = 0;
765
+ const typed = [];
743
766
  let at = 0;
744
767
  while (at < before.length) {
745
768
  const word = before[at];
746
769
  if (word === "--") {
747
- index += before.length - at - 1;
770
+ typed.push(...before.slice(at + 1));
748
771
  break;
749
772
  }
750
773
  if (!word.startsWith("-"))
751
- index++;
774
+ typed.push(word);
752
775
  else if (takesValue(word))
753
776
  at++;
754
777
  at++;
755
778
  }
756
779
  const last = positionals.at(-1);
757
- if (index < positionals.length)
758
- return positionals[index];
759
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
780
+ if (typed.length < positionals.length)
781
+ return { name: positionals[typed.length], typed };
782
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
760
783
  }
761
784
  async function leafCandidates(run, words) {
762
785
  const completing = await completingOf(run);
@@ -764,12 +787,12 @@ async function leafCandidates(run, words) {
764
787
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
765
788
  const flag = words.at(-2);
766
789
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
790
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
767
791
  if (option?.type === "string") {
768
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
792
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
769
793
  return values === undefined ? [FILES] : values.map(candidateLine);
770
794
  }
771
- const name = positionalBeingTyped(words.slice(0, -1), completing);
772
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
795
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
773
796
  return values === undefined ? [FILES] : values.map(candidateLine);
774
797
  }
775
798
  async function printCandidates(found) {
@@ -778,9 +801,13 @@ async function printCandidates(found) {
778
801
  return 0;
779
802
  }
780
803
  function packageVersion(entry = Bun.main) {
781
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
804
+ let resolved = entry;
805
+ try {
806
+ resolved = realpathSync2(entry);
807
+ } catch {}
808
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
782
809
  try {
783
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
810
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
784
811
  if (typeof version === "string")
785
812
  return version;
786
813
  } catch {}
@@ -788,7 +815,7 @@ function packageVersion(entry = Bun.main) {
788
815
  return "0.0.0";
789
816
  }
790
817
  }
791
- async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
818
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
792
819
  if (argv[0] === COMPLETE)
793
820
  return printCandidates(leafCandidates(run, argv.slice(1)));
794
821
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -816,6 +843,97 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
816
843
  var {Glob } = globalThis.Bun;
817
844
  var SESSION_FILES = new Glob("*.json");
818
845
  var ACCOUNT_DIRS = new Glob("*/sessions");
846
+ // ../kit/src/picker/line.ts
847
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend"]);
848
+ function isEditKey(key) {
849
+ return EDIT_KEYS.has(key);
850
+ }
851
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
852
+ var SPACE = /\s/;
853
+ function isWord(char) {
854
+ return char !== undefined && WORD_CHARACTER.test(char);
855
+ }
856
+ function wordStart(chars, from) {
857
+ let at = from;
858
+ while (at > 0 && !isWord(chars[at - 1]))
859
+ at--;
860
+ while (at > 0 && isWord(chars[at - 1]))
861
+ at--;
862
+ return at;
863
+ }
864
+ function wordEnd(chars, from) {
865
+ let at = from;
866
+ while (at < chars.length && !isWord(chars[at]))
867
+ at++;
868
+ while (at < chars.length && isWord(chars[at]))
869
+ at++;
870
+ return at;
871
+ }
872
+ function spacedStart(chars, from) {
873
+ let at = from;
874
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
875
+ at--;
876
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
877
+ at--;
878
+ return at;
879
+ }
880
+ function cut(chars, from, to) {
881
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
882
+ }
883
+ function editLine({ text, caret }, key) {
884
+ const chars = [...text];
885
+ const at = Math.min(Math.max(caret, 0), chars.length);
886
+ if (typeof key === "object") {
887
+ const typed = [...key.text];
888
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
889
+ }
890
+ switch (key) {
891
+ case "left":
892
+ return { text, caret: Math.max(at - 1, 0) };
893
+ case "right":
894
+ return { text, caret: Math.min(at + 1, chars.length) };
895
+ case "wordleft":
896
+ return { text, caret: wordStart(chars, at) };
897
+ case "wordright":
898
+ return { text, caret: wordEnd(chars, at) };
899
+ case "linestart":
900
+ return { text, caret: 0 };
901
+ case "lineend":
902
+ return { text, caret: chars.length };
903
+ case "erase":
904
+ return cut(chars, Math.max(at - 1, 0), at);
905
+ case "delete":
906
+ return cut(chars, at, Math.min(at + 1, chars.length));
907
+ case "word":
908
+ return cut(chars, spacedStart(chars, at), at);
909
+ case "killword":
910
+ return cut(chars, wordStart(chars, at), at);
911
+ case "killnext":
912
+ return cut(chars, at, wordEnd(chars, at));
913
+ case "clear":
914
+ return cut(chars, 0, at);
915
+ case "killend":
916
+ return cut(chars, at, chars.length);
917
+ }
918
+ }
919
+ function visible({ text, caret }, room) {
920
+ const chars = [...text];
921
+ const at = Math.min(Math.max(caret, 0), chars.length);
922
+ const cells = at === chars.length ? [...chars, " "] : chars;
923
+ const widths = cells.map((char) => Bun.stringWidth(char));
924
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
925
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
926
+ let start = at;
927
+ let end = at + 1;
928
+ while (start > 0 && fits(start - 1, end))
929
+ start--;
930
+ while (end < cells.length && fits(start, end + 1))
931
+ end++;
932
+ const left = start > 0 ? "\u2026" : "";
933
+ const right = end < cells.length ? "\u2026" : "";
934
+ 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) };
935
+ }
936
+
819
937
  // ../kit/src/picker/score.ts
820
938
  var MATCH = 16;
821
939
  var CONSECUTIVE = 12;
@@ -908,7 +1026,6 @@ var RESET = /^\x1B\[0?m$/;
908
1026
  var COLUMN_GAP = 2;
909
1027
  var PASTE_START = "\x1B[200~";
910
1028
  var PASTE_END = "\x1B[201~";
911
- var LAST_WORD = /\S*\s*$/;
912
1029
  var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
913
1030
  var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
914
1031
  var WHEEL_LINES = 3;
@@ -931,9 +1048,26 @@ var KEYS = {
931
1048
  "\n": "enter",
932
1049
  "\x03": "cancel",
933
1050
  "\x1B": "cancel",
1051
+ "\x1B[D": "left",
1052
+ "\x1BOD": "left",
1053
+ "\x1B[C": "right",
1054
+ "\x1BOC": "right",
1055
+ "\x1B[1;5D": "wordleft",
1056
+ "\x1B[1;3D": "wordleft",
1057
+ "\x1Bb": "wordleft",
1058
+ "\x1B[1;5C": "wordright",
1059
+ "\x1B[1;3C": "wordright",
1060
+ "\x1Bf": "wordright",
1061
+ "\x01": "linestart",
1062
+ "\x05": "lineend",
934
1063
  "\x7F": "erase",
935
- "\b": "erase",
1064
+ "\x1B[3~": "delete",
1065
+ "\b": "killword",
1066
+ "\x1B\x7F": "killword",
1067
+ "\x1B[3;5~": "killnext",
1068
+ "\x1Bd": "killnext",
936
1069
  "\x15": "clear",
1070
+ "\v": "killend",
937
1071
  "\x17": "word",
938
1072
  "\t": "tab",
939
1073
  "\x1F": "help",
@@ -1010,7 +1144,7 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1010
1144
  });
1011
1145
  }
1012
1146
  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 };
1147
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1014
1148
  return withRows(state, rows);
1015
1149
  }
1016
1150
  function withRows(state, rows, header = state.header) {
@@ -1020,8 +1154,9 @@ function withRows(state, rows, header = state.header) {
1020
1154
  const matches = rank(state.query, searchable);
1021
1155
  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
1156
  }
1023
- function withQuery(state, query) {
1024
- return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
1157
+ function withQuery(state, key) {
1158
+ const { text, caret } = editLine({ text: state.query, caret: state.caret }, key);
1159
+ return text === state.query ? { ...state, caret } : { ...state, query: text, caret, matches: rank(text, state.searchable), cursor: 0 };
1025
1160
  }
1026
1161
  function move(state, by) {
1027
1162
  return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
@@ -1036,9 +1171,11 @@ function press(state, key) {
1036
1171
  return { ...state, help: false };
1037
1172
  if (typeof key === "object") {
1038
1173
  if ("text" in key)
1039
- return withQuery(state, state.query + key.text);
1174
+ return withQuery(state, key);
1040
1175
  return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1041
1176
  }
1177
+ if (isEditKey(key))
1178
+ return withQuery(state, key);
1042
1179
  switch (key) {
1043
1180
  case "up":
1044
1181
  return move(state, -1);
@@ -1056,12 +1193,6 @@ function press(state, key) {
1056
1193
  return { ...state, done: "cancel" };
1057
1194
  case "help":
1058
1195
  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, ""));
1065
1196
  case "enter":
1066
1197
  return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1067
1198
  case "tab": {
@@ -1084,11 +1215,19 @@ function chosen(state) {
1084
1215
 
1085
1216
  // ../kit/src/picker/terminal.ts
1086
1217
  import { openSync } from "fs";
1087
- import process14 from "process";
1218
+ import process15 from "process";
1088
1219
  import tty from "tty";
1089
1220
 
1221
+ // ../kit/src/redraw.ts
1222
+ var SYNC_START = "\x1B[?2026h";
1223
+ var SYNC_END = "\x1B[?2026l";
1224
+ function overwrite(lines, columns) {
1225
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1226
+ `);
1227
+ }
1228
+
1090
1229
  // ../kit/src/picker/preview.ts
1091
- import process13 from "process";
1230
+ import process14 from "process";
1092
1231
 
1093
1232
  // ../kit/src/shell.ts
1094
1233
  var SEPARATORS = new Set([`
@@ -1157,7 +1296,7 @@ async function runPreview(template, line, signal, hidden = []) {
1157
1296
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1158
1297
  const stop = () => {
1159
1298
  try {
1160
- process13.kill(-proc.pid, "SIGKILL");
1299
+ process14.kill(-proc.pid, "SIGKILL");
1161
1300
  } catch {
1162
1301
  proc.kill();
1163
1302
  }
@@ -1233,13 +1372,19 @@ function fitStyled(line, width, plain = identity) {
1233
1372
  const { text, styles } = styled(line);
1234
1373
  return fit(text, width, plain, plain, new Set, styles);
1235
1374
  }
1236
- function caretColumn(state, layout) {
1237
- return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
1375
+ function queryShown(state, layout) {
1376
+ return visible({ text: state.query, caret: state.caret }, Math.max(1, layout.listWidth - Bun.stringWidth(state.prompt)));
1377
+ }
1378
+ function caretCell(state, layout) {
1379
+ const shown = queryShown(state, layout);
1380
+ return { column: Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + shown.column + 1), char: shown.at ?? " " };
1238
1381
  }
1239
1382
  function helpLines(state, layout, theme) {
1240
1383
  const lines = [
1241
1384
  "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`,
1385
+ "left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word",
1386
+ "ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead",
1387
+ `enter picks${state.multi ? ", tab marks" : ""}, esc or ctrl-c cancels`,
1243
1388
  ...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
1244
1389
  ];
1245
1390
  const title = "keys, any key closes this help";
@@ -1255,7 +1400,9 @@ function listLines(state, layout, theme) {
1255
1400
  const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
1256
1401
  const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
1257
1402
  const promptWidth = Bun.stringWidth(state.prompt);
1258
- const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
1403
+ const shown = queryShown(state, layout);
1404
+ const text = `${shown.before}${shown.at ?? ""}${shown.after}`;
1405
+ const query = { text, width: Bun.stringWidth(text) };
1259
1406
  const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
1260
1407
  const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
1261
1408
  const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
@@ -1288,7 +1435,8 @@ var ESCAPE_WAIT_MS = 30;
1288
1435
  var OPEN = { ctrl: "open" };
1289
1436
  var HIDE_CURSOR = "\x1B[?25l";
1290
1437
  var SHOW_CURSOR = "\x1B[?25h";
1291
- var CARET = "\x1B[7m \x1B[27m";
1438
+ var REVERSE = "\x1B[7m";
1439
+ var REVERSE_END = "\x1B[27m";
1292
1440
  var PASTE_ON = "\x1B[?2004h";
1293
1441
  var PASTE_OFF = "\x1B[?2004l";
1294
1442
  var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
@@ -1306,7 +1454,7 @@ function openTerminal() {
1306
1454
  return fail("no terminal to read keys from (/dev/tty)");
1307
1455
  }
1308
1456
  const keys = Bun.file("/dev/tty").stream().getReader();
1309
- const out = process14.stderr;
1457
+ const out = process15.stderr;
1310
1458
  let resize;
1311
1459
  async function read(onChunk) {
1312
1460
  const decoder = new TextDecoder;
@@ -1359,14 +1507,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1359
1507
  if (restored)
1360
1508
  return;
1361
1509
  const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1362
- let frame = HIDE_CURSOR;
1510
+ let frame = SYNC_START + HIDE_CURSOR;
1363
1511
  if (reserved !== layout.height || clear) {
1364
1512
  frame += CLEAR_BELOW + `
1365
1513
  `.repeat(layout.height - 1) + up(layout.height - 1);
1366
1514
  reserved = layout.height;
1367
1515
  }
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`;
1516
+ const caret = caretCell(state, layout);
1517
+ 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
1518
  terminal.write(frame);
1371
1519
  }
1372
1520
  function pageSize() {
@@ -1480,9 +1628,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1480
1628
  const ended = new Promise((resolve) => {
1481
1629
  finish = resolve;
1482
1630
  });
1483
- process14.once("exit", restore);
1631
+ process15.once("exit", restore);
1484
1632
  for (const signal of SIGNALS)
1485
- process14.once(signal, stop);
1633
+ process15.once(signal, stop);
1486
1634
  try {
1487
1635
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1488
1636
  terminal.listen(onChunk, () => draw(true));
@@ -1495,8 +1643,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1495
1643
  await ended;
1496
1644
  } finally {
1497
1645
  for (const signal of SIGNALS)
1498
- process14.off(signal, stop);
1499
- process14.off("exit", restore);
1646
+ process15.off(signal, stop);
1647
+ process15.off("exit", restore);
1500
1648
  restore();
1501
1649
  }
1502
1650
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1515,13 +1663,12 @@ async function choose(lines, settings) {
1515
1663
  // src/pick.ts
1516
1664
  var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
1517
1665
 
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.
1666
+ 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-/ or f1 shows the keys.
1519
1667
  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
1668
  --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
1669
 
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.
1523
-
1524
- Exits 0 when it printed a choice, 1 when cancelled, nothing matches or there are no lines, 2 on a usage error.`;
1670
+ Without a terminal on stderr there is nobody to choose: it prints the first line containing the query (case-insensitive), every one with --multi.`;
1671
+ var EXITS = [[0, "it printed a choice"], [1, "cancelled, nothing matches or there are no lines"], [2, "a usage error"]];
1525
1672
  var OPTIONS = {
1526
1673
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
1527
1674
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
@@ -1534,24 +1681,24 @@ function print(chosen, json) {
1534
1681
  if (json)
1535
1682
  printJson({ picked: chosen });
1536
1683
  else
1537
- process15.stdout.write(`${chosen.join(`
1684
+ process16.stdout.write(`${chosen.join(`
1538
1685
  `)}
1539
1686
  `);
1540
1687
  }
1541
1688
  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 {}'"] });
1689
+ 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 {}'"] });
1543
1690
  if (positionals.length > 0)
1544
1691
  badUsage("pick takes its lines on stdin, not as arguments");
1545
1692
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1546
1693
  if (height === undefined)
1547
1694
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1548
- if (process15.stdin.isTTY)
1695
+ if (process16.stdin.isTTY)
1549
1696
  badUsage("pipe the lines to pick on stdin");
1550
1697
  const lines = (await Bun.stdin.text()).split(`
1551
1698
  `).filter((line) => line !== "");
1552
1699
  if (lines.length === 0)
1553
1700
  fail("nothing to pick from", 1);
1554
- if (!process15.stderr.isTTY) {
1701
+ if (!process16.stderr.isTTY) {
1555
1702
  const query = (values.query ?? "").toLowerCase();
1556
1703
  const matching = lines.filter((line) => line.toLowerCase().includes(query));
1557
1704
  if (matching.length === 0)
@@ -1565,4 +1712,4 @@ async function main(args) {
1565
1712
  print(picked, values.json === true);
1566
1713
  return 0;
1567
1714
  }
1568
- process15.exitCode = await runMain({ name: "pick", run: main });
1715
+ process16.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.10.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.39.0"
39
39
  }
40
40
  }