Skip to content

Help with custom command, opening file from branch using fugitive Gvsplit #471

@ibhagwan

Description

@ibhagwan

Context: https://www.reddit.com/r/neovim/comments/vu7v92/custom_complete_for_nvim_create_user_command/

@pure-bliss, let me know if you need more help with this.

Notes:

  • For file type entries I prefer using files to fzf_exec, you get the benefit of multiprocessing (running the command in an external process) as wel as automatic entry processing (icons, relative paths, shortening paths, etc) so you can also skip calling fn_transform and make_entry.file since these will be done automatically for you
  • With files we also get the automatic previewer and action configurations, that's why I disabled both default and ctrl-s actions, assuming OP doesn't need/want those
  • When using file icons (either through files or fn_transform) the selected array will now contain entries with icons which must be stripped with path.entry_to_file before being sent to to the fugitive command
  • During development, I highly recommend using vim.pretty_print at strategic locations so you can inspect the contents of ceratain objects, use ':messages' to inspect the output of objects containing more than one line
vim.api.nvim_create_user_command(
  'ListFilesFromBranch',
  function(opts)
    require 'fzf-lua'.files({
      cmd = "git ls-tree -r --name-only " .. opts.args,
      prompt = opts.args .. "> ",
      actions = {
        ['default'] = false,
        ['ctrl-s'] = false,
        ['ctrl-v'] = function(selected, o)
          -- use vim.pretty_print to see what's inside objects:
          -- vim.pretty_print(selected)
          local file = require'fzf-lua'.path.entry_to_file(selected[1], o)
          local cmd = string.format("Gvsplit %s:%s", opts.args, file.path)
          print("running:", cmd)
          vim.cmd(cmd)
          vim.cmd("windo diffthis")
        end
      },
    })
  end,
  {
    nargs = 1,
    force = true,
    complete = function()
      local branches = vim.fn.systemlist("git branch --all --sort=-committerdate")
      if vim.v.shell_error == 0 then
        return vim.tbl_map(function(x)
          return x:match("[^%s%*]+"):gsub("^remotes/", "")
        end, branches)
      end
    end,
  })

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions