Skip to content

Commit

Permalink
fix(externalDocs): default to xdg-open/open / remove redundant urlencode
Browse files Browse the repository at this point in the history
  • Loading branch information
mrcjkb committed Oct 22, 2023
1 parent 6cd9686 commit acdb16d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 15 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.1.1] - 2023-10-22

### Fixed

- Open external docs: Use `xdg-open` or `open` (MacOS) by default
and fall back to `netrw`.
Remove redundant URL encoding.

## [2.1.0] - 2023-10-22

### Added
Expand Down
43 changes: 28 additions & 15 deletions lua/ferris/commands/external_docs.lua
Original file line number Diff line number Diff line change
@@ -1,27 +1,40 @@
local M = {}

---@param c string A single character
---@return string The hex representation
local char_to_hex = function(c)
return string.format('%%%02X', c:byte())
end
local rl = require('ferris.rust_analyzer')

---Encode a URL so it can be opened in a browser
---@param url string
---@return string encoded_url
local function urlencode(url)
url = url:gsub('\n', '\r\n')
url = url:gsub('([^%w ])', char_to_hex)
url = url:gsub(' ', '+')
return url
end
local function open_url(url)
---@param obj table
local function on_exit(obj)
if obj.code ~= 0 then
vim.schedule(function()
vim.notify('Could not open URL: ' .. url, vim.log.levels.ERROR)
end)
end
end

local rl = require('ferris.rust_analyzer')
if vim.fn.has('mac') == 1 then
vim.system({ 'open', url }, nil, on_exit)
return
end
if vim.fn.executable('sensible-browser') == 1 then
vim.system({ 'sensible-browser', url }, nil, on_exit)
return
end
if vim.fn.executable('xdg-open') == 1 then
vim.system({ 'xdg-open', url }, nil, on_exit)
return
end
local ok, err = pcall(vim.fn['netrw#BrowseX'], url, 0)
if not ok then
vim.notify('Could not open external docs. Neither xdg-open, nor netrw found: ' .. err, vim.log.levels.ERROR)
end
end

function M.open_external_docs()
rl.buf_request(0, 'experimental/externalDocs', vim.lsp.util.make_position_params(), function(_, url)
if url then
vim.fn['netrw#BrowseX'](urlencode(url), 0)
open_url(url)
end
end)
end
Expand Down

0 comments on commit acdb16d

Please sign in to comment.