Skip to content

attempt to yield across C-call boundary #3

Description

@samuelfite

Starting neovim gives the following error after installing ranger.nvim:
Error detected while processing /home/sam/dotfiles/config/nvim/nvim/init.vim: line 94: E5108: Error executing lua /home/sam/.vim/plugged/libp.nvim/lua/libp/fs/uv_async.lua:17: attempt to yield across C-call boundary stack traceback: [C]: in function 'async_fn' /home/sam/.vim/plugged/libp.nvim/lua/libp/fs/uv_async.lua:17: in function 'fs_open' /home/sam/.vim/plugged/libp.nvim/lua/libp/fs/init.lua:29: in function 'is_readable' ...sam/.vim/plugged/ranger.nvim/lua/ranger/action/Rifle.lua:45: in function 'init' ...e/sam/.vim/plugged/libp.nvim/lua/libp/datatype/Class.lua:151: in function 'Rifle' .../sam/.vim/plugged/ranger.nvim/lua/ranger/action/init.lua:24: in function 'setup' /home/sam/.vim/plugged/ranger.nvim/lua/ranger.lua:29: in function 'setup' [string ":lua"]:2: in main chunk Press ENTER or type command to continue

Neovim Version:
NVIM v0.9.0 Build type: RelWithDebInfo LuaJIT 2.1.0-beta3 Compilation: /usr/bin/gcc -O2 -g -Og -g -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wvla -Wdouble-promotion -Wmissing-noreturn -Wmissing-format-attribute -Wmissing-prototypes -fno-common -Wno-unused-result -Wimplicit-fallthrough -fdiagnostics-color=auto -fstack-protector-strong -DUNIT_TESTING -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -I/usr/include/luajit-2.1 -I/usr/include -I/usr/include/luajit-2.1 -I/builddir/build/BUILD/neovim-0.9.0/redhat-linux-build/src/nvim/auto -I/builddir/build/BUILD/neovim-0.9.0/redhat-linux-build/include -I/builddir/build/BUILD/neovim-0.9.0/redhat-linux-build/cmake.config -I/builddir/build/BUILD/neovim-0.9.0/src -I/usr/include -I/usr/include -I/usr/include -I/usr/include -I/usr/include -I/usr/include -I/usr/include

ranger version:
ranger version: ranger 1.9.3 Python version: 3.11.1 (main, Jan 6 2023, 00:00:00) [GCC 12.2.1 20221121 (Red Hat 12.2.1-4)] Locale: en_US.UTF-8

uname -a:
Linux fedora 6.1.8-200.fc37.x86_64 #1 SMP PREEMPT_DYNAMIC Tue Jan 24 20:32:16 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

lua version:
Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio

init.vim (I know it's messy I've been meaning to clean it up):

if empty(glob(data_dir . '/autoload/plug.vim'))
   silent execute '!curl -fLo '.data_dir.'/autoload/plug.vim --create-dirs  https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
   autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif

" polyglot indent can be slow, plus we have treesitter indent anyway
let g:polyglot_disabled = ['autoindent','sensible']

call plug#begin('~/.vim/plugged')

Plug 'machakann/vim-highlightedyank'    " Briefly highlight which text was yanked.
Plug 'nelstrom/vim-visual-star-search'  " Modify * to also work with visual selections.
Plug 'tpope/vim-commentary'             " Un/Comment via gc
" Plug 'ajh17/VimCompletesMe'             " complete file paths
Plug 'mhinz/vim-grepper'                " search vim files for term
Plug 'tpope/vim-repeat'                 " repeat commands
Plug 'ap/vim-css-color'                 " color highlighting of colorcodes
Plug 'Yggdroot/indentLine'              " indent line guides
Plug 'tpope/vim-fugitive'               " git wraper
Plug 'tpope/vim-capslock'               " Press <C-G>c in insert mode, or gC in normal mode
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'

Plug 'nathangrigg/vim-beancount'
Plug 'mbbill/undotree'

Plug 'sheerun/vim-polyglot'
Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}  " We recommend updating the parsers on update
Plug 'nvim-treesitter/nvim-treesitter-context'
Plug 'nvim-treesitter/playground'

Plug 'rbgrouleff/bclose.vim'
" Plug 'francoiscabrol/ranger.vim'   " LOOK AT RANGER.NVIM

" Plug 'gruvbox-community/gruvbox'
" Plug 'luisiacc/gruvbox-baby', {'branch': 'main'}


" Plug 'nathom/filetype.nvim'

Plug 'qxxxb/vim-searchhi'  "search highlighting
Plug 'osyo-manga/vim-anzu' "search match count

Plug 'godlygeek/tabular'
Plug 'sainnhe/gruvbox-material'
Plug 'nvim-lua/plenary.nvim' " don't forget to add this one if you don't have it yet!
Plug 'ThePrimeagen/harpoon'
Plug 'preservim/nerdtree'

" nvim v0.5.0
Plug 'kdheepak/lazygit.nvim'
Plug 'voldikss/vim-floaterm'

" Plug 'dhruvasagar/vim-table-mode' conflicts with tabular
" Plug 'vifm/vifm.vim'

" LSP Support
Plug 'neovim/nvim-lspconfig'             " Required
Plug 'williamboman/mason.nvim'           " Optional
Plug 'williamboman/mason-lspconfig.nvim' " Optional

" Autocompletion Engine
Plug 'hrsh7th/nvim-cmp'         " Required
Plug 'hrsh7th/cmp-nvim-lsp'     " Required
Plug 'hrsh7th/cmp-buffer'       " Optional
Plug 'hrsh7th/cmp-path'         " Optional
Plug 'saadparwaiz1/cmp_luasnip' " Optional
Plug 'hrsh7th/cmp-nvim-lua'     " Optional

" Snippets
Plug 'L3MON4D3/LuaSnip'             " Required
Plug 'rafamadriz/friendly-snippets' " Optional

" LSP Setup
Plug 'VonHeikemen/lsp-zero.nvim', {'branch': 'v1.x'}

Plug 'stsewd/fzf-checkout.vim' " :GBranches

Plug 'folke/which-key.nvim'     " also does register preview

Plug 'ipod825/libp.nvim'
Plug 'ipod825/ranger.nvim'
call plug#end()

set signcolumn=yes

nnoremap M M
nnoremap <leader>m :Man<CR>

lua << EOF
   require("libp").setup()
   require("ranger").setup()
EOF


" LSP-ZERO
  " set_lsp_keymaps = {omit = {'K'}},
lua <<EOF
local lsp = require('lsp-zero').preset({
  name = 'recommended',
  manage_nvim_cmp = true,
  suggest_lsp_servers = true,
})

lsp.default_keymaps({
  buffer = bufnr,
  preserve_mappings = false,
})

--- Don't preselect first match
--- For those who want to use the Enter key freely.
lsp.setup_nvim_cmp({
  preselect = 'none',
  completion = {
    completeopt = 'menu,menuone,noinsert,noselect'
  },
})

lsp.setup()
EOF

" TREESITTER CONTEXT
lua <<EOF
require'treesitter-context'.setup{
    enable = true, -- Enable this plugin (Can be enabled/disabled later via commands)
    max_lines = 0, -- How many lines the window should span. Values <= 0 mean no limit.
    trim_scope = 'outer', -- Which context lines to discard if `max_lines` is exceeded. Choices: 'inner', 'outer'
    min_window_height = 0, -- Minimum editor window height to enable context. Values <= 0 mean no limit.
    patterns = { -- Match patterns for TS nodes. These get wrapped to match at word boundaries.
        -- For all filetypes
        -- Note that setting an entry here replaces all other patterns for this entry.
        -- By setting the 'default' entry below, you can control which nodes you want to
        -- appear in the context window.
        default = {
            'class',
            'function',
            'method',
            'for',
            'while',
            'if',
            'switch',
            'case',
            'interface',
            'struct',
            'enum',
        },
        -- Patterns for specific filetypes
        -- If a pattern is missing, *open a PR* so everyone can benefit.
        tex = {
            'chapter',
            'section',
            'subsection',
            'subsubsection',
        },
        haskell = {
            'adt'
        },
        rust = {
            'impl_item',
        },
        terraform = {
            'block',
            'object_elem',
            'attribute',
        },
        scala = {
            'object_definition',
        },
        vhdl = {
            'process_statement',
            'architecture_body',
            'entity_declaration',
        },
        markdown = {
            'section',
        },
        elixir = {
            'anonymous_function',
            'arguments',
            'block',
            'do_block',
            'list',
            'map',
            'tuple',
            'quoted_content',
        },
        json = {
            'pair',
        },
        typescript = {
            'export_statement',
        },
        yaml = {
            'block_mapping_pair',
        },
    },
    exact_patterns = {
        -- Example for a specific filetype with Lua patterns
        -- Treat patterns.rust as a Lua pattern (i.e "^impl_item$" will
        -- exactly match "impl_item" only)
        -- rust = true,
    },

    -- [!] The options below are exposed but shouldn't require your attention,
    --     you can safely ignore them.

    zindex = 20, -- The Z-index of the context window
    mode = 'cursor',  -- Line used to calculate context. Choices: 'cursor', 'topline'
    -- Separator between context and content. Should be a single character string, like '-'.
    -- When separator is set, the context will only show up when there are at least 2 lines above cursorline.
    separator = nil,
}
EOF

" WHICH KEY
lua <<EOF
require'which-key'.setup{
  plugins = {
    marks = true, -- shows a list of your marks on ' and `
    registers = true, -- shows your registers on " in NORMAL or <C-r> in INSERT mode
    -- the presets plugin, adds help for a bunch of default keybindings in Neovim
    -- No actual key bindings are created
    spelling = {
      enabled = true, -- enabling this will show WhichKey when pressing z= to select spelling suggestions
      suggestions = 20, -- how many suggestions should be shown in the list?
    },
    presets = {
      operators = true, -- adds help for operators like d, y, ...
      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",
  },
  motions = {
    count = true,
  },
  icons = {
    breadcrumb = "»", -- symbol used in the command line area that shows your active key combo
    separator = "➜", -- symbol used between a key and it's label
    group = "+", -- symbol prepended to a group
  },
  popup_mappings = {
    scroll_down = "<c-d>", -- binding to scroll down inside the popup
    scroll_up = "<c-u>", -- binding to scroll up inside the popup
  },
  window = {
    border = "double", -- none, single, double, shadow
    position = "bottom", -- bottom, top
    margin = { 1, 0, 1, 0 }, -- extra window margin [top, right, bottom, left]
    padding = { 1, 2, 1, 2 }, -- extra window padding [top, right, bottom, left]
    winblend = 0, -- value between 0-100 0 for fully opaque and 100 for fully transparent
  },
  layout = {
    height = { min = 4, max = 50 }, -- min and max height of the columns
    width = { min = 20, max = 90 }, -- min and max width of the columns
    spacing = 3, -- spacing between columns
    align = "left", -- 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 a help message in the command line for using WhichKey
  show_keys = true, -- show the currently pressed key and its label as a message in the command line
  triggers = "auto", -- automatically setup triggers
  -- triggers = {"<leader>"} -- or specifiy a list manually
  -- list of triggers, where WhichKey should not wait for timeoutlen and show immediately
  triggers_nowait = {
    -- marks
    "`",
    "'",
    "g`",
    "g'",
    -- registers
    '"',
    "<c-r>",
    -- spelling
    "z=",
  },
  triggers_blacklist = {
    -- list of mode / prefixes that should never be hooked by WhichKey
    -- this is mostly relevant for keymaps that start with a native binding
    i = { "j", "k" },
    v = { "j", "k" },
  },
  -- disable the WhichKey popup for certain buf types and file types.
  -- Disabled by deafult for Telescope
  disable = {
    buftypes = {},
    filetypes = {},
  },
}
EOF
"--- Plugins of interest
" Plug 'nvim-lua/plenary.nvim'
" vim asterisk
" vimspector (debugger)
"tpope/vim-projectionist
" Plug 'nvim-lua/plenary.nvim'
" Plug 'folke/todo-comments.nvim'
" harpoon
" telescope

" lua <<EOF
" require('lspconfig').tsserver.setup({
"    on_attach = lsp_attach,
"    capabilities = lsp_capabilities,
" })
" EOF

" TREESITTER
lua <<EOF
require'nvim-treesitter.configs'.setup {
   -- A list of parser names, or "all"
  ensure_installed = "all",
  --ignore_install = { "verilog", "cmake", "vim" },

  -- Install parsers synchronously (only applied to `ensure_installed`)
  sync_install = false,

  -- Automatically install missing parsers when entering buffer
  auto_install = false,

  -- List of parsers to ignore installing (for "all")
  --- ignore_install = { "javascript" },
  highlight = {
    enable = true,
    -- Setting this to true will run `:h syntax` and tree-sitter at the same time.
    -- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
    -- Using this option may slow down your editor, and you may see some duplicate highlights.
    -- Instead of true it can also be a list of languages
    additional_vim_regex_highlighting = false,
  },
}
EOF

" need to do a TSInstal <lang> on initial install/config
"lua <<EOF
"  require"nvim-treesitter.highlight".set_custom_captures {
"    -- Highlight the comment capture group with the "" highlight group.
"    -- let vanilla vim/polyglot handle those highlights
"    ["comment"] = "",
"    ["string"] = "",
"  }
"EOF

" ===Plugings to look into===
"tpope/vim-projectionist
" Plug 'nvim-lua/plenary.nvim'
" Plug 'folke/todo-comments.nvim'


"--------APPEARANCE-----------------------
hi VertSplit ctermbg=black ctermfg=black
" set guifont=hack
set t_Co=256
set background=dark
set hlsearch
syntax on
set nocompatible
set hidden
" original, material, or mix
let g:gruvbox_material_foreground="original"

if (has("termguicolors"))
  set termguicolors
endif

"fix for tmux changing the color scheme
" set t_ut=
"


"-----------------------------------------
"--------BEHAVIOR-----------------------
set ignorecase
set smartcase
" only set when performing redraw intensive actions
" set lazyredraw
set ttyfast
set nowrap
set noswapfile
set foldmethod=indent
set foldignore=
set foldcolumn=0
" set foldmethod=expr
" set foldexpr=nvim_treesitter#foldexpr()
set norelativenumber
set number
set wildmenu
set wildmode=list:longest,full
set wildignore=*.o,tags,*~   "Don't show object files, etc when tab-completing
set tags=./tags,tags;$HOME
"diable scratch
set completeopt-=preview
" don't scan included files or tags, slow im vim8
" set complete-=i
" set complete-=t
set splitright
set splitbelow
set mouse=a
set autoread
" au CursorHold,CursorHoldI * checktime "time to trigger autoread
set timeoutlen=500
set ttimeoutlen=5
set noautochdir
set path+=**
set backspace=indent,eol,start  " more powerful backspacing
set shortmess-=F "needed to get nvim filetype autocmds working,
set cursorline


" Update the count when cursor is idle in command or insert mode.
" Update when idle for 1000 msec (default is 4000 msec).
set updatetime=100
set viewoptions=cursor,folds,curdir " options for vim-stay
set clipboard+=unnamedplus
set undodir=~/.undodir//
set undofile
set undolevels=10000
set history=10000

set directory+=,~/tmp,$TMP
set writebackup
set backup
set backupdir=~/.backup//

"---------------------------------------
"--------INDENT SETTINGS--------------------
filetype plugin indent on
" SHOW EXISTING TAB WITH SPACES WIDTH
set tabstop=3
" WHEN INDENTING WITH '>', USE SPACES WIDTH
set shiftwidth=3
" ON PRESSING TAB, INSERT SPACES
set expandtab
set smarttab
set cin "C-style indentation"
set ai "autoindent"
"---------------------------------------

"--------NETRW--------------------
let g:netrw_banner=0
let g:netrw_liststyle=3
"---------------------------------------

"---------KEY-REMAPS--------------------
let mapleader=" "
let maplocalleader=" "

" remap needed to prevent mouse functions from inserting characters
nnoremap <esc>^[ <esc>^[

"-----mouse scroll wheel------
nnoremap <ScrollWheelUp> <C-Y>
nnoremap <C-ScrollWheelUp> <C-U>
nnoremap <S-ScrollWheelUp> <C-B>

nnoremap <ScrollWheelDown> <C-E>
nnoremap <C-ScrollWheelDown> <C-D>
nnoremap <S-ScrollWheelDown> <C-F>

inoremap <ScrollWheelUp> <C-Y>
inoremap <C-ScrollWheelUp> <C-U>
inoremap <S-ScrollWheelUp> <C-B>

inoremap <ScrollWheelDown> <C-E>
inoremap <C-ScrollWheelDown> <C-D>
inoremap <S-ScrollWheelDown> <C-F>

vnoremap <ScrollWheelUp> <C-Y>
vnoremap <C-ScrollWheelUp> <C-U>
vnoremap <S-ScrollWheelUp> <C-B>

vnoremap <ScrollWheelDown> <C-E>
vnoremap <C-ScrollWheelDown> <C-D>
vnoremap <S-ScrollWheelDown> <C-F>
"-----------------------------

nnoremap <C-RightMouse> *Nzz
vnoremap <C-RightMouse> :<C-U>call <SNR>19_VSetSearch('/')<CR>/<C-R>=@/<CR><CR>Nzz
inoremap <C-RightMouse> *Nzz

set pastetoggle=<F3>

command! W w


"---------KEY-REMAPS-PLUGINS---------

"---------FZF------------
nmap <leader><tab> <plug>(fzf-maps-n)
xmap <leader><tab> <plug>(fzf-maps-x)
omap <leader><tab> <plug>(fzf-maps-o)
" nmap <leader> i <plug>(fzf-maps-n)


"---------SEARCHHI------------
nmap n <Plug>(searchhi-n)
nmap N <Plug>(searchhi-N)
nmap * <Plug>(searchhi-*)
nmap g* <Plug>(searchhi-g*)
nmap # <Plug>(searchhi-#)
nmap g# <Plug>(searchhi-g#)
" nmap gd <Plug>(searchhi-gd)
" nmap gD <Plug>(searchhi-gD)

vmap n <Plug>(searchhi-v-n)
vmap N <Plug>(searchhi-v-N)
" vmap * <Plug>(searchhi-v-*)
vmap g* <Plug>(searchhi-v-g*)
" vmap # <Plug>(searchhi-v-#)
vmap g# <Plug>(searchhi-v-g#)
" vmap gd <Plug>(searchhi-v-gd)
" vmap gD <Plug>(searchhi-v-gD)

" nmap <silent> <C-L> <Plug>(searchhi-clear-all)
" vmap <silent> <C-L> <Plug>(searchhi-v-clear-all)

let g:searchhi_user_autocmds_enabled = 1
let g:searchhi_redraw_before_on = 1


" noremap <C-G> 1<C-G>

" Seamlessly treat visual lines as actual lines when moving around.
noremap j gj
noremap k gk
noremap <Down> gj
noremap <Up> gk
inoremap <Down> <C-o>gj
inoremap <Up> <C-o>gk

"-------HARPOON--------
nnoremap <silent> <leader>y :lua require("harpoon.mark").add_file()<CR>:echo expand('%:t') "added to harpoon"<CR>
nnoremap <silent> <leader>h :lua require("harpoon.ui").toggle_quick_menu()<CR>
nnoremap <silent> <leader>H :lua require("harpoon.ui").nav_file(1)<CR>
nnoremap <silent> <leader>J :lua require("harpoon.ui").nav_file(2)<CR>
nnoremap <silent> <leader>K :lua require("harpoon.ui").nav_file(3)<CR>
nnoremap <silent> <leader>L :lua require("harpoon.ui").nav_file(4)<CR>
nnoremap <silent> <leader>j :lua require("harpoon.ui").nav_next()<CR>
nnoremap <silent> <leader>k :lua require("harpoon.ui").nav_prev()<CR>

"----------TABS---------------
" Go to tab by number
noremap <silent> <leader>1 1gt
noremap <silent> <leader>2 2gt
noremap <silent> <leader>3 3gt
noremap <silent> <leader>4 4gt
noremap <silent> <leader>5 5gt
noremap <silent> <leader>6 6gt
noremap <silent> <leader>7 7gt
noremap <silent> <leader>8 8gt
noremap <silent> <leader>9 9gt
noremap <silent> <leader>0 :tablast<CR>

"cycle through tabs
noremap <silent> <leader>p gT
noremap <silent> <leader>n gt
noremap <silent> <leader>d :q<CR>
noremap <silent> <M-Left> gT
noremap <silent> <M-Right> gt
"move tab location
noremap <silent> <S-M-Left>  :tabm -1<CR>
noremap <silent> <S-M-Right> :tabm +1<CR>

"new tab
noremap <silent> <leader>t :tabnew<CR>
noremap <silent> <leader>T :tabclose<CR>

"gimme terminal
noremap <silent> <leader>S :terminal<CR>

" move lines with alt j/k
nnoremap <A-j> :m .+1<CR>==
nnoremap <A-k> :m .-2<CR>==
inoremap <A-j> <Esc>:m .+1<CR>==gi
inoremap <A-k> <Esc>:m .-2<CR>==gi
vnoremap <A-j> :m '>+1<CR>gv=gv
vnoremap <A-k> :m '<-2<CR>gv=gv

" nnoremap <silent> <C-[> :redraw!<CR>

nnoremap <silent> <C-l> :vertical resize -5<CR>
nnoremap <silent> <C-h> :vertical resize +5<CR>
" nnoremap <silent> <C-k> :resize +5<CR>
" nnoremap <silent> <C-j> :resize -5<CR>

noremap <silent> <S-Right> :vertical resize -5<CR>
noremap <silent> <S-Left> :vertical resize +5<CR>
noremap <silent> <S-Up> :resize +5<CR>
noremap <silent> <S-Down> :resize -5<CR>

noremap <silent> <Right> :vertical resize -1<CR>
noremap <silent> <Left> :vertical resize +1<CR>
noremap <silent> <Up> :resize +1<CR>
noremap <silent> <Down> :resize -1<CR>

nnoremap <leader>z <C-w>_ \| <C-w>\|

" Go to last active tab
au TabLeave * let g:lasttab = tabpagenr()
" nnoremap <silent> <leader>L :exe "tabn ".g:lasttab<CR>
" vnoremap <silent> <leader>L :exe "tabn ".g:lasttab<CR>

" Cycle through splits.
" nnoremap <S-Tab> <C-w>w

" noremap <leader>y "*y
" noremap <leader>p "*p

noremap <leader>Y :let @+=expand('%:p')<CR>

" buffer navigation
nnoremap <leader>N :bn<CR>
nnoremap <leader>P :bp<CR>
nnoremap <leader>w :bn<CR>
nnoremap <leader>q :bp<CR>
nnoremap <leader>D :bd<CR>
nnoremap <leader>b :Buffers <CR>

" reverse selected string
vnoremap ;rv c<C-O>:set revins<CR><C-R>"<Esc>:set norevins<CR>

function! LastTab()
   call feedkeys("\g\<Tab>")
endfunction

func! MyRedir() abort
    redir! > ~/test.txt
    :ls
    redir END
endfunc

augroup save_files | au!
    au VimLeave * call MyRedir()
augroup end


function! SavePaths( path )
   let files = filter(map(range(1,bufnr('$')), 'bufname(v:val)'), '!empty(v:val)')
   call writefile(files, a:path )
endfunction

" --------------vim-peekaboo--------------------
" let g:peekaboo_window = "vert bo 40new"

" --------------floaterm--------------------
let g:floaterm_opener = 'edit'
let g:floaterm_width = 0.9
let g:floaterm_height = 0.9

" nnoremap <leader>a :set nomore <Bar> :pwd <Bar> :set more <CR>:cd<Space>

nnoremap <leader>f :Files
nnoremap <leader>ff :Files
nnoremap <leader>fs :Files ~/.scripts/
nnoremap <leader>fc :Files ~/.config/
nnoremap <leader>l :Lines

" search for selection
" fugitive sfite
" nnoremap <leader>v :vert G<CR>
" nnoremap <leader>gh :Gclog<CR>
" nnoremap <leader>gl :G log<CR>


" lazygit floaterm fugitive replacement
nnoremap <leader>v :vert G<CR>
" nnoremap <leader>v :FloatermNew lazygit<CR>
" nnoremap <leader>V :LazyGitCurrentFile<CR>
" nnoremap <leader>gh :Gclog<CR>
" nnoremap <leader>gl :G log<CR>

" -- fix so that grepper can see buffers that are loaded by haven't been visited
" nnoremap <leader>s :cex []<CR> :silent bufdo vimgrepadd // % <Left><Left><Left>
" nnoremap <leader>a :cex []<CR> :silent bufdo vimgrepadd /<C-r><C-w>/ %<CR>

" fugitive follow symlinks
nnoremap <leader>x :<C-u>execute 'file '.fnameescape(resolve(expand('%:p')))<bar>
    \ call FugitiveDetect(fnameescape(expand('%:p:h')))<CR>

"---------fzf----------------
" An action can be a reference to a function that processes selected lines
" function! s:build_quickfix_list(lines)
"   call setqflist(map(copy(a:lines), '{ "filename": v:val }'))
"   copen
"   cc
" endfunction

" let g:fzf_action = {
"   \ 'ctrl-q': function('s:build_quickfix_list'),
"   \ 'ctrl-t': 'tab split',
"   \ 'ctrl-x': 'split',
"   \ 'ctrl-v': 'vsplit' }


"Press * to search for the term under the cursor or a visual selection and
" then press a key below to replace all instances of it in the current file.
nnoremap <leader>C :bufdo %s///g<Left><Left>
nnoremap <leader>c :%s///g<Left><Left>

nnoremap <leader>s :cfdo %s///g<Left><Left>

" The usere as above but instead of acting on the whole file it will be
" restricted to the previously visually selected range. You can do that by
" pressing *, visually selecting the range you want it to apply to and then
" press a key below to replace all instances of it in the current selection.
"xnoremap <Leader>r :s///g<Left><Left>
"xnoremap <Leader>rc :s///gc<Left><Left><Left>

" Type a replacement term and press . to repeat the replacement again.
"Useful
" for replacing a few instances of the term (comparable to multiple
"cursors).
" nnoremap <silent> s* :let @/='\<'.expand('<cword>').'\>'<CR>cgn
" xnoremap <silent> s* "sy:let @/=@s<CR>cgn

" Prevent x from overriding what's in the clipboard.
noremap x "_x
noremap X "_x

" Prevent selecting and pasting from overwriting what you originally copied.
xnoremap p pgvy

" Keep cursor at the bottom of the visual selection after you yank it.
vmap y ygv<Esc>

"----Rename tmux window to filename-----
function! Ren()
   let cmd = "tmux rename-window " . expand("%:t")
   call system(cmd)
endfunction

nnoremap <silent> <leader>R :call Ren()<CR>

"-----InentLine-------------------------
let g:indentLine_concealcursor = 'nc'
let g:indentLine_conceallevel = 1
let g:indentLine_enabled = 1
let g:indentLine_char_list = ['|', '¦', '┆', '┊']

"-------GREPPER---------
" nnoremap gs  <plug>(GrepperOperator)
nnoremap <leader>g :Grepper -dir cwd
nnoremap <leader>G :Grepper -buffers

" the g:grepper dict will be appended to once plugin has loaded, after vim
"  sources this file, our changes will be kept
let g:grepper = {
   \ 'dir': 'cwd,file',
   \ 'tools' : ['grep'],
   \ 'grep': {
   \   'grepprg': 'grep -RIn --exclude=tags --exclude-dir=.git $* .',
   \ }}

"--------NERDTREE----------------------
nnoremap <leader>e :NERDTreeToggle<CR>

" Open the existing NERDTree on each new tab.
" autocmd BufWinEnter * if getcmdwintype() == '' | silent NERDTreeMirror | endif

"--------HighlightedYank-------------------------------
if !exists('##TextYankPost')
   map y <Plug>(highlightedyank)
endif
let g:highlightedyank_highlight_duration = 1000
let g:highlightedyank_highlight_in_visual = 1
" highlight HighlightedyankRegion ctermbg=214 ctermfg=0 guibg=214 guifg=0
highlight! link HighlightedyankRegion WarningFloat

function! HighYank()
   highlight link HighlightedyankRegion WarningFloat
endfunction

" augroup highlightedYankGroup
"    autocmd!
"    autocmd UIEnter * call HighYank()
" augroup END


"source this file
command! Source :source ~/.config/nvim/init.vim
command! Edit :e ~/.config/nvim/init.vim
command! Notes :e /home/sam/srpvm191/notes/TODO_GENERAL.txt

nnoremap <leader><leader>e :Edit<CR>
nnoremap <leader><leader>n :Notes<CR>

function! ThreeHorizontalWindows()
   wincmd h
   wincmd h
   wincmd K
   wincmd j
   wincmd l
   wincmd J
   wincmd k
endfunction

function! DiffgetFile(LR)
   let l:prevlastline = 0
   let l:curlastline = line("$")

   " until the last line stops changing after diffget, i.e no more changes
   while l:curlastline != l:prevlastline
      let l:prevlastline= line("$")

      call setpos("'<",[0,1,1])
      call setpos("'>",[0,l:curlastline,1])

      if a:LR == 'R'
         '<,'>diffget REMOTE
      else
         '<,'>diffget LOCAL
      endif

      let l:curlastline = line("$")
   endwhile

endfunction

function! DiffgetVisual(r,l1,l2,LR) abort
   " if no range supplied
   if a:r == 0
      if a:LR == 'R'
         diffget REMOTE
      else
         diffget LOCAL
      endif
   " if range supplied
   else
      call setpos("'<",[0,a:l1,1])
      call setpos("'>",[0,a:l2,1])
      echo "start line: " . a:l1
      echo "end line: " . a:l2
      if a:LR == 'R'
         '<,'>diffget REMOTE
      else
         '<,'>diffget LOCAL
      endif
   endif
endfunction

" do a three way fugitive merge
command! GM :Gdiffsplit!
command! Gt :diffget //2
command! Gm :diffget //3

command! Gl :diffget LOCAL
command! Gr :diffget REMOTE

command! -range GR :call DiffgetVisual(<range>,<line1>,<line2>,"R")
command! -range GL :call DiffgetVisual(<range>,<line1>,<line2>,"L")

command! GGRR :call DiffgetFile("R")
command! GGLL :call DiffgetFile("L")

command! TH :call ThreeHorizontalWindows()

nnoremap <leader><leader>ggr :GGRR<CR>
nnoremap <leader><leader>ggl :GGLL<CR>

nnoremap <leader><leader>gl :GL<CR>
nnoremap <leader><leader>gr :GR<CR>
vnoremap <leader><leader>gl :GL<CR>
vnoremap <leader><leader>gr :GR<CR>


nnoremap <leader><leader>gt :Gt<CR>
nnoremap <leader><leader>gm :Gm<CR>
vnoremap <leader><leader>gt :Gt<CR>
vnoremap <leader><leader>gm :Gm<CR>

command! RPS :!tmux set-environment cur_dir %:p:h \; neww bash -c "~/.scripts/rsync_vm.sh PUSH"
command! RPL :!tmux set-environment cur_dir %:p:h \; neww bash -c "~/.scripts/rsync_vm.sh PULL"

nnoremap <leader>u :RPS<CR>
nnoremap <leader>U :RPL<CR>

nnoremap <leader><leader>w :wq<CR>
nnoremap <leader><leader>W :wqa<CR>


" do tmux stuff
command! VCT   :!~/.scripts/vim_control_tmux.sh

nnoremap <F6> :VCT<CR>

nnoremap <F7> :UndotreeToggle<CR>
"Remove all trailing whitespace by pressing F5
function! RemoveTrailingWhitespace()
   let _s=@/|
   %s/\s\+$//e|
   let @/=_s|
endfunction
nnoremap <F5> :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar><CR>
"map <F8> :checktime<CR>
" autocmd BufWritePre * %s/\s\+$//e

nnoremap <F8> :!lualatex --output-format=pdf %<CR>

command! -complete=shellcmd -nargs=+ Shell call s:RunShellCommand(<q-args>)

" function! TabHi()
"    highlight!  TabNum     cterm=bold  ctermfg=208  ctermbg=240
"    highlight!  TabNumSel  cterm=bold  ctermfg=208  ctermbg=246
"    highlight!  WinNum     cterm=bold  ctermfg=223  ctermbg=240
"    highlight!  WinNumSel  cterm=bold  ctermfg=223  ctermbg=240
" endfunction

" needed for old tabliine highlighting
" augroup tabhi
"    autocmd!
"    autocmd TabNew * call TabHi()
"    autocmd SourcePost * call TabHi()
"    " autocmd TabEnter * call TabHi()
"    " autocmd TabNewEntered * call TabHi()
" augroup END


"FZF Buffer Delete

function! s:list_buffers()
  redir => list
  silent ls
  redir END
  return split(list, "\n")
endfunction

function! s:delete_buffers(lines)
  execute 'bwipeout!' join(map(a:lines, {_, line -> split(line)[0]}))
endfunction

command! BD call fzf#run(fzf#wrap({
  \ 'source': s:list_buffers(),
  \ 'sink*': { lines -> s:delete_buffers(lines) },
  \ 'options': '--multi --reverse --bind ctrl-a:select-all+accept'
\ }))

" ---------------BETTER TRADITIONAL TABLINE-----------------------
if exists("+showtabline")

" Rename tabs to show tab number.
" (Based on http://stackoverflow.com/questions/5927952/whats-implementation-of-vims-default-tabline-function)

function! MyTabLine()
    let s = ''
    let t = tabpagenr()
    let i = 1
    while i <= tabpagenr('$')
        let buflist = tabpagebuflist(i)
        let winnr = tabpagewinnr(i)
        let s .= '%' . i . 'T'
        let s .= (i == t ? '%1*' : '%2*')

        " let s .= (i == t ? '%#TabLineSel#' : '%#TabLine#')
        " let s .= ' '
        " let s .= (i == t ? '%#TabNumSel#' : '%#TabNum#')
        let s .= (i == t ? '%#CocErrorFloat#' : '%#CocErrorFloat#')
        let s .= ' ' . i . ''
        let s .= (i == t ? '%#CocWarningFloat#' : '%#CocInfoFloat#')

        let bufnr = buflist[winnr - 1]
        let file = bufname(bufnr)
        let buftype = getbufvar(bufnr, '&buftype')

        if buftype == 'help'
            let file = 'help:' . fnamemodify(file, ':t:r')

        elseif buftype == 'quickfix'
            let file = 'quickfix'

        elseif buftype == 'nofile'
            if file =~ '\/.'
                let file = substitute(file, '.*\/\ze.', '', '')
            endif

        else
            let file = pathshorten(fnamemodify(file, ':t'))
            if getbufvar(bufnr, '&modified')
                let file = '+' . file
            endif

        endif

        if file == ''
            let file = '[No Name]'
        endif

        let s .= ' ' . file

        let nwins = tabpagewinnr(i, '$')
        if nwins > 1
            let modified = ''
            for b in buflist
                if getbufvar(b, '&modified') && b != bufnr
                    let modified = '*'
                    break
                endif
            endfor
            let hl = (i == t ? '%#CocWarningFloat#' : '%#CocInfoFloat#')
            let nohl = (i == t ? '%#CocWarningFloat#' : '%#CocInfoFloat#')
            let s .= ' ' . modified . '(' . nohl . winnr . nohl . '/' . nwins . ')'
        endif

        if i < tabpagenr('$')
            let s .= ' %#CocInfoFloat#|'
        else
            let s .= ' '
        endif

        let i = i + 1

    endwhile

    let s .= '%T%#CocInfoFloat#%='
    let s .= (tabpagenr('$') > 1 ? '%999XX' : 'X')
    return s
endfunction
" let Black=0
" let DarkBlue=1
" let DarkGreen=2
" let DarkCyan=3
" let DarkRed=4
" let DarkMagenta=5
" let Brown=6
" let LightGray=7
" let DarkGray=8
" let Blue=9
" let Green=10
" let Cyan=11
" let Red=12
" let Magenta=13
" let Yellow=14
" let White=15

"
" TabLine        xxx ctermfg=223 ctermbg=240 guifg=#ebdbb2 guibg=#504945
" TabLineSel     xxx ctermfg=235 ctermbg=246 guifg=#282828 guibg=#a89984
" TabLineFill    xxx ctermfg=223 ctermbg=236 guifg=#ebdbb2 guibg=#32302f

set showtabline=1

set tabline=%!MyTabLine()

endif " exists("+showtabline")
"----------------------------------------------------------------------------



"---------------STATUSLINE---------------------------

function! CurrentDir()
   return fnamemodify(execute('pwd'), ":t")
endfunction

function! CurrentServer()
   " return v:servername
   return ""
endfunction

function! RangerLevel()
   return system("echo -n $RANGER_LEVEL")
endfunction

command! CD :cd %:p:h

function! FileNameStatus()
   if g:fullpath == '0'
      return expand('%:t')
   elseif g:fullpath == '1'
      return resolve(expand('%:t'))
   elseif g:fullpath == '2'
      return resolve(expand('%:p:.'))
   else
      return resolve(expand('%:p'))
   endif
endfunction

function! FullPathToggle()
   if g:fullpath == '0'
      let g:fullpath = '1'
   elseif g:fullpath == '1'
      let g:fullpath = '2'
   elseif g:fullpath == '2'
      let g:fullpath = '3'
   else
      let g:fullpath = '0'
   endif
endfunction

let g:git_status_line_counter = 0
let g:git_status_cached = ""

function! StatuslineGit()
   return FugitiveStatusline()[5:15]
endfunction

" function! StatuslineGit()
"    if (g:git_status_line_counter % 3) == 0
"       let g:git_status_cached = FugitiveStatusline()[5:15]
"    endif
"    let g:git_status_line_counter = (g:git_status_line_counter + 1) % 3
"    return g:git_status_cached
"    " return l:branch[0:15]
"    " return (len(l:branch) > 15 ? l:branch[0:15] : l:branch)
" endfunction



command! FullPathToggle call FullPathToggle()

let g:fullpath = '1'

set statusline=
set statusline+=%#CocHintFloat#
" set statusline+=\[%{StatuslineGit()}\]
set statusline+=%{StatuslineGit()}
set statusline+=%#CocWarningFloat#\ %{FileNameStatus()}
" set statusline+=%#CocWarningFloat#\ %{%FileNameStatus()%}
set statusline+=%m
set statusline+=%=
set statusline+=%#CocHintFloat#
set statusline+=\(%{anzu#search_status()}\)
set statusline+=\[%{CurrentDir()}\]
set statusline+=\ %y
" set statusline+=\ %{&fileencoding?&fileencoding:&encoding}
"set statusline+=\[%{&fileformat}\]
set statusline+=\ %p%%
set statusline+=\ %l:%c
" set statusline+=\ (%{CurrentServer()}\)
" set statusline+=\ {R:%{RangerLevel()}\}
set laststatus=2

"tabline is setup in .config/nvim/plugin/custom_tabline.vim

" function! RangerNerd()
"    vs
"    let $NO_CLOSE=""
"    let $SERVER_NAME=v:servername
"    let g:ranger_command_override = 'ranger --cmd "set column_ratios 1,1"'
"    RangerWorkingDirectoryServer
"    wincmd H
"    vert res 60
"    set winfixwidth
"    set winfixheight
"    let g:ranger_command_override = 'ranger'
" endfunction

" function! RangerNerdNoClose()
"    vs
"    let $SERVER_NAME=v:servername
"    let $NO_CLOSE=1
"    let g:ranger_command_override = 'ranger --cmd "set column_ratios 1,1"'
"    " maybe use this
"    " call termopen(s:ranger_command . ' --choosefiles=' . s:choice_file_path . ' "' . currentPath . '"', rangerCallback)
"    terminal ranger
"    wincmd H
"    vert res 50
"    set winfixwidth
"    set winfixheight
"    startinsert
"    let g:ranger_command_override = 'ranger'
" endfunction

" " --- Ranger config
" " let g:NERDTreeHijackNetrw = 0  " add this line if you use NERDTree
" let g:ranger_replace_netrw = 0 " open ranger when vim open a directory
" let g:ranger_command_override = 'ranger --cmd "set column_ratios 1,1"'
" " let g:ranger_command_override = 'ranger'


" " nnoremap <leader>e :call RangerNerdNoClose()<CR>

" let g:ranger_map_keys = 0
" nnoremap <leader>r :FloatermNew ranger<CR>
" " nnoremap <leader>r :FloatermNew ranger `cwd`<CR>
" nnoremap <leader>R :Ranger<CR>
" " nnoremap <leader>R :RangerWorkingDirectory<CR>

" command! RangerWorkingDirectoryServer call OpenRangerIn(".", 'silent ! SERVER_NAME='. v:servername . ' ~/.scripts/edit_remote.sh ')

" leave terminal mode with escape
tnoremap <Esc> <C-\><C-n>




function! TimeStamp()
   call system('date > ~/date.txt')
   r ~/date.txt
endfunction
command! -bar TimeStamp call TimeStamp()
nnoremap <leader>T :<C-U>TimeStamp<CR>

function! s:RunShellCommand(cmdline)
   echo a:cmdline
   let expanded_cmdline = a:cmdline
   for part in split(a:cmdline, ' ')
      if part[0] =~ '\v[%#<]'
         let expanded_part = fnameescape(expand(part))
         let expanded_cmdline = substitute(expanded_cmdline, part, expanded_part, '')
      endif
   endfor
   botright new
   setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap
   call setline(1, 'You entered:    ' . a:cmdline)
   call setline(2, 'Expanded Form:  ' .expanded_cmdline)
   call setline(3,substitute(getline(2),'.','=','g'))
   execute '$read !'. expanded_cmdline
   1
endfunction

function! Get_visual_selection()
   let [line_start, column_start] = getpos("'<")[1:2]
   let [line_end, column_end] = getpos("'>")[1:2]
   let lines = getline(line_start, line_end)
   if len(lines) == 0
      return ''
   endif
   let lines[-1] = lines[-1][: column_end - (&selection == 'inclusive' ? 1 : 2)]
   let lines[0] = lines[0][column_start -1:]
   return join(lines, "\n")
endfunction

function! StripVisualSelection ( string )
   let string=a:string
   let string = substitute(string, '\v', '', '' )
   return string
endfunction


"-------------AUGROUP-AUTOCMDS-------------------------

" autocmd BufWritePost ~/.config/nvim/*.vim source % | echom "update init.vim and friends "| redraw

augroup searchhi
    autocmd!
    autocmd User SearchHiOn AnzuUpdateSearchStatusOutput
    autocmd User SearchHiOff echo g:anzu_no_match_word
augroup END

augroup vimrc
  autocmd!
  autocmd BufWinEnter,Syntax * syn sync minlines=500 maxlines=500
augroup END

" persistent fold
augroup AutoSaveFolds
   autocmd!
   " autocmd BufWinLeave * silent! mkview
   autocmd BufLeave * silent! mkview
   autocmd BufWinEnter * silent! loadview
augroup END

function! SetupLog()
   setlocal tabstop=2
   setlocal shiftwidth=2
endfunction

augroup log_group
   autocmd!
   autocmd FileType log call SetupLog()
augroup END


function! SetupText()
   setlocal tabstop=2
   setlocal shiftwidth=2
endfunction

augroup text_group
   autocmd!
   autocmd FileType txt call SetupText()
augroup END

function! SetupYaml()
   setlocal tabstop=2
   setlocal shiftwidth=2
endfunctio

augroup yaml_group
   autocmd!
   autocmd FileType yaml call SetupYaml()
augroup END

augroup bean_group
   autocmd!
   autocmd FileType beancount setlocal shiftwidth=2  tabstop=2
augroup END

function! SetupRuby()
   setlocal shiftwidth=3  tabstop=3
   setlocal nocindent smartindent autoindent
   filetype indent on
   set foldmethod=indent
   setlocal foldignore=
   set indentexpr=GetRubyIndent(v:lnum)
endfunction

augroup ruby_group
   autocmd!
   autocmd FileType ruby call SetupRuby()
   autocmd FileType rspec call SetupRuby()
augroup END

function! SetupC()
   set colorcolumn=120
   set textwidth=120
   call css_color#init('hex', 'extended', 'cComment,cCommentL,cString,cCppString')
   " c header
   if expand('%:e') ==? 'h'
      set ft=c
   endif
   " cpp header
   " if expand('%:e') =~? '\v^h%(pp|h|\+\+|xx)?$'
   "  " your script here
   " endif
endfunction

augroup c_group
   autocmd!
   autocmd FileType c call SetupC()
augroup END

function! SetupCpp()
   set colorcolumn=120
   set textwidth=120
endfunction

augroup cpp_group
   autocmd!
   autocmd FileType cpp call SetupCpp()
augroup END

function! SetupMake()
   setlocal noexpandtab
endfunction

augroup make_group
   autocmd!
   autocmd FileType make call SetupMake()
augroup END

function! SpaceBeforeChar( char )
   exe '%s/' . '\([^ \\]\)' . a:char . '/' . '\1 ' . a:char . '/g'
endfunction

function! SpaceAfterChar( char )
   exe '%s/' . a:char . '\([^ \\]\)/' . a:char . ' \1/g'
endfunction

" need to set colorscheme as late as possible due to
"  syntax.vim needing to be sourced first I think
autocmd VimEnter * colorscheme gruvbox-material```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions