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

Re: Autoload vs regular function



On Sep 18, 11:45am, Ray Andrews wrote:
}
} Can you rough in an example of that for us Bart?  Sounds like an elegant 
} idea.

Functions/Misc/tetris in the zsh distribution is a perfect example of
this already.  It defines a whole bunch of helper functions (most of
which end up becoming zle widgets) and a single entry point function
"tetris" which kicks the whole thing off.

Note at the very end of Functions/Misc/tetris, the function that it
defined is explicitly called.  This is so tetris can be autoloaded in
the default zsh style.  If you do "autoload -k tetris" the command is
run twice.  (Many autoloadable functions in the zsh distribution test
for KSH_AUTOLOAD before calling themselves this way; tetris probably
ought to as well, but currently doesn't.)

} I wonder if it is possible that when one types a command that is not
} found, it could trigger a sort of search in some directory for a
} script that would itself source the very command not found and then
} run it? Sorta a reinvention of autoload but maybe more transparent.

Recent zsh support a command_not_found_handler function which is run
if a the searches of $fpath and $path do not find anything.  So you
can do this by building a custom search in command_not_found_handler.
I don't know that this any more "transparent" than otherwise.  Also
the command_not_found handler runs after the parent shell has forked,
so anything it loads does not appear in the parent.

E.g. to always attempt to load functions from a .zwc file in the
current working directory, you could:

    command_not_found_handler () {
        FPATH=$PWD autoload +X $1
        "$@"
    }

Similarly if you don't like zsh's way of handling autoloads, you can
do you own like this:

    auto_load_me () {
	FPATH=/my/custom/fpath autoload -X
    }

This is [almost!] the same as writing

    autoload auto_load_me

except that the custom fpath is asserted.  I say "almost" because things
like sticky emulation get handled a little differently when using the
"autoload -X" command, but that is pretty esoteric.  Of course you can
throw in other things besides just fpath changes, you have a whole
function body to play with, but at some point you're just ruining the
whole purpose of autoload and might as well define the real function.

-- 
Barton E. Schaefer



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