Created
October 5, 2022 14:14
-
-
Save tlindsay/6eafaae8b3555de52623b3fc8ad0bf58 to your computer and use it in GitHub Desktop.
Neovim buffer -> Rust Playground
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
function rust_playground(opts) | |
---@diagnostic disable-next-line: redefined-local | |
local opts = opts or {} | |
local copy = opts.copy or false | |
local open = opts.open or false | |
local char_to_hex = function(c) | |
return string.format('%%%02X', string.byte(c)) | |
end | |
local function urlencode(url) | |
if url == nil then | |
return | |
end | |
url = url:gsub('\n', '\r\n') | |
url = url:gsub('([^%w ])', char_to_hex) | |
url = url:gsub(' ', '+') | |
return url | |
end | |
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false) | |
local text = table.concat(lines, '\n') | |
local encoded = urlencode(text) | |
local root_url = 'https://play.rust-lang.org/' | |
local opts = { | |
'version=stable', | |
'mode=debug', | |
'edition=2021', | |
'code=' .. encoded, | |
} | |
local final_url = root_url .. '?' .. table.concat(opts, '&') | |
if open then | |
vim.fn.system({ 'open', final_url }) | |
end | |
if copy then | |
vim.cmd("let @*=trim('" .. final_url .. "')") | |
end | |
if not open and not copy then | |
print(final_url) | |
end | |
return final_url | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment