DEV Community

Sérgio Araújo
Sérgio Araújo

Posted on • Edited on

My ever growing neovim init.lua

Intro

Since I have now neovim ~5~ 0.9.4 installed and knowing it can run faster with init.lua I started to gradually annotating and copying pieces of others [neo]vimmers to reproduce my old environment.

The full configuration resides now at:
https://bitbucket.org/sergio/mylazy-nvim/src/master/

I will improve this article gradually, for now each file and its place
will be at the top of each file

This article will be rewritten

because now I am using the lazy.nvim plugin manager and a bunch of things have changed since I published the first version of this article.

init.lua

-- Filename: /home/sergio/.config/nvim/init.lua
-- Last Change: Mon, 06 Nov 2023 - 15:08

require('core.options')
require('core.filetype')
require('core.keymaps')
require('core.autocommands')
require('core.bootstrap')
require('core.commands')
require('core.files')
require('core.theme')
Enter fullscreen mode Exit fullscreen mode

options

-- Filename: options.lua
-- Last Change: Tue, 11 Jul 2023 - 16:23

-- Compile lua to bytecode if the nvim version supports it.
-- https://github.com/armyers/NormalNvim
-- if vim.loader and vim.fn.has "nvim-0.9.1" == 1 then vim.loader.enable() end

local opt = vim.opt
local g = vim.g

-- IMPROVE NEOVIM STARTUP
-- https://github.com/editorconfig/editorconfig-vim/issues/50
-- vim.g.loaded_python_provier = 0
-- vim.g.loaded_python3_provider = 1
-- vim.g.python_host_skip_check = 1
-- vim.g.python_host_prog='/bin/python2'
-- vim.g.python3_host_skip_check = 1
-- vim.g.python3_host_prog='/bin/python3'
-- vim.opt.pyxversion=3
-- vim.g.EditorConfig_core_mode = 'external_command'
-- https://vi.stackexchange.com/a/5318/7339
vim.g.matchparen_timeout = 20
vim.g.matchparen_insert_timeout = 20
vim.g.python3_host_prog = vim.loop.os_homedir() .. "/.virtualenvs/neovim/bin/python3"

local options = {
  -- keywordprg = ':help',
  winbar = '%=%m %F',
  virtualedit = "block",
  modelines = 5,
  modelineexpr = false,
  modeline = true,
  cursorline = false,
  cursorcolumn = false,
  splitright = true,
  splitbelow = true,
  smartcase = true,
  hlsearch = false,
  ignorecase = true,
  incsearch = true,
  inccommand = "nosplit",
  hidden = true,
  autoindent = true,
  termguicolors = true,
  showmode = false,
  showmatch = true,
  matchtime = 2,
  wildmode = "longest:full,full",
  number = true,
  linebreak = true,
  joinspaces = false,
  timeoutlen = 500,
  ttimeoutlen = 10, -- https://vi.stackexchange.com/a/4471/7339
  path = vim.opt.path + "**",
  isfname = vim.opt.isfname:append("@-@"),
  autochdir = false,
  relativenumber = true,
  numberwidth = 2,
  shada = "!,'50,<50,s10,h,r/tmp",
  expandtab = true,
  smarttab = true,
  smartindent = true,
  shiftround = true,
  shiftwidth = 2,
  tabstop = 2,
  foldenable = false,
  foldlevel = 99,
  foldlevelstart = 99,
  foldcolumn = '1',
  foldmethod = "expr",
  foldexpr = "nvim_treesitter#foldexpr()",
  undofile = true,
  showtabline = 0,
  mouse = 'a',
  scrolloff = 3,
  sidescrolloff = 3,
  wrap = true,
  list = true,
  listchars = { leadmultispace = "│ ", multispace = "│ ", tab = "│ ", },
  --lazyredraw = true,
  updatetime = 250,
  laststatus = 3,
  confirm = false,
  conceallevel = 3,
  cmdheight = 0,
  -- filetype = 'on', -- handled by filetypefiletype = 'on' --lugin
}

for k, v in pairs(options) do
  vim.opt[k] = v
end


if vim.fn.has("nvim-0.10") == 1 then
  opt.smoothscroll = true
end

-- disable builtins plugins
local disabled_built_ins = {
  "2html_plugin",
  "getscript",
  "getscriptPlugin",
  "gzip",
  "logipat",
  "matchit",
  "netrw",
  "netrwFileHandlers",
  "loaded_remote_plugins",
  "loaded_tutor_mode_plugin",
  "netrwPlugin",
  "netrwSettings",
  "rrhelper",
  "spellfile_plugin",
  "tar",
  "tarPlugin",
  "vimball",
  "vimballPlugin",
  "zip",
  "zipPlugin",
  "matchparen", -- matchparen.nvim disables the default
}

for _, plugin in pairs(disabled_built_ins) do
  vim.g["loaded_" .. plugin] = 1
end

if vim.fn.executable("rg") then
  -- if ripgrep installed, use that as a grepper
  vim.opt.grepprg = "rg --vimgrep --no-heading --smart-case"
  vim.opt.grepformat = "%f:%l:%c:%m,%f:%l:%m"
end
--lua require("notify")("install ripgrep!")

if vim.fn.executable("prettier") then
  opt.formatprg = "prettier --stdin-filepath=%"
end
--lua require("notify")("Install prettier formater!")

opt.formatoptions = "l"
opt.formatoptions = opt.formatoptions
- "a" -- Auto formatting is BAD.
- "t" -- Don't auto format my code. I got linters for that.
+ "c" -- In general, I like it when comments respect textwidth
- "o" -- O and o, don't continue comments
+ "r" -- But do continue when pressing enter.
+ "n" -- Indent past the formatlistpat, not underneath it.
+ "j" -- Auto-remove comments if possible.
- "2" -- I'm not in gradeschool anymore

opt.guicursor = {
  "n-v:block",
  "i-c-ci-ve:ver25",
  "r-cr:hor20",
  "o:hor50",
  "i:blinkwait700-blinkoff400-blinkon250-Cursor/lCursor",
  "sm:block-blinkwait175-blinkoff150-blinkon175",
}

-- window-local options
window_options = {
  numberwidth = 2,
  number = true,
  relativenumber = true,
  linebreak = true,
  cursorline = true,
  foldenable = false,
}

for k, v in pairs(window_options) do
  vim.wo[k] = v
end
Enter fullscreen mode Exit fullscreen mode

filetype

-- Filename: filetype.lua
-- Last Change: Wed, 25 Oct 2023 - 05:49

-- lua file detection feature:
-- https://github.com/neovim/neovim/pull/16600#issuecomment-990409210

-- filetype.lua is sourced before filetype.vim so any filetypes defined in
-- filetype.lua will take precedence.

-- on my init.lua i make a require to this file, so then I can place
-- it on my ~/.config/nvim/lua/core/ folder

vim.g.do_filetype_lua = 1
--vim.g.did_load_filetypes = 0

vim.filetype.add({
  extension = {
    conf = "conf",
    config = "conf",
    md = "markdown",
    lua = "lua",
    sh = "sh",
    zsh = "sh",
    h = function(path, bufnr)
      if vim.fn.search("\\C^#include <[^>.]\\+>$", "nw") ~= 0 then
        return "cpp"
      end
      return "c"
    end,
  },

  pattern = {
    ["^\\.(?:zsh(?:rc|env)?)$"] = "sh",
  },

  filename = {
    ["TODO"] = "markdown",
    [".git/config"] = "gitconfig",
    -- ["~/.dotfiles/zsh/.zshrc"] = "sh",
    -- ["~/.zshrc"] = "sh",
    -- [ "~/.config/mutt/muttrc"] = "muttrc",
    ["README$"] = function(path, bufnr)
      if string.find("#", vim.api.nvim_buf_get_lines(bufnr, 0, 1, true)) then
        return "markdown"
      end
      -- no return means the filetype won't be set and to try the next method
    end,
  },
})
Enter fullscreen mode Exit fullscreen mode

keymaps

-- Filename: keymaps.lua
-- Last Change: Tue, 11 Jul 2023 - 16:00

local map = require('core.utils').map

-- Set space as my leader key
map('', '<Space>', '<Nop>')
vim.g.mapleader = ' '
vim.g.maplocalleader = ' '

vim.keymap.set('n', '<c-k>',
  function()
    local word = vim.fn.expand("<cword>")
    vim.cmd('help ' .. word)
  end,
  { desc = 'help for current word' }
)

--{ silent = false, noremap = true, desc = 'toggles diagnostic'})
map('n', '<leader>l', '<cmd>Lazy<cr>', { desc = 'Lazy' })
map('n', '<Delete>', '<cmd>:update!<CR>', { desc = 'Save file if it has changed' })
map('n', '<c-s>', '<cmd>:update!<CR>', { desc = 'Save file if it has changed' })
map('n', '<F9>', '<cmd>:update!<CR>', { desc = 'Save file if it has changed' })

-- discard buffer
-- fixing a temporary issue:
-- https://github.com/dstein64/nvim-scrollview/issues/10
map('n', '<leader>x', ':wsh | up | sil! bd<cr>', { silent = true })
map('n', '<leader>w', ':bw!<cr>', { silent = true })

map('n', 'gl', '`.', { desc = 'Jump to the last changeoint' })

-- map('n',  '>',  '>>', { desc = "faster indent unindent" } )
-- map('n',  '<',  '<<', { desc = "faster indent unindent" } )
map('v', '<', '<gv', { desc = 'Reselect after < on visual mode' })
map('v', '>', '>gv', { desc = 'Reselect after > on visual mode' })

map(
  'n',
  '<leader>d',
  '<cmd>lua require("core.utils").toggle_diagnostics()<cr>',
  { desc = 'enable/disable diagnostcs', silent = true }
)

-- quickfix mappings
map('n', '[q', ':cprevious<CR>')
map('n', ']q', ':cnext<CR>')
map('n', ']Q', ':clast<CR>')
map('n', '[Q', ':cfirst<CR>')
map('n', '[b', ':bprevious<CR>')
map('n', ']b', ':bnext<CR>')

-- " Move to previous/next
-- nnoremap <silent>    <A-,> <Cmd>BufferPrevious<CR>
-- nnoremap <silent>    <A-.> <Cmd>BufferNext<CR>
map('n', '<A-,>', '<Cmd>BufferPrevious<CR>')
map('n', '<A-.>', '<Cmd>BufferNext<CR>')

-- Navigate buffers
map('n', '<M-,>', ':bnext<CR>')
map('n', '<M-.>', ':bprevious<CR>')

map('n', 'Y', 'yg_', { desc = 'Copy until the end of line' })

-- Make the dot command work as expected in visual mode (via
-- https://www.reddit.com/r/vim/comments/3y2mgt/
map('v', '.', ':norm .<cr>', { desc = 'Repear normal command in visual' })

-- Line bubbling
-- Move selected line / block of text in visual mode
map('x', 'K', ":move '<-2<CR>gv-gv", { noremap = true, silent = true })
map('x', 'J', ":move '>+1<CR>gv-gv", { noremap = true, silent = true })

map('n', "'", '`')
map('n', '`', "'")

vim.keymap.set('n', '<A-d>', '<cmd>Delblank<cr>', { desc = 'remove consecutive blank lines' })

-- vim.keymap.set('n', '<cr>', function()
--   if vim.fs.isfile(vim.fn.expand('<cfile>')) == true then
--     vim.api.nvim_feedkeys('gf', 'n', false)
--   else
--     vim.api.nvim_feedkeys('<cr>', 'n', false)
--   end
-- end, {})

-- vim.keymap.set("n", "<cr>", function()
--  local path = vim.fn.expand("<cfile>")
--  local buf = vim.api.nvim_get_current_buf()
--  local cwd = vim.api.nvim_buf_get_name(buf):match("(.*/)")
--  local handler = io.open(cwd .. path)
--  if handler == nil then
--   return "<cr>"
--  end
--  handler:close()
--  return "gf"
-- end, {})

-- empty lines go to black hole register
vim.keymap.set('n', 'dd', function()
  if vim.api.nvim_get_current_line():match('^%s*$') then
    vim.api.nvim_feedkeys('"_dd', 'n', false)
  else
    vim.api.nvim_feedkeys('dd', 'n', false)
  end
end)

vim.keymap.set('n', '<M-5>', function()
  -- https://stackoverflow.com/a/47074633
  -- https://codereview.stackexchange.com/a/282183

  local results = {}
  local buffers = vim.api.nvim_list_bufs()

  for _, buffer in ipairs(buffers) do
    if vim.api.nvim_buf_is_loaded(buffer) then
      local filename = vim.api.nvim_buf_get_name(buffer)
      if filename ~= '' then
        table.insert(results, filename)
      end
    end
  end
  curr_buf = vim.api.nvim_buf_get_name(0)
  if #results > 1 or curr_buf == '' then
    vim.cmd('bd')
  else
    vim.cmd('quit')
  end
end, { silent = false, desc = 'bd or quit' })

-- alternate file mapping (add silent true)
map(
  'n',
  '<bs>',
  [[:<c-u>exe v:count ? v:count . 'b' : 'b' . (bufloaded(0) ? '#' : 'n')<cr>]],
  { silent = true, noremap = true }
)

map('n', '<M-,>', '<cmd>BufferLineCyclePrev<cr>', { desc = 'Prev buffer' })
map('n', '<M-.>', '<cmd>BufferLineCycleNext<cr>', { desc = 'Next buffer' })

-- toggle number/relative number
map('n', '<M-n>', '<cmd>let [&nu, &rnu] = [!&rnu, &nu+&rnu==1]<cr>')

-- line text-objects
-- https://vimrcfu.com/snippet/269
map('o', 'al', [[v:count==0 ? ":<c-u>normal! 0V$h<cr>" : ":<c-u>normal! V" . (v:count) . "jk<cr>" ]], { expr = true })
map('v', 'al', [[v:count==0 ? ":<c-u>normal! 0V$h<cr>" : ":<c-u>normal! V" . (v:count) . "jk<cr>" ]], { expr = true })
map('o', 'il', [[v:count==0 ? ":<c-u>normal! ^vg_<cr>" : ":<c-u>normal! ^v" . (v:count) . "jkg_<cr>"]], { expr = true })
map('v', 'il', [[v:count==0 ? ":<c-u>normal! ^vg_<cr>" : ":<c-u>normal! ^v" . (v:count) . "jkg_<cr>"]], { expr = true })

-- other interesting text objects
-- reference: https://www.reddit.com/r/vim/comments/adsqnx/comment/edjw792
-- TODO: detect if we are over the first char and jump to the right
local chars = { '_', '-', '.', ':', ',', ';', '<bar>', '/', '<bslash>', '*', '+', '%', '#', '`' }
for k, v in ipairs(chars) do
  map('x', 'i' .. v, ':<C-u>norm! T' .. v .. 'vt' .. v .. '<CR>')
  map('x', 'a' .. v, ':<C-u>norm! F' .. v .. 'vf' .. v .. '<CR>')
  map('o', 'a' .. v, ':normal! va' .. v .. '<CR>')
  map('o', 'i' .. v, ':normal! vi' .. v .. '<CR>')
end

-- cnoremap <expr> <c-n> wildmenumode() ? "\<c-n>" : "\<down>"
-- cnoremap <expr> <c-p> wildmenumode() ? "\<c-p>" : "\<up>"
map('c', '<c-n>', [[wildmenumode() ? "\<c-n>" : "\<down>"]], { expr = true })
map('c', '<c-p>', [[wildmenumode() ? "\<c-p>" : "\<up>"]], { expr = true })

-- It adds motions like 25j and 30k to the jump list, so you can cycle
-- through them with control-o and control-i.
-- source: https://www.vi-improved.org/vim-tips/
map('n', 'j', [[v:count ? (v:count > 5 ? "m'" . v:count : '') . 'j' : 'gj']], { expr = true })
map('n', 'k', [[v:count ? (v:count > 5 ? "m'" . v:count : '') . 'k' : 'gk']], { expr = true })

map('n', '<leader>ci', '<cmd> lua vim.diagnostic.open_float()<cr>')

-- nvim file
map('n', '<Leader>n', "<cmd>lua require('core.files').nvim_files()<CR>")
map('n', '<F6>', "<cmd>lua require('core.colors').choose_colors()<cr>", { desc = 'Choose colorScheme' })

map('n', 'c*', '*<c-o>cgn')
map('n', 'c#', '#<c-o>cgn')

map('n', 'gl', '`.')
map('n', '<leader>=', '<cmd>Reindent<cr>', { desc = 'Reindent current file' })

local myvimrc = vim.env.MYVIMRC

map('n', '<Leader>v', '<cmd>drop ' .. myvimrc .. '<CR>')
map('n', '<Leader>z', '<cmd>drop ~/.zshrc<CR>')

map('i', '<C-r>+', '<C-r><C-o>+', { desc = 'Insert clipboard keeping indentation' })
map('i', '<C-r>*', '<C-r><C-o>*', { desc = 'Insert primary clipboard keeping indentation' })
map('i', '<S-Insert>', '<C-r><C-o>*', { desc = 'Insert primary clipboard keeping indentation' })
map('i', '<leader>+', '<C-r><C-o>+', { desc = 'Insert clipboard keeping indentation' })
map('i', '<S-Insert>', '<C-r><C-o>*', { desc = 'Insert clipboard keeping indentation' })

vim.keymap.set("n", "sx", "<cmd>lua require('substitute.exchange').operator({motion = 'iw'})<cr>", { noremap = true })
vim.keymap.set("n", "sxx", "<cmd>lua require('substitute.exchange').line<cr>", { noremap = true })
vim.keymap.set("x", "X", "<cmd>lua require('substitute.exchange').visual<cr>", { noremap = true })
vim.keymap.set("n", "sxc", "<cmd>lua require('substitute.exchange').cancel<cr>", { noremap = true })

map('n', '<M-p>', '"+gP')
map('v', '<M-p>', '"+gP')
map('i', '<M-p>', '<C-r><C-o>+')
map('v', '<leader>y', '"+y')
map('n', '<c-c>', '<cmd>%y+<cr>', { desc = 'copy file to clipboard', silent = true })
map('n', '<c-m-f>', '<cmd>Format<cr>', { desc = 'Reformat keeping cursor position' })

map('i', '.', '.<c-g>u')
map('i', '!', '!<c-g>u')
map('i', '?', '?<c-g>u')
map('i', ';', ';<c-g>u')
map('i', ':', ':<c-g>u')
map('i', ']', ']<c-g>u')
map('i', '}', '}<c-g>u')

-- map('n', 'n', 'n:lua require("core.utils").flash_cursorline()<CR><CR>')
-- map('n', 'N', 'N:lua require("core.utils").flash_cursorline()<CR><CR>')
-- map('n', 'n', 'n:lua require("neoscroll").zz(300)<cr>', { desc = "middle of screen"})
-- map('n', 'N', 'N:lua require("neoscroll").zz(300)<cr>', { desc = "middle of screen"})
-- map('n', '*', '*:lua require("core.utils").flash_cursorline()<CR><CR>')
-- map('n', '#', '#:lua require("core.utils").flash_cursorline()<CR><CR>')

-- map(
--   'n',
--   'n',
--   "n<cmd>lua require('core.utils').flash_cursorline()<cr><cr>",
--   { desc = 'center the next match', silent = true }
-- )
--
-- map(
--   'n',
--   'N',
--   "N<cmd>:lua require('core.utils').flash_cursorline()<cr><cr>",
--   { desc = 'center the next match', silent = true }
-- )

map('n', 'J', 'mzJ`z')

map(
  'n',
  '<C-l>',
  [[ (&hls && v:hlsearch ? ':nohls' : ':set hls')."\n" <BAR> redraw<CR>]],
  { silent = true, expr = true }
)

map('c', '<C-a>', '<home>')
map('c', '<C-e>', '<end>')

map('n', '<F8>', [[<cmd>lua require("core.files").xdg_config()<cr>]], { silent = true })

-- Quick write
-- map('n', '<leader>d', '<cmd>bd<CR>')

-- map("n", "<C-M-o>", ':lua require("telescope.builtin").oldfiles()<cr>') -- already mapped on which-key
map('n', '<C-M-o>', ':lua require("core.files").search_oldfiles()<cr>', { desc = 'Serach oldfiles' }) -- already mapped on which-key
-- map("n", "<c-p>", [[<cmd>lua require("telescope.builtin").find_files{cwd = "~/.dotfiles/wiki"}<cr>]], { silent = true })
map(
  'n',
  '<c-p>',
  [[<cmd>lua require("telescope.builtin").find_files({search_dirs = {"~/.config", "~/.dotfiles"}})<cr>]],
  { silent = true }
)
--map("n", "<leader>b", [[<cmd>lua require('telescope.builtin').buffers()<cr>]], { silent = true })
-- map("n", "<leader>b", ":buffers<CR>:buffer<Space>", {desc = "Swich buffers"})
-- nnoremap <F5> :buffers<CR>:buffer<Space>

vim.keymap.set(
  'n',
  '<C-d>',
  [[<Cmd>lua vim.cmd('normal! <C-d>'); MiniAnimate.execute_after('scroll', 'normal! zvzz')<CR>]]
)
vim.keymap.set(
  'n',
  '<C-u>',
  [[<Cmd>lua vim.cmd('normal! <C-u>'); MiniAnimate.execute_after('scroll', 'normal! zvzz')<CR>]]
)

-- Resize splits with arrow keys
map('n', '<C-Up>', '<cmd>resize +2<CR>')
map('n', '<C-Down>', '<cmd>resize -2<CR>')
map('n', '<C-Left>', '<cmd>vertical resize -2<CR>')
map('n', '<C-Right>', '<cmd>vertical resize +2<CR>')

local open_command = 'xdg-open'
if vim.fn.has('mac') == 1 then
  open_command = 'open'
end

local function url_repo()
  local cursorword = vim.fn.expand('<cfile>')
  if string.find(cursorword, '^[a-zA-Z0-9-_.]*/[a-zA-Z0-9-_.]*$') then
    cursorword = 'https://github.com/' .. cursorword
  end
  return cursorword or ''
end

vim.keymap.set('n', 'gx', function()
  vim.fn.jobstart({ open_command, url_repo() }, { detach = true })
end, { silent = true })

vim.keymap.set('n', '0', function()
  if vim.fn.reg_recording() ~= "" then
    vim.api.nvim_feedkeys('0', 'n', true)
  else
    local pos = vim.fn.col('.')
    if pos == 1 then
      vim.api.nvim_feedkeys('^', 'n', true)
    elseif pos == vim.fn.col('$') - 1 then
      vim.api.nvim_feedkeys('0', 'n', true)
    else
      vim.api.nvim_feedkeys('$', 'n', true)
    end
  end
end, { desc = 'smart zero movement' })

map('n', '-', '<cmd>split<cr>')
map('n', '|', '<cmd>vsplit<cr>')

map(
  'n',
  '<leader>L',
  '<cmd>lua require("luasnip.loaders.from_lua").load({paths = "~/.config/nvim/luasnip/"})<cr>',
  { desc = 'reload snippets', silent = false }
)

-- -- Insert 'n' lines below current line staying in normal mode (e.g. use 5<leader>o)
-- vim.keymap.set("n", "<m-o>", function()
--   return "m`" .. vim.v.count .. "o<Esc>``"
-- end, { expr = true })

-- -- Insert 'n' lines above current line staying in normal mode (e.g. use 5<leader>O)
-- vim.keymap.set("n", "<m-O>", function()
--   return "m`" .. vim.v.count .. "O<Esc>``"
-- end, { expr = true })

map("n", "<m-o>", "<cmd>Telescope oldfiles<cr>", { desc = "telescope oldfiles" })

map('n', '<leader>s', '<cmd>LuaSnipEdit<cr>', { desc = 'Edit snippets' })

map('n', '<Leader><CR>', '<cmd>drop ~/.config/nvim/luasnip/snippets.lua<cr>', { silent = true, noremap = true })

map('i', 'jk', '<Esc>', { desc = 'Exit insert mode' })
map('i', 'kj', '<Esc>', { desc = 'Exit insert mode' })

vim.keymap.set('n', '<leader>ll', function()
  return require('lazy').home()
end)
vim.keymap.set('n', '<leader>lu', function()
  return require('lazy').update()
end)
vim.keymap.set('n', '<leader>ls', function()
  return require('lazy').sync()
end)
vim.keymap.set('n', '<leader>lL', function()
  return require('lazy').log()
end)
vim.keymap.set('n', '<leader>lc', function()
  return require('lazy').clean()
end)
vim.keymap.set('n', '<leader>lp', function()
  return require('lazy').profile()
end)
Enter fullscreen mode Exit fullscreen mode

autocommands

-- ~/.config/nvim/lua/hore/autocommands.lua
-- Mon, 10 Jul 2023 07:13:37

-- Define local variables
local augroup = vim.api.nvim_create_augroup
local autocmd = vim.api.nvim_create_autocmd
local user_cmd = vim.api.nvim_create_user_command

-- the formatonsave does the job
-- augroup('write_pre', { clear = true })
-- autocmd('BufWritePre', {
--   callback = function()
--     local cursor_pos = vim.fn.getpos('.')
--     vim.cmd('%s/\\s\\+$//e')
--     vim.fn.setpos('.', cursor_pos)
--   end,
--   group = 'write_pre',
--   desc = 'Remove trailing whitespaces',
-- })

augroup('buf_empty', { clear = true })
autocmd({ "BufEnter" }, {
  group = 'buf_empty',
  pattern = { "" },
  callback = function()
    local buf_ft = vim.bo.filetype
    if buf_ft == "" or buf_ft == nil then
      vim.cmd [[
      nnoremap <silent> <buffer> q :close<CR>
      set nobuflisted
    ]]
    end
  end,
})

-- Highlight text on yank
augroup('YankHighlight', { clear = true })
autocmd('TextYankPost', {
  group = 'YankHighlight',
  callback = function()
    vim.highlight.on_yank { higroup = 'IncSearch', timeout = '700' }
  end,
  desc = 'Highlight yanked text',
})

augroup('lsp_disable_diagnostic', { clear = true })
autocmd('BufEnter', {
  group = 'lsp_disable_diagnostic',
  pattern = '*',
  command = 'lua vim.diagnostic.disable()',
  desc = 'Disable diagnostic for a while',
})

augroup('formatonsave', { clear = true })
autocmd('BufWritePost', {
  group = 'formatonsave',
  desc = 'Trigger format on save',
  pattern = { '*.lua', '*.py', '*.rb', '*.rs', '*.ts', '*.tsx', '*.sh', '*.md' },
  callback = function()
    vim.lsp.buf.format()
    vim.cmd('normal zz')
  end,
})

augroup('MatchRedundantSpaces', { clear = true })
autocmd('InsertLeave', {
  pattern = '*',
  callback = function()
    vim.cmd([[highlight RedundantSpaces ctermbg=red guibg=red]])
    vim.cmd([[match RedundantSpaces /\s\+$/]])
  end,
  desc = 'Higlight extra spaces',
})

augroup('clear_matches', { clear = true })
autocmd('InsertEnter', {
  pattern = '*',
  callback = function()
    vim.cmd([[call clearmatches()]])
    vim.cmd([[highlight RedundantSpaces ctermbg=red guibg=red]])
    vim.cmd([[set nohls]])
  end,
  desc = 'Do not show extra spaces during typing',
})

augroup('yankpost', { clear = true })
autocmd({ 'VimEnter', 'CursorMoved' }, {
  group = 'yankpost',
  pattern = '*',
  callback = function()
    cursor_pos = vim.fn.getpos('.')
  end,
  desc = 'Stores cursor position',
})

autocmd('TextYankPost', {
  pattern = '*',
  group = 'yankpost',
  callback = function()
    if vim.v.event.operator == 'y' then
      vim.fn.setpos('.', cursor_pos)
    end
  end,
})

augroup('equalwindow', { clear = true })
autocmd({ 'FileType' }, {
  pattern = 'help',
  group = 'equalwindow',
  callback = function ()
    vim.schedule(function ()
      vim.cmd('tabdo wincmd =')
    end)
  end
})

augroup('start_luasnip', { clear = true })
autocmd({ "CursorHold" }, {
  group = 'start_luasnip',
  callback = function()
    local status_ok, luasnip = pcall(require, "luasnip")
    if not status_ok then
      return
    end
    if luasnip.expand_or_jumpable() then
      -- ask maintainer for option to make this silent
      -- luasnip.unlink_current()
      vim.cmd [[silent! lua require("luasnip").unlink_current()]]
    end
  end,
})

-- Close man and help with just <q>
autocmd('FileType', {
  pattern = {
    'help',
    'man',
    'lspinfo',
    'checkhealth',
  },
  callback = function(event)
    vim.bo[event.buf].buflisted = false
    vim.keymap.set('n', 'q', '<cmd>q<cr>', { buffer = event.buf, silent = true })
  end,
})

-- Auto create dir when saving a file where some intermediate directory does not exist
augroup('write_pre', { clear = true })
autocmd('BufWritePre', {
  group = 'write_pre',
  callback = function(event)
    if event.match:match('^%w%w+://') then
      return
    end
    local file = vim.loop.fs_realpath(event.match) or event.match
    vim.fn.mkdir(vim.fn.fnamemodify(file, ':p:h'), 'p')
  end,
})

-- Check for spelling in text filetypes and enable wrapping, and set gj and gk keymaps
autocmd('FileType', {
  pattern = {
    'gitcommit',
    'markdown',
    'text',
  },
  callback = function()
    local opts = { noremap = true, silent = true }
    vim.opt_local.spell = true
    vim.opt_local.wrap = true
    vim.api.nvim_buf_set_keymap(0, 'n', 'j', 'gj', opts)
    vim.api.nvim_buf_set_keymap(0, 'n', 'k', 'gk', opts)
  end,
})

augroup('bufcheck', { clear = true })
autocmd('BufReadPost', {
  group = 'bufcheck',
  callback = function()
    local exclude = { 'gitcommit' }
    local buf = vim.api.nvim_get_current_buf()
    if vim.tbl_contains(exclude, vim.bo[buf].filetype) then
      return
    end
    local mark = vim.api.nvim_buf_get_mark(0, '"')
    local lcount = vim.api.nvim_buf_line_count(0)
    if mark[1] > 0 and mark[1] <= lcount then
      pcall(vim.api.nvim_win_set_cursor, 0, mark)
      vim.api.nvim_feedkeys('zz', 'n', true)
    end
  end,
  desc = 'Go to the last loc when opening a buffer',
})

-- Check if the file needs to be reloaded when it's changed
augroup('userconf', { clear = true })
autocmd({ 'FocusGained', 'TermClose', 'TermLeave' }, {
  command = 'checktime',
  group = 'userconf',
})

-- Toggle relative numbers based on certain events
augroup('GainFocus', { clear = true })
autocmd({ 'BufEnter', 'FocusGained', 'InsertLeave', 'CmdlineLeave', 'WinEnter' }, {
  pattern = '*',
  group = 'GainFocus',
  callback = function()
    if vim.o.nu and vim.api.nvim_get_mode().mode ~= 'i' then
      vim.opt.relativenumber = true
    end
  end,
})

autocmd({ 'BufLeave', 'FocusLost', 'InsertEnter', 'CmdlineEnter', 'WinLeave' }, {
  pattern = '*',
  group = 'GainFocus',
  callback = function()
    if vim.o.nu then
      vim.opt.relativenumber = false
      vim.cmd('redraw')
    end
  end,
})

-- Set cmdheight to 1 when recording, and put it back to normal when it stops
augroup('record_action', { clear = true })
autocmd('RecordingEnter', {
  callback = function()
    vim.opt_local.cmdheight = 1
  end,
  group = 'record_action',
})

autocmd('RecordingLeave', {
  callback = function()
    vim.opt_local.cmdheight = 0
  end,
  group = 'record_action',
})

augroup('make-executable', { clear = true })
autocmd('BufWritePost', {
  group = 'make-executable',
  pattern = { '*.sh', '*.py' },
  command = [[!chmod +x %]],
  desc = 'Make files ended with *.sh, *.py executable',
})
Enter fullscreen mode Exit fullscreen mode

autocommands

-- ~/.config/nvim/lua/hore/autocommands.lua
-- Mon, 10 Jul 2023 07:13:37

-- Define local variables
local augroup = vim.api.nvim_create_augroup
local autocmd = vim.api.nvim_create_autocmd
local user_cmd = vim.api.nvim_create_user_command

-- the formatonsave does the job
-- augroup('write_pre', { clear = true })
-- autocmd('BufWritePre', {
--   callback = function()
--     local cursor_pos = vim.fn.getpos('.')
--     vim.cmd('%s/\\s\\+$//e')
--     vim.fn.setpos('.', cursor_pos)
--   end,
--   group = 'write_pre',
--   desc = 'Remove trailing whitespaces',
-- })

augroup('buf_empty', { clear = true })
autocmd({ "BufEnter" }, {
  group = 'buf_empty',
  pattern = { "" },
  callback = function()
    local buf_ft = vim.bo.filetype
    if buf_ft == "" or buf_ft == nil then
      vim.cmd [[
      nnoremap <silent> <buffer> q :close<CR>
      set nobuflisted
    ]]
    end
  end,
})

-- Highlight text on yank
augroup('YankHighlight', { clear = true })
autocmd('TextYankPost', {
  group = 'YankHighlight',
  callback = function()
    vim.highlight.on_yank { higroup = 'IncSearch', timeout = '700' }
  end,
  desc = 'Highlight yanked text',
})

augroup('lsp_disable_diagnostic', { clear = true })
autocmd('BufEnter', {
  group = 'lsp_disable_diagnostic',
  pattern = '*',
  command = 'lua vim.diagnostic.disable()',
  desc = 'Disable diagnostic for a while',
})

augroup('formatonsave', { clear = true })
autocmd('BufWritePost', {
  group = 'formatonsave',
  desc = 'Trigger format on save',
  pattern = { '*.lua', '*.py', '*.rb', '*.rs', '*.ts', '*.tsx', '*.sh', '*.md' },
  callback = function()
    vim.lsp.buf.format()
    vim.cmd('normal zz')
  end,
})

augroup('MatchRedundantSpaces', { clear = true })
autocmd('InsertLeave', {
  pattern = '*',
  callback = function()
    vim.cmd([[highlight RedundantSpaces ctermbg=red guibg=red]])
    vim.cmd([[match RedundantSpaces /\s\+$/]])
  end,
  desc = 'Higlight extra spaces',
})

augroup('clear_matches', { clear = true })
autocmd('InsertEnter', {
  pattern = '*',
  callback = function()
    vim.cmd([[call clearmatches()]])
    vim.cmd([[highlight RedundantSpaces ctermbg=red guibg=red]])
    vim.cmd([[set nohls]])
  end,
  desc = 'Do not show extra spaces during typing',
})

augroup('yankpost', { clear = true })
autocmd({ 'VimEnter', 'CursorMoved' }, {
  group = 'yankpost',
  pattern = '*',
  callback = function()
    cursor_pos = vim.fn.getpos('.')
  end,
  desc = 'Stores cursor position',
})

autocmd('TextYankPost', {
  pattern = '*',
  group = 'yankpost',
  callback = function()
    if vim.v.event.operator == 'y' then
      vim.fn.setpos('.', cursor_pos)
    end
  end,
})

augroup('equalwindow', { clear = true })
autocmd({ 'FileType' }, {
  pattern = 'help',
  group = 'equalwindow',
  callback = function ()
    vim.schedule(function ()
      vim.cmd('tabdo wincmd =')
    end)
  end
})

augroup('start_luasnip', { clear = true })
autocmd({ "CursorHold" }, {
  group = 'start_luasnip',
  callback = function()
    local status_ok, luasnip = pcall(require, "luasnip")
    if not status_ok then
      return
    end
    if luasnip.expand_or_jumpable() then
      -- ask maintainer for option to make this silent
      -- luasnip.unlink_current()
      vim.cmd [[silent! lua require("luasnip").unlink_current()]]
    end
  end,
})

-- Close man and help with just <q>
autocmd('FileType', {
  pattern = {
    'help',
    'man',
    'lspinfo',
    'checkhealth',
  },
  callback = function(event)
    vim.bo[event.buf].buflisted = false
    vim.keymap.set('n', 'q', '<cmd>q<cr>', { buffer = event.buf, silent = true })
  end,
})

-- Auto create dir when saving a file where some intermediate directory does not exist
augroup('write_pre', { clear = true })
autocmd('BufWritePre', {
  group = 'write_pre',
  callback = function(event)
    if event.match:match('^%w%w+://') then
      return
    end
    local file = vim.loop.fs_realpath(event.match) or event.match
    vim.fn.mkdir(vim.fn.fnamemodify(file, ':p:h'), 'p')
  end,
})

-- Check for spelling in text filetypes and enable wrapping, and set gj and gk keymaps
autocmd('FileType', {
  pattern = {
    'gitcommit',
    'markdown',
    'text',
  },
  callback = function()
    local opts = { noremap = true, silent = true }
    vim.opt_local.spell = true
    vim.opt_local.wrap = true
    vim.api.nvim_buf_set_keymap(0, 'n', 'j', 'gj', opts)
    vim.api.nvim_buf_set_keymap(0, 'n', 'k', 'gk', opts)
  end,
})

augroup('bufcheck', { clear = true })
autocmd('BufReadPost', {
  group = 'bufcheck',
  callback = function()
    local exclude = { 'gitcommit' }
    local buf = vim.api.nvim_get_current_buf()
    if vim.tbl_contains(exclude, vim.bo[buf].filetype) then
      return
    end
    local mark = vim.api.nvim_buf_get_mark(0, '"')
    local lcount = vim.api.nvim_buf_line_count(0)
    if mark[1] > 0 and mark[1] <= lcount then
      pcall(vim.api.nvim_win_set_cursor, 0, mark)
      vim.api.nvim_feedkeys('zz', 'n', true)
    end
  end,
  desc = 'Go to the last loc when opening a buffer',
})

-- Check if the file needs to be reloaded when it's changed
augroup('userconf', { clear = true })
autocmd({ 'FocusGained', 'TermClose', 'TermLeave' }, {
  command = 'checktime',
  group = 'userconf',
})

-- Toggle relative numbers based on certain events
augroup('GainFocus', { clear = true })
autocmd({ 'BufEnter', 'FocusGained', 'InsertLeave', 'CmdlineLeave', 'WinEnter' }, {
  pattern = '*',
  group = 'GainFocus',
  callback = function()
    if vim.o.nu and vim.api.nvim_get_mode().mode ~= 'i' then
      vim.opt.relativenumber = true
    end
  end,
})

autocmd({ 'BufLeave', 'FocusLost', 'InsertEnter', 'CmdlineEnter', 'WinLeave' }, {
  pattern = '*',
  group = 'GainFocus',
  callback = function()
    if vim.o.nu then
      vim.opt.relativenumber = false
      vim.cmd('redraw')
    end
  end,
})

-- Set cmdheight to 1 when recording, and put it back to normal when it stops
augroup('record_action', { clear = true })
autocmd('RecordingEnter', {
  callback = function()
    vim.opt_local.cmdheight = 1
  end,
  group = 'record_action',
})

autocmd('RecordingLeave', {
  callback = function()
    vim.opt_local.cmdheight = 0
  end,
  group = 'record_action',
})

augroup('make-executable', { clear = true })
autocmd('BufWritePost', {
  group = 'make-executable',
  pattern = { '*.sh', '*.py' },
  command = [[!chmod +x %]],
  desc = 'Make files ended with *.sh, *.py executable',
})
Enter fullscreen mode Exit fullscreen mode

bootstrap

-- Install lazy.nvim automatically
-- Last Change: Sat, 09 Sep 2023 - 15:24:19

local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim'
if not vim.loop.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)

local opts = {
    git = { log = { '--since=3 days ago' } },
    ui = { custom_keys = { false } },
    install = { colorscheme = { 'tokyonight' } },
    performance = {
        rtp = {
            disabled_plugins = {
                'gzip',
                'netrwPlugin',
                'tarPlugin',
                'tohtml',
                'tutor',
                'zipPlugin',
                'rplugin',
                'editorconfig',
                'matchparen',
                'matchit',
            },
        },
    },
checker = { enabled = false },
}

-- Load the plugins and options
require('lazy').setup('plugins', opts)
Enter fullscreen mode Exit fullscreen mode

commands

-- Filename: /home/sergio/.config/nvim/lua/core/commands.lua
-- Last Change: Fri, 09 Dec 2022 - 19:18
-- vim:set ft=lua nolist softtabstop=2 shiftwidth=2 tabstop=2 expandtab:

local user_cmd = vim.api.nvim_create_user_command

user_cmd('LspSignatre', 'lua vim.lsp.buf.signature_help()', { nargs = '+' })
user_cmd('LspHover', 'lua vim.lsp.buf.hover()', { nargs = "+" })

-- commands and abbreviations
user_cmd('ClearBuffer', 'enew | bd! #', { nargs = 0, bang = true })
user_cmd('CopyUrl', 'let @+=expand("<cfile>")', { nargs = 0, bang = true })
user_cmd('HarponDel', ':lua require("harpoon.mark").rm_file()', { nargs = 0, bang = true })
user_cmd('BlockwiseZero', ':lua require("core.utils").blockwise_register("0")<CR>', { nargs = '?', bang = false })
user_cmd('BlockwisePlus', ':lua require("core.utils").blockwise_register("+")<CR>', { nargs = '?', bang = false })
user_cmd('BlockwisePrimary', ':lua require("core.utils").blockwise_register("*")<CR>', { nargs = '?', bang = false })

vim.cmd([[cnoreab Bz BlockwiseZero]])
vim.cmd([[cnoreab B+ BlockwisePlus]])
vim.cmd([[cnoreab B* BlockwisePrimary]])

user_cmd('Dos2unix', ':lua require("core.utils").dosToUnix()<CR>', { nargs = 0, bang = true })
user_cmd('ToggleBackground', 'lua require("core.utils").toggle_background()<cr>', { nargs = 0 })
user_cmd('ToggleSpell', 'lua require("core.utils").toggle_spell()<cr>', { nargs = 0 })
user_cmd('Wiki', 'lua require("core.files").wiki()<CR>', { desc = 'Search on my wiki'})

user_cmd("LuaSnipEdit", function()
  require("core.utils").edit_snippets()
end, {})

user_cmd("Cor", "lua print(vim.g.colors_name)<cr>", { desc = "show current colorscheme"})

user_cmd('SnipList', function()
  pcall(function()
    require('core.utils').list_snips()
  end)
end, {})

vim.cmd([[cnoreab Cb ClearBuffer]])
vim.cmd([[cabbrev vb vert sb]]) --vertical split buffer :vb <buffer>
vim.cmd([[cnoreab cls Cls]])
vim.cmd([[command! Cls lua require("core.utils").preserve('%s/\\s\\+$//ge')]])
vim.cmd([[command! Reindent lua require('core.utils').preserve("sil keepj normal! gg=G")]])
vim.cmd([[command! Format lua require('core.utils').preserve("lua vim.lsp.buf.format()")]])

vim.cmd([[highlight MinhasNotas ctermbg=Yellow ctermfg=red guibg=Yellow guifg=red]])
vim.cmd([[match MinhasNotas /NOTE:/]])


-- vim.cmd([[command! BufOnly lua require('core.utils').preserve("silent! %bd|e#|bd#")]])
user_cmd('BufOnly', function()
  pcall(function()
    -- vim.fn.Preserve("exec '%bd|e#|bd#'")
    require('core.utils').preserve('silent! up|%bd|e#|bd#')
  end)
end, {})

vim.cmd([[cnoreab Bo BufOnly]])
vim.cmd([[cnoreab W w]])
vim.cmd([[cnoreab W! w!]])
vim.cmd([[command! CloneBuffer new | 0put =getbufline('#',1,'$')]])
user_cmd('CloneBuffer', "new | 0put =getbufline('#',', '$')", { nargs = 0, bang = true })
-- vim.cmd([[command! Mappings drop ~/.config/nvim/lua/user/mappings.lua]])
vim.cmd([[command! Scratch new | setlocal bt=nofile bh=wipe nobl noswapfile nu]])
vim.cmd([[syntax sync minlines=64]]) --  faster syntax hl

user_cmd('Delblank', function()
  require('core.utils').squeeze_blank_lines()
end, { desc = 'Squeeze blank lines', nargs = 0, bang = true })

user_cmd('ToggleDiagnostics', function()
  require('core.utils').toggle_diagnostics()
end, { desc = 'Toggle lsp diagnostic', nargs = 0, bang = true })

user_cmd('Transparency', function()
  require('core.utils').toggle_transparency()
end, { desc = 'Toggle transparency', nargs = 0, bang = true })

user_cmd('MiniStarter', function()
  MiniStarter.open()
end, { desc = 'Fire MiniStarter' })

user_cmd('Old', 'Telescope oldfiles', { desc = 'List oldfiles (open)' })

user_cmd('Blockwise', function()
  require('core.utils').blockwise_clipboard()
end, { desc = 'Make + register blockwise', nargs = 0, bang = true })

vim.cmd([[cnoreab Bw Blockwise]])

-- Use ':Grep' or ':LGrep' to grep into quickfix|loclist
-- without output or jumping to first match
-- Use ':Grep <pattern> %' to search only current file
-- Use ':Grep <pattern> %:h' to search the current file dir
vim.cmd('command! -nargs=+ -complete=file Grep noautocmd grep! <args> | redraw! | copen')
vim.cmd('command! -nargs=+ -complete=file LGrep noautocmd lgrep! <args> | redraw! | lopen')

-- save as root, in my case I use the command 'doas'
vim.cmd([[cmap w!! w !doas tee % >/dev/null]])
vim.cmd([[command! SaveAsRoot w !doas tee %]])

-- vim.cmd([[hi ActiveWindow ctermbg=16 | hi InactiveWindow ctermbg=233]])
-- vim.cmd([[set winhighlight=Normal:ActiveWindow,NormalNC:InactiveWindow]])

-- vim.cmd('command! ReloadConfig lua require("utils").ReloadConfig()')
vim.cmd('command! ReloadConfig lua require("core.utils").ReloadConfig()')

-- inserts filename and Last Change: date
-- vim.cmd([[inoreab lc -- File: <c-r>=expand("%:p")<cr><cr>-- Last Change: <c-r>=strftime("%b %d %Y - %H:%M")<cr><cr>]])

vim.cmd('inoreabbrev Fname <c-r>=expand("%:p")<cr>')
vim.cmd('inoreabbrev Iname <c-r>=expand("%:p")<cr>')
vim.cmd('inoreabbrev fname <c-r>=expand("%:t")<cr>')
vim.cmd('inoreabbrev iname <c-r>=expand("%:t")<cr>')

vim.cmd('inoreabbrev idate <c-r>=strftime("%a, %d %b %Y %T")<cr>')
vim.cmd([[cnoreab cls Cls]])

vim.api.nvim_create_user_command('BiPolar', function(_)
  local moods_table = {
    ['true'] = 'false',
    ['false'] = 'true',
    ['on'] = 'off',
    ['off'] = 'on',
    ['Up'] = 'Down',
    ['Down'] = 'Up',
    ['up'] = 'down',
    ['down'] = 'up',
    ['enable'] = 'disable',
    ['disable'] = 'enable',
    ['no'] = 'yes',
    ['yes'] = 'no',
  }
  local cursor_word = vim.api.nvim_eval("expand('<cword>')")
  if moods_table[cursor_word] then
    vim.cmd('normal ciw' .. moods_table[cursor_word] .. '')
  end
end, { desc = 'Switch Moody Words', force = true })
Enter fullscreen mode Exit fullscreen mode

files

-- File: /home/sergio/.config/nvim/lua/files.lua
-- Last Change: Thu, 17 Mar 2022 15:05
-- https://github.com/nvim-telescope/telescope.nvim/wiki/Configuration-Recipes
-- https://youtu.be/Ua8FkgTL-94

local status_ok, telescope = pcall(require, "telescope")
if not status_ok then
  return
end

local M = {}

-- copied from https://github.com/nvim-telescope/telescope.nvim/wiki/Gallery
-- :Telescope find_files previewer=false theme=get_dropdown
local dropdown_theme = require('telescope.themes').get_dropdown({
  results_height = 20,
  -- winblend = 20;
  width = 0.6,
  prompt_title = '',
  prompt_prefix = 'Files> ',
  previewer = false,
  borderchars = {
    { '─', '│', '─', '│', '╭', '╮', '╯', '╰' },
    preview = { '─', '│', '─', '│', '╭', '╮', '╯', '╰' },
  },
})

-- searches files on ~/.config
M.xdg_config = function()
  require("telescope.builtin").find_files({
    prompt_title = "XDG-CONFIG",
    previewer = false,
    find_command={'fd','--no-ignore-vcs'},
    sorting_strategy = "ascending",
    file_ignore_patterns = { "lua-language-server", "chromium" },
    layout_config = { width = 0.7 },
    cwd = "~/.config",
    -- width = 0.6,
    layout_config = { height = 0.3 },
    layout_config = { width = 0.5 },
    results_height = 20,
    hidden = true,
    previewer = false,
    borderchars = {
      { '─', '│', '─', '│', '╭', '╮', '╯', '╰' },
      preview = { '─', '│', '─', '│', '╭', '╮', '╯', '╰' },
    },
  })
end
-- mapped to F8


-- searches files on ~/.config
M.wiki = function()
  require("telescope.builtin").find_files({
    prompt_title = "Search wiki",
    previewer = false,
    find_command={'fd','--no-ignore-vcs'},
    sorting_strategy = "ascending",
    -- file_ignore_patterns = { "lua-language-server", "chromium" },
    layout_config = { width = 0.7 },
    cwd = "~/.dotfiles/wiki/",
    -- width = 0.6,
    layout_config = { height = 0.3 },
    layout_config = { width = 0.5 },
    results_height = 20,
    hidden = true,
    previewer = false,
    borderchars = {
      { '─', '│', '─', '│', '╭', '╮', '╯', '╰' },
      preview = { '─', '│', '─', '│', '╭', '╮', '╯', '╰' },
    },
  })
end
-- mapped to F8

-- searches opened buffers
M.buffers = function()
  require("telescope.builtin").buffers({
    prompt_title = "BUFFERS",
    sorting_strategy = "ascending",
    file_ignore_patterns = { "lua-language-server", "chromium" },
    -- cwd = "~/.config",
    previewer = false,
    layout_config = { height = 0.3 },
    layout_config = { width = 0.5 },
    hidden = true,
  })
end
-- mapped to <leader>b

M.nvim_files = function()
  require("telescope.builtin").find_files({
    prompt_title = "NVIM FILES",
    previewer = false,
    find_command={'fd','--no-ignore-vcs'},
    sorting_strategy = "ascending",
    file_ignore_patterns = { ".git" },
    cwd = "~/.config/nvim",
    hidden = true,
  })
end
-- mapped to <leader>n

-- searches on ~/.dotfiles
M.search_dotfiles = function()
  require("telescope.builtin").find_files({
    prompt_title = "DOTFILES",
    find_command={'fd','--no-ignore-vcs'},
    shorten_path = true,
    sorting_strategy = "ascending",
    cwd = vim.env.DOTFILES,
    hidden = true,
    previewer = false,
    layout_config = { height = 0.3 },
    layout_config = { width = 0.5 },
  })
end
-- mapped to Ctrl-p

-- searches on ~/.dotfiles
M.search_oldfiles = function()
  require("telescope.builtin").oldfiles({
    prompt_title = "OLDFILES",
    previewer = false,
    shorten_path = true,
    sorting_strategy = "ascending",
    -- cwd = vim.env.DOTFILES,
    hidden = true,
    layout_config = { height = 0.3 },
    layout_config = { width = 0.5 },
  })
end
-- mapped to Ctrl-Alt-o

-- searches on ~/.dotfiles
M.grep_dotfiles = function()
  require("telescope.builtin").live_grep({
    prompt_title = "GREP DOTFILES",
    shorten_path = true,
    sorting_strategy = "ascending",
    cwd = vim.env.DOTFILES,
    hidden = true,
  })
end
-- mapped to

M.grep_wiki = function()
  local opts = {}
  opts.hidden = true
  opts.search_dirs = {
    "~/.dotfiles/wiki",
  }
  opts.prompt_prefix = ">"
  opts.prompt_title = "Grep Wiki"
  opts.path_display = { "smart" }
  require("telescope.builtin").live_grep(opts)
end

return M
Enter fullscreen mode Exit fullscreen mode

theme

-- File: /home/sergio/.config/nvim/lua/core/theme.lua
-- Last Change: Wed, Nov 2023/11/22 - gg12:03:46

function isDayOrNight()
  local currentTime = os.date("*t")

  local currentHour = currentTime.hour

  local startDaytimeHour = 6
  local endDaytimeHour = 18

  if currentHour >= startDaytimeHour and currentHour < endDaytimeHour then
    -- return "day"
    return "dawnfox"
  else
    -- return "night"
    return "tokyonight"
  end
end

local colorscheme = isDayOrNight()

local status_ok, _ = pcall(vim.cmd, "colorscheme " .. colorscheme)
if not status_ok then
  vim.notify("colorscheme " .. colorscheme .. " not found!")
  return
end
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
voyeg3r profile image
Sérgio Araújo

A function to make your clipboard blockwise, this will allow you paste text not bellow the current one but on its side:

M.blockwise_clipboard = function()
    vim.cmd("call setreg('+', @+, 'b')")
    -- print('set + reg: blockwise!')
    pcall(require("notify")('set + reg: blockwise!'))
end
Enter fullscreen mode Exit fullscreen mode