first commit

This commit is contained in:
yetone
2024-08-12 23:53:28 +08:00
commit 9edd4202af
11 changed files with 1944 additions and 0 deletions

778
lua/avante/diff.lua Normal file
View File

@@ -0,0 +1,778 @@
-- This file COPY and MODIFIED based on: https://github.com/akinsho/git-conflict.nvim/blob/main/lua/git-conflict.lua
local M = {}
local color = require("avante.diff.colors")
local utils = require("avante.diff.utils")
local fn = vim.fn
local api = vim.api
local fmt = string.format
local map = vim.keymap.set
local job = utils.job
-----------------------------------------------------------------------------//
-- REFERENCES:
-----------------------------------------------------------------------------//
-- Detecting the state of a git repository based on files in the .git directory.
-- https://stackoverflow.com/questions/49774200/how-to-tell-if-my-git-repo-is-in-a-conflict
-- git diff commands to git a list of conflicted files
-- https://stackoverflow.com/questions/3065650/whats-the-simplest-way-to-list-conflicted-files-in-git
-- how to show a full path for files in a git diff command
-- https://stackoverflow.com/questions/10459374/making-git-diff-stat-show-full-file-path
-- Advanced merging
-- https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging
-----------------------------------------------------------------------------//
-- Types
-----------------------------------------------------------------------------//
---@alias ConflictSide "'ours'"|"'theirs'"|"'both'"|"'base'"|"'none'"
--- @class ConflictHighlights
--- @field current string
--- @field incoming string
--- @field ancestor string?
---@class RangeMark
---@field label integer
---@field content string
--- @class PositionMarks
--- @field current RangeMark
--- @field incoming RangeMark
--- @field ancestor RangeMark
--- @class Range
--- @field range_start integer
--- @field range_end integer
--- @field content_start integer
--- @field content_end integer
--- @class ConflictPosition
--- @field incoming Range
--- @field middle Range
--- @field current Range
--- @field marks PositionMarks
--- @class ConflictBufferCache
--- @field lines table<integer, boolean> map of conflicted line numbers
--- @field positions ConflictPosition[]
--- @field tick integer
--- @field bufnr integer
--- @class AvanteConflictMappings
--- @field ours string
--- @field theirs string
--- @field none string
--- @field both string
--- @field next string
--- @field prev string
--- @class AvanteConflictConfig
--- @field default_mappings AvanteConflictMappings
--- @field disable_diagnostics boolean
--- @field list_opener string|function
--- @field highlights ConflictHighlights
--- @field debug boolean
--- @class AvanteConflictUserConfig
--- @field default_mappings boolean|AvanteConflictMappings
--- @field disable_diagnostics boolean
--- @field list_opener string|function
--- @field highlights ConflictHighlights
--- @field debug boolean
-----------------------------------------------------------------------------//
-- Constants
-----------------------------------------------------------------------------//
local SIDES = {
OURS = "ours",
THEIRS = "theirs",
BOTH = "both",
BASE = "base",
NONE = "none",
}
-- A mapping between the internal names and the display names
local name_map = {
ours = "current",
theirs = "incoming",
base = "ancestor",
both = "both",
none = "none",
}
local CURRENT_HL = "AvanteConflictCurrent"
local INCOMING_HL = "AvanteConflictIncoming"
local ANCESTOR_HL = "AvanteConflictAncestor"
local CURRENT_LABEL_HL = "AvanteConflictCurrentLabel"
local INCOMING_LABEL_HL = "AvanteConflictIncomingLabel"
local ANCESTOR_LABEL_HL = "AvanteConflictAncestorLabel"
local PRIORITY = vim.highlight.priorities.user
local NAMESPACE = api.nvim_create_namespace("avante-conflict")
local AUGROUP_NAME = "AvanteConflictCommands"
local sep = package.config:sub(1, 1)
local conflict_start = "^<<<<<<<"
local conflict_middle = "^======="
local conflict_end = "^>>>>>>>"
local conflict_ancestor = "^|||||||"
local DEFAULT_CURRENT_BG_COLOR = 4218238 -- #405d7e
local DEFAULT_INCOMING_BG_COLOR = 3229523 -- #314753
local DEFAULT_ANCESTOR_BG_COLOR = 6824314 -- #68217A
-----------------------------------------------------------------------------//
--- @type AvanteConflictMappings
local DEFAULT_MAPPINGS = {
ours = "co",
theirs = "ct",
none = "c0",
both = "cb",
next = "]x",
prev = "[x",
}
--- @type AvanteConflictConfig
local config = {
debug = false,
default_mappings = DEFAULT_MAPPINGS,
default_commands = true,
disable_diagnostics = false,
list_opener = "copen",
highlights = {
current = "DiffText",
incoming = "DiffAdd",
ancestor = nil,
},
}
--- @return table<string, ConflictBufferCache>
local function create_visited_buffers()
return setmetatable({}, {
__index = function(t, k)
if type(k) == "number" then
return t[api.nvim_buf_get_name(k)]
end
end,
})
end
--- A list of buffers that have conflicts in them. This is derived from
--- git using the diff command, and updated at intervals
local visited_buffers = create_visited_buffers()
-----------------------------------------------------------------------------//
---Get full path to the repository of the directory passed in
---@param dir any
---@param callback fun(data: string)
local function get_git_root(dir, callback)
job({ "git", "-C", dir, "rev-parse", "--show-toplevel" }, function(data)
callback(data[1])
end)
end
--- Get a list of the conflicted files within the specified directory
--- NOTE: only conflicted files within the git repository of the directory passed in are returned
--- also we add a line prefix to the git command so that the full path is returned
--- e.g. --line-prefix=`git rev-parse --show-toplevel`
---@reference: https://stackoverflow.com/a/10874862
---@param dir string?
---@param callback fun(files: table<string, integer[]>, string)
local function get_conflicted_files(dir, callback)
local cmd = { "git", "-C", dir, "diff", ("--line-prefix=%s%s"):format(dir, sep), "--name-only", "--diff-filter=U" }
job(cmd, function(data)
local files = {}
for _, filename in ipairs(data) do
if #filename > 0 then
files[filename] = files[filename] or {}
end
end
callback(files, dir)
end)
end
---Add the positions to the buffer in our in memory buffer list
---positions are keyed by a list of range start and end for each mark
---@param buf integer
---@param positions ConflictPosition[]
local function update_visited_buffers(buf, positions)
if not buf or not api.nvim_buf_is_valid(buf) then
return
end
local name = api.nvim_buf_get_name(buf)
-- If this buffer is not in the list
if not visited_buffers[name] then
return
end
visited_buffers[name].bufnr = buf
visited_buffers[name].tick = vim.b[buf].changedtick
visited_buffers[name].positions = positions
end
function M.add_visited_buffer(bufnr)
local name = api.nvim_buf_get_name(bufnr)
visited_buffers[name] = visited_buffers[name] or {}
end
---Set an extmark for each section of the git conflict
---@param bufnr integer
---@param hl string
---@param range_start integer
---@param range_end integer
---@return integer? extmark_id
local function hl_range(bufnr, hl, range_start, range_end)
if not range_start or not range_end then
return
end
return api.nvim_buf_set_extmark(bufnr, NAMESPACE, range_start, 0, {
hl_group = hl,
hl_eol = true,
hl_mode = "combine",
end_row = range_end,
priority = PRIORITY,
})
end
---Add highlights and additional data to each section heading of the conflict marker
---These works by covering the underlying text with an extmark that contains the same information
---with some extra detail appended.
---TODO: ideally this could be done by using virtual text at the EOL and highlighting the
---background but this doesn't work and currently this is done by filling the rest of the line with
---empty space and overlaying the line content
---@param bufnr integer
---@param hl_group string
---@param label string
---@param lnum integer
---@return integer extmark id
local function draw_section_label(bufnr, hl_group, label, lnum)
local remaining_space = api.nvim_win_get_width(0) - api.nvim_strwidth(label)
return api.nvim_buf_set_extmark(bufnr, NAMESPACE, lnum, 0, {
hl_group = hl_group,
virt_text = { { label .. string.rep(" ", remaining_space), hl_group } },
virt_text_pos = "overlay",
priority = PRIORITY,
})
end
---Highlight each part of a git conflict i.e. the incoming changes vs the current/HEAD changes
---TODO: should extmarks be ephemeral? or is it less expensive to save them and only re-apply
---them when a buffer changes since otherwise we have to reparse the whole buffer constantly
---@param positions table
---@param lines string[]
local function highlight_conflicts(positions, lines)
local bufnr = api.nvim_get_current_buf()
M.clear(bufnr)
for _, position in ipairs(positions) do
local current_start = position.current.range_start
local current_end = position.current.range_end
local incoming_start = position.incoming.range_start
local incoming_end = position.incoming.range_end
-- Add one since the index access in lines is 1 based
local current_label = lines[current_start + 1] .. " (Current changes)"
local incoming_label = lines[incoming_end + 1] .. " (Incoming changes)"
local curr_label_id = draw_section_label(bufnr, CURRENT_LABEL_HL, current_label, current_start)
local curr_id = hl_range(bufnr, CURRENT_HL, current_start, current_end + 1)
local inc_id = hl_range(bufnr, INCOMING_HL, incoming_start, incoming_end + 1)
local inc_label_id = draw_section_label(bufnr, INCOMING_LABEL_HL, incoming_label, incoming_end)
position.marks = {
current = { label = curr_label_id, content = curr_id },
incoming = { label = inc_label_id, content = inc_id },
ancestor = {},
}
if not vim.tbl_isempty(position.ancestor) then
local ancestor_start = position.ancestor.range_start
local ancestor_end = position.ancestor.range_end
local ancestor_label = lines[ancestor_start + 1] .. " (Base changes)"
local id = hl_range(bufnr, ANCESTOR_HL, ancestor_start + 1, ancestor_end + 1)
local label_id = draw_section_label(bufnr, ANCESTOR_LABEL_HL, ancestor_label, ancestor_start)
position.marks.ancestor = { label = label_id, content = id }
end
end
end
---Iterate through the buffer line by line checking there is a matching conflict marker
---when we find a starting mark we collect the position details and add it to a list of positions
---@param lines string[]
---@return boolean
---@return ConflictPosition[]
local function detect_conflicts(lines)
local positions = {}
local position, has_start, has_middle, has_ancestor = nil, false, false, false
for index, line in ipairs(lines) do
local lnum = index - 1
if line:match(conflict_start) then
has_start = true
position = {
current = { range_start = lnum, content_start = lnum + 1 },
middle = {},
incoming = {},
ancestor = {},
}
end
if has_start and line:match(conflict_ancestor) then
has_ancestor = true
position.ancestor.range_start = lnum
position.ancestor.content_start = lnum + 1
position.current.range_end = lnum - 1
position.current.content_end = lnum - 1
end
if has_start and line:match(conflict_middle) then
has_middle = true
if has_ancestor then
position.ancestor.content_end = lnum - 1
position.ancestor.range_end = lnum - 1
else
position.current.range_end = lnum - 1
position.current.content_end = lnum - 1
end
position.middle.range_start = lnum
position.middle.range_end = lnum + 1
position.incoming.range_start = lnum + 1
position.incoming.content_start = lnum + 1
end
if has_start and has_middle and line:match(conflict_end) then
position.incoming.range_end = lnum
position.incoming.content_end = lnum - 1
positions[#positions + 1] = position
position, has_start, has_middle, has_ancestor = nil, false, false, false
end
end
return #positions > 0, positions
end
---Helper function to find a conflict position based on a comparator function
---@param bufnr integer
---@param comparator fun(string, integer): boolean
---@param opts table?
---@return ConflictPosition?
local function find_position(bufnr, comparator, opts)
local match = visited_buffers[bufnr]
if not match then
return
end
local line = utils.get_cursor_pos()
line = line - 1 -- Convert to 0-based for position comparison
if opts and opts.reverse then
for i = #match.positions, 1, -1 do
local position = match.positions[i]
if comparator(line, position) then
return position
end
end
return nil
end
for _, position in ipairs(match.positions) do
if comparator(line, position) then
return position
end
end
return nil
end
---Retrieves a conflict marker position by checking the visited buffers for a supported range
---@param bufnr integer
---@return ConflictPosition?
local function get_current_position(bufnr)
return find_position(bufnr, function(line, position)
return position.current.range_start <= line and position.incoming.range_end >= line
end)
end
---@param position ConflictPosition?
---@param side ConflictSide
local function set_cursor(position, side)
if not position then
return
end
local target = side == SIDES.OURS and position.current or position.incoming
api.nvim_win_set_cursor(0, { target.range_start + 1, 0 })
end
---Get the conflict marker positions for a buffer if any and update the buffers state
---@param bufnr integer
---@param range_start integer
---@param range_end integer
local function parse_buffer(bufnr, range_start, range_end)
local lines = utils.get_buf_lines(range_start or 0, range_end or -1, bufnr)
local prev_conflicts = visited_buffers[bufnr].positions ~= nil and #visited_buffers[bufnr].positions > 0
local has_conflict, positions = detect_conflicts(lines)
update_visited_buffers(bufnr, positions)
if has_conflict then
highlight_conflicts(positions, lines)
else
M.clear(bufnr)
end
if prev_conflicts ~= has_conflict or not vim.b[bufnr].conflict_mappings_set then
local pattern = has_conflict and "AvanteConflictDetected" or "AvanteConflictResolved"
api.nvim_exec_autocmds("User", { pattern = pattern })
end
end
---Process a buffer if the changed tick has changed
---@param bufnr integer?
function M.process(bufnr, range_start, range_end)
bufnr = bufnr or api.nvim_get_current_buf()
if visited_buffers[bufnr] and visited_buffers[bufnr].tick == vim.b[bufnr].changedtick then
return
end
parse_buffer(bufnr, range_start, range_end)
end
-----------------------------------------------------------------------------//
-- Commands
-----------------------------------------------------------------------------//
local function set_commands()
local command = api.nvim_create_user_command
command("AvanteConflictListQf", function()
M.conflicts_to_qf_items(function(items)
if #items > 0 then
fn.setqflist(items, "r")
if type(config.list_opener) == "function" then
config.list_opener()
else
vim.cmd(config.list_opener)
end
end
end)
end, { nargs = 0 })
command("AvanteConflictChooseOurs", function()
M.choose("ours")
end, { nargs = 0 })
command("AvanteConflictChooseTheirs", function()
M.choose("theirs")
end, { nargs = 0 })
command("AvanteConflictChooseBoth", function()
M.choose("both")
end, { nargs = 0 })
command("AvanteConflictChooseBase", function()
M.choose("base")
end, { nargs = 0 })
command("AvanteConflictChooseNone", function()
M.choose("none")
end, { nargs = 0 })
command("AvanteConflictNextConflict", function()
M.find_next("ours")
end, { nargs = 0 })
command("AvanteConflictPrevConflict", function()
M.find_prev("ours")
end, { nargs = 0 })
end
-----------------------------------------------------------------------------//
-- Mappings
-----------------------------------------------------------------------------//
local function set_plug_mappings()
local function opts(desc)
return { silent = true, desc = "Git Conflict: " .. desc }
end
map({ "n", "v" }, "<Plug>(git-conflict-ours)", "<Cmd>AvanteConflictChooseOurs<CR>", opts("Choose Ours"))
map({ "n", "v" }, "<Plug>(git-conflict-both)", "<Cmd>AvanteConflictChooseBoth<CR>", opts("Choose Both"))
map({ "n", "v" }, "<Plug>(git-conflict-none)", "<Cmd>AvanteConflictChooseNone<CR>", opts("Choose None"))
map({ "n", "v" }, "<Plug>(git-conflict-theirs)", "<Cmd>AvanteConflictChooseTheirs<CR>", opts("Choose Theirs"))
map("n", "<Plug>(git-conflict-next-conflict)", "<Cmd>AvanteConflictNextConflict<CR>", opts("Next Conflict"))
map("n", "<Plug>(git-conflict-prev-conflict)", "<Cmd>AvanteConflictPrevConflict<CR>", opts("Previous Conflict"))
end
local function setup_buffer_mappings(bufnr)
local function opts(desc)
return { silent = true, buffer = bufnr, desc = "Git Conflict: " .. desc }
end
map({ "n", "v" }, config.default_mappings.ours, "<Plug>(git-conflict-ours)", opts("Choose Ours"))
map({ "n", "v" }, config.default_mappings.both, "<Plug>(git-conflict-both)", opts("Choose Both"))
map({ "n", "v" }, config.default_mappings.none, "<Plug>(git-conflict-none)", opts("Choose None"))
map({ "n", "v" }, config.default_mappings.theirs, "<Plug>(git-conflict-theirs)", opts("Choose Theirs"))
map({ "v", "v" }, config.default_mappings.ours, "<Plug>(git-conflict-ours)", opts("Choose Ours"))
-- map('V', config.default_mappings.ours, '<Plug>(git-conflict-ours)', opts('Choose Ours'))
map("n", config.default_mappings.prev, "<Plug>(git-conflict-prev-conflict)", opts("Previous Conflict"))
map("n", config.default_mappings.next, "<Plug>(git-conflict-next-conflict)", opts("Next Conflict"))
vim.b[bufnr].conflict_mappings_set = true
end
---@param key string
---@param mode "'n'|'v'|'o'|'nv'|'nvo'"?
---@return boolean
local function is_mapped(key, mode)
return fn.hasmapto(key, mode or "n") > 0
end
local function clear_buffer_mappings(bufnr)
if not bufnr or not vim.b[bufnr].conflict_mappings_set then
return
end
for _, mapping in pairs(config.default_mappings) do
if is_mapped(mapping) then
api.nvim_buf_del_keymap(bufnr, "n", mapping)
end
end
vim.b[bufnr].conflict_mappings_set = false
end
-----------------------------------------------------------------------------//
-- Highlights
-----------------------------------------------------------------------------//
---Derive the colour of the section label highlights based on each sections highlights
---@param highlights ConflictHighlights
local function set_highlights(highlights)
local current_color = utils.get_hl(highlights.current)
local incoming_color = utils.get_hl(highlights.incoming)
local ancestor_color = utils.get_hl(highlights.ancestor)
local current_bg = current_color.background or DEFAULT_CURRENT_BG_COLOR
local incoming_bg = incoming_color.background or DEFAULT_INCOMING_BG_COLOR
local ancestor_bg = ancestor_color.background or DEFAULT_ANCESTOR_BG_COLOR
local current_label_bg = color.shade_color(current_bg, 60)
local incoming_label_bg = color.shade_color(incoming_bg, 60)
local ancestor_label_bg = color.shade_color(ancestor_bg, 60)
api.nvim_set_hl(0, CURRENT_HL, { background = current_bg, bold = true, default = true })
api.nvim_set_hl(0, INCOMING_HL, { background = incoming_bg, bold = true, default = true })
api.nvim_set_hl(0, ANCESTOR_HL, { background = ancestor_bg, bold = true, default = true })
api.nvim_set_hl(0, CURRENT_LABEL_HL, { background = current_label_bg, default = true })
api.nvim_set_hl(0, INCOMING_LABEL_HL, { background = incoming_label_bg, default = true })
api.nvim_set_hl(0, ANCESTOR_LABEL_HL, { background = ancestor_label_bg, default = true })
end
---@param user_config AvanteConflictUserConfig
function M.setup(user_config)
local _user_config = user_config or {}
if _user_config.default_mappings == true then
_user_config.default_mappings = DEFAULT_MAPPINGS
end
config = vim.tbl_deep_extend("force", config, _user_config)
set_highlights(config.highlights)
if config.default_commands then
set_commands()
end
set_plug_mappings()
api.nvim_create_augroup(AUGROUP_NAME, { clear = true })
api.nvim_create_autocmd("ColorScheme", {
group = AUGROUP_NAME,
callback = function()
set_highlights(config.highlights)
end,
})
api.nvim_create_autocmd("User", {
group = AUGROUP_NAME,
pattern = "AvanteConflictDetected",
callback = function()
local bufnr = api.nvim_get_current_buf()
if config.disable_diagnostics then
vim.diagnostic.disable(bufnr)
end
if config.default_mappings then
setup_buffer_mappings(bufnr)
end
end,
})
api.nvim_create_autocmd("User", {
group = AUGROUP_NAME,
pattern = "AvanteConflictResolved",
callback = function()
local bufnr = api.nvim_get_current_buf()
if config.disable_diagnostics then
vim.diagnostic.enable(bufnr)
end
if config.default_mappings then
clear_buffer_mappings(bufnr)
end
end,
})
api.nvim_set_decoration_provider(NAMESPACE, {
on_buf = function(_, bufnr, _)
return utils.is_valid_buf(bufnr)
end,
on_win = function(_, _, bufnr, _, _)
if visited_buffers[bufnr] then
M.process(bufnr)
end
end,
})
end
--- Add additional metadata to a quickfix entry if we have already visited the buffer and have that
--- information
---@param item table<string, integer|string>
---@param items table<string, integer|string>[]
---@param visited_buf ConflictBufferCache
local function quickfix_items_from_positions(item, items, visited_buf)
if vim.tbl_isempty(visited_buf.positions) then
return
end
for _, pos in ipairs(visited_buf.positions) do
for key, value in pairs(pos) do
if vim.tbl_contains({ name_map.ours, name_map.theirs, name_map.base }, key) and not vim.tbl_isempty(value) then
local lnum = value.range_start + 1
local next_item = vim.deepcopy(item)
next_item.text = fmt("%s change", key, lnum)
next_item.lnum = lnum
next_item.col = 0
table.insert(items, next_item)
end
end
end
end
--- Convert the conflicts detected via get conflicted files into a list of quickfix entries.
---@param callback fun(files: table<string, integer[]>)
function M.conflicts_to_qf_items(callback)
local items = {}
for filename, visited_buf in pairs(visited_buffers) do
local item = {
filename = filename,
pattern = conflict_start,
text = "git conflict",
type = "E",
valid = 1,
}
if visited_buf and next(visited_buf) then
quickfix_items_from_positions(item, items, visited_buf)
else
table.insert(items, item)
end
end
callback(items)
end
---@param bufnr integer?
function M.clear(bufnr)
if bufnr and not api.nvim_buf_is_valid(bufnr) then
return
end
bufnr = bufnr or 0
api.nvim_buf_clear_namespace(bufnr, NAMESPACE, 0, -1)
end
---@param side ConflictSide
function M.find_next(side)
local pos = find_position(0, function(line, position)
return position.current.range_start >= line and position.incoming.range_end >= line
end)
set_cursor(pos, side)
end
---@param side ConflictSide
function M.find_prev(side)
local pos = find_position(0, function(line, position)
return position.current.range_start <= line and position.incoming.range_end <= line
end, { reverse = true })
set_cursor(pos, side)
end
---Select the changes to keep
---@param side ConflictSide
function M.choose(side)
local bufnr = api.nvim_get_current_buf()
if vim.fn.mode() == "v" or vim.fn.mode() == "V" or vim.fn.mode() == "" then
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "n", true)
-- have to defer so that the < and > marks are set
vim.defer_fn(function()
local start = vim.api.nvim_buf_get_mark(0, "<")[1]
local finish = vim.api.nvim_buf_get_mark(0, ">")[1]
local position = find_position(bufnr, function(line, pos)
local left = pos.current.range_start >= start - 1
local right = pos.incoming.range_end <= finish + 1
return left and right
end)
while position ~= nil do
local lines = {}
if vim.tbl_contains({ SIDES.OURS, SIDES.THEIRS, SIDES.BASE }, side) then
local data = position[name_map[side]]
lines = utils.get_buf_lines(data.content_start, data.content_end + 1)
elseif side == SIDES.BOTH then
local first = utils.get_buf_lines(position.current.content_start, position.current.content_end + 1)
local second = utils.get_buf_lines(position.incoming.content_start, position.incoming.content_end + 1)
lines = vim.list_extend(first, second)
elseif side == SIDES.NONE then
lines = {}
else
return
end
local pos_start = position.current.range_start < 0 and 0 or position.current.range_start
local pos_end = position.incoming.range_end + 1
api.nvim_buf_set_lines(0, pos_start, pos_end, false, lines)
api.nvim_buf_del_extmark(0, NAMESPACE, position.marks.incoming.label)
api.nvim_buf_del_extmark(0, NAMESPACE, position.marks.current.label)
if position.marks.ancestor.label then
api.nvim_buf_del_extmark(0, NAMESPACE, position.marks.ancestor.label)
end
parse_buffer(bufnr)
position = find_position(bufnr, function(line, pos)
local left = pos.current.range_start >= start - 1
local right = pos.incoming.range_end <= finish + 1
return left and right
end)
end
end, 50)
return
end
local position = get_current_position(bufnr)
if not position then
return
end
local lines = {}
if vim.tbl_contains({ SIDES.OURS, SIDES.THEIRS, SIDES.BASE }, side) then
local data = position[name_map[side]]
lines = utils.get_buf_lines(data.content_start, data.content_end + 1)
elseif side == SIDES.BOTH then
local first = utils.get_buf_lines(position.current.content_start, position.current.content_end + 1)
local second = utils.get_buf_lines(position.incoming.content_start, position.incoming.content_end + 1)
lines = vim.list_extend(first, second)
elseif side == SIDES.NONE then
lines = {}
else
return
end
local pos_start = position.current.range_start < 0 and 0 or position.current.range_start
local pos_end = position.incoming.range_end + 1
api.nvim_buf_set_lines(0, pos_start, pos_end, false, lines)
api.nvim_buf_del_extmark(0, NAMESPACE, position.marks.incoming.label)
api.nvim_buf_del_extmark(0, NAMESPACE, position.marks.current.label)
if position.marks.ancestor.label then
api.nvim_buf_del_extmark(0, NAMESPACE, position.marks.ancestor.label)
end
parse_buffer(bufnr)
end
function M.conflict_count(bufnr)
if bufnr and not api.nvim_buf_is_valid(bufnr) then
return 0
end
bufnr = bufnr or 0
local name = api.nvim_buf_get_name(bufnr)
if not visited_buffers[name] then
return 0
end
return #visited_buffers[name].positions
end
return M

View File

@@ -0,0 +1,39 @@
local M = {}
local bit = require("bit")
local rshift, band = bit.rshift, bit.band
--- Returns a table containing the RGB values encoded inside 24 least
--- significant bits of the number @rgb_24bit
---
--@param rgb_24bit (number) 24-bit RGB value
--@returns (table) with keys 'r', 'g', 'b' in [0,255]
local function decode_24bit_rgb(rgb_24bit)
vim.validate({ rgb_24bit = { rgb_24bit, "n", true } })
local r = band(rshift(rgb_24bit, 16), 255)
local g = band(rshift(rgb_24bit, 8), 255)
local b = band(rgb_24bit, 255)
return { r = r, g = g, b = b }
end
local function alter(attr, percent)
return math.floor(attr * (100 + percent) / 100)
end
---@source https://stackoverflow.com/q/5560248
---@see: https://stackoverflow.com/a/37797380
---Darken a specified hex color
---@param color string
---@param percent number
---@return string
function M.shade_color(color, percent)
local rgb = decode_24bit_rgb(color)
if not rgb.r or not rgb.g or not rgb.b then
return "NONE"
end
local r, g, b = alter(rgb.r, percent), alter(rgb.g, percent), alter(rgb.b, percent)
r, g, b = math.min(r, 255), math.min(g, 255), math.min(b, 255)
return string.format("#%02x%02x%02x", r, g, b)
end
return M

88
lua/avante/diff/utils.lua Normal file
View File

@@ -0,0 +1,88 @@
-----------------------------------------------------------------------------//
-- Utils
-----------------------------------------------------------------------------//
local M = {}
local api = vim.api
local fn = vim.fn
--- Wrapper for [vim.notify]
---@param msg string|string[]
---@param level "error" | "trace" | "debug" | "info" | "warn"
---@param once boolean?
function M.notify(msg, level, once)
if type(msg) == "table" then
msg = table.concat(msg, "\n")
end
local lvl = vim.log.levels[level:upper()] or vim.log.levels.INFO
local opts = { title = "Git conflict" }
if once then
return vim.notify_once(msg, lvl, opts)
end
vim.notify(msg, lvl, opts)
end
--- Start an async job
---@param cmd string
---@param callback fun(data: string[]): nil
function M.job(cmd, callback)
fn.jobstart(cmd, {
stdout_buffered = true,
on_stdout = function(_, data, _)
callback(data)
end,
})
end
---Only call the passed function once every timeout in ms
---@param timeout integer
---@param func function
---@return function
function M.throttle(timeout, func)
local timer = vim.loop.new_timer()
local running = false
return function(...)
if not running then
func(...)
running = true
timer:start(timeout, 0, function()
running = false
end)
end
end
end
---Wrapper around `api.nvim_buf_get_lines` which defaults to the current buffer
---@param start integer
---@param _end integer
---@param buf integer?
---@return string[]
function M.get_buf_lines(start, _end, buf)
return api.nvim_buf_get_lines(buf or 0, start, _end, false)
end
---Get cursor row and column as (1, 0) based
---@param win_id integer?
---@return integer, integer
function M.get_cursor_pos(win_id)
return unpack(api.nvim_win_get_cursor(win_id or 0))
end
---Check if the buffer is likely to have actionable conflict markers
---@param bufnr integer?
---@return boolean
function M.is_valid_buf(bufnr)
bufnr = bufnr or 0
return #vim.bo[bufnr].buftype == 0 and vim.bo[bufnr].modifiable
end
---@param name string?
---@return table<string, string>
function M.get_hl(name)
if not name then
return {}
end
return api.nvim_get_hl_by_name(name, true)
end
return M

664
lua/avante/init.lua Normal file
View File

@@ -0,0 +1,664 @@
local M = {}
local curl = require("plenary.curl")
local Path = require("plenary.path")
local n = require("nui-components")
local diff = require("avante.diff")
local api = vim.api
local fn = vim.fn
local RESULT_BUF_NAME = "AVANTE_RESULT"
local CONFLICT_BUF_NAME = "AVANTE_CONFLICT"
local function create_result_buf()
local buf = api.nvim_create_buf(false, true)
api.nvim_set_option_value("filetype", "markdown", { buf = buf })
api.nvim_set_option_value("buftype", "nofile", { buf = buf })
api.nvim_set_option_value("swapfile", false, { buf = buf })
api.nvim_set_option_value("modifiable", false, { buf = buf })
api.nvim_buf_set_name(buf, RESULT_BUF_NAME)
return buf
end
local result_buf = create_result_buf()
local function is_code_buf(buf)
local ignored_filetypes = {
"dashboard",
"alpha",
"neo-tree",
"NvimTree",
"TelescopePrompt",
"Prompt",
"qf",
"help",
}
if api.nvim_buf_is_valid(buf) and api.nvim_get_option_value("buflisted", { buf = buf }) then
local buftype = api.nvim_get_option_value("buftype", { buf = buf })
local filetype = api.nvim_get_option_value("filetype", { buf = buf })
if buftype == "" and filetype ~= "" and not vim.tbl_contains(ignored_filetypes, filetype) then
local bufname = api.nvim_buf_get_name(buf)
if bufname ~= "" and bufname ~= RESULT_BUF_NAME and bufname ~= CONFLICT_BUF_NAME then
return true
end
end
end
return false
end
local signal = n.create_signal({
is_loading = false,
text = "",
})
local _cur_code_buf = nil
local function get_cur_code_buf()
return _cur_code_buf
end
local function get_cur_code_buf_name()
local code_buf = get_cur_code_buf()
if code_buf == nil then
print("Error: cannot get code buffer")
return
end
return api.nvim_buf_get_name(code_buf)
end
local function get_cur_code_win()
local code_buf = get_cur_code_buf()
if code_buf == nil then
print("Error: cannot get code buffer")
return
end
return fn.bufwinid(code_buf)
end
local function get_cur_code_buf_content()
local code_buf = get_cur_code_buf()
if code_buf == nil then
print("Error: cannot get code buffer")
return {}
end
return api.nvim_buf_get_lines(code_buf, 0, -1, false)
end
local function prepend_line_number(content)
local lines = vim.split(content, "\n")
local result = {}
for i, line in ipairs(lines) do
table.insert(result, "L" .. i .. ": " .. line)
end
return table.concat(result, "\n")
end
local function extract_code_snippets(content)
local snippets = {}
local current_snippet = {}
local in_code_block = false
local lang, start_line, end_line
local explanation = ""
for line in content:gmatch("[^\r\n]+") do
local start_line_str, end_line_str = line:match("^Replace lines: (%d+)-(%d+)")
if start_line_str ~= nil and end_line_str ~= nil then
start_line = tonumber(start_line_str)
end_line = tonumber(end_line_str)
end
if line:match("^```") then
if in_code_block then
if start_line ~= nil and end_line ~= nil then
table.insert(snippets, {
range = { start_line, end_line },
content = table.concat(current_snippet, "\n"),
lang = lang,
explanation = explanation,
})
end
current_snippet = {}
start_line, end_line = nil, nil
explanation = ""
in_code_block = false
else
lang = line:match("^```(%w+)")
if not lang or lang == "" then
lang = "text"
end
in_code_block = true
end
elseif in_code_block then
table.insert(current_snippet, line)
else
explanation = explanation .. line .. "\n"
end
end
return snippets
end
local system_prompt = [[
You are an excellent programming expert.
]]
local user_prompt_tpl = [[
Your primary task is to suggest code modifications with precise line number ranges. Follow these instructions meticulously:
1. Carefully analyze the original code, paying close attention to its structure and line numbers. Line numbers start from 1 and include ALL lines, even empty ones.
2. When suggesting modifications:
a. Explain why the change is necessary or beneficial.
b. Provide the exact code snippet to be replaced using this format:
Replace lines: {{start_line}}-{{end_line}}
```{{language}}
{{suggested_code}}
```
3. Crucial guidelines for line numbers:
- L1:, L2:, L3:, ... in the prefix of each line represent line numbers in the original code, you must use these exact numbers, but you must NOT include them in your response.
- The range {{start_line}}-{{end_line}} is INCLUSIVE. Both start_line and end_line are included in the replacement.
- Count EVERY line, including empty lines, comments, and the LAST line of the file.
- For single-line changes, use the same number for start and end lines.
- For multi-line changes, ensure the range covers ALL affected lines, from the very first to the very last.
- Include the entire block (e.g., complete function) when modifying structured code.
- Pay special attention to the start_line, ensuring it's not omitted or incorrectly set.
- Double-check that your start_line is correct, especially for changes at the beginning of the file.
- Also, be careful with the end_line, especially when it's the last line of the file.
- Double-check that your line numbers align perfectly with the original code structure.
4. Context and verification:
- Show 1-2 unchanged lines before and after each modification as context.
- These context lines are NOT included in the replacement range.
- After each suggestion, recount the lines to verify the accuracy of your line numbers.
- Double-check that both the start_line and end_line are correct for each modification.
- Verify that your suggested changes align perfectly with the original code structure.
5. Final check:
- Review all suggestions, ensuring each line number is correct, especially the start_line and end_line.
- Pay extra attention to the start_line of each modification, ensuring it hasn't shifted down.
- Confirm that no unrelated code is accidentally modified or deleted.
- Verify that the start_line and end_line correctly include all intended lines for replacement.
- If a modification involves the first or last line of the file, explicitly state this in your explanation.
- Perform a final alignment check to ensure your line numbers haven't shifted, especially the start_line.
- Double-check that your line numbers align perfectly with the original code structure.
- Do not show the content after these modifications.
Remember: Accurate line numbers are CRITICAL. The range start_line to end_line must include ALL lines to be replaced, from the very first to the very last. Double-check every range before finalizing your response, paying special attention to the start_line to ensure it hasn't shifted down. Ensure that your line numbers perfectly match the original code structure without any overall shift.
QUESTION: ${{question}}
CODE:
```
${{code}}
```
]]
local function call_claude_api_stream(prompt, original_content, on_chunk, on_complete)
local api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key then
error("ANTHROPIC_API_KEY environment variable is not set")
end
local user_prompt = user_prompt_tpl:gsub("${{question}}", prompt):gsub("${{code}}", original_content)
print("Sending request to Claude API...")
local tokens = M.config.claude.model == "claude-3-5-sonnet-20240620" and 8192 or 4096
local headers = {
["Content-Type"] = "application/json",
["x-api-key"] = api_key,
["anthropic-version"] = "2023-06-01",
["anthropic-beta"] = "messages-2023-12-15",
}
if M.config.claude.model == "claude-3-5-sonnet-20240620" then
headers["anthropic-beta"] = "max-tokens-3-5-sonnet-2024-07-15"
end
local url = "https://api.anthropic.com/v1/messages"
curl.post(url, {
---@diagnostic disable-next-line: unused-local
stream = function(err, data, job)
if err then
error("Error: " .. vim.inspect(err))
return
end
if data then
for line in data:gmatch("[^\r\n]+") do
if line:sub(1, 6) == "data: " then
vim.schedule(function()
local success, parsed = pcall(fn.json_decode, line:sub(7))
if success and parsed and parsed.type == "content_block_delta" then
on_chunk(parsed.delta.text)
elseif success and parsed and parsed.type == "message_stop" then
-- Stream request completed
on_complete()
elseif success and parsed and parsed.type == "error" then
print("Error: " .. vim.inspect(parsed))
-- Stream request completed
on_complete()
end
end)
end
end
end
end,
headers = headers,
body = fn.json_encode({
model = M.config.claude.model,
system = system_prompt,
messages = {
{ role = "user", content = user_prompt },
},
stream = true,
temperature = M.config.claude.temperature,
max_tokens = tokens,
}),
})
end
local function call_openai_api_stream(prompt, original_content, on_chunk, on_complete)
local api_key = os.getenv("OPENAI_API_KEY")
if not api_key then
error("OPENAI_API_KEY environment variable is not set")
end
local user_prompt = user_prompt_tpl:gsub("${{question}}", prompt):gsub("${{code}}", original_content)
print("Sending request to OpenAI API...")
curl.post("https://api.openai.com/v1/chat/completions", {
---@diagnostic disable-next-line: unused-local
stream = function(err, data, job)
if err then
error("Error: " .. vim.inspect(err))
return
end
if data then
for line in data:gmatch("[^\r\n]+") do
if line:sub(1, 6) == "data: " then
vim.schedule(function()
local success, parsed = pcall(fn.json_decode, line:sub(7))
if success and parsed and parsed.choices and parsed.choices[1].delta.content then
on_chunk(parsed.choices[1].delta.content)
elseif success and parsed and parsed.choices and parsed.choices[1].finish_reason == "stop" then
-- Stream request completed
on_complete()
end
end)
end
end
end
end,
headers = {
["Content-Type"] = "application/json",
["Authorization"] = "Bearer " .. api_key,
},
body = fn.json_encode({
model = M.config.openai.model,
messages = {
{ role = "system", content = system_prompt },
{ role = "user", content = user_prompt },
},
temperature = M.config.openai.temperature,
max_tokens = M.config.openai.max_tokens,
stream = true,
}),
})
end
local function call_ai_api_stream(prompt, original_content, on_chunk, on_complete)
if M.config.provider == "openai" then
call_openai_api_stream(prompt, original_content, on_chunk, on_complete)
elseif M.config.provider == "claude" then
call_claude_api_stream(prompt, original_content, on_chunk, on_complete)
end
end
local function update_result_buf_content(content)
local current_win = api.nvim_get_current_win()
local result_win = fn.bufwinid(result_buf)
vim.defer_fn(function()
api.nvim_set_option_value("modifiable", true, { buf = result_buf })
api.nvim_buf_set_lines(result_buf, 0, -1, false, vim.split(content, "\n"))
api.nvim_set_option_value("filetype", "markdown", { buf = result_buf })
if result_win ~= -1 then
-- Move to the bottom
api.nvim_win_set_cursor(result_win, { api.nvim_buf_line_count(result_buf), 0 })
api.nvim_set_option_value("modifiable", false, { buf = result_buf })
api.nvim_set_current_win(current_win)
end
end, 0)
end
-- Add a new function to display notifications
local function show_notification(message)
vim.notify(message, vim.log.levels.INFO, {
title = "AI Assistant",
timeout = 3000,
})
end
-- Function to get the current project root directory
local function get_project_root()
local current_file = fn.expand("%:p")
local current_dir = fn.fnamemodify(current_file, ":h")
local git_root = fn.systemlist("git -C " .. fn.shellescape(current_dir) .. " rev-parse --show-toplevel")[1]
return git_root or current_dir
end
local function get_chat_history_filename()
local code_buf_name = get_cur_code_buf_name()
if code_buf_name == nil then
print("Error: cannot get code buffer name")
return
end
local relative_path = fn.fnamemodify(code_buf_name, ":~:.")
-- Replace path separators with double underscores
local path_with_separators = fn.substitute(relative_path, "/", "__", "g")
-- Replace other non-alphanumeric characters with single underscores
return fn.substitute(path_with_separators, "[^A-Za-z0-9._]", "_", "g")
end
-- Function to get the chat history file path
local function get_chat_history_file()
local project_root = get_project_root()
local filename = get_chat_history_filename()
local history_dir = Path:new(project_root, ".avante_chat_history")
return history_dir:joinpath(filename .. ".json")
end
-- Function to get current timestamp
local function get_timestamp()
return os.date("%Y-%m-%d %H:%M:%S")
end
-- Function to load chat history
local function load_chat_history()
local history_file = get_chat_history_file()
if history_file:exists() then
local content = history_file:read()
return fn.json_decode(content)
end
return {}
end
-- Function to save chat history
local function save_chat_history(history)
local history_file = get_chat_history_file()
local history_dir = history_file:parent()
-- Create the directory if it doesn't exist
if not history_dir:exists() then
history_dir:mkdir({ parents = true })
end
history_file:write(fn.json_encode(history), "w")
end
local function update_result_buf_with_history(history)
local content = ""
for _, entry in ipairs(history) do
content = content .. "## " .. entry.timestamp .. "\n\n"
content = content .. "> " .. entry.requirement:gsub("\n", "\n> ") .. "\n\n"
content = content .. entry.response .. "\n\n"
content = content .. "---\n\n"
end
update_result_buf_content(content)
end
local function get_conflict_content(content, snippets)
-- sort snippets by start_line
table.sort(snippets, function(a, b)
return a.range[1] < b.range[1]
end)
local lines = vim.split(content, "\n")
local result = {}
local current_line = 1
for _, snippet in ipairs(snippets) do
local start_line, end_line = unpack(snippet.range)
while current_line < start_line do
table.insert(result, lines[current_line])
current_line = current_line + 1
end
table.insert(result, "<<<<<<< HEAD")
for i = start_line, end_line do
table.insert(result, lines[i])
end
table.insert(result, "=======")
for _, line in ipairs(vim.split(snippet.content, "\n")) do
table.insert(result, line)
end
table.insert(result, ">>>>>>> Snippet")
current_line = end_line + 1
end
while current_line <= #lines do
table.insert(result, lines[current_line])
current_line = current_line + 1
end
return result
end
local renderer_width = math.ceil(vim.o.columns * 0.3)
local renderer = n.create_renderer({
width = renderer_width,
height = vim.o.lines,
position = vim.o.columns - renderer_width,
relative = "editor",
})
function M.render_sidebar()
local chat_history = load_chat_history()
update_result_buf_with_history(chat_history)
local function handle_submit()
local state = signal:get_value()
local user_input = state.text
local timestamp = get_timestamp()
update_result_buf_content(
"\n\n## " .. timestamp .. "\n\n> " .. user_input:gsub("\n", "\n> ") .. "\n\nGenerating response...\n"
)
local code_buf = get_cur_code_buf()
if code_buf == nil then
error("Error: cannot get code buffer")
return
end
local content = table.concat(get_cur_code_buf_content(), "\n")
local content_with_line_numbers = prepend_line_number(content)
local full_response = ""
signal.is_loading = true
call_ai_api_stream(user_input, content_with_line_numbers, function(chunk)
full_response = full_response .. chunk
update_result_buf_content(
"## " .. timestamp .. "\n\n> " .. user_input:gsub("\n", "\n> ") .. "\n\n" .. full_response
)
vim.schedule(function()
vim.cmd("redraw")
end)
end, function()
signal.is_loading = false
-- Execute when the stream request is actually completed
update_result_buf_content(
"## "
.. timestamp
.. "\n\n> "
.. user_input:gsub("\n", "\n> ")
.. "\n\n"
.. full_response
.. "\n\n**Generation complete!** Please review the code suggestions above.\n\n\n\n"
)
-- Display notification
show_notification("Content generation complete!")
-- Save chat history
table.insert(chat_history or {}, { timestamp = timestamp, requirement = user_input, response = full_response })
save_chat_history(chat_history)
local snippets = extract_code_snippets(full_response)
local conflict_content = get_conflict_content(content, snippets)
vim.defer_fn(function()
api.nvim_buf_set_lines(code_buf, 0, -1, false, conflict_content)
local code_win = get_cur_code_win()
if code_win == nil then
error("Error: cannot get code window")
return
end
api.nvim_set_current_win(code_win)
api.nvim_feedkeys(api.nvim_replace_termcodes("<Esc>", true, false, true), "n", true)
diff.add_visited_buffer(code_buf)
diff.process(code_buf)
api.nvim_feedkeys("gg", "n", false)
vim.defer_fn(function()
vim.cmd("AvanteConflictNextConflict")
api.nvim_feedkeys("zz", "n", false)
end, 1000)
end, 10)
end)
end
local body = function()
local code_buf = get_cur_code_buf()
if code_buf == nil then
error("Error: cannot get code buffer")
return
end
local filetype = api.nvim_get_option_value("filetype", { buf = code_buf })
local icon = require("nvim-web-devicons").get_icon_by_filetype(filetype, {})
local code_file_fullpath = api.nvim_buf_get_name(code_buf)
local code_filename = fn.fnamemodify(code_file_fullpath, ":t")
return n.rows(
{ flex = 0 },
n.box(
{
direction = "column",
size = vim.o.lines - 3,
},
n.buffer({
id = "response",
flex = 1,
buf = result_buf,
autoscroll = true,
border_label = {
text = "💬 Avante Chat",
align = "center",
},
})
),
n.gap(1),
n.columns(
{ flex = 0 },
n.text_input({
id = "text-input",
border_label = {
text = string.format(" 🙋 Your question (with %s %s): ", icon, code_filename),
},
autofocus = true,
wrap = true,
flex = 1,
on_change = function(value)
local state = signal:get_value()
local is_enter = value:sub(-1) == "\n" and #state.text < #value
if is_enter then
value = value:sub(1, -2)
end
signal.text = value
if is_enter and #value > 0 then
handle_submit()
end
end,
}),
n.gap(1),
n.spinner({
is_loading = signal.is_loading,
padding = { top = 1, left = 1 },
---@diagnostic disable-next-line: undefined-field
hidden = signal.is_loading:negate(),
})
)
)
end
renderer:render(body)
end
M.config = {
provider = "claude",
openai = {
model = "gpt-4o",
temperature = 0,
max_tokens = 4096,
},
claude = {
model = "claude-3-5-sonnet-20240620",
temperature = 0,
max_tokens = 4096,
},
mappings = {
show_sidebar = "<leader>aa",
apply = "co",
reject = "ct",
next = "]x",
prev = "[x",
},
}
function M.setup(opts)
local bufnr = vim.api.nvim_get_current_buf()
if is_code_buf(bufnr) then
_cur_code_buf = bufnr
end
diff.setup({
debug = false, -- log output to console
default_mappings = true, -- disable buffer local mapping created by this plugin
default_commands = true, -- disable commands created by this plugin
disable_diagnostics = true, -- This will disable the diagnostics in a buffer whilst it is conflicted
list_opener = "copen",
highlights = {
incoming = "DiffAdded",
current = "DiffRemoved",
},
})
M.config = vim.tbl_deep_extend("force", M.config, opts or {})
local function on_buf_enter()
bufnr = vim.api.nvim_get_current_buf()
if is_code_buf(bufnr) then
_cur_code_buf = bufnr
end
end
api.nvim_create_autocmd("BufEnter", {
callback = on_buf_enter,
})
api.nvim_create_user_command("AvanteAsk", function()
M.render_sidebar()
end, {
nargs = 0,
})
api.nvim_set_keymap("n", M.config.mappings.show_sidebar, "<cmd>AvanteAsk<CR>", { noremap = true, silent = true })
end
return M