summaryrefslogtreecommitdiffstats
path: root/.config/nvim/init.lua
blob: c1def6685f8627f45845165dc01320b1e6d6c5d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
if vim.env.DOTFILES_DIR == nil then
	vim.notify("DOTFILES_DIR is not set!", vim.log.levels.WARN)
end

vim.g.dotfiles = {
	augroup = vim.api.nvim_create_augroup("dotfiles", {}),
	-- Single source of truth for per-filetype formatting width
	-- (textwidth → gw, mdformat --wrap, render-markdown block widths).
	textwidth = { sh = 80, lua = 120, markdown = 120, gitcommit = 72 },
}

------------------------------------------------------------------------------------------------------------------------
-- Local functions
------------------------------------------------------------------------------------------------------------------------

-- Show the diff between the current buffer and the file it was loaded from
local function show_buf_diff_orig()
	local bname = vim.api.nvim_buf_get_name(0)
	if not vim.uv.fs_stat(bname) then
		vim.notify("Cannot diff with original because " .. bname .. " doesn't exist", vim.log.levels.WARN)
		return
	end
	local cwin = vim.api.nvim_get_current_win()
	vim.cmd.diffthis()
	local temp = vim.fn.tempname()
	local ok, err = vim.uv.fs_copyfile(bname, temp)
	if not ok then
		vim.notify("Could not copy file: " .. err, vim.log.levels.ERROR)
		return
	end
	vim.cmd.split({ temp, mods = { vertical = vim.api.nvim_win_get_width(0) >= vim.o.textwidth * 2, keepalt = true } })
	vim.cmd.diffthis()
	vim.opt_local.bufhidden = "wipe"
	vim.opt_local.buftype = "nofile"
	vim.opt_local.swapfile = false
	vim.opt_local.readonly = true
	vim.api.nvim_set_current_win(cwin)
end

local function reload_buffer()
	if vim.o.filetype == "netrw" then
		vim.cmd.edit(".")
	else
		-- `:edit` resets fold state; preserve it via `:mkview`/`:loadview`.
		vim.cmd.mkview()
		vim.cmd.edit()
		vim.cmd.loadview()
	end
end

local function toggle_wrap()
	vim.o.wrap = not vim.o.wrap
end

------------------------------------------------------------------------------------------------------------------------
-- Miscellaneous
------------------------------------------------------------------------------------------------------------------------

vim.g.mapleader = " " -- Set before any `vim.keymap.set()` call

-- Highlight on yank
vim.api.nvim_create_autocmd("TextYankPost", {
	desc = "Highlight on yank",
	group = vim.g.dotfiles.augroup,
	callback = function()
		vim.hl.on_yank()
	end,
})

-- Reload file when changed outside of nvim
vim.opt.autoread = false -- Must be false for FileChangedShell to trigger when the buffer was not changed
-- The manual says that FileChangedShell is triggered on FocusGained but it's not true. This function actually triggers
-- the next FileChangedShell when the buffer has unsaved changes and the file was modified outside of nvim.
vim.api.nvim_create_autocmd({ "FocusGained" }, {
	desc = "Trigger buffer reload when file is edited outside of nvim",
	group = vim.g.dotfiles.augroup,
	callback = function()
		vim.cmd.checktime()
	end,
})
vim.api.nvim_create_autocmd({ "FileChangedShell" }, {
	desc = "Prompt user to reload buffer when modified outside of nvim",
	group = vim.g.dotfiles.augroup,
	pattern = "*",
	callback = function()
		if vim.v.fcs_reason == "conflict" or vim.v.fcs_reason == "changed" then
			vim.v.fcs_choice = "ask"
		end
	end,
})
vim.api.nvim_create_autocmd({ "FileChangedShellPost" }, {
	desc = "Notify buffer reloaded because its file has changed on disk",
	group = vim.g.dotfiles.augroup,
	pattern = "*",
	callback = function(opts)
		vim.notify("File " .. opts.file .. " has changed on disk", vim.log.levels.WARN)
	end,
})

------------------------------------------------------------------------------------------------------------------------
-- Commands (there's more in the different plugins)
------------------------------------------------------------------------------------------------------------------------

vim.api.nvim_create_user_command("DiffOrig", show_buf_diff_orig, { desc = "Show diff between current buffer and file" })

------------------------------------------------------------------------------------------------------------------------
-- Keymaps (there's more in the different plugins)
------------------------------------------------------------------------------------------------------------------------
-- See `:help key-notation` and `:help <Cmd>`
-- `:map \ ` to see (most) user set keymaps (those starting with the `<Leader>` key)

-- Miscellaneous
vim.keymap.set("n", "<M-z>", "zA", { desc = "Toggle fold (recursively) under cursor" })
vim.keymap.set("n", "ZR", vim.cmd.SessionRestart, { desc = "Save and load default session and restart" })
vim.keymap.set("n", "ZZ", vim.cmd.SessionExitSave, { desc = "Save to default session and exit" })
vim.keymap.set("n", "ZQ", vim.cmd.SessionExitNoSave, { desc = "Quit without saving session" })
vim.keymap.set("t", "<C-\\><C-\\>", "<C-\\><C-n>", { desc = "Exit terminal mode" })
vim.keymap.set("n", "<Leader>mm", "<Cmd>messages<CR>", { desc = "Show all messages" })
vim.keymap.set("n", "<Leader>mc", "<Cmd>messages clear<CR>", { desc = "Clear all messages" })
vim.keymap.set("n", "<Leader>lh", vim.cmd.LspHintToggle, { desc = "Toggle inlay hints (LSP)" })
vim.keymap.set("n", "<Leader>y+", "<Cmd>let @+ = expand('%:p')<CR>", { desc = "Copy file path to clipboard" })
-- These two mappings work well together to start command mode and insert from history in two keystrokes.
vim.keymap.set("n", "<C-p>", ":", { desc = "Enter command mode" })
vim.keymap.set("c", "<C-p>", "<Up>", { desc = "Insert previous history entry" })
-- Navigate files
vim.keymap.set("n", "<M-e>", vim.cmd.GotoExplorer, { desc = "Open/close/focus netrw window" })
-- Buffers
vim.keymap.set("n", "<Leader>s", "<Cmd>update<CR>", { desc = "Save buffer" })
vim.keymap.set("n", "<Leader>be", reload_buffer, { desc = "Reload buffer" })
vim.keymap.set("n", "<Leader>bw", toggle_wrap, { desc = "Toggle text wrap" })
vim.keymap.set("n", "<Leader>bd", "<Cmd>bdelete<CR>", { desc = "Delete buffer" })
vim.keymap.set("n", "<Leader>bn", "<Cmd>enew<CR>", { desc = "Edit new buffer in current window" })
vim.keymap.set("n", "<Leader>bs", "<Cmd>new<CR>", { desc = "Edit new buffer in split" })
vim.keymap.set("n", "<Leader>bv", "<Cmd>vnew<CR>", { desc = "Edit new buffer in vertical split" })
-- Windows
vim.keymap.set("n", "<M-h>", "<C-w>h", { desc = "Move left a window" })
vim.keymap.set("n", "<M-j>", "<C-w>j", { desc = "Move down a window" })
vim.keymap.set("n", "<M-k>", "<C-w>k", { desc = "Move up a window" })
vim.keymap.set("n", "<M-l>", "<C-w>l", { desc = "Move right a window" })
vim.keymap.set("t", "<M-h>", "<C-\\><C-n><C-w>h", { desc = "Move left a window" })
vim.keymap.set("t", "<M-j>", "<C-\\><C-n><C-w>j", { desc = "Move down a window" })
vim.keymap.set("t", "<M-k>", "<C-\\><C-n><C-w>k", { desc = "Move up a window" })
vim.keymap.set("t", "<M-l>", "<C-\\><C-n><C-w>l", { desc = "Move right a window" })
vim.keymap.set("n", "<Leader>wc", "<Cmd>close<CR>", { desc = "Close window" })
vim.keymap.set("n", "<Leader>ws", "<Cmd>split<CR>", { desc = "Split window" })
vim.keymap.set("n", "<Leader>wv", "<Cmd>vsplit<CR>", { desc = "Split window vertically" })
vim.keymap.set("n", "<Leader>wr", "<C-W>r", { desc = "Rotate windows down/right" })
vim.keymap.set("n", "<Leader>wR", "<C-W>R", { desc = "Rotate windows up/left" })
vim.keymap.set("n", "<Leader>wx", "<C-W>x", { desc = "Exchange window with next one" })
vim.keymap.set("n", "<Leader>w=", "<C-W>=", { desc = "Equalize windows" })
vim.keymap.set("n", "<Leader>w+", "<C-W>+", { desc = "Increase window height" })
vim.keymap.set("n", "<Leader>w-", "<C-W>-", { desc = "Decrease window height" })
vim.keymap.set("n", "<Leader>w>", "<C-W>>", { desc = "Increase window width" })
vim.keymap.set("n", "<Leader>w<", "<C-W><", { desc = "Decrease window width" })
vim.keymap.set("n", "<Leader>w_", "<C-W>_", { desc = "Set window height" })
vim.keymap.set("n", "<Leader>w|", "<C-W>|", { desc = "Set window width" })
-- Tabpages
vim.keymap.set("n", "<M-t>", "<Cmd>tabnew<CR>", { desc = "Create new tabpage" })
vim.keymap.set("n", "<C-w>t", "<Cmd>tabclose<CR>", { desc = "Delete current tabpage" })
vim.keymap.set({ "n", "i", "t" }, "<M-p>", "<Cmd>tabnext #<CR>", { desc = "Move to last accessed tab page" })
vim.keymap.set({ "n", "i", "t" }, "<M-n>", "<Cmd>tabnext<CR>", { desc = "Move to next tab page" })
vim.keymap.set({ "n", "i", "t" }, "<M-b>", "<Cmd>tabprevious<CR>", { desc = "Move to previous tab page" })
vim.keymap.set("n", "<C-w>>", "<Cmd>tabmove +1<CR>", { desc = "Move tab to next position" })
vim.keymap.set("n", "<C-w><", "<Cmd>tabmove -1<CR>", { desc = "Move tab to next position" })
-- Scrolling
vim.keymap.set("n", "<C-u>", vim.cmd.ScrollSmoothUp, { desc = "Scroll up smoothly" })
vim.keymap.set("n", "<C-d>", vim.cmd.ScrollSmoothDown, { desc = "Scroll down smoothly" })
-- Navigate in command/insert mode
vim.keymap.set({ "c", "i" }, "<M-h>", "<Space><BS><Left>")
vim.keymap.set({ "c", "i" }, "<M-l>", "<Space><BS><Right>")
vim.keymap.set("c", "<M-H>", "<C-Left>")
vim.keymap.set("c", "<M-L>", "<C-Right>")
-- Non incremental history search, works when the completion menu is active
vim.keymap.set("c", "<C-k>", function()
	return vim.fn.pumvisible() == 1 and "<C-e><Up>" or "<Up>"
end, { expr = true })
vim.keymap.set("c", "<C-j>", function()
	return vim.fn.pumvisible() == 1 and "<C-e><Down>" or "<Down>"
end, { expr = true })
-- Simulate `i_CTRL-R` in terminal mode
vim.keymap.set("t", "<C-r>", function()
	local input = vim.fn.getchar()
	assert(type(input) == "number")
	local register = vim.fn.nr2char(input)
	local value = vim.fn.getreg(register)
	vim.api.nvim_put({ value }, "c", true, true)
end)

------------------------------------------------------------------------------------------------------------------------
-- Options
------------------------------------------------------------------------------------------------------------------------

vim.opt.shell = "/usr/bin/bash"
vim.opt.foldenable = true -- Folds are closed by default
vim.opt.pumheight = 16 -- Popup menu height uses all available space
vim.opt.confirm = true -- Confirm before losing buffer unsaved changes
vim.opt.splitbelow = false
vim.opt.splitright = false
vim.opt.clipboard = "unnamedplus" -- Sync clipboard
vim.opt.cursorline = true -- Highlight the line where the cursor is on
vim.opt.scrolloff = 2 -- Keep this many visible screen lines above/below the cursor
vim.opt.ignorecase = true -- Search ignores case by default
vim.opt.smartcase = true -- Search is case-sensitive if searching for uppercase characters
vim.opt.conceallevel = 2 -- Hide text with the "conceal" syntax attribute
vim.opt.showtabline = 2 -- Always show tabline
vim.opt.winbar = "%#WinBarCwd#%{fnamemodify(getcwd(),':~')}%* | %#WinBarFile#%f%*"
vim.opt.winborder = "rounded" -- Rounded outline for floating windows
vim.opt.updatetime = 1000 -- Swap file save frequency; also how often GitGutter signs update in ms
vim.opt.list = true -- Display <Tab> and other non-printables
vim.opt.listchars = { -- Characters used by 'list'
	tab = "> ", -- Tab
	trail = "-", -- Trailing space
	nbsp = "+", -- Non-breakable space
	extends = "→", -- Last column when 'wrap' is off
	precedes = "←", -- First column when there is text before it
}
-- See `'cpoptions'`
-- Use a `\` like `CTRL_V` in mappings, abbreviations, user commands and the "to" part of menu commands
-- Useful for example for matching mappings that start with space: `:map \ `
vim.opt.cpoptions:remove("B")
-- Backup
vim.opt.swapfile = true -- Store a swap file, see `:help swap-file`
vim.opt.undofile = true -- Save buffer undo history
vim.opt.backup = true -- Backup file before overwriting
vim.opt.backupdir = { vim.fn.stdpath("state") .. "/backup//" }
vim.opt.writebackup = true -- Keep backup after writing file
-- Gutter
vim.opt.number = true -- Show line number
vim.opt.relativenumber = true -- Show relative line number
vim.opt.numberwidth = 4 -- Minimal number of columns for line number (includes the space before the text)
vim.opt.signcolumn = "auto" -- Show sign column when there is a sign to display
vim.opt.foldcolumn = "0" -- Disable foldcolumn
-- Wrapping
vim.opt.wrap = false -- Don't wrap text by default
vim.opt.showbreak = "+++ " -- String to show wrapped lines
vim.opt.linebreak = true -- Wrap at characters in 'breakat'
vim.opt.breakindent = true -- Indent wrapped lines
-- Tab and backspace (See `help 30.5`)
vim.opt.tabstop = 4 -- <Tab> and <Bs> visually expand at columns multiple of 'tabstop'
vim.opt.shiftwidth = 0 -- Number of space in first indendation. If 0 use 'tabstop' value.
vim.opt.softtabstop = -1 -- <Tab> and <Bs> stop at columns multiple of 'softtabstop'. If <0 use 'shiftwidth' value.
vim.opt.expandtab = false -- Don't turn tabs into spaces