trans.lua (1000B)
1 local api = vim.api 2 3 local M = {} 4 5 local function translateText(line, from, to) 6 local text = table.concat(line, '') 7 return vim.fn.system(string.format('trans %s:%s --brief --no-autocorrect "%s"', from or '', to or '', text)) 8 end 9 10 local function getLines() 11 local open = api.nvim_buf_get_mark(0, '<') 12 local close = api.nvim_buf_get_mark(0, '>') 13 14 -- get text from visual 15 local lines = api.nvim_buf_get_lines(0, open[1] - 1, close[1], true) 16 local endColumn = #lines[1] 17 close[2] = math.min(close[2] + 1, endColumn) 18 if #lines > 1 then 19 print('translation on multiple lines not implemented') 20 return nil 21 else 22 lines[1] = string.sub(lines[1], open[2] + 1, close[2]) 23 end 24 return lines 25 end 26 27 local function replace(text) 28 text = text:gsub('\n', '') 29 vim.fn.setreg('t', text) 30 vim.cmd.norm('gv"tp') 31 end 32 33 function M.translate(to, from) 34 local lines = getLines() 35 if not lines then 36 return 37 end 38 local trans = translateText(lines, from, to) 39 replace(trans) 40 end 41 42 return M