SidOfc / mkdx

A vim plugin that adds some nice extra's for working with markdown documents
https://www.vim.org/scripts/script.php?script_id=5620
MIT License
482 stars 13 forks source link

Question: is anything needed to enable the plugin? #102

Closed al3xandru closed 4 years ago

al3xandru commented 4 years ago

This will probably sounds a little odd, but after adding the plugin to my .vimrc and installing it, I cannot tell if the plugin is actually active or not.

  1. When inside a list, Enter in insert mode or o in normal does not create a new item
  2. <Prefix>t doesn't seem to check a checkbox
  3. but :echo g:mkdx#settings displays a bunch of settings.

How can I check if the plugin is active?

SidOfc commented 4 years ago

Hi @al3xandru,

Thank you for reporting! Does nothing work, or only some mappings? It's a good thing you checked for g:mkdx#settings, this means that at least the mappings and settings do get loaded.

It could depend on your plugin manager, which one do you use? If you've manually installed it I'd need more info as to which files you copied.

In any case, mkdx does not step on user-defined mappings, so if only some functionality seems to "not work" there is probably a mapping defined by some other plugin which will prevent mkdx from actually mapping it, these can be checked with :verbose map <prefix>t where you replace <prefix> with the actual prefix key you use.

Perhaps, loading mkdx as the first plugin will allow it to map more keys, this could be an easy way to check if more functionality gets enabled then. (this is never true since mappings are loaded after entering markdown buffers, thus always last-in-slot)

I'd love to hear the results on any of the above, thanks for trying mkdx and hopefully the above can solve / narrow down the issue :)

SidOfc commented 4 years ago

Hi again @al3xandru, I made an edit to my previous comment since the section about loading mkdx first will not do anything actually, my bad there!

al3xandru commented 4 years ago

Thanks for the follow up. As I don't really know how to start tracking this I will take it step by step.

  1. echo g:mkdx#settings.enter.enable -> 1
  2. echo g:mdx#settings.tokens.enter -> ['-', '*', '>']

Given the above, my expectation was that while in a list item (or inside a blockquote), pressing enter would automatically add the prefix character to the next line.

  1. This is not happening.
  2. If I invoke :call mkdx#ToggleList(), the function is invoked and text updated.

This makes me thing that while the plugin is active, bindings are not working. Any ideas what I should check next?

al3xandru commented 4 years ago

Next experiment. I have added the following settings in my .vimrc:

let g:mkdx#settings.map.prefix = '<localleader>'
let g:mkdx#settings.tokens.italic = '_'

After reloading, restarting:

echo g:mkdx#settings.map.prefix 
<leader>
echo g:mkdx#settings.tokens.italic
*

When starting vim from Terminal:

Error detected while processing ~/.vimrc:
line 1023:
E121: Undefined variable: g:mkdx#settings
line 1025:
E121: Undefined variable: g:mkdx#settings
Press ENTER or type command to continue

I'm using vim-plug as a plugin manager.

SidOfc commented 4 years ago

Hi @al3xandru,

that is strange indeed, it's the first time I'm hearing of the issue that the settings are undefined :thinking:. Which kind of "Vim" are you using? Also, which version of Vim/Nvim/Gvim are you using? Where did you put the settings (did you place them below call plug#end())?

Also, can you try other mappings? Like try to mark something as bold using <leader>b? Please try more than one different mapping to see if some things do work (we already know enter doesn't, what about other functionality?), I've documented all of them here.

Can you post results of some :verbose map commands you ran while editing a markdown file?

Could you try :verbose imap <cr> for example? This should show you something like: image This shows that <Plug>(mkdx-enter) is indeed mapped to <cr> in my case.

Seeing as you mentioned that o also doesn't work, could you post :verbose nmap o too?: image

I don't think it is an issue with mkdx, since it's a pretty unique issue and I've already handled quite a few issues before, it could be that you're using an older vim/nvim/gvim which won't work, in which case I'd need to update docs to inform users.

It is also likely that these mappings are already being overridden by some other plugin, can you test mkdx in isolation, e.g disable all other plugins except mkdx and see if that makes a difference?

Keep me posted whenever you have had time to investigate, looking forward to a response. I must mention though that there isn't much else I can do but guess. If you could share your vimrc file I can try it out for myself and see if I can get things to work that way, this may be faster than trying to ask for specific details and I'm willing to give it a shot :)

al3xandru commented 4 years ago

I didn't know about the :verbose map command. Thank you.

Both are returning the mkdx binding. The mystery continues.

My .vimrc: https://github.com/al3xandru/dotfiles/blob/vimplug/.vimrc


I don't know of any ways to try a plugin in isolation. Can you point me towards anything?


You asked above about versions:

vim (built from source):

:version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled May  8 2020 19:30:16)
macOS version
Included patches: 1-717
Compiled by alex@202005081928/7d131b071
Huge version without GUI.  Features included (+) or not (-):
+acl               +cmdline_info      -farsi             +langmap           +mouse_sgr         +profile           +tag_binary        +virtualedit
+arabic            +comments          +file_in_path      +libcall           -mouse_sysmouse    +python/dyn        -tag_old_static    +visual
+autocmd           +conceal           +find_in_path      +linebreak         +mouse_urxvt       +python3/dyn       -tag_any_white     +visualextra
+autochdir         +cryptv            +float             +lispindent        +mouse_xterm       +quickfix          -tcl               +viminfo
-autoservername    +cscope            +folding           +listcmds          +multi_byte        +reltime           +termguicolors     +vreplace
-balloon_eval      +cursorbind        -footer            +localmap          +multi_lang        +rightleft         +terminal          +wildignore
+balloon_eval_term +cursorshape       +fork()            +lua/dyn           -mzscheme          -ruby              +terminfo          +wildmenu
-browse            +dialog_con        -gettext           +menu              +netbeans_intg     +scrollbind        +termresponse      +windows
++builtin_terms    +diff              -hangul_input      +mksession         +num64             +signs             +textobjects       +writebackup
+byte_offset       +digraphs          +iconv             +modify_fname      +packages          +smartindent       +textprop          -X11
+channel           -dnd               +insert_expand     +mouse             +path_extra        -sound             +timers            -xfontset
+cindent           -ebcdic            +ipv6              -mouseshape        +perl/dyn          +spell             +title             -xim
-clientserver      +emacs_tags        +job               +mouse_dec         +persistent_undo   +startuptime       -toolbar           -xpm
+clipboard         +eval              +jumplist          -mouse_gpm         +popupwin          +statusline        +user_commands     -xsmp
+cmdline_compl     +ex_extra          +keymap            -mouse_jsbterm     +postscript        -sun_workshop      +vartabs           -xterm_clipboard
+cmdline_hist      +extra_search      +lambda            +mouse_netterm     +printer           +syntax            +vertsplit         -xterm_save

Macvim (latest):

:version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Apr 18 2020 12:38:50)
macOS version
Included patches: 1-539
Compiled by alex@202004181237@5de428cde
Huge version with MacVim GUI.  Features included (+) or not (-):
+acl               +dnd               +listcmds          +popupwin          +termresponse
+arabic            -ebcdic            +localmap          +postscript        +textobjects
+autocmd           +emacs_tags        +lua/dyn           +printer           +textprop
+autochdir         +eval              +menu              +profile           +timers
-autoservername    +ex_extra          +mksession         +python/dyn        +title
+balloon_eval      +extra_search      +modify_fname      +python3/dyn       +toolbar
+balloon_eval_term -farsi             +mouse             +quickfix          +transparency
+browse            +file_in_path      +mouseshape        +reltime           +user_commands
++builtin_terms    +find_in_path      +mouse_dec         +rightleft         +vartabs
+byte_offset       +float             -mouse_gpm         -ruby              +vertsplit
+channel           +folding           -mouse_jsbterm     +scrollbind        +virtualedit
+cindent           -footer            +mouse_netterm     +signs             +visual
+clientserver      +fork()            +mouse_sgr         +smartindent       +visualextra
+clipboard         +fullscreen        -mouse_sysmouse    -sound             +viminfo
+cmdline_compl     -gettext           +mouse_urxvt       +spell             +vreplace
+cmdline_hist      -hangul_input      +mouse_xterm       +startuptime       +wildignore
+cmdline_info      +iconv             +multi_byte        +statusline        +wildmenu
+comments          +insert_expand     +multi_lang        -sun_workshop      +windows
+conceal           +job               -mzscheme          +syntax            +writebackup
+cryptv            +jumplist          +netbeans_intg     +tag_binary        -X11
+cscope            +keymap            +num64             -tag_old_static    -xfontset
+cursorbind        +lambda            +odbeditor         -tag_any_white     +xim
+cursorshape       +langmap           +packages          -tcl               -xpm
+dialog_con_gui    +libcall           +path_extra        +termguicolors     -xsmp
+diff              +linebreak         +perl/dyn          +terminal          -xterm_clipboard
+digraphs          +lispindent        +persistent_undo   +terminfo          -xterm_save
victorkristof commented 4 years ago

For the record, I get the same error when sourcing my vimrc once a markdown file is loaded in a buffer. The plugin works fine except from that.

victorkristof commented 4 years ago

I don't know of any ways to try a plugin in isolation. Can you point me towards anything?

@al3xandru You could try to disable all the settings you have for Markdown in your config, except for mkdx: comment out everything between line 1012 and 1136 in your vimrc linked above, but keep line 1022.

Run

:PlugClean
:PlugUpdate

and restart Vim.

Does it work now?

SidOfc commented 4 years ago

Thank you @al3xandru for your reply, I will check it out ASAP (got friends over tonight so will be tomorrow at best), well done on confirming that mkdx bindings are in fact mapped as well, this means it could be a bug in mkdx's enter handler (hope not though, ugliest code I ever wrote hehe :sweat_smile:).

And also @victorkristof thank you for checking this out and finding out what causes the g:mkdx#settings error upon resourcing the vimrc file. Indeed this is an edge case which could probably be guarded against by checking if !exists('g:mkdx#settings') | g:mkdx#settings = ... | endif.

Much appreciated feedback from both of you, I will try the vimrc when I can and report back :+1:

al3xandru commented 4 years ago

While I cannot offer a comprehensive confirmation of what works and what not, I'd say that:

  1. majority of bindings work. The default prefix being <leader> increases the chances for conflicts. As a suggestion, would it be safer to make the prefix localleader instead?

  2. what I cannot get to work is list completion on Enter and o. Amazingly, O works :-).

2.1 :verbose map displays the correct bindings for all 3 of them.

2.2 Looking at the code there seem to be significant difference between mkdx#OHandler and mkdx#ShiftOHandler. There doesn't seem to be any code in the former meant for list continuation, but my VimL knowledge is limited so I might be wrong.

2.3 Adding an echom "Inside mkdx#EnterHandler" at line 1549 doesn't show in the :messages which makes me think that the handler is actually not invoked.

al3xandru commented 4 years ago

@victorkristof @SidOfc can you share what version of vim are you using (not sure the OS matters)? On my system, neither terminal vim, nor MacVim accept settings in the format let g:mkdx#settings.enter.enable complaining g:mkdx#settings does not exist.

SidOfc commented 4 years ago

Hi @al3xandru,

I just took a quick look at your vimrc and disabled all plugins except mkdx (this more or less is "testing in isolation") so all other Plug github/repo things were commented and some settings causing crashes due to missing plugin code were disabled too. (and some additional colorscheme commands I couldn't get to work on my machine). The result was that mkdx worked as intended, both o and enter started working after I did that.

I do not know however, which plugin was in the way, you have quite a lot of config / plugins and it could take me a while to figure that out, I don't think I want to go through 1.5k lines of config either :sweat_smile:

Furthermore, about the settings; You are correct, you cannot define let g:mkdx#settings.map.prefix as such in vimrc, these are only to be used for changing stuff on the fly after having initially loaded the plugin, I think I'll add a note about this in the README whenever I find the time.

To have your settings the way you want, may I suggest using this format instead:

let g:mkdx#settings = {
      \ 'map': {
      \   'prefix': '<localleader>'
      \   },
      \ 'tokens': {
      \   'italic': '_'
      \   }
      \ }

As for the plugin situation, really the only way to find out is to disable all the plugins initially, then enable ones that enable themselves on markdown files.

Hopefully this helps in resolving your issue, since it doesn't seem to have to do with the vim version I think, but rather some plugin with about 99% certainty :)

SidOfc commented 4 years ago

For reference, this is your vimrc with my "tweaks" which did make it work (note: I did not check if localleader / italic token were actually applied properly, I think they will be):

modified vimrc (click to expand)

scriptencoding utf-8

" Organization
" 1. important
" 2. moving around, searching and patterns
" 3. tags
" 4. displaying text
" 5. syntax, highlighting and spelling
" 6. multiple windows
" 7. multiple tab pages
" 8. terminal
" 9. using the mouse
" 10. printing
" 11. messages and info
" 12. selecting text
" 13. editing text
" 14. tabs and indenting
" 15. folding
" 16. diff mode
" 17. mapping
" 18. reading and writing files
" 19. the swap file
" 20. command line editing
" 21. executing external commands
" 22. running make and jumping to errors
" 23. language specific
" 24. multi-byte characters
" 25. various

" 1. important {{{
set nocompatible
set backspace=2
set backspace=indent,eol,start  " allow backspace in insert mode
" Use the OS clipboard by default (on versions compiled with `+clipboard`)
if has('clipboard')
    if has('unnamedplus')
        set clipboard^=unnamed,unnamedplus
    else
        set clipboard=unnamed
    endif
endif
if !has('nvim')
    set esckeys     " allow cursor keys in insert mode
endif
set hidden      " allow buffer switching without saving
set lazyredraw
set modeline
set modelines=5
set mouse=a
set mousehide
set sessionoptions-=options
set sessionoptions+=curdir
set showcmd     " show command in bottom bar
set showmode    " display the current mode
set wildmenu    " enhance command-line completion
set wildignore+=.hg,.git,.svn  " version control
set wildignore+=*.o,*.obj,*.exe,*.dll,*.pyc,*.pyo,*.class,*.luac " compiled
set wildignore+=*.DS_Store,*.sw?
set wildignore+=.idea/**
set wildignore+=*.png,*.jpg,*.gif,*.bmp
set wildignore+=*.egg,*.egg-info,*.gem
set wildignore+=*.zip,*.tar.gz,*.gzip,*.rar
set wildignore+=*.aux,*.toc " Latex intermediary files

" }}}

" 2. moving around, searching and patterns {{{
set ignorecase
set incsearch
set nohlsearch
set smartcase
set showmatch
set matchtime=3     " tenths of a second to show the matching paren
set scrolloff=5
" }}}

" 3. omnicomplete {{{
set infercase
set omnifunc=syntaxcomplete#Complete
" https://github.com/sjl/dotfiles/blob/eea18b00b8c74943f5094fddf91d3c2a7e0a7242/vim/vimrc#L534
" kspell: dictionary completion only when spell enabled set spell 
set complete=.,w,b,u,t,i,kspell
" http://vim.wikia.com/wiki/Make_Vim_completion_popup_menu_work_just_like_in_an_IDE
set completeopt=longest,menu,preview
" http://stackoverflow.com/questions/7722177/how-do-i-map-ctrl-x-ctrl-o-to-ctrl-space-in-terminal-vim
inoremap  
inoremap  
" }}}

" 4. displaying text {{{
filetype on
filetype plugin on
filetype plugin indent on

set synmaxcol=500
set listchars=tab:▸\ ,trail:·,eol:¬
set showbreak=↪
" set showbreak=⤿

" line numbers {{{
" http://jeffkreeftmeijer.com/2012/relative-line-numbers-in-vim-for-super-fast-movement/
function! ToggleLineNo()
    if(&relativenumber == 1)
        set norelativenumber number
    else
        set number relativenumber
    endif
endfunction
" mappings inspired by vim-unimpaired
nmap [o- :set number relativenumber
nmap ]o- :set norelativenumber number
nmap co- :call ToggleLineNo()
map  :call ToggleLineNo()
augroup lineno
    autocmd!
    autocmd FocusLost * set norelativenumber number
    autocmd InsertEnter * set norelativenumber number
    autocmd InsertLeave * set relativenumber number
    autocmd Filetype qf setlocal norelativenumber number nowrap
augroup END
set number
set relativenumber
set numberwidth=2   " keep the line number gutter narrow so 3 digits is cozy
" }}}
" }}}

" 5. syntax, highlighting and spelling" {{{
syntax on       " enable syntax processing

" keyworkdprg, dictionary, thesaurus {{{
set dictionary=/usr/share/dict/words
set thesaurus+=~/.vim/mthesaur.txt

if has('mac')  " unix, win32, win64
    set keywordprg=:!open\ dict://\
else
    set keywordprg=:!open\ https://www.google.com/search?q=\
endif
augroup keywordprog
    autocmd!
    autocmd FileType vim setlocal keywordprg=:help
augroup END

" }}}
" }}}

" 6. multiple windows {{{
set title
set laststatus=2
" http://got-ravings.blogspot.co.at/2008/08/vim-pr0n-making-statuslines-that-own.html
" Colors: Error, Question, Search, Todo, Visual, WarningMsg
set statusline=%q[%#Error#%{toupper(mode())}%*:b%n]\ %f%m%r
set statusline+=\ %#Todo#%{exists('g:loaded_fugitive')?fugitive#statusline():''}%*
set statusline+=%= "left/right separator
set statusline+=%#Todo#%{exists('g:loaded_obsession')?ObsessionStatus():''}%*
set statusline+=%y[%{&fileencoding?&fileencoding:&encoding}]
set statusline+=%<[%v:%l/%L][a\%03.3b:h\%02.2B]

" GUI {{{
" set guicursor=n-v-c:block-Cursor,ve:ver35-Cursor,o:hor50-Cursor,i-ci:ver25-lCursor,r-cr:hor20-Cursor,sm:block
set guioptions=aAce
set selection=exclusive
if has("gui_running")
    set go-=T
    set go-=l
    set go-=L
    set go-=r " no scrollbar
    set go-=R
    if has("gui_macvim")
        " set gfn=Anonymous_Pro:h12
        " set gfn=Consolas:h12
        " set gfn=Cousine:h11
        " set gfn=Fira_Code_Regular:h12
        " set gfn=Hack:h12
        " set gfn=Inconsolata:h13
        " set gfn=Input_Mono:h11
        " set gfn=Liberation_Mono:h11
        set gfn=Operator_Mono:h12
        " set gfn=PragmataPro_Mono:h13
        " set gfn=Source_Code_Pro:h11
        " set gfn=SF_Mono_Regular:h12 linespace=2
        " add "New Window" menu to MacVim (stupid but needed)
        " aun File.New\ Window
        an  10.290 File.New\ Window :silent !mvim
        macm File.New\ Window key=
    elseif has("gui_gtk2")
        set gfn=monofur\ 12,SourceCodePro\ 10,Anonymous\ Pro\ 10
    endif

    set columns=110
    set lines=80
    if &diff 
        set columns=180
    endif
elseif has("gui_vimr")
    set columns=110
    set lines=80
endif
" augroup VimTransparency
"     autocmd!
"     autocmd FocusGained * set transparency=0
"     autocmd FocusLost * set transparency=25
" augroup END
" }}}

" splits
set splitbelow
set splitright

" automatically open the location/quickfix window after :make, :grep,
" :lvimgrep and friends if there are valid locations/errors
"augroup qf
    "autocmd QuickFixCmdPost [^l]* cwindow
    "autocmd QuickFixCmdPost l* lwindow
"augroup END
" }}}

" 11. messages and info {{{
set ruler
set noerrorbells
set novisualbell
set t_vb=
if has("gui_macvim")
    set visualbell t_vb=
endif
" }}}

" 14. tabs and indenting {{{
set expandtab       " TABs are spaces
set tabstop=4       " number of visual spaces per TAB
set shiftwidth=4
set softtabstop=4   " number of spaces in TAB when editing
set smartindent
set autoindent
" }}}

" 15. folding {{{
set foldenable
set foldmethod=indent
set foldnestmax=10
set foldlevel=100
"HTML folding tag
nnoremap zha Vatzf
" }}}

" 16 diff mode
set diffopt=filler,vertical

" 17. mappings {{{
set timeoutlen=750

" abbreviations
cnoreabbrev W w
cnoreabbrev Q q

" leader = space (default \)
" localleader = ,
" remap , 
let mapleader="\"
let maplocalleader=","

" (I)Mapping: escape (disabled) {{{
" inoremap jk :echoerr "mapping disabled. forget about it :-)"i
" inoremap fd :w
" }}}

" (I)Mapping: disable arrows {{{
inoremap  
inoremap  
inoremap  
inoremap  
" }}}

" (I)Mappings: insert at end of line {{{
" insert at the end of line while in insert mode; 
" i_CTRL-A is insert previously inserted text; i_CTRL-I is insert 
inoremap  A
inoremap  A
inoremap å A
" Insert a newline in normal mode
" nnoremap  O
" nnoremap  o
" nnoremap  i " Ctrl-j: break the line at cursor
" }}}

" (N)Mapings: buffers {{{
" https://www.reddit.com/r/vim/comments/4gjbqn/what_tricks_do_you_use_instead_of_popular_plugins/
nnoremap b :ls:buffer

" buffer switch (disabled) {{{
" nmap  :bNext
" nmap  :e#
" }}}
" }}}

" (N)Mappings: change (bind c[hange] to replace word under cursor) {{{2
nnoremap c :%s/\<\>//cg
" change word under cursor and use `.` to repeat (cheap rename refactor)
nnoremap c* *Ncgn
nnoremap c# #NcgN
nnoremap cg* g*Ncgn
nnoremap cg# g#NcgN
" }}}

" (N)Mappings: files {{{
"  Opens an edit command with the path of the currently edited file filled in
nnoremap ef :e =expand("%:p:h") . "/" 
nnoremap et :tabe =expand("%:p:h") . "/" 
nnoremap es :split =expand("%:p:h") . "/" 
nnoremap ev :vsplit =expand("%:p:h") . "/" 
"Source: http://superuser.com/questions/132029/how-do-you-reload-your-vimrc-file-without-restarting-vim
nnoremap e. :tabe $MYVIMRC
nnoremap s. :source $MYVIMRC
" see also edit commands using extensions:
" open with CtrlP
" }}}

" (N)Mappings: highlights {{{
" Show special characters (highlighting)
nmap hc :set nolist!
" Disable highlighted search 
nnoremap hh :nohlsearch
nnoremap  :nohlsearch
" Highlight matches http://www.jeffcomput.es/posts/2016/02/vim-tips-helpful-leader-key-commands/
" case sensitive, partial match inclusive
nnoremap hi :set hlsearch:let @/=''
" case sensitive, no partial match
nnoremap ho :set hlsearch:let @/='\<\>'
" }}}

" (N)Mappings: moves by line {{{
" make vertical line nav better http://stackoverflow.com/questions/20975928/moving-the-cursor-through-long-soft-wrapped-lines-in-vim/21000307#21000307
" and add the jumplist https://medium.com/@kadek/understanding-vims-jump-list-7e1bfc72cdf0
nnoremap  k (v:count == 0 ? 'gk' : "m'" .  v:count .  'k')
nnoremap  j (v:count == 0 ? 'gj' : "m'" .  v:count .  'j')
nnoremap  gk
nnoremap  gj
" }}}

" (N)Mappings: n/N with blip, center the line, and directional {{{
" nnoremap  n v:searchforward ? 'nzzzv:call HLNext(0.6)' : 'Nzzzv:call HLNext(0.6)'
" nnoremap  N v:searchforward ? 'Nzzzv:call HLNext(0.6)' : 'nzzzv:call HLNext(0.6)'

nnoremap  n 'Nn'[v:searchforward] . 'zzzv:call HLNext(0.6)'
nnoremap  N 'nN'[v:searchforward] . 'zzzv:call HLNext(0.6)'
" http://vi.stackexchange.com/questions/2761/set-cursor-colour-different-when-on-a-highlighted-word
" Plug 'timakro/vim-searchant'
" nnoremap  n nzzzv:call HLNext(0.6)
" nnoremap  N Nzzzv:call HLNext(0.6)
" directional n/N
" nnoremap  n 'Nn'[v:searchforward]
" nnoremap  N 'nN'[v:searchforward]

function! HLNext (blinktime)
    let l:target_pat = '\c\%#'.@/
    let l:ring = matchadd('ErrorMsg', l:target_pat, 101)
    redraw
    exec 'sleep ' . float2nr(a:blinktime * 1000) . 'm'
    call matchdelete(l:ring)
    redraw
endfunction
" }}}

" nnoremap  ; getcharsearch().forward ? ';' : ','
" nnoremap  , getcharsearch().forward ? ',' : ';'

" (N)Mappings: search with grep {{{
" bind f and F to perform grep for the word under cursor
" grep results go into quicklist: copen/cclose
nnoremap /fg :grep! -R '' =getcwd()
nnoremap /fG :grep -R '' =expand("%:p:h")
"nnoremap F :vimgrep! /\C\<\>/gj =expand("%:p:h")
"nnoremap F :vimgrep! /\<\>/j
" }}}

" (N)Mappings: search [I/]I {{{2
nnoremap [I [I:let nr = input("Jump to: ")exe "normal " . nr ."[\t"
nnoremap ]I ]I:let nr = input("Jump to: ")exe "normal " . nr ."]\t"
" 2}}}
" See (N)Mappings: search with ack/ag

" Mappings: selections {{{
" reselect pasted text
nnoremap v V`] 
" https://github.com/henrik/dotfiles/blob/master/vim/config/mappings.vim#L22
" select the text that was last edited/pasted
" http://vimcasts.org/episodes/bubbling-text/
nmap gV `[v`]
" keep selection when indenting
vnoremap > >gv
vnoremap < gt :tabs:tabn
nnoremap  :silent tabprevious
nnoremap  :silent tabnext
inoremap  :tabprevious
inoremap  :tabnext
" open tag in tab
nnoremap  T
inoremap  T
" Alt+] on OS X
nmap  
imap  
if (has('mac') || has('macunix')) && has('gui')
    nmap ‘ 
    imap ‘ 
endif
" }}}

" Mappings: window resizing {{{
nmap < :vertical resize -10
nmap > :vertical resize +10
nmap - :resize -10
nmap + :resize +10
" }}}

" (C)Mappings: Inserts the path of the currently edited file into a command {{{
cnoremap  =expand("%:p:h") . "/" 
cnoremap  =expand("%:t")
" }}}

" (C)Mappings: Save current session {{{
function! SaveSession() 
    let l:parentDir = getcwd()
    let l:sessionFile = expand("~/.sessions/vim/") .  strftime("%Y-%m-%dT%H%M%S") .  "_" .  join(split(l:parentDir, "/"),"~") . ".vim"
    echom "Parent dir  :" .  l:parentDir
    echom "Session file:" .  l:sessionFile
    " exec "mksession! " . l:parentDir . "/.session.vim"
    " echo "session saved " . l:parentDir . "/.session.vim"
    if isdirectory(l:parentDir . "/.git")
        let l:sessionFile = l:parentDir  .  "/.git/.session.vim"
    endif
    if exists("g:loaded_obsession")
        exec "Obsession " .  l:sessionFile
    else
        exec "mksession! " . l:sessionFile
    endif
    echom "session saved in " . l:sessionFile 
endfunction
cnoremap   call SaveSession()
nnoremap  :call SaveSession()
cnoremap  call SaveSession()
nnoremap  :call SaveSession()
"cnoremap  ="mksession! " . getcwd() . "/.session.vim" 
"cnoremap  ="mksession! " . expand("%:p:h") . "/.session.vim" 
" }}}

" disable auto-sourcing of $MYVIMRC
" augroup myvimrc
"     au!
"     au BufWritePost .vimrc,_vimrc,vimrc,.gvimrc,_gvimrc,gvimrc so $MYVIMRC | if has('gui_running') | so $MYGVIMRC | endif
" augroup END

" }}}

" 19. backup & swap file {{{
set backup
set noswapfile
set undofile
set history=10000
set backupdir=~/.vim/tmp/backup// "~/.vim/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
set directory=~/.vim/tmp/swap// "~/.vim/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
set undodir=~/.vim/tmp/undo//
set writebackup

if !isdirectory(expand(&backupdir))
    call mkdir(expand(&backupdir), "p")
endif
if !isdirectory(expand(&directory))
    call mkdir(expand(&directory), "p")
endif
if !isdirectory(expand(&undodir))
    call mkdir(expand(&undodir), "p")
endif
"}}}

" 24. multi-byte characters
setglobal fileencoding=utf-8
set encoding=utf-8 nobomb

" autocmds
if has("autocmd")
    augroup vimrc
        autocmd!
        " autosave on focus lost
        autocmd FocusLost, BufLeave * silent! :wall
        " default to markdown if not in diff mode
        autocmd BufEnter * if &filetype == "" && !&diff | setlocal ft=markdown | endif
        " crontab -e
        autocmd BufNewFile,BufRead crontab.* set nobackup nowritebackup

        " json is javascript
        autocmd BufNewFile,BufRead *.json setfiletype json syntax=javascript

        autocmd FileType html,htm setlocal ts=2 sts=2 sw=2 expandtab
        autocmd FileType make setlocal ts=4 sts=4 sw=4 noexpandtab
        autocmd FileType java setlocal omnifunc=javacomplete#Complete
        autocmd FileType python setlocal ts=4 sts=4 sw=4 expandtab autoindent
        autocmd FileType vim setlocal nowrap
        autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab

        if filereadable(expand("~/.vim/bundle/HTML-AutoCloseTag/ftplugin/html_autoclosetag.vim"))
            autocmd FileType html,htm,xhtml,xml source ~/.vim/bundle/HTML-AutoCloseTag/ftplugin/html_autoclosetag.vim
        end
    augroup END
end

" https://github.com/macvim-dev/macvim/issues/386
if has('mac')
    if executable("pyenv") && !has('nvim')
        " v.1
        " let _cmd = 'pyenv version-name'
        " let _pyenv=substitute(system(_cmd), '[\]\|[[:cntrl:]]', '', 'g')
        " v.2
        " let _cmd = 'python -c "import sys;vt=sys.version_info;sys.stdout.write(\".\".join([str(v) for v in vt[:3]]))"'
        " let _pyver=substitute(system(_cmd), '[\]\|[[:cntrl:]]', '', 'g')
        " check: https://github.com/macvim-dev/macvim/blob/b906f87e8c0ef8585e5aaeb72ca4aadbbd1b8155/src/MacVim/vimrc#L21
        " Python 2
        let _cmd = 'pyenv versions --bare --skip-aliases | grep -E "2\.[[:digit:]]+\.[[:digit:]]+$" | tail -1'
        let _pyenv=substitute(system(_cmd), '[\]\|[[:cntrl:]]', '', 'g')
        let _pyver=substitute(_pyenv, '^\s*\(.*\)', '\1', '')
        let _pyvermaj=join(split(_pyver, "\\.")[0:1], ".")
        let &pythondll=$HOME . "/.pyenv/versions/" . _pyver . "/lib/libpython" . _pyvermaj . ".dylib"
        let &pythonhome=$HOME . "/.pyenv/versions/" . _pyver
        " Python 3
        let _cmd = 'pyenv versions --bare --skip-aliases | grep -E "3\.[[:digit:]]\.[[:digit:]]+$" | tail -1'
        let _pyenv=substitute(system(_cmd), '[\]\|[[:cntrl:]]', '', 'g')
        let _pyver=substitute(_pyenv, '^\s*\(.*\)', '\1', '')
        " let _pyver=_pyenv
        " following line replaced by next one dealing better with versions
        " let _pyvermaj=strpart(_pyver, 0, 3)
        let _pyvermaj=join(split(_pyver, "\\.")[0:1], ".")

        " I don't know how to do set pythondll thus the let &pythondll
        let &pythonthreehome = $HOME .  "/.pyenv/versions/" . _pyver
        let &pythonthreedll = $HOME . "/.pyenv/versions/" . _pyver . "/lib/libpython" . _pyvermaj . ".dylib"

        " echom "&pythonhome     :" . &pythonhome
        " echom "&pythondll      :" . &pythondll
        " echom "&pythonthreehome:" . &pythonthreehome
        " echom "&pythonthreedll :" . &pythonthreedll

        " http://stackoverflow.com/questions/30443836/install-vim-via-homebrew-with-python-and-python3-support
        if _pyvermaj > '3.0' && has('python3')
            " echom "PYTHON3k  :YES"
            let g:jedi#force_py_version = 3
            let g:pymode_python = 'python3'
        else
            " echom "PYTHON3k  :NO"
            let g:jedi#force_py_version = 2
            let g:pymode_python = 'python'
        endif
    endif
endif

function! BigWnd() 
    " colorscheme nuvola
    " set gfn=Operator_Mono:h24
    set gfn=mononoki:h24
    set colorcolumn=0
    set columns=80
    " edit "~/Desktop/" .  strftime("%Y%m%d-%H%M") .  ".md"
    exec "edit ~/Dropbox/Dox/mydox/tmp-" .  strftime("%Y%m%d-%H%M") .  ".md"
    startinsert
endfunction
command! Bigwnd call BigWnd()

function! Fonts()
    let l:fonts = "Anka/Coder_Narrow Cousine Fira_Code Go_Mono Hack IBM_Plex_Mono Iosevka JetBrains_Mono mononoki Operator_Mono PragmataPro_Mono Source_Code_Pro"
    let l:flst = split(l:fonts)
    echo "Fonts:"
    echo join(l:flst, "\n")
    echo "\n"
    exec "set gfn=" . input("Font: ", "mononoki") . ":h" . input("Size: ", "24")
endfunction
command! SetFont call Fonts()

" Load vim-plug https://github.com/junegunn/vim-plug
call plug#begin('~/.vim/plugged-al3xandru')
" Alternative plugin managers
" - vundle
" - junegunn/vim-plug 
" - Shougo/neobundle.vim

" colorschemes {{{1
" Plug 'vim-scripts/Colour-Sampler-Pack'

" sources {{{2
" https://www.reddit.com/r/neovim/comments/e04207/what_are_the_best_maintained_and_most_extensive/ " {{{2
" https://www.reddit.com/r/neovim/comments/ehjsbk/looking_for_good_light_colorscheme/
" }}}

" top (supporting text styling) {{{2
" Plug 'morhetz/gruvbox'
" Plug 'gruvbox-community/gruvbox'

" light
" Plug 'NLKNguyen/papercolor-theme'

" dark
" Plug 'arcticicestudio/nord-vim'
" Plug 'joshdick/onedark.vim'
" Plug 'trevordmiller/nova-vim'
" }}}

" ok {{{2
" Plug 'AlessandroYorba/Alduin'
let g:alduin_Shout_Aura_Whisper = 1
let g:alduin_Shout_Fire_Breath = 1

" light
" Plug 'nice/sweater'
" Plug 'zefei/cake16'
" }}}

" simple light {{{2
" Plug 'arzg/vim-colors-xcode'
" Plug 'arzg/vim-plan9'
" Plug 'ayu-theme/ayu-vim'
let ayucolor="light" "options: light mirage dark
" Plug 'cormacrelf/vim-colors-github'
let g:github_colors_soft = 1
" Plug 'jaredgorski/fogbell.vim'
" Plug 'rakr/vim-one'
let g:one_allow_italics = 1

" simplified and optimized Gruvbox 
" Plug 'lifepillar/vim-gruvbox8'
" }}}
"}}}

" disabled colorschemes {{{2 
" Plug 'adampasz/vim-stonewashed'
" Plug 'AlessandroYorba/Sierra'
" Plug 'altercation/vim-colors-solarized'
let g:solarized_termtrans=0
let g:solarized_termcolors=256
let g:solarized_visibility="high"
let g:solarized_contrast="normal"
" Plug 'blerins/flattown'
" Plug 'chriskempson/base16-vim'
" Plug 'cocopon/iceberg.vim'
" Plug 'colepeters/spacemacs-theme.vim'
" Plug 'fcpg/vim-fahrenheit'
" Plug 'fenetikm/falcon'
" Plug 'freeo/vim-kalisi'
" Plug 'jdkanani/vim-material-theme'
" Plug 'jeetsukumaran/vim-nefertiti'
" Plug 'jonathanfilip/vim-lucius'
" After enabling: :Lucius[Black|BlackHighContrast|BlackLowContrast|
"   Dark|DarkHighContrast|DarkLowContrast|Light|LightLowContrast|
"   White|WhiteLowContrast]
" Plug 'junegunn/seoul256.vim'
" Plug 'lifepillar/vim-wwdc17-theme'
" Plug 'mayansmoke'
" Plug 'mhartington/oceanic-next'
" Plug 'nanotech/jellybeans.vim'
" Plug 'NLKNguyen/papercolor-theme'
" Plug 'rakr/vim-two-firewatch'
let g:two_firewatch_italics=1
let g:airline_theme='twofirewatch'
" Plug 'rodnaph/vim-color-schemes'
" Plug 'swalladge/antarctic-vim'
" Plug 'whatyouhide/vim-gotham'
" Plug '256-grayvim'
" Plug 'blacklight'
" Plug 'gregsexton/Atom'
" Plug 'zeis/vim-kolor'
" }}}
" }}}

" Extra text objects {{{1
" Plug 'kana/vim-textobj-user'
" Line object: il al
" Plug 'kana/vim-textobj-line'
" Function argument object: i, a,
" Shift: <, >,
" Jump: [, ],
" Plug 'PeterRincker/vim-argumentative'
" Plug 'argtextobj.vim' 
" Indent object: ii ai aI iI 
" Plug 'michaeljsmith/vim-indent-object' 
" Function call object: am im aM iM
" Plug 'thalesmello/vim-textobj-methodcall'
" Function object: if af iF aF
" Plug 'kana/vim-textobj-function'
" Plug 'kamichidu/vim-textobj-function-go'
" Plug 'thinca/vim-textobj-function-javascript'
" Plug 'thinca/vim-textobj-function-perl'
" Plug 'nelstrom/vim-textobj-rubyblock'
" Comment object: ic ac aC
" Plug 'glts/vim-textobj-comment'
" URIs: iu au
" Plug 'jceb/vim-textobj-uri'
" Plug 'wellle/targets.vim'
" }}}

" Essentials {{{1
"
" Files {{{2
"{{{3
" Plug 'ctrlpvim/ctrlp.vim' 
let g:loaded_ctrlp = 1
let g:ctrlp_map = ''
let g:ctrlp_cmd = 'CtrlP'
let g:ctrlp_match_window = 'top,order:ttb,min:1,max:10,results:10'
" only cache if we're over this number of files
let g:ctrlp_use_caching = 2000
" Mappings: CtrlP {{{4
" nnoremap o :CtrlP
" nnoremap ] :CtrlPBufTag
" nnoremap B :CtrlPBuffer
" " open with CtrlP
" nnoremap eT :tabnew:CtrlP
" nnoremap eS :split:CtrlP
" nnoremap eV :vsplit:CtrlP
" 4}}}
"3}}}

" Plug 'junegunn/fzf'
" Plug 'junegunn/fzf.vim'
let g:fzf_layout = {'up': '~20%'}
" Mappings: fzf {{{3
nnoremap of :Files
nnoremap og :GFiles
nnoremap ob :Buffers
nnoremap oB :History
nnoremap ot :BTags
nnoremap o] :BTags
nnoremap oT :Tags
nnoremap ol :BLines
nnoremap oL :Lines
nnoremap ow :Windows
" Other commands:
" :BLines, :Lines, :Marks
" :Commits, BCommits
" :Windows
" :Colors, :Commands, :Filetypes, :Maps
" :History:, :History/
" 3}}}
" }}}

" Netrw {{{3
autocmd FileType netrw setlocal bufhidden=delete "wipe
nnoremap p :Lex
nnoremap P :Lex =expand("%:p:h") . "/"
let g:netrw_banner = 0
let g:netrw_browse_split=0      " re-use the same window
let g:netrw_hide=0
" let g:netrw_home='~'
let g:netrw_preview=0   "horizontal
let g:netrw_alto=0      "aboveleft
let g:netrw_altv=1      "open splits to the right
let g:netrw_liststyle=0 " 3: thin long wide tree; 0: thin list
let g:netrw_winsize=25
" from vinegar
let s:dotfiles = '\(^\|\s\s\)\zs\.\S\+'
let s:escape = 'substitute(escape(v:val, ".$~"), "*", ".*", "g")'
let g:netrw_sort_sequence = '[\/]$,*,\%(' . join(map(split(&suffixes, ','), 'escape(v:val, ".*$~")'), '\|') . '\)[*@]\=$'
let g:netrw_list_hide =
      \ join(map(split(&wildignore, ','), '"^".' . s:escape . '. "$"'), ',') . ',^\.\.\=/\=$' .
      \ (get(g:, 'netrw_list_hide', '')[-strlen(s:dotfiles)-1:-1] ==# s:dotfiles ? ','.s:dotfiles : '')
" }}}
" 2}}}

" Tags/ctags/omnicomplete (check tagfiles: echo tagfiles()) {{{2
" Disable to use fzf
" Plug 'majutsushi/tagbar'
if filereadable("/usr/local/bin/ctags")
    let g:tagbar_ctags_bin = '/usr/local/bin/ctags'
else
    let g:tagbar_ctags_bin = '/usr/bin/ctags'
endif
let g:tagbar_autoclose = 1
let g:tagbar_show_linenumbers = 0
let g:tagbar_hide_nonpublic = 0
" nnoremap t :TagbarToggle

set tags=./.git/tags;,./.tags;,./tags;,~/.vim/.vimtags
" Plug 'ludovicchabant/vim-gutentags'
if filereadable("/usr/local/bin/ctags")
    let g:gutentags_ctags_executable = '/usr/local/bin/ctags'
else
    let g:gutentags_ctags_executable = '/usr/bin/ctags'
endif
let g:gutentags_ctags_tagfile = '.tags'
let g:gutentags_generate_on_missing = 0
let g:gutentags_generate_on_new = 0
" }}}

" Plug 'beloglazov/vim-online-thesaurus'

" Plug 'mbbill/undotree' " {{{
nnoremap u :UndotreeToggle
let g:undotree_WindowLayout = 2
let g:undotree_SetFocusWhenToggle = 1
" }}}

" Plug 'tpope/vim-commentary'   " {{{
" Plug 'al3xandru/nerdcommenter'
" Plug 'scrooloose/nerdcommenter'
" Plug 'tomtom/tcomment_vim'
" }}}

" Plug 'w0rp/ale'   " {{{
let g:ale_enabled = 1
let g:ale_completion_delay = 250
let g:ale_completion_enabled = 0
let g:ale_echo_delay = 100
let g:ale_lint_delay = 500
let g:ale_lint_on_enter = 1
let g:ale_lint_on_insert_leave = 0
let g:ale_lint_on_save = 1
let g:ale_lint_on_text_changed = 'never'
let g:ale_list_window_size = 10
let g:ale_open_list = 'on_save'
" let g:ale_set_balloons = 1
let g:ale_set_highlights = 1
let g:ale_set_loclist = 1
let g:ale_set_signs = 1
let g:ale_sign_error = 'E'
let g:ale_sign_info = 'I'
let g:ale_sign_warning = 'W'
let g:ale_sign_style_error = 'ES'
let g:ale_sign_style_warning = 'WS'
let g:ale_linters = {
    \ 'go': ['gometalinter'],
    \ 'python': ['pyflakes',  'pylint'],
    \ }
let g:ale_go_gometalinter_options = '--no-config --disable-all --aggregate --enable=errcheck --enable=golint --enable=gofmt --enable=vet --enable=goimports'
let g:ale_python_pylint_executable = expand('~/.pyenv/versions/neovim2/bin/python')
let g:ale_python_pylint_options = '-m pylint'
let g:ale_python_pyflakes_executable = expand('~/.penv/versions/neovim2/bin/pyflakes')
let g:ale_python_pyflakes_options = '-m pyflakes'
" Alternatives:
" Plug 'scrooloose/syntastic'
" Plug 'maralla/validator.vim'
" }}}

" Search: Ack and Ag {{{2
" Plug 'wincent/ferret' " asycn!!!
let g:FerretExecutable='ag,ack'
let g:FerretMap=0
" Possible replacements:
" Plug 'mileszs/ack.vim'
" Plug 'rking/ag.vim'
" Plug 'dyng/ctrlsf.vim'
" Plug 'mhinz/vim-grepper'
" (N)Mappings: ack {{{3
" Using the_silver_searcher to look for word under cursor in current dir
" when using with Ferret there're no quotes
nnoremap /fa :Ack! --=&filetype \b\b =getcwd()
nnoremap /fA :Ack! --=&filetype \b\b =expand("%:p:h")
nmap / (FerretAck)

" Using Ack to search the word under cursor in the current dir
" nnoremap f :Ack! --type==%filetype "\b\b" =expand("%:p:h")
" 3}}}
"}}}

" Snippets {{{2
" Plug 'Shougo/neosnippet.vim'
" Plug 'Shougo/neosnippet-snippets' "{{{
imap  (neosnippet_expand_or_jump)
smap  (neosnippet_expand_or_jump)
xmap  (neosnippet_expand_target)
let g:neosnippet#snippets_directory=expand("~/.vim/xsnippets/neosnippets")
" let g:neosnippet#expand_word_boundary=0
" }}}
" }}}
" }}}

" Language support {{{1
"
" Plug 'sheerun/vim-polyglot' "{{{
let g:polyglot_disabled = ['markdown']
" replacing for now applescript, fatih/vim-go, pangloss/vim-javascript,  hdima/python-syntax
" }}}

" Plug 'applescript.vim'

" Plug 'VimClojure'
let vimclojure#SetupKeyMap = 0

" C/C++ 
" Plug 'OmniCppComplete'

" Go {{{2
" Plug 'fatih/vim-go'
" let g:go_bin_path = expand("~/.golang")
let g:go_echo_command_info = 0
let g:go_fmt_autosave = 1
let g:go_fmt_command = 'goimports'      " alternative gofmt
let g:go_fmt_fail_silently = 0
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_structs = 1
let g:go_list_type = 'locationlist'
let g:go_metalinter_autosave = 1
let g:go_metalinter_autosave_enabled = ['vet', 'golint', 'errcheck']
let g:go_list_type_commands = {"GoMetalinter": "quickfix"}
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'
\ }
augroup go
    autocmd!
    autocmd FileType go nmap gs (go-implements)
    autocmd FileType go nmap gi (go-info)
    autocmd FileType go nmap gh (go-doc)
    autocmd FileType go nmap ghv (go-doc-vertical)
    autocmd FileType go nmap ghb (go-doc-browser)
    autocmd FileType go nmap ger (go-run)
    autocmd FileType go nmap geb (go-build)
    autocmd FileType go nmap get (go-test)
    autocmd FileType go nmap gec (go-coverage)
    " autocmd BufWritePost *.go GoMetaLinter
    autocmd BufNewFile,BufRead *.toml setlocal ts=2 sts=2 sw=2 expandtab
augroup END
"}}}

" HTML Zen Coding
" Plug 'mattn/emmet-vim'
let g:user_emmet_install_global=0
augroup emmet
    autocmd!
    autocmd FileType html,css EmmetInstall
augroup END
let g:user_emmet_leader_key=''

" Java completion
" Plug 'VictorDenisov/javacomplete'
" Plug 'artur-shaik/vim-javacomplete2'

" Javascript
" Plug 'pangloss/vim-javascript'

" Asciidoc {{{2
" Plug 'dahu/vim-asciidoc'
" Plug 'dahu/vimple'
" Plug 'dahu/Asif'
" Plug 'Raimondi/VimRegStyle'
" let g:asciidoc_title_style = 'setext'
" augroup asciidoc
"     autocmd!
"     autocmd BufNewFile,BufRead *.adoc.txt setfiletype asciidoc syntax=asciidoc
" augroup END
"}}}

" Markdown {{{2
" Plug 'plasticboy/vim-markdown', {'as': 'plasticboy-vim-markdown'} " disabled with sheerun/vim-polyglot
set conceallevel=2
let g:vim_markdown_conceal=1
let g:vim_markdown_folding_disabled=0
let g:vim_markdown_folding_level=1
let g:vim_markdown_follow_anchor=0 "use get to jump to anchors
let g:vim_markdown_strikethrough=1
" let g:vim_markdown_no_default_key_mappings=1
nmap  Markdown_MoveToCurHeader
vmap  Markdown_MoveToCurHeader

Plug 'SidOfc/mkdx'
let g:mkdx#settings = {
      \ 'map': {
      \   'prefix': ''
      \   },
      \ 'tokens': {
      \   'italic': '_'
      \   }
      \ }
" let g:mkdx#settings.map.prefix = ''
" let g:mkdx#settings.tokens.italic = '_'

" Markdown preview {{{3
"Plug 'greyblake/vim-preview' could not get it to work
" Plug 'JamshedVesuna/vim-markdown-preview'
" let vim_markdown_preview_hotkey='mp'
let vim_markdown_preview_toggle=1
let vim_markdown_preview_github=0
let vim_markdown_preview_perl=0
let vim_markdown_preview_pandoc=0

" Plug 'skanehira/preview-markdown.vim'
" let g:preview_markdown_parser='htmlmarkdown'
" function! MarkdownPreview(file)
"     if has("unix")
"         let l:uname = system("uname -s")
"         if l:uname =~ "Darwin"
"             if filereadable("/Applications/Marked\ 2.app/Contents/Info.plist")
"                 execute ":silent !open -a 'Marked 2.app' '" . a:file . "'"
"                 " nnoremap mp :silent !open -a 'Marked 2.app' '%:p'
"             else
"                 execute ":silent !open -a Google Chrome.app' '" . a:file . "'"
"                 " nnoremap mp :silent !open -a 'Google Chrome.app' '%:p'
"             endif
"         endif
"     endif
" endfunction
"}}}
" Markdown editing {{{3
" Plug 'junegunn/goyo.vim'
" Plug 'junegunn/limelight.vim'
let g:limelight_default_coefficient = 0.7
let g:limelight_paragraph_span = 1
nmap [of :Limelight
nmap ]of :Limelight!
nmap cof :Limelight!!

" Plug 'reedes/vim-colors-pencil'
let g:pencil_higher_contrast_ui = 1
let g:pencil_neutral_code_bg = 1
let g:pencil_terminal_italics = 1

let g:iawriter_active = 0
let g:iawriter_save_colorscheme = ""
let g:iawriter_save_bgr = ""
function! IAWriter()
    if g:iawriter_active == 0
        let g:iawriter_save_colorscheme = g:colors_name
        if exists( "&background" )
            let g:iawriter_save_bgr = &background
        endif
        setlocal spell
        setlocal linespace=3
        setlocal background=light
        setlocal gfn=Operator_Mono:h14
        colorscheme pencil
        Goyo
        Limelight0.7
        " call goyo#execute(0, '')
        augroup lineno
            autocmd!
            autocmd FocusLost *.{mk,markdown,mdown,mkdn,mkd,rst}   setlocal norelativenumber nonumber
            autocmd InsertEnter *.{mk,markdown,mdown,mkdn,mkd,rst} setlocal norelativenumber nonumber
            autocmd InsertLeave *.{mk,markdown,mdown,mkdn,mkd,rst} setlocal norelativenumber nonumber
        augroup END
        let g:iawriter_active = 1
        echom "IAWriter activated [new: pencil, old: " .  g:iawriter_save_colorscheme . ", background:" . g:iawriter_save_bgr . "]"
    else
        augroup lineno
            autocmd!
            autocmd FocusLost * setlocal norelativenumber number
            autocmd InsertEnter * setlocal norelativenumber number
            autocmd InsertLeave * setlocal relativenumber number
        augroup END
        " call goyo#execute(0, '') 
        Limelight!
        Goyo
        execute printf("colorscheme %s", g:iawriter_save_colorscheme)
        if g:iawriter_save_bgr
            execute printf("set background=%s", g:iawriter_save_bgr)
        endif
        setlocal gfn=Operator_Mono:h12
        setlocal linespace=1
        setlocal nospell
        let g:iawriter_active = 0
        echom "IAWriter deactivated [new: " . g:iawriter_save_colorscheme . ", old: pencil, background:" . g:iawriter_save_bgr . "]"
    endif
endfunction
augroup markdown
    autocmd!
    " autocmd BufRead,BufNewFile *.{mk,markdown,mdown,mkdn,mkd,rst} set filetype=markdown
    autocmd FileType markdown setlocal textwidth=80 wrap foldenable "linebreak
    autocmd FileType markdown nnoremap  t :Toc:q:lop 
    autocmd FileType markdown nnoremap  me :call IAWriter()
    " autocmd FileType markdown nnoremap  mp :call MarkdownPreview('%:p')
    autocmd FileType markdown nnoremap  mv :call Vim_Markdown_Preview()
    autocmd FileType markdown nnoremap  mg :! $HOME/bin/emarkdown --format=1 =expand("%:p") \| pbcopy
    autocmd FileType markdown nnoremap  mp :! $HOME/bin/pubmarkup.sh -a vim =expand("%:p")
    " Paste clipboard as blockquote
    " autocmd FileType markdown nnoremap bq pmaV`]gwv`a:s/^/> /g:nohlsearcho
    " autocmd FileType markdown nnoremap bq pgw`]V`]:s/^/> /g:nohlsearcho
    autocmd FileType markdown nnoremap  bq p`]gw`[V`[:s/^/> /g:nohlsearcho
    " visual selection to blockquote
    " autocmd FileType markdown vmap bq mzgw` /g:nohlsearch2xo
    autocmd FileType markdown vmap  bq gq$v`<:s/^/> /g:nohlsearch
    " autocmd BufRead,BufNewFile *.{md,markdown,mdown,mkd,mkdn} call s:setupMarkdownPreview()
    " https://sts10.github.io/post/2015-08-02-markdwon-hyperlink-remap-for-vim/
    autocmd FileType markdown vnoremap  il ``>a]("+]pa) 
augroup END

"}}}
"}}}

" Node.js https://github.com/joyent/node/wiki/Vim-Plugins

" Python {{{2
" Plug 'lambdalisue/vim-pyenv'
" Plug 'hdima/python-syntax' " disabled with sheerun/vim-polyglot
" Plug 'klen/python-mode'
let g:pymode_doc = 1
let g:pymode_doc_bind = 'K'
let g:pymode_folding = 1
let g:pymode_indent = 1
let g:pymode_motion = 1
let g:pymode_options_max_line_length=99
let g:pymode_lint = 0
let g:pymode_lint_checkers = ['pyflakes', 'pep8', 'mccabe']
let g:pymode_lint_ignore = ["E501"]
let g:pymode_syntax_slow_sync = 0
let g:pymode_virtualenv = 1
let g:pymode_run = 0
" let g:pymode_run_bind = 'ger'
let g:pymode_breakpoint = 1
let g:pymode_breakpoint_bind = 'gb'
let g:pymode_rope = 0
let g:pymode_rope_completion = 0
let g:pymode_rope_complete_on_dot = 0

" Plug 'davidhalter/jedi-vim'
let g:jedi#auto_initialization = 1
let g:jedi#completions_enabled = 1
let g:jedi#completions_command = ""
let g:jedi#use_splits_not_buffers = "bottom"
let g:jedi#popup_on_dot = 0
let g:jedi#show_call_signatures = 2 " 2: show in command line instead of popup
" bindings
let g:jedi#goto_assignments_command = "ga"
let g:jedi#goto_definitions_command = "gd"
let g:jedi#goto_command="gd"
let g:jedi#documentation_command = "gh"
let g:jedi#usages_command = "gu"
let g:jedi#rename_command = "gr"

" https://github.com/macvim-dev/macvim/issues/386
" if !has('gui') ||  !has('mac')
" endif
" if !has('gui') || !has('mac')
" endif
"}}}

" Plug 'derekwyatt/vim-scala'

" Plug 'keith/swift.vim'

" Plug 'davidoc/taskpaper.vim' " Taskpaper {{{
let g:task_paper_date_format="%Y-%m-%d %H:%M%p"
" }}}

" Plug 'digitalrounin/vim-yaml-folds'
" }}}

" Enhancements {{{1
"
"
" Improve matching chars, parentheses {{{2
" Improved %
" Plug 'jwhitley/vim-matchit' " {{{
" Plug 'edsono/vim-matchit' " dead
" Plug 'isa/vim-matchit'
" }}}

" Plug 'kien/rainbow_parentheses.vim' " {{{
" augroup rainbowpar
"     autocmd!
"     autocmd VimEnter * RainbowParenthesesToggle
"     autocmd Syntax * RainbowParenthesesLoadRound
"     autocmd Syntax * RainbowParenthesesLoadSquare
"     autocmd Syntax * RainbowParenthesesLoadBraces
" augroup END
" }}}

" {{{ auto pairs 
" Check fork https://krasjet.com/voice/auto.pairs/
" Plug 'Krasjet/auto.pairs'
" Plug 'jiangmiao/auto-pairs'
let g:AutoPairsMapSpace=1
" Alt+< and Alt+> (changed from Alt+0 and Alt+9)
if (has('mac') || has('macunix')) && has('gui')
    let g:AutoPairsShortcutJump='ª'
    let g:AutoPairsShortcutFastWrap='º'
else
    let g:AutoPairsShortcutJump=''
    let g:AutoPairsShortcutFastWrap=''
endif
"Plug 'Raimondi/delimitMate'
"let delimitMate_expand_cr=1

" Plug 'tmsvg/pear-tree'
let g:pear_tree_pairs = {
    \ '(': {'closer': ')'}, 
    \ '[': {'closer': ']'}, 
    \ '{': {'closer': '}'},
    \ "'": {'closer': "'"},
    \ '"': {'closer': '"'},
    \ "'},
    \ "/*": {'closer': '*/'},
    \ '<*>': {'closer': '', 'not_if': ['br', 'meta', 'http', 'https', 'ftp'], 'not_like': '/$'}
    \ } 
let g:pear_tree_smart_openers = 1
let g:pear_tree_smart_closers = 1
if (has('mac') || has('macunix')) && has('gui')
    imap º (PearTreeJump)
else
    imap  (PearTreeJump)
endif
" }}}

"auto close parentheses and repeat by dot dot dot {{{
" Plug 'alvan/vim-closetag'
"Plug 'cohama/lexima.vim'
"Plug 'Townk/vim-autoclose'

" Plug 'HTML-AutoCloseTag'
" let b:mapped_auto_closetag = 1
" }}}
" 2}}}

" Startup buffer {{{2
" Plug 'mhinz/vim-startify'
let g:startify_lists = [
    \ {'type': 'bookmarks', 'header': ['   Bookmarks']},
    \ {'type': 'dir', 'header': ['   MRU in ' .  getcwd()]},
    \ {'type': 'files', 'header': ['   Recent files']},
    \ {'type': 'sessions', 'header': ['   Sessions']},
    \ ]
" DEPRECATED
" let g:startify_list_order = [
"     \ ['Bookmarks:'],
"     \ 'bookmarks', 
"     \ ['Most recent in current directory:'],
"     \ 'dir', 
"     \ ['Recent files:'], 
"     \ 'files',
"     \ ['Sessions:'], 
"     \ 'sessions',
"     \ ]
let g:startify_bookmarks = [
    \ {'a': '~/Dropbox/Dox/mydox/'},
    \ {'b': '~/Dropbox/Dox/myjrnl/'},
    \ {'c': '~/Dropbox/Dox/nvall/'},
    \ '~/.vimrc',
    \ '~/Dropbox/Dox/mydox/01-weekly.taskpaper',
    \ '~/Dropbox/Dox/mydox/02-thoughts.md',
    \ '~/Dropbox/Dox/mydox/03-email_drafts.md',
    \ '~/Dropbox/Dox/mydox/04-blog.md',
    \ '~/Dropbox/Dox/mydox/05-blog_ideas_and_drafts.md',
    \ '/Users/Shared/homepage/h.html',
    \]
let g:startify_files_number = 10
let g:startify_session_autoload = 1
let g:startify_session_dir = '~/.sessions/vim'
let g:startify_skiplist = [
    \ '.git/.*',
    \ '.hg/.*',
    \ ]
let g:startify_change_to_dir = 1
let g:startify_change_to_vcs_root = 0
nnoremap bh :Startify
"}}}

" CamelCase {{{2
" Plug 'camelcasemotion'
" Plug 'kana/vim-smartword'
" Plug 'bkad/CamelCaseMotion' 
" Ver.1: Alt - w/b/3/g => ∑/∫/£/© {{{3
" map ∑ CamelCaseMotion_w
" map ∫ CamelCaseMotion_b
" map £ CamelCaseMotion_e
" map © CamelCaseMotion_ge
" omap  i∑ CamelCaseMotion_iw
" xmap  i∑ CamelCaseMotion_iw
" omap  i∫ CamelCaseMotion_ib
" xmap  i∫ CamelCaseMotion_ib
" omap CamelCaseMotion_ie
" xmap CamelCaseMotion_ie
" end ver }}}
" Ver.2: w -> CamelCase, orig w -> W, orig.W -> Alt+w {{{3
" these remaps work if I want to
" noremap ∑ W
" noremap ∫ B
" noremap £ E
" noremap © gE
" noremap W w
" noremap B b
" noremap E e
" noremap gE ge
" map w CamelCaseMotion_w
" map b CamelCaseMotion_b
" map e CamelCaseMotion_e
" map ge CamelCaseMotion_ge
" end ver.2}}}
" Ver.3
map ]w CamelCaseMotion_w
map [w CamelCaseMotion_e
map ]W CamelCaseMotion_b
map [W CamelCaseMotion_ge
" }}}

" Search 2 chars and improved t/f {{{2
" Plug 'justinmk/vim-sneak'
let g:sneak#label = 1
let g:sneak#use_ic_scs = 1
" let g:sneak#target_labels = "abcdefghijklmnopqrstuvwxyz"
nmap f Sneak_f
nmap F Sneak_F
nmap t Sneak_t
nmap T Sneak_T
nmap \ Sneak_,
xmap f Sneak_f
xmap F Sneak_F
xmap t Sneak_t
xmap T Sneak_T
xmap \ Sneak_,
omap f Sneak_f
omap F Sneak_F
omap t Sneak_t
omap T Sneak_T
omap \ Sneak_,

" }}}

"Plug 'easymotion/vim-easymotion'     " Disabled: Quick navigation {{{2
"let g:EasyMotion_loaded = 1
"" Disable default mappings
"let g:EasyMotion_do_mapping=0
"let g:EasyMotion_use_upper=1
"let g:EasyMotion_keys = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
"let g:EasyMotion_inc_highlight=1
"let g:EasyMotion_move_highlight=1
"let g:EasyMotion_landing_highlight=0
"let g:EasyMotion_add_search_history=0
""map ' (easymotion-prefix)
"" nmap s (easymotion-sn)
"" nmap s (easymotion-sn)
"" vmap s (easymotion-sn)
"" nmap w (easymotion-bd-w)
"" vmap w (easymotion-bd-w)
"" nmap e (easymotion-bd-e)
"" vmap e (easymotion-bd-e)
"" nmap n (easymotion-next)
"" vmap n (easymotion-next)
"" nmap p (easymotion-next)
"" vmap p (easymotion-next)
"" nmap t (easymotion-bd-t)
"" vmap t (easymotion-bd-t)
"" nmap f (easymotion-bd-f)
"" vmap f (easymotion-bd-f)
"nmap ,s (easymotion-sn)
"nmap ,w (easymotion-bd-w)
"nmap ,e (easymotion-bd-e)
"nmap ,f (easymotion-bd-f)
"nmap ,t (easymotion-bd-t)
"nmap ,n (easymotion-next)
"vmap ,s (easymotion-sn)
"vmap ,w (easymotion-bd-w)
"vmap ,e (easymotion-bd-e)
"vmap ,f (easymotion-bd-f)
"vmap ,t (easymotion-bd-t)
"vmap ,n (easymotion-next)
" }}}

" Plug 'yuttie/comfortable-motion.vim'  " smoother scrolling physics

" Plug 'christoomey/vim-tmux-navigator' " vim & tmux
" other option: https://github.com/wincent/terminus

" Plug 'roman/golden-ratio'   " Disabled: automatic resizing of Vim windows to golden ratio {{{
let g:golden_ratio_exclude_nonmodifiable = 1
" https://github.com/roman/golden-ratio/issues/22

" Plug 'zhaocai/GoldenView.Vim'
let g:goldenview__enable_default_mapping=0
" nmap  GoldenViewSplit
" }}}

" tpope extensions: surround, unimpaired {{{
" Plug 'tpope/vim-surround'
" Plug 'tpope/vim-unimpaired'
" to disable a mapping
let g:nremap = {"[": '', "]": ''}
" Plug 'tpope/vim-obsession'
" }}}

" Dash.app {{{
" Plug 'rizzatti/funcoo.vim'
" Plug 'rizzatti/dash.vim'
" noremap does *not* work with 
" nmap h DashSearch
nmap k DashSearch
" }}}

" Plug 'vim-scripts/TaskList.vim' " Eclipse-like TASK list {{{
augroup tasklist
    autocmd!
    autocmd BufWinEnter -TaskList_* setlocal norelativenumber number nowrap
augroup END
map t TaskList
" }}}

" Git {{{2
" Plug 'airblade/vim-gitgutter'
" let g:gitgutter_map_keys=0
let g:gitgutter_max_signs = 250
let g:gitgutter_realtime = 0
nmap  [og :GitGutterSignsEnable
nmap  ]og :GitGutterSignsDisable
nmap  cog :GitGutterSignsToggle
" nnoremap G :GitGutterSignsToggle
" Plug 'mhinz/vim-signify'

" Plug 'tpope/vim-fugitive'

" Plug 'gregsexton/gitv'
" Plug 'junegunn/gv.vim'
" Magit for Vim
" Plug 'jreybert/vimagit'
"}}}
"}}}

" Experimental {{{1
" Plug 'MattesGroeger/vim-bookmarks'
" allows toggling bookmarks per line

" Plug 'liuchengxu/vim-which-key'
" nnoremap   :WhichKey ','
" nnoremap        :WhichKey "\"

" Plug 'alok/notational-fzf-vim' " disabled {{{2
" Plug 'file:///Users/alexandp/Dropbox/workspaces/mine/miscellaneous/notational-fzf-vim', {'name': 'alpo-nv'}
let g:nv_search_paths = ['~/Dropbox/Dox/nvall']
let g:nv_use_short_pathnames=0
let g:nv_ignore_pattern=['non-qq-nvalt/*', 'attachments/*']
let g:nv_python_executable='~/.pyenv/versions/3.7.1/bin/python3'
let s:search_paths = map(copy(g:nv_search_paths), 'expand(v:val)')
let s:search_path_str = join(map(copy(s:search_paths), 'shellescape(v:val)'))
if has('win64') || has('win32')
  let s:null_path = 'NUL'
  let s:command = ''
else
  let s:null_path = '/dev/null'
  let s:command = 'command'
endif
" Use `command` in front of 'rg' to ignore aliases.
" The `' "\S" '` is so that the backslash itself doesn't require escaping.
" g:search_paths is already shell escaped, so we don't do it again
command! -nargs=* -bang QQ
      \ call fzf#run(
          \ fzf#wrap({
              \ 'sink': 'e',
              \ 'window': 'belowright 30%split',
              \ 'source': join([
                   \ s:command,
                   \ 'rg',
                   \ '--follow',
                   \ '--smart-case',
                   \ '--color never',
                   \ '--no-messages',
                   \ '--no-heading',
                   \ '--no-line-number',
                   \ '--files-with-matches',
                   \ '--sort accessed',
                   \ (( is '') ?  '"\S"' :  shellescape()),
                   \ s:search_path_str,
                   \ '2>' . s:null_path,
                   \ ]),
              \ 'options': join([
                               \ '--exact',
                               \ '--delimiter=":"',
                               \ '--tiebreak=' . 'length,begin',
                               \ '--preview="cat {}"',
                               \ '--preview-window=right:40%:wrap',
                               \ ])},0))
"}}}

" Plug 'fmoralesc/vim-pad' " disabled {{{2
" :Pad
let g:pad#dir='~/Dropbox/Dox/nvall'
let g:pad#exclude_dirnames="attachments,non-qq-nvalt"
let g:pad#default_file_extension='.md'
let g:pad#search_backend='ag'
let g:pad#query_dirnames=0
let g:pad#query_filenames=1
let g:pad#rename_files=0
let g:pad#read_nchars_from_files=0
let g:pad#title_first_line=0
let g:pad#window_height=12
let g:pad#ignored_extensions=["plist", "pdf", "odt", "docx", "doc"]
"let g:pad#open_in_split=0
let g:pad#set_mappings=0
" nmap ql (pad-list)
" nmap qn (pad-new)
" nmap qq (pad-search)
" }}}
"}}}

call plug#end()
" colorscheme {{{

" default colorscheme
colorscheme evening " morning zellner

" THEME command: custom colorscheme groups {{{2
" Color scheme sites:
" http://vimcolors.com/
" http://colorswat.ch/
let s:cs_dark = "(rich) onedark nord nova (vimdefault) desert256 molokai dante koehler vividchalk vibrantink molokai tango fnaqeran motus railcast tir_black inkpot"
let s:cs_light = "(rich) ironman nuvola gruvbox (vimdefault) morning zellner (misc) cake16 sweater--- simpleandfriendly summerfruit256 calmbreeze autumnleaf buttercream navajo papayawhip pyte (disabled)"
let s:cs_pastel = "(rich) earendel gruvbox (misc) alduin lucius --- jellybeans railcast2 tango2 wombat wombat256 wombat256mod camo (disabled) kolor"

function! ChooseColorscheme(args)
    let l:cslist = []
    if len(a:args) == 0
        echo 'Usage: :THEME [all|dark|light|paster]'
        return
    elseif a:args == 'all'
        let paths = split(globpath(&runtimepath, 'colors/*vim'), "\n")
        let l:cslist = map(paths, 'fnamemodify(v:val, ":t:r")')
        echo 'List of all installed colorschemes:'
        echo join(l:cslist, "\n")
        return
    elseif a:args == 'light'
        let l:cslist = split(s:cs_light)
        echo 'Light colorschemes:'
    elseif a:args == 'pastel'
        let l:cslist = split(s:cs_pastel)
        echo 'Pastel colorschemes:'
    elseif a:args == 'dark'
        let l:cslist = split(s:cs_dark)
        echo 'Dark colorschemes:'
    endif
    echo join(l:cslist, "\n")
    echo "\n"
    execute "colorscheme " . input("Choice: ", "", "color")
endfunction
command! -nargs=* THEME call ChooseColorscheme('')
" }}}

function! s:RandomColorschemeFromList(list)
    let m = len(a:list)
    let tmstmp = str2nr(strftime('%s'))
    let selIdx = float2nr(fmod(tmstmp, m))
    " echom "Timestamp:" .  tmstmp . "; len(list):" . string(m) . "; selected idx:" . string(selIdx)
    let selColorscheme = a:list[selIdx]
    " echom "Timestamp:" .  tmstmp . "; len(list):" . string(m) . "; colorscheme :" . selColorscheme
    return selColorscheme
endfunction

" set colorscheme based on vim flavor {{{2
if has("unix")
    " use if needed to determine the os
    " or use has("mac")
    " let s:uname = system("uname -s")

    if &diff 
        " colorscheme ironman
    elseif has("gui_running")
        let color_schemes = ['ironman', 'nuvola', 'gruvbox', 'papercolor', 'cake16', 'sweater', 'plan9', 'github', 'earendel', 'onedark', 'nord', 'nova', 'ironman', 'nuvola', 'gruvbox', 'papercolor']
        let cs = s:RandomColorschemeFromList(color_schemes)
        if cs == 'gruvbox'
            set background=light
        elseif cs == 'papercolor'
            set background=light
        endif

        execute ":colorscheme " .  cs
        " if fmod(s:tmstmp, s:mod) == 0 || fmod(s:tmstmp, s:mod) == 7
        "     colorscheme nuvola
        " elseif (fmod(s:tmstmp, s:mod) == 1) || (fmod(s:tmstmp, s:mod) == 8)
        "     colorscheme ironman
        " elseif fmod(s:tmstmp, s:mod) == 2 || fmod(s:tmstmp, s:mod) == 9
        "     set background=light
        "     colorscheme gruvbox8
        " elseif fmod(s:tmstmp, s:mod) == 3 || fmod(s:tmstmp, s:mod) == 10
        "     colorscheme plan9
        " elseif fmod(s:tmstmp, s:mod) == 4
        "     colorscheme alduin
        " elseif fmod(s:tmstmp, s:mod) == 5
        "     colorscheme nova
        " elseif fmod(s:tmstmp, s:mod) == 6
        "     set background=dark
        "     colorscheme gruvbox8
        " else
        "     colorscheme nuvola
        " endif
    elseif has("gui_vimr")
        colorscheme alduin
    elseif has('nvim')
        " colorscheme gruvbox
        let color_schemes = ['ironman', 'gruvbox', 'papercolor', 'onedark','nord', 'alduin']
        let cs = s:RandomColorschemeFromList(color_schemes)
        " execute ":colorscheme " .  cs
    else
        " colorscheme gruvbox
        let color_schemes = ['ironman', 'gruvbox', 'papercolor', 'onedark','nord', 'alduin']
        let cs = s:RandomColorschemeFromList(color_schemes)
        " execute ":colorscheme " .  cs
    endif
endif
" }}}

" color column & cursor line {{{2
function! SetColorColumn()
    " highlight ColorColumn ctermbg=235 guibg=#2c2d27
    set colorcolumn=81,161
    " Following setting colors all columns after 121
    " let &colorcolumn="81,".join(range(121,999),",")
endfunction

" http://vim.wikia.com/wiki/Highlight_current_line
set cursorline
augroup CursorLine
    autocmd!
    autocmd VimEnter,WinEnter,BufWinEnter * setlocal cursorline
    autocmd WinLeave * setlocal nocursorline
augroup END
function! SetCursorLineColors()
    hi CursorLine    ctermbg=52 guibg=#424242
    hi CursorLineNr  term=bold ctermfg=226 gui=bold guifg=#ffff00
endfunction

"call SetCursorLineColors()
call SetColorColumn()
" }}}

" }}}

" * * * * * * * * * * * * * * * * * * * * * * * * * *
" Old, disabled plugins {{{ 

" Plug 'chrisbra/NrrwRgn'               " edit just a region (inspired by Emacs)

" Plug 'kopischke/vim-fetch'            " open files at line and column

" Plug 'terryma/vim-expand-region' {{{2
" let g:expand_region_text_objects = {
"     \ 'iw' :0,
"     \ 'i"' :0,
"     \ 'i''' :0,
"     \ 'ia' :0,
"     \ 'i]' :1,
"     \ 'ib' :1,
"     \ 'iB' :1,
"     \ 'is' :0,
"     \ 'il' :0,
"     \ 'ii' :0,
"     \ 'if' :0,
"     \ 'ip' :0,
"     \ 'ie' :0,
"     \}
" }}}

" Plug 'vim-airline/vim-airline' {{{2
" Plug 'vim-airline/vim-airline-themes'
" let g:airline_left_sep = '»'
" let g:airline_right_sep = '«'
" let g:airline_theme='twofirewatch' "kolor papercolor light kalisi molokai bubblegum solarized durant luna
" " let g:airline_section_b='[%{airline#extensions#branch#get_head()}] b:%n w:%{winnr()}' "%{airline#section#create([\'b:%n w:%{winnr()} [\', \'branch\', \']\'])}'
" let g:airline_section_c='%f%m %#__accent_red#%{airline#util#wrap(airline#parts#readonly(),0)}%#__restore__#'
" let g:airline_section_z='%4l:%-3c %3p%% b%n:w%{winnr()}'   
" let g:airline_mode_map={
"        \ '__' : '-',
"        \ 'n'  : 'N',
"        \ 'i'  : 'I',
"        \ 'R'  : 'R',
"        \ 'c'  : 'C',
"        \ 'v'  : 'V',
"        \ 'V'  : 'V',
"        \ '' : 'V',
"        \ 's'  : 'S',
"        \ 'S'  : 'S',
"        \ '' : 'S',
"        \ }
" let g:airline_left_sep=''
" let g:airline_right_sep=''
" let g:airline#extensions#tabline#left_sep = ' '
" let g:airline#extensions#tabline#left_alt_sep = '|'
" }}}

" Unite: can replace CtrlP, Tagbar {{{2
" Note: vimproc requires compiling a c file
" Plug 'Shougo/vimproc.vim'
" Plug 'Shougo/unite.vim'
" Plug 'Shougo/unite-outline'
" Plug 'Shougo/vimfiler.vim'
" Plug 'Shougo/neoyank.vim'
" Plug 'Shougo/unite-help'
" Plug 'tsukkee/unite-tag'
" nnoremap u  :Unite -start-insert file_rec/async
" nnoremap p  :Unite -start-insert file_rec/async
" nnoremap gt :Unite tab
" nnoremap ff :Unite -start-insert file/async
" nnoremap fb :Unite buffer bookmark
" nnoremap b :Unite buffer bookmark
" nnoremap fo :Unite -vertical -winwidth=35 -direction=belowright outline
" nnoremap fh :Unite history/yank
" nnoremap   (unite-redraw)
" }}}

" Plug 'thisivan/vim-taglist' {{{2
" let Tlist_Ctags_Cmd='/usr/local/bin/ctags'
" let Tlist_Show_One_File=1
" let Tlist_Auto_Highlight_Tag=1
" let Tlist_Use_Right_Window=0
" let Tlist_Close_On_Select=1
" let Tlist_GainFocus_On_ToggleOpen=1
" let Tlist_Sort_Type="name"
" nnoremap   :TlistToggle
" map  t :TlistToggle
" }}}

" Plug 'git://git.wincent.com/command-t.git' {{{2
" CommandT settings
" disabled; using CtrlP
" let g:command_t_loaded = 1
" map  t :CommandT
" let g:CommandTCancelMap=''
" }}}

" Plug 'scrooloose/nerdtree' {{{2
" let NERDTreeIgnore=['\.pyc', '\.pyo', '\~$', '\.o$', '\.class$', 
"     \ '\.egg$', '\.idea$',
"     \ '\.bzr', '\.git', '\.hg', '\.svn']
" let NERDChristmasTree=1
" let NERDTreeBookmarksFile='~/.vim/.NERDTreeBookmarks'
" let NERDTreeHighlightCursorline=1
" let NERDTreeQuitOnOpen=1
" let NERDTreeShowHidden=1
" let NERDTreeWinPos="left"
" nnoremap p :NERDTreeToggle
" nnoremap P :NERDTreeFind
" nnoremap   :NERDTreeToggle
" nnoremap   :NERDTreeFind
" }}}

" Plug 'jeetsukumaran/vim-buffergator' {{{2
" let g:buffergator_viewport_split_policy = "T"
" let g:buffergator_autodismiss_on_select = 1
" let g:buffergator_suppress_keymaps = 1
" nnoremap gt :BuffergatorTabsToggle
" nnoremap gb :BuffergatorToggle
" Replaced by CtrlPBuffer 
" Plug 'jlanzarotta/bufexplorer'
" }}}

" Plug 'AndrewRadev/tagfinder.vim' {{{2
" augroup TagFinder
"   autocmd!
"   autocmd FileType * DefineTagFinder Class c,class,e,s,t,u
"   autocmd FileType * DefineTagFinder Method f,m,method,F,singleton\ method
" augroup END
" }}}

" Plug 'AutoTag'
" Plug 'xolox/vim-misc'
" Plug 'xolox/vim-easytags' {{{2
if filereadable("/usr/local/bin/ctags")
    let g:easytags_cmd = '/usr/local/bin/ctags'
else
    let g:easytags_cmd = '/usr/bin/ctags'
endif
let g:easytags_async = 1
let g:easytags_dynamic_files = 1
let g:easytags_auto_highlight = 0
let g:easytags_include_members = 1
let g:easytags_updatetime_min = 60000
let g:easytags_syntax_keyword = 'always'  " 'always'  'auto'
" if using Universal ctags
let g:easytags_suppress_ctags_warning = 1
"let g:easytags_languages = {
            "\ 'language': {
            "\   'cmd': g:easytags_cmd,
            "\   'args': [],
            "\   'fileoutput_opt': '-f',
            "\   'stdout_opt': '-f-',
            "\   'recurse_flag': '-R'
            "\ }
"\}
" }}}

" Plug 'Shougo/neocomplete.vim' {{{2
" " let g:neocomplete#enable_at_startup=1
" let g:neocomplete#auto_complete_delay=400
" let g:neocomplete#auto_completion_start_length=2
" if !exists('g:neocomplete#sources')
"     let g:neocomplete#sources = {}
" endif
" let g:neocomplete#sources.md = ['dictionary', 'buffer', 'neosnippet'] "['omni', 'tag', 'buffer', 'dictionary', 'neosnippet']
" let g:neocomplete#fallback_mappings=["\\", "\\"]
" augroup neocomplete
"     autocmd!
"     autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
"     autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
"     autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
"     autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
"     " autocmd BufNew,BufRead css,html,javascript,html,markdown,xml :NeoCompleteEnable
" augroup END
" nmap [op :NeoCompleteEnable
" nmap ]op :NeoCompleteDisable
" nmap cop :NeoCompleteToggle
" }}}

" Plug 'junegunn/vim-peekaboo' {{{2
" can be replaced by :registers
" let g:peekaboo_delay=800
" let g:peekaboo_window='vertical botright 45new'
" let g:peekaboo_window='topleft 15new'
" }}}

" Plug 'scrooloose/syntastic' {{{2
"let g:syntastic_auto_loc_list = 1
"let g:syntastic_check_on_open = 0
"let g:syntastic_check_on_wq = 0
"let g:syntastic_auto_jump = 0
""let g:syntastic_error_symbol = "✗"
""let g:syntastic_warning_symbol = "⚠"
"" if _pyvermaj > '3.0'
""     echom "PYTHON3k  :YES"
""     let g:syntastic_python_python_exec = g:syntastic_python3_python_exe
""     let g:syntastic_python_checkers = g:syntastic_python3_checkers
"" else
""     echom "PYTHON3k  :NO"
""     let g:syntastic_python_python_exec = g:syntastic_python2_python_exe
""     let g:syntastic_python_checkers = g:syntastic_python2_checkers
"" endif
"" echom "syntastic:" . g:syntastic_python_python_exec
"" echom "syntastic:" . g:syntastic_python_checkers
" }}}

" Plug 'maralla/validator.vim' {{{2
" check syntax on the fly asynchronously
" }}}

" Plug 'mileszs/ack.vim' {{{2
" if executable('rg')
"     let g:ackprg = 'rg --vimgrep -n --smart-case -t'
" elseif executable('ag')
if executable('ag')
    let g:ackprg = 'ag --vimgrep --smart-case'
endif
" }}}

" Snippets {{{2
" if has("python")
"     Plug 'SirVer/ultisnips'
"     let g:UltiSnipsSnippetsDir=expand("~/.vim/xsnippets/ultisnips")
" else
"     Plug 'MarcWeber/vim-addon-mw-utils'
"     Plug 'tomtom/tlib_vim'
"     Plug 'garbas/vim-snipmate'
" endif
" Plug 'honza/vim-snippets'
" }}}

" Scratch files, notes, outliner etc. {{{2

"  Org-mode {{{3
" Plug 'axvr/org.vim'
" Plug 'jceb/vim-orgmode' 
let g:org_heading_shade_leading_stars=1
" let g:org_indent=1
let g:org_todo_keywords = [
    \ [ 'TODO(t)', 'NEXT(n)', '|', 'DONE(d)' ],
    \ [ 'WIPR(p)', 'WAIT(w)', '|', 'DONE(d)', 'FILED(f)', 'SKIP(x)'],
\ ]
let g:org_agenda_files = ['~/Dropbox/Dox/mydox/*.org']
" autocmd BufNewFile,BufRead *.org setfiletype org
autocmd FileType org setlocal textwidth=0 nowrap nolinebreak
" augroup org
"     autocmd!
"     autocmd FileType org inoremap  :silent! :py ORGMODE.plugins[u"EditStructure"].promote_heading(including_children=False)
"     autocmd FileType org nnoremap  :py ORGMODE.plugins[u"EditStructure"].promote_heading(including_children=False)
"     autocmd FileType org inoremap  :silent! :py ORGMODE.plugins[u"EditStructure"].promote_heading(including_children=True)
"     autocmd FileType org nnoremap  :py ORGMODE.plugins[u"EditStructure"].promote_heading(including_children=True)
"     autocmd FileType org inoremap  :silent! :py ORGMODE.plugins[u"EditStructure"].demote_heading(including_children=False)
"     autocmd FileType org nnoremap  :py ORGMODE.plugins[u"EditStructure"].demote_heading(including_children=False)
"     autocmd FileType org inoremap  :silent! :py ORGMODE.plugins[u"EditStructure"].demote_heading(including_children=True)
"     autocmd FileType org nnoremap  :py ORGMODE.plugins[u"EditStructure"].demote_heading(including_children=True)
" augroup END

" Orgmode helping plugins
" Plug 'tpope/vim-speeddating'
" Plug 'vim-scripts/utl.vim'
" nmap glo :Utl openLink underCursor edit
" nmap glt :Utl openLink underCursor tabe
" nmap glv :Utl openLink underCursor vsplit
" nmap gls :Utl openLink underCursor split
" nmap gly :Utl copyLink underCursor
" Plug 'mattn/calendar-vim'
" }}}

" Plug 'xolox/vim-misc' " {{{3
" Plug 'xolox/vim-notes'
" :Note
let g:notes_directories=['~/Dropbox/Dox/nvall']
let g:notes_suffix='.md'
let g:title_sync='no'
let g:notes_smart_quotes=0
let g:notes_list_bullets=['*', '-', '+']
let g:notes_word_boundaries=1
let g:notes_unicode_enabled=1
let g:notes_conceal_code=0
" }}}

" Plug 'duff/vim-scratch' " {{{3
" :scratch :Sscratch
" }}}

" Plug 'vimoutliner/vimoutliner' " {{{3
" outliner .otl
" }}}

" Plug 'vimwiki/vimwiki'
"}}}

" }}}
"
" * * * * * * * * * * * * * * * * * * * * * * * * * *
"
" Credits:
"
" http://blog.danielfischer.com/2010/11/19/a-starting-guide-to-vim-from-textmate/
" http://items.sjbach.com/319/configuring-vim-right
" https://github.com/tpope/vim-pathogen
" http://dougireton.com/blog/2013/02/23/layout-your-vimrc-like-a-boss/
" 

SidOfc commented 4 years ago

@al3xandru alright, checking back in after doing some additional research, found the culprit:

image

All I did was ran :verbose imap <cr> while editing a markdown buffer. And indeed, disabling this plugin allows mkdx to work normally:

" line 1239 in your .vimrc
" Plug 'tmsvg/pear-tree'

I also found the following in the README file of the plugin:

image

Within it's documentation file, I can find: g:pear_tree_map_special_keys = 1, setting this to 0 will allow you to remap its enter handler. Alternatively you could do this for mkdx if that's what you prefer, the how-to is described here.

For now, I'm going to close this issue as it's not a bug in mkdx, it's just the usual plugin-conflict in which case mkdx will always play it safe and allow the other plugin to do its thing.

Cheers for reporting of course :+1:. I will clarify that one cannot use the let g:mkdx#settings.some.setting style in their vimrc, this may prevent future users from shooting themselves in the foot :)

al3xandru commented 4 years ago

@SidOfc I really appreciate the investigation you have done. While I do see the mapping you are pointing too, what is the explanation of this:

:verbose imap <cr>
i  <CR>         @<Plug>(mkdx-enter)
        Last set from ~/.vim/plugged/mkdx/ftplugin/markdown/mkdx.vim line 187

That seem to suggest that mkdx is the one that should be invoked, right?

al3xandru commented 4 years ago

What I ended up doing is:

if exists('g:mkdx#settings')
    autocmd FileType markdown let b:pear_tree_map_special_keys = 0
endif
SidOfc commented 4 years ago

@al3xandru you said that you saw the mapping I was pointing to (assuming its the pear-tree one), yet you show me a different one, so did you run :verbose imap <cr> twice in a row with different results, or are you only showing the "relevant half" of the output you see?

I mean, you are correct in that if you see:

:verbose imap <cr>
i  <CR>         @<Plug>(mkdx-enter)
        Last set from ~/.vim/plugged/mkdx/ftplugin/markdown/mkdx.vim line 187

the plugin should be called. Perhaps it is a difference in :verbose between vim and neovim. honestly that's guesswork on my part, but it does come up every now and then.

With that I'm trying to say is that maybe neovim is lying to me about what is mapped, or vim could be lying to you about what is mapped. I see no logical explanation otherwise if you have a markdown buffer open and see @<Plug>(mkdx-enter) it should work, but since it did not something really strange is happening there.

There could be another million reasons why, but our machines arent the same, I actually tested your config in neovim, not regular vim as well, in the end if this works I think we should just leave it at that, if a new problem pops up you are free to open a new issue about it of course, I've got other people waiting on features I still have to build :)