ronantakizawa/codereview-bench huggingface dataset:
Repository: neovim/neovim
File: runtime/lua/vim/_core/util.lua (Lua)

Code before:
local M = {}

--- Edit a file in a specific window
--- @param winnr number
--- @param file string
--- @return number buffer number of the edited buffer
M.edit_in = function(winnr, file)
  local function resolved_path(path)
    if not path or path == '' then
      return ''
    end
    return vim.fn.resolve(vim.fs.abspath(path))
  end

  return vim.api.nvim_win_call(winnr, function()
    local current_buf = vim.api.nvim_win_get_buf(winnr)
    local current = resolved_path(vim.api.nvim_buf_get_name(current_buf))

    -- Check if the current buffer is already the target file
    if current == resolved_path(file) then
      return current_buf
    end

    -- Read the file into the buffer
    vim.cmd.edit(vim.fn.fnameescape(file))
    return vim.api.nvim_get_current_buf()
  end)
end

--- Read a chunk of data from a file
--- @param file string
--- @param size number
--- @return string? chunk or nil on error
function M.read_chunk(file, size)
  local fd = io.open(file, 'rb')
  if not fd then
    return nil
  end
  local chunk = fd:read(size)
  fd:close()
  return tostring(chunk)
end

return M


Review comment (suggestion):
Just for future reference: We can start adding topic-specific files in `_core/` easily. Meanwhile, `_core/util.lua` is only for stuff that doesn't have a home yet. But this function could obviously live in something like `_core/treesitter.lua`.

Code after:
    vim.cmd.edit(vim.fn.fnameescape(file))
    return vim.api.nvim_get_current_buf()
  end)
end

--- Read a chunk of data from a file
--- @param file string
--- @param size number
--- @return string? chunk or nil on error
function M.read_chunk(file, size)
  local fd = io.open(file, 'rb')
  if not fd then
    return nil
  end
  local chunk = fd:read(size)
  fd:close()
  return tostring(chunk)
end

--- Check if a range in a buffer is inside a Lua codeblock via treesitter injection.
--- Used by :source to detect Lua code in non-Lua files (e.g., vimdoc).
--- @param bufnr integer Buffer number
--- @param line1 integer Start line (1-indexed)
--- @param line2 integer End line (1-indexed)
--- @return boolean True if the range is in a Lua injection
function M.source_is_lua(bufnr, line1, line2)
  local ok, parser = pcall(vim.treesitter.get_parser, bufnr)
  if not ok or not parser then
    return false
  end
  -- Parse from buffer start through one line past line2 to include injection closing markers
  local range = { line1 - 1, 0, line2 - 1, -1 }
  parser:parse({ 0, 0, line2, -1 })
  local lang_tree = parser:language_for_range(range)
  return lang_tree:lang() == 'lua'
end

return M
Repository: neovim/neovim
File: runtime/lua/vim/lsp/diagnostic.lua (Lua)

Code before:
    diag_opts.namespace = M.get_namespace(client_id, false)
  end

  diag_opts.lnum = line_nr or (api.nvim_win_get_cursor(0)[1] - 1)

  return M.from(vim.diagnostic.get(bufnr, diag_opts))
end

--- Clear diagnostics from pull based clients
local function clear(bufnr)
  for _, namespace in pairs(client_pull_namespaces) do
    vim.diagnostic.reset(namespace, bufnr)
  end
end

--- Disable pull diagnostics for a buffer
--- @param bufnr integer
local function disable(bufnr)
  local bufstate = bufstates[bufnr]
  if bufstate then
    bufstate.pull_kind = 'disabled'
  end
  clear(bufnr)
end

--- @nodoc
--- Refresh diagnostics, only if we have attached clients that support it
---@param bufnr integer buffer number
---@param client_id? integer Client ID to refresh (default: all clients)
---@param only_visible? boolean Whether to only refresh for the visible regions of the buffer (default: false)
function M._refresh(bufnr, client_id, only_visible)
  if
    only_visible
    and vim.iter(api.nvim_list_wins()):all(function(window)
      return api.nvim_win_get_buf(window) ~= bufnr
    end)
  then
    return
  end

  local method = 'textDocument/diagnostic'
  local clients = lsp.get_clients({ bufnr = bufnr, method = method, id = client_id })
  local bufstate = bufstates[bufnr]

  util._cancel_requests({
    bufnr = bufnr,
    clients = clients,
    method = method,
    type = 'pending',
  })
  for _, client in ipairs(clients) do

Review comment (suggestion):
Because the method is underscored it will be private and we won't generate docs.
```suggestion
```

Code after:
    diag_opts.namespace = M.get_namespace(client_id, false)
  end

  diag_opts.lnum = line_nr or (api.nvim_win_get_cursor(0)[1] - 1)

  return M.from(vim.diagnostic.get(bufnr, diag_opts))
end

--- Clear diagnostics from pull based clients
local function clear(bufnr)
  for _, namespace in pairs(client_pull_namespaces) do
    vim.diagnostic.reset(namespace, bufnr)
  end
end

--- Disable pull diagnostics for a buffer
--- @param bufnr integer
local function disable(bufnr)
  local bufstate = bufstates[bufnr]
  if bufstate then
    bufstate.pull_kind = 'disabled'
  end
  clear(bufnr)
end

--- Refresh diagnostics, only if we have attached clients that support it
---@param bufnr integer buffer number
---@param client_id? integer Client ID to refresh (default: all clients)
---@param only_visible? boolean Whether to only refresh for the visible regions of the buffer (default: false)
function M._refresh(bufnr, client_id, only_visible)
  if
    only_visible
    and vim.iter(api.nvim_list_wins()):all(function(window)
      return api.nvim_win_get_buf(window) ~= bufnr
    end)
  then
    return
  end

  local method = 'textDocument/diagnostic'
  local clients = lsp.get_clients({ bufnr = bufnr, method = method, id = client_id })
  local bufstate = bufstates[bufnr]

  util._cancel_requests({
    bufnr = bufnr,
    clients = clients,
    method = method,
    type = 'pending',
  })
  for _, client in ipairs(clients) do
    ---@type lsp.DocumentDiagnosticParams
Repository: neovim/neovim
File: runtime/lua/vim/_core/ex_cmd/lsp.lua (Lua)

Code before:
local api = vim.api
local lsp = vim.lsp
local ERROR = vim.log.levels.ERROR

local M = {}

--- @return string[]
local function get_client_names()
  local client_names = vim
    .iter(lsp.get_clients())
    :map(function(client)
      return client.name
    end)
    :totable()
  return vim.list.unique(client_names)
end

--- @return string[]
local function get_config_names()
  local config_names = vim
    .iter(api.nvim_get_runtime_file('lsp/*.lua', true))
    --- @param path string
    :map(function(path)
      local file_name = path:match('[^/]*.lua$')
      return file_name:sub(0, #file_name - 4)
    end)
    :totable()


Review comment (suggestion):
just a nit to avoid this becoming a pattern: if anything is going to be aliased, alias `levels` , not the specific level names.
```suggestion
local loglevel = vim.log.levels
```

Code after:
local api = vim.api
local lsp = vim.lsp

local M = {}

--- @return string[]
local function get_client_names()
  local client_names = vim
    .iter(lsp.get_clients())
    :map(function(client)
      return client.name
    end)
    :totable()
  return vim.list.unique(client_names)
end

--- @return string[]
local function get_config_names()
  local config_names = vim
    .iter(api.nvim_get_runtime_file('lsp/*.lua', true))
    --- @param path string
    :map(function(path)
      local file_name = path:match('[^/]*.lua$')
      return file_name:sub(0, #file_name - 4)
    end)
    :totable()

  --- @diagnostic disable-next-line
Repository: neovim/neovim
File: runtime/lua/vim/_core/ex_cmd/lsp.lua (Lua)

Code before:

    client:stop(client.exit_timeout)
  end
end

--- @param client_names string[]
local function ex_lsp_stop(client_names)
  local clients = get_clients_from_names(client_names)

  for _, client in ipairs(clients) do
    client:stop(client.exit_timeout)
  end
end

local actions = {
  enable = ex_lsp_enable,
  disable = ex_lsp_disable,
  restart = ex_lsp_restart,
  stop = ex_lsp_stop,
}

local available_subcmds = vim.tbl_keys(actions)

--- Use for `:lsp {subcmd} {name}?` command
--- @param args string
M.lsp = function(args)
  local fargs = api.nvim_parse_cmd('lsp ' .. args, {}).args
  if not fargs then
    return
  end
  local subcmd = fargs[1]
  if not vim.list_contains(available_subcmds, subcmd) then
    vim.notify(("Invalid subcommand '%s'"):format(subcmd), ERROR)
    return
  end

  local clients = { unpack(fargs, 2) }

  actions[subcmd](clients)
end

--- Completion logic for `:lsp` command
--- @param line string content of the current command line
--- @return string[] list of completions
function M.lsp_complete(line)
  local split = vim.split(line, '%s+')
  if #split == 2 then
    return available_subcmds
  else
    local subcmd = split[2]
    return vim

Review comment (suggestion):
The general idea for `_core` stuff is that it has a similar layout as the C modules. So this should be named `ex_lsp` since that is how we name the C thing. (And hopefully it's understand that everything in `_core` is private.)

Code after:
  end
end

local actions = {
  enable = ex_lsp_enable,
  disable = ex_lsp_disable,
  restart = ex_lsp_restart,
  stop = ex_lsp_stop,
}

local available_subcmds = vim.tbl_keys(actions)

--- Implements command: `:lsp {subcmd} {name}?`.
--- @param args string
M.ex_lsp = function(args)
  local fargs = api.nvim_parse_cmd('lsp ' .. args, {}).args
  if not fargs then
    return
  end
  local subcmd = fargs[1]
  if not vim.list_contains(available_subcmds, subcmd) then
    vim.notify(("Invalid subcommand '%s'"):format(subcmd), vim.log.levels.ERROR)
    return
  end

  local clients = { unpack(fargs, 2) }

  actions[subcmd](clients)
end

--- Completion logic for `:lsp` command
--- @param line string content of the current command line
--- @return string[] list of completions
function M.lsp_complete(line)
  local split = vim.split(line, '%s+')
  if #split == 2 then
    return available_subcmds
  else
    local subcmd = split[2]
    return vim
      .iter(complete_args[subcmd]())
      --- @param n string
      :map(function(n)
        return vim.fn.escape(n, ' \t')
      end)
      :totable()
  end
end

return M
Repository: neovim/neovim
File: runtime/lua/vim/_core/ex_cmd/lsp.lua (Lua)

Code before:
      end,
    })

    client:stop(client.exit_timeout)
  end
end

--- @param client_names string[]
local function ex_lsp_stop(client_names)
  local clients = get_clients_from_names(client_names)

  for _, client in ipairs(clients) do
    client:stop(client.exit_timeout)
  end
end

local actions = {
  enable = ex_lsp_enable,
  disable = ex_lsp_disable,
  restart = ex_lsp_restart,
  stop = ex_lsp_stop,
}

local available_subcmds = vim.tbl_keys(actions)

--- Use for `:lsp {subcmd} {name}?` command
--- @param args string
M.lsp = function(args)
  local fargs = api.nvim_parse_cmd('lsp ' .. args, {}).args
  if not fargs then
    return
  end
  local subcmd = fargs[1]
  if not vim.list_contains(available_subcmds, subcmd) then
    vim.notify(("Invalid subcommand '%s'"):format(subcmd), ERROR)
    return
  end

  local clients = { unpack(fargs, 2) }

  actions[subcmd](clients)
end

--- Completion logic for `:lsp` command
--- @param line string content of the current command line
--- @return string[] list of completions
function M.lsp_complete(line)
  local split = vim.split(line, '%s+')
  if #split == 2 then
    return available_subcmds
  else

Review comment (suggestion):
```suggestion
--- Implements command: `:lsp {subcmd} {name}?`.
```

Code after:
  for _, client in ipairs(clients) do
    client:stop(client.exit_timeout)
  end
end

local actions = {
  enable = ex_lsp_enable,
  disable = ex_lsp_disable,
  restart = ex_lsp_restart,
  stop = ex_lsp_stop,
}

local available_subcmds = vim.tbl_keys(actions)

--- Implements command: `:lsp {subcmd} {name}?`.
--- @param args string
M.ex_lsp = function(args)
  local fargs = api.nvim_parse_cmd('lsp ' .. args, {}).args
  if not fargs then
    return
  end
  local subcmd = fargs[1]
  if not vim.list_contains(available_subcmds, subcmd) then
    vim.notify(("Invalid subcommand '%s'"):format(subcmd), vim.log.levels.ERROR)
    return
  end

  local clients = { unpack(fargs, 2) }

  actions[subcmd](clients)
end

--- Completion logic for `:lsp` command
--- @param line string content of the current command line
--- @return string[] list of completions
function M.lsp_complete(line)
  local split = vim.split(line, '%s+')
  if #split == 2 then
    return available_subcmds
  else
    local subcmd = split[2]
    return vim
      .iter(complete_args[subcmd]())
      --- @param n string
      :map(function(n)
        return vim.fn.escape(n, ' \t')
      end)
      :totable()
  end
end
Repository: neovim/neovim
File: runtime/lua/vim/_core/ex_cmd/lsp.lua (Lua)

Code before:
      callback = function(info)
        if info.data.client_id ~= client.id then
          return
        end

        local new_client_id = lsp.start(client.config, { attach = false })
        if new_client_id then
          for _, buffer in ipairs(attached_buffers) do
            lsp.buf_attach_client(buffer, new_client_id)
          end
        end

        return true -- Delete autocmd
      end,
    })

    client:stop(client.exit_timeout)
  end
end

--- @param client_names string[]
local function ex_lsp_stop(client_names)
  local clients = get_clients_from_names(client_names)

  for _, client in ipairs(clients) do
    client:stop(client.exit_timeout)
  end
end

local actions = {
  enable = ex_lsp_enable,
  disable = ex_lsp_disable,
  restart = ex_lsp_restart,
  stop = ex_lsp_stop,
}

local available_subcmds = vim.tbl_keys(actions)

--- Use for `:lsp {subcmd} {name}?` command
--- @param args string
M.lsp = function(args)
  local fargs = api.nvim_parse_cmd('lsp ' .. args, {}).args
  if not fargs then
    return
  end
  local subcmd = fargs[1]
  if not vim.list_contains(available_subcmds, subcmd) then
    vim.notify(("Invalid subcommand '%s'"):format(subcmd), ERROR)
    return
  end


Review comment (suggestion):
For reference: builtin support for subcommands was proposed in https://github.com/neovim/neovim/pull/29116 in the Lua layer, but it probabably should be part of `nvim_create_user_command`.

Code after:

        return true -- Delete autocmd
      end,
    })

    client:stop(client.exit_timeout)
  end
end

--- @param client_names string[]
local function ex_lsp_stop(client_names)
  local clients = get_clients_from_names(client_names)

  for _, client in ipairs(clients) do
    client:stop(client.exit_timeout)
  end
end

local actions = {
  enable = ex_lsp_enable,
  disable = ex_lsp_disable,
  restart = ex_lsp_restart,
  stop = ex_lsp_stop,
}

local available_subcmds = vim.tbl_keys(actions)

--- Implements command: `:lsp {subcmd} {name}?`.
--- @param args string
M.ex_lsp = function(args)
  local fargs = api.nvim_parse_cmd('lsp ' .. args, {}).args
  if not fargs then
    return
  end
  local subcmd = fargs[1]
  if not vim.list_contains(available_subcmds, subcmd) then
    vim.notify(("Invalid subcommand '%s'"):format(subcmd), vim.log.levels.ERROR)
    return
  end

  local clients = { unpack(fargs, 2) }

  actions[subcmd](clients)
end

--- Completion logic for `:lsp` command
--- @param line string content of the current command line
--- @return string[] list of completions
function M.lsp_complete(line)
  local split = vim.split(line, '%s+')
  if #split == 2 then
Repository: neovim/neovim
File: test/functional/ex_cmds/lsp_spec.lua (Lua)

Code before:
local t = require('test.testutil')
local n = require('test.functional.testnvim')()
local t_lsp = require('test.functional.plugin.lsp.testutil')

local clear = n.clear
local eq = t.eq
local exec_lua = n.exec_lua

local create_server_definition = t_lsp.create_server_definition

describe(':lsp', function()
  before_each(function()
    clear()
    exec_lua(create_server_definition)
    exec_lua(function()
      local server = _G._create_server()
      vim.lsp.config('dummy', {
        filetypes = { 'lua' },
        cmd = server.cmd,
      })
      vim.cmd('set ft=lua')
    end)
  end)

  it('enable with arguments', function()
    local is_enabled = exec_lua(function()
      vim.cmd('lsp enable dummy')
      return vim.lsp.is_enabled('dummy')
    end)
    eq(true, is_enabled)
  end)

  it('enable without arguments', function()
    local is_enabled = exec_lua(function()
      vim.cmd('lsp enable')
      return vim.lsp.is_enabled('dummy')
    end)
    eq(true, is_enabled)
  end)

  it('disable with arguments', function()
    local is_enabled = exec_lua(function()
      vim.lsp.enable('dummy')
      vim.cmd('lsp disable dummy')
      return vim.lsp.is_enabled('dummy')
    end)
    eq(false, is_enabled)
  end)

  it('disable without arguments', function()

Review comment (bug):
Also need 1 mini-test which just checks how things fail with `nvim -u NONE` (i.e. when the runtime is missing). Mainly just want to check that nvim doesn't crash.

```lua
    clear {
      args_rm = { '-u' },
      args = { '-u', 'NONE' },
      env = { VIMRUNTIME = 'non-existent' },
    }
    eq('..', t.pcall_err(n.command, 'lsp enable dummy'))
```

Code after:
local t = require('test.testutil')
local n = require('test.functional.testnvim')()
local t_lsp = require('test.functional.plugin.lsp.testutil')

local clear = n.clear
local eq = t.eq
local exec_lua = n.exec_lua

local create_server_definition = t_lsp.create_server_definition

describe(':lsp', function()
  before_each(function()
    clear()
    exec_lua(create_server_definition)
    exec_lua(function()
      local server = _G._create_server()
      vim.lsp.config('dummy', {
        filetypes = { 'lua' },
        cmd = server.cmd,
      })
      vim.cmd('set ft=lua')
    end)
  end)

  for _, test_with_arguments in ipairs({ true, false }) do
    local test_message_suffix, lsp_command_suffix
    if test_with_arguments then
      test_message_suffix = ' with arguments'
      lsp_command_suffix = ' dummy'
    else
      test_message_suffix = ' without arguments'
      lsp_command_suffix = ''
    end

    it('enable' .. test_message_suffix, function()
      local is_enabled = exec_lua(function()
        vim.cmd('lsp enable' .. lsp_command_suffix)
        return vim.lsp.is_enabled('dummy')
      end)
      eq(true, is_enabled)
    end)

    it('disable' .. test_message_suffix, function()
      local is_enabled = exec_lua(function()
        vim.lsp.enable('dummy')
        vim.cmd('lsp disable' .. lsp_command_suffix)
        return vim.lsp.is_enabled('dummy')
      end)
      eq(false, is_enabled)
    end)
Repository: neovim/neovim
File: test/functional/options/num_options_spec.lua (Lua)

Code before:
    should_fail('updatetime', -1, 'E487')

    should_fail('foldlevel', -5, 'E487')
    should_fail('foldcolumn', '13', 'E474')
    should_fail('conceallevel', 4, 'E474')
    should_fail('numberwidth', 21, 'E474')
    should_fail('numberwidth', 0, 'E487')

    -- If smaller than 1 this one is set to 'lines'-1
    command('setglobal window=-10')
    api.nvim_set_option_value('window', -10, {})
    eq(23, api.nvim_get_option_value('window', {}))
    eq('', eval('v:errmsg'))

    -- 'scrolloff' and 'sidescrolloff' can have a -1 value when
    -- set for the current window, but not globally
    matches('E487', pcall_err(command, 'setglobal scrolloff=-1'))
    matches('E487', pcall_err(command, 'setglobal sidescrolloff=-1'))

    eq(true, pcall(command, 'setlocal scrolloff=-1'))
    eq(true, pcall(command, 'setlocal sidescrolloff=-1'))
  end)

  it('set wmh/wh wmw/wiw checks', function()
    command('set winheight=2')
    matches('E591', pcall_err(command, 'set winminheight=3'))

    command('set winwidth=2')
    matches('E592', pcall_err(command, 'set winminwidth=3'))
  end)

  it('set maxcombine resets to 6', function()
    local function setto(value)
      command('setglobal maxcombine=' .. value)
      command('setlocal maxcombine=' .. value)
      api.nvim_set_option_value('maxcombine', value, {})
      eq(6, api.nvim_get_option_value('maxcombine', {}))
      eq('', eval('v:errmsg'))
    end
    setto(0)
    setto(1)
    setto(6)
    setto(7)
  end)
end)


Review comment (suggestion):
```suggestion
    matches('E591:', pcall_err(command, 'set winminheight=3'))
```

Code after:
    should_fail('updatetime', -1, 'E487')

    should_fail('foldlevel', -5, 'E487')
    should_fail('foldcolumn', '13', 'E474')
    should_fail('conceallevel', 4, 'E474')
    should_fail('numberwidth', 21, 'E474')
    should_fail('numberwidth', 0, 'E487')

    -- If smaller than 1 this one is set to 'lines'-1
    command('setglobal window=-10')
    api.nvim_set_option_value('window', -10, {})
    eq(23, api.nvim_get_option_value('window', {}))
    eq('', eval('v:errmsg'))

    -- 'scrolloff' and 'sidescrolloff' can have a -1 value when
    -- set for the current window, but not globally
    matches('E487:', pcall_err(command, 'setglobal scrolloff=-1'))
    matches('E487:', pcall_err(command, 'setglobal sidescrolloff=-1'))

    eq(true, pcall(command, 'setlocal scrolloff=-1'))
    eq(true, pcall(command, 'setlocal sidescrolloff=-1'))
  end)

  it('set wmh/wh wmw/wiw checks', function()
    command('set winheight=2')
    matches('E591:', pcall_err(command, 'set winminheight=3'))

    command('set winwidth=2')
    matches('E592:', pcall_err(command, 'set winminwidth=3'))
  end)

  it('set maxcombine resets to 6', function()
    local function setto(value)
      command('setglobal maxcombine=' .. value)
      command('setlocal maxcombine=' .. value)
      api.nvim_set_option_value('maxcombine', value, {})
      eq(6, api.nvim_get_option_value('maxcombine', {}))
      eq('', eval('v:errmsg'))
    end
    setto(0)
    setto(1)
    setto(6)
    setto(7)
  end)
end)