diff --git a/vimwiki_0_9_7.vba b/vimwiki_0_9_701.vba similarity index 99% rename from vimwiki_0_9_7.vba rename to vimwiki_0_9_701.vba index 6fd91a0..28d9744 100644 --- a/vimwiki_0_9_7.vba +++ b/vimwiki_0_9_701.vba @@ -1,4356 +1,4361 @@ " Vimball Archiver by Charles E. Campbell, Jr., Ph.D. UseVimball finish -syntax\vimwiki.vim [[[1 -140 -" Vimwiki syntax file +autoload\vimwiki.vim [[[1 +680 +" Vimwiki autoload plugin file " Author: Maxim Kim " Home: http://code.google.com/p/vimwiki/ -" vim:tw=79: -" Quit if syntax file is already loaded -if version < 600 - syntax clear -elseif exists("b:current_syntax") +if exists("g:loaded_vimwiki_auto") || &cp finish endif +let g:loaded_vimwiki_auto = 1 -"" use max highlighting - could be quite slow if there are too many wikifiles -if VimwikiGet('maxhi') - " Every WikiWord is nonexistent - if g:vimwiki_camel_case - execute 'syntax match VimwikiNoExistsWord /\%(^\|[^!]\)\zs'.g:vimwiki_word1.'/' - endif - execute 'syntax match VimwikiNoExistsWord /'.g:vimwiki_word2.'/' - execute 'syntax match VimwikiNoExistsWord /'.g:vimwiki_word3.'/' - " till we find them in vimwiki's path - call vimwiki#WikiHighlightWords() +if has("win32") + let s:os_sep = '\' else - " A WikiWord (unqualifiedWikiName) - execute 'syntax match VimwikiWord /\%(^\|[^!]\)\zs\<'.g:vimwiki_word1.'\>/' - " A [[bracketed wiki word]] - execute 'syntax match VimwikiWord /'.g:vimwiki_word2.'/' + let s:os_sep = '/' endif -execute 'syntax match VimwikiLink `'.g:vimwiki_rxWeblink.'`' +let s:badsymbols = '['.g:vimwiki_badsyms.g:vimwiki_stripsym.'<>|?*:"]' -" Emoticons: must come after the Textilisms, as later rules take precedence -" over earlier ones. This match is an approximation for the ~70 distinct -syntax match VimwikiEmoticons /\%((.)\|:[()|$@]\|:-[DOPS()\]|$@]\|;)\|:'(\)/ +" MISC helper functions {{{ -let g:vimwiki_rxTodo = '\C\%(TODO:\|DONE:\|FIXME:\|FIXED:\|XXX:\)' -execute 'syntax match VimwikiTodo /'. g:vimwiki_rxTodo .'/' +" This function is double defined. +" TODO: refactor common functions into new module. +function! s:chomp_slash(str)"{{{ + return substitute(a:str, '[/\\]\+$', '', '') +endfunction"}}} -" Load concrete Wiki syntax -execute 'runtime! syntax/vimwiki_'.VimwikiGet('syntax').'.vim' +function! vimwiki#mkdir(path) "{{{ + let path = expand(a:path) + if !isdirectory(path) && exists("*mkdir") + let path = s:chomp_slash(path) + call mkdir(path, "p") + endif +endfunction +" }}} -" Tables -execute 'syntax match VimwikiTable /'.g:vimwiki_rxTable.'/' +function! vimwiki#safe_link(string) "{{{ + return substitute(a:string, s:badsymbols, g:vimwiki_stripsym, 'g') +endfunction +"}}} -execute 'syntax match VimwikiBold /'.g:vimwiki_rxBold.'/' +function! vimwiki#unsafe_link(string) "{{{ + return substitute(a:string, g:vimwiki_stripsym, s:badsymbols, 'g') +endfunction +"}}} -execute 'syntax match VimwikiItalic /'.g:vimwiki_rxItalic.'/' +function! vimwiki#subdir(path, filename)"{{{ + let path = expand(a:path) + let filename = expand(a:filename) + let idx = 0 + while path[idx] == filename[idx] + let idx = idx + 1 + endwhile -execute 'syntax match VimwikiBoldItalic /'.g:vimwiki_rxBoldItalic.'/' + let p = split(strpart(filename, idx), '[/\\]') + let res = join(p[:-2], s:os_sep) + if len(res) > 0 + let res = res.s:os_sep + endif + return res +endfunction"}}} -execute 'syntax match VimwikiItalicBold /'.g:vimwiki_rxItalicBold.'/' +function! vimwiki#current_subdir()"{{{ + return vimwiki#subdir(VimwikiGet('path'), expand('%:p')) +endfunction"}}} -execute 'syntax match VimwikiDelText /'.g:vimwiki_rxDelText.'/' +function! vimwiki#msg(message) "{{{ + echohl WarningMsg + echomsg 'vimwiki: '.a:message + echohl None +endfunction +" }}} -execute 'syntax match VimwikiSuperScript /'.g:vimwiki_rxSuperScript.'/' +function! s:filename(link) "{{{ + let result = vimwiki#safe_link(a:link) + if a:link =~ '|' + let result = vimwiki#safe_link(split(a:link, '|')[0]) + elseif a:link =~ '][' + let result = vimwiki#safe_link(split(a:link, '][')[0]) + endif + return result +endfunction +" }}} -execute 'syntax match VimwikiSubScript /'.g:vimwiki_rxSubScript.'/' +function! s:is_wiki_word(str) "{{{ + if a:str =~ g:vimwiki_word1 && a:str !~ '[[:space:]\\/]' + return 1 + endif + return 0 +endfunction +" }}} -execute 'syntax match VimwikiCode /'.g:vimwiki_rxCode.'/' +function! s:edit_file(command, filename) "{{{ + let fname = escape(a:filename, '% ') + call vimwiki#mkdir(fnamemodify(a:filename, ":p:h")) + execute a:command.' '.fname +endfunction +" }}} -"
horizontal rule -execute 'syntax match VimwikiHR /'.g:vimwiki_rxHR.'/' +function! s:search_word(wikiRx, cmd) "{{{ + let match_line = search(a:wikiRx, 's'.a:cmd) + if match_line == 0 + call vimwiki#msg('WikiWord not found') + endif +endfunction +" }}} -" List items -execute 'syntax match VimwikiList /'.g:vimwiki_rxListBullet.'/' -execute 'syntax match VimwikiList /'.g:vimwiki_rxListNumber.'/' -execute 'syntax match VimwikiList /'.g:vimwiki_rxListDefine.'/' +function! s:get_word_at_cursor(wikiRX) "{{{ + let col = col('.') - 1 + let line = getline('.') + let ebeg = -1 + let cont = match(line, a:wikiRX, 0) + while (ebeg >= 0 || (0 <= cont) && (cont <= col)) + let contn = matchend(line, a:wikiRX, cont) + if (cont <= col) && (col < contn) + let ebeg = match(line, a:wikiRX, cont) + let elen = contn - ebeg + break + else + let cont = match(line, a:wikiRX, contn) + endif + endwh + if ebeg >= 0 + return strpart(line, ebeg, elen) + else + return "" + endif +endf "}}} -execute 'syntax region VimwikiPre start=/'.g:vimwiki_rxPreStart. - \ '/ end=/'.g:vimwiki_rxPreEnd.'/ contains=VimwikiComment' +function! s:strip_word(word) "{{{ + let result = a:word + if strpart(a:word, 0, 2) == "[[" + " get rid of [[ and ]] + let w = strpart(a:word, 2, strlen(a:word)-4) -" List item checkbox -syntax match VimwikiCheckBox /\[.\?\]/ -if g:vimwiki_hl_cb_checked - execute 'syntax match VimwikiCheckBoxDone /'.g:vimwiki_rxListBullet.'\s*\[x\].*$/' - execute 'syntax match VimwikiCheckBoxDone /'.g:vimwiki_rxListNumber.'\s*\[x\].*$/' -endif + if w =~ '|' + " we want "link" from [[link|link desc]] + let w = split(w, "|")[0] + elseif w =~ '][' + " we want "link" from [[link][link desc]] + let w = split(w, "][")[0] + endif -syntax region VimwikiComment start='' + let result = vimwiki#safe_link(w) + endif + return result +endfunction +" }}} -if !vimwiki#hl_exists("VimwikiHeader1") - execute 'syntax match VimwikiHeader /'.g:vimwiki_rxHeader.'/' -else - " Header levels, 1-6 - execute 'syntax match VimwikiHeader1 /'.g:vimwiki_rxH1.'/' - execute 'syntax match VimwikiHeader2 /'.g:vimwiki_rxH2.'/' - execute 'syntax match VimwikiHeader3 /'.g:vimwiki_rxH3.'/' - execute 'syntax match VimwikiHeader4 /'.g:vimwiki_rxH4.'/' - execute 'syntax match VimwikiHeader5 /'.g:vimwiki_rxH5.'/' - execute 'syntax match VimwikiHeader6 /'.g:vimwiki_rxH6.'/' -endif +function! s:is_link_to_non_wiki_file(word) "{{{ + " Check if word is link to a non-wiki file. + " The easiest way is to check if it has extension like .txt or .html + if a:word =~ '\.\w\{1,4}$' + return 1 + endif + return 0 +endfunction +" }}} -" group names "{{{ -if !vimwiki#hl_exists("VimwikiHeader1") - hi def link VimwikiHeader Title -else - hi def link VimwikiHeader1 Title - hi def link VimwikiHeader2 Title - hi def link VimwikiHeader3 Title - hi def link VimwikiHeader4 Title - hi def link VimwikiHeader5 Title - hi def link VimwikiHeader6 Title -endif +function! s:print_wiki_list() "{{{ + let idx = 0 + while idx < len(g:vimwiki_list) + if idx == g:vimwiki_current_idx + let sep = ' * ' + echohl TablineSel + else + let sep = ' ' + echohl None + endif + echo (idx + 1).sep.VimwikiGet('path', idx) + let idx += 1 + endwhile + echohl None +endfunction +" }}} -hi def VimwikiBold term=bold cterm=bold gui=bold -hi def VimwikiItalic term=italic cterm=italic gui=italic -hi def VimwikiBoldItalic term=bold cterm=bold gui=bold,italic -hi def link VimwikiItalicBold VimwikiBoldItalic +function! s:wiki_select(wnum)"{{{ + if a:wnum < 1 || a:wnum > len(g:vimwiki_list) + return + endif + let b:vimwiki_idx = g:vimwiki_current_idx + let g:vimwiki_current_idx = a:wnum - 1 +endfunction +" }}} -hi def link VimwikiCode PreProc -hi def link VimwikiWord Underlined -hi def link VimwikiNoExistsWord Error +function! s:update_wiki_link(fname, old, new) " {{{ + echo "Updating links in ".a:fname + let has_updates = 0 + let dest = [] + for line in readfile(a:fname) + if !has_updates && match(line, a:old) != -1 + let has_updates = 1 + endif + call add(dest, substitute(line, a:old, escape(a:new, "&"), "g")) + endfor + " add exception handling... + if has_updates + call rename(a:fname, a:fname.'#vimwiki_upd#') + call writefile(dest, a:fname) + call delete(a:fname.'#vimwiki_upd#') + endif +endfunction +" }}} -hi def link VimwikiPre SpecialComment -hi def link VimwikiLink Underlined -hi def link VimwikiList Function -hi def link VimwikiCheckBox VimwikiList -hi def link VimwikiCheckBoxDone Comment -hi def link VimwikiTable PreProc -hi def link VimwikiEmoticons Character -hi def link VimwikiDelText Constant -hi def link VimwikiSuperScript Number -hi def link VimwikiSubScript Number -hi def link VimwikiTodo Todo -hi def link VimwikiComment Comment -"}}} - -let b:current_syntax="vimwiki" +function! s:update_wiki_links_dir(dir, old_fname, new_fname) " {{{ + let old_fname = substitute(a:old_fname, '[/\\]', '[/\\\\]', 'g') + let new_fname = a:new_fname -" EMBEDDED syntax setup "{{{ -let nested = VimwikiGet('nested_syntaxes') -if !empty(nested) - for [hl_syntax, vim_syntax] in items(nested) - call vimwiki#nested_syntax(vim_syntax, - \ '^{{{\%(.*[[:blank:][:punct:]]\)\?'. - \ hl_syntax.'\%([[:blank:][:punct:]].*\)\?', - \ '^}}}', 'VimwikiPre') + if !s:is_wiki_word(new_fname) + let new_fname = '[['.new_fname.']]' + endif + if !s:is_wiki_word(old_fname) + let old_fname = '\[\['.vimwiki#unsafe_link(old_fname). + \ '\%(|.*\)\?\%(\]\[.*\)\?\]\]' + else + let old_fname = '\<'.old_fname.'\>' + endif + let files = split(glob(VimwikiGet('path').a:dir.'*'.VimwikiGet('ext')), '\n') + for fname in files + call s:update_wiki_link(fname, old_fname, new_fname) endfor -endif -"}}} -syntax\vimwiki_default.vim [[[1 -76 -" Vimwiki syntax file -" Default syntax -" Author: Maxim Kim -" Home: http://code.google.com/p/vimwiki/ -" vim:tw=78: - -" text: *strong* -" let g:vimwiki_rxBold = '\*[^*]\+\*' -let g:vimwiki_rxBold = '\%(^\|\s\|[[:punct:]]\)\@<='. - \'\*'. - \'\([^*`[:space:]][^*`]*[^*`[:space:]]\|[^*`]\)'. - \'\*'. - \'\%([[:punct:]]\|\s\|$\)\@=' - -" text: _emphasis_ -" let g:vimwiki_rxItalic = '_[^_]\+_' -let g:vimwiki_rxItalic = '\%(^\|\s\|[[:punct:]]\)\@<='. - \'_'. - \'\([^_`[:space:]][^_`]*[^_`[:space:]]\|[^_`]\)'. - \'_'. - \'\%([[:punct:]]\|\s\|$\)\@=' +endfunction +" }}} -" text: *_bold italic_* or _*italic bold*_ -let g:vimwiki_rxBoldItalic = '\%(^\|\s\|[[:punct:]]\)\@<='. - \'\*_'. - \'\([^*_`[:space:]][^*_`]*[^*_`[:space:]]\|[^*_`]\)'. - \'_\*'. - \'\%([[:punct:]]\|\s\|$\)\@=' +function! s:tail_name(fname) "{{{ + let result = substitute(a:fname, ":", "__colon__", "g") + let result = fnamemodify(result, ":t:r") + let result = substitute(result, "__colon__", ":", "g") + return result +endfunction "}}} -let g:vimwiki_rxItalicBold = '\%(^\|\s\|[[:punct:]]\)\@<='. - \'_\*'. - \'\([^*_`[:space:]][^*_`]*[^*_`[:space:]]\|[^*_`]\)'. - \'\*_'. - \'\%([[:punct:]]\|\s\|$\)\@=' +function! s:update_wiki_links(old_fname, new_fname) " {{{ + let old_fname = s:tail_name(a:old_fname) + let new_fname = s:tail_name(a:new_fname) -" text: `code` -let g:vimwiki_rxCode = '`[^`]\+`' + let subdirs = split(a:old_fname, '[/\\]')[: -2] -" text: ~~deleted text~~ -let g:vimwiki_rxDelText = '\~\~[^~`]\+\~\~' + " TODO: Use Dictionary here... + let dirs_keys = [''] + let dirs_vals = [''] + if len(subdirs) > 0 + let dirs_keys = [''] + let dirs_vals = [join(subdirs, '/').'/'] + let idx = 0 + while idx < len(subdirs) - 1 + call add(dirs_keys, join(subdirs[: idx], '/').'/') + call add(dirs_vals, join(subdirs[idx+1 :], '/').'/') + let idx = idx + 1 + endwhile + call add(dirs_keys,join(subdirs, '/').'/') + call add(dirs_vals, '') + endif -" text: ^superscript^ -let g:vimwiki_rxSuperScript = '\^[^^`]\+\^' + let idx = 0 + while idx < len(dirs_keys) + let dir = dirs_keys[idx] + let new_dir = dirs_vals[idx] + call s:update_wiki_links_dir(dir, + \ new_dir.old_fname, new_dir.new_fname) + let idx = idx + 1 + endwhile +endfunction +" }}} -" text: ,,subscript,, -let g:vimwiki_rxSubScript = ',,[^,`]\+,,' +function! s:get_wiki_buffers() "{{{ + let blist = [] + let bcount = 1 + while bcount<=bufnr("$") + if bufexists(bcount) + let bname = fnamemodify(bufname(bcount), ":p") + if bname =~ VimwikiGet('ext')."$" + let bitem = [bname, getbufvar(bname, "vimwiki_prev_word")] + call add(blist, bitem) + endif + endif + let bcount = bcount + 1 + endwhile + return blist +endfunction +" }}} -" Header levels, 1-6 -let g:vimwiki_rxH1 = '^\s*=\{1}[^=]\+.*[^=]\+=\{1}\s*$' -let g:vimwiki_rxH2 = '^\s*=\{2}[^=]\+.*[^=]\+=\{2}\s*$' -let g:vimwiki_rxH3 = '^\s*=\{3}[^=]\+.*[^=]\+=\{3}\s*$' -let g:vimwiki_rxH4 = '^\s*=\{4}[^=]\+.*[^=]\+=\{4}\s*$' -let g:vimwiki_rxH5 = '^\s*=\{5}[^=]\+.*[^=]\+=\{5}\s*$' -let g:vimwiki_rxH6 = '^\s*=\{6}[^=]\+.*[^=]\+=\{6}\s*$' -let g:vimwiki_rxHeader = '\%('.g:vimwiki_rxH1.'\)\|'. - \ '\%('.g:vimwiki_rxH2.'\)\|'. - \ '\%('.g:vimwiki_rxH3.'\)\|'. - \ '\%('.g:vimwiki_rxH4.'\)\|'. - \ '\%('.g:vimwiki_rxH5.'\)\|'. - \ '\%('.g:vimwiki_rxH6.'\)' +function! s:open_wiki_buffer(item) "{{{ + call s:edit_file('e', a:item[0]) + if !empty(a:item[1]) + call setbufvar(a:item[0], "vimwiki_prev_word", a:item[1]) + endif +endfunction +" }}} -"
, horizontal rule -let g:vimwiki_rxHR = '^----.*$' +" }}} -" Tables. Each line starts and ends with '||'; each cell is separated by '||' -let g:vimwiki_rxTable = '||' +" SYNTAX highlight {{{ +function! vimwiki#WikiHighlightWords() "{{{ + " search all wiki files in 'path' and its subdirs. + let subdir = vimwiki#current_subdir() + let wikies = glob(VimwikiGet('path').subdir.'**/*'.VimwikiGet('ext')) -" List items start with whitespace(s) then '*' or '#' -let g:vimwiki_rxListBullet = '^\s\+\*' -let g:vimwiki_rxListNumber = '^\s\+#' + " remove .wiki extensions + let wikies = substitute(wikies, '\'.VimwikiGet('ext'), "", "g") + let g:vimwiki_wikiwords = split(wikies, '\n') -let g:vimwiki_rxListDefine = '::\(\s\|$\)' + " remove backup files (.wiki~) + call filter(g:vimwiki_wikiwords, 'v:val !~ ''.*\~$''') -" Preformatted text -let g:vimwiki_rxPreStart = '{{{' -let g:vimwiki_rxPreEnd = '}}}' -syntax\vimwiki_media.vim [[[1 -58 -" Vimwiki syntax file -" MediaWiki syntax -" Author: Maxim Kim -" Home: http://code.google.com/p/vimwiki/ -" vim:tw=78: + " remove paths + let rem_path = escape(expand(VimwikiGet('path')).subdir, '\') + call map(g:vimwiki_wikiwords, 'substitute(v:val, rem_path, "", "g")') -" text: '''strong''' -let g:vimwiki_rxBold = "'''[^']\\+'''" + " Links with subdirs should be highlighted for linux and windows separators + " Change \ or / to [/\\] + let os_p = '[/\\]' + let os_p2 = escape(os_p, '\') + call map(g:vimwiki_wikiwords, 'substitute(v:val, os_p, os_p2, "g")') -" text: ''emphasis'' -let g:vimwiki_rxItalic = "''[^']\\+''" + for word in g:vimwiki_wikiwords + if g:vimwiki_camel_case && + \ word =~ g:vimwiki_word1 && !s:is_link_to_non_wiki_file(word) + execute 'syntax match VimwikiWord /\%(^\|[^!]\)\zs\<'.word.'\>/' + endif + execute 'syntax match VimwikiWord /\[\[\<'. + \ vimwiki#unsafe_link(word). + \ '\>\%(|\+.*\)*\]\]/' + execute 'syntax match VimwikiWord /\[\[\<'. + \ vimwiki#unsafe_link(word). + \ '\>\]\[.\+\]\]/' + endfor + execute 'syntax match VimwikiWord /\[\[.\+\.\%(jpg\|png\|gif\)\%(|\+.*\)*\]\]/' + execute 'syntax match VimwikiWord /\[\[.\+\.\%(jpg\|png\|gif\)\]\[.\+\]\]/' +endfunction +" }}} -" text: '''''strong italic''''' -let g:vimwiki_rxBoldItalic = "'''''[^']\\+'''''" -let g:vimwiki_rxItalicBold = g:vimwiki_rxBoldItalic +function! vimwiki#hl_exists(hl)"{{{ + if !hlexists(a:hl) + return 0 + endif + redir => hlstatus + exe "silent hi" a:hl + redir END + return (hlstatus !~ "cleared") +endfunction +"}}} -" text: `code` -let g:vimwiki_rxCode = '`[^`]\+`' +function! vimwiki#nested_syntax(filetype, start, end, textSnipHl) abort "{{{ +" From http://vim.wikia.com/wiki/VimTip857 + let ft=toupper(a:filetype) + let group='textGroup'.ft + if exists('b:current_syntax') + let s:current_syntax=b:current_syntax + " Remove current syntax definition, as some syntax files (e.g. cpp.vim) + " do nothing if b:current_syntax is defined. + unlet b:current_syntax + endif -" text: ~~deleted text~~ -let g:vimwiki_rxDelText = '\~\~[^~]\+\~\~' + " Some syntax files set up iskeyword which might scratch vimwiki a bit. + " Let us save and restore it later. + " let b:skip_set_iskeyword = 1 + let is_keyword = &iskeyword -" text: ^superscript^ -let g:vimwiki_rxSuperScript = '\^[^^]\+\^' + execute 'syntax include @'.group.' syntax/'.a:filetype.'.vim' + try + execute 'syntax include @'.group.' after/syntax/'.a:filetype.'.vim' + catch + endtry -" text: ,,subscript,, -let g:vimwiki_rxSubScript = ',,[^,]\+,,' + let &iskeyword = is_keyword -" Header levels, 1-6 -let g:vimwiki_rxH1 = '^\s*=\{1}[^=]\+.*[^=]\+=\{1}\s*$' -let g:vimwiki_rxH2 = '^\s*=\{2}[^=]\+.*[^=]\+=\{2}\s*$' -let g:vimwiki_rxH3 = '^\s*=\{3}[^=]\+.*[^=]\+=\{3}\s*$' -let g:vimwiki_rxH4 = '^\s*=\{4}[^=]\+.*[^=]\+=\{4}\s*$' -let g:vimwiki_rxH5 = '^\s*=\{5}[^=]\+.*[^=]\+=\{5}\s*$' -let g:vimwiki_rxH6 = '^\s*=\{6}[^=]\+.*[^=]\+=\{6}\s*$' -let g:vimwiki_rxHeader = '\%('.g:vimwiki_rxH1.'\)\|'. - \ '\%('.g:vimwiki_rxH2.'\)\|'. - \ '\%('.g:vimwiki_rxH3.'\)\|'. - \ '\%('.g:vimwiki_rxH4.'\)\|'. - \ '\%('.g:vimwiki_rxH5.'\)\|'. - \ '\%('.g:vimwiki_rxH6.'\)' - -"
, horizontal rule -let g:vimwiki_rxHR = '^----.*$' - -" Tables. Each line starts and ends with '||'; each cell is separated by '||' -let g:vimwiki_rxTable = '||' - -" Bulleted list items start with whitespace(s), then '*' -" highlight only bullets and digits. -let g:vimwiki_rxListBullet = '^\s*\*\+\([^*]*$\)\@=' -let g:vimwiki_rxListNumber = '^\s*#\+' - -let g:vimwiki_rxListDefine = '^\%(;\|:\)\s' + if exists('s:current_syntax') + let b:current_syntax=s:current_syntax + else + unlet b:current_syntax + endif + execute 'syntax region textSnip'.ft.' + \ matchgroup='.a:textSnipHl.' + \ start="'.a:start.'" end="'.a:end.'" + \ contains=@'.group +endfunction "}}} -" Preformatted text -let g:vimwiki_rxPreStart = '
'
-let g:vimwiki_rxPreEnd = '<\/pre>'
-ftplugin\vimwiki.vim	[[[1
-286
-" Vimwiki filetype plugin file
-" Author: Maxim Kim 
-" Home: http://code.google.com/p/vimwiki/
+"}}}
 
-if exists("b:did_ftplugin")
-  finish
-endif
-let b:did_ftplugin = 1  " Don't load another plugin for this buffer
+" WIKI functions {{{
+function! vimwiki#WikiNextWord() "{{{
+  call s:search_word(g:vimwiki_rxWikiWord.'\|'.g:vimwiki_rxWeblink, '')
+endfunction
+" }}}
 
-" UNDO list {{{
-" Reset the following options to undo this plugin.
-let b:undo_ftplugin = "setlocal wrap< linebreak< ".
-      \ "suffixesadd< isfname< comments< ".
-      \ "autowriteall< ".
-      \ "formatoptions< foldtext< ".
-      \ "foldmethod< foldexpr< commentstring< "
-" UNDO }}}
+function! vimwiki#WikiPrevWord() "{{{
+  call s:search_word(g:vimwiki_rxWikiWord.'\|'.g:vimwiki_rxWeblink, 'b')
+endfunction
+" }}}
 
-" MISC STUFF {{{
+function! vimwiki#WikiFollowWord(split) "{{{
+  if a:split == "split"
+    let cmd = ":split "
+  elseif a:split == "vsplit"
+    let cmd = ":vsplit "
+  else
+    let cmd = ":e "
+  endif
 
-setlocal wrap
-setlocal linebreak
-setlocal autowriteall
-setlocal commentstring=
-" MISC }}}
+  let word = s:strip_word(s:get_word_at_cursor(g:vimwiki_rxWikiWord))
+  if word == ""
+    let weblink = s:strip_word(s:get_word_at_cursor(g:vimwiki_rxWeblink))
+    if weblink != ""
+      call VimwikiWeblinkHandler(weblink)
+    else
+      execute "normal! \n"
+    endif
+    return
+  endif
 
-" GOTO FILE: gf {{{
-execute 'setlocal suffixesadd='.VimwikiGet('ext')
-setlocal isfname-=[,]
-" gf}}}
+  if s:is_link_to_non_wiki_file(word)
+    call s:edit_file(cmd, word)
+  else
+    let vimwiki_prev_word = [expand('%:p'), getpos('.')]
+    let subdir = vimwiki#current_subdir()
+    call s:edit_file(cmd, VimwikiGet('path').subdir.word.VimwikiGet('ext'))
+    let b:vimwiki_prev_word = vimwiki_prev_word
+  endif
+endfunction
+" }}}
 
-" COMMENTS: autocreate list items {{{
-" for list items, and list items with checkboxes
-if VimwikiGet('syntax') == 'default'
-  exe 'setl comments=b:\ *\ ['.escape(g:vimwiki_listsyms[0], ' ').
-        \ '],b:\ *\ ['.g:vimwiki_listsyms[4].']'
-  exe 'setl comments+=b:\ #\ ['.escape(g:vimwiki_listsyms[0], ' ').
-        \ '],b:\ #\ ['.g:vimwiki_listsyms[4].']'
-  setl comments+=b:\ *,b:\ #
-  setl formatlistpat=^\\s\\+[*#]\\s*
-else
-  exe 'setl comments=n:*\ ['.escape(g:vimwiki_listsyms[0], ' ').
-        \ '],n:*\ ['.g:vimwiki_listsyms[4].']'
-  exe 'setl comments+=n:#\ ['.escape(g:vimwiki_listsyms[0], ' ').
-        \ '],n:#\ ['.g:vimwiki_listsyms[4].']'
-  setl comments+=n:*,n:#
-endif
-setlocal formatoptions=tnro
-" COMMENTS }}}
+function! vimwiki#WikiGoBackWord() "{{{
+  if exists("b:vimwiki_prev_word")
+    " go back to saved WikiWord
+    let prev_word = b:vimwiki_prev_word
+    execute ":e ".substitute(prev_word[0], '\s', '\\\0', 'g')
+    call setpos('.', prev_word[1])
+  endif
+endfunction
+" }}}
 
-" FOLDING for headers and list items using expr fold method. {{{
-if g:vimwiki_folding == 1
-  setlocal fdm=expr
-  setlocal foldexpr=VimwikiFoldLevel(v:lnum)
-  setlocal foldtext=VimwikiFoldText()
-endif
+function! vimwiki#WikiGoHome(index) "{{{
+  call s:wiki_select(a:index)
+  call vimwiki#mkdir(VimwikiGet('path'))
 
-function! VimwikiFoldLevel(lnum) "{{{
-  let line = getline(a:lnum)
+  try
+    execute ':e '.VimwikiGet('path').VimwikiGet('index').VimwikiGet('ext')
+  catch /E37/ " catch 'No write since last change' error
+    " this is really unsecure!!!
+    execute ':'.VimwikiGet('gohome').' '.
+          \ VimwikiGet('path').
+          \ VimwikiGet('index').
+          \ VimwikiGet('ext')
+  catch /E325/ " catch 'ATTENTION' error
+    " TODO: Hmmm, if open already opened index.wiki there is an error...
+    " Find out what is the reason and how to avoid it. Is it dangerous?
+    echomsg "Unknown error!"
+  endtry
+endfunction
+"}}}
 
-  " Header folding...
-  if line =~ g:vimwiki_rxHeader
-    let n = vimwiki#count_first_sym(line)
-    return '>' . n
+function! vimwiki#WikiDeleteWord() "{{{
+  "" file system funcs
+  "" Delete WikiWord you are in from filesystem
+  let val = input('Delete ['.expand('%').'] (y/n)? ', "")
+  if val != 'y'
+    return
   endif
+  let fname = expand('%:p')
+  try
+    call delete(fname)
+  catch /.*/
+    call vimwiki#msg('Cannot delete "'.expand('%:t:r').'"!')
+    return
+  endtry
+  execute "bdelete! ".escape(fname, " ")
 
-  if g:vimwiki_fold_empty_lines == 0
-    let nnline = getline(nextnonblank(a:lnum + 1))
-    if nnline =~ g:vimwiki_rxHeader
-      let n = vimwiki#count_first_sym(nnline)
-      return '<' . n
-    endif
+  " reread buffer => deleted WikiWord should appear as non-existent
+  if expand('%:p') != ""
+    execute "e"
   endif
+endfunction
+"}}}
 
-  " List item folding...
-  if g:vimwiki_fold_lists
-    let rx_list_item = '\('.
-          \ g:vimwiki_rxListBullet.'\|'.g:vimwiki_rxListNumber.
-          \ '\)'
+function! vimwiki#WikiRenameWord() "{{{
+  "" Rename WikiWord, update all links to renamed WikiWord
+  let subdir = vimwiki#current_subdir()
+  let old_fname = subdir.expand('%:t')
 
-    if line =~ rx_list_item
-      let [nnum, nline] = s:find_next_item(rx_list_item, a:lnum)
-      if nline =~ rx_list_item
-        let level = s:get_li_level(a:lnum, nnum)
-        if !(level < 0 && (nnum - a:lnum) > 1)
-          return s:fold_marker(level)
-        endif
-      elseif nnum - a:lnum == 1
-        " last single-lined list item in a list
-        let level = s:get_li_level_last(a:lnum)
-        return s:fold_marker(level)
-      endif
-    else
-      let [pnum, pline] = s:find_prev_item(rx_list_item, a:lnum)
-      if pline =~ rx_list_item
-        if getline(a:lnum + 1) =~ rx_list_item
-          let level = s:get_li_level(pnum, a:lnum + 1)
-          if level < 0
-            return s:fold_marker(level)
-          endif
-        endif
+  " there is no file (new one maybe)
+  if glob(expand('%:p')) == ''
+    call vimwiki#msg('Cannot rename "'.expand('%:p').
+          \ '". It does not exist! (New file? Save it before renaming.)')
+    return
+  endif
 
-        let [nnum, nline] = s:find_next_item(rx_list_item, pnum)
-        if nline !~ rx_list_item && nnum-a:lnum == 1
-          " last multi-lined list item in a list
-          let level = s:get_li_level_last(pnum)
-          return s:fold_marker(level)
-        endif
+  let val = input('Rename "'.expand('%:t:r').'" (y/n)? ', "")
+  if val!='y'
+    return
+  endif
 
-      endif
-    endif
+  let new_link = input('Enter new name: ', "")
 
+  if new_link =~ '[/\\]'
+    " It is actually doable but I do not have free time to do it.
+    call vimwiki#msg('Cannot rename to a filename with path!')
+    return
   endif
 
-  return '='
-endfunction "}}}
+  let new_link = subdir.new_link
 
-function! s:fold_marker(level) "{{{
-  if a:level > 0
-    return "a".a:level
-  elseif a:level < 0
-    return "s".abs(a:level)
-  else
-    return "="
+  " check new_fname - it should be 'good', not empty
+  if substitute(new_link, '\s', '', 'g') == ''
+    call vimwiki#msg('Cannot rename to an empty filename!')
+    return
+  endif
+  if s:is_link_to_non_wiki_file(new_link)
+    call vimwiki#msg('Cannot rename to a filename with extension (ie .txt .html)!')
+    return
   endif
-endfunction "}}}
-
-function! s:find_next_item(rx_item, lnum) "{{{
-  let lnum = a:lnum + 1
 
-  while lnum <= line('$')
-    if getline(lnum) =~ a:rx_item
-          \ || getline(lnum) =~ '^\S'
-          \ || indent(lnum) <= indent(a:lnum)
-      break
-    endif
-    let lnum += 1
-  endwhile
-
-  return [lnum, getline(lnum)]
-endfunction "}}}
-
-function! s:find_prev_item(rx_item, lnum) "{{{
-  let lnum = a:lnum - 1
-
-  while lnum > 1
-    if getline(lnum) =~ a:rx_item
-          \ || getline(lnum) =~ '^\S'
-      break
-    endif
-    let lnum -= 1
-  endwhile
-
-  return [lnum, getline(lnum)]
-endfunction "}}}
-
-function! s:get_li_level(lnum, nnum) "{{{
-  if VimwikiGet('syntax') == 'media'
-    let level = vimwiki#count_first_sym(getline(a:nnum)) -
-          \ vimwiki#count_first_sym(getline(a:lnum))
-  else
-    let level = ((indent(a:nnum) - indent(a:lnum)) / &sw)
-  endif
-  return level
-endfunction "}}}
+  let new_link = s:strip_word(new_link)
+  let new_fname = VimwikiGet('path').s:filename(new_link).VimwikiGet('ext')
 
-function! s:get_li_level_last(lnum) "{{{
-  if VimwikiGet('syntax') == 'media'
-    return -(vimwiki#count_first_sym(getline(a:lnum)) - 1)
-  else
-    return -(indent(a:lnum) / &sw - 1)
+  " do not rename if word with such name exists
+  let fname = glob(new_fname)
+  if fname != ''
+    call vimwiki#msg('Cannot rename to "'.new_fname.
+          \ '". File with that name exist!')
+    return
   endif
-endfunction "}}}
-
-function! VimwikiFoldText() "{{{
-  let line = getline(v:foldstart)
-  return line.' ['.(v:foldend - v:foldstart).'] '
-endfunction "}}}
+  " rename WikiWord file
+  try
+    echomsg "Renaming ".VimwikiGet('path').old_fname." to ".new_fname
+    let res = rename(expand('%:p'), expand(new_fname))
+    if res != 0
+      throw "Cannot rename!"
+    end
+  catch /.*/
+    call vimwiki#msg('Cannot rename "'.expand('%:t:r').'" to "'.new_fname.'"')
+    return
+  endtry
 
-" FOLDING }}}
+  let &buftype="nofile"
 
-" COMMANDS {{{
-command! -buffer Vimwiki2HTML
-      \ call vimwiki_html#Wiki2HTML(expand(VimwikiGet('path_html')),
-      \                             expand('%'))
-command! -buffer VimwikiAll2HTML
-      \ call vimwiki_html#WikiAll2HTML(expand(VimwikiGet('path_html')))
+  let cur_buffer = [expand('%:p'),
+        \getbufvar(expand('%:p'), "vimwiki_prev_word")]
 
-command! -buffer VimwikiNextWord call vimwiki#WikiNextWord()
-command! -buffer VimwikiPrevWord call vimwiki#WikiPrevWord()
-command! -buffer VimwikiDeleteWord call vimwiki#WikiDeleteWord()
-command! -buffer VimwikiRenameWord call vimwiki#WikiRenameWord()
-command! -buffer VimwikiFollowWord call vimwiki#WikiFollowWord('nosplit')
-command! -buffer VimwikiGoBackWord call vimwiki#WikiGoBackWord()
-command! -buffer VimwikiSplitWord call vimwiki#WikiFollowWord('split')
-command! -buffer VimwikiVSplitWord call vimwiki#WikiFollowWord('vsplit')
+  let blist = s:get_wiki_buffers()
 
-command! -buffer -range VimwikiToggleListItem call vimwiki_lst#ToggleListItem(, )
+  " save wiki buffers
+  for bitem in blist
+    execute ':b '.escape(bitem[0], ' ')
+    execute ':update'
+  endfor
 
-exe 'command! -buffer -nargs=* Search vimgrep  '.
-      \ VimwikiGet('path').'**/*'.VimwikiGet('ext')
+  execute ':b '.escape(cur_buffer[0], ' ')
 
-" COMMANDS }}}
+  " remove wiki buffers
+  for bitem in blist
+    execute 'bwipeout '.escape(bitem[0], ' ')
+  endfor
 
-" KEYBINDINGS {{{
-if g:vimwiki_use_mouse
-  nmap   
-  nmap   
-  noremap  <2-LeftMouse> :VimwikiFollowWord
-  noremap   :VimwikiSplitWord
-  noremap   :VimwikiVSplitWord
-  noremap   :VimwikiGoBackWord
-endif
+  let setting_more = &more
+  setlocal nomore
 
-if !hasmapto('VimwikiFollowWord')
-  nmap   VimwikiFollowWord
-endif
-noremap