summaryrefslogtreecommitdiffstats
path: root/init.lua
blob: c1fe45d163584a4f2f1e9ac0880b1d944b09fbf8 (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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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 = 100, markdown = 120, python = 88 },
}

-- Sets the window bar content and style (custom hl-groups WinBarCwd and WinBarFilePath)
-- Note that this will usually be cleared when loading a colorscheme (which do the equivalent of :hi clear)
vim.api.nvim_set_hl(0, "WinBarCwd", { bold = true })
vim.api.nvim_set_hl(0, "WinBarFilePath", { link = "Normal" })
vim.opt.winbar = "%#WinBarCwd#%{fnamemodify(getcwd(),':~')}%* | %#WinBarFilePath#%f%*"

------------------------------------------------------------------------------------------------------------------------
-- 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

-- Simulate `i_CTRL-R` in terminal mode (read a register name, put its contents)
local function terminal_put_register()
	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

-- Toggle "follow" mode for the current terminal: while on, leaving terminal mode jumps to the
-- bottom (G) so the view tracks the latest output. Shown as `+T` in the statusline (50-color.lua).
local function toggle_terminal_follow()
	if vim.bo.buftype ~= "terminal" then
		vim.notify("TerminalFollow only applies to terminal buffers", vim.log.levels.WARN)
		return
	end
	vim.b.terminal_follow = not vim.b.terminal_follow
end

-- Kill from the cursor to the end of the command line, akin to Readline's kill-line
local function cmdline_kill_line()
	local pos = vim.fn.getcmdpos() -- 1-based byte index of the cursor
	vim.fn.setcmdline(vim.fn.getcmdline():sub(1, pos - 1), pos)
end

-- Non incremental command-line history search that works while the completion menu is active
local function cmdline_history_prev()
	return vim.fn.pumvisible() == 1 and "<C-e><Up>" or "<Up>"
end

local function cmdline_history_next()
	return vim.fn.pumvisible() == 1 and "<C-e><Down>" or "<Down>"
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,
})

------------------------------------------------------------------------------------------------------------------------
-- 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" }
)
vim.api.nvim_create_user_command(
	"TerminalFollow",
	toggle_terminal_follow,
	{ desc = "Toggle following terminal output" }
)

------------------------------------------------------------------------------------------------------------------------
-- 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)

-- stylua: ignore start
-- Miscellaneous
vim.keymap.set("n", "<M-z>", "zA", { desc = "Toggle fold (recursively) under cursor" })
vim.keymap.set("n", "<Leader>lh", vim.cmd.LspHintToggle, { desc = "Toggle inlay hints (LSP)" })
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" })
-- Files
vim.keymap.set("n", "<M-e>", vim.cmd.GotoExplorer, { desc = "Open/close/focus netrw window" })
vim.keymap.set("n", "<Leader>y+", "<Cmd>let @+ = expand('%:p')<CR>", { desc = "Copy file path to clipboard" })
-- Buffers
vim.keymap.set("n", "<C-s>", "<Cmd>update<CR>", { desc = "Save buffer" })
vim.keymap.set("n", "<M-n>", "<Cmd>new<CR>", { desc = "Edit new buffer in split" })
vim.keymap.set("n", "<Leader>bw", toggle_wrap, { desc = "Toggle text wrap" })
-- 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("n", "<M-p>", "<Cmd>wincmd p<CR>", { desc = "Go to previously accessed window" })
vim.keymap.set("n", "<M-v>", "<Cmd>vsplit<CR>", { desc = "Split window vertically" })
vim.keymap.set("n", "<M-c>", "<Cmd>close<CR>", { desc = "Close window" })
vim.keymap.set("n", "<M-o>", "<Cmd>only<CR>", { desc = "Close all other windows" })
-- Tabpages
vim.keymap.set("n", "<M-t>", "<Cmd>tabnew<CR>", { desc = "Open new tabpage" })
vim.keymap.set("n", "<C-w>t", "<Cmd>tabclose<CR>", { desc = "Delete current tabpage" })
vim.keymap.set("n", "<C-w>p", "<Cmd>tabnext #<CR>", { desc = "Go to previously accessed tabpage" })
vim.keymap.set("n", "<C-w><C-p>", "<Cmd>tabnext #<CR>", { desc = "Go to previously accessed tabpage" })
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" })
-- Command-line and insert
-- <C-p> enters command mode, then <C-p>/<C-n> walk history (recall a command in two keystrokes)
vim.keymap.set("n", "<C-p>", ":", { desc = "Enter command mode" })
vim.keymap.set({ "c", "i" }, "<Left>", "<Space><BS><Left>", { desc = "Move cursor left" })
vim.keymap.set({ "c", "i" }, "<Right>", "<Space><BS><Right>", { desc = "Move cursor right" })
vim.keymap.set("c", "<C-k>", cmdline_kill_line, { desc = "Kill from cursor to end of line" })
vim.keymap.set("c", "<C-p>", cmdline_history_prev, { expr = true, desc = "Previous history entry" })
vim.keymap.set("c", "<C-n>", cmdline_history_next, { expr = true, desc = "Next history entry" })
-- Terminal
vim.keymap.set("n", "<M-s>", "<Cmd>terminal<CR>", { desc = "Open terminal in window" })
vim.keymap.set("t", "<Esc>", "<C-\\><C-n>", { desc = "Exit terminal mode" })
vim.keymap.set("t", "<M-[>", "<Esc>", { desc = "Send <Esc> to the terminal program" })
vim.keymap.set("t", "<C-o>", "<C-\\><C-o>", { desc = "Execute one normal-mode command" })
vim.keymap.set("t", "<C-r>", terminal_put_register, { desc = "Paste register" })
vim.keymap.set("n", "<Leader>F", "<Cmd>TerminalFollow<CR>", { desc = "Toggle following terminal output" })
-- stylua: ignore end
vim.api.nvim_create_autocmd("TermOpen", {
	desc = "Enter terminal mode and follow output by default",
	group = vim.g.dotfiles.augroup,
	callback = function()
		vim.b.terminal_follow = true
		vim.cmd.startinsert()
	end,
})
vim.api.nvim_create_autocmd("TermLeave", {
	desc = "Follow terminal output (jump to bottom) when enabled, see :TerminalFollow",
	group = vim.g.dotfiles.augroup,
	callback = function()
		if vim.b.terminal_follow then
			vim.cmd.normal({ "G", bang = true })
		end
	end,
})

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

vim.opt.shell = "/usr/bin/bash"
vim.opt.pumheight = 16 -- Popup menu height to 16 lines
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.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")
vim.g.netrw_banner = 0 -- No netrw banner
-- 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 = "yes" -- Always show sign column
vim.opt.foldcolumn = "1" -- width of the 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