-- This API requires nvim 0.7
--[[
require('gitsigns').setup {
    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', '<leader>gn', function() gs.next_hunk({wrap=true}) end, {expr=true})
        map('n', '<leader>gp', function() gs.prev_hunk({wrap=true}) end, {expr=true})

        -- Actions
        map({'n', 'v'}, '<leader>gs', gs.stage_hunk)
        map('n', '<leader>gS', gs.stage_buffer)
        map('n', '<leader>gu', gs.undo_stage_hunk)
        map({'n', 'v'}, '<leader>gr', gs.reset_hunk)
        map('n', '<leader>gR', gs.reset_buffer)
        map('n', '<leader>gP', gs.preview_hunk)
        map('n', '<leader>gb', function() gs.blame_line{full=true} end)
        map('n', '<leader>gB', gs.toggle_current_line_blame)
        map('n', '<leader>gd', gs.diffthis)
        map('n', '<leader>gdp', function() gs.diffthis('~') end)
        map('n', '<leader>gD', gs.toggle_deleted)

        -- Text object
        map({'o', 'x'}, 'ih', ':<C-U>Gitsigns select_hunk<CR>')
    end
}
]]--

require('gitsigns').setup {
    on_attach = function(bufnr)
        local function map(mode, lhs, rhs, opts)
            opts = vim.tbl_extend('force', {noremap = true, silent = true}, opts or {})
            vim.api.nvim_buf_set_keymap(bufnr, mode, lhs, rhs, opts)
        end

        -- Navigation
        map('n', '<leader>gn', "&diff ? ']c' : '<cmd>Gitsigns next_hunk<CR>'", {expr=true})
        map('n', '<leader>gp', "&diff ? '[c' : '<cmd>Gitsigns prev_hunk<CR>'", {expr=true})

        -- Actions
        map('n', '<leader>gs', '<cmd>Gitsigns stage_hunk<CR>')
        map('v', '<leader>gs', '<cmd>Gitsigns stage_hunk<CR>')
        map('n', '<leader>gr', '<cmd>Gitsigns reset_hunk<CR>')
        map('v', '<leader>gr', '<cmd>Gitsigns reset_hunk<CR>')
        map('n', '<leader>gS', '<cmd>Gitsigns stage_buffer<CR>')
        map('n', '<leader>gu', '<cmd>Gitsigns undo_stage_hunk<CR>')
        map('n', '<leader>gR', '<cmd>Gitsigns reset_buffer<CR>')
        map('n', '<leader>gP', '<cmd>Gitsigns preview_hunk<CR>')
        map('n', '<leader>gb', '<cmd>lua require"gitsigns".blame_line{full=true}<CR>')
        map('n', '<leader>gB', '<cmd>Gitsigns toggle_current_line_blame<CR>')
        map('n', '<leader>gd', '<cmd>Gitsigns diffthis<CR>')
        map('n', '<leader>gdp', '<cmd>lua require"gitsigns".diffthis("~")<CR>')
        map('n', '<leader>gD', '<cmd>Gitsigns toggle_deleted<CR>')

        -- Text object
        map('o', 'ih', ':<C-U>Gitsigns select_hunk<CR>')
        map('x', 'ih', ':<C-U>Gitsigns select_hunk<CR>')
    end
}


vim.cmd [[
    highlight! link GitSignsAdd DiffAdd
]]
