1
0
mirror of https://github.com/jdhao/nvim-config.git synced 2025-06-08 14:14:33 +02:00

190 Commits

Author SHA1 Message Date
jdhao
52426e0ce8 Remove config for neoformat 2025-06-08 00:18:43 +02:00
jdhao
ae5e7c5bb4 Add plugin neogit 2025-06-08 00:14:32 +02:00
jdhao
6e6a09e32f Add support for markdown ref-style link (#415) 2025-06-07 19:12:01 +02:00
jdhao
88044b252e add new colorscheme citruszest (#414) 2025-06-05 00:51:10 +02:00
jdhao
448f2394fe Add new bunch of colorschemes (#413) 2025-06-03 13:22:02 +02:00
jdhao
6c10223062 change kanagawa theme variant 2025-06-03 12:36:50 +02:00
jdhao
ec557001af bump supported nvim version to 0.11.2 (#412) 2025-06-02 23:25:06 +02:00
jdhao
082111fa4e update LSP config (#410) 2025-05-13 18:15:08 +02:00
jdhao
30b3c09dda update readme 2025-04-30 19:07:07 +02:00
jdhao
3b964c3d1f remove format mapping for lsp 2025-04-30 19:04:44 +02:00
jdhao
999a1733cf use nvim-cmp for cmd line completion
- remove wilder.nvim and its config
- add blink.cmp config as backup solution
2025-04-30 19:01:57 +02:00
Alessandro Zini
b69dcb3a6b fix neovim link for linux install script (#408) 2025-04-30 11:00:50 +02:00
jdhao
ea23f913b4 set default conf for all LSP in one place (#405) 2025-04-26 22:02:48 +02:00
jdhao
8839201450 upgrade nvim to 0.11.1 (#404) 2025-04-26 21:48:18 +02:00
jdhao
ba991064b6 change lualine refresh interval 2025-04-26 19:00:11 +02:00
jdhao
6c620ecc32 update the enabled lsp server list 2025-04-26 18:59:25 +02:00
jdhao
be862a83d6 Use new lsp configuration structure (#403)
In this new structure, the main configuration for a LSP server is
provided by the plugin nvim-lspconfig.
Some of the config may be overridden by the configuration under
directory `after/lsp/xxx.lua`, where `xxx` is the lsp server name used
by nvim-lspconfig.

Note that it is necessary to put the custom lsp server configuration
under `after/` directory, in order to correctly override the config
provided by nvim-lspconfig.
2025-04-26 17:19:46 +02:00
jdhao
488ba52644 use new api vim.lsp.config for lsp configuration (#402)
Now nvim-lspconfig serves as ready made configuration for different lsp
server configurations.
See also related PR in lspconfig: https://github.com/neovim/nvim-lspconfig/pull/3659
2025-04-22 17:54:29 +02:00
jdhao
e23d4bb661 use black to format python file 2025-04-11 21:06:53 +02:00
jdhao
510a5501c5 update config for git-conflict.nvim (#401) 2025-04-11 21:06:23 +02:00
jdhao
e08b17f335 optimize nvim startup time with lazy.nvim (#400) 2025-04-08 19:35:47 +02:00
jdhao
adddbc0ba6 remove indent-blankline and use mini.indentscope 2025-04-08 19:13:01 +02:00
jdhao
aadfdae677 switch from nvim-web-devicons to mini.icons (#399) 2025-04-08 19:11:20 +02:00
jdhao
5826161160 move fzf-lua config to separate file 2025-04-04 18:17:24 +02:00
jdhao
ea2b4a728d remove plugin vim-markdown (#398)
use tree-sitter based markdown render instead.
2025-04-04 18:16:20 +02:00
jdhao
ad4a0e82dc Simplify condition check (#397) 2025-04-02 21:57:37 +02:00
jdhao
9e6be1f001 update type hints 2025-04-02 21:33:32 +02:00
jdhao
c4160b6f85 update handling of large files (#396) 2025-04-02 21:30:25 +02:00
jdhao
60852c0473 Switch from LeaderF to Fzf-lua as the default fuzzy finder (#395) 2025-04-02 18:20:01 +02:00
Ya Zhuang
7fa77fbfbf fix typo (#394) 2025-03-31 08:50:35 +02:00
jdhao
f76ef3dbb4 fix diagnostic issues 2025-03-30 21:01:02 +02:00
jdhao
d17289cd6b use builtin log level enum to specify log level (#393) 2025-03-30 21:00:21 +02:00
jdhao
bfc531656a Add option messagesopt config 2025-03-30 20:56:43 +02:00
jdhao
72e6480933 Use LspAttach to configure buffer behavior (#392) 2025-03-30 20:54:53 +02:00
jdhao
625a4ffa47 update config for lazydev and nvim-lightbulb (#391) 2025-03-30 20:21:35 +02:00
jdhao
265f171172 remove unused variable 2025-03-30 18:58:23 +02:00
jdhao
b82c1c112f update colorscheme (#390)
1. Remove catppuccin, it is too purple/blue for me
2. use another nightfox variant
2025-03-30 18:02:28 +02:00
jdhao
0816faee76 Separate diagnostic config from lsp ones (#389) 2025-03-30 17:58:09 +02:00
jdhao
12147bec86 Use glance.nvim for lsp references/implementations preview (#388) 2025-03-30 17:55:51 +02:00
jdhao
a8a1b92921 update floating window highlight (#387) 2025-03-28 20:29:39 +01:00
jdhao
5f662f143b update various config after nvim 0.11 release (#386) 2025-03-28 20:27:02 +01:00
jdhao
f005a8303d Nvim version bump (#385)
* update nvim version to 0.11.0

* replace deprecated nvim_err_write/nvim_err_writeln call

* replace deprecated func for diagnostic and lsp

* use vim.hl instead

* use new way to define diagnostic signs
2025-03-26 22:33:39 +01:00
Okarin
8cba1ba234 Install treesitter on all systems (#384)
For some reason treesitter gets only installed on mac os. This conflicts with treesitter-textobjects which gets installed for every system.
2025-03-21 14:42:33 +01:00
jdhao
a00e1fd92a Remove luarocks (#383)
remove luarocks.nvim as it is causing startup delays
2025-03-05 23:08:27 +01:00
jdhao
2383eb7075 switch back to nvim-cmp (#381) 2025-02-16 21:03:17 +01:00
jdhao
ab059bbb6d use treesitter-textobjects instead (#380)
Note that we should keep the branch of nvim-treesitter and nvim-treesitter-textobjects the same. `main` is targeted at nightly neovim and `master` is for stable neovim. See also https://github.com/nvim-treesitter/nvim-treesitter/issues/4767
2025-02-16 20:15:41 +01:00
jdhao
93166c65a5 update colorscheme config (#379) 2025-02-16 19:52:34 +01:00
jdhao
4b8c490abd fix gitsign word_diff flickering issue (#378)
I guess it is due to the reason that we are doing constant git fetch,
and somehow gitsigns word diff is affected.

Changing the gitsigns debounce or changing lualine refresh rate do not
seem to help. So gitsigns word diff is disabled.
2025-02-16 19:20:21 +01:00
jdhao
2242961925 Remove obsolete func (#377)
- remove function: SynGroup, HasColorscheme and
  GetGitBranch
- rewrite Inside_git_repo in lua instead
2025-02-16 19:13:24 +01:00
jdhao
ac421715d3 Lualine async git info (#376)
make everything async and non-blocking and also remove the branch name fetching. It is not needed if we use the @{upstream} notation.
2025-02-16 01:15:07 +01:00
jdhao
28bda349e8 Update lualine config (#375)
- components are re-ordered
- add new component to show git ahead/behind info
- remove some unused component
2025-02-15 18:58:15 +01:00
jdhao
ee4bce4671 enable mouse in normal mode 2025-02-15 14:36:24 +01:00
jdhao
7f53743255 remove automcd to go to last place
This conflicts with the fuzzy finder, if you grep for a word using fuzzy
finder and then press enter to go to the place, it does not work
anymore, it will go the line where you are last time.
2025-02-14 22:12:33 +01:00
jdhao
94497c0a73 snack config update 2025-02-13 00:41:35 +01:00
jdhao
70e9943aac update supported nvim version to latest stable
Update a few plugins
2025-02-12 23:32:21 +01:00
jdhao
9a6584bec3 add plugin colorzier 2025-01-29 00:21:10 +01:00
jdhao
c7fb090e4c update README 2024-12-22 14:04:56 +01:00
jdhao
a02f317a1d update supported nvim version to v0.10.3 2024-12-22 13:56:41 +01:00
jdhao
f95d4c09b4 disable mouse 2024-12-21 00:03:38 +01:00
jdhao
7e706515a8 silently format lua file using stylua
We need to disable the mapping set for LSP, otherwise the mapping set in
lua.vim will be overridden.
2024-12-19 23:45:15 +01:00
jdhao
1d66475cae make option showcmd shown in statusline instead
Related issues:

+ https://groups.google.com/g/vim_dev/c/YwFLUaduXTQ
+ https://github.com/neovim/neovim/pull/21202
+ https://github.com/nvim-lualine/lualine.nvim/issues/949
2024-12-19 23:39:14 +01:00
jdhao
5328c477a8 reformat with stylua 2024-12-19 22:16:23 +01:00
jdhao
917ab82ffb update dict 2024-12-19 22:13:53 +01:00
jdhao
54eb3ca811 install new plugins 2024-12-19 22:08:56 +01:00
jdhao
64b41fbd58 use native lua api instead of vim.cmd 2024-12-19 22:01:04 +01:00
jdhao
d941be482b update lualine config 2024-12-08 21:34:47 +01:00
jdhao
ab75189231 Fix command CopyPath issue
the string.gsub in lua is not flexible and use vim.fn.substitute()
instead.
2024-11-29 23:25:19 +01:00
jdhao
7645751dc1 Update readme 2024-11-27 00:05:38 +01:00
jdhao
8880268140 custom command update
1. Add new command `CopyPath`
2. Revise command `JSONFormat`: implemented using the nvim lua interface
   and fix a few issues. The previous implementation is removed.
2024-11-27 00:05:38 +01:00
jdhao
d86f599483 update the fold level allowed for statuscol.nvim 2024-11-08 22:57:33 +01:00
jdhao
8dfae271d0 use plaintext for pyright hover request
see my comment here for the details: https://www.reddit.com/r/neovim/comments/1gdv1rc/comment/lvt9nlm/
2024-11-07 21:53:32 +01:00
jdhao
1141a18c5f update config for pyright 2024-11-06 23:19:55 +01:00
jdhao
fe3d5e5922 remove plugin committia.vim 2024-11-05 22:16:54 +01:00
jdhao
9769c24633 Switch Python LSP for completion and add ruff
pyright servers type checking, completion, and ruff servers linting and
diagnostics (ruff can also format Python files, but it is slightly
different from black)
2024-11-05 22:09:33 +01:00
jdhao
97f72936ac Enable LSP format also for visual selection 2024-11-05 22:04:49 +01:00
jdhao
94cade03be enable inlayhint for lua_ls server
The client side inlayhint can be enabled by uncommentting the code in
this PR.
2024-11-05 22:01:23 +01:00
jdhao
590bd6c7e6 use stylua to format lua files 2024-11-05 21:56:18 +01:00
jdhao
4171f190f2 Add plugin nvim-lightbulb to hint code actions 2024-11-05 21:47:34 +01:00
jdhao
5426c88a90 update Leaderf setting
Only search file content and not file name when using Leaderf rg
2024-11-05 21:44:34 +01:00
jdhao
d715ce8f31 update supported nvim version to 0.10.2 2024-10-09 18:00:15 +02:00
jdhao
3040fa7969 use a cmp-fork for now
Until cmp is maintained again or switch??
2024-10-09 17:37:21 +02:00
jdhao
b9cf3cc6ed update conf for plugin live-command.nvim 2024-09-20 21:26:28 +02:00
jdhao
154cde3d71 Add plugin live-command.nvim 2024-09-19 22:07:03 +02:00
jdhao
81f64ed32e Use absolute path for viml config
Full path should be used to load viml config, otherwise, when we open
nvim in other directories, we see errors that the viml config can not be
found.
2024-09-02 22:19:52 +02:00
jdhao
db380ca7a7 remove inspect() from lua _G table
Nvim nows provides `vim.inspect()` and `vim.print()`.
2024-09-01 21:47:21 +02:00
jdhao
51f81093da restructure init.lua 2024-08-31 21:25:18 +02:00
jdhao
a9fc298063 update documentation for resuming cursor position 2024-08-30 01:03:13 +02:00
jdhao
9071e045eb Make * and # search case aware
By default, when you press `*` to search word under the cursor, the
option `smartcase` is ignored. This means that if you press `*` when
your cursor is on `The`, the lower case one `the` is also searched.

In this commit, we translate star and # search into normal search so that
'smartcase' option is respected.
2024-08-30 01:01:04 +02:00
jdhao
fa79647a63 Fix type for option relativenumber
"relativenumber" should be window local option, not buffer local option.
2024-08-29 21:45:07 +02:00
jdhao
4b4ff5f549 Add error handling for resuming the cursor
This will close issue #328.
2024-08-29 21:41:13 +02:00
jdhao
12b0ff02b6 Move autocmd in viml to Lua 2024-08-27 23:12:33 +02:00
jdhao
e3930e8aa7 remove unused plugins 2024-08-25 23:36:29 +02:00
jdhao
21522bd194 update config for yanky 2024-08-25 23:34:03 +02:00
jdhao
a3c8b3d5b5 Update configuration for nvim-cmp
1. restrict max width of the completion menu. Here I am using
   lspkind.nvim to achieve this. There are other native ways to do this,
   see also https://github.com/hrsh7th/nvim-cmp/discussions/609 and
   https://github.com/hrsh7th/nvim-cmp/issues/980
2. remove cmp-emoji as it is rarely used and interfere when I write
   Python
3. lower the transparency for popup menu
2024-08-20 01:04:02 +02:00
jdhao
d150f39afc Add new plugins 2024-08-19 23:37:57 +02:00
jdhao
3904cd4ccf Update config for handling large files 2024-08-19 23:34:21 +02:00
jdhao
95d3b2f2d8 remove setting for JSON file 2024-08-19 22:36:58 +02:00
jdhao
c3d8dc3e1d Add mapping to delete other buffers 2024-08-17 17:33:36 +02:00
jdhao
f9780c2dff update config for bufferline.nvim
Do not show buffer number and use a mapping to pick buffer instead.
2024-08-17 17:29:33 +02:00
jdhao
256c37a946 update vim-fugitive mapping 2024-08-17 15:16:08 +02:00
jdhao
eff98d036d update README 2024-08-17 15:10:33 +02:00
jdhao
6e60475f3f Use gx.nvim for browsing in Browser 2024-08-16 00:03:43 +02:00
jdhao
d90273df8e remove lua_ls conf in favor of lazydev.nvim
The removed settings are already set by lazydev.nvim.
2024-08-15 23:44:50 +02:00
jdhao
659f410b9e move version check into function 2024-08-15 23:38:31 +02:00
jdhao
a602d98819 fix git mapping issue
`<cmd> `mapping must end with `<CR>`
2024-08-09 22:23:04 +02:00
jdhao
9ff76931e3 update git related mappings 2024-08-09 22:19:13 +02:00
jdhao
85232b82a8 Update mapping of plugin open-browser.vim 2024-08-09 22:05:54 +02:00
jdhao
cfc0089bb5 add plugin lazydev.nvim 2024-08-07 00:48:21 +08:00
jdhao
f1062a3d8f filter fold level sign for statuscol.nvim
Only show fold signs for fold level below a certain level to avoid
clutter the left side columns with a lot of folding signs
2024-08-07 00:14:19 +08:00
jdhao
fd6df981cd Update nvim-ufo settings 2024-08-06 23:58:54 +08:00
jdhao
8af8ebd72a remove statusline.lua 2024-08-06 17:25:33 +02:00
jdhao
4c697d89f3 change name of lualine config 2024-08-06 23:04:37 +08:00
jdhao
e6f95cedb1 Update installation doc 2024-08-06 06:51:39 +08:00
jdhao
262ad6aa38 Add new colorscheme kanagawa 2024-08-06 06:16:07 +08:00
jdhao
b30cc9ed78 update user dictionary 2024-08-06 06:05:20 +08:00
jdhao
b3a26e4226 update load condtion for nvim-tree 2024-08-06 06:02:02 +08:00
jdhao
794b098090 Add git blame mapping 2024-08-06 05:59:14 +08:00
jdhao
b728b39784 update type hint for functions 2024-08-06 05:35:19 +08:00
jdhao
acc3ed7829 show error message only when no word is under cursor 2024-08-06 05:33:24 +08:00
jdhao
44e9e5a1ce Fix lua_ls diagnostic warnings 2024-08-06 05:24:16 +08:00
jdhao
5502d29f40 update config related to folding
1. For python and lua, rely on LSP for folding
2. show fold signs on the right of the number column
2024-08-06 05:17:51 +08:00
jdhao
fe95658319 Add colorscheme arctic.nvim 2024-08-05 06:25:28 +08:00
jdhao
e165276763 fix error when there is no cursor word 2024-08-05 06:23:18 +08:00
jdhao
933b887281 update config for nvim-ufo 2024-08-05 05:50:45 +08:00
jdhao
69643e143a use plugin nvim-ufo for better folding
The settings are copied from https://github.com/kevinhwang91/nvim-ufo/issues/4#issuecomment-1514537245,
with some modification.
2024-08-05 05:27:49 +08:00
jdhao
7f4772fd31 update setting for colorscheme gruvbox-material 2024-08-05 05:04:35 +08:00
jdhao
bf49e90947 change value for option 'splitkeep' 2024-08-05 05:03:02 +08:00
jdhao
784b435f0e update LeaderF settings 2024-08-02 23:41:36 +08:00
jdhao
beec97c086 Fix firenvim and LeaderF build issues
In lazy.nvim, the `build` parameter accept value in different format.
If the value is
1. a string and starts with `:`, it will be treated as vim command
2. a string and starts without `:`, it will be treated as shell command
3. a function. Lazy.nvim will run this function

I compared closely between case 1 and case 3. In case 1, when lazy.nvim
runs the viml command, the runtimepath is already populated with the
current plugin we are trying to build.
However in case 3, the runtimepath is not populated with the plugin
path, which means that any command you run by this plugin is not
available.

So I did it in a hacky way to add the plugin path to runtimepath
manually, and source it manually using `:runtime` command. The `:
runtime` command is needed because in the init process, adding the
plugin path to runtimepath does not ensure that the script under this
plugin is sourced immediately. So if we want to use the command/function
immediately, we need to source it manually, see also https://github.com/neovim/neovim/issues/29957.
2024-08-02 23:38:16 +08:00
jdhao
bbb8545403 update lualine config
- rearrange a few components
- add and remove a few components
2024-08-02 06:23:21 +08:00
jdhao
9efadac8fb update lazy.nvim config 2024-08-01 04:14:34 +08:00
jdhao
6e137fe9a3 make firenvim work again
1. fix build issue
2. fix PATH env issue
2024-07-31 07:09:50 +08:00
jdhao
719fbfc1ab update lua_ls settings 2024-07-31 05:42:33 +08:00
jdhao
e815de294f update plugin for markdown preview 2024-07-27 03:25:36 +08:00
jdhao
ca7430056c update to neovim version 0.10.1 2024-07-26 03:32:54 +08:00
jdhao
cb8c9208e1 update which-key conf and some mappings 2024-07-25 04:00:17 +08:00
jdhao
ce1e13e2c9 use plugin nvim-autopairs for autopair
delimitMate is not updated for a long time.
2024-07-14 05:17:49 +08:00
jdhao
2af616bb0d Update hop.nvim conf to support Chinese 2024-06-26 03:33:24 +08:00
jdhao
3694d3c237 Update config for GitSigns 2024-06-26 03:25:01 +08:00
jdhao
69d8543495 remove emmylua since neovim has builtin annotation
Seee also this https://github.com/neovim/neovim/pull/24493
2024-05-20 22:09:07 +02:00
jdhao
be3d134c37 use vim.uv instead of vim.loop 2024-05-20 21:52:52 +02:00
jdhao
601396f700 upgrade neovim to latest stable
The way to compare versions are changed due to a bug in comparing
versions in the neovim core: https://github.com/neovim/neovim/issues/28782
2024-05-20 21:33:38 +02:00
jdhao
e462ebcbcc Enable treesitter folding for Python and Lua 2024-05-08 03:46:45 +08:00
jdhao
2f8482639d update some mappings
1. fix a typo in gJ mapping when setting the mark, the correct syntax is
   `mz` (set mark `z`), not `zm`

2. fix bug with `iB` text object: previously `viB` does not work as
   expected, because it does not select the entire buffer as expected.
   After much investigation, I found it is because the `<cmd>` mapping
   argument. If we use `<cmd>` argument for mapping, the mode does not
   change. So if we use `viB`, inititally we are still in visual mode.
   Later in the implementation, when we use `` normal! `<V`>  `` to
   select the entire buffer, it interferes with original visual mode. As
   a result, the entire buffer is not selected. In the text obj
   implementation, we can use `exe "normal! \<Esc>"` to clear the visual
   mode and make `viB`, but this is not ideal. I think it is eaiser to
   just not use the `<cmd>` argument and use `:<C-U>` instead.
2024-02-28 06:36:05 +08:00
jdhao
050eacaee2 Stop showing percent location
The percent location is useless and just noise.
2024-02-23 06:11:21 +08:00
jdhao
01bc4b40d3 update used plugins 2024-02-02 03:52:26 +08:00
jdhao
c06d46e84d remove lazylock
I don't use this feature at all.
2024-02-02 03:43:55 +08:00
jdhao
7cf70f31af Update colorscheme conf
1. remove some colorscheme that doesn't work well with Markdown
2. change how the colorscheme conf is organized.
2024-02-02 03:40:11 +08:00
jdhao
8416508686 Enable nvim-tree to open dir during startup
Now when you open a directory when starting nvim, nvim-tree will be
opened to handle the directory correctly, see also issue #257.
2024-01-07 15:24:47 +01:00
jdhao
df9491b05b bump neovim version to 0.9.5 2024-01-07 14:45:29 +01:00
jdhao
17d2e3ab3e Deal with other variant of unix timestamp 2023-10-21 00:53:15 +02:00
jdhao
2c9948300d Add diffview.nvim for viewing diffs 2023-10-18 22:10:11 +02:00
jdhao
dfaa3d97a5 update plugin spec 2023-10-12 23:26:43 +02:00
jdhao
8d74fcb75c Remove obsolete options for nvim-tree 2023-10-11 20:43:24 +02:00
jdhao
b1f0ef63ef Rename vimscript conf directory 2023-10-11 20:41:25 +02:00
jdhao
54ca6d4191 update to nvim 0.9.4 2023-10-11 20:35:50 +02:00
jdhao
97af59e670 remove obsolete option for indent-blankline 2023-10-03 15:14:34 +02:00
jdhao
4d8ef868ad upgrade indent-blankline to v3 2023-09-28 23:41:42 +02:00
jdhao
3137850db6 Show Py virtual env on statusline 2023-09-28 09:42:27 +02:00
jdhao
eccdc62f38 remove colorschemes rose-pine 2023-09-22 19:38:28 +02:00
jdhao
ad483a7dc0 Use the matained fork of hop.nvim 2023-09-16 14:47:43 +02:00
jdhao
6df27d1c22 upgrade to neovim 0.9.2 2023-09-16 14:26:38 +02:00
jdhao
7f6627cfa1 update plugin conf for Lazy.nvim 2023-09-10 22:16:16 +02:00
jdhao
7ff11a9760 update plugin lazy loading events 2023-09-05 00:22:02 +02:00
jdhao
cc4688d089 Loosen the version check condition
Other version of nvim can still run this config, but should use with
care.
2023-09-01 21:39:08 +02:00
jdhao
8a1b3193a4 fix bufferline loading issue 2023-09-01 21:27:13 +02:00
jdhao
e92362041c fix hlslens issue when no pattern is found
The captured error message is not correct before.
2023-09-01 21:22:22 +02:00
jdhao
63ff776758 fix loading order of nvim-cmp and nvim-lsp 2023-09-01 20:52:46 +02:00
jdhao
41c8c81f21 update spell 2023-09-01 01:08:41 +02:00
jdhao
997c6286df Optimize plugin loading speed 2023-09-01 01:07:16 +02:00
jdhao
359621b126 fix multi visual line delete issue
For TextYankPost event, it includes both yank and delete, we should only
restore cursor position for yank, not for delete. Otherwise, it messes
up with text deletion when you visually select multiple lines and delete
them. See also issue reported here: https://github.com/jdhao/nvim-config/pull/222#issuecomment-1698634645
2023-09-01 00:26:08 +02:00
jdhao
4dc2d9575b disable horizontal scroll by mouse 2023-08-29 23:44:07 +02:00
jdhao
fc1c447319 fix multi-line yank issue, close #220
The previous way of keep the cursor while yanking is not perfect.
It will break multi-line yank (`{count}yy`).
2023-08-28 21:11:32 +02:00
jdhao
1391ca7ff1 feat: switch from packer.nvim to lazy.nvim 2023-08-27 23:14:31 +02:00
jdhao
6a6f8ff597 Update condition for installing vim-xkbswitch 2023-08-23 00:48:21 +02:00
jdhao
946e65662b fix nvimtree conf, close #215 2023-08-14 23:55:17 +02:00
jdhao
4a6379ca5d update git-linker conf
1. Add configuration for azure devops
2. change the mappings slightly
2023-08-09 19:52:58 +02:00
jdhao
855a88b532 fix: user lua conf reloading fails
The cache should be invalidated. This fix does not work 100%, because, e.g.,
there are other configs hiding deeper under lua/config/ directory.
A restart is the best way to reload the config.
2023-07-29 14:34:42 +02:00
jdhao
892cd49f06 doc: update doc and install guide for pylsp 2023-07-29 13:09:37 +02:00
jdhao
e53ee104ec feat: move lua conf under lua directory 2023-07-28 22:28:36 +02:00
jdhao
671c78df9b feat: more ignore files for LeaderF (#209) 2023-07-29 04:09:50 +08:00
jdhao
1608a36dd3 fix: conf is not local 2023-07-25 23:00:25 +02:00
jdhao
450f058da5 feat: support venv in Mypy
Specify the correct python executable path for mypy to work well.
2023-07-25 22:59:06 +02:00
jdhao
e2f348cb37 fix: missing nerdfonts
Since wezterm upgrade its support for Nerd Fonts 3.0, we should update
the codepoints used for some of the Unicode Icons. Their code points are
changed due to breaking changes in Nerd Fonts.
2023-07-25 22:53:20 +02:00
jdhao
fc8175d32d feat: update diagnostic mappings
Use separate key mappings to show diagnostics for the current buffer and
all opened files.
2023-07-22 15:01:41 +02:00
jdhao
4034b6b673 feat: update pylsp conf
1. support using black as formatter
2. replace obsolete pyls-isort with maintained ones
2023-07-22 14:51:27 +02:00
jdhao
67a4b6e6d0 feat: add treesitter toml 2023-07-22 14:46:10 +02:00
jdhao
bb27d93433 fix: move location indication to the right of statusline 2023-07-20 23:00:06 +02:00
jdhao
9d9c3ef32f feat: update diagnostic position in statusline
Do not show it in far right, move it to the left side for easier
visibility.
2023-07-20 22:52:55 +02:00
jdhao
00e8c77b23 Fix LeaderF bug
It will add files to buffer list even if we have not confirmed the
selection. This behavior is really annoying.
See also 27bd938a42.
2023-06-27 20:39:26 +02:00
59 changed files with 2318 additions and 1687 deletions

1
.gitignore vendored
View File

@@ -4,3 +4,4 @@ en.utf-8.add.spl
.netrwhist .netrwhist
*.log *.log
.DS_Store .DS_Store
lazy-lock.json

View File

@@ -9,11 +9,8 @@
<a> <a>
<img alt="Windows" src="https://img.shields.io/badge/Windows-%23.svg?style=flat-square&logo=windows&color=0078D6&logoColor=white" /> <img alt="Windows" src="https://img.shields.io/badge/Windows-%23.svg?style=flat-square&logo=windows&color=0078D6&logoColor=white" />
</a> </a>
<a href="https://github.com/jdhao/nvim-config/releases/latest">
<img alt="Latest release" src="https://img.shields.io/github/v/release/jdhao/nvim-config" />
</a>
<a href="https://github.com/neovim/neovim/releases/tag/stable"> <a href="https://github.com/neovim/neovim/releases/tag/stable">
<img src="https://img.shields.io/badge/Neovim-0.9.1-blueviolet.svg?style=flat-square&logo=Neovim&logoColor=green" alt="Neovim minimum version"/> <img src="https://img.shields.io/badge/Neovim-0.11.2-blueviolet.svg?style=flat-square&logo=Neovim&logoColor=green" alt="Neovim minimum version"/>
</a> </a>
<a href="https://github.com/jdhao/nvim-config/search?l=vim-script"> <a href="https://github.com/jdhao/nvim-config/search?l=vim-script">
<img src="https://img.shields.io/github/languages/top/jdhao/nvim-config" alt="Top languages"/> <img src="https://img.shields.io/github/languages/top/jdhao/nvim-config" alt="Top languages"/>
@@ -21,9 +18,6 @@
<a href="https://github.com/jdhao/nvim-config/graphs/commit-activity"> <a href="https://github.com/jdhao/nvim-config/graphs/commit-activity">
<img src="https://img.shields.io/github/commit-activity/m/jdhao/nvim-config?style=flat-square" /> <img src="https://img.shields.io/github/commit-activity/m/jdhao/nvim-config?style=flat-square" />
</a> </a>
<a href="https://github.com/jdhao/nvim-config/releases/tag/v0.9.1">
<img src="https://img.shields.io/github/commits-since/jdhao/nvim-config/v0.9.1?style=flat-square" />
</a>
<a href="https://github.com/jdhao/nvim-config/graphs/contributors"> <a href="https://github.com/jdhao/nvim-config/graphs/contributors">
<img src="https://img.shields.io/github/contributors/jdhao/nvim-config?style=flat-square" /> <img src="https://img.shields.io/github/contributors/jdhao/nvim-config?style=flat-square" />
</a> </a>
@@ -57,14 +51,14 @@ and how to set up on different platforms (Linux, macOS, and Windows).
# Features # # Features #
+ Plugin management via [Packer.nvim](https://github.com/wbthomason/packer.nvim). + Plugin management via [Lazy.nvim](https://github.com/folke/lazy.nvim).
+ Code, snippet, word auto-completion via [nvim-cmp](https://github.com/hrsh7th/nvim-cmp). + Code, snippet, word auto-completion via [nvim-cmp](https://github.com/hrsh7th/nvim-cmp).
+ Language server protocol (LSP) support via [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig). + Language server protocol (LSP) support via [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig).
+ Git integration via [vim-fugitive](https://github.com/tpope/vim-fugitive). + Git integration via [vim-fugitive](https://github.com/tpope/vim-fugitive).
+ Better escaping from insert mode via [better-escape.vim](https://github.com/nvim-zh/better-escape.vim). + Better escaping from insert mode via [better-escape.vim](https://github.com/nvim-zh/better-escape.vim).
+ Ultra-fast project-wide fuzzy searching via [LeaderF](https://github.com/Yggdroot/LeaderF). + Ultra-fast project-wide fuzzy searching via [fzf-lua](https://github.com/ibhagwan/fzf-lua).
+ Faster code commenting via [vim-commentary](https://github.com/tpope/vim-commentary). + Faster code commenting via [vim-commentary](https://github.com/tpope/vim-commentary).
+ Faster matching pair insertion and jump via [delimitMate](https://github.com/Raimondi/delimitMate). + Faster matching pair insertion and jump via [nvim-autopairs](https://github.com/windwp/nvim-autopairs).
+ Smarter and faster matching pair management (add, replace or delete) via [vim-sandwich](https://github.com/machakann/vim-sandwich). + Smarter and faster matching pair management (add, replace or delete) via [vim-sandwich](https://github.com/machakann/vim-sandwich).
+ Fast buffer jump via [hop.nvim](https://github.com/phaazon/hop.nvim). + Fast buffer jump via [hop.nvim](https://github.com/phaazon/hop.nvim).
+ Powerful snippet insertion via [Ultisnips](https://github.com/SirVer/ultisnips). + Powerful snippet insertion via [Ultisnips](https://github.com/SirVer/ultisnips).
@@ -72,7 +66,6 @@ and how to set up on different platforms (Linux, macOS, and Windows).
+ File tree explorer via [nvim-tree.lua](https://github.com/nvim-tree/nvim-tree.lua). + File tree explorer via [nvim-tree.lua](https://github.com/nvim-tree/nvim-tree.lua).
+ Better quickfix list with [nvim-bqf](https://github.com/kevinhwang91/nvim-bqf). + Better quickfix list with [nvim-bqf](https://github.com/kevinhwang91/nvim-bqf).
+ Show search index and count with [nvim-hlslens](https://github.com/kevinhwang91/nvim-hlslens). + Show search index and count with [nvim-hlslens](https://github.com/kevinhwang91/nvim-hlslens).
+ Command line auto-completion via [wilder.nvim](https://github.com/gelguy/wilder.nvim).
+ User-defined mapping hint via [which-key.nvim](https://github.com/folke/which-key.nvim). + User-defined mapping hint via [which-key.nvim](https://github.com/folke/which-key.nvim).
+ Asynchronous code execution via [asyncrun.vim](https://github.com/skywind3000/asyncrun.vim). + Asynchronous code execution via [asyncrun.vim](https://github.com/skywind3000/asyncrun.vim).
+ Code highlighting via [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter). + Code highlighting via [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter).
@@ -82,8 +75,8 @@ and how to set up on different platforms (Linux, macOS, and Windows).
+ LaTeX editing and previewing via [vimtex](https://github.com/lervag/vimtex) + LaTeX editing and previewing via [vimtex](https://github.com/lervag/vimtex)
+ Animated GUI style notification via [nvim-notify](https://github.com/rcarriga/nvim-notify). + Animated GUI style notification via [nvim-notify](https://github.com/rcarriga/nvim-notify).
+ Tags navigation via [vista](https://github.com/liuchengxu/vista.vim). + Tags navigation via [vista](https://github.com/liuchengxu/vista.vim).
+ Code formatting via [Neoformat](https://github.com/sbdchd/neoformat).
+ Undo management via [vim-mundo](https://github.com/simnalamburt/vim-mundo) + Undo management via [vim-mundo](https://github.com/simnalamburt/vim-mundo)
+ Code folding with [nvim-ufo](https://github.com/kevinhwang91/nvim-ufo) and [statuscol.nvim](https://github.com/luukvbaal/statuscol.nvim)
+ ...... + ......
# UI Demo # UI Demo
@@ -96,10 +89,10 @@ For more UI demos, check [here](https://github.com/jdhao/nvim-config/issues/15).
<img src="https://user-images.githubusercontent.com/16662357/183256752-fb23b215-a6b8-4646-beed-9999f52d53f1.png" width="800"> <img src="https://user-images.githubusercontent.com/16662357/183256752-fb23b215-a6b8-4646-beed-9999f52d53f1.png" width="800">
</p> </p>
## File fuzzy finding using LeaderF ## File fuzzy finding using fzf-lua
<p align="center"> <p align="center">
<img src="https://user-images.githubusercontent.com/16662357/183257017-2d9d7605-3c4b-4e1d-8955-30998f9b6f28.gif" width="800"> <img src="https://github.com/user-attachments/assets/3199e35d-121a-487b-bfd1-58eb69b0b48a" width="800">
</p> </p>
## Code autocompletion with nvim-cmp ## Code autocompletion with nvim-cmp
@@ -114,12 +107,6 @@ For more UI demos, check [here](https://github.com/jdhao/nvim-config/issues/15).
<img src="https://user-images.githubusercontent.com/16662357/128590833-aaa05d53-19ef-441d-a5a9-ba1bbd3936c1.gif" width="800"> <img src="https://user-images.githubusercontent.com/16662357/128590833-aaa05d53-19ef-441d-a5a9-ba1bbd3936c1.gif" width="800">
</p> </p>
## Command-line autocompletion with wilder.nvim
<p align="center">
<img src="https://user-images.githubusercontent.com/16662357/147677787-8e5d229a-a16a-420e-98f5-88f2a1be84a2.gif" width="800">
</p>
## Tags ## Tags
<p align="center"> <p align="center">
@@ -140,6 +127,12 @@ Go to a string starting with `se`
<img src="https://user-images.githubusercontent.com/16662357/128589873-aadb8264-1098-4834-9876-fa66a309be05.gif" width="800"> <img src="https://user-images.githubusercontent.com/16662357/128589873-aadb8264-1098-4834-9876-fa66a309be05.gif" width="800">
</p> </p>
## code folding with nvim-ufo and statuscol.nvim
<p align="center">
<img src="https://github.com/user-attachments/assets/a01a56b2-7c91-43de-b305-f2fbaa81dcec" width="800">
</p>
# Shortcuts # Shortcuts
Some of the shortcuts I use frequently are listed here. In the following shortcuts, `<leader>` represents ASCII character `,`. Some of the shortcuts I use frequently are listed here. In the following shortcuts, `<leader>` represents ASCII character `,`.
@@ -165,12 +158,14 @@ Some of the shortcuts I use frequently are listed here. In the following shortcu
| `<space>t` | Normal | Linux/macOS/Win | Toggle tag window (show project tags in the right window) | | `<space>t` | Normal | Linux/macOS/Win | Toggle tag window (show project tags in the right window) |
| `<leader>gs` | Normal | Linux/macOS/Win | Show Git status result | | `<leader>gs` | Normal | Linux/macOS/Win | Show Git status result |
| `<leader>gw` | Normal | Linux/macOS/Win | Run Git add for current file | | `<leader>gw` | Normal | Linux/macOS/Win | Run Git add for current file |
| `<leader>gd` | Normal | Linux/macOS/Win | Run git diff for current file |
| `<leader>gc` | Normal | Linux/macOS/Win | Run git commit | | `<leader>gc` | Normal | Linux/macOS/Win | Run git commit |
| `<leader>gpl` | Normal | Linux/macOS/Win | Run git pull | | `<leader>gpl` | Normal | Linux/macOS/Win | Run git pull |
| `<leader>gpu` | Normal | Linux/macOS/Win | Run git push | | `<leader>gpu` | Normal | Linux/macOS/Win | Run git push |
| `<leader>gl` | Normal/Visual | Linux/macOS/Win | Get perm link for current/visually-select lines | `<leader>gbd` | Normal | Linux/macOS/Win | Delete a branch |
| `<leader>gb` | Normal | macOS | Browse current git repo in browser | `<leader>gbn` | Normal | Linux/macOS/Win | Create a new branch |
| `<leader>gl` | Normal/Visual | Linux/macOS/Win | Get perm link for current/visually-select lines |
| `<leader>gbr` | Normal | macOS | Browse current git repo in browser |
| `<leader>gb` | Visual | macOS | Blame current line |
| `<F9>` | Normal | Linux/macOS/Win | Compile&run current source file (for C++, LaTeX, Lua, Python) | | `<F9>` | Normal | Linux/macOS/Win | Compile&run current source file (for C++, LaTeX, Lua, Python) |
| `<F11>` | Normal | Linux/macOS/Win | Toggle spell checking | | `<F11>` | Normal | Linux/macOS/Win | Toggle spell checking |
| `<F12>` | Normal | Linux/macOS/Win | Toggle paste mode | | `<F12>` | Normal | Linux/macOS/Win | Toggle paste mode |
@@ -182,7 +177,6 @@ Some of the shortcuts I use frequently are listed here. In the following shortcu
| `Alt-j` | Normal | Linux/macOS/Win | Move current line or selected lines down | | `Alt-j` | Normal | Linux/macOS/Win | Move current line or selected lines down |
| `Alt-m` | Normal | macOS/Win | Markdown previewing in system browser | | `Alt-m` | Normal | macOS/Win | Markdown previewing in system browser |
| `Alt-Shift-m` | Normal | macOS/Win | Stopping Markdown previewing in system browser | | `Alt-Shift-m` | Normal | macOS/Win | Stopping Markdown previewing in system browser |
| `ob` | Normal/Visual | macOS/Win | Open link under cursor or search visual selection |
| `ctrl-u` | Insert | Linux/macOS/Win | Turn word under cursor to upper case | | `ctrl-u` | Insert | Linux/macOS/Win | Turn word under cursor to upper case |
| `ctrl-t` | Insert | Linux/macOS/Win | Turn word under cursor to title case | | `ctrl-t` | Insert | Linux/macOS/Win | Turn word under cursor to title case |
| `jk` | Insert | Linux/macOS/Win | Return to Normal mode without lagging | | `jk` | Insert | Linux/macOS/Win | Return to Normal mode without lagging |
@@ -192,10 +186,12 @@ Some of the shortcuts I use frequently are listed here. In the following shortcu
In addition to commands provided by various plugins, I have also created some custom commands for personal use. In addition to commands provided by various plugins, I have also created some custom commands for personal use.
| command | description | example | | command | description | example |
|------------|-------------------------------------------------------------------------|--------------------------------| |--------------|-------------------------------------------------------------------------|--------------------------------|
| `Redir` | capture command output to a tabpage for easier inspection. | `Redir hi` | | `Redir` | capture command output to a tabpage for easier inspection. | `Redir hi` |
| `Edit` | edit multiple files at the same time, supports globing | `Edit *.vim` | | `Edit` | edit multiple files at the same time, supports globing | `Edit *.vim` |
| `Datetime` | print current date and time or convert Unix time stamp to date and time | `Datetime 12345` or `Datetime` | | `Datetime` | print current date and time or convert Unix time stamp to date and time | `Datetime 12345` or `Datetime` |
| `JSONFormat` | format a JSON file | `JSONFormat` |
| `CopyPath` | copy current file path to clipboard | `CopyPath relative` |
# Contributing # Contributing

View File

@@ -34,6 +34,3 @@ function s:create_term_buf(_type, size) abort
endif endif
execute 'resize ' . a:size execute 'resize ' . a:size
endfunction endfunction
" For delimitMate
let b:delimitMate_matchpairs = "(:),[:],{:}"

View File

@@ -1,6 +0,0 @@
" let the initial folding state be that all folds are closed.
set foldlevel=0
" Use nvim-treesitter for folding
set foldmethod=expr
set foldexpr=nvim_treesitter#foldexpr()

View File

@@ -4,5 +4,4 @@ set formatoptions-=r
nnoremap <buffer><silent> <F9> :luafile %<CR> nnoremap <buffer><silent> <F9> :luafile %<CR>
" For delimitMate nnoremap <buffer><silent> <space>f <cmd>silent !stylua %<CR>
let b:delimitMate_matchpairs = "(:),[:],{:}"

107
after/ftplugin/markdown.lua Normal file
View File

@@ -0,0 +1,107 @@
local function add_reference_at_end(label, url, title)
vim.schedule(function()
local bufnr = vim.api.nvim_get_current_buf()
local line_count = vim.api.nvim_buf_line_count(bufnr)
-- Prepare reference definition
local ref_def = "[" .. label .. "]: " .. url
if title and title ~= "" then
ref_def = ref_def .. ' "' .. title .. '"'
end
-- Check if references section exists
local buffer_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
local has_ref_section = false
for _, line in ipairs(buffer_lines) do
if line:match("^%s*<!%-%-.*[Rr]eferences.*%-%->[%s]*$") then
has_ref_section = true
break
end
end
local lines_to_add = {}
-- Add references header if it doesn't exist
if not has_ref_section then
if #lines_to_add == 0 then
table.insert(lines_to_add, "")
end
table.insert(lines_to_add, "<!-- References -->")
end
table.insert(lines_to_add, ref_def)
-- Insert at buffer end
vim.api.nvim_buf_set_lines(bufnr, line_count, line_count, false, lines_to_add)
end)
end
local function get_ref_link_labels()
local labels = {}
local seen = {} -- To avoid duplicates
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
for _, line in ipairs(lines) do
-- Pattern explanation:
-- %[.-%] matches [link text] (non-greedy)
-- %[(.-)%] matches [label] and captures the label content
local start_pos = 1
while start_pos <= #line do
local match_start, match_end, label = string.find(line, "%[.-%]%[(.-)%]", start_pos)
if not match_start then
break
end
-- Only add unique labels
if label and label ~= "" and not seen[label] then
table.insert(labels, label)
seen[label] = true
end
start_pos = match_end + 1
end
end
return labels
end
local function count_consecutive_spaces(str)
-- Remove leading spaces first
local trimmed = str:match("^%s*(.*)")
local count = 0
-- Count each sequence of one or more consecutive spaces
for spaces in trimmed:gmatch("%s+") do
count = count + 1
end
return count
end
vim.api.nvim_buf_create_user_command(0, "AddRef", function(opts)
local args = vim.split(opts.args, " ", { trimempty = true })
if #args < 2 then
vim.print("Usage: :AddRef <label> <url>")
return
end
local label = args[1]
local url = args[2]
add_reference_at_end(label, url, "")
end, {
desc = "Add reference link at buffer end",
nargs = "+",
complete = function(arg_lead, cmdline, curpos)
vim.print(string.format("arg_lead: '%s', cmdline: '%s', curpos: %d", arg_lead, cmdline, curpos))
-- only complete the first argument
if count_consecutive_spaces(cmdline) > 1 then
-- we are now starting the second argument, so no completion anymore
return {}
end
local ref_link_labels = get_ref_link_labels()
return ref_link_labels
end,
})

View File

@@ -13,5 +13,4 @@ set softtabstop=4 " number of spaces in tab when editing
set shiftwidth=4 " number of spaces to use for autoindent set shiftwidth=4 " number of spaces to use for autoindent
set expandtab " expand tab to spaces so that tabs are spaces set expandtab " expand tab to spaces so that tabs are spaces
" For delimitMate nnoremap <buffer><silent> <space>f <cmd>silent !black %<CR>
let b:delimitMate_matchpairs = "(:),[:],{:}"

3
after/lsp/clangd.lua Normal file
View File

@@ -0,0 +1,3 @@
return {
filetypes = { "c", "cpp", "cc" },
}

8
after/lsp/ltex.lua Normal file
View File

@@ -0,0 +1,8 @@
return {
filetypes = { "text", "plaintex", "tex", "markdown" },
settings = {
ltex = {
language = "en",
},
},
}

14
after/lsp/lua_ls.lua Normal file
View File

@@ -0,0 +1,14 @@
-- settings for lua-language-server can be found on https://luals.github.io/wiki/settings/
return {
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = "LuaJIT",
},
hint = {
enable = true,
},
},
},
}

51
after/lsp/pyright.lua Normal file
View File

@@ -0,0 +1,51 @@
-- For what diagnostic is enabled in which type checking mode, check doc:
-- https://github.com/microsoft/pyright/blob/main/docs/configuration.md#diagnostic-settings-defaults
-- Currently, the pyright also has some issues displaying hover documentation:
-- https://www.reddit.com/r/neovim/comments/1gdv1rc/what_is_causeing_the_lsp_hover_docs_to_looks_like/
local new_capability = {
-- this will remove some of the diagnostics that duplicates those from ruff, idea taken and adapted from
-- here: https://github.com/astral-sh/ruff-lsp/issues/384#issuecomment-1989619482
textDocument = {
publishDiagnostics = {
tagSupport = {
valueSet = { 2 },
},
},
hover = {
contentFormat = { "plaintext" },
dynamicRegistration = true,
},
},
}
return {
cmd = { "delance-langserver", "--stdio" },
settings = {
pyright = {
-- disable import sorting and use Ruff for this
disableOrganizeImports = true,
disableTaggedHints = false,
},
python = {
analysis = {
autoSearchPaths = true,
diagnosticMode = "workspace",
typeCheckingMode = "standard",
useLibraryCodeForTypes = true,
-- we can this setting below to redefine some diagnostics
diagnosticSeverityOverrides = {
deprecateTypingAliases = false,
},
-- inlay hint settings are provided by pylance?
inlayHints = {
callArgumentNames = "partial",
functionReturnTypes = true,
pytestParameters = true,
variableTypes = true,
},
},
},
},
capabilities = new_capability,
}

8
after/lsp/ruff.lua Normal file
View File

@@ -0,0 +1,8 @@
return {
init_options = {
-- the settings can be found here: https://docs.astral.sh/ruff/editors/settings/
settings = {
organizeImports = true,
},
},
}

View File

@@ -10,23 +10,6 @@ function! s:Single_quote(str) abort
return "'" . substitute(copy(a:str), "'", "''", 'g') . "'" return "'" . substitute(copy(a:str), "'", "''", 'g') . "'"
endfunction endfunction
" Check the syntax group in the current cursor position, see
" https://stackoverflow.com/q/9464844/6064933 and
" https://jordanelver.co.uk/blog/2015/05/27/working-with-vim-colorschemes/
function! utils#SynGroup() abort
if !exists('*synstack')
return
endif
echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')
endfunction
" Check if a colorscheme exists in runtimepath.
" The following two functions are inspired by https://stackoverflow.com/a/5703164/6064933.
function! utils#HasColorscheme(name) abort
let l:pat = printf('colors/%s.vim', a:name)
return !empty(globpath(&runtimepath, l:pat))
endfunction
" Custom fold expr, adapted from https://vi.stackexchange.com/a/9094/15292 " Custom fold expr, adapted from https://vi.stackexchange.com/a/9094/15292
function! utils#VimFolds(lnum) abort function! utils#VimFolds(lnum) abort
" get content of current line and the line below " get content of current line and the line below
@@ -128,34 +111,22 @@ endfunction
" Output current time or unix timestamp in human-readable format. " Output current time or unix timestamp in human-readable format.
function! utils#iso_time(timestamp) abort function! utils#iso_time(timestamp) abort
if a:timestamp " Get current datetime
return strftime('%Y-%m-%d %H:%M:%S%z', a:timestamp) if !a:timestamp
endif
return strftime('%Y-%m-%d %H:%M:%S%z') return strftime('%Y-%m-%d %H:%M:%S%z')
endfunction
" Check if we are inside a Git repo.
function! utils#Inside_git_repo() abort
let res = system('git rev-parse --is-inside-work-tree')
if match(res, 'true') == -1
return v:false
else
" Manually trigger a special user autocmd InGitRepo (to use it for
" lazyloading of fugitive by packer.nvim).
" See also https://github.com/wbthomason/packer.nvim/discussions/534.
doautocmd User InGitRepo
return v:true
endif endif
endfunction
function! utils#GetGitBranch() " this timestamp in expressed in milliseconds
let l:res = systemlist('git rev-parse --abbrev-ref HEAD')[0] if len(a:timestamp) == 13
if match(l:res, 'fatal') != -1 let l:timestamp = a:timestamp[:-4]
return '' " this timestamp in expressed in microseconds
elseif len(a:timestamp) == 16
let l:timestamp = a:timestamp[:-7]
else else
return l:res let l:timestamp = a:timestamp
endif endif
return strftime('%Y-%m-%d %H:%M:%S%z', l:timestamp)
endfunction endfunction
" Redirect command output to a register for later processing. " Redirect command output to a register for later processing.

View File

@@ -1,123 +0,0 @@
" Do not use smart case in command line mode, extracted from https://vi.stackexchange.com/a/16511/15292.
augroup dynamic_smartcase
autocmd!
autocmd CmdLineEnter : set nosmartcase
autocmd CmdLineLeave : set smartcase
augroup END
augroup term_settings
autocmd!
" Do not use number and relative number for terminal inside nvim
autocmd TermOpen * setlocal norelativenumber nonumber
" Go to insert mode by default to start typing command
autocmd TermOpen * startinsert
augroup END
" More accurate syntax highlighting? (see `:h syn-sync`)
augroup accurate_syn_highlight
autocmd!
autocmd BufEnter * :syntax sync fromstart
augroup END
" Return to last cursor position when opening a file
augroup resume_cursor_position
autocmd!
autocmd BufReadPost * call s:resume_cursor_position()
augroup END
" Only resume last cursor position when there is no go-to-line command (something like '+23').
function s:resume_cursor_position() abort
if line("'\"") > 1 && line("'\"") <= line("$") && &ft !~# 'commit'
let l:args = v:argv " command line arguments
for l:cur_arg in l:args
" Check if a go-to-line command is given.
let idx = match(l:cur_arg, '\v^\+(\d){1,}$')
if idx != -1
return
endif
endfor
execute "normal! g`\"zvzz"
endif
endfunction
augroup numbertoggle
autocmd!
autocmd BufEnter,FocusGained,InsertLeave,WinEnter * if &nu | set rnu | endif
autocmd BufLeave,FocusLost,InsertEnter,WinLeave * if &nu | set nornu | endif
augroup END
" Define or override some highlight groups
augroup custom_highlight
autocmd!
autocmd ColorScheme * call s:custom_highlight()
augroup END
function! s:custom_highlight() abort
" For yank highlight
highlight YankColor ctermfg=59 ctermbg=41 guifg=#34495E guibg=#2ECC71
" For cursor colors
highlight Cursor cterm=bold gui=bold guibg=#00c918 guifg=black
highlight Cursor2 guifg=red guibg=red
" For floating windows border highlight
highlight FloatBorder guifg=LightGreen guibg=NONE
" highlight for matching parentheses
highlight MatchParen cterm=bold,underline gui=bold,underline
endfunction
augroup auto_close_win
autocmd!
autocmd BufEnter * call s:quit_current_win()
augroup END
" Quit Nvim if we have only one window, and its filetype match our pattern.
function! s:quit_current_win() abort
let l:quit_filetypes = ['qf', 'vista', 'NvimTree']
let l:should_quit = v:true
let l:tabwins = nvim_tabpage_list_wins(0)
for w in l:tabwins
let l:buf = nvim_win_get_buf(w)
let l:bf = getbufvar(l:buf, '&filetype')
if index(l:quit_filetypes, l:bf) == -1
let l:should_quit = v:false
endif
endfor
if l:should_quit
qall
endif
endfunction
augroup git_repo_check
autocmd!
autocmd VimEnter,DirChanged * call utils#Inside_git_repo()
augroup END
" ref: https://vi.stackexchange.com/a/169/15292
function! s:handle_large_file() abort
let g:large_file = 10485760 " 10MB
let f = expand("<afile>")
if getfsize(f) > g:large_file || getfsize(f) == -2
set eventignore+=all
" turning off relative number helps a lot
set norelativenumber
setlocal noswapfile bufhidden=unload buftype=nowrite undolevels=-1
else
set eventignore-=all relativenumber
endif
endfunction
augroup LargeFile
autocmd!
autocmd BufReadPre * call s:handle_large_file()
augroup END
" Load auto-command defined in Lua
lua require("custom-autocmd")

View File

@@ -1,153 +0,0 @@
--- This module will load a random colorscheme on nvim startup process.
local utils = require("utils")
local M = {}
-- Colorscheme to its directory name mapping, because colorscheme repo name is not necessarily
-- the same as the colorscheme name itself.
M.colorscheme2dir = {
onedark = "onedark.nvim",
edge = "edge",
sonokai = "sonokai",
gruvbox_material = "gruvbox-material",
nord = "nord.nvim",
everforest = "everforest",
nightfox = "nightfox.nvim",
kanagawa = "kanagawa.nvim",
catppuccin = "catppuccin",
rose_pine = "rose-pine",
onedarkpro = "onedarkpro.nvim",
monokai = "monokai.nvim",
material = "material.nvim",
}
M.gruvbox8 = function()
-- Italic options should be put before colorscheme setting,
-- see https://github.com/morhetz/gruvbox/wiki/Terminal-specific#1-italics-is-disabled
vim.g.gruvbox_italics = 1
vim.g.gruvbox_italicize_strings = 1
vim.g.gruvbox_filetype_hi_groups = 1
vim.g.gruvbox_plugin_hi_groups = 1
vim.cmd([[colorscheme gruvbox8_hard]])
end
M.onedark = function()
vim.cmd([[colorscheme onedark]])
end
M.edge = function()
vim.g.edge_enable_italic = 1
vim.g.edge_better_performance = 1
vim.cmd([[colorscheme edge]])
end
M.sonokai = function()
vim.g.sonokai_enable_italic = 1
vim.g.sonokai_better_performance = 1
vim.cmd([[colorscheme sonokai]])
end
M.gruvbox_material = function()
-- foreground option can be material, mix, or original
vim.g.gruvbox_material_foreground = "material"
--background option can be hard, medium, soft
vim.g.gruvbox_material_background = "soft"
vim.g.gruvbox_material_enable_italic = 1
vim.g.gruvbox_material_better_performance = 1
vim.cmd([[colorscheme gruvbox-material]])
end
M.nord = function()
vim.cmd([[colorscheme nord]])
end
M.doom_one = function()
vim.cmd([[colorscheme doom-one]])
end
M.everforest = function()
vim.g.everforest_enable_italic = 1
vim.g.everforest_better_performance = 1
vim.cmd([[colorscheme everforest]])
end
M.nightfox = function()
vim.cmd([[colorscheme nordfox]])
end
M.kanagawa = function()
vim.cmd([[colorscheme kanagawa]])
end
M.catppuccin = function()
-- available option: latte, frappe, macchiato, mocha
vim.g.catppuccin_flavour = "frappe"
require("catppuccin").setup()
vim.cmd([[colorscheme catppuccin]])
end
M.rose_pine = function()
require('rose-pine').setup({
--- @usage 'main' | 'moon'
dark_variant = 'moon',
})
-- set colorscheme after options
vim.cmd('colorscheme rose-pine')
end
M.onedarkpro = function()
-- set colorscheme after options
vim.cmd('colorscheme onedark_vivid')
end
M.monokai = function()
vim.cmd('colorscheme monokai_pro')
end
M.material = function ()
vim.g.material_style = "oceanic"
vim.cmd('colorscheme material')
end
--- Use a random colorscheme from the pre-defined list of colorschemes.
M.rand_colorscheme = function()
local colorscheme = utils.rand_element(vim.tbl_keys(M.colorscheme2dir))
if not vim.tbl_contains(vim.tbl_keys(M), colorscheme) then
local msg = "Invalid colorscheme: " .. colorscheme
vim.notify(msg, vim.log.levels.ERROR, { title = "nvim-config" })
return
end
-- Load the colorscheme, because all the colorschemes are declared as opt plugins, so the colorscheme isn't loaded yet.
local status = utils.add_pack(M.colorscheme2dir[colorscheme])
if not status then
local msg = string.format("Colorscheme %s is not installed. Run PackerSync to install.", colorscheme)
vim.notify(msg, vim.log.levels.ERROR, { title = "nvim-config" })
return
end
-- Load the colorscheme and its settings
M[colorscheme]()
if vim.g.logging_level == "debug" then
local msg = "Colorscheme: " .. colorscheme
vim.notify(msg, vim.log.levels.DEBUG, { title = "nvim-config" })
end
end
-- Load a random colorscheme
M.rand_colorscheme()

View File

@@ -65,7 +65,7 @@ pip install -U pynvim
[python-lsp-server (pylsp)](https://github.com/python-lsp/python-lsp-server) is a Python [Language Server](https://microsoft.github.io/language-server-protocol/) for completion, linting, go to definition, etc. [python-lsp-server (pylsp)](https://github.com/python-lsp/python-lsp-server) is a Python [Language Server](https://microsoft.github.io/language-server-protocol/) for completion, linting, go to definition, etc.
``` ```
pip install 'python-lsp-server[all]' pylsp-mypy pyls-isort pip install 'python-lsp-server[all]' pylsp-mypy python-lsp-isort python-lsp-black
``` ```
Note the executable for pylsp is also named `pylsp`. You need to set its PATH correctly. Note the executable for pylsp is also named `pylsp`. You need to set its PATH correctly.
@@ -111,23 +111,23 @@ vim-language-server is installed in the same directory as the node executable.
### Git ### Git
Git is required by plugin manager [packer.nvim](https://github.com/wbthomason/packer.nvim) and other git-related plugins. Git is required by plugin manager [lazy.nvim](https://github.com/folke/lazy.nvim) and other git-related plugins.
For Linux and macOS, Git is usually pre-installed. For Linux and macOS, Git is usually pre-installed.
The version of Git on the Linux system may be too old so that plugins may break. The version of Git on the Linux system may be too old so that plugins may break.
Check [here](https://jdhao.github.io/2021/03/27/upgrade_git_on_linux/) on how to install and set up the latest version of Git. Check [here](https://jdhao.github.io/2021/03/27/upgrade_git_on_linux/) on how to install and set up the latest version of Git.
For Windows, install [Git for Windows](https://git-scm.com/download/win) and make sure you can run `git` from command line. For Windows, install [Git for Windows](https://git-scm.com/download/win) and make sure you can run `git` from command line.
### ctags ### universal-ctags
In order to use tags related plugins such as [vista.vim](https://github.com/liuchengxu/vista.vim), we need to install a ctags distribution. In order to use tags related plugins such as [vista.vim](https://github.com/liuchengxu/vista.vim), we need to install a ctags distribution.
Universal-ctags is preferred. Universal-ctags is preferred.
To install it on Linux, we need to build it from source. See [here](https://askubuntu.com/a/836521/768311) for the details. To install it on Linux, we need to build it from source. See [here](https://askubuntu.com/a/836521/768311) for the details.
To install ctags on macOS, use [Homebrew](https://github.com/universal-ctags/homebrew-universal-ctags): To install ctags on macOS, use [Homebrew](https://formulae.brew.sh/formula/universal-ctags):
```bash ```bash
brew install ctags brew install universal-ctags
``` ```
To install it Windows, use [chocolatey](https://chocolatey.org/) or [scoop](https://scoop.sh/) To install it Windows, use [chocolatey](https://chocolatey.org/) or [scoop](https://scoop.sh/)
@@ -166,57 +166,15 @@ Set their PATH properly and make sure you can run `pylint`, `flake8` and `vint`
There are various ways to install Nvim depending on your system. There are various ways to install Nvim depending on your system.
This config is only maintained for [the latest nvim stable release](https://github.com/neovim/neovim/releases/tag/stable). This config is only maintained for [the latest nvim stable release](https://github.com/neovim/neovim/releases/tag/stable).
### Linux Please check the official doc on how to install Neovim on different systems: https://github.com/neovim/neovim/blob/master/INSTALL.md
You can directly download the binary release from [here](https://github.com/neovim/neovim/releases/download/stable/nvim-linux64.tar.gz). After installing Nvim, we need to set the PATH to nvim correctly.
You can also use the system package manager to install nvim,
but that is not reliable since the latest version may not be available.
### Windows
You may download from [nvim release](https://github.com/neovim/neovim/releases/download/stable/nvim-win64.zip) from GitHub and manually extract it.
Another way to install Nvim on Windows is via chocolatey or scoop:
```
choco install neovim
# via scoop
# scoop bucket add versions
# scoop install neovim
```
### macOS
It is recommended to install neovim via [Homebrew](https://brew.sh/) on macOS. Simply run the following command:
```bash
brew install neovim
```
After installing Nvim, we need to set the path to nvim correctly.
**Make sure that you can run `nvim` from the command line after all these setups**. **Make sure that you can run `nvim` from the command line after all these setups**.
## Setting up Nvim ## Setting up Nvim
After installing nvim and all the dependencies, we will install plugin managers and set up this config. After installing nvim and all the dependencies, we will install plugin managers and set up this config.
### Install plugin manager packer.nvim
I use packer.nvim to manage my plugins. We need to install packer.nvim on our system first.
For Windows, if curl is installed, run the following command (on PowerShell):
```
git clone --depth=1 https://github.com/wbthomason/packer.nvim "$env:LOCALAPPDATA\nvim-data\site\pack\packer\opt\packer.nvim"
```
For macOS and Linux, run the following command:
```bash
git clone --depth=1 https://github.com/wbthomason/packer.nvim ~/.local/share/nvim/site/pack/packer/opt/packer.nvim
```
### How to install this configuration ### How to install this configuration
On Linux and macOS, the directory is `~/.config/nvim`. On Linux and macOS, the directory is `~/.config/nvim`.
@@ -228,7 +186,7 @@ then go to this directory, and run the following command:
git clone --depth=1 https://github.com/jdhao/nvim-config.git . git clone --depth=1 https://github.com/jdhao/nvim-config.git .
``` ```
After that, when we first open nvim, run command `:PackerSync` to install all the plugins. After that, when we first open nvim, all the plugins will be installed automatically.
Since I use quite a lot of plugins (more than 60), it may take some time to install all of them. Since I use quite a lot of plugins (more than 60), it may take some time to install all of them.
[^1]: Use `echo %userprofile%` to see where your `$HOME` is. [^1]: Use `echo %userprofile%` to see where your `$HOME` is.

View File

@@ -68,7 +68,7 @@ fi
# Install some Python packages used by Nvim plugins. # Install some Python packages used by Nvim plugins.
echo "Installing Python packages" echo "Installing Python packages"
declare -a PY_PACKAGES=("pynvim" 'python-lsp-server[all]' "black" "vim-vint" "pyls-isort" "pylsp-mypy") declare -a PY_PACKAGES=("pynvim" 'python-lsp-server[all]' "vim-vint" "python-lsp-isort" "pylsp-mypy" "python-lsp-black")
if [[ "$SYSTEM_PYTHON" = true ]]; then if [[ "$SYSTEM_PYTHON" = true ]]; then
echo "Using system Python to install $(PY_PACKAGES)" echo "Using system Python to install $(PY_PACKAGES)"
@@ -221,7 +221,7 @@ fi
NVIM_DIR=$HOME/tools/nvim NVIM_DIR=$HOME/tools/nvim
NVIM_SRC_NAME=$HOME/packages/nvim-linux64.tar.gz NVIM_SRC_NAME=$HOME/packages/nvim-linux64.tar.gz
NVIM_CONFIG_DIR=$HOME/.config/nvim NVIM_CONFIG_DIR=$HOME/.config/nvim
NVIM_LINK="https://github.com/neovim/neovim/releases/download/stable/nvim-linux64.tar.gz" NVIM_LINK="https://github.com/neovim/neovim/releases/download/stable/nvim-linux-x86_64.tar.gz"
if [[ ! -f "$NVIM_DIR/bin/nvim" ]]; then if [[ ! -f "$NVIM_DIR/bin/nvim" ]]; then
echo "Installing Nvim" echo "Installing Nvim"
echo "Creating nvim directory under tools directory" echo "Creating nvim directory under tools directory"
@@ -252,13 +252,7 @@ fi
git clone --depth=1 https://github.com/jdhao/nvim-config.git "$NVIM_CONFIG_DIR" git clone --depth=1 https://github.com/jdhao/nvim-config.git "$NVIM_CONFIG_DIR"
echo "Installing packer.nvim"
if [[ ! -d ~/.local/share/nvim/site/pack/packer/opt/packer.nvim ]]; then
git clone --depth=1 https://github.com/wbthomason/packer.nvim \
~/.local/share/nvim/site/pack/packer/opt/packer.nvim
fi
echo "Installing nvim plugins, please wait" echo "Installing nvim plugins, please wait"
"$NVIM_DIR/bin/nvim" -c "autocmd User PackerComplete quitall" -c "PackerSync" "$NVIM_DIR/bin/nvim" -c "autocmd User LazyInstall quitall" -c "lua require('lazy').install()"
echo "Finished installing Nvim and its dependencies!" echo "Finished installing Nvim and its dependencies!"

View File

@@ -27,7 +27,7 @@ scoop install miniconda3
pip install -U pynvim pip install -U pynvim
# Install python-language-server # Install python-language-server
pip install 'python-lsp-server[all]' pylsp-mypy pyls-isort pip install 'python-lsp-server[all]' pylsp-mypy python-lsp-isort
# Install visual c++ redistribution # Install visual c++ redistribution
scoop install vcredist2022 scoop install vcredist2022

View File

@@ -11,33 +11,30 @@
-- StackOverflow: https://stackoverflow.com/users/6064933/jdhao -- StackOverflow: https://stackoverflow.com/users/6064933/jdhao
vim.loader.enable() vim.loader.enable()
local api = vim.api local utils = require("utils")
local version = vim.version
-- check if we have the latest stable version of nvim local expected_version = "0.11.2"
local expected_ver = "0.9.1" utils.is_compatible_version(expected_version)
local ev = version.parse(expected_ver)
local actual_ver = version()
if version.cmp(ev, actual_ver) ~= 0 then local config_dir = vim.fn.stdpath("config")
local _ver = string.format("%s.%s.%s", actual_ver.major, actual_ver.minor, actual_ver.patch) ---@cast config_dir string
local msg = string.format("Unsupported nvim version: expect %s, but got %s instead!", expected_ver, _ver)
api.nvim_err_writeln(msg)
return
end
local core_conf_files = { -- some global settings
"globals.lua", -- some global settings require("globals")
"options.vim", -- setting options in nvim -- setting options in nvim
"autocommands.vim", -- various autocommands vim.cmd("source " .. vim.fs.joinpath(config_dir, "viml_conf/options.vim"))
"mappings.lua", -- all the user-defined mappings -- various autocommands
"plugins.vim", -- all the plugins installed and their configurations require("custom-autocmd")
"colorschemes.lua", -- colorscheme settings -- all the user-defined mappings
} require("mappings")
-- all the plugins installed and their configurations
vim.cmd("source " .. vim.fs.joinpath(config_dir, "viml_conf/plugins.vim"))
-- source all the core config files -- diagnostic related config
for _, name in ipairs(core_conf_files) do require("diagnostic-conf")
local path = string.format("%s/core/%s", vim.fn.stdpath("config"), name)
local source_cmd = "source " .. path -- colorscheme settings
vim.cmd(source_cmd) local color_scheme = require("colorschemes")
end
-- Load a random colorscheme
color_scheme.rand_colorscheme()

105
lua/colorschemes.lua Normal file
View File

@@ -0,0 +1,105 @@
--- This module will load a random colorscheme on nvim startup process.
local utils = require("utils")
local M = {}
-- Colorscheme to its directory name mapping, because colorscheme repo name is not necessarily
-- the same as the colorscheme name itself.
M.colorscheme_conf = {
onedark = function()
-- Lua
require("onedark").setup {
style = "darker",
}
require("onedark").load()
end,
edge = function()
vim.g.edge_style = "default"
vim.g.edge_enable_italic = 1
vim.g.edge_better_performance = 1
vim.cmd([[colorscheme edge]])
end,
sonokai = function()
vim.g.sonokai_enable_italic = 1
vim.g.sonokai_better_performance = 1
vim.cmd([[colorscheme sonokai]])
end,
gruvbox_material = function()
-- foreground option can be material, mix, or original
vim.g.gruvbox_material_foreground = "original"
--background option can be hard, medium, soft
vim.g.gruvbox_material_background = "hard"
vim.g.gruvbox_material_enable_italic = 1
vim.g.gruvbox_material_better_performance = 1
vim.cmd([[colorscheme gruvbox-material]])
end,
everforest = function()
vim.g.everforest_background = "hard"
vim.g.everforest_enable_italic = 1
vim.g.everforest_better_performance = 1
vim.cmd([[colorscheme everforest]])
end,
nightfox = function()
vim.cmd([[colorscheme carbonfox]])
end,
onedarkpro = function()
-- set colorscheme after options
-- onedark_vivid does not enough contrast
vim.cmd("colorscheme onedark_dark")
end,
material = function()
vim.g.material_style = "darker"
vim.cmd("colorscheme material")
end,
arctic = function()
vim.cmd("colorscheme arctic")
end,
kanagawa = function()
vim.cmd("colorscheme kanagawa-dragon")
end,
modus = function()
vim.cmd([[colorscheme modus]])
end,
jellybeans = function()
vim.cmd([[colorscheme jellybeans]])
end,
github = function()
vim.cmd([[colorscheme github_dark_default]])
end,
e_ink = function()
require("e-ink").setup()
vim.cmd.colorscheme("e-ink")
end,
ashen = function()
vim.cmd([[colorscheme ashen]])
end,
melange = function()
vim.cmd([[colorscheme melange]])
end,
makurai = function()
vim.cmd.colorscheme("makurai_warrior")
end,
vague = function()
vim.cmd([[colorscheme vague]])
end,
kanso = function()
vim.cmd([[colorscheme kanso]])
end,
citruszest = function()
vim.cmd([[colorscheme citruszest]])
end,
}
--- Use a random colorscheme from the pre-defined list of colorschemes.
M.rand_colorscheme = function()
local colorscheme = utils.rand_element(vim.tbl_keys(M.colorscheme_conf))
-- Load the colorscheme and its settings
M.colorscheme_conf[colorscheme]()
end
return M

View File

@@ -1,6 +1,6 @@
require("bufferline").setup { require("bufferline").setup {
options = { options = {
numbers = "buffer_id", numbers = "none",
close_command = "bdelete! %d", close_command = "bdelete! %d",
right_mouse_command = nil, right_mouse_command = nil,
left_mouse_command = "buffer %d", left_mouse_command = "buffer %d",
@@ -9,7 +9,7 @@ require("bufferline").setup {
icon = "", -- this should be omitted if indicator style is not 'icon' icon = "", -- this should be omitted if indicator style is not 'icon'
style = "icon", style = "icon",
}, },
buffer_close_icon = "", buffer_close_icon = "",
modified_icon = "", modified_icon = "",
close_icon = "", close_icon = "",
left_trunc_marker = "", left_trunc_marker = "",
@@ -44,3 +44,7 @@ require("bufferline").setup {
sort_by = "id", sort_by = "id",
}, },
} }
vim.keymap.set("n", "<space>bp", "<cmd>BufferLinePick<CR>", {
desc = "pick a buffer",
})

View File

@@ -2,7 +2,7 @@ local api = vim.api
local keymap = vim.keymap local keymap = vim.keymap
local dashboard = require("dashboard") local dashboard = require("dashboard")
conf = {} local conf = {}
conf.header = { conf.header = {
" ", " ",
" ", " ",
@@ -21,25 +21,25 @@ conf.header = {
conf.center = { conf.center = {
{ {
icon = " ", icon = "󰈞 ",
desc = "Find File ", desc = "Find File ",
action = "Leaderf file --popup", action = "FzfLua files",
key = "<Leader> f f", key = "<Leader> f f",
}, },
{ {
icon = " ", icon = "󰈢 ",
desc = "Recently opened files ", desc = "Recently opened files ",
action = "Leaderf mru --popup", action = "FzfLua oldfiles",
key = "<Leader> f r", key = "<Leader> f r",
}, },
{ {
icon = " ", icon = "󰈬 ",
desc = "Project grep ", desc = "Project grep ",
action = "Leaderf rg --popup", action = "FzfLua live_grep",
key = "<Leader> f g", key = "<Leader> f g",
}, },
{ {
icon = " ", icon = " ",
desc = "Open Nvim config ", desc = "Open Nvim config ",
action = "tabnew $MYVIMRC | tcd %:p:h", action = "tabnew $MYVIMRC | tcd %:p:h",
key = "<Leader> e v", key = "<Leader> e v",
@@ -51,7 +51,7 @@ conf.center = {
key = "e", key = "e",
}, },
{ {
icon = " ", icon = "󰗼 ",
desc = "Quit Nvim ", desc = "Quit Nvim ",
-- desc = "Quit Nvim ", -- desc = "Quit Nvim ",
action = "qa", action = "qa",
@@ -59,17 +59,17 @@ conf.center = {
}, },
} }
dashboard.setup({ dashboard.setup {
theme = 'doom', theme = "doom",
shortcut_type = 'number', shortcut_type = "number",
config = conf config = conf,
}) }
api.nvim_create_autocmd("FileType", { api.nvim_create_autocmd("FileType", {
pattern = "dashboard", pattern = "dashboard",
group = api.nvim_create_augroup("dashboard_enter", { clear = true }), group = api.nvim_create_augroup("dashboard_enter", { clear = true }),
callback = function () callback = function()
keymap.set("n", "q", ":qa<CR>", { buffer = true, silent = true }) keymap.set("n", "q", ":qa<CR>", { buffer = true, silent = true })
keymap.set("n", "e", ":enew<CR>", { buffer = true, silent = true }) keymap.set("n", "e", ":enew<CR>", { buffer = true, silent = true })
end end,
}) })

View File

@@ -1,11 +1,27 @@
local keymap = vim.keymap local keymap = vim.keymap
keymap.set("n", "<leader>gs", "<cmd>Git<cr>", { desc = "Git status" }) keymap.set("n", "<leader>gs", "<cmd>Git<cr>", { desc = "Git: show status" })
keymap.set("n", "<leader>gw", "<cmd>Gwrite<cr>", { desc = "Git add" }) keymap.set("n", "<leader>gw", "<cmd>Gwrite<cr>", { desc = "Git: add file" })
keymap.set("n", "<leader>gc", "<cmd>Git commit<cr>", { desc = "Git commit" }) keymap.set("n", "<leader>gc", "<cmd>Git commit<cr>", { desc = "Git: commit changes" })
keymap.set("n", "<leader>gd", "<cmd>Gdiffsplit<cr>", { desc = "Git diff" }) keymap.set("n", "<leader>gpl", "<cmd>Git pull<cr>", { desc = "Git: pull changes" })
keymap.set("n", "<leader>gpl", "<cmd>Git pull<cr>", { desc = "Git pull" }) keymap.set("n", "<leader>gpu", "<cmd>15 split|term git push<cr>", { desc = "Git: push changes" })
keymap.set("n", "<leader>gpu", "<cmd>15 split|term git push<cr>", { desc = "Git push" }) keymap.set("v", "<leader>gb", ":Git blame<cr>", { desc = "Git: blame selected line" })
-- convert git to Git in command line mode -- convert git to Git in command line mode
vim.fn['utils#Cabbrev']('git', 'Git') vim.fn["utils#Cabbrev"]("git", "Git")
keymap.set("n", "<leader>gbn", function()
vim.ui.input({ prompt = "Enter a new branch name" }, function(user_input)
if user_input == nil or user_input == "" then
return
end
local cmd_str = string.format("G checkout -b %s", user_input)
vim.cmd(cmd_str)
end)
end, {
desc = "Git: create new branch",
})
keymap.set("n", "<leader>gf", ":Git fetch ", { desc = "Git: prune branches" })
keymap.set("n", "<leader>gbd", ":Git branch -D ", { desc = "Git: delete branch" })

18
lua/config/fzf-lua.lua Normal file
View File

@@ -0,0 +1,18 @@
require("fzf-lua").setup {
defaults = {
file_icons = "mini",
},
winopts = {
row = 0.5,
height = 0.7,
},
files = {
previewer = false,
},
}
vim.keymap.set("n", "<leader>ff", "<cmd>FzfLua files<cr>", { desc = "Fuzzy find files" })
vim.keymap.set("n", "<leader>fg", "<cmd>FzfLua live_grep<cr>", { desc = "Fuzzy grep files" })
vim.keymap.set("n", "<leader>fh", "<cmd>FzfLua helptags<cr>", { desc = "Fuzzy grep tags in help files" })
vim.keymap.set("n", "<leader>ft", "<cmd>FzfLua btags<cr>", { desc = "Fuzzy search buffer tags" })
vim.keymap.set("n", "<leader>fb", "<cmd>FzfLua buffers<cr>", { desc = "Fuzzy search opened buffers" })

View File

@@ -0,0 +1,12 @@
require("git-conflict").setup {}
vim.api.nvim_create_autocmd("User", {
pattern = "GitConflictResolved",
callback = function()
-- clear qf list
vim.fn.setqflist({}, "r")
-- reopen it?
vim.cmd([[GitConflictListQf]])
end,
})

View File

@@ -2,24 +2,46 @@ local keymap = vim.keymap
local gitlinker = require("gitlinker") local gitlinker = require("gitlinker")
gitlinker.setup { gitlinker.setup {
callbacks = {
["dev.azure.com"] = function(url_data)
vim.print(url_data)
local url = require("gitlinker.hosts").get_base_https_url(url_data)
if url_data.lstart then
if url_data.lend == nil then
url_data.lend = url_data.lstart
end
url = url
.. "?path=/"
.. url_data.file
.. "&version=GC"
.. url_data.rev
.. "&line="
.. url_data.lstart
.. "&lineEnd="
.. url_data.lend
.. "&lineStartColumn=1"
.. "&lineEndColumn=120"
end
return url
end,
},
mappings = nil, mappings = nil,
} }
keymap.set({ "n", "v" }, "<leader>gl", "", { keymap.set({ "n", "v" }, "<leader>gl", function()
silent = true,
desc = "get git permlink",
callback = function()
local mode = string.lower(vim.fn.mode()) local mode = string.lower(vim.fn.mode())
gitlinker.get_buf_range_url(mode) gitlinker.get_buf_range_url(mode)
end, end, {
silent = true,
desc = "Git: get permlink",
}) })
keymap.set("n", "<leader>gb", "", { keymap.set("n", "<leader>gbr", function()
gitlinker.get_repo_url {
action_callback = gitlinker.actions.open_in_browser,
}
end, {
silent = true, silent = true,
desc = "browse repo in browser", desc = "Git: browse repo in browser",
callback = function()
gitlinker.get_repo_url({
action_callback = gitlinker.actions.open_in_browser
})
end
}) })

View File

@@ -2,13 +2,13 @@ local gs = require("gitsigns")
gs.setup { gs.setup {
signs = { signs = {
add = { hl = "GitSignsAdd", text = "+", numhl = "GitSignsAddNr", linehl = "GitSignsAddLn" }, add = { text = "+" },
change = { hl = "GitSignsChange", text = "~", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn" }, change = { text = "~" },
delete = { hl = "GitSignsDelete", text = "_", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn" }, delete = { text = "_" },
topdelete = { hl = "GitSignsDelete", text = "", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn" }, topdelete = { text = "" },
changedelete = { hl = "GitSignsChange", text = "", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn" }, changedelete = { text = "" },
}, },
word_diff = true, word_diff = false,
on_attach = function(bufnr) on_attach = function(bufnr)
local function map(mode, l, r, opts) local function map(mode, l, r, opts)
opts = opts or {} opts = opts or {}
@@ -38,20 +38,20 @@ gs.setup {
end, { expr = true, desc = "previous hunk" }) end, { expr = true, desc = "previous hunk" })
-- Actions -- Actions
map("n", "<leader>hp", gs.preview_hunk) map("n", "<leader>hp", gs.preview_hunk, { desc = "preview hunk" })
map("n", "<leader>hb", function() map("n", "<leader>hb", function()
gs.blame_line { full = true } gs.blame_line { full = true }
end) end, { desc = "blame hunk" })
end, end,
} }
vim.api.nvim_create_autocmd('ColorScheme', { vim.api.nvim_create_autocmd("ColorScheme", {
pattern = "*", pattern = "*",
callback = function() callback = function()
vim.cmd [[ vim.cmd([[
hi GitSignsChangeInline gui=reverse hi GitSignsChangeInline gui=reverse
hi GitSignsAddInline gui=reverse hi GitSignsAddInline gui=reverse
hi GitSignsDeleteInline gui=reverse hi GitSignsDeleteInline gui=reverse
]] ]])
end end,
}) })

12
lua/config/glance.lua Normal file
View File

@@ -0,0 +1,12 @@
local glance = require("glance")
glance.setup {
height = 25,
border = {
enable = true,
},
}
vim.keymap.set("n", "<space>gd", "<cmd>Glance definitions<cr>")
vim.keymap.set("n", "<space>gr", "<cmd>Glance references<cr>")
vim.keymap.set("n", "<space>gi", "<cmd>Glance implementations<cr>")

View File

@@ -12,10 +12,11 @@ local activate_hlslens = function(direction)
local cmd = string.format("normal! %s%szzzv", vim.v.count1, direction) local cmd = string.format("normal! %s%szzzv", vim.v.count1, direction)
local status, msg = pcall(vim.cmd, cmd) local status, msg = pcall(vim.cmd, cmd)
-- Deal with the case that there is no such pattern in current buffer.
if not status then if not status then
-- 13 is the index where real error message starts local start_idx, _ = string.find(msg, "E486", 1, true)
msg = msg:sub(13) local msg_part = string.sub(msg, start_idx)
api.nvim_err_writeln(msg) api.nvim_echo({ { msg_part } }, true, { err = true })
return return
end end
@@ -34,15 +35,48 @@ keymap.set("n", "N", "", {
end, end,
}) })
local check_cursor_word = function()
local cursor_word = vim.fn.expand("<cword>")
local result = cursor_word == ""
if result then
local msg = "E348: No string under cursor"
api.nvim_echo({ { msg } }, true, { err = true })
end
return result, cursor_word
end
keymap.set("n", "*", "", { keymap.set("n", "*", "", {
callback = function() callback = function()
vim.fn.execute("normal! *N") local cursor_word_empty, cursor_word = check_cursor_word()
if cursor_word_empty then
return
end
local cmd = string.format([[normal! /\v<%s>]], cursor_word)
-- In order to say that we are pressing Enter key, instead of typing literally the character,
-- we need to replace special notation with their internal representation.
local escaped_enter = vim.api.nvim_replace_termcodes("<CR>", true, false, true)
-- character `N` is used to keep the cursor when pressing `*`
local full_cmd = cmd .. escaped_enter .. "N"
vim.fn.execute(full_cmd)
hlslens.start() hlslens.start()
end, end,
}) })
keymap.set("n", "#", "", { keymap.set("n", "#", "", {
callback = function() callback = function()
vim.fn.execute("normal! #N") local cursor_word_empty, cursor_word = check_cursor_word()
if cursor_word_empty then
return
end
local cmd = string.format([[normal! ?\v<%s>]], cursor_word)
local escaped_enter = vim.api.nvim_replace_termcodes("<CR>", true, false, true)
local full_cmd = cmd .. escaped_enter .. "N"
vim.fn.execute(full_cmd)
hlslens.start() hlslens.start()
end, end,
}) })

View File

@@ -1,29 +0,0 @@
local api = vim.api
local exclude_ft = { "help", "git", "markdown", "snippets", "text", "gitconfig", "alpha" }
require("indent_blankline").setup {
-- U+2502 may also be a good choice, it will be on the middle of cursor.
-- U+250A is also a good choice
char = "",
show_end_of_line = false,
disable_with_nolist = true,
buftype_exclude = { "terminal" },
filetype_exclude = exclude_ft,
}
local gid = api.nvim_create_augroup("indent_blankline", { clear = true })
api.nvim_create_autocmd("InsertEnter", {
pattern = "*",
group = gid,
command = "IndentBlanklineDisable",
})
api.nvim_create_autocmd("InsertLeave", {
pattern = "*",
group = gid,
callback = function()
if not vim.tbl_contains(exclude_ft, vim.bo.filetype) then
vim.cmd([[IndentBlanklineEnable]])
end
end,
})

20
lua/config/lightbulb.lua Normal file
View File

@@ -0,0 +1,20 @@
---@diagnostic disable: missing-fields
require("nvim-lightbulb").setup {
autocmd = {
enabled = true,
updatetime = -1,
},
---@diagnostic disable-next-line: unused-local
filter = function(client_name, result)
-- Ruff always sends these two actions even if there are no action to take,
-- so it is better to just ignore this to avoid noise. See also discussion below:
-- https://github.com/astral-sh/ruff-lsp/issues/91
local ignored_kinds = { "source.fixAll.ruff", "source.organizeImports.ruff" }
if vim.tbl_contains(ignored_kinds, result.kind) then
return false
end
return true
end,
}

View File

@@ -0,0 +1,4 @@
require("live-command").setup {
enable_highlighting = true,
inline_highlighting = true,
}

View File

@@ -1,235 +1,143 @@
local fn = vim.fn
local api = vim.api
local keymap = vim.keymap
local lsp = vim.lsp
local diagnostic = vim.diagnostic
local utils = require("utils") local utils = require("utils")
local custom_attach = function(client, bufnr) vim.api.nvim_create_autocmd("LspAttach", {
group = vim.api.nvim_create_augroup("lsp_buf_conf", { clear = true }),
callback = function(event_context)
local client = vim.lsp.get_client_by_id(event_context.data.client_id)
-- vim.print(client.name, client.server_capabilities)
if not client then
return
end
local bufnr = event_context.buf
-- Mappings. -- Mappings.
local map = function(mode, l, r, opts) local map = function(mode, l, r, opts)
opts = opts or {} opts = opts or {}
opts.silent = true opts.silent = true
opts.buffer = bufnr opts.buffer = bufnr
keymap.set(mode, l, r, opts) vim.keymap.set(mode, l, r, opts)
end end
map("n", "gd", vim.lsp.buf.definition, { desc = "go to definition" }) map("n", "gd", function()
vim.lsp.buf.definition {
on_list = function(options)
-- custom logic to avoid showing multiple definition when you use this style of code:
-- `local M.my_fn_name = function() ... end`.
-- See also post here: https://www.reddit.com/r/neovim/comments/19cvgtp/any_way_to_remove_redundant_definition_in_lua_file/
-- vim.print(options.items)
local unique_defs = {}
local def_loc_hash = {}
-- each item in options.items contain the location info for a definition provided by LSP server
for _, def_location in pairs(options.items) do
-- use filename and line number to uniquelly indentify a definition,
-- we do not expect/want multiple definition in single line!
local hash_key = def_location.filename .. def_location.lnum
if not def_loc_hash[hash_key] then
def_loc_hash[hash_key] = true
table.insert(unique_defs, def_location)
end
end
options.items = unique_defs
-- set the location list
---@diagnostic disable-next-line: param-type-mismatch
vim.fn.setloclist(0, {}, " ", options)
-- open the location list when we have more than 1 definitions found,
-- otherwise, jump directly to the definition
if #options.items > 1 then
vim.cmd.lopen()
else
vim.cmd([[silent! lfirst]])
end
end,
}
end, { desc = "go to definition" })
map("n", "<C-]>", vim.lsp.buf.definition) map("n", "<C-]>", vim.lsp.buf.definition)
map("n", "K", vim.lsp.buf.hover) map("n", "K", function()
vim.lsp.buf.hover { border = "single", max_height = 25, max_width = 120 }
end)
map("n", "<C-k>", vim.lsp.buf.signature_help) map("n", "<C-k>", vim.lsp.buf.signature_help)
map("n", "<space>rn", vim.lsp.buf.rename, { desc = "varialbe rename" }) map("n", "<space>rn", vim.lsp.buf.rename, { desc = "varialbe rename" })
map("n", "gr", vim.lsp.buf.references, { desc = "show references" })
map("n", "[d", diagnostic.goto_prev, { desc = "previous diagnostic" })
map("n", "]d", diagnostic.goto_next, { desc = "next diagnostic" })
map("n", "<space>q", diagnostic.setqflist, { desc = "put diagnostic to qf" })
map("n", "<space>ca", vim.lsp.buf.code_action, { desc = "LSP code action" }) map("n", "<space>ca", vim.lsp.buf.code_action, { desc = "LSP code action" })
map("n", "<space>wa", vim.lsp.buf.add_workspace_folder, { desc = "add workspace folder" }) map("n", "<space>wa", vim.lsp.buf.add_workspace_folder, { desc = "add workspace folder" })
map("n", "<space>wr", vim.lsp.buf.remove_workspace_folder, { desc = "remove workspace folder" }) map("n", "<space>wr", vim.lsp.buf.remove_workspace_folder, { desc = "remove workspace folder" })
map("n", "<space>wl", function() map("n", "<space>wl", function()
inspect(vim.lsp.buf.list_workspace_folders()) vim.print(vim.lsp.buf.list_workspace_folders())
end, { desc = "list workspace folder" }) end, { desc = "list workspace folder" })
-- Set some key bindings conditional on server capabilities -- Set some key bindings conditional on server capabilities
if client.server_capabilities.documentFormattingProvider then -- Disable ruff hover feature in favor of Pyright
map("n", "<space>f", vim.lsp.buf.format, { desc = "format code" }) if client.name == "ruff" then
client.server_capabilities.hoverProvider = false
end end
api.nvim_create_autocmd("CursorHold", { -- Uncomment code below to enable inlay hint from language server, some LSP server supports inlay hint,
buffer = bufnr, -- but disable this feature by default, so you may need to enable inlay hint in the LSP server config.
callback = function() -- vim.lsp.inlay_hint.enable(true, {buffer=bufnr})
local float_opts = {
focusable = false,
close_events = { "BufLeave", "CursorMoved", "InsertEnter", "FocusLost" },
border = "rounded",
source = "always", -- show source in diagnostic popup window
prefix = " ",
}
if not vim.b.diagnostics_pos then
vim.b.diagnostics_pos = { nil, nil }
end
local cursor_pos = api.nvim_win_get_cursor(0)
if (cursor_pos[1] ~= vim.b.diagnostics_pos[1] or cursor_pos[2] ~= vim.b.diagnostics_pos[2])
and #diagnostic.get() > 0
then
diagnostic.open_float(nil, float_opts)
end
vim.b.diagnostics_pos = cursor_pos
end,
})
-- The blow command will highlight the current variable and its usages in the buffer. -- The blow command will highlight the current variable and its usages in the buffer.
if client.server_capabilities.documentHighlightProvider then if client.server_capabilities.documentHighlightProvider then
vim.cmd([[ local gid = vim.api.nvim_create_augroup("lsp_document_highlight", { clear = true })
hi! link LspReferenceRead Visual vim.api.nvim_create_autocmd("CursorHold", {
hi! link LspReferenceText Visual
hi! link LspReferenceWrite Visual
]])
local gid = api.nvim_create_augroup("lsp_document_highlight", { clear = true })
api.nvim_create_autocmd("CursorHold" , {
group = gid, group = gid,
buffer = bufnr, buffer = bufnr,
callback = function () callback = function()
lsp.buf.document_highlight() vim.lsp.buf.document_highlight()
end end,
}) })
api.nvim_create_autocmd("CursorMoved" , { vim.api.nvim_create_autocmd("CursorMoved", {
group = gid, group = gid,
buffer = bufnr, buffer = bufnr,
callback = function () callback = function()
lsp.buf.clear_references() vim.lsp.buf.clear_references()
end end,
}) })
end end
end,
if vim.g.logging_level == "debug" then nested = true,
local msg = string.format("Language server %s started!", client.name) desc = "Configure buffer keymap and behavior based on LSP",
vim.notify(msg, vim.log.levels.DEBUG, { title = "Nvim-config" })
end
end
local capabilities = require('cmp_nvim_lsp').default_capabilities()
local lspconfig = require("lspconfig")
if utils.executable("pylsp") then
lspconfig.pylsp.setup {
on_attach = custom_attach,
settings = {
pylsp = {
plugins = {
pylint = { enabled = true, executable = "pylint" },
pyflakes = { enabled = false },
pycodestyle = { enabled = false },
jedi_completion = { fuzzy = true },
pyls_isort = { enabled = true },
pylsp_mypy = { enabled = true },
},
},
},
flags = {
debounce_text_changes = 200,
},
capabilities = capabilities,
}
else
vim.notify("pylsp not found!", vim.log.levels.WARN, { title = "Nvim-config" })
end
-- if utils.executable('pyright') then
-- lspconfig.pyright.setup{
-- on_attach = custom_attach,
-- capabilities = capabilities
-- }
-- else
-- vim.notify("pyright not found!", vim.log.levels.WARN, {title = 'Nvim-config'})
-- end
if utils.executable("ltex-ls") then
lspconfig.ltex.setup {
on_attach = custom_attach,
cmd = { "ltex-ls" },
filetypes = { "text", "plaintex", "tex", "markdown" },
settings = {
ltex = {
language = "en"
},
},
flags = { debounce_text_changes = 300 },
}
end
if utils.executable("clangd") then
lspconfig.clangd.setup {
on_attach = custom_attach,
capabilities = capabilities,
filetypes = { "c", "cpp", "cc" },
flags = {
debounce_text_changes = 500,
},
}
end
-- set up vim-language-server
if utils.executable("vim-language-server") then
lspconfig.vimls.setup {
on_attach = custom_attach,
flags = {
debounce_text_changes = 500,
},
capabilities = capabilities,
}
else
vim.notify("vim-language-server not found!", vim.log.levels.WARN, { title = "Nvim-config" })
end
-- set up bash-language-server
if utils.executable("bash-language-server") then
lspconfig.bashls.setup {
on_attach = custom_attach,
capabilities = capabilities,
}
end
if utils.executable("lua-language-server") then
-- settings for lua-language-server can be found on https://github.com/LuaLS/lua-language-server/wiki/Settings .
lspconfig.lua_ls.setup {
on_attach = custom_attach,
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" },
},
workspace = {
-- Make the server aware of Neovim runtime files,
-- see also https://github.com/LuaLS/lua-language-server/wiki/Libraries#link-to-workspace .
-- Lua-dev.nvim also has similar settings for lua ls, https://github.com/folke/neodev.nvim/blob/main/lua/neodev/luals.lua .
library = {
fn.stdpath("data") .. "/site/pack/packer/opt/emmylua-nvim",
fn.stdpath("config"),
},
maxPreload = 2000,
preloadFileSize = 50000,
},
},
},
capabilities = capabilities,
}
end
-- Change diagnostic signs.
fn.sign_define("DiagnosticSignError", { text = "", texthl = "DiagnosticSignError" })
fn.sign_define("DiagnosticSignWarn", { text = "!", texthl = "DiagnosticSignWarn" })
fn.sign_define("DiagnosticSignInformation", { text = "", texthl = "DiagnosticSignInfo" })
fn.sign_define("DiagnosticSignHint", { text = "", texthl = "DiagnosticSignHint" })
-- global config for diagnostic
diagnostic.config {
underline = false,
virtual_text = false,
signs = true,
severity_sort = true,
}
-- lsp.handlers["textDocument/publishDiagnostics"] = lsp.with(lsp.diagnostic.on_publish_diagnostics, {
-- underline = false,
-- virtual_text = false,
-- signs = true,
-- update_in_insert = false,
-- })
-- Change border of documentation hover window, See https://github.com/neovim/neovim/pull/13998.
lsp.handlers["textDocument/hover"] = lsp.with(vim.lsp.handlers.hover, {
border = "rounded",
}) })
-- Enable lsp servers when they are available
local capabilities = require("lsp_utils").get_default_capabilities()
vim.lsp.config("*", {
capabilities = capabilities,
flags = {
debounce_text_changes = 500,
},
})
-- A mapping from lsp server name to the executable name
local enabled_lsp_servers = {
pyright = "delance-langserver",
ruff = "ruff",
lua_ls = "lua-language-server",
-- ltex = "ltex-ls",
-- clangd = "clangd",
vimls = "vim-language-server",
bashls = "bash-language-server",
yamlls = "yaml-language-server",
}
for server_name, lsp_executable in pairs(enabled_lsp_servers) do
if utils.executable(lsp_executable) then
vim.lsp.enable(server_name)
else
local msg = string.format(
"Executable '%s' for server '%s' not found! Server will not be enabled",
lsp_executable,
server_name
)
vim.notify(msg, vim.log.levels.WARN, { title = "Nvim-config" })
end
end

310
lua/config/lualine.lua Normal file
View File

@@ -0,0 +1,310 @@
local fn = vim.fn
local git_status_cache = {}
local on_exit_fetch = function(result)
if result.code == 0 then
git_status_cache.fetch_success = true
end
end
local function handle_numeric_result(cache_key)
return function(result)
if result.code == 0 then
git_status_cache[cache_key] = tonumber(result.stdout:match("(%d+)")) or 0
end
end
end
local async_cmd = function(cmd_str, on_exit)
local cmd = vim.tbl_filter(function(element)
return element ~= ""
end, vim.split(cmd_str, " "))
vim.system(cmd, { text = true }, on_exit)
end
local async_git_status_update = function()
-- Fetch the latest changes from the remote repository (replace 'origin' if needed)
async_cmd("git fetch origin", on_exit_fetch)
if not git_status_cache.fetch_success then
return
end
-- Get the number of commits behind
-- the @{upstream} notation is inspired by post: https://www.reddit.com/r/neovim/comments/t48x5i/git_branch_aheadbehind_info_status_line_component/
-- note that here we should use double dots instead of triple dots
local behind_cmd_str = "git rev-list --count HEAD..@{upstream}"
async_cmd(behind_cmd_str, handle_numeric_result("behind_count"))
-- Get the number of commits ahead
local ahead_cmd_str = "git rev-list --count @{upstream}..HEAD"
async_cmd(ahead_cmd_str, handle_numeric_result("ahead_count"))
end
local function get_git_ahead_behind_info()
async_git_status_update()
local status = git_status_cache
if not status then
return ""
end
local msg = ""
if type(status.ahead_count) == "number" and status.ahead_count > 0 then
local ahead_str = string.format("↑[%d] ", status.ahead_count)
msg = msg .. ahead_str
end
if type(status.behind_count) == "number" and status.behind_count > 0 then
local behind_str = string.format("↓[%d] ", status.behind_count)
msg = msg .. behind_str
end
return msg
end
local function spell()
if vim.o.spell then
return string.format("[SPELL]")
end
return ""
end
--- show indicator for Chinese IME
local function ime_state()
if vim.g.is_mac then
-- ref: https://github.com/vim-airline/vim-airline/blob/master/autoload/airline/extensions/xkblayout.vim#L11
local layout = fn.libcall(vim.g.XkbSwitchLib, "Xkb_Switch_getXkbLayout", "")
-- We can use `xkbswitch -g` on the command line to get current mode.
-- mode for macOS builtin pinyin IME: com.apple.inputmethod.SCIM.ITABC
-- mode for Rime: im.rime.inputmethod.Squirrel.Rime
local res = fn.match(layout, [[\v(Squirrel\.Rime|SCIM.ITABC)]])
if res ~= -1 then
return "[CN]"
end
end
return ""
end
local function trailing_space()
if not vim.o.modifiable then
return ""
end
local line_num = nil
for i = 1, fn.line("$") do
local linetext = fn.getline(i)
-- To prevent invalid escape error, we wrap the regex string with `[[]]`.
local idx = fn.match(linetext, [[\v\s+$]])
if idx ~= -1 then
line_num = i
break
end
end
local msg = ""
if line_num ~= nil then
msg = string.format("[%d]trailing", line_num)
end
return msg
end
local function mixed_indent()
if not vim.o.modifiable then
return ""
end
local space_pat = [[\v^ +]]
local tab_pat = [[\v^\t+]]
local space_indent = fn.search(space_pat, "nwc")
local tab_indent = fn.search(tab_pat, "nwc")
local mixed = (space_indent > 0 and tab_indent > 0)
local mixed_same_line
if not mixed then
mixed_same_line = fn.search([[\v^(\t+ | +\t)]], "nwc")
mixed = mixed_same_line > 0
end
if not mixed then
return ""
end
if mixed_same_line ~= nil and mixed_same_line > 0 then
return "MI:" .. mixed_same_line
end
local space_indent_cnt = fn.searchcount({ pattern = space_pat, max_count = 1e3 }).total
local tab_indent_cnt = fn.searchcount({ pattern = tab_pat, max_count = 1e3 }).total
if space_indent_cnt > tab_indent_cnt then
return "MI:" .. tab_indent
else
return "MI:" .. space_indent
end
end
local diff = function()
local git_status = vim.b.gitsigns_status_dict
if git_status == nil then
return
end
local modify_num = git_status.changed
local remove_num = git_status.removed
local add_num = git_status.added
local info = { added = add_num, modified = modify_num, removed = remove_num }
-- vim.print(info)
return info
end
local virtual_env = function()
-- only show virtual env for Python
if vim.bo.filetype ~= "python" then
return ""
end
local conda_env = os.getenv("CONDA_DEFAULT_ENV")
local venv_path = os.getenv("VIRTUAL_ENV")
if venv_path == nil then
if conda_env == nil then
return ""
else
return string.format(" %s (conda)", conda_env)
end
else
local venv_name = vim.fn.fnamemodify(venv_path, ":t")
return string.format(" %s (venv)", venv_name)
end
end
local get_active_lsp = function()
local msg = "🚫"
local buf_ft = vim.api.nvim_get_option_value("filetype", {})
local clients = vim.lsp.get_clients { bufnr = 0 }
if next(clients) == nil then
return msg
end
for _, client in ipairs(clients) do
---@diagnostic disable-next-line: undefined-field
local filetypes = client.config.filetypes
if filetypes and vim.fn.index(filetypes, buf_ft) ~= -1 then
return client.name
end
end
return msg
end
require("lualine").setup {
options = {
icons_enabled = true,
theme = "auto",
component_separators = { left = "", right = "" },
section_separators = "",
disabled_filetypes = {},
always_divide_middle = true,
refresh = {
statusline = 1000,
},
},
sections = {
lualine_a = {
{
"filename",
symbols = {
readonly = "[🔒]",
},
},
},
lualine_b = {
{
"branch",
fmt = function(name, _)
-- truncate branch name in case the name is too long
return string.sub(name, 1, 20)
end,
color = { gui = "italic,bold" },
},
{
get_git_ahead_behind_info,
color = { fg = "#E0C479" },
},
{
"diff",
source = diff,
},
{
virtual_env,
color = { fg = "black", bg = "#F1CA81" },
},
},
lualine_c = {
{
"%S",
color = { gui = "bold", fg = "cyan" },
},
{
spell,
color = { fg = "black", bg = "#a7c080" },
},
},
lualine_x = {
{
get_active_lsp,
icon = "📡",
},
{
"diagnostics",
sources = { "nvim_diagnostic" },
symbols = { error = "🆇 ", warn = "⚠️ ", info = " ", hint = "" },
},
{
trailing_space,
color = "WarningMsg",
},
{
mixed_indent,
color = "WarningMsg",
},
},
lualine_y = {
{
"encoding",
fmt = string.upper,
},
{
"fileformat",
symbols = {
unix = "unix",
dos = "win",
mac = "mac",
},
},
"filetype",
{
ime_state,
color = { fg = "black", bg = "#f46868" },
},
},
lualine_z = {
"location",
"progress",
},
},
inactive_sections = {
lualine_a = {},
lualine_b = {},
lualine_c = { "filename" },
lualine_x = { "location" },
lualine_y = {},
lualine_z = {},
},
tabline = {},
extensions = { "quickfix", "fugitive", "nvim-tree" },
}

View File

@@ -1,6 +1,15 @@
-- Setup nvim-cmp. -- Setup nvim-cmp.
local cmp = require("cmp") local cmp = require("cmp")
local lspkind = require("lspkind")
-- The extentions needed by nvim-cmp should be loaded beforehand
require("cmp_nvim_lsp")
require("cmp_path")
require("cmp_buffer")
require("cmp_omni")
require("cmp_nvim_ultisnips")
require("cmp_cmdline")
local MiniIcons = require("mini.icons")
cmp.setup { cmp.setup {
snippet = { snippet = {
@@ -35,7 +44,6 @@ cmp.setup {
{ name = "ultisnips" }, -- For ultisnips user. { name = "ultisnips" }, -- For ultisnips user.
{ name = "path" }, -- for path completion { name = "path" }, -- for path completion
{ name = "buffer", keyword_length = 2 }, -- for buffer word completion { name = "buffer", keyword_length = 2 }, -- for buffer word completion
{ name = "emoji", insert = true }, -- emoji completion
}, },
completion = { completion = {
keyword_length = 1, keyword_length = 1,
@@ -44,19 +52,14 @@ cmp.setup {
view = { view = {
entries = "custom", entries = "custom",
}, },
-- solution taken from https://github.com/echasnovski/mini.nvim/issues/1007#issuecomment-2258929830
formatting = { formatting = {
format = lspkind.cmp_format { format = function(_, vim_item)
mode = "symbol_text", local icon, hl = MiniIcons.get("lsp", vim_item.kind)
menu = { vim_item.kind = icon .. " " .. vim_item.kind
nvim_lsp = "[LSP]", vim_item.kind_hl_group = hl
ultisnips = "[US]", return vim_item
nvim_lua = "[Lua]", end,
path = "[Path]",
buffer = "[Buffer]",
emoji = "[Emoji]",
omni = "[Omni]",
},
},
}, },
} }
@@ -69,6 +72,23 @@ cmp.setup.filetype("tex", {
}, },
}) })
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" },
}),
matching = { disallow_symbol_nonprefix_matching = false },
})
-- see https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance#how-to-add-visual-studio-code-dark-theme-colors-to-the-menu -- see https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance#how-to-add-visual-studio-code-dark-theme-colors-to-the-menu
vim.cmd([[ vim.cmd([[
highlight! link CmpItemMenu Comment highlight! link CmpItemMenu Comment

View File

@@ -0,0 +1,23 @@
local builtin = require("statuscol.builtin")
local ffi = require("statuscol.ffidef")
local C = ffi.C
-- only show fold level up to this level
local fold_level_limit = 3
local function foldfunc(args)
local foldinfo = C.fold_info(args.wp, args.lnum)
if foldinfo.level > fold_level_limit then
return " "
end
return builtin.foldfunc(args)
end
require("statuscol").setup {
relculright = false,
segments = {
{ text = { "%s" }, click = "v:lua.ScSa" },
{ text = { builtin.lnumfunc, " " }, click = "v:lua.ScLa" },
{ text = { foldfunc, " " }, condition = { true, builtin.not_empty }, click = "v:lua.ScFa" },
},
}

View File

@@ -4,26 +4,19 @@ local nvim_tree = require("nvim-tree")
nvim_tree.setup { nvim_tree.setup {
auto_reload_on_write = true, auto_reload_on_write = true,
disable_netrw = false, disable_netrw = false,
hijack_cursor = false,
hijack_netrw = true, hijack_netrw = true,
hijack_cursor = false,
hijack_unnamed_buffer_when_opening = false, hijack_unnamed_buffer_when_opening = false,
open_on_tab = false, open_on_tab = false,
sort_by = "name", sort_by = "name",
update_cwd = false, update_cwd = false,
view = { view = {
width = 30, width = 30,
hide_root_folder = false,
side = "left", side = "left",
preserve_window_proportions = false, preserve_window_proportions = false,
number = false, number = false,
relativenumber = false, relativenumber = false,
signcolumn = "yes", signcolumn = "yes",
mappings = {
custom_only = false,
list = {
-- user mappings go here
},
},
}, },
renderer = { renderer = {
indent_markers = { indent_markers = {
@@ -85,7 +78,7 @@ nvim_tree.setup {
enable = true, enable = true,
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
exclude = { exclude = {
filetype = { "notify", "packer", "qf", "diff", "fugitive", "fugitiveblame" }, filetype = { "notify", "qf", "diff", "fugitive", "fugitiveblame" },
buftype = { "nofile", "terminal", "help" }, buftype = { "nofile", "terminal", "help" },
}, },
}, },

View File

@@ -1,13 +1,10 @@
vim.cmd([[hi HopNextKey cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff]])
vim.cmd([[hi HopNextKey1 cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff]])
vim.cmd([[hi HopNextKey2 cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff]])
local keymap = vim.keymap local keymap = vim.keymap
local hop = require("hop") local hop = require("hop")
hop.setup { hop.setup {
case_insensitive = true, case_insensitive = true,
char2_fallback_key = "<CR>", char2_fallback_key = "<CR>",
quit_key = "<Esc>", quit_key = "<Esc>",
match_mappings = { "zh_sc" },
} }
keymap.set({ "n", "v", "o" }, "f", "", { keymap.set({ "n", "v", "o" }, "f", "", {
@@ -18,3 +15,14 @@ keymap.set({ "n", "v", "o" }, "f", "", {
end, end,
desc = "nvim-hop char2", desc = "nvim-hop char2",
}) })
vim.api.nvim_create_autocmd("ColorScheme", {
pattern = "*",
callback = function()
vim.cmd([[
hi HopNextKey cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff
hi HopNextKey1 cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff
hi HopNextKey2 cterm=bold ctermfg=176 gui=bold guibg=#ff00ff guifg=#ffffff
]])
end,
})

44
lua/config/nvim_ufo.lua Normal file
View File

@@ -0,0 +1,44 @@
local handler = function(virtText, lnum, endLnum, width, truncate)
local newVirtText = {}
local foldedLines = endLnum - lnum
local suffix = (" 󰁂 %d"):format(foldedLines)
local sufWidth = vim.fn.strdisplaywidth(suffix)
local targetWidth = width - sufWidth
local curWidth = 0
for _, chunk in ipairs(virtText) do
local chunkText = chunk[1]
local chunkWidth = vim.fn.strdisplaywidth(chunkText)
if targetWidth > curWidth + chunkWidth then
table.insert(newVirtText, chunk)
else
chunkText = truncate(chunkText, targetWidth - curWidth)
local hlGroup = chunk[2]
table.insert(newVirtText, { chunkText, hlGroup })
chunkWidth = vim.fn.strdisplaywidth(chunkText)
-- str width returned from truncate() may less than 2nd argument, need padding
if curWidth + chunkWidth < targetWidth then
suffix = suffix .. (" "):rep(targetWidth - curWidth - chunkWidth)
end
break
end
curWidth = curWidth + chunkWidth
end
local rAlignAppndx = math.max(math.min(vim.opt.textwidth["_value"], width - 1) - curWidth - sufWidth, 0)
suffix = (" "):rep(rAlignAppndx) .. suffix
table.insert(newVirtText, { suffix, "MoreMsg" })
return newVirtText
end
require("ufo").setup {
fold_virt_text_handler = handler,
}
vim.keymap.set("n", "zR", require("ufo").openAllFolds)
vim.keymap.set("n", "zM", require("ufo").closeAllFolds)
vim.keymap.set("n", "zr", require("ufo").openFoldsExceptKinds)
vim.keymap.set("n", "<leader>K", function()
local _ = require("ufo").peekFoldedLinesUnderCursor()
end, {
desc = "Preview folded maps",
})

View File

@@ -1,170 +0,0 @@
local fn = vim.fn
local function spell()
if vim.o.spell then
return string.format("[SPELL]")
end
return ""
end
--- show indicator for Chinese IME
local function ime_state()
if vim.g.is_mac then
-- ref: https://github.com/vim-airline/vim-airline/blob/master/autoload/airline/extensions/xkblayout.vim#L11
local layout = fn.libcall(vim.g.XkbSwitchLib, "Xkb_Switch_getXkbLayout", "")
-- We can use `xkbswitch -g` on the command line to get current mode.
-- mode for macOS builtin pinyin IME: com.apple.inputmethod.SCIM.ITABC
-- mode for Rime: im.rime.inputmethod.Squirrel.Rime
local res = fn.match(layout, [[\v(Squirrel\.Rime|SCIM.ITABC)]])
if res ~= -1 then
return "[CN]"
end
end
return ""
end
local function trailing_space()
if not vim.o.modifiable then
return ""
end
local line_num = nil
for i = 1, fn.line("$") do
local linetext = fn.getline(i)
-- To prevent invalid escape error, we wrap the regex string with `[[]]`.
local idx = fn.match(linetext, [[\v\s+$]])
if idx ~= -1 then
line_num = i
break
end
end
local msg = ""
if line_num ~= nil then
msg = string.format("[%d]trailing", line_num)
end
return msg
end
local function mixed_indent()
if not vim.o.modifiable then
return ""
end
local space_pat = [[\v^ +]]
local tab_pat = [[\v^\t+]]
local space_indent = fn.search(space_pat, "nwc")
local tab_indent = fn.search(tab_pat, "nwc")
local mixed = (space_indent > 0 and tab_indent > 0)
local mixed_same_line
if not mixed then
mixed_same_line = fn.search([[\v^(\t+ | +\t)]], "nwc")
mixed = mixed_same_line > 0
end
if not mixed then
return ""
end
if mixed_same_line ~= nil and mixed_same_line > 0 then
return "MI:" .. mixed_same_line
end
local space_indent_cnt = fn.searchcount({ pattern = space_pat, max_count = 1e3 }).total
local tab_indent_cnt = fn.searchcount({ pattern = tab_pat, max_count = 1e3 }).total
if space_indent_cnt > tab_indent_cnt then
return "MI:" .. tab_indent
else
return "MI:" .. space_indent
end
end
local diff = function()
local git_status = vim.b.gitsigns_status_dict
if git_status == nil then
return
end
local modify_num = git_status.changed
local remove_num = git_status.removed
local add_num = git_status.added
local info = { added = add_num, modified = modify_num, removed = remove_num }
-- vim.print(info)
return info
end
require("lualine").setup {
options = {
icons_enabled = true,
theme = "auto",
-- component_separators = { left = "", right = "" },
-- section_separators = { left = "", right = "" },
section_separators = "",
component_separators = "",
disabled_filetypes = {},
always_divide_middle = true,
},
sections = {
lualine_a = { "mode" },
lualine_b = {
"branch",
{
"diff",
source = diff,
},
},
lualine_c = {
"filename",
{
ime_state,
color = { fg = "black", bg = "#f46868" },
},
{
spell,
color = { fg = "black", bg = "#a7c080" },
},
},
lualine_x = {
"encoding",
{
"fileformat",
symbols = {
unix = "unix",
dos = "win",
mac = "mac",
},
},
"filetype",
},
lualine_y = { "progress" },
lualine_z = {
"location",
{
"diagnostics",
sources = { "nvim_diagnostic" },
},
{
trailing_space,
color = "WarningMsg",
},
{
mixed_indent,
color = "WarningMsg",
},
},
},
inactive_sections = {
lualine_a = {},
lualine_b = {},
lualine_c = { "filename" },
lualine_x = { "location" },
lualine_y = {},
lualine_z = {},
},
tabline = {},
extensions = { "quickfix", "fugitive", "nvim-tree" },
}

View File

@@ -0,0 +1,44 @@
require("nvim-treesitter.configs").setup {
textobjects = {
select = {
enable = true,
-- Automatically jump forward to textobj, similar to targets.vim
lookahead = true,
keymaps = {
-- You can use the capture groups defined in textobjects.scm
["af"] = "@function.outer",
["if"] = "@function.inner",
["ac"] = "@class.outer",
-- You can optionally set descriptions to the mappings (used in the desc parameter of
-- nvim_buf_set_keymap) which plugins like which-key display
["ic"] = { query = "@class.inner", desc = "Select inner part of a class region" },
},
-- You can choose the select mode (default is charwise 'v')
--
-- Can also be a function which gets passed a table with the keys
-- * query_string: eg '@function.inner'
-- * method: eg 'v' or 'o'
-- and should return the mode ('v', 'V', or '<c-v>') or a table
-- mapping query_strings to modes.
selection_modes = {
["@function.inner"] = "V", -- linewise
["@function.outer"] = "V", -- linewise
["@class.outer"] = "V", -- linewise
["@class.inner"] = "V", -- linewise
["@parameter.outer"] = "v", -- charwise
},
-- If you set this to `true` (default is `false`) then any textobject is
-- extended to include preceding or succeeding whitespace. Succeeding
-- whitespace has priority in order to act similarly to eg the built-in
-- `ap`.
--
-- Can also be a function which gets passed a table with the keys
-- * query_string: eg '@function.inner'
-- * selection_mode: eg 'v'
-- and should return true or false
include_surrounding_whitespace = false,
},
},
}

View File

@@ -1,8 +1,8 @@
require("nvim-treesitter.configs").setup { require("nvim-treesitter.configs").setup {
ensure_installed = { "python", "cpp", "lua", "vim", "json" }, ensure_installed = { "python", "cpp", "lua", "vim", "json", "toml" },
ignore_install = {}, -- List of parsers to ignore installing ignore_install = {}, -- List of parsers to ignore installing
highlight = { highlight = {
enable = true, -- false will disable the whole extension enable = true, -- false will disable the whole extension
disable = { 'help' }, -- list of language that will be disabled disable = { "help" }, -- list of language that will be disabled
}, },
} }

View File

@@ -1,60 +1,6 @@
require("which-key").setup { require("which-key").setup {
plugins = { preset = "modern",
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 = 9, -- 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 = true, -- 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
},
},
-- add operators that will trigger motion and text object completion
-- to enable all native operators, set the preset / operators plugin above
operators = { gc = "Comments" },
key_labels = {
-- override the label used to display some keys. It doesn't effect WK in any other way.
-- For example:
-- ["<space>"] = "SPC",
-- ["<cr>"] = "RET",
-- ["<tab>"] = "TAB",
},
icons = { icons = {
breadcrumb = "»", -- symbol used in the command line area that shows your active key combo mappings = false,
separator = "", -- symbol used between a key and it's label
group = "+", -- symbol prepended to a group
},
window = {
border = "none", -- none, single, double, shadow
position = "bottom", -- bottom, top
margin = { 0, 0, 0, 0 }, -- extra window margin [top, right, bottom, left]
padding = { 1, 0, 1, 0 }, -- extra window padding [top, right, bottom, left]
},
layout = {
height = { min = 1, max = 25 }, -- min and max height of the columns
width = { min = 20, max = 50 }, -- min and max width of the columns
spacing = 1, -- spacing between columns
align = "center", -- align columns left, center or right
},
ignore_missing = false, -- enable this to hide mappings for which you didn't specify a label
hidden = { "<silent>", "<cmd>", "<Cmd>", "<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
triggers_blacklist = {
-- list of mode / prefixes that should never be hooked by WhichKey
-- this is mostly relevant for key maps that start with a native binding
-- most people should not need to change this
n = { "o", "O" },
}, },
} }

View File

@@ -1,13 +1,17 @@
require("yanky").setup({ require("yanky").setup {
ring = {
history_length = 50,
storage = "memory",
},
preserve_cursor_position = { preserve_cursor_position = {
enabled = false, enabled = false,
}, },
}) highlight = {
on_put = true,
on_yank = false,
timer = 300,
},
}
vim.keymap.set({ "n", "x" }, "p", "<Plug>(YankyPutAfter)")
vim.keymap.set({ "n", "x" }, "P", "<Plug>(YankyPutBefore)")
-- cycle through the yank history, only work after paste -- cycle through the yank history, only work after paste
vim.keymap.set("n", "[y", "<Plug>(YankyCycleForward)") vim.keymap.set("n", "[y", "<Plug>(YankyPreviousEntry)")
vim.keymap.set("n", "]y", "<Plug>(YankyCycleBackward)") vim.keymap.set("n", "]y", "<Plug>(YankyNextEntry)")

View File

@@ -1,15 +0,0 @@
require("zen-mode").setup {
window = {
backdrop = 0.8, -- shade the backdrop of the Zen window. Set to 1 to keep the same as Normal
width = 120,
options = {
-- signcolumn = "no", -- disable signcolumn
-- number = false, -- disable number column
-- relativenumber = false, -- disable relative numbers
cursorline = false, -- disable cursorline
cursorcolumn = false, -- disable cursor column
foldcolumn = "0", -- disable fold column
list = false, -- disable whitespace characters
},
},
}

View File

@@ -17,11 +17,31 @@ api.nvim_create_autocmd({ "BufRead" }, {
}) })
-- highlight yanked region, see `:h lua-highlight` -- highlight yanked region, see `:h lua-highlight`
local yank_group = api.nvim_create_augroup("highlight_yank", { clear = true })
api.nvim_create_autocmd({ "TextYankPost" }, { api.nvim_create_autocmd({ "TextYankPost" }, {
pattern = "*", pattern = "*",
group = api.nvim_create_augroup("highlight_yank", { clear = true }), group = yank_group,
callback = function() callback = function()
vim.highlight.on_yank { higroup = "YankColor", timeout = 300 } vim.hl.on_yank { higroup = "YankColor", timeout = 300 }
end,
})
api.nvim_create_autocmd({ "CursorMoved" }, {
pattern = "*",
group = yank_group,
callback = function()
vim.g.current_cursor_pos = vim.fn.getcurpos()
end,
})
api.nvim_create_autocmd("TextYankPost", {
pattern = "*",
group = yank_group,
---@diagnostic disable-next-line: unused-local
callback = function(context)
if vim.v.event.operator == "y" then
vim.fn.setpos(".", vim.g.current_cursor_pos)
end
end, end,
}) })
@@ -64,3 +84,161 @@ api.nvim_create_autocmd("VimResized", {
desc = "autoresize windows on resizing operation", desc = "autoresize windows on resizing operation",
command = "wincmd =", command = "wincmd =",
}) })
local function open_nvim_tree(data)
-- check if buffer is a directory
local directory = vim.fn.isdirectory(data.file) == 1
if not directory then
return
end
-- create a new, empty buffer
vim.cmd.enew()
-- wipe the directory buffer
vim.cmd.bw(data.buf)
-- open the tree
require("nvim-tree.api").tree.open()
end
api.nvim_create_autocmd({ "VimEnter" }, { callback = open_nvim_tree })
-- Do not use smart case in command line mode, extracted from https://vi.stackexchange.com/a/16511/15292.
api.nvim_create_augroup("dynamic_smartcase", { clear = true })
api.nvim_create_autocmd("CmdLineEnter", {
group = "dynamic_smartcase",
pattern = ":",
callback = function()
vim.o.smartcase = false
end,
})
api.nvim_create_autocmd("CmdLineLeave", {
group = "dynamic_smartcase",
pattern = ":",
callback = function()
vim.o.smartcase = true
end,
})
api.nvim_create_autocmd("TermOpen", {
group = api.nvim_create_augroup("term_start", { clear = true }),
pattern = "*",
callback = function()
-- Do not use number and relative number for terminal inside nvim
vim.wo.relativenumber = false
vim.wo.number = false
-- Go to insert mode by default to start typing command
vim.cmd("startinsert")
end,
})
local number_toggle_group = api.nvim_create_augroup("numbertoggle", { clear = true })
api.nvim_create_autocmd({ "BufEnter", "FocusGained", "InsertLeave", "WinEnter" }, {
pattern = "*",
group = number_toggle_group,
desc = "togger line number",
callback = function()
if vim.wo.number then
vim.wo.relativenumber = true
end
end,
})
api.nvim_create_autocmd({ "BufLeave", "FocusLost", "InsertEnter", "WinLeave" }, {
group = number_toggle_group,
desc = "togger line number",
callback = function()
if vim.wo.number then
vim.wo.relativenumber = false
end
end,
})
api.nvim_create_autocmd("ColorScheme", {
group = api.nvim_create_augroup("custom_highlight", { clear = true }),
pattern = "*",
desc = "Define or overrride some highlight groups",
callback = function()
-- For yank highlight
vim.api.nvim_set_hl(0, "YankColor", { fg = "#34495E", bg = "#2ECC71", ctermfg = 59, ctermbg = 41 })
-- For cursor colors
vim.api.nvim_set_hl(0, "Cursor", { fg = "black", bg = "#00c918", bold = true })
vim.api.nvim_set_hl(0, "Cursor2", { fg = "red", bg = "red" })
-- For floating windows border highlight
vim.api.nvim_set_hl(0, "FloatBorder", { fg = "LightGreen", bg = "None", bold = true })
local hl = vim.api.nvim_get_hl(0, { name = "NormalFloat" })
-- change the background color of floating window to None, so it blenders better
vim.api.nvim_set_hl(0, "NormalFloat", { fg = hl.fg, bg = "None" })
-- highlight for matching parentheses
vim.api.nvim_set_hl(0, "MatchParen", { bold = true, underline = true })
end,
})
api.nvim_create_autocmd("BufEnter", {
pattern = "*",
group = api.nvim_create_augroup("auto_close_win", { clear = true }),
desc = "Quit Nvim if we have only one window, and its filetype match our pattern",
---@diagnostic disable-next-line: unused-local
callback = function(context)
local quit_filetypes = { "qf", "vista", "NvimTree" }
local should_quit = true
local tabwins = api.nvim_tabpage_list_wins(0)
for _, win in pairs(tabwins) do
local buf = api.nvim_win_get_buf(win)
local buf_type = vim.api.nvim_get_option_value("filetype", { buf = buf })
if not vim.tbl_contains(quit_filetypes, buf_type) then
should_quit = false
end
end
if should_quit then
vim.cmd("qall")
end
end,
})
api.nvim_create_autocmd({ "VimEnter", "DirChanged" }, {
group = api.nvim_create_augroup("git_repo_check", { clear = true }),
pattern = "*",
desc = "check if we are inside Git repo",
callback = function()
utils.inside_git_repo()
end,
})
-- ref: https://vi.stackexchange.com/a/169/15292
api.nvim_create_autocmd("BufReadPre", {
group = api.nvim_create_augroup("large_file", { clear = true }),
pattern = "*",
desc = "optimize for large file",
callback = function(ev)
local file_size_limit = 524288 -- 0.5MB
local f = ev.file
if fn.getfsize(f) > file_size_limit or fn.getfsize(f) == -2 then
vim.o.eventignore = "all"
-- show ruler
vim.o.ruler = true
-- turning off relative number helps a lot
vim.wo.relativenumber = false
vim.wo.number = false
vim.bo.swapfile = false
vim.bo.bufhidden = "unload"
vim.bo.undolevels = -1
end
end,
})

66
lua/diagnostic-conf.lua Normal file
View File

@@ -0,0 +1,66 @@
local diagnostic = vim.diagnostic
local api = vim.api
-- global config for diagnostic
diagnostic.config {
underline = false,
virtual_text = false,
virtual_lines = false,
signs = {
text = {
[diagnostic.severity.ERROR] = "🆇",
[diagnostic.severity.WARN] = "⚠️",
[diagnostic.severity.INFO] = "",
[diagnostic.severity.HINT] = "",
},
},
severity_sort = true,
float = {
source = true,
header = "Diagnostics:",
prefix = " ",
border = "single",
},
}
-- set quickfix list from diagnostics in a certain buffer, not the whole workspace
local set_qflist = function(buf_num, severity)
local diagnostics = nil
diagnostics = diagnostic.get(buf_num, { severity = severity })
local qf_items = diagnostic.toqflist(diagnostics)
vim.fn.setqflist({}, " ", { title = "Diagnostics", items = qf_items })
-- open quickfix by default
vim.cmd([[copen]])
end
-- this puts diagnostics from opened files to quickfix
vim.keymap.set("n", "<space>qw", diagnostic.setqflist, { desc = "put window diagnostics to qf" })
-- this puts diagnostics from current buffer to quickfix
vim.keymap.set("n", "<space>qb", function()
set_qflist(0)
end, { desc = "put buffer diagnostics to qf" })
-- automatically show diagnostic in float win for current line
api.nvim_create_autocmd("CursorHold", {
pattern = "*",
callback = function()
if #vim.diagnostic.get(0) == 0 then
return
end
if not vim.b.diagnostics_pos then
vim.b.diagnostics_pos = { nil, nil }
end
local cursor_pos = api.nvim_win_get_cursor(0)
if not vim.deep_equal(cursor_pos, vim.b.diagnostics_pos) then
diagnostic.open_float { width = 100 }
end
vim.b.diagnostics_pos = cursor_pos
end,
})

View File

@@ -1,12 +1,7 @@
local fn = vim.fn local fn = vim.fn
local api = vim.api local api = vim.api
local utils = require('utils') local utils = require("utils")
-- Inspect something
function _G.inspect(item)
vim.print(item)
end
------------------------------------------------------------------------ ------------------------------------------------------------------------
-- custom variables -- -- custom variables --
@@ -15,7 +10,7 @@ vim.g.is_win = (utils.has("win32") or utils.has("win64")) and true or false
vim.g.is_linux = (utils.has("unix") and (not utils.has("macunix"))) and true or false vim.g.is_linux = (utils.has("unix") and (not utils.has("macunix"))) and true or false
vim.g.is_mac = utils.has("macunix") and true or false vim.g.is_mac = utils.has("macunix") and true or false
vim.g.logging_level = "info" vim.g.logging_level = vim.log.levels.INFO
------------------------------------------------------------------------ ------------------------------------------------------------------------
-- builtin variables -- -- builtin variables --
@@ -25,25 +20,26 @@ vim.g.loaded_ruby_provider = 0 -- Disable ruby provider
vim.g.loaded_node_provider = 0 -- Disable node provider vim.g.loaded_node_provider = 0 -- Disable node provider
vim.g.did_install_default_menus = 1 -- do not load menu vim.g.did_install_default_menus = 1 -- do not load menu
if utils.executable('python3') then if utils.executable("python3") then
if vim.g.is_win then if vim.g.is_win then
vim.g.python3_host_prog = fn.substitute(fn.exepath("python3"), ".exe$", '', 'g') vim.g.python3_host_prog = fn.substitute(fn.exepath("python3"), ".exe$", "", "g")
else else
vim.g.python3_host_prog = fn.exepath("python3") vim.g.python3_host_prog = fn.exepath("python3")
end end
else else
api.nvim_err_writeln("Python3 executable not found! You must install Python3 and set its PATH correctly!") local msg = "Python3 executable not found! You must install Python3 and set its PATH correctly!"
api.nvim_echo({ { msg } }, true, { err = true })
return return
end end
-- Custom mapping <leader> (see `:h mapleader` for more info) -- Custom mapping <leader> (see `:h mapleader` for more info)
vim.g.mapleader = ',' vim.g.mapleader = ","
-- Enable highlighting for lua HERE doc inside vim script -- Enable highlighting for lua HERE doc inside vim script
vim.g.vimsyn_embed = 'l' vim.g.vimsyn_embed = "l"
-- Use English as main language -- Use English as main language
vim.cmd [[language en_US.UTF-8]] vim.cmd([[language en_US.UTF-8]])
-- Disable loading certain plugins -- Disable loading certain plugins
@@ -73,3 +69,6 @@ vim.g.loaded_matchparen = 1
-- Disable sql omni completion, it is broken. -- Disable sql omni completion, it is broken.
vim.g.loaded_sql_completion = 1 vim.g.loaded_sql_completion = 1
-- control how to show health check window
vim.g.health = { style = nil }

15
lua/lsp_utils.lua Normal file
View File

@@ -0,0 +1,15 @@
local M = {}
M.get_default_capabilities = function()
local capabilities = vim.lsp.protocol.make_client_capabilities()
-- required by nvim-ufo
capabilities.textDocument.foldingRange = {
dynamicRegistration = false,
lineFoldingOnly = true,
}
return capabilities
end
return M

View File

@@ -1,6 +1,5 @@
local keymap = vim.keymap local keymap = vim.keymap
local api = vim.api local uv = vim.uv
local uv = vim.loop
-- Save key strokes (now we do not need to press shift to enter command mode). -- Save key strokes (now we do not need to press shift to enter command mode).
keymap.set({ "n", "x" }, ";", ":") keymap.set({ "n", "x" }, ";", ":")
@@ -24,19 +23,6 @@ keymap.set("n", "<leader>q", "<cmd>x<cr>", { silent = true, desc = "quit current
-- Quit all opened buffers -- Quit all opened buffers
keymap.set("n", "<leader>Q", "<cmd>qa!<cr>", { silent = true, desc = "quit nvim" }) keymap.set("n", "<leader>Q", "<cmd>qa!<cr>", { silent = true, desc = "quit nvim" })
-- Navigation in the location and quickfix list
keymap.set("n", "[l", "<cmd>lprevious<cr>zv", { silent = true, desc = "previous location item" })
keymap.set("n", "]l", "<cmd>lnext<cr>zv", { silent = true, desc = "next location item" })
keymap.set("n", "[L", "<cmd>lfirst<cr>zv", { silent = true, desc = "first location item" })
keymap.set("n", "]L", "<cmd>llast<cr>zv", { silent = true, desc = "last location item" })
keymap.set("n", "[q", "<cmd>cprevious<cr>zv", { silent = true, desc = "previous qf item" })
keymap.set("n", "]q", "<cmd>cnext<cr>zv", { silent = true, desc = "next qf item" })
keymap.set("n", "[Q", "<cmd>cfirst<cr>zv", { silent = true, desc = "first qf item" })
keymap.set("n", "]Q", "<cmd>clast<cr>zv", { silent = true, desc = "last qf item" })
-- Close location list or quickfix list if they are present, see https://superuser.com/q/355325/736190 -- Close location list or quickfix list if they are present, see https://superuser.com/q/355325/736190
keymap.set("n", [[\x]], "<cmd>windo lclose <bar> cclose <cr>", { keymap.set("n", [[\x]], "<cmd>windo lclose <bar> cclose <cr>", {
silent = true, silent = true,
@@ -46,7 +32,21 @@ keymap.set("n", [[\x]], "<cmd>windo lclose <bar> cclose <cr>", {
-- Delete a buffer, without closing the window, see https://stackoverflow.com/q/4465095/6064933 -- Delete a buffer, without closing the window, see https://stackoverflow.com/q/4465095/6064933
keymap.set("n", [[\d]], "<cmd>bprevious <bar> bdelete #<cr>", { keymap.set("n", [[\d]], "<cmd>bprevious <bar> bdelete #<cr>", {
silent = true, silent = true,
desc = "delete buffer", desc = "delete current buffer",
})
keymap.set("n", [[\D]], function()
local buf_ids = vim.api.nvim_list_bufs()
local cur_buf = vim.api.nvim_win_get_buf(0)
for _, buf_id in pairs(buf_ids) do
-- do not Delete unlisted buffers, which may lead to unexpected errors
if vim.api.nvim_get_option_value("buflisted", { buf = buf_id }) and buf_id ~= cur_buf then
vim.api.nvim_buf_delete(buf_id, { force = true })
end
end
end, {
desc = "delete other buffers",
}) })
-- Insert a blank line below or above current line (do not move the cursor), -- Insert a blank line below or above current line (do not move the cursor),
@@ -104,7 +104,7 @@ keymap.set("n", "<leader>v", "printf('`[%s`]', getregtype()[0])", {
}) })
-- Always use very magic mode for searching -- Always use very magic mode for searching
keymap.set("n", "/", [[/\v]]) -- keymap.set("n", "/", [[/\v]])
-- Search in selected region -- Search in selected region
-- xnoremap / :<C-U>call feedkeys('/\%>'.(line("'<")-1).'l\%<'.(line("'>")+1)."l")<CR> -- xnoremap / :<C-U>call feedkeys('/\%>'.(line("'<")-1).'l\%<'.(line("'>")+1)."l")<CR>
@@ -130,9 +130,6 @@ keymap.set("x", "c", '"_c')
-- Remove trailing whitespace characters -- Remove trailing whitespace characters
keymap.set("n", "<leader><space>", "<cmd>StripTrailingWhitespace<cr>", { desc = "remove trailing space" }) keymap.set("n", "<leader><space>", "<cmd>StripTrailingWhitespace<cr>", { desc = "remove trailing space" })
-- check the syntax group of current cursor position
keymap.set("n", "<leader>st", "<cmd>call utils#SynGroup()<cr>", { desc = "check syntax group" })
-- Copy entire buffer. -- Copy entire buffer.
keymap.set("n", "<leader>y", "<cmd>%yank<cr>", { desc = "yank entire buffer" }) keymap.set("n", "<leader>y", "<cmd>%yank<cr>", { desc = "yank entire buffer" })
@@ -170,7 +167,7 @@ keymap.set("n", "<Down>", "<C-W>j")
keymap.set({ "x", "o" }, "iu", "<cmd>call text_obj#URL()<cr>", { desc = "URL text object" }) keymap.set({ "x", "o" }, "iu", "<cmd>call text_obj#URL()<cr>", { desc = "URL text object" })
-- Text objects for entire buffer -- Text objects for entire buffer
keymap.set({ "x", "o" }, "iB", "<cmd>call text_obj#Buffer()<cr>", { desc = "buffer text object" }) keymap.set({ "x", "o" }, "iB", ":<C-U>call text_obj#Buffer()<cr>", { desc = "buffer text object" })
-- Do not move my cursor when joining lines. -- Do not move my cursor when joining lines.
keymap.set("n", "J", function() keymap.set("n", "J", function()
@@ -179,17 +176,17 @@ keymap.set("n", "J", function()
delmarks z delmarks z
]]) ]])
end, { end, {
desc = "join line", desc = "join lines without moving cursor",
}) })
keymap.set("n", "gJ", function() keymap.set("n", "gJ", function()
-- we must use `normal!`, otherwise it will trigger recursive mapping -- we must use `normal!`, otherwise it will trigger recursive mapping
vim.cmd([[ vim.cmd([[
normal! zmgJ`z normal! mzgJ`z
delmarks z delmarks z
]]) ]])
end, { end, {
desc = "join visual lines", desc = "join lines without moving cursor",
}) })
-- Break inserted text into smaller undo units when we insert some punctuation chars. -- Break inserted text into smaller undo units when we insert some punctuation chars.
@@ -201,20 +198,6 @@ end
-- insert semicolon in the end -- insert semicolon in the end
keymap.set("i", "<A-;>", "<Esc>miA;<Esc>`ii") keymap.set("i", "<A-;>", "<Esc>miA;<Esc>`ii")
-- Keep cursor position after yanking
keymap.set("n", "y", "myy")
api.nvim_create_autocmd("TextYankPost", {
pattern = "*",
group = api.nvim_create_augroup("restore_after_yank", { clear = true }),
callback = function()
vim.cmd([[
silent! normal! `y
silent! delmarks y
]])
end,
})
-- Go to the beginning and end of current line in insert mode quickly -- Go to the beginning and end of current line in insert mode quickly
keymap.set("i", "<C-A>", "<HOME>") keymap.set("i", "<C-A>", "<HOME>")
keymap.set("i", "<C-E>", "<END>") keymap.set("i", "<C-E>", "<END>")
@@ -229,17 +212,24 @@ keymap.set("n", "<leader>cb", function()
local cnt = 0 local cnt = 0
local blink_times = 7 local blink_times = 7
local timer = uv.new_timer() local timer = uv.new_timer()
if timer == nil then
return
end
timer:start(0, 100, vim.schedule_wrap(function() timer:start(
vim.cmd[[ 0,
100,
vim.schedule_wrap(function()
vim.cmd([[
set cursorcolumn! set cursorcolumn!
set cursorline! set cursorline!
]] ]])
if cnt == blink_times then if cnt == blink_times then
timer:close() timer:close()
end end
cnt = cnt + 1 cnt = cnt + 1
end)) end)
end) )
end, { desc = "show cursor" })

670
lua/plugin_specs.lua Normal file
View File

@@ -0,0 +1,670 @@
local utils = require("utils")
local plugin_dir = vim.fn.stdpath("data") .. "/lazy"
local lazypath = plugin_dir .. "/lazy.nvim"
if not vim.uv.fs_stat(lazypath) then
vim.fn.system {
"git",
"clone",
"--filter=blob:none",
"https://github.com/folke/lazy.nvim.git",
"--branch=stable", -- latest stable release
lazypath,
}
end
vim.opt.rtp:prepend(lazypath)
-- check if firenvim is active
local firenvim_not_active = function()
return not vim.g.started_by_firenvim
end
local plugin_specs = {
-- auto-completion engine
{ "hrsh7th/cmp-nvim-lsp", lazy = true },
{ "hrsh7th/cmp-path", lazy = true },
{ "hrsh7th/cmp-buffer", lazy = true },
{ "hrsh7th/cmp-omni", lazy = true },
{ "hrsh7th/cmp-cmdline", lazy = true },
{ "quangnguyen30192/cmp-nvim-ultisnips", lazy = true },
{
"hrsh7th/nvim-cmp",
name = "nvim-cmp",
event = "VeryLazy",
config = function()
require("config.nvim-cmp")
end,
},
--{
-- "saghen/blink.cmp",
-- -- optional: provides snippets for the snippet source
-- dependencies = { "rafamadriz/friendly-snippets" },
-- -- use a release tag to download pre-built binaries
-- version = "1.*",
-- ---@module 'blink.cmp'
-- ---@type blink.cmp.Config
-- opts = {
-- -- 'default' (recommended) for mappings similar to built-in completions (C-y to accept)
-- -- 'super-tab' for mappings similar to vscode (tab to accept)
-- -- 'enter' for enter to accept
-- -- 'none' for no mappings
-- --
-- keymap = {
-- preset = "default",
-- ["<Tab>"] = { "select_next", "fallback" },
-- ["<S-Tab>"] = { "select_prev", "fallback" },
-- ["<Enter>"] = { "select_and_accept", "fallback" },
-- ["<C-U>"] = { "scroll_documentation_up", "fallback" },
-- ["<C-D>"] = { "scroll_documentation_down", "fallback" },
-- },
-- appearance = {
-- -- 'mono' (default) for 'Nerd Font Mono' or 'normal' for 'Nerd Font'
-- -- Adjusts spacing to ensure icons are aligned
-- nerd_font_variant = "mono",
-- },
-- -- (Default) Only show the documentation popup when manually triggered
-- completion = {
-- documentation = {
-- auto_show = true,
-- },
-- },
-- -- Default list of enabled providers defined so that you can extend it
-- -- elsewhere in your config, without redefining it, due to `opts_extend`
-- sources = {
-- default = { "lsp", "path", "buffer" },
-- },
-- -- (Default) Rust fuzzy matcher for typo resistance and significantly better performance
-- -- You may use a lua implementation instead by using `implementation = "lua"` or fallback to the lua implementation,
-- -- when the Rust fuzzy matcher is not available, by using `implementation = "prefer_rust"`
-- --
-- -- See the fuzzy documentation for more information
-- fuzzy = { implementation = "prefer_rust_with_warning" },
-- cmdline = {
-- completion = {
-- menu = {
-- auto_show = true,
-- },
-- },
-- keymap = {
-- ["<Enter>"] = { "select_and_accept", "fallback" },
-- },
-- },
-- },
-- opts_extend = { "sources.default" },
--},
{
"neovim/nvim-lspconfig",
event = { "BufRead", "BufNewFile" },
config = function()
require("config.lsp")
end,
},
{
"dnlhc/glance.nvim",
config = function()
require("config.glance")
end,
event = "VeryLazy",
},
{
"nvim-treesitter/nvim-treesitter",
lazy = true,
build = ":TSUpdate",
config = function()
require("config.treesitter")
end,
},
{
"nvim-treesitter/nvim-treesitter-textobjects",
event = "VeryLazy",
branch = "master",
config = function()
require("config.treesitter-textobjects")
end,
},
{ "machakann/vim-swap", event = "VeryLazy" },
-- IDE for Lisp
-- 'kovisoft/slimv'
{
"vlime/vlime",
enabled = function()
return utils.executable("sbcl")
end,
config = function(plugin)
vim.opt.rtp:append(plugin.dir .. "/vim")
end,
ft = { "lisp" },
},
-- Super fast buffer jump
{
"smoka7/hop.nvim",
keys = { "f" },
config = function()
require("config.nvim_hop")
end,
},
-- Show match number and index for searching
{
"kevinhwang91/nvim-hlslens",
branch = "main",
keys = { "*", "#", "n", "N" },
config = function()
require("config.hlslens")
end,
},
{
"nvim-telescope/telescope.nvim",
cmd = "Telescope",
dependencies = {
"nvim-telescope/telescope-symbols.nvim",
},
},
{
"ibhagwan/fzf-lua",
config = function()
require("config.fzf-lua")
end,
event = "VeryLazy",
},
{
"MeanderingProgrammer/markdown.nvim",
main = "render-markdown",
opts = {},
ft = { "markdown" },
},
-- A list of colorscheme plugin you may want to try. Find what suits you.
{ "navarasu/onedark.nvim", lazy = true },
{ "sainnhe/edge", lazy = true },
{ "sainnhe/sonokai", lazy = true },
{ "sainnhe/gruvbox-material", lazy = true },
{ "sainnhe/everforest", lazy = true },
{ "EdenEast/nightfox.nvim", lazy = true },
{ "catppuccin/nvim", name = "catppuccin", lazy = true },
{ "olimorris/onedarkpro.nvim", lazy = true },
{ "marko-cerovac/material.nvim", lazy = true },
{
"rockyzhang24/arctic.nvim",
dependencies = { "rktjmp/lush.nvim" },
name = "arctic",
branch = "v2",
},
{ "rebelot/kanagawa.nvim", lazy = true },
{ "miikanissi/modus-themes.nvim", priority = 1000 },
{ "wtfox/jellybeans.nvim", priority = 1000 },
{ "projekt0n/github-nvim-theme", name = "github-theme" },
{ "e-ink-colorscheme/e-ink.nvim", priority = 1000 },
{ "ficcdaf/ashen.nvim", priority = 1000 },
{ "savq/melange-nvim", priority = 1000 },
{ "Skardyy/makurai-nvim", priority = 1000 },
{ "vague2k/vague.nvim", priority = 1000 },
{ "webhooked/kanso.nvim", priority = 1000 },
{ "zootedb0t/citruszest.nvim", priority = 1000 },
-- plugins to provide nerdfont icons
{
"echasnovski/mini.icons",
version = false,
config = function()
-- this is the compatibility fix for plugins that only support nvim-web-devicons
require("mini.icons").mock_nvim_web_devicons()
require("mini.icons").tweak_lsp_kind()
end,
lazy = true,
},
{
"nvim-lualine/lualine.nvim",
event = "BufRead",
cond = firenvim_not_active,
config = function()
require("config.lualine")
end,
},
{
"akinsho/bufferline.nvim",
event = { "BufEnter" },
cond = firenvim_not_active,
config = function()
require("config.bufferline")
end,
},
-- fancy start screen
{
"nvimdev/dashboard-nvim",
cond = firenvim_not_active,
config = function()
require("config.dashboard-nvim")
end,
},
{
"echasnovski/mini.indentscope",
version = false,
config = function()
local mini_indent = require("mini.indentscope")
mini_indent.setup {
draw = {
animation = mini_indent.gen_animation.none(),
},
symbol = "",
}
end,
},
{
"luukvbaal/statuscol.nvim",
opts = {},
config = function()
require("config.nvim-statuscol")
end,
},
{
"kevinhwang91/nvim-ufo",
dependencies = "kevinhwang91/promise-async",
event = "VeryLazy",
opts = {},
init = function()
vim.o.foldcolumn = "1" -- '0' is not bad
vim.o.foldlevel = 99 -- Using ufo provider need a large value, feel free to decrease the value
vim.o.foldlevelstart = 99
vim.o.foldenable = true
end,
config = function()
require("config.nvim_ufo")
end,
},
-- Highlight URLs inside vim
{ "itchyny/vim-highlighturl", event = "BufReadPost" },
-- notification plugin
{
"rcarriga/nvim-notify",
event = "VeryLazy",
config = function()
require("config.nvim-notify")
end,
},
{ "nvim-lua/plenary.nvim", lazy = true },
-- For Windows and Mac, we can open an URL in the browser. For Linux, it may
-- not be possible since we maybe in a server which disables GUI.
{
"chrishrb/gx.nvim",
keys = { { "gx", "<cmd>Browse<cr>", mode = { "n", "x" } } },
cmd = { "Browse" },
init = function()
vim.g.netrw_nogx = 1 -- disable netrw gx
end,
enabled = function()
return vim.g.is_win or vim.g.is_mac
end,
config = true, -- default settings
submodules = false, -- not needed, submodules are required only for tests
},
-- Only install these plugins if ctags are installed on the system
-- show file tags in vim window
{
"liuchengxu/vista.vim",
enabled = function()
return utils.executable("ctags")
end,
cmd = "Vista",
},
-- Snippet engine and snippet template
{
"SirVer/ultisnips",
dependencies = {
"honza/vim-snippets",
},
event = "InsertEnter",
},
-- Automatic insertion and deletion of a pair of characters
{
"windwp/nvim-autopairs",
event = "InsertEnter",
config = true,
},
-- Comment plugin
{
"tpope/vim-commentary",
keys = {
{ "gc", mode = "n" },
{ "gc", mode = "v" },
},
},
-- Multiple cursor plugin like Sublime Text?
-- 'mg979/vim-visual-multi'
-- Show undo history visually
{ "simnalamburt/vim-mundo", cmd = { "MundoToggle", "MundoShow" } },
-- Manage your yank history
{
"gbprod/yanky.nvim",
config = function()
require("config.yanky")
end,
cmd = "YankyRingHistory",
},
-- Handy unix command inside Vim (Rename, Move etc.)
{ "tpope/vim-eunuch", cmd = { "Rename", "Delete" } },
-- Repeat vim motions
{ "tpope/vim-repeat", event = "VeryLazy" },
{ "nvim-zh/better-escape.vim", event = { "InsertEnter" } },
{
"lyokha/vim-xkbswitch",
enabled = function()
return vim.g.is_mac and utils.executable("xkbswitch")
end,
event = { "InsertEnter" },
},
{
"Neur1n/neuims",
enabled = function()
return vim.g.is_win
end,
event = { "InsertEnter" },
},
-- Git command inside vim
{
"tpope/vim-fugitive",
event = "User InGitRepo",
config = function()
require("config.fugitive")
end,
},
{
"NeogitOrg/neogit",
dependencies = {
"nvim-lua/plenary.nvim", -- required
"sindrets/diffview.nvim", -- optional - Diff integration
-- Only one of these is needed.
"ibhagwan/fzf-lua", -- optional
},
event = "User InGitRepo",
},
-- Better git log display
{ "rbong/vim-flog", cmd = { "Flog" } },
{
"akinsho/git-conflict.nvim",
version = "*",
event = "VeryLazy",
config = function()
require("config.git-conflict")
end,
},
{
"ruifm/gitlinker.nvim",
event = "User InGitRepo",
config = function()
require("config.git-linker")
end,
},
-- Show git change (change, delete, add) signs in vim sign column
{
"lewis6991/gitsigns.nvim",
config = function()
require("config.gitsigns")
end,
event = "BufRead",
},
{
"sindrets/diffview.nvim",
cmd = { "DiffviewOpen" },
},
{
"kevinhwang91/nvim-bqf",
ft = "qf",
config = function()
require("config.bqf")
end,
},
-- Faster footnote generation
{ "vim-pandoc/vim-markdownfootnotes", ft = { "markdown" } },
-- Vim tabular plugin for manipulate tabular, required by markdown plugins
{ "godlygeek/tabular", ft = { "markdown" } },
-- Markdown previewing (only for Mac and Windows)
{
"iamcco/markdown-preview.nvim",
enabled = function()
return vim.g.is_win or vim.g.is_mac
end,
build = "cd app && npm install && git restore .",
ft = { "markdown" },
},
{
"rhysd/vim-grammarous",
enabled = function()
return vim.g.is_mac
end,
ft = { "markdown" },
},
{ "chrisbra/unicode.vim", keys = { "ga" }, cmd = { "UnicodeSearch" } },
-- Additional powerful text object for vim, this plugin should be studied
-- carefully to use its full power
{ "wellle/targets.vim", event = "VeryLazy" },
-- Plugin to manipulate character pairs quickly
{ "machakann/vim-sandwich", event = "VeryLazy" },
-- Only use these plugin on Windows and Mac and when LaTeX is installed
{
"lervag/vimtex",
enabled = function()
return utils.executable("latex")
end,
ft = { "tex" },
},
-- Since tmux is only available on Linux and Mac, we only enable these plugins
-- for Linux and Mac
-- .tmux.conf syntax highlighting and setting check
{
"tmux-plugins/vim-tmux",
enabled = function()
return utils.executable("tmux")
end,
ft = { "tmux" },
},
-- Modern matchit implementation
{ "andymass/vim-matchup", event = "BufRead" },
{ "tpope/vim-scriptease", cmd = { "Scriptnames", "Messages", "Verbose" } },
-- Asynchronous command execution
{ "skywind3000/asyncrun.vim", lazy = true, cmd = { "AsyncRun" } },
{ "cespare/vim-toml", ft = { "toml" }, branch = "main" },
-- Edit text area in browser using nvim
{
"glacambre/firenvim",
enabled = function()
return vim.g.is_win or vim.g.is_mac
end,
-- it seems that we can only call the firenvim function directly.
-- Using vim.fn or vim.cmd to call this function will fail.
build = function()
local firenvim_path = plugin_dir .. "/firenvim"
vim.opt.runtimepath:append(firenvim_path)
vim.cmd("runtime! firenvim.vim")
-- macOS will reset the PATH when firenvim starts a nvim process, causing the PATH variable to change unexpectedly.
-- Here we are trying to get the correct PATH and use it for firenvim.
-- See also https://github.com/glacambre/firenvim/blob/master/TROUBLESHOOTING.md#make-sure-firenvims-path-is-the-same-as-neovims
local path_env = vim.env.PATH
local prologue = string.format('export PATH="%s"', path_env)
-- local prologue = "echo"
local cmd_str = string.format(":call firenvim#install(0, '%s')", prologue)
vim.cmd(cmd_str)
end,
},
-- Debugger plugin
{
"sakhnik/nvim-gdb",
enabled = function()
return vim.g.is_win or vim.g.is_linux
end,
build = { "bash install.sh" },
lazy = true,
},
-- Session management plugin
{ "tpope/vim-obsession", cmd = "Obsession" },
{
"ojroques/vim-oscyank",
enabled = function()
return vim.g.is_linux
end,
cmd = { "OSCYank", "OSCYankReg" },
},
-- showing keybindings
{
"folke/which-key.nvim",
event = "VeryLazy",
config = function()
require("config.which-key")
end,
},
{
"folke/snacks.nvim",
priority = 1000,
lazy = false,
opts = {
-- more beautiful vim.ui.input
input = {
enabled = true,
win = {
relative = "cursor",
backdrop = true,
},
},
-- more beautiful vim.ui.select
picker = { enabled = true },
},
},
-- show and trim trailing whitespaces
{ "jdhao/whitespace.nvim", event = "VeryLazy" },
-- file explorer
{
"nvim-tree/nvim-tree.lua",
keys = { "<space>s" },
config = function()
require("config.nvim-tree")
end,
},
{
"j-hui/fidget.nvim",
event = "BufRead",
config = function()
require("config.fidget-nvim")
end,
},
{
"folke/lazydev.nvim",
ft = "lua", -- only load on lua files
opts = {
library = {
-- See the configuration section for more details
-- Load luvit types when the `vim.uv` word is found
{ path = "${3rd}/luv/library", words = { "vim%.uv" } },
},
},
},
{
"CopilotC-Nvim/CopilotChat.nvim",
dependencies = {
{ "zbirenbaum/copilot.lua" }, -- or github/copilot.vim
},
opts = {
debug = true, -- Enable debugging
-- See Configuration section for rest
},
cmd = { "CopilotChat" },
},
{
"zbirenbaum/copilot.lua",
cmd = "Copilot",
config = function()
require("copilot").setup {}
end,
},
{
"smjonas/live-command.nvim",
-- live-command supports semantic versioning via Git tags
-- tag = "2.*",
cmd = "Preview",
config = function()
require("config.live-command")
end,
},
{
-- show hint for code actions, the user can also implement code actions themselves,
-- see discussion here: https://github.com/neovim/neovim/issues/14869
"kosayoda/nvim-lightbulb",
config = function()
require("config.lightbulb")
end,
event = "LspAttach",
},
{
"Bekaboo/dropbar.nvim",
event = "VeryLazy",
},
{
"catgoose/nvim-colorizer.lua",
event = "BufReadPre",
opts = { -- set to setup table
},
},
}
---@diagnostic disable-next-line: missing-fields
require("lazy").setup {
spec = plugin_specs,
ui = {
border = "rounded",
title = "Plugin Manager",
title_pos = "center",
},
rocks = {
enabled = false,
hererocks = false,
},
}

View File

@@ -1,396 +0,0 @@
local api = vim.api
local fn = vim.fn
local utils = require("utils")
-- The root dir to install all plugins. Plugins are under opt/ or start/ sub-directory.
vim.g.plugin_home = fn.stdpath("data") .. "/site/pack/packer"
--- Install packer if it has not been installed.
--- Return:
--- true: if this is a fresh install of packer
--- false: if packer has been installed
local function packer_ensure_install()
-- Where to install packer.nvim -- the package manager (we make it opt)
local packer_dir = vim.g.plugin_home .. "/opt/packer.nvim"
if fn.glob(packer_dir) ~= "" then
return false
end
-- Auto-install packer in case it hasn't been installed.
vim.api.nvim_echo({ { "Installing packer.nvim", "Type" } }, true, {})
local packer_repo = "https://github.com/wbthomason/packer.nvim"
local install_cmd = string.format("!git clone --depth=1 %s %s", packer_repo, packer_dir)
vim.cmd(install_cmd)
return true
end
local fresh_install = packer_ensure_install()
-- Load packer.nvim
vim.cmd("packadd packer.nvim")
local packer = require("packer")
local packer_util = require("packer.util")
-- check if firenvim is active
local firenvim_not_active = function()
return not vim.g.started_by_firenvim
end
packer.startup {
function(use)
use { "wbthomason/packer.nvim", opt = true }
use { "onsails/lspkind-nvim", event = "VimEnter" }
-- auto-completion engine
use { "hrsh7th/nvim-cmp", after = "lspkind-nvim", config = [[require('config.nvim-cmp')]] }
-- nvim-cmp completion sources
use { "hrsh7th/cmp-nvim-lsp", after = "nvim-cmp" }
use { "hrsh7th/cmp-path", after = "nvim-cmp" }
use { "hrsh7th/cmp-buffer", after = "nvim-cmp" }
use { "hrsh7th/cmp-omni", after = "nvim-cmp" }
use { "quangnguyen30192/cmp-nvim-ultisnips", after = { "nvim-cmp", "ultisnips" } }
if vim.g.is_mac then
use { "hrsh7th/cmp-emoji", after = "nvim-cmp" }
end
-- nvim-lsp configuration (it relies on cmp-nvim-lsp, so it should be loaded after cmp-nvim-lsp).
use { "neovim/nvim-lspconfig", after = "cmp-nvim-lsp", config = [[require('config.lsp')]] }
if vim.g.is_mac then
use {
"nvim-treesitter/nvim-treesitter",
event = "BufEnter",
run = ":TSUpdate",
config = [[require('config.treesitter')]],
}
end
-- Python indent (follows the PEP8 style)
use { "Vimjas/vim-python-pep8-indent", ft = { "python" } }
-- Python-related text object
use { "jeetsukumaran/vim-pythonsense", ft = { "python" } }
use { "machakann/vim-swap", event = "VimEnter" }
-- IDE for Lisp
if utils.executable("sbcl") then
-- use 'kovisoft/slimv'
use { "vlime/vlime", rtp = "vim/", ft = { "lisp" } }
end
-- Super fast buffer jump
use {
"phaazon/hop.nvim",
event = "VimEnter",
config = function()
vim.defer_fn(function()
require("config.nvim_hop")
end, 2000)
end,
}
-- Show match number and index for searching
use {
"kevinhwang91/nvim-hlslens",
branch = "main",
keys = { { "n", "*" }, { "n", "#" }, { "n", "n" }, { "n", "N" } },
config = [[require('config.hlslens')]],
}
-- File search, tag search and more
if vim.g.is_win then
use { "Yggdroot/LeaderF", cmd = "Leaderf" }
else
use { "Yggdroot/LeaderF", cmd = "Leaderf", run = ":LeaderfInstallCExtension" }
end
use {
"nvim-telescope/telescope.nvim",
cmd = "Telescope",
requires = { { "nvim-lua/plenary.nvim" } },
}
-- search emoji and other symbols
use { "nvim-telescope/telescope-symbols.nvim", after = "telescope.nvim" }
-- A list of colorscheme plugin you may want to try. Find what suits you.
use { "navarasu/onedark.nvim", opt = true }
use { "sainnhe/edge", opt = true }
use { "sainnhe/sonokai", opt = true }
use { "sainnhe/gruvbox-material", opt = true }
use { "shaunsingh/nord.nvim", opt = true }
use { "sainnhe/everforest", opt = true }
use { "EdenEast/nightfox.nvim", opt = true }
use { "rebelot/kanagawa.nvim", opt = true }
use { "catppuccin/nvim", as = "catppuccin", opt = true }
use({ "rose-pine/neovim", as = 'rose-pine', opt = true })
use { "olimorris/onedarkpro.nvim", opt = true }
use { "tanvirtin/monokai.nvim", opt = true }
use { "marko-cerovac/material.nvim", opt = true }
use { "nvim-tree/nvim-web-devicons", event = "VimEnter" }
use {
"nvim-lualine/lualine.nvim",
event = "VimEnter",
cond = firenvim_not_active,
config = [[require('config.statusline')]],
}
use { "akinsho/bufferline.nvim", event = "VimEnter",
cond = firenvim_not_active,
config = [[require('config.bufferline')]] }
-- fancy start screen
use { "nvimdev/dashboard-nvim", event = "VimEnter",
cond = firenvim_not_active,
config = [[require('config.dashboard-nvim')]]
}
use {
"lukas-reineke/indent-blankline.nvim",
event = "VimEnter",
config = [[require('config.indent-blankline')]],
}
-- Highlight URLs inside vim
use { "itchyny/vim-highlighturl", event = "VimEnter" }
-- notification plugin
use {
"rcarriga/nvim-notify",
event = "BufEnter",
config = function()
vim.defer_fn(function()
require("config.nvim-notify")
end, 2000)
end,
}
-- For Windows and Mac, we can open an URL in the browser. For Linux, it may
-- not be possible since we maybe in a server which disables GUI.
if vim.g.is_win or vim.g.is_mac then
-- open URL in browser
use { "tyru/open-browser.vim", event = "VimEnter" }
end
-- Only install these plugins if ctags are installed on the system
if utils.executable("ctags") then
-- show file tags in vim window
use { "liuchengxu/vista.vim", cmd = "Vista" }
end
-- Snippet engine and snippet template
use { "SirVer/ultisnips", event = "InsertEnter" }
use { "honza/vim-snippets", after = "ultisnips" }
-- Automatic insertion and deletion of a pair of characters
use { "Raimondi/delimitMate", event = "InsertEnter" }
-- Comment plugin
use { "tpope/vim-commentary", event = "VimEnter" }
-- Multiple cursor plugin like Sublime Text?
-- use 'mg979/vim-visual-multi'
-- Autosave files on certain events
use { "907th/vim-auto-save", event = "InsertEnter" }
-- Show undo history visually
use { "simnalamburt/vim-mundo", cmd = { "MundoToggle", "MundoShow" } }
-- better UI for some nvim actions
use {'stevearc/dressing.nvim'}
-- Manage your yank history
use({
"gbprod/yanky.nvim",
config = [[require('config.yanky')]]
})
-- Handy unix command inside Vim (Rename, Move etc.)
use { "tpope/vim-eunuch", cmd = { "Rename", "Delete" } }
-- Repeat vim motions
use { "tpope/vim-repeat", event = "VimEnter" }
use { "nvim-zh/better-escape.vim", event = { "InsertEnter" } }
if vim.g.is_mac then
use { "lyokha/vim-xkbswitch", event = { "InsertEnter" } }
elseif vim.g.is_win then
use { "Neur1n/neuims", event = { "InsertEnter" } }
end
-- Auto format tools
use { "sbdchd/neoformat", cmd = { "Neoformat" } }
-- Git command inside vim
use { "tpope/vim-fugitive", event = "User InGitRepo", config = [[require('config.fugitive')]] }
-- Better git log display
use { "rbong/vim-flog", requires = "tpope/vim-fugitive", cmd = { "Flog" } }
use { "christoomey/vim-conflicted", requires = "tpope/vim-fugitive", cmd = { "Conflicted" } }
use {
"ruifm/gitlinker.nvim",
requires = "nvim-lua/plenary.nvim",
event = "User InGitRepo",
config = [[require('config.git-linker')]],
}
-- Show git change (change, delete, add) signs in vim sign column
use { "lewis6991/gitsigns.nvim", config = [[require('config.gitsigns')]] }
-- Better git commit experience
use { "rhysd/committia.vim", opt = true, setup = [[vim.cmd('packadd committia.vim')]] }
use { "kevinhwang91/nvim-bqf", ft = "qf", config = [[require('config.bqf')]] }
-- Another markdown plugin
use { "preservim/vim-markdown", ft = { "markdown" } }
-- Faster footnote generation
use { "vim-pandoc/vim-markdownfootnotes", ft = { "markdown" } }
-- Vim tabular plugin for manipulate tabular, required by markdown plugins
use { "godlygeek/tabular", cmd = { "Tabularize" } }
-- Markdown previewing (only for Mac and Windows)
if vim.g.is_win or vim.g.is_mac then
use {
"iamcco/markdown-preview.nvim",
run = "cd app && npm install",
ft = { "markdown" },
}
end
use { "folke/zen-mode.nvim", cmd = "ZenMode", config = [[require('config.zen-mode')]] }
if vim.g.is_mac then
use { "rhysd/vim-grammarous", ft = { "markdown" } }
end
use { "chrisbra/unicode.vim", event = "VimEnter" }
-- Additional powerful text object for vim, this plugin should be studied
-- carefully to use its full power
use { "wellle/targets.vim", event = "VimEnter" }
-- Plugin to manipulate character pairs quickly
use { "machakann/vim-sandwich", event = "VimEnter" }
-- Add indent object for vim (useful for languages like Python)
use { "michaeljsmith/vim-indent-object", event = "VimEnter" }
-- Only use these plugin on Windows and Mac and when LaTeX is installed
if utils.executable("latex") then
use { "lervag/vimtex", ft = { "tex" } }
end
-- Since tmux is only available on Linux and Mac, we only enable these plugins
-- for Linux and Mac
if utils.executable("tmux") then
-- .tmux.conf syntax highlighting and setting check
use { "tmux-plugins/vim-tmux", ft = { "tmux" } }
end
-- Modern matchit implementation
use { "andymass/vim-matchup", event = "VimEnter" }
use { "tpope/vim-scriptease", cmd = { "Scriptnames", "Message", "Verbose" } }
-- Asynchronous command execution
use { "skywind3000/asyncrun.vim", opt = true, cmd = { "AsyncRun" } }
use { "cespare/vim-toml", ft = { "toml" }, branch = "main" }
-- Edit text area in browser using nvim
if vim.g.is_win or vim.g.is_mac then
use {
"glacambre/firenvim",
run = function()
fn["firenvim#install"](0)
end,
opt = true,
setup = [[vim.cmd('packadd firenvim')]],
}
end
-- Debugger plugin
if vim.g.is_win or vim.g.is_linux then
use { "sakhnik/nvim-gdb", run = { "bash install.sh" }, opt = true, setup = [[vim.cmd('packadd nvim-gdb')]] }
end
-- Session management plugin
use { "tpope/vim-obsession", cmd = "Obsession" }
if vim.g.is_linux then
use { "ojroques/vim-oscyank", cmd = { "OSCYank", "OSCYankReg" } }
end
-- The missing auto-completion for cmdline!
use { "gelguy/wilder.nvim", opt = true, setup = [[vim.cmd('packadd wilder.nvim')]] }
-- showing keybindings
use {
"folke/which-key.nvim",
event = "VimEnter",
config = function()
vim.defer_fn(function()
require("config.which-key")
end, 2000)
end,
}
-- show and trim trailing whitespaces
use { "jdhao/whitespace.nvim", event = "VimEnter" }
-- file explorer
use {
"nvim-tree/nvim-tree.lua",
requires = { "nvim-tree/nvim-web-devicons" },
config = [[require('config.nvim-tree')]],
}
use { "ii14/emmylua-nvim", ft = "lua" }
use { "j-hui/fidget.nvim", after = "nvim-lspconfig", tag = "legacy", config = [[require('config.fidget-nvim')]] }
end,
config = {
max_jobs = 16,
compile_path = packer_util.join_paths(fn.stdpath("data"), "site", "lua", "packer_compiled.lua"),
},
}
-- For fresh install, we need to install plugins. Otherwise, we just need to require `packer_compiled.lua`.
if fresh_install then
-- We run packer.sync() here, because only after packer.startup, can we know which plugins to install.
-- So plugin installation should be done after the startup process.
packer.sync()
else
local status, _ = pcall(require, "packer_compiled")
if not status then
local msg = "File packer_compiled.lua not found: run PackerSync to fix!"
vim.notify(msg, vim.log.levels.ERROR, { title = "nvim-config" })
end
end
-- Auto-generate packer_compiled.lua file
api.nvim_create_autocmd({ "BufWritePost" }, {
pattern = "*/nvim/lua/plugins.lua",
group = api.nvim_create_augroup("packer_auto_compile", { clear = true }),
callback = function(ctx)
local cmd = "source " .. ctx.file
vim.cmd(cmd)
vim.cmd("PackerCompile")
vim.notify("PackerCompile done!", vim.log.levels.INFO, { title = "Nvim-config" })
end,
})

View File

@@ -1,19 +1,18 @@
local fn = vim.fn local fn = vim.fn
local version = vim.version
local M = {} local M = {}
--- Check if an executable exists
--- @param name string An executable name/path
--- @return boolean
function M.executable(name) function M.executable(name)
if fn.executable(name) > 0 then return fn.executable(name) > 0
return true
end
return false
end end
--- check whether a feature exists in Nvim --- check whether a feature exists in Nvim
--- @feat: string --- @param feat string the feature name, like `nvim-0.7` or `unix`.
--- the feature name, like `nvim-0.7` or `unix`. --- @return boolean
--- return: bool
M.has = function(feat) M.has = function(feat)
if fn.has(feat) == 1 then if fn.has(feat) == 1 then
return true return true
@@ -33,8 +32,9 @@ end
--- Generate random integers in the range [Low, High], inclusive, --- Generate random integers in the range [Low, High], inclusive,
--- adapted from https://stackoverflow.com/a/12739441/6064933 --- adapted from https://stackoverflow.com/a/12739441/6064933
--- @low: the lower value for this range --- @param low integer the lower value for this range
--- @high: the upper value for this range --- @param high integer the upper value for this range
--- @return integer
function M.rand_int(low, high) function M.rand_int(low, high)
-- Use lua to generate random int, see also: https://stackoverflow.com/a/20157671/6064933 -- Use lua to generate random int, see also: https://stackoverflow.com/a/20157671/6064933
math.randomseed(os.time()) math.randomseed(os.time())
@@ -43,17 +43,53 @@ function M.rand_int(low, high)
end end
--- Select a random element from a sequence/list. --- Select a random element from a sequence/list.
--- @seq: the sequence to choose an element --- @param seq any[] the sequence to choose an element
function M.rand_element(seq) function M.rand_element(seq)
local idx = M.rand_int(1, #seq) local idx = M.rand_int(1, #seq)
return seq[idx] return seq[idx]
end end
function M.add_pack(name) --- check if the current nvim version is compatible with the allowed version
local status, error = pcall(vim.cmd, "packadd " .. name) --- @param expected_version string
--- @return boolean
function M.is_compatible_version(expected_version)
-- check if we have the latest stable version of nvim
local expect_ver = version.parse(expected_version)
local actual_ver = vim.version()
return status if expect_ver == nil then
local msg = string.format("Unsupported version string: %s", expected_version)
vim.api.nvim_echo({ { msg } }, true, { err = true })
return false
end
local result = version.cmp(expect_ver, actual_ver)
if result ~= 0 then
local _ver = string.format("%s.%s.%s", actual_ver.major, actual_ver.minor, actual_ver.patch)
local msg = string.format(
"Expect nvim version %s, but your current nvim version is %s. Use at your own risk!",
expected_version,
_ver
)
vim.api.nvim_echo({ { msg } }, true, { err = true })
end
return true
end
--- check if we are inside a git repo
--- @return boolean
function M.inside_git_repo()
local result = vim.system({ "git", "rev-parse", "--is-inside-work-tree" }, { text = true }):wait()
if result.code ~= 0 then
return false
end
-- Manually trigger a special user autocmd InGitRepo (used lazyloading.
vim.cmd([[doautocmd User InGitRepo]])
return true
end end
return M return M

View File

@@ -54,6 +54,10 @@ snippet link "Markdown links"
[$1]($2)$0 [$1]($2)$0
endsnippet endsnippet
snippet rlink "Markdown ref link"
[${1:link_text}][${2:label}]
endsnippet
post_jump "gen_header(snip)" post_jump "gen_header(snip)"
snippet "h([1-6])" "Markdown header" br snippet "h([1-6])" "Markdown header" br
`!p snip.rv = match.group(1)` `!p snip.rv = match.group(1)`

59
plugin/command.lua Normal file
View File

@@ -0,0 +1,59 @@
-- Copy file path to clipboard
vim.api.nvim_create_user_command("CopyPath", function(context)
local full_path = vim.fn.glob("%:p")
local file_path = nil
if context["args"] == "nameonly" then
file_path = vim.fn.fnamemodify(full_path, ":t")
end
-- get the file path relative to project root
if context["args"] == "relative" then
local project_marker = { ".git", "pyproject.toml" }
local project_root = vim.fs.root(0, project_marker)
if project_root == nil then
vim.print("can not find project root")
return
end
file_path = vim.fn.substitute(full_path, project_root, "<project-root>", "g")
end
if context["args"] == "absolute" then
file_path = full_path
end
vim.fn.setreg("+", file_path)
vim.print("Filepath copied to clipboard!")
end, {
bang = false,
nargs = 1,
force = true,
desc = "Copy current file path to clipboard",
complete = function()
return { "nameonly", "relative", "absolute" }
end,
})
-- JSON format part of or the whole file
vim.api.nvim_create_user_command("JSONFormat", function(context)
local range = context["range"]
local line1 = context["line1"]
local line2 = context["line2"]
if range == 0 then
-- the command is invoked without range, then we assume whole buffer
local cmd_str = string.format("%s,%s!python -m json.tool", line1, line2)
vim.fn.execute(cmd_str)
elseif range == 2 then
-- the command is invoked with some range
local cmd_str = string.format("%s,%s!python -m json.tool", line1, line2)
vim.fn.execute(cmd_str)
else
local msg = string.format("unsupported range: %s", range)
vim.api.nvim_echo({ { msg } }, true, { err = true })
end
end, {
desc = "Format JSON string",
range = "%",
})

View File

@@ -45,6 +45,3 @@ function! s:md_to_pdf() abort
echoerr "Error running command" echoerr "Error running command"
endif endif
endfunction endfunction
" json format
command! -range JSONFormat <line1>,<line2>!python -m json.tool

View File

@@ -458,3 +458,21 @@ pyright
stubgen stubgen
pylance pylance
variadic variadic
Vimium
Databricks
Jira
databricks
FastAPI
pylintrc
PYTHONPATH
Uvicorn
qpdf
Elasticsearch
kibana
submodule
unix
GCP
Kubernetes
pubsub
Luarocks
luarocks

View File

@@ -1,11 +1,14 @@
scriptencoding utf-8 scriptencoding utf-8
" change fillchars for folding, vertical split, end of buffer, and message separator " change fillchars for folding, vertical split, end of buffer, and message separator
set fillchars=fold:\ ,vert:\│,eob:\ ,msgsep:‾ set fillchars=fold:\ ,foldsep:\ ,foldopen:,foldclose:,vert:\│,eob:\ ,msgsep:‾,diff:
" Split window below/right when creating horizontal/vertical windows " Split window below/right when creating horizontal/vertical windows
set splitbelow splitright set splitbelow splitright
" avoid the flickering when splitting window horizontal
set splitkeep=screen
" Time in milliseconds to wait for a mapped sequence to complete, " Time in milliseconds to wait for a mapped sequence to complete,
" see https://unix.stackexchange.com/q/36882/221410 for more info " see https://unix.stackexchange.com/q/36882/221410 for more info
set timeoutlen=500 set timeoutlen=500
@@ -69,9 +72,9 @@ set wildmode=list:longest
set scrolloff=3 set scrolloff=3
" Use mouse to select and resize windows, etc. " Use mouse to select and resize windows, etc.
set mouse=nic " Enable mouse in several mode set mouse=n
set mousemodel=popup " Set the behaviour of mouse set mousemodel=popup " Set the behaviour of mouse
set mousescroll=ver:1,hor:6 set mousescroll=ver:1,hor:0
" Disable showing current mode on command line since statusline plugins can show it. " Disable showing current mode on command line since statusline plugins can show it.
set noshowmode set noshowmode
@@ -112,15 +115,18 @@ set shortmess+=S
" Disable showing intro message (:intro) " Disable showing intro message (:intro)
set shortmess+=I set shortmess+=I
set messagesopt=hit-enter,history:500
" Completion behaviour " Completion behaviour
" set completeopt+=noinsert " Auto select the first completion entry " set completeopt+=noinsert " Auto select the first completion entry
set completeopt+=menuone " Show menu even if there is only one item set completeopt+=menuone " Show menu even if there is only one item
set completeopt-=preview " Disable the preview window set completeopt-=preview " Disable the preview window
set pumheight=10 " Maximum number of items to show in popup menu set pumheight=10 " Maximum number of items to show in popup menu
set pumblend=10 " pseudo transparency for completion menu set pumblend=5 " pseudo transparency for completion menu
set winblend=0 " pseudo transparency for floating window set winblend=0 " pseudo transparency for floating window
set winborder=none
" Insert mode key word completion setting " Insert mode key word completion setting
set complete+=kspell complete-=w complete-=b complete-=u complete-=t set complete+=kspell complete-=w complete-=b complete-=u complete-=t
@@ -176,3 +182,5 @@ set diffopt+=linematch:60
set nowrap " do no wrap set nowrap " do no wrap
set noruler set noruler
set showcmdloc=statusline

View File

@@ -1,16 +1,16 @@
scriptencoding utf-8 scriptencoding utf-8
" Plugin specification and lua stuff " Plugin specification and lua stuff
lua require('plugins') lua require('plugin_specs')
" Use short names for common plugin manager commands to simplify typing. " Use short names for common plugin manager commands to simplify typing.
" To use these shortcuts: first activate command line with `:`, then input the " To use these shortcuts: first activate command line with `:`, then input the
" short alias, e.g., `pi`, then press <space>, the alias will be expanded to " short alias, e.g., `pi`, then press <space>, the alias will be expanded to
" the full command automatically. " the full command automatically.
call utils#Cabbrev('pi', 'PackerInstall') call utils#Cabbrev('pi', 'Lazy install')
call utils#Cabbrev('pud', 'PackerUpdate') call utils#Cabbrev('pud', 'Lazy update')
call utils#Cabbrev('pc', 'PackerClean') call utils#Cabbrev('pc', 'Lazy clean')
call utils#Cabbrev('ps', 'PackerSync') call utils#Cabbrev('ps', 'Lazy sync')
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" configurations for vim script plugin " " configurations for vim script plugin "
@@ -34,91 +34,6 @@ let g:UltiSnipsSnippetDirectories=['UltiSnips', 'my_snippets']
"""""""""""""""""""""""""" vlime settings """""""""""""""""""""""""""""""" """""""""""""""""""""""""" vlime settings """"""""""""""""""""""""""""""""
command! -nargs=0 StartVlime call jobstart(printf("sbcl --load %s/vlime/lisp/start-vlime.lisp", g:package_home)) command! -nargs=0 StartVlime call jobstart(printf("sbcl --load %s/vlime/lisp/start-vlime.lisp", g:package_home))
"""""""""""""""""""""""""""""LeaderF settings"""""""""""""""""""""
" Do not use cache file
let g:Lf_UseCache = 0
" Refresh each time we call leaderf
let g:Lf_UseMemoryCache = 0
" Ignore certain files and directories when searching files
let g:Lf_WildIgnore = {
\ 'dir': ['.git', '__pycache__', '.DS_Store'],
\ 'file': ['*.exe', '*.dll', '*.so', '*.o', '*.pyc', '*.jpg', '*.png',
\ '*.gif', '*.svg', '*.ico', '*.db', '*.tgz', '*.tar.gz', '*.gz',
\ '*.zip', '*.bin', '*.pptx', '*.xlsx', '*.docx', '*.pdf', '*.tmp',
\ '*.wmv', '*.mkv', '*.mp4', '*.rmvb', '*.ttf', '*.ttc', '*.otf',
\ '*.mp3', '*.aac']
\}
" Do not show fancy icons for Linux server.
if g:is_linux
let g:Lf_ShowDevIcons = 0
endif
" Only fuzzy-search files names
let g:Lf_DefaultMode = 'FullPath'
" Popup window settings
let w = float2nr(&columns * 0.8)
if w > 140
let g:Lf_PopupWidth = 140
else
let g:Lf_PopupWidth = w
endif
let g:Lf_PopupPosition = [0, float2nr((&columns - g:Lf_PopupWidth)/2)]
" Do not use version control tool to list files under a directory since
" submodules are not searched by default.
let g:Lf_UseVersionControlTool = 0
" Use rg as the default search tool
let g:Lf_DefaultExternalTool = "rg"
" show dot files
let g:Lf_ShowHidden = 1
" Disable default mapping
let g:Lf_ShortcutF = ''
let g:Lf_ShortcutB = ''
" set up working directory for git repository
let g:Lf_WorkingDirectoryMode = 'a'
" Search files in popup window
nnoremap <silent> <leader>ff :<C-U>Leaderf file --popup<CR>
" Grep project files in popup window
nnoremap <silent> <leader>fg :<C-U>Leaderf rg --no-messages --popup<CR>
" Search vim help files
nnoremap <silent> <leader>fh :<C-U>Leaderf help --popup<CR>
" Search tags in current buffer
nnoremap <silent> <leader>ft :<C-U>Leaderf bufTag --popup<CR>
" Switch buffers
nnoremap <silent> <leader>fb :<C-U>Leaderf buffer --popup<CR>
" Search recent files
nnoremap <silent> <leader>fr :<C-U>Leaderf mru --popup --absolute-path<CR>
let g:Lf_PopupColorscheme = 'gruvbox_material'
" Change keybinding in LeaderF prompt mode, use ctrl-n and ctrl-p to navigate
" items.
let g:Lf_CommandMap = {'<C-J>': ['<C-N>'], '<C-K>': ['<C-P>']}
""""""""""""""""""""""""""""open-browser.vim settings"""""""""""""""""""
if g:is_win || g:is_mac
" Disable netrw's gx mapping.
let g:netrw_nogx = 1
" Use another mapping for the open URL method
nmap ob <Plug>(openbrowser-smart-search)
xmap ob <Plug>(openbrowser-smart-search)
endif
""""""""""""""""""""""""""" vista settings """""""""""""""""""""""""""""""""" """"""""""""""""""""""""""" vista settings """"""""""""""""""""""""""""""""""
let g:vista#renderer#icons = { let g:vista#renderer#icons = {
\ 'member': '', \ 'member': '',
@@ -143,39 +58,6 @@ let g:better_escape_interval = 200
""""""""""""""""""""""""""""vim-xkbswitch settings""""""""""""""""""""""""" """"""""""""""""""""""""""""vim-xkbswitch settings"""""""""""""""""""""""""
let g:XkbSwitchEnabled = 1 let g:XkbSwitchEnabled = 1
"""""""""""""""""""""""""""""" neoformat settings """""""""""""""""""""""
let g:neoformat_enabled_python = ['black', 'yapf']
let g:neoformat_cpp_clangformat = {
\ 'exe': 'clang-format',
\ 'args': ['--style="{IndentWidth: 4}"']
\ }
let g:neoformat_c_clangformat = {
\ 'exe': 'clang-format',
\ 'args': ['--style="{IndentWidth: 4}"']
\ }
let g:neoformat_enabled_cpp = ['clangformat']
let g:neoformat_enabled_c = ['clangformat']
"""""""""""""""""""""""""vim-markdown settings"""""""""""""""""""
" Disable header folding
let g:vim_markdown_folding_disabled = 1
" Whether to use conceal feature in markdown
let g:vim_markdown_conceal = 1
" Disable math tex conceal and syntax highlight
let g:tex_conceal = ''
let g:vim_markdown_math = 0
" Support front matter of various format
let g:vim_markdown_frontmatter = 1 " for YAML format
let g:vim_markdown_toml_frontmatter = 1 " for TOML format
let g:vim_markdown_json_frontmatter = 1 " for JSON format
" Let the TOC window autofit so that it doesn't take too much space
let g:vim_markdown_toc_autofit = 1
"""""""""""""""""""""""""markdown-preview settings""""""""""""""""""" """""""""""""""""""""""""markdown-preview settings"""""""""""""""""""
" Only setting this for suitable platforms " Only setting this for suitable platforms
if g:is_win || g:is_mac if g:is_win || g:is_mac
@@ -344,52 +226,3 @@ endif
""""""""""""""""""""""""""""""nvim-gdb settings"""""""""""""""""""""""""""""" """"""""""""""""""""""""""""""nvim-gdb settings""""""""""""""""""""""""""""""
nnoremap <leader>dp :<C-U>GdbStartPDB python -m pdb %<CR> nnoremap <leader>dp :<C-U>GdbStartPDB python -m pdb %<CR>
""""""""""""""""""""""""""""""wilder.nvim settings""""""""""""""""""""""""""""""
call timer_start(250, { -> s:wilder_init() })
function! s:wilder_init() abort
try
call wilder#setup({
\ 'modes': [':', '/', '?'],
\ 'next_key': '<Tab>',
\ 'previous_key': '<S-Tab>',
\ 'accept_key': '<C-y>',
\ 'reject_key': '<C-e>'
\ })
call wilder#set_option('pipeline', [
\ wilder#branch(
\ wilder#cmdline_pipeline({
\ 'language': 'python',
\ 'fuzzy': 1,
\ 'sorter': wilder#python_difflib_sorter(),
\ 'debounce': 30,
\ }),
\ wilder#python_search_pipeline({
\ 'pattern': wilder#python_fuzzy_pattern(),
\ 'sorter': wilder#python_difflib_sorter(),
\ 'engine': 're',
\ 'debounce': 30,
\ }),
\ ),
\ ])
let l:hl = wilder#make_hl('WilderAccent', 'Pmenu', [{}, {}, {'foreground': '#f4468f'}])
call wilder#set_option('renderer', wilder#popupmenu_renderer({
\ 'highlighter': wilder#basic_highlighter(),
\ 'max_height': 15,
\ 'highlights': {
\ 'accent': l:hl,
\ },
\ 'left': [' ', wilder#popupmenu_devicons(),],
\ 'right': [' ', wilder#popupmenu_scrollbar(),],
\ 'apply_incsearch_fix': 0,
\ }))
catch /^Vim\%((\a\+)\)\=:E117/
echohl Error |echomsg "Wilder.nvim missing: run :PackerSync to fix."|echohl None
endtry
endfunction
""""""""""""""""""""""""""""""vim-auto-save settings""""""""""""""""""""""""""""""
let g:auto_save = 1 " enable AutoSave on Vim startup