From 205677da04c2974cd20f5950e68ca84809cf180b Mon Sep 17 00:00:00 2001 From: Marcin Dziewulski Date: Sat, 4 May 2024 17:00:25 +0200 Subject: [PATCH] fix: display the initial value of the Prompt component correctly --- lua/nui-components/prompt.lua | 39 ++++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/lua/nui-components/prompt.lua b/lua/nui-components/prompt.lua index 3e5de83..db3bd52 100644 --- a/lua/nui-components/prompt.lua +++ b/lua/nui-components/prompt.lua @@ -2,7 +2,7 @@ local Text = require("nui.text") local TextInput = require("nui-components.text-input") local fn = require("nui-components.utils.fn") -local Prompt = TextInput:extend("Gap") +local Prompt = TextInput:extend("Prompt") function Prompt:init(props, popup_options) Prompt.super.init( @@ -37,30 +37,38 @@ end function Prompt:_attach_change_listener() local props = self:get_props() + self._private.once = true + vim.api.nvim_buf_attach(self.bufnr, false, { on_lines = self:if_not_mounting_phase_wrap(function() local prefix_length = self._private.prefix:length() - local value_with_prompt = vim.api.nvim_buf_get_lines(self.bufnr, 0, 1, false)[1] + + local lines = vim.api.nvim_buf_get_lines(self.bufnr, 0, -1, false) + local value_with_prompt = table.concat(lines, "") local value = string.sub(value_with_prompt, prefix_length + 1) - self:set_current_value(value) - props.on_change(value, self) + if not self._private.once then + self:set_current_value(value) + props.on_change(value, self) + end self:_update_placeholder() - if prefix_length > 0 then + if prefix_length > 0 and self._private.once then vim.schedule(function() self._private.prefix:highlight(self.bufnr, self.ns_id, 1, 0) + self._private.once = false end) end end), }) end -function Prompt:on_renderer_initialization(...) - Prompt.super.on_renderer_initialization(self, ...) - +function Prompt:on_mount() local props = self:get_props() + + Prompt.super.on_mount(self) + local function is_nui_text(value) return value.class and value.class.name == "NuiText" end @@ -69,6 +77,21 @@ function Prompt:on_renderer_initialization(...) vim.fn.prompt_setprompt(self.bufnr, self._private.prefix:content()) end +function Prompt:on_update() + local mode = vim.fn.mode() + local current_winid = vim.api.nvim_get_current_win() + + if not (current_winid == self.winid and mode == "i") then + vim.schedule(function() + if self:is_first_render() then + local value = table.concat(self:get_lines(), "") + vim.api.nvim_feedkeys(value, "n", true) + vim.api.nvim_win_set_cursor(self.winid, { 1, #value }) + end + end) + end +end + function Prompt:mappings() local props = self:get_props()