summaryrefslogtreecommitdiff
path: root/config/essentials/nvim/lua/user/live-server.lua
blob: 4f5992a40d70da89ddb8c5056fbbc09caba4e606 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
local M = {}
-- keep track of jobs
local live_servers = {}

function M.start_live_server()
	-- Search for available port and use it
    local port = 5500
    local running = true
    while running do
        local output = vim.fn.systemlist('lsof -i :' .. port)
        if #output == 0 then
            running = false
        else
            port = port + 1
        end
    end

    local command = "live-server --no-browser --port=" .. port .. " \"" .. vim.fn.expand("%:p:h") .. "\""
	-- run
    local job_id = vim.fn.jobstart(command, {
        on_exit = function(_, _, _) end
    })
	-- save
    live_servers[port] = job_id

    print("Started live-server on :" .. port .. ".")
end

function M.stop_live_servers()
    for port, job_id in pairs(live_servers) do
        local output = vim.fn.systemlist('lsof -i :' .. port)
        if #output > 0 then
            vim.fn.jobstop(job_id)
            print("Killed live-server on :" .. port .. ".")
        end
        live_servers[port] = nil
    end
end

vim.api.nvim_create_user_command("LiveServer", function(opts)
	local opt = string.format(opts.args)
	if #opts.args == 0 then
		M.start_live_server()
	elseif opt == "start" then
		M.start_live_server()
	elseif opt == "stop" then
		M.stop_live_servers()
	else
		print("Invalid argument. Usage: LiveServer [start|stop]")
	end
end, { nargs = '*' })

return M