Skip to content

feat: commandline edit --accept to instantly execute command - #16193

Merged
sholderbach merged 2 commits into
nushell:mainfrom
stuartcarnie:immediate_accept
Aug 17, 2025
Merged

sholderbach merged 2 commits into
nushell:mainfrom
stuartcarnie:immediate_accept

Conversation

@stuartcarnie

@stuartcarnie stuartcarnie commented Jul 16, 2025 •

Copy link
Copy Markdown
Contributor

Description

Fixes

Revised

Depends on

Adds the --accept flag to the commandline command, to immediately accept the input.

Example use case: atuin

User-facing changes

Release notes summary - What our users need to know

The commandline edit command has a new flag --accept (or -A) which immediately executes the resulting commandline.

Tests + Formatting

I added two test cases that execute commandline edit -A.
There is also some documentation about their unintuitive expectations output.

After Submitting

The docs can be updated to the new flag:

--accept, -A: immediately execute the command (no additional return required)

Note

This PR will be revised if / when nushell/reedline#933 is accepted

Demo

asciicast

@stuartcarnie

stuartcarnie commented Jul 17, 2025 •

Copy link
Copy Markdown
Contributor Author

UPDATED

  • Adjusted for atuin 18.9.0, which replaced ATUIN_SHELL_ZSH with ATUIN_SHELL=zsh

Trialing with atuin

Using the following script, you can use this PR with atuin. It works just like the zsh version, such that pressing return will accept and execute the line, whereas tab or right arrow will leave the line open for editing.

# Source this in your ~/.config/nushell/config.nu
# minimum supported version = 0.93.0
module compat {
  export def --wrapped "random uuid -v 7" [...rest] { atuin uuid }
}
use (if not (
    (version).major > 0 or
    (version).minor >= 103
) { "compat" }) *

$env.ATUIN_SESSION = (random uuid -v 7 | str replace -a "-" "")
hide-env -i ATUIN_HISTORY_ID

# Magic token to make sure we don't record commands run by keybindings
let ATUIN_KEYBINDING_TOKEN = $"# (random uuid)"

let _atuin_pre_execution = {||
    if ($nu | get -i history-enabled) == false {
        return
    }
    let cmd = (commandline)
    if ($cmd | is-empty) {
        return
    }
    if not ($cmd | str starts-with $ATUIN_KEYBINDING_TOKEN) {
        $env.ATUIN_HISTORY_ID = (atuin history start -- $cmd)
    }
}

let _atuin_pre_prompt = {||
    let last_exit = $env.LAST_EXIT_CODE
    if 'ATUIN_HISTORY_ID' not-in $env {
        return
    }
    with-env { ATUIN_LOG: error } {
        if (version).minor >= 104 or (version).major > 0 {
            job spawn -t atuin {
                ^atuin history end $'--exit=($env.LAST_EXIT_CODE)' -- $env.ATUIN_HISTORY_ID | complete
            } | ignore
        } else {
            do { atuin history end $'--exit=($last_exit)' -- $env.ATUIN_HISTORY_ID } | complete
        }

    }
    hide-env ATUIN_HISTORY_ID
}

def _atuin_search_cmd [...flags: string] {
    [
        $ATUIN_KEYBINDING_TOKEN,
        ([
            `with-env { ATUIN_LOG: error, ATUIN_QUERY: (commandline), ATUIN_SHELL: zsh } {`,
                ([
                    'let output = (run-external atuin search',
                    ($flags | append [--interactive] | each {|e| $'"($e)"'}),
                    'e>| str trim)',
                ] | flatten | str join ' '),
                'if ($output | str starts-with "__atuin_accept__:") {',
                'commandline edit --accept ($output | str replace "__atuin_accept__:" "")',
                '} else {',
                'commandline edit $output',
                '}',
            `}`,
        ] | flatten | str join "\n"),
    ] | str join "\n"
}

$env.config = ($env | default {} config).config
$env.config = ($env.config | default {} hooks)
$env.config = (
    $env.config | upsert hooks (
        $env.config.hooks
        | upsert pre_execution (
            $env.config.hooks | get -i pre_execution | default [] | append $_atuin_pre_execution)
        | upsert pre_prompt (
            $env.config.hooks | get -i pre_prompt | default [] | append $_atuin_pre_prompt)
    )
)

$env.config = ($env.config | default [] keybindings)

$env.config = (
    $env.config | upsert keybindings (
        $env.config.keybindings
        | append {
            name: atuin
            modifier: control
            keycode: char_r
            mode: [emacs, vi_normal, vi_insert]
            event: { send: executehostcommand cmd: (_atuin_search_cmd) }
        }
    )
)

$env.config = (
    $env.config | upsert keybindings (
        $env.config.keybindings
        | append {
            name: atuin
            modifier: none
            keycode: up
            mode: [emacs, vi_normal, vi_insert]
            event: {
                until: [
                    {send: menuup}
                    {send: executehostcommand cmd: (_atuin_search_cmd '--shell-up-key-binding') }
                ]
            }
        }
    )
)

@stuartcarnie

Copy link
Copy Markdown
Contributor Author

I have updated both PRs to the latest

@VuiMuich

Copy link
Copy Markdown

When I run commandline edit --accept (run-external "atuin" "search" "--interactive" e>| str trim) it works perfectly fine, but not with the atuin initalisation script, I added this to unset the keybinds my regular config inits (but that should not be relevant for it not working, I guess):

@@ -79,6 +79,9 @@

 $env.config = ($env.config | default [] keybindings)

+# unset previously added default keybinds
+$env.config.keybindings = $env.config.keybindings | where name != atuin
+
 $env.config = (
     $env.config | upsert keybindings (
         $env.config.keybindings

@stuartcarnie

Copy link
Copy Markdown
Contributor Author

When I run commandline edit --accept (run-external "atuin" "search" "--interactive" e>| str trim) it works perfectly fine, but not with the atuin initalisation script, I added this to unset the keybinds my regular config inits (but that should not be relevant for it not working, I guess):

@@ -79,6 +79,9 @@

 $env.config = ($env.config | default [] keybindings)

+# unset previously added default keybinds
+$env.config.keybindings = $env.config.keybindings | where name != atuin
+
 $env.config = (
     $env.config | upsert keybindings (
         $env.config.keybindings

The existing initialisation script is expected to work fine, but won't auto-accept until it is updated. If this PR is accepted, I will open a PR to Atuin to resolve that.

@VuiMuich

VuiMuich commented Jul 28, 2025 •

Copy link
Copy Markdown

Sorry, for being imprecise, the keybindings seem to be correct with the applied script from your post and the old keybindings removed with $env.config.keybindings | where name == atuin | to json (I added to json so it is nicer readable here on github):

[
  {
    "name": "atuin",
    "modifier": "control",
    "keycode": "char_r",
    "event": {
      "send": "executehostcommand",
      "cmd": "# f4494cb6-57bc-4482-973b-ea700d982f63\nwith-env { ATUIN_LOG: error, ATUIN_QUERY: (commandline), ATUIN_SHELL_ZSH: t } {\nlet output = (run-external atuin search \"--interactive\" e>| str trim)\nif ($output | str starts-with \"__atuin_accept__:\") {\ncommandline edit --accept ($output | str replace \"__atuin_accept__:\" \"\")\n} else {\ncommandline edit $output\n}\n}"
    },
    "mode": [
      "emacs",
      "vi_normal",
      "vi_insert"
    ]
  },
  {
    "name": "atuin",
    "modifier": "none",
    "keycode": "up",
    "event": {
      "until": [
        {
          "send": "menuup"
        },
        {
          "send": "executehostcommand",
          "cmd": "# f4494cb6-57bc-4482-973b-ea700d982f63\nwith-env { ATUIN_LOG: error, ATUIN_QUERY: (commandline), ATUIN_SHELL_ZSH: t } {\nlet output = (run-external atuin search \"--shell-up-key-binding\" \"--interactive\" e>| str trim)\nif ($output | str starts-with \"__atuin_accept__:\") {\ncommandline edit --accept ($output | str replace \"__atuin_accept__:\" \"\")\n} else {\ncommandline edit $output\n}\n}"
        }
      ]
    },
    "mode": [
      "emacs",
      "vi_normal",
      "vi_insert"
    ]
  }
]

So, to me this looks like the keybinds should be correct, yet I don't get immediate accept behaviour.

Sure I can wait patiently until this gets merged, I just wanted to help by providing a report of it working "in the wild".

Edit:
Another observation I just made, is that with the script of your post above, atuin is tracking the atuin search command itself:
2025-07-28-082955_836x210_scrot

@stuartcarnie

Copy link
Copy Markdown
Contributor Author

When I run commandline edit --accept (run-external "atuin" "search" "--interactive" e>| str trim) it works perfectly fine

This is an important point – you can confirm it is working when you run it explicitly.

What version of Atuin are you running? It may be that you are not running a version compatible with the script I provided. An example might be that it isn't returning the __atuin_accept__: prefix, which is required.

atuin --version
atuin 18.7.1

Another observation I just made, is that with the script of your post above, atuin is tracking the atuin search command itself:

The script has code explicitly to ignore that:

# Magic token to make sure we don't record commands run by keybindings
let ATUIN_KEYBINDING_TOKEN = $"# (random uuid)"
...

Comment thread tests/repl/test_commandline.rs Outdated
Comment on lines +144 to +151
#[test]
fn commandline_test_accept() -> TestResult {
// Explanation: run_test captures a command's output.
// But `--accept` executes a new command that then outputs "accepted".
// So `commandline edit -A` doesn't have any output.
// Therefore the additional test that pipes to `commandline`
run_test("commandline edit --accept \"print accepted\"", "")
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not really sure that this is a useful test

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will remove that

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed

Comment thread crates/nu-cli/src/repl.rs Outdated
// If the engine is configured to immediately
line_editor = if engine_state
.immediately_accept
.compare_exchange(true, false, Ordering::Acquire, Ordering::Relaxed)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this compare_exchange is clever!

@stuartcarnie

Copy link
Copy Markdown
Contributor Author

Thanks for the initial review @132ikl! Now that the PR for reedline has been merged, I will update this PR

@stuartcarnie
stuartcarnie force-pushed the immediate_accept branch 2 times, most recently from e92befe to 9803370 Compare July 29, 2025 22:15

@sholderbach sholderbach left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My memory ordering knowledge get's rusty quickly so I am not quite sure if it should be either Release and Acquire or could suffice with a Relaxed on both ends.

Trying to assume the worst case, I think in a multithreaded environment commandline as implemented currently can tear between the value set when passing --accept and further edits set by commandline from different threads. Not sure if we want to accept that.

Comment on lines +72 to +75
engine_state
.immediately_accept
.store(true, Ordering::Relaxed);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how much it matters in practice, but shouldn't this be Ordering::Release which would imply a happens-before relationship for the writes in the critical section of engine_state.repl_state?

In nu-cli/repl.rs the compare_exchange which you set to Acquire is ahead of the read of the repl_state mutex which happens right before the call into Reedline::read_line.

I guess for singular uses of commandline --accept the mutex should ensure ordering in itself, as the MutexGuard::drop happens after the store.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good questions! I agree that the mutex guarantees overall ordering.

As for the use of Relaxed, for this specific flag, we don't care about other memory operations, because the flag itself is used in isolation and consumers of the flag are not dependent on other operations happening before this.

Same for the compare_exchange, which is used in isolation to determine whether we need to call the line_editor.with_immediately_accept API, which is also configured in isolation.

@VuiMuich

Copy link
Copy Markdown

atuin 18.7.1

This is exactly my atuin version.

Another observation I just made, is that with the script of your post above, atuin is tracking the atuin search command itself:

The script has code explicitly to ignore that:

# Magic token to make sure we don't record commands run by keybindings

let ATUIN_KEYBINDING_TOKEN = $"# (random uuid)"

...

Maybe there is something off with my general nushell config, I'll see if I can test this on another system or in a VM to rule this out.

@VuiMuich

Copy link
Copy Markdown

I finally found the issue:
I was under the impression, that the script would set enter_accept for atuin, but apparently it does not. So setting enter_accept = true in my atuin config fixed it.

Now working like a charm, thanks!!

@stuartcarnie

Copy link
Copy Markdown
Contributor Author

Now working like a charm, thanks!!

Great news!

@132ikl

132ikl commented Aug 12, 2025

Copy link
Copy Markdown
Member

@sholderbach are you satisfied here? if yes, let's get this merged

@sholderbach

sholderbach commented Aug 12, 2025 •

Copy link
Copy Markdown
Member

Sadly no. I don't think we should ship it in a way that background jobs can overwrite what gets evaled:

0..10 | each {job spawn {commandline edit --replace "calc.exe"}}; commandline edit --accept --replace "print hello"
grafik

While this logic is sound assuming no background tasks and just the REPL with its hooks, we now have multiple threads writing the content and the request for eval separately.

The minimal fix would be to say that all other commandline edits have to reset the accept flag first. If there is a race on the buffer content it wouldn't execute.

Alternative routes would be to disallow writing of the buffer in non primary tasks or have an elaborate queue of edits but I am not sure how much we want to bring into that. We live in a multithreaded environment but the REPL itself is a pretty sequential thing.

@sholderbach sholderbach left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For it to be considered background-job-safe we need to consider repl_state and immediately_accept together.

@stuartcarnie

stuartcarnie commented Aug 14, 2025 •

Copy link
Copy Markdown
Contributor Author

@sholderbach thanks – I wondered that too, given these commands can be executed on multiple threads and manipulate shared state, but it didn't seem obvious how to address it. You mentioned a queue, which makes the most sense, but definitely beyond the scope of this PR.

The minimal fix would be to say that all other commandline edits have to reset the accept flag first. If there is a race on the buffer content it wouldn't execute.

Are you saying this is enough to have the PR accepted? That is, I'll update the edit.rs to always set or clear the immediately_accept flag based on whether --accept is provided.

@stuartcarnie

stuartcarnie commented Aug 14, 2025 •

Copy link
Copy Markdown
Contributor Author

@sholderbach / @132ikl I've updated the logic:

  • ReplState now stores an additional flag, accept, treating it as a single unit
  • flush_engine_state_repl_buffer reads and resets the accept

I have run it many times and cannot get it to produce "no" in the following:

0..10 | each {job spawn {commandline edit --replace "print no"}}; commandline edit --accept --replace "print hello"
CleanShot 2025-08-15 at 06 08 37@2x

@sholderbach sholderbach left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for iterating on this.

Comment thread crates/nu-cli/src/repl.rs Outdated

start_time = std::time::Instant::now();
line_editor = line_editor.with_transient_prompt(transient_prompt);
line_editor = if engine_state.immediately_accept {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There shouldn't be a need for a separate immediately_accept if it is part of the repl_state, right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I kept these separate is because the engine_state.repl_state is parsed (and therefore set) in the parse_operation function:

match parse_operation(repl_cmd_line_text.clone(), engine_state, &stack) {

When executing commandline edit --accept, after this call, ReplState will be updated with changes to the buffer and the accept flag set to true. When flush_engine_state_repl_buffer is called, it sends any changes to the buffer, from the commandline edit command:

line_editor.run_edit_commands(&[
EditCommand::Clear,
EditCommand::InsertString(repl.buffer.to_string()),
EditCommand::MoveToPosition {
position: repl.cursor_pos,
select: false,
},
]);

and then clears its state:

repl.buffer = "".to_string();
repl.cursor_pos = 0;

You mentioned:

we need to consider repl_state and immediately_accept together

which I agree is more correct. That means that accept should be used with the next call to line_editor.read_line. In that case, I'm taking the value of accept and storing it for the next iteration (and read_line call) and clearing it here. This ensures that from when the lock of repl_state is released and when we call loop_iteration the next time, we take and clear the immediately_accept value from the last flush.

An alternative is we could mutate the line_editor that is passed in, if repl_state.accept is true. Something like:

*line_editor = line_editor.with_immediately_accept(repl.accept);

or return the line_editor from flush_engine_state_repl_buffer, so that it is assigned at the call site:

line_editor = flush_engine_state_repl_buffer(engine_state, &mut line_editor);

In either case, we always clear the accept flag after calling line_editor.read_line:

    line_editor = line_editor
        // CLEAR STACK-REFERENCE 1
        .with_highlighter(Box::<NoOpHighlighter>::default())
        // CLEAR STACK-REFERENCE 2
        .with_completer(Box::<DefaultCompleter>::default())
        // Ensure immediately accept is always cleared
        .with_immediately_accept(false);

Comment thread crates/nu-cli/src/repl.rs Outdated
Comment on lines +1148 to +1149
engine_state.immediately_accept = repl.accept;
repl.accept = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If flush_engine_state_repl_buffer is the only place we alter the buffer, I think it would make sense to place the .with_immediately_accept there as well, reading directly from repl_state.accept. Then it would be guaranteed that any alterations being observed through the whole chain of hooks etc. would be consistent, and no bugs could be introduced by someone in the future unintentionally modifying engine_state.immediately_accept

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good – I'll make that change 👍🏻

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sholderbach done! Can confirm the test script is still consistent:

0..10 | each {job spawn {commandline edit --replace "print no"}}; commandline edit --accept --replace "print hello"
print hello

Instead of storing the immediately_accept flag in EngineState, handle
it directly when flushing the REPL buffer by returning a modified
Reedline instance. This simplifies the state management and removes
the need for a persistent flag in EngineState, making the code more
maintainable and reducing coupling between components.

@sholderbach sholderbach left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, looks good. Thanks for iterating with us

@sholderbach
sholderbach merged commit fd4a042 into nushell:main Aug 17, 2025
@github-actions github-actions Bot added this to the v0.107.0 milestone Aug 17, 2025
@stuartcarnie
stuartcarnie deleted the immediate_accept branch August 18, 2025 09:08
@WindSoilder WindSoilder added the notes:additions Noted in "Additions" section label Aug 20, 2025
@NotTheDr01ds NotTheDr01ds added the notes:ready Indicates Ready for Release notes label Aug 27, 2025
@wjarka

wjarka commented Oct 20, 2025

Copy link
Copy Markdown

I finally found the issue: I was under the impression, that the script would set enter_accept for atuin, but apparently it does not. So setting enter_accept = true in my atuin config fixed it.

Now working like a charm, thanks!!

Did it also fixed showing the history item for atuin search? This is happening to me as well and I have enter_accept set to true

@wjarka

wjarka commented Oct 20, 2025

Copy link
Copy Markdown

@VuiMuich ^^

@VuiMuich

Copy link
Copy Markdown

@wjarka I am not sure I understand correctly what you mean.
Is your question about atuin putting a command from the history in the prompt?

@wjarka

wjarka commented Oct 20, 2025

Copy link
Copy Markdown

@VuiMuich yes.

0s 42s ago # 0414a6d3-2f84-4d6f-b088-7155f2e1b5ee^Jwith-env { ATUIN_LOG: error, ATUIN_QUERY: (commandline), ATUIN_SHELL_ZSH: t } {^Jlet output = (run-e
[ DIRECTORY ]

0414a6d3-2f84-4d6f-b088-7155f2e1b5ee

with-env { ATUIN_LOG: error, ATUIN_QUERY: (commandline), ATUIN_SHELL_ZSH: t } {
let output = (run-external atuin search "--shell-up-key-binding" "--interactive" e>| str trim)
if ($output | str starts-with "atuin_accept:") {

This is what I am getting

@wjarka

wjarka commented Oct 20, 2025

Copy link
Copy Markdown

Alright, for anyone having this issue - it turned out I had the original init.nu created when I set up atuin still active. So it was the original file adding that item, not the one proposed here.

Fixed.

@stuartcarnie

Copy link
Copy Markdown
Contributor Author

📣 Heads up that atuin 18.9.0 changed the shell variable from ATUIN_SHELL_ZSH to a generic ATUIN_SHELL=<shell>.

I've updated the posted script:

#16193 (comment)

stuartcarnie added a commit to stuartcarnie/atuin that referenced this pull request Oct 21, 2025
ellie pushed a commit to atuinsh/atuin that referenced this pull request Oct 21, 2025
# Summary

Adjust the Nushell script to check the version and enable accept support
when Nushell 0.106.0 or greater is found.

See: nushell/nushell#16193

<!-- Thank you for making a PR! Bug fixes are always welcome, but if
you're adding a new feature or changing an existing one, we'd really
appreciate if you open an issue, post on the forum, or drop in on
Discord -->

## Checks
- [x] I am happy for maintainers to push small adjustments to this PR,
to speed up the review cycle
- [x] I have checked that there are no existing pull requests for the
same thing
@ThomasCode92

Copy link
Copy Markdown

Alright, for anyone having this issue - it turned out I had the original init.nu created when I set up atuin still active. So it was the original file adding that item, not the one proposed here.

Fixed.

How did you fix it?

@c-git

c-git commented Feb 17, 2026

Copy link
Copy Markdown

Alright, for anyone having this issue - it turned out I had the original init.nu created when I set up atuin still active. So it was the original file adding that item, not the one proposed here.
Fixed.

How did you fix it?

When I started using nushell my atuin was older (I think v18.08, while the current version is v18.12.1) and pressing enter wasn't executing the command for me. It works now for me and I:

  • I installed the latest version of atuin (v18.12.1 right now)
  • Then deleted the old config (which I hadn't changed at ~/.local/share/atuin/init.nu)
  • Then regenerated the config from atuin using atuin init nu | save ~/.local/share/atuin/init.nu

PS. Don't recall where I got the save command originally, I got it from my history today

@VuiMuich

VuiMuich commented Feb 17, 2026 •

Copy link
Copy Markdown

You can put atuin init nu | save --force ~/.local/share/atuin/init.nu in your env.nu and always will have a config matching your atuin version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

notes:additions Noted in "Additions" section notes:ready Indicates Ready for Release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants