Skip to content

Instantly share code, notes, and snippets.

@belotn
Last active October 5, 2021 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belotn/35a77afd4b2e5e9c96c90e5bb6d469eb to your computer and use it in GitHub Desktop.
Save belotn/35a77afd4b2e5e9c96c90e5bb6d469eb to your computer and use it in GitHub Desktop.
Add Key Handler in VIMode Command set to $EditKey or Space by default to open commandline with console editor set in $EDITOR
Set-PSReadLineKeyHandler -VIMode Command -Key $(@{$False="\";$True=$EditKey}[$(Test-Path Variable:EditKey)]) -ScriptBlock {
if( Get-Command $EDITOR){
# Grab BufferLine
$Line = $Null
$Cursor = $Null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$Line, [ref]$Cursor)
# Launch Editor with temporary file
$File = New-TemporaryFile
Set-Content -Path $File -Value $Line
if($EDITOR -match '[ng]?vim?'){
Start-Process -wait $EDITOR -ArgumentList @($File, '-c ":set ft=ps1"', '-c ":set syntax=ps1"') -NoNewWindow
}elseif($EDITOR -eq 'nano.exe'){
Start-Process -wait $EDITOR -ArgumentList $File -NoNewWindow
}else{
Start-Process -wait $EDITOR -ArgumentList $File -NoNewWindow
}
$Line = get-content $File
# Write Command at prompt
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
$Line |% {
[Microsoft.Powershell.PSConsoleReadLine]::Insert( $_.replace("`t",' ') + "`n" )
}
Remove-Item $File
}else {
throw [System.IO.FileNotFoundException] "$Editor not found."
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment