From 80cf245e7952a633e06849406c742831af0ddaac Mon Sep 17 00:00:00 2001 From: t0xa Date: Mon, 28 Jul 2025 18:28:03 +0300 Subject: [PATCH] Some merge magic --- README.md | 71 ++++++++ ftplugin/go.lua | 0 init.lua | 40 +++++ lua/custom/README.md | 59 +++++++ lua/custom/colorschemes.lua | 9 ++ lua/custom/completion.lua | 65 ++++++++ lua/custom/lsp.lua | 222 ++++++++++++++++++++++++++ lua/custom/lualine.lua | 14 ++ lua/custom/luasnip.lua | 34 ++++ lua/custom/neogen.lua | 7 + lua/custom/obsidian.lua | 72 +++++++++ lua/custom/oil.lua | 27 ++++ lua/custom/plugins/colorschemes.lua | 20 +++ lua/custom/plugins/completion.lua | 20 +++ lua/custom/plugins/dressing.lua | 4 + lua/custom/plugins/lsp.lua | 35 ++++ lua/custom/plugins/lualine.lua | 25 +++ lua/custom/plugins/luasnip.lua | 9 ++ lua/custom/plugins/neogen.lua | 12 ++ lua/custom/plugins/obsidian.lua | 16 ++ lua/custom/plugins/oil.lua | 8 + lua/custom/plugins/telescope.lua | 12 ++ lua/custom/plugins/tmux_navigator.lua | 18 +++ lua/custom/plugins/todo.lua | 8 + lua/custom/plugins/treesitter.lua | 14 ++ lua/custom/plugins/trouble.lua | 10 ++ lua/custom/plugins/which_key.lua | 20 +++ lua/custom/snippets/README.md | 20 +++ lua/custom/snippets/lua.lua | 9 ++ lua/custom/snippets/python.lua | 121 ++++++++++++++ lua/custom/telescope.lua | 19 +++ lua/custom/todo.lua | 12 ++ lua/custom/treesitter.lua | 17 ++ lua/custom/trouble.lua | 28 ++++ main.py | 1 + plugin/keymaps.lua | 15 ++ plugin/options.lua | 29 ++++ plugin/providers.lua | 3 + 38 files changed, 1125 insertions(+) create mode 100644 README.md create mode 100644 ftplugin/go.lua create mode 100644 init.lua create mode 100644 lua/custom/README.md create mode 100644 lua/custom/colorschemes.lua create mode 100644 lua/custom/completion.lua create mode 100644 lua/custom/lsp.lua create mode 100644 lua/custom/lualine.lua create mode 100644 lua/custom/luasnip.lua create mode 100644 lua/custom/neogen.lua create mode 100644 lua/custom/obsidian.lua create mode 100644 lua/custom/oil.lua create mode 100644 lua/custom/plugins/colorschemes.lua create mode 100644 lua/custom/plugins/completion.lua create mode 100644 lua/custom/plugins/dressing.lua create mode 100644 lua/custom/plugins/lsp.lua create mode 100644 lua/custom/plugins/lualine.lua create mode 100644 lua/custom/plugins/luasnip.lua create mode 100644 lua/custom/plugins/neogen.lua create mode 100644 lua/custom/plugins/obsidian.lua create mode 100644 lua/custom/plugins/oil.lua create mode 100644 lua/custom/plugins/telescope.lua create mode 100644 lua/custom/plugins/tmux_navigator.lua create mode 100644 lua/custom/plugins/todo.lua create mode 100644 lua/custom/plugins/treesitter.lua create mode 100644 lua/custom/plugins/trouble.lua create mode 100644 lua/custom/plugins/which_key.lua create mode 100644 lua/custom/snippets/README.md create mode 100644 lua/custom/snippets/lua.lua create mode 100644 lua/custom/snippets/python.lua create mode 100644 lua/custom/telescope.lua create mode 100644 lua/custom/todo.lua create mode 100644 lua/custom/treesitter.lua create mode 100644 lua/custom/trouble.lua create mode 100644 main.py create mode 100644 plugin/keymaps.lua create mode 100644 plugin/options.lua create mode 100644 plugin/providers.lua diff --git a/README.md b/README.md new file mode 100644 index 0000000..e144f85 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# Config refactor (v2.0) +## Useful links +- [Переписывание конфига с автором telescope](https://www.youtube.com/watch?v=kJVqxFnhIuw&t=510s) +- [Документация по Lua в Nvim](https://neovim.io/doc/user/lua-guide.html) +- [Конфиг TJ](https://github.com/tjdevries/config.nvim/tree/master) +## Основные прицнипы формирования конфига +### Root plugin папка +Скрипты в этой папке загружаются автоматически после инициализации `neovim`, но до загрузки файлов типа `ftplugin/` или `after/`. +### Plugins +Разберем на примере `oil.nvim`: Сначала базовые настройки, такие как инструкция откуда качать и всякие зависимости и атрибуты по типу приоритета кладутся в директорию `custom/plugins` в виде названия плагина: +*lua/custom/plugins/oil.lua* +```lua +return { + "stevearc/oil.nvim", + dependencies = { { "echasnovski/mini.icons", opts = {} } }, + config = function() + require "custom/oil" + end, +} +``` +Затем, как можно видеть, сама функция настроек расположена отдельно в файле с идентичным названием, но в директории "повыше": +*lua/custom/oil.lua* +```lua +require("oil").setup{ + opts = { + keymaps = { + ["g?"] = "actions.show_help", + }, + }, +} +``` + +## Разница между ftplugin и after/ftplugin +Суть одна и та-же: загрузка конфигураций для конкретных типов файлов, однако: +### ftplugin +Тут храняться настройки, которые будут применены **до** загразуки плагинов. Т.е. настройки, что определны где-то в настройках плагинов будут переписывать если что те, которые установлены для типов файлов тут +### after/ftplugin +Настройки для типов файлов тут будут применены уже после того, как загрузится все содержимое neovim => эти настройки будут перегружать все то, что было настроено в плагинах +## Включение / Выключение некоторых плагинов +Из за возникновения случаев, когда некоторые плагины на некоторых машинах не нужно включать (например obsidian мне нужен только на хостовых машинах, на удаленных он будет только мешать открывать .md файлы), то в `init.lua` у меня в самом начале устанавливаются для таких плагинов глобальные переменные со следующей семантикой: +``` +vim.g._enabled = +``` +Например: +```lua +vim.g.obsidian_enabled = false +``` +Это позволяет динамически включать/выключать плагины без необходимости усложнять конфиг `lazy` +# FAQ +> Зачем так мучаться? Не проще все кидать в один файл? + +Проще, но такое распараллеливание позволяет легче дебажить файлы настроек. Т.е. исправляя настройки мы можем просто `source`ить файл настроек, не трогая конфигурации скачивания файлов, чтобы лишний раз не триггерить Lazy. + +> Что делать, если в `checkhealth` выдается ошибка `luarocks not found`? + +Необходимо его установить по инструкции с [сайта](https://luarocks.org/) + +> Что делать, если при установке `luarocks` выдает ошибку что не найдены `.h` файлы? + +Надо установить хэдеры lua командой: +```bash +sudo apt install liblua5.3-dev +``` + +> checkhealth не может найти tree-sitter cli + +Надо установить соответствующий `npm` пакет: +```js +npm install -g tree-sitter-cli +``` + diff --git a/ftplugin/go.lua b/ftplugin/go.lua new file mode 100644 index 0000000..e69de29 diff --git a/init.lua b/init.lua new file mode 100644 index 0000000..45408d8 --- /dev/null +++ b/init.lua @@ -0,0 +1,40 @@ +-- Global settings params +--- Option to enable/disalbe obsidian plugin +vim.g.obsidian_enabled = false + +-- Making leader () key to space +vim.g.mapleader = "\\" +-- Making local leader () key to backslash +vim.g.maplocalleader = "" + +-- Bootstrap lazy.nvim +local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim" +if not (vim.uv or vim.loop).fs_stat(lazypath) then + local lazyrepo = "https://github.com/folke/lazy.nvim.git" + local out = vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath }) + if vim.v.shell_error ~= 0 then + vim.api.nvim_echo({ + { "Failed to clone lazy.nvim:\n", "ErrorMsg" }, + { out, "WarningMsg" }, + { "\nPress any key to exit..." }, + }, true, {}) + vim.fn.getchar() + os.exit(1) + end +end +vim.opt.rtp:prepend(lazypath) + + +-- Setup lazy.nvim +require("lazy").setup({ + spec = { + -- import your plugins + { import = "custom/plugins" }, + }, + -- Configure any other settings here. See the documentation for more details. + -- colorscheme that will be used when installing plugins. + install = { colorscheme = { "gruvbox-material" } }, + -- automatically check for plugin updates + checker = { enabled = false }, +}) + diff --git a/lua/custom/README.md b/lua/custom/README.md new file mode 100644 index 0000000..d725dd7 --- /dev/null +++ b/lua/custom/README.md @@ -0,0 +1,59 @@ +# Справка по интересным моментам в коде +## Функция получения версии `python` в `lsp.lua` + +```lua +local function get_python_version() + local handle = io.popen("python --version 2>&1") -- Redirect stderr to stdout + if handle then + local result = handle:read("*a") + handle:close() + -- Check if the output contains a version number + local version = result:match("Python (%d+%.%d+%.%d+)") + if version then + return version + end + end + + handle = io.popen("python3 --version 2>&1") -- Redirect stderr to stdout + if handle then + local result = handle:read("*a") + handle:close() + -- Check if the output contains a version number + local version = result:match("Python (%d+%.%d+%.%d+)") + if version then + return version + end + end + -- TODO: Add some exception handling if python not installed on user machine + return "Python 0.0.0" +end +``` +Что тут есть примечательного: +- Получение данных, выполняя команду в shell оболочке системы с помощью + `io.popen`. *Важно*: Данная функция может работать не во всех ОС +- Функция выполняет команду, указанную в аргументе, и возвращает *файловый + дескриптор*, который можно использовать для чтения вывода команды (или + записи в нее) + +Разберем флоу подробнее: +Если про `python --version` - все понятно, то вот: +```lua +2>&1 +``` +Уже надо прояснить: +- В UNIX-подобных системах есть три стандартных потока - `stdin` = 0; `stdout` = 1; + `strerr` = 2; +- По умолчанию `io.popen` передает только вывод `stdout` в handle, поэтому для обработки +ошибок, надо дополнительно захватывать поток `stderr` +- `2>&1` означает, что мы хотим перенаправить поток ошибок 2 в стандартный вывод 1; +- Это нужно для того, чтобы захватить не только вывод команды, но и возможные ошибки +(например если питон не установлен); +- `>&` - оператор перенаправления потоков. + +Дополнительно: +`*a` внутри `read` - конструкция формата чтения файловых объектов в `Lua`. Они +указывают - как именно стоит читать данные из файла или потока. Помимо `a` есть +еще: +- `*a` - читать все содержимое +- `*l` - читать строку +- `*n` - читать число. diff --git a/lua/custom/colorschemes.lua b/lua/custom/colorschemes.lua new file mode 100644 index 0000000..5a92f02 --- /dev/null +++ b/lua/custom/colorschemes.lua @@ -0,0 +1,9 @@ +-- Turn on termguicolors for colorschemes +-- (Have to use true color terminal to see theese setting work) +vim.opt.termguicolors = true +vim.opt.background = "dark" -- colorschemes that can be light or dark will be made dark +vim.opt.signcolumn = "yes" -- show sigh columns so that text doesn't shift + +vim.g.gruvbox_material_background = 'hard' +vim.g.gruvbox_material_enable_italic = true +vim.cmd.colorscheme("gruvbox-material") diff --git a/lua/custom/completion.lua b/lua/custom/completion.lua new file mode 100644 index 0000000..ab16127 --- /dev/null +++ b/lua/custom/completion.lua @@ -0,0 +1,65 @@ +-- Set some settings for competion +-- For more info type `:help completeopt` +-- menu: Show menu when completions available (more than 1) +-- menuone: Show menu even when there is only 1 option +-- noselect: Force user to select convinient option + +-- Load luasnip setup +require "custom.luasnip" + +vim.opt.completeopt = { "menu", "menuone", "noselect" } + +local lspkind = require "lspkind" + +local kind_formatter = lspkind.cmp_format { + mode = "symbol_text", + menu = { + buffer = "[buf]", + nvim_lsp = "[LSP]", + nvim_lua = "[api]", + path = "[path]", + luasnip = "[snip]", + gh_issues = "[issues]", + tn = "[TabNine]", + eruby = "[erb]", + }, +} + +local cmp = require "cmp" + +cmp.setup { + sources = { + { name = "luasnip" }, + { name = "nvim_lsp" }, + { name = "path" }, + { name = "buffer" }, + }, + mapping = { + [""] = cmp.mapping.select_next_item { behavior = cmp.SelectBehavior.Insert }, + [""] = cmp.mapping.select_prev_item { behavior = cmp.SelectBehavior.Insert }, + [""] = cmp.mapping( + cmp.mapping.confirm { + behavior = cmp.ConfirmBehavior.Insert, + select = true, + }, + { "i", "c" } + ), + }, + + -- Enable luasnip to handle snippet expansion for nvim-cmp + snippet = { + expand = function(args) + vim.snippet.expand(args.body) + end, + }, + + formatting = { + fields = { "abbr", "kind", "menu" }, + expandable_indicator = true, + format = function(entry, vim_item) + -- Lspkind setup for icons + vim_item = kind_formatter(entry, vim_item) + return vim_item + end, + }, +} diff --git a/lua/custom/lsp.lua b/lua/custom/lsp.lua new file mode 100644 index 0000000..9498ec0 --- /dev/null +++ b/lua/custom/lsp.lua @@ -0,0 +1,222 @@ +local lspconfig = require("lspconfig") + +local keymap = vim.keymap + +local capabilities = nil +if pcall(require, "cmp_nvim_lsp") then + capabilities = require("cmp_nvim_lsp").default_capabilities() +end + + +local servers = { + gopls = { + settings = { + gopls = { + hints = { + assignVariableTypes = true, + compositeLiteralFields = true, + compositeLiteralTypes = true, + constantValues = true, + functionTypeParameters = true, + parameterNames = true, + rangeVariableTypes = true, + }, + }, + }, + }, + ruff = { + init_options = { + settings = { + -- Ruff language server settings go here + logLevel = "debug", + }, + }, + }, + pyright = { + settings = { + pyright = { + -- Using Ruff's import organizer + disableOrganizeImports = true, + }, + python = { + analysis = { + -- Ignore all files for analysis to exclusively use Ruff for linting + -- ignore = { "*" }, + diagnosticMode = "off", + -- typeCheckingMode = "off", + }, + }, + }, + }, + lua_ls = { + capabilities = capabilities, + settings = { + Lua = { + -- make the language server recognize "vim" global + diagnostics = { + globals = { "vim" }, + }, + completion = { + callSnippet = "Replace", + }, + }, + }, + }, + clangd = { + filetypes = { "c" }, + cmd = { + "clangd", + "--offset-encoding=utf-16", + }, + }, +} + +local servers_to_install = vim.tbl_filter(function(key) + local t = servers[key] + if type(t) == "table" then + return not t.manual_install + else + return t + end +end, vim.tbl_keys(servers)) + + + +require("mason").setup() +local ensure_installed = { + -- Normal settings + "stylua", + "lua_ls", + "gofumpt", + "golines", + "prettier", +} + +local function get_python_version() + local handle = io.popen("python --version 2>&1") -- Redirect stderr to stdout + if handle then + local result = handle:read("*a") + handle:close() + -- Check if the output contains a version number + local version = result:match("Python (%d+%.%d+%.%d+)") + if version then + return version + end + end + + handle = io.popen("python3 --version 2>&1") -- Redirect stderr to stdout + if handle then + local result = handle:read("*a") + handle:close() + -- Check if the output contains a version number + local version = result:match("Python (%d+%.%d+%.%d+)") + if version then + return version + end + end + -- TODO: Add some exception handling if python not installed on user machine + return "Python 0.0.0" +end + +-- Now we need to make things work in Astra +-- Main Astra cockblock - low python version, that prevents installation of +-- some modules, so in order to prevent mason from whining - disable some +-- autoinstall modules depending on currently installed python version +-- NOTE: You must install removed dependencies manually +local python_version = get_python_version() +if python_version == nil then + python_version = "Python 3.13" +end +local _, minor, _ = python_version:match(".*(%d+)%.(%d+)%.(%d+)") +if tonumber(minor) < 8 then + for i, k in pairs(servers_to_install) do + -- Ruff is not supported for python lower than 3.8 + if k == "ruff" then + table.remove(servers_to_install, i) + end + end +end +vim.list_extend(ensure_installed, servers_to_install) +require("mason-tool-installer").setup { ensure_installed = ensure_installed } + +for name, config in pairs(servers) do + if config == true then + config = {} + end + config = vim.tbl_deep_extend("force", {}, { + capabilities = capabilities, + }, config) + + lspconfig[name].setup(config) +end + +-- Here it is used the LSP server attaches to file +vim.api.nvim_create_autocmd("LspAttach", { + -- Grouping together autocommands. + -- Here we creating new group and calling it "UserLspConfig" + group = vim.api.nvim_create_augroup("UserLspConfig", {}), + -- callback defining logic to execute on the event + callback = function(ev) + -- Buffer local mappings. + -- See `:help vim.lsp.*` for documentation on any of the below functions + local opts = { buffer = ev.buf, silent = true } + + -- set keybinds + -- show definition, references + opts.desc = "Show LSP references" + keymap.set("n", "gR", "Telescope lsp_references", opts) + + -- go to declaration + opts.desc = "Go to declaration" + keymap.set("n", "gD", vim.lsp.buf.declaration, opts) + + -- show lsp definitions + opts.desc = "Show LSP definitions" + keymap.set("n", "gd", "Telescope lsp_definitions", opts) + + -- show lsp implementations + opts.desc = "Show LSP implementations" + keymap.set("n", "gi", "Telescope lsp_implementations", opts) + + -- show lsp type definitions + opts.desc = "Show LSP type definitions" + keymap.set("n", "gt", "Telescope lsp_type_definitions", opts) + + -- see available code actions, in visual mode will apply to selection + opts.desc = "See available code actions" + keymap.set({ "n", "v" }, "ca", vim.lsp.buf.code_action, opts) + + -- smart rename + opts.desc = "Smart rename" + keymap.set("n", "rn", vim.lsp.buf.rename, opts) + + -- show diagnostics for file + opts.desc = "Show buffer diagnostics" + keymap.set("n", "D", "Telescope diagnostics bufnr=0", opts) + + -- show diagnostics for line + opts.desc = "Show line diagnostics" + keymap.set("n", "d", vim.diagnostic.open_float, opts) + + -- jump to previous diagnostic in buffer + opts.desc = "Go to previous diagnostic" + keymap.set("n", "[d", vim.diagnostic.goto_prev, opts) + + -- jump to next diagnostic in buffer + opts.desc = "Go to next diagnostic" + keymap.set("n", "]d", vim.diagnostic.goto_next, opts) + + -- show documentation for what is under cursor + opts.desc = "Show documentation for what is under cursor" + keymap.set("n", "K", vim.lsp.buf.hover, opts) + + -- mapping to restart lsp if necessary + opts.desc = "Restart LSP" + keymap.set("n", "rs", ":LspRestart", opts) + + opts.desc = "Run formatting on current buffer" + keymap.set("n", "f", function() + vim.lsp.buf.format({ async = true }) + end, opts) + end, +}) diff --git a/lua/custom/lualine.lua b/lua/custom/lualine.lua new file mode 100644 index 0000000..c968ac7 --- /dev/null +++ b/lua/custom/lualine.lua @@ -0,0 +1,14 @@ +require("lualine").setup({ + options = { + theme = "gruvbox-material", + }, + sections = { + lualine_c = { + { + "filename", + file_status = true, + path = 2, + }, + }, + }, +}) diff --git a/lua/custom/luasnip.lua b/lua/custom/luasnip.lua new file mode 100644 index 0000000..9b98678 --- /dev/null +++ b/lua/custom/luasnip.lua @@ -0,0 +1,34 @@ +local ls = require "luasnip" +local types = require "luasnip.util.types" + +ls.config.set_config { + history = true, + updateevents = "TextChanged, TextChangedI", + enable_autosnippets = true, + store_selection_keys = "", +} + +vim.keymap.set({ "i", "s" }, "", function() + if ls.expand_or_jumpable() then + ls.expand_or_jump() + end +end, { silent = true }) + +vim.keymap.set({ "i", "s" }, "", function() + if ls.jumpable() then + ls.jump(-1) + end +end, { silent = true }) + +vim.keymap.set({ "i", "s" }, "", function() + if ls.choice_active() then + ls.change_choice(1) + end +end, { silent = true }) + +vim.keymap.set("n", "s", "source ~/.config/nvim/lua/custom/luasnip.lua") + +-- Load custom snippets +for _, ft_path in ipairs(vim.api.nvim_get_runtime_file("lua/custom/snippets/*.lua", true)) do + loadfile(ft_path)() +end diff --git a/lua/custom/neogen.lua b/lua/custom/neogen.lua new file mode 100644 index 0000000..c071acf --- /dev/null +++ b/lua/custom/neogen.lua @@ -0,0 +1,7 @@ +require("neogen").setup { + enabled = true +} + +local keymap = vim.keymap +local opts = { noremap = true, silent = true } +keymap.set("n", "ids", ":lua require('neogen').generate()", opts) diff --git a/lua/custom/obsidian.lua b/lua/custom/obsidian.lua new file mode 100644 index 0000000..1d02283 --- /dev/null +++ b/lua/custom/obsidian.lua @@ -0,0 +1,72 @@ +require("obsidian").setup { + -- Set workspace setting + workspaces = { + { + name = "personal", + path = "~/Documents/t0xa_vault", + } + }, + -- Disable conceal level to supress varning log message + ui = { + enable = false + }, + -- Set notes subdir to store new notes + notes_subdir = "Unsorted", + new_notes_location = "notes_subdir", + -- Set template params + templates = { + folder = "Templates", + date_format = "%Y-%m-%d", + time_format = "%H:%M", + substitutions = { + yesterday = function() + return os.date("%Y-%m-%d", os.time() - 86400) + end + } + }, + -- Set behaviour of following links + follow_url_func = function(url) + -- vim.fn.jobstart({ "open", url }) -- Mac OS + vim.fn.jobstart({ "xdg-open", url }) -- linux + -- vim.cmd(':silent exec "!start ' .. url .. '"') -- Windows + -- vim.ui.open(url) -- need Neovim 0.10.0+ + end, + -- Set behaviour for opening images + follow_img_func = function(img) + -- vim.fn.jobstart { "qlmanage", "-p", img } -- Mac OS quick look preview + vim.fn.jobstart({ "xdg-open", url }) -- linux + -- vim.cmd(':silent exec "!start ' .. url .. '"') -- Windows + end, + -- Set sorting for creation date + sort_by = "created", + -- Set attachements new folder + attachments = { + img_folder = "Media" + }, + -- Disable auto formatter for files + disable_frontmatter = true, +} + + +-- Obsidian-related keybinds +vim.keymap.set("n", "oit", "ObsidianTemplate", + { silent = true, noremap = true, desc = "Obsidian: insert template" }) +vim.keymap.set("n", "oo", "ObsidianQuickSwitch", + { silent = true, noremap = true, desc = "Obsidian: open file" }) +vim.keymap.set("n", "opi", "ObsidianPasteImg", + { silent = true, noremap = true, desc = "Obsidian: paste image" }) +vim.keymap.set("n", "or", "ObsidianRename", + { silent = true, noremap = true, desc = "Obsidian: rename file" }) +vim.keymap.set("n", "oc", "ObsidianToggleCheckbox", + { silent = true, noremap = true, desc = "Obsidian: toggle checkbox" }) +vim.keymap.set("n", "on", "ObsidianNew", { silent = true, noremap = true, desc = "Obsidian: new file" }) +vim.keymap.set("n", "otoc", "ObsidianTOC", + { silent = true, noremap = true, desc = "Obsidian: open TOC" }) +vim.keymap.set("n", "ofl", "ObsidianFollowLink", + { silent = true, noremap = true, desc = "Obsidian: follow link" }) +vim.keymap.set("n", "olt", "ObsidianTags", + { silent = true, noremap = true, desc = "Obsidian: Get tags list" }) +vim.keymap.set("n", "osb", "ObsidianBacklinks", + { silent = true, noremap = true, desc = "Obsidian: Show Backlinks" }) +vim.keymap.set("n", "osl", "ObsidianLinks", + { silent = true, noremap = true, desc = "Obsidian: Show Links" }) diff --git a/lua/custom/oil.lua b/lua/custom/oil.lua new file mode 100644 index 0000000..cf32130 --- /dev/null +++ b/lua/custom/oil.lua @@ -0,0 +1,27 @@ +require("oil").setup { + keymaps = { + ["g?"] = "actions.show_help", + [""] = "actions.select", + [""] = { "actions.select", opts = { vertical = true }, desc = "Open the entry in a vertical split" }, + [""] = false, + [""] = { "actions.select", opts = { tab = true }, desc = "Open the entry in new tab" }, + [""] = "actions.preview", + [""] = "actions.close", + [""] = false, + ["-"] = "actions.parent", + ["_"] = "actions.open_cwd", + ["`"] = "actions.cd", + ["~"] = { "actions.cd", opts = { scope = "tab" }, desc = ":tcd to the current oil directory", mode = "n" }, + ["gs"] = "actions.change_sort", + ["gx"] = "actions.open_external", + ["g."] = "actions.toggle_hidden", + ["g\\"] = "actions.toggle_trash", + ["gr"] = "actions.refresh", + }, + view_options = { + show_hidden = true, + }, + -- Open parent directory in current window +} + +vim.keymap.set("n", "-", "Oil", { desc = "Open parent directory" }) diff --git a/lua/custom/plugins/colorschemes.lua b/lua/custom/plugins/colorschemes.lua new file mode 100644 index 0000000..7fe659b --- /dev/null +++ b/lua/custom/plugins/colorschemes.lua @@ -0,0 +1,20 @@ +-- TODO: Need to refactor ways of downloading colorschemes +-- Now it is just a hack to download all colorschemes as dependecies +return { + "folke/tokyonight.nvim", + dependencies = { + "ellisonleao/gruvbox.nvim", + "sainnhe/everforest", + "sainnhe/gruvbox-material", + "rebelot/kanagawa.nvim", + "catppuccin/nvim", + "folke/tokyonight.nvim", + "luisiacc/gruvbox-baby", + }, + lazy = false, + priority = 1000, + config = function() + require "custom/colorschemes" + end, +} + diff --git a/lua/custom/plugins/completion.lua b/lua/custom/plugins/completion.lua new file mode 100644 index 0000000..2628a4c --- /dev/null +++ b/lua/custom/plugins/completion.lua @@ -0,0 +1,20 @@ +return { + "hrsh7th/nvim-cmp", + event = "InsertEnter", -- Only load plugin when in INSERT mode + dependencies = { + "hrsh7th/cmp-buffer", -- source for text in buffer + "hrsh7th/cmp-path", -- source for file system paths + { + "L3MON4D3/LuaSnip", + -- follow latest release. + version = "v2.*", -- Replace by the latest released major (first number of latest release) + }, + "saadparwaiz1/cmp_luasnip", -- for autocompletion + "rafamadriz/friendly-snippets", -- useful snippets + "onsails/lspkind.nvim", -- vs-code like pictograms + "hrsh7th/cmp-nvim-lsp", + }, + config = function() + require "custom/completion" + end, +} diff --git a/lua/custom/plugins/dressing.lua b/lua/custom/plugins/dressing.lua new file mode 100644 index 0000000..feadb27 --- /dev/null +++ b/lua/custom/plugins/dressing.lua @@ -0,0 +1,4 @@ +return { + "stevearc/dressing.nvim", + event = "VeryLazy" +} diff --git a/lua/custom/plugins/lsp.lua b/lua/custom/plugins/lsp.lua new file mode 100644 index 0000000..022c2eb --- /dev/null +++ b/lua/custom/plugins/lsp.lua @@ -0,0 +1,35 @@ +return { + { + "neovim/nvim-lspconfig", + dependencies = { + { + --`lazydev` configures Lua LSP for your Neovim config, runtime and plugins + -- used for completion, annotations and signatures of Neovim apis + "folke/lazydev.nvim", + ft = "lua", + opts = { + library = { + -- Load luvit types when the `vim.uv` word is found + { path = "luvit-meta/library", words = { "vim%.uv" } }, + }, + }, + }, + { "Bilal2453/luvit-meta", lazy = true }, + "williamboman/mason.nvim", + "williamboman/mason-lspconfig.nvim", + "WhoIsSethDaniel/mason-tool-installer.nvim", + + -- Some enhancements for notifications in bottom-right corner + { "j-hui/fidget.nvim", opts = {} }, + + -- Following plugin enables enhancements for diagnostics info + -- { "https://git.sr.ht/~whynothugo/lsp_lines.nvim" }, + + -- Autoformatting + "stevearc/conform.nvim", + }, + config = function() + require "custom/lsp" + end, + }, +} diff --git a/lua/custom/plugins/lualine.lua b/lua/custom/plugins/lualine.lua new file mode 100644 index 0000000..e17801b --- /dev/null +++ b/lua/custom/plugins/lualine.lua @@ -0,0 +1,25 @@ +return { + "nvim-lualine/lualine.nvim", + dependencies = { "nvim-tree/nvim-web-devicons" }, + config = function() + local lualine = require("lualine") + -- configure lualine with modified theme + lualine.setup({ + options = { + -- theme = "tokyonight", + -- theme = "catppuccin-mocha", + theme = "gruvbox-material", + }, + sections = { + lualine_c = { + { + "filename", + file_status = true, + path = 2, + }, + }, + }, + }) + end, +} + diff --git a/lua/custom/plugins/luasnip.lua b/lua/custom/plugins/luasnip.lua new file mode 100644 index 0000000..99006fc --- /dev/null +++ b/lua/custom/plugins/luasnip.lua @@ -0,0 +1,9 @@ +return { + { + "L3MON4D3/LuaSnip", + -- follow latest release. + version = "v2.*", -- Replace by the latest released major (first number of latest release) + -- install jsregexp (optional!). + build = "make install_jsregexp" + } +} diff --git a/lua/custom/plugins/neogen.lua b/lua/custom/plugins/neogen.lua new file mode 100644 index 0000000..1f0174e --- /dev/null +++ b/lua/custom/plugins/neogen.lua @@ -0,0 +1,12 @@ +-- Plugin for generating annotations +return { + { + "danymat/neogen", + config = true, + -- Uncomment next line if you want to follow only stable versions + version = "*", + config = function() + require "custom/neogen" + end, + } +} diff --git a/lua/custom/plugins/obsidian.lua b/lua/custom/plugins/obsidian.lua new file mode 100644 index 0000000..0f9377d --- /dev/null +++ b/lua/custom/plugins/obsidian.lua @@ -0,0 +1,16 @@ +if vim.g.obsidian_enabled then + return { + "epwalsh/obsidian.nvim", + version = "*", + lazy = true, + ft = "markdown", + dependencies = { + "nvim-lua/plenary.nvim", + }, + config = function() + require "custom.obsidian" + end + } +else + return {} +end diff --git a/lua/custom/plugins/oil.lua b/lua/custom/plugins/oil.lua new file mode 100644 index 0000000..96156df --- /dev/null +++ b/lua/custom/plugins/oil.lua @@ -0,0 +1,8 @@ +return { + "stevearc/oil.nvim", + dependencies = { { "echasnovski/mini.icons", opts = {} } }, + config = function() + require "custom/oil" + end, +} + diff --git a/lua/custom/plugins/telescope.lua b/lua/custom/plugins/telescope.lua new file mode 100644 index 0000000..2575d64 --- /dev/null +++ b/lua/custom/plugins/telescope.lua @@ -0,0 +1,12 @@ +return { + "nvim-telescope/telescope.nvim", + dependencies = { + { "nvim-telescope/telescope-fzf-native.nvim", build = "make" }, + "nvim-lua/plenary.nvim", + "nvim-tree/nvim-web-devicons", + "folke/todo-comments.nvim", + }, + config = function() + require "custom.telescope" + end +} diff --git a/lua/custom/plugins/tmux_navigator.lua b/lua/custom/plugins/tmux_navigator.lua new file mode 100644 index 0000000..e7fa738 --- /dev/null +++ b/lua/custom/plugins/tmux_navigator.lua @@ -0,0 +1,18 @@ +return { + "christoomey/vim-tmux-navigator", + cmd = { + "TmuxNavigateLeft", + "TmuxNavigateDown", + "TmuxNavigateUp", + "TmuxNavigateRight", + "TmuxNavigatePrevious", + }, + keys = { + { "", "TmuxNavigateLeft" }, + { "", "TmuxNavigateDown" }, + { "", "TmuxNavigateUp" }, + { "", "TmuxNavigateRight" }, + { "", "TmuxNavigatePrevious" }, + }, +} + diff --git a/lua/custom/plugins/todo.lua b/lua/custom/plugins/todo.lua new file mode 100644 index 0000000..76b7eee --- /dev/null +++ b/lua/custom/plugins/todo.lua @@ -0,0 +1,8 @@ +return { + "folke/todo-comments.nvim", + event = { "BufReadPre", "BufNewFile" }, + dependencies = { "nvim-lua/plenary.nvim" }, + config = function() + require "custom/todo" + end, +} diff --git a/lua/custom/plugins/treesitter.lua b/lua/custom/plugins/treesitter.lua new file mode 100644 index 0000000..2b2979a --- /dev/null +++ b/lua/custom/plugins/treesitter.lua @@ -0,0 +1,14 @@ +return { + "nvim-treesitter/nvim-treesitter", + -- open this plugin on two events: + -- BufReadPre - open existing file + -- BufNewFile - open new file + event = { "BufReadPre", "BufNewFile" }, + build = ":TSUpdate", -- Run whenever this plugin is installed or updated + dependencies = { + "windwp/nvim-ts-autotag", -- Auto-closing functionality within treesitter + }, + config = function() + require "custom/treesitter" + end, +} diff --git a/lua/custom/plugins/trouble.lua b/lua/custom/plugins/trouble.lua new file mode 100644 index 0000000..fe73a96 --- /dev/null +++ b/lua/custom/plugins/trouble.lua @@ -0,0 +1,10 @@ +return { + { + "folke/trouble.nvim", + opts = {}, -- for default options, refer to the configuration section for custom setup. + cmd = "Trouble", + config = function() + require "custom/trouble" + end, + }, +} diff --git a/lua/custom/plugins/which_key.lua b/lua/custom/plugins/which_key.lua new file mode 100644 index 0000000..f2cff19 --- /dev/null +++ b/lua/custom/plugins/which_key.lua @@ -0,0 +1,20 @@ +return { + "folke/which-key.nvim", + -- Telling nvim that it can load this plugin later, and that it is not + -- that important for initial UI + event = "VeryLazy", + -- Function that will run while neovim startup instead of when plugin is actualy loads + init = function() + -- How long which-key will wait until activation + vim.o.timeout = true + vim.o.timeoutlen = 500 + end, + -- Options that will pass to setup function, but we are leaving it empty to use + -- default configuration + opts = { + -- your configuration comes here + -- or leave it empty to use the default settings + -- refer to the configuration section below + } +} + diff --git a/lua/custom/snippets/README.md b/lua/custom/snippets/README.md new file mode 100644 index 0000000..5eb0b03 --- /dev/null +++ b/lua/custom/snippets/README.md @@ -0,0 +1,20 @@ +# Гайд по формированию сниппетов +## fmta + f +Рассмотрим пример использования `fmta` в сочетании с `f`: +``` +f(function(args) return string.lower(args[1][1]) end, {1}) +``` +Тут: +- `f`: Это функция LuaSnip, которая позволяет выполнять произвольные преобразования над входными данными. + Она принимает два аргумента: + - Функцию, которая выполняет преобразование. + - Список индексов, указывающих, какие входные данные использовать. + +- `function(args)`: Это функция, которая принимает аргумент args — таблица, содержащая значения, переданные из других узлов (например, i(1), i(2) и т.д.). +- `args[1][1]`: + - `args[1]` — это первая группа входных данных, переданная в f. + - `args[1][1]` — это первое значение из этой группы. Например, если вы используете i(1), то args[1][1] будет содержать текст, введенный пользователем для этого узла. + +- `string.lower(args[1][1])`: `string.lower` — это стандартная функция Lua, которая преобразует строку в нижний регистр. + +- `{1}`: Это список индексов, указывающих, какие входные данные использовать. `{1}` означает, что функция будет использовать значение из первого узла (например, i(1)). diff --git a/lua/custom/snippets/lua.lua b/lua/custom/snippets/lua.lua new file mode 100644 index 0000000..eaefb80 --- /dev/null +++ b/lua/custom/snippets/lua.lua @@ -0,0 +1,9 @@ +-- Clear snippets collection when souring lua file +require("luasnip.session.snippet_collection").clear_snippets "lua" + +local ls = require "luasnip" + +ls.add_snippets("lua", { + ls.parser.parse_snippet("expand", "-- this is what was expanded kek"), + ls.parser.parse_snippet("pipa", "Pipasik"), +}) diff --git a/lua/custom/snippets/python.lua b/lua/custom/snippets/python.lua new file mode 100644 index 0000000..93626a1 --- /dev/null +++ b/lua/custom/snippets/python.lua @@ -0,0 +1,121 @@ +-- Clear snippets collection when souring lua file +require("luasnip.session.snippet_collection").clear_snippets "python" + +local ls = require "luasnip" + +local s = ls.snippet +local t = ls.text_node +local i = ls.insert_node +local c = ls.choice_node +local f = ls.function_node + +local fmt = require("luasnip.extras.fmt").fmt +local fmta = require("luasnip.extras.fmt").fmta +local rep = require("luasnip.extras").rep + +ls.add_snippets("python", { + s( + { trig = "ctable", dscr = "Create method or function with test stub" }, + fmt( + [[ + {} = Table( + "{}", + metadata_obj, + Column("id", Integer, primary_key=True), + {} + ) + ]], + { + i(1), + rep(1), + i(0) + } + ) + ), + s({ trig = "cmethod", dscr = "Create method or function with test stub" }, + fmta( + [[ + def <>(): + """<> for performing <>""" + pass + + def test_<>_<>(): + """Test for checking correct work of <> <>""" + assert 1 == 2 + <> + ]], + { + i(1), + c(2, { t "Function", t "Method" }), + i(3), + rep(1), + f(function(args) return string.lower(args[1][1]) end, { 2 }), + rep(1), + f(function(args) return string.lower(args[1][1]) end, { 2 }), + i(0) + } + ) + ), + s({ trig = "implog", dscr = "Import necessary logging utils" }, { + t({ + "import logging", + "_log = logging.getLogger(__name__)" + } + ) + }), + s({ trig = "logevent", dscr = "Import necessary logging utils" }, + fmt( + [[ + _log.{}('{}' * 60)) + _log.{}({}) + _log.{}('{}' * 60)) + ]], + { + c(1, { t "error", t "warning", t "info" }), + i(2), + rep(1), + i(3), + rep(1), + rep(2) + } + ) + ), + s({ trig = "pybasetest", dscr = "Create test suite boilerplate" }, + fmt( + [[ + class Test{}: + """Test suite for checking correct work of {} feature""" + + @pytest.fixture(autouse=True) + def setup_test(self): + """Fixture for initializing test cases base data""" + {} + + {} + ]], + { i(1), rep(1), i(2), i(0) } + ) + ), + s({ trig = "rupysection", dscr = "Secion snippet" }, + fmt( + [[ + ##################################### Секция ############################################# + # Тема: {} + ########################################################################################## + {} + ]], + { i(1), i(0) } + ) + ), + s({ trig = "pysection", dscr = "Secion snippet" }, + fmt( + [[ + ##################################### Section ############################################ + # Section topic: {} + ########################################################################################## + {} + ]], + { i(1), i(0) } + ) + ), +}) diff --git a/lua/custom/telescope.lua b/lua/custom/telescope.lua new file mode 100644 index 0000000..e9198d5 --- /dev/null +++ b/lua/custom/telescope.lua @@ -0,0 +1,19 @@ +require("telescope").setup { + defaults = { + path_display = { shorten = 4 }, + }, +} + +-- Load fzf extension to imporve performance +pcall(require("telescope").load_extension, "fzf") + +local builtin = require("telescope.builtin") +local keymap = vim.keymap +keymap.set("n", "ff", builtin.find_files, { desc = "FZF: find files in cwd" }) +keymap.set("n", "fml", builtin.marks, { desc = "FZF: find marks list" }) +keymap.set("n", "fmp", builtin.man_pages, { desc = "FZF: find available man pages" }) +keymap.set("n", "fg", builtin.live_grep, { desc = "FZF: find string in cwd" }) +keymap.set("n", "fb", builtin.buffers, { desc = "FZF: display opened buffers" }) +keymap.set("n", "fh", builtin.help_tags, { desc = "FZF: display help tags" }) +keymap.set("n", "ft", "TodoTelescope", { desc = "FZF: display TODO comments" }) +keymap.set("n", "fds", builtin.lsp_document_symbols, { desc = "FZF: Document symbols" }) diff --git a/lua/custom/todo.lua b/lua/custom/todo.lua new file mode 100644 index 0000000..e10a301 --- /dev/null +++ b/lua/custom/todo.lua @@ -0,0 +1,12 @@ +local todo_comments = require("todo-comments") +local keymap = vim.keymap + +keymap.set("n", "]t", function() + todo_comments.jump_next() +end, { desc = "Next todo comment" }) + +keymap.set("n", "[t", function() + todo_comments.jump_prev() +end, { desc = "Previous todo comment" }) + +todo_comments.setup(opts) diff --git a/lua/custom/treesitter.lua b/lua/custom/treesitter.lua new file mode 100644 index 0000000..388efc8 --- /dev/null +++ b/lua/custom/treesitter.lua @@ -0,0 +1,17 @@ +require 'nvim-treesitter.configs'.setup { + ensure_installed = { + "python", + "lua", + "vim", + "vimdoc", + "query", + "elixir", + "heex", + "javascript", + "html", + "go" + }, + sync_install = false, + highlight = { enable = true }, + indent = { enable = true }, +} diff --git a/lua/custom/trouble.lua b/lua/custom/trouble.lua new file mode 100644 index 0000000..e22abbc --- /dev/null +++ b/lua/custom/trouble.lua @@ -0,0 +1,28 @@ +local trouble = require("trouble") + +-- Setup Trouble +trouble.setup() + +-- Keybindings +vim.keymap.set("n", "xx", "Trouble diagnostics toggle", { desc = "Diagnostics (Trouble)" }) +vim.keymap.set("n", "xX", "Trouble diagnostics toggle filter.buf=0", + { desc = "Buffer Diagnostics (Trouble)" }) +vim.keymap.set("n", "cs", "Trouble symbols toggle focus=false", { desc = "Symbols (Trouble)" }) +vim.keymap.set("n", "cl", "Trouble lsp toggle focus=false win.position=right", + { desc = "LSP Definitions / references / ... (Trouble)" }) +vim.keymap.set("n", "xL", "Trouble loclist toggle", { desc = "Location List (Trouble)" }) +vim.keymap.set("n", "xQ", "Trouble qflist toggle", { desc = "Quickfix List (Trouble)" }) + +-- Telescope integration +-- local actions = require("telescope.actions") +local open_with_trouble = require("trouble.sources.telescope").open +-- local add_to_trouble = require("trouble.sources.telescope").add + +require("telescope").setup({ + defaults = { + mappings = { + i = { [""] = open_with_trouble }, + n = { [""] = open_with_trouble }, + }, + }, +}) diff --git a/main.py b/main.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/main.py @@ -0,0 +1 @@ + diff --git a/plugin/keymaps.lua b/plugin/keymaps.lua new file mode 100644 index 0000000..44f5019 --- /dev/null +++ b/plugin/keymaps.lua @@ -0,0 +1,15 @@ +local set = vim.keymap.set + +-- Basic movement keybinds, these make navigating splits easy for me +-- set("n", "", "") +-- set("n", "", "") +-- set("n", "", "") +-- set("n", "", "") + +-- Bindings for reloading LUA files (used when working with lua files) +-- set("n", "x", ".lua", { desc = "Execute the current lne" }) +set("n", "x", "source %", { desc = "Execute the current file" }) + +-- Following section purprose is to rebind some Russian missing binds +-- TODO: Maybe there is more clean and percise way, dunno right now +set("i", "", "") diff --git a/plugin/options.lua b/plugin/options.lua new file mode 100644 index 0000000..c95973e --- /dev/null +++ b/plugin/options.lua @@ -0,0 +1,29 @@ +local opt = vim.opt + +-- Command to show inline what are you trying to perform +opt.inccommand = "split" + +-- Search settings to toggle "smart case" search only if 1+ uppercase char +-- persist in search line +opt.smartcase = true +opt.ignorecase = true + +-- Enable line numbers and relative setting +opt.number = true +opt.relativenumber = true + +-- Tabulation and indentation settings +opt.shiftwidth = 2 -- Set spaces for tabs == 2 +opt.tabstop = 2 -- Set spaces for indent with == 2 +opt.expandtab = true -- use number of spaces to insert a +opt.softtabstop = 2 + +-- Disable swap files creation +opt.swapfile = false + +-- Add line at 80 symbols +opt.colorcolumn = "99" + +-- config to set up clipboard as default register +opt.clipboard:append("unnamedplus") + diff --git a/plugin/providers.lua b/plugin/providers.lua new file mode 100644 index 0000000..1e00d4a --- /dev/null +++ b/plugin/providers.lua @@ -0,0 +1,3 @@ +-- Disable unneccesary providers +vim.g.loaded_ruby_provider = 0 +vim.g.loaded_perl_provider = 0