Quote or bracket completion in bash, without pressing TAB

3

3

Is there any way to have bash autocomplete matching symbols like '"[{( with their right handed counterparts? I would like to do this without having to press tab.

For example typing the string echo " would immediately result in this string echo "|", where my cursor (the pipe) is in between the two quotes.

Bonus points if you can find a way that, when the first quote is deleted, the second one is also deleted.

If you've ever used any mature text editor (eg. sublime text), you can understand how this interaction works. Answers utilizing fish shell are also accepted.

codysehl

Posted 2013-08-09T13:20:17.787

Reputation: 328

Answers

3

Although you can not bind keys on itself in GNU Readline — something like "(": "()" drives to endless loop — there is a way. Not for readline in general, only for bash. Add this to you .bashrc:

readline-brackets() {
    READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}${1}${READLINE_LINE:$READLINE_POINT}"
    ((READLINE_POINT+=1))
}
bind -m vi-insert -x '"\"" : "readline-brackets \"\""'
bind -m vi-insert -x $'"\047" : "readline-brackets \\\047\\\047"' # SINGLE QUOTE
bind -m vi-insert -x '"<" : "readline-brackets \<\>"'
bind -m vi-insert -x '"(" : "readline-brackets \(\)"'
bind -m vi-insert -x '"[" : "readline-brackets []"'
bind -m vi-insert -x '"{" : "readline-brackets {}"'

Remove -m vi-insert if you use emacs mode, not vi.

Dmitry Alexandrov

Posted 2013-08-09T13:20:17.787

Reputation: 984

This is a great tip ! However, although this works great for the normal case, I encountered 2 problems:

  • tab completions (ie: assuming $FOO is defined echo ${FO<tab>} results in ${FOO}})
  • backspace handling (ie: '<backspace>' leave us with ') . Any ideas on how to handle these ?
  • < – lonetwin – 2017-02-20T11:31:21.403