From 82fa2a008a3bfab763fbf6035036af462122c0c3 Mon Sep 17 00:00:00 2001 From: JuanZoran <1430359574@qq.com> Date: Fri, 24 Mar 2023 00:56:36 +0800 Subject: [PATCH] style: code format use lua_ls --- lua/Trans/backend/baidu.lua | 8 +- lua/Trans/backend/iciba.lua | 3 +- lua/Trans/backend/offline.lua | 110 +++++++++++++------------- lua/Trans/backend/youdao.lua | 111 +++++++++++++-------------- lua/Trans/core/backend.lua | 8 +- lua/Trans/core/conf.lua | 9 +-- lua/Trans/core/data.lua | 4 +- lua/Trans/core/frontend.lua | 4 +- lua/Trans/core/immersive.lua | 22 +++--- lua/Trans/core/install.lua | 8 +- lua/Trans/core/setup.lua | 4 +- lua/Trans/core/translate.lua | 4 +- lua/Trans/core/util.lua | 21 +++-- lua/Trans/core/window.lua | 22 +++--- lua/Trans/frontend/hover/execute.lua | 8 +- lua/Trans/frontend/hover/init.lua | 22 +++--- lua/Trans/frontend/hover/load.lua | 6 +- lua/Trans/frontend/hover/offline.lua | 10 +-- lua/Trans/health.lua | 50 ++++++------ lua/Trans/init.lua | 12 +-- lua/Trans/util/init.lua | 16 ---- lua/Trans/util/node.lua | 12 +-- 22 files changed, 227 insertions(+), 247 deletions(-) delete mode 100644 lua/Trans/util/init.lua diff --git a/lua/Trans/backend/baidu.lua b/lua/Trans/backend/baidu.lua index 1a96717..38984c6 100644 --- a/lua/Trans/backend/baidu.lua +++ b/lua/Trans/backend/baidu.lua @@ -5,14 +5,14 @@ ---@field app_passwd string ---@field disable boolean local M = { - uri = "https://fanyi-api.baidu.com/api/trans/vip/translate", + uri = 'https://fanyi-api.baidu.com/api/trans/vip/translate', salt = tostring(math.random(bit.lshift(1, 15))), - name = "baidu", + name = 'baidu', method = 'get', } -local Trans = require("Trans") +local Trans = require 'Trans' ---@class BaiduQuery ---@field q string @@ -52,7 +52,7 @@ function M.formatter(body, data) result = result[1] return { str = result.src, - [data.from == "en" and "translation" or "definition"] = { result.dst }, + [data.from == 'en' and 'translation' or 'definition'] = { result.dst }, } end diff --git a/lua/Trans/backend/iciba.lua b/lua/Trans/backend/iciba.lua index 6857134..121dfed 100644 --- a/lua/Trans/backend/iciba.lua +++ b/lua/Trans/backend/iciba.lua @@ -20,9 +20,8 @@ function M.get_query(data) } end - function M.formatter(body, data) - print('TODO') + print 'TODO' -- if true and not status or not body or body.errorCode ~= "0" then -- data.result.iciba = false -- data[#data + 1] = res diff --git a/lua/Trans/backend/offline.lua b/lua/Trans/backend/offline.lua index eaed48c..b3b2a46 100644 --- a/lua/Trans/backend/offline.lua +++ b/lua/Trans/backend/offline.lua @@ -1,10 +1,10 @@ -local Trans = require("Trans") +local Trans = require 'Trans' -local db = require("sqlite.db") -local path = Trans.conf.dir .. Trans.separator .. "ultimate.db" +local db = require 'sqlite.db' +local path = Trans.conf.dir .. Trans.separator .. 'ultimate.db' local dict = db:open(path) -local db_name = "stardict" -vim.api.nvim_create_autocmd("VimLeavePre", { +local db_name = 'stardict' +vim.api.nvim_create_autocmd('VimLeavePre', { callback = function() if db:isopen() then db:close() end end, @@ -12,7 +12,7 @@ vim.api.nvim_create_autocmd("VimLeavePre", { ---@class TransOfflineBackend local M = { - name = "offline", + name = 'offline', no_wait = true, } @@ -20,7 +20,7 @@ local M = { ---@return any ---@overload fun(TransData): TransResult function M.query(data) - if data.is_word == false or data.from == "zh" then + if data.is_word == false or data.from == 'zh' then return end @@ -35,19 +35,19 @@ end -- this is a awesome plugin M.query_field = { - "word", - "phonetic", - "definition", - "translation", - "pos", - "collins", - "oxford", - "tag", - "exchange", + 'word', + 'phonetic', + 'definition', + 'translation', + 'pos', + 'collins', + 'oxford', + 'tag', + 'exchange', } local function exist(str) - return str and str ~= "" + return str and str ~= '' end ---@type (fun(res):any)[] @@ -71,18 +71,18 @@ local formatter = { return end local tag_map = { - zk = "中考", - gk = "高考", - ky = "考研", - gre = "gre ", - cet4 = "四级", - cet6 = "六级", - ielts = "雅思", - toefl = "托福", + zk = '中考', + gk = '高考', + ky = '考研', + gre = 'gre ', + cet4 = '四级', + cet6 = '六级', + ielts = '雅思', + toefl = '托福', } local tag = {} - for i, _tag in ipairs(vim.split(res.tag, " ", { plain = true })) do + for i, _tag in ipairs(vim.split(res.tag, ' ', { plain = true })) do tag[i] = tag_map[_tag] end @@ -93,20 +93,20 @@ local formatter = { return end local exchange_map = { - ["0"] = "原型 ", - ["1"] = "类别 ", - ["p"] = "过去式 ", - ["r"] = "比较级 ", - ["t"] = "最高级 ", - ["s"] = "复数 ", - ["d"] = "过去分词 ", - ["i"] = "现在分词 ", - ["3"] = "第三人称单数", - ["f"] = "第三人称单数", + ['0'] = '原型 ', + ['1'] = '类别 ', + ['p'] = '过去式 ', + ['r'] = '比较级 ', + ['t'] = '最高级 ', + ['s'] = '复数 ', + ['d'] = '过去分词 ', + ['i'] = '现在分词 ', + ['3'] = '第三人称单数', + ['f'] = '第三人称单数', } local exchange = {} - for _, _exchange in ipairs(vim.split(res.exchange, "/", { plain = true })) do + for _, _exchange in ipairs(vim.split(res.exchange, '/', { plain = true })) do exchange[exchange_map[_exchange:sub(1, 1)]] = _exchange:sub(3) end @@ -117,24 +117,24 @@ local formatter = { return end 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 ", + 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 pos = {} - for _, _pos in ipairs(vim.split(res.pos, "/", { plain = true })) do - pos[pos_map[_pos:sub(1, 1)]] = ("%2s%%"):format(_pos:sub(3)) + for _, _pos in ipairs(vim.split(res.pos, '/', { plain = true })) do + pos[pos_map[_pos:sub(1, 1)]] = ('%2s%%'):format(_pos:sub(3)) end return pos @@ -144,7 +144,7 @@ local formatter = { return end local translation = {} - for i, _translation in ipairs(vim.split(res.translation, "\n", { plain = true })) do + for i, _translation in ipairs(vim.split(res.translation, '\n', { plain = true })) do translation[i] = _translation end @@ -155,9 +155,9 @@ local formatter = { return end local definition = {} - for i, _definition in ipairs(vim.split(res.definition, "\n", { plain = true })) do + for i, _definition in ipairs(vim.split(res.definition, '\n', { plain = true })) do -- -- TODO :判断是否需要分割空格 - definition[i] = _definition:gsub("^%s+", "", 1) + definition[i] = _definition:gsub('^%s+', '', 1) end return definition diff --git a/lua/Trans/backend/youdao.lua b/lua/Trans/backend/youdao.lua index d9d967b..d62961f 100644 --- a/lua/Trans/backend/youdao.lua +++ b/lua/Trans/backend/youdao.lua @@ -55,31 +55,31 @@ end local function check_untracked_field(body) local field = { - "phonetic", + 'phonetic', 'usPhonetic', - "ukPhonetic", - "text", -- text 短语 - "explain", -- String Array 词义解释列表 - "wordFormats", -- Object Array 单词形式变化列表 - "name", -- String 形式名称,例如:复数 - "phrase", -- String 词组 - "meaning", -- String 含义 - "synonyms", -- JSONObject 近义词 - "pos", -- String 词性 - "words", -- String Array 近义词列表 - "trans", -- String 释义 - "antonyms", -- ObjectArray 反义词 - "relatedWords", -- JSONArray 相关词 - "wordNet", -- JSONObject 汉语词典网络释义 - "phonetic", -- String 发音 - "meanings", -- ObjectArray 释义 - "meaning", -- String 释义 - "example", -- array 示例 - "sentenceSample", -- text 例句 - "sentence", -- text 例句 - "sentenceBold", -- text 将查询内容加粗的例句 - "wfs", -- text 单词形式变化 - "exam_type", -- text 考试类型 + 'ukPhonetic', + 'text', -- text 短语 + 'explain', -- String Array 词义解释列表 + 'wordFormats', -- Object Array 单词形式变化列表 + 'name', -- String 形式名称,例如:复数 + 'phrase', -- String 词组 + 'meaning', -- String 含义 + 'synonyms', -- JSONObject 近义词 + 'pos', -- String 词性 + 'words', -- String Array 近义词列表 + 'trans', -- String 释义 + 'antonyms', -- ObjectArray 反义词 + 'relatedWords', -- JSONArray 相关词 + 'wordNet', -- JSONObject 汉语词典网络释义 + 'phonetic', -- String 发音 + 'meanings', -- ObjectArray 释义 + 'meaning', -- String 释义 + 'example', -- array 示例 + 'sentenceSample', -- text 例句 + 'sentence', -- text 例句 + 'sentenceBold', -- text 将查询内容加粗的例句 + 'wfs', -- text 单词形式变化 + 'exam_type', -- text 考试类型 } for _, f in ipairs(field) do if body[f] then @@ -96,33 +96,33 @@ function M.debug(body) vim.notify('Unknown errors, nil body', vim.log.levels.ERROR) end local debug_msg = ({ - [101] = "缺少必填的参数,首先确保必填参数齐全,然后确认参数书写是否正确。", - [102] = "不支持的语言类型", - [103] = "翻译文本过长", - [104] = "不支持的API类型", - [105] = "不支持的签名类型", - [106] = "不支持的响应类型", - [107] = "不支持的传输加密类型", - [108] = "应用ID无效,注册账号,登录后台创建应用和实例并完成绑定,可获得应用ID和应用密钥等信息", - [109] = "batchLog格式不正确", - [110] = "无相关服务的有效实例,应用没有绑定服务实例,可以新建服务实例,绑定服务实例。注:某些服务的翻译结果发音需要tts实例,需要在控制台创建语音合成实例绑定应用后方能使用。", - [111] = "开发者账号无效", - [113] = "q不能为空", - [120] = "不是词,或未收录", - [201] = "解密失败,可能为DES,BASE64,URLDecode的错误", - [202] = "签名检验失败", - [203] = "访问IP地址不在可访问IP列表", - [205] = "请求的接口与应用的平台类型不一致,确保接入方式(Android SDK、IOS SDK、API)与创建的应用平台类型一致。如有疑问请参考入门指南", - [206] = "因为时间戳无效导致签名校验失败", - [207] = "重放请求", - [301] = "辞典查询失败", - [302] = "翻译查询失败", - [303] = "服务端的其它异常", - [305] = "批量翻译部分成功", - [401] = "账户已经欠费,请进行账户充值", - [411] = "访问频率受限,请稍后访问", - [412] = "长请求过于频繁,请稍后访问", - [390001] = "词典名称不正确", + [101] = '缺少必填的参数,首先确保必填参数齐全,然后确认参数书写是否正确。', + [102] = '不支持的语言类型', + [103] = '翻译文本过长', + [104] = '不支持的API类型', + [105] = '不支持的签名类型', + [106] = '不支持的响应类型', + [107] = '不支持的传输加密类型', + [108] = '应用ID无效,注册账号,登录后台创建应用和实例并完成绑定,可获得应用ID和应用密钥等信息', + [109] = 'batchLog格式不正确', + [110] = '无相关服务的有效实例,应用没有绑定服务实例,可以新建服务实例,绑定服务实例。注:某些服务的翻译结果发音需要tts实例,需要在控制台创建语音合成实例绑定应用后方能使用。', + [111] = '开发者账号无效', + [113] = 'q不能为空', + [120] = '不是词,或未收录', + [201] = '解密失败,可能为DES,BASE64,URLDecode的错误', + [202] = '签名检验失败', + [203] = '访问IP地址不在可访问IP列表', + [205] = '请求的接口与应用的平台类型不一致,确保接入方式(Android SDK、IOS SDK、API)与创建的应用平台类型一致。如有疑问请参考入门指南', + [206] = '因为时间戳无效导致签名校验失败', + [207] = '重放请求', + [301] = '辞典查询失败', + [302] = '翻译查询失败', + [303] = '服务端的其它异常', + [305] = '批量翻译部分成功', + [401] = '账户已经欠费,请进行账户充值', + [411] = '访问频率受限,请稍后访问', + [412] = '长请求过于频繁,请稍后访问', + [390001] = '词典名称不正确', })[tonumber(body.errorCode)] vim.notify('Youdao API Error: ' .. (debug_msg or vim.inspect(body)), vim.log.levels.ERROR) @@ -134,7 +134,7 @@ end ---@param data TransData Data obj ---@return table|false? function M.formatter(body, data) - if body.errorCode ~= "0" then return false end + if body.errorCode ~= '0' then return false end check_untracked_field(body) if not body.isWord then @@ -146,15 +146,14 @@ function M.formatter(body, data) return { - title = { + title = { word = body.query, phonetic = body.basic.phonetic, }, - web = body.web, - explains = body.basic.explains, + web = body.web, + explains = body.basic.explains, [data.from == 'en' and 'translation' or 'definition'] = body.translation, } - end ---@class TransBackend diff --git a/lua/Trans/core/backend.lua b/lua/Trans/core/backend.lua index ce80914..bbb6390 100644 --- a/lua/Trans/core/backend.lua +++ b/lua/Trans/core/backend.lua @@ -1,4 +1,4 @@ -local Trans = require('Trans') +local Trans = require 'Trans' ---@class TransBackend @@ -18,12 +18,12 @@ local Trans = require('Trans') local conf = Trans.conf --- INFO :Parse online engine keys config file local path = conf.dir .. '/Trans.json' -local file = io.open(path, "r") +local file = io.open(path, 'r') local user_conf = {} if file then - local content = file:read("*a") + local content = file:read '*a' user_conf = vim.json.decode(content) or user_conf file:close() end @@ -56,5 +56,5 @@ return setmetatable({ self[name] = backend return backend - end + end, }) diff --git a/lua/Trans/core/conf.lua b/lua/Trans/core/conf.lua index c691895..3652ad8 100644 --- a/lua/Trans/core/conf.lua +++ b/lua/Trans/core/conf.lua @@ -5,7 +5,7 @@ ---@class TransConf return { ---@type string the directory for database file and password file - dir = require('Trans').relative_path({ 'extra' }, true), + dir = require 'Trans'.relative_path({ 'extra' }, true), debug = true, ---@type 'default' | 'dracula' | 'tokyonight' global Trans theme [see lua/Trans/style/theme.lua] theme = 'default', -- default | tokyonight | dracula @@ -23,7 +23,7 @@ return { default = { query = 'fallback', border = 'rounded', - title = vim.fn.has('nvim-0.9') == 1 and { + title = vim.fn.has 'nvim-0.9' == 1 and { { '', 'TransTitleRound' }, { ' Trans', 'TransTitle' }, { '', 'TransTitleRound' }, @@ -49,7 +49,7 @@ return { fallback_message = '{{notfound}} 翻译超时或没有找到相关的翻译', auto_resize = true, split_width = 60, - padding = 10, -- padding for hover window width + padding = 10, -- padding for hover window width keymaps = { pageup = '[[', pagedown = ']]', @@ -84,9 +84,8 @@ return { 'translation', 'definition', 'web', - } + }, }, - ---@type table icon = { -- or use emoji list = '●', -- ● | ○ | ◉ | ◯ | ◇ | ◆ | ▪ | ▫ | ⬤ | 🟢 | 🟡 | 🟣 | 🟤 | 🟠| 🟦 | 🟨 | 🟧 | 🟥 | 🟪 | 🟫 | 🟩 | 🟦 diff --git a/lua/Trans/core/data.lua b/lua/Trans/core/data.lua index ee576da..35f4ea6 100644 --- a/lua/Trans/core/data.lua +++ b/lua/Trans/core/data.lua @@ -1,4 +1,4 @@ -local Trans = require('Trans') +local Trans = require 'Trans' ---@class TransData @@ -21,8 +21,8 @@ function M.new(opts) local mode = opts.mode local str = opts.str - local strategy = Trans.conf.strategy[mode] + local strategy = Trans.conf.strategy[mode] local data = setmetatable({ str = str, mode = mode, diff --git a/lua/Trans/core/frontend.lua b/lua/Trans/core/frontend.lua index ded3ddd..148831b 100644 --- a/lua/Trans/core/frontend.lua +++ b/lua/Trans/core/frontend.lua @@ -1,4 +1,4 @@ -local Trans = require('Trans') +local Trans = require 'Trans' local conf = Trans.conf local frontend_opts = conf.frontend @@ -50,5 +50,5 @@ return setmetatable({}, { set_frontend_keymap(frontend) return frontend - end + end, }) diff --git a/lua/Trans/core/immersive.lua b/lua/Trans/core/immersive.lua index 6c48b97..a86354b 100644 --- a/lua/Trans/core/immersive.lua +++ b/lua/Trans/core/immersive.lua @@ -4,22 +4,22 @@ local function trans() -- TODO : trim empty lines in the beginning and the end for index, line in ipairs(lines) do - if line:match('%S+') then + if line:match '%S+' then table.insert(paragraphs, { index - 1, line }) end end - local Trans = require('Trans') + local Trans = require 'Trans' local baidu = Trans.backend.baidu ---@cast baidu Baidu for _, line in ipairs(paragraphs) do - local query = baidu.get_query({ + local query = baidu.get_query { str = line[2], - from = "en", - to = "zh", - }) + from = 'en', + to = 'zh', + } Trans.curl.get(baidu.uri, { query = query, @@ -27,9 +27,9 @@ local function trans() -- vim.print(output) local body = output.body local status, ret = pcall(vim.json.decode, body) - assert(status and ret, "Failed to parse json:" .. vim.inspect(body)) + assert(status and ret, 'Failed to parse json:' .. vim.inspect(body)) local result = ret.trans_result - assert(result, "Failed to get result: " .. vim.inspect(ret)) + assert(result, 'Failed to get result: ' .. vim.inspect(ret)) result = result[1] @@ -38,7 +38,7 @@ local function trans() }) end - local ns = vim.api.nvim_create_namespace("Trans") + local ns = vim.api.nvim_create_namespace 'Trans' for _, line in ipairs(paragraphs) do local index = line[1] local co = coroutine.running() @@ -60,12 +60,12 @@ local function trans() Trans.util.main_loop(function() vim.api.nvim_buf_set_extmark(0, ns, index, #line[2], { virt_lines = { - { { translation, "MoreMsg" } } + { { translation, 'MoreMsg' } }, }, }) end) - print('done') + print 'done' end -- TODO :双语翻译 end diff --git a/lua/Trans/core/install.lua b/lua/Trans/core/install.lua index 9ca7dea..b97b66f 100644 --- a/lua/Trans/core/install.lua +++ b/lua/Trans/core/install.lua @@ -1,7 +1,7 @@ ---@class Trans ---@field install fun() Download database and tts dependencies return function() - local Trans = require('Trans') + local Trans = require 'Trans' -- INFO :Check ultimate.db exists local dir = Trans.conf.dir local path = dir .. 'ultimate.db' @@ -26,7 +26,7 @@ return function() local handle = function(output) if output.exit == 0 and fn.filereadable(zip) then - if fn.executable('unzip') == 0 then + if fn.executable 'unzip' == 0 then vim.notify('unzip not found, Please unzip ' .. zip .. 'manually', vim.log.ERROR) return end @@ -50,7 +50,7 @@ return function() }) -- INFO : Install tts dependencies - if fn.has('linux') == 0 and fn.has('mac') == 0 then - os.execute('cd ./tts && npm install') + if fn.has 'linux' == 0 and fn.has 'mac' == 0 then + os.execute 'cd ./tts && npm install' end end diff --git a/lua/Trans/core/setup.lua b/lua/Trans/core/setup.lua index 8405be8..b6673d9 100644 --- a/lua/Trans/core/setup.lua +++ b/lua/Trans/core/setup.lua @@ -1,4 +1,4 @@ -local Trans = require('Trans') +local Trans = require 'Trans' local function set_strategy_opts(conf) local all_backends = Trans.backend.all_name @@ -21,7 +21,7 @@ local function set_strategy_opts(conf) setmetatable(conf.strategy, { __index = function() return default_strategy - end + end, }) for _, strategy in pairs(conf.strategy) do diff --git a/lua/Trans/core/translate.lua b/lua/Trans/core/translate.lua index 895af14..bfb7d99 100644 --- a/lua/Trans/core/translate.lua +++ b/lua/Trans/core/translate.lua @@ -1,4 +1,4 @@ -local Trans = require('Trans') +local Trans = require 'Trans' local util = Trans.util local function init_opts(opts) @@ -19,7 +19,7 @@ local function do_query(data, backend) local method = backend.method local formatter = backend.formatter local query = backend.get_query(data) - local header = type(backend.header) == "function" and backend.header(data) or backend.header + local header = type(backend.header) == 'function' and backend.header(data) or backend.header local function handle(output) local status, body = pcall(vim.json.decode, output.body) diff --git a/lua/Trans/core/util.lua b/lua/Trans/core/util.lua index 903f48b..9943ac0 100644 --- a/lua/Trans/core/util.lua +++ b/lua/Trans/core/util.lua @@ -1,14 +1,14 @@ local fn, api = vim.fn, vim.api ---@class TransUtil -local M = require('Trans').metatable('util') +local M = require 'Trans'.metatable 'util' ---Get selected text ---@return string function M.get_select() - local _start = fn.getpos("v") - local _end = fn.getpos('.') + local _start = fn.getpos 'v' + local _end = fn.getpos '.' if _start[2] > _end[2] or (_start[3] > _end[3] and _start[2] == _end[2]) then _start, _end = _end, _start @@ -42,19 +42,19 @@ end function M.get_str(mode) return ({ n = function() - return fn.expand('') + return fn.expand '' end, v = function() - api.nvim_input('') + api.nvim_input '' return M.get_select() end, i = function() - return fn.input('需要翻译的字符串: ') + return fn.input '需要翻译的字符串: ' end, V = function() - print('TODO') - end - })[mode]():match('^%s*(.-)%s*$') + print 'TODO' + end, + })[mode]():match '^%s*(.-)%s*$' end ---Puase coroutine for {ms} milliseconds @@ -103,7 +103,6 @@ function M.display_width(lines) return width end - ---Center node utility function ---@param node string -- TODO :Node ---@param win_width integer window width @@ -175,7 +174,7 @@ end ---@param str string ---@return boolean function M.is_word(str) - return str:match('%w+') == str + return str:match '%w+' == str end ---@param list any[] diff --git a/lua/Trans/core/window.lua b/lua/Trans/core/window.lua index 7d20e71..4a1b019 100644 --- a/lua/Trans/core/window.lua +++ b/lua/Trans/core/window.lua @@ -1,6 +1,6 @@ local api = vim.api ---@class Trans -local Trans = require("Trans") +local Trans = require 'Trans' ---@class TransWindow local window = {} @@ -61,10 +61,10 @@ function window:adjust_height(height) local display_height = Trans.util.display_height(self.buffer:lines(), self:width()) height = height and math.min(display_height, height) or display_height - self:smooth_expand({ + self:smooth_expand { field = 'height', - to = height - }) + to = height, + } end ---Expand window [width | height] value @@ -82,7 +82,7 @@ function window:smooth_expand(opts) local method = api['nvim_win_set_' .. field] - local wrap = self:option('wrap') + local wrap = self:option 'wrap' local interval = self.animation.interval for i = from + 1, to, (from < to and 1 or -1) do self:set('wrap', false) @@ -99,14 +99,14 @@ function window:resize(opts) if opts.height and self:height() ~= opts.height then self:smooth_expand { field = 'height', - to = opts.height + to = opts.height, } end if opts.width and self:width() ~= opts.width then self:smooth_expand { field = 'width', - to = opts.width + to = opts.width, } end end @@ -120,10 +120,10 @@ function window:try_close() fold = 'height', })[close_animation] - self:smooth_expand({ + self:smooth_expand { field = field, to = 1, - }) + } end api.nvim_win_close(self.winid, true) @@ -150,10 +150,10 @@ function window:open() local to = win_opts[field] win_opts[field] = 1 self.winid = api.nvim_open_win(self.buffer.bufnr, self.enter, win_opts) - self:smooth_expand({ + self:smooth_expand { field = field, to = to, - }) + } else self.winid = api.nvim_open_win(self.buffer.bufnr, self.enter, win_opts) end diff --git a/lua/Trans/frontend/hover/execute.lua b/lua/Trans/frontend/hover/execute.lua index 3b4edfa..651893e 100644 --- a/lua/Trans/frontend/hover/execute.lua +++ b/lua/Trans/frontend/hover/execute.lua @@ -3,10 +3,10 @@ local api = vim.api ---@type table local strategy = { pageup = function(hover) - hover.buffer:normal("gg") + hover.buffer:normal 'gg' end, pagedown = function(hover) - hover.buffer:normal("G") + hover.buffer:normal 'G' end, pin = function(hover) if hover.pin then @@ -22,10 +22,10 @@ local strategy = { col = col, width = width, height = height, - relative = "editor", + relative = 'editor', } - window:set("wrap", true) + window:set('wrap', true) end, close = function(hover) hover:destroy() diff --git a/lua/Trans/frontend/hover/init.lua b/lua/Trans/frontend/hover/init.lua index 0b202e7..60fd2a7 100644 --- a/lua/Trans/frontend/hover/init.lua +++ b/lua/Trans/frontend/hover/init.lua @@ -1,5 +1,5 @@ ---@type Trans -local Trans = require("Trans") +local Trans = require 'Trans' -- FIXME :Adjust Window Size @@ -11,8 +11,8 @@ local Trans = require("Trans") ---@field destroy_funcs fun(hover:TransHover)[] @functions to be executed when hover window is closed ---@field opts TransHoverOpts @options for hover window ---@field pin boolean @whether hover window is pinned -local M = Trans.metatable("frontend.hover", { - ns = vim.api.nvim_create_namespace("TransHoverWin"), +local M = Trans.metatable('frontend.hover', { + ns = vim.api.nvim_create_namespace 'TransHoverWin', queue = {}, }) M.__index = M @@ -85,12 +85,12 @@ function M:init_window(opts) title = m_opts.title, width = opts.width or m_opts.width, height = opts.height or m_opts.height, - relative = opts.relative or "cursor", + relative = opts.relative or 'cursor', } -- stylua: ignore end if win_opts.title then - win_opts.title_pos = "center" + win_opts.title_pos = 'center' end option.win_opts = win_opts @@ -103,7 +103,7 @@ end ---@return string formatted text ---@return integer _ replaced count function M:icon_format(format) - return format:gsub("{{(%w+)}}", self.opts.icon) + return format:gsub('{{(%w+)}}', self.opts.icon) end ---Get Check function for waiting @@ -127,7 +127,7 @@ function M:wait() return function() cur = cur + 1 buffer[1] = spinner[cur % size + 1] .. (cell):rep(cur) - buffer:add_highlight(1, "TransWaitting") + buffer:add_highlight(1, 'TransWaitting') pause(interval) return cur < times end @@ -150,14 +150,14 @@ function M:fallback() -- TODO :Center buffer[1] = Trans.util.center(fallback_msg, opts.width) - buffer:add_highlight(1, "TransFailed") + buffer:add_highlight(1, 'TransFailed') self:defer() end ---Defer function when process done function M:defer() - self.window:set("wrap", true) - self.buffer:set("modifiable", false) + self.window:set('wrap', true) + self.buffer:set('modifiable', false) local auto_close_events = self.opts.auto_close_events if not auto_close_events then return end @@ -191,7 +191,7 @@ function M:process(data) local buffer = self.buffer if opts.auto_play then - (data.from == "en" and data.str or result.definition[1]):play() + (data.from == 'en' and data.str or result.definition[1]):play() end -- vim.pretty_print(result) diff --git a/lua/Trans/frontend/hover/load.lua b/lua/Trans/frontend/hover/load.lua index 92952b0..41aa9ac 100644 --- a/lua/Trans/frontend/hover/load.lua +++ b/lua/Trans/frontend/hover/load.lua @@ -1,4 +1,4 @@ -local node = require('Trans').util.node +local node = require 'Trans'.util.node local it, conjunction = node.item, node.conjunction local interval = (' '):rep(4) @@ -35,7 +35,7 @@ local default = { ) end - buffer:setline('') + buffer:setline '' end, definition = function(hover, result) local definition = result.definition @@ -50,7 +50,7 @@ local default = { ) end - buffer:setline('') + buffer:setline '' end, } diff --git a/lua/Trans/frontend/hover/offline.lua b/lua/Trans/frontend/hover/offline.lua index fee7d79..6a93510 100644 --- a/lua/Trans/frontend/hover/offline.lua +++ b/lua/Trans/frontend/hover/offline.lua @@ -1,4 +1,4 @@ -local node = require('Trans').util.node +local node = require 'Trans'.util.node local it, t, f, co = node.item, node.text, node.format, node.conjunction local interval = (' '):rep(4) @@ -26,7 +26,7 @@ function M.title(hover, result) t { it { '[' }, it { (phonetic and phonetic ~= '') and phonetic or icon.notfound, 'TransPhonetic' }, - it { ']' } + it { ']' }, }, it { collins and icon.star:rep(collins) or icon.notfound, 'TransCollins' }, @@ -54,7 +54,7 @@ function M.tag(hover, result) }) end - buffer:setline('') + buffer:setline '' end function M.exchange(hover, result) @@ -70,7 +70,7 @@ function M.exchange(hover, result) ) end - buffer:setline('') + buffer:setline '' end function M.pos(hover, result) @@ -86,7 +86,7 @@ function M.pos(hover, result) ) end - buffer:setline('') + buffer:setline '' end return M diff --git a/lua/Trans/health.lua b/lua/Trans/health.lua index 5383b84..e26b13b 100644 --- a/lua/Trans/health.lua +++ b/lua/Trans/health.lua @@ -1,4 +1,4 @@ -local Trans = require('Trans') +local Trans = require 'Trans' local health, fn = vim.health, vim.fn local ok = health.report_ok @@ -8,73 +8,73 @@ local has = fn.has local executable = fn.executable local function check_neovim_version() - if has("nvim-0.9") == 1 then - ok([[You have [neovim-nightly] ]]) + if has 'nvim-0.9' == 1 then + ok [[You have [neovim-nightly] ]] else - warn([[Trans Title requires Neovim 0.9 or newer + warn [[Trans Title requires Neovim 0.9 or newer See neovim-nightly: [https://github.com/neovim/neovim/releases/tag/nightly] - ]]) + ]] end end local function check_plugin_dependencies() local plugin_dependencies = { -- 'plenary', - "sqlite", + 'sqlite', } for _, dep in ipairs(plugin_dependencies) do if pcall(require, dep) then - ok(string.format("Dependency [%s] is installed", dep)) + ok(string.format('Dependency [%s] is installed', dep)) else - error(string.format("Dependency [%s] is not installed", dep)) + error(string.format('Dependency [%s] is not installed', dep)) end end end local function check_binary_dependencies() local binary_dependencies = { - "curl", - "sqlite3", + 'curl', + 'sqlite3', } - if has("linux") == 1 then - binary_dependencies[3] = "festival" - elseif has("mac") == 1 then - binary_dependencies[3] = "say" + if has 'linux' == 1 then + binary_dependencies[3] = 'festival' + elseif has 'mac' == 1 then + binary_dependencies[3] = 'say' else - binary_dependencies[3] = "node" + binary_dependencies[3] = 'node' end for _, dep in ipairs(binary_dependencies) do if executable(dep) == 1 then - ok(string.format("Binary dependency [%s] is installed", dep)) + ok(string.format('Binary dependency [%s] is installed', dep)) else - error(string.format("Binary dependency [%s] is not installed", dep)) + error(string.format('Binary dependency [%s] is not installed', dep)) end end end local function check_database() - local db_path = Trans.conf.dir .. Trans.separator .. "ultimate.db" + local db_path = Trans.conf.dir .. Trans.separator .. 'ultimate.db' if fn.filereadable(db_path) == 1 then - ok([[ultimate database found ]]) + ok [[ultimate database found ]] else - error([[Stardict database not found + error [[Stardict database not found [Manually]: Please check the doc in github: [https://github.com/JuanZoran/Trans.nvim] [Automatically]: Try to run `:lua require "Trans".install()` - ]]) + ]] end end local function check_configure_file() - local path = fn.expand(Trans.conf.dir .. Trans.separator .. "Trans.json") + local path = fn.expand(Trans.conf.dir .. Trans.separator .. 'Trans.json') if not fn.filereadable(path) then - warn("Backend configuration file[%s] not found") + warn 'Backend configuration file[%s] not found' end - local file = io.open(path, "r") - local valid = file and pcall(vim.json.decode, file:read("*a")) + local file = io.open(path, 'r') + local valid = file and pcall(vim.json.decode, file:read '*a') if valid then ok(string.format([[Backend configuration file [%s] found and valid ]], path)) diff --git a/lua/Trans/init.lua b/lua/Trans/init.lua index cb82ae9..6de2beb 100644 --- a/lua/Trans/init.lua +++ b/lua/Trans/init.lua @@ -5,7 +5,7 @@ local function metatable(folder_name, origin) return setmetatable(origin or {}, { __index = function(tbl, key) - local status, result = pcall(require, ("Trans.%s.%s"):format(folder_name, key)) + local status, result = pcall(require, ('Trans.%s.%s'):format(folder_name, key)) if status then tbl[key] = result return result @@ -19,16 +19,16 @@ end ---@field play function @Use tts to play string -local separator = vim.loop.os_uname().sysname == "Windows" and "\\" or "/" +local separator = vim.loop.os_uname().sysname == 'Windows' and '\\' or '/' ---@class Trans ---@field style table @Style module ---@field cache table @Cache for translated data object ---@field plugin_dir string @Plugin directory ---@field separator string @Path separator -local M = metatable("core", { +local M = metatable('core', { cache = {}, - style = metatable("style"), - plugin_dir = debug.getinfo(1, "S").source:sub(2):match("(.-)lua" .. separator .. "Trans"), + style = metatable 'style', + plugin_dir = debug.getinfo(1, 'S').source:sub(2):match('(.-)lua' .. separator .. 'Trans'), separator = separator, }) @@ -39,7 +39,7 @@ M.metatable = metatable ---@param is_dir boolean? ---@return string function M.relative_path(path, is_dir) - return M.plugin_dir .. table.concat(path, separator) .. (is_dir and separator or "") + return M.plugin_dir .. table.concat(path, separator) .. (is_dir and separator or '') end return M diff --git a/lua/Trans/util/init.lua b/lua/Trans/util/init.lua deleted file mode 100644 index 53a976e..0000000 --- a/lua/Trans/util/init.lua +++ /dev/null @@ -1,16 +0,0 @@ -local M = {} -M.test_api_latency = function(urls) - urls = type(urls) == 'string' and { urls } or urls - - local f = [[curl -s -o /dev/null -w '[%s]延迟: %%{time_total}s %s']] - local result = {} - for _, url in ipairs(urls) do - local cmd = string.format(f, url, url) - local res = vim.fn.system(cmd) - result[#result + 1] = res - end - - vim.pretty_print(result) -end - -return M diff --git a/lua/Trans/util/node.lua b/lua/Trans/util/node.lua index 73626b0..db12531 100644 --- a/lua/Trans/util/node.lua +++ b/lua/Trans/util/node.lua @@ -1,4 +1,4 @@ -local util = require('Trans').util +local util = require 'Trans'.util ---@class TransNode ---@field [1] string text to be rendered @@ -29,7 +29,7 @@ local text_meta = { render = function(self, buffer, line, col) local nodes = self.nodes local step = self.step - local len = step and #step or 0 + local len = step and #step or 0 for _, node in ipairs(nodes) do node:render(buffer, line, col) @@ -66,7 +66,7 @@ end ---@return TransText local function format(args) local width = args.width - local spin = args.spin or " " + local spin = args.spin or ' ' local size = #args local wid = 0 for i = 1, size do @@ -93,9 +93,9 @@ return { format = format, conjunction = function(str) return { - item { "", "TransTitleRound" }, - item { str, "TransTitle" }, - item { "", "TransTitleRound" }, + item { '', 'TransTitleRound' }, + item { str, 'TransTitle' }, + item { '', 'TransTitleRound' }, } end, }