4

I need a way to use the current line which the users typed into as variable for a shell function.

my current code, which can be called by ctrl+r

zle -N search

bindkey "^R" search

search () {
read str;
fc -ln -30 | grep $(printf "%q\n" "$str");
}

or simply, to call it as a function

search () {
fc -ln -30 | grep $(printf "%q\n" "$1");
}

updated: target pseudo code, to call as a function called by ctrl+r that needs no further input prompt

zle -N search

bindkey "^R" search

search ()
echo ""; #for better formatting because ctrl+R is not enter so the BUFFER(current line) gets corrupted and looks messy and the current input is not correctly shown
fc -ln -30 | grep $(printf "%q\n" "$BUFFER"); #edited to be the solution where $BUFFER is the current terminal line
}
  • 3
    In zle widgets, it's in `$BUFFER`. See also `$LBUFFER` and `$CURSOR`. Those can also be assigned to. You may want to have a look at the documentation and example widgets. – Stéphane Chazelas Aug 26 '14 at 15:16
  • I've searched for proper documentation the last 3 hours and found only 2 tutorials, but no list of available variables or anything like a documentation, but I'm pretty new to linux so it's probably build in somewhere into zsh but I can't find it. – HopefullyHelpful Aug 26 '14 at 15:24
  • 2
    Try `info zsh` (you may need to install a `zsh-doc` package), press `i` to bring up the index, enter `BUFFER` (completion available with Tab). Or `info -f zsh -n 'Zle Widgets'`. See also `man zshzle` though I wouldn't use `man` for such a big manual. See also [the user guide on the zsh website](http://zsh.sourceforge.net/Guide/zshguide04.html#l75) – Stéphane Chazelas Aug 26 '14 at 15:27
  • I think `fc ... | grep $str` is wrong approach. Please keep in mind that `$var` can contain special characters like `#;/\"'` etc. Even if you would assign them to variable, grep would not do what you want. – jimmij Aug 27 '14 at 01:30
  • $(printf "%q\n" "$BUFFER") should solve the problem, thanks for the hint !!! – HopefullyHelpful Aug 27 '14 at 15:22

1 Answers1

1

In zle widgets, the contents of the editing buffer is made available in the $BUFFER variable. $LBUFFER contains what's left of the cursor (same $BUFFER[1,CURSOR-1]) and $RBUFFER what's to the right (same as $BUFFER[CURSOR,-1]).

For a widget that prints a report of the previous command lines that contain the string entered so far (among the 30 most recent ones), you could do something like:

search() {
  zle -I
  print -rC1 -- ${(M)${history:0:30}:#*$BUFFER*}
}
zle -N search
bindkey '^R' search
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501