refactor: reduce useless code

This commit is contained in:
JuanZoran
2023-01-14 01:57:12 +08:00
parent 17ffaf69c9
commit 6d1bfbc437
25 changed files with 978 additions and 1472 deletions

View File

@@ -1,294 +0,0 @@
local M = {}
local opt = {
method = 'select',
view = 'cursor',
}
M.Translate = function(opts)
local res = get_query_res(opts.method)
-- TODO <++>
end
-- M.Translate_online = function ()
-- -- TOOD
-- end
-- local win = 0
-- local line = 0
-- local pos_info = {}
--
-- local handler = {}
-- api.nvim_buf_set_option(buf, 'filetype', 'Trans')
--
-- local function show_win(width, height)
-- end
--
-- -- NOTE title
-- handler.title = function(text, query_res)
-- local title = ('%s [%s] %s %s'):format(
-- query_res.word,
-- query_res.phonetic,
-- (display.oxford and (query_res.oxford == 1 and icon.isOxford or icon.notOxford) or ''),
-- ((display.collins_star and query_res.collins) and string.rep(icon.star, query_res.collins) or '')
-- )
-- table.insert(text, title)
--
-- pos_info.title = {}
-- pos_info.title.word = #query_res.word
-- pos_info.title.phonetic = query_res.phonetic and #query_res.phonetic or 3
-- pos_info.title.line = line
-- line = line + 1
-- end
--
-- -- NOTE tag
-- handler.tag = function(text, query_res)
-- if query_res.tag and #query_res.tag > 0 then
-- local tag = query_res.tag:gsub('zk', '中考'):gsub('gk', '高考'):gsub('ky', '考研'):gsub('cet4', '四级'):
-- gsub('cet6', '六级'):gsub('ielts', '雅思'):gsub('toefl', '托福'):gsub('gre', 'GRE')
--
-- table.insert(text, '标签:')
-- table.insert(text, ' ' .. tag)
-- table.insert(text, '')
--
-- pos_info.tag = line
-- line = line + 3
-- end
-- end
--
-- -- NOTE pos 词性
-- handler.pos = function(text, query_res)
-- if query_res.pos and #query_res.pos > 0 then
-- table.insert(text, '词性:')
--
-- local content = 0
-- for v in vim.gsplit(query_res.pos, [[/]]) do
-- table.insert(text, string.format(' %s', v .. '%'))
-- content = content + 1
-- end
--
-- table.insert(text, '')
--
-- pos_info.pos = {}
-- pos_info.pos.line = line
-- pos_info.pos.content = content
-- line = line + content + 2
-- end
-- end
--
-- -- NOTE exchange
-- handler.exchange = function(text, query_res)
-- if query_res.exchange and #query_res.exchange > 0 then
-- table.insert(text, '词形变化:')
--
-- local exchange_map = {
-- p = '过去式',
-- d = '过去分词',
-- i = '现在分词',
-- r = '形容词比较级',
-- t = '形容词最高级',
-- s = '名词复数形式',
-- O = '词干',
-- ['3'] = '第三人称单数',
-- }
--
-- local content = 0
-- for v in vim.gsplit(query_res.exchange, [[/]]) do
-- table.insert(text, string.format(' %s: %s', exchange_map[v:sub(1, 1)], v:sub(3)))
-- content = content + 1
-- -- FIXME: 中文字符与字母位宽不一致, 暂时无法对齐
-- end
-- table.insert(text, '')
--
-- pos_info.exchange = {}
-- pos_info.exchange.line = line
-- pos_info.exchange.content = content
-- line = line + content + 2
-- end
-- end
--
-- -- NOTE 中文翻译
-- handler.zh = function(text, query_res)
-- if query_res.translation then
-- table.insert(text, '中文翻译:')
--
-- local content = 0
-- for v in vim.gsplit(query_res.translation, '\n') do
-- table.insert(text, ' ' .. v)
-- content = content + 1
-- end
-- table.insert(text, '')
--
-- pos_info.zh = {}
-- pos_info.zh.line = line
-- pos_info.zh.content = content
-- line = content + line + 2
-- end
-- end
--
-- -- NOTE 英文翻译
-- handler.en = function(text, query_res)
-- if query_res.definition and #query_res.definition > 0 then
-- table.insert(text, '英文翻译:')
--
-- local content = 0
-- for v in vim.gsplit(query_res.definition, '\n') do
-- table.insert(text, ' ' .. v)
-- content = content + 1
-- end
-- table.insert(text, '')
--
-- pos_info.en = {}
-- pos_info.en.line = line
-- pos_info.en.content = content
-- line = line + content + 2
-- end
-- end
--
-- -- @return string array
-- local function get_text(query_res)
-- local text = {}
-- for _, v in ipairs(order) do
-- handler[v](text, query_res)
-- end
-- return text
-- end
--
-- local function set_text(query_res)
-- local text = query_res and get_text(query_res) or { '没有找到相关定义' }
--
-- api.nvim_buf_set_lines(buf, 0, -1, false, text)
-- local width = 0
-- for _, v in ipairs(text) do
-- if #v > width then
-- width = v:len()
-- end
-- end
-- return width, #text
-- end
--
-- local hl_handler = {}
--
-- hl_handler.title = function()
-- api.nvim_buf_add_highlight(buf, -1, hl.word, pos_info.title.line, 0, pos_info.title.word)
-- api.nvim_buf_add_highlight(buf, -1, hl.phonetic, pos_info.title.line, pos_info.title.word + 5,
-- pos_info.title.word + 5 + pos_info.title.phonetic)
-- end
--
-- hl_handler.tag = function()
-- if pos_info.tag then
-- api.nvim_buf_add_highlight(buf, -1, hl.ref, pos_info.tag, 0, -1)
-- api.nvim_buf_add_highlight(buf, -1, hl.tag, pos_info.tag + 1, 0, -1)
-- end
-- end
--
-- hl_handler.pos = function()
-- if pos_info.pos then
-- api.nvim_buf_add_highlight(buf, -1, hl.ref, pos_info.pos.line, 0, -1)
-- for i = 1, pos_info.pos.content, 1 do
-- api.nvim_buf_add_highlight(buf, -1, hl.pos, pos_info.pos.line + i, 0, -1)
-- end
-- end
-- end
--
-- hl_handler.exchange = function()
-- if pos_info.exchange then
-- api.nvim_buf_add_highlight(buf, -1, hl.ref, pos_info.exchange.line, 0, -1)
-- for i = 1, pos_info.exchange.content, 1 do
-- api.nvim_buf_add_highlight(buf, -1, hl.exchange, pos_info.exchange.line + i, 0, -1)
-- end
-- end
-- end
--
-- hl_handler.zh = function()
-- api.nvim_buf_add_highlight(buf, -1, hl.ref, pos_info.zh.line, 0, -1)
-- for i = 1, pos_info.zh.content, 1 do
-- api.nvim_buf_add_highlight(buf, -1, hl.zh, pos_info.zh.line + i, 0, -1)
-- end
-- end
--
-- hl_handler.en = function()
-- if pos_info.en then
-- api.nvim_buf_add_highlight(buf, -1, hl.ref, pos_info.en.line, 0, -1)
-- for i = 1, pos_info.en.content, 1 do
-- api.nvim_buf_add_highlight(buf, -1, hl.en, pos_info.en.line + i, 0, -1)
-- end
-- end
-- end
--
--
-- local function set_hl()
-- for _, v in ipairs(order) do
-- hl_handler[v]()
-- end
-- end
--
-- local function clear_tmp_info()
-- pos_info = {}
-- line = 0
-- end
--
--
-- function M.query(mode)
-- assert(buf > 0)
-- local word = ''
-- if mode == 'n' then
-- word = vim.fn.expand('<cword>')
-- elseif mode == 'v' then
-- word = get_visual_selection()
-- elseif mode == 'I' then
-- word = vim.fn.input('请输入您要查询的单词: ')
-- -- vim.ui.input({prompt = '请输入您要查询的单词: '}, function (input)
-- -- word = input
-- -- end)
-- else
-- error('mode argument is invalid')
-- end
--
-- local res = require("Trans.database").query(word)
-- local width, height = set_text(res)
-- show_win(width, height)
-- if res then
-- set_hl()
-- clear_tmp_info()
-- end
--
-- if auto_close then
-- api.nvim_create_autocmd(
-- { 'InsertEnter', 'CursorMoved', 'BufLeave', }, {
-- buffer = 0,
-- once = true,
-- callback = M.close_win,
-- })
-- end
-- end
--
-- function M.query_cursor()
-- M.query('n')
-- end
--
-- function M.query_select()
-- M.query('v')
-- end
--
-- function M.query_input()
-- M.query('I')
-- end
--
-- function M.close_win()
-- if win > 0 then
-- api.nvim_win_close(win, true)
-- win = 0
-- end
-- end
--
-- -- function M.enter_win()
-- -- if api.nvim_win_is_valid(win) then
-- -- else
-- -- error('current win is not valid')
-- -- end
-- -- end
--
-- return M

145
lua/Trans/core/content.lua Normal file
View File

@@ -0,0 +1,145 @@
local M = {}
M.__index = M
local get_width = vim.fn.strdisplaywidth
-- local get_width = vim.fn.strwidth
-- local get_width = vim.api.nvim_strwidth
---@alias block table add_hl(key, hl_name)
---返回分配的块状区域, e_col 设置为-1则为末尾
---@param s_row integer 起始行
---@param s_col integer 起始列
---@param height integer 行数
---@param width integer 块的宽度
---@return block
function M:alloc_block(s_row, s_col, height, width)
-- -1为到行尾
width = width == -1 and self.width or width
local e_col = s_col + width
local block = {
add_hl = function(key, hl_name)
table.insert(self.highlight[s_row + key], {
name = hl_name,
_start = s_col,
_end = e_col,
})
end
}
return setmetatable(block, {
-- 访问该表的操作, 映射成lines
__index = function(_, key)
assert(0 < key and key <= height)
--- FIXME : Unicode stirng sub
return self.lines[s_row + key]:sub(s_col, e_col)
end,
__newindex = function(_, key, value)
assert(0 < key and key <= height)
local wid = get_width(value)
if wid > width then
error('check out the str width: Max ->' .. self.width .. ' str ->' .. wid)
else
value = value .. (' '):rep(width - wid)
end
local line = s_row + key - 1
self.lines[line] = self.lines[line]:sub(1, s_col - 1) .. value .. self.lines[line]:sub(e_col + 1)
end,
})
end
function M:alloc_newline()
self.len = self.len + 1
local items = {}
local len = 0
local size = 0
return {
add_item = function(item, highlight)
size = size + 1
local wid = get_width(item)
items[size] = { item, highlight }
len = len + wid
end,
load_line = function()
local space = math.floor((self.width - len) / (size - 1))
assert(space > 0)
local interval = (' '):rep(space)
local value = ''
local function load_item(index)
if items[index][2] then
local _start = #value
local _end = _start + #items[index][2]
table.insert(self.highlights[self.len], {
name = items[index][2],
_start = _start,
_end = _end
})
end
value = value .. items[index][1]
end
load_item(1)
for i = 2, size do
value = value .. interval
load_item(i)
end
self.lines[self.len] = value
end
}
end
function M:addline(text, highlight)
self.len = self.len + 1
if highlight then
table.insert(self.highlights[self.len], {
name = highlight,
_start = 1,
_end = -1
})
end
self.lines[self.len] = text
end
-- 窗口宽度
function M:new(width)
vim.validate {
width = { width, 'n' }
}
local default = (' '):rep(width) -- default value is empty line
local new_content = {
width = width,
len = 0,
highlights = setmetatable({}, { -- always has default value
__index = function(tbl, key)
tbl[key] = {}
return tbl[key]
end
}),
}
new_content.lines = setmetatable({}, {
__index = function(tbl, key)
tbl[key] = default
return tbl[key]
end,
__newindex = function(tbl, key, value)
if value then
for _ = new_content.len + 1, key - 1 do
rawset(tbl, key, '')
end
rawset(tbl, key, value)
new_content.len = key
end
end
})
return setmetatable(new_content, self)
end
return M

152
lua/Trans/core/handler.lua Normal file
View File

@@ -0,0 +1,152 @@
local icon = require('Trans').conf.icon
-- local components = {
-- 'title',
-- 'tag',
-- 'pos',
-- 'exchange',
-- 'translation',
-- 'definition'
-- }
local tag_map = {
zk = '中考',
gk = '高考',
ky = '考研',
cet4 = '四级',
cet6 = '六级',
ielts = '雅思',
toefl = '托福',
gre = 'gre ',
}
local pos_map = {
a = '代词pron ',
c = '连接词conj ',
i = '介词prep ',
j = '形容词adj ',
m = '数词num ',
n = '名词n ',
p = '代词pron ',
r = '副词adv ',
u = '感叹词int ',
v = '动词v ',
x = '否定标记not ',
t = '不定式标记infm ',
d = '限定词determiner',
}
local exchange_map = {
['p'] = '过去式 ',
['d'] = '过去分词 ',
['i'] = '现在分词 ',
['r'] = '比较级 ',
['t'] = '最高级 ',
['s'] = '复数 ',
['0'] = '原型 ',
['1'] = '类别 ',
['3'] = '第三人称单数',
-- ['f'] = '第三人称单数',
}
local function exist(res)
return res and res ~= ''
end
M = {
title = function(result, content)
local line = content:alloc_newline()
line.add_item(result.word, 'TransWord')
local pho = ('[' .. (exist(result.phonetic) and result.phonetic or icon.notfound) .. ']')
-- line.add_item(pho, 'TransPhonetic', #pho)
line.add_item(pho, 'TransPhonetic')
line.add_item((exist(result.collins) and icon.star:rep(result.collins) or icon.notfound))
line.add_item((exist(result.oxford) and icon.yes or icon.no))
line.load_line()
end,
tag = function(result, content)
if exist(result.tag) then
content:addline('标签:', 'TransRef')
local tags = vim.tbl_map(function(tag)
return tag_map[tag]
end, vim.split(result.tag, ' ', { plain = true, trimempry = true }))
local size = #tags
local i = 1
while i <= size do
content:addline(' ' .. tags[i] .. ' ' .. (tags[i + 1] or '') .. ' ' .. (tags[i + 2] or ''),
'TransTag')
i = i + 3
end
content:addline('')
end
end,
pos = function(result, content)
if exist(result.pos) then
content:addline('词性:', 'TransRef')
vim.tbl_map(function(pos)
content:addline(' ' .. pos_map[pos:sub(1, 1)] .. pos:sub(3) .. '%', 'TransPos')
end, vim.split(result.pos, '/', { plain = true, trimempry = true }))
content:addline('')
end
end,
exchange = function(result, content)
if exist(result.exchange) then
content:addline('词性变化:', 'TransRef')
vim.tbl_map(function(exc)
content:addline(' ' .. exchange_map[exc:sub(1, 1)] .. ' ' .. exc:sub(3), 'TransExchange')
-- content:addline(' ' .. exchange_map[exc:sub(1, 1)] .. exc:sub(2), 'TransExchange')
end, vim.split(result.exchange, '/', { plain = true, trimempry = true }))
content:addline('')
end
end,
translation = function(result, content)
if result.translation and result.translation ~= '' then
local ref = {
{ '中文翻译:', 'TransRef' }
}
local translations = {
highlight = 'TransTranslation',
indent = 4,
emptyline = true,
}
for trans in vim.gsplit(result.translation, '\n', true) do
table.insert(translations, trans)
end
return { ref, translations }
end
end,
definition = function(result, content)
if result.definition and result.definition ~= '' then
local ref = {
{ '英文注释:', 'TransRef' }
}
local definitions = {
highlight = 'TransDefinition',
indent = 4,
emptyline = true,
}
for defin in vim.gsplit(result.definition, '\n', true) do
if defin ~= '' then
table.insert(definitions, defin)
end
end
return { ref, definitions }
end
end
}
return M

View File

@@ -1,7 +1,59 @@
local M = {}
local conf = require('Trans').conf
local api = require('Trans.api')
local win = require('Trans.core.window')
local handler = require('Trans.core.handler')
local c = require('Trans.core.content')
local function get_select()
local s_start = vim.fn.getpos("v")
local s_end = vim.fn.getpos(".")
local n_lines = math.abs(s_end[2] - s_start[2]) + 1
local lines = vim.api.nvim_buf_get_lines(0, s_start[2] - 1, s_end[2], false)
lines[1] = string.sub(lines[1], s_start[3], -1)
if n_lines == 1 then
lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3] - s_start[3] + 1)
else
lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3])
end
return table.concat(lines, '')
end
M.translate = function(method, view)
method = method or vim.api.nvim_get_mode().mode
view = view or conf.view[method]
local word
if method == 'input' then
---@diagnostic disable-next-line: param-type-mismatch
word = vim.fn.input('请输入您要查询的单词:') -- TODO Use Telescope with fuzzy finder
elseif method == 'n' then
word = vim.fn.expand('<cword>')
elseif method == 'v' then
word = get_select()
end
win.init(view)
local result = api.query('offline', word)
if result then
local content = c:new(win.width)
for i = 1, #conf.order do
handler[conf.order[i]](result, content)
end
win.draw(content)
else
local line = { '⚠️ 本地没有找到相应的结果' }
vim.api.nvim_buf_set_lines(win.bufnr, 0, -1, false, line)
local wid = vim.fn.strdisplaywidth(line[1])
vim.api.nvim_win_set_width(win.id, wid)
vim.api.nvim_win_set_height(win.id, #line)
win.auto_close()
end
end
M.process = require('Trans.core.process')
M.query = require('Trans.core.query')
-- M.show_win = require('Trans.core.show_win')
return M

View File

@@ -1,170 +0,0 @@
local type_check = vim.validate
-- NOTE :中文字符及占两个字节宽但是在lua里是3个字节长度
-- 为了解决中文字符在lua的长度和neovim显示不一致的问题
local get_width = vim.fn.strdisplaywidth
local function format(win_width, items)
local size = #items
local tot_width = 0
if items.indent then
win_width = win_width - items.indent
end
for i = 1, size do
if type(items[i]) == 'string' then
items[i] = { items[i] }
end
tot_width = tot_width + #items[i][1] + 4
end
-- 判断宽度是否超过最大宽度
if tot_width > win_width + 4 then
-- 放不下则需要分成多行
local lines = {}
-- 行内字符串按照宽度排序
table.sort(items, function(a, b)
return #a[1] > #b[1]
end)
local cols = 1
win_width = win_width - #items[1][1]
while win_width > 0 and cols < size do
cols = cols + 1
win_width = win_width - #items[cols][1] + 4
end
if cols > 1 then
cols = cols - 1
end
if cols == 1 then -- 只能放在一行时就对齐了
for i = size, 1, -1 do
lines[i] = {
items[i][1],
highlight = items.highlight,
indent = items.indent,
}
end
return lines, true
end
local rows = math.ceil(size / cols)
local rest = size % cols
if rest == 0 then
rest = cols
end
local max_width = get_width(items[1][1])
local index = 1 -- 当前操作的字符串下标
for i = rows, 1, -1 do -- 当前操作的行号
lines[i] = {
highlight = items.highlight,
indent = items.indent,
}
local item = items[index]
-- if not item then
-- error('item nil ' .. tostring(index) .. ' rows:' .. tostring(rows) .. vim.inspect(items) )
-- end
item[1] = item[1] .. (' '):rep(max_width - get_width(item[1]))
lines[i][1] = items[index]
index = index + 1
end
for col = 2, cols do
max_width = get_width(items[index][1])
local _end = col > rest and rows - 1 or rows
for i = _end, 1, -1 do
local item = items[index]
item[1] = item[1] .. (' '):rep(max_width - get_width(item[1]))
lines[i][col] = item
index = index + 1
end
end
return lines, true
end
return items
end
local function process(opts)
type_check {
opts = { opts, 'table' },
['opts.field'] = { opts.field, 'table', true },
['opts.order'] = { opts.order, 'table' },
['opts.win'] = { opts.win, 'table' },
['opts.engine'] = { opts.engine, 'table' },
}
if opts.field == nil then
local lines = { '⚠️ 本地没有找到相关释义' }
vim.api.nvim_buf_set_lines(opts.bufnr, 0, -1, false, lines)
vim.api.nvim_win_set_height(opts.winid, 1)
vim.api.nvim_win_set_width(opts.winid, get_width(lines[1]))
else
local content = require('Trans.component.content'):new(opts)
for _, v in ipairs(opts.order) do
local component
if type(v) == 'table' then
component = require("Trans.component." .. 'offline' --[[ opts.engine ]] .. '.' .. v[1]).component(opts.field
, v.max_size)
else
component = require("Trans.component." .. 'offline' --[[ opts.engine ]] .. '.' .. v).component(opts.field)
end
if component then
for _, items in ipairs(component) do
if items.needformat then
local formatted_items, split = format(opts.win.width, items)
if split then
for _, itms in ipairs(formatted_items) do
content:insert(itms)
end
else
content:insert(formatted_items)
end
else
content:insert(items)
end
if items.emptyline then
content:insert({ '' })
end
end
end
end
content:attach()
end
vim.api.nvim_buf_set_option(opts.bufnr, 'modifiable', false)
vim.api.nvim_buf_set_option(opts.bufnr, 'filetype', 'Trans')
vim.api.nvim_win_set_option(opts.winid, 'wrap', true)
vim.api.nvim_win_set_option(opts.winid, 'winhl', 'Normal:TransCursorWin,FloatBorder:TransCursorBorder')
if opts.win.style == 'cursor' then
vim.api.nvim_create_autocmd(
{ 'InsertEnter', 'CursorMoved', 'BufLeave', }, {
buffer = 0,
once = true,
callback = function()
if vim.api.nvim_win_is_valid(opts.winid) then
vim.api.nvim_win_close(opts.winid, true)
end
end,
})
end
end
return process

View File

@@ -1,43 +0,0 @@
local type_check = vim.validate
local query = require("Trans.api").query
local function get_select()
local s_start = vim.fn.getpos("v")
local s_end = vim.fn.getpos(".")
local n_lines = math.abs(s_end[2] - s_start[2]) + 1
local lines = vim.api.nvim_buf_get_lines(0, s_start[2] - 1, s_end[2], false)
lines[1] = string.sub(lines[1], s_start[3], -1)
if n_lines == 1 then
lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3] - s_start[3] + 1)
else
lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3])
end
return table.concat(lines, '\n')
end
local query_wrapper = function(opts)
type_check {
opts = { opts, 'table' },
['opts.method'] = { opts.method, 'string' },
}
local word = ''
if opts.method == 'input' then
---@diagnostic disable-next-line: param-type-mismatch
word = vim.fn.input('请输入您要查询的单词:') -- TODO Use Telescope with fuzzy finder
elseif opts.method == 'n' then
word = vim.fn.expand('<cword>')
elseif opts.method == 'v' then
word = get_select()
-- TODO : other method
else
error('invalid method' .. opts.method)
end
return query(word)
end
return query_wrapper

View File

@@ -1,110 +0,0 @@
-- Default conf
local conf = require("Trans.conf.loader").loaded_conf
local core = require("Trans.core")
local function get_opts(opts)
local mode = vim.api.nvim_get_mode().mode
local default_conf = {
method = mode,
engine = conf.base.engine,
win = {
style = conf.style.ui[opts.method or mode],
width = conf.style.window.cursor.width,
height = conf.style.window.cursor.height
},
}
if type(opts.engine) == 'string' then
opts.engine = { opts.engine }
end
if opts.win then
local width, height = opts.win.width, opts.win.height
if width and width > 0 and width <= 1 then
opts.win.width = math.floor(vim.o.columns * width)
end
if height and height > 0 and height <= 1 then
opts.win.height = math.floor(vim.o.lines * opts.win.height)
end
end
return vim.tbl_extend('force', default_conf, opts)
end
-- EXAMPLE :
-- require('Trans').translate({
-- method = 'input', -- 不填则自动判断mode获取查询的单词
-- engine = { -- 异步查询所有的引擎, 按照列表
-- 'offline',
-- 'youdao',
-- 'baidu'
-- },
-- -- win = 'cursor'
-- win = {
-- style = 'cursor',
-- height = 50,
-- width = 30,
-- }
-- })
local function create_win(win)
local bufnr = vim.api.nvim_create_buf(false, true)
local is_float = win.style == 'float'
local win_opts = {
relative = is_float and 'editor' or 'cursor',
width = win.width,
height = win.height,
style = 'minimal',
border = conf.style.window[win.style].border,
title = 'Trans',
title_pos = 'center',
focusable = true,
zindex = 100,
}
if is_float then
win_opts.row = math.floor((vim.o.lines - win_opts.height - vim.o.cmdheight) / 2)
win_opts.col = math.floor((vim.o.columns - win_opts.width) / 2)
else
win_opts.row = 2
win_opts.col = 2
end
local winid = vim.api.nvim_open_win(bufnr, is_float, win_opts)
return bufnr, winid
end
local function translate(opts)
vim.validate {
opts = { opts, 'table', true }
}
--- TODO : 异步请求
-- NOTE : 这里只处理了本地数据库查询
opts = get_opts(opts or {})
local field = core.query(opts)
local bufnr, winid = create_win(opts.win)
local proc_opts = {
bufnr = bufnr,
winid = winid,
win = opts.win,
field = field,
order = conf.order['offline'],
engine = { 'offline' },
}
core.process(proc_opts)
end
return translate

94
lua/Trans/core/window.lua Normal file
View File

@@ -0,0 +1,94 @@
local M = {}
local api = vim.api
local conf = require('Trans').conf
M.id = 0
M.bufnr = 0
M.ns = api.nvim_create_namespace('Trans')
function M.init(view)
vim.validate {
view = { view, 's' }
}
M.view = view
M.float = view == 'float'
M.height = conf.window[view].height
M.width = conf.window[view].width
local opts = {
relative = M.float and 'editor' or 'cursor',
width = M.width,
height = M.height,
style = 'minimal',
border = conf.window.border,
title = 'Trans',
title_pos = 'center',
focusable = true,
zindex = 100,
}
if M.float then
opts.row = math.floor((vim.o.lines - M.height) / 2)
opts.col = math.floor((vim.o.columns - M.width) / 2)
else
opts.row = 2
opts.col = 2
end
M.bufnr = api.nvim_create_buf(false, true)
M.id = api.nvim_open_win(M.bufnr, M.float, opts)
end
M.draw = function(content)
api.nvim_buf_set_lines(M.bufnr, 0, -1, false, content.lines)
if content.highlights then
for l, _hl in pairs(content.highlights) do
for _, hl in ipairs(_hl) do
api.nvim_buf_add_highlight(M.bufnr, M.ns, hl.name, l - 1, hl._start, hl._end) -- zero index
end
end
end
local len = #content.lines
if M.height > len then
api.nvim_win_set_height(M.id, len + 1)
end
api.nvim_buf_set_option(M.bufnr, 'modifiable', false)
api.nvim_buf_set_option(M.bufnr, 'filetype', 'Trans')
api.nvim_win_set_option(M.id, 'wrap', not M.float)
api.nvim_win_set_option(M.id, 'winhl', 'Normal:TransCursorWin,FloatBorder:TransCursorBorder')
if M.float then
vim.keymap.set('n', 'q', function()
if api.nvim_win_is_valid(M.id) then
api.nvim_win_close(M.id, true)
end
end, { buffer = M.bufnr, silent = true })
else
-- TODO : set keymaps for window
M.auto_close()
end
end
M.auto_close = function()
api.nvim_create_autocmd(
{ 'InsertEnter', 'CursorMoved', 'BufLeave', }, {
buffer = 0,
once = true,
callback = function()
if api.nvim_win_is_valid(M.id) then
api.nvim_win_close(M.id, true)
end
end,
})
end
return M