Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Disable most shell expansion to function or script



On 1/4/24, Sam B. <me@xxxxxx> wrote:
> Hello,
>
> I'm looking for a way to disable most shell expansion for the arguments
> to a script or function and treat everything up to a newline char as
> verbatim text, i.e. as if quoted.
>
> For example, given a function/script "todo", I'd like
>
>      todo Text inc. $var, *glob?, events!, <redirs, >(sub) & more
>
> to behave more like it was quoted:
>
>      todo 'Text inc. $var, *glob?, events!, <redirs, >(sub) & more'
>
> I know of noglob to disable glob chars, and can have a look at histchars
> to see if events can be disabled. But I'm not sure if any of the other
> expansion can possibly disabled.
>
> Mostly I'm interested joting down some plain text which could include
> '?!&' and have "todo" receive it all without the shell having done some
> magic beforehand.
>
> Any ideas?

function _accept_line () {
  if [[ $CONTEXT = vared ]] || [[ $zsh_eval_context != shfunc ]]; then
    zle .$WIDGET
    return
  fi
  if [[ "$BUFFER" = todo\ * ]]; then
    BUFFER="todo ${(q)BUFFER[6,-1]}"
    zle .$WIDGET
    return # not needed in this example but if you handle other stuff below
  fi
}

zle -N accept-line _accept_line
zle -N accept-line-and-down-history _accept_line
zle -N accept-and-hold _accept_line

Note that the quoted version will be saved in the history, and if you
recall the event, it will be quoted again by the above code, so there
is room for improvement / other ideas.

For example, make a function that takes no arguments, reads a single
line, and runs todo $REPLY for you. (todo itself could handle this if
given no arguments too?)

runquoted() {
  local cmd=( ${@:-todo} ) REPLY
  IFS= read -r
  $cmd $REPLY
}

% runquoted print -rl
asoeu a-;ua;,. ua-h,.uch <- my input
asoeu a-;ua;,. ua-h,.uch
% runquoted
aosot
zsh: command not found: todo

-- 
Mikael Magnusson




Messages sorted by: Reverse Date, Date, Thread, Author