← All posts
May 4, 20242 min read

Vim Commands & Neovim C++ Setup

Search-and-replace patterns worth memorizing, plus wiring up NvChad with Mason and clangd for C++ development.

#vim#neovim#editor

Useful vim commands

Search and replace

  • :s/search/replace/ — current line, first occurrence.
  • :s/search/replace/g — current line, all occurrences.
  • :%s/search/replace/g — entire file.
  • :3,10s/search/replace/g — lines 3 through 10.
  • :.,+4s/search/replace/g — current line through the next 4 lines.
  • :.,$s/search/replace/ — current line to end of file.
  • Append gc to confirm each substitution individually.
  • Append gi to ignore case.

Folding

:set foldmethod=indent folds lines by indentation.

Line numbers

  • :set number — absolute line numbers; :set relativenumber — distances from the cursor.
  • :set number relativenumber — current line shows its real number, everything else relative to it.
  • :set nonumber norelativenumber — back to no numbers.

Buffers

  • :ls — list open buffers.
  • :b 2 or :b file.cpp — jump to a buffer by number or name.
  • :bd — close the current buffer (without quitting Vim).

Tabs

  • :tabnew file.cpp — open a file in a new tab.
  • :tabs — list tabs and what's in each one; :tabnext / :tabprev (or gt / gT) move between them.

Visual block

  • Ctrl-v — enter visual block mode; select a column of lines, press I (or A) to insert at the start (or end) of every selected line, then press Esc to apply to all of them.

Neovim for C++ (NvChad)

  1. Install mason.nvim. Add M.plugins = "custom.plugins" to chadrc.lua under ~/.config/nvim/lua/custom.
  2. Create a plugins file and ensure clangd gets installed:
local plugins = {
  {
    "williamboman/mason.nvim",
    opts = {
      ensure_installed = { "clangd" }
    }
  }
}
return plugins
  1. Reopen Neovim and run :MasonInstallAll.

  2. Wire clangd into nvim-lspconfig:

local plugins = {
  {
    "neovim/nvim-lspconfig",
    config = function()
      require "plugins.configs.lspconfig"
      require "custom.configs.lspconfig"
    end
  },
  {
    "williamboman/mason.nvim",
    opts = {
      ensure_installed = { "clangd" }
    }
  }
}
return plugins
  1. Create custom/configs/lspconfig.lua:
local base = require("plugins.configs.lspconfig")
local on_attach = base.on_attach
local capabilities = base.capabilities
 
local lspconfig = require("lspconfig")
 
lspconfig.clangd.setup{
  on_attach = function(client, bufnr)
    client.server_capabilities.signatureHelpProvider = false
    on_attach(client, bufnr)
  end,
  capabilities = capabilities,
}
  1. Exit and re-enter Neovim, then run :TSInstall cpp.

  2. For formatting, add a null-ls source at custom/configs/null-ls.lua:

local null_ls = require("null_ls")
 
local opts = {
  sources = {
    null_ls.builtins.formatting.clang_format,
  }
}
 
return opts