I have a zsh script that loads when start new shell with default is zsh.

func1() {
  <..check if in a git repo, if not return..>
  <..code here..>
zle -N func1
bindkey '\eo' func1

The above function func1 is triggered when press Alt-o. This function only loaded when in a git repo.

The problem is that the cost of load this function is pretty high and slowing down the shell prompt if it always loaded when start new shell, how to "lazy" - load only when first time trigger Alt-o?


autoload is the mechanism for delaying the load of functions until they are used; in a $fpath directory create a testfunc file:

% < testfunc
testfunc() {
    sleep 3
    print this is a test function

and then autoload it (and then zle ..., if necessary):

% grep testfunc ~/.zshrc
autoload -U testfunc

it should not be in memory until used:

% exec zsh -l
% print $functions[testfunc]
builtin autoload -XU
% testfunc
this is a test function
% print $functions[testfunc]
    sleep 3
    print this is a test function
  • Thanks, if I trigger for the first time I got this error: testfunc: no such file or directory: testfunc, and then trigger for the second time, testfunc run as expected, Is there reason why? – Tuyen Pham Jan 29 at 4:04
  • not without more detail on your exact setup. try from a zsh -f to clear out any other configuration – thrig Jan 29 at 4:10
  • What exactly that depends on setup can cause the issue? I tried zsh -f then manually set fpath export fpath=(~/.zsh/functions $fpath), then autoload -U testfunc, and run > testfunc. Still the same error for first time run. – Tuyen Pham Jan 29 at 6:03
  • try strace or the like then. autoload is how all the tab completions get loaded, and I've never seen the error you report before – thrig Jan 29 at 6:13
  • Does zsh -f ignores .zshrc file? I have fpath exported in .zshenv. Really confused but this task seems to be critical to my workflow, so I'll really appreciated if you can point it out a little more clearly, I'm normal zsh user, I can't understand some implication. – Tuyen Pham Jan 30 at 4:13

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.