···11-> A video showcasing how pnpm autocompletions work on a test CLI command like `my-cli`
22-33-# tab
44-55-> Instant feedback for your CLI tool when hitting [TAB] in your terminal
66-77-As CLI tooling authors, if we can spare our users a second or two by not checking the documentation or writing the `-h` option, we're doing them a huge favor. The unconscious loves hitting the [TAB] key. It always expects feedback. So it feels disappointing when hitting that key in the terminal but then nothing happens. That frustration is apparent across the whole JavaScript CLI tooling ecosystem.
88-99-Autocompletions are the solution to not break the user's flow. The issue is they're not simple to add. `zsh` expects them in one way, and `bash` in another way. Then where do we provide them so the shell environment parses them? Too many headaches to ease the user's experience. Whether it's worth it or not is out of the question. Because tab is the solution to this complexity.
1010-1111-`my-cli.ts`:
1212-1313-```typescript
1414-import t from '@bomb.sh/tab';
1515-1616-t.name('my-cli');
1717-1818-t.command('start', 'start the development server');
1919-2020-if (process.argv[2] === 'complete') {
2121- const [shell, ...args] = process.argv.slice(3);
2222- if (shell === '--') {
2323- t.parse(args);
2424- } else {
2525- t.setup(shell, x);
2626- }
2727-}
2828-```
2929-3030-This `my-cli.ts` would be equipped with all the tools required to provide autocompletions.
3131-3232-```bash
3333-node my-cli.ts complete -- "st"
3434-```
3535-3636-```
3737-start start the development server
3838-:0
3939-```
4040-4141-This output was generated by the `t.parse` method to autocomplete "st" to "start".
4242-4343-Obviously, the user won't be running that command directly in their terminal. They'd be running something like this.
4444-4545-```bash
4646-source <(node my-cli.ts complete zsh)
4747-```
4848-4949-Now whenever the shell sees `my-cli`, it would bring the autocompletions we wrote for this CLI tool. The `node my-cli.ts complete zsh` part would output the zsh script that loads the autocompletions provided by `t.parse` which then would be executed using `source`.
5050-5151-The autocompletions only live through the current shell session. To set them up across all terminal sessions, the autocompletion script should be injected in the `.zshrc` file.
5252-5353-```bash
5454-my-cli complete zsh > ~/completion-for-my-cli.zsh && echo 'source ~/completion-for-my-cli.zsh' >> ~/.zshrc
5555-```
5656-5757-Or
5858-5959-```bash
6060-echo 'source <(npx --offline my-cli complete zsh)' >> ~/.zshrc
6161-```
6262-6363-This is an example of autocompletions on a global CLI command that is usually installed using the `-g` flag (e.g. `npm add -g my-cli`) which is available across the computer.
6464-6565----
6666-6767-While working on tab, we came to the realization that most JavaScript CLIs are not global CLI commands but rather, per-project dependencies.
6868-6969-For instance, Vite won't be installed globally and instead it'd be always installed on a project. Here's an example usage:
7070-7171-```bash
7272-pnpm vite dev
7373-```
7474-7575-Rather than installing it globally. This example is pretty rare:
7676-7777-```bash
7878-vite dev
7979-```
8080-8181-So in this case, a computer might have hundreds of Vite instances each installed separately and potentially from different versions on different projects.
8282-8383-We were looking for a fluid strategy that would be able to load the autocompletions from each of these dependencies on a per-project basis.
8484-8585-And that made us develop our own autocompletion abstraction over npm, pnpm and yarn. This would help tab identify which binaries are available in a project and which of these binaries provide autocompletions. So the user would not have to `source` anything or inject any script in their `.zshrc`.
8686-8787-They'd only have to run this command once and inject it in their shell config.
8888-8989-```bash
9090-npx @bomb.sh/tab pnpm zsh
9191-```
9292-9393-These autocompletions on top of the normal autocompletions that these package managers provide are going to be way more powerful.
9494-9595-These new autocompletions on top of package managers would help us with autocompletions on commands like `pnpm vite` and other global or per-project binaries. The only requirement would be that the npm binary itself would be a tab-compatible binary.
9696-9797-What is a tab-compatible binary? It's a tool that provides the `complete` subcommand that was showcased above. Basically any CLI tool that uses tab for its autocompletions is a tab-compatible binary.
9898-9999-```bash
100100-pnpm my-cli complete --
101101-```
102102-103103-```
104104-start start the development server
105105-:0
106106-```
107107-108108-We are planning to maintain these package manager autocompletions on our own and turn them into full-fledged autocompletions that touch on every part of our package managers.
+131-167
README.md
···11+> A video showcasing how pnpm autocompletions work on a test CLI command
22+> like `my-cli`
33+14# tab
2533-Shell autocompletions are largely missing in the javascript cli ecosystem. This tool is an attempt to make autocompletions come out of the box for any cli tool.
66+Shell autocompletions are largely missing in the JavaScript CLI ecosystem. Tab provides a simple API for adding autocompletions to any JavaScript CLI tool.
4755-Tools like git and their autocompletion experience inspired us to build this tool and make the same ability available for any javascript cli project. Developers love hitting the tab key, hence why they prefer tabs over spaces.
88+Additionally, tab supports autocompletions for `pnpm`, `npm`, `yarn`, and `bun`.
6977-## Examples
1010+As CLI tooling authors, if we can spare our users a second or two by not checking documentation or writing the `-h` flag, we're doing them a huge favor. The unconscious mind loves hitting the [TAB] key and always expects feedback. When nothing happens, it breaks the user's flow - a frustration apparent across the whole JavaScript CLI tooling ecosystem.
81199-Check out the [examples directory](./examples) for complete examples of using Tab with different command-line frameworks:
1212+Tab solves this complexity by providing autocompletions that work consistently across `zsh`, `bash`, `fish`, and `powershell`.
10131111-- [CAC](./examples/demo.cac.ts)
1212-- [Citty](./examples/demo.citty.ts)
1313-- [Commander.js](./examples/demo.commander.ts)
1414+## Installation
14151515-## Usage
1616+```bash
1717+npm install @bomb.sh/tab
1818+# or
1919+pnpm add @bomb.sh/tab
2020+# or
2121+yarn add @bomb.sh/tab
2222+# or
2323+bun add @bomb.sh/tab
2424+```
2525+2626+## Quick Start
2727+2828+Add autocompletions to your CLI tool:
16291717-```ts
1818-import { Completion, script } from '@bomb.sh/tab';
3030+```typescript
3131+import t from '@bomb.sh/tab';
19322020-const name = 'my-cli';
2121-const completion = new Completion();
3333+// Define your CLI structure
3434+const devCmd = t.command('dev', 'Start development server');
3535+devCmd.option('port', 'Specify port', (complete) => {
3636+ complete('3000', 'Development port');
3737+ complete('8080', 'Production port');
3838+});
22392323-completion.addCommand(
2424- 'start',
2525- 'Start the application',
2626- async (previousArgs, toComplete, endsWithSpace) => {
2727- // suggestions
2828- return [
2929- { value: 'dev', description: 'Start in development mode' },
3030- { value: 'prod', description: 'Start in production mode' },
3131- ];
4040+// Handle completion requests
4141+if (process.argv[2] === 'complete') {
4242+ const shell = process.argv[3];
4343+ if (shell === '--') {
4444+ const args = process.argv.slice(4);
4545+ t.parse(args);
4646+ } else {
4747+ t.setup('my-cli', 'node my-cli.js', shell);
3248 }
3333-);
4949+}
5050+```
5151+5252+Test your completions:
5353+5454+```bash
5555+node my-cli.js complete -- dev --port=<TAB>
5656+# Output: --port=3000 Development port
5757+# --port=8080 Production port
5858+```
5959+6060+Install for users:
6161+6262+```bash
6363+# One-time setup
6464+source <(my-cli complete zsh)
6565+6666+# Permanent setup
6767+my-cli complete zsh > ~/.my-cli-completion.zsh
6868+echo 'source ~/.my-cli-completion.zsh' >> ~/.zshrc
6969+```
34703535-completion.addOption(
3636- 'start',
3737- '--port',
3838- 'Specify the port number',
3939- async (previousArgs, toComplete, endsWithSpace) => {
4040- return [
4141- { value: '3000', description: 'Development port' },
4242- { value: '8080', description: 'Production port' },
4343- ];
4444- }
4545-);
7171+## Package Manager Completions
46724747-// a way of getting the executable path to pass to the shell autocompletion script
4848-function quoteIfNeeded(path: string) {
4949- return path.includes(' ') ? `'${path}'` : path;
5050-}
5151-const execPath = process.execPath;
5252-const processArgs = process.argv.slice(1);
5353-const quotedExecPath = quoteIfNeeded(execPath);
5454-const quotedProcessArgs = processArgs.map(quoteIfNeeded);
5555-const quotedProcessExecArgs = process.execArgv.map(quoteIfNeeded);
5656-const x = `${quotedExecPath} ${quotedProcessExecArgs.join(' ')} ${quotedProcessArgs[0]}`;
7373+As mentioned earlier, tab provides completions for package managers as well:
57745858-if (process.argv[2] === '--') {
5959- // autocompletion logic
6060- await completion.parse(process.argv.slice(2), 'start'); // TODO: remove "start"
6161-} else {
6262- // process.argv[2] can be "zsh", "bash", "fish", "powershell"
6363- script(process.argv[2], name, x);
6464-}
7575+```bash
7676+# Generate and install completion scripts
7777+npx @bomb.sh/tab pnpm zsh > ~/.pnpm-completion.zsh && echo 'source ~/.pnpm-completion.zsh' >> ~/.zshrc
7878+npx @bomb.sh/tab npm bash > ~/.npm-completion.bash && echo 'source ~/.npm-completion.bash' >> ~/.bashrc
7979+npx @bomb.sh/tab yarn fish > ~/.config/fish/completions/yarn.fish
8080+npx @bomb.sh/tab bun powershell > ~/.bun-completion.ps1 && echo '. ~/.bun-completion.ps1' >> $PROFILE
6581```
66826767-Now your user can run `source <(my-cli complete zsh)` and they will get completions for the `my-cli` command using the [autocompletion server](#autocompletion-server).
8383+Example in action:
8484+8585+```bash
8686+pnpm install --reporter=<TAB>
8787+# Shows: append-only, default, ndjson, silent (with descriptions)
8888+8989+yarn add --emoji=<TAB>
9090+# Shows: true, false
9191+```
68926969-## Adapters
9393+## Framework Adapters
70947171-Since we are heavy users of tools like `cac` and `citty`, we have created adapters for both of them. Ideally, tab would be integrated internally into these tools, but for now, this is a good compromise.
9595+Tab provides adapters for popular JavaScript CLI frameworks.
72967373-### `@bomb.sh/tab/cac`
9797+### CAC Integration
74987575-```ts
9999+```typescript
76100import cac from 'cac';
77101import tab from '@bomb.sh/tab/cac';
7810279103const cli = cac('my-cli');
801048181-cli.command('dev', 'Start dev server').option('--port <port>', 'Specify port');
105105+// Define your CLI
106106+cli
107107+ .command('dev', 'Start dev server')
108108+ .option('--port <port>', 'Specify port')
109109+ .option('--host <host>', 'Specify host');
82110111111+// Initialize tab completions
83112const completion = tab(cli);
841138585-// Get the dev command completion handler
8686-const devCommandCompletion = completion.commands.get('dev');
8787-8888-// Get and configure the port option completion handler
8989-const portOptionCompletion = devCommandCompletion.options.get('--port');
9090-portOptionCompletion.handler = async (
9191- previousArgs,
9292- toComplete,
9393- endsWithSpace
9494-) => {
9595- return [
9696- { value: '3000', description: 'Development port' },
9797- { value: '8080', description: 'Production port' },
9898- ];
9999-};
114114+// Add custom completions for option values
115115+completion.commands.get('dev')?.options.get('--port')!.handler = async () => [
116116+ { value: '3000', description: 'Development port' },
117117+ { value: '8080', description: 'Production port' },
118118+];
100119101120cli.parse();
102121```
103122104104-Now autocompletion will be available for any specified command and option in your cac instance. If your user writes `my-cli dev --po`, they will get suggestions for the `--port` option. Or if they write `my-cli d` they will get suggestions for the `dev` command.
123123+### Citty Integration
105124106106-Suggestions are missing in the adapters since yet cac or citty do not have a way to provide suggestions (tab just came out!), we'd have to provide them manually. Mutations do not hurt in this situation.
107107-108108-### `@bomb.sh/tab/citty`
109109-110110-```ts
111111-import citty, { defineCommand, createMain } from 'citty';
125125+```typescript
126126+import { defineCommand, createMain } from 'citty';
112127import tab from '@bomb.sh/tab/citty';
113128114129const main = defineCommand({
115115- meta: {
116116- name: 'my-cli',
117117- description: 'My CLI tool',
130130+ meta: { name: 'my-cli', description: 'My CLI tool' },
131131+ subCommands: {
132132+ dev: defineCommand({
133133+ meta: { name: 'dev', description: 'Start dev server' },
134134+ args: {
135135+ port: { type: 'string', description: 'Specify port' },
136136+ host: { type: 'string', description: 'Specify host' },
137137+ },
138138+ }),
118139 },
119140});
120141121121-const devCommand = defineCommand({
122122- meta: {
123123- name: 'dev',
124124- description: 'Start dev server',
125125- },
126126- args: {
127127- port: { type: 'string', description: 'Specify port' },
128128- },
129129-});
130130-131131-main.subCommands = {
132132- dev: devCommand,
133133-};
134134-142142+// Initialize tab completions
135143const completion = await tab(main);
136144137137-// TODO: addHandler function to export
138138-const devCommandCompletion = completion.commands.get('dev');
139139-140140-const portOptionCompletion = devCommandCompletion.options.get('--port');
141141-142142-portOptionCompletion.handler = async (
143143- previousArgs,
144144- toComplete,
145145- endsWithSpace
146146-) => {
147147- return [
148148- { value: '3000', description: 'Development port' },
149149- { value: '8080', description: 'Production port' },
150150- ];
151151-};
145145+// Add custom completions
146146+completion.commands.get('dev')?.options.get('--port')!.handler = async () => [
147147+ { value: '3000', description: 'Development port' },
148148+ { value: '8080', description: 'Production port' },
149149+];
152150153151const cli = createMain(main);
154152cli();
155153```
156154157157-### `@bomb.sh/tab/commander`
155155+### Commander.js Integration
158156159159-```ts
157157+```typescript
160158import { Command } from 'commander';
161159import tab from '@bomb.sh/tab/commander';
162160163161const program = new Command('my-cli');
164162program.version('1.0.0');
165163166166-// Add commands
164164+// Define commands
167165program
168166 .command('serve')
169167 .description('Start the server')
···173171 console.log('Starting server...');
174172 });
175173176176-// Initialize tab completion
174174+// Initialize tab completions
177175const completion = tab(program);
178176179179-// Configure custom completions
180180-for (const command of completion.commands.values()) {
181181- if (command.name === 'serve') {
182182- for (const [option, config] of command.options.entries()) {
183183- if (option === '--port') {
184184- config.handler = () => {
185185- return [
186186- { value: '3000', description: 'Default port' },
187187- { value: '8080', description: 'Alternative port' },
188188- ];
189189- };
190190- }
191191- }
192192- }
193193-}
177177+// Add custom completions
178178+completion.commands.get('serve')?.options.get('--port')!.handler = async () => [
179179+ { value: '3000', description: 'Default port' },
180180+ { value: '8080', description: 'Alternative port' },
181181+];
194182195183program.parse();
196184```
197185198198-## Recipe
199199-200200-`source <(my-cli complete zsh)` won't be enough since the user would have to run this command each time they spin up a new shell instance.
201201-202202-We suggest this approach for the end user that you as a maintainer might want to push.
203203-204204-```
205205-my-cli completion zsh > ~/completion-for-my-cli.zsh
206206-echo 'source ~/completion-for-my-cli.zsh' >> ~/.zshrc
207207-```
208208-209209-For other shells:
186186+Tab uses a standardized completion protocol that any CLI can implement:
210187211188```bash
212212-# Bash
213213-my-cli complete bash > ~/.bash_completion.d/my-cli
214214-echo 'source ~/.bash_completion.d/my-cli' >> ~/.bashrc
215215-216216-# Fish
217217-my-cli complete fish > ~/.config/fish/completions/my-cli.fish
189189+# Generate shell completion script
190190+my-cli complete zsh
218191219219-# PowerShell
220220-my-cli complete powershell > $PROFILE.CurrentUserAllHosts
192192+# Parse completion request (called by shell)
193193+my-cli complete -- install --port=""
221194```
222195223223-## Autocompletion Server
196196+**Output Format:**
224197225225-By integrating tab into your cli, your cli would have a new command called `complete`. This is where all the magic happens. And the shell would contact this command to get completions. That's why we call it the autocompletion server.
226226-227227-```zsh
228228-my-cli complete -- --po
229229---port Specify the port number
230230-:0
198198+```
199199+--port=3000 Development port
200200+--port=8080 Production port
201201+:4
231202```
232203233233-The autocompletion server can be a standard to identify whether a package provides autocompletions. Whether running `tool complete --` would result in an output that ends with `:{Number}` (matching the pattern `/:\d+$/`).
234234-235235-In situations like `my-cli dev --po` you'd have autocompletions! But in the case of `pnpm my-cli dev --po` which is what most of us use, tab does not inject autocompletions for a tool like pnpm.
236236-237237-Since pnpm already has its own autocompletion [script](https://pnpm.io/completion), this provides the opportunity to check whether a package provides autocompletions and use those autocompletions if available.
238238-239239-This would also have users avoid injecting autocompletions in their shell config for any tool that provides its own autocompletion script, since pnpm would already support proxying the autocompletions out of the box.
204204+## Documentation
240205241241-Other package managers like `npm` and `yarn` can decide whether to support this or not too for more universal support.
206206+See [bombshell docs](https://bomb.sh/docs/tab/).
242207243243-## Inspiration
208208+## Contributing
244209245245-- git
246246-- [cobra](https://github.com/spf13/cobra/blob/main/shell_completions.go), without cobra, tab would have took 10x longer to build
210210+We welcome contributions! Tab's architecture makes it easy to add support for new package managers or CLI frameworks.