80 lines
2.0 KiB
Lua
80 lines
2.0 KiB
Lua
local shortenurl = {}
|
|
|
|
-- Trim whitespace from string.
|
|
local function trim(s)
|
|
return (s:gsub("^%s*(.-)%s*$", "%1"))
|
|
end
|
|
|
|
-- Get url on the current line.
|
|
local function get_url()
|
|
local line = vim.api.nvim_get_current_line()
|
|
local url = string.match(line, 'http?s://[^ ,;)]*')
|
|
return url
|
|
end
|
|
|
|
-- Remove trailing newline if present
|
|
local function trimNewline(s)
|
|
return s:gsub("\n$", "")
|
|
end
|
|
|
|
local function trimQuotes(s)
|
|
return s:gsub("\"", "")
|
|
end
|
|
|
|
-- Helper function that prompts for user input to generate a short link.
|
|
shortenurl.prompt = function(s)
|
|
local url = s
|
|
if not url or string.len(url) == 0 then
|
|
url = vim.fn.input("URL: ")
|
|
end
|
|
|
|
local tags = vim.fn.input("[Optional] Tag(s) (seperated by commas): ")
|
|
local expires = vim.fn.input("[Optional] Expire: ")
|
|
local shortCode = vim.fn.input("[Optional] Short Code: ")
|
|
local cmd = "shorten-url --no-spin create"
|
|
|
|
for tag in tags:gmatch('([^,]+)') do
|
|
cmd = cmd .. " --tag " .. trim(tag)
|
|
end
|
|
|
|
if string.len(expires) > 0 then
|
|
cmd = cmd .. " --expire " .. expires
|
|
end
|
|
|
|
if string.len(shortCode) > 0 then
|
|
cmd = cmd .. " --code " .. shortCode
|
|
end
|
|
|
|
cmd = cmd .. " " .. url
|
|
return cmd
|
|
end
|
|
|
|
-- Convert url on the current line.
|
|
shortenurl.convertUrl = function()
|
|
local url = get_url()
|
|
local cmd = shortenurl.prompt(url)
|
|
local output = trimNewline(vim.fn.system(cmd))
|
|
if output == "" then
|
|
print("Got empty output")
|
|
return
|
|
end
|
|
output = trimQuotes(output)
|
|
-- Replace occurence of the url with the shortened url.
|
|
vim.cmd(":%s/" .. vim.fn.escape(url, "/") .. "/" .. vim.fn.escape(output, "/"))
|
|
end
|
|
|
|
-- Convert a url in the system clipboard, and insert at cursor postion.
|
|
shortenurl.convertFromClipboard = function()
|
|
local url = trimNewline(vim.fn.system("wl-paste"))
|
|
local cmd = shortenurl.prompt(url)
|
|
local output = trimNewline(vim.fn.system(cmd))
|
|
if not output or output == "" then
|
|
print("Got empty output")
|
|
return
|
|
end
|
|
local row, col = unpack(vim.api.nvim_win_get_cursor(0))
|
|
vim.api.nvim_buf_set_text(0, row - 1, col, row - 1, col, { output })
|
|
end
|
|
|
|
return shortenurl
|