local function lines_with_preview()
  local current_file = vim.fn.fnameescape(vim.fn.expand('%'))
  local rg_command = string.format("rg --with-filename --column --line-number --no-heading --color=always --smart-case . %s", current_file)
  local fzf_command = string.format("call fzf#vim#grep('%s', 1, fzf#vim#with_preview({'options': '--delimiter : --nth 4.. --no-sort'}, 'up:50%%', '?'), 1)", rg_command)
  vim.cmd(fzf_command)
end
function DevtoolsPath()
    local devPath = vim.fn.trim(vim.fn.system('ls ' .. vim.fn.expand("%:p:h") .. ' | grep DESCRIPTION'))
    
    if devPath == "" then
        devPath = vim.fn.trim(vim.fn.system('realpath ' .. vim.fn.expand("%:p:h") .. '/../'))
        return devPath
    else
        devPath = vim.fn.expand('%:p:h')
        return devPath
    end
end

vim.api.nvim_create_user_command('LinesWithPreview', lines_with_preview, {})
vim.api.nvim_create_autocmd({"BufNewFile", "BufRead"}, {
    pattern = "DESCRIPTION",
    command = "set filetype=r"
})

local function IronQuiteSend(opts)
    -- Get the current filetype to send to the appropriate REPL
    local ft = vim.bo.filetype

    -- Concatenate all arguments passed to the command
    local command = table.concat(opts.fargs, " ")

    -- Send the command to the REPL
    require('iron.core').send(ft, command)
end

-- Create the primary command in Neovim
vim.api.nvim_create_user_command('IronQuiteSend', IronQuiteSend, {
    nargs = '+', -- Allows for multiple arguments
})



-- Map <C-c>wd to send devtools::document command in R
vim.api.nvim_create_autocmd("FileType", {
    pattern = "r",
    callback = function()
        vim.api.nvim_set_keymap('n', '<C-c>wd', ':IronQuiteSend devtools::document("' .. DevtoolsPath() .. '")<CR>', { noremap = true, silent = true })
    end
})

-- Map <C-c>wi to send devtools::install command in R
vim.api.nvim_create_autocmd("FileType", {
    pattern = "r",
    callback = function()
        vim.api.nvim_set_keymap('n', '<C-c>wi', ':IronQuiteSend devtools::install("' .. DevtoolsPath() .. '", upgrade = "never")<CR>', { noremap = true, silent = true })
    end
})

vim.api.nvim_create_autocmd("FileType", {
    pattern = "r",
    callback = function()
        vim.api.nvim_set_keymap('n', '<C-c>i', ':IronQuiteSend install.packages("")<Left><Left>', { noremap = true, silent = true })
    end
})



