Add documentation for how to easily use async prompt filtering.
chrisant996 opened this issue · comments
It's very easy with flexprompt.prompt_info()
, but there's no documentation yet for how to use that.
Step 1 -- Collect info to be shown in the prompt
Make a function that collects the info that should appear in the prompt.
Make the function return a table containing the info.
-- This function uses async prompt filtering to count the number
-- of files in the current directory.
local function collect_foo_info()
local ret = {}
local count_files = 0
local f = io.popen("dir /b /a-d *")
if f then
for line in f:lines() do
count_files = count_files + 1
end
f:close()
end
ret.count_files = count_files
return ret
end
Step Two -- Make it collect the info asynchronously
Make a module that calls flexprompt.prompt_info()
.
We'll discuss the middle two parameters later -- they can be empty strings if you don't need them.
local foo_data = {}
local function foo_module(args)
-- Use async prompt filtering to call the collect_foo_info() function.
local info = flexprompt.prompt_info(foo_data, "", "", collect_foo_info)
-- Build the prompt text.
local text = info.count_files or 0
text = flexprompt.append_text(text, flexprompt.make_fluent_text("file(s)"))
return text, "cyan"
end
flexprompt.add_module("foo", foo_module)
Step Three -- [Optional] Maybe reset the cached prompt info
Async prompt filtering shows the previous prompt content until the async collection function finishes.
But sometimes you may know in advance that the previous prompt content is no longer relevant. There is a simple way to automatically discard the previous cached prompt content.
The flexprompt.prompt_info()
function takes two parameters which, if either is different from the previous prompt, will automatically reset the cached prompt content.
For example, the {git}
module passes the git repo root directory and the current git branch. This is so that if you cd
to a different repo or git switch
to a different branch, the prompt doesn't mislead by showing info from a different repo or branch.
So, since this sample {foo}
module counts the files in the current directory, it makes sense to use the current directory for one of those two parameters:
local function foo_module(args)
-- Use async prompt filtering to call the collect_foo_info() function.
local info = flexprompt.prompt_info(foo_data, os.getcwd(), "", collect_foo_info)
-- Build the prompt text.
local text = info.count_files or 0
text = flexprompt.append_text(text, flexprompt.make_fluent_text("file(s)"))
return text, "cyan"
end
Step Four -- Be happy
Tada!
Oh, I added documentation a while ago. Can close as completed.