aznhe21 / actions-preview.nvim

Fully customizable previewer for LSP code actions.
GNU General Public License v3.0
365 stars 9 forks source link

Code deduplication of `vim.lsp.util.apply_text_edits` #20

Closed ibhagwan closed 7 months ago

ibhagwan commented 8 months ago

Hi @aznhe21 and ty for this plugin!

I was recently acquainted with it as part of a feature request for my plugin https://github.com/ibhagwan/fzf-lua/issues/944.

As part of the implementation I reused your diff generation code (with proper credit in the commit/comments) https://github.com/ibhagwan/fzf-lua/commit/b3b05f9d438736bb1f88aa373476753ddf83f481.

While doing so I noticed you created your own version of vim.lsp.util.apply_text_edits that applies the edits to lines input (instead of the original buffer argument): https://github.com/aznhe21/actions-preview.nvim/blob/8f79029a36ab6807478f157538a91ccd4af5858f/lua/actions-preview/action.lua#L75

I personally try to avoid duping vim code whenever possible and rely on the runtime in case the logic is changed in the future (bug fixes, etc). In my implementation I opted for reusing the runtime code by creating a temp buffer (with the original lines in its contents) and thus I am able to call vim.lsp.util.apply_text_edits directly:

So instead of: https://github.com/aznhe21/actions-preview.nvim/blob/8f79029a36ab6807478f157538a91ccd4af5858f/lua/actions-preview/action.lua#L141-L149

I use:

local function diff_text_edits(text_edits, bufnr, offset_encoding, diff_opts)
  local eol = get_eol(bufnr)
  local orig_lines = get_lines(bufnr)
  local tmpbuf = vim.api.nvim_create_buf(false, true)
  vim.api.nvim_buf_set_lines(tmpbuf, 0, -1, false, orig_lines)
  vim.lsp.util.apply_text_edits(text_edits, tmpbuf, offset_encoding)
  local new_lines = get_lines(tmpbuf)
  vim.api.nvim_buf_delete(tmpbuf, { force = true })
  local diff = vim.diff(
    table.concat(orig_lines, eol) .. eol,
    table.concat(new_lines, eol) .. eol,
    diff_opts)
  return utils.strsplit(vim.trim(diff), eol)
end

Thought you might be interested should you decide to take a similar approach one day.

Hopefully this helps and thanks again!

aznhe21 commented 7 months ago

Merged in #23. Thank you for your suggestion!