Bash Emacs – How to Copy and Set Mark in Bash as in Emacs

bashinputrcline-editor

I would like to be able to copy and paste text in the command line in Bash using the same keyboard bindings that Emacs uses by default (i.e. using C-space for set-mark, M-w to copy text, C-y, M-y to paste it, etc.).

The GNU Bash documentation says that Bash comes with some of these key bindings set up by default.

For example, yanking (C-y) works by default on my terminal. However, I can't get the set-mark and copy commands to work, and they don't seem to be bound to any keys by default.

Usually, the way a user can define her own key bindings is to add them to .inputrc. So I looked and found the following bash functions in the documentation that I presume can help me define the Emacs-like behavior that I want (i.e. set-mark with C-space and copy with M-w).

copy-region-as-kill ()

Copy the text in the region to the
kill buffer, so it can be yanked right
away. By default, this command is
unbound.

and

set-mark (C-@)

Set the mark to the point. If a
numeric argument is supplied, the mark
is set to that position.

If I understand correctly, the above means that copy-region-as-kill is not bound to any keyboard sequence by default, while set-mark is bound to C-@ by default.

I tried C-@ on my terminal, but I don't think it runs set-mark because I don't see any text highlighted when I move my cursor. In any case, I tried adding keyboard bindings (M-w and C-) to the functions copy-region-as-kill and set-mark above in my .inputrc and then reloading it with C-x C-r, but this didn't work. I know that my other entries in .inputrc work because I have other user-defined keybindings defined in it.

Is there anything I am doing wrong? Am I missing anything?

Best Answer

It doesn't highlight the selection, but otherwise I think it works fine.

Try running

$ bind -p | grep copy-region-as-kill

to make sure that C-x C-r actually worked.

It should say:

"\ew": copy-region-as-kill

After that, it should work fine.

Example:

$ abc<C-Spc><C-a><M-w> def <C-y>

gives me

$ abc def abc

If you ever want to know where mark is, just do C-x C-x.

Example:

$ <C-Spc>abc<C-x><C-x>

will put the cursor back to where you set mark (the start of the line).

Also, I don't think you need to add the set-mark binding. I didn't.

$ bind -p | grep set-mark
"\C-@": set-mark
"\e ": set-mark
# vi-set-mark (not bound)

(note that most terminals send C-@ when C-Spc is pressed. I assume yours does too.)

If all this fails:

  • does Ctrl+Space work in emacs -nw on the same terminal?
  • do other Alt/Meta shortcuts work in bash?
Related Question