Make Ctrl-k in Terminal copy to the system clipboard

copy/pasteterminal

I'd like whatever I last "cut" with Ctrl-k in Terminal to be available in my text editor when I hit Cmd-v. Is that possible? Or something close?

Update with additional explanation: Ctrl-k is by default in Terminal "delete to end of line". As well as deleting it puts the deleted text into the Terminal's clipboard (emacs "kill ring") and it can be retrieved with Ctrl-y. This is essentially a second clipboard separate from the system clipboard. I want to use the same clipboard for Terminal and for the rest of the system such as my text editor.

Best Answer

There's a very simple solution if you're willing to extend your shell's functionality. (Though it is pretty cool to see the automator solution)

Assuming you're using zsh, the current macOS default shell, then just add this to your ~/.zshrc profile.

pb-kill-line () {
  zle kill-line   # `kill-line` is the default ctrl+k binding
  echo -n $CUTBUFFER | pbcopy
}

zle -N pb-kill-line  # register our new function

bindkey '^K' pb-kill-line  # change the ctrl+k binding to use our new function

All this is doing is wrapping the Ctrl+k key binding so that in addition to performing its default behavior (kill-line), it also copies the relevant text into the system wide clipboard. The mysterious $CUTBUFFER contains the text that was just cut, and the macOS pbcopy utility puts whatever it receives from the STDIN into the system clipboard.

This solution was mostly just copied from https://gist.github.com/welldan97/5127861 ! My only original content is the explanation. :-)