0

I defined a simple function prepend (below) that should automatically place a repeated term of a bash command in the following input prompts. For example, by typing prepend git in the terminal, all following inputs should have git already entered. For the most part, prepend does this; however, seemingly at random, prepend will cut off the first letter of the word (e.g. $prepend sensors yields $ensors on the following input prompt).

I was wondering why this is happening and how to possibly fix it. However, if there's an alternative/canonical way to have text entered into input prompts, I wouldn't mind implementing this differently.

#!/bin/bash

#stty to stop text from being displayed before $PS1

function prepend {
    if ! [ -z "$1" ]
        then
            PROMPT_COMMAND="stty -echo && xdotool type $1 && stty echo"
            set PROMPT_COMMAND
    else
        unset PROMPT_COMMAND
    fi
}
SWV
  • 101
  • 3
  • 1
    I'm not aware of a proper solution, however, your hack is quite fragile. E.g. if you have another window (let's say a browser) focused when a terminal command completes, you'll end up "typing" into that window. On a side note: the "set" command doesn't do what you think it does. For your actual problem: you might inject a few "sleep 0.1"s into PROMPT_COMMAND and see if that helps, I have no clue why the first letter could be swallowed. – egmont Jan 09 '19 at 22:07
  • @egmont Thank you. Beyond the window focus, are there other major use-cases I should consider to make the function more robust? – SWV Jan 10 '19 at 00:42
  • Use the ioctl TIOCSTI to stuff data into the input. See here. – meuh Jan 10 '19 at 18:15

1 Answers1

0

I believe that the first letter is cut off when the key for that character is already held down. To see this in effect, you can run the following command in your terminal:

$ xdotool type foof

If you release the f key before pressing Return, this will print foof, but it you hold down the final f while pressing Return it will print oof. I believe that this occurs becasue xdotool is sending keydown events, which don't have any effect when the key is already down.

You can work around this issue by manually sending a keyup event:

$ xdotool keyup f type foof

will always print foof correctly.

In your case, this will be slightly more complicated; you'll need to detect the first chararacter of the string to send the correct keyup. But, once you have done so, this approch should work for you as well.

codesections
  • 121
  • 4