Neovim Lua Config, Keymaps, and Autocmds

Modern Neovim configuration patterns using Lua, keymaps, options, and autocommands.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Lua options
Enable line numbers
vim.opt.number = true
vim.opt.relativenumber = true

# Turn on absolute and relative line numbers.

Configure tabs and indentation
vim.opt.tabstop = 2
vim.opt.shiftwidth = 2
vim.opt.expandtab = true

# Set width and spacing rules.

Set the leader key
vim.g.mapleader = " "

# Define your custom mapping prefix.

## Lua keymaps
Map a save command
vim.keymap.set("n", "<leader>w", "<cmd>write<CR>")

# Bind a normal-mode key to save the file.

Map Telescope file search
vim.keymap.set("n", "<leader>ff", function()
  require("telescope.builtin").find_files()
end, { desc = "Find files", silent = true })

# Bind a key to file-finding with a Lua callback.

Map line movement in visual mode
vim.keymap.set("v", "J", ":m '>+1<CR>gv=gv")
vim.keymap.set("v", "K", ":m '<-2<CR>gv=gv")

# Move selected lines up or down.

## Lua autocommands
Create an autocmd
vim.api.nvim_create_autocmd("BufWritePost", {
  pattern = "*.lua",
  callback = function()
    print("saved lua file")
  end,
})

# Run code when matching files are written.

Create an augroup
local grp = vim.api.nvim_create_augroup("MyGroup", { clear = true })

# Group related autocmds together.

Format on save with LSP
vim.api.nvim_create_autocmd("BufWritePre", {
  pattern = "*.ts",
  callback = function()
    vim.lsp.buf.format()
  end,
})

# Trigger LSP formatting before write.

Recommended next

No recommendations yet.