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

Code before:
    'XTERM_VERSION',
    'VTE_VERSION',
    'TERM_PROGRAM',
    'COLORTERM',
    'SSH_TTY',
  }) do
    if vim.env[env_var] then
      health.info(string.format('$%s="%s"', env_var, vim.env[env_var]))
    end
  end
end

local function check_external_tools()
  health.start('External Tools')

  if vim.fn.executable('rg') == 1 then
    local rg = vim.fn.exepath('rg')
    local cmd = 'rg -V'
    local out = vim.fn.system(vim.fn.split(cmd))
    health.ok(('%s (%s)'):format(vim.trim(out), rg))
  else
    health.warn('ripgrep not available')
  end
  if vim.fn.executable('curl') == 1 then
    local curl_path = vim.fn.exepath('curl')
    local curl_out = vim.fn.system({ curl_path, '--version' })
    local curl_version = vim.fn.matchstr(curl_out, [[^curl[^\n]*]])

    if vim.v.shell_error == 0 then
      local lines = {}
      table.insert(lines, string.format('%s (%s)', curl_version, curl_path))

      for line in vim.gsplit(curl_out, '\n', { plain = true }) do
        if line ~= '' and not line:match('^curl') then
          table.insert(lines, line)
        end
      end

      -- Add subtitle only if any env var is present
      local added_env_header = false
      for _, var in ipairs({
        'curl_ca_bundle',
        'curl_home',
        'curl_ssl_backend',
        'ssl_cert_dir',
        'ssl_cert_file',
        'https_proxy',
        'http_proxy',
        'all_proxy',
        'no_proxy',
      }) do

Review comment (suggestion):
use `vim.system():wait()`. that avoids fragile things like `vim.v.shell_error` :)

Code after:
    'XTERM_VERSION',
    'VTE_VERSION',
    'TERM_PROGRAM',
    'COLORTERM',
    'SSH_TTY',
  }) do
    if vim.env[env_var] then
      health.info(string.format('$%s="%s"', env_var, vim.env[env_var]))
    end
  end
end

local function check_external_tools()
  health.start('External Tools')

  if vim.fn.executable('rg') == 1 then
    local rg_path = vim.fn.exepath('rg')
    local rg_job = vim.system({ rg_path, '-V' }):wait()
    if rg_job.code == 0 then
      health.ok(('%s (%s)'):format(vim.trim(rg_job.stdout), rg_path))
    else
      health.warn('found `rg` but failed to run `rg -V`', { rg_job.stderr })
    end
  else
    health.warn('ripgrep not available')
  end

  -- `vim.pack` requires `git` executable with version at least 2.36
  if vim.fn.executable('git') == 1 then
    local git = vim.fn.exepath('git')
    local out = vim.system({ 'git', 'version' }, {}):wait().stdout or ''
    local version = vim.version.parse(out)
    if version < vim.version.parse('2.36') then
      local msg = string.format(
        'git is available (%s), but needs at least version 2.36 (not %s) to work with `vim.pack`',
        git,
        tostring(version)
      )
      health.warn(msg)
    else
      health.ok(('%s (%s)'):format(vim.trim(out), git))
    end
  else
    health.warn('git not available (required by `vim.pack`)')
  end

  if vim.fn.executable('curl') == 1 then
    local curl_path = vim.fn.exepath('curl')
    local curl_job = vim.system({ curl_path, '--version' }):wait()

    if curl_job.code == 0 then
Repository: neovim/neovim
File: runtime/lua/vim/net.lua (Lua)

Code before:
  table.insert(args, url)

  local job_result = {}

  local function on_exit(res)
    local err_msg = nil
    local response_obj = nil

    if res.code ~= 0 then
      err_msg = (res.stderr ~= '' and res.stderr)
        or string.format('Request failed with exit code %d', res.code)
    else
      response_obj = {
        text = opts.outpath and true or res.stdout,
      }
    end

    job_result.err = err_msg
    job_result.response = response_obj

    if on_response then
      on_response(job_result.err, job_result.response)
    end
  end

  local job = vim.system(args, { text = true }, on_exit)

  if not on_response then
    job:wait()
    return job_result.response, job_result.err
  else
    -- TODO Response Handler for asynchronous requests
    return true, nil
  end
end

return M


Review comment (suggestion):
Is `text=true` always valid? What happens if a `.jpg` url is requested ?

Maybe we should drop `text=true` here, and return `{body: string}` and let the caller decide how to treat `body` for now. (Note: Lua strings can have binary data.)

Code after:
local M = {}

--- Makes an HTTP GET request to the given URL (asynchronous).
---
--- This function operates in one mode:
---   - Asynchronous (non-blocking): Returns immediately and passes the response object to the
---   provided `on_response` handler on completetion.
---
--- @param url string The URL for the request.
--- @param opts? table Optional parameters:
---   - `verbose` (boolean|nil): Enables verbose output.
---   - `retry`   (integer|nil): Number of retries on transient failures (default: 3).
---   - `outpath`  (string|nil): File path to save the response body to. If set, the `body` value in the Response Object will be `true` instead of the response body.
--- @param on_response fun(err?: string, response?: { body: string|boolean }) Callback invoked on request
--- completetion. The `body` field in the response object contains the raw response data (text or binary).
--- Called with (err, nil) on failure, or (nil, { body = string|boolean }) on success.
function M.request(url, opts, on_response)
  vim.validate({
    url = { url, 'string' },
    opts = { opts, 'table', true },
    on_response = { on_response, 'function' },
  })

  opts = opts or {}
  local retry = opts.retry or 3

  -- Build curl command
  local args = { 'curl' }
  if opts.verbose then
    table.insert(args, '--verbose')
  else
    vim.list_extend(args, { '--silent', '--show-error', '--fail' })
  end
  vim.list_extend(args, { '--location', '--retry', tostring(retry) })

  if opts.outpath then
    vim.list_extend(args, { '--output', opts.outpath })
  end

  table.insert(args, url)

  local function on_exit(res)
    local err_msg = nil
    local response = nil

    if res.code ~= 0 then
      err_msg = (res.stderr ~= '' and res.stderr)
        or string.format('Request failed with exit code %d', res.code)
    else
      response = {
        body = opts.outpath and true or res.stdout,
      }
    end

    if on_response then
      on_response(err_msg, response)
    end
  end

  vim.system(args, {}, on_exit)
end

return M
Repository: neovim/neovim
File: test/functional/ui/messages_spec.lua (Lua)

Code before:
      messages = {
        {
          content = { { '  shiftwidth=8\n  tabstop=8\n  softtabstop=0' } },
          kind = 'list_cmd',
        },
      },
    })
  end)

  it('clears showmode after insert_expand mode', function()
    feed('i<C-N>')
    screen:expect({
      grid = [[
        ^                         |
        {1:~                        }|*4
      ]],
      showmode = { { '-- Keyword completion (^N^P) ', 5, 11 }, { 'Pattern not found', 9, 6 } },
    })
    feed('<Esc>')
    screen:expect([[
      ^                         |
      {1:~                        }|*4
    ]])
  end)

  it('sets append', function()
    command('echo "foo" | echon " bar" | echon " baz"')
    screen:expect({
      grid = [[
        ^                         |
        {1:~                        }|*4
      ]],
      messages = {
        { content = { { 'foo' } }, kind = 'echo' },
        { content = { { ' bar' } }, kind = 'echo', append = true },
        { content = { { ' baz' } }, kind = 'echo', append = true },
        {
          content = { { 'Press ENTER or type command to continue', 6, 18 } },
          kind = 'return_prompt',
        },
      },
    })
  end)
end)

describe('ui/builtin messages', function()
  local screen
  before_each(function()
    clear()
    screen = Screen.new(60, 7, { rgb = true, ext_popupmenu = true })
    screen:add_extra_attr_ids {

Review comment (suggestion):
```suggestion
  it(':echon sets append', function()
```

Code after:
      messages = {
        {
          content = { { '  shiftwidth=8\n  tabstop=8\n  softtabstop=0' } },
          kind = 'list_cmd',
        },
      },
    })
  end)

  it('clears showmode after insert_expand mode', function()
    feed('i<C-N>')
    screen:expect({
      grid = [[
        ^                         |
        {1:~                        }|*4
      ]],
      showmode = { { '-- Keyword completion (^N^P) ', 5, 11 }, { 'Pattern not found', 9, 6 } },
    })
    feed('<Esc>')
    screen:expect([[
      ^                         |
      {1:~                        }|*4
    ]])
  end)

  it(':echon sets append', function()
    command('echo "foo" | echon " bar" | echon " baz"')
    screen:expect({
      grid = [[
        ^                         |
        {1:~                        }|*4
      ]],
      messages = {
        { content = { { 'foo' } }, kind = 'echo' },
        { content = { { ' bar' } }, kind = 'echo', append = true },
        { content = { { ' baz' } }, kind = 'echo', append = true },
        {
          content = { { 'Press ENTER or type command to continue', 6, 18 } },
          kind = 'return_prompt',
        },
      },
    })
  end)
end)

describe('ui/builtin messages', function()
  local screen
  before_each(function()
    clear()
    screen = Screen.new(60, 7, { rgb = true, ext_popupmenu = true })
    screen:add_extra_attr_ids {
Repository: neovim/neovim
File: src/nvim/insexpand.c (C)

Code before:
    if (is_nearest_active() && in_curbuf) {
      score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
      if (score < 0) {
        score = -score;
      }
      score++;
    }

    if (ins_compl_add_infercase(ptr, len, p_ic,
                                in_curbuf ? NULL : st->ins_buf->b_sfname,
                                0, cont_s_ipos, score) != NOTDONE) {
      if (in_collect && score == compl_first_match->cp_next->cp_score) {
        compl_num_bests++;
      }
      found_new_match = OK;
      break;
    }
  }
  p_scs = save_p_scs;
  p_ws = save_p_ws;

  return found_new_match;
}

// Get completion matches from register contents.
// Extracts words from all available registers and adds them to the completion list.
static void get_register_completion(void)
{
  int dir = compl_direction;

  for (int i = 0; i < NUM_REGISTERS; i++) {
    int regname = get_register_name(i);

    if (regname == '_') {
      continue;
    }

    if (!valid_yank_reg(regname, false)) {
      continue;
    }

    yankreg_T *reg = copy_register(regname);
    if (reg == NULL || reg->y_array == NULL) {
      continue;
    }

    for (size_t j = 0; j < reg->y_size; j++) {
      char *str = reg->y_array[j].data;
      if (str == NULL) {
        continue;
      }

Review comment (refactor):
```suggestion
/// Get completion matches from register contents.
/// Extracts words from all available registers and adds them to the completion list.
```

Code after:

    if (is_nearest_active() && in_curbuf) {
      score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
      if (score < 0) {
        score = -score;
      }
      score++;
    }

    if (ins_compl_add_infercase(ptr, len, p_ic,
                                in_curbuf ? NULL : st->ins_buf->b_sfname,
                                0, cont_s_ipos, score) != NOTDONE) {
      if (in_collect && score == compl_first_match->cp_next->cp_score) {
        compl_num_bests++;
      }
      found_new_match = OK;
      break;
    }
  }
  p_scs = save_p_scs;
  p_ws = save_p_ws;

  return found_new_match;
}

/// Get completion matches from register contents.
/// Extracts words from all available registers and adds them to the completion list.
static void get_register_completion(void)
{
  Direction dir = compl_direction;

  for (int i = 0; i < NUM_REGISTERS; i++) {
    int regname = get_register_name(i);
    // Skip invalid or black hole register
    if (!valid_yank_reg(regname, false) || regname == '_') {
      continue;
    }

    yankreg_T *reg = copy_register(regname);

    if (reg->y_array == NULL || reg->y_size == 0) {
      free_register(reg);
      xfree(reg);
      continue;
    }

    for (size_t j = 0; j < reg->y_size; j++) {
      char *str = reg->y_array[j].data;
      if (str == NULL) {
        continue;
      }
Repository: neovim/neovim
File: src/nvim/insexpand.c (C)

Code before:
      continue;
    }

    for (size_t j = 0; j < reg->y_size; j++) {
      char *str = reg->y_array[j].data;
      if (str == NULL) {
        continue;
      }

      char *p = str;
      while (*p != NUL) {
        p = find_word_start(p);
        if (*p == NUL) {
          break;
        }

        char *word_end = find_word_end(p);
        int len = (int)(word_end - p);

        if (len > 0 && (!compl_orig_text.data
                        || (p_ic ? STRNICMP(p, compl_orig_text.data,
                                            compl_orig_text.size) == 0
                                 : strncmp(p, compl_orig_text.data,
                                           compl_orig_text.size) == 0))) {
          if (ins_compl_add_infercase(p, len, p_ic, NULL,
                                      dir, FALSE, 0) == OK) {
            dir = FORWARD;
          }
        }
        p = word_end;
      }
    }

    free_register(reg);
    xfree(reg);
  }
}

/// get the next set of completion matches for "type".
/// @return  true if a new match is found, otherwise false.
static bool get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
{
  int found_new_match = FAIL;

  switch (type) {
  case -1:
    break;
  case CTRL_X_PATH_PATTERNS:
  case CTRL_X_PATH_DEFINES:
    get_next_include_file_completion(type);
    break;

Review comment (suggestion):
```suggestion
                                      dir, false, 0) == OK) {
```

Code after:
      continue;
    }

    for (size_t j = 0; j < reg->y_size; j++) {
      char *str = reg->y_array[j].data;
      if (str == NULL) {
        continue;
      }

      char *p = str;
      while (*p != NUL) {
        p = find_word_start(p);
        if (*p == NUL) {
          break;
        }

        char *word_end = find_word_end(p);
        int len = (int)(word_end - p);

        // Add the word to the completion list
        if (len > 0 && (!compl_orig_text.data
                        || (p_ic ? STRNICMP(p, compl_orig_text.data,
                                            compl_orig_text.size) == 0
                                 : strncmp(p, compl_orig_text.data,
                                           compl_orig_text.size) == 0))) {
          if (ins_compl_add_infercase(p, len, p_ic, NULL,
                                      dir, false, 0) == OK) {
            dir = FORWARD;
          }
        }
        p = word_end;
      }
    }

    free_register(reg);
    xfree(reg);
  }
}

/// get the next set of completion matches for "type".
/// @return  true if a new match is found, otherwise false.
static bool get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
{
  int found_new_match = FAIL;

  switch (type) {
  case -1:
    break;
  case CTRL_X_PATH_PATTERNS:
  case CTRL_X_PATH_DEFINES:
    get_next_include_file_completion(type);
Repository: neovim/neovim
File: src/nvim/insexpand.c (C)

Code before:
        score = -score;
      }
      score++;
    }

    if (ins_compl_add_infercase(ptr, len, p_ic,
                                in_curbuf ? NULL : st->ins_buf->b_sfname,
                                0, cont_s_ipos, score) != NOTDONE) {
      if (in_collect && score == compl_first_match->cp_next->cp_score) {
        compl_num_bests++;
      }
      found_new_match = OK;
      break;
    }
  }
  p_scs = save_p_scs;
  p_ws = save_p_ws;

  return found_new_match;
}

/// Get completion matches from register contents.
/// Extracts words from all available registers and adds them to the completion list.
static void get_register_completion(void)
{
  int dir = compl_direction;

  for (int i = 0; i < NUM_REGISTERS; i++) {
    int regname = get_register_name(i);

    if (regname == '_') {
      continue;
    }

    // Skip invalid or black hole register
    if (!valid_yank_reg(regname, false) || regname == '_') {
      continue;
    }

    yankreg_T *reg = copy_register(regname);
    if (reg == NULL) {
      continue;
    }

    if (reg->y_array == NULL || reg->y_size == 0) {
      free_register(reg);
      xfree(reg);
      continue;
    }

    for (size_t j = 0; j < reg->y_size; j++) {

Review comment (suggestion):
```suggestion
  Direction dir = compl_direction;
```

Code after:
        score = -score;
      }
      score++;
    }

    if (ins_compl_add_infercase(ptr, len, p_ic,
                                in_curbuf ? NULL : st->ins_buf->b_sfname,
                                0, cont_s_ipos, score) != NOTDONE) {
      if (in_collect && score == compl_first_match->cp_next->cp_score) {
        compl_num_bests++;
      }
      found_new_match = OK;
      break;
    }
  }
  p_scs = save_p_scs;
  p_ws = save_p_ws;

  return found_new_match;
}

/// Get completion matches from register contents.
/// Extracts words from all available registers and adds them to the completion list.
static void get_register_completion(void)
{
  Direction dir = compl_direction;

  for (int i = 0; i < NUM_REGISTERS; i++) {
    int regname = get_register_name(i);
    // Skip invalid or black hole register
    if (!valid_yank_reg(regname, false) || regname == '_') {
      continue;
    }

    yankreg_T *reg = copy_register(regname);

    if (reg->y_array == NULL || reg->y_size == 0) {
      free_register(reg);
      xfree(reg);
      continue;
    }

    for (size_t j = 0; j < reg->y_size; j++) {
      char *str = reg->y_array[j].data;
      if (str == NULL) {
        continue;
      }

      char *p = str;
      while (*p != NUL) {
        p = find_word_start(p);
Repository: neovim/neovim
File: test/functional/plugin/lsp_spec.lua (Lua)

Code before:
      end)

      eq(
        'Error here!',
        exec_lua(function()
          return vim.diagnostic.get()[1].message
        end)
      )
    end)

    it('ignores unchanged diagnostic reports', function()
      setup_server('unchanged')

      eq(
        0,
        exec_lua(function()
          -- Wait for diagnostics to be processed.
          vim.uv.sleep(50)

          return #vim.diagnostic.get()
        end)
      )
    end)
  end)
end)


Review comment (suggestion):
It doesn't feel right to use `sleep` but if I don't then this test might just become a no-op since diagnostics are likely to be empty before the workspace request is processed.

Code after:

      retry(nil, nil, function()
        eq(
          1,
          exec_lua(function()
            return #vim.diagnostic.get()
          end)
        )
      end)

      eq(
        'Error here',
        exec_lua(function()
          return vim.diagnostic.get()[1].message
        end)
      )
    end)

    it('ignores unchanged diagnostic reports', function()
      setup_server({ make_report('unchanged', '', 1) })

      eq(
        0,
        exec_lua(function()
          -- Wait for diagnostics to be processed.
          vim.uv.sleep(50)

          return #vim.diagnostic.get()
        end)
      )
    end)

    it('favors document diagnostics over workspace diagnostics', function()
      local client_id = setup_server({ make_report('full', 'Workspace error', 1) })
      local diagnostic_bufnr = exec_lua(function()
        return vim.uri_to_bufnr(fake_uri)
      end)

      exec_lua(function()
        vim.lsp.diagnostic.on_diagnostic(nil, {
          kind = 'full',
          items = {
            {
              range = {
                start = { line = 2, character = 2 },
                ['end'] = { line = 2, character = 2 },
              },
              message = 'Document error',
              severity = 1,
            },
          },
Repository: neovim/neovim
File: src/nvim/os/os_win_console.c (C)

Code before:

void os_replace_stdin_to_conin(void)
{
  close(STDIN_FILENO);
  const int conin_fd = os_open_conin_fd();
  assert(conin_fd == STDIN_FILENO);
}

void os_replace_stdout_and_stderr_to_conout(void)
{
  const HANDLE conout_handle =
    CreateFile("CONOUT$",
               GENERIC_READ | GENERIC_WRITE,
               FILE_SHARE_READ | FILE_SHARE_WRITE,
               (LPSECURITY_ATTRIBUTES)NULL,
               OPEN_EXISTING, 0, (HANDLE)NULL);
  assert(conout_handle != INVALID_HANDLE_VALUE);
  close(STDOUT_FILENO);
  const int conout_fd = _open_osfhandle((intptr_t)conout_handle, 0);
  assert(conout_fd == STDOUT_FILENO);
  close(STDERR_FILENO);
  const int conerr_fd = _open_osfhandle((intptr_t)conout_handle, 0);
  assert(conerr_fd == STDERR_FILENO);
}

/// resets Windows console icon if we got an original one on startup
void os_icon_reset(void) {
  if (hWnd == NULL) {
    return;
  }

  if (hOrigIconSmall) {
    SendMessage(hWnd, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hOrigIconSmall);
  }
  if (hOrigIcon) {
    SendMessage(hWnd, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hOrigIcon);
  }
}

/// Sets Nvim logo as Windows console icon.
///
/// Saves the original icon so it can be restored at exit.
void os_icon_init(void)
{
  if ((hWnd = GetConsoleWindow()) == NULL) {
    return;
  }

  char *vimruntime = os_getenv("VIMRUNTIME");
  if (vimruntime != NULL) {
    snprintf(NameBuff, MAXPATHL, "%s/neovim.ico", vimruntime);

Review comment (suggestion):
```suggestion
/// Resets Windows console icon if we got an original one on startup.
```

Code after:

void os_replace_stdin_to_conin(void)
{
  close(STDIN_FILENO);
  const int conin_fd = os_open_conin_fd();
  assert(conin_fd == STDIN_FILENO);
}

void os_replace_stdout_and_stderr_to_conout(void)
{
  const HANDLE conout_handle =
    CreateFile("CONOUT$",
               GENERIC_READ | GENERIC_WRITE,
               FILE_SHARE_READ | FILE_SHARE_WRITE,
               (LPSECURITY_ATTRIBUTES)NULL,
               OPEN_EXISTING, 0, (HANDLE)NULL);
  assert(conout_handle != INVALID_HANDLE_VALUE);
  close(STDOUT_FILENO);
  const int conout_fd = _open_osfhandle((intptr_t)conout_handle, 0);
  assert(conout_fd == STDOUT_FILENO);
  close(STDERR_FILENO);
  const int conerr_fd = _open_osfhandle((intptr_t)conout_handle, 0);
  assert(conerr_fd == STDERR_FILENO);
}

/// Resets Windows console icon if we got an original one on startup.
void os_icon_reset(void) {
  if (hWnd == NULL) {
    return;
  }

  if (hOrigIconSmall) {
    SendMessage(hWnd, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hOrigIconSmall);
  }
  if (hOrigIcon) {
    SendMessage(hWnd, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hOrigIcon);
  }
}

/// Sets Nvim logo as Windows console icon.
///
/// Saves the original icon so it can be restored at exit.
void os_icon_init(void)
{
  if ((hWnd = GetConsoleWindow()) == NULL) {
    return;
  }

  char *vimruntime = os_getenv("VIMRUNTIME");
  if (vimruntime != NULL) {
    snprintf(NameBuff, MAXPATHL, "%s/neovim.ico", vimruntime);