ronantakizawa/codereview-bench huggingface dataset:
Repository: neovim/neovim
File: src/nvim/main.c (C)

Code before:
    vim_snprintf(IObuff, IOSIZE, "ta %s", tagname);
    do_cmdline_cmd(IObuff);
    TIME_MSG("jumping to tag");

    // If the user doesn't want to edit the file then we quit here.
    if (swap_exists_did_quit) {
      ui_call_error_exit(1);
      getout(1);
    }
  }
}

/// Read text from stdin.
static void read_stdin(void)
{
  // When getting the ATTENTION prompt here, use a dialog.
  swap_exists_action = SEA_DIALOG;
  no_wait_return = true;
  bool save_msg_didany = msg_didany;
  buf_T *prev_buf = NULL;

  if (curbuf->b_ffname) {
    // curbuf is already opened for a file, create a new buffer for stdin #35269
    buf_T *newbuf = buflist_new(NULL, NULL, 0, 0);
    if (newbuf == NULL) {
      ELOG("Unable to allocate buffer for stdin");
      return;
    }

    // remember the current buffer so we can go back to it
    prev_buf = curbuf;
    set_curbuf(newbuf, 0, false);
  }

  set_buflisted(true);
  // Create memfile and read from stdin.
  open_buffer(true, NULL, 0);
  if (buf_is_empty(curbuf)) {
    // stdin was empty so we should wipe it (e.g. "echo file1 | xargs nvim"). #8561
    // stdin buffer may be first or last #35269
    if ((curbuf->b_next != NULL) || (curbuf->b_prev != NULL)) {
      do_bufdel(DOBUF_WIPE, NULL, 0, 0, 0, 1);
    }
  }

  // we had to switch buffers to load stdin, switch back
  if (prev_buf) {
    set_curbuf(prev_buf, 0, false);
  }

  no_wait_return = false;

Review comment (bug):
based on other parts of main.c it looks like we can use `semsg` here, which helps avoids confused users. though this should "never" happen in practice.
```suggestion
      semsg("Failed to create buffer for stdin");
```

Code after:
    vim_snprintf(IObuff, IOSIZE, "ta %s", tagname);
    do_cmdline_cmd(IObuff);
    TIME_MSG("jumping to tag");

    // If the user doesn't want to edit the file then we quit here.
    if (swap_exists_did_quit) {
      ui_call_error_exit(1);
      getout(1);
    }
  }
}

/// Read text from stdin.
static void read_stdin(void)
{
  // When getting the ATTENTION prompt here, use a dialog.
  swap_exists_action = SEA_DIALOG;
  no_wait_return = true;
  bool save_msg_didany = msg_didany;
  buf_T *prev_buf = NULL;

  if (curbuf->b_ffname) {
    // curbuf is already opened for a file, create a new buffer for stdin. #35269
    buf_T *newbuf = buflist_new(NULL, NULL, 0, 0);
    if (newbuf == NULL) {
      semsg("Failed to create buffer for stdin");
      return;
    }

    // remember the current buffer so we can go back to it
    prev_buf = curbuf;
    set_curbuf(newbuf, 0, false);
  }

  set_buflisted(true);
  // Create memfile and read from stdin.
  open_buffer(true, NULL, 0);
  if (buf_is_empty(curbuf)) {
    // stdin was empty so we should wipe it (e.g. "echo file1 | xargs nvim"). #8561
    // stdin buffer may be first or last ("echo foo | nvim file1 -"). #35269
    if ((curbuf->b_next != NULL) || (curbuf->b_prev != NULL)) {
      do_bufdel(DOBUF_WIPE, NULL, 0, 0, 0, 1);
    }
  }

  // we had to switch buffers to load stdin, switch back
  if (prev_buf) {
    set_curbuf(prev_buf, 0, false);
  }

  no_wait_return = false;
Repository: neovim/neovim
File: src/nvim/main.c (C)

Code before:
  if (tagname != NULL) {
    swap_exists_did_quit = false;

    vim_snprintf(IObuff, IOSIZE, "ta %s", tagname);
    do_cmdline_cmd(IObuff);
    TIME_MSG("jumping to tag");

    // If the user doesn't want to edit the file then we quit here.
    if (swap_exists_did_quit) {
      ui_call_error_exit(1);
      getout(1);
    }
  }
}

/// Read text from stdin.
static void read_stdin(void)
{
  // When getting the ATTENTION prompt here, use a dialog.
  swap_exists_action = SEA_DIALOG;
  no_wait_return = true;
  bool save_msg_didany = msg_didany;
  buf_T *prev_buf = NULL;

  if (curbuf->b_ffname) {
    // curbuf is already opened for a file, create a new buffer for stdin #35269
    buf_T *newbuf = buflist_new(NULL, NULL, 0, 0);
    if (newbuf == NULL) {
      ELOG("Unable to allocate buffer for stdin");
      return;
    }

    // remember the current buffer so we can go back to it
    prev_buf = curbuf;
    set_curbuf(newbuf, 0, false);
  }

  set_buflisted(true);
  // Create memfile and read from stdin.
  open_buffer(true, NULL, 0);
  if (buf_is_empty(curbuf)) {
    // stdin was empty so we should wipe it (e.g. "echo file1 | xargs nvim"). #8561
    // stdin buffer may be first or last #35269
    if ((curbuf->b_next != NULL) || (curbuf->b_prev != NULL)) {
      do_bufdel(DOBUF_WIPE, NULL, 0, 0, 0, 1);
    }
  }

  // we had to switch buffers to load stdin, switch back
  if (prev_buf) {
    set_curbuf(prev_buf, 0, false);

Review comment (suggestion):
```suggestion
    // curbuf is already opened for a file, create a new buffer for stdin. #35269
```

Code after:
  if (tagname != NULL) {
    swap_exists_did_quit = false;

    vim_snprintf(IObuff, IOSIZE, "ta %s", tagname);
    do_cmdline_cmd(IObuff);
    TIME_MSG("jumping to tag");

    // If the user doesn't want to edit the file then we quit here.
    if (swap_exists_did_quit) {
      ui_call_error_exit(1);
      getout(1);
    }
  }
}

/// Read text from stdin.
static void read_stdin(void)
{
  // When getting the ATTENTION prompt here, use a dialog.
  swap_exists_action = SEA_DIALOG;
  no_wait_return = true;
  bool save_msg_didany = msg_didany;
  buf_T *prev_buf = NULL;

  if (curbuf->b_ffname) {
    // curbuf is already opened for a file, create a new buffer for stdin. #35269
    buf_T *newbuf = buflist_new(NULL, NULL, 0, 0);
    if (newbuf == NULL) {
      semsg("Failed to create buffer for stdin");
      return;
    }

    // remember the current buffer so we can go back to it
    prev_buf = curbuf;
    set_curbuf(newbuf, 0, false);
  }

  set_buflisted(true);
  // Create memfile and read from stdin.
  open_buffer(true, NULL, 0);
  if (buf_is_empty(curbuf)) {
    // stdin was empty so we should wipe it (e.g. "echo file1 | xargs nvim"). #8561
    // stdin buffer may be first or last ("echo foo | nvim file1 -"). #35269
    if ((curbuf->b_next != NULL) || (curbuf->b_prev != NULL)) {
      do_bufdel(DOBUF_WIPE, NULL, 0, 0, 0, 1);
    }
  }

  // we had to switch buffers to load stdin, switch back
  if (prev_buf) {
    set_curbuf(prev_buf, 0, false);
Repository: neovim/neovim
File: test/functional/core/startup_spec.lua (Lua)

Code before:
        'test/functional/fixtures/shell-test.c',
      }, { 'ohyeah', '' })
    )
  end)

  it('if stdin is empty: selects buffer 2, deletes buffer 1 #8561', function()
    eq(
      '\r\n  2 %a   "file1"                        line 0\r\n  3      "file2"                        line 0',
      fn.system({
        nvim_prog,
        '-n',
        '-u',
        'NONE',
        '-i',
        'NONE',
        '--headless',
        '+ls!',
        '+qall!',
        '-',
        'file1',
        'file2',
      }, { '' })
    )
  end)

  it('if stdin and file arguments, keep first file even if empty #35269', function()
    eq(
      '\r\n  1 %a   "file1"                        line 0\r\n  2 #h   "file2"                        line 1',
      fn.system({
        nvim_prog,
        '-n',
        '-u',
        'NONE',
        '-i',
        'NONE',
        '--headless',
        '+ls!',
        '+qall!',
        'file1',
        'file2',
        '-',
      }, { '' })
    )
  end)

  it('stdin with -es/-Es #7679', function()
    local input = { 'append', 'line1', 'line2', '.', '%print', '' }
    local inputstr = table.concat(input, '\n')

    --
    -- -Es: read stdin as text

Review comment (suggestion):

```suggestion
  it('file args + empty stdin #35269', function()
```

Code after:
        'test/functional/fixtures/shell-test.c',
      }, { 'ohyeah', '' })
    )
  end)

  it('if stdin is empty: selects buffer 2, deletes buffer 1 #8561', function()
    eq(
      '\r\n  2 %a   "file1"                        line 0\r\n  3      "file2"                        line 0',
      fn.system({
        nvim_prog,
        '-n',
        '-u',
        'NONE',
        '-i',
        'NONE',
        '--headless',
        '+ls!',
        '+qall!',
        '-',
        'file1',
        'file2',
      }, { '' })
    )
  end)

  it('if stdin is empty and - is last: selects buffer 1, deletes buffer 3 #35269', function()
    eq(
      '\r\n  1 %a   "file1"                        line 0\r\n  2 #h   "file2"                        line 1',
      fn.system({
        nvim_prog,
        '-n',
        '-u',
        'NONE',
        '-i',
        'NONE',
        '--headless',
        '+ls!',
        '+qall!',
        'file1',
        'file2',
        '-',
      }, { '' })
    )
  end)

  it('stdin with -es/-Es #7679', function()
    local input = { 'append', 'line1', 'line2', '.', '%print', '' }
    local inputstr = table.concat(input, '\n')

    --
    -- -Es: read stdin as text
Repository: neovim/neovim
File: src/nvim/main.c (C)

Code before:

/// Read text from stdin.
static void read_stdin(void)
{
  // When getting the ATTENTION prompt here, use a dialog.
  swap_exists_action = SEA_DIALOG;
  no_wait_return = true;
  bool save_msg_didany = msg_didany;
  buf_T *prev_buf = NULL;
  buf_T *newbuf = NULL;

  if (curbuf->b_ffname) {
    // curbuf is already opened for a file, create a new buffer for stdin. #35269
    newbuf = buflist_new(NULL, NULL, 0, 0);
    if (newbuf == NULL) {
      semsg("Failed to create buffer for stdin");
      return;
    }

    // remember the current buffer so we can go back to it
    prev_buf = curbuf;
    set_curbuf(newbuf, 0, false);
  }

  set_buflisted(true);

  if (newbuf) {
    readfile(NULL, NULL, 0, 0, (linenr_T)MAXLNUM, NULL, READ_NEW + READ_STDIN, true);
  } else {
    open_buffer(true, NULL, 0);
  }

  if (buf_is_empty(curbuf)) {
    // stdin was empty so we should wipe it (e.g. "echo file1 | xargs nvim"). #8561
    // stdin buffer may be first or last ("echo foo | nvim file1 -"). #35269
    if ((curbuf->b_next != NULL) || (curbuf->b_prev != NULL)) {
      do_bufdel(DOBUF_WIPE, NULL, 0, 0, 0, 1);
    }
  }

  // we had to switch buffers to load stdin, switch back
  if (prev_buf) {
    set_curbuf(prev_buf, 0, false);
  }

  no_wait_return = false;
  msg_didany = save_msg_didany;
  TIME_MSG("reading stdin");
  check_swap_exists_action();
}


Review comment (suggestion):
```suggestion
    // Create memfile and read from stdin.
    open_buffer(true, NULL, 0);
```

Code after:

/// Read text from stdin.
static void read_stdin(void)
{
  // When getting the ATTENTION prompt here, use a dialog.
  swap_exists_action = SEA_DIALOG;
  no_wait_return = true;
  bool save_msg_didany = msg_didany;
  buf_T *prev_buf = NULL;

  if (curbuf->b_ffname) {
    // curbuf is already opened for a file, create a new buffer for stdin. #35269
    buf_T *newbuf = buflist_new(NULL, NULL, 0, BLN_LISTED);
    if (newbuf == NULL) {
      semsg("Failed to create buffer for stdin");
      return;
    }

    // remember the current buffer so we can go back to it
    prev_buf = curbuf;
    set_curbuf(newbuf, 0, false);
    readfile(NULL, NULL, 0, 0, (linenr_T)MAXLNUM, NULL, READ_NEW + READ_STDIN, true);
  } else {
    set_buflisted(true);
    // Create memfile and read from stdin.
    open_buffer(true, NULL, 0);
  }

  if (buf_is_empty(curbuf)) {
    // stdin was empty so we should wipe it (e.g. "echo file1 | xargs nvim"). #8561
    // stdin buffer may be first or last ("echo foo | nvim file1 -"). #35269
    if ((curbuf->b_next != NULL) || (curbuf->b_prev != NULL)) {
      do_bufdel(DOBUF_WIPE, NULL, 0, 0, 0, 1);
    }
  }

  // we had to switch buffers to load stdin, switch back
  if (prev_buf) {
    set_curbuf(prev_buf, 0, false);
  }

  no_wait_return = false;
  msg_didany = save_msg_didany;
  TIME_MSG("reading stdin");
  check_swap_exists_action();
}

// Create the requested number of windows and edit buffers in them.
// Also does recovery if "recoverymode" set.
static void create_windows(mparm_T *parmp)
{
Repository: neovim/neovim
File: test/functional/plugin/lsp/completion_spec.lua (Lua)

Code before:
    }
    create_server('dummy1', results1, { trigger_chars = { 'e' } })
    local results2 = {
      isIncomplete = false,
      items = {
        {
          label = 'hallo',
        },
      },
    }
    create_server('dummy2', results2, { trigger_chars = { 'h' } })

    feed('h')
    exec_lua(function()
      vim.v.char = 'h'
      vim.cmd.startinsert()
      vim.api.nvim_exec_autocmds('InsertCharPre', {})
    end)

    assert_matches(function(matches)
      eq(1, #matches)
      eq('hallo', matches[1].word)
    end)
  end)

  it('insert two characters at once triggers clients matching only the second one', function()
    local results1 = {
      isIncomplete = false,
      items = {
        {
          label = 'first',
        },
      },
    }
    create_server('dummy1', results1, { trigger_chars = { '-' } })
    local results2 = {
      isIncomplete = false,
      items = {
        {
          label = 'second',
        },
      },
    }
    create_server('dummy2', results2, { trigger_chars = { '>' } })

    feed('i->')

    assert_matches(function(matches)
      eq(1, #matches)
      eq('second', matches[1].word)
    end)

Review comment (suggestion):
```suggestion
  it('treats 2-triggers-at-once as "last char wins"', function()
```

Code after:
    }
    create_server('dummy1', results1, { trigger_chars = { 'e' } })
    local results2 = {
      isIncomplete = false,
      items = {
        {
          label = 'hallo',
        },
      },
    }
    create_server('dummy2', results2, { trigger_chars = { 'h' } })

    feed('h')
    exec_lua(function()
      vim.v.char = 'h'
      vim.cmd.startinsert()
      vim.api.nvim_exec_autocmds('InsertCharPre', {})
    end)

    assert_matches(function(matches)
      eq(1, #matches)
      eq('hallo', matches[1].word)
    end)
  end)

  it('treats 2-triggers-at-once as "last char wins"', function()
    local results1 = {
      isIncomplete = false,
      items = {
        {
          label = 'first',
        },
      },
    }
    create_server('dummy1', results1, { trigger_chars = { '-' } })
    local results2 = {
      isIncomplete = false,
      items = {
        {
          label = 'second',
        },
      },
    }
    create_server('dummy2', results2, { trigger_chars = { '>' } })

    feed('i->')

    assert_matches(function(matches)
      eq(1, #matches)
      eq('second', matches[1].word)
    end)
Repository: neovim/neovim
File: runtime/lua/vim/lsp/completion.lua (Lua)

Code before:
      local debounce_ms = next_debounce()
      local ctx = { triggerKind = protocol.CompletionTriggerKind.TriggerForIncompleteCompletions }
      if debounce_ms == 0 then
        vim.schedule(function()
          M.get({ ctx = ctx })
        end)
      else
        completion_timer = new_timer()
        completion_timer:start(
          math.floor(debounce_ms),
          0,
          vim.schedule_wrap(function()
            M.get({ ctx = ctx })
          end)
        )
      end
    end

    return
  end

  local char = api.nvim_get_vvar('char')
  local matched_clients = handle.triggers[char]
  reset_timer()
  if matched_clients then
    completion_timer = assert(vim.uv.new_timer())
    completion_timer:start(25, 0, function()
      reset_timer()
      vim.schedule(function()
        trigger(
          api.nvim_get_current_buf(),
          matched_clients,
          { triggerKind = protocol.CompletionTriggerKind.TriggerCharacter, triggerCharacter = char }
        )
      end)
    end)
  end
end

local function on_insert_leave()
  reset_timer()
  Context.cursor = nil
  Context:reset()
end

local function on_complete_done()
  local completed_item = api.nvim_get_vvar('completed_item')
  if not completed_item or not completed_item.user_data or not completed_item.user_data.nvim then
    Context:reset()
    return
  end

Review comment (suggestion):
```suggestion
  -- Discard pending trigger char, complete the "latest" one.
  -- Can happen if a mapping inputs multiple trigger chars simultaneously.
  reset_timer()
```

Code after:
      local debounce_ms = next_debounce()
      local ctx = { triggerKind = protocol.CompletionTriggerKind.TriggerForIncompleteCompletions }
      if debounce_ms == 0 then
        vim.schedule(function()
          M.get({ ctx = ctx })
        end)
      else
        completion_timer = new_timer()
        completion_timer:start(
          math.floor(debounce_ms),
          0,
          vim.schedule_wrap(function()
            M.get({ ctx = ctx })
          end)
        )
      end
    end

    return
  end

  local char = api.nvim_get_vvar('char')
  local matched_clients = handle.triggers[char]
  -- Discard pending trigger char, complete the "latest" one.
  -- Can happen if a mapping inputs multiple trigger chars simultaneously.
  reset_timer()
  if matched_clients then
    completion_timer = assert(vim.uv.new_timer())
    completion_timer:start(25, 0, function()
      reset_timer()
      vim.schedule(function()
        trigger(
          api.nvim_get_current_buf(),
          matched_clients,
          { triggerKind = protocol.CompletionTriggerKind.TriggerCharacter, triggerCharacter = char }
        )
      end)
    end)
  end
end

local function on_insert_leave()
  reset_timer()
  Context.cursor = nil
  Context:reset()
end

local function on_complete_done()
  local completed_item = api.nvim_get_vvar('completed_item')
  if not completed_item or not completed_item.user_data or not completed_item.user_data.nvim then
    Context:reset()
Repository: neovim/neovim
File: test/functional/legacy/028_source_ctrl_v_spec.lua (Lua)

Code before:
      map __3 asdXX
      map __4 asdXXX
      map __5 asdXXX
      lastline]])

    feed(':%s/X/<C-v><C-v>/g<cr>')
    feed(':/firstline/+1,/lastline/-1w! Xtestfile<cr>')
    feed_command('so Xtestfile')
    feed_command('%d')
    feed('Gmm__1<Esc><Esc>__2<Esc>__3<Esc><Esc>__4<Esc>__5<Esc>')
    feed(":'m,$s/<C-v><C-@>/0/g<cr>")

    expect([[
      sd
      map __2 asdsecondsdsd0map __5 asd0fifth]])
  end)

  it('CTRL-X/CTRL-A is working', function()
    insert([[
      12352

      12354]])
    feed_command('/12352')
    feed('')
    feed_command('/12354')
    feed('')
    expect([[
      12353

      12353]])
  end)

  teardown(function()
    os.remove('Xtestfile')
  end)
end)


Review comment (suggestion):
`feed('')` doesn't do anything:
```lua
local function nvim_feed(input)
  while #input > 0 do
```

Code after:
      map __3 asdXX
      map __4 asdXXX
      map __5 asdXXX
      lastline]])

    feed(':%s/X/<C-v><C-v>/g<cr>')
    feed(':/firstline/+1,/lastline/-1w! Xtestfile<cr>')
    feed_command('so Xtestfile')
    feed_command('%d')
    feed('Gmm__1<Esc><Esc>__2<Esc>__3<Esc><Esc>__4<Esc>__5<Esc>')
    feed(":'m,$s/<C-v><C-@>/0/g<cr>")

    expect([[
      sd
      map __2 asdsecondsdsd0map __5 asd0fifth]])
  end)

  it('CTRL-X/CTRL-A is working', function()
    insert([[
      12352

      12354]])
    feed_command('/12352')
    feed('<C-A>')
    feed_command('/12354')
    feed('<C-X>')
    expect([[
      12353

      12353]])
  end)

  teardown(function()
    os.remove('Xtestfile')
  end)
end)
Repository: neovim/neovim
File: src/nvim/os/env.c (C)

Code before:
  assert(len > 0);
  return xmemdupz(str, (size_t)len);
#endif
}

/// Get the process ID of the Nvim process.
///
/// @return the process ID.
int64_t os_get_pid(void)
{
#ifdef MSWIN
  return (int64_t)GetCurrentProcessId();
#else
  return (int64_t)getpid();
#endif
}

/// Apply a priority appropriate for interactive work to the Nvim process.
void os_hint_priority(void)
{
#ifdef __APPLE__
  // Inform the macOS scheduler that Nvim renders UI, and so shouldn’t have its threads’ quality
  // of service classes clamped. The main thread runs at User Interactive by default so we don’t
  // need to adjust that.
  integer_t policy = TASK_DEFAULT_APPLICATION;
  task_policy_set(mach_task_self(), TASK_CATEGORY_POLICY, &policy, 1);
#endif
}

/// Gets the hostname of the current machine.
///
/// @param hostname   Buffer to store the hostname.
/// @param size       Size of `hostname`.
void os_get_hostname(char *hostname, size_t size)
{
#ifdef HAVE_SYS_UTSNAME_H
  struct utsname vutsname;

  if (uname(&vutsname) < 0) {
    *hostname = NUL;
  } else {
    xstrlcpy(hostname, vutsname.nodename, size);
  }
#elif defined(MSWIN)
  wchar_t host_utf16[MAX_COMPUTERNAME_LENGTH + 1];
  DWORD host_wsize = sizeof(host_utf16) / sizeof(host_utf16[0]);
  if (GetComputerNameW(host_utf16, &host_wsize) == 0) {
    *hostname = NUL;
    DWORD err = GetLastError();
    semsg("GetComputerNameW failed: %d", err);
    return;

Review comment (suggestion):
If the main thread's priority doesn't need adjusting, what does this actually adjust? Usually there are no other threads.

Code after:
  assert(len > 0);
  return xmemdupz(str, (size_t)len);
#endif
}

/// Get the process ID of the Nvim process.
///
/// @return the process ID.
int64_t os_get_pid(void)
{
#ifdef MSWIN
  return (int64_t)GetCurrentProcessId();
#else
  return (int64_t)getpid();
#endif
}

/// Signals to the OS that Nvim is an application for "interactive work"
/// which should be prioritized similar to a GUI app.
void os_hint_priority(void)
{
#ifdef __APPLE__
  // By default, processes have the TASK_UNSPECIFIED "role", which means all of its threads are
  // clamped to Default QoS. Setting the role to TASK_DEFAULT_APPLICATION removes this clamp.
  integer_t policy = TASK_DEFAULT_APPLICATION;
  task_policy_set(mach_task_self(), TASK_CATEGORY_POLICY, &policy, 1);
#endif
}

/// Gets the hostname of the current machine.
///
/// @param hostname   Buffer to store the hostname.
/// @param size       Size of `hostname`.
void os_get_hostname(char *hostname, size_t size)
{
#ifdef HAVE_SYS_UTSNAME_H
  struct utsname vutsname;

  if (uname(&vutsname) < 0) {
    *hostname = NUL;
  } else {
    xstrlcpy(hostname, vutsname.nodename, size);
  }
#elif defined(MSWIN)
  wchar_t host_utf16[MAX_COMPUTERNAME_LENGTH + 1];
  DWORD host_wsize = sizeof(host_utf16) / sizeof(host_utf16[0]);
  if (GetComputerNameW(host_utf16, &host_wsize) == 0) {
    *hostname = NUL;
    DWORD err = GetLastError();
    semsg("GetComputerNameW failed: %d", err);
    return;