1

Let us say:

% ls ./ _

when foo is called, where _ is the cursor position.

foo(){
    echo $COMMAND
}
zle -N foo

How can COMMAND be set such that foo will write out the 'command' (as in, the first word of the line - doesn't need to list or anything where && and the like is used) that was issued?

2

So you want the ls bit from the beginning of the current line? Let's see what's set by zsh

% foo(){ set > whatallisset }
% zle -N foo
% bindkey "^W" foo
% ls ./  # here I mash control+w, etc
% fgrep 'ls ./' whatallisset
BUFFER='ls ./ '
LBUFFER='ls ./ '

So we're probably looking at parsing one of those variables for the "first word", so assuming BUFFER is most appropriate, and then after delving through the zshexpn(1) docs and looking for "split" related things:

foo(){ echo -n ${${(z)BUFFER}[1]} }
  • Thanks for an answer that I can actually follow through instead of just giving the concluding one-liner! :) – OJFord Mar 30 '16 at 23:12
  • If $BUFFER is a single word, then it returns just the first letter. Is there a way to address this to get the whole word when it's just a single word? – spex Feb 27 at 3:28
1

You have access to a number of variables in user-defined widgets, in particular BUFFER which contains the content of the line (or more broadly, the whole buffer, which can be multiline).

How to extract the first word from BUFFER depends on your definition of words. In this context, the most useful definition is probably based on shell syntax, which is available through the z parameter expansion flag.

first_word=${${(z)BUFFER}[1]}

Other sensible definitions are to use whitespace-delimited words, or words consisting of $WORDCHARS. There are movement commands for that, but while you can call them via the zle builtin and watch CURSOR move, it would be easier to manually split the string $BUFFER.

In completion widgets, the words of the command for which the completion is taking place are in the words parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.