From 2bb4b4d46b0a259638b096484702a9b5c5e4e199 Mon Sep 17 00:00:00 2001 From: JuanZoran <1430359574@qq.com> Date: Wed, 22 Mar 2023 22:27:27 +0800 Subject: [PATCH] feat: add TranslateInput command --- lua/Trans/core/translate.lua | 1 + lua/Trans/core/util.lua | 27 +++++++++++++-------------- plugin/Trans.lua | 9 +++++++-- 3 files changed, 21 insertions(+), 16 deletions(-) diff --git a/lua/Trans/core/translate.lua b/lua/Trans/core/translate.lua index 6eb709f..1d88451 100644 --- a/lua/Trans/core/translate.lua +++ b/lua/Trans/core/translate.lua @@ -8,6 +8,7 @@ local function init_opts(opts) v = 'visual', })[vim.api.nvim_get_mode().mode] + opts.str = util.get_str(opts.mode) return opts end diff --git a/lua/Trans/core/util.lua b/lua/Trans/core/util.lua index 439e98a..753256f 100644 --- a/lua/Trans/core/util.lua +++ b/lua/Trans/core/util.lua @@ -1,5 +1,3 @@ -local Trans = require('Trans') - local fn, api = vim.fn, vim.api ---@class TransUtil @@ -42,16 +40,18 @@ end ---@param mode TransMode ---@return string function M.get_str(mode) - if mode == 'n' or mode == 'normal' then - return fn.expand('') - elseif mode == 'v' or mode == 'visual' then - api.nvim_input('') - return M.get_select() - elseif mode == 'input' then - return fn.expand('') - else - error('Unsupported mode' .. mode) - end + return ({ + normal = function() + return fn.expand('') + end, + visual = function() + api.nvim_input('') + return M.get_select() + end, + input = function() + return fn.input('需要翻译的字符串: ') + end, + })[mode]():match('^%s*(.-)%s*$') end ---Puase coroutine for {ms} milliseconds @@ -166,7 +166,7 @@ end ---@param opts { winid: integer, height: integer }? ---@return string[] function M.visible_lines(opts) - opts = opts or {} + opts = opts or {} -- INFO : don't calculate the height of statusline and cmdheight or winbar? local winid = opts.winid or 0 @@ -188,7 +188,6 @@ function M.is_word(str) return str:match('%w+') == str end - ---@class Trans ---@field util TransUtil return M diff --git a/plugin/Trans.lua b/plugin/Trans.lua index 6507ab4..10a8c82 100644 --- a/plugin/Trans.lua +++ b/plugin/Trans.lua @@ -26,11 +26,16 @@ local command = api.nvim_create_user_command command("Translate", function() Trans.translate() -end, { desc = " 单词翻译" }) +end, { desc = " Translate cursor word" }) + + +command("TranslateInput", function() + Trans.translate({ mode = 'input' }) +end, { desc = " Translate input word" }) command("TransPlay", function() local str = Trans.util.get_str(api.nvim_get_mode().mode) if str and str ~= "" and Trans.util.is_English(str) then str:play() end -end, { desc = " 自动发音" }) +end, { desc = " auto play" })