Created
May 11, 2024 20:37
-
-
Save DanSM-5/a5cc247419c7deff7a622570fe1d0e3e to your computer and use it in GitHub Desktop.
Edit prompt in editor (C-x C-e) for bash, zsh and powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Bash | |
# Credits: https://unix.stackexchange.com/a/684760 | |
# Difference with built-in one is that it won't run the | |
# command when closing the editor | |
__edit_command_no_execute () { | |
local editor="${EDITOR:-vim}" | |
local tmpf="$(mktemp)" | |
printf '%s\n' "$READLINE_LINE" >| "$tmpf" | |
"$editor" "$tmpf" | |
READLINE_LINE="$(cat "$tmpf")" | |
READLINE_POINT="${#READLINE_LINE}" | |
rm -f "$tmpf" &> /dev/null | |
} | |
bind -m emacs -x '"\C-o\C-e":__edit_command_no_execute' | |
bind -m vi -x '"\C-o\C-e":__edit_command_no_execute' | |
bind -m vi-insert -x '"\C-o\C-e":__edit_command_no_execute' | |
# Zsh | |
# Credits: https://gist.github.com/raven-rock/4fc8152f91eedf663755b65432f48ce5 | |
autoload -U edit-command-line | |
zle -N edit-command-line | |
bindkey '^x^e' edit-command-line | |
# Powershell | |
Set-PSReadLineKeyHandler -Chord 'ctrl+o,ctrl+e' -ScriptBlock { | |
$line = $cursor = $proc = $null | |
$editorArgs = @() | |
$editor = if ($env:EDITOR) { $env:EDITOR } | |
else { 'vim' } | |
try { | |
$tmpf = New-TemporaryFile | |
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $line, [ref] $cursor) | |
# If (n)vim, start at last line | |
if ( $editor -Like '*vim' ) { | |
$editorArgs += '+' | |
} | |
$line > $tmpf.FullName | |
$editorArgs += $tmpf.FullName | |
# Start editor and wait for it to close | |
$proc = Start-Process $editor -NoNewWindow -PassThru -ArgumentList $editorArgs | |
$proc.WaitForExit() | |
$proc = $null | |
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() | |
$content = (Get-Content -Path $tmpf.FullName -Raw -Encoding UTF8).Replace("`r","").Trim() | |
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($content) | |
# If you want to execute command on file closed: | |
# [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine() | |
} finally { | |
# Cleanup | |
$proc = $null | |
Remove-Item -Force $tmpf.FullName | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment