From af6e6ccf3dee815850639ec5613dda3442caa7d6 Mon Sep 17 00:00:00 2001 From: marshmallow Date: Sun, 30 Apr 2023 15:53:02 +1000 Subject: feat(vim.ui): vim.ui.open, "gx" without netrw MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Mathias Fußenegger Co-authored-by: Justin M. Keyes Co-authored-by: ii14 <59243201+ii14@users.noreply.github.com> --- runtime/doc/lua.txt | 24 +++++++++++++++ runtime/doc/news.txt | 6 ++++ runtime/doc/various.txt | 8 +++++ runtime/lua/vim/lsp/handlers.lua | 15 +++------- runtime/lua/vim/ui.lua | 65 ++++++++++++++++++++++++++++++++++++++++ runtime/plugin/nvim.lua | 8 +++++ 6 files changed, 115 insertions(+), 11 deletions(-) (limited to 'runtime') diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index fb6cbca6e3..f180471bde 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -2343,6 +2343,30 @@ input({opts}, {on_confirm}) *vim.ui.input()* typed (it might be an empty string if nothing was entered), or `nil` if the user aborted the dialog. +open({path}) *vim.ui.open()* + Opens a path in the system's default handler. This function utilizes + `xdg-open`, `wslview`, `explorer`, or `open` commands depending on the + system to open the provided path. + + Notifies the user if unsuccessful + + Example: >lua + + vim.ui.open("https://neovim.io/") + + vim.ui.open("/path/to/file") +< + + Parameters: ~ + • {path} (string) Path to be opened + + Return: ~ + SystemCompleted|nil result Result of command, if an appropriate one + could be found. + + See also: ~ + • |vim.system| + select({items}, {opts}, {on_choice}) *vim.ui.select()* Prompts the user to pick from a list of items, allowing arbitrary (potentially asynchronous) work until `on_choice`. diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index 61ae92296f..ed797f94ba 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -107,6 +107,9 @@ The following new APIs and features were added. • Bundled treesitter parser and queries (highlight, folds) for Markdown, Python, and Bash. +• |vim.ui.open()| opens URIs using the system default handler (macOS `open`, +Windows `explorer`, Linux `xdg-open`, etc.) + ============================================================================== CHANGED FEATURES *news-changed* @@ -143,6 +146,9 @@ The following changes to existing APIs or features add new behavior. • |:Man| now respects 'wrapmargin' +• The |gx| command now uses |vim.ui.open()| and not netrw. Continue using +netrw with `vim.g.use_lua_gx = false`. + ============================================================================== REMOVED FEATURES *news-removed* diff --git a/runtime/doc/various.txt b/runtime/doc/various.txt index 1b1dca321b..de1c21b310 100644 --- a/runtime/doc/various.txt +++ b/runtime/doc/various.txt @@ -97,6 +97,14 @@ g8 Print the hex values of the bytes used in the cursor is halfway through a multibyte character the command won't move the cursor. + *gx* +gx Open the current path or URL under the cursor in the + system's default handler with |vim.ui.open|. + + To use the netrw keymap, set `use_lua_gx` to false: +>lua + vim.g.use_lua_gx = false +< *:p* *:pr* *:print* *E749* :[range]p[rint] [flags] Print [range] lines (default current line). diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 625a2ed282..9b102c0f84 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -573,22 +573,15 @@ M['window/showDocument'] = function(_, result, ctx, _) if result.external then -- TODO(lvimuser): ask the user for confirmation - local cmd - if vim.fn.has('win32') == 1 then - cmd = { 'cmd.exe', '/c', 'start', '""', uri } - elseif vim.fn.has('macunix') == 1 then - cmd = { 'open', uri } - else - cmd = { 'xdg-open', uri } - end - local ret = vim.fn.system(cmd) - if vim.v.shell_error ~= 0 then + local ret = vim.ui.open(uri) + + if ret.code ~= 0 or ret == nil then return { success = false, error = { code = protocol.ErrorCodes.UnknownErrorCode, - message = ret, + message = ret and ret.stderr or 'No handler could be found', }, } end diff --git a/runtime/lua/vim/ui.lua b/runtime/lua/vim/ui.lua index aaee175f3a..2200ee7bc3 100644 --- a/runtime/lua/vim/ui.lua +++ b/runtime/lua/vim/ui.lua @@ -104,4 +104,69 @@ function M.input(opts, on_confirm) end end +--- Opens a path in the system's default handler. +--- This function utilizes `xdg-open`, `wslview`, `explorer`, or `open` commands +--- depending on the system to open the provided path. +--- +--- Notifies the user if unsuccessful +--- +---@param path string Path to be opened +--- +---@return SystemCompleted|nil result Result of command, if an appropriate one +---could be found. +--- +---@see |vim.system| +--- +--- Example: +---
lua
+--- vim.ui.open("https://neovim.io/")
+---
+--- vim.ui.open("/path/to/file")
+--- 
+function M.open(path) + if not path or path == '' then + vim.notify('os_open: No path provided', vim.log.levels.ERROR) + return nil + end + + local cmd + + if vim.fn.has('macunix') == 1 then + cmd = { 'open', path } + elseif vim.fn.has('win32') == 1 then + cmd = { 'explorer', path } + else + if vim.fn.executable('wslview') == 1 then + cmd = { 'wslview', path } + elseif vim.fn.executable('xdg-open') == 1 then + cmd = { 'xdg-open', path } + else + vim.notify( + 'os_open: Could not find an appropriate command to use (Is xdg-open installed?)', + vim.log.levels.ERROR + ) + + return nil + end + end + + local ret = vim + .system(cmd, { + text = true, + detach = true, + }) + :wait() + + if ret.code ~= 0 then + local msg = { + 'Failed to open path', + ret, + vim.inspect(cmd), + } + vim.notify(table.concat(msg, '\n'), vim.log.levels.ERROR) + end + + return ret +end + return M diff --git a/runtime/plugin/nvim.lua b/runtime/plugin/nvim.lua index 0a33826b82..fcc1b016aa 100644 --- a/runtime/plugin/nvim.lua +++ b/runtime/plugin/nvim.lua @@ -18,3 +18,11 @@ vim.api.nvim_create_user_command('InspectTree', function(cmd) vim.treesitter.inspect_tree() end end, { desc = 'Inspect treesitter language tree for buffer', count = true }) + +if vim.g.use_lua_gx == nil or vim.g.use_lua_gx == true then + vim.keymap.set({ 'n', 'x' }, 'gx', function() + local uri = vim.fn.expand('') + + vim.ui.open(uri) + end, { desc = 'Open URI under cursor with system app' }) +end -- cgit From 67b2ed1004ae551c9fe1bbd29a86b5a301570800 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Sun, 2 Jul 2023 16:51:30 +0200 Subject: fix(gx): visual selection, expand env vars --- Rejected experiment: move vim.ui.open() to vim.env.open() Problem: `vim.ui` is where user-interface "providers" live, which can be overridden. It would also be useful to have a "providers" namespace for platform-specific features such as "open", clipboard, python, and the other providers listed in `:help providers`. We could overload `vim.ui` to serve that purpose as the single "providers" namespace, but `vim.ui.nodejs()` for example seems awkward. Solution: `vim.env` currently has too narrow of a purpose. Overload it to also be a namespace for `vim.env.open`. diff --git a/runtime/lua/vim/_meta.lua b/runtime/lua/vim/_meta.lua index 913f1fe20348..17d05ff37595 100644 --- a/runtime/lua/vim/_meta.lua +++ b/runtime/lua/vim/_meta.lua @@ -37,8 +37,28 @@ local options_info = setmetatable({}, { end, }) -vim.env = setmetatable({}, { - __index = function(_, k) +vim.env = setmetatable({ + open = setmetatable({}, { + __call = function(_, uri) + print('xxxxx'..uri) + return true + end, + __tostring = function() + local v = vim.fn.getenv('open') + if v == vim.NIL then + return nil + end + return v + end, + }) + }, + { + __index = function(t, k, ...) + if k == 'open' then + error() + -- vim.print({...}) + -- return rawget(t, k) + end local v = vim.fn.getenv(k) if v == vim.NIL then return nil --- runtime/doc/lua.txt | 20 +++++------ runtime/doc/news.txt | 9 ++--- runtime/doc/various.txt | 13 +++---- runtime/lua/vim/lsp/handlers.lua | 6 ++-- runtime/lua/vim/ui.lua | 75 ++++++++++++++++------------------------ runtime/plugin/nvim.lua | 17 +++++---- 6 files changed, 65 insertions(+), 75 deletions(-) (limited to 'runtime') diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index f180471bde..b09e308e80 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -2344,28 +2344,26 @@ input({opts}, {on_confirm}) *vim.ui.input()* entered), or `nil` if the user aborted the dialog. open({path}) *vim.ui.open()* - Opens a path in the system's default handler. This function utilizes - `xdg-open`, `wslview`, `explorer`, or `open` commands depending on the - system to open the provided path. + Opens `path` with the system default handler (macOS `open`, Windows + `explorer.exe`, Linux `xdg-open`, …), or shows a message on failure. - Notifies the user if unsuccessful + Expands "~/" and environment variables in filesystem paths. - Example: >lua + Examples: >lua vim.ui.open("https://neovim.io/") - - vim.ui.open("/path/to/file") + vim.ui.open("~/path/to/file") + vim.ui.open("$VIMRUNTIME") < Parameters: ~ - • {path} (string) Path to be opened + • {path} (string) Path or URL to open Return: ~ - SystemCompleted|nil result Result of command, if an appropriate one - could be found. + SystemCompleted|nil result Command result, or nil if not found. See also: ~ - • |vim.system| + • |vim.system()| select({items}, {opts}, {on_choice}) *vim.ui.select()* Prompts the user to pick from a list of items, allowing arbitrary diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index ed797f94ba..24e9dc917b 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -105,10 +105,10 @@ The following new APIs and features were added. https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_inlayHint • Bundled treesitter parser and queries (highlight, folds) for Markdown, -Python, and Bash. + Python, and Bash. • |vim.ui.open()| opens URIs using the system default handler (macOS `open`, -Windows `explorer`, Linux `xdg-open`, etc.) + Windows `explorer`, Linux `xdg-open`, etc.) ============================================================================== CHANGED FEATURES *news-changed* @@ -146,8 +146,9 @@ The following changes to existing APIs or features add new behavior. • |:Man| now respects 'wrapmargin' -• The |gx| command now uses |vim.ui.open()| and not netrw. Continue using -netrw with `vim.g.use_lua_gx = false`. +• |gx| now uses |vim.ui.open()| and not netrw. To customize, you can redefine + `vim.ui.open` or remap `gx`. To continue using netrw (deprecated): >vim + :call netrw#BrowseX(expand(exists("g:netrw_gx")? g:netrw_gx : ''), netrw#CheckIfRemote()) ============================================================================== REMOVED FEATURES *news-removed* diff --git a/runtime/doc/various.txt b/runtime/doc/various.txt index de1c21b310..956c37fc0f 100644 --- a/runtime/doc/various.txt +++ b/runtime/doc/various.txt @@ -98,13 +98,14 @@ g8 Print the hex values of the bytes used in the command won't move the cursor. *gx* -gx Open the current path or URL under the cursor in the - system's default handler with |vim.ui.open|. +gx Opens the current filepath or URL (decided by + ||, 'isfname') at cursor using the system + default handler, by calling |vim.ui.open()|. + + *v_gx* +{Visual}gx Opens the selected text using the system default + handler, by calling |vim.ui.open()|. - To use the netrw keymap, set `use_lua_gx` to false: ->lua - vim.g.use_lua_gx = false -< *:p* *:pr* *:print* *E749* :[range]p[rint] [flags] Print [range] lines (default current line). diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 9b102c0f84..79d3f7aab0 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -576,12 +576,12 @@ M['window/showDocument'] = function(_, result, ctx, _) local ret = vim.ui.open(uri) - if ret.code ~= 0 or ret == nil then + if ret == nil or ret.code ~= 0 then return { success = false, error = { code = protocol.ErrorCodes.UnknownErrorCode, - message = ret and ret.stderr or 'No handler could be found', + message = ret and ret.stderr or 'No handler found', }, } end @@ -593,7 +593,7 @@ M['window/showDocument'] = function(_, result, ctx, _) local client = vim.lsp.get_client_by_id(client_id) local client_name = client and client.name or string.format('id=%d', client_id) if not client then - err_message({ 'LSP[', client_name, '] client has shut down after sending ', ctx.method }) + err_message('LSP[', client_name, '] client has shut down after sending ', ctx.method) return vim.NIL end diff --git a/runtime/lua/vim/ui.lua b/runtime/lua/vim/ui.lua index 2200ee7bc3..3ffa329f74 100644 --- a/runtime/lua/vim/ui.lua +++ b/runtime/lua/vim/ui.lua @@ -104,69 +104,54 @@ function M.input(opts, on_confirm) end end ---- Opens a path in the system's default handler. ---- This function utilizes `xdg-open`, `wslview`, `explorer`, or `open` commands ---- depending on the system to open the provided path. +--- Opens `path` with the system default handler (macOS `open`, Windows `explorer.exe`, Linux +--- `xdg-open`, …), or shows a message on failure. --- ---- Notifies the user if unsuccessful +--- Expands "~/" and environment variables in filesystem paths. --- ----@param path string Path to be opened ---- ----@return SystemCompleted|nil result Result of command, if an appropriate one ----could be found. ---- ----@see |vim.system| ---- ---- Example: +--- Examples: ---
lua
 --- vim.ui.open("https://neovim.io/")
----
---- vim.ui.open("/path/to/file")
+--- vim.ui.open("~/path/to/file")
+--- vim.ui.open("$VIMRUNTIME")
 --- 
+--- +---@param path string Path or URL to open +--- +---@return SystemCompleted|nil result Command result, or nil if not found. +--- +---@see |vim.system()| function M.open(path) - if not path or path == '' then - vim.notify('os_open: No path provided', vim.log.levels.ERROR) - return nil + vim.validate{ + path={path, 'string'} + } + local is_uri = path:match('%w+:') + if not is_uri then + path = vim.fn.expand(path) end local cmd - if vim.fn.has('macunix') == 1 then + if vim.fn.has('mac') == 1 then cmd = { 'open', path } elseif vim.fn.has('win32') == 1 then cmd = { 'explorer', path } + elseif vim.fn.executable('wslview') == 1 then + cmd = { 'wslview', path } + elseif vim.fn.executable('xdg-open') == 1 then + cmd = { 'xdg-open', path } else - if vim.fn.executable('wslview') == 1 then - cmd = { 'wslview', path } - elseif vim.fn.executable('xdg-open') == 1 then - cmd = { 'xdg-open', path } - else - vim.notify( - 'os_open: Could not find an appropriate command to use (Is xdg-open installed?)', - vim.log.levels.ERROR - ) - - return nil - end + vim.notify('vim.ui.open: no handler found (tried: wslview, xdg-open)', vim.log.levels.ERROR) + return nil end - local ret = vim - .system(cmd, { - text = true, - detach = true, - }) - :wait() - - if ret.code ~= 0 then - local msg = { - 'Failed to open path', - ret, - vim.inspect(cmd), - } - vim.notify(table.concat(msg, '\n'), vim.log.levels.ERROR) + local rv = vim.system(cmd, { text = true, detach = true, }):wait() + if rv.code ~= 0 then + local msg = ('vim.ui.open: command failed (%d): %s'):format(rv.code, vim.inspect(cmd)) + vim.notify(msg, vim.log.levels.ERROR) end - return ret + return rv end return M diff --git a/runtime/plugin/nvim.lua b/runtime/plugin/nvim.lua index fcc1b016aa..9fff6246e3 100644 --- a/runtime/plugin/nvim.lua +++ b/runtime/plugin/nvim.lua @@ -19,10 +19,15 @@ vim.api.nvim_create_user_command('InspectTree', function(cmd) end end, { desc = 'Inspect treesitter language tree for buffer', count = true }) -if vim.g.use_lua_gx == nil or vim.g.use_lua_gx == true then - vim.keymap.set({ 'n', 'x' }, 'gx', function() - local uri = vim.fn.expand('') - - vim.ui.open(uri) - end, { desc = 'Open URI under cursor with system app' }) +-- TODO: use vim.region() when it lands... #13896 #16843 +local function get_visual_selection() + local save_a = vim.fn.getreginfo('a') + vim.cmd[[norm! "ay]] + local selection = vim.fn.getreg('a', 1) + vim.fn.setreg('a', save_a) + return selection end + +local gx_desc = 'Opens filepath or URI under cursor with the system handler (file explorer, web browser, …)' +vim.keymap.set({ 'n' }, 'gx', function() vim.ui.open(vim.fn.expand('')) end, { desc = gx_desc }) +vim.keymap.set({ 'x' }, 'gx', function() vim.ui.open(get_visual_selection()) end, { desc = gx_desc }) -- cgit From e644e7ce0b36dd5e75770f3faa0a84f15e2561e8 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Tue, 4 Jul 2023 23:33:23 +0200 Subject: fix(vim.ui.open): return (don't show) error message Problem: Showing an error via vim.notify() makes it awkward for callers such as lsp/handlers.lua to avoid showing redundant errors. Solution: Return the message instead of showing it. Let the caller decide whether and when to show the message. --- runtime/doc/lua.txt | 6 ++++-- runtime/lua/vim/lsp/handlers.lua | 5 ++--- runtime/lua/vim/ui.lua | 20 ++++++++++---------- runtime/plugin/nvim.lua | 19 +++++++++++++++---- 4 files changed, 31 insertions(+), 19 deletions(-) (limited to 'runtime') diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index b09e308e80..77a89a123d 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -2345,7 +2345,8 @@ input({opts}, {on_confirm}) *vim.ui.input()* open({path}) *vim.ui.open()* Opens `path` with the system default handler (macOS `open`, Windows - `explorer.exe`, Linux `xdg-open`, …), or shows a message on failure. + `explorer.exe`, Linux `xdg-open`, …), or returns (but does not show) an + error message on failure. Expands "~/" and environment variables in filesystem paths. @@ -2360,7 +2361,8 @@ open({path}) *vim.ui.open()* • {path} (string) Path or URL to open Return: ~ - SystemCompleted|nil result Command result, or nil if not found. + SystemCompleted|nil # Command result, or nil if not found. + (string|nil) # Error message on failure See also: ~ • |vim.system()| diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 79d3f7aab0..70781cb7a6 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -573,15 +573,14 @@ M['window/showDocument'] = function(_, result, ctx, _) if result.external then -- TODO(lvimuser): ask the user for confirmation - - local ret = vim.ui.open(uri) + local ret, err = vim.ui.open(uri) if ret == nil or ret.code ~= 0 then return { success = false, error = { code = protocol.ErrorCodes.UnknownErrorCode, - message = ret and ret.stderr or 'No handler found', + message = ret and ret.stderr or err, }, } end diff --git a/runtime/lua/vim/ui.lua b/runtime/lua/vim/ui.lua index 3ffa329f74..fd06611da2 100644 --- a/runtime/lua/vim/ui.lua +++ b/runtime/lua/vim/ui.lua @@ -105,7 +105,7 @@ function M.input(opts, on_confirm) end --- Opens `path` with the system default handler (macOS `open`, Windows `explorer.exe`, Linux ---- `xdg-open`, …), or shows a message on failure. +--- `xdg-open`, …), or returns (but does not show) an error message on failure. --- --- Expands "~/" and environment variables in filesystem paths. --- @@ -118,13 +118,14 @@ end --- ---@param path string Path or URL to open --- ----@return SystemCompleted|nil result Command result, or nil if not found. +---@return SystemCompleted|nil # Command result, or nil if not found. +---@return string|nil # Error message on failure --- ---@see |vim.system()| function M.open(path) - vim.validate{ - path={path, 'string'} - } + vim.validate({ + path = { path, 'string' }, + }) local is_uri = path:match('%w+:') if not is_uri then path = vim.fn.expand(path) @@ -141,17 +142,16 @@ function M.open(path) elseif vim.fn.executable('xdg-open') == 1 then cmd = { 'xdg-open', path } else - vim.notify('vim.ui.open: no handler found (tried: wslview, xdg-open)', vim.log.levels.ERROR) - return nil + return nil, 'vim.ui.open: no handler found (tried: wslview, xdg-open)' end - local rv = vim.system(cmd, { text = true, detach = true, }):wait() + local rv = vim.system(cmd, { text = true, detach = true }):wait() if rv.code ~= 0 then local msg = ('vim.ui.open: command failed (%d): %s'):format(rv.code, vim.inspect(cmd)) - vim.notify(msg, vim.log.levels.ERROR) + return rv, msg end - return rv + return rv, nil end return M diff --git a/runtime/plugin/nvim.lua b/runtime/plugin/nvim.lua index 9fff6246e3..33d399e577 100644 --- a/runtime/plugin/nvim.lua +++ b/runtime/plugin/nvim.lua @@ -22,12 +22,23 @@ end, { desc = 'Inspect treesitter language tree for buffer', count = true }) -- TODO: use vim.region() when it lands... #13896 #16843 local function get_visual_selection() local save_a = vim.fn.getreginfo('a') - vim.cmd[[norm! "ay]] + vim.cmd([[norm! "ay]]) local selection = vim.fn.getreg('a', 1) vim.fn.setreg('a', save_a) return selection end -local gx_desc = 'Opens filepath or URI under cursor with the system handler (file explorer, web browser, …)' -vim.keymap.set({ 'n' }, 'gx', function() vim.ui.open(vim.fn.expand('')) end, { desc = gx_desc }) -vim.keymap.set({ 'x' }, 'gx', function() vim.ui.open(get_visual_selection()) end, { desc = gx_desc }) +local gx_desc = + 'Opens filepath or URI under cursor with the system handler (file explorer, web browser, …)' +local function do_open(uri) + local _, err = vim.ui.open(uri) + if err then + vim.notify(err, vim.log.levels.ERROR) + end +end +vim.keymap.set({ 'n' }, 'gx', function() + do_open(vim.fn.expand('')) +end, { desc = gx_desc }) +vim.keymap.set({ 'x' }, 'gx', function() + do_open(get_visual_selection()) +end, { desc = gx_desc }) -- cgit