gitsigns-nvim: git support

{src}: # local-args
{ config, pkgs, stdenv, lib, ... }:
let
  # TODO: npins tracks gitsigns.nvim main only for the unified diff view
  # (`:Gitsigns diffthis unified=true`), which no released version has yet. Switch back to
  # pkgs.vimPlugins.gitsigns-nvim once nixpkgs ships something newer than this pin.
  my-gitsigns-nvim = {
    plugin = pkgs.vimUtils.buildVimPlugin {
      name = "gitsigns.nvim";
      inherit src;
      patches = [ ./unified/main.patch ];
      doCheck = false;
      # Use hl_group+hl_eol instead of line_hl_group so that higher-priority
      # character-level extmarks (e.g. todo-comments) can override the line
      # background. Workaround for neovim/neovim#31151.
      postPatch = ''
        substituteInPlace lua/gitsigns/signs.lua \
          --replace-fail "line_hl_group = self:hl(ty, 'linehl')," \
                         "hl_group = self:hl(ty, 'linehl'), hl_eol = true, end_row = lnum, end_col = 0,"
      '';
    };
    type = "lua";
    config = /*lua*/ ''
      require('gitsigns').setup {
        numhl      = true,
        linehl     = true,

        current_line_blame = true,
        current_line_blame_formatter = '🖂 <author> 🖃 <author_time:%R> 🖆 <summary>',

        -- keymaps
        on_attach = function(bufnr)
          local gs = package.loaded.gitsigns

          local function map(mode, l, r, opts)
            opts = opts or {}
            opts.buffer = bufnr
            vim.keymap.set(mode, l, r, opts)
          end

          -- Navigation
          map('n', ']c', function()
            if vim.wo.diff then return ']c' end
            vim.schedule(function() gs.next_hunk() end)
            return '<Ignore>'
          end, {expr=true})

          map('n', ']C', function()
            if vim.wo.diff then return ']c' end
            vim.schedule(function() gs.next_hunk({target="all"}) end)
            return '<Ignore>'
          end, {expr=true})

          map('n', '[c', function()
            if vim.wo.diff then return '[c' end
            vim.schedule(function() gs.prev_hunk() end)
            return '<Ignore>'
          end, {expr=true})

          map('n', '[C', function()
            if vim.wo.diff then return '[c' end
            vim.schedule(function() gs.prev_hunk({target="all"}) end)
            return '<Ignore>'
          end, {expr=true})

          -- Actions
          map({'n', 'v'}, '<leader>hs', ':Gitsigns stage_hunk<CR>')
          map({'n', 'v'}, '<leader>hr', ':Gitsigns reset_hunk<CR>')
          map('n', '<leader>hS', gs.stage_buffer)
          map('n', '<leader>hu', gs.undo_stage_hunk)
          map('n', '<leader>hR', gs.reset_buffer)
          map('n', '<leader>hp', gs.preview_hunk)
          map('n', '<leader>hb', gs.blame)
          -- map('n', '<leader>tb', gs.toggle_current_line_blame)
          map('n', '<leader>hd', function() gs.diffthis(nil, { unified = true }) end)
          map('n', '<leader>hD', function() gs.diffthis(nil, { unified = false }) end)
          -- map('n', '<leader>td', gs.toggle_deleted)

          -- Text object
          map({'o', 'x'}, 'ih', ':<C-U>Gitsigns select_hunk<CR>')
        end
      }
      -- By default, staged hunks share the same background color as unstaged hunks.
      -- Clear GitSignsStagedXXXLn highlight groups to remove background from staged hunks.
      for _, ty in ipairs({'Add', 'Change', 'Delete', 'Topdelete', 'Changedelete'}) do
        local hl_name = 'GitSignsStaged' .. ty .. "Ln"
        vim.api.nvim_set_hl(0, hl_name, {})
      end
      -- The inline word-diff groups derive from TermCursor, which is a white background in
      -- sonokai: the text becomes unreadable in the unified diff view (it always word-diffs
      -- the deleted lines). Use the highlight diff mode shows in the split view instead.
      -- Gitsigns re-derives its defaults on ColorScheme, so reapply there as well.
      local function use_diff_text_inline()
        for _, hl_name in ipairs({'GitSignsAddInline', 'GitSignsChangeInline', 'GitSignsDeleteVirtLnInLine'}) do
          vim.api.nvim_set_hl(0, hl_name, {link = 'DiffText'})
        end
      end
      use_diff_text_inline()
      vim.api.nvim_create_autocmd('ColorScheme', {callback = use_diff_text_inline})
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-gitsigns-nvim
    ];
  };
}