init nvim

This commit is contained in:
2023-04-02 13:46:42 +03:00
parent 3bceb62c33
commit 3d1c72039a
19 changed files with 33 additions and 33 deletions

64
pwnvim/abbreviations.lua Normal file
View File

@@ -0,0 +1,64 @@
vim.cmd("ab jjcheck ✓")
vim.cmd("ab Ironcore IronCore")
vim.cmd("ab Hubspot HubSpot")
vim.cmd("ab jjheart ♥")
vim.cmd("ab jjcomm ⌘")
vim.cmd("ab accidant accident")
vim.cmd("ab accomodate accommodate")
vim.cmd("ab accross across")
vim.cmd("ab acheive achieve")
vim.cmd("ab accomodate accommodate")
vim.cmd("ab acomodate accommodate")
vim.cmd("ab andthe and the")
vim.cmd("ab apparant apparent")
vim.cmd("ab aquisition acquisition")
vim.cmd("ab assistent assistant")
vim.cmd("ab asthe as the")
vim.cmd("ab atthe at the")
vim.cmd("ab beutiful beautiful")
vim.cmd("ab cemetary cemetery")
vim.cmd("ab changeing changing")
vim.cmd("ab convertable convertible")
vim.cmd("ab defendent defendant")
vim.cmd("ab embarass embarrass")
vim.cmd("ab equivalant equivalent")
vim.cmd("ab guage gauge")
vim.cmd("ab harrass harass")
vim.cmd("ab hte the")
vim.cmd("ab teh the")
vim.cmd("ab judgment judgement")
vim.cmd("ab liason liaison")
vim.cmd("ab lieutenent lieutenant")
vim.cmd("ab performence performance")
vim.cmd("ab permanant permanent")
vim.cmd("ab questionaire questionnaire")
vim.cmd("ab recieve receive")
vim.cmd("ab relevent relevant")
vim.cmd("ab rythm rhythm")
vim.cmd("ab seperate separate")
vim.cmd("ab shouldnt shouldn't")
vim.cmd("ab couldnt couldn't")
vim.cmd("ab supercede supersede")
vim.cmd("ab taht that")
vim.cmd("ab threshhold threshold")
vim.cmd("ab tomorow tomorrow")
vim.cmd("ab transfered transferred")
vim.cmd("ab vacume vacuum")
vim.cmd("ab wierd weird")
vim.cmd("ab wouldnt wouldn't")
vim.cmd("ab independant independent")
vim.cmd("ab independance independence")
vim.cmd("ab occured occurred")
vim.cmd("ab occurence occurrence")
vim.cmd("ab occurance occurrence")
vim.cmd("ab occurrance occurrence")
vim.cmd("ab reccomend recommend")
vim.cmd("ab reccommend recommend")
vim.cmd("ab monday Monday")
vim.cmd("ab tuesday Tuesday")
vim.cmd("ab wednesday Wednesday")
vim.cmd("ab thursday Thursday")
vim.cmd("ab friday Friday")
vim.cmd("ab saturday Saturday")
vim.cmd("ab sunday Sunday")

93
pwnvim/filetypes.lua Normal file
View File

@@ -0,0 +1,93 @@
local M = {}
M.config = function()
local filetypes = vim.api.nvim_create_augroup("filetypes", { clear = true })
local autocmd = vim.api.nvim_create_autocmd
-- Function below makes direnv impure by design. We need to keep the LSP servers and other nvim dependencies
-- in our path even after direnv overwrites the path. Whatever direnv puts in place will take precedence, but
-- we fall back to the various language tools installed with pwnvim using this hack
local initial_path = vim.env.PATH
autocmd("User DirenvLoaded",
{ callback = function()
if not string.find(vim.env.PATH, initial_path, 0, true) then
vim.env.PATH = vim.env.PATH .. ":" .. initial_path
end
end, group = filetypes })
autocmd("BufRead", { pattern = { "*.markdown", "*.md" }, command = "setlocal filetype=markdown", group = filetypes })
autocmd("BufRead", { pattern = { "*.sbt" }, command = "setlocal filetype=scala", group = filetypes })
autocmd("BufRead",
{ pattern = { "~/mail/*", "/tmp/mutt*", "~/.signature*" }, command = "setlocal filetype=mail", group = filetypes })
autocmd("BufRead", { pattern = { "~/.mutt/*" }, command = "setlocal filetype=muttrc", group = filetypes })
autocmd("BufRead", { pattern = { "*.*html*" }, command = "setlocal filetype=html", group = filetypes })
autocmd("BufRead", { pattern = { "*.css*" }, command = "setlocal filetype=css", group = filetypes })
autocmd("BufRead", { pattern = { "*.rss" }, command = "setlocal filetype=xml", group = filetypes })
autocmd("BufRead", { pattern = { "flake.lock" }, command = "setlocal filetype=json", group = filetypes })
autocmd("FileType",
{ pattern = { "sql", "mysql", "plsql" },
callback = function() require('cmp').setup.buffer({ sources = { { name = 'vim-dadbod-completion' } } }) end,
group = filetypes })
autocmd("FileType",
{ pattern = { "c", "ruby", "php", "php3", "perl", "python", "mason", "vim", "sh", "zsh", "scala", "javascript",
"javascriptreact", "typescript", "typescriptreact", "html", "svelte", "css", "nix" },
callback = function() require('pwnvim.options').programming() end, group = filetypes })
autocmd("FileType",
{ pattern = { "lua", "xml" }, callback = function() require('pwnvim.filetypes').lua() end, group = filetypes })
autocmd("FileType",
{ pattern = { "md", "markdown", "vimwiki" }, callback = function() require('pwnvim.markdown').setup() end,
group = filetypes })
autocmd("FileType",
{ pattern = { "rust" }, callback = function() require('pwnvim.filetypes').rust() end, group = filetypes })
autocmd("FileType",
{ pattern = { "Outline" }, command = "setlocal nospell", group = filetypes })
autocmd("TermOpen", { pattern = { "*" }, command = "setlocal nospell", group = filetypes })
-- Run when page pager is invoked
autocmd('User',
{ pattern = { 'PageOpen', 'PageOpenFile' }, group = filetypes,
callback = function() require('pwnvim.filetypes').page() end })
end
M.rust = function()
require('pwnvim.options').programming()
require('pwnvim.options').fourspaceindent()
vim.bo.makeprg = "cargo"
vim.cmd("compiler cargo")
vim.g.rustfmt_autosave = 1
vim.g.rust_fold = 1
vim.api.nvim_exec([[
augroup rustquickfix
autocmd!
autocmd BufReadPost quickfix setlocal foldmethod=expr
autocmd BufReadPost quickfix setlocal foldexpr=getline(v:lnum)[0:1]=='\|\|'
autocmd BufEnter quickfix setlocal foldexpr=getline(v:lnum)[0:1]=='\|\|'
autocmd BufReadPost quickfix setlocal foldlevel=0
augroup END
]], false)
end
M.c = function()
require('pwnvim.options').programming()
require('pwnvim.options').fourspaceindent()
vim.bo.makeprg = "make"
end
M.lua = function()
require('pwnvim.options').programming()
require('pwnvim.options').twospaceindent()
end
M.page = function()
-- disable status bar -- handled in config
-- map space to ctrl-f
vim.api.nvim_buf_set_keymap(0, 'n', '<space>',
'<PageDown>', {})
end
M.reloadFile = function()
require("plenary.reload").reload_module '%'
vim.cmd("luafile %")
end
return M

479
pwnvim/mappings.lua Normal file
View File

@@ -0,0 +1,479 @@
-- We use which-key in mappings, which is loaded before plugins, so set up here
local which_key = require("which-key")
which_key.setup({
plugins = {
marks = true, -- shows a list of your marks on ' and `
registers = true, -- shows your registers on " in NORMAL or <C-r> in INSERT mode
spelling = {
enabled = true, -- enabling this will show WhichKey when pressing z= to select spelling suggestions
suggestions = 20 -- how many suggestions should be shown in the list?
},
-- the presets plugin, adds help for a bunch of default keybindings in Neovim
-- No actual key bindings are created
presets = {
operators = true, -- adds help for operators like d, y, ... and registers them for motion / text object completion
motions = false, -- adds help for motions
text_objects = true, -- help for text objects triggered after entering an operator
windows = true, -- default bindings on <c-w>
nav = true, -- misc bindings to work with windows
z = true, -- bindings for folds, spelling and others prefixed with z
g = true -- bindings for prefixed with g
}
},
icons = {
breadcrumb = "»", -- symbol used in the command line area that shows your active key combo
separator = "", -- symbol used between a key and it's label
group = "+" -- symbol prepended to a group
},
popup_mappings = {
scroll_down = "<c-d>", -- binding to scroll down inside the popup
scroll_up = "<c-u>" -- binding to scroll up inside the popup
},
window = {
border = "rounded", -- none, single, double, shadow
position = "bottom", -- bottom, top
margin = { 1, 0, 1, 0 }, -- extra window margin [top, right, bottom, left]
padding = { 2, 2, 2, 2 }, -- extra window padding [top, right, bottom, left]
winblend = 0
},
layout = {
height = { min = 4, max = 25 }, -- min and max height of the columns
width = { min = 20, max = 50 }, -- min and max width of the columns
spacing = 3, -- spacing between columns
align = "left" -- align columns left, center or right
},
ignore_missing = true, -- enable this to hide mappings for which you didn't specify a label
hidden = {
"<silent>", "<CMD>", "<cmd>", "<Cmd>", "<cr>", "<CR>", "call", "lua",
"^:", "^ "
}, -- hide mapping boilerplate
show_help = true, -- show help message on the command line when the popup is visible
triggers = "auto" -- automatically setup triggers
-- triggers = {"<leader>"} -- or specify a list manually
})
-- This file is for mappings that will work regardless of filetype. Always available.
local options = { noremap = true, silent = true }
-- Make F1 act like escape for accidental hits
vim.api.nvim_set_keymap('', '#1', '<Esc>', options)
vim.api.nvim_set_keymap('!', '#1', '<Esc>', options)
-- TODO: try using the WinNew and WinClosed autocmd events with CHADtree filetype
-- to remap #2 to either open or close commands. Or BufDelete, BufAdd, BufWinLeave, BufWinEnter
-- Make F2 bring up a file browser
vim.api.nvim_set_keymap('', '#2', '<cmd>NvimTreeToggle<CR>', options)
vim.api.nvim_set_keymap('!', '#2', '<cmd>NvimTreeToggle<CR>', options)
vim.api.nvim_set_keymap('', '-', '<cmd>NvimTreeFindFile<CR>', options)
-- Make ctrl-p open a file finder
-- When using ctrl-p, screen out media files that we probably don't want
-- to open in vim. And if we really want, then we can use ,ff
vim.api
.nvim_set_keymap('', '<c-p>', ':silent Telescope find_files<CR>', options)
vim.api.nvim_set_keymap('!', '<c-p>', '<ESC>:silent Telescope find_files<CR>',
options)
-- Make F4 toggle showing invisible characters
vim.api
.nvim_set_keymap('', '_z', ':set list<CR>:map #4 _Z<CR>', { silent = true })
vim.api.nvim_set_keymap('', '_Z', ':set nolist<CR>:map #4 _z<CR>',
{ silent = true })
vim.api.nvim_set_keymap('', '#4', '_Z', {})
-- Enter the date on F8
vim.api.nvim_set_keymap('', '#8', '"=strftime("%Y-%m-%d")<CR>P', options)
vim.api.nvim_set_keymap('!', '#8', '<C-R>=strftime("%Y-%m-%d")<CR>', options)
-- Make F9 toggle distraction-free writing setup
vim.api.nvim_set_keymap('', '#9', ':TZAtaraxis<CR>', options)
vim.api.nvim_set_keymap('!', '#9', '<ESC>:TZAtaraxis<CR>', options)
-- Make F10 quicklook. Not sure how to do this best in linux so mac only for now
vim.api.nvim_set_keymap('', '<F10>', ':silent !qlmanage -p "%"<CR>', options)
vim.api.nvim_set_keymap('!', '<F10>', '<ESC>:silent !qlmanage -p "%"<CR>', options)
-- Make F12 restart highlighting
vim.api.nvim_set_keymap('', '<F12>', ':syntax sync fromstart<CR>', options)
vim.api
.nvim_set_keymap('!', '<F12>', '<C-o>:syntax sync fromstart<CR>', options)
-- Have ctrl-l continue to do what it did, but also temp clear search match highlighting
vim.api.nvim_set_keymap('', '<C-l>', ':<C-u>nohlsearch<CR><C-l>',
{ silent = true })
-- Yank to end of line using more familiar method
vim.api.nvim_set_keymap('', 'Y', 'y$', options)
-- Center screen vertically when navigating by half screens
vim.keymap.set("n", "<C-d>", "<C-d>zz")
vim.keymap.set("n", "<C-u>", "<C-u>zz")
-- Center search hits vertically on screen
vim.keymap.set("n", "n", "nzzzv")
vim.keymap.set("n", "N", "Nzzzv")
-- Move visually selected lines up and down
vim.keymap.set("v", "J", ":m '>+1<CR>gv=gv")
vim.keymap.set("v", "K", ":m '<-2<CR>gv=gv")
local global_leader_opts = {
mode = "n", -- NORMAL mode
prefix = "<leader>",
buffer = nil, -- Global mappings. Specify a buffer number for buffer local mappings
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local global_leader_opts_visual = {
mode = "v", -- VISUAL mode
prefix = "<leader>",
buffer = nil, -- Global mappings. Specify a buffer number for buffer local mappings
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local leader_mappings = {
["e"] = { "<cmd>NvimTreeToggle<cr>", "Explorer" },
["/"] = { "<cmd>nohlsearch<CR>", "No Highlight" },
["x"] = { "<cmd>Bdelete!<CR>", "Close Buffer" },
["q"] = {
[["<cmd>".(get(getqflist({"winid": 1}), "winid") != 0? "cclose" : "botright copen")."<cr>"]],
"Toggle Quicklist"
},
f = {
name = "Find",
f = { "<cmd>lua require('telescope.builtin').find_files()<CR>", "Files" },
g = { "<cmd>lua require('telescope.builtin').live_grep()<CR>", "Grep" },
b = {
"<cmd>lua require('telescope.builtin').buffers(require('telescope.themes').get_dropdown{previewer = false})<cr>",
"Buffers"
},
h = { "<cmd>lua require('telescope.builtin').oldfiles()<cr>", "History" },
q = { "<cmd>lua require('telescope.builtin').quickfix()<cr>", "Quickfix" },
l = { "<cmd>lua require('telescope.builtin').loclist()<cr>", "Loclist" },
p = { "<cmd>Telescope projects<cr>", "Projects" },
k = { "<cmd>Telescope keymaps<cr>", "Keymaps" },
t = { "<cmd>lua require('telescope.builtin').grep_string{search = \"^\\\\s*[*-] \\\\[ \\\\]\", previewer = false, glob_pattern = \"*.md\", use_regex = true, disable_coordinates=true}<cr>",
"Todos" },
n = { "<Cmd>ZkNotes { match = {vim.fn.input('Search: ')} }<CR>", "Find" },
},
-- Quickly change indent defaults in a file
i = {
name = "Indent",
["1"] = { "<cmd>lua require('pwnvim.options').tabindent()<CR>", "Tab" },
["2"] = {
"<cmd>lua require('pwnvim.options').twospaceindent()<CR>", "Two Space"
},
["4"] = {
"<cmd>lua require('pwnvim.options').fourspaceindent()<CR>",
"Four Space"
},
r = { "<cmd>%retab!<cr>", "Change existing indent to current with retab" }
},
g = {
name = "Git",
s = { "<cmd>lua require('telescope.builtin').git_status()<cr>", "Status" },
b = {
"<cmd>lua require('telescope.builtin').git_branches()<cr>",
"Branches"
},
c = {
"<cmd>lua require('telescope.builtin').git_commits()<cr>", "Commits"
},
h = { "<cmd>lua require 'gitsigns'.toggle_current_line_blame<cr>", "Toggle Blame" },
["-"] = { "<cmd>lua require 'gitsigns'.reset_hunk()<cr>", "Reset Hunk" },
["+"] = { "<cmd>lua require 'gitsigns'.stage_hunk()<cr>", "Stage Hunk" }
},
n = {
name = "Notes",
d = {
"<cmd>ZkNew { dir = vim.env.ZK_NOTEBOOK_DIR .. '/Calendar', title = os.date('%Y%m%d') }<CR>",
"New diary"
},
e = { "<cmd>!mv \"<cfile>\" \"<c-r>=expand('%:p:h')<cr>/\"<cr>", "Embed file moving to current file's folder" },
f = { "<Cmd>ZkNotes { match = {vim.fn.input('Search: ') }}<CR>", "Find" },
g = {
"<cmd>lua require('pwnvim.plugins').grammar_check()<cr>",
"Check Grammar"
},
h = { "<cmd>edit ~/Notes/Notes/HotSheet.md<CR>", "Open HotSheet" },
i = {
c = { "<cmd>r!/opt/homebrew/bin/icalBuddy --bullet '* ' --timeFormat '\\%H:\\%M' --dateFormat '' --noPropNames --noCalendarNames --excludeAllDayEvents --includeCals 'IC - Work' --includeEventProps datetime,title,attendees,location --propertyOrder datetime,title,attendees,location --propertySeparators '| |\\n * |\\n * | |' eventsToday<cr>",
"Insert today's calendar" },
o = { "<cmd>r!gtm-okr goals<cr>", "Insert OKRs" },
j = { "<cmd>r!( (curl -s https://icanhazdadjoke.com/ | grep '\\\"subtitle\\\"') || curl -s https://icanhazdadjoke.com/ ) | sed 's/<[^>]*>//g' | sed -z 's/\\n/ /'<cr>",
"Insert joke" },
},
m = {
"<cmd>lua require('zk.commands').get('ZkNew')({ dir = vim.fn.input({prompt='Folder: ',default=vim.env.ZK_NOTEBOOK_DIR .. '/Notes/meetings',completion='dir'}), title = vim.fn.input('Title: ') })<CR>",
"New meeting"
},
n = {
"<Cmd>ZkNew { dir = vim.fn.input({prompt='Folder: ',default=vim.env.ZK_NOTEBOOK_DIR .. '/Notes',completion='dir'}), title = vim.fn.input('Title: ') }<CR>",
"New"
},
o = { "<cmd>ZkNotes<CR>", "Open" },
t = { "<cmd>ZkTags<CR>", "Open by tag" },
-- in open note (defined in plugins.lua as local-only shortcuts):
-- p: new peer note
-- l: show outbound links
-- r: show outbound links
-- i: info preview
},
t = {
name = "Tasks",
--d = { "<cmd>lua require('pwnvim.tasks').completeTask()<cr>", "Done" },
d = { function() require('pwnvim.tasks').completeTaskDirect() end, "Done" },
c = { function() require('pwnvim.tasks').createTaskDirect() end, "Create" },
s = { function() require('pwnvim.tasks').scheduleTaskPrompt() end, "Schedule" },
t = { function() require('pwnvim.tasks').scheduleTaskTodayDirect() end, "Today" },
}
}
local leader_visual_mappings = {
t = {
name = "Tasks",
a = { ':grep "^\\s*[*-] \\[ \\] "<cr>:Trouble quickfix<cr>', "All tasks quickfix" },
--d = { function() require("pwnvim.tasks").eachSelectedLine(require("pwnvim.tasks").completeTask) end, "Done" },
d = { ":luado return require('pwnvim.tasks').completeTask(line)<cr>", "Done" },
s = { require("pwnvim.tasks").scheduleTaskBulk, "Schedule" },
-- s needs a way to call the prompt then reuse the value
--t = { function() require("pwnvim.tasks").eachSelectedLine(require("pwnvim.tasks").scheduleTaskToday) end, "Today" },
t = { ":luado return require('pwnvim.tasks').scheduleTaskToday(line)<cr>", "Today" },
},
n = {
e = { "\"0y:!mv \"<c-r>0\" \"<c-r>=expand('%:p:h')<cr>/\"<cr>", "Embed file moving to current file's folder" },
f = { ":'<,'>ZkMatch<CR>", "Find Selected" }
},
i = leader_mappings.i,
f = leader_mappings.f,
e = leader_mappings.e,
q = leader_mappings.q,
x = leader_mappings.x
}
which_key.register(leader_mappings, global_leader_opts)
which_key.register(leader_visual_mappings, global_leader_opts_visual)
vim.api.nvim_set_keymap('', '<leader>fd',
':silent Telescope lsp_document_symbols<CR>', options)
-- Set cwd to current file's dir
vim.api.nvim_set_keymap('', '<leader>cd', ':cd %:h<CR>', options)
vim.api.nvim_set_keymap('', '<leader>lcd', ':lcd %:h<CR>', options)
-- Debug syntax files
vim.api.nvim_set_keymap('', '<leader>sd',
[[:echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')<CR>]],
options)
-- """"""""" Global Shortcuts """""""""""""
vim.api.nvim_set_keymap('', '<D-j>', 'gj', options)
vim.api.nvim_set_keymap('', '<D-4>', 'g$', options)
vim.api.nvim_set_keymap('', '<D-6>', 'g^', options)
vim.api.nvim_set_keymap('', '<D-0>', 'g^', options)
-- Bubble lines up and down using the unimpaired plugin
vim.api.nvim_set_keymap('n', '<A-Up>', '[e', options)
vim.api.nvim_set_keymap('n', '<A-Down>', ']e', options)
vim.api.nvim_set_keymap('v', '<A-Up>', '[egv', options)
vim.api.nvim_set_keymap('v', '<A-Down>', ']egv', options)
-- Visually select the text that was last edited/pasted
-- Similar to gv but works after paste
vim.api.nvim_set_keymap('', 'gV', '`[v`]', options)
-- What do these do?
-- inoremap <C-U> <C-G>u<C-U>
-- nnoremap & :&&<CR>
-- xnoremap & :&&<CR>
-- Indent/outdent shortcuts
vim.api.nvim_set_keymap('n', '<D-[>', '<<', options)
vim.api.nvim_set_keymap('v', '<D-[>', '<gv', options)
vim.api.nvim_set_keymap('!', '<D-[>', '<C-o><<', options)
vim.api.nvim_set_keymap('n', '<D-]>', '>>', options)
vim.api.nvim_set_keymap('v', '<D-]>', '>gv', options)
vim.api.nvim_set_keymap('!', '<D-]>', '<C-o>>>', options)
-- keep visual block so you can move things repeatedly
vim.api.nvim_set_keymap('v', "<", "<gv", options)
vim.api.nvim_set_keymap('v', ">", ">gv", options)
-- TODO: this should be in programming setup
-- nmap <D-b> :make<CR>
-- imap <D-b> <C-o>:make<CR>
-- easy expansion of the active directory with %% on cmd
local options_nosilent = { noremap = true, silent = false }
vim.api.nvim_set_keymap('c', '%%', "<c-r>=expand('%:p:h')<cr>/", options_nosilent)
-- gx is a built-in to open URLs under the cursor, but when
-- not using netrw, it doesn't work right. Or maybe it's just me
-- but anyway this command works great.
-- /Users/pwalsh/Documents/md2rtf-style.html
-- ../README.md
-- ~/Desktop/Screen Shot 2018-04-06 at 5.19.32 PM.png
-- [abc](https://github.com/adsr/mle/commit/e4dc4314b02a324701d9ae9873461d34cce041e5.patch)
vim.api.nvim_set_keymap('', 'gx',
":silent !open \"<c-r><c-f>\" || xdg-open \"<c-r><c-f>\"<cr>",
options)
vim.api.nvim_set_keymap('v', 'gx',
"\"0y:silent !open \"<c-r>0\" || xdg-open \"<c-r>0\"<cr>gv",
options)
vim.api.nvim_set_keymap('', '<CR>',
":silent !open \"<c-r><c-f>\" || xdg-open \"<c-r><c-f>\"<cr>",
options)
vim.api.nvim_set_keymap('v', '<CR>',
"\"0y:silent !open \"<c-r>0\" || xdg-open \"<c-r>0\"<cr>gv",
options)
-- open/close folds with space bar
vim.api.nvim_set_keymap('', '<Space>',
[[@=(foldlevel('.')?'za':"\<Space>")<CR>]], options)
-- Make nvim terminal more sane
vim.api.nvim_set_keymap('t', '<Esc>', [[<C-\><C-n>]], options)
vim.api.nvim_set_keymap('t', '<M-[>', "<Esc>", options)
vim.api.nvim_set_keymap('t', '<C-v><Esc>', "<Esc>", options)
-- gui nvim stuff
-- Adjust font sizes
vim.api.nvim_set_keymap('', '<D-=>', [[:silent! let &guifont = substitute(
\ &guifont,
\ ':h\zs\d\+',
\ '\=eval(submatch(0)+1)',
\ '')<CR>]], options)
vim.api.nvim_set_keymap('', '<C-=>', [[:silent! let &guifont = substitute(
\ &guifont,
\ ':h\zs\d\+',
\ '\=eval(submatch(0)+1)',
\ '')<CR>]], options)
vim.api.nvim_set_keymap('', '<D-->', [[:silent! let &guifont = substitute(
\ &guifont,
\ ':h\zs\d\+',
\ '\=eval(submatch(0)-1)',
\ '')<CR>]], options)
vim.api.nvim_set_keymap('', '<C-->', [[:silent! let &guifont = substitute(
\ &guifont,
\ ':h\zs\d\+',
\ '\=eval(submatch(0)-1)',
\ '')<CR>]], options)
-- Need to map cmd-c and cmd-v to get natural copy/paste behavior
vim.api.nvim_set_keymap('n', '<D-v>', '"*p', options)
vim.api.nvim_set_keymap('v', '<D-v>', '"*p', options)
vim.api.nvim_set_keymap('!', '<D-v>', '<C-R>*', options)
vim.api.nvim_set_keymap('c', '<D-v>', '<C-R>*', options)
vim.api.nvim_set_keymap('v', '<D-c>', '"*y', options)
-- When pasting over selected text, keep original register value
vim.api.nvim_set_keymap('v', 'p', '"_dP', options)
-- cmd-w to close the current buffer
vim.api.nvim_set_keymap('', '<D-w>', ':bd<CR>', options)
vim.api.nvim_set_keymap('!', '<D-w>', '<ESC>:bd<CR>', options)
-- cmd-t or cmd-n to open a new buffer
vim.api.nvim_set_keymap('', '<D-t>', ':enew<CR>', options)
vim.api.nvim_set_keymap('!', '<D-t>', '<ESC>:enew<CR>', options)
vim.api.nvim_set_keymap('', '<D-n>', ':tabnew<CR>', options)
vim.api.nvim_set_keymap('!', '<D-n>', '<ESC>:tabnew<CR>', options)
-- cmd-s to save
vim.api.nvim_set_keymap('', '<D-s>', ':w<CR>', options)
vim.api.nvim_set_keymap('!', '<D-s>', '<ESC>:w<CR>', options)
-- cmd-q to quit
vim.api.nvim_set_keymap('', '<D-q>', ':q<CR>', options)
vim.api.nvim_set_keymap('!', '<D-q>', '<ESC>:q<CR>', options)
-- cmd-o to open
vim.api.nvim_set_keymap('', '<D-o>', ':Telescope file_browser cmd=%:h<CR>',
options)
vim.api.nvim_set_keymap('!', '<D-o>',
'<ESC>:Telescope file_browser cmd=%:h<CR>', options)
-- emacs bindings to jump around in lines
vim.api.nvim_set_keymap("i", "<C-e>", "<C-o>A", options)
vim.api.nvim_set_keymap("i", "<C-a>", "<C-o>I", options)
-- TODO:
-- Use ctrl-x, ctrl-u to complete :emoji: symbols, then use
-- ,e to turn it into a symbol if desired
-- vim.api.nvim_set_keymap('!', '<leader>e',
-- [[:%s/:\([^:]\+\):/\=emoji#for(submatch(1), submatch(0))/g<CR>]],
-- options)
-- Setup tpope unimpaired-like forward/backward shortcuts
which_key.register({
["[a"] = "Prev file arg",
["]a"] = "Next file arg",
["[b"] = { '<Cmd>BufferLineCyclePrev<CR>', "Prev buffer" },
["]b"] = { '<Cmd>BufferLineCycleNext<CR>', "Next buffer" },
["[c"] = "Prev git hunk",
["]c"] = "Next git hunk",
["[l"] = "Prev loclist item",
["]l"] = "Next loclist item",
["[q"] = "Prev quicklist item",
["]q"] = "Next quicklist item",
["[t"] = { '<Cmd>tabprevious<cr>', "Prev tab" },
["[T"] = { '<Cmd>tabprevious<cr>', "First tab" },
["]t"] = { '<Cmd>tabnext<cr>', "Next tab" },
["]T"] = { '<Cmd>tablast<cr>', "Last tab" },
["[n"] = "Prev conflict",
["]n"] = "Next conflict",
["[ "] = "Add blank line before",
["] "] = "Add blank line after",
["[e"] = "Swap line with previous",
["]e"] = "Swap line with next",
["[x"] = "XML encode",
["]x"] = "XML decode",
["[u"] = "URL encode",
["]u"] = "URL decode",
["[y"] = "C escape",
["]y"] = "C unescape",
["[d"] = { "<cmd>lua vim.diagnostic.goto_prev()<CR>", "Prev diagnostic" },
["]d"] = { "<cmd>lua vim.diagnostic.goto_next()<CR>", "Next diagnostic" },
["[1"] = { ':BufferLineGoToBuffer 1<CR>', "Go to buffer 1" },
["]1"] = { ':BufferLineGoToBuffer 1<CR>', "Go to buffer 1" },
["[2"] = { ':BufferLineGoToBuffer 2<CR>', "Go to buffer 2" },
["]2"] = { ':BufferLineGoToBuffer 2<CR>', "Go to buffer 2" },
["[3"] = { ':BufferLineGoToBuffer 3<CR>', "Go to buffer 3" },
["]3"] = { ':BufferLineGoToBuffer 3<CR>', "Go to buffer 3" },
["[4"] = { ':BufferLineGoToBuffer 4<CR>', "Go to buffer 4" },
["]4"] = { ':BufferLineGoToBuffer 4<CR>', "Go to buffer 4" },
["[5"] = { ':BufferLineGoToBuffer 5<CR>', "Go to buffer 5" },
["]5"] = { ':BufferLineGoToBuffer 5<CR>', "Go to buffer 5" },
["[6"] = { ':BufferLineGoToBuffer 6<CR>', "Go to buffer 6" },
["]6"] = { ':BufferLineGoToBuffer 6<CR>', "Go to buffer 6" },
["[7"] = { ':BufferLineGoToBuffer 7<CR>', "Go to buffer 7" },
["]7"] = { ':BufferLineGoToBuffer 7<CR>', "Go to buffer 7" },
["[8"] = { ':BufferLineGoToBuffer 8<CR>', "Go to buffer 8" },
["]8"] = { ':BufferLineGoToBuffer 8<CR>', "Go to buffer 8" },
["[9"] = { ':BufferLineGoToBuffer 9<CR>', "Go to buffer 9" },
["]9"] = { ':BufferLineGoToBuffer 9<CR>', "Go to buffer 9" },
["<S-h>"] = { ':BufferLineCyclePrev<CR>', "Go to next buffer" },
["<S-l>"] = { ':BufferLineCycleNext<CR>', "Go to prev buffer" },
}, { mode = 'n', silent = true })
-- Close buffer
vim.api.nvim_set_keymap('', '<D-w>', ':Bdelete<CR>', options)
vim.api.nvim_set_keymap('!', '<D-w>', '<ESC>:Bdelete<CR>', options)
vim.api.nvim_set_keymap('', '<A-w>', ':Bdelete<CR>', options)
vim.api.nvim_set_keymap('!', '<A-w>', '<ESC>:Bdelete<CR>', options)
vim.api.nvim_set_keymap('', '<M-w>', ':Bdelete<CR>', options)
vim.api.nvim_set_keymap('!', '<M-w>', '<ESC>:Bdelete<CR>', options)
-- Magic buffer-picking mode
vim.api.nvim_set_keymap('', '<M-b>', ':BufferPick<CR>', options)
vim.api.nvim_set_keymap('!', '<M-b>', '<ESC>:BufferPick<CR>', options)
vim.api.nvim_set_keymap('', '[0', ':BufferPick<CR>', options)
vim.api.nvim_set_keymap('', ']0', ':BufferPick<CR>', options)
vim.api.nvim_set_keymap('', '[\\', ':BufferPick<CR>', options)
vim.api.nvim_set_keymap('', ']\\', ':BufferPick<CR>', options)
-- Pane navigation integrated with tmux
vim.api.nvim_set_keymap('', '<c-h>', ':TmuxNavigateLeft<cr>', { silent = true })
vim.api.nvim_set_keymap('', '<c-j>', ':TmuxNavigateDown<cr>', { silent = true })
vim.api.nvim_set_keymap('', '<c-k>', ':TmuxNavigateUp<cr>', { silent = true })
vim.api.nvim_set_keymap('', '<c-l>', ':TmuxNavigateRight<cr>', { silent = true })
-- add mapping for :TmuxNavigatePrevious ? c-\, the default, used by toggleterm

250
pwnvim/markdown.lua Normal file
View File

@@ -0,0 +1,250 @@
local M = {}
M.setup = function()
local bufnr = vim.api.nvim_get_current_buf()
vim.g.joinspaces = true
vim.wo.number = false
vim.wo.relativenumber = false
vim.wo.spell = true
vim.wo.list = false
-- vim.bo.formatoptions = "jcroqln"
vim.wo.foldmethod = "expr"
vim.wo.foldexpr = "nvim_treesitter#foldexpr()"
vim.wo.foldlevel = 3
vim.wo.foldenable = true
vim.bo.formatoptions = 'jtqlnr' -- no c (insert comment char on wrap), with r (indent)
vim.bo.comments = 'b:>,b:*,b:+,b:-'
vim.bo.suffixesadd = '.md'
vim.bo.syntax = "off" -- we use treesitter exclusively on markdown now
require('pwnvim.markdown').markdownsyntax()
-- TODO: make all this whichkey instead
local opts = { noremap = false, silent = true }
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(0, ...) end
-- normal mode mappings
require("which-key").register(
{
["<leader>"] = {
m = { ':silent !open -a Marked\\ 2.app "%:p"<cr>', "Open Marked preview" },
},
["gl*"] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/* /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>2l]], "Add bullets" },
["gl>"] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/> /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>2l]], "Add quotes" },
["gl["] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/* [ ] /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>5l]], "Add task" },
["gt"] = { "<cmd>lua require('pwnvim.markdown').transformUrlUnderCursorToMdLink()<cr>", "Convert URL to link" },
["gp"] = { require('pwnvim.markdown').pasteUrl, "Paste URL as link" },
["<C-M-v>"] = { require('pwnvim.markdown').pasteUrl, "Paste URL as link" },
}, { mode = "n", buffer = bufnr, silent = true, noremap = true }
)
-- insert mode mappings
require("which-key").register(
{
["<C-M-v>"] = { require('pwnvim.markdown').pasteUrl, "Paste URL as link" },
}, { mode = "i", buffer = bufnr, silent = true, noremap = true }
)
-- visual mode mappings
require("which-key").register(
{
["<leader>"] = {
m = { ':silent !open -a Marked\\ 2.app "%:p"<cr>', "Open Marked preview" },
},
["gl*"] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/* /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>gv]], "Add bullets" },
["gl>"] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/> /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>gv]], "Add quotes" },
["gl["] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/* [ ] /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>gv]], "Add task" },
["gt"] = { "<cmd>lua require('pwnvim.markdown').transformUrlUnderCursorToMdLink()<cr>", "Convert URL to link" }
}, { mode = "v", buffer = bufnr, silent = true, noremap = true }
)
--Leave F7 at SymbolOutline which happens when zk LSP attaches
--buf_set_keymap('', '#7', ':Toc<CR>', opts)
--buf_set_keymap('!', '#7', '<ESC>:Toc<CR>', opts)
--TODO: add [t ]t for navigating tasks (instead of tabs) -- but can it work between files?
--TODO: add desc to opts
--buf_set_keymap('i', '#', '<plug>(mkdx-link-compl)', opts)
--buf_set_keymap('', '][', '<Plug>Markdown_MoveToNextSiblingHeader', opts)
--buf_set_keymap('', '[]', '<Plug>Markdown_MoveToPreviousSiblingHeader', opts)
--buf_set_keymap('', ']u', '<Plug>Markdown_MoveToParentHeader', opts)
--buf_set_keymap('', ']c', '<Plug>Markdown_MoveToCurHeader', opts)
--buf_set_keymap('', 'ge', '<Plug>Markdown_EditUrlUnderCursor', opts)
-- Handle cmd-b for bold
buf_set_keymap('!', '<D-b>', '****<C-O>h', opts)
buf_set_keymap('v', '<D-b>', 'Se', opts)
--buf_set_keymap('v', '<leader>b', 'S*gvS*', opts)
buf_set_keymap('v', '<leader>b', 'Se', opts) -- e is an alias configured at surround setup and equal to **
buf_set_keymap('n', '<D-b>', 'ysiwe', opts)
buf_set_keymap('n', '<leader>b', 'ysiwe', opts)
-- Handle cmd-i for italic
buf_set_keymap('!', '<D-i>', [[__<C-O>h]], opts)
buf_set_keymap('v', '<D-i>', 'S_', opts)
buf_set_keymap('v', '<leader>i', 'S_', opts)
buf_set_keymap('n', '<D-i>', 'ysiw_', opts)
buf_set_keymap('n', '<leader>i', 'ysiw_', opts)
-- Handle cmd-1 for inline code blocks (since cmd-` has special meaning already)
buf_set_keymap('!', '<D-1>', [[``<C-O>h]], opts)
buf_set_keymap('v', '<D-1>', 'S`', opts)
buf_set_keymap('v', '<leader>`', 'S`', opts)
buf_set_keymap('n', '<D-1>', 'ysiw`', opts)
buf_set_keymap('n', '<leader>`', 'ysiw`', opts)
-- Handle cmd-l and ,l for adding a link
buf_set_keymap('v', '<D-l>', 'S]%a(', opts)
buf_set_keymap('v', '<leader>l', 'S]%a(', opts)
buf_set_keymap('n', '<D-l>', 'ysiW]%a(', opts)
buf_set_keymap('n', '<leader>l', 'ysiW]%a(', opts)
buf_set_keymap('i', '<tab>', "<cmd>lua require('pwnvim.markdown').indent()<cr>", opts)
buf_set_keymap('i', '<s-tab>', "<cmd>lua require('pwnvim.markdown').outdent()<cr>", opts)
-- no idea why the lua version of adding the command is failing
-- vim.api.nvim_buf_add_user_command(0, 'PasteUrl', function(opts) require('pwnvim.markdown').pasteUrl() end, {})
vim.cmd("command! PasteUrl lua require('pwnvim.markdown').pasteUrl()")
-- This is wonderful when it's working, but I sometimes get too many open files errors that seem to come from this plugin. Plus
-- some weirdness where my entire terminal (kitty) completely hangs for a time. Especially when typing in an alt description.
-- So, sadly, commenting out for now. 2023-01-19
-- if vim.env.KITTY_INSTALLATION_DIR and not vim.g.neovide then
-- vim.cmd('packadd hologram.nvim')
-- require('hologram').setup {
-- auto_display = true -- WIP automatic markdown image display, may be prone to breaking
-- }
-- end
vim.cmd('packadd clipboard-image.nvim')
require 'clipboard-image'.setup {
default = {
img_name = function()
vim.fn.inputsave()
local name = vim.fn.input({ prompt = "Name: " })
-- TODO: swap spaces out for dashes
vim.fn.inputrestore()
return os.date('%Y-%m-%d') .. "-" .. name
end,
img_dir = { "%:p:h", "%:t:r:s?$?_attachments?" },
img_dir_txt = "%:t:r:s?$?_attachments?",
-- TODO: can I put the name as the title somehow?
affix = "![](%s)",
}
}
-- I have historically always used spaces for indents wherever possible including markdown
-- Changing now to use tabs because NotePlan 3 can't figure out nested lists that are space
-- indented and I go back and forth between that and nvim (mainly for iOS access to notes).
-- So, for now, this is the compatibility compromise. 2022-09-27
require('pwnvim.options').tabindent()
require('pwnvim.options').retab() -- turn spaces to tabs when markdown file is opened
end
M.markdownsyntax = function()
vim.api.nvim_exec([[
" markdownWikiLink is a new region
"syn region markdownWikiLink matchgroup=markdownLinkDelimiter start="\[\[" end="\]\]" contains=markdownUrl keepend oneline concealends
" markdownLinkText is copied from runtime files with 'concealends' appended
"syn region markdownLinkText matchgroup=markdownLinkTextDelimiter start="!\=\[\%(\%(\_[^][]\|\[\_[^][]*\]\)*]\%( \=[[(]\)\)\@=" end="\]\%( \=[[(]\)\@=" nextgroup=markdownLink,markdownId skipwhite contains=@markdownInline,markdownLineStart concealends
" markdownLink is copied from runtime files with 'conceal' appended
"syn region markdownLink matchgroup=markdownLinkDelimiter start="(" end=")" contains=markdownUrl keepend contained conceal
" syn match markdownTag '#\w\+'
" syn cluster markdownInline add=markdownTag
" Edit htmlTag to ignore tags starting with a number like <2022
" syn region htmlTag start=+<[^/0-9]+ end=+>+ fold contains=htmlTagN,htmlString,htmlArg,htmlValue,htmlTagError,htmlEvent,htmlCssDefinition,@htmlPreproc,@htmlArgCluster
" syn match mkdListItemCheckbox /\[[xXoO\> -]\]\ze\s\+/ contained contains=mkdListItem
let m = matchadd("bareLink", "\\<https:[a-zA-Z?&,;=$+%#/.!~':@0-9_-]*")
" let m = matchadd("markdownCheckboxChecked", "[*-] \\[x\\] ")
let m = matchadd("markdownCheckboxCanceled", "[*-] \\[-\\] .\\+")
let m = matchadd("markdownCheckboxPostponed", "[*-] \\[>\\] .\\+")
" below is because Noteplan uses capital X and default styling is a link on [X] so this will at least make it green
let m = matchadd("@text.todo.checked", "[*-] \\[[xX]\\] ")
let m = matchadd("markdownTag", '#\w\+')
let m = matchadd("markdownStrikethrough", "\\~\\~[^~]*\\~\\~")
let m = matchadd("doneTag", '@done(20[^)]*)')
let m = matchadd("highPrioTask", "[*-] \\[ \\] .\\+!!!")
]], false)
end
local check_backspace = function()
local col = vim.fn.col "." - 1
return col == 0 or vim.fn.getline(vim.fn.line(".")):sub(col, col):match "%s"
end
M.indent = function()
local line = vim.api.nvim_get_current_line()
if line:match("^%s*[*-]") then
local ctrlt = vim.api.nvim_replace_termcodes("<C-t>", true, false, true)
vim.api.nvim_feedkeys(ctrlt, "n", false)
--line = "\t" .. line
--vim.api.nvim_set_current_line(line)
--vim.cmd("normal l")
-- local norm_mode = vim.api.nvim_replace_termcodes("<C-o>", true, false, true)
-- local shiftwidth = vim.bo.shiftwidth + 1
-- vim.api.nvim_feedkeys(norm_mode .. ">>", "n", false)
-- vim.api.nvim_feedkeys(norm_mode .. shiftwidth .. "l", "n", false)
elseif check_backspace() then
-- we are at first col or there is whitespace immediately before cursor
-- send through regular tab character at current position
vim.api.nvim_feedkeys("\t", "n", false)
else
require 'cmp'.mapping.complete({})
end
end
M.outdent = function()
local line = vim.api.nvim_get_current_line()
if line:match("^%s*[*-]") then
local ctrld = vim.api.nvim_replace_termcodes("<C-d>", true, false, true)
vim.api.nvim_feedkeys(ctrld, "n", false)
-- TODO: shift width is correct if at least that many characters are between us and last column
-- but if we're on last column already, we'll auto move and compensate should be 0
-- local col = vim.api.nvim_win_get_cursor(0)
--local shiftwidth = vim.bo.shiftwidth
--vim.api.nvim_feedkeys(norm_mode .. "<<", "n", false)
--vim.api.nvim_feedkeys(norm_mode .. shiftwidth .. "h", "n", false)
end
end
M.getTitleFor = function(url)
local curl = require "plenary.curl"
if not string.match(url, "^https?:[^%s]*$") then
return "" -- doesn't look like a URL -- avoid curl sadness
end
local res = curl.request {
url = url,
method = "get",
accept = "text/html",
raw = { "-L" } -- follow redirects
}
local title = ""
if res then
title = string.match(res.body, "<title[^>]*>([^<]+)</title>")
if not title then
title = string.match(res.body, "<h1[^>]*>([^<]+)</h1>")
end
end
if not title then
title = "could not get title" -- TODO: put domain here
end
return title
end
M.transformUrlUnderCursorToMdLink = function()
--local url = vim.fn.expand("<cfile>")
local url = vim.fn.expand("<cWORD>")
local title = require("pwnvim.markdown").getTitleFor(url)
vim.cmd("normal! ciW[" .. title .. "](" .. url .. ")")
end
M.pasteUrl = function()
local url = vim.fn.getreg('*')
local title = require("pwnvim.markdown").getTitleFor(url)
vim.cmd("normal! a[" .. title .. "](" .. url .. ")")
-- cursor ends up one to the left, so move over right one if possible
local right = vim.api.nvim_replace_termcodes("<right>", true, false, true)
vim.api.nvim_feedkeys(right, "n", false)
end
return M

427
pwnvim/options.lua Normal file
View File

@@ -0,0 +1,427 @@
local M = {}
SimpleUI = (os.getenv("SIMPLEUI") == "1" or os.getenv("TERM_PROGRAM") ==
"Apple_Terminal" or os.getenv("TERM") == "linux") and
not vim.g.neovide
M.defaults = function()
-- disable builtin vim plugins
vim.g.loaded_gzip = 0
vim.g.loaded_tar = 0
vim.g.loaded_tarPlugin = 0
vim.g.loaded_zipPlugin = 0
vim.g.loaded_2html_plugin = 0
vim.g.loaded_netrw = 1 -- disable netrw
vim.g.loaded_netrwPlugin = 1 -- disable netrw
-- we just use lua plugins here so disable others
vim.g.loaded_perl_provider = 0
vim.g.loaded_node_provider = 0
vim.g.loaded_python3_provider = 0
vim.g.loaded_ruby_provider = 0
-- vim.g.loaded_matchit = 0
-- vim.g.loaded_matchparen = 0
vim.g.loaded_spec = 0
vim.g.vim_markdown_no_default_key_mappings = 1
vim.g.markdown_folding = 1
vim.g.vim_markdown_strikethrough = 1
vim.g.vim_markdown_auto_insert_bullets = 1
vim.g.vim_markdown_new_list_item_indent = 0
vim.g.vim_markdown_conceal = 1
vim.g.vim_markdown_math = 0
vim.g.vim_markdown_conceal_code_blocks = 0
vim.g.vim_markdown_frontmatter = 1
vim.g.db_ui_use_nerd_fonts = true
-- this would allow spaces in filenames for commands like `gf` but results are really mixed.
-- commenting for now 2022-12-22
-- vim.opt.isfname:append { "32" }
vim.opt.grepprg =
"rg\\ --vimgrep\\ --no-heading\\ --smart-case\\ --color\\ never"
vim.opt.grepformat = "%f:%l:%c:%m,%f:%l:%m,%f"
-- ignore completions and menus for the below
vim.opt.wildignore =
"*/node_modules/*,_site,*/__pycache__/,*/venv/*,*/target/*,*/.vim$,\\~$,*/.log,*/.aux,*/.cls,*/.aux,*/.bbl,*/.blg,*/.fls,*/.fdb*/,*/.toc,*/.out,*/.glo,*/.log,*/.ist,*/.fdb_latexmk,*.bak,*.o,*.a,*.sw?,.git/,*.class,.direnv/,.DS_Store"
vim.opt.wildmenu = true -- cmd line completion a-la zsh
vim.opt.wildmode = "list:longest" -- matches mimic that of bash or zsh
vim.opt.swapfile = false
vim.opt.spell = true
vim.opt.spelllang = "en_us"
vim.opt.ruler = true -- show the cursor position all the time
vim.opt.cursorline = true -- add indicator for current line
vim.opt.secure = true -- don't execute shell cmds in .vimrc not owned by me
vim.opt.history = 50 -- keep 50 lines of command line history
vim.opt.shell = "zsh"
vim.opt.modelines = 0 -- Don't allow vim settings embedded in text files for security reasons
vim.opt.showcmd = true -- display incomplete commands
vim.opt.showmode = true -- display current mode
-- with backup off and writebackup on: backup current file, deleted afterwards
vim.opt.backup = false
vim.opt.writebackup = true
vim.opt.backupcopy = "auto"
vim.opt.hidden = true
vim.opt.cf = true -- jump to errors based on error files
vim.o.listchars = "tab:⇥ ,trail:␣,extends:⇉,precedes:⇇,nbsp:·"
vim.opt.list = true -- render special chars (tabs, trails, ...)
vim.opt.ttyfast = true
vim.opt.expandtab = true
vim.opt.splitbelow = true -- allow splits below
vim.opt.splitright = true -- and to the right
vim.opt.dictionary:append { '/usr/share/dict/words', '~/.aspell.english.pws' }
vim.opt.complete = vim.opt.complete + { 'k', ']' }
vim.opt.complete = vim.opt.complete - { 'i' }
vim.opt.encoding = "utf-8"
vim.opt.backspace = "indent,eol,start" -- allow backspacing over everything in insert mode
vim.opt.joinspaces = false -- don't insert two spaces after sentences on joins
vim.opt.binary = false
vim.opt.display = "lastline"
vim.opt.viewoptions = "folds,cursor,unix,slash" -- better unix / windows compatibility
vim.o.shortmess = "filnxtToSAcOF"
vim.opt.foldnestmax = 5
-- wrapping
vim.opt.wrap = true
vim.opt.sidescroll = 2 -- min number of columns to scroll from edge
vim.opt.scrolloff = 8 -- when 4 away from edge start scrolling
vim.opt.sidescrolloff = 8 -- keep cursor one col from end of line
vim.opt.textwidth = 0
vim.opt.breakindent = true
vim.opt.showbreak = "» "
vim.opt.breakat:remove { '/', '*', '_', '`' }
vim.opt.linebreak = true -- wraps on word boundaries but only if nolist is set
-- Make tabs be spaces of 4 characters by default
vim.opt.tabstop = 4
vim.opt.shiftwidth = 4
vim.opt.softtabstop = 4
vim.opt.expandtab = true -- turn tabs to spaces by default
vim.opt.autoindent = true -- autoindent to same level as previous line
vim.opt.smartindent = true -- indent after { and cinwords words
vim.opt.smartcase = true -- intelligently ignore case in searches
vim.opt.ignorecase = true -- default to not being case sensitive
vim.opt.smarttab = true
vim.opt.icm = "nosplit" -- show substitutions as you type
vim.opt.hlsearch = true
vim.opt.updatetime = 250 -- Decrease update time
vim.wo.signcolumn = 'yes'
vim.opt.visualbell = true
vim.opt.autoread = true -- auto reload files changed on disk if not changed in buffer
vim.opt.cursorline = false
vim.opt.ttyfast = true
vim.opt.formatoptions = 'jcroqlt' -- t=text, c=comments, q=format with "gq"
vim.opt.showmatch = true -- auto hilights matching bracket or paren
vim.opt.nrformats = vim.opt.nrformats - { 'octal' }
vim.opt.shiftround = true
vim.opt.ttimeout = true
vim.opt.ttimeoutlen = 50
vim.opt.fileformats = "unix,dos,mac"
vim.o.matchpairs = "(:),{:},[:],<:>"
vim.opt.number = false
vim.opt.relativenumber = false
-- noinsert: don't insert until selection made, noselect: don't select automatically
vim.opt.completeopt = "menu,menuone,noinsert,noselect" -- needed for autocompletion stuff
vim.opt.conceallevel = 2
vim.opt.fileencoding = "utf-8"
-- Globals
vim.g.vimsyn_embed = 'l' -- Highlight Lua code inside .vim files
-- vim.g.polyglot_disabled = { 'sensible', 'autoindent' } -- preserve in case I want to bring back polyglot
vim.g.foldlevelstart = 3
-- map the leader key
vim.api.nvim_set_keymap('n', ',', '', {})
vim.g.mapleader = ',' -- Namespace for custom shortcuts
if not SimpleUI then
vim.g.termguicolors = true
vim.o.termguicolors = true
else
vim.g.termguicolors = false
vim.o.termguicolors = false
end
vim.o.background = "dark"
if not SimpleUI then
require("onedarkpro").setup({
-- Call :OnedarkproCache if you make changes below and to speed startups
caching = true,
highlights = {
mkdLink = { fg = "${blue}", style = "underline" },
bareLink = { fg = "${blue}", style = "underline" },
mkdURL = { fg = "${green}", style = "underline" },
mkdInlineURL = { fg = "${blue}", style = "underline" },
mkdListItem = { fg = "${cyan}" },
markdownListMarker = { fg = "${cyan}" },
mkdListItemCheckbox = { fg = "${green}" },
-- markdownCheckbox = { fg = "${purple}" },
-- markdownCheckboxUnchecked = { fg = "${purple}" },
-- markdownCheckboxChecked = { fg = "${green}" },
markdownCheckboxCanceled = {
fg = "${comment}",
style = "strikethrough"
},
markdownCheckboxPostponed = { fg = "${comment}" },
markdownStrikethrough = {
fg = "${comment}",
style = "strikethrough"
},
markdownTag = { fg = "${comment}" },
doneTag = { fg = "${comment}", style = "italic" },
highPrioTask = { fg = "${red}", style = "bold" },
-- mkdLinkTitle
-- mkdID
-- mkdDelimiter
-- mkdInlineURL
-- mkdCode
-- mkdFootnote
-- mkdMath
-- htmlLink
TSURI = { fg = "${blue}", style = "underline" },
TSPunctSpecial = { fg = "${red}" },
markdownTSTitle = { fg = "${cyan}", style = "bold" },
markdownAutomaticLink = { fg = "${blue}", style = "underline" },
markdownLink = { fg = "${green}", style = "underline" },
markdownLinkText = { fg = "${blue}", style = "underline" },
markdownUrl = { fg = "${green}", style = "underline" },
markdownWikiLink = { fg = "${blue}", style = "underline" },
markdownH1 = { fg = "${yellow}", style = "bold" },
markdownH2 = { fg = "${yellow}", style = "bold" },
markdownH3 = { fg = "${yellow}" },
markdownH4 = { fg = "${green}", style = "italic" },
markdownH5 = { fg = "${green}", style = "italic" },
markdownH6 = { fg = "${green}", style = "italic" },
htmlH1 = { fg = "${yellow}", style = "bold" },
htmlH2 = { fg = "${yellow}", style = "bold" },
htmlH3 = { fg = "${yellow}" },
htmlH4 = { fg = "${green}", style = "italic" },
htmlH5 = { fg = "${green}", style = "italic" },
htmlH6 = { fg = "${green}", style = "italic" },
markdownBold = { fg = "#ffffff", style = "bold" },
htmlBold = { fg = "#ffffff", style = "bold" },
markdownItalic = { fg = "#eeeeee", style = "italic" },
htmlItalic = { fg = "#eeeeee", style = "italic" },
markdownBoldItalic = { fg = "#ffffff", style = "bold,italic" },
htmlBoldItalic = { fg = "#ffffff", style = "bold,italic" },
SpellBad = { style = "undercurl", sp = "${red}" },
SpellCap = { style = "undercurl", sp = "${cyan}" },
SpellRare = { style = "undercurl", sp = "Magenta" },
SpellLocal = { style = "undercurl", sp = "${cyan}" },
IndentBlanklineChar = { fg = "#444444" },
-- Todo = { fg = "#282c34", bg = "${highlight}", style = "bold" },
VertSplit = { fg = "#202020", bg = "#606060" },
Folded = { fg = "#c0c8d0", bg = "#384058" },
["@comment.markdown"] = { fg = "${comment}" },
["@field.markdown_inline"] = { fg = "${purple}" },
["@text.literal.markdown_inline"] = { fg = "${green}" },
["@text.reference.markdown_inline"] = {
fg = "${blue}",
style = "underline"
},
["@text.underline"] = { style = "underline" },
["@text.strong.markdown_inline"] = {
fg = "#ffffff",
style = "bold"
},
["@text.emphasis.markdown_inline"] = {
fg = "#eeeeee",
style = "italic"
},
["@strikethrough.markdown_inline"] = {
fg = "${comment}",
style = "strikethrough"
},
["@tag"] = { fg = "${comment}" },
["@block_quote.markdown"] = { fg = "${purple}", style = "italic" },
["@text.title.markdown"] = { fg = "${yellow}", style = "bold" },
-- ["@parameter.markdown_inline"] = { fg = theme.palette.fg },
["@punctuation.special.markdown"] = { fg = "${cyan}" },
["@punctuation.delimiter.markdown_inline"] = { fg = "${orange}" },
["@text.uri.markdown_inline"] = { fg = "${blue}" },
["@text.todo.unchecked"] = {
fg = "#ffffff",
bg = "",
style = "bold"
},
["@text.todo.checked"] = { fg = "${green}", style = "bold" },
TelescopeBorder = {
fg = "${telescope_results}",
bg = "${telescope_results}"
},
TelescopePromptBorder = {
fg = "${telescope_prompt}",
bg = "${telescope_prompt}"
},
TelescopePromptCounter = { fg = "${fg}" },
TelescopePromptNormal = {
fg = "${fg}",
bg = "${telescope_prompt}"
},
TelescopePromptPrefix = {
fg = "${purple}",
bg = "${telescope_prompt}"
},
TelescopePromptTitle = {
fg = "${telescope_prompt}",
bg = "${purple}"
},
TelescopePreviewTitle = {
fg = "${telescope_results}",
bg = "${green}"
},
TelescopeResultsTitle = {
fg = "${telescope_results}",
bg = "${telescope_results}"
},
TelescopeMatching = { fg = "${blue}" },
TelescopeNormal = { bg = "${telescope_results}" },
TelescopeSelection = { bg = "${telescope_prompt}" }
},
styles = { -- Choose from "bold,italic,underline"
virtual_text = "italic" -- Style that is applied to virtual text
},
plugins = { all = true },
options = {
bold = not SimpleUI,
italic = not SimpleUI,
underline = not SimpleUI,
undercurl = not SimpleUI,
cursorline = true,
transparency = false,
terminal_colors = false,
highlight_inactive_windows = true
},
colors = {
onedark = {
telescope_prompt = "#2e323a",
telescope_results = "#21252d"
},
onelight = {
telescope_prompt = "#f5f5f5",
telescope_results = "#eeeeee"
}
}
})
end
local cscheme
if SimpleUI then
cscheme = "ir_black"
else
cscheme = "onedark"
end
vim.cmd("colorscheme " .. cscheme)
vim.api.nvim_exec([[
filetype plugin indent on
syntax on
syntax sync minlines=5000
]], false)
-- Brief highlight on yank
vim.api.nvim_exec([[
augroup YankHighlight
autocmd!
autocmd TextYankPost * silent! lua vim.highlight.on_yank()
augroup end
]], false)
end
M.gui = function()
vim.opt.title = true
vim.opt.switchbuf = "useopen,usetab,newtab"
-- vim.opt.guifont = "Liga DejaVuSansMono Nerd Font:h16"
-- vim.opt.guifont = "FiraCode Nerd Font:h16" -- no italics
-- if vim.loop.os_uname().sysname == "Darwin" then
if vim.fn.has('mac') == 1 then
vim.opt.guifont = "Hasklug Nerd Font:h18"
else
vim.opt.guifont = "Hasklug Nerd Font:h9"
end
vim.g.neovide_transparency = 0.92
vim.g.neovide_cursor_animation_length = 0.01
vim.g.neovide_cursor_trail_length = 0.1
vim.g.neovide_cursor_antialiasing = true
vim.g.neovide_refresh_rate = 60
vim.g.neovide_remember_window_size = true
vim.g.neovide_input_macos_alt_is_meta = false
vim.g.neovide_hide_mouse_when_typing = false
vim.opt.mouse = "nv" -- only use mouse in normal and visual modes (notably not insert and command)
vim.opt.mousemodel = "popup_setpos"
-- use the system clipboard for all unnamed yank operations
vim.opt.clipboard = "unnamedplus"
vim.cmd([[set guioptions="gmrLae"]])
-- nvim-qt options
-- Disable GUI Tabline
vim.api.nvim_exec([[
if exists(':GuiTabline')
GuiTabline 0
endif
]], false)
end
M.twospaceindent = function()
vim.bo.textwidth = 0
vim.bo.tabstop = 2
vim.bo.shiftwidth = 2
vim.bo.softtabstop = 2
vim.bo.expandtab = true -- turn tabs to spaces by default
vim.bo.autoindent = true
-- vim.cmd('retab')
end
M.fourspaceindent = function()
vim.bo.textwidth = 0
vim.bo.tabstop = 4
vim.bo.shiftwidth = 4
vim.bo.softtabstop = 4
vim.bo.expandtab = true -- turn tabs to spaces by default
vim.bo.autoindent = true
-- vim.cmd('retab')
end
M.tabindent = function()
vim.bo.textwidth = 0
vim.bo.tabstop = 4
vim.bo.shiftwidth = 4
vim.bo.softtabstop = 4
vim.bo.expandtab = false -- don't turn tabs to spaces
vim.bo.autoindent = true
end
M.retab = function() vim.cmd('%retab!') end
M.programming = function()
vim.opt.number = true
vim.wo.number = true
vim.wo.spell = false
vim.wo.relativenumber = false
vim.wo.cursorline = true -- add indicator for current line
M.twospaceindent()
-- Could be a performance penalty on this
-- Will make periodic checks to see if the file changed
vim.api.nvim_exec([[
augroup programming
autocmd!
autocmd CursorHold,CursorHoldI * silent! checktime
augroup END
]], false)
-- Load direnv when we're in a programming file as we may want
-- the nix environment provided. Run explicitly since the autocmds
-- might not otherwise fire.
vim.cmd('packadd direnv.vim')
vim.cmd('DirenvExport')
end
return M

872
pwnvim/plugins.lua Normal file
View File

@@ -0,0 +1,872 @@
-- This is a mega file. Rather than make each plugin have its own config file,
-- which is how I managed my packer-based nvim config prior to Nix, I'm
-- putting everything in here in sections and themed functions. It just makes it
-- easier for me to quickly update things and it's cleaner when there's
-- interdependencies between plugins. We'll see how it goes.
local M = {}
local signs = require("pwnvim.signs")
----------------------- UI --------------------------------
-- Tree, GitSigns, Indent markers, Colorizer, bufferline, lualine, treesitter
M.ui = function()
-- following options are the default
-- each of these are documented in `:help nvim-tree.OPTION_NAME`
-- local nvim_tree_config = require("nvim-tree.config")
-- local tree_cb = nvim_tree_config.nvim_tree_callback
require("pwnvim.plugins.nvim-tree")
require("nvim-surround").setup({
aliases = {
["e"] = "**" -- e for emphasis -- bold in markdown
}
})
require("pwnvim.plugins.todo-comments")
require("pwnvim.plugins.gitsigns")
require("diffview").setup {}
if not SimpleUI then require("colorizer").setup({}) end
require("pwnvim.plugins.lualine")
require("pwnvim.plugins.treesitter")
require("pwnvim.plugins.bufferline")
end -- UI setup
----------------------- DIAGNOSTICS --------------------------------
M.diagnostics = function()
-- IMPORTANT: make sure to setup neodev BEFORE lspconfig
require("neodev").setup({
-- help for neovim lua api
override = function(root_dir, library)
if string.match(root_dir, "neovim") or
string.match(root_dir, "pwnvim") or
string.match(root_dir, "lua") then
library.enabled = true
library.plugins = true
library.types = true
library.runtime = true
end
end,
lspconfig = true
})
require "fidget".setup {} -- shows status of lsp clients as they issue updates
vim.diagnostic.config({
virtual_text = false,
signs = { active = { signs.signs } },
update_in_insert = true,
underline = true,
severity_sort = true,
float = {
focusable = false,
style = "minimal",
border = "rounded",
source = "always",
header = "",
prefix = ""
}
})
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(
vim.lsp.handlers.hover,
{ border = "rounded" })
vim.lsp.handlers["textDocument/signatureHelp"] =
vim.lsp.with(vim.lsp.handlers.signature_help, { border = "rounded" })
require("trouble").setup {
group = true, -- group results by file
icons = true,
auto_preview = true,
signs = {
error = signs.error,
warning = signs.warn,
hint = signs.hint,
information = signs.info,
other = ""
}
}
local function attached(client, bufnr)
local function buf_set_keymap(...)
vim.api.nvim_buf_set_keymap(bufnr, ...)
end
local opts = { noremap = true, silent = false }
if client.name == "tsserver" or client.name == "jsonls" or client.name ==
"nil" or client.name == "eslint" or client.name == "html" or
client.name == "cssls" or client.name == "tailwindcss" then
-- Most of these are being turned off because prettier handles the use case better
client.server_capabilities.documentFormattingProvider = false
client.server_capabilities.documentRangeFormattingProvider = false
else
client.server_capabilities.documentFormattingProvider = true
client.server_capabilities.documentRangeFormattingProvider = true
require("lsp-format").on_attach(client)
end
print("LSP attached " .. client.name)
vim.api.nvim_buf_set_option(bufnr, "formatexpr",
"v:lua.vim.lsp.formatexpr()")
vim.api.nvim_buf_set_option(bufnr, "omnifunc", "v:lua.vim.lsp.omnifunc")
vim.api.nvim_buf_set_option(bufnr, "tagfunc", "v:lua.vim.lsp.tagfunc")
local which_key = require("which-key")
local local_leader_opts = {
mode = "n", -- NORMAL mode
prefix = "<leader>",
buffer = bufnr, -- Local mappings.
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local local_leader_opts_visual = {
mode = "v", -- VISUAL mode
prefix = "<leader>",
buffer = bufnr, -- Local mappings.
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
require("symbols-outline").setup({
keymaps = { close = { "<Esc>", "q", "#7" } }
})
local leader_mappings = {
["q"] = { "<cmd>TroubleToggle<CR>", "Show Trouble list" },
l = {
name = "Local LSP",
s = { "<cmd>SymbolsOutline<CR>", "Show Symbols" },
d = {
"<Cmd>lua vim.lsp.buf.definition()<CR>", "Go to definition"
},
D = {
"<cmd>lua vim.lsp.buf.implementation()<CR>",
"Implementation"
},
i = { "<Cmd>lua vim.lsp.buf.hover()<CR>", "Info hover" },
I = {
"<Cmd>Telescope lsp_implementations<CR>", "Implementations"
},
r = { "<cmd>Telescope lsp_references<CR>", "References" },
f = { "<cmd>Lspsaga code_action<CR>", "Fix Code Actions" },
t = { "<cmd>lua vim.lsp.buf.signature_help()<CR>", "Signature" },
e = {
"<cmd>lua vim.diagnostic.open_float()<CR>",
"Show Line Diags"
}
},
f = {
["sd"] = {
"<cmd>Telescope lsp_document_symbols<CR>",
"Find symbol in document"
},
["sw"] = {
"<cmd>Telescope lsp_workspace_symbols<CR>",
"Find symbol in workspace"
}
}
}
which_key.register(leader_mappings, local_leader_opts)
-- Create a new note after asking for its title.
buf_set_keymap('', "#7", "<cmd>SymbolsOutline<CR>", opts)
buf_set_keymap('!', "#7", "<cmd>SymbolsOutline<CR>", opts)
buf_set_keymap('', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
-- override standard tag jump
buf_set_keymap('', 'C-]', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('!', 'C-]', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
-- Set some keybinds conditional on server capabilities
if client.server_capabilities.document_formatting then
which_key.register({
l = {
["="] = {
"<cmd>lua vim.lsp.buf.formatting_sync()<CR>", "Format"
}
}
}, local_leader_opts)
-- vim.cmd([[
-- augroup LspFormatting
-- autocmd! * <buffer>
-- autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()
-- augroup END
-- ]])
end
if client.server_capabilities.implementation then
which_key.register({
l = {
["I"] = {
"<cmd>Telescope lsp_implementations<CR>",
"Implementations"
}
}
}, local_leader_opts)
end
if client.server_capabilities.document_range_formatting then
which_key.register({
l = {
["="] = {
"<cmd>lua vim.lsp.buf.range_formatting()<CR>",
"Format Range"
}
}
}, local_leader_opts_visual)
end
if client.server_capabilities.rename then
which_key.register({
l = { ["R"] = { "<cmd>lua vim.lsp.buf.rename()<CR>", "Rename" } }
}, local_leader_opts)
end
end
-- LSP stuff - minimal with defaults for now
local null_ls = require("null-ls")
-- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/formatting
local formatting = null_ls.builtins.formatting
-- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/diagnostics
local diagnostics = null_ls.builtins.diagnostics
local codeactions = null_ls.builtins.code_actions
require("lsp-format").setup {}
null_ls.setup {
debug = false,
sources = {
-- formatting.lua_format,
formatting.alejandra, -- for nix
formatting.prismaFmt, -- for node prisma db orm
formatting.prettier.with {
-- extra_args = {
-- "--use-tabs", "--single-quote", "--jsx-single-quote"
-- },
-- Disable markdown because formatting on save conflicts in weird ways
-- with the taskwiki (roam-task) stuff.
filetypes = {
"javascript", "javascriptreact", "typescript",
"typescriptreact", "vue", "scss", "less", "html", "css",
"json", "jsonc", "yaml", "graphql", "handlebars", "svelte"
},
disabled_filetypes = { "markdown" }
}, diagnostics.eslint_d.with {
args = {
"-f", "json", "--stdin", "--stdin-filename", "$FILENAME"
}
}, -- diagnostics.vale,
codeactions.eslint_d, codeactions.gitsigns, codeactions.statix, -- for nix
diagnostics.statix, -- for nix
null_ls.builtins.hover.dictionary, codeactions.shellcheck,
diagnostics.shellcheck
-- removed formatting.rustfmt since rust_analyzer seems to do the same thing
},
on_attach = attached
}
local lspconfig = require("lspconfig")
local cmp_nvim_lsp = require("cmp_nvim_lsp")
local capabilities = vim.tbl_extend('keep', vim.lsp.protocol
.make_client_capabilities(),
cmp_nvim_lsp.default_capabilities());
-- require('rust-tools').setup({
-- server = {
-- on_attach = attached,
-- capabilities = capabilities,
-- standalone = false
-- },
-- tools = {
-- autoSetHints = true,
-- inlay_hints = { auto = true, only_current_line = true },
-- runnables = { use_telescope = true }
-- }
-- })
require('crates').setup {}
require('cmp-npm').setup({})
lspconfig.tsserver.setup { capabilities = capabilities, on_attach = attached }
lspconfig.lua_ls.setup {
on_attach = attached,
capabilities = capabilities,
filetypes = { "lua" },
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = 'LuaJIT'
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = { 'vim', "string", "require" }
},
workspace = {
-- Make the server aware of Neovim runtime files
library = vim.api.nvim_get_runtime_file("", true),
checkThirdParty = false
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = { enable = false },
completion = { enable = true, callSnippet = "Replace" }
}
}
}
lspconfig.svelte.setup { on_attach = attached, capabilities = capabilities }
lspconfig.tailwindcss.setup {
on_attach = attached,
capabilities = capabilities,
settings = {
files = { exclude = { "**/.git/**", "**/node_modules/**", "**/*.md" } }
}
}
-- nil_ls is a nix lsp
lspconfig.nil_ls.setup { on_attach = attached, capabilities = capabilities }
lspconfig.cssls.setup {
on_attach = attached,
capabilities = capabilities,
settings = { css = { lint = { unknownAtRules = "ignore" } } }
}
lspconfig.eslint.setup { on_attach = attached, capabilities = capabilities }
lspconfig.html.setup { on_attach = attached, capabilities = capabilities }
lspconfig.bashls.setup { on_attach = attached, capabilities = capabilities }
-- TODO: investigate nvim-metals and remove line below
lspconfig.metals.setup { on_attach = attached, capabilities = capabilities } -- for scala
lspconfig.pylsp.setup { on_attach = attached, capabilities = capabilities } -- for python
lspconfig.jsonls.setup {
on_attach = attached,
settings = {
json = {
schemas = require('schemastore').json.schemas(),
validate = { enable = true }
}
},
setup = {
commands = {
Format = {
function()
vim.lsp.buf.range_formatting({}, { 0, 0 },
{ vim.fn.line "$", 0 })
end
}
}
},
capabilities = capabilities
}
require 'lspsaga'.init_lsp_saga({
use_saga_diagnostic_sign = not SimpleUI,
use_diagnostic_virtual_text = false,
code_action_prompt = {
enable = true,
sign = false,
sign_priority = 20,
virtual_text = true
}
-- TODO: re-enable this at next update - getting error 2022-08-02
-- code_action_lightbulb = {
-- enable = false,
-- sign = true,
-- enable_in_insert = true,
-- sign_priority = 20,
-- virtual_text = false,
-- },
})
end -- Diagnostics setup
----------------------- TELESCOPE --------------------------------
M.telescope = function()
local actions = require('telescope.actions')
local action_state = require('telescope.actions.state')
local function quicklook_selected_entry(prompt_bufnr)
local entry = action_state.get_selected_entry()
-- actions.close(prompt_bufnr)
vim.cmd("silent !qlmanage -p '" .. entry.value .. "'")
end
local function yank_selected_entry(prompt_bufnr)
local entry = action_state.get_selected_entry()
actions.close(prompt_bufnr)
-- Put it in the unnamed buffer and the system clipboard both
vim.api.nvim_call_function("setreg", { '"', entry.value })
vim.api.nvim_call_function("setreg", { "*", entry.value })
end
local function system_open_selected_entry(prompt_bufnr)
local entry = action_state.get_selected_entry()
actions.close(prompt_bufnr)
os.execute("open '" .. entry.value .. "'")
end
require('telescope').setup {
file_ignore_patterns = {
"*.bak", ".git/", "node_modules", ".zk/", "Caches/"
},
prompt_prefix = SimpleUI and ">" or "",
selection_caret = SimpleUI and "" or "",
-- path_display = { "smart" },
defaults = {
path_display = function(_, path)
local tail = require("telescope.utils").path_tail(path)
return string.format("%s (%s)", tail,
require("telescope.utils").path_smart(
path:gsub("/Users/[^/]*/", "~/"):gsub(
"/[^/]*$", ""):gsub(
"/Library/Containers/co.noteplan.NotePlan3/Data/Library/Application Support/co.noteplan.NotePlan3",
"/NotePlan")))
end,
-- path_display = { "truncate" },
mappings = {
n = {
["<C-y>"] = yank_selected_entry,
["<C-o>"] = system_open_selected_entry,
["<F10>"] = quicklook_selected_entry,
["q"] = require("telescope.actions").close
},
i = {
["<C-y>"] = yank_selected_entry,
["<F10>"] = quicklook_selected_entry,
["<C-o>"] = system_open_selected_entry
}
},
vimgrep_arguments = {
"rg", "--color=never", "--no-heading", "--with-filename",
"--line-number", "--column", "--smart-case"
},
-- Telescope smart history
history = {
path = '~/.local/share/nvim/databases/telescope_history.sqlite3',
limit = 100
},
layout_strategy = "flex",
layout_config = {
horizontal = { prompt_position = "bottom", preview_width = 0.55 },
vertical = { mirror = false },
width = 0.87,
height = 0.80,
preview_cutoff = 1
},
color_devicons = not SimpleUI,
set_env = { ["COLORTERM"] = "truecolor" }, -- default = nil,
file_previewer = require("telescope.previewers").vim_buffer_cat.new,
grep_previewer = require("telescope.previewers").vim_buffer_vimgrep
.new,
qflist_previewer = require("telescope.previewers").vim_buffer_qflist
.new
},
extensions = {
fzy_native = {
override_generic_sorter = true,
override_file_sorter = true
}
}
}
require 'telescope'.load_extension('fzy_native')
require("telescope").load_extension("zk")
if vim.fn.has('mac') ~= 1 then
-- doesn't currently work on mac
require 'telescope'.load_extension('media_files')
end
end -- telescope
----------------------- COMPLETIONS --------------------------------
-- cmp, luasnip
M.completions = function()
require("luasnip/loaders/from_vscode").lazy_load()
local luasnip = require("luasnip")
local check_backspace = function()
local col = vim.fn.col "." - 1
return col == 0 or
vim.fn.getline(vim.fn.line(".")):sub(col, col):match "%s"
end
local cmp = require 'cmp'
cmp.setup {
enabled = function()
local context = require 'cmp.config.context'
local buftype = vim.api.nvim_buf_get_option(0, "buftype")
-- prevent completions in prompts like telescope prompt
if buftype == "prompt" then return false end
-- allow completions in command mode
if vim.api.nvim_get_mode().mode == 'c' then return true end
-- forbid completions in comments
return not context.in_treesitter_capture("comment") and
not context.in_syntax_group("Comment")
end,
mapping = {
['<C-p>'] = cmp.mapping.select_prev_item(),
['<C-n>'] = cmp.mapping.select_next_item(),
['<C-d>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete({}),
['<C-e>'] = cmp.mapping.close(),
['<CR>'] = cmp.mapping.confirm {
behavior = cmp.ConfirmBehavior.Replace,
select = false
},
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand({})
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
cmp.mapping.complete({})
-- fallback()
end
end, { "i", "s" }),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { "i", "s" })
},
window = { documentation = cmp.config.window.bordered() },
sources = {
{ name = 'nvim_lsp' }, { name = 'nvim_lsp_signature_help' },
{ name = 'nvim_lua' }, { name = 'emoji' }, { name = 'luasnip' },
{ name = 'path' }, { name = "crates" },
{ name = 'npm', keyword_length = 3 },
{ name = "buffer", keyword_length = 3 }
},
formatting = {
fields = { "kind", "abbr", "menu" },
format = function(entry, vim_item)
-- Kind icons
vim_item.kind = string.format("%s",
signs.kind_icons[vim_item.kind])
vim_item.menu = ({
nvim_lsp = "[LSP]",
nvim_lsp_signature_help = "[LSPS]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]"
})[entry.source.name]
return vim_item
end
},
snippet = { expand = function(args) luasnip.lsp_expand(args.body) end }
}
cmp.setup.cmdline('/', {
mapping = cmp.mapping.preset.cmdline(),
sources = { { name = 'buffer' } }
})
cmp.setup.cmdline(':', {
mapping = cmp.mapping.preset.cmdline(),
sources = cmp.config.sources({ { name = 'path' } }, {
{ name = 'cmdline', option = { ignore_cmds = { 'Man', '!' } } }
})
})
end -- completions
----------------------- NOTES --------------------------------
-- zk (zettelkasten lsp), taskwiki, focus mode, grammar
M.notes = function()
require("zk").setup({
picker = "telescope",
-- automatically attach buffers in a zk notebook that match the given filetypes
lsp = {
auto_attach = {
enabled = true,
filetypes = { "markdown", "vimwiki", "md" }
},
config = {
on_attach = function(_, bufnr)
print("ZK attached")
local which_key = require("which-key")
local local_leader_opts = {
mode = "n", -- NORMAL mode
prefix = "<leader>",
buffer = bufnr, -- Local mappings.
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local local_leader_opts_visual = {
mode = "v", -- VISUAL mode
prefix = "<leader>",
buffer = bufnr, -- Local mappings.
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local leader_mappings = {
K = { "<Cmd>lua vim.lsp.buf.hover()<CR>", "Info preview" },
n = {
-- Create the note in the same directory as the current buffer after asking for title
p = {
"<Cmd>ZkNew { dir = vim.fn.expand('%:p:h'), title = vim.fn.input('Title: ') }<CR>",
"New peer note (same dir)"
},
l = { "<Cmd>ZkLinks<CR>", "Show note links" },
-- the following duplicate with the ,l_ namespace on purpose because of programming muscle memory
r = {
"<cmd>Telescope lsp_references<CR>",
"References to this note"
}
},
l = {
name = "Local LSP",
-- Open notes linking to the current buffer.
r = {
"<cmd>Telescope lsp_references<CR>",
"References to this note"
},
i = {
"<Cmd>lua vim.lsp.buf.hover()<CR>",
"Info preview"
},
f = {
"<cmd>Lspsaga code_action<CR>",
"Fix Code Actions"
},
e = {
"<cmd>lua vim.diagnostic.open_float()<CR>",
"Show Line Diags"
}
}
}
which_key.register(leader_mappings, local_leader_opts)
local leader_mappings_visual = {
n = {
p = {
":'<,'>ZkNewFromTitleSelection { dir = vim.fn.expand('%:p:h') }<CR>",
"New peer note (same dir) selection for title"
}
-- Create a new note in the same directory as the current buffer, using the current selection for title.
}
}
which_key.register(leader_mappings_visual,
local_leader_opts_visual)
local opts = { noremap = true, silent = true }
-- TODO: Make <CR> magic...
-- in normal mode, if on a link, it should open the link (note or url)
-- in visual mode, it should prompt for folder, create a note, and make a link
-- Meanwhile, just go to definition
vim.api.nvim_buf_set_keymap(bufnr, "n", "<CR>",
"<Cmd>lua vim.lsp.buf.definition()<CR>",
opts)
-- Preview a linked note.
vim.api.nvim_buf_set_keymap(bufnr, "", "K",
"<Cmd>lua vim.lsp.buf.hover()<CR>",
opts)
require('pwnvim.options').tabindent()
end
}
}
})
-- Focus mode dimming of text out of current block
--[[ require("twilight").setup {
dimming = {
alpha = 0.25, -- amount of dimming
-- we try to get the foreground from the highlight groups or fallback color
color = { "Normal", "#ffffff" },
term_bg = "#000000", -- if guibg=NONE, this will be used to calculate text color
inactive = true -- when true, other windows will be fully dimmed (unless they contain the same buffer)
},
context = 12, -- amount of lines we will try to show around the current line
treesitter = true, -- use treesitter when available for the filetype
-- treesitter is used to automatically expand the visible text,
-- but you can further control the types of nodes that should always be fully expanded
expand = { -- for treesitter, we we always try to expand to the top-most ancestor with these types
"function", "method", "table", "if_statement"
},
exclude = {} -- exclude these filetypes
} ]]
-- Focus mode / centering
require("true-zen").setup {
-- your config goes here
-- or just leave it empty :)
modes = {
-- configurations per mode
ataraxis = {
shade = "dark", -- if `dark` then dim the padding windows, otherwise if it's `light` it'll brighten said windows
backdrop = 0, -- percentage by which padding windows should be dimmed/brightened. Must be a number between 0 and 1. Set to 0 to keep the same background color
minimum_writing_area = {
-- minimum size of main window
width = 70,
height = 44
},
quit_untoggles = true, -- type :q or :qa to quit Ataraxis mode
padding = {
-- padding windows
left = 52,
right = 52,
top = 0,
bottom = 0
},
callbacks = {
-- run functions when opening/closing Ataraxis mode
open_pre = function()
vim.opt.scrolloff = 999 -- keep cursor in vertical middle of screen
end,
open_pos = nil,
close_pre = nil,
close_pos = function()
vim.opt.scrolloff = 8
end
}
},
minimalist = {
ignored_buf_types = { "nofile" }, -- save current options from any window except ones displaying these kinds of buffers
options = {
-- options to be disabled when entering Minimalist mode
number = false,
relativenumber = false,
showtabline = 0,
signcolumn = "no",
statusline = "",
cmdheight = 1,
laststatus = 0,
showcmd = false,
showmode = false,
ruler = false,
numberwidth = 1
},
callbacks = {
-- run functions when opening/closing Minimalist mode
open_pre = nil,
open_pos = nil,
close_pre = nil,
close_pos = nil
}
},
narrow = {
--- change the style of the fold lines. Set it to:
--- `informative`: to get nice pre-baked folds
--- `invisible`: hide them
--- function() end: pass a custom func with your fold lines. See :h foldtext
folds_style = "informative",
run_ataraxis = true, -- display narrowed text in a Ataraxis session
callbacks = {
-- run functions when opening/closing Narrow mode
open_pre = nil,
open_pos = nil,
close_pre = nil,
close_pos = nil
}
},
focus = {
callbacks = {
-- run functions when opening/closing Focus mode
open_pre = nil,
open_pos = nil,
close_pre = nil,
close_pos = nil
}
}
},
integrations = {
tmux = false, -- hide tmux status bar in (minimalist, ataraxis)
kitty = {
-- increment font size in Kitty. Note: you must set `allow_remote_control socket-only` and `listen_on unix:/tmp/kitty` in your personal config (ataraxis)
enabled = false, -- disabled 2023-03-20 because it doesn't reset the font size on exit
font = "+2"
},
twilight = false, -- enable twilight text dimming outside cursor block
lualine = true -- hide nvim-lualine (ataraxis)
}
}
-- Grammar
vim.g["grammarous#disabled_rules"] = {
['*'] = {
'WHITESPACE_RULE', 'EN_QUOTES', 'ARROWS', 'SENTENCE_WHITESPACE',
'WORD_CONTAINS_UNDERSCORE', 'COMMA_PARENTHESIS_WHITESPACE',
'EN_UNPAIRED_BRACKETS', 'UPPERCASE_SENTENCE_START',
'ENGLISH_WORD_REPEAT_BEGINNING_RULE', 'DASH_RULE', 'PLUS_MINUS',
'PUNCTUATION_PARAGRAPH_END', 'MULTIPLICATION_SIGN', 'PRP_CHECKOUT',
'CAN_CHECKOUT', 'SOME_OF_THE', 'DOUBLE_PUNCTUATION', 'HELL',
'CURRENCY', 'POSSESSIVE_APOSTROPHE', 'ENGLISH_WORD_REPEAT_RULE',
'NON_STANDARD_WORD'
}
}
-- Grammar stuff
vim.cmd(
[[command StartGrammar2 lua require('pwnvim.plugins').grammar_check()]])
end -- notes
M.grammar_check = function()
vim.cmd('packadd vim-grammarous')
local opts = { noremap = false, silent = true }
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(0, ...) end
buf_set_keymap('', '<leader>gf', '<Plug>(grammarous-fixit)', opts)
buf_set_keymap('', '<leader>gx', '<Plug>(grammarous-remove-error)', opts)
buf_set_keymap('', ']g', '<Plug>(grammarous-move-to-next-error)', opts)
buf_set_keymap('', '[g', '<Plug>(grammarous-move-to-previous-error)', opts)
vim.cmd('GrammarousCheck')
end
----------------------- MISC --------------------------------
-- rooter, kommentary, autopairs, tmux, toggleterm
M.misc = function()
vim.g.lf_map_keys = 0 -- lf.vim disable default keymapping
-- Change project directory using local cd only
-- vim.g.rooter_cd_cmd = 'lcd'
-- Look for these files/dirs as hints
-- vim.g.rooter_patterns = {
-- '.git', '_darcs', '.hg', '.bzr', '.svn', 'Makefile', 'package.json',
-- '.zk', 'Cargo.toml', 'build.sbt', 'Package.swift', 'Makefile.in'
-- }
require('project_nvim').setup({
active = true,
on_config_done = nil,
manual_mode = false,
detection_methods = { "pattern", "lsp" },
patterns = {
".git", "_darcs", ".hg", ".bzr", ".svn", "Makefile", "package.json",
".zk", "build.sbt", "Package.swift", "Makefile.in", "README.md",
"flake.nix"
},
show_hidden = false,
silent_chdir = true,
ignore_lsp = {}
})
require('telescope').load_extension('projects')
require('Comment').setup()
require("which-key").register({
["<leader>c<space>"] = {
'<Plug>(comment_toggle_linewise_current)', "Toggle comments"
},
["g/"] = { '<Plug>(comment_toggle_linewise_current)', "Toggle comments" }
}, { mode = "n", silent = true, norewrap = true })
require("which-key").register({
["<leader>c<space>"] = {
'<Plug>(comment_toggle_linewise_visual)', "Toggle comments"
},
["g/"] = { '<Plug>(comment_toggle_linewise_visual)', "Toggle comments" }
}, { mode = "v", silent = true, norewrap = true })
require('nvim-autopairs').setup({})
vim.g.tmux_navigator_no_mappings = 1
require("toggleterm").setup {
open_mapping = [[<c-\>]],
insert_mappings = true, -- from normal or insert mode
start_in_insert = true,
hide_numbers = true,
direction = 'vertical',
size = function(_) return vim.o.columns * 0.3 end,
close_on_exit = true
}
vim.api.nvim_set_keymap('t', [[<C-\]], "<Cmd>ToggleTermToggleAll<cr>",
{ noremap = true })
end -- misc
return M

View File

@@ -0,0 +1,59 @@
require 'bufferline'.setup {
options = {
numbers = "none", -- | "ordinal" | "buffer_id" | "both" | function({ ordinal, id, lower, raise }): string,
close_command = "Bdelete! %d", -- can be a string | function, see "Mouse actions"
right_mouse_command = "Bdelete! %d", -- can be a string | function, see "Mouse actions"
left_mouse_command = "buffer %d", -- can be a string | function, see "Mouse actions"
middle_mouse_command = nil, -- can be a string | function, see "Mouse actions"
indicator = {
style = "icon",
icon = "",
},
-- buffer_close_icon = '',
modified_icon = "",
close_icon = SimpleUI and "x" or "",
-- close_icon = '',
-- hover doesn't work in tmux
-- hover = {
-- enabled = true,
-- delay = 200,
-- reveal = { 'close' }
-- },
left_trunc_marker = SimpleUI and "⬅️" or "",
right_trunc_marker = SimpleUI and "➡️" or "",
max_name_length = 40,
max_prefix_length = 30, -- prefix used when a buffer is de-duplicated
tab_size = 20,
-- name_formatter = function(buf) -- buf contains a "name", "path" and "bufnr"
-- -- remove extension from markdown files for example
-- if buf.name:match('%.md') then
-- return vim.fn.fnamemodify(buf.name, ':t:r')
-- end
-- end,
diagnostics = false, -- | "nvim_lsp" | "coc",
diagnostics_update_in_insert = false,
offsets = { { filetype = "NvimTree", text = "", padding = 1 } },
show_buffer_close_icons = true,
show_close_icon = true,
show_buffer_icons = not SimpleUI,
show_buffer_default_icon = not SimpleUI,
color_icons = not SimpleUI,
buffer_close_icon = SimpleUI and "x" or "",
show_tab_indicators = true,
persist_buffer_sort = false, -- whether or not custom sorted buffers should persist
-- can also be a table containing 2 custom separators
-- [focused and unfocused]. eg: { '|', '|' }
separator_style = "thick", -- | "thick" | "thin" | { 'any', 'any' },
enforce_regular_tabs = false, -- if true, all tabs same width
always_show_bufferline = true
},
highlights = {
indicator_selected = {
fg = {
attribute = "fg",
highlight = "LspDiagnosticsDefaultHint"
},
bg = { attribute = "bg", highlight = "Normal" }
}
}
}

View File

@@ -0,0 +1,99 @@
require("gitsigns").setup {
signs = {
add = {
hl = 'GitSignsAdd',
text = '',
numhl = 'GitSignsAddNr',
linehl = 'GitSignsAddLn'
},
change = {
hl = 'GitSignsChange',
text = '',
numhl = 'GitSignsChangeNr',
linehl = 'GitSignsChangeLn'
},
delete = {
hl = 'GitSignsDelete',
text = '_',
numhl = 'GitSignsDeleteNr',
linehl = 'GitSignsDeleteLn'
},
topdelete = {
hl = 'GitSignsDelete',
text = '',
numhl = 'GitSignsDeleteNr',
linehl = 'GitSignsDeleteLn'
},
changedelete = {
hl = 'GitSignsChange',
text = '~',
numhl = 'GitSignsChangeNr',
linehl = 'GitSignsChangeLn'
}
},
on_attach = function(bufnr)
local gs = package.loaded.gitsigns
local function map(mode, l, r, opts)
opts = opts or {}
opts.buffer = bufnr
vim.keymap.set(mode, l, r, opts)
end
-- Navigation
map('n', ']c', function()
if vim.wo.diff then return ']c' end
vim.schedule(function() gs.next_hunk() end)
return '<Ignore>'
end, { expr = true })
map('n', '[c', function()
if vim.wo.diff then return '[c' end
vim.schedule(function() gs.prev_hunk() end)
return '<Ignore>'
end, { expr = true })
-- Actions -- normal mode
require("which-key").register(
{
["<leader>"] = {
h = {
name = "hunk (git)",
s = { ':Gitsigns stage_hunk<CR>', "Stage hunk" },
r = { ':Gitsigns reset_hunk<CR>', "Reset hunk" },
S = { gs.stage_buffer, "Stage buffer" },
u = { gs.undo_stage_hunk, "Undo stage hunk" },
R = { gs.reset_buffer, "Reset buffer" },
p = { gs.preview_hunk, "Preview hunk" },
b = { function() gs.blame_line { full = true } end, "Blame hunk" },
d = { gs.diffthis, "Diff this to index" },
D = { function() gs.diffthis('~') end, "Diff this to previous" },
},
t = {
name = "git toggles",
b = { gs.toggle_current_line_blame, "Toggle current line blame" },
d = { gs.toggle_deleted, "Toggle deleted" },
}
}
}, { mode = "n", buffer = bufnr, silent = true, norewrap = true }
)
-- Actions -- visual and select mode
require("which-key").register(
{
["<leader>"] = {
h = {
name = "hunk (git)",
s = { ':Gitsigns stage_hunk<CR>', "Stage hunk" },
r = { ':Gitsigns reset_hunk<CR>', "Reset hunk" },
}
}
}, { mode = "v", buffer = bufnr, silent = true, norewrap = true }
)
-- Actions -- operator pending mode
require("which-key").register(
{
["ih"] = { ':<C-U>Gitsigns select_hunk<CR>', "Select git hunk" }
}, { mode = "o", buffer = bufnr, silent = true, norewrap = true }
)
end
}

View File

@@ -0,0 +1,30 @@
if not SimpleUI then
vim.g.indentLine_enabled = 1
vim.g.indent_blankline_char = ''
-- vim.g.indent_blankline_char = "▏"
vim.g.indent_blankline_filetype_exclude = { 'help', 'packer' }
vim.g.indent_blankline_buftype_exclude = { 'terminal', 'nofile' }
vim.g.indent_blankline_char_highlight = 'LineNr'
vim.g.indent_blankline_show_trailing_blankline_indent = false
vim.g.indent_blankline_filetype_exclude = {
"help", "startify", "dashboard", "packer", "neogitstatus", "NvimTree",
"Trouble"
}
vim.g.indent_blankline_use_treesitter = true
vim.g.indent_blankline_show_current_context = true
vim.g.indent_blankline_context_patterns = {
"class", "return", "function", "method", "^if", "^while", "jsx_element",
"^for", "^object", "^table", "block", "arguments", "if_statement",
"else_clause", "jsx_element", "jsx_self_closing_element",
"try_statement", "catch_clause", "import_statement", "operation_type"
}
-- HACK: work-around for https://github.com/lukas-reineke/indent-blankline.nvim/issues/59
vim.wo.colorcolumn = "99999"
require('indent_blankline').setup({
show_current_context = true,
use_treesitter = true,
buftype_exclude = { 'terminal' },
filetype_exclude = { 'help', 'markdown' },
})
end

View File

@@ -0,0 +1,27 @@
require('lualine').setup {
options = {
theme = 'papercolor_light',
icons_enabled = not SimpleUI,
component_separators = { left = SimpleUI and '>' or '', right = SimpleUI and '<' or '' },
disabled_filetypes = { 'pager' },
section_separators = { left = SimpleUI and '>' or '', right = SimpleUI and '<' or '' }
},
extensions = { 'quickfix', 'nvim-tree', 'fugitive' },
sections = {
lualine_a = { 'mode' },
lualine_b = { 'branch' },
lualine_c = { 'nvim-tree', 'filename' },
lualine_x = { 'encoding', 'fileformat', 'filetype' },
lualine_y = { 'progress' },
lualine_z = {
{
'diagnostics',
sources = { 'nvim_diagnostic' },
-- displays diagnostics from defined severity
sections = { 'error', 'warn' }, -- 'info', 'hint'},}}
color_error = "#E06C75", -- changes diagnostic's error foreground color
color_warn = "#E5C07B"
}
}
}
}

View File

@@ -0,0 +1,74 @@
local signs = require("pwnvim.signs")
require 'nvim-tree'.setup {
renderer = {
icons = {
webdev_colors = true,
git_placement = "before",
padding = " ",
symlink_arrow = "",
show = {
file = not SimpleUI,
folder = true,
folder_arrow = true,
git = true
},
glyphs = {
default = SimpleUI and "🖹" or "",
symlink = SimpleUI and "🔗" or "",
git = {
unstaged = SimpleUI and "" or "",
staged = "",
unmerged = SimpleUI and "⚡︎" or "",
renamed = "",
deleted = SimpleUI and "" or "",
untracked = "U",
ignored = ""
},
folder = {
default = SimpleUI and "📁" or "",
open = SimpleUI and "📂" or "",
empty = SimpleUI and "🗀" or "",
empty_open = SimpleUI and "🗁" or "",
symlink = SimpleUI and "🔗" or ""
}
}
}
},
-- disables netrw completely
disable_netrw = true,
-- hijack netrw window on startup
hijack_netrw = true,
-- open the tree when running this setup function
open_on_setup = false,
update_cwd = true,
-- update_to_buf_dir = { enable = true, auto_open = true },
update_focused_file = { enable = true, update_cwd = true },
-- show lsp diagnostics in the signcolumn
diagnostics = {
enable = true,
icons = { hint = signs.hint, info = signs.info, warning = signs.warn, error = signs.error }
},
git = {
enable = true,
timeout = 400 -- (in ms)
},
view = {
width = 30,
-- height = 30,
hide_root_folder = false,
side = "left",
-- auto_resize = true,
mappings = {
custom_only = false,
list = {
{ key = { "l", "<CR>", "o" }, action = "edit" },
{ key = "h", action = "close_node" },
{ key = "<F10>", action = "quicklook",
action_cb = function(node) vim.cmd("silent !qlmanage -p '" .. node.absolute_path .. "'") end },
{ key = "v", action = "vsplit" }
}
},
number = false,
relativenumber = false
}
}

View File

@@ -0,0 +1,58 @@
local signs = require("pwnvim.signs")
require("todo-comments").setup {
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
signs = false, -- show icons in the signs column
keywords = {
FIX = {
icon = "", -- icon used for the sign, and in search results
color = "error", -- can be a hex color, or a named color (see below)
alt = { "ERROR", "FIXME", "BUG", "FIXIT", "ISSUE", "!!!" }, -- a set of other keywords that all map to this FIX keywords
-- signs = false, -- configure signs for some keywords individually
},
TODO = { icon = "", color = "info", alt = { "PWTODO", "TK" } },
HACK = { icon = "", color = "warning" },
WARN = { icon = signs.warn, color = "warning", alt = { "WARNING", "XXX" } },
PERF = { icon = "", alt = { "OPTIM", "PERFORMANCE", "OPTIMIZE" } },
NOTE = { icon = "", color = "hint", alt = { "INFO" } },
TEST = { icon = "", color = "test", alt = { "TESTING", "PASSED", "FAILED" } },
},
merge_keywords = true, -- when true, custom keywords will be merged with the defaults
-- highlighting of the line containing the todo comment
-- * before: highlights before the keyword (typically comment characters)
-- * keyword: highlights of the keyword
-- * after: highlights after the keyword (todo text)
highlight = {
multiline = false,
before = "", -- "fg" or "bg" or empty
keyword = "wide", -- "fg", "bg", "wide" or empty. (wide is the same as bg, but will also highlight surrounding characters)
after = "fg", -- "fg" or "bg" or empty
pattern = [[<(KEYWORDS)]], -- pattern or table of patterns, used for highlightng (vim regex)
comments_only = false, -- uses treesitter to match keywords in comments only
max_line_len = 400, -- ignore lines longer than this
exclude = {}, -- list of file types to exclude highlighting
},
-- list of named colors where we try to extract the guifg from the
-- list of hilight groups or use the hex color if hl not found as a fallback
colors = {
error = { "DiagnosticError", "ErrorMsg", "#DC2626" },
warning = { "DiagnosticWarning", "WarningMsg", "#FBBF24" },
info = { "DiagnosticInfo", "#2563EB" },
hint = { "DiagnosticHint", "#10B981" },
default = { "Identifier", "#7C3AED" },
},
search = {
command = "rg",
args = {
"--color=never",
"--no-heading",
"--with-filename",
"--line-number",
"--column",
},
-- regex that will be used to match keywords.
-- don't replace the (KEYWORDS) placeholder
pattern = [[\b(KEYWORDS)]], -- match without the extra colon. You'll likely get false positives
},
}

View File

@@ -0,0 +1,60 @@
require 'nvim-treesitter.configs'.setup {
auto_install = false,
autotag = { enable = true },
highlight = {
enable = true,
--disable = { "markdown", "markdown_inline" }, -- 2022-11-30 conflicts with markdown plugin, which detects more things like bold+italic and strikethrough
--additional_vim_regex_highlighting = { "markdown" } -- leaving in case we bring back markdown plugin
},
indent = { enable = true, disable = { "yaml" } },
incremental_selection = { enable = true },
context_commentstring = {
enable = true,
},
textobjects = {
select = {
enable = true,
lookahead = true,
keymaps = {
-- You can use the capture groups defined in textobjects.scm
["af"] = { query = "@function.outer", desc = "Select outer function" },
["if"] = { query = "@function.inner", desc = "Select inner function" },
["ac"] = { query = "@class.outer", desc = "Select outer class" },
["ic"] = { query = "@class.inner", desc = "Select inner class" },
["im"] = { query = "@block.inner", desc = "Select inner block" },
["am"] = { query = "@block.outer", desc = "Select outer block" },
-- ["il"] = { query = "@list.inner", desc = "Select inner list" },
-- ["al"] = { query = "@list.outer", desc = "Select outer list" },
-- ["ih"] = { query = "@section.inner", desc = "Select inner section" },
-- ["ah"] = { query = "@section.outer", desc = "Select outer section" },
},
},
move = {
enable = true,
set_jumps = true, -- whether to set jumps in the jumplist
goto_next_start = {
["]m"] = "@function.outer",
["]]"] = { query = "@class.outer", desc = "Next class start" },
},
goto_next_end = {
["]M"] = "@function.outer",
["]["] = "@class.outer",
},
goto_previous_start = {
["[m"] = "@function.outer",
["[["] = "@class.outer",
},
goto_previous_end = {
["[M"] = "@function.outer",
["[]"] = "@class.outer",
},
},
}
}
require 'treesitter-context'.setup {
max_lines = 0, -- no max window height
patterns = {
markdown = { "atx_heading" }
},
}

77
pwnvim/signs.lua Normal file
View File

@@ -0,0 +1,77 @@
local M = {}
M.error = SimpleUI and "🛑" or ""
M.warn = SimpleUI and "⚠️" or ""
M.hint = SimpleUI and "" or ""
M.info = SimpleUI and "" or ""
M.signs = {
{ name = "DiagnosticSignError", text = M.error },
{ name = "DiagnosticSignWarn", text = M.warn },
{ name = "DiagnosticSignHint", text = M.hint },
{ name = "DiagnosticSignInfo", text = M.info }
}
if SimpleUI then
M.kind_icons = {
Text = "T",
Method = "m",
Function = "f",
Constructor = "c",
Field = "f",
Variable = "v",
Class = "",
Interface = "i",
Module = "m",
Property = "p",
Unit = "u",
Value = "v",
Enum = "e",
Keyword = "",
Snippet = "s",
Color = "",
File = "F",
Reference = "r",
Folder = "🖿",
EnumMember = "em",
Constant = "c",
Struct = "s",
Event = "e",
Operator = "o",
TypeParameter = "t"
}
else
M.kind_icons = {
Text = "",
Method = "m",
Function = "",
Constructor = "",
Field = "",
Variable = "",
Class = "",
Interface = "",
Module = "",
Property = "",
Unit = "",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "",
Event = "",
Operator = "",
TypeParameter = ""
}
end
for _, sign in ipairs(M.signs) do
vim.fn.sign_define(sign.name,
{ texthl = M.name, text = M.text, numhl = "" })
end
return M

196
pwnvim/tasks.lua Normal file
View File

@@ -0,0 +1,196 @@
local M = {}
M.completeTaskDirect = function()
local line = vim.api.nvim_get_current_line()
local nline = require("pwnvim.tasks").completeTask(line)
vim.api.nvim_set_current_line(nline)
end
M.completeTask = function(line)
local nline = line:gsub("%[[ oO]%]", "[x]", 1)
if line ~= nline then -- substitution successful, now add date completed
nline = nline .. ' @done(' .. os.date("%Y-%m-%d %-I:%M %p") .. ")"
return nline
else -- or do nothing
return line
end
end
M.scheduleTaskDirect = function(newyear, newmonth, newday)
local line = vim.api.nvim_get_current_line()
local nline = require("pwnvim.tasks").scheduleTask(line, newyear, newmonth, newday)
vim.api.nvim_set_current_line(nline)
end
M.scheduleTask = function(line, newyear, newmonth, newday)
newmonth = string.format("%02d", newmonth)
newday = string.format("%02d", newday)
local buf = vim.api.nvim_get_current_buf()
local win = vim.api.nvim_get_current_win()
-- Step 1: change current task to [>]
local nline = line:gsub("%[[ oO>-]%] ", "[>] ", 1)
if line == nline then
-- no changes then abort
return line
end
-- Step 2: add scheduled date to end as ">YYYY-mm-dd" removing any existing ">date" tags
nline = nline:gsub(">[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]?", "")
nline = nline .. " >" .. newyear .. "-" .. newmonth .. "-" .. newday
--vim.api.nvim_set_current_line(nline)
-- Step 3: try to get the date from the current note
local date = require("pwnvim.tasks").getDateFromCurrentFile()
-- Step 4: add "<YYYY-mm-dd" to end of the copied task if it doesn't already have a date
-- and if we can glean a source date from a date in the filename or frontmatter
-- or worst case, just don't put that
if line:match("<%d+-%d+-%d+") == nil and date ~= nil then
line = line .. " <" .. date
end
-- Step 5: take current task and copy it to Calendar/YYYYmmdd.md
local target = vim.env.ZK_NOTEBOOK_DIR .. '/Calendar/' .. newyear .. newmonth .. newday .. '.md'
vim.api.nvim_command('edit ' .. target)
vim.api.nvim_buf_set_lines(0, -1, -1, false, { line })
vim.api.nvim_set_current_win(win)
vim.api.nvim_set_current_buf(buf)
return nline
end
M.scheduleTaskBulk = function()
require("pwnvim.tasks").datePromptThen(function(year, month, day)
vim.cmd("'<,'>luado return require('pwnvim.tasks').scheduleTask(line,'" ..
year .. "','" .. month .. "','" .. day .. "')")
end)
end
M.scheduleTaskPrompt = function()
require("pwnvim.tasks").datePromptThen(require("pwnvim.tasks").scheduleTaskDirect)
end
M.datePromptThen = function(myfunc)
local days = {}
-- Generate dates for next two weeks with handy shortcut labels
for i = 0, 14, 1 do
local day
if i == 0 then
day = os.date("%Y-%m-%d (today)", os.time() + 86400 * i)
elseif i == 1 then
day = os.date("%Y-%m-%d (tomorrow)", os.time() + 86400 * i)
elseif i > 7 then
day = os.date("%Y-%m-%d (next %a)", os.time() + 86400 * i)
else
day = os.date("%Y-%m-%d (%a)", os.time() + 86400 * i)
end
table.insert(days, day)
end
-- These will pop up in telescope for quick filtering
vim.ui.select(days, { prompt = 'Pick a date:' }, function(choice)
if choice then
local t = {}
for w in string.gmatch(choice, "(%d+)") do
table.insert(t, w)
end
if #t == 3 then
myfunc(t[1], t[2], t[3])
end
else
-- if no choice was made, assume a desire to specify something outside the 14 days
M.datePromptRawThen(myfunc)
end
end)
end
-- Just give three prompts for year/month/day
M.datePromptRawThen = function(myfunc)
local defaultyear = os.date("%Y")
local defaultmonth = os.date("%m")
local defaultday = os.date("%d")
vim.ui.input({ prompt = "Enter year: ", default = defaultyear }, function(year)
vim.ui.input({ prompt = "Enter month: ", default = defaultmonth }, function(month)
vim.ui.input({ prompt = "Enter day: ", default = defaultday }, function(day)
month = string.format("%02d", month)
day = string.format("%02d", day)
myfunc(year, month, day)
end)
end)
end)
end
M.scheduleTaskTodayDirect = function()
local year = os.date("%Y")
local month = os.date("%m")
local day = os.date("%d")
require("pwnvim.tasks").scheduleTaskDirect(year, month, day)
end
M.scheduleTaskToday = function(line)
local year = os.date("%Y")
local month = os.date("%m")
local day = os.date("%d")
return require("pwnvim.tasks").scheduleTask(line, year, month, day)
end
M.getDateFromCurrentFile = function()
local srcfilename = vim.api.nvim_buf_get_name(0)
local date = srcfilename:match("%d+-%d+-%d+")
-- TODO: also check for filenames that are "YYYYmmdd.md"
if date == nil then
local srcheader = vim.api.nvim_buf_get_lines(0, 0, 10, false)
for _, l in ipairs(srcheader) do
date = l:match("^[dD]ate: (%d+-%d+-%d+)")
if date ~= nil then break end
end
end
return date
end
M.createTask = function(line)
local nline = line:gsub("^%s*[-*] ", "%0[ ] ", 1)
if line == nline then
nline = line:gsub("^%s*", "%0* [ ] ", 1)
end
return nline
end
M.createTaskDirect = function()
local line = vim.api.nvim_get_current_line()
local nline = require("pwnvim.tasks").createTask(line)
vim.api.nvim_set_current_line(nline)
vim.cmd("normal 4l")
end
local function visual_selection_range()
local _, csrow, cscol, _ = unpack(vim.fn.getpos("'<"))
local _, cerow, cecol, _ = unpack(vim.fn.getpos("'>"))
if csrow < cerow or (csrow == cerow and cscol <= cecol) then
return csrow - 1, cscol - 1, cerow - 1, cecol
else
return cerow - 1, cecol - 1, csrow - 1, cscol
end
end
M.eachSelectedLine = function(myfunc)
-- local rowstart, _, rowend, _ = visual_selection_range()
local rowstart = vim.api.nvim_buf_get_mark(0, "<")[1] - 1
local rowend = vim.api.nvim_buf_get_mark(0, ">")[1] - 1
local buf = vim.api.nvim_get_current_buf()
local win = vim.api.nvim_get_current_win()
print("row start:" .. rowstart .. " row end:" .. rowend)
for i = rowstart, rowend do
print("i:" .. i)
vim.api.nvim_set_current_buf(buf)
vim.api.nvim_set_current_win(win)
vim.api.nvim_win_set_cursor(win, { i + 1, 0 })
-- All we're really doing here is putting the cursor on each line of the selection
myfunc()
end
end
return M