feat: add TranslateInput command

This commit is contained in:
JuanZoran 2023-03-22 22:27:27 +08:00
parent 34a01920a5
commit 2bb4b4d46b
3 changed files with 21 additions and 16 deletions

View File

@ -8,6 +8,7 @@ local function init_opts(opts)
v = 'visual', v = 'visual',
})[vim.api.nvim_get_mode().mode] })[vim.api.nvim_get_mode().mode]
opts.str = util.get_str(opts.mode) opts.str = util.get_str(opts.mode)
return opts return opts
end end

View File

@ -1,5 +1,3 @@
local Trans = require('Trans')
local fn, api = vim.fn, vim.api local fn, api = vim.fn, vim.api
---@class TransUtil ---@class TransUtil
@ -42,16 +40,18 @@ end
---@param mode TransMode ---@param mode TransMode
---@return string ---@return string
function M.get_str(mode) function M.get_str(mode)
if mode == 'n' or mode == 'normal' then return ({
return fn.expand('<cword>') normal = function()
elseif mode == 'v' or mode == 'visual' then return fn.expand('<cword>')
api.nvim_input('<ESC>') end,
return M.get_select() visual = function()
elseif mode == 'input' then api.nvim_input('<Esc>')
return fn.expand('<cword>') return M.get_select()
else end,
error('Unsupported mode' .. mode) input = function()
end return fn.input('需要翻译的字符串: ')
end,
})[mode]():match('^%s*(.-)%s*$')
end end
---Puase coroutine for {ms} milliseconds ---Puase coroutine for {ms} milliseconds
@ -166,7 +166,7 @@ end
---@param opts { winid: integer, height: integer }? ---@param opts { winid: integer, height: integer }?
---@return string[] ---@return string[]
function M.visible_lines(opts) function M.visible_lines(opts)
opts = opts or {} opts = opts or {}
-- INFO : don't calculate the height of statusline and cmdheight or winbar? -- INFO : don't calculate the height of statusline and cmdheight or winbar?
local winid = opts.winid or 0 local winid = opts.winid or 0
@ -188,7 +188,6 @@ function M.is_word(str)
return str:match('%w+') == str return str:match('%w+') == str
end end
---@class Trans ---@class Trans
---@field util TransUtil ---@field util TransUtil
return M return M

View File

@ -26,11 +26,16 @@ local command = api.nvim_create_user_command
command("Translate", function() command("Translate", function()
Trans.translate() Trans.translate()
end, { desc = " 单词翻译" }) end, { desc = " Translate cursor word" })
command("TranslateInput", function()
Trans.translate({ mode = 'input' })
end, { desc = " Translate input word" })
command("TransPlay", function() command("TransPlay", function()
local str = Trans.util.get_str(api.nvim_get_mode().mode) local str = Trans.util.get_str(api.nvim_get_mode().mode)
if str and str ~= "" and Trans.util.is_English(str) then if str and str ~= "" and Trans.util.is_English(str) then
str:play() str:play()
end end
end, { desc = "自动发音" }) end, { desc = "auto play" })