diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml new file mode 100644 index 0000000..37cb224 --- /dev/null +++ b/.github/workflows/compatibility.yml @@ -0,0 +1,64 @@ +name: Compatibility + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + editors: + name: ${{ matrix.os }} / ${{ matrix.editor }} ${{ matrix.version }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + editor: [vim, nvim] + version: [stable] + include: + - os: ubuntu-latest + editor: vim + version: v7.4 + - os: ubuntu-latest + editor: nvim + version: v0.9.5 + - os: ubuntu-latest + editor: nvim + version: v0.11.5 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - name: Install Linux test tools + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y libncurses-dev ripgrep fzf universal-ctags shellcheck + - name: Install macOS test tools + if: runner.os == 'macOS' + run: brew install ripgrep fzf universal-ctags shellcheck + - uses: rhysd/action-setup-vim@v1 + id: editor + env: + CFLAGS: -O2 -std=gnu89 -Wno-error=implicit-function-declaration -Wno-error=incompatible-pointer-types + with: + version: ${{ matrix.version }} + neovim: ${{ matrix.editor == 'nvim' }} + configure-args: --with-features=normal --disable-gui --without-x --disable-nls --enable-multibyte + - name: Check the installer + run: | + sh -n bootstrap.sh + shellcheck -s sh bootstrap.sh + - name: Check editor and installer behavior + env: + DOTVIM_TEST_EDITOR: ${{ steps.editor.outputs.executable }} + NVIM_LOG_FILE: ${{ runner.temp }}/dotvim-nvim.log + run: | + "$DOTVIM_TEST_EDITOR" -u NONE -i NONE -n -es --noplugin -S scripts/install_plugins.vim + python3 -m unittest discover -s tests -v diff --git a/.gitignore b/.gitignore index d70459e..8bd30fb 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,15 @@ Thumbs.db *.swp .svn .netrwhist + +# Local editor state and machine-specific overrides. +vimrc.local +.dotvim-profile +.vimrc.local +.viminfo +.shada +*.un~ +.nvimlog + +# Plugin checkouts are managed by vim-plug; pins live in plugins.vim. +/plugged/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 4858cea..0000000 --- a/.gitmodules +++ /dev/null @@ -1,188 +0,0 @@ -[submodule "bundle/fugitive"] - path = bundle/fugitive - url = https://github.com/tpope/vim-fugitive.git - ignore = dirty -[submodule "bundle/gundo"] - path = bundle/gundo - url = https://github.com/sjl/gundo.vim.git - ignore = dirty -[submodule "bundle/jade"] - path = bundle/jade - url = https://github.com/digitaltoad/vim-jade.git - ignore = dirty -[submodule "bundle/autocomplpop"] - path = bundle/autocomplpop - url = https://github.com/vim-scripts/AutoComplPop.git - ignore = dirty -[submodule "bundle/surround"] - path = bundle/surround - url = https://github.com/tpope/vim-surround.git - ignore = dirty -[submodule "bundle/vst"] - path = bundle/vst - url = https://github.com/vim-scripts/VST.git - ignore = dirty -[submodule "bundle/tagbar"] - path = bundle/tagbar - url = https://github.com/vim-scripts/Tagbar.git - ignore = dirty -[submodule "bundle/jinja2"] - path = bundle/jinja2 - url = https://github.com/Glench/Vim-Jinja2-Syntax.git - ignore = dirty -[submodule "bundle/tabular"] - path = bundle/tabular - url = https://github.com/godlygeek/tabular.git - ignore = dirty -[submodule "bundle/pydoc"] - path = bundle/pydoc - url = https://github.com/fs111/pydoc.vim.git - ignore = dirty -[submodule "bundle/pathogen"] - path = bundle/pathogen - url = https://github.com/tpope/vim-pathogen.git - ignore = dirty -[submodule "bundle/unimpaired"] - path = bundle/unimpaired - url = https://github.com/tpope/vim-unimpaired.git - ignore = dirty -[submodule "bundle/lusty"] - path = bundle/lusty - url = https://github.com/sjbach/lusty.git - ignore = dirty -[submodule "bundle/stylus"] - path = bundle/stylus - url = https://github.com/wavded/vim-stylus.git - ignore = dirty -[submodule "ftplugin/python/pyflakes"] - path = ftplugin/python/pyflakes - url = https://github.com/kevinw/pyflakes.git - ignore = dirty -[submodule "bundle/nerdtree"] - path = bundle/nerdtree - url = https://github.com/scrooloose/nerdtree.git - ignore = dirty -[submodule "bundle/genutils"] - path = bundle/genutils - url = https://github.com/vim-scripts/genutils.git - ignore = dirty -[submodule "bundle/minibufexpl"] - path = bundle/minibufexpl - url = https://github.com/fholgado/minibufexpl.vim.git - ignore = dirty -[submodule "bundle/ack"] - path = bundle/ack - url = https://github.com/mileszs/ack.vim.git - ignore = dirty -[submodule "bundle/bufexplorer"] - path = bundle/bufexplorer - url = https://github.com/vim-scripts/bufexplorer.zip.git - ignore = dirty -[submodule "bundle/mako"] - path = bundle/mako - url = https://github.com/vim-scripts/mako.vim.git - ignore = dirty -[submodule "bundle/speeddating"] - path = bundle/speeddating - url = https://github.com/tpope/vim-speeddating.git - ignore = dirty -[submodule "bundle/vimball"] - path = bundle/vimball - url = https://github.com/vim-scripts/Vimball.git - ignore = dirty -[submodule "bundle/grep"] - path = bundle/grep - url = https://github.com/vim-scripts/grep.vim.git - ignore = dirty -[submodule "bundle/ctrlp"] - path = bundle/ctrlp - url = https://github.com/kien/ctrlp.vim.git - ignore = dirty -[submodule "bundle/tmuxconf"] - path = bundle/tmuxconf - url = https://github.com/tsaleh/vim-tmux.git - ignore = dirty -[submodule "bundle/easymotion"] - path = bundle/easymotion - url = https://github.com/Lokaltog/vim-easymotion.git - ignore = dirty -[submodule "bundle/visualmark"] - path = bundle/visualmark - url = https://github.com/everbird/Visual-Mark.git - ignore = dirty -[submodule "bundle/puppet"] - path = bundle/puppet - url = https://github.com/rodjek/vim-puppet.git - ignore = dirty -[submodule "bundle/indent-guides"] - path = bundle/indent-guides - url = https://github.com/nathanaelkane/vim-indent-guides.git - ignore = dirty -[submodule "bundle/wombat256mod"] - path = bundle/wombat256mod - url = https://github.com/everbird/wombat256.vim.git - ignore = dirty -[submodule "bundle/python"] - path = bundle/python - url = https://github.com/everbird/python.vim--Vasiliev.git - ignore = dirty -[submodule "bundle/buffergator"] - path = bundle/buffergator - url = https://github.com/jeetsukumaran/vim-buffergator.git - ignore = dirty -[submodule "bundle/nerdcommenter"] - path = bundle/nerdcommenter - url = https://github.com/scrooloose/nerdcommenter.git - ignore = dirty -[submodule "bundle/vim-markdown"] - path = bundle/vim-markdown - url = https://github.com/plasticboy/vim-markdown.git - ignore = dirty -[submodule "bundle/vimclojure"] - path = bundle/vimclojure - url = https://github.com/vim-scripts/VimClojure.git - ignore = dirty -[submodule "bundle/easyalign"] - path = bundle/easyalign - url = https://github.com/junegunn/vim-easy-align.git - ignore = dirty -[submodule "bundle/exchange"] - path = bundle/exchange - url = https://github.com/tommcdo/vim-exchange.git -[submodule "bundle/pythonmode"] - path = bundle/pythonmode - url = https://github.com/klen/python-mode.git - ignore = dirty -[submodule "bundle/mips"] - path = bundle/mips - url = https://github.com/vim-scripts/mips.vim.git -[submodule "bundle/json"] - path = bundle/json - url = https://github.com/elzr/vim-json.git -[submodule "bundle/wmgraphviz"] - path = bundle/wmgraphviz - url = https://github.com/wannesm/wmgraphviz.vim.git -[submodule "bundle/snipmate"] - path = bundle/snipmate - url = https://github.com/msanders/snipmate.vim.git -[submodule "bundle/syntastic"] - path = bundle/syntastic - url = https://github.com/vim-syntastic/syntastic.git -[submodule "bundle/vim-go"] - path = bundle/vim-go - url = https://github.com/fatih/vim-go.git -[submodule "bundle/airline"] - path = bundle/airline - url = https://github.com/vim-airline/vim-airline.git -[submodule "bundle/vim-pants"] - path = bundle/vim-pants - url = https://github.com/pantsbuild/vim-pants.git -[submodule "bundle/ansible"] - path = bundle/ansible - url = https://github.com/pearofducks/ansible-vim.git -[submodule "bundle/onedark"] - path = bundle/onedark - url = https://github.com/joshdick/onedark.vim.git -[submodule "bundle/bufonly"] - path = bundle/bufonly - url = https://github.com/vim-scripts/BufOnly.vim.git diff --git a/README.md b/README.md index c9c4ff6..e1fbb96 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,289 @@ -# The automatic installer -You can install this via the command line with either `curl` or `wget`. -## via `curl` +# dotvim - curl -L https://raw.github.com/everbird/dotvim/master/bootstrap.sh | sh -## via `wget` +A shared Vim and Neovim configuration for macOS and Linux. Basic editing works +without plugins or external language runtimes. Optional tools add capabilities +independently, so a server can stay small while a workstation has more features. - wget --no-check-certificate https://raw.github.com/everbird/dotvim/master/bootstrap.sh -O - | sh +## Install -# The manual way -## 1. Installation: - git clone git@github.com:everbird/dotvim.git ~/.vim +```sh +git clone https://github.com/everbird/dotvim.git ~/.everbird-dotvim +sh ~/.everbird-dotvim/bootstrap.sh --basic +``` -## 2. Create symlinks: - ln -s ~/.vim/vimrc ~/.vimrc - ln -s ~/.vim/gvimrc ~/.gvimrc +The default is `--basic`, for both editors. Use `--vim-only` or `--nvim-only` to +install just one entry point. Basic installation needs neither an editor nor Git +when using an existing local copy. -## 3. Switch to the `~/.vim` directory and fetch submodules: - cd ~/.vim - git submodule init - git submodule update +The installer links `~/.vim`, `~/.vimrc`, `~/.gvimrc`, and +`${XDG_CONFIG_HOME:-~/.config}/nvim` to this checkout or its entry files. Existing +files, directories, and broken symlinks are saved under `~/.dotvim-backups/` before +replacement. An existing Neovim configuration directory is backed up as a whole, +including `init.lua`. Repeating the same installation leaves correct links alone. + +To use an existing checkout elsewhere: + +```sh +sh /path/to/dotvim/bootstrap.sh --basic --checkout /path/to/dotvim +``` + +An absent `--checkout` directory is cloned first. Existing checkouts are used as +they are; the installer never pulls or resets them. A local copy of the project +can be installed in basic mode without Git. Git is needed to clone or fetch +plugins. Editor startup never downloads anything. + +For a trial installation away from your real configuration: + +```sh +DOTVIM_HOME=/tmp/dotvim-trial \ +XDG_CONFIG_HOME=/tmp/dotvim-trial/.config \ +sh ./bootstrap.sh --basic +``` + +## Compatibility and profiles + +The shared configuration targets regular Vim 7.4+ builds with `+eval`, +`+autocmd`, and the standard runtime files, and Neovim 0.9+. Vim's tiny build and +plain vi lack the scripting features this configuration uses. +Language syntax follows the installed runtime; older runtimes have fewer filetypes. + +| Profile | Behavior | Runtime dependencies | +| --- | --- | --- | +| `basic` | Native editing, file lookup, directory browsing, search, syntax, and completion | Vim or Neovim | +| `full` | Selected plugin packages, individually checked for required tools | Only the tools for features you use | + +Both profiles work on both operating systems. macOS does not automatically imply +that Homebrew, Python, or other developer tools are present. + +Switch profiles with the installer: + +```sh +sh ~/.everbird-dotvim/bootstrap.sh --full +sh ~/.everbird-dotvim/bootstrap.sh --basic +``` + +The choice is stored in `~/.dotvim-profile`. Restart the editor after changing +profiles or installing plugins. To override the profile for one invocation: + +```sh +DOTVIM_PROFILE=basic vim +DOTVIM_PROFILE=full nvim +``` + +Both editors use [vim-plug](https://github.com/junegunn/vim-plug) in the full +profile. It supports Vim versions without native packages and requires no Python, +Ruby, Lua, or Node.js runtime. Its unmodified `autoload/plug.vim` is included at +revision [`7e5aae5e1187842cb0b1d8def986e48d481c4410`](https://github.com/junegunn/vim-plug/tree/7e5aae5e1187842cb0b1d8def986e48d481c4410), +with its MIT license intact. Basic mode does not load the manager. + +The shared plugin list and exact commit pins are in `plugins.vim`; downloads go +into the ignored `plugged/` directory. No Git submodules are needed. Individual +plugins and LSP features can still require a newer editor. The repeat plugin is +pinned to v1.2 to retain Vim 7 compatibility. + +Even the full profile starts without downloaded plugins. Missing plugins or +tools are skipped, and native editing remains usable. Run `:DotvimHealth` to see +the selected profile, manager, enabled plugins, and reasons for skipped features. + +## Optional features + +`--full` fetches the 13 pinned plugin repositories. It does not install system +packages, run plugin build hooks, or download language servers. +Installation requires Git and either Vim or Neovim. Set `DOTVIM_INSTALL_EDITOR` +to select an executable explicitly. The installer checks every downloaded commit +before replacing configuration links. Repeating an installation with matching +pins works offline, and installed plugins that need no external tools can also +run without Git. + +| Feature | Packages | Required tools or capabilities | +| --- | --- | --- | +| Surround editing and repeat | surround, repeat | None | +| Commenting and alignment | nerdcommenter, easyalign | None | +| File tree | nerdtree | None | +| One Dark theme | onedark | None; basic mode uses desert | +| Git commands | fugitive | `git` | +| Undo history browser | undotree | Persistent undo support and `diff` | +| Symbol outline | tagbar | Universal Ctags | +| Fuzzy file search | fzf, fzf-vim | Vim 8+ or Neovim, and `fzf` 0.63+ | +| Vim LSP client | lsp | Opt-in; Vim 9+ with jobs and channels, and language servers | +| Personal snippets | ultisnips | Opt-in; Vim 8.2+ with Python 3 support, or Neovim's Python provider | + +`rg` improves `:Grep` in either profile. Without it, search uses Vim's built-in +`:vimgrep` and quickfix. Without fzf, `` starts native `:find` completion. +Without NERDTree, the directory mappings use the runtime's native file browser. + +On a workstation, install whichever optional tools you want. For example: + +```sh +# macOS with Homebrew +brew install ripgrep fzf universal-ctags + +# Debian/Ubuntu (package versions vary) +sudo apt-get install ripgrep fzf universal-ctags +``` + +An older fzf executable is skipped. The minimum above follows the pinned +fzf-vim implementation; its upstream README may advertise an older minimum. +Preview helpers such as bat, Perl-based tag commands, and other fzf commands +can have additional optional dependencies; see the +[fzf-vim documentation](https://github.com/junegunn/fzf.vim). + +Tagbar checks the implementation behind `ctags`, `ctags-universal`, and `uctags`. +BSD/macOS ctags and Emacs ctags are skipped. Executables are found through PATH, +so Intel Homebrew, Apple Silicon Homebrew, and Linux need no hardcoded paths. + +## Local settings + +Both editors read `~/.vimrc.local` before configuring optional features. This file +is yours and is never written by the installer. For example: + +```vim +let g:dotvim_profile = 'full' +let g:dotvim_lsp = 1 +let g:dotvim_snippets = 0 +let g:dotvim_colorscheme = 'onedark' + +" Optional executable overrides, including paths with spaces. +" let g:dotvim_ctags = '/custom/path/to/ctags' +" let g:dotvim_python = '/custom/virtualenv/bin/python3' + +" Optional final option and mapping overrides. +function! DotvimLocal() abort + set nocursorcolumn +endfunction +``` + +`DOTVIM_PROFILE` takes precedence over the file. Other settings include +`g:dotvim_truecolor`, `g:dotvim_guifont`, `g:dotvim_guifontwide`, and +`g:dotvim_state_dir`. True color is enabled when the terminal advertises it via +`COLORTERM` or a direct-color `TERM`; the local setting can override detection. +The GUI font defaults to Menlo only in MacVim. + +Swap, backup, and persistent undo directories are kept under +`${XDG_STATE_HOME:-~/.local/state}/dotvim`. An unavailable state directory does +not prevent editing. Viminfo/Shada keep the original preference to omit registers. + +## LSP and snippets + +LSP is off by default. Set `g:dotvim_lsp = 1` in the full profile to enable it: + +- Neovim 0.11+ uses its built-in `vim.lsp.config` and `vim.lsp.enable` APIs. +- Vim 9+ uses [yegappan/lsp](https://github.com/yegappan/lsp). +- Earlier editors keep their native completion and editing features. + +Available servers are detected on PATH: `pylsp`, `gopls`, `clangd`, +`rust-analyzer`, and `typescript-language-server`. Only opening a corresponding +file starts its server. Install the servers you actually use separately; their +own dependencies apply only to those language features. No Node.js or embedded +Python requirement is imposed by the shared LSP configuration. + +To replace that list, define `g:dotvim_lsp_servers` in `~/.vimrc.local`: + +```vim +let g:dotvim_lsp_servers = [ + \ {'name': 'gopls', 'cmd': ['gopls'], 'filetypes': ['go', 'gomod'], + \ 'root_markers': ['go.work', 'go.mod', '.git']} + \ ] +``` + +The original mindflow snippets are preserved as +`snippets/markdown_mindflow.snippets` so modern Markdown filetypes can find them. +Set `g:dotvim_snippets = 1` to load UltiSnips when the Python integration is +available. Vim needs `+python3`; Neovim needs its Python provider and `pynvim`. +Use `mfs` and `mfss` in Markdown, then Tab to expand. These snippets retain their +original Python timestamp interpolation. Snippet dependencies are independent +of LSP and are never required for basic editing. + +## Familiar mappings + +The leader remains comma. + +| Mapping | Action | +| --- | --- | +| `,ve` / `,vs` | Edit / reload the shared vimrc | +| `,cd` | Change to the current file's directory | +| `,d` | Insert today's date | +| `,hl` / `,l` / `,w` / `,s` | Toggle search highlighting / hidden characters / wrapping / spelling | +| `,py` | Save and run the current file with Python 3, falling back to Python | +| `Ctrl-n` / `Ctrl-b` | Next / previous buffer | +| `Ctrl-p` | fzf files, or native file lookup | +| `,nt` / `,nf` | Browse the working directory / current file's directory | +| `wm` / `,wm` | Open/toggle the file browser (sidebar toggle when supported) | +| `Ctrl-Up` / `Ctrl-Down` | Move a line or selected lines | +| `F3` / `:Grep {pattern}` | Search into quickfix | +| `F4` | Toggle Tagbar when available | +| `F5` | Strip trailing whitespace and collapse duplicate blank lines | +| `F6` | Toggle Undotree when available | +| `,a` / visual Enter | EasyAlign in the full profile | +| `,cc` / `,c` | NERDCommenter comment / toggle in the full profile | +| `,gd` / `,gh` / `,gr` | LSP definition / hover / references | +| `F8` / `Ctrl-j` / `Ctrl-k` | UltiSnips list / next / previous placeholder | + +## Updates, migration, and recovery + +Update the configuration explicitly, then refresh the selected profile: + +```sh +git -C ~/.everbird-dotvim pull --ff-only +sh ~/.everbird-dotvim/bootstrap.sh --full +``` + +Use `--basic` instead on a minimal machine. Full mode restores the revisions +recorded in `plugins.vim`. Existing checkouts at those revisions are reused; +changed pins are updated and missing plugins are installed. vim-plug generates +plugin help tags during installation. + +Inside a full-profile editor, `:PlugStatus` reports plugin state, `:PlugInstall` +installs missing plugins, and `:PlugUpdate` updates them to the declared pins. +`PlugUpdate` does not advance pinned plugins to upstream HEAD. `:PlugClean` +offers to remove repositories no longer declared. Plugins disabled by capability +checks or opt-in settings remain declared, so cleanup retains them. + +To update a plugin intentionally, change its commit in `plugins.vim`, run +`bootstrap.sh --full`, and test the relevant editor versions. Updating vim-plug +itself is a separate, reviewed replacement of `autoload/plug.vim`; record its +upstream revision here. Routine configuration updates do not require `:PlugUpgrade`. + +The former Pathogen `bundle/` tree and the earlier `pack/dotvim/opt/` layout are +no longer used by this configuration. Old directories left by +a Git upgrade can be archived after checking for local plugin changes. Redundant +buffer browsers, Python-mode/Syntastic, Ruby-based explorers, Gundo, and bundled +language syntax plugins have been consolidated into native features, the optional +LSP client, and the smaller package set. The original themes remain in `colors/`. + +Each installation prints its backup directory. Only replaced entries are saved: + +| Saved entry | Original location | +| --- | --- | +| `vim` | `~/.vim` | +| `vimrc` | `~/.vimrc` | +| `gvimrc` | `~/.gvimrc` | +| `nvim` | `${XDG_CONFIG_HOME:-~/.config}/nvim` | +| `profile` | `~/.dotvim-profile` | + +To restore one, move the installed link aside and move the corresponding saved +entry back to its original location. Download failures leave existing editor +configuration alone; failures while linking restore entries already moved. + +## Maintenance checks + +Tests use Python 3's standard library and write only to temporary directories. +Python is a development test dependency, not an editor runtime dependency. + +```sh +sh -n bootstrap.sh +shellcheck -s sh bootstrap.sh +python3 -m unittest discover -s tests -v +DOTVIM_TEST_EDITOR=nvim python3 -m unittest discover -s tests -v +``` + +Run `vim -u NONE -i NONE -n -es --noplugin -S scripts/install_plugins.vim` first +to include plugin integration tests; `nvim` can run the same command. This downloads +plugins without changing editor configuration links. The GitHub Actions matrix +covers current Vim and Neovim on Linux/macOS, Vim 7.4 without native packages, +and Neovim 0.9/0.11. Checks include missing plugins and tools, startup without +downloads, reloading, path quoting, LSP initialization, pinned upgrades, offline +reinstallation, backups, idempotence, and rollback. The installer tests use local +Git fixtures and do not need network access. + +Keep comments, documentation, commit messages, and PR descriptions in English. diff --git a/autoload/dotvim.vim b/autoload/dotvim.vim new file mode 100644 index 0000000..b64f410 --- /dev/null +++ b/autoload/dotvim.vim @@ -0,0 +1,92 @@ +" Small helpers shared by Vim and Neovim; no plugin dependencies. +function! dotvim#browse(file_directory) abort + let directory = a:file_directory && !empty(expand('%:p')) ? expand('%:p:h') : getcwd() + if exists(':NERDTreeToggle') == 2 + execute (a:file_directory ? 'NERDTree ' : 'NERDTreeToggle ') . fnameescape(directory) + elseif exists(':Lexplore') == 2 + if !a:file_directory && exists('t:netrw_lexbufnr') && bufwinnr(t:netrw_lexbufnr) > 0 + Lexplore + else + execute 'Lexplore ' . fnameescape(directory) + endif + else + execute 'edit ' . fnameescape(directory) + endif +endfunction + +function! dotvim#optional(command, feature) abort + if exists(':' . a:command) == 2 + execute a:command + else + echo a:feature . ' is optional. See :DotvimHealth and README.md.' + endif +endfunction + +function! dotvim#python() abort + let interpreter = get(g:, 'dotvim_python', executable('python3') ? 'python3' : 'python') + if !executable(interpreter) || empty(expand('%:p')) + echo 'Save this buffer and install Python to run it.' + return + endif + update + execute '!' . escape(shellescape(interpreter) . ' ' . shellescape(expand('%:p')), '!%#') +endfunction + +function! dotvim#grep(pattern) abort + if executable('rg') + let output = system('rg --vimgrep --smart-case -- ' . shellescape(a:pattern) . ' .') + if v:shell_error > 1 + echohl WarningMsg + echomsg output + echohl None + return + endif + let saved_format = &errorformat + try + let &errorformat = '%f:%l:%c:%m' + cgetexpr output + finally + let &errorformat = saved_format + endtry + else + try + execute 'vimgrep /' . escape(a:pattern, '/') . '/gj **/*' + catch /^Vim\%((\a\+)\)\=:E480/ + call setqflist([]) + endtry + endif + if !empty(getqflist()) + copen + else + echo 'No matches.' + endif +endfunction + +function! dotvim#clean() abort + let saved_search = @/ + let saved_view = winsaveview() + let changed = b:changedtick + try + silent keepjumps %s/\s\+$//e + if b:changedtick != changed + undojoin + endif + silent keepjumps %s/\n\{3,}/\r\r/ge + finally + let @/ = saved_search + call winrestview(saved_view) + endtry +endfunction + +function! dotvim#health() abort + echo (has('nvim') ? 'Neovim' : 'Vim') . ' / profile: ' . g:dotvim_profile + echo 'Plugin loader: ' . get(g:, 'dotvim_package_loader', 'disabled') + echo 'Enabled plugins: ' . join(get(g:, 'dotvim_loaded_plugins', []), ', ') + for reason in get(g:, 'dotvim_skipped_plugins', []) + echo 'Skipped: ' . reason + endfor + echo 'LSP: ' . get(g:, 'dotvim_lsp_status', 'disabled (opt in with g:dotvim_lsp)') + for tool in ['git', 'rg', 'fzf', 'ctags', 'python3'] + echo tool . ': ' . (executable(tool) ? 'available' : 'optional, not found') + endfor +endfunction diff --git a/autoload/pathogen.vim b/autoload/pathogen.vim deleted file mode 120000 index a202405..0000000 --- a/autoload/pathogen.vim +++ /dev/null @@ -1 +0,0 @@ -../bundle/pathogen/autoload/pathogen.vim \ No newline at end of file diff --git a/autoload/plug.vim b/autoload/plug.vim new file mode 100644 index 0000000..58a894e --- /dev/null +++ b/autoload/plug.vim @@ -0,0 +1,2914 @@ +" vim-plug: Vim plugin manager +" ============================ +" +" 1. Download plug.vim and put it in 'autoload' directory +" +" # Vim +" curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ +" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim +" +" # Neovim +" sh -c 'curl -fLo "${XDG_DATA_HOME:-$HOME/.local/share}"/nvim/site/autoload/plug.vim --create-dirs \ +" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim' +" +" 2. Add a vim-plug section to your ~/.vimrc (or ~/.config/nvim/init.vim for Neovim) +" +" call plug#begin() +" +" " List your plugins here +" Plug 'tpope/vim-sensible' +" +" call plug#end() +" +" 3. Reload the file or restart Vim, then you can, +" +" :PlugInstall to install plugins +" :PlugUpdate to update plugins +" :PlugDiff to review the changes from the last update +" :PlugClean to remove plugins no longer in the list +" +" For more information, see https://github.com/junegunn/vim-plug +" +" +" Copyright (c) 2024 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:shell_error = 0 +if s:is_win && &shellslash + set noshellslash + let s:me = resolve(expand(':p')) + set shellslash +else + let s:me = resolve(expand(':p')) +endif +let s:base_spec = { 'branch': '', '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! s:is_powershell(shell) + return a:shell =~# 'powershell\(\.exe\)\?$' || a:shell =~# 'pwsh\(\.exe\)\?$' +endfunction + +function! s:isabsolute(dir) abort + return a:dir =~# '^/' || (has('win32') && a:dir =~? '^\%(\\\|[A-Z]:\)') +endfunction + +function! s:git_dir(dir) abort + let gitdir = s:trim(a:dir) . '/.git' + if isdirectory(gitdir) + return gitdir + endif + if !filereadable(gitdir) + return '' + endif + let gitdir = matchstr(get(readfile(gitdir), 0, ''), '^gitdir: \zs.*') + if len(gitdir) && !s:isabsolute(gitdir) + let gitdir = a:dir . '/' . gitdir + endif + return isdirectory(gitdir) ? gitdir : '' +endfunction + +function! s:git_origin_url(dir) abort + let gitdir = s:git_dir(a:dir) + let config = gitdir . '/config' + if empty(gitdir) || !filereadable(config) + return '' + endif + return matchstr(join(readfile(config)), '\[remote "origin"\].\{-}url\s*=\s*\zs\S*\ze') +endfunction + +function! s:git_revision(dir) abort + let gitdir = s:git_dir(a:dir) + let head = gitdir . '/HEAD' + if empty(gitdir) || !filereadable(head) + return '' + endif + + let line = get(readfile(head), 0, '') + let ref = matchstr(line, '^ref: \zs.*') + if empty(ref) + return line + endif + + if filereadable(gitdir . '/' . ref) + return get(readfile(gitdir . '/' . ref), 0, '') + endif + + if filereadable(gitdir . '/packed-refs') + for line in readfile(gitdir . '/packed-refs') + if line =~# ' ' . ref + return matchstr(line, '^[0-9a-f]*') + endif + endfor + endif + + return '' +endfunction + +function! s:git_local_branch(dir) abort + let gitdir = s:git_dir(a:dir) + let head = gitdir . '/HEAD' + if empty(gitdir) || !filereadable(head) + return '' + endif + let branch = matchstr(get(readfile(head), 0, ''), '^ref: refs/heads/\zs.*') + return len(branch) ? branch : 'HEAD' +endfunction + +function! s:git_origin_branch(spec) + if len(a:spec.branch) + return a:spec.branch + endif + + " The file may not be present if this is a local repository + let gitdir = s:git_dir(a:spec.dir) + let origin_head = gitdir.'/refs/remotes/origin/HEAD' + if len(gitdir) && filereadable(origin_head) + return matchstr(get(readfile(origin_head), 0, ''), + \ '^ref: refs/remotes/origin/\zs.*') + endif + + " The command may not return the name of a branch in detached HEAD state + let result = s:lines(s:system('git symbolic-ref --short HEAD', a:spec.dir)) + return s:shell_error ? '' : result[-1] +endfunction + +if s:is_win + function! s:plug_call(fn, ...) + let shellslash = &shellslash + try + set noshellslash + return call(a:fn, a:000) + finally + let &shellslash = shellslash + endtry + endfunction +else + function! s:plug_call(fn, ...) + return call(a:fn, a:000) + endfunction +endif + +function! s:plug_getcwd() + return s:plug_call('getcwd') +endfunction + +function! s:plug_fnamemodify(fname, mods) + return s:plug_call('fnamemodify', a:fname, a:mods) +endfunction + +function! s:plug_expand(fmt) + return s:plug_call('expand', a:fmt, 1) +endfunction + +function! s:plug_tempname() + return s:plug_call('tempname') +endfunction + +function! plug#begin(...) + if a:0 > 0 + let home = s:path(s:plug_fnamemodify(s:plug_expand(a:1), ':p')) + elseif exists('g:plug_home') + let home = s:path(g:plug_home) + elseif has('nvim') + let home = stdpath('data') . '/plugged' + 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 s:plug_fnamemodify(home, ':t') ==# 'plugin' && s:plug_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 + if has('win32') + \ && &shellslash + \ && (&shell =~# 'cmd\(\.exe\)\?$' || s:is_powershell(&shell)) + return s:err('vim-plug does not support shell, ' . &shell . ', when shellslash is set.') + endif + if !has('nvim') + \ && (has('win32') || has('win32unix')) + \ && !has('multi_byte') + return s:err('Vim needs +multi_byte feature on Windows to run shell commands. Enable +iconv for best results.') + 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('plug#end() called without calling plug#begin() first') + endif + + if exists('#PlugLOD') + augroup PlugLOD + autocmd! + augroup END + augroup! PlugLOD + endif + let lod = { 'ft': {}, 'map': {}, 'cmd': {} } + + if get(g:, 'did_load_filetypes', 0) + 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') + if has('nvim-0.5.0') + call s:source(s:rtp(plug), 'ftdetect/**/*.lua', 'after/ftdetect/**/*.lua') + endif + 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( + \ has('patch-7.4.1898') + \ ? 'command! -nargs=* -range -bang -complete=file %s call s:lod_cmd(%s, "", , , , ,%s)' + \ : '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') + if has('nvim-0.5.0') + call s:source(s:rtp(a:spec), 'plugin/**/*.lua', 'after/plugin/**/*.lua') + endif +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 + +function! s:rtp(spec) + return s:path(a:spec.dir . get(a:spec, 'rtp', '')) +endfunction + +if s:is_win + 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 + + " Copied from fzf + function! s:wrap_cmds(cmds) + let cmds = [ + \ '@echo off', + \ 'setlocal enabledelayedexpansion'] + \ + (type(a:cmds) == type([]) ? a:cmds : [a:cmds]) + \ + ['endlocal'] + if has('iconv') + if !exists('s:codepage') + let s:codepage = libcallnr('kernel32.dll', 'GetACP', 0) + endif + return map(cmds, printf('iconv(v:val."\r", "%s", "cp%d")', &encoding, s:codepage)) + endif + return map(cmds, 'v:val."\r"') + endfunction + + function! s:batchfile(cmd) + let batchfile = s:plug_tempname().'.bat' + call writefile(s:wrap_cmds(a:cmd), batchfile) + let cmd = plug#shellescape(batchfile, {'shell': &shell, 'script': 0}) + if s:is_powershell(&shell) + let cmd = '& ' . cmd + endif + return [batchfile, cmd] + endfunction +else + 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 = map(filter(copy(rtps), 'isdirectory(v:val."/after")'), 's:path(v:val."/after")') + 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) + " Nothing to detect in an unnamed empty buffer, e.g. the one on startup + if empty(bufname('%')) && line('$') == 1 && empty(getline(1)) + return + endif + for name in a:names + let path = s:rtp(g:plugs[name]) + for dir in ['ftdetect', 'ftplugin', 'after/ftdetect', 'after/ftplugin'] + if isdirectory(path.'/'.dir) + 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') + if has('nvim-0.5.0') " see neovim#14686 + call s:source(rtp, dir.'/**/*.lua') + endif + 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 + +if has('patch-7.4.1898') + function! s:lod_cmd(cmd, bang, l1, l2, args, mods, names) + call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin']) + call s:dobufread(a:names) + execute printf('%s %s%s%s %s', a:mods, (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args) + endfunction +else + 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 +endif + +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', s:plug_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(repo . ' ' . v:exception) + endtry +endfunction + +function! s:parse_options(arg) + let opts = copy(s:base_spec) + let type = type(a:arg) + let opt_errfmt = 'Invalid argument for "%s" option of :Plug (expected: %s)' + if type == s:TYPE.string + if empty(a:arg) + throw printf(opt_errfmt, 'tag', 'string') + endif + let opts.tag = a:arg + elseif type == s:TYPE.dict + for opt in ['branch', 'tag', 'commit', 'rtp', 'dir', 'as'] + if has_key(a:arg, opt) + \ && (type(a:arg[opt]) != s:TYPE.string || empty(a:arg[opt])) + throw printf(opt_errfmt, opt, 'string') + endif + endfor + for opt in ['on', 'for'] + if has_key(a:arg, opt) + \ && type(a:arg[opt]) != s:TYPE.list + \ && (type(a:arg[opt]) != s:TYPE.string || empty(a:arg[opt])) + throw printf(opt_errfmt, opt, 'string or list') + endif + endfor + if has_key(a:arg, 'do') + \ && type(a:arg.do) != s:TYPE.funcref + \ && (type(a:arg.do) != s:TYPE.string || empty(a:arg.do)) + throw printf(opt_errfmt, 'do', 'string or funcref') + endif + call extend(opts, a:arg) + if has_key(opts, 'dir') + let opts.dir = s:dirpath(s:plug_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(s:plug_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,plugAbort + syn match plugNumber /[0-9]\+[0-9.]*/ contained + syn match plugBracket /[[\]]/ contained + syn match plugX /x/ contained + syn match plugAbort /\~/ contained + syn match plugDash /^-\{1}\ / + 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 match plugH2 /^-\{2,}/ + 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 plugAbort Ignore + 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', '-tabnew') +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(s:plug_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(0) + if s:switch_in() + if b:plug_preview == 1 + pc + endif + enew + else + call s:new_window() + endif + + nnoremap q :call close_pane() + 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:close_pane() + if b:plug_preview == 1 + pc + let b:plug_preview = -1 + elseif exists('s:jobs') && !empty(s:jobs) + call s:job_abort(1) + else + bd + 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=sh + endif + if a:swap + if s:is_powershell(&shell) + let &shellredir = '2>&1 | Out-File -Encoding UTF8 %s' + elseif &shell =~# 'sh' || &shell =~# 'cmd\(\.exe\)\?$' + set shellredir=>%s\ 2>&1 + endif + endif + return prev +endfunction + +function! s:bang(cmd, ...) + let batchfile = '' + 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, {'shell': s:is_win ? 'cmd.exe' : &shell}) : a:cmd + if s:is_win + let [batchfile, cmd] = s:batchfile(cmd) + 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 && filereadable(batchfile) + 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) + if has('nvim') + " Reset &rtp to invalidate Neovim cache of loaded Lua modules + " See https://github.com/junegunn/vim-plug/pull/1157#issuecomment-1809226110 + let &rtp = &rtp + endif + 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 + call s:load_plugin(spec) + 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:disable_credential_helper() + return s:git_version_requirement(2) && get(g:, 'plug_disable_credential_helper', 1) +endfunction + +function! s:checkout(spec) + let sha = a:spec.commit + let output = s:git_revision(a:spec.dir) + let error = 0 + if !empty(output) && !s:hash_match(sha, s:lines(output)[0]) + let credential_helper = s:disable_credential_helper() ? '-c credential.helper= ' : '' + let output = s:system( + \ 'git '.credential_helper.'fetch --depth 999999 && git checkout '.plug#shellescape(sha).' --', a:spec.dir) + let error = s:shell_error + endif + return [output, error] +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(deepcopy(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 + + " Set remote name, overriding a possible user git config's clone.defaultRemoteName + let s:clone_opt = ['--origin', 'origin'] + if get(g:, 'plug_shallow', 1) + call extend(s:clone_opt, ['--depth', '1']) + if s:git_version_requirement(1, 7, 10) + call add(s:clone_opt, '--no-single-branch') + endif + endif + + if has('win32unix') || has('wsl') + call extend(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 + let out = '' + let error = 0 + if has_key(spec, 'commit') + call s:log4(name, 'Checking out '.spec.commit) + let [out, error] = s:checkout(spec) + elseif has_key(spec, 'tag') + let tag = spec.tag + if tag =~ '\*' + let tags = s:lines(s:system('git tag --list '.plug#shellescape(tag).' --sort -version:refname 2>&1', spec.dir)) + if !s: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 '.plug#shellescape(tag).' -- 2>&1', spec.dir) + let error = s:shell_error + endif + if !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) + let error = v:shell_error + endif + let msg = s:format_message(error ? 'x': '-', name, out) + if 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:mark_aborted(name, message) + let attrs = { 'running': 0, 'error': 1, 'abort': 1, 'lines': [a:message] } + let s:jobs[a:name] = extend(get(s:jobs, a:name, {}), attrs) +endfunction + +function! s:job_abort(cancel) + 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:rm_rf(g:plugs[name].dir) + endif + if a:cancel + call s:mark_aborted(name, 'Aborted') + endif + endfor + + if a:cancel + for todo in values(s:update.todo) + let todo.abort = 1 + endfor + else + let s:jobs = {} + endif +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:bullet_for(job, ...) + if a:job.running + return a:job.new ? '+' : '*' + endif + if get(a:job, 'abort', 0) + return '~' + endif + return a:job.error ? 'x' : get(a:000, 0, '-') +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 result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines) + if len(result) + call s:log(s:bullet_for(self), self.name, result) + endif + 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(0) + endif + call call(a:fn, [a:job, a:data]) +endfunction + +function! s:nvim_cb(job_id, data, event) dict abort + return (a:event == 'stdout' || a:event == 'stderr') ? + \ 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, spec, queue, opts) + let job = { 'name': a:name, 'spec': a:spec, 'running': 1, 'error': 0, 'lines': [''], + \ 'new': get(a:opts, 'new', 0), 'queue': copy(a:queue) } + let Item = remove(job.queue, 0) + let argv = type(Item) == s:TYPE.funcref ? call(Item, [a:spec]) : Item + let s:jobs[a:name] = job + + if s:nvim + if has_key(a:opts, 'dir') + let job.cwd = a:opts.dir + endif + call extend(job, { + \ 'on_stdout': function('s:nvim_cb'), + \ 'on_stderr': function('s:nvim_cb'), + \ 'on_exit': function('s:nvim_cb'), + \ }) + let jid = s:plug_call('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 cmd = join(map(copy(argv), 'plug#shellescape(v:val, {"script": 0})')) + if has_key(a:opts, 'dir') + let cmd = s:with_cd(cmd, a:opts.dir, {'shell': s:is_win ? 'cmd.exe' : 'sh', 'script': 0}) + endif + let argv = s:is_win ? ['cmd', '/s', '/c', '"'.cmd.'"'] : ['sh', '-c', cmd] + let jid = job_start(s:is_win ? join(argv, ' ') : argv, { + \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]), + \ 'err_cb': function('s:job_cb', ['s:job_out_cb', job]), + \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]), + \ 'err_mode': 'raw', + \ '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', has_key(a:opts, 'dir') ? [argv, a:opts.dir] : [argv])) + let job.error = s:shell_error != 0 + let job.running = 0 + endif +endfunction + +function! s:reap(name) + let job = remove(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 more = len(get(job, 'queue', [])) + let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines) + if len(result) + call s:log(s:bullet_for(job), a:name, result) + endif + + if !job.error && more + let job.spec.queue = job.queue + let s:update.todo[a:name] = job.spec + else + let s:update.bar .= s:bullet_for(job, '=') + call s:bar() + endif +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) + let max = line('$') + for i in range(4, max > 4 ? max : 4) + if getline(i) =~# '^[-+x*] '.a:name.':' + for j in range(i + 1, max > 5 ? max : 5) + 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:checkout_command(spec) + let a:spec.branch = s:git_origin_branch(a:spec) + return ['git', 'checkout', '-q', a:spec.branch, '--'] +endfunction + +function! s:merge_command(spec) + let a:spec.branch = s:git_origin_branch(a:spec) + return ['git', 'merge', '--ff-only', 'origin/'.a:spec.branch] +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) + if get(spec, 'abort', 0) + call s:mark_aborted(name, 'Skipped') + call s:reap(name) + continue + endif + + let queue = get(spec, 'queue', []) + let new = empty(globpath(spec.dir, '.git', 1)) + + if empty(queue) + call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...') + redraw + endif + + let has_tag = has_key(spec, 'tag') + if len(queue) + call s:spawn(name, spec, queue, { 'dir': spec.dir }) + elseif !new + let [error, _] = s:git_validate(spec, 0) + if empty(error) + if pull + let cmd = s:disable_credential_helper() ? ['git', '-c', 'credential.helper=', 'fetch'] : ['git', 'fetch'] + if has_tag && !empty(globpath(spec.dir, '.git/shallow')) + call extend(cmd, ['--depth', '99999999']) + endif + if !empty(prog) + call add(cmd, prog) + endif + let queue = [cmd, split('git remote set-head origin -a')] + if !has_tag && !has_key(spec, 'commit') + call extend(queue, [function('s:checkout_command'), function('s:merge_command')]) + endif + call s:spawn(name, spec, queue, { '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 + let cmd = ['git', 'clone'] + if !has_tag + call extend(cmd, s:clone_opt) + endif + if !empty(prog) + call add(cmd, prog) + endif + call s:spawn(name, spec, [extend(cmd, [spec.uri, s:trim(spec.dir)]), function('s:checkout_command'), function('s:merge_command')], { '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 = ' '.join(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').join(' ') + 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, script) + let escaped = substitute('"'.a:arg.'"', '[&|<>()@^!"]', '^&', 'g') + return substitute(escaped, '%', (a:script ? '%' : '^') . '&', 'g') +endfunction + +function! s:shellesc_ps1(arg) + return "'".substitute(escape(a:arg, '\"'), "'", "''", 'g')."'" +endfunction + +function! s:shellesc_sh(arg) + return "'".substitute(a:arg, "'", "'\\\\''", 'g')."'" +endfunction + +" Escape the shell argument based on the shell. +" Vim and Neovim's shellescape() are insufficient. +" 1. shellslash determines whether to use single/double quotes. +" Double-quote escaping is fragile for cmd.exe. +" 2. It does not work for powershell. +" 3. It does not work for *sh shells if the command is executed +" via cmd.exe (ie. cmd.exe /c sh -c command command_args) +" 4. It does not support batchfile syntax. +" +" Accepts an optional dictionary with the following keys: +" - shell: same as Vim/Neovim 'shell' option. +" If unset, fallback to 'cmd.exe' on Windows or 'sh'. +" - script: If truthy and shell is cmd.exe, escape for batchfile syntax. +function! plug#shellescape(arg, ...) + if a:arg =~# '^[A-Za-z0-9_/:.-]\+$' + return a:arg + endif + let opts = a:0 > 0 && type(a:1) == s:TYPE.dict ? a:1 : {} + let shell = get(opts, 'shell', s:is_win ? 'cmd.exe' : 'sh') + let script = get(opts, 'script', 1) + if shell =~# 'cmd\(\.exe\)\?$' + return s:shellesc_cmd(a:arg, script) + elseif s:is_powershell(shell) + return s:shellesc_ps1(a:arg) + endif + return s:shellesc_sh(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, ...) + let opts = a:0 > 0 && type(a:1) == s:TYPE.dict ? a:1 : {} + let opts.shell = get(opts, 'shell', &shell) + let opts.script = get(opts, 'script', 1) + + let pwsh = s:is_powershell(opts.shell) + let cd = s:is_win && !pwsh ? 'cd /d' : 'cd' + let sep = pwsh ? ';' : '&&' + let pwsh_block_required = pwsh && !has('patch-9.2.6') + let start = pwsh_block_required ? '& { ' : '' + let end = pwsh_block_required ? ' }' : '' + + return printf('%s%s %s %s %s%s', start, cd, plug#shellescape(a:dir, opts), sep, a:cmd, end) +endfunction + +function! s:system_job(cmd) abort + let tmp = tempname() + let job = job_start(['/bin/sh', '-c', a:cmd], { + \ 'out_io': 'file', + \ 'out_name': tmp, + \ 'err_io': 'out', + \}) + while job_status(job) ==# 'run' + sleep 1m + endwhile + let s:shell_error = job_info(job).exitval + let result = filereadable(tmp) ? join(readfile(tmp, 'b'), "\n") : '' + silent! call delete(tmp) + return result +endfunction + +function! s:system(cmd, ...) + let batchfile = '' + try + let [sh, shellcmdflag, shrd] = s:chsh(1) + if type(a:cmd) == s:TYPE.list + " Neovim's system() supports list argument to bypass the shell + " but it cannot set the working directory for the command. + " Assume that the command does not rely on the shell. + if has('nvim') && a:0 == 0 + let ret = system(a:cmd) + let s:shell_error = v:shell_error + return ret + endif + let cmd = join(map(copy(a:cmd), 'plug#shellescape(v:val, {"shell": &shell, "script": 0})')) + if s:is_powershell(&shell) + let cmd = '& ' . cmd + endif + else + let cmd = a:cmd + endif + if a:0 > 0 + let cmd = s:with_cd(cmd, a:1, {'script': type(a:cmd) != s:TYPE.list}) + endif + if s:is_win && type(a:cmd) != s:TYPE.list && !s:is_powershell(&shell) + let [batchfile, cmd] = s:batchfile(cmd) + endif + if s:vim8 && has('gui_running') && !s:is_win + return s:system_job(cmd) + endif + let ret = system(cmd) + let s:shell_error = v:shell_error + return ret + finally + let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] + if s:is_win && filereadable(batchfile) + call delete(batchfile) + endif + endtry +endfunction + +function! s:system_chomp(...) + let ret = call('s:system', a:000) + return s:shell_error ? '' : substitute(ret, '\n$', '', '') +endfunction + +function! s:git_validate(spec, check_branch) + let err = '' + if isdirectory(a:spec.dir) + let result = [s:git_local_branch(a:spec.dir), s:git_origin_url(a:spec.dir)] + let remote = result[-1] + if empty(remote) + 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 + return ['', 0] + elseif has_key(a:spec, 'commit') + let sha = s:git_revision(a:spec.dir) + if empty(sha) + 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 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 + elseif a:check_branch + let current_branch = result[0] + let origin_branch = s:git_origin_branch(a:spec) + if origin_branch !=# current_branch + let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.', + \ current_branch, origin_branch) + endif + if empty(err) + let ahead_behind = split(s:lastline(s:system([ + \ 'git', 'rev-list', '--count', '--left-right', + \ printf('HEAD...origin/%s', origin_branch) + \ ], a:spec.dir)), '\t') + if s:shell_error || len(ahead_behind) != 2 + let err = "Failed to compare with the origin. The default branch might have changed.\nPlugClean required." + else + let [ahead, behind] = ahead_behind + if ahead && 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.', origin_branch, ahead, behind) + elseif ahead + let err = printf("Ahead of origin/%s by %d commit(s).\n" + \ .'Cannot update until local changes are pushed.', + \ origin_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) + return s:system(!s:is_win + \ ? ['rm', '-rf', a:dir] + \ : s:is_powershell(&shell) + \ ? ['Remove-Item', '-Recurse', '-Force', a:dir] + \ : 'rmdir /S /Q '.plug#shellescape(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) || get(spec, 'frozen', 0) + 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(s:plug_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 + let err_count = 0 + 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 + let err = s:rm_rf(line[2:]) + setlocal modifiable + if empty(err) + call setline(l1, '~'.line[1:]) + let s:clean_count += 1 + else + delete _ + call append(l1 - 1, s:format_message('x', line[1:], err)) + let l2 += len(s:lines(err)) + let err_count += 1 + endif + let msg = printf('Removed %d directories.', s:clean_count) + if err_count > 0 + let msg .= printf(' Failed to remove %d directories.', err_count) + endif + call setline(4, msg) + setlocal nomodifiable + endif + endif + let l1 += 1 + endwhile +endfunction + +function! s:upgrade() + echo 'Downloading the latest version of vim-plug' + redraw + let tmp = s:plug_tempname() + let new = tmp . '/plug.vim' + + try + let out = s:system(['git', 'clone', '--depth', '1', s:plug_src, tmp]) + if s: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) + let name = matchstr(getline('.'), '^- \zs[^:]*\ze:$') + if empty(name) + return + endif + let title = 'HEAD@{1}..' + let command = 'git diff --no-color HEAD@{1}' + else + let title = sha + let command = 'git show --no-color --pretty=medium '.sha + let name = s:find_name(line('.')) + endif + + if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir) + return + endif + + if !s:is_preview_window_open() + execute get(g:, 'plug_pwindow', 'vertical rightbelow new') + execute 'e' title + else + execute 'pedit' title + wincmd P + endif + setlocal previewwindow filetype=git buftype=nofile bufhidden=wipe nobuflisted modifiable + let batchfile = '' + try + let [sh, shellcmdflag, shrd] = s:chsh(1) + let cmd = 'cd '.plug#shellescape(g:plugs[name].dir).' && '.command + if s:is_win + let [batchfile, cmd] = s:batchfile(cmd) + endif + execute 'silent %!' cmd + finally + let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd] + if s:is_win && filereadable(batchfile) + 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 branch = s:git_origin_branch(v) + if len(branch) + let range = origin ? '..origin/'.branch : 'HEAD@{1}..' + let cmd = ['git', 'log', '--graph', '--color=never'] + if s:git_version_requirement(2, 10, 0) + call add(cmd, '--no-show-signature') + endif + call extend(cmd, ['--pretty=format:%x01%h%x01%d%x01%s%x01%cr', range]) + if has_key(v, 'rtp') + call extend(cmd, ['--', 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 + 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 '.plug#shellescape(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") && isdirectory(v:val.dir)'))) + for name in reverse(names) + let sha = has_key(g:plugs[name], 'commit') ? g:plugs[name].commit : s:git_revision(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 = s:plug_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, '\\\@&2 +The default installs basic configuration for both Vim and Neovim. +--full downloads pinned plugins with vim-plug; Git and Vim or Neovim are required. +--checkout uses an existing checkout or clones into DIR if it is absent. +DOTVIM_HOME overrides the installation home (useful for a trial installation). +XDG_CONFIG_HOME sets the Neovim configuration parent directory. +DOTVIM_INSTALL_EDITOR selects the Vim or Neovim executable for plugin installation. +Existing configurations are backed up under DOTVIM_HOME/.dotvim-backups. +EOF } die() { - warn "$1" - exit 1 + printf '%s\n' "$*" >&2 + exit 1 } -# Backup existing .vim stuff -echo "backing up current vim config\n" -today=`date +%Y%m%d` -for i in $HOME/.vim $HOME/.vimrc $HOME/.gvimrc; do [ -e $i ] && mv $i $i.$today; done +profile=basic +editors=both +checkout= +while [ "$#" -gt 0 ]; do + case "$1" in + --basic) profile=basic ;; + --full) profile=full ;; + --vim-only) editors=vim ;; + --nvim-only) editors=nvim ;; + --checkout) + [ "$#" -ge 2 ] || die '--checkout requires a directory' + checkout=$2 + shift + ;; + --help|-h) usage; exit 0 ;; + *) die "Unknown option: $1 (see --help)" ;; + esac + shift +done +install_home=${DOTVIM_HOME:-$HOME} +config_home=${XDG_CONFIG_HOME:-$install_home/.config} +script_dir=$(CDPATH='' cd -P "$(dirname "$0")" 2>/dev/null && pwd) || script_dir= +if [ -z "$checkout" ]; then + if [ -f "$script_dir/vimrc" ] && [ -f "$script_dir/plugins.vim" ]; then + checkout=$script_dir + else + checkout=$install_home/.everbird-dotvim + fi +fi -echo "cloning everbird-dotvim\n" -git clone --recursive https://github.com/everbird/dotvim.git $endpath -mkdir -p $endpath/bundle -ln -s $endpath/vimrc $HOME/.vimrc -ln -s $endpath $HOME/.vim +stage=$(mktemp -d "${TMPDIR:-/tmp}/dotvim-install.XXXXXX") +clone_dir= +profile_tmp= +committed=0 +touch "$stage/journal" + +cleanup() { + if [ "$committed" -eq 0 ]; then + while IFS= read -r target && IFS= read -r source && IFS= read -r saved; do + if [ "$source" = '@profile' ]; then + if [ -f "$target" ] && cmp -s "$stage/profile" "$target"; then + rm -f "$target" + fi + elif [ -L "$target" ] && [ "$(readlink "$target")" = "$source" ]; then + rm "$target" + fi + if [ "$saved" != '-' ] && { [ -e "$saved" ] || [ -L "$saved" ]; }; then + if [ ! -e "$target" ] && [ ! -L "$target" ]; then + mv "$saved" "$target" + else + printf 'Restore the saved configuration manually: %s\n' "$saved" >&2 + fi + fi + done < "$stage/journal" + fi + [ -z "$clone_dir" ] || rm -rf "$clone_dir" + [ -z "$profile_tmp" ] || rm -f "$profile_tmp" + rm -rf "$stage" +} +trap cleanup 0 +trap 'exit 1' HUP INT TERM + +# Complete downloads and validation before changing existing editor configuration. +if [ ! -e "$checkout" ] && [ ! -L "$checkout" ]; then + command -v git >/dev/null 2>&1 || die 'Git is required to clone the configuration.' + mkdir -p "$(dirname "$checkout")" + clone_dir=$(mktemp -d "$checkout.clone.XXXXXX") + git clone "${DOTVIM_REPOSITORY:-https://github.com/everbird/dotvim.git}" "$clone_dir" + mv "$clone_dir" "$checkout" + clone_dir= +fi +checkout=$(CDPATH='' cd -P "$checkout" && pwd) || die 'Cannot access the checkout.' +for file in vimrc plugins.vim gvimrc init.vim; do + [ -f "$checkout/$file" ] || die "Missing $file in $checkout" +done +if [ "$profile" = full ]; then + command -v git >/dev/null 2>&1 || die 'Git is required to download plugins.' + install_editor=${DOTVIM_INSTALL_EDITOR:-} + if [ -z "$install_editor" ]; then + if [ "$editors" = nvim ] && command -v nvim >/dev/null 2>&1; then + install_editor=nvim + elif command -v vim >/dev/null 2>&1; then + install_editor=vim + elif command -v nvim >/dev/null 2>&1; then + install_editor=nvim + else + die 'Vim or Neovim is required to install plugins with vim-plug.' + fi + fi + command -v "$install_editor" >/dev/null 2>&1 || die "Cannot find the installation editor: $install_editor" + [ -f "$checkout/scripts/install_plugins.vim" ] || die 'Missing scripts/install_plugins.vim' + # Vim 7.4 expands -S paths through the shell; use POSIX quoting before it does. + if ! "$install_editor" -u NONE -i NONE -n -es --noplugin --cmd 'set shell=/bin/sh' -S "$checkout/scripts/install_plugins.vim"; then + die 'Plugin installation failed; editor configuration was not changed.' + fi +fi +mkdir -p "$install_home" +install_home=$(CDPATH='' cd -P "$install_home" && pwd) +if [ "$editors" != vim ]; then + mkdir -p "$config_home" + config_home=$(CDPATH='' cd -P "$config_home" && pwd) +fi +printf '%s\n' "$profile" > "$stage/profile" +backup_dir=$install_home/.dotvim-backups/$(date +%Y%m%dT%H%M%S).$$ + +save_target() { + target=$1 + source=$2 + label=$3 + saved=- + if [ -e "$target" ] || [ -L "$target" ]; then + saved=$backup_dir/$label + fi + # Record intent before moving anything, so a failed link can be rolled back. + printf '%s\n%s\n%s\n' "$target" "$source" "$saved" >> "$stage/journal" + if [ "$saved" != '-' ]; then + mkdir -p "$backup_dir" + mv "$target" "$saved" + fi +} + +link_config() { + source=$1 + target=$2 + label=$3 + if [ -L "$target" ] && [ "$(readlink "$target")" = "$source" ]; then + return + fi + # Manual installations may already use ~/.vim as the actual checkout. + if [ -d "$source" ] && [ -d "$target" ] && [ "$(CDPATH='' cd -P "$target" && pwd)" = "$source" ]; then + return + fi + save_target "$target" "$source" "$label" + ln -s "$source" "$target" +} + +if [ "$editors" != nvim ]; then + link_config "$checkout" "$install_home/.vim" vim + link_config "$checkout/vimrc" "$install_home/.vimrc" vimrc + link_config "$checkout/gvimrc" "$install_home/.gvimrc" gvimrc +fi +if [ "$editors" != vim ]; then + link_config "$checkout" "$config_home/nvim" nvim +fi +if ! cmp -s "$stage/profile" "$install_home/.dotvim-profile"; then + profile_tmp=$(mktemp "$install_home/.dotvim-profile.XXXXXX") + cp "$stage/profile" "$profile_tmp" + save_target "$install_home/.dotvim-profile" '@profile' profile + mv "$profile_tmp" "$install_home/.dotvim-profile" + profile_tmp= +fi +committed=1 +printf 'Installed the %s profile from %s\n' "$profile" "$checkout" +if [ -d "$backup_dir" ]; then + printf 'Previous configuration: %s\n' "$backup_dir" +fi +printf 'Restart the editor, then run :DotvimHealth for optional feature status.\n' diff --git a/bundle/ack b/bundle/ack deleted file mode 160000 index 9895285..0000000 --- a/bundle/ack +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9895285042a2fd5691b2f6582aa979e4d1bdffea diff --git a/bundle/airline b/bundle/airline deleted file mode 160000 index 251ed06..0000000 --- a/bundle/airline +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 251ed064e84dc684a944edbe37d3c559af3e02bf diff --git a/bundle/ansible b/bundle/ansible deleted file mode 160000 index dec377d..0000000 --- a/bundle/ansible +++ /dev/null @@ -1 +0,0 @@ -Subproject commit dec377ddffd6616aa156029a5f065496582f697b diff --git a/bundle/bufexplorer b/bundle/bufexplorer deleted file mode 160000 index 8c75e65..0000000 --- a/bundle/bufexplorer +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 8c75e65b647238febd0257658b150f717a136359 diff --git a/bundle/buffergator b/bundle/buffergator deleted file mode 160000 index e3d24db..0000000 --- a/bundle/buffergator +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e3d24db7313c1375d3694e48b62c53ed125f6fbf diff --git a/bundle/bufonly b/bundle/bufonly deleted file mode 160000 index 43dd923..0000000 --- a/bundle/bufonly +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 43dd92303979bdb234a3cb2f5662847f7a3affe7 diff --git a/bundle/ctrlp b/bundle/ctrlp deleted file mode 160000 index 6ddbfe2..0000000 --- a/bundle/ctrlp +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 6ddbfe2cc00a7eeb2a4450552b78276488a2e2c9 diff --git a/bundle/easyalign b/bundle/easyalign deleted file mode 160000 index cbb005e..0000000 --- a/bundle/easyalign +++ /dev/null @@ -1 +0,0 @@ -Subproject commit cbb005ee71508b463f7a7a620fcd843eb88fe4fb diff --git a/bundle/easymotion b/bundle/easymotion deleted file mode 160000 index 667a668..0000000 --- a/bundle/easymotion +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 667a668e114e9ec0e5d4cbcb0962d835b23614c4 diff --git a/bundle/exchange b/bundle/exchange deleted file mode 160000 index f841536..0000000 --- a/bundle/exchange +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f841536eace341ef229f48eb6f9cef3d0cd98be4 diff --git a/bundle/fugitive b/bundle/fugitive deleted file mode 160000 index 0abe1fb..0000000 --- a/bundle/fugitive +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0abe1fb12232abe5b7bdfa4d244f04faf3450ba3 diff --git a/bundle/genutils b/bundle/genutils deleted file mode 160000 index e30cc0c..0000000 --- a/bundle/genutils +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e30cc0c3cd333bea3df352041cf51943c548d2e5 diff --git a/bundle/grep b/bundle/grep deleted file mode 160000 index 1e5658c..0000000 --- a/bundle/grep +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1e5658c6d9575cd34be32d0227e06f07c9d58a2e diff --git a/bundle/gundo b/bundle/gundo deleted file mode 160000 index 4c376a8..0000000 --- a/bundle/gundo +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4c376a8061fa335228da420937ce385b847dd56a diff --git a/bundle/indent-guides b/bundle/indent-guides deleted file mode 160000 index 5bc809d..0000000 --- a/bundle/indent-guides +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5bc809d0558d7086075ef8ff1d05dec0f403b2c1 diff --git a/bundle/jade b/bundle/jade deleted file mode 160000 index 6a1f809..0000000 --- a/bundle/jade +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 6a1f80934605cd200bb646c4997b1b0e5d3bcf28 diff --git a/bundle/jinja2 b/bundle/jinja2 deleted file mode 160000 index ce9edd3..0000000 --- a/bundle/jinja2 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ce9edd3e4e6d97d5b4132470f2b5a1cd8cdf0f01 diff --git a/bundle/json b/bundle/json deleted file mode 160000 index f5e3181..0000000 --- a/bundle/json +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f5e3181d0b33a9c51377bb7ea8492feddca8b503 diff --git a/bundle/lusty b/bundle/lusty deleted file mode 160000 index a9b501e..0000000 --- a/bundle/lusty +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a9b501e76c458c0cc91cf59f6e2fab0e1abc06a3 diff --git a/bundle/mako b/bundle/mako deleted file mode 160000 index 603bf2d..0000000 --- a/bundle/mako +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 603bf2dd47a9a53a218660308d7df16598c667f4 diff --git a/bundle/minibufexpl b/bundle/minibufexpl deleted file mode 160000 index d92c8b0..0000000 --- a/bundle/minibufexpl +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d92c8b01248d612444829001b3e081629d37a1aa diff --git a/bundle/mips b/bundle/mips deleted file mode 160000 index 7e24f6b..0000000 --- a/bundle/mips +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 7e24f6b7ce82f3ad1f4429de9077c0b0aa34a893 diff --git a/bundle/nerdcommenter b/bundle/nerdcommenter deleted file mode 160000 index 0b3d928..0000000 --- a/bundle/nerdcommenter +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0b3d928dce8262dedfc2f83b9aeb59a94e4f0ae4 diff --git a/bundle/nerdtree b/bundle/nerdtree deleted file mode 160000 index a1433c4..0000000 --- a/bundle/nerdtree +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a1433c485eb254838c1db52e087d5ec4d1e77cfd diff --git a/bundle/nginx-vim-syntax/README.md b/bundle/nginx-vim-syntax/README.md deleted file mode 100644 index 2893faf..0000000 --- a/bundle/nginx-vim-syntax/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# nginx syntax files for Vim. - -*NOTE*: As of Dec. 2013, these scripts are maintained in the "contrib" directory of the Nginx source: - -* http://hg.nginx.org/nginx/rev/f38043bd15f5 - -You can see the original vim.org version here: - -* http://www.vim.org/scripts/script.php?script_id=1886 - diff --git a/bundle/nginx-vim-syntax/ftdetect/nginx.vim b/bundle/nginx-vim-syntax/ftdetect/nginx.vim deleted file mode 100644 index 3ae470d..0000000 --- a/bundle/nginx-vim-syntax/ftdetect/nginx.vim +++ /dev/null @@ -1,4 +0,0 @@ -au BufRead,BufNewFile *.nginx set ft=nginx -au BufRead,BufNewFile */etc/nginx/* set ft=nginx -au BufRead,BufNewFile */usr/local/nginx/conf/* set ft=nginx -au BufRead,BufNewFile nginx.conf set ft=nginx diff --git a/bundle/nginx-vim-syntax/indent/nginx.vim b/bundle/nginx-vim-syntax/indent/nginx.vim deleted file mode 100644 index 8601366..0000000 --- a/bundle/nginx-vim-syntax/indent/nginx.vim +++ /dev/null @@ -1,11 +0,0 @@ -if exists("b:did_indent") - finish -endif -let b:did_indent = 1 - -setlocal indentexpr= - -" cindent actually works for nginx' simple file structure -setlocal cindent -" Just make sure that the comments are not reset as defs would be. -setlocal cinkeys-=0# diff --git a/bundle/nginx-vim-syntax/syntax/nginx.vim b/bundle/nginx-vim-syntax/syntax/nginx.vim deleted file mode 100644 index 50d809b..0000000 --- a/bundle/nginx-vim-syntax/syntax/nginx.vim +++ /dev/null @@ -1,703 +0,0 @@ -" Vim syntax file -" Language: nginx.conf - -if exists("b:current_syntax") - finish -end - -setlocal iskeyword+=. -setlocal iskeyword+=/ -setlocal iskeyword+=: - -syn match ngxVariable '\$\(\w\+\|{\w\+}\)' -syn match ngxVariableBlock '\$\(\w\+\|{\w\+}\)' contained -syn match ngxVariableString '\$\(\w\+\|{\w\+}\)' contained -syn region ngxBlock start=+^+ end=+{+ skip=+\${+ contains=ngxComment,ngxDirectiveBlock,ngxVariableBlock,ngxString oneline -syn region ngxString start=+\z(["']\)+ end=+\z1+ skip=+\\\\\|\\\z1+ contains=ngxVariableString -syn match ngxComment ' *#.*$' - -syn keyword ngxBoolean on -syn keyword ngxBoolean off - -syn keyword ngxDirectiveBlock http contained -syn keyword ngxDirectiveBlock mail contained -syn keyword ngxDirectiveBlock events contained -syn keyword ngxDirectiveBlock server contained -syn keyword ngxDirectiveBlock types contained -syn keyword ngxDirectiveBlock location contained -syn keyword ngxDirectiveBlock upstream contained -syn keyword ngxDirectiveBlock charset_map contained -syn keyword ngxDirectiveBlock limit_except contained -syn keyword ngxDirectiveBlock if contained -syn keyword ngxDirectiveBlock geo contained -syn keyword ngxDirectiveBlock map contained - -syn keyword ngxDirectiveImportant include -syn keyword ngxDirectiveImportant root -syn keyword ngxDirectiveImportant server -syn keyword ngxDirectiveImportant server_name -syn keyword ngxDirectiveImportant listen -syn keyword ngxDirectiveImportant internal -syn keyword ngxDirectiveImportant proxy_pass -syn keyword ngxDirectiveImportant memcached_pass -syn keyword ngxDirectiveImportant fastcgi_pass -syn keyword ngxDirectiveImportant try_files - -syn keyword ngxDirectiveControl break -syn keyword ngxDirectiveControl return -syn keyword ngxDirectiveControl rewrite -syn keyword ngxDirectiveControl set - -syn keyword ngxDirectiveError error_page -syn keyword ngxDirectiveError post_action - -syn keyword ngxDirectiveDeprecated connections -syn keyword ngxDirectiveDeprecated imap -syn keyword ngxDirectiveDeprecated open_file_cache_retest -syn keyword ngxDirectiveDeprecated optimize_server_names -syn keyword ngxDirectiveDeprecated satisfy_any - -syn keyword ngxDirective accept_mutex -syn keyword ngxDirective accept_mutex_delay -syn keyword ngxDirective access_log -syn keyword ngxDirective add_after_body -syn keyword ngxDirective add_before_body -syn keyword ngxDirective add_header -syn keyword ngxDirective addition_types -syn keyword ngxDirective aio -syn keyword ngxDirective alias -syn keyword ngxDirective allow -syn keyword ngxDirective ancient_browser -syn keyword ngxDirective ancient_browser_value -syn keyword ngxDirective auth_basic -syn keyword ngxDirective auth_basic_user_file -syn keyword ngxDirective auth_http -syn keyword ngxDirective auth_http_header -syn keyword ngxDirective auth_http_timeout -syn keyword ngxDirective autoindex -syn keyword ngxDirective autoindex_exact_size -syn keyword ngxDirective autoindex_localtime -syn keyword ngxDirective charset -syn keyword ngxDirective charset_types -syn keyword ngxDirective client_body_buffer_size -syn keyword ngxDirective client_body_in_file_only -syn keyword ngxDirective client_body_in_single_buffer -syn keyword ngxDirective client_body_temp_path -syn keyword ngxDirective client_body_timeout -syn keyword ngxDirective client_header_buffer_size -syn keyword ngxDirective client_header_timeout -syn keyword ngxDirective client_max_body_size -syn keyword ngxDirective connection_pool_size -syn keyword ngxDirective create_full_put_path -syn keyword ngxDirective daemon -syn keyword ngxDirective dav_access -syn keyword ngxDirective dav_methods -syn keyword ngxDirective debug_connection -syn keyword ngxDirective debug_points -syn keyword ngxDirective default_type -syn keyword ngxDirective degradation -syn keyword ngxDirective degrade -syn keyword ngxDirective deny -syn keyword ngxDirective devpoll_changes -syn keyword ngxDirective devpoll_events -syn keyword ngxDirective directio -syn keyword ngxDirective directio_alignment -syn keyword ngxDirective empty_gif -syn keyword ngxDirective env -syn keyword ngxDirective epoll_events -syn keyword ngxDirective error_log -syn keyword ngxDirective eventport_events -syn keyword ngxDirective expires -syn keyword ngxDirective fastcgi_bind -syn keyword ngxDirective fastcgi_buffer_size -syn keyword ngxDirective fastcgi_buffers -syn keyword ngxDirective fastcgi_busy_buffers_size -syn keyword ngxDirective fastcgi_cache -syn keyword ngxDirective fastcgi_cache_key -syn keyword ngxDirective fastcgi_cache_methods -syn keyword ngxDirective fastcgi_cache_min_uses -syn keyword ngxDirective fastcgi_cache_path -syn keyword ngxDirective fastcgi_cache_use_stale -syn keyword ngxDirective fastcgi_cache_valid -syn keyword ngxDirective fastcgi_catch_stderr -syn keyword ngxDirective fastcgi_connect_timeout -syn keyword ngxDirective fastcgi_hide_header -syn keyword ngxDirective fastcgi_ignore_client_abort -syn keyword ngxDirective fastcgi_ignore_headers -syn keyword ngxDirective fastcgi_index -syn keyword ngxDirective fastcgi_intercept_errors -syn keyword ngxDirective fastcgi_max_temp_file_size -syn keyword ngxDirective fastcgi_next_upstream -syn keyword ngxDirective fastcgi_param -syn keyword ngxDirective fastcgi_pass_header -syn keyword ngxDirective fastcgi_pass_request_body -syn keyword ngxDirective fastcgi_pass_request_headers -syn keyword ngxDirective fastcgi_read_timeout -syn keyword ngxDirective fastcgi_send_lowat -syn keyword ngxDirective fastcgi_send_timeout -syn keyword ngxDirective fastcgi_split_path_info -syn keyword ngxDirective fastcgi_store -syn keyword ngxDirective fastcgi_store_access -syn keyword ngxDirective fastcgi_temp_file_write_size -syn keyword ngxDirective fastcgi_temp_path -syn keyword ngxDirective fastcgi_upstream_fail_timeout -syn keyword ngxDirective fastcgi_upstream_max_fails -syn keyword ngxDirective flv -syn keyword ngxDirective geoip_city -syn keyword ngxDirective geoip_country -syn keyword ngxDirective google_perftools_profiles -syn keyword ngxDirective gzip -syn keyword ngxDirective gzip_buffers -syn keyword ngxDirective gzip_comp_level -syn keyword ngxDirective gzip_disable -syn keyword ngxDirective gzip_hash -syn keyword ngxDirective gzip_http_version -syn keyword ngxDirective gzip_min_length -syn keyword ngxDirective gzip_no_buffer -syn keyword ngxDirective gzip_proxied -syn keyword ngxDirective gzip_static -syn keyword ngxDirective gzip_types -syn keyword ngxDirective gzip_vary -syn keyword ngxDirective gzip_window -syn keyword ngxDirective if_modified_since -syn keyword ngxDirective ignore_invalid_headers -syn keyword ngxDirective image_filter -syn keyword ngxDirective image_filter_buffer -syn keyword ngxDirective image_filter_jpeg_quality -syn keyword ngxDirective image_filter_transparency -syn keyword ngxDirective imap_auth -syn keyword ngxDirective imap_capabilities -syn keyword ngxDirective imap_client_buffer -syn keyword ngxDirective index -syn keyword ngxDirective ip_hash -syn keyword ngxDirective keepalive_requests -syn keyword ngxDirective keepalive_timeout -syn keyword ngxDirective kqueue_changes -syn keyword ngxDirective kqueue_events -syn keyword ngxDirective large_client_header_buffers -syn keyword ngxDirective limit_conn -syn keyword ngxDirective limit_conn_log_level -syn keyword ngxDirective limit_rate -syn keyword ngxDirective limit_rate_after -syn keyword ngxDirective limit_req -syn keyword ngxDirective limit_req_log_level -syn keyword ngxDirective limit_req_zone -syn keyword ngxDirective limit_zone -syn keyword ngxDirective lingering_time -syn keyword ngxDirective lingering_timeout -syn keyword ngxDirective lock_file -syn keyword ngxDirective log_format -syn keyword ngxDirective log_not_found -syn keyword ngxDirective log_subrequest -syn keyword ngxDirective map_hash_bucket_size -syn keyword ngxDirective map_hash_max_size -syn keyword ngxDirective master_process -syn keyword ngxDirective memcached_bind -syn keyword ngxDirective memcached_buffer_size -syn keyword ngxDirective memcached_connect_timeout -syn keyword ngxDirective memcached_next_upstream -syn keyword ngxDirective memcached_read_timeout -syn keyword ngxDirective memcached_send_timeout -syn keyword ngxDirective memcached_upstream_fail_timeout -syn keyword ngxDirective memcached_upstream_max_fails -syn keyword ngxDirective merge_slashes -syn keyword ngxDirective min_delete_depth -syn keyword ngxDirective modern_browser -syn keyword ngxDirective modern_browser_value -syn keyword ngxDirective msie_padding -syn keyword ngxDirective msie_refresh -syn keyword ngxDirective multi_accept -syn keyword ngxDirective open_file_cache -syn keyword ngxDirective open_file_cache_errors -syn keyword ngxDirective open_file_cache_events -syn keyword ngxDirective open_file_cache_min_uses -syn keyword ngxDirective open_file_cache_valid -syn keyword ngxDirective open_log_file_cache -syn keyword ngxDirective output_buffers -syn keyword ngxDirective override_charset -syn keyword ngxDirective perl -syn keyword ngxDirective perl_modules -syn keyword ngxDirective perl_require -syn keyword ngxDirective perl_set -syn keyword ngxDirective pid -syn keyword ngxDirective pop3_auth -syn keyword ngxDirective pop3_capabilities -syn keyword ngxDirective port_in_redirect -syn keyword ngxDirective postpone_gzipping -syn keyword ngxDirective postpone_output -syn keyword ngxDirective protocol -syn keyword ngxDirective proxy -syn keyword ngxDirective proxy_bind -syn keyword ngxDirective proxy_buffer -syn keyword ngxDirective proxy_buffer_size -syn keyword ngxDirective proxy_buffering -syn keyword ngxDirective proxy_buffers -syn keyword ngxDirective proxy_busy_buffers_size -syn keyword ngxDirective proxy_cache -syn keyword ngxDirective proxy_cache_key -syn keyword ngxDirective proxy_cache_methods -syn keyword ngxDirective proxy_cache_min_uses -syn keyword ngxDirective proxy_cache_path -syn keyword ngxDirective proxy_cache_use_stale -syn keyword ngxDirective proxy_cache_valid -syn keyword ngxDirective proxy_connect_timeout -syn keyword ngxDirective proxy_headers_hash_bucket_size -syn keyword ngxDirective proxy_headers_hash_max_size -syn keyword ngxDirective proxy_hide_header -syn keyword ngxDirective proxy_ignore_client_abort -syn keyword ngxDirective proxy_ignore_headers -syn keyword ngxDirective proxy_intercept_errors -syn keyword ngxDirective proxy_max_temp_file_size -syn keyword ngxDirective proxy_method -syn keyword ngxDirective proxy_next_upstream -syn keyword ngxDirective proxy_pass_error_message -syn keyword ngxDirective proxy_pass_header -syn keyword ngxDirective proxy_pass_request_body -syn keyword ngxDirective proxy_pass_request_headers -syn keyword ngxDirective proxy_read_timeout -syn keyword ngxDirective proxy_redirect -syn keyword ngxDirective proxy_send_lowat -syn keyword ngxDirective proxy_send_timeout -syn keyword ngxDirective proxy_set_body -syn keyword ngxDirective proxy_set_header -syn keyword ngxDirective proxy_ssl_session_reuse -syn keyword ngxDirective proxy_store -syn keyword ngxDirective proxy_store_access -syn keyword ngxDirective proxy_temp_file_write_size -syn keyword ngxDirective proxy_temp_path -syn keyword ngxDirective proxy_timeout -syn keyword ngxDirective proxy_upstream_fail_timeout -syn keyword ngxDirective proxy_upstream_max_fails -syn keyword ngxDirective random_index -syn keyword ngxDirective read_ahead -syn keyword ngxDirective real_ip_header -syn keyword ngxDirective recursive_error_pages -syn keyword ngxDirective request_pool_size -syn keyword ngxDirective reset_timedout_connection -syn keyword ngxDirective resolver -syn keyword ngxDirective resolver_timeout -syn keyword ngxDirective rewrite_log -syn keyword ngxDirective rtsig_overflow_events -syn keyword ngxDirective rtsig_overflow_test -syn keyword ngxDirective rtsig_overflow_threshold -syn keyword ngxDirective rtsig_signo -syn keyword ngxDirective satisfy -syn keyword ngxDirective secure_link_secret -syn keyword ngxDirective send_lowat -syn keyword ngxDirective send_timeout -syn keyword ngxDirective sendfile -syn keyword ngxDirective sendfile_max_chunk -syn keyword ngxDirective server_name_in_redirect -syn keyword ngxDirective server_names_hash_bucket_size -syn keyword ngxDirective server_names_hash_max_size -syn keyword ngxDirective server_tokens -syn keyword ngxDirective set_real_ip_from -syn keyword ngxDirective smtp_auth -syn keyword ngxDirective smtp_capabilities -syn keyword ngxDirective smtp_client_buffer -syn keyword ngxDirective smtp_greeting_delay -syn keyword ngxDirective so_keepalive -syn keyword ngxDirective source_charset -syn keyword ngxDirective ssi -syn keyword ngxDirective ssi_ignore_recycled_buffers -syn keyword ngxDirective ssi_min_file_chunk -syn keyword ngxDirective ssi_silent_errors -syn keyword ngxDirective ssi_types -syn keyword ngxDirective ssi_value_length -syn keyword ngxDirective ssl -syn keyword ngxDirective ssl_certificate -syn keyword ngxDirective ssl_certificate_key -syn keyword ngxDirective ssl_ciphers -syn keyword ngxDirective ssl_client_certificate -syn keyword ngxDirective ssl_crl -syn keyword ngxDirective ssl_dhparam -syn keyword ngxDirective ssl_engine -syn keyword ngxDirective ssl_prefer_server_ciphers -syn keyword ngxDirective ssl_protocols -syn keyword ngxDirective ssl_session_cache -syn keyword ngxDirective ssl_session_timeout -syn keyword ngxDirective ssl_verify_client -syn keyword ngxDirective ssl_verify_depth -syn keyword ngxDirective starttls -syn keyword ngxDirective stub_status -syn keyword ngxDirective sub_filter -syn keyword ngxDirective sub_filter_once -syn keyword ngxDirective sub_filter_types -syn keyword ngxDirective tcp_nodelay -syn keyword ngxDirective tcp_nopush -syn keyword ngxDirective thread_stack_size -syn keyword ngxDirective timeout -syn keyword ngxDirective timer_resolution -syn keyword ngxDirective types_hash_bucket_size -syn keyword ngxDirective types_hash_max_size -syn keyword ngxDirective underscores_in_headers -syn keyword ngxDirective uninitialized_variable_warn -syn keyword ngxDirective use -syn keyword ngxDirective user -syn keyword ngxDirective userid -syn keyword ngxDirective userid_domain -syn keyword ngxDirective userid_expires -syn keyword ngxDirective userid_mark -syn keyword ngxDirective userid_name -syn keyword ngxDirective userid_p3p -syn keyword ngxDirective userid_path -syn keyword ngxDirective userid_service -syn keyword ngxDirective valid_referers -syn keyword ngxDirective variables_hash_bucket_size -syn keyword ngxDirective variables_hash_max_size -syn keyword ngxDirective worker_connections -syn keyword ngxDirective worker_cpu_affinity -syn keyword ngxDirective worker_priority -syn keyword ngxDirective worker_processes -syn keyword ngxDirective worker_rlimit_core -syn keyword ngxDirective worker_rlimit_nofile -syn keyword ngxDirective worker_rlimit_sigpending -syn keyword ngxDirective worker_threads -syn keyword ngxDirective working_directory -syn keyword ngxDirective xclient -syn keyword ngxDirective xml_entities -syn keyword ngxDirective xslt_stylesheet -syn keyword ngxDirective xslt_types - -" 3rd party module list: -" http://wiki.nginx.org/Nginx3rdPartyModules - -" Accept Language Module -" Parses the Accept-Language header and gives the most suitable locale from a list of supported locales. -syn keyword ngxDirectiveThirdParty set_from_accept_language - -" Access Key Module -" Denies access unless the request URL contains an access key. -syn keyword ngxDirectiveThirdParty accesskey -syn keyword ngxDirectiveThirdParty accesskey_arg -syn keyword ngxDirectiveThirdParty accesskey_hashmethod -syn keyword ngxDirectiveThirdParty accesskey_signature - -" Auth PAM Module -" HTTP Basic Authentication using PAM. -syn keyword ngxDirectiveThirdParty auth_pam -syn keyword ngxDirectiveThirdParty auth_pam_service_name - -" Cache Purge Module -" Module adding ability to purge content from FastCGI and proxy caches. -syn keyword ngxDirectiveThirdParty fastcgi_cache_purge -syn keyword ngxDirectiveThirdParty proxy_cache_purge - -" Chunkin Module -" HTTP 1.1 chunked-encoding request body support for Nginx. -syn keyword ngxDirectiveThirdParty chunkin -syn keyword ngxDirectiveThirdParty chunkin_keepalive -syn keyword ngxDirectiveThirdParty chunkin_max_chunks_per_buf -syn keyword ngxDirectiveThirdParty chunkin_resume - -" Circle GIF Module -" Generates simple circle images with the colors and size specified in the URL. -syn keyword ngxDirectiveThirdParty circle_gif -syn keyword ngxDirectiveThirdParty circle_gif_max_radius -syn keyword ngxDirectiveThirdParty circle_gif_min_radius -syn keyword ngxDirectiveThirdParty circle_gif_step_radius - -" Drizzle Module -" Make nginx talk directly to mysql, drizzle, and sqlite3 by libdrizzle. -syn keyword ngxDirectiveThirdParty drizzle_connect_timeout -syn keyword ngxDirectiveThirdParty drizzle_dbname -syn keyword ngxDirectiveThirdParty drizzle_keepalive -syn keyword ngxDirectiveThirdParty drizzle_module_header -syn keyword ngxDirectiveThirdParty drizzle_pass -syn keyword ngxDirectiveThirdParty drizzle_query -syn keyword ngxDirectiveThirdParty drizzle_recv_cols_timeout -syn keyword ngxDirectiveThirdParty drizzle_recv_rows_timeout -syn keyword ngxDirectiveThirdParty drizzle_send_query_timeout -syn keyword ngxDirectiveThirdParty drizzle_server - -" Echo Module -" Brings 'echo', 'sleep', 'time', 'exec' and more shell-style goodies to Nginx config file. -syn keyword ngxDirectiveThirdParty echo -syn keyword ngxDirectiveThirdParty echo_after_body -syn keyword ngxDirectiveThirdParty echo_before_body -syn keyword ngxDirectiveThirdParty echo_blocking_sleep -syn keyword ngxDirectiveThirdParty echo_duplicate -syn keyword ngxDirectiveThirdParty echo_end -syn keyword ngxDirectiveThirdParty echo_exec -syn keyword ngxDirectiveThirdParty echo_flush -syn keyword ngxDirectiveThirdParty echo_foreach_split -syn keyword ngxDirectiveThirdParty echo_location -syn keyword ngxDirectiveThirdParty echo_location_async -syn keyword ngxDirectiveThirdParty echo_read_request_body -syn keyword ngxDirectiveThirdParty echo_request_body -syn keyword ngxDirectiveThirdParty echo_reset_timer -syn keyword ngxDirectiveThirdParty echo_sleep -syn keyword ngxDirectiveThirdParty echo_subrequest -syn keyword ngxDirectiveThirdParty echo_subrequest_async - -" Events Module -" Privides options for start/stop events. -syn keyword ngxDirectiveThirdParty on_start -syn keyword ngxDirectiveThirdParty on_stop - -" EY Balancer Module -" Adds a request queue to Nginx that allows the limiting of concurrent requests passed to the upstream. -syn keyword ngxDirectiveThirdParty max_connections -syn keyword ngxDirectiveThirdParty max_connections_max_queue_length -syn keyword ngxDirectiveThirdParty max_connections_queue_timeout - -" Fancy Indexes Module -" Like the built-in autoindex module, but fancier. -syn keyword ngxDirectiveThirdParty fancyindex -syn keyword ngxDirectiveThirdParty fancyindex_exact_size -syn keyword ngxDirectiveThirdParty fancyindex_footer -syn keyword ngxDirectiveThirdParty fancyindex_header -syn keyword ngxDirectiveThirdParty fancyindex_localtime -syn keyword ngxDirectiveThirdParty fancyindex_readme -syn keyword ngxDirectiveThirdParty fancyindex_readme_mode - -" GeoIP Module (DEPRECATED) -" Country code lookups via the MaxMind GeoIP API. -syn keyword ngxDirectiveThirdParty geoip_country_file - -" Headers More Module -" Set and clear input and output headers...more than "add"! -syn keyword ngxDirectiveThirdParty more_clear_headers -syn keyword ngxDirectiveThirdParty more_clear_input_headers -syn keyword ngxDirectiveThirdParty more_set_headers -syn keyword ngxDirectiveThirdParty more_set_input_headers - -" HTTP Push Module -" Turn Nginx into an adept long-polling HTTP Push (Comet) server. -syn keyword ngxDirectiveThirdParty push_buffer_size -syn keyword ngxDirectiveThirdParty push_listener -syn keyword ngxDirectiveThirdParty push_message_timeout -syn keyword ngxDirectiveThirdParty push_queue_messages -syn keyword ngxDirectiveThirdParty push_sender - -" HTTP Redis Module > -" Redis support.> -syn keyword ngxDirectiveThirdParty redis_bind -syn keyword ngxDirectiveThirdParty redis_buffer_size -syn keyword ngxDirectiveThirdParty redis_connect_timeout -syn keyword ngxDirectiveThirdParty redis_next_upstream -syn keyword ngxDirectiveThirdParty redis_pass -syn keyword ngxDirectiveThirdParty redis_read_timeout -syn keyword ngxDirectiveThirdParty redis_send_timeout - -" HTTP JavaScript Module -" Embedding SpiderMonkey. Nearly full port on Perl module. -syn keyword ngxDirectiveThirdParty js -syn keyword ngxDirectiveThirdParty js_filter -syn keyword ngxDirectiveThirdParty js_filter_types -syn keyword ngxDirectiveThirdParty js_load -syn keyword ngxDirectiveThirdParty js_maxmem -syn keyword ngxDirectiveThirdParty js_require -syn keyword ngxDirectiveThirdParty js_set -syn keyword ngxDirectiveThirdParty js_utf8 - -" Log Request Speed -" Log the time it took to process each request. -syn keyword ngxDirectiveThirdParty log_request_speed_filter -syn keyword ngxDirectiveThirdParty log_request_speed_filter_timeout - -" Memc Module -" An extended version of the standard memcached module that supports set, add, delete, and many more memcached commands. -syn keyword ngxDirectiveThirdParty memc_buffer_size -syn keyword ngxDirectiveThirdParty memc_cmds_allowed -syn keyword ngxDirectiveThirdParty memc_connect_timeout -syn keyword ngxDirectiveThirdParty memc_flags_to_last_modified -syn keyword ngxDirectiveThirdParty memc_next_upstream -syn keyword ngxDirectiveThirdParty memc_pass -syn keyword ngxDirectiveThirdParty memc_read_timeout -syn keyword ngxDirectiveThirdParty memc_send_timeout -syn keyword ngxDirectiveThirdParty memc_upstream_fail_timeout -syn keyword ngxDirectiveThirdParty memc_upstream_max_fails - -" Mogilefs Module -" Implements a MogileFS client, provides a replace to the Perlbal reverse proxy of the original MogileFS. -syn keyword ngxDirectiveThirdParty mogilefs_connect_timeout -syn keyword ngxDirectiveThirdParty mogilefs_domain -syn keyword ngxDirectiveThirdParty mogilefs_methods -syn keyword ngxDirectiveThirdParty mogilefs_noverify -syn keyword ngxDirectiveThirdParty mogilefs_pass -syn keyword ngxDirectiveThirdParty mogilefs_read_timeout -syn keyword ngxDirectiveThirdParty mogilefs_send_timeout -syn keyword ngxDirectiveThirdParty mogilefs_tracker - -" MP4 Streaming Lite Module -" Will seek to a certain time within H.264/MP4 files when provided with a 'start' parameter in the URL. -syn keyword ngxDirectiveThirdParty mp4 - -" Nginx Notice Module -" Serve static file to POST requests. -syn keyword ngxDirectiveThirdParty notice -syn keyword ngxDirectiveThirdParty notice_type - -" Phusion Passenger -" Easy and robust deployment of Ruby on Rails application on Apache and Nginx webservers. -syn keyword ngxDirectiveThirdParty passenger_base_uri -syn keyword ngxDirectiveThirdParty passenger_default_user -syn keyword ngxDirectiveThirdParty passenger_enabled -syn keyword ngxDirectiveThirdParty passenger_log_level -syn keyword ngxDirectiveThirdParty passenger_max_instances_per_app -syn keyword ngxDirectiveThirdParty passenger_max_pool_size -syn keyword ngxDirectiveThirdParty passenger_pool_idle_time -syn keyword ngxDirectiveThirdParty passenger_root -syn keyword ngxDirectiveThirdParty passenger_ruby -syn keyword ngxDirectiveThirdParty passenger_use_global_queue -syn keyword ngxDirectiveThirdParty passenger_user_switching -syn keyword ngxDirectiveThirdParty rack_env -syn keyword ngxDirectiveThirdParty rails_app_spawner_idle_time -syn keyword ngxDirectiveThirdParty rails_env -syn keyword ngxDirectiveThirdParty rails_framework_spawner_idle_time -syn keyword ngxDirectiveThirdParty rails_spawn_method - -" RDS JSON Module -" Help ngx_drizzle and other DBD modules emit JSON data. -syn keyword ngxDirectiveThirdParty rds_json -syn keyword ngxDirectiveThirdParty rds_json_content_type -syn keyword ngxDirectiveThirdParty rds_json_format -syn keyword ngxDirectiveThirdParty rds_json_ret - -" RRD Graph Module -" This module provides an HTTP interface to RRDtool's graphing facilities. -syn keyword ngxDirectiveThirdParty rrd_graph -syn keyword ngxDirectiveThirdParty rrd_graph_root - -" Secure Download -" Create expiring links. -syn keyword ngxDirectiveThirdParty secure_download -syn keyword ngxDirectiveThirdParty secure_download_fail_location -syn keyword ngxDirectiveThirdParty secure_download_path_mode -syn keyword ngxDirectiveThirdParty secure_download_secret - -" SlowFS Cache Module -" Module adding ability to cache static files. -syn keyword ngxDirectiveThirdParty slowfs_big_file_size -syn keyword ngxDirectiveThirdParty slowfs_cache -syn keyword ngxDirectiveThirdParty slowfs_cache_key -syn keyword ngxDirectiveThirdParty slowfs_cache_min_uses -syn keyword ngxDirectiveThirdParty slowfs_cache_path -syn keyword ngxDirectiveThirdParty slowfs_cache_purge -syn keyword ngxDirectiveThirdParty slowfs_cache_valid -syn keyword ngxDirectiveThirdParty slowfs_temp_path - -" Strip Module -" Whitespace remover. -syn keyword ngxDirectiveThirdParty strip - -" Substitutions Module -" A filter module which can do both regular expression and fixed string substitutions on response bodies. -syn keyword ngxDirectiveThirdParty subs_filter -syn keyword ngxDirectiveThirdParty subs_filter_types - -" Supervisord Module -" Module providing nginx with API to communicate with supervisord and manage (start/stop) backends on-demand. -syn keyword ngxDirectiveThirdParty supervisord -syn keyword ngxDirectiveThirdParty supervisord_inherit_backend_status -syn keyword ngxDirectiveThirdParty supervisord_name -syn keyword ngxDirectiveThirdParty supervisord_start -syn keyword ngxDirectiveThirdParty supervisord_stop - -" Upload Module -" Parses multipart/form-data allowing arbitrary handling of uploaded files. -syn keyword ngxDirectiveThirdParty upload_aggregate_form_field -syn keyword ngxDirectiveThirdParty upload_buffer_size -syn keyword ngxDirectiveThirdParty upload_cleanup -syn keyword ngxDirectiveThirdParty upload_limit_rate -syn keyword ngxDirectiveThirdParty upload_max_file_size -syn keyword ngxDirectiveThirdParty upload_max_output_body_len -syn keyword ngxDirectiveThirdParty upload_max_part_header_len -syn keyword ngxDirectiveThirdParty upload_pass -syn keyword ngxDirectiveThirdParty upload_pass_args -syn keyword ngxDirectiveThirdParty upload_pass_form_field -syn keyword ngxDirectiveThirdParty upload_set_form_field -syn keyword ngxDirectiveThirdParty upload_store -syn keyword ngxDirectiveThirdParty upload_store_access - -" Upload Progress Module -" Tracks and reports upload progress. -syn keyword ngxDirectiveThirdParty report_uploads -syn keyword ngxDirectiveThirdParty track_uploads -syn keyword ngxDirectiveThirdParty upload_progress -syn keyword ngxDirectiveThirdParty upload_progress_content_type -syn keyword ngxDirectiveThirdParty upload_progress_header -syn keyword ngxDirectiveThirdParty upload_progress_json_output -syn keyword ngxDirectiveThirdParty upload_progress_template - -" Upstream Fair Balancer -" Sends an incoming request to the least-busy backend server, rather than distributing requests round-robin. -syn keyword ngxDirectiveThirdParty fair -syn keyword ngxDirectiveThirdParty upstream_fair_shm_size - -" Upstream Consistent Hash -" Select backend based on Consistent hash ring. -syn keyword ngxDirectiveThirdParty consistent_hash - -" Upstream Hash Module -" Provides simple upstream load distribution by hashing a configurable variable. -syn keyword ngxDirectiveThirdParty hash -syn keyword ngxDirectiveThirdParty hash_again - -" XSS Module -" Native support for cross-site scripting (XSS) in an nginx. -syn keyword ngxDirectiveThirdParty xss_callback_arg -syn keyword ngxDirectiveThirdParty xss_get -syn keyword ngxDirectiveThirdParty xss_input_types -syn keyword ngxDirectiveThirdParty xss_output_type - -" uWSGI Module -" Allows Nginx to interact with uWSGI processes and control what parameters are passed to the process. -syn keyword ngxDirectiveThirdParty uwsgi_bind -syn keyword ngxDirectiveThirdParty uwsgi_buffer_size -syn keyword ngxDirectiveThirdParty uwsgi_buffering -syn keyword ngxDirectiveThirdParty uwsgi_buffers -syn keyword ngxDirectiveThirdParty uwsgi_busy_buffers_size -syn keyword ngxDirectiveThirdParty uwsgi_cache -syn keyword ngxDirectiveThirdParty uwsgi_cache_bypass -syn keyword ngxDirectiveThirdParty uwsgi_cache_key -syn keyword ngxDirectiveThirdParty uwsgi_cache_lock -syn keyword ngxDirectiveThirdParty uwsgi_cache_lock_timeout -syn keyword ngxDirectiveThirdParty uwsgi_cache_methods -syn keyword ngxDirectiveThirdParty uwsgi_cache_min_uses -syn keyword ngxDirectiveThirdParty uwsgi_cache_path -syn keyword ngxDirectiveThirdParty uwsgi_cache_use_stale -syn keyword ngxDirectiveThirdParty uwsgi_cache_valid -syn keyword ngxDirectiveThirdParty uwsgi_connect_timeout -syn keyword ngxDirectiveThirdParty uwsgi_hide_header -syn keyword ngxDirectiveThirdParty uwsgi_ignore_client_abort -syn keyword ngxDirectiveThirdParty uwsgi_ignore_headers -syn keyword ngxDirectiveThirdParty uwsgi_intercept_errors -syn keyword ngxDirectiveThirdParty uwsgi_max_temp_file_size -syn keyword ngxDirectiveThirdParty uwsgi_modifier1 -syn keyword ngxDirectiveThirdParty uwsgi_modifier2 -syn keyword ngxDirectiveThirdParty uwsgi_next_upstream -syn keyword ngxDirectiveThirdParty uwsgi_no_cache -syn keyword ngxDirectiveThirdParty uwsgi_param -syn keyword ngxDirectiveThirdParty uwsgi_pass -syn keyword ngxDirectiveThirdParty uwsgi_pass_header -syn keyword ngxDirectiveThirdParty uwsgi_pass_request_body -syn keyword ngxDirectiveThirdParty uwsgi_pass_request_headers -syn keyword ngxDirectiveThirdParty uwsgi_read_timeout -syn keyword ngxDirectiveThirdParty uwsgi_send_timeout -syn keyword ngxDirectiveThirdParty uwsgi_store -syn keyword ngxDirectiveThirdParty uwsgi_store_access -syn keyword ngxDirectiveThirdParty uwsgi_string -syn keyword ngxDirectiveThirdParty uwsgi_temp_file_write_size -syn keyword ngxDirectiveThirdParty uwsgi_temp_path - -" highlight - -hi link ngxComment Comment -hi link ngxVariable Identifier -hi link ngxVariableBlock Identifier -hi link ngxVariableString PreProc -hi link ngxBlock Normal -hi link ngxString String - -hi link ngxBoolean Boolean -hi link ngxDirectiveBlock Statement -hi link ngxDirectiveImportant Type -hi link ngxDirectiveControl Keyword -hi link ngxDirectiveError Constant -hi link ngxDirectiveDeprecated Error -hi link ngxDirective Identifier -hi link ngxDirectiveThirdParty Special - -let b:current_syntax = "nginx" diff --git a/bundle/onedark b/bundle/onedark deleted file mode 160000 index d7b596a..0000000 --- a/bundle/onedark +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d7b596a2528ca109a5917d9babc526b49b74e5ec diff --git a/bundle/pathogen b/bundle/pathogen deleted file mode 160000 index 5e3fdd3..0000000 --- a/bundle/pathogen +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5e3fdd3a8a3b244e1fedd0f5597f4a9879e16c3b diff --git a/bundle/puppet b/bundle/puppet deleted file mode 160000 index 27d2af1..0000000 --- a/bundle/puppet +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 27d2af11223349088f5c7fb3187bb3184364ea12 diff --git a/bundle/pydoc b/bundle/pydoc deleted file mode 160000 index 56c2397..0000000 --- a/bundle/pydoc +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 56c23972ad6de20e558ec7806371042529f0a41e diff --git a/bundle/python b/bundle/python deleted file mode 160000 index 5cf49d6..0000000 --- a/bundle/python +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5cf49d6577822ab5186ad2dc7c99e198b2fddf0a diff --git a/bundle/pythonmode b/bundle/pythonmode deleted file mode 160000 index ae6f8d5..0000000 --- a/bundle/pythonmode +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ae6f8d5f710007d6bdb9b9da7f9e74eaa1da58a5 diff --git a/bundle/snipmate b/bundle/snipmate deleted file mode 160000 index f5a75d0..0000000 --- a/bundle/snipmate +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f5a75d075d3c005ebe69e3f5e56cf99516e8aa3b diff --git a/bundle/speeddating b/bundle/speeddating deleted file mode 160000 index e5995ff..0000000 --- a/bundle/speeddating +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e5995ffe63381151dd2956703df560abefa4f020 diff --git a/bundle/stylus b/bundle/stylus deleted file mode 160000 index 9ab38f0..0000000 --- a/bundle/stylus +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9ab38f066ff2b726eb1680da489b184fd17dee50 diff --git a/bundle/surround b/bundle/surround deleted file mode 160000 index 6f0984a..0000000 --- a/bundle/surround +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 6f0984a5ca1430047fe760fc680c6cf98ae94b01 diff --git a/bundle/syntastic b/bundle/syntastic deleted file mode 160000 index 0bfac45..0000000 --- a/bundle/syntastic +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0bfac45565efa4e94364818b3b0cb2ee46826a0f diff --git a/bundle/tabular b/bundle/tabular deleted file mode 160000 index ad2a5a1..0000000 --- a/bundle/tabular +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ad2a5a1d54443ab27f1282c5617f55b8e0819623 diff --git a/bundle/tagbar b/bundle/tagbar deleted file mode 160000 index 2206079..0000000 --- a/bundle/tagbar +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2206079863dbf85526f0bbd2e510e1285fdf7399 diff --git a/bundle/tmuxconf b/bundle/tmuxconf deleted file mode 160000 index 1a09007..0000000 --- a/bundle/tmuxconf +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1a09007ca47ee04ca014f40f401291be61bf0f66 diff --git a/bundle/unimpaired b/bundle/unimpaired deleted file mode 160000 index fe95324..0000000 --- a/bundle/unimpaired +++ /dev/null @@ -1 +0,0 @@ -Subproject commit fe95324a679685054f2db2cc47fe482e9861ee8f diff --git a/bundle/vim-go b/bundle/vim-go deleted file mode 160000 index 155836d..0000000 --- a/bundle/vim-go +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 155836d47052ea9c9bac81ba3e937f6f22c8e384 diff --git a/bundle/vim-markdown b/bundle/vim-markdown deleted file mode 160000 index 2cd50d2..0000000 --- a/bundle/vim-markdown +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2cd50d2ca657091c6aa787a3847284fb4cceff49 diff --git a/bundle/vim-pants b/bundle/vim-pants deleted file mode 160000 index 6112add..0000000 --- a/bundle/vim-pants +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 6112addaeee02963aa1ed3cf180b5b3fea56c9d3 diff --git a/bundle/vimball b/bundle/vimball deleted file mode 160000 index 4ba9a9e..0000000 --- a/bundle/vimball +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4ba9a9ec152cb63c302cebed526b9bf5acade787 diff --git a/bundle/vimclojure b/bundle/vimclojure deleted file mode 160000 index 2a17c24..0000000 --- a/bundle/vimclojure +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2a17c249571395a7f45523d38cac6a9326ecf8f1 diff --git a/bundle/visualmark b/bundle/visualmark deleted file mode 160000 index 0a2984a..0000000 --- a/bundle/visualmark +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0a2984acc004235cf492c0151a9697b3a467de16 diff --git a/bundle/vst b/bundle/vst deleted file mode 160000 index 5d864b6..0000000 --- a/bundle/vst +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5d864b620e1e1f5c44fd070200ecc8f51ee8cb8f diff --git a/bundle/wmgraphviz b/bundle/wmgraphviz deleted file mode 160000 index c0d1a61..0000000 --- a/bundle/wmgraphviz +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c0d1a61c66a0ba5fdb2633b8fdcfc30c8cb24fbc diff --git a/bundle/wombat256mod b/bundle/wombat256mod deleted file mode 160000 index 4b22adc..0000000 --- a/bundle/wombat256mod +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4b22adcee4cff454cb12189da7565870448aea39 diff --git a/gvimrc b/gvimrc index ef62d8d..fcb02b4 100644 --- a/gvimrc +++ b/gvimrc @@ -1,28 +1,12 @@ -"============================================================================== -"HOW IT LOOKS -"============================================================================== - -"colorscheme wombat -colorscheme onedark - -if &background == "dark" - hi normal guibg=black - set transp=1 +" GUI settings are isolated from terminal Vim and Neovim. +if !has('gui_running') + finish endif - -"Macvim -" +set guioptions-=T if has('gui_macvim') - "set lines=56 columns=240 - "set guifont=Monaco:h12 - "set guifontwide=Monaco:h12 - set guifont=Menlo:h14 - set guifontwide=Menlo:h14 - - "" full screen on statup - "set fu - "set fuopt=maxvert,maxhorz + let &guifont = get(g:, 'dotvim_guifont', 'Menlo:h14') + let &guifontwide = get(g:, 'dotvim_guifontwide', &guifont) + command! FS set guifont=Menlo:h17 +elseif exists('g:dotvim_guifont') + let &guifont = g:dotvim_guifont endif - -" Indent Guides -let g:indent_guides_enable_on_vim_startup = 1 diff --git a/init.vim b/init.vim new file mode 100644 index 0000000..8bf2ac3 --- /dev/null +++ b/init.vim @@ -0,0 +1,3 @@ +" Neovim entry point; resolve the symlink to find the shared checkout. +let s:root = fnamemodify(resolve(expand(':p')), ':h') +execute 'source ' . fnameescape(s:root . '/vimrc') diff --git a/lsp.vim b/lsp.vim new file mode 100644 index 0000000..33b0a35 --- /dev/null +++ b/lsp.vim @@ -0,0 +1,35 @@ +" Servers are optional executables on PATH; nothing is downloaded by the editor. +let s:defaults = [ + \ {'name': 'pylsp', 'cmd': ['pylsp'], 'filetypes': ['python'], 'root_markers': ['pyproject.toml', 'setup.py', '.git']}, + \ {'name': 'gopls', 'cmd': ['gopls'], 'filetypes': ['go', 'gomod'], 'root_markers': ['go.work', 'go.mod', '.git']}, + \ {'name': 'clangd', 'cmd': ['clangd'], 'filetypes': ['c', 'cpp'], 'root_markers': ['compile_commands.json', 'compile_flags.txt', '.git']}, + \ {'name': 'rust_analyzer', 'cmd': ['rust-analyzer'], 'filetypes': ['rust'], 'root_markers': ['Cargo.toml', '.git']}, + \ {'name': 'typescript', 'cmd': ['typescript-language-server', '--stdio'], 'filetypes': ['javascript', 'javascriptreact', 'typescript', 'typescriptreact'], 'root_markers': ['tsconfig.json', 'package.json', '.git']} + \ ] +let g:dotvim_lsp_servers = get(g:, 'dotvim_lsp_servers', s:defaults) +if has('nvim') + execute 'luafile ' . fnameescape(g:dotvim_root . '/nvim/lsp.lua') +else + let g:lsp_options = {'autoComplete': 1, 'showDiagWithVirtualText': 0} + let g:lsp_servers = [] + for s:server in g:dotvim_lsp_servers + if executable(s:server.cmd[0]) + call add(g:lsp_servers, { + \ 'name': s:server.name, + \ 'filetype': s:server.filetypes, + \ 'path': exepath(s:server.cmd[0]), + \ 'args': s:server.cmd[1:], + \ 'rootSearch': s:server.root_markers + (index(s:server.root_markers, '.git') >= 0 ? ['.git/'] : []) + \ }) + endif + endfor + let g:dotvim_lsp_status = 'Vim LSP: ' . len(g:lsp_servers) . ' available server(s)' + augroup dotvim_lsp + autocmd! + for s:server in g:lsp_servers + execute 'autocmd FileType ' . join(s:server.filetype, ',') . ' nnoremap gd :LspGotoDefinition' + execute 'autocmd FileType ' . join(s:server.filetype, ',') . ' nnoremap gh :LspHover' + execute 'autocmd FileType ' . join(s:server.filetype, ',') . ' nnoremap gr :LspShowReferences' + endfor + augroup END +endif diff --git a/nvim/lsp.lua b/nvim/lsp.lua new file mode 100644 index 0000000..9858313 --- /dev/null +++ b/nvim/lsp.lua @@ -0,0 +1,29 @@ +-- Use Neovim's built-in LSP; no Lua plugin manager or completion framework. +local group = vim.api.nvim_create_augroup('dotvim_lsp', { clear = true }) +vim.api.nvim_create_autocmd('LspAttach', { + group = group, + callback = function(event) + local options = { buffer = event.buf, silent = true } + vim.keymap.set('n', 'gd', vim.lsp.buf.definition, options) + vim.keymap.set('n', 'gh', vim.lsp.buf.hover, options) + vim.keymap.set('n', 'gr', vim.lsp.buf.references, options) + local client = vim.lsp.get_client_by_id(event.data.client_id) + if client and client:supports_method('textDocument/completion') then + vim.lsp.completion.enable(true, client.id, event.buf, { autotrigger = true }) + end + end, +}) + +local available = 0 +for _, server in ipairs(vim.g.dotvim_lsp_servers) do + if vim.fn.executable(server.cmd[1]) == 1 then + vim.lsp.config('dotvim_' .. server.name, { + cmd = server.cmd, + filetypes = server.filetypes, + root_markers = server.root_markers, + }) + vim.lsp.enable('dotvim_' .. server.name) + available = available + 1 + end +end +vim.g.dotvim_lsp_status = 'Neovim built-in LSP: ' .. available .. ' available server(s)' diff --git a/plugins.vim b/plugins.vim new file mode 100644 index 0000000..77965db --- /dev/null +++ b/plugins.vim @@ -0,0 +1,109 @@ +" Exact plugin revisions are shared by Vim, Neovim, and the installer. +let g:dotvim_loaded_plugins = [] +let g:dotvim_skipped_plugins = [] +let g:dotvim_package_loader = 'disabled (basic profile or --noplugin)' +let g:dotvim_lsp_status = 'disabled (opt in with g:dotvim_lsp)' +if g:dotvim_profile !=# 'full' || (!&loadplugins && !get(g:, 'dotvim_installing', 0)) + finish +endif +if !filereadable(g:dotvim_root . '/autoload/plug.vim') + call add(g:dotvim_skipped_plugins, 'vim-plug: autoload/plug.vim is missing') + finish +endif + +let s:installing = get(g:, 'dotvim_installing', 0) +let g:dotvim_package_loader = 'vim-plug' +" Git is needed for installation, but existing pure Vimscript plugins work without it. +silent! call plug#begin(g:dotvim_root . '/plugged') + +function! s:Plugin(repo, name, commit, supported, requirement) abort + let options = {'as': a:name, 'commit': a:commit} + if s:installing || !a:supported + " Keep every pin registered for PlugInstall/PlugClean, without loading it. + let options.on = [] + endif + execute 'Plug ' . string(a:repo) . ', ' . string(options) + if s:installing + return 0 + elseif !a:supported + call add(g:dotvim_skipped_plugins, a:name . ': ' . a:requirement) + return 0 + elseif empty(glob(g:plugs[a:name].dir . '/*')) + call add(g:dotvim_skipped_plugins, a:name . ': not installed (run bootstrap.sh --full)') + return 0 + endif + call add(g:dotvim_loaded_plugins, a:name) + return 1 +endfunction + +" repeat v1.2 supports Vim 7; current upstream requires Vim 8. +call s:Plugin('tpope/vim-repeat', 'repeat', '8106e142dfdc278ff3eaaadd7b362ad7949d4357', 1, '') +call s:Plugin('tpope/vim-surround', 'surround', '3d188ed2113431cf8dac77be61b842acb64433d9', 1, '') +call s:Plugin('preservim/nerdcommenter', 'nerdcommenter', 'a462bbda1e26f44fb3d3eb9d9d1c6a07aa98e665', 1, '') +call s:Plugin('preservim/nerdtree', 'nerdtree', '690d061b591525890f1471c6675bcb5bdc8cdff9', 1, '') +call s:Plugin('joshdick/onedark.vim', 'onedark', '47bec7a6196a843dad195d2666c3ac84c6e80c78', 1, '') +if s:Plugin('junegunn/vim-easy-align', 'easyalign', '9815a55dbcd817784458df7a18acacc6f82b1241', 1, '') + xmap (EasyAlign) + nmap a (EasyAlign) +endif +call s:Plugin('tpope/vim-fugitive', 'fugitive', '3b753cf8c6a4dcde6edee8827d464ba9b8c4a6f0', executable('git'), 'Git is required') +let g:NERDTreeWinPos = 'left' +let g:tagbar_width = 30 + +" BSD ctags (including /usr/bin/ctags on macOS) cannot power Tagbar. +function! s:Ctags() abort + if s:installing + return 0 + endif + for candidate in (exists('g:dotvim_ctags') ? [g:dotvim_ctags] : ['ctags', 'ctags-universal', 'uctags']) + if executable(candidate) + let ctags_version = system(shellescape(candidate) . ' --version') + if !v:shell_error && ctags_version =~# 'Universal Ctags' + let g:tagbar_ctags_bin = candidate + return 1 + endif + endif + endfor + return 0 +endfunction +call s:Plugin('preservim/tagbar', 'tagbar', '07cb8247487208124978daff8e13624667635457', s:Ctags(), 'Universal Ctags is required; set g:dotvim_ctags for a custom path') +call s:Plugin('mbbill/undotree', 'undotree', '6fa6b57cda8459e1e4b2ca34df702f55242f4e4d', has('persistent_undo') && executable('diff'), 'persistent undo and diff are required') + +" Check the executable before loading fzf so it never offers a binary download. +let s:fzf = 0 +if !s:installing && (has('nvim') || v:version >= 800) && executable('fzf') + let s:version = matchstr(system('fzf --version'), '\d\+\.\d\+') + if !v:shell_error && !empty(s:version) + let s:parts = split(s:version, '\.') + let s:fzf = str2nr(s:parts[0]) > 0 || str2nr(s:parts[1]) >= 63 + endif +endif +let s:fzf_loaded = s:Plugin('junegunn/fzf', 'fzf', '55c122f1a0e1340546c8709682bea5561fe0e8fd', s:fzf, 'Vim 8+ or Neovim, and fzf 0.63+ are required') +if s:Plugin('junegunn/fzf.vim', 'fzf-vim', '023de3c0e158ff9c2b0992175af10be97c2f2158', s:fzf, 'Vim 8+ or Neovim, and fzf 0.63+ are required') && s:fzf_loaded + nnoremap :Files +endif + +" Personal UltiSnips remain opt-in because they use Python interpolation. +let g:UltiSnipsListSnippets = '' +let g:UltiSnipsJumpForwardTrigger = '' +let g:UltiSnipsJumpBackwardTrigger = '' +let g:UltiSnipsSnippetDirectories = ['UltiSnips', 'snippets'] +let s:snippets = !s:installing && get(g:, 'dotvim_snippets', 0) +call s:Plugin('SirVer/ultisnips', 'ultisnips', '0ca6a21386021e74a91034365809dcca56ed13f0', s:snippets && (has('nvim') || v:version >= 802) && has('python3'), 'opt in with g:dotvim_snippets; Vim 8.2+ with Python 3, or a Neovim Python provider, is required') + +let s:vim_lsp = !s:installing && get(g:, 'dotvim_lsp', 0) && !has('nvim') && has('vim9script') && has('job') && has('channel') +let s:lsp_loaded = s:Plugin('yegappan/lsp', 'lsp', 'c741b2f1afb42b9f267824dac4049674908f4a41', s:vim_lsp, 'opt in with g:dotvim_lsp on Vim 9+ with jobs/channels; Neovim uses its built-in client') +if s:installing + finish +endif +if get(g:, 'dotvim_lsp', 0) + if has('nvim-0.11') || s:lsp_loaded + " Configure Vim LSP globals before plug#end can source plugin scripts. + execute 'source ' . fnameescape(g:dotvim_root . '/lsp.vim') + elseif has('nvim') || !s:vim_lsp + let g:dotvim_lsp_status = 'requires Vim 9+ with jobs/channels or Neovim 0.11+' + else + let g:dotvim_lsp_status = 'Vim LSP plugin is not installed' + endif +endif +call plug#end() diff --git a/scripts/install_plugins.vim b/scripts/install_plugins.vim new file mode 100644 index 0000000..c982990 --- /dev/null +++ b/scripts/install_plugins.vim @@ -0,0 +1,42 @@ +" Install pinned plugins without evaluating the user's configuration or plugin code. +set nocompatible nomore +set shell=/bin/sh +let g:dotvim_root = fnamemodify(resolve(expand(':p')), ':h:h') +let &runtimepath = escape(g:dotvim_root, ',') . ',' . escape($VIMRUNTIME, ',') +let g:dotvim_profile = 'full' +let g:dotvim_installing = 1 + +function! s:Revision(spec) abort + let revision = system('git -C ' . shellescape(a:spec.dir) . ' rev-parse --verify HEAD 2>/dev/null') + return v:shell_error ? '' : matchstr(revision, '^\x\{40}') +endfunction + +try + execute 'source ' . fnameescape(g:dotvim_root . '/plugins.vim') + if !exists(':PlugUpdate') || empty(get(g:, 'plugs', {})) + throw 'vim-plug and Git are required to install plugins' + endif + let s:pending = [] + for s:name in g:plugs_order + if s:Revision(g:plugs[s:name]) !=# g:plugs[s:name].commit + call add(s:pending, s:name) + endif + endfor + if !empty(s:pending) + execute 'PlugUpdate --sync ' . join(s:pending) + endif + for s:name in g:plugs_order + if s:Revision(g:plugs[s:name]) !=# g:plugs[s:name].commit + throw 'Plugin installation failed: ' . s:name . ' (expected ' . g:plugs[s:name].commit . ')' + endif + endfor +catch + call writefile([v:exception, v:throwpoint], '/dev/stderr') + cquit +endtry +if !has('nvim') && v:version < 800 + " Vim 7.4 counts vim-plug's silent! unmaps as Ex errors. Pins are verified; + " leave Ex mode so a successful installation returns zero. + visual +endif +qa! diff --git a/snippets/mkd_mindflow.snippets b/snippets/markdown_mindflow.snippets similarity index 100% rename from snippets/mkd_mindflow.snippets rename to snippets/markdown_mindflow.snippets diff --git a/snippets/mkd.snippets b/snippets/mkd.snippets deleted file mode 120000 index 02e23ff..0000000 --- a/snippets/mkd.snippets +++ /dev/null @@ -1 +0,0 @@ -../bundle/ultisnips/UltiSnips/markdown.snippets \ No newline at end of file diff --git a/tests/lsp_server.py b/tests/lsp_server.py new file mode 100644 index 0000000..3c4a3f9 --- /dev/null +++ b/tests/lsp_server.py @@ -0,0 +1,31 @@ +"""A tiny stdio LSP peer for the editor integration smoke test.""" +import json +import os +from pathlib import Path +import sys + + +while True: + headers = {} + while True: + line = sys.stdin.buffer.readline() + if not line: + sys.exit(0) + if line == b'\r\n': + break + key, value = line.decode().split(':', 1) + headers[key.lower()] = value.strip() + message = json.loads(sys.stdin.buffer.read(int(headers['content-length']))) + method = message.get('method', '') + with Path(os.environ['DOTVIM_LSP_LOG']).open('a') as log: + log.write(method + '\n') + if method == 'exit': + break + if 'id' in message: + result = None + if method == 'initialize': + result = {'capabilities': {'textDocumentSync': 1, 'definitionProvider': True, + 'completionProvider': {'triggerCharacters': ['.']}}} + response = json.dumps({'jsonrpc': '2.0', 'id': message['id'], 'result': result}).encode() + sys.stdout.buffer.write(('Content-Length: ' + str(len(response)) + '\r\n\r\n').encode() + response) + sys.stdout.buffer.flush() diff --git a/tests/test_dotvim.py b/tests/test_dotvim.py new file mode 100644 index 0000000..12d43c5 --- /dev/null +++ b/tests/test_dotvim.py @@ -0,0 +1,502 @@ +"""Compatibility and installer smoke tests using only Python's standard library.""" +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +EDITOR = shutil.which(os.environ.get('DOTVIM_TEST_EDITOR', 'vim')) + + +def vim_string(value): + return "'" + str(value).replace("'", "''") + "'" + + +class Workspace(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix='dotvim-test-') + self.addCleanup(self.temporary.cleanup) + self.scratch = Path(self.temporary.name) + self.environment = dict(os.environ, DOTVIM_HOME=str(self.scratch / 'home'), + XDG_CONFIG_HOME=str(self.scratch / 'config'), + XDG_DATA_HOME=str(self.scratch / 'data'), + XDG_STATE_HOME=str(self.scratch / 'state'), + XDG_CACHE_HOME=str(self.scratch / 'cache'), + NVIM_LOG_FILE=str(self.scratch / 'nvim.log')) + + def copy_configuration(self, destination): + destination.mkdir(parents=True) + for name in ['vimrc', 'gvimrc', 'init.vim', 'plugins.vim', 'lsp.vim', 'bootstrap.sh']: + shutil.copy2(ROOT / name, destination / name) + for name in ['autoload', 'colors', 'snippets', 'nvim', 'scripts']: + shutil.copytree(ROOT / name, destination / name) + return destination + + +@unittest.skipUnless(EDITOR, 'Set DOTVIM_TEST_EDITOR to a Vim or Neovim executable') +class EditorTests(Workspace): + def run_editor(self, body, profile='basic', checkout=ROOT, settings='', environment=None, + native_browser=False): + version = subprocess.check_output([EDITOR, '--version'], text=True) + is_nvim = 'NVIM' in version + # Vim 7.4's bundled netrw uses silent! unmaps which behave differently + # inside try/catch and leave a nonzero batch exit status even on success. + legacy_netrw = native_browser and 'VIM - Vi IMproved 7.4' in version + result = self.scratch / 'result' + script = self.scratch / 'check.vim' + script.write_text(''' +function! Check(condition, message) abort + if !a:condition + throw a:message + endif +endfunction +''' + ('' if legacy_netrw else 'try\n') + ''' + call Check(empty(v:errmsg), 'Startup: ' . v:errmsg) +''' + body + ''' + call Check(empty(v:errmsg), 'Runtime: ' . v:errmsg) + call writefile(['ok'], $DOTVIM_TEST_RESULT) +''' + ('' if legacy_netrw else '''catch + call writefile([v:exception, v:throwpoint, v:errmsg], $DOTVIM_TEST_RESULT) + cquit +endtry +''') + ''' +qa! +''') + initial = ('let g:dotvim_state_dir=' + vim_string(self.scratch / 'editor-state') + + ' | let g:dotvim_local_config=' + vim_string(self.scratch / 'no-local') + + ' | let g:netrw_home=' + vim_string(self.scratch) + + " | let g:dotvim_snippets=0 | let g:dotvim_lsp=0 | let v:errmsg=''" + + (' | ' + settings if settings else '')) + arguments = [EDITOR, '-n', '-i', 'NONE', '-u', str(checkout / ('init.vim' if is_nvim else 'vimrc')), + '--cmd', initial, '-S', str(script)] + arguments[1:1] = ['--headless'] if is_nvim else ['-N', '-U', 'NONE', '-es'] + env = dict(self.environment, DOTVIM_PROFILE=profile, DOTVIM_TEST_RESULT=str(result)) + env.update(environment or {}) + process = subprocess.run(arguments, env=env, capture_output=True, text=True, timeout=30) + details = result.read_text() if result.exists() else 'No result was written.' + self.assertIn(process.returncode, [0, 1] if legacy_netrw else [0], + details + process.stdout + process.stderr) + self.assertEqual(details, 'ok\n', details + process.stdout + process.stderr) + + def test_basic_with_installed_plugins(self): + self.run_editor(''' + call Check(empty(g:dotvim_loaded_plugins), 'Basic loaded optional plugins') + call Check(!exists('g:loaded_plug'), 'Basic loaded the plugin manager') + call Check(!exists('g:loaded_surround'), 'Surround loaded in basic mode') + call Check(maparg(',ve', 'n') =~# 'dotvim_root', 'Configuration mapping lost') + call Check(maparg('', 'n') =~# 'find', 'Native file lookup missing') + new sample.py + call Check(&filetype ==# 'python' && &shiftwidth == 2, 'Python indentation changed') + execute 'source ' . fnameescape(g:dotvim_root . '/vimrc') + call Check(&shiftwidth == 2, 'Reload changed Python indentation') + new sample.yaml + call Check(&filetype ==# 'yaml' && &shiftwidth == 2, 'YAML indentation changed') + DotvimHealth +''') + + def test_fresh_checkout_and_repeat_source(self): + checkout = self.copy_configuration(self.scratch / "checkout with spaces and 'quote'") + self.run_editor(''' + let before_path = &runtimepath + let before_ignore = &wildignore + let before_list = &list + redir => before_commands + silent autocmd dotvim + redir END + execute 'source ' . fnameescape(g:dotvim_root . '/vimrc') + execute 'source ' . fnameescape(g:dotvim_root . '/vimrc') + redir => after_commands + silent autocmd dotvim + redir END + call Check(before_path ==# &runtimepath, 'Runtime paths accumulated') + call Check(before_ignore ==# &wildignore && before_list == &list, 'Options changed on reload') + call Check(before_commands ==# after_commands, 'Autocommands accumulated') +''', checkout=checkout) + + def test_full_without_downloads(self): + checkout = self.copy_configuration(self.scratch / 'no plugins') + self.run_editor(''' + call Check(empty(g:dotvim_loaded_plugins), 'Unexpected plugin loaded') + call Check(!empty(g:dotvim_skipped_plugins), 'Missing plugins not explained') + call dotvim#optional('TagbarToggle', 'Tagbar') + call dotvim#optional('UndotreeToggle', 'Undotree') +''', profile='full', checkout=checkout) + + def test_full_without_manager(self): + checkout = self.copy_configuration(self.scratch / 'no manager') + (checkout / 'autoload/plug.vim').unlink() + self.run_editor(''' + call Check(empty(g:dotvim_loaded_plugins), 'Plugins loaded without the manager') + call Check(g:dotvim_skipped_plugins[0] =~# 'vim-plug', 'Missing manager not explained') + call Check(!exists('g:loaded_plug'), 'Loaded a manager from elsewhere') +''', profile='full', checkout=checkout) + + def test_full_with_plugins_disabled(self): + self.run_editor(''' + call Check(!exists('g:loaded_plug'), '--noplugin loaded the manager') + call Check(empty(g:dotvim_loaded_plugins), '--noplugin loaded plugins') +''', profile='full', settings='set noloadplugins') + + def test_unwritable_state_directory(self): + blocker = self.scratch / 'not a directory' + blocker.write_text('keep this file') + self.run_editor('call Check(&number, "Basic options missing")', + settings='let g:dotvim_state_dir=' + vim_string(blocker / 'state')) + self.assertEqual(blocker.read_text(), 'keep this file') + + def test_native_directory_browser(self): + project = self.scratch / 'directory with spaces' + project.mkdir() + (project / 'sample.txt').write_text('sample\n') + self.run_editor(''' + execute 'cd ' . fnameescape(''' + vim_string(project) + ''') + doautocmd VimEnter + call dotvim#browse(0) + let found = 0 + for number in range(1, bufnr('$')) + if bufwinnr(number) > 0 && getbufvar(number, '&filetype') ==# 'netrw' + let found = 1 + endif + endfor + call Check(found, 'Native directory browser did not open') + if exists(':Lexplore') == 2 + call dotvim#browse(0) + call Check(!exists('t:netrw_lexbufnr'), 'Native sidebar did not close') + endif + " Some bundled netrw versions leave E31 after harmless silent! unmaps. + if v:errmsg =~# '^E31:' + let v:errmsg = '' + endif +''', native_browser=True) + + def test_native_search_and_cleanup(self): + project = self.scratch / 'project' + project.mkdir() + (project / 'sample.txt').write_text('unique_dotvim_needle\n') + empty_path = self.scratch / 'empty-bin' + empty_path.mkdir() + self.run_editor(''' + execute 'cd ' . fnameescape(''' + vim_string(project) + ''') + call dotvim#grep('unique_dotvim_needle') + call Check(len(getqflist()) == 1, 'Native search did not populate quickfix') + cclose + enew! + call setline(1, ['first ', '', '', '', 'last\t']) + let @/ = 'preserve_search' + call cursor(1, 2) + call dotvim#clean() + call Check(getline(1, '$') ==# ['first', '', 'last'], 'Whitespace cleanup failed') + call Check(@/ ==# 'preserve_search' && col('.') == 2, 'Cleanup changed search or cursor') +''', environment={'PATH': str(empty_path)}) + + @unittest.skipUnless((ROOT / 'plugged/surround/plugin/surround.vim').exists(), + 'Plugins have not been installed with vim-plug') + def test_full_plugins_and_shared_manager(self): + self.run_editor(''' + call Check(exists('g:loaded_surround'), 'Surround plugin did not load') + call Check(exists(':NERDTreeToggle') == 2, 'File tree plugin did not load') + call Check(exists(':UndotreeToggle') == 2, 'Undo tree plugin did not load') + call Check(g:dotvim_package_loader ==# 'vim-plug', 'Wrong loader') + enew + call setline(1, 'hello') + normal ysiw] + call Check(getline(1) ==# '[hello]', 'Surround editing failed') + execute 'source ' . fnameescape(g:dotvim_root . '/vimrc') + call Check(exists(':NERDTreeToggle') == 2, 'Plugin lost on reload') +''', profile='full') + + def test_full_without_external_tools(self): + empty_path = self.scratch / 'empty-bin' + empty_path.mkdir() + self.run_editor(''' + for name in ['fugitive', 'tagbar', 'fzf', 'fzf-vim', 'undotree', 'ultisnips', 'lsp'] + call Check(index(g:dotvim_loaded_plugins, name) < 0, 'Loaded unavailable feature: ' . name) + endfor + call Check(!exists(':Git') && !exists(':TagbarToggle'), 'Unavailable commands were loaded') + call Check(len(g:plugs) == 13, 'Disabled plugins disappeared from the manifest') + for name in ['tagbar', 'fzf', 'fzf-vim', 'ultisnips', 'lsp'] + call Check(get(g:plugs[name], 'on', ['unexpected']) ==# [], 'Unavailable plugin was not disabled') + endfor +''', profile='full', environment={'PATH': str(empty_path)}) + + def test_startup_does_not_download(self): + git = shutil.which('git') + if not git: + self.skipTest('Git is not installed') + commands = self.scratch / 'bin' + commands.mkdir() + wrapper = commands / 'git' + wrapper.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> "$DOTVIM_GIT_LOG"\nexec ' + + "'" + git.replace("'", "'\\''") + "'" + ' "$@"\n') + wrapper.chmod(0o755) + log = self.scratch / 'git-log' + checkout = self.copy_configuration(self.scratch / 'no downloads') + self.run_editor('call Check(exists(":PlugInstall") == 2, "vim-plug commands missing")', + profile='full', checkout=checkout, + environment={'PATH': str(commands) + os.pathsep + os.environ['PATH'], + 'DOTVIM_GIT_LOG': str(log)}) + calls = log.read_text() if log.exists() else '' + self.assertNotRegex(calls, r'\b(clone|fetch|pull|ls-remote)\b') + self.assertFalse((checkout / 'plugged').exists()) + + @unittest.skipUnless(shutil.which('rg'), 'ripgrep is not installed') + def test_ripgrep_search(self): + project = self.scratch / 'project' + project.mkdir() + (project / 'file with spaces.txt').write_text('needle with "quotes"\n') + self.run_editor(''' + execute 'cd ' . fnameescape(''' + vim_string(project) + ''') + let saved_format = &errorformat + call dotvim#grep('needle with "quotes"') + call Check(len(getqflist()) == 1 && getqflist()[0].lnum == 1, 'ripgrep search failed') + call Check(&errorformat ==# saved_format, 'Search changed errorformat') + cclose +''') + + def test_python_path_quoting(self): + interpreter = self.scratch / "python with 'quote'" + interpreter.write_text('#!/bin/sh\nprintf "%s\\n" "$1" > "$DOTVIM_PYTHON_LOG"\n') + interpreter.chmod(0o755) + sample = self.scratch / "script with %#! and 'quote'.py" + sample.write_text('pass\n') + log = self.scratch / 'python-log' + self.run_editor(''' + execute 'edit ' . fnameescape(''' + vim_string(sample) + ''') + call dotvim#python() +''', settings='let g:dotvim_python=' + vim_string(interpreter), + environment={'DOTVIM_PYTHON_LOG': str(log)}) + self.assertEqual(log.read_text().strip(), str(sample)) + + def test_available_enhanced_tools(self): + if not (ROOT / 'plugged/fzf-vim/plugin/fzf.vim').exists(): + self.skipTest('Plugins are not installed with vim-plug') + self.run_editor(''' + if index(g:dotvim_loaded_plugins, 'fzf-vim') >= 0 + call Check(exists(':Files') == 2, 'fzf file command missing') + call Check(executable(fzf#exec()), 'fzf executable not resolved') + endif + if index(g:dotvim_loaded_plugins, 'tagbar') >= 0 + call Check(exists(':TagbarToggle') == 2, 'Tagbar command missing') + endif +''', profile='full') + + def test_lsp_without_servers(self): + self.run_editor(r''' + call Check(g:dotvim_lsp_status =~# '0 available\|requires\|disabled\|not installed', 'Unexpected LSP status') +''', profile='full', settings='let g:dotvim_lsp=1 | let g:dotvim_lsp_servers=[]') + + def test_optional_snippet_engine(self): + self.run_editor(''' + if index(g:dotvim_loaded_plugins, 'ultisnips') >= 0 + call Check(exists(':UltiSnipsEdit') == 2, 'Snippet engine did not initialize') + endif +''', profile='full', settings='let g:dotvim_snippets=1') + + def test_local_settings_and_final_overrides(self): + local = self.scratch / 'local.vim' + local.write_text("let g:dotvim_colorscheme='missing_dotvim_test_theme'\n" + 'function! DotvimLocal() abort\n set nocursorcolumn\nendfunction\n') + self.run_editor(''' + call Check(!&cursorcolumn, 'Final local override was ignored') + call Check(g:colors_name ==# 'desert', 'Missing theme did not fall back') +''', settings='let g:dotvim_local_config=' + vim_string(local)) + + def test_lsp_handshake(self): + version = subprocess.check_output([EDITOR, '--version'], text=True) + nvim_version = re.search(r'NVIM v(\d+)\.(\d+)', version) + vim_version = re.search(r'VIM - Vi IMproved (\d+)\.', version) + if not ((nvim_version and tuple(map(int, nvim_version.groups())) >= (0, 11)) + or (vim_version and int(vim_version[1]) >= 9)): + self.skipTest('LSP requires Vim 9+ or Neovim 0.11+') + if not (ROOT / 'plugged/lsp/plugin/lsp.vim').exists() and 'NVIM' not in version: + self.skipTest('Vim LSP plugin is not installed') + project = self.scratch / 'lsp-project' + project.mkdir() + (project / '.git').mkdir() + sample = project / 'sample.py' + sample.write_text('value = 1\n') + log = self.scratch / 'lsp-log' + server = {'name': 'test', 'cmd': [sys.executable, str(ROOT / 'tests/lsp_server.py')], + 'filetypes': ['python'], 'root_markers': ['.git']} + settings = 'let g:dotvim_lsp=1 | let g:dotvim_lsp_servers=[' + str(server) + ']' + self.run_editor(''' + doautocmd VimEnter + execute 'edit ' . fnameescape(''' + vim_string(sample) + ''') + let attempts = 0 + while attempts < 250 && (!filereadable($DOTVIM_LSP_LOG) || join(readfile($DOTVIM_LSP_LOG), '') !~# 'textDocument/didOpen') + sleep 20m + let attempts += 1 + endwhile + call Check(filereadable($DOTVIM_LSP_LOG), 'LSP server was not started') + call Check(join(readfile($DOTVIM_LSP_LOG), '') =~# 'textDocument/didOpen', 'LSP handshake did not open the document') +''', profile='full', settings=settings, environment={'DOTVIM_LSP_LOG': str(log)}) + + +class InstallerTests(Workspace): + def setUp(self): + super().setUp() + self.checkout = self.copy_configuration(self.scratch / "checkout with spaces and 'quote'") + self.install_home = Path(self.environment['DOTVIM_HOME']) + self.install_home.mkdir() + if EDITOR: + self.environment['DOTVIM_INSTALL_EDITOR'] = EDITOR + + def install(self, *arguments, success=True, environment=None): + env = dict(self.environment) + env.update(environment or {}) + result = subprocess.run(['/bin/sh', str(self.checkout / 'bootstrap.sh'), *arguments], + env=env, capture_output=True, text=True, timeout=30) + if success: + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + else: + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + return result + + def test_backup_and_idempotence(self): + (self.install_home / '.vim').mkdir() + (self.install_home / '.vim' / 'keep').write_text('vim data') + (self.install_home / '.vimrc').symlink_to('missing-original-config') + nvim = Path(self.environment['XDG_CONFIG_HOME']) / 'nvim' + nvim.mkdir(parents=True) + (nvim / 'init.lua').write_text('-- existing Neovim configuration') + self.install() + backups = list((self.install_home / '.dotvim-backups').iterdir()) + self.assertEqual(len(backups), 1) + self.assertEqual((backups[0] / 'vim' / 'keep').read_text(), 'vim data') + self.assertEqual(os.readlink(backups[0] / 'vimrc'), 'missing-original-config') + self.assertTrue((backups[0] / 'nvim' / 'init.lua').exists()) + self.assertEqual((self.install_home / '.vim').resolve(), self.checkout) + self.assertEqual(nvim.resolve(), self.checkout) + self.install() + self.assertEqual(list((self.install_home / '.dotvim-backups').iterdir()), backups) + self.assertEqual((self.install_home / '.dotvim-profile').read_text(), 'basic\n') + + def test_basic_install_without_git_or_editors(self): + commands = self.scratch / 'bin' + commands.mkdir() + for name in ['dirname', 'mktemp', 'touch', 'mkdir', 'mv', 'date', 'ln', 'readlink', 'cmp', 'cp', 'rm']: + (commands / name).symlink_to(shutil.which(name)) + self.install('--vim-only', environment={'PATH': str(commands)}) + self.assertTrue((self.install_home / '.vimrc').is_symlink()) + self.assertFalse((Path(self.environment['XDG_CONFIG_HOME']) / 'nvim').exists()) + + def test_rollback_after_failed_link(self): + (self.install_home / '.vim').mkdir() + (self.install_home / '.vim' / 'keep').write_text('original data') + (self.install_home / '.vimrc').write_text('original vimrc') + commands = self.scratch / 'bin' + commands.mkdir() + fake_ln = commands / 'ln' + fake_ln.write_text('#!/bin/sh\ncase "$3" in */.vimrc) exit 1;; esac\nexec ' + + str(shutil.which('ln')) + ' "$@"\n') + fake_ln.chmod(0o755) + self.install(success=False, environment={'PATH': str(commands) + os.pathsep + os.environ['PATH']}) + self.assertEqual((self.install_home / '.vim' / 'keep').read_text(), 'original data') + self.assertEqual((self.install_home / '.vimrc').read_text(), 'original vimrc') + self.assertFalse((self.install_home / '.dotvim-profile').exists()) + + def test_failed_download_keeps_configuration(self): + (self.install_home / '.vimrc').write_text('original vimrc') + commands = self.scratch / 'bin' + commands.mkdir() + fake_git = commands / 'git' + fake_git.write_text('#!/bin/sh\nexit 1\n') + fake_git.chmod(0o755) + self.install('--full', success=False, + environment={'PATH': str(commands) + os.pathsep + os.environ['PATH']}) + self.assertEqual((self.install_home / '.vimrc').read_text(), 'original vimrc') + self.assertFalse((self.install_home / '.dotvim-backups').exists()) + + def test_full_requires_an_editor_before_replacing_configuration(self): + (self.install_home / '.vimrc').write_text('original vimrc') + self.install('--full', success=False, + environment={'DOTVIM_INSTALL_EDITOR': str(self.scratch / 'missing-editor')}) + self.assertEqual((self.install_home / '.vimrc').read_text(), 'original vimrc') + self.assertFalse((self.install_home / '.dotvim-backups').exists()) + + @unittest.skipUnless(EDITOR and shutil.which('git'), 'Git and an editor are required') + def test_pinned_install_upgrade_and_offline_repeat(self): + upstream = self.scratch / "upstream with 'quote'" + upstream.mkdir() + + def git(*arguments): + return subprocess.check_output( + ['git', '-c', 'user.name=Dotvim Test', '-c', 'user.email=test@example.invalid', + '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', + '-C', str(upstream), *arguments], env=self.environment, + stderr=subprocess.STDOUT, text=True).strip() + + git('init', '--quiet') + (upstream / 'plugin').mkdir() + (upstream / 'plugin/trap.vim').write_text("throw 'Installer evaluated plugin code'\n") + (upstream / 'ftdetect').mkdir() + (upstream / 'ftdetect/trap.vim').write_text("throw 'Installer evaluated filetype detection'\n") + git('add', '.') + git('commit', '--quiet', '-m', 'Initial fixture') + first = git('rev-parse', 'HEAD') + (upstream / 'version').write_text('second revision\n') + git('add', '.') + git('commit', '--quiet', '-m', 'Update fixture') + second = git('rev-parse', 'HEAD') + manifest = self.checkout / 'plugins.vim' + source = manifest.read_text() + + def pin(revision): + manifest.write_text(re.sub( + r"s:Plugin\('[^']+', '([^']+)', '[0-9a-f]{40}'", + lambda match: "s:Plugin(" + vim_string(upstream.as_uri()) + ", '" + + match[1] + "', '" + revision + "'", source)) + + def check_revisions(revision): + plugins = list((self.checkout / 'plugged').iterdir()) + self.assertEqual(len(plugins), 13) + for plugin in plugins: + actual = subprocess.check_output(['git', '-C', str(plugin), 'rev-parse', 'HEAD'], + text=True).strip() + self.assertEqual(actual, revision, str(plugin)) + + pin(first) + self.install('--full') + check_revisions(first) + pin(second) + self.install('--full') + check_revisions(second) + shutil.rmtree(upstream) + self.install('--full') + check_revisions(second) + self.assertEqual((self.install_home / '.dotvim-profile').read_text(), 'full\n') + + def test_failed_profile_write_restores_configuration(self): + (self.install_home / '.vimrc').write_text('original vimrc') + (self.install_home / '.dotvim-profile').write_text('full\n') + commands = self.scratch / 'bin' + commands.mkdir() + fake_cp = commands / 'cp' + fake_cp.write_text('#!/bin/sh\nexit 1\n') + fake_cp.chmod(0o755) + self.install(success=False, environment={'PATH': str(commands) + os.pathsep + os.environ['PATH']}) + self.assertEqual((self.install_home / '.vimrc').read_text(), 'original vimrc') + self.assertEqual((self.install_home / '.dotvim-profile').read_text(), 'full\n') + self.assertFalse((self.install_home / '.vim').exists()) + + def test_checkout_already_at_vim_directory(self): + destination = self.install_home / '.vim' + shutil.move(self.checkout, destination) + self.checkout = destination + self.install('--vim-only') + self.assertFalse(destination.is_symlink()) + self.assertEqual((self.install_home / '.vimrc').resolve(), destination / 'vimrc') + + def test_nvim_only(self): + self.install('--nvim-only') + self.assertFalse((self.install_home / '.vimrc').exists()) + self.assertTrue((Path(self.environment['XDG_CONFIG_HOME']) / 'nvim' / 'init.vim').exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/vimrc b/vimrc index d1a3c29..b952cf9 100644 --- a/vimrc +++ b/vimrc @@ -1,341 +1,173 @@ -" List of mappings -"---------------- -" ,ve - Open vimrc -" ,vs - Source vimrc -" ,d - Insert current date -" ,hl - Toggle search highlighting -" ,l - Show hidden characters -" ,py - Execute current python script -" ,w - Toggle word wrapping -" ,s - Toggle spell checking -" -" ,nt - Open NERDtree -" ,nf - Open NERDtree using current file's directory -" ,wm - Toggle NERDTree -" -" C-down - Move current line/selection down -" C-up - Move current line/selection up -" C-] - Simple brace completion +" Shared configuration for Vim 7.4+ and Neovim. +set nocompatible -" Pathogen +let g:dotvim_root = fnamemodify(resolve(expand(':p')), ':h') +let s:root = escape(g:dotvim_root, ',') +if stridx(',' . &runtimepath . ',', ',' . s:root . ',') < 0 + let &runtimepath = s:root . ',' . &runtimepath +endif -call pathogen#infect() +" Machine-specific settings are shared by both editors and never tracked. +let s:local = get(g:, 'dotvim_local_config', expand('~/.vimrc.local')) +if filereadable(s:local) + execute 'source ' . fnameescape(s:local) +endif +if !exists('g:dotvim_profile') + let s:profile = expand('~/.dotvim-profile') + let g:dotvim_profile = filereadable(s:profile) ? get(readfile(s:profile, '', 1), 0, 'basic') : 'basic' +endif +if !empty($DOTVIM_PROFILE) + let g:dotvim_profile = $DOTVIM_PROFILE +endif +if index(['basic', 'full'], g:dotvim_profile) < 0 + let g:dotvim_profile = 'basic' +endif -"============================================================================== -"HOW IT WORKS -"============================================================================== -set backspace=indent,eol,start "Allows backspacing over stuff -set complete+=t "Tag completion -"set cpoptions+=$ "Overwrite text (visually) -set cursorline -set cursorcolumn +set backspace=indent,eol,start set encoding=utf-8 -set fillchars= "Remove the characters in window separators -set hidden "Allows hidden buffers with changes -set hlsearch "When there is a previous search pattern, highlight all its matches. -set ignorecase "Search is case insensitive unless... -set incsearch "Show match while entering search -set laststatus=2 "Status line is always on -"set mouse-=a "Disable mouse -set nocompatible "Git tae, Vi compatibility -set nostartofline "Stop jumping to the start of a line -set nofoldenable "Don't fold by default" -set pastetoggle= "Use F2 to toggle paste on/off in insert mode -set ruler "Show the line and column number of the cursor position, separated by a comma. -"set scrolloff=8 "Keeps the cursor centered while scrolling -"set shellslash "Use / instead of \ for file paths and such -set shortmess+=I "Remove the intro message -set showmatch "Jump to matching paren when inserting -set smartcase "An uppercase letter is found -set spl=en_gb "Language for spellchecking -set vb "Visual bell -set viminfo+=<0 "Don't save registers -set viminfo-=<50 "Same as above, removes default stuff from viminfo -set virtualedit=all "Cursor can move anywhere (ish) -"set wildmenu "Display options when autocompleting in cmdline mode - -set fileencoding=utf8 -set termencoding=utf8 - -if version >= 703 - set colorcolumn=72,79 "Highlight columns - set relativenumber "Show the line number relative to the line with the cursor in front of each line. - set undofile +set hidden +set hlsearch incsearch ignorecase smartcase +set cursorline cursorcolumn +set laststatus=2 ruler number +set nostartofline nofoldenable +set shortmess+=I +set showmatch visualbell +set virtualedit=all +set tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent smarttab +set wrap linebreak +set list listchars=tab:>-,trail:~ +set wildmenu +set wildignore+=*.o,*.so,*.pyc,*.swp,*.zip,*~,.DS_Store,*/.git/*,*/node_modules/* +set path+=** +set completeopt=menu,menuone +set background=dark +if exists('+colorcolumn') + set colorcolumn=72,79 endif - -"filetype off -filetype plugin indent on "Filetype plugin -syntax on "Syntax highlighting - -"============================================================================== -"MAPPINGS -"============================================================================== -let mapleader=',' - -"Default vimrc mappings -nnoremap ve :e $MYVIMRC -nnoremap vs :so $MYVIMRC - -"Macvim vimrc mappings -if has('unix') - nnoremap ve :e ~/.gvimrc - nnoremap vs :so ~/.gvimrc +if exists('+relativenumber') + set relativenumber +endif +if exists('+spelllang') + set spelllang=en_gb +endif +if exists('+pastetoggle') + set pastetoggle= +endif +if has('nvim') && exists('+shada') + set shada-=<50 shada+=<0 +elseif exists('+viminfo') + set viminfo-=<50 viminfo+=<0 +endif +if has('nvim') || v:version >= 800 + set completeopt+=noinsert +endif +if exists('+termguicolors') && get(g:, 'dotvim_truecolor', $COLORTERM =~# 'truecolor\|24bit' || $TERM =~# 'direct') + set termguicolors endif -"Cd to current file's dir -nnoremap cd :cd %:h:pwd - -"Insert current date -nnoremap d "=strftime('%d %b %Y')P - -"Moving between buffers -nnoremap :bn -nnoremap :bp - -"Toggle search highlighting -nnoremap hl :set invhls:set hls? - -"Show hidden chars -nnoremap l :set invlist - -"Run python script -nnoremap py :!python % - -"wrap / Nowrap -nnoremap w :set invwrap - -"Spell checking -nnoremap s :set invspell - -"Simple brace completion -inoremap {}O - -"Remove quoutes -nnoremap q di'hPl2x - -"============================================================================== -"HOW IT LOOKS -"============================================================================== - -set t_Co=256 -"colorscheme wombat256mod -colorscheme onedark - -set tabstop=4 "Tab character width -set softtabstop=4 "Amount of whitespace to be inserted -set shiftwidth=4 "Amount of whitespace in Normal mode -set expandtab "Spaces rather than tabs -set autoindent -set smarttab - -set number "Line numbering -set background=dark "Better colours for a dark background - -set go-=T - -"Stops words being hypenated when wrapping -set wrap lbr - -" Show hidden tabs -set list! - -" Shortcut to rapidly toggle `set list` -nmap l :set list! - -"Setting hidden chars -set listchars=tab:>-,trail:~ -"set listchars=tab:>-,trail:~,eol:¬ -"" Use the same symbols as TextMate for tabstops and EOLs -"set listchars=tab:▸\ ,eol:¬ +" Keep state out of edited projects; unwritable state directories are optional. +let s:state = get(g:, 'dotvim_state_dir', (empty($XDG_STATE_HOME) ? expand('~/.local/state') : $XDG_STATE_HOME) . '/dotvim') +for s:kind in ['swap', 'backup', 'undo'] + let s:directory = s:state . '/' . s:kind + let s:parent = s:directory + while !isdirectory(s:parent) && empty(getftype(s:parent)) + let s:parent = fnamemodify(s:parent, ':h') + endwhile + if !isdirectory(s:parent) || filewritable(s:parent) != 2 + continue + endif + try + if !isdirectory(s:directory) + call mkdir(s:directory, 'p', 0700) + endif + if filewritable(s:directory) == 2 + let s:directory = escape(s:directory, ',') . '//' + if s:kind ==# 'swap' + let &directory = s:directory + elseif s:kind ==# 'backup' + let &backupdir = s:directory + elseif has('persistent_undo') + let &undodir = s:directory + set undofile + endif + endif + catch + " Editing still works when the state directory cannot be created. + endtry +endfor + +let mapleader = ',' +nnoremap ve :execute 'edit ' . fnameescape(g:dotvim_root . '/vimrc') +nnoremap vs :execute 'source ' . fnameescape(g:dotvim_root . '/vimrc') +nnoremap cd :execute 'cd ' . fnameescape(expand('%:p:h')):pwd +nnoremap d "=strftime('%d %b %Y')P +nnoremap :bnext +nnoremap :bprevious +nnoremap hl :set invhlsearch:set hlsearch? +nnoremap l :set invlist +nnoremap w :set invwrap +if exists('+spell') + nnoremap s :set invspell +endif +nnoremap py :call dotvim#python() +inoremap {}O +nnoremap q di'hPl2x +nnoremap :silent! move .-2== +nnoremap :silent! move .+1== +xnoremap :move '<-2gv=gv +xnoremap :move '>+1gv=gv + +" Native fallbacks remain available without any installed plugins. +nnoremap :find +nnoremap nt :call dotvim#browse(0) +nnoremap nf :call dotvim#browse(1) +nnoremap wm :call dotvim#browse(0) +nnoremap wm :call dotvim#browse(0) +nnoremap :Grep +nnoremap :call dotvim#optional('TagbarToggle', 'Tagbar with Universal Ctags') +nnoremap :call dotvim#clean() +nnoremap :call dotvim#optional('UndotreeToggle', 'Undotree') +command! -nargs=+ Grep call dotvim#grep() +command! DotvimHealth call dotvim#health() + +if filereadable(g:dotvim_root . '/plugins.vim') + execute 'source ' . fnameescape(g:dotvim_root . '/plugins.vim') +endif +filetype plugin indent on -"Autocmds -"-------- if has('autocmd') - "Setting filetypes - au BufRead,BufNewFile *.ini set filetype=dosini - au BufRead,BufNewFile supervisord.conf set filetype=dosini - au BufRead,BufNewFile Vagrantfile set filetype=ruby - au BufRead,BufNewFile Rakefile set filetype=ruby - - " nginx - au BufRead,BufNewFile */webserver/files/conf/* set ft=nginx - - " Python indent for Twitter - au BufRead,BufNewFile *.py setl shiftwidth=2 tabstop=2 softtabstop=2 - - "html/css/js indentation - au BufRead,BufNewFile *.html setl shiftwidth=2 tabstop=2 softtabstop=2 - au BufRead,BufNewFile *.css setl shiftwidth=2 tabstop=2 softtabstop=2 - au BufRead,BufNewFile *.js setl shiftwidth=2 tabstop=2 softtabstop=2 - au BufRead,BufNewFile *.jade setl shiftwidth=2 tabstop=2 softtabstop=2 - au BufRead,BufNewFile *.scss setl shiftwidth=2 tabstop=2 softtabstop=2 - au BufRead,BufNewFile *.yml setl shiftwidth=2 tabstop=2 softtabstop=2 - - au BufRead,BufNewFile Vagrantfile setl shiftwidth=2 tabstop=2 softtabstop=2 - au BufRead,BufNewFile Rakefile setl shiftwidth=2 tabstop=2 softtabstop=2 - au BufRead,BufNewFile *.rb setl shiftwidth=2 tabstop=2 softtabstop=2 - + augroup dotvim + autocmd! + autocmd BufRead,BufNewFile *.ini,supervisord.conf setfiletype dosini + autocmd BufRead,BufNewFile Vagrantfile,Rakefile setfiletype ruby + autocmd BufRead,BufNewFile */webserver/files/conf/* setfiletype nginx + " Preserve the original two-space indentation for these languages. + autocmd FileType python,ruby,html,css,javascript,javascriptreact,typescript,typescriptreact,jade,pug,scss,yaml setlocal shiftwidth=2 tabstop=2 softtabstop=2 + augroup END + if !empty(&filetype) && exists('#dotvim#FileType#' . &filetype) + execute 'doautocmd dotvim FileType ' . &filetype + endif endif - -"============================================================================== -"PLUGINS -"============================================================================== - -"NERDTree -let NERDTreeWinPos='left' -nnoremap nt :NERDTree. -"Open tree using file's directory -nnoremap nf :NERDTree %:p:h -nmap wm :NERDTreeToggle - -" MiniBufExpl -let g:miniBufExplMapWindowNavArrows = 1 -let g:miniBufExplMapCTabSwitchBufs = 1 - -" Grep -nnoremap :Grep - -" Tagbar -nnoremap :TagbarToggle -if executable("/usr/local/bin/ctags") - let g:tagbar_ctags_bin = '/usr/local/bin/ctags' -else - let g:tagbar_ctags_bin = '/usr/bin/ctags' +if has('syntax') + syntax enable + let s:theme = get(g:, 'dotvim_colorscheme', index(get(g:, 'dotvim_loaded_plugins', []), 'onedark') >= 0 ? 'onedark' : 'desert') + let s:theme_available = 0 + for s:extension in (has('nvim') ? ['vim', 'lua'] : ['vim']) + let s:color = 'colors/' . s:theme . '.' . s:extension + if !empty(globpath(&runtimepath, s:color)) + let s:theme_available = 1 + break + endif + if exists('+packpath') && (!empty(globpath(&packpath, 'pack/*/opt/*/' . s:color)) || !empty(globpath(&packpath, 'pack/*/start/*/' . s:color))) + let s:theme_available = 1 + break + endif + endfor + execute 'colorscheme ' . fnameescape(s:theme_available ? s:theme : 'desert') endif -let g:tagbar_width = 30 -" For gotags per https://github.com/jstemmer/gotags -let g:tagbar_type_go = { - \ 'ctagstype' : 'go', - \ 'kinds' : [ - \ 'p:package', - \ 'i:imports:1', - \ 'c:constants', - \ 'v:variables', - \ 't:types', - \ 'n:interfaces', - \ 'w:fields', - \ 'e:embedded', - \ 'm:methods', - \ 'r:constructor', - \ 'f:functions' - \ ], - \ 'sro' : '.', - \ 'kind2scope' : { - \ 't' : 'ctype', - \ 'n' : 'ntype' - \ }, - \ 'scope2kind' : { - \ 'ctype' : 't', - \ 'ntype' : 'n' - \ }, - \ 'ctagsbin' : 'gotags', - \ 'ctagsargs' : '-sort -silent' -\ } - -" Gundo -nnoremap :GundoToggle - -" Python-mode -let g:pymode_virtualenv = 1 "Enable automatic virtualenv detection -let g:pymode_python = 'python3' - -" CtrlP -let g:ctrlp_map = '' -let g:ctrlp_cmd = 'CtrlP' -let g:ctrlp_working_path_mode = 'rc' -set wildignore+=*/tmp/*,*.so,*.swp,*.zip,*~,.DS_Store " MacOSX/Linux -let g:ctrlp_custom_ignore = { - \ 'dir': '\.git$\|\.hg$\|\.svn$', - \ 'file': '\.exe$\|\.so$\|\.dll$', - \ 'python': '\.pyc$\|\.ptlc$', - \ 'link': 'some_bad_symbolic_links', - \ } - -" unimpaired -" Bubbing single line -nmap [e -nmap ]e - -" Bubbing multiple lines -vmap [egv -vmap ]egv - -" LustyExplorer -let g:LustyJugglerSuppressRubyWarning = 1 -let g:LustyExplorerSuppressRubyWarning = 1 - - -"============================================================================== -"FUNCTIONS -"============================================================================== - -if has("autocmd") - autocmd bufwritepost .vimrc source $MYVIMRC - - "" Resovle the stange color mass up issue - "if !has('gui_macvim') - " au VimEnter * source ~/.vim/bundle/wombat256mod/colors/wombat256mod.vim - "endif +" Optional final overrides, defined in ~/.vimrc.local. +if exists('*DotvimLocal') + call DotvimLocal() endif - -function! StripTrailingWhitespacesAndDuplicateBlankLines() - " Preparation: save last search, and cursor position. - let _s=@/ - let l = line(".") - let c = col(".") - " Do the business: - %s/\s\+$//e - %s/^\n$//g - " Clean up: restore previous search history, and cursor position - let @/=_s - call cursor(l, c) -endfunction -nnoremap :call StripTrailingWhitespacesAndDuplicateBlankLines() - -" In line copy and paste to system clipboard -" reference: http://vim.wikia.com/wiki/In_line_copy_and_paste_to_system_clipboard -"vmap y:call system("pbcopy", getreg("\"")) -"nmap :call setreg("\"",system("pbpaste"))p - -hi link EasyMotionTarget ErrorMsg -hi link EasyMotionShade Comment - -" ultisnips -let g:UltiSnipsListSnippets = "" -let g:UltiSnipsJumpForwardTrigger="" -let g:UltiSnipsJumpBackwardTrigger="" -let g:UltiSnipsDontReverseSearchPath="1" -let g:UltiSnipsSnippetDirectories = ['UltiSnips', 'snippets'] - -" vim-markdonw -let g:vim_markdown_initial_foldlevel=1 - -" vim-easy-align -" Start interactive EasyAlign in visual mode (e.g. vip) -vmap (EasyAlign) -" -" Start interactive EasyAlign for a motion/text object (e.g. aip) -nmap a (EasyAlign) - -" Disable new window auto documentation -" reference: https://github.com/klen/python-mode/issues/384 -set completeopt=menu -set completeopt+=menuone " show the popup menu even when there is only 1 match -set completeopt-=longest " don't insert the longest common text -set completeopt-=preview " don't show preview window -set completeopt+=noinsert " don't insert any text until user chooses a match -set completeopt-=noselect " select first match - -" vim freezes when using pymode autocomplete, disable it -" reference: https://github.com/klen/python-mode/issues/405 -" let g:pymode_rope_lookup_project = 0 -" let g:pymode_rope_complete_on_dot = 0 -" let g:pymode_rope = 0 - -"============================================================================== -"ALIAS -"============================================================================== -:command FS set guifont=Menlo:h17 -let g:tagbar_ctags_bin = "/opt/homebrew/bin/ctags"