6

I can not find a way to do that from bash. So Is there a way to define a bash readline shortcut that will insert a dynamically generated string at the position of the cursor?

E.g., I want to insert date:

bind '"\C-xx": my-dynamical-date'

aaa  bbb
--------
    ^ cursor is here

# After pressing "\C-xx":

aaa Sun Apr 22 22:19:00 CST 2018 bbb
------------------------------------
                                ^ cursor is here

So how to define my-dynamical-date readline command?

terdon
  • 242,166

2 Answers2

9

A bit silly but it could be something like this:

bind '"\C-xx":"$(date) \e\C-e\ef\ef\ef\ef\ef"'

It first enters a literal $(date), then calls shell-expand-line and then moves 5 words forward.

To save the keybinding, add the following to inputrc:

"\C-xx":"$(date) \e\C-e\ef\ef\ef\ef\ef"
  • Nice! Any idea how to do this in .inputrc? I tried but couldn't figure out how to have a command substitution ($(command)) be expanded from the .inputrc file. – terdon Apr 22 '18 at 16:03
  • @terdon: I've just the added the line above to my ~/.inputrc and run bind -f .inputrc. I pressed C-x x a couple of times and a current time was displayed each time. – Arkadiusz Drabczyk Apr 22 '18 at 16:18
  • 1
    shell-expand-line can be used like this! It's great! – Big Shield Apr 22 '18 at 16:18
  • 1
    @ArkadiuszDrabczyk ah! I hadn't noticed the \e\C-e for shell-expand-line! That's what I was missing. Thanks! – terdon Apr 22 '18 at 16:20
  • The only solution to get that in .inputrc. Could you make shell-expand-line work in ipython, python or perl REPL ? – Tinmarino Mar 31 '19 at 16:30
4

You can write a function that edits the readline variables READLINE_POINT and READLINE_LINE. For example, set in your .bashrc:

_myinsert() { # add date at point
    local TOADD=$(date)
    READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}${TOADD}${READLINE_LINE:$READLINE_POINT}"
    READLINE_POINT=$(($READLINE_POINT + ${#TOADD}))
}
# cannot put this in ~/.inputrc
bind -x '"\C-xx":_myinsert'

This uses the -x option of bind to call your function. I don't know of any way to put the equivalent in a ~/.inputrc file. (You certainly cannot just begin the line with -x, for example).

meuh
  • 51,383