-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(neovim): Implement markdown paste function using lua
- Loading branch information
1 parent
b6be543
commit be022fa
Showing
2 changed files
with
35 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,48 @@ | ||
-- TODO: convert this to lua | ||
-- http://lua-users.org/wiki/GettingTheTitleFromHtmlFiles | ||
|
||
-- https://benjamincongdon.me/blog/2020/06/27/Vim-Tip-Paste-Markdown-Link-with-Automatic-Title-Fetching/ | ||
-- https://vim.fandom.com/wiki/Make_an_HTML_anchor_and_href_tag | ||
-- https://stackoverflow.com/questions/1115447/how-can-i-get-the-word-under-the-cursor-and-the-text-of-the-current-line-in-vim | ||
|
||
local function is_url(text) | ||
local url_pattern = "^https?://[%w-_%.%?%.:/%+=&]+$" | ||
return string.match(text, url_pattern) ~= nil | ||
end | ||
|
||
local function get_url_title(url) | ||
local html = os.execute("curl -s " .. url) | ||
local regex = ".*head.*<title[^>]*>%s*([^%s]*)%s*</title>" | ||
local title = string.gsub(string.match(html, regex), "\n", " ") | ||
local handle = io.popen("curl -s " .. url) | ||
if not handle then | ||
return "Error fetching URL" | ||
end | ||
|
||
local html = handle:read("*a") | ||
handle:close() | ||
|
||
if not html then | ||
return "Error reading HTML" | ||
end | ||
|
||
local title = html:match("<title>(.-)</title>") | ||
if title then | ||
title = title:gsub("\n", " "):gsub("%s+", " ") | ||
else | ||
title = "No Title Found" | ||
end | ||
return title | ||
end | ||
|
||
local function paste_md_link() | ||
local url = vim.fn.getreg('+') | ||
|
||
if not is_url(url) then | ||
print("Clipboard content is not a valid URL") | ||
return | ||
end | ||
|
||
local title = get_url_title(url) | ||
vim.fn.put("[", title, "](", url, ")") | ||
local markdown_link = string.format("[%s](%s)", title, url) | ||
|
||
vim.api.nvim_put({ markdown_link }, 'l', true, true) | ||
end | ||
|
||
-- Make a keybinding (mnemonic: "mark down paste") | ||
vim.keymap.set('n', '<Leader>mdp', paste_md_link(), {noremap = true}) | ||
vim.keymap.set('n', '<Leader>mdp', paste_md_link, { noremap = true, silent = true }) |