Ber*_*kin 3 lua asynchronous neovim
我试图让 Vim 在白天自动更改其主题,每 30 秒运行一次检查。我正在遵循本指南。不过,我想借助这个网站将他的 Vimscript 功能移植到 Lua 上。问题是,当我运行代码时,它在前台运行,这意味着在杀死它之前我无法执行任何操作。
这是 Vimscript 代码:
" Automatic light mode / dark mode switcher
function! ChangeColorScheme(channel, msg)
let time = trim(a:msg)
if time ==# "day"
call LightMode()
else
call DarkMode()
endif
endfunction
function! Sunshine(timer)
if executable("sunshine")
" Add your desired location here instead of '@45 15' (I probably could have
" made it into a variable)
let job = job_start(["sunshine", "-s", "@45 15"], {"out_cb": "ChangeColorScheme"})
else
call DarkMode()
endif
endfunction
function! AutoDarkModeSetup()
let timer = timer_start(30000, 'Sunshine', {'repeat': -1})
call Sunshine(timer) " Initial call to setup the theme
endfunction
call AutoDarkModeSetup()
Run Code Online (Sandbox Code Playgroud)
这是我的 Lua 代码:
-- Automatic light mode / dark mode switcher
local loop = vim.loop
local cmd = vim.cmd
local stat = require("posix.sys.stat")
local socket = require ("socket")
local gettime = socket.gettime
function LightMode()
cmd [[colorscheme github]]
end
function DarkMode()
cmd [[colorscheme dracula]]
end
function trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
function ChangeColorScheme(msg)
local time = trim(msg)
if time == "day" then
return LightMode()
else
return DarkMode()
end
end
function Sunshine()
if stat["/usr/local/bin/sunshine"] then
job = loop.spawn('sunshine', {
args = {'-s', '@36 30'},
stdio = {nil,stdout,stderr}
},
vim.schedule_wrap(function()
stdout:read_stop()
stderr:read_stop()
stdout:close()
stderr:close()
job:close()
setQF()
end
)
)
loop.read_start(stdout, ChangeColorScheme)
loop.read_start(stderr, ChangeColorScheme)
else
return DarkMode()
end
end
function AutoDarkModeSetup()
local function timer(seconds)
local exp_time = gettime() + seconds
return function()
if gettime() < exp_time then return false end
exp_time = exp_time + seconds
return true
end
end
local t1 = timer(30) -- a timer that expires every 30 seconds
while true do
if t1() then Sunshine() end
end
end
AutoDarkModeSetup()
Run Code Online (Sandbox Code Playgroud)
我通过简单地添加 require() 在 init.lua 中调用它。
如果我的问题太明显,我深表歉意,我以前从未用 Lua 编码过。
小智 6
你可以timer像这样使用 vim.loop :
local function time_background()
local timer = vim.loop.new_timer()
timer:start(0, 600, vim.schedule_wrap(function()
local hour = tonumber(os.date('%H'))
local bg = (hour > 6 and hour < 18) and 'light' or 'dark'
if vim.o.bg ~= bg then vim.o.bg = bg end
end))
end
Run Code Online (Sandbox Code Playgroud)