Vim plugins: Difference between revisions

From miki
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 1,009: Line 1,009:
" }}}
" }}}
</source>
</source>

;Troubleshooting
* Bad indentation of closing braces: check that <code>equalprg</code> is not set in {{file|.vimrc}}.


=== Vimtex ===
=== Vimtex ===
See also [[Vim-tex]] for usage.

{| class=wikitable width=100%
{| class=wikitable width=100%
|-
|-
Line 1,095: Line 1,100:
</source>
</source>
Install [https://github.com/vim-scripts/vim-auto-save vim-auto-save] plugin to save the file and trigger compilation regularly.
Install [https://github.com/vim-scripts/vim-auto-save vim-auto-save] plugin to save the file and trigger compilation regularly.

;Usage
See [[Vim-tex]].


=== VimWiki ===
=== VimWiki ===
Line 1,138: Line 1,140:
-endif
-endif
</source>
</source>
* <code>Exception not caught: VimwikiTags5: Metadata file corrupted"</code> [https://github.com/vimwiki/vimwiki/issues/1286]
:The fix is simply to delete the file {{file|vimwiki/.vimwiki_tags}}, and optionally run the command <code>:VimwikiRebuildTags</code>.


=== YouCompleteMe ===
=== YouCompleteMe ===

Latest revision as of 14:44, 8 April 2023

This page is about Vim plugins.

Overview

Find a plugin

Most plugins are found on vim.org or GitHub:

A mirror of all plugins originally found on http://www.vim.org/scripts/ ;
  • GitHub.

Install a plugin

The best is to use a plugin manager (see below). Otherwise,

  • Unzip the plugin in ~/.vim directory (or plugin, autoload...)
  • Generate the help tags with:
helptags ~/.vim/tags

Getting help

Most plugins come with local help files. Do :help local-additions to get a list of help files for locally installed plugins.

Plugin Managers

Here I list various plugin managers. My current favorite is vim-plug.

apt-vim

Fully-automated, Cross-platform Plugin Manager for Vim.

Pathogen

Plugin manager from Tim Pope.

VAM (vim-addon-manager)

VAM manage and install vim plugins (including their dependencies) in a sane way.

vim-plug

Plugin manager from junegunn, author of fzf, vim-easy-align.

Install
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
Update plugins on offline computer

To update plugins on a computer that has no internet access, the simplest solution is to clone all repositories in a folder accessible by the offline computer, and use the git URL rewriting feature to point to this folder instead.

Use the following script to sync the folder, vim-plug-mirror.sh:

#! /bin/bash

die()
{
    CODE=$1
    shift
    >&2 echo "ERROR -- $@"
    exit $CODE
}

usage()
{
    echo "Usage: $(basename $0) <mirror_dir>"
    die 1 "$*"
}

DIR=${1%%/}
echo $DIR

[ -n "$DIR" -a -d "$(dirname "$DIR")" ] || usage "Missing <mirror_dir>"

if ! [ -d "$DIR" ]; then
    echo "Creating $DIR"
    mkdir "$DIR" || die 1 "Cannot create '$DIR'"
fi

PLUGINS_DIR=$(find ~/.vim/plugged -name .git|sed -r 's_/\.git__')

for plugin_dir in $PLUGINS_DIR; do
    echo "Processing '$plugin_dir'"
    URL=$(git -C "$plugin_dir" remote get-url origin)
    plugin=$(echo $URL|sed -r 's_https://github.com/__; s_github\.com:__; s_\.git__')
    PLUGINDIR=$DIR/${plugin}.git
    PARENTDIR=$(dirname $PLUGINDIR)
    if [ -d "$PLUGINDIR" ]; then
        false && echo git -C "$PLUGINDIR" fetch --all
    else
        mkdir -p "$PARENTDIR" || die 1 "Cannot create '$PARENTDIR'"
        git clone --mirror $URL "$PLUGINDIR"
    fi
done

To use the script, simply give a folder path:

vim-plug-mirror.sh /smb/some/path

Then, on the offline machine:

sudo git config --system url./smb/some/path/.insteadOf https://github.com/


Interaction with $HOME version control

If we store our HOME files (dot-files) in git, we can't store the plugins anymore because they are fetched and stored locally as squashed git submodules. We can circumvent this by managing these plugins as git submodules.

First create .gitmodules:

[submodule "ack.vim"]
    path = .vim/plugged/ack.vim
    url = ./.vim/plugged/ack.vim
[submodule "auto-pairs"]
    path = .vim/plugged/auto-pairs
    url = ./.vim/plugged/auto-pairs
[submodule "a.vim"]
    path = .vim/plugged/a.vim
    url = ./.vim/plugged/a.vim

Then create the bare repositories:

git clone --bare /home/peetersm home.git
cd home.git/
mkdir -p .vim/plugged
cd .vim/plugged
for g in ~/.vim/plugged/*; do git clone --bare $g; done

Then, to clone the HOME repository:

git clone --recursive .../home.git

Finally we must update the tags file in vim. Start vim and run PlugInstall!. Ignore the error messages.


Troubleshooting
  • Using short path may fail if plugin name has an extension. For instance:
" The following FAILS because of trailing .vim
Plug 'ctrlpvim/ctrlp.vim'
" Use the following instead.
Plug 'https://github.com/ctrlpvim/ctrlp.vim.git'
  • Conditional plugin activation.
See the FAQ.

Installed plugins

Plugins I'm currently using.

A

a.vim : Alternate Files quickly (.c --> .h etc) (forked version, the original version)

vim.org GitHub a.vim Alternate Files quickly (.c --> .h etc) (original)
:A Switch between header / source file
:AS Split and Switch
:AV Vertical split and Switch
:AT New Tab and Switch
:AN Cycles through matches
:IH Cih switches to file under cursor
:IHS splits and switches
:IHV vertical splits and switches
:IHT new tab and switches
:IHN Leaderihn cycles through matches
Leaderis switches to the alternate file of file under cursor

Plugin high-level description, or comment on the configuration.

" Plug 'nacitar/a.vim'                                " Alternate Files quickly (.c --> .h etc) - fork of original
Plug 'xeyownt/a.vim'                                  " Alternate Files quickly (.c --> .h etc) - fork of original

ack.vim

GitHub ack.vim Vim plugin for the Perl module / CLI script 'ack'

I fell back to this plugin because ag.vim is stalled. But we can still use ag as search engine.

My settings [1]:

if executable('ag')
  " Use ag over grep - See ag man page for option '--vimgrep'
  set grepprg=ag\ --vimgrep\ $*
  set grepformat=%f:%l:%c:%m

  " bind K to grep word under cursor
  nnoremap K :grep! "\b<C-R><C-W>\b"<CR>:cw<CR>
  let g:ackprg = 'ag --vimgrep'
  " Allow lowercase command 'ag' - see http://vim.wikia.com/wiki/Replace_a_builtin_command_using_cabbrev
  cnoreabbrev ag <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'Ack' : 'ag')<CR>
endif

Auto-Pairs

vim.org GitHub auto-pairs Vim plugin, insert or delete brackets, parens, quotes in pair
M-e Fast wrap (e.g. (|)wrapme)
M-n Jump to next closed pair

Tested on NeoVim: undoable and dot-repeatable (.) (and should be the same on vim 7.4.849+).

Works better than ClosePairs and similar.

More auto-close plugins or similar:

Tested on NeoVim: undo broken but dot-repeatable (.).
Tested on NeoVim: undoable and dot-repeatable (.) (and should be the same on vim 7.4.849+).
breaks undo / dot-repeat (tested on neovim). Nice support of triple apostrophe.
Requires Python.
Tested on NeoVim: undo broken but dot-repeatable (.).

More on auto-close plugins:

More on the issue of dot-repeat (with list of plugins):

AutoSave

vim.org GitHub auto-pairs Automatically save changes to disk
M-e Fast wrap (e.g. (|)wrapme)
M-n Jump to next closed pair

Useful in particular when editing TeX file with continuous compilation to view changes live in PDF viewer.

Configuration
let g:auto_save = 1                 " enable AutoSave on Vim startup

" Optional:
let g:auto_save_no_updatetime = 1               " do not change the 'updatetime' option
let g:auto_save_in_insert_mode = 0              " do not save while in insert mode
let g:auto_save_silent = 1                      " do not display the auto-save notification
let g:auto_save_postsave_hook = 'TagsGenerate'  " this will run :TagsGenerate after each save

AutoTag

AutoTag : Updates entries in a tags file automatically when saving

Cpp.vim

cpp.vim: General C++ Settings (no indentation for namespace...)

(disabled highlight of leading tabs, line length overruns, unit test header test + nice AlterColour function that computes new colour...)

cpsm

GitHub cpsm A CtrlP matcher, specialized for paths.
C-p Ctrl-P file mode
C-o Ctrl-P MRU mode

To install:

sudo apt install libboost-all-dev cmake python-dev libicu-dev
cd ~/.vim/plugged/cpsm
./install.sh

Cscope_maps

SF [xeyownt/cscope_maps.vim GitHub] cscope_maps Some boilerplate settings and keyboard mappings for cscope
Leadercs ^Spaces symbol: Find all references to token, split
Leadercg ^Spaceg global: Find all global definitions, split
Leadercc ^Spacec call: Find all calls to function, split
Leaderct ^Spacet text: Find all instance of text, split
Leaderce ^Spacee egrep: egrep search, split
Leadercf ^Spacef file: open filename, split
Leaderci ^Spacei includes: Find all files that include fname, split
Leadercd ^Spaced called: Find functions that function calls, hsplit
^Space^Space s Same but vsplit
:cs f s foo Same but as command (use :scs for split)
^] Jump to symbol declaration (ctags shortcut)

Cscope page is available on SourceForge.

" Plug 'simplyzhao/cscope_maps.vim'                     " Some boilerplate settings and keyboard mappings for cscope
Plug 'xeyownt/cscope_maps.vim'                        " Some boilerplate settings and keyboard mappings for cscope

ctrlp.vim

vim.org GitHub ctrlp.vim Active fork of kien/ctrlp.vim—Fuzzy file, buffer, mru, tag, etc finder. home
^p Invoke CtrlP ^j ^k Navigate list ^z ^o Mark/unmark, open
F5 Refresh cache ^t Open new tab :diffthis Compare marked files
^f ^b Cycle between modes ^v ^x Open new split
^d Switch filename/full ^n ^p Next/prev hist
^r Switch regexp mode ^y Create new file

Currently works best using ag (this and [7]) as file scanner and cpsm as match engine.

My settings:

" Set root directory
let g:ctrlp_working_path_mode = 'rwa'

" Enable filename search (instead of full path) - Ctrl-D to switch
let g:ctrlp_by_filename = 1
"
"  Use AG for look-up. See https://robots.thoughtbot.com/faster-grepping-in-vim
if executable('ag')
  " Use ag in CtrlP for listing files. Lightning fast and DOESN'T respect .gitignore
  let g:ctrlp_user_command = 'ag %s -U -l --nocolor -g ""'

  " ag is fast enough that CtrlP doesn't need to cache - BUT we are on a slow filesystem
  " let g:ctrlp_use_caching = 0
endif

DoxygenToolkit.vim

GitHub DoxygenToolkit.vim Simplify Doxygen documentation in C, C++, Python
:Dox Fill doxygen for function declaration.

My configuration

" --- DoxygenToolkit --------------------------------------------------------------------------{{{
let g:DoxygenToolkit_briefTag_pre="@Synopsis  "
let g:DoxygenToolkit_paramTag_pre="@Param "
let g:DoxygenToolkit_returnTag="@Returns   "
let g:DoxygenToolkit_blockHeader="--------------------------------------------------------------------------"
let g:DoxygenToolkit_blockFooter="----------------------------------------------------------------------------"
let g:DoxygenToolkit_authorName="Michael Peeters"
" let g:DoxygenToolkit_licenseTag=""

FastFold

GitHub FastFold Speed up Vim by updating folds only when called-for
zuz Force fold update (same as :FastFoldUpdate)
Plug 'Konfekt/FastFold'                               " Speed up Vim by updating folds only when called-for

Fugitive

vim.org GitHub fugitive.vim A Git wrapper so awesome, it should be illegal

Add to .vimrc:

set diffopt+=vertical                       " Favor vertical split for vimdiff
Some commands
" Gdiff
:Gdiff                                      " View differences with index
:Gdiff HEAD                                 " View differences with HEAD
:Gdiff -                                    " View differences with HEAD
:Gdiff ^                                    " View differences with previous commit
:Gdiff ~3                                   " View differences with 3 commits ago

" Glog
:Glog                                       " Load previous file revision in quickfix. :cn / :cp for next/previous
:Glog -- %                                  " Load commits (i.e. diff) impacting current file.
:Glog -Sfindme --                           " Pickaxe string 'findme'

" Gedit
:Gedit                                      " Edit back current file
Typical workflow
  • View history of changes on a file
:Glog                                       " Load previous file revision in quickfix
:cn                                         " next revision (or open quickfix window and <CR> to select)
:cp                                         " previous revision (or open quickfix window and <CR> to select)
:Gdiff                                      " View diff with version in work tree
:q                                          " Quit diff, and return to selected revision
:Gdiff ^                                    " View diff with previous version
:q
:Gedit                                      " Edit back original file

fzf.vim

GitHub fzf.vim fzf :heart: vim
C-p Ctrl-P file mode
C-o Ctrl-P MRU mode
Neovim

fzf.vim uses neovim terminal emulator. Use this mapping to have esc key leave fzf, but go to normal mode in other terminals [8]:

tnoremap <expr> <esc> &filetype == 'fzf' ? "\<esc>" : "\<c-\>\<c-n>"

IndentTab

vim.org GitHub IndentTab Use tabs for indent at the beginning, spaces for alignment in the rest of a line

This plugin works better than Smart-Tabs (ctab.vim).

See also Indent with tabs & align with spaces.

Configuration

We must make sure that it is loaded before plugin SuperTab (so that the latter can record IndentTab maps for Tab).

Plug 'xeyownt/IndentTab' |                            " Use tabs for indent at the beginning, spaces for alignment in the rest of a line
    Plug 'ervandew/supertab'                          " Perform all your vim insert mode completions with Tab
" --- IndentTab -------------------------------------------------------------------------------{{{
let g:IndentTab = 1                                 " Enable the plugin
let g:IndentTab_IsSuperTab = 1                      " Enable integration with supertab
let g:IndentTab_scopes = 'indent'                   " Disable 'commentprefix' and 'string', which require ingo-library
" }}}

MatchIt

matchit.zip : extended % matching for HTML, LaTeX, and many other languages

Mcf-make-target

mcf-make-target: Persistent make target in Vim This plugin lets Vim to store the last arguments passed to make, and use that argument when make is invoked without arguments. For ease, define the following macro:

:nmap <F5> :wa<CR>:Make<CR>:cw<CR>             # Note the capital M to Make

To build a custom target:

:Make <targetname>           # first invocation. Store targetname for future use
<F5>                         # next

Repeat

Install repeat.vim : Use the repeat command (.) with supported plugins

SparkUp

Sparkup — A parser for a condensed HTML format Use ^e in edit mode to extend sparkup text, and ^n to go to next empty item. Some examples (more at Zen Coding:

div#page.section.main
div[title]
a[title="Hello world" rel]
td[colspan=2]
ul > li*5
li.item$$$*3
div#page>(div#header>ul#nav>li*4>a)+(div#page>(h1>span)+p*2)+div#footer
#content>.section
div#content>div.section
p>{Click }+a{here}+{ to continue}

Supertab

vim.org GitHub Supertab Perform all your vim insert mode completions with Tab
Tab Complete, insert
Plug 'ervandew/supertab'                          " Perform all your vim insert mode completions with Tab
" --- SuperTab---------------------------------------------------------------------------------{{{
let g:SuperTabDefaultCompletionType    = '<C-n>'
let g:SuperTabCrMapping = 0
" }}}
Issues
  • Tab does not work in vimwiki files
This is because Tab is mapped by vimwiki plugin to jump to next table cell. The best work-around is to use C-n / C-p to trigger YCM completion. Alternative we can disable table mapping [9]
let g:vimwiki_table_mappings = 0

Surround

vim.org GitHub Surround quoting/parenthesizing made simple.
cs"' Change surrounding " to '
cs'<q> Change surrounding ' to <q>...</q>
cst" Change surrounding tag back to "
ds" Remove the surrounding "
ysiw] Add [ ] around word (motion iw)
yssb yss) Add ( ) around current line (ignoring leading ws)
VmS<p id="a"> Add surrounding tag to selected lines
ysibspace Add surrounding blank inside current () block
Plug 'tpope/vim-surround'                             " quoting/parenthesizing made simple.
" --- Vim-Surround ----------------------------------------------------------------------------{{{
" Use lowercase 's' instead of 'S' to surround in visual mode
xmap s      <Plug>VSurround
" }}}

tComment

vim.org GitHub tComment An extensible & universal comment plugin that also handles embedded filetypes
gcm Toggle comments motion
gcc Toggle comment for the current line
gCm Comment region motion
gCc Comment the current line
Plug 'tomtom/tcomment_vim'                            " An extensible & universal comment vim-plugin that also handles embedded filetypes

Ultisnips

GitHub ultisnips UltiSnips - The ultimate snippet solution for Vim. Send pull requests to SirVer/ultisnips!
GitHub vim-snippets vim-snipmate default snippets (Previously snipmate-snippets)
^J Expand snippet / go to next placeholder
^K Go to previous placeholder

Ultisnips is a snippet engine written in Python. Other snippet plugins:

Configuration
  • We configure ultisnips to use ^J / ^K for expansion and next/previous, and leave Tab key for completion with plugin SuperTab (which will trigger YouCompleteMe as well).
  • Another option is to use Tab for expansion (see these posts for instance).
" --- Ultisnips / vim-snippets-----------------------------------------------------------------{{{
" Use C-j/C-k for snippet expansion and next/previous.
" To use 'tab', see https://github.com/christoomey/dotfiles/blob/master/vim/rcplugins/youcompleteme-ultisnips-supertab
let g:UltiSnipsEditSplit = 'vertical'
let g:UltiSnipsExpandTrigger = '<C-j>'
let g:UltiSnipsJumpForwardTrigger = '<C-j>'
let g:UltiSnipsJumpBackwardTrigger = '<C-k>'
Writing snippets
  • Use command :UltiSnipsEdit to start editing snippets for current filetype.
This will automatically opens a private snippet definition file for the current filetype. Use :UltiSnipsEdit! to add snippet in public definition files.
  • For advanced snippets (Python, auto-expand, use of context), see LaTeX snippets from Gilles Castel.
Snippets

Snippets must be installed separately. Some snippets from vim-snippets:

#### C ####
main  main()
inc   #include <...>
Inc   #include "..."
Def   #ifndef ... #define ... #endif
def   #define
ifdef #ifdef ... #endif
#if   #if ... #endif
once  #ifndef HEADER_H .... # define HEADER_H ... #endif (Header Include-Guard)
if    If (...) { ... }
el    else { ... }
t     ... ? ... : ... (tertiary conditional)
do    do ... while ( ... )
wh    while (...) { ... }
for   for (... = 0; ...; ...) { ... }
forr  for (... = ...; ...; ...) { ... }
fun   ... function(...) { ... }
fund  ... function(...;)
td    typedef
st    struct
tds   typedef struct
tde   typedef enum
pr    printf
fpr   fprintf
.     [ ... ]
un    unsigned
#### C++ ####
readfile  snippet for reading file
map       std::map<... , ...> map...
vector    std::vector<...> v...
ns        namespace ... { ... }
cl        class { public: ... private: };

vim-airline

GitHub vim-airline lean & mean status/tabline for vim that's light as air
GitHub vim-airline-themes A collection of themes for vim-airline

vim-airline-themes is optional, and here not needed since I use gruvbox for the theme.

" ----- Vim-airline ----------------------------------------------------------
let g:airline_theme= 'gruvbox'
let g:airline_section_c = '%F'
let g:airline_section_y = ''
let g:airline_section_error = ''
let g:airline_section_warning = ''
let g:airline_section_x = ''

Vim-auto-save

GitHub vim-auto-save Automatically save changes to disk
Configuration
let g:auto_save = 1                 " enable AutoSave on Vim startup
let g:auto_save_no_updatetime = 1   " do not change the 'updatetime' option
let g:auto_save_in_insert_mode = 0  " do not save while in insert mode
let g:auto_save_silent = 1          " do not display the auto-save notification

Vim-easy-align

GitHub vim-easy-align A Vim alignment plugin
gaip*= Auto-align around all occurences of =
:%EasyAlign /;;/ Align on ;;. This allows using any delimiter.

Vim-easymotion

vim.org GitHub vim-easymotion Vim motions on speed!
\\w \\f Horizontal move
\\j \\k Vertical move
Example configuration
" <Leader>f{char} to move to {char}
map  <Leader>f <Plug>(easymotion-bd-f)
nmap <Leader>f <Plug>(easymotion-overwin-f)

" s{char}{char} to move to {char}{char}
nmap s <Plug>(easymotion-overwin-f2)

" Move to line
map <Leader>L <Plug>(easymotion-bd-jk)
nmap <Leader>L <Plug>(easymotion-overwin-line)

" Move to word
map  <Leader>w <Plug>(easymotion-bd-w)
nmap <Leader>w <Plug>(easymotion-overwin-w)

Vim-gitgutter

GitHub vim-gitgutter A Vim plugin which shows a git diff in the gutter (sign column) and stages/undoes hunks

Vim-incsearch

 ❗  vim-incsearch is dead and create conflicts. Core is now part of vim/neovim. Use vim-is instead for extra features.
vim.org GitHub incsearch.vim Improved incremental searching for Vim
GitHub incsearch-easymotion.vim Integration between incsearch and easymotion
Tab Move cursor to next match
S-Tab Move cursor to previous match

See website for more features (including fuzzy search, etc.).

Integration with easy-motion
" You can use other keymappings like <C-l> instead of <CR> if you want to
" use these mappings as default search and somtimes want to move cursor with
" EasyMotion.
function! s:incsearch_config(...) abort
  return incsearch#util#deepextend(deepcopy({
  \   'modules': [incsearch#config#easymotion#module({'overwin': 1})],
  \   'keymap': {
  \     "\<CR>": '<Over>(easymotion)'
  \   },
  \   'is_expr': 0
  \ }), get(a:, 1, {}))
endfunction

noremap <silent><expr> /  incsearch#go(<SID>incsearch_config())
noremap <silent><expr> ?  incsearch#go(<SID>incsearch_config({'command': '?'}))
noremap <silent><expr> g/ incsearch#go(<SID>incsearch_config({'is_stay': 1}))

Vim-LaTeX

vim-latex (documentation) See page vim-latex.

vim-mundo

GitHub vim-mundo Vim undo tree visualizer https://simnalamburt.github.io/vim-mundo
F12 Open mundo

vim-mundo is a fork of plugin gundo (originally written by Steve Losh) that is up-to-date and works on neovim.

" --- Vim-mundo -------------------------------------------------------------------------------{{{
let g:mundo_verbose_graph = 0               " Create shorter graph
let g:mundo_inline_undo = 1                 " Show a small one line diff at each node
set undofile                                " Enable persistent undo so that undo history persists across vim sessions
set undodir=~/.vim/undo
nnoremap <F12> :MundoToggle<CR>
" }}}

vim-ps1

GitHub vim-ps1 A Vim plugin for Windows PowerShell support
Plug 'PProvost/vim-ps1'                          " A Vim plugin for Windows PowerShell support
" --- PS1.vim ---------------------------------------------------------------------------------{{{
" Source: https://robindouglas.uk/powershell/vim/2018/04/05/PowerShell-with-Vim.html
if has('win32')
    set shell=powershell.exe
    set shellcmdflag=-NoProfile\ -NoLogo\ -NonInteractive\ -Command
    set shellpipe=|
    set shellredir=>
endif
" }}}
Troubleshooting
  • Bad indentation of closing braces: check that equalprg is not set in .vimrc.

Vimtex

See also Vim-tex for usage.

GitHub vim-mundo A modern vim plugin for editing LaTeX files. (wiki)

Delete / change surrounding...

Text objects...

dsc csc command ic ac Commands
id ad Delimiters
dse cse environment ie ae LaTeX environments
ds$ cs$ math structure i$ a$ Inline math structures
tsd Toggle delimiters, eg. () / \left(\right)
]] (insert) Close current environment/delimiter
F7 Insert new command
:VimtexImapsList View current insert-mode mappings.
Install (using Plug)
  • Add to .vimrc
Plug 'lervag/vimtex'                       " A modern vim plugin for editing LaTeX files.
pip3 install neovim-remote
Configuration
" --- VimTex ----------------------------------------------------------------------------------{{{
" Inspired from https://castel.dev/post/lecture-notes-1/
let g:tex_flavor='latex'
let g:vimtex_view_method='zathura'
let g:vimtex_quickfix_mode=0
set conceallevel=1
let g:tex_conceal='abdmg'
if has('nvim')
  let g:vimtex_compiler_progname='nvr'
endif
" }}}

In addition, the following helps for insert-mode mappings:

imap ² `

Install vim-auto-save plugin to save the file and trigger compilation regularly.

VimWiki

vim.org GitHub vimwiki Personal Wiki for Vim
S-CR Continue list
gq Quote text block with {{{ ... }}}

To quote a text block with {{{ ... }}} in visual mode, add to ~/.vim/ftplugin/vimwiki_custom.vim:

" Quote a block of text with {{{ }}} in visual mode
:vmap gq DO {{{<CR><ESC>P
Troubleshooting
  • Tab not working anymore on dev branch. This is because tab is already mapped by plugin SuperTab, and Vimwiki refuses to remap.
--- a/ftplugin/vimwiki.vim
+++ b/ftplugin/vimwiki.vim
@@ -532,13 +532,9 @@ endfunction

 " insert mode table mappings
 if str2nr(vimwiki#vars#get_global('key_mappings').table_mappings)
-  if maparg('<Tab>', 'i') ==# ''
   inoremap <expr><buffer> <Tab> vimwiki#tbl#kbd_tab()
-  endif
-  if maparg('<S-Tab>', 'i') ==# ''
   inoremap <expr><buffer> <S-Tab> vimwiki#tbl#kbd_shift_tab()
 endif
-endif
  • Exception not caught: VimwikiTags5: Metadata file corrupted" [10]
The fix is simply to delete the file vimwiki/.vimwiki_tags, and optionally run the command :VimwikiRebuildTags.

YouCompleteMe

GitHub YouCompleteMe A code-completion engine for Vim http://valloric.github.io/YouCompleteMe/
  • Fast fuzzy auto-completion engine (suggest as you type).
  • Semantic completion using clang.
  • Instant diagnostics (errors and warnings reporting).
^n Next completion (also Tab using SuperTab plugin)
^p Previous completion (also S-Tab using SuperTab plugin)
:YcmDiags Fill location lists with current error and warnings.
:YcmCompleter FixIt Fix current warning / error.
Installation
cd .vim/plugged/YouCompleteMe
./install.py
Configuration (without semantic completion)
  • We don't configure YCM to use Tab for completion but the usual vim's map ^n and ^p.
  • Instead, we install SuperTab plugin, which will also trigger YCM completion with Tab and S-Tab (thanks Christoomey).
Plug 'Valloric/YouCompleteMe', { 'do': './install.py' } " A code-completion engine for Vim

" ...

" --- YouCompleteMe----------------------------------------------------------------------------{{{
let g:ycm_autoclose_preview_window_after_completion = 1 " Auto-close preview window on completion

let g:ycm_dont_warn_on_startup = 0
let g:ycm_complete_in_comments = 1
let g:ycm_complete_in_strings = 1
let g:ycm_collect_identifiers_from_comments_and_strings = 1

let g:ycm_filetype_blacklist = {}

let g:ycm_key_list_select_completion   = ['<C-n>', '<Down>']
let g:ycm_key_list_previous_completion = ['<C-p>', '<Up>']
" Bug workaround - avoid spurious scrolling on completion when typing '.'
let g:ycm_filetype_specific_completion_to_disable = {
      \ 'cpp': 1,
      \ 'gitcommit': 1
      \}
" }}}
Configuration (semantic completion)

Add the default compilation flags files (see manual for more details [11]):

# file .ycm_extra_conf_cpp.py
def FlagsForFile( filename, **kwargs ):
  return {
    'flags': [ '-x', 'c++', '-std=gnu++14', '-Wall', '-Wextra', '-Werror', '-I.', '-Iinclude', '-I../include' ],
  }
# file .ycm_extra_conf_c.py
def FlagsForFile( filename, **kwargs ):
  return {
    'flags': [ '-x', 'c', '-gnu11', '-Wall', '-Wextra', '-Werror', '-I.', '-Iinclude', '-I../include' ],
  }

Then in .vimrc:

-Plug 'Valloric/YouCompleteMe', { 'do': './install.py' } " A code-completion engine for Vim
+Plug 'Valloric/YouCompleteMe', { 'do': './install.py  --clang-completer' } " A code-completion engine for Vim
-let g:ycm_filetype_specific_completion_to_disable = {
-      \ 'cpp': 1,
-      \ 'gitcommit': 1
-      \}
+let g:ycm_global_ycm_extra_conf = "~/.vim/.ycm_extra_conf.py"
 ❗  Care must be taken with space in the option list. When using clang options like -I, -iquote the directory argument can be collated to the flag, like in '-Iinclude', or '-iquoteinclude', . Alternatively the flag and argmument must be split on two array element ('-iquote', 'include'). But '-iquote include', doesn't work.
Project-specific configuration

YCM can use project-specific compilation flags to report warnings / errors that are relevant to your project. YCM can either use a compilation database (such as BEAR, cmake, ninja...), or use manually defined flags. For the latter, just define a file .ycm_extra_conf.py in the root of your project:

import os

def IsCPPFile(filename):
  extension = os.path.splitext(filename)[1]
  return extension in ['.cpp','.cxx','.hpp','.hxx']

FLAGS_CPP = [ \
        '-x', 'c++', '-Wall', '-Werror', '-std=gnu++14', '-funsigned-char', '-fshort-enums', '-fno-common', \
        '-I.', '-Iinclude', '-I../include' \
        ]

FLAGS_C = [ \
        '-x', 'c', '-Wall', '-Werror', '-std=gnu11', '-funsigned-char', '-fshort-enums', '-fno-common', \
        '-I.', '-Iinclude', '-I../include' \
        ]

def FlagsForFile( filename, **kwargs ):
  return { 'flags': FLAGS_CPP } if IsCPPFile(filename) else { 'flags': FLAGS_C }
Configuration - offline install
  • When installing on a computer without internet access, transfer the file clang+llvm-5.0.0-linux-x86_64-ubuntu14.04.tar.xz from ~/.vim/plugged/YouCompleteMe/third_party/ycmd/clang_archives/ manually.

VisIncr

vim.org GitHub VisIncr Produce increasing/decreasing columns of numbers, dates, or daynames
:I [#] Increment by 1 (or by #)
:II [#] Justified increment by 1 (or by #)
:IX [#] Increment (hex) by 1 (or by #)
:IIX [#] Justified increment (hex) by 1 (or by #)

More tips about visual increment here.

Visual-increment

GitHub visual-increment.vim use CTRL+A/X to create increasing sequence of numbers or letters via visual mode
^A Increment
^X Decrement

Plugins to try

Language Server

  • coc.nvim — Intellisense engine for vim8 & neovim, full language server protocol support as VSCode
Related posts [12]
To be combined with deoplete, and UltiSnips [13].

Misc

Plugins I need to try or install some day.

  • Other completion plugins, but probably not as good as YouCompleteMe (which also integrates nicely with Ultisnips and SuperTab)
vim.org OmniCppComplete C/C++ omni-completion with ctags database
vim.org neocomplcache Ultimate auto completion system for Vim
  • autoswap.mac (manage automatically swap file — Mac only)
  • vmath.mac (compute sums, averages, min and max)
  • vis.vim (let : commands to act on visual blocks, not the full lines)
  • visualdrags (allows moving / duplicate visual)
An extended version of closetag.vim. Press ^_ to automatically close current tag (HTML, XML, LaTeX...)
Currently using custom mapping / autocmd (see below).
  • syntastic — Syntax checking hacks for vim
  • diffchar.vim — Highlight the exact differences, based on characters and words

Tim Pope

Plugins from Tim Pope:

However tComment seems more complete, and works fine for me.
vim.org GitHub vim-rsi TRY_ME rsi.vim: Readline style insertion
vim.org GitHub vim-abolish abolish.vim: easily search for, substitute, and abbreviate multiple variants of a word
vim.org GitHub vim-obsession obsession.vim: continuously updated session files
GitHub vim-ragtag ragtag.vim: ghetto HTML/XML mappings (formerly allml.vim)
A set of mappings for HTML, XML, PHP, ASP, eRuby, JSP, and more (formerly allml)

Videos

Some videos that illustrates those plugins:

vim.org GitHub unimpaired.vim Pairs of handy bracket mappings
For interaction with plugin fugitive, and quickfix mappings [q, ]q, [Q, and ]Q.
vim.org GitHub ifdef-highlighting #ifdef highlighting in c/c++/idl
GitHub VimFold4C Vim folding ftplugin for C & C++ (and similar langages)

Interesting plugin, but does not handle well nested #ifdef it seems.

GitHub GoldenView.Vim Always have a nice view for vim split windows! http://zhaocai.github.io/GoldenView.Vim/
Doxygen support

Uninstalled plugins

Plugins I'm no longer using (with uninstalled date/year when available).

Align

vim.org GitHub Align Help folks to align text, eqns, declarations, tables, etc
see examples.

Let's give vim-easy-align a try instead.

AutoClose

vim.org GitHub AutoClose Inserts matching bracket, paren, brace or quote
Plugin - autoclose

{{

Insert & push closing brace down a new line

Don't like it much because inserting the closing pair will jump out of nested pair, which is annoying when one try to simply insert a closing brace (but a solution is to use the Surround plugin to surround some selected text with braces).

Calendar

calendar.vim - A calendar application for Vim

  • :Calendar to launch. < and > to cycle through views, E and T to view Event list or Task list.
  • :Calendar 2001 1 1 to focus a specific date.

My settings in .vimrc:

" ----- Vim-Calendar ---------------------------------------------------------
let g:calendar_week_number=1
let g:calendar_first_day='monday'

ClosePairs

vim.org GitHub ClosePairs Auto closes pairs of characters

simpler than AutoClose, and can also delete pair of braces at once with <BS>. However breaks undo and not dot-repeatable.

Below is a patch to push down the closing brace when typing { twice (inspired from AutoClose plugin).

Conque Shell

vim.org GitHub Conque Shell Run interactive commands inside a Vim buffer.

I'm using mostly NeoVim now, and neovim native command :term offers a much better alternative.

DiffChanges

diffchanges.vim : Show changes made to current buffer since the last save

  • Never used. Functionality quite limited (only compared with last save). And if file is stored in Git, plugin fugitive is a much better alternative.
Plugin - diffchanges

Leaderdcd
Leaderdcp

DiffChangesDiffToggle
DiffChangesPatchToggle

EasyTags

easytags.vim : Automated tag file generation and syntax highlighting of tags in Vim

  • Replaced by AutoTag — syntax highlighting of tags is limited to c files; moreover AutoTag has a clever way to look for the tags file in project hierarchy.

FuzzyFinder (2016)

FuzzyFinder : buffer/file/command/tag/etc explorer with fuzzy matching

  • Alternative, Command-T (inspired from TextMate)
  • See also Super-Finder in Vim (using FuzzyFinder)
  • After :set path=/path/to/project/**, one can do :find filename.ext (See [14], more details at [15])
  • To find a file in a sub-directory, use the fuzzy query **/filename

Removed because superseeded by fzf.vim.

Troubleshooting
  • FuzzyFinder plugin complains about:
Error detected while processing function 148..229..fuf#openTag:
line    1:
E432: Tags file not sorted: tags
Tags were generated with ctags --sort=foldcase -R .
Solution is to set option :set ignorecase

Git-file

git:file.vim : open any version of a file in git For instance, to open file filename.c at commit HEAD~4:

vim HEAD~4:./filename.c
  • Never used. Similar functionality available in plugin fugitive.

Hexman

vim.org GitHub Hexman Simpler Hex viewing and editing

Uninstalled because it contains the sign of the devil... Well, no, in fact because I don't use it much and standard mappings interfere with vim-gitgutter.

LaTeX Text Formatter

Latex Text Formatter : This scripts makes it easier to format latex text

  • Does not work well (line too short, line merge too aggressive)

LustyExplorer (2016)

vim.org GitHub LustyExplorer Dynamic filesystem and buffer explore
More recent GitHub (merged with LustyJuggler)

Removed because frequent segfaults in Neovim. Superseeded by fzf.vim.

LustyJuggler

vim.org GitHub LustyJuggler Switch very quickly among your active buffers
More recent GitHub (merged with LustyExplorer

Removed because I don't use it. LustyExplorer, NERDTree and FuzzyFinder are much better alternatives.

MiniBufExpl

minibufexpl.vim : Elegant buffer explorer - takes very little screen space

  • 1st attempt: No real tab support. Seems to interfere with trinity plugin. Interesting key bindings inside though. To reassess...
  • 2nd attempt: Don't care about tabs, the idea is to fully replace tabs with buffers since most plugins interface better with buffers. Disabled

trinity plugin.

  • Closing a buffer: Use d in minibufexpl window to close a buffer, or :bd[elete] seems to work most of the time.
  • Uninstalled because found better alternative (bufstat)

MRU

mru.vim : Plugin to manage Most Recently Used (MRU) files

  • Never used. And same functionality is available in Ctrl-P plugin anyway.
Plugin - MRU

:MRU
:MRU p
CR
o
t
v

Open MRU file list
Open MRU file list, only files containing p
Open file in previous window if possible
Open file in a new window
Open file in a new tab
Open file read-only (view)


Trinity.vim (2011)

trinity.vim : Build the trinity of srcexpl, taglist, NERD_tree to be a good IDE

Plugin - taglist window (:help taglist-keys)

[[ or BS
]] or Tab
Space
- or zc
+ or zo
* or zR
= or zM
x
CR or LMouse*2
o O
P
p
t
u
s

Previous file
Next file
Show tag prototype
Close a fold
Open a fold
Open all folds
Close all folds
Maximimze/Restore window
Jump to tag location
Jump to tag location (new window, vertical)
Jump to tag location (in previous window)
tag preview (cursor remains in taglist window)
Jump to tag (new tab)
Update tags
Change the sort order

vim-bufferline (2017)

GitHub vim-bufferline Super simple vim plugin to show the list of buffers in the command bar

Beware that airline interferes with bufferline settings. My settings below.

" ----- Vim-bufferline -------------------------------------------------------

let g:bufferline_rotate = 1                " scrolling with fixed current buffer position
let g:bufferline_show_bufnr = 0            " Do not display buffer numbers
let g:bufferline_active_buffer_left = '['  " Separator used on the left side of current buffer
let g:bufferline_active_buffer_right = ']' " Separator used on the right side of current buffer

let g:airline#extensions#bufferline#overwrite_variables = 0

Loved it, but unfortunately was hiding Vim messages and YCM semantic completion messages (errors/warnings). Trying to live without it...

Vim BufStat (2016)

Vim BufStat

" GRB: use fancy buffer closing that doesn't close the split
cnoremap <expr> bd (getcmdtype() == ':' ? 'Bclose' : 'bd')

Replaced by vim-airline and vim-bufferline.

Vim-is

GitHub is.vim is.vim - incremental search improved
Tab Move cursor to next match
S-Tab Move cursor to previous match

Disabled because did not like the loss of highlight on move. I'm using this feature a lot to locate quickly some identifiers in files.