From 29b912d8981db152ef86ecb8d1ce1542ea765a63 Mon Sep 17 00:00:00 2001 From: Adam Pippin Date: Thu, 14 Jul 2022 10:43:33 -0400 Subject: [PATCH] Initial commit --- .gitignore | 1 + README.md | 9 + autoload/plug.vim | 2526 ++++++++++++++++++ colors/base16-eighties.vim | 414 +++ doc/nukevim.txt | 517 ++++ doc/tags | 42 + lua/_config.lua | 193 ++ lua/config/_keymap.lua | 86 + lua/config/_plugins.lua | 29 + lua/config/_settings.lua | 61 + lua/config/plugins/development.lua | 269 ++ lua/config/plugins/editing.lua | 37 + lua/config/plugins/lang-php.lua | 49 + lua/config/plugins/lib.lua | 28 + lua/config/plugins/local.lua | 8 + lua/config/plugins/tmp.lua | 13 + lua/config/plugins/ui.lua | 146 + lua/data/start.lua | 13 + lua/impatient/impatient.lua | 420 +++ lua/impatient/profile.lua | 222 ++ lua/lib/autocmd.lua | 51 + lua/lib/dump.lua | 15 + lua/lib/file_exists.lua | 9 + lua/lib/get_visual_selection.lua | 14 + lua/lib/has_command.lua | 4 + lua/lib/map.lua | 7 + lua/lib/merge.lua | 9 + lua/module.lua | 47 + lua/module/keymap.lua | 249 ++ lua/module/lsp.lua | 27 + lua/module/phpunit.lua | 66 + lua/module/plugins.lua | 88 + lua/module/settings.lua | 13 + lua/module/start.lua | 154 ++ lua/module/syntax.lua | 14 + lua/module/ui.lua | 35 + lua/modules.lua | 62 + lua/nukevim.lua | 55 + lua/plugin/akinsho/toggleterm-nvim.lua | 9 + lua/plugin/apzelos/blamer-nvim.lua | 12 + lua/plugin/dein.lua | 38 + lua/plugin/editorconfig/editorconfig-vim.lua | 11 + lua/plugin/folke/todo-comments-nvim.lua | 9 + lua/plugin/folke/trouble-nvim.lua | 17 + lua/plugin/jghauser/shade-nvim.lua | 12 + lua/plugin/joonty/vim-phpunitqf.lua | 9 + lua/plugin/nacro90/numb-nvim.lua | 10 + lua/plugin/preservim/tagbar.lua | 18 + lua/plugin/stevearc/dressing-nvim.lua | 8 + lua/plugin/tpope/vim-fugitive.lua | 40 + lua/plugin/vim-airline/vim-airline.lua | 9 + lua/plugin/vim-vdebug/vdebug.lua | 70 + lua/plugin/vim_plug.lua | 37 + 53 files changed, 6311 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100755 autoload/plug.vim create mode 100644 colors/base16-eighties.vim create mode 100644 doc/nukevim.txt create mode 100644 doc/tags create mode 100644 lua/_config.lua create mode 100644 lua/config/_keymap.lua create mode 100644 lua/config/_plugins.lua create mode 100644 lua/config/_settings.lua create mode 100644 lua/config/plugins/development.lua create mode 100644 lua/config/plugins/editing.lua create mode 100644 lua/config/plugins/lang-php.lua create mode 100644 lua/config/plugins/lib.lua create mode 100644 lua/config/plugins/local.lua create mode 100644 lua/config/plugins/tmp.lua create mode 100644 lua/config/plugins/ui.lua create mode 100644 lua/data/start.lua create mode 100644 lua/impatient/impatient.lua create mode 100644 lua/impatient/profile.lua create mode 100644 lua/lib/autocmd.lua create mode 100644 lua/lib/dump.lua create mode 100644 lua/lib/file_exists.lua create mode 100644 lua/lib/get_visual_selection.lua create mode 100644 lua/lib/has_command.lua create mode 100644 lua/lib/map.lua create mode 100644 lua/lib/merge.lua create mode 100644 lua/module.lua create mode 100644 lua/module/keymap.lua create mode 100644 lua/module/lsp.lua create mode 100644 lua/module/phpunit.lua create mode 100644 lua/module/plugins.lua create mode 100644 lua/module/settings.lua create mode 100644 lua/module/start.lua create mode 100644 lua/module/syntax.lua create mode 100644 lua/module/ui.lua create mode 100644 lua/modules.lua create mode 100644 lua/nukevim.lua create mode 100644 lua/plugin/akinsho/toggleterm-nvim.lua create mode 100644 lua/plugin/apzelos/blamer-nvim.lua create mode 100644 lua/plugin/dein.lua create mode 100644 lua/plugin/editorconfig/editorconfig-vim.lua create mode 100644 lua/plugin/folke/todo-comments-nvim.lua create mode 100644 lua/plugin/folke/trouble-nvim.lua create mode 100644 lua/plugin/jghauser/shade-nvim.lua create mode 100644 lua/plugin/joonty/vim-phpunitqf.lua create mode 100644 lua/plugin/nacro90/numb-nvim.lua create mode 100644 lua/plugin/preservim/tagbar.lua create mode 100644 lua/plugin/stevearc/dressing-nvim.lua create mode 100644 lua/plugin/tpope/vim-fugitive.lua create mode 100644 lua/plugin/vim-airline/vim-airline.lua create mode 100644 lua/plugin/vim-vdebug/vdebug.lua create mode 100644 lua/plugin/vim_plug.lua diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..375a75d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/plugins/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..1d0c7c4 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# NukeVim -- nucleardog's nvim config + +This is my modular-ish and configurable-ish neovim config. + +It's not intended to serve anyone's purposes but my own, but the core of it +should be fairly adaptable (if poorly implemented) to anything you want it to +do. + +For further information, check out the [vim help file](doc/nukevim.txt). diff --git a/autoload/plug.vim b/autoload/plug.vim new file mode 100755 index 0000000..4e05630 --- /dev/null +++ b/autoload/plug.vim @@ -0,0 +1,2526 @@ +" vim-plug: Vim plugin manager +" ============================ +" +" Download plug.vim and put it in ~/.vim/autoload +" +" curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ +" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim +" +" Edit your .vimrc +" +" call plug#begin('~/.vim/plugged') +" +" " Make sure you use single quotes +" +" " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align +" Plug 'junegunn/vim-easy-align' +" +" " Any valid git URL is allowed +" Plug 'https://github.com/junegunn/vim-github-dashboard.git' +" +" " Multiple Plug commands can be written in a single line using | separators +" Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets' +" +" " On-demand loading +" Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' } +" Plug 'tpope/vim-fireplace', { 'for': 'clojure' } +" +" " Using a non-master branch +" Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' } +" +" " Using a tagged release; wildcard allowed (requires git 1.9.2 or above) +" Plug 'fatih/vim-go', { 'tag': '*' } +" +" " Plugin options +" Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' } +" +" " Plugin outside ~/.vim/plugged with post-update hook +" Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' } +" +" " Unmanaged plugin (manually installed and updated) +" Plug '~/my-prototype-plugin' +" +" " Initialize plugin system +" call plug#end() +" +" Then reload .vimrc and :PlugInstall to install plugins. +" +" Plug options: +" +"| Option | Description | +"| ----------------------- | ------------------------------------------------ | +"| `branch`/`tag`/`commit` | Branch/tag/commit of the repository to use | +"| `rtp` | Subdirectory that contains Vim plugin | +"| `dir` | Custom directory for the plugin | +"| `as` | Use different name for the plugin | +"| `do` | Post-update hook (string or funcref) | +"| `on` | On-demand loading: Commands or ``-mappings | +"| `for` | On-demand loading: File types | +"| `frozen` | Do not update unless explicitly specified | +" +" More information: https://github.com/junegunn/vim-plug +" +" +" Copyright (c) 2017 Junegunn Choi +" +" MIT License +" +" Permission is hereby granted, free of charge, to any person obtaining +" a copy of this software and associated documentation files (the +" "Software"), to deal in the Software without restriction, including +" without limitation the rights to use, copy, modify, merge, publish, +" distribute, sublicense, and/or sell copies of the Software, and to +" permit persons to whom the Software is furnished to do so, subject to +" the following conditions: +" +" The above copyright notice and this permission notice shall be +" included in all copies or substantial portions of the Software. +" +" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +" NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +" LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +if exists('g:loaded_plug') + finish +endif +let g:loaded_plug = 1 + +let s:cpo_save = &cpo +set cpo&vim + +let s:plug_src = 'https://github.com/junegunn/vim-plug.git' +let s:plug_tab = get(s:, 'plug_tab', -1) +let s:plug_buf = get(s:, 'plug_buf', -1) +let s:mac_gui = has('gui_macvim') && has('gui_running') +let s:is_win = has('win32') +let s:nvim = has('nvim-0.2') || (has('nvim') && exists('*jobwait') && !s:is_win) +let s:vim8 = has('patch-8.0.0039') && exists('*job_start') +let s:me = resolve(expand(':p')) +let s:base_spec = { 'branch': 'master', 'frozen': 0 } +let s:TYPE = { +\ 'string': type(''), +\ 'list': type([]), +\ 'dict': type({}), +\ 'funcref': type(function('call')) +\ } +let s:loaded = get(s:, 'loaded', {}) +let s:triggers = get(s:, 'triggers', {}) + +function! plug#begin(...) + if a:0 > 0 + let s:plug_home_org = a:1 + let home = s:path(fnamemodify(expand(a:1), ':p')) + elseif exists('g:plug_home') + let home = s:path(g:plug_home) + elseif !empty(&rtp) + let home = s:path(split(&rtp, ',')[0]) . '/plugged' + else + return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.') + endif + if fnamemodify(home, ':t') ==# 'plugin' && fnamemodify(home, ':h') ==# s:first_rtp + return s:err('Invalid plug home. '.home.' is a standard Vim runtime path and is not allowed.') + endif + + let g:plug_home = home + let g:plugs = {} + let g:plugs_order = [] + let s:triggers = {} + + call s:define_commands() + return 1 +endfunction + +function! s:define_commands() + command! -nargs=+ -bar Plug call plug#() + if !executable('git') + return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.') + endif + command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(0, []) + command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(0, []) + command! -nargs=0 -bar -bang PlugClean call s:clean(0) + command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif + command! -nargs=0 -bar PlugStatus call s:status() + command! -nargs=0 -bar PlugDiff call s:diff() + command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(0, ) +endfunction + +function! s:to_a(v) + return type(a:v) == s:TYPE.list ? a:v : [a:v] +endfunction + +function! s:to_s(v) + return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n" +endfunction + +function! s:glob(from, pattern) + return s:lines(globpath(a:from, a:pattern)) +endfunction + +function! s:source(from, ...) + let found = 0 + for pattern in a:000 + for vim in s:glob(a:from, pattern) + execute 'source' s:esc(vim) + let found = 1 + endfor + endfor + return found +endfunction + +function! s:assoc(dict, key, val) + let a:dict[a:key] = add(get(a:dict, a:key, []), a:val) +endfunction + +function! s:ask(message, ...) + call inputsave() + echohl WarningMsg + let answer = input(a:message.(a:0 ? ' (y/N/a) ' : ' (y/N) ')) + echohl None + call inputrestore() + echo "\r" + return (a:0 && answer =~? '^a') ? 2 : (answer =~? '^y') ? 1 : 0 +endfunction + +function! s:ask_no_interrupt(...) + try + return call('s:ask', a:000) + catch + return 0 + endtry +endfunction + +function! s:lazy(plug, opt) + return has_key(a:plug, a:opt) && + \ (empty(s:to_a(a:plug[a:opt])) || + \ !isdirectory(a:plug.dir) || + \ len(s:glob(s:rtp(a:plug), 'plugin')) || + \ len(s:glob(s:rtp(a:plug), 'after/plugin'))) +endfunction + +function! plug#end() + if !exists('g:plugs') + return s:err('Call plug#begin() first') + endif + + if exists('#PlugLOD') + augroup PlugLOD + autocmd! + augroup END + augroup! PlugLOD + endif + let lod = { 'ft': {}, 'map': {}, 'cmd': {} } + + if exists('g:did_load_filetypes') + filetype off + endif + for name in g:plugs_order + if !has_key(g:plugs, name) + continue + endif + let plug = g:plugs[name] + if get(s:loaded, name, 0) || !s:lazy(plug, 'on') && !s:lazy(plug, 'for') + let s:loaded[name] = 1 + continue + endif + + if has_key(plug, 'on') + let s:triggers[name] = { 'map': [], 'cmd': [] } + for cmd in s:to_a(plug.on) + if cmd =~? '^.\+' + if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i')) + call s:assoc(lod.map, cmd, name) + endif + call add(s:triggers[name].map, cmd) + elseif cmd =~# '^[A-Z]' + let cmd = substitute(cmd, '!*$', '', '') + if exists(':'.cmd) != 2 + call s:assoc(lod.cmd, cmd, name) + endif + call add(s:triggers[name].cmd, cmd) + else + call s:err('Invalid `on` option: '.cmd. + \ '. Should start with an uppercase letter or ``.') + endif + endfor + endif + + if has_key(plug, 'for') + let types = s:to_a(plug.for) + if !empty(types) + augroup filetypedetect + call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim') + augroup END + endif + for type in types + call s:assoc(lod.ft, type, name) + endfor + endif + endfor + + for [cmd, names] in items(lod.cmd) + execute printf( + \ 'command! -nargs=* -range -bang -complete=file %s call s:lod_cmd(%s, "", , , , %s)', + \ cmd, string(cmd), string(names)) + endfor + + for [map, names] in items(lod.map) + for [mode, map_prefix, key_prefix] in + \ [['i', '', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']] + execute printf( + \ '%snoremap %s %s:call lod_map(%s, %s, %s, "%s")', + \ mode, map, map_prefix, string(map), string(names), mode != 'i', key_prefix) + endfor + endfor + + for [ft, names] in items(lod.ft) + augroup PlugLOD + execute printf('autocmd FileType %s call lod_ft(%s, %s)', + \ ft, string(ft), string(names)) + augroup END + endfor + + call s:reorg_rtp() + filetype plugin indent on + if has('vim_starting') + if has('syntax') && !exists('g:syntax_on') + syntax enable + end + else + call s:reload_plugins() + endif +endfunction + +function! s:loaded_names() + return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)') +endfunction + +function! s:load_plugin(spec) + call s:source(s:rtp(a:spec), 'plugin/**/*.vim', 'after/plugin/**/*.vim') +endfunction + +function! s:reload_plugins() + for name in s:loaded_names() + call s:load_plugin(g:plugs[name]) + endfor +endfunction + +function! s:trim(str) + return substitute(a:str, '[\/]\+$', '', '') +endfunction + +function! s:version_requirement(val, min) + for idx in range(0, len(a:min) - 1) + let v = get(a:val, idx, 0) + if v < a:min[idx] | return 0 + elseif v > a:min[idx] | return 1 + endif + endfor + return 1 +endfunction + +function! s:git_version_requirement(...) + if !exists('s:git_version') + let s:git_version = map(split(split(s:system('git --version'))[2], '\.'), 'str2nr(v:val)') + endif + return s:version_requirement(s:git_version, a:000) +endfunction + +function! s:progress_opt(base) + return a:base && !s:is_win && + \ s:git_version_requirement(1, 7, 1) ? '--progress' : '' +endfunction + +if s:is_win + function! s:rtp(spec) + return s:path(a:spec.dir . get(a:spec, 'rtp', '')) + endfunction + + function! s:path(path) + return s:trim(substitute(a:path, '/', '\', 'g')) + endfunction + + function! s:dirpath(path) + return s:path(a:path) . '\' + endfunction + + function! s:is_local_plug(repo) + return a:repo =~? '^[a-z]:\|^[%~]' + endfunction +else + function! s:rtp(spec) + return s:dirpath(a:spec.dir . get(a:spec, 'rtp', '')) + endfunction + + function! s:path(path) + return s:trim(a:path) + endfunction + + function! s:dirpath(path) + return substitute(a:path, '[/\\]*$', '/', '') + endfunction + + function! s:is_local_plug(repo) + return a:repo[0] =~ '[/$~]' + endfunction +endif + +function! s:err(msg) + echohl ErrorMsg + echom '[vim-plug] '.a:msg + echohl None +endfunction + +function! s:warn(cmd, msg) + echohl WarningMsg + execute a:cmd 'a:msg' + echohl None +endfunction + +function! s:esc(path) + return escape(a:path, ' ') +endfunction + +function! s:escrtp(path) + return escape(a:path, ' ,') +endfunction + +function! s:remove_rtp() + for name in s:loaded_names() + let rtp = s:rtp(g:plugs[name]) + execute 'set rtp-='.s:escrtp(rtp) + let after = globpath(rtp, 'after') + if isdirectory(after) + execute 'set rtp-='.s:escrtp(after) + endif + endfor +endfunction + +function! s:reorg_rtp() + if !empty(s:first_rtp) + execute 'set rtp-='.s:first_rtp + execute 'set rtp-='.s:last_rtp + endif + + " &rtp is modified from outside + if exists('s:prtp') && s:prtp !=# &rtp + call s:remove_rtp() + unlet! s:middle + endif + + let s:middle = get(s:, 'middle', &rtp) + let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])') + let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), '!empty(v:val)') + let rtp = join(map(rtps, 'escape(v:val, ",")'), ',') + \ . ','.s:middle.',' + \ . join(map(afters, 'escape(v:val, ",")'), ',') + let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g') + let s:prtp = &rtp + + if !empty(s:first_rtp) + execute 'set rtp^='.s:first_rtp + execute 'set rtp+='.s:last_rtp + endif +endfunction + +function! s:doautocmd(...) + if exists('#'.join(a:000, '#')) + execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '' : '') join(a:000) + endif +endfunction + +function! s:dobufread(names) + for name in a:names + let path = s:rtp(g:plugs[name]).'/**' + for dir in ['ftdetect', 'ftplugin'] + if len(finddir(dir, path)) + if exists('#BufRead') + doautocmd BufRead + endif + return + endif + endfor + endfor +endfunction + +function! plug#load(...) + if a:0 == 0 + return s:err('Argument missing: plugin name(s) required') + endif + if !exists('g:plugs') + return s:err('plug#begin was not called') + endif + let names = a:0 == 1 && type(a:1) == s:TYPE.list ? a:1 : a:000 + let unknowns = filter(copy(names), '!has_key(g:plugs, v:val)') + if !empty(unknowns) + let s = len(unknowns) > 1 ? 's' : '' + return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', '))) + end + let unloaded = filter(copy(names), '!get(s:loaded, v:val, 0)') + if !empty(unloaded) + for name in unloaded + call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + endfor + call s:dobufread(unloaded) + return 1 + end + return 0 +endfunction + +function! s:remove_triggers(name) + if !has_key(s:triggers, a:name) + return + endif + for cmd in s:triggers[a:name].cmd + execute 'silent! delc' cmd + endfor + for map in s:triggers[a:name].map + execute 'silent! unmap' map + execute 'silent! iunmap' map + endfor + call remove(s:triggers, a:name) +endfunction + +function! s:lod(names, types, ...) + for name in a:names + call s:remove_triggers(name) + let s:loaded[name] = 1 + endfor + call s:reorg_rtp() + + for name in a:names + let rtp = s:rtp(g:plugs[name]) + for dir in a:types + call s:source(rtp, dir.'/**/*.vim') + endfor + if a:0 + if !s:source(rtp, a:1) && !empty(s:glob(rtp, a:2)) + execute 'runtime' a:1 + endif + call s:source(rtp, a:2) + endif + call s:doautocmd('User', name) + endfor +endfunction + +function! s:lod_ft(pat, names) + let syn = 'syntax/'.a:pat.'.vim' + call s:lod(a:names, ['plugin', 'after/plugin'], syn, 'after/'.syn) + execute 'autocmd! PlugLOD FileType' a:pat + call s:doautocmd('filetypeplugin', 'FileType') + call s:doautocmd('filetypeindent', 'FileType') +endfunction + +function! s:lod_cmd(cmd, bang, l1, l2, args, names) + call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + call s:dobufread(a:names) + execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args) +endfunction + +function! s:lod_map(map, names, with_prefix, prefix) + call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + call s:dobufread(a:names) + let extra = '' + while 1 + let c = getchar(0) + if c == 0 + break + endif + let extra .= nr2char(c) + endwhile + + if a:with_prefix + let prefix = v:count ? v:count : '' + let prefix .= '"'.v:register.a:prefix + if mode(1) == 'no' + if v:operator == 'c' + let prefix = "\" . prefix + endif + let prefix .= v:operator + endif + call feedkeys(prefix, 'n') + endif + call feedkeys(substitute(a:map, '^', "\", '') . extra) +endfunction + +function! plug#(repo, ...) + if a:0 > 1 + return s:err('Invalid number of arguments (1..2)') + endif + + try + let repo = s:trim(a:repo) + let opts = a:0 == 1 ? s:parse_options(a:1) : s:base_spec + let name = get(opts, 'as', fnamemodify(repo, ':t:s?\.git$??')) + let spec = extend(s:infer_properties(name, repo), opts) + if !has_key(g:plugs, name) + call add(g:plugs_order, name) + endif + let g:plugs[name] = spec + let s:loaded[name] = get(s:loaded, name, 0) + catch + return s:err(v:exception) + endtry +endfunction + +function! s:parse_options(arg) + let opts = copy(s:base_spec) + let type = type(a:arg) + if type == s:TYPE.string + let opts.tag = a:arg + elseif type == s:TYPE.dict + call extend(opts, a:arg) + if has_key(opts, 'dir') + let opts.dir = s:dirpath(expand(opts.dir)) + endif + else + throw 'Invalid argument type (expected: string or dictionary)' + endif + return opts +endfunction + +function! s:infer_properties(name, repo) + let repo = a:repo + if s:is_local_plug(repo) + return { 'dir': s:dirpath(expand(repo)) } + else + if repo =~ ':' + let uri = repo + else + if repo !~ '/' + throw printf('Invalid argument: %s (implicit `vim-scripts'' expansion is deprecated)', repo) + endif + let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git') + let uri = printf(fmt, repo) + endif + return { 'dir': s:dirpath(g:plug_home.'/'.a:name), 'uri': uri } + endif +endfunction + +function! s:install(force, names) + call s:update_impl(0, a:force, a:names) +endfunction + +function! s:update(force, names) + call s:update_impl(1, a:force, a:names) +endfunction + +function! plug#helptags() + if !exists('g:plugs') + return s:err('plug#begin was not called') + endif + for spec in values(g:plugs) + let docd = join([s:rtp(spec), 'doc'], '/') + if isdirectory(docd) + silent! execute 'helptags' s:esc(docd) + endif + endfor + return 1 +endfunction + +function! s:syntax() + syntax clear + syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber + syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX + syn match plugNumber /[0-9]\+[0-9.]*/ contained + syn match plugBracket /[[\]]/ contained + syn match plugX /x/ contained + syn match plugDash /^-/ + syn match plugPlus /^+/ + syn match plugStar /^*/ + syn match plugMessage /\(^- \)\@<=.*/ + syn match plugName /\(^- \)\@<=[^ ]*:/ + syn match plugSha /\%(: \)\@<=[0-9a-f]\{4,}$/ + syn match plugTag /(tag: [^)]\+)/ + syn match plugInstall /\(^+ \)\@<=[^:]*/ + syn match plugUpdate /\(^* \)\@<=[^:]*/ + syn match plugCommit /^ \X*[0-9a-f]\{7,9} .*/ contains=plugRelDate,plugEdge,plugTag + syn match plugEdge /^ \X\+$/ + syn match plugEdge /^ \X*/ contained nextgroup=plugSha + syn match plugSha /[0-9a-f]\{7,9}/ contained + syn match plugRelDate /([^)]*)$/ contained + syn match plugNotLoaded /(not loaded)$/ + syn match plugError /^x.*/ + syn region plugDeleted start=/^\~ .*/ end=/^\ze\S/ + syn match plugH2 /^.*:\n-\+$/ + syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean + hi def link plug1 Title + hi def link plug2 Repeat + hi def link plugH2 Type + hi def link plugX Exception + hi def link plugBracket Structure + hi def link plugNumber Number + + hi def link plugDash Special + hi def link plugPlus Constant + hi def link plugStar Boolean + + hi def link plugMessage Function + hi def link plugName Label + hi def link plugInstall Function + hi def link plugUpdate Type + + hi def link plugError Error + hi def link plugDeleted Ignore + hi def link plugRelDate Comment + hi def link plugEdge PreProc + hi def link plugSha Identifier + hi def link plugTag Constant + + hi def link plugNotLoaded Comment +endfunction + +function! s:lpad(str, len) + return a:str . repeat(' ', a:len - len(a:str)) +endfunction + +function! s:lines(msg) + return split(a:msg, "[\r\n]") +endfunction + +function! s:lastline(msg) + return get(s:lines(a:msg), -1, '') +endfunction + +function! s:new_window() + execute get(g:, 'plug_window', 'vertical topleft new') +endfunction + +function! s:plug_window_exists() + let buflist = tabpagebuflist(s:plug_tab) + return !empty(buflist) && index(buflist, s:plug_buf) >= 0 +endfunction + +function! s:switch_in() + if !s:plug_window_exists() + return 0 + endif + + if winbufnr(0) != s:plug_buf + let s:pos = [tabpagenr(), winnr(), winsaveview()] + execute 'normal!' s:plug_tab.'gt' + let winnr = bufwinnr(s:plug_buf) + execute winnr.'wincmd w' + call add(s:pos, winsaveview()) + else + let s:pos = [winsaveview()] + endif + + setlocal modifiable + return 1 +endfunction + +function! s:switch_out(...) + call winrestview(s:pos[-1]) + setlocal nomodifiable + if a:0 > 0 + execute a:1 + endif + + if len(s:pos) > 1 + execute 'normal!' s:pos[0].'gt' + execute s:pos[1] 'wincmd w' + call winrestview(s:pos[2]) + endif +endfunction + +function! s:finish_bindings() + nnoremap R :call retry() + nnoremap D :PlugDiff + nnoremap S :PlugStatus + nnoremap U :call status_update() + xnoremap U :call status_update() + nnoremap ]] :silent! call section('') + nnoremap [[ :silent! call section('b') +endfunction + +function! s:prepare(...) + if empty(getcwd()) + throw 'Invalid current working directory. Cannot proceed.' + endif + + for evar in ['$GIT_DIR', '$GIT_WORK_TREE'] + if exists(evar) + throw evar.' detected. Cannot proceed.' + endif + endfor + + call s:job_abort() + if s:switch_in() + if b:plug_preview == 1 + pc + endif + enew + else + call s:new_window() + endif + + nnoremap q :if b:plug_preview==1pcendifbd + if a:0 == 0 + call s:finish_bindings() + endif + let b:plug_preview = -1 + let s:plug_tab = tabpagenr() + let s:plug_buf = winbufnr(0) + call s:assign_name() + + for k in ['', 'L', 'o', 'X', 'd', 'dd'] + execute 'silent! unmap ' k + endfor + setlocal buftype=nofile bufhidden=wipe nobuflisted nolist noswapfile nowrap cursorline modifiable nospell + if exists('+colorcolumn') + setlocal colorcolumn= + endif + setf vim-plug + if exists('g:syntax_on') + call s:syntax() + endif +endfunction + +function! s:assign_name() + " Assign buffer name + let prefix = '[Plugins]' + let name = prefix + let idx = 2 + while bufexists(name) + let name = printf('%s (%s)', prefix, idx) + let idx = idx + 1 + endwhile + silent! execute 'f' fnameescape(name) +endfunction + +function! s:chsh(swap) + let prev = [&shell, &shellcmdflag, &shellredir] + if s:is_win + set shell=cmd.exe shellcmdflag=/c shellredir=>%s\ 2>&1 + elseif a:swap + set shell=sh shellredir=>%s\ 2>&1 + endif + return prev +endfunction + +function! s:bang(cmd, ...) + try + let [sh, shellcmdflag, shrd] = s:chsh(a:0) + " FIXME: Escaping is incomplete. We could use shellescape with eval, + " but it won't work on Windows. + let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd + if s:is_win + let batchfile = tempname().'.bat' + call writefile(["@echo off\r", cmd . "\r"], batchfile) + let cmd = batchfile + endif + let g:_plug_bang = (s:is_win && has('gui_running') ? 'silent ' : '').'!'.escape(cmd, '#!%') + execute "normal! :execute g:_plug_bang\\" + finally + unlet g:_plug_bang + let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] + if s:is_win + call delete(batchfile) + endif + endtry + return v:shell_error ? 'Exit status: ' . v:shell_error : '' +endfunction + +function! s:regress_bar() + let bar = substitute(getline(2)[1:-2], '.*\zs=', 'x', '') + call s:progress_bar(2, bar, len(bar)) +endfunction + +function! s:is_updated(dir) + return !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', a:dir)) +endfunction + +function! s:do(pull, force, todo) + for [name, spec] in items(a:todo) + if !isdirectory(spec.dir) + continue + endif + let installed = has_key(s:update.new, name) + let updated = installed ? 0 : + \ (a:pull && index(s:update.errors, name) < 0 && s:is_updated(spec.dir)) + if a:force || installed || updated + execute 'cd' s:esc(spec.dir) + call append(3, '- Post-update hook for '. name .' ... ') + let error = '' + let type = type(spec.do) + if type == s:TYPE.string + if spec.do[0] == ':' + if !get(s:loaded, name, 0) + let s:loaded[name] = 1 + call s:reorg_rtp() + endif + call s:load_plugin(spec) + try + execute spec.do[1:] + catch + let error = v:exception + endtry + if !s:plug_window_exists() + cd - + throw 'Warning: vim-plug was terminated by the post-update hook of '.name + endif + else + let error = s:bang(spec.do) + endif + elseif type == s:TYPE.funcref + try + let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged') + call spec.do({ 'name': name, 'status': status, 'force': a:force }) + catch + let error = v:exception + endtry + else + let error = 'Invalid hook type' + endif + call s:switch_in() + call setline(4, empty(error) ? (getline(4) . 'OK') + \ : ('x' . getline(4)[1:] . error)) + if !empty(error) + call add(s:update.errors, name) + call s:regress_bar() + endif + cd - + endif + endfor +endfunction + +function! s:hash_match(a, b) + return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0 +endfunction + +function! s:checkout(spec) + let sha = a:spec.commit + let output = s:system('git rev-parse HEAD', a:spec.dir) + if !v:shell_error && !s:hash_match(sha, s:lines(output)[0]) + let output = s:system( + \ 'git fetch --depth 999999 && git checkout '.s:esc(sha).' --', a:spec.dir) + endif + return output +endfunction + +function! s:finish(pull) + let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen')) + if new_frozen + let s = new_frozen > 1 ? 's' : '' + call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s)) + endif + call append(3, '- Finishing ... ') | 4 + redraw + call plug#helptags() + call plug#end() + call setline(4, getline(4) . 'Done!') + redraw + let msgs = [] + if !empty(s:update.errors) + call add(msgs, "Press 'R' to retry.") + endif + if a:pull && len(s:update.new) < len(filter(getline(5, '$'), + \ "v:val =~ '^- ' && v:val !~# 'Already up.to.date'")) + call add(msgs, "Press 'D' to see the updated changes.") + endif + echo join(msgs, ' ') + call s:finish_bindings() +endfunction + +function! s:retry() + if empty(s:update.errors) + return + endif + echo + call s:update_impl(s:update.pull, s:update.force, + \ extend(copy(s:update.errors), [s:update.threads])) +endfunction + +function! s:is_managed(name) + return has_key(g:plugs[a:name], 'uri') +endfunction + +function! s:names(...) + return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)')) +endfunction + +function! s:check_ruby() + silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'") + if !exists('g:plug_ruby') + redraw! + return s:warn('echom', 'Warning: Ruby interface is broken') + endif + let ruby_version = split(g:plug_ruby, '\.') + unlet g:plug_ruby + return s:version_requirement(ruby_version, [1, 8, 7]) +endfunction + +function! s:update_impl(pull, force, args) abort + let sync = index(a:args, '--sync') >= 0 || has('vim_starting') + let args = filter(copy(a:args), 'v:val != "--sync"') + let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ? + \ remove(args, -1) : get(g:, 'plug_threads', 16) + + let managed = filter(copy(g:plugs), 's:is_managed(v:key)') + let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') : + \ filter(managed, 'index(args, v:key) >= 0') + + if empty(todo) + return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install')) + endif + + if !s:is_win && s:git_version_requirement(2, 3) + let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : '' + let $GIT_TERMINAL_PROMPT = 0 + for plug in values(todo) + let plug.uri = substitute(plug.uri, + \ '^https://git::@github\.com', 'https://github.com', '') + endfor + endif + + if !isdirectory(g:plug_home) + try + call mkdir(g:plug_home, 'p') + catch + return s:err(printf('Invalid plug directory: %s. '. + \ 'Try to call plug#begin with a valid directory', g:plug_home)) + endtry + endif + + if has('nvim') && !exists('*jobwait') && threads > 1 + call s:warn('echom', '[vim-plug] Update Neovim for parallel installer') + endif + + let use_job = s:nvim || s:vim8 + let python = (has('python') || has('python3')) && !use_job + let ruby = has('ruby') && !use_job && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) && threads > 1 && s:check_ruby() + + let s:update = { + \ 'start': reltime(), + \ 'all': todo, + \ 'todo': copy(todo), + \ 'errors': [], + \ 'pull': a:pull, + \ 'force': a:force, + \ 'new': {}, + \ 'threads': (python || ruby || use_job) ? min([len(todo), threads]) : 1, + \ 'bar': '', + \ 'fin': 0 + \ } + + call s:prepare(1) + call append(0, ['', '']) + normal! 2G + silent! redraw + + let s:clone_opt = get(g:, 'plug_shallow', 1) ? + \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : '' + + if has('win32unix') + let s:clone_opt .= ' -c core.eol=lf -c core.autocrlf=input' + endif + + let s:submodule_opt = s:git_version_requirement(2, 8) ? ' --jobs='.threads : '' + + " Python version requirement (>= 2.7) + if python && !has('python3') && !ruby && !use_job && s:update.threads > 1 + redir => pyv + silent python import platform; print platform.python_version() + redir END + let python = s:version_requirement( + \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6]) + endif + + if (python || ruby) && s:update.threads > 1 + try + let imd = &imd + if s:mac_gui + set noimd + endif + if ruby + call s:update_ruby() + else + call s:update_python() + endif + catch + let lines = getline(4, '$') + let printed = {} + silent! 4,$d _ + for line in lines + let name = s:extract_name(line, '.', '') + if empty(name) || !has_key(printed, name) + call append('$', line) + if !empty(name) + let printed[name] = 1 + if line[0] == 'x' && index(s:update.errors, name) < 0 + call add(s:update.errors, name) + end + endif + endif + endfor + finally + let &imd = imd + call s:update_finish() + endtry + else + call s:update_vim() + while use_job && sync + sleep 100m + if s:update.fin + break + endif + endwhile + endif +endfunction + +function! s:log4(name, msg) + call setline(4, printf('- %s (%s)', a:msg, a:name)) + redraw +endfunction + +function! s:update_finish() + if exists('s:git_terminal_prompt') + let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt + endif + if s:switch_in() + call append(3, '- Updating ...') | 4 + for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.force || s:update.pull || has_key(s:update.new, v:key))')) + let [pos, _] = s:logpos(name) + if !pos + continue + endif + if has_key(spec, 'commit') + call s:log4(name, 'Checking out '.spec.commit) + let out = s:checkout(spec) + elseif has_key(spec, 'tag') + let tag = spec.tag + if tag =~ '\*' + let tags = s:lines(s:system('git tag --list '.s:shellesc(tag).' --sort -version:refname 2>&1', spec.dir)) + if !v:shell_error && !empty(tags) + let tag = tags[0] + call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag)) + call append(3, '') + endif + endif + call s:log4(name, 'Checking out '.tag) + let out = s:system('git checkout -q '.s:esc(tag).' -- 2>&1', spec.dir) + else + let branch = s:esc(get(spec, 'branch', 'master')) + call s:log4(name, 'Merging origin/'.branch) + let out = s:system('git checkout -q '.branch.' -- 2>&1' + \. (has_key(s:update.new, name) ? '' : ('&& git merge --ff-only origin/'.branch.' 2>&1')), spec.dir) + endif + if !v:shell_error && filereadable(spec.dir.'/.gitmodules') && + \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir)) + call s:log4(name, 'Updating submodules. This may take a while.') + let out .= s:bang('git submodule update --init --recursive'.s:submodule_opt.' 2>&1', spec.dir) + endif + let msg = s:format_message(v:shell_error ? 'x': '-', name, out) + if v:shell_error + call add(s:update.errors, name) + call s:regress_bar() + silent execute pos 'd _' + call append(4, msg) | 4 + elseif !empty(out) + call setline(pos, msg[0]) + endif + redraw + endfor + silent 4 d _ + try + call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")')) + catch + call s:warn('echom', v:exception) + call s:warn('echo', '') + return + endtry + call s:finish(s:update.pull) + call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.') + call s:switch_out('normal! gg') + endif +endfunction + +function! s:job_abort() + if (!s:nvim && !s:vim8) || !exists('s:jobs') + return + endif + + for [name, j] in items(s:jobs) + if s:nvim + silent! call jobstop(j.jobid) + elseif s:vim8 + silent! call job_stop(j.jobid) + endif + if j.new + call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir)) + endif + endfor + let s:jobs = {} +endfunction + +function! s:last_non_empty_line(lines) + let len = len(a:lines) + for idx in range(len) + let line = a:lines[len-idx-1] + if !empty(line) + return line + endif + endfor + return '' +endfunction + +function! s:job_out_cb(self, data) abort + let self = a:self + let data = remove(self.lines, -1) . a:data + let lines = map(split(data, "\n", 1), 'split(v:val, "\r", 1)[-1]') + call extend(self.lines, lines) + " To reduce the number of buffer updates + let self.tick = get(self, 'tick', -1) + 1 + if !self.running || self.tick % len(s:jobs) == 0 + let bullet = self.running ? (self.new ? '+' : '*') : (self.error ? 'x' : '-') + let result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines) + call s:log(bullet, self.name, result) + endif +endfunction + +function! s:job_exit_cb(self, data) abort + let a:self.running = 0 + let a:self.error = a:data != 0 + call s:reap(a:self.name) + call s:tick() +endfunction + +function! s:job_cb(fn, job, ch, data) + if !s:plug_window_exists() " plug window closed + return s:job_abort() + endif + call call(a:fn, [a:job, a:data]) +endfunction + +function! s:nvim_cb(job_id, data, event) dict abort + return a:event == 'stdout' ? + \ s:job_cb('s:job_out_cb', self, 0, join(a:data, "\n")) : + \ s:job_cb('s:job_exit_cb', self, 0, a:data) +endfunction + +function! s:spawn(name, cmd, opts) + let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [''], + \ 'batchfile': (s:is_win && (s:nvim || s:vim8)) ? tempname().'.bat' : '', + \ 'new': get(a:opts, 'new', 0) } + let s:jobs[a:name] = job + let cmd = has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd + if !empty(job.batchfile) + call writefile(["@echo off\r", cmd . "\r"], job.batchfile) + let cmd = job.batchfile + endif + let argv = add(s:is_win ? ['cmd', '/c'] : ['sh', '-c'], cmd) + + if s:nvim + call extend(job, { + \ 'on_stdout': function('s:nvim_cb'), + \ 'on_exit': function('s:nvim_cb'), + \ }) + let jid = jobstart(argv, job) + if jid > 0 + let job.jobid = jid + else + let job.running = 0 + let job.error = 1 + let job.lines = [jid < 0 ? argv[0].' is not executable' : + \ 'Invalid arguments (or job table is full)'] + endif + elseif s:vim8 + let jid = job_start(s:is_win ? join(argv, ' ') : argv, { + \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]), + \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]), + \ 'out_mode': 'raw' + \}) + if job_status(jid) == 'run' + let job.jobid = jid + else + let job.running = 0 + let job.error = 1 + let job.lines = ['Failed to start job'] + endif + else + let job.lines = s:lines(call('s:system', [cmd])) + let job.error = v:shell_error != 0 + let job.running = 0 + endif +endfunction + +function! s:reap(name) + let job = s:jobs[a:name] + if job.error + call add(s:update.errors, a:name) + elseif get(job, 'new', 0) + let s:update.new[a:name] = 1 + endif + let s:update.bar .= job.error ? 'x' : '=' + + let bullet = job.error ? 'x' : '-' + let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines) + call s:log(bullet, a:name, empty(result) ? 'OK' : result) + call s:bar() + + if has_key(job, 'batchfile') && !empty(job.batchfile) + call delete(job.batchfile) + endif + call remove(s:jobs, a:name) +endfunction + +function! s:bar() + if s:switch_in() + let total = len(s:update.all) + call setline(1, (s:update.pull ? 'Updating' : 'Installing'). + \ ' plugins ('.len(s:update.bar).'/'.total.')') + call s:progress_bar(2, s:update.bar, total) + call s:switch_out() + endif +endfunction + +function! s:logpos(name) + for i in range(4, line('$')) + if getline(i) =~# '^[-+x*] '.a:name.':' + for j in range(i + 1, line('$')) + if getline(j) !~ '^ ' + return [i, j - 1] + endif + endfor + return [i, i] + endif + endfor + return [0, 0] +endfunction + +function! s:log(bullet, name, lines) + if s:switch_in() + let [b, e] = s:logpos(a:name) + if b > 0 + silent execute printf('%d,%d d _', b, e) + if b > winheight('.') + let b = 4 + endif + else + let b = 4 + endif + " FIXME For some reason, nomodifiable is set after :d in vim8 + setlocal modifiable + call append(b - 1, s:format_message(a:bullet, a:name, a:lines)) + call s:switch_out() + endif +endfunction + +function! s:update_vim() + let s:jobs = {} + + call s:bar() + call s:tick() +endfunction + +function! s:tick() + let pull = s:update.pull + let prog = s:progress_opt(s:nvim || s:vim8) +while 1 " Without TCO, Vim stack is bound to explode + if empty(s:update.todo) + if empty(s:jobs) && !s:update.fin + call s:update_finish() + let s:update.fin = 1 + endif + return + endif + + let name = keys(s:update.todo)[0] + let spec = remove(s:update.todo, name) + let new = empty(globpath(spec.dir, '.git', 1)) + + call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...') + redraw + + let has_tag = has_key(spec, 'tag') + if !new + let [error, _] = s:git_validate(spec, 0) + if empty(error) + if pull + let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : '' + call s:spawn(name, printf('git fetch %s %s 2>&1', fetch_opt, prog), { 'dir': spec.dir }) + else + let s:jobs[name] = { 'running': 0, 'lines': ['Already installed'], 'error': 0 } + endif + else + let s:jobs[name] = { 'running': 0, 'lines': s:lines(error), 'error': 1 } + endif + else + call s:spawn(name, + \ printf('git clone %s %s %s %s 2>&1', + \ has_tag ? '' : s:clone_opt, + \ prog, + \ s:shellesc(spec.uri), + \ s:shellesc(s:trim(spec.dir))), { 'new': 1 }) + endif + + if !s:jobs[name].running + call s:reap(name) + endif + if len(s:jobs) >= s:update.threads + break + endif +endwhile +endfunction + +function! s:update_python() +let py_exe = has('python') ? 'python' : 'python3' +execute py_exe "<< EOF" +import datetime +import functools +import os +try: + import queue +except ImportError: + import Queue as queue +import random +import re +import shutil +import signal +import subprocess +import tempfile +import threading as thr +import time +import traceback +import vim + +G_NVIM = vim.eval("has('nvim')") == '1' +G_PULL = vim.eval('s:update.pull') == '1' +G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1 +G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)')) +G_CLONE_OPT = vim.eval('s:clone_opt') +G_PROGRESS = vim.eval('s:progress_opt(1)') +G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads')) +G_STOP = thr.Event() +G_IS_WIN = vim.eval('s:is_win') == '1' + +class PlugError(Exception): + def __init__(self, msg): + self.msg = msg +class CmdTimedOut(PlugError): + pass +class CmdFailed(PlugError): + pass +class InvalidURI(PlugError): + pass +class Action(object): + INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-'] + +class Buffer(object): + def __init__(self, lock, num_plugs, is_pull): + self.bar = '' + self.event = 'Updating' if is_pull else 'Installing' + self.lock = lock + self.maxy = int(vim.eval('winheight(".")')) + self.num_plugs = num_plugs + + def __where(self, name): + """ Find first line with name in current buffer. Return line num. """ + found, lnum = False, 0 + matcher = re.compile('^[-+x*] {0}:'.format(name)) + for line in vim.current.buffer: + if matcher.search(line) is not None: + found = True + break + lnum += 1 + + if not found: + lnum = -1 + return lnum + + def header(self): + curbuf = vim.current.buffer + curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs) + + num_spaces = self.num_plugs - len(self.bar) + curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ') + + with self.lock: + vim.command('normal! 2G') + vim.command('redraw') + + def write(self, action, name, lines): + first, rest = lines[0], lines[1:] + msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)] + msg.extend([' ' + line for line in rest]) + + try: + if action == Action.ERROR: + self.bar += 'x' + vim.command("call add(s:update.errors, '{0}')".format(name)) + elif action == Action.DONE: + self.bar += '=' + + curbuf = vim.current.buffer + lnum = self.__where(name) + if lnum != -1: # Found matching line num + del curbuf[lnum] + if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]): + lnum = 3 + else: + lnum = 3 + curbuf.append(msg, lnum) + + self.header() + except vim.error: + pass + +class Command(object): + CD = 'cd /d' if G_IS_WIN else 'cd' + + def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None): + self.cmd = cmd + if cmd_dir: + self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd) + self.timeout = timeout + self.callback = cb if cb else (lambda msg: None) + self.clean = clean if clean else (lambda: None) + self.proc = None + + @property + def alive(self): + """ Returns true only if command still running. """ + return self.proc and self.proc.poll() is None + + def execute(self, ntries=3): + """ Execute the command with ntries if CmdTimedOut. + Returns the output of the command if no Exception. + """ + attempt, finished, limit = 0, False, self.timeout + + while not finished: + try: + attempt += 1 + result = self.try_command() + finished = True + return result + except CmdTimedOut: + if attempt != ntries: + self.notify_retry() + self.timeout += limit + else: + raise + + def notify_retry(self): + """ Retry required for command, notify user. """ + for count in range(3, 0, -1): + if G_STOP.is_set(): + raise KeyboardInterrupt + msg = 'Timeout. Will retry in {0} second{1} ...'.format( + count, 's' if count != 1 else '') + self.callback([msg]) + time.sleep(1) + self.callback(['Retrying ...']) + + def try_command(self): + """ Execute a cmd & poll for callback. Returns list of output. + Raises CmdFailed -> return code for Popen isn't 0 + Raises CmdTimedOut -> command exceeded timeout without new output + """ + first_line = True + + try: + tfile = tempfile.NamedTemporaryFile(mode='w+b') + preexec_fn = not G_IS_WIN and os.setsid or None + self.proc = subprocess.Popen(self.cmd, stdout=tfile, + stderr=subprocess.STDOUT, + stdin=subprocess.PIPE, shell=True, + preexec_fn=preexec_fn) + thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,)) + thrd.start() + + thread_not_started = True + while thread_not_started: + try: + thrd.join(0.1) + thread_not_started = False + except RuntimeError: + pass + + while self.alive: + if G_STOP.is_set(): + raise KeyboardInterrupt + + if first_line or random.random() < G_LOG_PROB: + first_line = False + line = '' if G_IS_WIN else nonblock_read(tfile.name) + if line: + self.callback([line]) + + time_diff = time.time() - os.path.getmtime(tfile.name) + if time_diff > self.timeout: + raise CmdTimedOut(['Timeout!']) + + thrd.join(0.5) + + tfile.seek(0) + result = [line.decode('utf-8', 'replace').rstrip() for line in tfile] + + if self.proc.returncode != 0: + raise CmdFailed([''] + result) + + return result + except: + self.terminate() + raise + + def terminate(self): + """ Terminate process and cleanup. """ + if self.alive: + if G_IS_WIN: + os.kill(self.proc.pid, signal.SIGINT) + else: + os.killpg(self.proc.pid, signal.SIGTERM) + self.clean() + +class Plugin(object): + def __init__(self, name, args, buf_q, lock): + self.name = name + self.args = args + self.buf_q = buf_q + self.lock = lock + self.tag = args.get('tag', 0) + + def manage(self): + try: + if os.path.exists(self.args['dir']): + self.update() + else: + self.install() + with self.lock: + thread_vim_command("let s:update.new['{0}'] = 1".format(self.name)) + except PlugError as exc: + self.write(Action.ERROR, self.name, exc.msg) + except KeyboardInterrupt: + G_STOP.set() + self.write(Action.ERROR, self.name, ['Interrupted!']) + except: + # Any exception except those above print stack trace + msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip()) + self.write(Action.ERROR, self.name, msg.split('\n')) + raise + + def install(self): + target = self.args['dir'] + if target[-1] == '\\': + target = target[0:-1] + + def clean(target): + def _clean(): + try: + shutil.rmtree(target) + except OSError: + pass + return _clean + + self.write(Action.INSTALL, self.name, ['Installing ...']) + callback = functools.partial(self.write, Action.INSTALL, self.name) + cmd = 'git clone {0} {1} {2} {3} 2>&1'.format( + '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'], + esc(target)) + com = Command(cmd, None, G_TIMEOUT, callback, clean(target)) + result = com.execute(G_RETRIES) + self.write(Action.DONE, self.name, result[-1:]) + + def repo_uri(self): + cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url' + command = Command(cmd, self.args['dir'], G_TIMEOUT,) + result = command.execute(G_RETRIES) + return result[-1] + + def update(self): + actual_uri = self.repo_uri() + expect_uri = self.args['uri'] + regex = re.compile(r'^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$') + ma = regex.match(actual_uri) + mb = regex.match(expect_uri) + if ma is None or mb is None or ma.groups() != mb.groups(): + msg = ['', + 'Invalid URI: {0}'.format(actual_uri), + 'Expected {0}'.format(expect_uri), + 'PlugClean required.'] + raise InvalidURI(msg) + + if G_PULL: + self.write(Action.UPDATE, self.name, ['Updating ...']) + callback = functools.partial(self.write, Action.UPDATE, self.name) + fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else '' + cmd = 'git fetch {0} {1} 2>&1'.format(fetch_opt, G_PROGRESS) + com = Command(cmd, self.args['dir'], G_TIMEOUT, callback) + result = com.execute(G_RETRIES) + self.write(Action.DONE, self.name, result[-1:]) + else: + self.write(Action.DONE, self.name, ['Already installed']) + + def write(self, action, name, msg): + self.buf_q.put((action, name, msg)) + +class PlugThread(thr.Thread): + def __init__(self, tname, args): + super(PlugThread, self).__init__() + self.tname = tname + self.args = args + + def run(self): + thr.current_thread().name = self.tname + buf_q, work_q, lock = self.args + + try: + while not G_STOP.is_set(): + name, args = work_q.get_nowait() + plug = Plugin(name, args, buf_q, lock) + plug.manage() + work_q.task_done() + except queue.Empty: + pass + +class RefreshThread(thr.Thread): + def __init__(self, lock): + super(RefreshThread, self).__init__() + self.lock = lock + self.running = True + + def run(self): + while self.running: + with self.lock: + thread_vim_command('noautocmd normal! a') + time.sleep(0.33) + + def stop(self): + self.running = False + +if G_NVIM: + def thread_vim_command(cmd): + vim.session.threadsafe_call(lambda: vim.command(cmd)) +else: + def thread_vim_command(cmd): + vim.command(cmd) + +def esc(name): + return '"' + name.replace('"', '\"') + '"' + +def nonblock_read(fname): + """ Read a file with nonblock flag. Return the last line. """ + fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK) + buf = os.read(fread, 100000).decode('utf-8', 'replace') + os.close(fread) + + line = buf.rstrip('\r\n') + left = max(line.rfind('\r'), line.rfind('\n')) + if left != -1: + left += 1 + line = line[left:] + + return line + +def main(): + thr.current_thread().name = 'main' + nthreads = int(vim.eval('s:update.threads')) + plugs = vim.eval('s:update.todo') + mac_gui = vim.eval('s:mac_gui') == '1' + + lock = thr.Lock() + buf = Buffer(lock, len(plugs), G_PULL) + buf_q, work_q = queue.Queue(), queue.Queue() + for work in plugs.items(): + work_q.put(work) + + start_cnt = thr.active_count() + for num in range(nthreads): + tname = 'PlugT-{0:02}'.format(num) + thread = PlugThread(tname, (buf_q, work_q, lock)) + thread.start() + if mac_gui: + rthread = RefreshThread(lock) + rthread.start() + + while not buf_q.empty() or thr.active_count() != start_cnt: + try: + action, name, msg = buf_q.get(True, 0.25) + buf.write(action, name, ['OK'] if not msg else msg) + buf_q.task_done() + except queue.Empty: + pass + except KeyboardInterrupt: + G_STOP.set() + + if mac_gui: + rthread.stop() + rthread.join() + +main() +EOF +endfunction + +function! s:update_ruby() + ruby << EOF + module PlugStream + SEP = ["\r", "\n", nil] + def get_line + buffer = '' + loop do + char = readchar rescue return + if SEP.include? char.chr + buffer << $/ + break + else + buffer << char + end + end + buffer + end + end unless defined?(PlugStream) + + def esc arg + %["#{arg.gsub('"', '\"')}"] + end + + def killall pid + pids = [pid] + if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM + pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil } + else + unless `which pgrep 2> /dev/null`.empty? + children = pids + until children.empty? + children = children.map { |pid| + `pgrep -P #{pid}`.lines.map { |l| l.chomp } + }.flatten + pids += children + end + end + pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil } + end + end + + def compare_git_uri a, b + regex = %r{^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$} + regex.match(a).to_a.drop(1) == regex.match(b).to_a.drop(1) + end + + require 'thread' + require 'fileutils' + require 'timeout' + running = true + iswin = VIM::evaluate('s:is_win').to_i == 1 + pull = VIM::evaluate('s:update.pull').to_i == 1 + base = VIM::evaluate('g:plug_home') + all = VIM::evaluate('s:update.todo') + limit = VIM::evaluate('get(g:, "plug_timeout", 60)') + tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1 + nthr = VIM::evaluate('s:update.threads').to_i + maxy = VIM::evaluate('winheight(".")').to_i + vim7 = VIM::evaluate('v:version').to_i <= 703 && RUBY_PLATFORM =~ /darwin/ + cd = iswin ? 'cd /d' : 'cd' + tot = VIM::evaluate('len(s:update.todo)') || 0 + bar = '' + skip = 'Already installed' + mtx = Mutex.new + take1 = proc { mtx.synchronize { running && all.shift } } + logh = proc { + cnt = bar.length + $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})" + $curbuf[2] = '[' + bar.ljust(tot) + ']' + VIM::command('normal! 2G') + VIM::command('redraw') + } + where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } } + log = proc { |name, result, type| + mtx.synchronize do + ing = ![true, false].include?(type) + bar += type ? '=' : 'x' unless ing + b = case type + when :install then '+' when :update then '*' + when true, nil then '-' else + VIM::command("call add(s:update.errors, '#{name}')") + 'x' + end + result = + if type || type.nil? + ["#{b} #{name}: #{result.lines.to_a.last || 'OK'}"] + elsif result =~ /^Interrupted|^Timeout/ + ["#{b} #{name}: #{result}"] + else + ["#{b} #{name}"] + result.lines.map { |l| " " << l } + end + if lnum = where.call(name) + $curbuf.delete lnum + lnum = 4 if ing && lnum > maxy + end + result.each_with_index do |line, offset| + $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp) + end + logh.call + end + } + bt = proc { |cmd, name, type, cleanup| + tried = timeout = 0 + begin + tried += 1 + timeout += limit + fd = nil + data = '' + if iswin + Timeout::timeout(timeout) do + tmp = VIM::evaluate('tempname()') + system("(#{cmd}) > #{tmp}") + data = File.read(tmp).chomp + File.unlink tmp rescue nil + end + else + fd = IO.popen(cmd).extend(PlugStream) + first_line = true + log_prob = 1.0 / nthr + while line = Timeout::timeout(timeout) { fd.get_line } + data << line + log.call name, line.chomp, type if name && (first_line || rand < log_prob) + first_line = false + end + fd.close + end + [$? == 0, data.chomp] + rescue Timeout::Error, Interrupt => e + if fd && !fd.closed? + killall fd.pid + fd.close + end + cleanup.call if cleanup + if e.is_a?(Timeout::Error) && tried < tries + 3.downto(1) do |countdown| + s = countdown > 1 ? 's' : '' + log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type + sleep 1 + end + log.call name, 'Retrying ...', type + retry + end + [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"] + end + } + main = Thread.current + threads = [] + watcher = Thread.new { + if vim7 + while VIM::evaluate('getchar(1)') + sleep 0.1 + end + else + require 'io/console' # >= Ruby 1.9 + nil until IO.console.getch == 3.chr + end + mtx.synchronize do + running = false + threads.each { |t| t.raise Interrupt } unless vim7 + end + threads.each { |t| t.join rescue nil } + main.kill + } + refresh = Thread.new { + while true + mtx.synchronize do + break unless running + VIM::command('noautocmd normal! a') + end + sleep 0.2 + end + } if VIM::evaluate('s:mac_gui') == 1 + + clone_opt = VIM::evaluate('s:clone_opt') + progress = VIM::evaluate('s:progress_opt(1)') + nthr.times do + mtx.synchronize do + threads << Thread.new { + while pair = take1.call + name = pair.first + dir, uri, tag = pair.last.values_at *%w[dir uri tag] + exists = File.directory? dir + ok, result = + if exists + chdir = "#{cd} #{iswin ? dir : esc(dir)}" + ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil + current_uri = data.lines.to_a.last + if !ret + if data =~ /^Interrupted|^Timeout/ + [false, data] + else + [false, [data.chomp, "PlugClean required."].join($/)] + end + elsif !compare_git_uri(current_uri, uri) + [false, ["Invalid URI: #{current_uri}", + "Expected: #{uri}", + "PlugClean required."].join($/)] + else + if pull + log.call name, 'Updating ...', :update + fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : '' + bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1", name, :update, nil + else + [true, skip] + end + end + else + d = esc dir.sub(%r{[\\/]+$}, '') + log.call name, 'Installing ...', :install + bt.call "git clone #{clone_opt unless tag} #{progress} #{uri} #{d} 2>&1", name, :install, proc { + FileUtils.rm_rf dir + } + end + mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok + log.call name, result, ok + end + } if running + end + end + threads.each { |t| t.join rescue nil } + logh.call + refresh.kill if refresh + watcher.kill +EOF +endfunction + +function! s:shellesc_cmd(arg) + let escaped = substitute(a:arg, '[&|<>()@^]', '^&', 'g') + let escaped = substitute(escaped, '%', '%%', 'g') + let escaped = substitute(escaped, '"', '\\^&', 'g') + let escaped = substitute(escaped, '\(\\\+\)\(\\^\)', '\1\1\2', 'g') + return '^"'.substitute(escaped, '\(\\\+\)$', '\1\1', '').'^"' +endfunction + +function! s:shellesc(arg) + if &shell =~# 'cmd.exe$' + return s:shellesc_cmd(a:arg) + endif + return shellescape(a:arg) +endfunction + +function! s:glob_dir(path) + return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)') +endfunction + +function! s:progress_bar(line, bar, total) + call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']') +endfunction + +function! s:compare_git_uri(a, b) + " See `git help clone' + " https:// [user@] github.com[:port] / junegunn/vim-plug [.git] + " [git@] github.com[:port] : junegunn/vim-plug [.git] + " file:// / junegunn/vim-plug [/] + " / junegunn/vim-plug [/] + let pat = '^\%(\w\+://\)\='.'\%([^@/]*@\)\='.'\([^:/]*\%(:[0-9]*\)\=\)'.'[:/]'.'\(.\{-}\)'.'\%(\.git\)\=/\?$' + let ma = matchlist(a:a, pat) + let mb = matchlist(a:b, pat) + return ma[1:2] ==# mb[1:2] +endfunction + +function! s:format_message(bullet, name, message) + if a:bullet != 'x' + return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))] + else + let lines = map(s:lines(a:message), '" ".v:val') + return extend([printf('x %s:', a:name)], lines) + endif +endfunction + +function! s:with_cd(cmd, dir) + return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd) +endfunction + +function! s:system(cmd, ...) + try + let [sh, shellcmdflag, shrd] = s:chsh(1) + let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd + if s:is_win + let batchfile = tempname().'.bat' + call writefile(["@echo off\r", cmd . "\r"], batchfile) + let cmd = batchfile + endif + return system(s:is_win ? '('.cmd.')' : cmd) + finally + let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] + if s:is_win + call delete(batchfile) + endif + endtry +endfunction + +function! s:system_chomp(...) + let ret = call('s:system', a:000) + return v:shell_error ? '' : substitute(ret, '\n$', '', '') +endfunction + +function! s:git_validate(spec, check_branch) + let err = '' + if isdirectory(a:spec.dir) + let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url', a:spec.dir)) + let remote = result[-1] + if v:shell_error + let err = join([remote, 'PlugClean required.'], "\n") + elseif !s:compare_git_uri(remote, a:spec.uri) + let err = join(['Invalid URI: '.remote, + \ 'Expected: '.a:spec.uri, + \ 'PlugClean required.'], "\n") + elseif a:check_branch && has_key(a:spec, 'commit') + let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir)) + let sha = result[-1] + if v:shell_error + let err = join(add(result, 'PlugClean required.'), "\n") + elseif !s:hash_match(sha, a:spec.commit) + let err = join([printf('Invalid HEAD (expected: %s, actual: %s)', + \ a:spec.commit[:6], sha[:6]), + \ 'PlugUpdate required.'], "\n") + endif + elseif a:check_branch + let branch = result[0] + " Check tag + if has_key(a:spec, 'tag') + let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir) + if a:spec.tag !=# tag && a:spec.tag !~ '\*' + let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.', + \ (empty(tag) ? 'N/A' : tag), a:spec.tag) + endif + " Check branch + elseif a:spec.branch !=# branch + let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.', + \ branch, a:spec.branch) + endif + if empty(err) + let [ahead, behind] = split(s:lastline(s:system(printf( + \ 'git rev-list --count --left-right HEAD...origin/%s', + \ a:spec.branch), a:spec.dir)), '\t') + if !v:shell_error && ahead + if behind + " Only mention PlugClean if diverged, otherwise it's likely to be + " pushable (and probably not that messed up). + let err = printf( + \ "Diverged from origin/%s (%d commit(s) ahead and %d commit(s) behind!\n" + \ .'Backup local changes and run PlugClean and PlugUpdate to reinstall it.', a:spec.branch, ahead, behind) + else + let err = printf("Ahead of origin/%s by %d commit(s).\n" + \ .'Cannot update until local changes are pushed.', + \ a:spec.branch, ahead) + endif + endif + endif + endif + else + let err = 'Not found' + endif + return [err, err =~# 'PlugClean'] +endfunction + +function! s:rm_rf(dir) + if isdirectory(a:dir) + call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir)) + endif +endfunction + +function! s:clean(force) + call s:prepare() + call append(0, 'Searching for invalid plugins in '.g:plug_home) + call append(1, '') + + " List of valid directories + let dirs = [] + let errs = {} + let [cnt, total] = [0, len(g:plugs)] + for [name, spec] in items(g:plugs) + if !s:is_managed(name) + call add(dirs, spec.dir) + else + let [err, clean] = s:git_validate(spec, 1) + if clean + let errs[spec.dir] = s:lines(err)[0] + else + call add(dirs, spec.dir) + endif + endif + let cnt += 1 + call s:progress_bar(2, repeat('=', cnt), total) + normal! 2G + redraw + endfor + + let allowed = {} + for dir in dirs + let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1 + let allowed[dir] = 1 + for child in s:glob_dir(dir) + let allowed[child] = 1 + endfor + endfor + + let todo = [] + let found = sort(s:glob_dir(g:plug_home)) + while !empty(found) + let f = remove(found, 0) + if !has_key(allowed, f) && isdirectory(f) + call add(todo, f) + call append(line('$'), '- ' . f) + if has_key(errs, f) + call append(line('$'), ' ' . errs[f]) + endif + let found = filter(found, 'stridx(v:val, f) != 0') + end + endwhile + + 4 + redraw + if empty(todo) + call append(line('$'), 'Already clean.') + else + let s:clean_count = 0 + call append(3, ['Directories to delete:', '']) + redraw! + if a:force || s:ask_no_interrupt('Delete all directories?') + call s:delete([6, line('$')], 1) + else + call setline(4, 'Cancelled.') + nnoremap d :set opfunc=delete_opg@ + nmap dd d_ + xnoremap d :call delete_op(visualmode(), 1) + echo 'Delete the lines (d{motion}) to delete the corresponding directories' + endif + endif + 4 + setlocal nomodifiable +endfunction + +function! s:delete_op(type, ...) + call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0) +endfunction + +function! s:delete(range, force) + let [l1, l2] = a:range + let force = a:force + while l1 <= l2 + let line = getline(l1) + if line =~ '^- ' && isdirectory(line[2:]) + execute l1 + redraw! + let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1) + let force = force || answer > 1 + if answer + call s:rm_rf(line[2:]) + setlocal modifiable + call setline(l1, '~'.line[1:]) + let s:clean_count += 1 + call setline(4, printf('Removed %d directories.', s:clean_count)) + setlocal nomodifiable + endif + endif + let l1 += 1 + endwhile +endfunction + +function! s:upgrade() + echo 'Downloading the latest version of vim-plug' + redraw + let tmp = tempname() + let new = tmp . '/plug.vim' + + try + let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp)) + if v:shell_error + return s:err('Error upgrading vim-plug: '. out) + endif + + if readfile(s:me) ==# readfile(new) + echo 'vim-plug is already up-to-date' + return 0 + else + call rename(s:me, s:me . '.old') + call rename(new, s:me) + unlet g:loaded_plug + echo 'vim-plug has been upgraded' + return 1 + endif + finally + silent! call s:rm_rf(tmp) + endtry +endfunction + +function! s:upgrade_specs() + for spec in values(g:plugs) + let spec.frozen = get(spec, 'frozen', 0) + endfor +endfunction + +function! s:status() + call s:prepare() + call append(0, 'Checking plugins') + call append(1, '') + + let ecnt = 0 + let unloaded = 0 + let [cnt, total] = [0, len(g:plugs)] + for [name, spec] in items(g:plugs) + let is_dir = isdirectory(spec.dir) + if has_key(spec, 'uri') + if is_dir + let [err, _] = s:git_validate(spec, 1) + let [valid, msg] = [empty(err), empty(err) ? 'OK' : err] + else + let [valid, msg] = [0, 'Not found. Try PlugInstall.'] + endif + else + if is_dir + let [valid, msg] = [1, 'OK'] + else + let [valid, msg] = [0, 'Not found.'] + endif + endif + let cnt += 1 + let ecnt += !valid + " `s:loaded` entry can be missing if PlugUpgraded + if is_dir && get(s:loaded, name, -1) == 0 + let unloaded = 1 + let msg .= ' (not loaded)' + endif + call s:progress_bar(2, repeat('=', cnt), total) + call append(3, s:format_message(valid ? '-' : 'x', name, msg)) + normal! 2G + redraw + endfor + call setline(1, 'Finished. '.ecnt.' error(s).') + normal! gg + setlocal nomodifiable + if unloaded + echo "Press 'L' on each line to load plugin, or 'U' to update" + nnoremap L :call status_load(line('.')) + xnoremap L :call status_load(line('.')) + end +endfunction + +function! s:extract_name(str, prefix, suffix) + return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$') +endfunction + +function! s:status_load(lnum) + let line = getline(a:lnum) + let name = s:extract_name(line, '-', '(not loaded)') + if !empty(name) + call plug#load(name) + setlocal modifiable + call setline(a:lnum, substitute(line, ' (not loaded)$', '', '')) + setlocal nomodifiable + endif +endfunction + +function! s:status_update() range + let lines = getline(a:firstline, a:lastline) + let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)') + if !empty(names) + echo + execute 'PlugUpdate' join(names) + endif +endfunction + +function! s:is_preview_window_open() + silent! wincmd P + if &previewwindow + wincmd p + return 1 + endif +endfunction + +function! s:find_name(lnum) + for lnum in reverse(range(1, a:lnum)) + let line = getline(lnum) + if empty(line) + return '' + endif + let name = s:extract_name(line, '-', '') + if !empty(name) + return name + endif + endfor + return '' +endfunction + +function! s:preview_commit() + if b:plug_preview < 0 + let b:plug_preview = !s:is_preview_window_open() + endif + + let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-f]\{7,9}') + if empty(sha) + return + endif + + let name = s:find_name(line('.')) + if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir) + return + endif + + if exists('g:plug_pwindow') && !s:is_preview_window_open() + execute g:plug_pwindow + execute 'e' sha + else + execute 'pedit' sha + wincmd P + endif + setlocal previewwindow filetype=git buftype=nofile nobuflisted modifiable + try + let [sh, shellcmdflag, shrd] = s:chsh(1) + let cmd = 'cd '.s:shellesc(g:plugs[name].dir).' && git show --no-color --pretty=medium '.sha + if s:is_win + let batchfile = tempname().'.bat' + call writefile(["@echo off\r", cmd . "\r"], batchfile) + let cmd = batchfile + endif + execute 'silent %!' cmd + finally + let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] + if s:is_win + call delete(batchfile) + endif + endtry + setlocal nomodifiable + nnoremap q :q + wincmd p +endfunction + +function! s:section(flags) + call search('\(^[x-] \)\@<=[^:]\+:', a:flags) +endfunction + +function! s:format_git_log(line) + let indent = ' ' + let tokens = split(a:line, nr2char(1)) + if len(tokens) != 5 + return indent.substitute(a:line, '\s*$', '', '') + endif + let [graph, sha, refs, subject, date] = tokens + let tag = matchstr(refs, 'tag: [^,)]\+') + let tag = empty(tag) ? ' ' : ' ('.tag.') ' + return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date) +endfunction + +function! s:append_ul(lnum, text) + call append(a:lnum, ['', a:text, repeat('-', len(a:text))]) +endfunction + +function! s:diff() + call s:prepare() + call append(0, ['Collecting changes ...', '']) + let cnts = [0, 0] + let bar = '' + let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)') + call s:progress_bar(2, bar, len(total)) + for origin in [1, 0] + let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))')))) + if empty(plugs) + continue + endif + call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:') + for [k, v] in plugs + let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..' + let cmd = 'git log --graph --color=never '.join(map(['--pretty=format:%x01%h%x01%d%x01%s%x01%cr', range], 's:shellesc(v:val)')) + if has_key(v, 'rtp') + let cmd .= ' -- '.s:shellesc(v.rtp) + endif + let diff = s:system_chomp(cmd, v.dir) + if !empty(diff) + let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : '' + call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)'))) + let cnts[origin] += 1 + endif + let bar .= '=' + call s:progress_bar(2, bar, len(total)) + normal! 2G + redraw + endfor + if !cnts[origin] + call append(5, ['', 'N/A']) + endif + endfor + call setline(1, printf('%d plugin(s) updated.', cnts[0]) + \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : '')) + + if cnts[0] || cnts[1] + nnoremap (plug-preview) :silent! call preview_commit() + if empty(maparg("\", 'n')) + nmap (plug-preview) + endif + if empty(maparg('o', 'n')) + nmap o (plug-preview) + endif + endif + if cnts[0] + nnoremap X :call revert() + echo "Press 'X' on each block to revert the update" + endif + normal! gg + setlocal nomodifiable +endfunction + +function! s:revert() + if search('^Pending updates', 'bnW') + return + endif + + let name = s:find_name(line('.')) + if empty(name) || !has_key(g:plugs, name) || + \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y' + return + endif + + call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch).' --', g:plugs[name].dir) + setlocal modifiable + normal! "_dap + setlocal nomodifiable + echo 'Reverted' +endfunction + +function! s:snapshot(force, ...) abort + call s:prepare() + setf vim + call append(0, ['" Generated by vim-plug', + \ '" '.strftime("%c"), + \ '" :source this file in vim to restore the snapshot', + \ '" or execute: vim -S snapshot.vim', + \ '', '', 'PlugUpdate!']) + 1 + let anchor = line('$') - 3 + let names = sort(keys(filter(copy(g:plugs), + \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)'))) + for name in reverse(names) + let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir) + if !empty(sha) + call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha)) + redraw + endif + endfor + + if a:0 > 0 + let fn = expand(a:1) + if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?')) + return + endif + call writefile(getline(1, '$'), fn) + echo 'Saved as '.a:1 + silent execute 'e' s:esc(fn) + setf vim + endif +endfunction + +function! s:split_rtp() + return split(&rtp, '\\\@hi(group, guifg, guibg, ctermfg, ctermbg, attr, guisp) + call g:Base16hi(a:group, a:guifg, a:guibg, a:ctermfg, a:ctermbg, a:attr, a:guisp) +endfun + +" Vim editor colors +call hi("Normal", s:gui05, s:gui00, s:cterm05, s:cterm00, "", "") +call hi("Bold", "", "", "", "", "bold", "") +call hi("Debug", s:gui08, "", s:cterm08, "", "", "") +call hi("Directory", s:gui0D, "", s:cterm0D, "", "", "") +call hi("Error", s:gui00, s:gui08, s:cterm00, s:cterm08, "", "") +call hi("ErrorMsg", s:gui08, s:gui00, s:cterm08, s:cterm00, "", "") +call hi("Exception", s:gui08, "", s:cterm08, "", "", "") +call hi("FoldColumn", s:gui0C, s:gui01, s:cterm0C, s:cterm01, "", "") +call hi("Folded", s:gui03, s:gui01, s:cterm03, s:cterm01, "", "") +call hi("IncSearch", s:gui01, s:gui09, s:cterm01, s:cterm09, "none", "") +call hi("Italic", "", "", "", "", "none", "") +call hi("Macro", s:gui08, "", s:cterm08, "", "", "") +call hi("MatchParen", "", s:gui03, "", s:cterm03, "", "") +call hi("ModeMsg", s:gui0B, "", s:cterm0B, "", "", "") +call hi("MoreMsg", s:gui0B, "", s:cterm0B, "", "", "") +call hi("Question", s:gui0D, "", s:cterm0D, "", "", "") +call hi("Search", s:gui01, s:gui0A, s:cterm01, s:cterm0A, "", "") +call hi("Substitute", s:gui01, s:gui0A, s:cterm01, s:cterm0A, "none", "") +call hi("SpecialKey", s:gui03, "", s:cterm03, "", "", "") +call hi("TooLong", s:gui08, "", s:cterm08, "", "", "") +call hi("Underlined", s:gui08, "", s:cterm08, "", "", "") +call hi("Visual", "", s:gui02, "", s:cterm02, "", "") +call hi("VisualNOS", s:gui08, "", s:cterm08, "", "", "") +call hi("WarningMsg", s:gui08, "", s:cterm08, "", "", "") +call hi("WildMenu", s:gui08, s:gui0A, s:cterm08, "", "", "") +call hi("Title", s:gui0D, "", s:cterm0D, "", "none", "") +call hi("Conceal", s:gui0D, s:gui00, s:cterm0D, s:cterm00, "", "") +call hi("Cursor", s:gui00, s:gui05, s:cterm00, s:cterm05, "", "") +call hi("NonText", s:gui03, "", s:cterm03, "", "", "") +call hi("LineNr", s:gui03, s:gui01, s:cterm03, s:cterm01, "", "") +call hi("SignColumn", s:gui03, s:gui01, s:cterm03, s:cterm01, "", "") +call hi("StatusLine", s:gui04, s:gui02, s:cterm04, s:cterm02, "none", "") +call hi("StatusLineNC", s:gui03, s:gui01, s:cterm03, s:cterm01, "none", "") +call hi("VertSplit", s:gui02, s:gui02, s:cterm02, s:cterm02, "none", "") +call hi("ColorColumn", "", s:gui01, "", s:cterm01, "none", "") +call hi("CursorColumn", "", s:gui01, "", s:cterm01, "none", "") +call hi("CursorLine", "", s:gui01, "", s:cterm01, "none", "") +call hi("CursorLineNr", s:gui04, s:gui01, s:cterm04, s:cterm01, "", "") +call hi("QuickFixLine", "", s:gui01, "", s:cterm01, "none", "") +call hi("PMenu", s:gui05, s:gui01, s:cterm05, s:cterm01, "none", "") +call hi("PMenuSel", s:gui01, s:gui05, s:cterm01, s:cterm05, "", "") +call hi("TabLine", s:gui03, s:gui01, s:cterm03, s:cterm01, "none", "") +call hi("TabLineFill", s:gui03, s:gui01, s:cterm03, s:cterm01, "none", "") +call hi("TabLineSel", s:gui0B, s:gui01, s:cterm0B, s:cterm01, "none", "") + +" Standard syntax highlighting +call hi("Boolean", s:gui09, "", s:cterm09, "", "", "") +call hi("Character", s:gui08, "", s:cterm08, "", "", "") +call hi("Comment", s:gui03, "", s:cterm03, "", "", "") +call hi("Conditional", s:gui0E, "", s:cterm0E, "", "", "") +call hi("Constant", s:gui09, "", s:cterm09, "", "", "") +call hi("Define", s:gui0E, "", s:cterm0E, "", "none", "") +call hi("Delimiter", s:gui0F, "", s:cterm0F, "", "", "") +call hi("Float", s:gui09, "", s:cterm09, "", "", "") +call hi("Function", s:gui0D, "", s:cterm0D, "", "", "") +call hi("Identifier", s:gui08, "", s:cterm08, "", "none", "") +call hi("Include", s:gui0D, "", s:cterm0D, "", "", "") +call hi("Keyword", s:gui0E, "", s:cterm0E, "", "", "") +call hi("Label", s:gui0A, "", s:cterm0A, "", "", "") +call hi("Number", s:gui09, "", s:cterm09, "", "", "") +call hi("Operator", s:gui05, "", s:cterm05, "", "none", "") +call hi("PreProc", s:gui0A, "", s:cterm0A, "", "", "") +call hi("Repeat", s:gui0A, "", s:cterm0A, "", "", "") +call hi("Special", s:gui0C, "", s:cterm0C, "", "", "") +call hi("SpecialChar", s:gui0F, "", s:cterm0F, "", "", "") +call hi("Statement", s:gui08, "", s:cterm08, "", "", "") +call hi("StorageClass", s:gui0A, "", s:cterm0A, "", "", "") +call hi("String", s:gui0B, "", s:cterm0B, "", "", "") +call hi("Structure", s:gui0E, "", s:cterm0E, "", "", "") +call hi("Tag", s:gui0A, "", s:cterm0A, "", "", "") +call hi("Todo", s:gui0A, s:gui01, s:cterm0A, s:cterm01, "", "") +call hi("Type", s:gui0A, "", s:cterm0A, "", "none", "") +call hi("Typedef", s:gui0A, "", s:cterm0A, "", "", "") + +" C highlighting +call hi("cOperator", s:gui0C, "", s:cterm0C, "", "", "") +call hi("cPreCondit", s:gui0E, "", s:cterm0E, "", "", "") + +" C# highlighting +call hi("csClass", s:gui0A, "", s:cterm0A, "", "", "") +call hi("csAttribute", s:gui0A, "", s:cterm0A, "", "", "") +call hi("csModifier", s:gui0E, "", s:cterm0E, "", "", "") +call hi("csType", s:gui08, "", s:cterm08, "", "", "") +call hi("csUnspecifiedStatement", s:gui0D, "", s:cterm0D, "", "", "") +call hi("csContextualStatement", s:gui0E, "", s:cterm0E, "", "", "") +call hi("csNewDecleration", s:gui08, "", s:cterm08, "", "", "") + +" CSS highlighting +call hi("cssBraces", s:gui05, "", s:cterm05, "", "", "") +call hi("cssClassName", s:gui0E, "", s:cterm0E, "", "", "") +call hi("cssColor", s:gui0C, "", s:cterm0C, "", "", "") + +" Diff highlighting +call hi("DiffAdd", s:gui0B, s:gui01, s:cterm0B, s:cterm01, "", "") +call hi("DiffChange", s:gui03, s:gui01, s:cterm03, s:cterm01, "", "") +call hi("DiffDelete", s:gui08, s:gui01, s:cterm08, s:cterm01, "", "") +call hi("DiffText", s:gui0D, s:gui01, s:cterm0D, s:cterm01, "", "") +call hi("DiffAdded", s:gui0B, s:gui00, s:cterm0B, s:cterm00, "", "") +call hi("DiffFile", s:gui08, s:gui00, s:cterm08, s:cterm00, "", "") +call hi("DiffNewFile", s:gui0B, s:gui00, s:cterm0B, s:cterm00, "", "") +call hi("DiffLine", s:gui0D, s:gui00, s:cterm0D, s:cterm00, "", "") +call hi("DiffRemoved", s:gui08, s:gui00, s:cterm08, s:cterm00, "", "") + +" Git highlighting +call hi("gitcommitOverflow", s:gui08, "", s:cterm08, "", "", "") +call hi("gitcommitSummary", s:gui0B, "", s:cterm0B, "", "", "") +call hi("gitcommitComment", s:gui03, "", s:cterm03, "", "", "") +call hi("gitcommitUntracked", s:gui03, "", s:cterm03, "", "", "") +call hi("gitcommitDiscarded", s:gui03, "", s:cterm03, "", "", "") +call hi("gitcommitSelected", s:gui03, "", s:cterm03, "", "", "") +call hi("gitcommitHeader", s:gui0E, "", s:cterm0E, "", "", "") +call hi("gitcommitSelectedType", s:gui0D, "", s:cterm0D, "", "", "") +call hi("gitcommitUnmergedType", s:gui0D, "", s:cterm0D, "", "", "") +call hi("gitcommitDiscardedType", s:gui0D, "", s:cterm0D, "", "", "") +call hi("gitcommitBranch", s:gui09, "", s:cterm09, "", "bold", "") +call hi("gitcommitUntrackedFile", s:gui0A, "", s:cterm0A, "", "", "") +call hi("gitcommitUnmergedFile", s:gui08, "", s:cterm08, "", "bold", "") +call hi("gitcommitDiscardedFile", s:gui08, "", s:cterm08, "", "bold", "") +call hi("gitcommitSelectedFile", s:gui0B, "", s:cterm0B, "", "bold", "") + +" GitGutter highlighting +call hi("GitGutterAdd", s:gui0B, s:gui01, s:cterm0B, s:cterm01, "", "") +call hi("GitGutterChange", s:gui0D, s:gui01, s:cterm0D, s:cterm01, "", "") +call hi("GitGutterDelete", s:gui08, s:gui01, s:cterm08, s:cterm01, "", "") +call hi("GitGutterChangeDelete", s:gui0E, s:gui01, s:cterm0E, s:cterm01, "", "") + +" HTML highlighting +call hi("htmlBold", s:gui0A, "", s:cterm0A, "", "", "") +call hi("htmlItalic", s:gui0E, "", s:cterm0E, "", "", "") +call hi("htmlEndTag", s:gui05, "", s:cterm05, "", "", "") +call hi("htmlTag", s:gui05, "", s:cterm05, "", "", "") + +" JavaScript highlighting +call hi("javaScript", s:gui05, "", s:cterm05, "", "", "") +call hi("javaScriptBraces", s:gui05, "", s:cterm05, "", "", "") +call hi("javaScriptNumber", s:gui09, "", s:cterm09, "", "", "") +" pangloss/vim-javascript highlighting +call hi("jsOperator", s:gui0D, "", s:cterm0D, "", "", "") +call hi("jsStatement", s:gui0E, "", s:cterm0E, "", "", "") +call hi("jsReturn", s:gui0E, "", s:cterm0E, "", "", "") +call hi("jsThis", s:gui08, "", s:cterm08, "", "", "") +call hi("jsClassDefinition", s:gui0A, "", s:cterm0A, "", "", "") +call hi("jsFunction", s:gui0E, "", s:cterm0E, "", "", "") +call hi("jsFuncName", s:gui0D, "", s:cterm0D, "", "", "") +call hi("jsFuncCall", s:gui0D, "", s:cterm0D, "", "", "") +call hi("jsClassFuncName", s:gui0D, "", s:cterm0D, "", "", "") +call hi("jsClassMethodType", s:gui0E, "", s:cterm0E, "", "", "") +call hi("jsRegexpString", s:gui0C, "", s:cterm0C, "", "", "") +call hi("jsGlobalObjects", s:gui0A, "", s:cterm0A, "", "", "") +call hi("jsGlobalNodeObjects", s:gui0A, "", s:cterm0A, "", "", "") +call hi("jsExceptions", s:gui0A, "", s:cterm0A, "", "", "") +call hi("jsBuiltins", s:gui0A, "", s:cterm0A, "", "", "") + +" Mail highlighting +call hi("mailQuoted1", s:gui0A, "", s:cterm0A, "", "", "") +call hi("mailQuoted2", s:gui0B, "", s:cterm0B, "", "", "") +call hi("mailQuoted3", s:gui0E, "", s:cterm0E, "", "", "") +call hi("mailQuoted4", s:gui0C, "", s:cterm0C, "", "", "") +call hi("mailQuoted5", s:gui0D, "", s:cterm0D, "", "", "") +call hi("mailQuoted6", s:gui0A, "", s:cterm0A, "", "", "") +call hi("mailURL", s:gui0D, "", s:cterm0D, "", "", "") +call hi("mailEmail", s:gui0D, "", s:cterm0D, "", "", "") + +" Markdown highlighting +call hi("markdownCode", s:gui0B, "", s:cterm0B, "", "", "") +call hi("markdownError", s:gui05, s:gui00, s:cterm05, s:cterm00, "", "") +call hi("markdownCodeBlock", s:gui0B, "", s:cterm0B, "", "", "") +call hi("markdownHeadingDelimiter", s:gui0D, "", s:cterm0D, "", "", "") + +" NERDTree highlighting +call hi("NERDTreeDirSlash", s:gui0D, "", s:cterm0D, "", "", "") +call hi("NERDTreeExecFile", s:gui05, "", s:cterm05, "", "", "") + +" PHP highlighting +call hi("phpMemberSelector", s:gui05, "", s:cterm05, "", "", "") +call hi("phpComparison", s:gui05, "", s:cterm05, "", "", "") +call hi("phpParent", s:gui05, "", s:cterm05, "", "", "") +call hi("phpMethodsVar", s:gui0C, "", s:cterm0C, "", "", "") + +" Python highlighting +call hi("pythonOperator", s:gui0E, "", s:cterm0E, "", "", "") +call hi("pythonRepeat", s:gui0E, "", s:cterm0E, "", "", "") +call hi("pythonInclude", s:gui0E, "", s:cterm0E, "", "", "") +call hi("pythonStatement", s:gui0E, "", s:cterm0E, "", "", "") + +" Ruby highlighting +call hi("rubyAttribute", s:gui0D, "", s:cterm0D, "", "", "") +call hi("rubyConstant", s:gui0A, "", s:cterm0A, "", "", "") +call hi("rubyInterpolationDelimiter", s:gui0F, "", s:cterm0F, "", "", "") +call hi("rubyRegexp", s:gui0C, "", s:cterm0C, "", "", "") +call hi("rubySymbol", s:gui0B, "", s:cterm0B, "", "", "") +call hi("rubyStringDelimiter", s:gui0B, "", s:cterm0B, "", "", "") + +" SASS highlighting +call hi("sassidChar", s:gui08, "", s:cterm08, "", "", "") +call hi("sassClassChar", s:gui09, "", s:cterm09, "", "", "") +call hi("sassInclude", s:gui0E, "", s:cterm0E, "", "", "") +call hi("sassMixing", s:gui0E, "", s:cterm0E, "", "", "") +call hi("sassMixinName", s:gui0D, "", s:cterm0D, "", "", "") + +" Signify highlighting +call hi("SignifySignAdd", s:gui0B, s:gui01, s:cterm0B, s:cterm01, "", "") +call hi("SignifySignChange", s:gui0D, s:gui01, s:cterm0D, s:cterm01, "", "") +call hi("SignifySignDelete", s:gui08, s:gui01, s:cterm08, s:cterm01, "", "") + +" Spelling highlighting +call hi("SpellBad", "", "", "", "", "undercurl", s:gui08) +call hi("SpellLocal", "", "", "", "", "undercurl", s:gui0C) +call hi("SpellCap", "", "", "", "", "undercurl", s:gui0D) +call hi("SpellRare", "", "", "", "", "undercurl", s:gui0E) + +" Startify highlighting +call hi("StartifyBracket", s:gui03, "", s:cterm03, "", "", "") +call hi("StartifyFile", s:gui07, "", s:cterm07, "", "", "") +call hi("StartifyFooter", s:gui03, "", s:cterm03, "", "", "") +call hi("StartifyHeader", s:gui0B, "", s:cterm0B, "", "", "") +call hi("StartifyNumber", s:gui09, "", s:cterm09, "", "", "") +call hi("StartifyPath", s:gui03, "", s:cterm03, "", "", "") +call hi("StartifySection", s:gui0E, "", s:cterm0E, "", "", "") +call hi("StartifySelect", s:gui0C, "", s:cterm0C, "", "", "") +call hi("StartifySlash", s:gui03, "", s:cterm03, "", "", "") +call hi("StartifySpecial", s:gui03, "", s:cterm03, "", "", "") + +" Java highlighting +call hi("javaOperator", s:gui0D, "", s:cterm0D, "", "", "") + +" Remove functions +delf hi + +" Remove color variables +unlet s:gui00 s:gui01 s:gui02 s:gui03 s:gui04 s:gui05 s:gui06 s:gui07 s:gui08 s:gui09 s:gui0A s:gui0B s:gui0C s:gui0D s:gui0E s:gui0F +unlet s:cterm00 s:cterm01 s:cterm02 s:cterm03 s:cterm04 s:cterm05 s:cterm06 s:cterm07 s:cterm08 s:cterm09 s:cterm0A s:cterm0B s:cterm0C s:cterm0D s:cterm0E s:cterm0F + diff --git a/doc/nukevim.txt b/doc/nukevim.txt new file mode 100644 index 0000000..14e96c9 --- /dev/null +++ b/doc/nukevim.txt @@ -0,0 +1,517 @@ +*NukeVim* nucleardog's vim config + + + ~ + ~ + \ | | \ \ /_) ~ + . | | | | / -_)\ \ / | ` \ ~ + _|\_|\_,_|_\_\\___| \_/ _|_|_|_| ~ + ~ + by nucleardog ~ + ~ + ~ + + +-------------------------------------------------------------------------+ + | HELP QUICK GUIDE | + +-------------------------------------------------------------------------+ + | Ctrl+] : follow link Ctrl+O : go back Ctrl+I : go forward | + | gO : table of contents | + +-------------------------------------------------------------------------+ + +================================================================================ +CONTENTS *NukeVim-contents* + + 1. Introduction |NukeVimIntro| + 1.1 Goals |NukeVimIntroGoals| + 1.2 Really Quick Start |NukeVimReallyQuickStart| + 1.3 Less Quick Start |NukeVimLessQuickStart| + 2. Installation |NukeVimInstall| + 2.1 Dependencies |NukeVimDependencies| + 3. Features |NukeVimFeature| + 3.1 Development |NukeVimFeatureDev| + 3.1.1 Debugger |NukeVimFeatureDebugger| + 3.1.2 Code Completion |NukeVimFeatureCodeCompletion| + 3.1.3 Tag Bar |NukeVimFeatureTagBar| + 3.1.4 Todos |NukeVimFeatureTodos| + 3.1.5 Git |NukeVimFeatureGit| + 3.1.6 Docker |NukeVimFeatureDocker| + 3.2 PHP |NukeVimFeaturePhp| + 3.2.1 Debugger |NukeVimFeaturePhpDebugger| + 3.2.1 Composer |NukeVimFeaturePhpComposer| + 3.3 UI |NukeVimFeatureUi| + 3.3.1 Fuzzy Find |NukeVimFeatureUiFuzzyFind| + 3.3.2 Terminal |NukevimFeatureUiTerminal| + 4. Architecture |NukeVimArch| + 4.1 Startup |NukeVimArchStartup| + 4.2 Modules |NukeVimArchModule| + 4.3 Plugins |NukeVimArchPlugin| + 5. Modules |NukeVimModule| + 5.1 Keymap |NukeVimModuleKeymap| + 5.2 LSP |NukeVimModuleLSP| + 5.3 PHPUnit |NukeVimModulePhpUnit| + 5.4 Plugins |NukeVimModulePlugins| + 5.5 Settings |NukeVimModuleSettings| + 5.6 Start |NukeVimModuleStart| + 5.7 Syntax |NukeVimModuleSyntax| + 5.8 UI |NukeVimModuleUi| + + + + +================================================================================ +1. Introduction *NukeVimIntro* + + +This is my modular-ish and configurable-ish neovim config. + +It's not intended to serve anyone's purpose but my own, but the core of it +should be fairly adaptable (even if a bit poorly implemented). + + +-------------------------------------------------------------------------------- +1.1 Goals *NukeVimIntroGoals* + + +The primary thing I try and do with this configuration is _enhance_ vim, not +make it into something else. + + * This config should only _add_ or _enhance_ functionality, not make any major + changes to existing functionality or workflows. + * If I'm working on a server or any other computer that doesn't have my config, + I shouldn't be totally lost and useless. Which, conversely, means someone that + is used to vim should not feel lost when using this config. + * The core experience should not be complex. Additional functionality should be + surfaced as it's required or requested. + + +-------------------------------------------------------------------------------- +1.2 Really Quick Start *NukeVimReallyQuickStart* + + +Basically... it's vim. Pretty much all of the things you're used to in vim +should be there exactly where you would expect them. + +You can press `???` at any time to trigger a pop-up help bar that shows the +customized key bindings available. (Try it now!) + +The leader key is, out of the box, the spacebar. Press it and wait briefly and +a similar legend should pop up to show the actions available. + +Some actions are only available when specific file types are loaded (e.g., +phpunit actions only display when you have a php file open). Several tools are +only available when the associated program is found in your path (e.g., git +tools are only available if git is found). If something seems missing, check +the install section and see if installing a dependency would help. + +Good luck! + + +-------------------------------------------------------------------------------- +1.3 Less Quick Start *NukeVimQuickStart* + + +This should be a quick run-down of the things that I think are probably most +important to get immediately productive. + +*Important Key Mappings:* + ++------+-------------------+---------------------------------------------------+ +| Mode | Key | Description | ++------+-------------------+---------------------------------------------------+ +| n | - (hyphen) | Open file browser in current buffer | +| nit | Alt+H/J/K/L | Select the buffer in the direction | +| n | Alt+Shift+H/J/K/L | Move the current buffer in the direction | +| nit | Ctrl+H/L | Switch tab left/right | +| n t | Ctrl+K | New tab | ++------+-------------------+---------------------------------------------------+ + +*Important Files:* + +* `lua/config/_keymap.lua`: customize general key mappings +* `lua/config/_settings.lua`: customize vim settings and global variables +* `lua/config/plugins/local.lua`: add your own plugins + + +================================================================================ +2. Installation *NukeVimInstall* + +Check out, unzip, copy or otherwise place the repo contents in your +`~/.config/nvim` folder (or whatever your platform uses). + +Run `nvim +PlugInstall +NukeVimInstall +qall` to install all the relevant +plugins, perform any initial NukeVim or other plugin setup tasks, and exit. + +This may take several minutes if you have a few coc extensions. npm is sloooow. + + +-------------------------------------------------------------------------------- +2.1 Dependencies *NukeVimDependencies* + +Your nvim install should have the Python3 provider properly set up. Verify +this with the `:checkhealth` command. Generally this requires installing the +`pynvim` package, but the checkhealth command should point you in the right +direction. + +// TODO: Add a NukeVim checkhealth provider to just validate all this shit automatically. + +Several plugins require external programs in order to function (in many cases +to even make sense at all). Those are listed below. + +Generally you should be able to get by without any of these programs installed, +the associated plugins should just automatically be disabled. If not, that's +a bug. + +*composer* -- php package manager +Required By: phpctags, vim-composer +See: https://getcomposer.org/ + +*ctags* -- code tag parser +Required By: phpctags, tagbar +See: https://github.com/universal-ctags/ctags + +*deno* -- javascript/typescript plugin runtime +Required By: denops-docker +See: https://deno.land/ + +*docker* -- build and run containers +Required By: vim-docker-tools, denops-docker, +See: https://www.docker.com/ + +*git* -- source code control +Required By: vim-fugitive, gv, vim-gitgutter, blamer +See: https://git-scm.com/ + +*npm* -- javascript package manager +Required By: coc +See: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm + +*php* -- php language runtime +Required By: phpctags, vim-composer +See: https://php.org/ + + +================================================================================ +3. Features *NukeVimFeature* + + +-------------------------------------------------------------------------------- +3.1 Development *NukeVimFeatureDev* + + +-------------------------------------------------------------------------------- +3.1.1 Debugger *NukeVimFeatureDebugger* + + +-------------------------------------------------------------------------------- +3.1.2 Code Completion *NukeVimFeatureCodeCompletion* + + +-------------------------------------------------------------------------------- +3.1.3 Tag Bar *NukeVimFeatureTagBar* + + +-------------------------------------------------------------------------------- +3.1.4 Todos *NukeVimFeatureTodos* + + +-------------------------------------------------------------------------------- +3.1.5 Git *NukeVimFeatureGit* + + +-------------------------------------------------------------------------------- +3.1.6 Docker *NukevimFeatureDocker* + + +-------------------------------------------------------------------------------- +3.2 PHP *NukeVimFeaturePhp* + + +-------------------------------------------------------------------------------- +3.2.1 Debugger *NukeVimFeaturePhpDebugger* + + +-------------------------------------------------------------------------------- +3.2.2 Composer *NukeVimFeaturePhpComposer* + + +-------------------------------------------------------------------------------- +3.3 UI *NukeVimFeatureUi* + + +-------------------------------------------------------------------------------- +3.3.1 Fuzzy Find *NukeVimFeatureUiFuzzyFind* + + +-------------------------------------------------------------------------------- +3.3.2 Terminal *NukeVimFeatureUiTerminal* + + +================================================================================ +4. Architecture *NukeVimArch* + + +-------------------------------------------------------------------------------- +4.1 Startup *NukeVimArchStartup* + + +-------------------------------------------------------------------------------- +4.2 Modules *NukeVimArchModule* + + +-------------------------------------------------------------------------------- +4.3 Plugins *NukeVimArchPlugin* + + +================================================================================ +5. Modules *NukeVimModule* + +Modules are the core of NukeVim, generally providing high-level/core +functionality. Though because of technical limitations there are a couple that +are quite specific. + +In addition to the module-specific configuration listed below, every module's +configuration block supports two top-level properties, though both are optional: + +* `enable`: if this is set and not `true`, then this module is skipped +* `order`: all modules are loaded, initialized, etc sorted by the ascending + value of the order property; any modules which do not specify an order value + (order = nil) are sorted to the end of the initialization list; any modules + with matching orders (including nil) are initialized in an undefined order + relative to each other. + + +-------------------------------------------------------------------------------- +5.1 Keymap *NukeVimModuleKeymap* + + +The keymap module provides the ability to map keys directly as well as is +used by the Plugins module to register plugin-specific key mappings. If enabled, +the keymap module also handles generating the help/legend that you can trigger +with `???` or after pressing the leader key. + +In `lua/_config.lua`, a couple of options are provided directly: + + * `ui.enable`: whether to enable the legend when pressing the `???` combo or + after pressing the leader key. + * `ui.show_builtin`: if this is enabled then the legend will also show vim's + built-in key bindings, not just the customized ones. + +A list of key bindings can be provided on the `keys` property. + +By default, the general key mappings registered through the `keys` property are +included from `lua/config/_keymap.lua`. Mappings for plugins are generally +contained in the plugin config block in the plugin files. See +|NukeVimModulePlugins|. + +Supported options for each keymap are: + + * `mode`: the mode to register this key combo in (e.g., `n`, `i`, `v`, etc) + * `key`: either a string where each character is expected to represent a single + key (e.g., 'jj') or an array where each element is a key (e.g., + `{ '', 'g', 'c' }`. + * `map`: what to bind to this keypress + * `label`: the label to show in the legend/help + * `group`: set true if this doesn't actually map a key but just provides a label + for a group of keys + * `virtual`: set true if this doesn't actually map a key but instead is just + intended to provide a label for an existing mapping + * `hidden`: set true if you want this map registered but to _not_ display in + the legend; no effect if the legend UI isn't enabled + * `options`: these are passed through to the map api, you can set `silent`, + `nowait`, and `noremap`. If the `options` table isn't specified, than the + default options is `noremap`. + +Examples: + +Basic Mapping: + + { + mode = 'n', + key = 'jj', + map = '', + label = 'escape' + }, + +Multiple Key Mapping: + + { + mode = 'n', + key = { '', '' }, + map = ':syn sync fromstart', + label = 'recalculate syntax highlighting' + }, + +Virtual Mapping (Label Only): + + { + mode = 'n', + key = '-', + virtual = true, + label = 'browse files with netrw' + } + +Hidden Mapping: + + { + mode = 'n', + key = '', + map = ':lua nukevim:help()', + label = 'help', + hidden = true + }, + +Group Mapping (Label Only): + + { + mode = 'n', + key = { '', 'd' }, + group = true, + label = 'development tools' + }, + { mode = 'n', key = { '', 'd', 'a' }, map = '...', label = 'tool a' }, + { mode = 'n', key = { '', 'd', 'b' }, map = '...', label = 'tool b' }, + { mode = 'n', key = { '', 'd', 'c' }, map = '...', label = 'tool c' }, + +Vim Mapping Options: + + { + mode = 'i', + key = { '' }, + map = 'j', + label = 'select buffer down', + options = { silent = true } + } + + +-------------------------------------------------------------------------------- +5.2 LSP *NukeVimModuleLSP* + + +The LSP module is responsible for initializing and configuring NeoVim's built in +LSP client. + +It provides only minimal functionality, but must be configured with any LSP +providers you expect to use in NeoVim. + +All providers are configured under a top level `provders` property. The LSP +configuration is fairly specific to each provider, but the general format +is: + + providers = { + intelephense = { + command = { 'intelephense', '--stdio' }, + filetypes = { 'php' } + } + } + + +-------------------------------------------------------------------------------- +5.3 PHPUnit *NukeVimModulePhpUnit* + + +The PHPUnit module is responsible for providing an interface to PHPUnit. It has +no configuration options, but registers several key bindings in the +interface for running PHPUnit tests when you have a PHP file open. + +It is hardcoded to run PHPUnit using the path `./vendor/bin/phpunit` so should +always use the version of PHPUnit included in your project. + + +-------------------------------------------------------------------------------- +5.4 Plugins *NukeVimModulePlugins* + + +The plugins module is responsible for initializing and configuring all external +vim plugins. By default, this relies on `vim-plug` to provide the actual plugin +management. + +The plugins module provides one top-level option: + + * `path`: the path on disk where plugins should be stored + +The list of plugins should be provided as the `plugins` property. By default, +this is included from `lua/config/_plugins.lua` which in turn includes and +merges all the plugins in the files in `lua/config/plugins/`. + +Each plugin supports a several properties, all except `name` are optional: + + * `enable`: if set and not `true`, the plugin will be skipped + * `name`: the name of the plugin, generally a github reference (`user/plugin`) + * `config`: passed through as-is to both `vim-plug` and the plugin itself, some + useful options available from vim-plug: + * `branch`: override the branch to check out from git + * `on`: delay loading the plugin until one of the specified commands is called + * `do`: command to run after install/update + * `requires`: a list of programs that should be available in your path in order + for this plugin to be enabled (to, e.g., disable a docker plugin if docker + isn't installed) + * `keys`: a list of key mappings in the format expected by the keymap module + (see |NukeVimModuleKeymap|) that should be registered if this plugin is enabled + +In addition to the plugin itself, if a file is present at +`lua/plugin/.lua` it will be loaded and registered with the module +system to allow you to provide additional customization or initialization +logic. See |NukeVimArchPlugin| for more information. + + +-------------------------------------------------------------------------------- +5.5 Settings *NukeVimModuleSettings* + + +This module is responsible for setting vim settings and global variables. + +The settings module provides a single top-level option: + + * `settings`: Set a `o` table to provide options, and a `g` table to set + global variables. + +By default, the settings configuration is loaded from `lua/config/_settings.lua`. + +The `o` property should be set to a table containing vim options and their value. +Generally, this is anything you would configure with `set option` or +`set option=value`. + +In the case of "boolean" options (e.g., `wrap` and `nowrap`) you should not set +the `no` option, but instead set the option to value. That is, instead of +`nowrap = true`, set `wrap = false`. + +The `g` property should be set to a table containing any global variables you +want to set on startup. Generally, this is anything you would configure with +`let g:option=value`. + + +-------------------------------------------------------------------------------- +5.6 Start *NukeVimModuleStart* + + +This module has no configuration options available. It provides the NukeVim +splash screen on startup. + + +-------------------------------------------------------------------------------- +5.7 Syntax *NukeVimModuleSyntax* + + +This module has no configuration options available. It simply exists to resolve +some conflicts between some syntax highlighting plugins. + + +-------------------------------------------------------------------------------- +5.8 UI *NukeVimModuleUi* + + +The UI module is generally responsible for how vim looks. + +It provides two top level properties: + + * `tui`: configuration to apply on startup unconditionally + * `gui`: configuration to apply on top of the `tui` options if we detect + that vim is running in some sort of gui + +Each property supports the following options: + + * `theme`: the colorscheme to apply, this is basically `set colorscheme` + * `show_whitespace`: if enabled, then highlighting rules will be added to + make whitespace visible in the editor + * `font`: supports two properties: `family` and `size` + diff --git a/doc/tags b/doc/tags new file mode 100644 index 0000000..0b2b655 --- /dev/null +++ b/doc/tags @@ -0,0 +1,42 @@ +NukeVim nukevim.txt /*NukeVim* +NukeVim-contents nukevim.txt /*NukeVim-contents* +NukeVimArch nukevim.txt /*NukeVimArch* +NukeVimArchModule nukevim.txt /*NukeVimArchModule* +NukeVimArchPlugin nukevim.txt /*NukeVimArchPlugin* +NukeVimArchStartup nukevim.txt /*NukeVimArchStartup* +NukeVimDependencies nukevim.txt /*NukeVimDependencies* +NukeVimFeature nukevim.txt /*NukeVimFeature* +NukeVimFeatureCodeCompletion nukevim.txt /*NukeVimFeatureCodeCompletion* +NukeVimFeatureDebugger nukevim.txt /*NukeVimFeatureDebugger* +NukeVimFeatureDev nukevim.txt /*NukeVimFeatureDev* +NukeVimFeatureGit nukevim.txt /*NukeVimFeatureGit* +NukeVimFeaturePhp nukevim.txt /*NukeVimFeaturePhp* +NukeVimFeaturePhpComposer nukevim.txt /*NukeVimFeaturePhpComposer* +NukeVimFeaturePhpDebugger nukevim.txt /*NukeVimFeaturePhpDebugger* +NukeVimFeatureTagBar nukevim.txt /*NukeVimFeatureTagBar* +NukeVimFeatureTodos nukevim.txt /*NukeVimFeatureTodos* +NukeVimFeatureUi nukevim.txt /*NukeVimFeatureUi* +NukeVimFeatureUiFuzzyFind nukevim.txt /*NukeVimFeatureUiFuzzyFind* +NukeVimFeatureUiTerminal nukevim.txt /*NukeVimFeatureUiTerminal* +NukeVimInstall nukevim.txt /*NukeVimInstall* +NukeVimIntro nukevim.txt /*NukeVimIntro* +NukeVimIntroGoals nukevim.txt /*NukeVimIntroGoals* +NukeVimModule nukevim.txt /*NukeVimModule* +NukeVimModuleKeymap nukevim.txt /*NukeVimModuleKeymap* +NukeVimModuleLSP nukevim.txt /*NukeVimModuleLSP* +NukeVimModulePhpUnit nukevim.txt /*NukeVimModulePhpUnit* +NukeVimModulePlugins nukevim.txt /*NukeVimModulePlugins* +NukeVimModuleSettings nukevim.txt /*NukeVimModuleSettings* +NukeVimModuleStart nukevim.txt /*NukeVimModuleStart* +NukeVimModuleSyntax nukevim.txt /*NukeVimModuleSyntax* +NukeVimModuleUi nukevim.txt /*NukeVimModuleUi* +NukeVimQuickStart nukevim.txt /*NukeVimQuickStart* +NukeVimReallyQuickStart nukevim.txt /*NukeVimReallyQuickStart* +NukevimFeatureDocker nukevim.txt /*NukevimFeatureDocker* +composer nukevim.txt /*composer* +ctags nukevim.txt /*ctags* +deno nukevim.txt /*deno* +docker nukevim.txt /*docker* +git nukevim.txt /*git* +npm nukevim.txt /*npm* +php nukevim.txt /*php* diff --git a/lua/_config.lua b/lua/_config.lua new file mode 100644 index 0000000..048ace3 --- /dev/null +++ b/lua/_config.lua @@ -0,0 +1,193 @@ +-------------------------------------------------------------------------------- +-- _config.lua -- +-------------------------------------------------------------------------------- +-- +-- This is where you change settings for nukevim modules. +-- + +-- +-- * Each key in this table is a nukevim module. (Valid modules are any +-- file under `lua/module/`). +-- * Each value in this table is the configuration for the module. +-- * The configuration _must_ be a table (`{ ... }`). +-- * The configuration _may_ include a `enable` property. +-- * If this is present and not `true`, then the module will be skipped. +-- * The configuration _may_ include a `order` property. +-- * Modules are processed from lowest to highest order number. +-- * Modules which do not have an order specified are processed last. +-- * Those with matching orders (including nil) will be processed in +-- an _undefined order_. And I mean undefined. I have no idea what lua +-- is doing but it's basically random. +-- + +return { + + +-------------------------------------------------------------------------------- +-- CORE -- +-------------------------------------------------------------------------------- + + + ------------------------------------------------------------ + -- Plugins + -- + -- Manage loading and initializing vim plugins. + -- + -- * The general plugin list is kept in `_plugins.lua` (and + -- pulled in by the `require()` below. Add your plugins + -- there. + -- * Some modules have their own plugin dependencies. Those + -- modules automatically register their own plugins. They + -- do not need to also be listed here. + -- + plugins = { + order = 10, + -- Path on disk to store the actual plugin code at. + path = "~/.config/nvim/plugins", + -- A list of plugins to install and load. + -- Load from `_plugins.lua`. + plugins = require('config/_plugins') + }, + + ------------------------------------------------------------ + -- Keymap + -- + -- Handle mapping keys to things and, optionally, generating + -- a UI for showing a legend. + -- + -- * The general keymap list is kept in `_keymap.lua` (and + -- pulled in by the `require()` below. Add your keymaps + -- there. + -- * Many keymaps associated with plugins are defined in + -- the plugin's configuration. Look at the plugins module + -- configuration for those. + -- * Many modules have their own mappings that need to be + -- included. They automatically register them. They do + -- not need to also be listed here. + -- + keymap = { + order = 20, + -- Whether to provide a UI/legend for the key mappings. + ui = { + -- If enabled, the `which-key` plugin will be set up and + -- all key bindings will be run through it. + -- If disabled, the plugin will not be included and all + -- key bindings will be registered through the nvim native API. + enable = true, + -- If enabled, the legend will show keys built-in to vim as well + -- as custom plugin/module key bindings. + -- If disabled, only custom plugin/module key bindings will be + -- shown. + show_builtin = false + }, + -- The list of keymaps to register. + -- Load from `_keymap.lua`. + keys = require('config/_keymap') + }, + + ------------------------------------------------------------ + -- Settings + -- + -- Allows setting vim's native configuration options and + -- global variables. + -- + -- * The settings are kept in `_settings.lua` (and pulled in + -- by the `require()` below. Add your settings there. + -- * Several modules and plugins may also set options or + -- global variables. They automatically manage this and + -- the settings do not need to be listed here. + -- * In the event of a conflict between a module/plugin + -- and your settings file, your settings file will + -- _generally_ prevail. + -- + settings = { + order = 30, + settings = require('config/_settings'), + }, + + +-------------------------------------------------------------------------------- +-- UI -- +-------------------------------------------------------------------------------- + + + ------------------------------------------------------------ + -- UI + -- + -- General user interface settings + -- + -- * These settings are split into two sections: tui and gui + -- * tui: these settings are _always_ applied + -- * gui: these settings are applied _on top of_ tui settings + -- when running vim in a gui such as neovim-qt + -- * If for some reason you want to set a tui theme but _not_ + -- any theme for gui, you can set gui's theme to `default`. + -- + ui = { + order = 40, + -- Base settings -- applied in terminal, and applied before + -- gui settings in gui + tui = { + -- Colorscheme to use (i.e., set colorscheme ) + theme = "base16-eighties", + -- If configured, this will apply styling to whitespace so + -- it is visible in the editor + -- If set to true, default styling will be applied. + -- If set to a string, the specified colour will be used as the + -- highlight for whitespace (e.g., `gray30`) + show_whitespace = true + }, + -- Override settings for gui mode + gui = { + -- Set the font family and size to use + font = { family = 'Source Code Variable', size = 10 }, + theme = 'base16-eighties', + show_whitespace = true + }, + }, + +-------------------------------------------------------------------------------- +-- PROGRAMMING -- +-------------------------------------------------------------------------------- + +-------------------------------------------------------------------------------- +-- OTHER -- +-------------------------------------------------------------------------------- + + + ------------------------------------------------------------ + -- Syntax + -- + -- More comprehensive and up-to-date syntax highlighting rules + -- + -- This is basically just a plugin, but it requires a specific + -- global variable to be set earlier than the plugin system + -- allows (i.e., before the plugin itself is loaded) so it's + -- a module. + -- + -- There are no options to configure. + -- + syntax = { + order = 50, + }, + + ----------------------------------------------------------- + phpunit = { + order = 60, + }, + + lsp = { + order = 70, + providers = { + intelephense = { + command = { 'intelephense', '--stdio' }, + filetypes = { 'php' } + } + } + }, + + start = { + order = 80, + }, + +} diff --git a/lua/config/_keymap.lua b/lua/config/_keymap.lua new file mode 100644 index 0000000..b3a6959 --- /dev/null +++ b/lua/config/_keymap.lua @@ -0,0 +1,86 @@ +-- This file allows binding arbitrary keys in vim. +-- If a keymap is tied to a specific plugin, it should generally be specified +-- in the plugins file attached to that plugin. +-- +-- When making a binding, group, etc, the key to bind to shoudl be specified +-- as an array. However, as long as _each character_ represents a single keypress +-- the key can be specified as a string. E.g., `key = 'jj'` and `key = { 'j', 'j' }` +-- are equivalent. However, `key = { '' }` would be parsed as +-- `key = {'<', 'A', '-', 'h', '>'} +-- +-- There are four main types of keymap bindings: +-- * Group: This only serves to provide a label for the keymap legend for +-- keys under a prefix. (e.g., label for `f` when we have bindings +-- for `fg` and `fh`). +-- `{ mode = 'n', key = { '', 'p' }, group = true, label = "Sample Group" }` +-- * Virtual: This registers a label in the keymap legend, but doesn't +-- actually change the binding of the key. +-- `{ mode = 'n', key = { 'g', 'q' }, virtual = true, description = 'reformat text, wrapping line length' }` +-- * Hidden: The key is bound through normal vim functionality, bypassing the +-- keymap legend so that the key will not show up in the legend. +-- `{ mode = 'n', key = { 'h' }, map = ':echo "Hello, world!'"', label = 'Hello world button', hidden = true +-- `{ mode = 'n', key = 'aaa', map = ':echo "Hello, world!'"', label = 'Hello world button', hidden = true} +-- * Normal: The key is bound, and the key is shown in the legend. +-- `{ mode = 'n', key = { 'j' }, map = ':echo "Hello, world!'"', label = 'Hello world button' } +-- `{ mode = 'n', key = 'aaa', map = ':echo "Hello, world!'"', label = 'Hello world button' } + +return { + -- { mode = 'n', key = { '' }, map = ':call SynStack()', label = 'show syntax token' }, + { mode = 'n', key = { '' }, map = ':lua nukevim:help()', label = 'help' }, + + -- Provide labels for the main leader groups + { mode = 'n', key = { '', 'c' }, group = true, label = 'code' }, + { mode = 'n', key = { '', 'd' }, group = true, label = 'dev tools' }, + { mode = 'v', key = { '', 'd' }, group = true, label = 'dev tools' }, + { mode = 'n', key = { '', 'g' }, group = true, label = 'git' }, + { mode = 'n', key = { '', 'l' }, group = true, label = 'language tools' }, + { mode = 'n', key = { '', 'w' }, group = true, label = 'workspace' }, + + -- A group label for the key legend + { mode = 'n', key = 'z', group = true, label = 'text operations' }, + -- A "virtual" key to add an existing vim bind to the legend + { mode = 'n', key = 'z=', virtual = true, description = 'check spelling' }, + + -- Escape from insert with jj + { mode = 'i', key = 'j', group = true, label = 'j' }, + { mode = 'i', key = 'jj', map = '', label = 'escape' }, + + -- Dehighlight and recompute syntax highlighting + { mode = 'n', key = { '', '' }, map = ':silent noh echo:syn sync fromstart', label = 'refresh' }, + + -- Directory browsing + { mode = 'n', key = { '-' }, virtual = true, label = "browse files" }, + + -- Move between buffers + { mode = 'n', key = { '' }, map = 'h', label = 'select buffer left' }, + { mode = 'n', key = { '' }, map = 'j', label = 'select buffer down' }, + { mode = 'n', key = { '' }, map = 'k', label = 'select buffer up' }, + { mode = 'n', key = { '' }, map = 'l', label = 'select buffer right' }, + + { mode = 'i', key = { '' }, map = 'h', label = 'select buffer left', hidden = true }, + -- { mode = 'i', key = { '' }, map = 'j', label = 'select buffer down', hidden = true }, + -- { mode = 'i', key = { '' }, map = 'k', label = 'select buffer up', hidden = true }, + { mode = 'i', key = { '' }, map = 'j', label = 'select buffer down', hidden = true, options = { silent = true }}, + { mode = 'i', key = { '' }, map = 'k', label = 'select buffer up', hidden = true, options = { silent = true }}, + { mode = 'i', key = { '' }, map = 'l', label = 'select buffer right', hidden = true }, + + -- Tab navigation + { mode = 'n', key = { '' }, map = ':tabnew', label = 'new tab' }, + { mode = 'n', key = { '' }, map = ':tabnext', label = 'next tab' }, + { mode = 'i', key = { '' }, map = ':tabnext', label = 'next tab' }, + { mode = 'n', key = { '' }, map = ':tabprev', label = 'previous tab' }, + { mode = 'i', key = { '' }, map = ':tabprev', label = 'previous tab' }, + + -- Scroll autocomplete + { mode = 'i', key = { '' }, map = '', label = 'next autocomplete', hidden = true }, + { mode = 'i', key = { '' }, map = '', label = 'previous autocomplete', hidden = true }, + + -- Terminal bindings + { mode = 't', key = { '' }, map = 'h', label = 'select buffer left', hidden = true }, + { mode = 't', key = { '' }, map = 'j', label = 'select buffer down', hidden = true }, + { mode = 't', key = { '' }, map = 'k', label = 'select buffer up', hidden = true }, + { mode = 't', key = { '' }, map = 'l', label = 'select buffer right', hidden = true }, + { mode = 't', key = { '' }, map = ':tabprev', label = 'select buffer right', hidden = true }, + { mode = 't', key = { '' }, map = ':tabnext', label = 'select buffer right', hidden = true }, + { mode = 't', key = { 'j', 'j' }, map = '', label = 'escape', hidden = true }, +} diff --git a/lua/config/_plugins.lua b/lua/config/_plugins.lua new file mode 100644 index 0000000..7ced49f --- /dev/null +++ b/lua/config/_plugins.lua @@ -0,0 +1,29 @@ +-- Plugins +-- +-- Each entry in this table specifies one plugin that could be loaded. Each +-- plugin can contain the following properties: +-- +-- * name: plugin path, generally a github username/repo-name +-- * config: a table to pass through to the plugin manager, see, e.g., https://github.com/junegunn/vim-plug +-- * enable: if present and not set to true, this plugin won't be loaded +-- * requires: a table listing system binaries that must be present for this +-- plugin to be enabled +-- * keys: a list of keymaps (in the same format as _keymap.lua) that will be +-- registered when this plugin is enabled +-- +local merge = require('lib/merge') + +return merge({ + -- Libraries and frameworks that provide functionality that other plugins + -- consume. + require('config/plugins/lib'), + + require('config/plugins/development'), + require('config/plugins/editing'), + require('config/plugins/ui'), + + require('config/plugins/tmp'), + + require('config/plugins/lang-php'), + +}) diff --git a/lua/config/_settings.lua b/lua/config/_settings.lua new file mode 100644 index 0000000..78ee93d --- /dev/null +++ b/lua/config/_settings.lua @@ -0,0 +1,61 @@ +return { + -- vim options + -- these are things you would apply with `set thing` or `set thing=value`. + o = { + -- Disable modeline (security risk) + modeline = false, + -- Enable wrapping (visually) at the end of the window + wrap = true, + -- Display markers _after_ the 80th and 120th columns + cc = '81,121', + -- Smart search case sensitivity: If anything in search term is + -- uppercase, match case sensitive. Otherwise match case-insensitive. + ignorecase = true, + smartcase = true, + -- Allow backspace through indentation and stop at the beginning of + -- the line + backspace = 'start,indent', + + -- Set defaults, should be overridden by the editorconfig plugin if you + -- have one. + softtabstop = 0, + shiftwidth = 4, + tabstop = 4, + expandtab = false, + + -- Use smart-ish indentation + autoindent = true, + copyindent = true, + preserveindent = true, + + -- Enable extended color support on terminal + termguicolors = true, + + -- Automatically reload changed files + autoread = true, + + -- How long for a multi-key binding to time out + -- This basically just controls how long before + -- the key helper pops up if you have the keymap + -- ui enabled. + timeoutlen = 300, + + -- Show line numbers + number = true, + + -- Highlight the line the cursor is on + cursorline = true, + + -- Keep a persistent undo file, allow undoing after closing and reopening + -- a file. + undofile = true, + + }, + -- global variables + -- these are things you would apply with `let g:thing=value` + g = { + -- Control the 'leader' key for extended key bindings + mapleader = ' ' + } + +} diff --git a/lua/config/plugins/development.lua b/lua/config/plugins/development.lua new file mode 100644 index 0000000..b32f3b2 --- /dev/null +++ b/lua/config/plugins/development.lua @@ -0,0 +1,269 @@ +-------------------------------------------------------------------------------- +-- Development +-------------------------------------------------------------------------------- +-- Tools for supporting development, excluding language-specific which should +-- go in `lang-.lua`. +-- + +return { + +-------------------------------------------------------------------------------- +-- Debugging +-------------------------------------------------------------------------------- + + { + name = 'vim-vdebug/vdebug', + keys = { + { mode = 'n', key = { '', 'd', 'd' }, group = true, label = 'debugger' }, + { mode = 'v', key = { '', 'd', 'd' }, group = true, label = 'debugger' }, + { mode = 'n', key = { '' }, virtual = true, label = 'start debugger' }, + { mode = 'n', key = { '' }, virtual = true, label = 'set breakpoint' }, + { mode = 'n', key = { '', 'd', 'd', 'b' }, map = ':lua nukevim.modules:get("vim-vdebug/vdebug"):setBreakpoint()', label = 'toggle breakpoint' }, + { mode = 'n', key = { '', 'd', 'd', 'c' }, map = ':lua nukevim.modules:get("vim-vdebug/vdebug"):setConditionalBreakpoint()', label = 'conditional breakpoint' }, + { mode = 'n', key = { '', 'd', 'd', 't' }, map = ':lua nukevim.modules:get("vim-vdebug/vdebug"):startTrace()', label = 'trace expression' }, + { mode = 'v', key = { '', 'd', 'd', 't' }, map = ':lua nukevim.modules:get("vim-vdebug/vdebug"):startTrace()', label = 'trace expression' }, + { mode = 'n', key = { '', 'd', 'd', 'e' }, map = ':lua nukevim.modules:get("vim-vdebug/vdebug"):eval()', label = 'eval code' }, + { mode = 'v', key = { '', 'd', 'd', 'e' }, map = ':lua nukevim.modules:get("vim-vdebug/vdebug"):eval()', label = 'eval code' }, + { mode = 'n', key = { '', 'd', 'd', 'w' }, map = ':lua nukevim.modules:get("vim-vdebug/vdebug"):showBreakpoints()', label = 'show breakpoints' }, + } + }, + +-------------------------------------------------------------------------------- +-- Editing +-------------------------------------------------------------------------------- +-- Things that make the actual typing experience better. + + ---------------------------------------------------------------------------- + -- .editorconfig + -- + -- Load and respect the .editorconfig file in projects + -- + { name = 'editorconfig/editorconfig-vim' }, + + +-------------------------------------------------------------------------------- +-- Intellisense +-------------------------------------------------------------------------------- +-- Things that provide code insights and completion. + + ---------------------------------------------------------------------------- + -- Code completion provider + -- + -- Provides completions for a whole bunch of stuff, managed separately through + -- the coc package.json + -- + { + name = 'neoclide/coc.nvim', + -- Only enable this plugin if npm is installed + requires = { 'npm' }, + config = { + branch = 'master', + ['do'] = 'npm install' + }, + keys = { + { mode = 'n', key = { '', 'c', 'r' }, map = ":call CocAction('jumpReferences')", label = "references" }, + } + }, + + ---------------------------------------------------------------------------- + -- Code tag sidebar + -- + -- Provides a UI for browsing code "tags" (classes, functions, etc) in the + -- currently open file. + -- + { + name = 'preservim/tagbar', + requires = { 'ctags' }, + config = { ['on'] = { 'TagbarToggle', 'TagbarOpen', 'TagbarOpenAutoClose' } }, + -- keys = { + -- { mode = 'n', key = { '', 't' }, map = ':TagbarOpenAutoClose', label = 'Show File Structure' } + -- } + keys = { + { mode = 'n', key = { '' }, map = ':TagbarOpenAutoClose', label = 'show tagbar' }, + { mode = 'i', key = { '' }, map = ':TagbarOpenAutoClose', label = 'show tagbar' }, + } + }, + +-------------------------------------------------------------------------------- +-- Projects +-------------------------------------------------------------------------------- +-- Things that make working with projects better. + + ---------------------------------------------------------------------------- + -- Making the working directory follow your projects + -- + -- Whenever you load a new file, changes the working directory to the + -- nearest parent that has a `.git` folder in it, generally just working to + -- automatically always be in your current project's folder. + -- + { name = 'airblade/vim-rooter' }, + + ---------------------------------------------------------------------------- + -- Trouble - Show a todo list and list of errors from the lsp + -- + { name = 'kyazdani42/nvim-web-devicons' }, + { name = 'folke/trouble.nvim', config = { branch = 'main' } }, + + ---------------------------------------------------------------------------- + -- Todo Comments + -- + -- Find todo/fixme/etc and highlight them, and allow viewing a list + -- project-wide + { + name = 'folke/todo-comments.nvim', + config = { branch = "main" }, + keys = { + { mode = 'n', key = { '', 'w', 't' }, map = ':TodoTrouble', label = "todos" }, + } + }, + + +-------------------------------------------------------------------------------- +-- UI +-------------------------------------------------------------------------------- +-- Things that make the UI nicer. + + ---------------------------------------------------------------------------- + -- Collect scope at the top of the editor to maintain context + -- + -- E.g., as you scroll down, if you're within a function() whose + -- declaration has scrolled off-screen, this will pin it to the top of the + -- editor so it's always visible. + -- + { enable = false, name = 'wellle/context.vim' }, + + +-------------------------------------------------------------------------------- +-- Tool: Git +-------------------------------------------------------------------------------- +-- Things that make your git experience better. + + ---------------------------------------------------------------------------- + -- Git Wrapper + -- + -- Adds a :G command that allows you to specify most git commands and have + -- them do sensible things from within vim with a vim-y interface. + -- + { + name = 'tpope/vim-fugitive', + -- Only enable if git is installed + requires = { 'git' }, + config = { ['on'] = { 'G', 'Gdiffsplit', 'GDelete' } }, + -- Put a bunch of stuff in the menu + keys = { + { mode = 'n', key = { '', 'g', 'b' }, map = ':G blame', label = 'blame' }, + { mode = 'n', key = { '', 'g', 'd' }, map = ':Gdiffsplit', label = 'diff' }, + { mode = 'n', key = { '', 'g', 'l' }, map = ':G log', label = 'log' }, + { mode = 'n', key = { '', 'g', 'r' }, map = ':GDelete', label = 'rm' }, + { mode = 'n', key = { '', 'g', 's' }, map = ':G', label = 'status' }, + + { mode = 'n', key = { '', 'g', 'a' }, map = ':G add %', label = 'add' }, + { mode = 'n', key = { '', 'g', 'c' }, map = ':G commit', label = 'commit' }, + { mode = 'n', key = { '', 'g', 'p' }, map = ':G push', label = 'push' }, + + { mode = 'n', key = { '', 'g', 'x' }, map = ':lua nukevim.modules:get("tpope/vim-fugitive"):on_change_branch()', label = 'change branch' }, + { mode = 'n', key = { '', 'g', 'z' }, map = ':lua nukevim.modules:get("tpope/vim-fugitive"):on_checkout()', label = 'checkout', without = { 'nvim-telescope/telescope.nvim' } }, + } + }, + + ---------------------------------------------------------------------------- + -- Better log browsing + -- + -- Show the commit history of the repo in the usual branching tree type + -- list. + -- + { + name = 'junegunn/gv.vim', + requires = { 'git' }, + keys = { + { mode = 'n', key = { '', 'g', 'g' }, map = ':GV', label = 'graph' } + } + }, + + ---------------------------------------------------------------------------- + -- Show line-by-line changes in the editor + -- + -- Shows +/-/~ in the gutter to signify line-level changes versus the most + -- recent commit and provides tools for working with hunks. + -- + { + name = 'airblade/vim-gitgutter', + requires = { 'git' }, + keys = { + { mode = 'n', key = { '', 'g', 'r' }, map = '(GitGutterPrevHunk)', label = 'previous hunk' }, + { mode = 'n', key = { '', 'g', 'f' }, map = '(GitGutterNextHunk)', label = 'next hunk' }, + { mode = 'n', key = { '', 'g', 't' }, map = '(GitGutterStageHunk)', label = 'stage hunk' }, + { mode = 'n', key = { '', 'g', 'y' }, map = '(GitGutterPreviewHunk)', label = 'preview hunk' }, + } + }, + + ---------------------------------------------------------------------------- + -- Show blame on each line + -- + -- vscode style codelens blame shown on each line after a delay + -- + { + name = 'apzelos/blamer.nvim', + requires = { 'git' }, + -- config = { + -- ['on'] = { 'BlamerToggle' } + -- }, + keys = { + { mode = 'n', key = { '', 'g', 'w' }, map = 'BlamerToggle', label = 'toggle inline blame' }, + } + }, + + +-------------------------------------------------------------------------------- +-- Tool: Docker +-------------------------------------------------------------------------------- +-- Things that make your docker experience better. + + ---------------------------------------------------------------------------- + -- Pure vimscript docker container management + -- + -- This plugin is disabled by default as I prefer the "denops-docker" listed + -- below, but if you can't/won't install deno then this is an option. + -- + { + enable = false, + name = 'kkvh/vim-docker-tools', + requires = { 'docker' }, + config = { ['on'] = { 'DockerToolsOpen', 'DockerToolsToggle' } }, + keys = { + { mode = 'n', key = { '', 'd', 'c' }, map = ':below new:DockerToolsOpen', label = 'docker containers' } + } + }, + + ---------------------------------------------------------------------------- + -- Docker container and image management + -- + -- This plugin seems a little more polished and full-featured, so as long + -- as deno is available enable this instead. + -- + { + enable = true, + name = 'skanehira/denops-docker.vim', + config = { branch = 'main', ['on'] = { 'DockerContainers', 'DockerImages' } }, + requires = { 'deno', 'docker' }, + keys = { + { mode = 'n', key = { '', 'd', 'c' }, map = ':below new:DockerContainers8_', options = { silent = true }, label = 'docker containers' }, + { mode = 'n', key = { '', 'd', 'i' }, map = ':below new:DockerImages8_', options = { silent = true }, label = 'docker images' }, + { filetype = 'docker-containers', mode = 'n', key = { 'u' }, label = 'start', virtual = true }, + { filetype = 'docker-containers', mode = 'n', key = { 'd' }, label = 'stop', virtual = true }, + { filetype = 'docker-containers', mode = 'n', key = { '' }, label = 'kill', virtual = true }, + { filetype = 'docker-containers', mode = 'n', key = { 'a' }, label = 'terminal', virtual = true }, + { filetype = 'docker-containers', mode = 'n', key = { 't' }, label = 'log', virtual = true }, + { filetype = 'docker-containers', mode = 'n', key = { '' }, label = 'delete', virtual = true }, + { filetype = 'docker-containers', mode = 'n', key = { 'q' }, label = 'close window', virtual = true }, + { filetype = 'docker-containers', mode = 'n', key = { 'r' }, label = 'restart', virtual = true }, + { filetype = 'docker-containers', mode = 'n', key = { '' }, label = 'inspect', virtual = true }, + { filetype = 'docker-images', mode = 'n', key = { '' }, label = 'inspect', virtual = true }, + { filetype = 'docker-images', mode = 'n', key = { '' }, label = 'delete', virtual = true }, + { filetype = 'docker-images', mode = 'n', key = { 'r' }, label = 'run', virtual = true }, + { filetype = 'docker-images', mode = 'n', key = { 'q' }, label = 'close window', virtual = true }, + + } + }, + +} diff --git a/lua/config/plugins/editing.lua b/lua/config/plugins/editing.lua new file mode 100644 index 0000000..c4f01f1 --- /dev/null +++ b/lua/config/plugins/editing.lua @@ -0,0 +1,37 @@ +return { +-------------------------------------------------------------------------------- +-- Editing +-------------------------------------------------------------------------------- + + + ---------------------------------------------------------------------------- + -- Toggle comments + -- + -- Allow toggling comments on lines or blocks of lines in visual mode. + -- + { + name = 'tpope/vim-commentary' + }, + + ---------------------------------------------------------------------------- + -- Lightspeed - quick motions... or something, it's some big brain shit + -- + { + name = 'ggandor/lightspeed.nvim', + config = { branch = 'main' }, + keys = { + { mode = 'n', key = { 's' }, virtual = true, label = "smart jump forward" }, + { mode = 'n', key = { 'S' }, virtual = true, label = "smart jump backward" }, + } + }, + + ---------------------------------------------------------------------------- + -- Preview line number jump + -- + -- This will cause vim to temporarily scroll to the line number you're + -- entering when doing `:123`. When you press enter the cursor move will be + -- committed, but you can press to cancel and return to where you + -- were. + -- + { name = 'nacro90/numb.nvim' }, +} diff --git a/lua/config/plugins/lang-php.lua b/lua/config/plugins/lang-php.lua new file mode 100644 index 0000000..8be04ed --- /dev/null +++ b/lua/config/plugins/lang-php.lua @@ -0,0 +1,49 @@ +return { +-------------------------------------------------------------------------------- +-- PHP +-------------------------------------------------------------------------------- + + + ---------------------------------------------------------------------------- + -- Improved PHP syntax highlighting + -- + -- TysonAndre maintains several very impressive PHP-adjacent projects and + -- I'd generally trust his stuff will be better than some of the other + -- abandoned projects or any stuff coming from an all-in-one type project. + -- + { name = 'TysonAndre/php-vim-syntax' }, + + ---------------------------------------------------------------------------- + -- PHP ctags provider + -- + -- Allows parsing out PHP files to provide listings of classes/functions/etc + -- for use by other plugins, e.g., the tag sidebar + -- + { + name = 'vim-php/phpctags', + requires = { 'ctags', 'php', 'composer' }, + config = { + ['do'] = 'composer install' + } + }, + + ---------------------------------------------------------------------------- + -- Composer interface + -- + -- Very rudimentary, but allows for performing basic install/update/etc from + -- within vim. + -- + { + name = 'vim-php/vim-composer', + requires = { 'php', 'composer' }, + -- Only load this plugin if a composer function is called + config = { ['on'] = { 'ComposerInstall', 'ComposerUpdate', 'ComposerJSON' } }, + keys = { + { filetype = 'php', mode = 'n', key = { '', 'l', 'c' }, group = true, label = 'composer' }, + { filetype = 'php', mode = 'n', key = { '', 'l', 'c', 'i' }, map = ':ComposerInstall', label = 'composer install' }, + { filetype = 'php', mode = 'n', key = { '', 'l', 'c', 'u' }, map = ':ComposerUpdate', label = 'composer update' }, + { filetype = 'php', mode = 'n', key = { '', 'l', 'c', 'j' }, map = ':ComposerJSON', label = 'open composer.json' }, + } + }, + +} diff --git a/lua/config/plugins/lib.lua b/lua/config/plugins/lib.lua new file mode 100644 index 0000000..8a91762 --- /dev/null +++ b/lua/config/plugins/lib.lua @@ -0,0 +1,28 @@ +return { +-------------------------------------------------------------------------------- +-- Dependencies +-------------------------------------------------------------------------------- + + + ---------------------------------------------------------------------------- + -- Denops - Provides for deno/js-based plugins + -- + { name = 'vim-denops/denops.vim', requires = { 'deno' }, config = { branch = 'main' } }, + + ---------------------------------------------------------------------------- + -- Asyncrun - Run shell commands and stream their output into a window + -- + -- Usually vim waits for the command to finish and then opens the window and + -- shows the output which doesn't provide a great experience for anything + -- that takes more than a second to run. This works around that. + -- + { name = 'skywind3000/asyncrun.vim' }, + + ---------------------------------------------------------------------------- + -- Plenary - A bunch of utility functions + -- + -- This is depended on by a bunch of other plugins. + -- + { name = 'nvim-lua/plenary.nvim' }, + +} diff --git a/lua/config/plugins/local.lua b/lua/config/plugins/local.lua new file mode 100644 index 0000000..2f019a6 --- /dev/null +++ b/lua/config/plugins/local.lua @@ -0,0 +1,8 @@ +return { +-------------------------------------------------------------------------------- +-- Local +-------------------------------------------------------------------------------- +-- Add local modifications here. + + +} diff --git a/lua/config/plugins/tmp.lua b/lua/config/plugins/tmp.lua new file mode 100644 index 0000000..7f8ee7d --- /dev/null +++ b/lua/config/plugins/tmp.lua @@ -0,0 +1,13 @@ +return { +-------------------------------------------------------------------------------- +-- Maybe Later +-------------------------------------------------------------------------------- + + ---------------------------------------------------------------------------- + -- nvim-cmp + -- + -- LSP-integrated completion engine that is an absolute beast to install and + -- configure + + +} diff --git a/lua/config/plugins/ui.lua b/lua/config/plugins/ui.lua new file mode 100644 index 0000000..8f49f96 --- /dev/null +++ b/lua/config/plugins/ui.lua @@ -0,0 +1,146 @@ +return { +-------------------------------------------------------------------------------- +-- UI +-------------------------------------------------------------------------------- + + + ---------------------------------------------------------------------------- + -- Better netrw file browsing + -- + -- Rather than use something like NERDtree, allow browsing the filesystem + -- directly in a buffer. For a general overview of why I think this is + -- good, see http://vimcasts.org/blog/2013/01/oil-and-vinegar-split-windows-and-project-drawer/ + -- + -- * Press '-' anywhere to open the file browser, and go up a folder when + -- in the file browser. + -- * Press gh in the file browser to toggle hidden (dot) files. + -- * Press y to tank the absolute path of the file you've selected. + -- * Press ~ to go to your home directory. + -- + { name = 'tpope/vim-vinegar' }, + + ---------------------------------------------------------------------------- + -- Improved status bar + -- + -- Show your current mode... but also git branch, file path, changes, file + -- type, line endings, line number, and a whole bunch of other stuff. With + -- icons and pretty colours. + -- + -- The "themes" package provides color schemes that will adapt to several + -- popular pre-existing themes. + -- + -- TODO: Actually configure this because the default options are quite noisy. + -- + { name = 'vim-airline/vim-airline' }, + { name = 'vim-airline/vim-airline-themes' }, + + ---------------------------------------------------------------------------- + -- Fuzzy find files + -- + -- Search through all files in the current folder (or current project thanks + -- to vim-rooter) with a fuzzy search. + -- + -- Telescope can provide similar functionality (more colors, previews files, + -- etc) but I don't like the interface and can't be arsed to figure out the + -- customization right now. Main issues are that it supports "command" mode + -- (why) so cancelling takes two escapes, and I want to use either j/k or + -- ctrl+j/k to scroll lists not arrow keys and ctrl+n/p. + -- + { + name = 'ctrlpvim/ctrlp.vim', + config = { + -- Only load this plugin once one of these vim commands is triggered + ['on'] = { 'CtrlP', 'CtrlPMixed', 'CtrlPMRU' } + }, + keys = { + { mode = 'n', key = { '' }, map = ':CtrlP', options = { silent = true }, label = 'fuzzy find files' }, + } + }, + + ---------------------------------------------------------------------------- + -- Toggleterm - Better vim terminals + -- + -- This provides a persistent, hide-able terminal that you can pull up + -- anywhere. It seems to be a little less awkward than the built-in terminal + -- as well as far as vim modes and such. + -- + { + name = 'akinsho/toggleterm.nvim', + config = { branch = 'main' }, + keys = { + -- { mode = 'n', key = { '' }, map = 'exe "v:count" + tabpagenr() . "ToggleTerm"', label = "open terminal", options = { silent = true } }, + -- { mode = 't', key = { '' }, map = 'exe "v:count" + tabpagenr() . "ToggleTerm"', label = "close terminal", options = { silent = true } }, + { mode = 'n', key = { '' }, map = 'exe v:count1 . "ToggleTerm"', label = "toggle terminal", options = { silent = true } }, + { mode = 't', key = { '' }, map = 'exe v:count1 . "ToggleTerm"', label = "toggle terminal", options = { silent = true } }, + } + }, + + ---------------------------------------------------------------------------- + -- Input/select UI improvements + -- + -- Dressing provides an improved vim.ui.input and vim.ui.select interface by + -- using any of a variety of drivers. + -- + -- Telescope is one such driver. If telescope isn't enabled, this should + -- fall back on some less-good-but-still-better-than-default builtins. + -- + { name = 'stevearc/dressing.nvim' }, + + ---------------------------------------------------------------------------- + -- UI framework + -- + -- Telescope provides an implementation of some nicer select boxes as well + -- as several built-in functions for triggering them to do various things. + -- + -- If telescope is enabled, it will take over the git branch selection ui + -- from the custom one I've added to vim-fugitive. + -- + { + name = 'nvim-telescope/telescope.nvim', + keys = { + { mode = 'n', key = { '', 'g', 'z' }, map = ':lua require("telescope.builtin").git_branches()', label = 'checkout' }, + } + }, + + ---------------------------------------------------------------------------- + -- Colour previews + -- + -- Highlight hex codes (and in css, css named colors + rgb/hsl, etc) by + -- colouring their background to match the colour. + -- + { name = 'ap/vim-css-color' }, + + ---------------------------------------------------------------------------- + -- Dim inactive buffers + -- + -- By default this is set to dim them only a little so it's _very_ slight. + -- Still able to reference things in other buffers easily but provides a + -- small focusing effect on the active buffer. + -- + -- + -- This is the original. Bunch of unmerged PRs that fix bugs. + -- { name = 'sunjon/Shade.nvim', config = { opacity = 75 } }, + -- This is a fork that, at least at the time, basically just had all the PRs + -- merged. + { name = 'jghauser/shade.nvim', config = { opacity = 60 , branch = "main" } }, + + ---------------------------------------------------------------------------- + -- Easier buffer moving + -- + -- This allows you to move buffers around a little more easily. + -- + { + name = 'sindrets/winshift.nvim', + config = { + branch = 'main', + ['on'] = { 'WinShift' } + }, + keys = { + { mode = 'n', key = { '' }, map = 'WinShift left', label = 'move buffer left' }, + { mode = 'n', key = { '' }, map = 'WinShift down', label = 'move buffer down' }, + { mode = 'n', key = { '' }, map = 'WinShift up', label = 'move buffer up' }, + { mode = 'n', key = { '' }, map = 'WinShift right', label = 'move buffer right' }, + } + }, + +} diff --git a/lua/data/start.lua b/lua/data/start.lua new file mode 100644 index 0000000..b9dbaad --- /dev/null +++ b/lua/data/start.lua @@ -0,0 +1,13 @@ +return { + [[ ]], + [[ ]], + [[ \ | | \ \ /_) ]], + [[ . | | | | / -_)\ \ / | ` \ ]], + [[ _|\_|\_,_|_\_\\___| \_/ _|_|_|_| ]], + [[ ]], + [[ by nucleardog ]], + [[ ]], + [[ ]], + [[ Press `Alt+F1` for help. ]], + [[ ]], +} diff --git a/lua/impatient/impatient.lua b/lua/impatient/impatient.lua new file mode 100644 index 0000000..bb3d40b --- /dev/null +++ b/lua/impatient/impatient.lua @@ -0,0 +1,420 @@ +-- from https://github.com/lewis6991/impatient.nvim +local vim = vim +local api = vim.api +local uv = vim.loop +local _loadfile = loadfile +local get_runtime = api.nvim__get_runtime +local fs_stat = uv.fs_stat +local mpack = vim.mpack + +local std_cache = vim.fn.stdpath('cache') + +local std_dirs = { + [''] = os.getenv('APPDIR'), + [''] = os.getenv('VIMRUNTIME'), + [''] = vim.fn.stdpath('data'), + [''] = vim.fn.stdpath('config'), +} + +local function modpath_mangle(modpath) + for name, dir in pairs(std_dirs) do + modpath = modpath:gsub(dir, name) + end + return modpath +end + +local function modpath_unmangle(modpath) + for name, dir in pairs(std_dirs) do + modpath = modpath:gsub(name, dir) + end + return modpath +end + +-- Overridable by user +local default_config = { + chunks = { + enable = true, + path = std_cache..'/luacache_chunks', + }, + modpaths = { + enable = true, + path = std_cache..'/luacache_modpaths', + }, +} + +-- State used internally +local default_state = { + chunks = { + cache = {}, + profile = nil, + dirty = false, + get = function(self, path) + return self.cache[modpath_mangle(path)] + end, + set = function(self, path, chunk) + self.cache[modpath_mangle(path)] = chunk + end + }, + modpaths = { + cache = {}, + profile = nil, + dirty = false, + get = function(self, mod) + if self.cache[mod] then + return modpath_unmangle(self.cache[mod]) + end + end, + set = function(self, mod, path) + self.cache[mod] = modpath_mangle(path) + end + }, + log = {} +} + +---@diagnostic disable-next-line: undefined-field +local M = vim.tbl_deep_extend('keep', _G.__luacache_config or {}, default_config, default_state) +_G.__luacache = M + +local function log(...) + M.log[#M.log+1] = table.concat({string.format(...)}, ' ') +end + +function M.print_log() + for _, l in ipairs(M.log) do + print(l) + end +end + +function M.enable_profile() + local P = require('impatient.profile') + + M.chunks.profile = {} + M.modpaths.profile = {} + + P.setup(M.modpaths.profile) + + M.print_profile = function() + P.print_profile(M) + end + + vim.cmd[[command! LuaCacheProfile lua _G.__luacache.print_profile()]] +end + +local function hash(modpath) + local stat = fs_stat(modpath) + if stat then + return stat.mtime.sec..stat.mtime.nsec..stat.size + end + error('Could not hash '..modpath) +end + +local function profile(m, entry, name, loader) + if m.profile then + local mp = m.profile + mp[entry] = mp[entry] or {} + if not mp[entry].loader and loader then + mp[entry].loader = loader + end + if not mp[entry][name] then + mp[entry][name] = uv.hrtime() + end + end +end + +local function mprofile(mod, name, loader) + profile(M.modpaths, mod, name, loader) +end + +local function cprofile(path, name, loader) + if M.chunks.profile then + path = modpath_mangle(path) + end + profile(M.chunks, path, name, loader) +end + +local function get_runtime_file_from_parent(basename, paths) + -- Look in the cache to see if we have already loaded a parent module. + -- If we have then try looking in the parents directory first. + local parents = vim.split(basename, '/') + for i = #parents, 1, -1 do + local parent = table.concat(vim.list_slice(parents, 1, i), '/') + local ppath = M.modpaths:get(parent) + if ppath then + if ppath:sub(-9) == '/init.lua' then + ppath = ppath:sub(1, -10) -- a/b/init.lua -> a/b + else + ppath = ppath:sub(1, -5) -- a/b.lua -> a/b + end + + for _, path in ipairs(paths) do + -- path should be of form 'a/b/c.lua' or 'a/b/c/init.lua' + local modpath = ppath..'/'..path:sub(#('lua/'..parent)+2) + if fs_stat(modpath) then + return modpath, 'cache(p)' + end + end + end + end +end + +local function get_runtime_file_cached(basename, paths) + local modpath, loader + local mp = M.modpaths + if mp.enable then + if mp.cache[basename] then + local modpath_cached = mp:get(basename) + if fs_stat(modpath_cached) then + modpath, loader = modpath_cached, 'cache' + else + -- Invalidate + mp.cache[basename] = nil + mp.dirty = true + end + end + + if not modpath then + modpath, loader = get_runtime_file_from_parent(basename, paths) + end + end + + if not modpath then + -- What Neovim does by default; slowest + modpath, loader = get_runtime(paths, false, {is_lua=true})[1], 'standard' + end + + if modpath then + mprofile(basename, 'resolve_end', loader) + if mp.enable and loader ~= 'cache' then + log('Creating cache for module %s', basename) + mp:set(basename, modpath) + mp.dirty = true + end + end + + return modpath +end + +local function extract_basename(pats) + local basename + + -- Deconstruct basename from pats + for _, pat in ipairs(pats) do + for i, npat in ipairs{ + -- Ordered by most specific + 'lua/(.*)/init%.lua', + 'lua/(.*)%.lua' + } do + local m = pat:match(npat) + if i == 2 and m and m:sub(-4) == 'init' then + m = m:sub(0, -6) + end + if not basename then + if m then + basename = m + end + elseif m and m ~= basename then + -- matches are inconsistent + return + end + end + end + + return basename +end + +local function get_runtime_cached(pats, all, opts) + local fallback = false + if all or not opts or not opts.is_lua then + -- Fallback + fallback = true + end + + local basename + + if not fallback then + basename = extract_basename(pats) + end + + if fallback or not basename then + return get_runtime(pats, all, opts) + end + + return {get_runtime_file_cached(basename, pats)} +end + +-- Copied from neovim/src/nvim/lua/vim.lua with two lines changed +local function load_package(name) + local basename = name:gsub('%.', '/') + local paths = {"lua/"..basename..".lua", "lua/"..basename.."/init.lua"} + + -- Original line: + -- local found = vim.api.nvim__get_runtime(paths, false, {is_lua=true}) + local found = {get_runtime_file_cached(basename, paths)} + if #found > 0 then + local f, err = loadfile(found[1]) + return f or error(err) + end + + local so_paths = {} + for _,trail in ipairs(vim._so_trails) do + local path = "lua"..trail:gsub('?', basename) -- so_trails contains a leading slash + table.insert(so_paths, path) + end + + -- Original line: + -- found = vim.api.nvim__get_runtime(so_paths, false, {is_lua=true}) + found = {get_runtime_file_cached(basename, so_paths)} + if #found > 0 then + -- Making function name in Lua 5.1 (see src/loadlib.c:mkfuncname) is + -- a) strip prefix up to and including the first dash, if any + -- b) replace all dots by underscores + -- c) prepend "luaopen_" + -- So "foo-bar.baz" should result in "luaopen_bar_baz" + local dash = name:find("-", 1, true) + local modname = dash and name:sub(dash + 1) or name + local f, err = package.loadlib(found[1], "luaopen_"..modname:gsub("%.", "_")) + return f or error(err) + end + return nil +end + +local function load_from_cache(path) + local mc = M.chunks + + local cache = mc:get(path) + + if not cache then + return nil, string.format('No cache for path %s', path) + end + + local mhash, codes = unpack(cache) + + if mhash ~= hash(path) then + mc:set(path) + mc.dirty = true + return nil, string.format('Stale cache for path %s', path) + end + + local chunk = loadstring(codes) + + if not chunk then + mc:set(path) + mc.dirty = true + return nil, string.format('Cache error for path %s', path) + end + + return chunk +end + +local function loadfile_cached(path) + cprofile(path, 'load_start') + + local chunk, err + + if M.chunks.enable then + chunk, err = load_from_cache(path) + if chunk and not err then + log('Loaded cache for path %s', path) + cprofile(path, 'load_end', 'cache') + return chunk + end + log(err) + end + + chunk, err = _loadfile(path) + + if not err and M.chunks.enable then + log('Creating cache for path %s', path) + M.chunks:set(path, {hash(path), string.dump(chunk)}) + M.chunks.dirty = true + end + + cprofile(path, 'load_end', 'standard') + return chunk, err +end + +function M.save_cache() + local function _save_cache(t) + if not t.enable then + return + end + if t.dirty then + log('Updating chunk cache file: %s', t.path) + local f = assert(io.open(t.path, 'w+b')) + f:write(mpack.encode(t.cache)) + f:flush() + t.dirty = false + end + end + _save_cache(M.chunks) + _save_cache(M.modpaths) +end + +function M.clear_cache() + local function _clear_cache(t) + t.cache = {} + os.remove(t.path) + end + _clear_cache(M.chunks) + _clear_cache(M.modpaths) +end + +local function init_cache() + local function _init_cache(t) + if not t.enable then + return + end + if fs_stat(t.path) then + log('Loading cache file %s', t.path) + local f = assert(io.open(t.path, 'rb')) + local ok + ok, t.cache = pcall(function() + return mpack.decode(f:read'*a') + end) + + if not ok then + log('Corrupted cache file, %s. Invalidating...', t.path) + os.remove(t.path) + t.cache = {} + end + t.dirty = not ok + end + end + + if not uv.fs_stat(std_cache) then + vim.fn.mkdir(std_cache, 'p') + end + + _init_cache(M.chunks) + _init_cache(M.modpaths) +end + +local function setup() + init_cache() + + -- Override default functions + for i, loader in ipairs(package.loaders) do + if loader == vim._load_package then + package.loaders[i] = load_package + break + end + end + vim._load_package = load_package + + vim.api.nvim__get_runtime = get_runtime_cached + loadfile = loadfile_cached + + vim.cmd[[ + augroup impatient + autocmd VimEnter,VimLeave * lua _G.__luacache.save_cache() + augroup END + + command! LuaCacheClear lua _G.__luacache.clear_cache() + command! LuaCacheLog lua _G.__luacache.print_log() + ]] + +end + +setup() + +return M diff --git a/lua/impatient/profile.lua b/lua/impatient/profile.lua new file mode 100644 index 0000000..9906f44 --- /dev/null +++ b/lua/impatient/profile.lua @@ -0,0 +1,222 @@ +local M = {} + +local api, uv = vim.api, vim.loop + +local function load_buffer(title, lines) + local bufnr = api.nvim_create_buf(false, false) + api.nvim_buf_set_lines(bufnr, 0, 0, false, lines) + api.nvim_buf_set_option(bufnr, 'bufhidden', 'wipe') + api.nvim_buf_set_option(bufnr, 'buftype', 'nofile') + api.nvim_buf_set_option(bufnr, 'swapfile', false) + api.nvim_buf_set_option(bufnr, "modifiable", false) + api.nvim_buf_set_name(bufnr, title) + api.nvim_set_current_buf(bufnr) +end + +local function time_tostr(x) + if x == 0 then + return '?' + end + return string.format('%8.3fms', x) +end + +local function mem_tostr(x) + local unit = '' + for _, u in ipairs{'K', 'M', 'G'} do + if x < 1000 then + break + end + x = x / 1000 + unit = u + end + return string.format('%1.1f%s', x, unit) +end + +function M.print_profile(I) + local mod_profile = I.modpaths.profile + local chunk_profile = I.chunks.profile + + if not mod_profile and not chunk_profile then + print('Error: profiling was not enabled') + return + end + + local total_resolve = 0 + local total_load = 0 + local modules = {} + + for path, m in pairs(chunk_profile) do + m.load = m.load_end - m.load_start + m.load = m.load / 1000000 + m.path = path or '?' + end + + local module_content_width = 0 + + for module, m in pairs(mod_profile) do + m.resolve = 0 + if m.resolve_end then + m.resolve = m.resolve_end - m.resolve_start + m.resolve = m.resolve / 1000000 + end + + m.module = module:gsub('/', '.') + m.loader = m.loader or m.loader_guess + + local path = I.modpaths.cache[module] + local path_prof = chunk_profile[path] + m.path = path or '?' + + if path_prof then + chunk_profile[path] = nil + m.load = path_prof.load + m.ploader = path_prof.loader + else + m.load = 0 + m.ploader = 'NA' + end + + total_resolve = total_resolve + m.resolve + total_load = total_load + m.load + + if #module > module_content_width then + module_content_width = #module + end + + modules[#modules+1] = m + end + + table.sort(modules, function(a, b) + return (a.resolve + a.load) > (b.resolve + b.load) + end) + + local paths = {} + + local total_paths_load = 0 + for _, m in pairs(chunk_profile) do + paths[#paths+1] = m + total_paths_load = total_paths_load + m.load + end + + table.sort(paths, function(a, b) + return a.load > b.load + end) + + + local lines = {} + local function add(fmt, ...) + local args = {...} + for i, a in ipairs(args) do + if type(a) == 'number' then + args[i] = time_tostr(a) + end + end + + lines[#lines+1] = string.format(fmt, unpack(args)) + end + + local time_cell_width = 12 + local loader_cell_width = 11 + local time_content_width = time_cell_width - 2 + local loader_content_width = loader_cell_width - 2 + local module_cell_width = module_content_width + 2 + + local tcwl = string.rep('─', time_cell_width) + local lcwl = string.rep('─', loader_cell_width) + local mcwl = string.rep('─', module_cell_width+2) + + local n = string.rep('─', 200) + + local module_cell_format = '%-'..module_cell_width..'s' + local loader_format = '%-'..loader_content_width..'s' + local line_format = '%s │ %s │ %s │ %s │ %s │ %s' + + local row_fmt = line_format:format( + ' %'..time_content_width..'s', + loader_format, + '%'..time_content_width..'s', + loader_format, + module_cell_format, + '%s') + + local title_fmt = line_format:format( + ' %-'..time_content_width..'s', + loader_format, + '%-'..time_content_width..'s', + loader_format, + module_cell_format, + '%s') + + local title1_width = time_cell_width+loader_cell_width-1 + local title1_fmt = ('%s │ %s │'):format( + ' %-'..title1_width..'s', '%-'..title1_width..'s') + + add('Note: this report is not a measure of startup time. Only use this for comparing') + add('between cached and uncached loads of Lua modules') + add('') + + add('Cache files:') + for _, f in ipairs{ I.chunks.path, I.modpaths.path } do + local size = vim.loop.fs_stat(f).size + add(' %s %s', f, mem_tostr(size)) + end + add('') + + add('%s─%s┬%s─%s┐', tcwl, lcwl, tcwl, lcwl) + add(title1_fmt, 'Resolve', 'Load') + add('%s┬%s┼%s┬%s┼%s┬%s', tcwl, lcwl, tcwl, lcwl, mcwl, n) + add(title_fmt, 'Time', 'Method', 'Time', 'Method', 'Module', 'Path') + add('%s┼%s┼%s┼%s┼%s┼%s', tcwl, lcwl, tcwl, lcwl, mcwl, n) + add(row_fmt, total_resolve, '', total_load, '', 'Total', '') + add('%s┼%s┼%s┼%s┼%s┼%s', tcwl, lcwl, tcwl, lcwl, mcwl, n) + for _, p in ipairs(modules) do + add(row_fmt, p.resolve, p.loader, p.load, p.ploader, p.module, p.path) + end + add('%s┴%s┴%s┴%s┴%s┴%s', tcwl, lcwl, tcwl, lcwl, mcwl, n) + + if #paths > 0 then + add('') + add(n) + local f3 = ' %'..time_content_width..'s │ %'..loader_content_width..'s │ %s' + add('Files loaded with no associated module') + add('%s┬%s┬%s', tcwl, lcwl, n) + add(f3, 'Time', 'Loader', 'Path') + add('%s┼%s┼%s', tcwl, lcwl, n) + add(f3, total_paths_load, '', 'Total') + add('%s┼%s┼%s', tcwl, lcwl, n) + for _, p in ipairs(paths) do + add(f3, p.load, p.loader, p.path) + end + add('%s┴%s┴%s', tcwl, lcwl, n) + add('') + end + + load_buffer('Impatient Profile Report', lines) +end + +M.setup = function(profile) + local _require = require + + require = function(mod) + local basename = mod:gsub('%.', '/') + if not profile[basename] then + profile[basename] = {} + profile[basename].resolve_start = uv.hrtime() + profile[basename].loader_guess = 'C' + end + return _require(mod) + end + + -- Add profiling around all the loaders + local pl = package.loaders + for i = 1, #pl do + local l = pl[i] + pl[i] = function(mod) + local basename = mod:gsub('%.', '/') + profile[basename].loader_guess = i == 1 and 'preloader' or 'loader #'..i + return l(mod) + end + end +end + +return M diff --git a/lua/lib/autocmd.lua b/lua/lib/autocmd.lua new file mode 100644 index 0000000..378e5ec --- /dev/null +++ b/lua/lib/autocmd.lua @@ -0,0 +1,51 @@ +-- +-- Move this file to your neovim lua runtime path ie. ~/.config/nvim/lua/au.lua +-- +local cmd = vim.api.nvim_command + +local function autocmd(this, event, spec) + local is_table = type(spec) == 'table' + local pattern = is_table and spec[1] or '*' + local action = is_table and spec[2] or spec + if type(action) == 'function' then + action = this.set(action) + end + -- local e = type(event) == 'table' and table.concat(event, ',') or event + local pattern = type(pattern) == 'table' and table.concat(pattern, ',') or pattern + cmd('autocmd ' .. e .. ' ' .. pattern .. ' ' .. action) +end + +local S = { + __au = {}, +} + +local X = setmetatable({}, { + __index = S, + __newindex = autocmd, + __call = autocmd, +}) + +function S.exec(id) + S.__au[id]() +end + +function S.set(fn) + local id = string.format('%p', fn) + S.__au[id] = fn + return string.format('lua require("au").exec("%s")', id) +end + +function S.group(grp, cmds) + cmd('augroup ' .. grp) + cmd('autocmd!') + if type(cmds) == 'function' then + cmds(X) + else + for _, au in ipairs(cmds) do + autocmd(S, au[1], { au[2], au[3] }) + end + end + cmd('augroup END') +end + +return X diff --git a/lua/lib/dump.lua b/lua/lib/dump.lua new file mode 100644 index 0000000..779c9ba --- /dev/null +++ b/lua/lib/dump.lua @@ -0,0 +1,15 @@ +local dump = nil +dump = function(o) + if type(o) == 'table' then + local s = '{ ' + for k,v in pairs(o) do + if type(k) ~= 'number' then k = '"'..k..'"' end + s = s .. '['..k..'] = ' .. dump(v) .. ',' + end + return s .. '} ' + else + return tostring(o) + end +end + +return dump diff --git a/lua/lib/file_exists.lua b/lua/lib/file_exists.lua new file mode 100644 index 0000000..d980c59 --- /dev/null +++ b/lua/lib/file_exists.lua @@ -0,0 +1,9 @@ +return function(path) + f = io.open(path, 'r') + if (f ~= nil) then + io.close(f) + return true + else + return false + end +end diff --git a/lua/lib/get_visual_selection.lua b/lua/lib/get_visual_selection.lua new file mode 100644 index 0000000..22f364f --- /dev/null +++ b/lua/lib/get_visual_selection.lua @@ -0,0 +1,14 @@ +return function() + local s_start = vim.fn.getpos("'<") + local s_end = vim.fn.getpos("'>") + local n_lines = math.abs(s_end[2] - s_start[2]) + 1 + local lines = vim.api.nvim_buf_get_lines(0, s_start[2] - 1, s_end[2], false) + if (lines[1] == nil) then return nil end + lines[1] = string.sub(lines[1], s_start[3], -1) + if n_lines == 1 then + lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3] - s_start[3] + 1) + else + lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3]) + end + return table.concat(lines, '\n') +end diff --git a/lua/lib/has_command.lua b/lua/lib/has_command.lua new file mode 100644 index 0000000..efc83b4 --- /dev/null +++ b/lua/lib/has_command.lua @@ -0,0 +1,4 @@ +return function(command) + result = vim.fn.executable(command) + return result == 1 +end diff --git a/lua/lib/map.lua b/lua/lib/map.lua new file mode 100644 index 0000000..4d9a0fa --- /dev/null +++ b/lua/lib/map.lua @@ -0,0 +1,7 @@ +return function(mode, lhs, rhs, opts) + local options = { noremap = true } + if opts then + options = vim.tbl_extend("force", options, opts) + end + vim.api.nvim_set_keymap(mode, lhs, rhs, options) +end diff --git a/lua/lib/merge.lua b/lua/lib/merge.lua new file mode 100644 index 0000000..997f784 --- /dev/null +++ b/lua/lib/merge.lua @@ -0,0 +1,9 @@ +return function(arrays) + o = {} + for idx,arr in ipairs(arrays) do + for i=1,#arr do + table.insert(o, arr[i]) + end + end + return o +end diff --git a/lua/module.lua b/lua/module.lua new file mode 100644 index 0000000..b1a46a3 --- /dev/null +++ b/lua/module.lua @@ -0,0 +1,47 @@ +local Module = {} + +function Module:new(obj) + obj = obj or {} + setmetatable(obj, self) + self.__index = self + return obj +end + +function Module:configure(config) + self.config = config or {} +end + +-- Called first to give the module a change to initialize class vars, etc +-- If any configuration is present, configure() will have been called before +-- initialize +function Module:initialize() +end + +-- Give the moduel a chance to register dependencies/etc (e.g., add plugins) +function Module:register() +end + +-- After all modules have had a chance to register dependencies/etc with +-- each other, commit gives all plugins a chance to take action on those. +function Module:commit() +end + +-- Do any further module startup required +function Module:boot() +end + +-- Do core module things, this is _always called +function Module:run() +end + +-- This is _only_ called if we think we're running in a ui (e.g., neovim-qt) +function Module:gui() +end + +-- For doing first-time setup/install +-- This could be called multiple times and should not lose data +-- (E.g., plug#install) +function Module:install() +end + +return Module diff --git a/lua/module/keymap.lua b/lua/module/keymap.lua new file mode 100644 index 0000000..6cad086 --- /dev/null +++ b/lua/module/keymap.lua @@ -0,0 +1,249 @@ +local M = require('module'):new() + +local map = require('lib/map') + +function M:initialize(config) + self.plugins = nukevim.modules:get('plugins') + self.keymap = {} +end + +function M:register() + if (self.config.ui.enable) then + self.plugins:add('folke/which-key.nvim', { branch = "main" }, { + { mode = 'n', key = { '?', '?', '?' }, map = ":lua nukevim.modules:get('keymap'):show()", hidden = true }, + { mode = 'i', key = { '?', '?', '?' }, map = " lua nukevim.modules:get('keymap'):show()", hidden = true }, + { mode = 'v', key = { '?', '?', '?' }, map = " lua nukevim.modules:get('keymap'):show()", hidden = true }, + }) + end + + if (self.config.keys ~= nil) then + for idx, key in ipairs(self.config.keys) do + self:add(key) + end + end +end + +function M:show() + mode = vim.fn.mode() + buffer = vim.fn.expand('%') + -- n, i, v/V + + show_buffer_keys = false + for i=1,#self.keymap do + if (self.keymap[i].buffer ~= nil and self.keymap[i].buffer == buffer) then + show_buffer_keys = true + break + end + end + + if (show_buffer_keys and false) then + + -- buf = vim.api.nvim_create_buf(false, true) + -- win = vim.api.nvim_open_win(buf, false, { + -- relative = "editor", + -- height = 6, + -- focusable = false, + -- anchor = "SW", + -- style = "minimal", + -- row = vim.o.lines, + -- col = 0, + -- width = vim.o.columns + -- }) + -- vim.api.nvim_buf_set_option(buf, "filetype", "WhichKey") + -- vim.api.nvim_buf_set_option(buf, "buftype", "nofile") + -- vim.api.nvim_win_set_option(win, "winhighlight", "NormalFloat:WhichKeyFloat") + -- vim.api.nvim_win_set_option(win, "foldmethod", "manual") + -- -- vim.api.nvim_win_set_option(win, "winblend", true) + -- vim.cmd([[autocmd! WinClosed lua nukevim.modules:get('keymap'):closed()]]) + + -- vim.api.nvim_buf_set_lines(buf, 0, -1, false, { + -- "hello, world!", + -- "this is a window" + -- }) + else + require('which-key').show('', { mode = mode }) + end +end + +function M:registerBufferLocal() + filetype = vim.bo.filetype + + local_binds = {} + + for i=1,#self.keymap do + if (self.keymap[i].filetype ~= nil and self.keymap[i].filetype == filetype) then + table.insert(local_binds, self.keymap[i]) + end + end + + self:registerWithWhichKey(local_binds, { buffer = 0 }) + +end + +function M:map(mode, key, map, options) + M:add({ + mode = mode, + key = key, + map = map, + options = options or { noremap = true } + }) +end + +function M:add(keymap) + -- todo: validate + keymap.mode = keymap.mode or nil + keymap.key = keymap.key or nil + if (type(keymap.key) == "string") then + parts = {} + for part in string.gmatch(keymap.key, '.') do + table.insert(parts, part) + end + keymap.key = parts + end + keymap.map = keymap.map or nil + keymap.options = keymap.options or { noremap = true } + keymap.label = keymap.label or nil + keymap.virtual = keymap.virtual or false + keymap.hidden = keymap.hidden or false + keymap.group = keymap.group or false + keymap.with = keymap.with or {} + keymap.without = keymap.without or {} + table.insert(self.keymap, keymap) +end + +function M:commit() + if (self.plugins:has('folke/which-key.nvim') and self.config.ui.enable) then + self:commitWithWhichKey() + else + self:commitWithNative() + end +end + +function M:commitWithWhichKey() + -- Set up whichkey + whichkey = require('which-key') + whichkey.setup({ + ignore_missing = true, + plugins = { + marks = true, + registers = true, + spelling = { + enabled = true, + suggestions = 20 + }, + presets = { + operators = self.config.ui.show_builtin, + motions = self.config.ui.show_builtin, + text_objects = self.config.ui.show_builtin, + windows = self.config.ui.show_builtin, + nav = self.config.ui.show_builtin, + z = self.config.ui.show_builtin, + g = self.config.ui.show_builtin, + } + } + }) + + -- Build tree of key binds + self:registerWithWhichKey(self.keymap) + +end + +function M:registerWithWhichKey(keys, opts) + opts = opts or {} + tree = {} + node = nil + + for idx, keymap in ipairs(keys) do + if (keymap.hidden) then + if (keymap.label ~= nil) then + keymap.options.desc = keymap.label + end + map(keymap.mode, table.concat(keymap.key, ""), keymap.map, keymap.options) + -- TODO: Hack-y hack. + elseif (keymap.filetype ~= nil and opts.buffer == nil) then + -- this only applies to a specific filetype, register() will register + -- it buffer-local when it's opened + else + if (tree[keymap.mode] == nil) then + tree[keymap.mode] = {} + end + + node = tree[keymap.mode] + + for i = 1, #keymap.key - 1 do + if (node[keymap.key[i]] == nil) then + node[keymap.key[i]] = {} + end + node = node[keymap.key[i]] + end + + last = keymap.key[#keymap.key] + + have_all_with = true + for idx,plugin in ipairs(keymap.with) do + have_all_with = have_all_with and self.plugins:has(plugin) + end + have_any_without = false + for idx,plugin in ipairs(keymap.without) do + have_any_without = have_any_without or self.plugins:has(plugin) + end + + if (have_all_with and not have_any_without) then + if (keymap.group) then + node[last] = node[last] or {} + node[last]['name'] = keymap.label + elseif (keymap.virtual) then + node[last] = { keymap.label } + else + node[last] = { keymap.map, keymap.label or nil } + if (keymap.options.noremap) then + node[last].noremap = true + end + if (keymap.options.silent) then + node[last].silent = true + end + if (keymap.options.nowait) then + node[last].nowait = true + end + end + end + + end + end + + for mode, node in pairs(tree) do + local_opts = {} + for k, v in pairs(opts) do + local_opts[k] = v + end + local_opts['mode'] = mode + whichkey.register(node, local_opts) + end + +end + +function M:commitWithNative() + for idx, keymap in ipairs(self.keymap) do + if (keymap.label ~= nil) then + keymap.options.desc = keymap.label + end + + if (keymap.virtual ~= true) then + + have_all_with = true + for plugin in ipairs(keymap.with) do + have_all_with = have_all_with and self.plugins:has(plugin) + end + have_any_without = false + for plugin in ipairs(keymap.without) do + have_any_without = have_any_without or self.plugins:has(plugin) + end + + if (have_all_with and not have_any_without) then + map(keymap.mode, table.concat(keymap.key, ''), keymap.map, keymap.options) + end + end + end +end + +return M diff --git a/lua/module/lsp.lua b/lua/module/lsp.lua new file mode 100644 index 0000000..79b00a3 --- /dev/null +++ b/lua/module/lsp.lua @@ -0,0 +1,27 @@ +local M = require('module'):new() + +local has_command = require('lib/has_command') + +function M:initialize() + self.plugins = nukevim.modules:get('plugins') +end + +function M:register() + self.plugins:add('neovim/nvim-lspconfig') +end + +function M:run() + local lsp = require('lspconfig') + for provider,config in pairs(self.config.providers) do + if (has_command(config.command[1])) then + lsp[provider].setup({ + cmd = config.command, + filetypes = config.filetypes + }) + else + print("can't find command") + end + end +end + +return M diff --git a/lua/module/phpunit.lua b/lua/module/phpunit.lua new file mode 100644 index 0000000..62eeb3a --- /dev/null +++ b/lua/module/phpunit.lua @@ -0,0 +1,66 @@ +local M = require('module'):new() + +function M:initialize() + self.keymap = nukevim.modules:get('keymap') +end + +function M:register() + self.keymap:add({ + filetype = 'php', + mode = 'n', + key = { '', 'l', 'p' }, + group = true, + label = 'phpunit' + }) + self.keymap:add({ + filetype = 'php', + mode = 'n', + key = { '', 'l', 'p', 'a' }, + map = ':lua nukevim.modules:get("phpunit"):all()', + label = 'run all' + }) + self.keymap:add({ + filetype = 'php', + mode = 'n', + key = { '', 'l', 'p', 'f' }, + map = ':lua nukevim.modules:get("phpunit"):file()', + label = 'run file' + }) + self.keymap:add({ + filetype = 'php', + mode = 'n', + key = { '', 'l', 'p', 't' }, + map = ':lua nukevim.modules:get("phpunit"):test()', + label = 'run single test' + }) +end + +function M:run() + vim.g.asyncrun_open = 8 +end + +function M:all() + vim.call('asyncrun#run', '', {}, './vendor/bin/phpunit --colors=never') +end + +function M:file() + file = vim.fn.expand('%') + vim.call('asyncrun#run', '', {}, './vendor/bin/phpunit --colors=never '..file) +end + +function M:test() + -- so... this tries to get the current tag in the which-key window which is + -- always blank. there's probably a smarter way to do this, but we just... + -- wait a half second then do it. + vim.defer_fn(function() + file = vim.fn.expand('%') + test = vim.fn['tagbar#currenttag']('%s', 'nil') + if (test == 'nil') then + print('cannot find test function') + return + end + vim.call('asyncrun#run', '', {}, './vendor/bin/phpunit --colors=never --filter '..test..' '..file) + end, 500) +end + +return M diff --git a/lua/module/plugins.lua b/lua/module/plugins.lua new file mode 100644 index 0000000..548782f --- /dev/null +++ b/lua/module/plugins.lua @@ -0,0 +1,88 @@ +local M = require('module'):new() + +local package_manager = require('plugin/vim_plug') +local file_exists = require('lib/file_exists') +local has_command = require('lib/has_command') + +function M:initialize() + self.path = self.config.path or "~/.config/nvim/plugins/" + self.auto_install = self.config.auto_install or true + self.auto_cleanup = self.config.auto_cleanup or true + self.plugins = {} + self.keymap = nukevim.modules:get('keymap') +end + +function M:register() + for idx, plugin in pairs(self.config.plugins) do + if (plugin.enable == nil or plugin.enable == true) then + self:add(plugin.name, plugin.config or nil, plugin.keys or nil, plugin.requires or nil) + end + end +end + +function M:commit() + package_manager:initialize(self.path) + package_manager:enter() + for idx, plugin in pairs(self.plugins) do + package_manager:add(plugin.name, plugin.config or nil) + end + package_manager:exit() + + -- Check if any plugins have lua modules, if so register them + for idx, plugin in pairs(self.plugins) do + if (file_exists(vim.env.HOME .. '/.config/nvim/lua/plugin/' .. plugin.name:gsub('%.', '-') .. '.lua')) then + local plugin_module = require('plugin/' .. plugin.name:gsub('%.', '-')):new() + plugin_module:configure(plugin.config) + nukevim.modules:addInstance(plugin.name, plugin_module) + end + end + +end + +function M:boot() + if (self.auto_install and package_manager:hasPendingPackages()) then + package_manager:install() + end + if (self.auto_cleanup) then + package_manager:cleanup() + end +end + +function M:add(name, config, keys, requires) + + if (requires ~= nil) then + for i=1,#requires do + if (not has_command(requires[i])) then + return + end + end + end + + table.insert(self.plugins, { name = name, config = config }) + + if (keys ~= nil) then + for idx, key in ipairs(keys) do + self.keymap:add(key) + end + end + +end + +function M:has(name) + for idx, plugin in pairs(self.plugins) do + if (plugin.name == name) then + return true + end + end + return false +end + +function M:install() + package_manager:install() +end + +function M:cleanup() + package_manager:cleanup() +end + +return M diff --git a/lua/module/settings.lua b/lua/module/settings.lua new file mode 100644 index 0000000..1ea73ed --- /dev/null +++ b/lua/module/settings.lua @@ -0,0 +1,13 @@ +local M = require('module'):new() + +-- We run this late to give this a chance to override most other modules since +-- they're explicitly set by the user. +function M:run() + for t,opts in pairs(self.config.settings) do + for k, v in pairs(opts) do + vim[t][k] = v + end + end +end + +return M diff --git a/lua/module/start.lua b/lua/module/start.lua new file mode 100644 index 0000000..58846b8 --- /dev/null +++ b/lua/module/start.lua @@ -0,0 +1,154 @@ +local M = require('module'):new() + +function M:boot() + self.opts = { + win = { + number = false, + list = false, + colorcolumn = "", + cursorline = false + }, + buf = { + } + } + self.is_gui = false + self.is_visible = false +end + +function M:run() + if (vim.fn.argc() == 0 or vim.fn.line2byte("$") ~= -1) then -- and not vim.opt.insertmode) then + self:show() + end +end + +function M:gui() + local win = vim.api.nvim_get_current_win() + local buf = vim.api.nvim_get_current_buf() + + self.is_gui = true + self.opts.win.list = vim.api.nvim_win_get_option(win, 'list') + + if (self.is_visible) then + vim.api.nvim_win_set_option(win, 'list', false) + self:draw(buf) + end +end + +function M:show() + local height = vim.api.nvim_get_option('lines') - 2 + local width = vim.api.nvim_get_option('columns') + + local lines = require('data/start') + + if (#lines > height) then + return + end + + for i=1,#lines do + if (#lines[i] > width) then + return + end + end + + self.is_visible = true + local win = vim.api.nvim_get_current_win() + local buf = vim.api.nvim_create_buf(true, true) + + self:draw(buf) + + vim.api.nvim_buf_set_option(buf, "modified", false) + vim.api.nvim_buf_set_option(buf, "buflisted", false) + vim.api.nvim_buf_set_option(buf, "bufhidden", "wipe") + vim.api.nvim_buf_set_option(buf, "buftype", "nofile") + vim.api.nvim_buf_set_option(buf, "swapfile", false) + + for k, v in pairs(self.opts.win) do + old_val = vim.api.nvim_win_get_option(win, k) + vim.api.nvim_win_set_option(win, k, v) + self.opts.win[k] = old_val + end + for k, v in pairs(self.opts.buf) do + old_val = vim.api.nvim_buf_get_option(buf, k) + vim.api.nvim_buf_set_option(buf, k, v) + self.opts.buf[k] = old_val + end + + -- vim.api.nvim_win_set_option(win, "number", false) + -- vim.api.nvim_win_set_option(win, "list", false) + -- vim.api.nvim_win_set_option(win, "cursorline", false) + -- vim.api.nvim_win_set_option(win, "colorcolumn", "") + + vim.api.nvim_set_current_buf(buf) + + vim.api.nvim_create_autocmd("InsertEnter,WinEnter", { + pattern = "", + callback = function() + vim.cmd("enew") + self:hide() + end + }) + vim.api.nvim_create_autocmd("FileType", { + pattern = "netrw", + callback = function() + self:hide() + end + }) +end + +function M:hide() + if (not self.is_visible) then + return + end + self.is_visible = false + local buf = vim.api.nvim_get_current_buf() + local win = vim.api.nvim_get_current_win() + + vim.api.nvim_buf_set_option(buf, "modifiable", true) + vim.api.nvim_buf_set_option(buf, "buflisted", true) + vim.api.nvim_buf_set_option(buf, "buflisted", true) + + -- vim.api.nvim_win_set_option(win, "number", nukevim.config.settings.settings.o.number or false) + -- vim.api.nvim_win_set_option(win, "colorcolumn", nukevim.config.settings.settings.o.cc or nukevim.config.settings.settings.o.colorcolumn or "") + -- vim.api.nvim_win_set_option(win, "cursorline", nukevim.config.settings.settings.o.cursorline or false) + -- if (self.is_gui) then + -- enable_list = nukevim.config.ui.gui.show_whitespace or nukevim.config.ui.tui.show_whitespace or false + -- else + -- enable_list = nukevim.config.ui.tui.show_whitespace or false + -- end + -- vim.api.nvim_win_set_option(win, "list", enable_list) + + for k, v in pairs(self.opts.win) do + vim.api.nvim_win_set_option(win, k, v) + end + for k, v in pairs(self.opts.buf) do + vim.api.nvim_buf_set_option(buf, k, v) + end + +end + +function M:draw(buf) + local height = vim.api.nvim_get_option('lines') - 2 + local width = vim.api.nvim_get_option('columns') + + local lines = require('data/start') + + for i=1,#lines do + lines[i] = self:center(lines[i]) + end + + vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines) +end + +function M:center(string) + width = vim.api.nvim_get_option('columns') + string_length = #string + padding_length = (width - string_length) / 2 - 1 + padding = '' + for i=1,padding_length do + padding = padding .. ' ' + end + return padding .. string .. padding +end + + +return M diff --git a/lua/module/syntax.lua b/lua/module/syntax.lua new file mode 100644 index 0000000..36999aa --- /dev/null +++ b/lua/module/syntax.lua @@ -0,0 +1,14 @@ +local M = require('module'):new() + +function M:initialize(config) + self.plugins = nukevim.modules:get('plugins') +end + +function M:register() + if (self.plugins:has('TysonAndre/php-vim-syntax')) then + vim.g.polyglot_disabled = { "php" } + end + self.plugins:add('sheerun/vim-polyglot') +end + +return M diff --git a/lua/module/ui.lua b/lua/module/ui.lua new file mode 100644 index 0000000..aa12850 --- /dev/null +++ b/lua/module/ui.lua @@ -0,0 +1,35 @@ +local M = require('module'):new() + +function M:run() + self:configureUi(self.config.tui) +end + +function M:gui() + self:configureUi(self.config.gui) +end + +function M:configureUi(config) + -- Set the font if set + if (config.font ~= nil and config.font.family ~= nil and config.font.size ~= nil) then + vim.o.guifont = config.font.family..':h'..config.font.size + end + + -- Set the color scheme if set + if (config.theme ~= nil) then + vim.cmd('colorscheme '..config.theme) + end + + if (config.show_whitespace) then + vim.o.listchars = "tab:>-,trail:.,extends:.,precedes:.,space:." + vim.o.list = true + -- used to be 22, changed to not perfectly match the line highlight or cursor + if (config.show_whitespace == true) then + guifg = 'gray30' + else + guifg = config.show_whitespace + end + vim.highlight.create('Whitespace', { guifg = guifg }) + end +end + +return M diff --git a/lua/modules.lua b/lua/modules.lua new file mode 100644 index 0000000..752b695 --- /dev/null +++ b/lua/modules.lua @@ -0,0 +1,62 @@ +local Modules = {} + +function Modules:new(obj) + obj = obj or {} + setmetatable(obj, self) + self.__index = self + obj:initialize() + return obj +end + +function Modules:initialize() + self.modules = {} +end + +function Modules:add(name, config) + local module = require('module/'..name) + self.modules[name] = { instance = module:new(), config = config } +end + +function Modules:addInstance(name, instance, config) + self.modules[name] = { instance = instance, config = config } +end + +function Modules:get(name) + if (self.modules[name] == nil) then + print("MODULE NOT LOADED: "..name) + end + return self.modules[name]['instance'] +end + +function Modules:configure() + for name, module in pairs(self.modules) do + module.instance:configure(module.config) + end +end + +function Modules:call(method) + orders = {} + for name, module in pairs(self.modules) do + if (module.config ~= nil and module.config.order ~= nil) then + table.insert(orders, module.config.order) + end + end + + table.sort(orders) + + for idx,order in ipairs(orders) do + for name, module in pairs(self.modules) do + if (module.config ~= nil and module.config.order ~= nil and module.config.order == order) then + module['instance'][method](module['instance']) + end + end + end + + for name, module in pairs(self.modules) do + if (module.config == nil or module.config.order == nil) then + module['instance'][method](module['instance']) + end + end +end + +return Modules diff --git a/lua/nukevim.lua b/lua/nukevim.lua new file mode 100644 index 0000000..eb66cc9 --- /dev/null +++ b/lua/nukevim.lua @@ -0,0 +1,55 @@ +local NukeVim = {} + +function NukeVim:new(obj) + obj = obj or {} + setmetatable(obj, self) + self.__index = self + return obj +end + +function NukeVim:enableCaching() + self.lua_cache = require('impatient/impatient') +end + +function NukeVim:enableProfiling() + self.lua_cache.enable_profile() +end + +function NukeVim:initialize() + -- init dependencies + self.config = require('_config') + self.modules = require('modules'):new() + + -- load modules based on config + for module, config in pairs(self.config) do + if (config.enable == nil or config.enable == true) then + self.modules:add(module, config) + end + end + + -- Start up modules + self.modules:configure() + self.modules:call('initialize') + self.modules:call('register') + self.modules:call('commit') + self.modules:call('boot') +end + +function NukeVim:run() + self.modules:call('run') +end + +function NukeVim:gui() + self.modules:call('gui') +end + +function NukeVim:install() + self.modules:call('install') + vim.cmd(':helptags ~/.config/nvim/doc/') +end + +function NukeVim:help() + vim.cmd(':h nukevim') +end + +return NukeVim diff --git a/lua/plugin/akinsho/toggleterm-nvim.lua b/lua/plugin/akinsho/toggleterm-nvim.lua new file mode 100644 index 0000000..7bc49fd --- /dev/null +++ b/lua/plugin/akinsho/toggleterm-nvim.lua @@ -0,0 +1,9 @@ +local M = require('module'):new() + +function M:boot() + require('toggleterm').setup({ + }) +end + +return M + diff --git a/lua/plugin/apzelos/blamer-nvim.lua b/lua/plugin/apzelos/blamer-nvim.lua new file mode 100644 index 0000000..b436b26 --- /dev/null +++ b/lua/plugin/apzelos/blamer-nvim.lua @@ -0,0 +1,12 @@ +local M = require('module'):new() + +function M:boot() + vim.g.blamer_enabled = 1 + vim.g.blamer_delay = 1000 + vim.g.blamer_show_in_visual_modes = 0 + vim.g.blamer_show_in_insert_modes = 0 + vim.g.blamer_relative_time = 1 +end + +return M + diff --git a/lua/plugin/dein.lua b/lua/plugin/dein.lua new file mode 100644 index 0000000..243ad71 --- /dev/null +++ b/lua/plugin/dein.lua @@ -0,0 +1,38 @@ +local M = {} + +M.path = nil + +function M:initialize(path) + self.path = path + vim.o.runtimepath = vim.o.runtimepath .. "," .. self.path .. "repos/github.com/Shougo/dein.vim/" +end + +function M:enter() + vim.call('dein#begin', self.path) +end + +function M:exit() + vim.call('dein#end') +end + +function M:add(name, config) + if (type(config) == "nil") then + vim.call('dein#add', name) + else + vim.call('dein#add', name, config) + end +end + +function M:install() + vim.call('dein#install') +end + +function M:hasPendingPackages() + return vim.call('dein#check_install') ~= 0 +end + +function M:cleanup() + vim.call('map', vim.call('dein#check_clean'), "delete(v:val, 'rf')") +end + +return M diff --git a/lua/plugin/editorconfig/editorconfig-vim.lua b/lua/plugin/editorconfig/editorconfig-vim.lua new file mode 100644 index 0000000..ca9d9b6 --- /dev/null +++ b/lua/plugin/editorconfig/editorconfig-vim.lua @@ -0,0 +1,11 @@ +local M = require('module'):new() + +function M:boot() + -- If fugitive is loaded this requires an exclusion to + -- prevent conflicts. + if (nukevim.modules:get('plugins'):has('tpope/vim-fugitive')) then + vim.g.EditorConfig_exclude_patterns = { 'fugitive://.*' } + end +end + +return M diff --git a/lua/plugin/folke/todo-comments-nvim.lua b/lua/plugin/folke/todo-comments-nvim.lua new file mode 100644 index 0000000..ac456f7 --- /dev/null +++ b/lua/plugin/folke/todo-comments-nvim.lua @@ -0,0 +1,9 @@ +local M = require('module'):new() + +function M:boot() + require('todo-comments').setup({ + }) +end + +return M + diff --git a/lua/plugin/folke/trouble-nvim.lua b/lua/plugin/folke/trouble-nvim.lua new file mode 100644 index 0000000..ea92570 --- /dev/null +++ b/lua/plugin/folke/trouble-nvim.lua @@ -0,0 +1,17 @@ +local M = require('module'):new() + +function M:boot() + require('trouble').setup({ + icons = false, + fold_open = 'v', + fold_closed = '>', + action_keys = { + jump = { '' }, + jump_close = { '' }, + }, + auto_preview = false + }) +end + +return M + diff --git a/lua/plugin/jghauser/shade-nvim.lua b/lua/plugin/jghauser/shade-nvim.lua new file mode 100644 index 0000000..244427b --- /dev/null +++ b/lua/plugin/jghauser/shade-nvim.lua @@ -0,0 +1,12 @@ +local M = require('module'):new() + +function M:boot() + opacity = self.config.opacity + if (opacity == nil) then opacity = 90 end + + require('shade').setup({ + overlay_opacity = opacity + }) +end + +return M diff --git a/lua/plugin/joonty/vim-phpunitqf.lua b/lua/plugin/joonty/vim-phpunitqf.lua new file mode 100644 index 0000000..6e494a6 --- /dev/null +++ b/lua/plugin/joonty/vim-phpunitqf.lua @@ -0,0 +1,9 @@ +local M = require('module'):new() + +function M:boot() + vim.g.phpunit_cmd = "./vendor/bin/phpunit" + vim.g.phpunit_args = "--colors=always" +end + +return M + diff --git a/lua/plugin/nacro90/numb-nvim.lua b/lua/plugin/nacro90/numb-nvim.lua new file mode 100644 index 0000000..60eb37b --- /dev/null +++ b/lua/plugin/nacro90/numb-nvim.lua @@ -0,0 +1,10 @@ +local M = require('module'):new() + +function M:boot() + require('numb').setup({ + centered_peeking = false + }) +end + +return M + diff --git a/lua/plugin/preservim/tagbar.lua b/lua/plugin/preservim/tagbar.lua new file mode 100644 index 0000000..1e3dca0 --- /dev/null +++ b/lua/plugin/preservim/tagbar.lua @@ -0,0 +1,18 @@ +local M = require('module'):new() + +function M:boot() + vim.g.tagbar_silent = 1 + + vim.g.tagbar_type_php = { + kinds = { + 'i:interfaces', + 'c:classes', + 'd:constant definitions:0:0', + 'f:functions', + -- 'v:variables:0:0', + 'j:javascript functions', + } + } +end + +return M diff --git a/lua/plugin/stevearc/dressing-nvim.lua b/lua/plugin/stevearc/dressing-nvim.lua new file mode 100644 index 0000000..a893ed8 --- /dev/null +++ b/lua/plugin/stevearc/dressing-nvim.lua @@ -0,0 +1,8 @@ +local M = require('module'):new() + +function M:boot() + require('dressing').setup({ + }) +end + +return M diff --git a/lua/plugin/tpope/vim-fugitive.lua b/lua/plugin/tpope/vim-fugitive.lua new file mode 100644 index 0000000..6ea84cb --- /dev/null +++ b/lua/plugin/tpope/vim-fugitive.lua @@ -0,0 +1,40 @@ +local M = require('module'):new() + +function M:boot() + self.plugins = nukevim.modules:get('plugins') +end + +function M:on_change_branch() + vim.ui.input({ + prompt = "branch? ", + -- completion = + }, function(branch) + if (branch ~= nil) then + vim.cmd(':G branch '..branch) + vim.cmd(':G checkout '..branch) + end + end) +end + +function M:on_checkout() + branches_out = vim.fn.system('git branch') + branches = {} + + for branch in branches_out:gmatch("[^\r\n]+") do + if (branch:sub(1, 1) ~= '*') then + table.insert(branches, branch) + end + end + + vim.ui.select(branches, { + prompt = 'branch? ' + }, + function(branch) + if (branch ~= nil) then + vim.cmd(':G checkout '..branch) + end + end + ) +end + +return M diff --git a/lua/plugin/vim-airline/vim-airline.lua b/lua/plugin/vim-airline/vim-airline.lua new file mode 100644 index 0000000..7f0098e --- /dev/null +++ b/lua/plugin/vim-airline/vim-airline.lua @@ -0,0 +1,9 @@ +local M = require('module'):new() + +function M:boot() + -- Don't show mode in status bar since it's in our new fancy bar + vim.o.showmode = false + vim.g.airline_powerline_fonts = 1 +end + +return M diff --git a/lua/plugin/vim-vdebug/vdebug.lua b/lua/plugin/vim-vdebug/vdebug.lua new file mode 100644 index 0000000..6d12648 --- /dev/null +++ b/lua/plugin/vim-vdebug/vdebug.lua @@ -0,0 +1,70 @@ +local M = require('module'):new() +local get_visual_selection = require('lib/get_visual_selection') + +function M:boot() + vim.g.vdebug_options = { + break_on_open = 0, + path_maps = { + -- This is only evaluated on startup so will work if the editor is + -- started inside the project (I think vim-rooter will have run by + -- now) but not if you've navigated into a project like I do basically + -- every single time. + -- ["/var/www/html"] = getcwd() + }, + marker_default = '*', + marker_closed_tree = '>', + marker_open_tree = 'v', + } +end + +function M:setBreakpoint() + vim.cmd(":Breakpoint") +end + +function M:setConditionalBreakpoint() + eval = vim.ui.input({ + prompt = "Enter condition" + }, function(expression) + if (expression ~= nil) then + vim.cmd(":Breakpoint conditional " .. expression) + end + end) +end + +function M:startTrace() + selected = get_visual_selection() + + if (selected == nil) then + vim.ui.input({ + prompt = "Enter trace expression" + }, function(expression) + if (expression ~= nil) then + vim.cmd(":VdebugTrace " .. expression) + end + end) + else + vim.cmd(":VdebugTrace " .. selected) + end +end + +function M:eval() + selected = get_visual_selection() + + if (selected == nil) then + vim.ui.input({ + prompt = "Enter eval expression" + }, function(expression) + if (expression ~= nil) then + vim.cmd(":VdebugEval " .. expression) + end + end) + else + vim.cmd(":VdebugEval " .. selected) + end +end + +function M:showBreakpoints() + vim.cmd(":BreakpointWindow") +end + +return M diff --git a/lua/plugin/vim_plug.lua b/lua/plugin/vim_plug.lua new file mode 100644 index 0000000..db91dbe --- /dev/null +++ b/lua/plugin/vim_plug.lua @@ -0,0 +1,37 @@ +local M = {} + +M.path = nil + +function M:initialize(path) + self.path = path +end + +function M:enter() + vim.call('plug#begin', self.path) +end + +function M:exit() + vim.call('plug#end') +end + +function M:add(name, config) + if (type(config) == "nil") then + vim.fn['plug#'](name) + else + vim.fn['plug#'](name, config) + end +end + +function M:install() + -- Bleh, but it works + vim.cmd(':PlugInstall') +end + +function M:hasPendingPackages() + return false +end + +function M:cleanup() +end + +return M