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

Code before:

  local map = {
    KITTY_WINDOW_ID = 'kitty',
    ALACRITTY_SOCKET = 'alacritty',
    ALACRITTY_LOG = 'alacritty',
    WEZTERM_EXECUTABLE = 'wezterm',
    KONSOLE_VERSION = function()
      return 'konsole ' .. e.KONSOLE_VERSION
    end,
    VTE_VERSION = function()
      return 'vte ' .. e.VTE_VERSION
    end,
  }

  for key, val in pairs(map) do
    local env = e[key] --- @type string?
    if env then
      return type(val) == 'function' and val() or val
    end
  end

  return 'unknown'
end

---@param nvim_version string
local function check_stable_version(nvim_version)
  local latest_version = nil
  if vim.fn.executable('git') == 1 then
    local result = vim
      .system({
        'git',
        'ls-remote',
        '--tags',
        'https://github.com/neovim/neovim',
      }, { text = true })
      :wait()
    local stable_sha = result.stdout:match('(%x+)%s+refs/tags/stable\n')
    if stable_sha then
      latest_version = result.stdout:match(stable_sha .. '%s+refs/tags/v?(%d+%.%d+%.%d+)%^{}')
    end
  end

  if latest_version then
    local current_version = nvim_version:match('v(%d+%.%d+%.%d+)')
    if latest_version ~= current_version then
      vim.health.warn(
        string.format('Nvim %s is available (current: %s)', latest_version, current_version)
      )
    end
  end
end

Review comment (bug):
does this need to report `Cannot check for updates` (like `check_head_hash` already does)?

please always check failure cases, that is always expected.

Code after:

  local map = {
    KITTY_WINDOW_ID = 'kitty',
    ALACRITTY_SOCKET = 'alacritty',
    ALACRITTY_LOG = 'alacritty',
    WEZTERM_EXECUTABLE = 'wezterm',
    KONSOLE_VERSION = function()
      return 'konsole ' .. e.KONSOLE_VERSION
    end,
    VTE_VERSION = function()
      return 'vte ' .. e.VTE_VERSION
    end,
  }

  for key, val in pairs(map) do
    local env = e[key] --- @type string?
    if env then
      return type(val) == 'function' and val() or val
    end
  end

  return 'unknown'
end

---@param nvim_version string
local function check_stable_version(nvim_version)
  local result = vim
    .system(
      { 'git', 'ls-remote', '--tags', 'https://github.com/neovim/neovim' },
      { text = true, timeout = 5000 }
    )
    :wait()
  if result.code ~= 0 or not result.stdout or result.stdout == '' then
    return
  end
  local stable_sha = result.stdout:match('(%x+)%s+refs/tags/stable%^{}')
    or result.stdout:match('(%x+)%s+refs/tags/stable\n')
  if not stable_sha then
    return
  end
  local latest_version = result.stdout:match(stable_sha .. '%s+refs/tags/v?(%d+%.%d+%.%d+)%^{}')
  if not latest_version then
    return
  end
  local current_version = nvim_version:match('v?(%d+%.%d+%.%d+)')
  if not current_version then
    return
  end
  local current = vim.version.parse(current_version)
  local latest = vim.version.parse(latest_version)
  if current and latest and vim.version.lt(current, latest) then
Repository: neovim/neovim
File: runtime/lua/vim/health/health.lua (Lua)

Code before:
  for key, val in pairs(map) do
    local env = e[key] --- @type string?
    if env then
      return type(val) == 'function' and val() or val
    end
  end

  return 'unknown'
end

---@param nvim_version string
local function check_stable_version(nvim_version)
  local latest_version = nil
  if vim.fn.executable('git') == 1 then
    local result = vim
      .system({
        'git',
        'ls-remote',
        '--tags',
        'https://github.com/neovim/neovim',
      }, { text = true })
      :wait()
    local stable_sha = result.stdout:match('(%x+)%s+refs/tags/stable\n')
    if stable_sha then
      latest_version = result.stdout:match(stable_sha .. '%s+refs/tags/v?(%d+%.%d+%.%d+)%^{}')
    end
  end

  if latest_version then
    local current_version = nvim_version:match('v(%d+%.%d+%.%d+)')
    if latest_version ~= current_version then
      vim.health.warn(
        string.format('Nvim %s is available (current: %s)', latest_version, current_version)
      )
    end
  end
end

---@param commit string
local function check_head_hash(commit)
  local result = vim
    .system({ 'git', 'ls-remote', 'https://github.com/neovim/neovim', 'HEAD' }, { text = true })
    :wait()
  if result.code ~= 0 then
    return
  end
  local upstream = result.stdout:match('^(%x+)')
  if not upstream then
    return
  end
  if upstream:sub(1, #commit) ~= commit then

Review comment (suggestion):
```suggestion
    local latest_version = stable_sha and result.stdout:match(stable_sha .. '%s+refs/tags/v?(%d+%.%d+%.%d+)%^{}')
```

Code after:
  for key, val in pairs(map) do
    local env = e[key] --- @type string?
    if env then
      return type(val) == 'function' and val() or val
    end
  end

  return 'unknown'
end

---@param nvim_version string
local function check_stable_version(nvim_version)
  local result = vim
    .system(
      { 'git', 'ls-remote', '--tags', 'https://github.com/neovim/neovim' },
      { text = true, timeout = 5000 }
    )
    :wait()
  if result.code ~= 0 or not result.stdout or result.stdout == '' then
    return
  end
  local stable_sha = result.stdout:match('(%x+)%s+refs/tags/stable%^{}')
    or result.stdout:match('(%x+)%s+refs/tags/stable\n')
  if not stable_sha then
    return
  end
  local latest_version = result.stdout:match(stable_sha .. '%s+refs/tags/v?(%d+%.%d+%.%d+)%^{}')
  if not latest_version then
    return
  end
  local current_version = nvim_version:match('v?(%d+%.%d+%.%d+)')
  if not current_version then
    return
  end
  local current = vim.version.parse(current_version)
  local latest = vim.version.parse(latest_version)
  if current and latest and vim.version.lt(current, latest) then
    vim.health.warn(('Nvim %s is available (current: %s)'):format(latest_version, current_version))
  else
    vim.health.ok(('Up to date (%s)'):format(current_version))
  end
end

---@param commit string
local function check_head_hash(commit)
  local result = vim
    .system(
      { 'git', 'ls-remote', 'https://github.com/neovim/neovim', 'HEAD' },
      { text = true, timeout = 5000 }
    )
    :wait()
Repository: neovim/neovim
File: runtime/lua/vim/health/health.lua (Lua)

Code before:
      commit,
      os_string,
      terminal,
      term_env
    )
  )

  vim.api.nvim_create_autocmd('FileType', {
    pattern = 'checkhealth',
    once = true,
    callback = function(args)
      local buf = args.buf
      local win = vim.fn.bufwinid(buf)
      if win == -1 then
        return
      end
      local encoded_body = vim.uri_encode(body) --- @type string
      local issue_url = 'https://github.com/neovim/neovim/issues/new?type=Bug&body=' .. encoded_body

      _G.nvim_health_bugreport_open = function()
        vim.ui.open(issue_url)
      end
      vim.wo[win].winbar =
        '%#WarningMsg#%@v:lua.nvim_health_bugreport_open@Click to Create Bug Report on GitHub%X%*'

      vim.api.nvim_create_autocmd('BufWipeout', {
        buffer = buf,
        once = true,
        command = 'lua _G.nvim_health_bugreport_open = nil',
      })
    end,
  })
end

function M.check()
  check_sysinfo()
  check_config()
  check_runtime()
  check_performance()
  check_rplugin_manifest()
  check_terminal()
  check_tmux()
  check_external_tools()
end

return M


Review comment (suggestion):
 `BufDelete` raised for both bdelete and bwipeout, so why narrow this to `BufWipeout` ?  user or a plugin may delete the buffer without using bwipeout. although `bufhidden` might take precedence, not sure... but it's better to be more generic here.

Code after:
]],
      nvim_version,
      commit,
      os_string,
      terminal,
      term_env
    )
  )

  vim.api.nvim_create_autocmd('FileType', {
    pattern = 'checkhealth',
    once = true,
    callback = function(args)
      local buf = args.buf
      local win = vim.fn.bufwinid(buf)
      if win == -1 then
        return
      end
      local encoded_body = vim.uri_encode(body) --- @type string
      local issue_url = 'https://github.com/neovim/neovim/issues/new?type=Bug&body=' .. encoded_body

      _G.nvim_health_bugreport_open = function()
        vim.ui.open(issue_url)
      end
      vim.wo[win].winbar =
        '%#WarningMsg#%@v:lua.nvim_health_bugreport_open@Click to Create Bug Report on GitHub%X%*'

      vim.api.nvim_create_autocmd('BufDelete', {
        buffer = buf,
        once = true,
        command = 'lua _G.nvim_health_bugreport_open = nil',
      })
    end,
  })
end

function M.check()
  check_sysinfo()
  check_config()
  check_runtime()
  check_performance()
  check_rplugin_manifest()
  check_terminal()
  check_tmux()
  check_external_tools()
end

return M
Repository: neovim/neovim
File: src/nvim/version.c (C)

Code before:

  return (major < NVIM_VERSION_MAJOR
          || (major == NVIM_VERSION_MAJOR
              && (minor < NVIM_VERSION_MINOR
                  || (minor == NVIM_VERSION_MINOR
                      && patch <= NVIM_VERSION_PATCH))));
}

int highest_patch(void)
{
  // this relies on the highest patch number to be the first entry
  return included_patches[0];
}

/// Checks whether a Vim patch has been included.
///
/// @param n Patch number.
///
/// @return true if patch `n` has been included.
bool has_vim_patch(int n)
  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
  // Perform a binary search.
  int l = 0;
  int h = (int)(ARRAY_SIZE(included_patches)) - 1;
  for (;;) {
    const int m = (l + h) / 2;
    if (included_patches[m] == n) {
      return true;
    }
    if (l == h) {
      break;
    }
    if (included_patches[m] < n) {
      h = m;
    } else {
      l = m + 1;
    }
  }
  return false;
}

void ex_version(exarg_T *eap)
{
  // Ignore a ":version 9.99" command.
  if (*eap->arg == NUL) {
    if (!ui_has(kUIMessages)) {
      msg_putchar('\n');
    }
    list_version();
  }

Review comment (bug):
lint failure
```suggestion
  while (true) {
```

Code after:

  return (major < NVIM_VERSION_MAJOR
          || (major == NVIM_VERSION_MAJOR
              && (minor < NVIM_VERSION_MINOR
                  || (minor == NVIM_VERSION_MINOR
                      && patch <= NVIM_VERSION_PATCH))));
}

int highest_patch(void)
{
  // this relies on the highest patch number to be the first entry
  return included_patches[0];
}

/// Checks whether a Vim patch has been included.
///
/// @param n Patch number.
///
/// @return true if patch `n` has been included.
bool has_vim_patch(int n)
  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
  // Perform a binary search.
  int l = 0;
  int h = (int)(ARRAY_SIZE(included_patches)) - 1;
  while (true) {
    const int m = (l + h) / 2;
    if (included_patches[m] == n) {
      return true;
    }
    if (l == h) {
      break;
    }
    if (included_patches[m] < n) {
      h = m;
    } else {
      l = m + 1;
    }
  }
  return false;
}

void ex_version(exarg_T *eap)
{
  // Ignore a ":version 9.99" command.
  if (*eap->arg == NUL) {
    if (!ui_has(kUIMessages)) {
      msg_putchar('\n');
    }
    list_version();
  }
Repository: neovim/neovim
File: src/nvim/statusline.c (C)

Code before:

      if (tp == curtab) {
        cwp = curwin;
        wp = firstwin;
      } else {
        cwp = tp->tp_curwin;
        wp = tp->tp_firstwin;
      }

      if (tp->tp_topframe == topframe) {
        attr = win_hl_attr(cwp, HLF_TPS);
      }
      if (use_sep_chars && col > 0) {
        grid_line_put_schar(col++, schar_from_ascii('|'), attr);
      }

      if (tp->tp_topframe != topframe) {
        attr = win_hl_attr(cwp, HLF_TP);
      }

      grid_line_put_schar(col++, schar_from_ascii(' '), attr);

      bool modified = false;

      for (wincount = 0; wp != NULL; wp = wp->w_next, wincount++) {
        if (!wp->w_config.focusable || (wp->w_floating && wp->w_config.hide)) {
          wincount--;
        } else if (bufIsChanged(wp->w_buffer)) {
          modified = true;
        }
      }

      if (modified || wincount > 1) {
        if (wincount > 1) {
          int len = vim_snprintf(NameBuff, MAXPATHL, "%d", wincount);
          if (col + len >= Columns - 3) {
            break;
          }
          grid_line_puts(col, NameBuff, len,
                         hl_combine_attr(attr, win_hl_attr(cwp, HLF_T)));
          col += len;
        }
        if (modified) {
          grid_line_put_schar(col++, schar_from_ascii('+'), attr);
        }
        grid_line_put_schar(col++, schar_from_ascii(' '), attr);
      }

      int room = scol - col + tabwidth - 1;
      if (room > 0) {
        // Get buffer name in NameBuff[]

Review comment (suggestion):
```suggestion
        if (!wp->w_config.focusable || wp->w_config.hide) {
```

Please also change the `focusable` condition in `ex_docmd.c:ex_tabs()`, ref #27984.

Code after:

      if (tp == curtab) {
        cwp = curwin;
        wp = firstwin;
      } else {
        cwp = tp->tp_curwin;
        wp = tp->tp_firstwin;
      }

      if (tp->tp_topframe == topframe) {
        attr = win_hl_attr(cwp, HLF_TPS);
      }
      if (use_sep_chars && col > 0) {
        grid_line_put_schar(col++, schar_from_ascii('|'), attr);
      }

      if (tp->tp_topframe != topframe) {
        attr = win_hl_attr(cwp, HLF_TP);
      }

      grid_line_put_schar(col++, schar_from_ascii(' '), attr);

      bool modified = false;

      for (wincount = 0; wp != NULL; wp = wp->w_next, wincount++) {
        if (!wp->w_config.focusable || wp->w_config.hide) {
          wincount--;
        } else if (bufIsChanged(wp->w_buffer)) {
          modified = true;
        }
      }

      if (modified || wincount > 1) {
        if (wincount > 1) {
          int len = vim_snprintf(NameBuff, MAXPATHL, "%d", wincount);
          if (col + len >= Columns - 3) {
            break;
          }
          grid_line_puts(col, NameBuff, len,
                         hl_combine_attr(attr, win_hl_attr(cwp, HLF_T)));
          col += len;
        }
        if (modified) {
          grid_line_put_schar(col++, schar_from_ascii('+'), attr);
        }
        grid_line_put_schar(col++, schar_from_ascii(' '), attr);
      }

      int room = scol - col + tabwidth - 1;
      if (room > 0) {
        // Get buffer name in NameBuff[]
Repository: neovim/neovim
File: runtime/lua/vim/_editor.lua (Lua)

Code before:
    local displayed = vim._truncated_echo_once(msg)
    return displayed and msg or nil
  else
    vim.validate('name', name, 'string')
    vim.validate('alternative', alternative, 'string', true)
    vim.validate('version', version, 'string', true)
    vim.validate('plugin', plugin, 'string', true)

    local msg = ('%s is deprecated'):format(name)
    msg = alternative and ('%s, use %s instead.'):format(msg, alternative) or (msg .. '.')
    msg = ('%s\nFeature will be removed in %s %s'):format(msg, plugin, version)
    local displayed = vim.notify_once(msg, vim.log.levels.WARN)
    if displayed and backtrace ~= false then
      vim.notify(debug.traceback('', 2):sub(2), vim.log.levels.WARN)
    end
    return displayed and msg or nil
  end
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 vim._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 to ensure injections are processed
  parser:parse(true)
  -- Convert to 0-indexed range
  local range = { line1 - 1, 0, line2 - 1, -1 }
  local lang_tree = parser:language_for_range(range)
  return lang_tree:lang() == 'lua'
end

require('vim._options')

--- Remove at Nvim 1.0
---@deprecated
vim.loop = vim.uv

-- Deprecated. Remove at Nvim 2.0
vim.highlight = vim._defer_deprecated_module('vim.highlight', 'vim.hl')

return vim


Review comment (suggestion):
Using Lua for core code is the right instinct, but let's put this in `runtime/lua/vim/_core/util.lua` . (After https://github.com/neovim/neovim/pull/36870 , code in `_core/` will be available with `nvim -u NONE` )

Code after:
    local displayed = vim._truncated_echo_once(msg)
    return displayed and msg or nil
  else
    vim.validate('name', name, 'string')
    vim.validate('alternative', alternative, 'string', true)
    vim.validate('version', version, 'string', true)
    vim.validate('plugin', plugin, 'string', true)

    local msg = ('%s is deprecated'):format(name)
    msg = alternative and ('%s, use %s instead.'):format(msg, alternative) or (msg .. '.')
    msg = ('%s\nFeature will be removed in %s %s'):format(msg, plugin, version)
    local displayed = vim.notify_once(msg, vim.log.levels.WARN)
    if displayed and backtrace ~= false then
      vim.notify(debug.traceback('', 2):sub(2), vim.log.levels.WARN)
    end
    return displayed and msg or nil
  end
end

require('vim._options')

--- Remove at Nvim 1.0
---@deprecated
vim.loop = vim.uv

-- Deprecated. Remove at Nvim 2.0
vim.highlight = vim._defer_deprecated_module('vim.highlight', 'vim.hl')

return vim
Repository: neovim/neovim
File: test/functional/ex_cmds/source_spec.lua (Lua)

Code before:
    os.remove(test_file)
  end)

  describe('treesitter Lua codeblock detection', function()
    it('sources Lua codeblock in vimdoc file', function()
      insert([[
        *test.txt*  Test help file

        Example: >lua
          vim.g.test_vimdoc_lua = 42
        <]])
      feed('dd') -- remove trailing empty line from insert
      command('setlocal filetype=help')
      -- Select the Lua code line (line 4) and source it
      feed('4GV')
      feed_command(':source')
      eq(42, eval('g:test_vimdoc_lua'))
    end)

    it('sources Vimscript when not in a Lua codeblock', function()
      insert([[
        *test.txt*  Test help file

        Example: >vim
          let g:test_vimdoc_vim = 99
        <]])
      feed('dd')
      command('setlocal filetype=help')
      -- Select the Vimscript code line (line 4) and source it
      feed('4GV')
      feed_command(':source')
      eq(99, eval('g:test_vimdoc_vim'))
    end)

    it('falls back to Vimscript when no treesitter parser', function()
      insert([[let g:test_no_ts = 123]])
      -- Don't set a filetype with treesitter support
      command('setlocal filetype=')
      command('source')
      eq(123, eval('g:test_no_ts'))
    end)
  end)
end)

it('$HOME is not shortened in filepath in v:stacktrace from sourced file', function()
  local sep = n.get_pathsep()
  local xhome = table.concat({ vim.uv.cwd(), 'Xhome' }, sep)
  mkdir(xhome)
  clear({ env = { HOME = xhome } })
  finally(function()
    rmdir(xhome)

Review comment (suggestion):
this can be added to the above test, then just move the cursor. that also makes the test closer to real-world. and the `setlocal filetype=` test can be done here. so then instead of a `describe()` just one `it()`.

Code after:
    os.remove(test_file)
  end)

  it('sources Lua/Vimscript codeblocks based on treesitter injection', function()
    insert([[
      *test.txt*  Test help file

      Lua example: >lua
        vim.g.test_lua = 42
      <

      Vim example: >vim
        let g:test_vim = 99
      <]])
    command('setlocal filetype=help')

    -- Source Lua codeblock (line 4 contains the Lua code)
    command(':4source')
    eq(42, eval('g:test_lua'))

    -- Source Vimscript codeblock (line 8 contains the Vim code)
    command(':8source')
    eq(99, eval('g:test_vim'))

    -- Test fallback without treesitter
    command('enew')
    insert([[let g:test_no_ts = 123]])
    command('setlocal filetype=')
    command('source')
    eq(123, eval('g:test_no_ts'))
  end)
end)

it('$HOME is not shortened in filepath in v:stacktrace from sourced file', function()
  local sep = n.get_pathsep()
  local xhome = table.concat({ vim.uv.cwd(), 'Xhome' }, sep)
  mkdir(xhome)
  clear({ env = { HOME = xhome } })
  finally(function()
    rmdir(xhome)
  end)
  local filepath = table.concat({ xhome, 'Xstacktrace.vim' }, sep)
  local script = [[
    func Xfunc()
      throw 'Exception from Xfunc'
    endfunc
  ]]
  write_file(filepath, script)
  exec('source ' .. filepath)
  exec([[
    try
Repository: neovim/neovim
File: test/functional/ex_cmds/source_spec.lua (Lua)

Code before:
    ok, result = pcall(exec_capture, ':source ' .. test_file)
    eq(false, ok)
    eq(nil, result:find('E484'))
    os.remove(test_file)

    -- Doesn't throw for runtime error
    write_file(test_file, "error('Cause error anyway :D')")
    ok, result = pcall(exec_capture, ':source ' .. test_file)
    eq(false, ok)
    eq(nil, result:find('E484'))
    os.remove(test_file)
  end)

  describe('treesitter Lua codeblock detection', function()
    it('sources Lua codeblock in vimdoc file', function()
      insert([[
        *test.txt*  Test help file

        Example: >lua
          vim.g.test_vimdoc_lua = 42
        <]])
      feed('dd') -- remove trailing empty line from insert
      command('setlocal filetype=help')
      -- Select the Lua code line (line 4) and source it
      feed('4GV')
      feed_command(':source')
      eq(42, eval('g:test_vimdoc_lua'))
    end)

    it('sources Vimscript when not in a Lua codeblock', function()
      insert([[
        *test.txt*  Test help file

        Example: >vim
          let g:test_vimdoc_vim = 99
        <]])
      feed('dd')
      command('setlocal filetype=help')
      -- Select the Vimscript code line (line 4) and source it
      feed('4GV')
      feed_command(':source')
      eq(99, eval('g:test_vimdoc_vim'))
    end)

    it('falls back to Vimscript when no treesitter parser', function()
      insert([[let g:test_no_ts = 123]])
      -- Don't set a filetype with treesitter support
      command('setlocal filetype=')
      command('source')
      eq(123, eval('g:test_no_ts'))
    end)

Review comment (suggestion):
You can use range
```suggestion
      feed_command(':4source')
```

Code after:
    ok, result = pcall(exec_capture, ':source ' .. test_file)
    eq(false, ok)
    eq(nil, result:find('E484'))
    os.remove(test_file)

    -- Doesn't throw for runtime error
    write_file(test_file, "error('Cause error anyway :D')")
    ok, result = pcall(exec_capture, ':source ' .. test_file)
    eq(false, ok)
    eq(nil, result:find('E484'))
    os.remove(test_file)
  end)

  it('sources Lua/Vimscript codeblocks based on treesitter injection', function()
    insert([[
      *test.txt*  Test help file

      Lua example: >lua
        vim.g.test_lua = 42
      <

      Vim example: >vim
        let g:test_vim = 99
      <]])
    command('setlocal filetype=help')

    -- Source Lua codeblock (line 4 contains the Lua code)
    command(':4source')
    eq(42, eval('g:test_lua'))

    -- Source Vimscript codeblock (line 8 contains the Vim code)
    command(':8source')
    eq(99, eval('g:test_vim'))

    -- Test fallback without treesitter
    command('enew')
    insert([[let g:test_no_ts = 123]])
    command('setlocal filetype=')
    command('source')
    eq(123, eval('g:test_no_ts'))
  end)
end)

it('$HOME is not shortened in filepath in v:stacktrace from sourced file', function()
  local sep = n.get_pathsep()
  local xhome = table.concat({ vim.uv.cwd(), 'Xhome' }, sep)
  mkdir(xhome)
  clear({ env = { HOME = xhome } })
  finally(function()
    rmdir(xhome)
  end)